Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with using react three fiber in grafana #22

Closed
JakovGlavac opened this issue Dec 15, 2022 · 4 comments
Closed

Problem with using react three fiber in grafana #22

JakovGlavac opened this issue Dec 15, 2022 · 4 comments

Comments

@JakovGlavac
Copy link

Hi, I'm using grafana.
And I'm trying to create grafana plugin, witch is basically react component with custom props.

When adding <Canvas/> into JSX I get its-fine: useFiber must be called within a <FiberProvider />!

import { PanelProps } from '@grafana/data';
import { Canvas } from '@react-three/fiber';
import React, { useRef, useState } from 'react';


export const SimplePanel: React.FC<PanelProps> = ({ options, data, width, height }) => {

  return (
    <Canvas>
      <h1>epic</h1>
    </Canvas>
  )
};

I really don't know what's wrong, nether can I find anything useful online, and I'm not sure if this issue belongs in this ripo or not I'm just looking for a step in right direction, cuz I've ran out of options.
I think that maybe webpack config is at fault.

So here is grafana default webpack config:

/*
 * ⚠️⚠️⚠️ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠️⚠️⚠️
 *
 * In order to extend the configuration follow the steps in .config/README.md
 */

import CopyWebpackPlugin from 'copy-webpack-plugin';
import ESLintPlugin from 'eslint-webpack-plugin';
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
import LiveReloadPlugin from 'webpack-livereload-plugin';
import path from 'path';
import ReplaceInFileWebpackPlugin from 'replace-in-file-webpack-plugin';
import { Configuration } from 'webpack';

import { getPackageJson, getPluginId, hasReadme, getEntries } from './utils';
import { SOURCE_DIR, DIST_DIR } from './constants';

const config = async (env): Promise<Configuration> => ({
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename],
    },
  },

  context: path.join(process.cwd(), SOURCE_DIR),

  devtool: env.production ? 'source-map' : 'eval-source-map',

  entry: await getEntries(),

  externals: [
    'lodash',
    'jquery',
    'moment',
    'slate',
    'emotion',
    '@emotion/react',
    '@emotion/css',
    'prismjs',
    'slate-plain-serializer',
    '@grafana/slate-react',
    'react',
    'react-dom',
    'react-redux',
    'redux',
    'rxjs',
    'react-router',
    'react-router-dom',
    'd3',
    'angular',
    '@grafana/ui',
    '@grafana/runtime',
    '@grafana/data',

    // Mark legacy SDK imports as external if their name starts with the "grafana/" prefix
    ({ request }, callback) => {
      const prefix = 'grafana/';
      const hasPrefix = (request) => request.indexOf(prefix) === 0;
      const stripPrefix = (request) => request.substr(prefix.length);

      if (hasPrefix(request)) {
        return callback(undefined, stripPrefix(request));
      }

      callback();
    },
  ],

  mode: env.production ? 'production' : 'development',

  module: {
    rules: [
      {
        exclude: /(node_modules)/,
        test: /\.[tj]sx?$/,
        use: {
          loader: 'swc-loader',
          options: {
            jsc: {
              baseUrl: './src',
              target: 'es2015',
              loose: false,
              parser: {
                syntax: 'typescript',
                tsx: true,
                decorators: false,
                dynamicImport: true,
              },
            },
          },
        },
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
      {
        exclude: /(node_modules)/,
        test: /\.s[ac]ss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        type: 'asset/resource',
        generator: {
          // Keep publicPath relative for host.com/grafana/ deployments
          publicPath: `public/plugins/${getPluginId()}/img/`,
          outputPath: 'img/',
          filename: Boolean(env.production) ? '[hash][ext]' : '[name][ext]',
        },
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)(\?v=\d+\.\d+\.\d+)?$/,
        type: 'asset/resource',
        generator: {
          // Keep publicPath relative for host.com/grafana/ deployments
          publicPath: `public/plugins/${getPluginId()}/fonts`,
          outputPath: 'fonts/',
          filename: Boolean(env.production) ? '[hash][ext]' : '[name][ext]',
        },
      },
    ],
  },

  output: {
    clean: {
      keep: /gpx_.*/,
    },
    filename: '[name].js',
    library: {
      type: 'amd',
    },
    path: path.resolve(process.cwd(), DIST_DIR),
    publicPath: '/',
  },

  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        // If src/README.md exists use it; otherwise the root README
        // To `compiler.options.output`
        { from: hasReadme() ? 'README.md' : '../README.md', to: '.', force: true },
        { from: 'plugin.json', to: '.' },
        { from: '../LICENSE', to: '.' },
        { from: '../CHANGELOG.md', to: '.', force: true },
        { from: '**/*.json', to: '.' }, // TODO<Add an error for checking the basic structure of the repo>
        { from: '**/*.svg', to: '.', noErrorOnMissing: true }, // Optional
        { from: '**/*.png', to: '.', noErrorOnMissing: true }, // Optional
        { from: '**/*.html', to: '.', noErrorOnMissing: true }, // Optional
        { from: 'img/**/*', to: '.', noErrorOnMissing: true }, // Optional
        { from: 'libs/**/*', to: '.', noErrorOnMissing: true }, // Optional
        { from: 'static/**/*', to: '.', noErrorOnMissing: true }, // Optional
      ],
    }),
    // Replace certain template-variables in the README and plugin.json
    new ReplaceInFileWebpackPlugin([
      {
        dir: DIST_DIR,
        files: ['plugin.json', 'README.md'],
        rules: [
          {
            search: /\%VERSION\%/g,
            replace: getPackageJson().version,
          },
          {
            search: /\%TODAY\%/g,
            replace: new Date().toISOString().substring(0, 10),
          },
          {
            search: /\%PLUGIN_ID\%/g,
            replace: getPluginId(),
          },
        ],
      },
    ]),
    new ForkTsCheckerWebpackPlugin({
      async: Boolean(env.development),
      issue: {
        include: [{ file: '**/*.{ts,tsx}' }],
      },
      typescript: { configFile: path.join(process.cwd(), 'tsconfig.json') },
    }),
    new ESLintPlugin({
      extensions: ['.ts', '.tsx'],
      lintDirtyModulesOnly: Boolean(env.development), // don't lint on start, only lint changed files
    }),
    ...(env.development ? [new LiveReloadPlugin()] : []),
  ],

  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
    // handle resolving "rootDir" paths
    modules: [path.resolve(process.cwd(), 'src'), 'node_modules'],
    unsafeCache: true,
  },
});

export default config;
@kevinwgutierrez
Copy link

2nd this

having same problem but in a Next.js app, just installed all necessary deps and libs

@LouisMarzorati
Copy link

3rd this

Just have a <Canvas> element rendering on a new nextjs app.

  "dependencies": {
    "@react-three/drei": "^8.10.6",
    "@react-three/fiber": "^8.9.1",
    "@types/three": "^0.146.0",
    "autoprefixer": "^10.4.13",
    "next": "12.1.0",
    "postcss": "^8.4.20",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "tailwindcss": "^3.2.4",
    "three": "^0.147.0"
  },
  
import { Canvas } from "@react-three/fiber";

export default function Home() {
  return (
    <div className="flex flex-colitems-center justify-center">
      <Canvas camera={{ position: [0, 0, 5] }}>
        <ambientLight />
        <pointLight position={[10, 10, 10]} />
        <mesh>
          <boxBufferGeometry args={[2, 2, 2]} />
          <meshStandardMaterial color="hotpink" />
        </mesh>
      </Canvas>
    </div>
  );
}

error - Error: its-fine: useFiber must be called within a !

image

@CodyJasonBennett
Copy link
Member

This would likely come from mismatched versions of react which can break context and create false positives like this. @react-three/fiber requires react and react-dom 18+, so try upgrading those with a clean install.

@LouisMarzorati
Copy link

That worked. updated package.json pasted below

  "dependencies": {
    "@react-three/drei": "^8.10.6",
    "@react-three/fiber": "^8.9.1",
    "@types/three": "^0.146.0",
    "autoprefixer": "^10.4.13",
    "next": "^13.0.7",
    "postcss": "^8.4.20",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "sass": "^1.49.8",
    "tailwindcss": "^3.2.4",
    "three": "^0.147.0"
  },

@CodyJasonBennett CodyJasonBennett closed this as not planned Won't fix, can't repro, duplicate, stale Dec 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants