Code Monkey home page Code Monkey logo

click-to-component's Introduction

npm Release

Option+Click a Component in the browser to instantly goto the source in your editor.

Next.js Demo

Features

  • Option+Click opens the immediate Component's source

  • Option+Right-click opens a context menu with the parent Components' props, fileName, columnNumber, and lineNumber

    props

  • Works with frameworks like Next.js, Create React App, & Vite that use @babel/plugin-transform-react-jsx-source

  • Supports vscode & vscode-insiders' URL handling

  • Automatically tree-shaken from production builds

  • Keyboard navigation in context menu (e.g. , , )

  • More context & faster than using React DevTools:

    React DevTools

Installation

npm
npm install click-to-react-component
pnpm
pnpm add click-to-react-component
yarn
yarn add click-to-react-component

Even though click-to-react-component is added to dependencies, tree-shaking will remove click-to-react-component from production builds.

Usage

Create React App

/src/index.js

+import { ClickToComponent } from 'click-to-react-component';
 import React from 'react';
 import ReactDOM from 'react-dom/client';
 import './index.css';
@@ -8,7 +7,6 @@ import reportWebVitals from './reportWebVitals';
 const root = ReactDOM.createRoot(document.getElementById('root'));
 root.render(
   <React.StrictMode>
+    <ClickToComponent />
     <App />
   </React.StrictMode>
 );

Create React App Demo

Next.js

pages/_app.tsx

+import { ClickToComponent } from 'click-to-react-component'
 import type { AppProps } from 'next/app'
 import '../styles/globals.css'

 function MyApp({ Component, pageProps }: AppProps) {
   return (
     <>
+      <ClickToComponent />
       <Component {...pageProps} />
     </>
   )

Next.js Demo

Vite
+import { ClickToComponent } from "click-to-react-component";
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App />
+   <ClickToComponent />
  </React.StrictMode>
);

Vite Demo

Docusaurus
npm install @babel/plugin-transform-react-jsx-source

babel.config.js:

module.exports = {
  presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
  plugins: [
    ...(process.env.BABEL_ENV === 'development'
      ? ['@babel/plugin-transform-react-jsx-source']
      : []),
  ],
};

src/theme/Root.js:

import { ClickToComponent } from 'click-to-react-component';
import React from 'react';

// Default implementation, that you can customize
export default function Root({ children }) {
  return (
    <>
      <ClickToComponent />
      {children}
    </>
  );
}

If developing in container?

editor

By default, clicking will default editor to vscode.

If, like me, you use vscode-insiders, you can set editor explicitly:

-<ClickToComponent />
+<ClickToComponent editor="vscode-insiders" />

Run Locally

Clone the project

gh repo clone ericclemmons/click-to-component

Go to the project directory

cd click-to-component

Install dependencies

pnpm install

Run one of the examples:

Create React App
cd apps/cra
pnpm start
Next.js
cd apps/next
pnpm dev

click-to-component's People

Contributors

alefduarte avatar arthurdenner avatar dcastil avatar ericclemmons avatar frantic avatar github-actions[bot] avatar hosseinagha avatar iamyoki avatar leonmueller-oneandonly avatar neil-buckley avatar piyushjohnson avatar snouzy avatar zjffun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

click-to-component's Issues

Update Next.js docs

The installation and configuration section in the docs is missing how to configure this plugin if you're using Next.js 14 and the new App Router.

I got it to work partially by doing the following:

  1. npm install click-to-react-component -D -E
  2. In my app/layout.tsx:

`import type { Metadata } from "next";
import { GeistSans } from "geist/font/sans";
import { GeistMono } from "geist/font/mono";
import { Providers } from "./providers";

import "./styles/globals.css";

export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (

<body
className={h-full font-sans antialiased} > <Providers>{children}</Providers> </body> </html> ); }

Then in my app/providers.tsx:

`// @ts-nocheck
"use client";

import { ClickToComponent } from "click-to-react-component";
import { ThemeProvider } from "next-themes";

export function Providers({ children }) {
return (
<>
< ClickToComponent / >
<ThemeProvider
attribute="class"
themes={["light", "dark", "swiss", "neon"]}
>
{children}
< / ThemeProvider >
</>
);
}`

This works partially. For some component selections I get the following error:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'columnNumber')

Call Stack
getPathToSource
node_modules/click-to-react-component/src/getPathToSource.js (14:0)
handleClick
node_modules/click-to-react-component/src/ClickToComponent.js (44:36)

which is already mentioned here: #70

Out of curiosity I've got a couple of questions:

  1. Does this feature exist natively in the official react tools?
  2. If not, why? I'm sure you've delved into this question.
  3. I know of https://github.com/zthxxx/react-dev-inspector. Are there any other alternatives except click-to-react-component and react-dev-inspector that you know of?
  4. I would rather install click-to-react-component in devDependencies in package.json; will this break something or will it work just as fine as if I would install it under dependencies?

Just trying to learn as much as possible about these types of tooling.

Thanks!

Context menu keyboard navigation

Describe the bug
Right now the context menu doesn't follow the correct tabbing semantics for a menu role.

FloatingFocusManager should have the preventTabbing prop (so only arrow key navigation controls the menu).

Further, is the first item intentionally focused upon opening the menu? When pressing the ArrowDown key, it requires two presses to begin navigating to the items but should only require one. The activeIndex may not be synced correctly.

In the example it focuses the floating element on open and arrow key nav will then work as expected.

    useLayoutEffect(() => {
      if (open) {
        refs.floating.current?.focus();
      }
    }, [open, refs.floating]);

To Reproduce
Right click and use keyboard nav

NextJS 13 incompatbility, does not work in /app directory at all

Describe the bug
Works inside the /pages directory, but not inside /app directory.

To Reproduce

  1. create fresh app npx create-next-app@latest
  2. create /app/ClickToComponentClient.tsx, put at the top of the file 'use client'; and import and add <ClickToComponent />
  3. create /app/test/page.ts and import and add <ClickToComponentClient />
  4. goto http://localhost:3000/test and try to use
    • WORKS: hover works, I see green selections, no problem there
    • ERROR: when I click it starts to download the page and produces error message instead going to the VSCode

Expected behavior
Expected to open VSCode to the component, as it worked in /pages directory.

Screenshots
None.

Desktop (please complete the following information):

  • OS: MacOS
  • Browser Chrome
  • Version latest

To support apps running in docker containers

Your work has been very useful to us and makes our development easy. But there is one thing we felt that can be improved is adding support to apps running in Docker containers. We have our frontend and backend running simultaneously inside docker, so when we try to access a component it returns an error stating "This path does not exist on this computer".

We recommend a feature where we can provide a function as a prop which receives the actual path (in our case it's the path written in docker file) as input and converts that path to our current working directory.

Eg: <ClickToComponent pathModifier={(path)=>{ const modifiedPath = actualPath + path.slice(n); return modifiedPath; }}/>

Screenshot 2022-06-28 at 11 32 40 PM

`Option` + `Click` on link element is overlapped with browser native download behavior.

Describe the bug
Option + Click on link element is overlapped with browser native download behavior.

OS
Macos

To Reproduce
Steps to reproduce the behavior:

  1. Option + Click on some link element like <a href=...>
  2. Will download the link

Expected behavior
Not overlapped with download behavior.

Screenshots
image

Desktop (please complete the following information):

  • OS: Macos
  • Browser: [e.g. chrome, safari]
  • Version: latest

Additional context
This happens because of hotkey conflict, I can think of 2 ways of solutions:

  1. Change to another hotkey.
  2. Add event.preventDefault() but that will deactivate the download behavior and that is not perfect
    const onKeyDown = React.useCallback(
    function handleKeyDown(
    /**
    * @type {KeyboardEvent}
    */
    event
    ) {
    switch (state) {
    case State.IDLE:
    if (event.altKey) setState(State.HOVER)
    break
    default:
    }
    },
    [state]
    )

TypeScript error "Could not find a declaration file for module"

Describe the bug
Could not find a declaration file for module 'click-to-react-component'. This error appears if tsconfig.json is set to "strict": true

To Reproduce
Steps to reproduce the behavior:

  1. Init new project with Vite (React + typescript + SWC) npm create vite@latest
  2. Install click-to-react-component npm i click-to-react-component
  3. Import click-to-react-component in main.tsx
  4. See typescript error

Expected behavior
No typescript error in VS Code.

Screenshots
Снимок экрана 2024-05-15 в 23 42 41

Error from TypeScript

Could not find a declaration file for module 'click-to-react-component'. '/Users/danitatt/Work/nnp/app/node_modules/click-to-react-component/src/index.js' implicitly has an 'any' type. There are types at '/Users/danitatt/Work/nnp/app/node_modules/click-to-react-component/src/types.d.ts', but this result could not be resolved when respecting package.json "exports". The 'click-to-react-component' library may need to update its package.json or typings.

Thanks for the great tool!

How to use the library with webpack?

I using the webpack to build React. How can I use this library with webpack?

My code:
index.tsx file

const container = document.getElementById('root');
const root = createRoot(container!);
root.render(
    <>
        <ClickToComponent />
        <App />
    </>
);

webpack.config.js file

 plugins: ['@babel/plugin-transform-react-jsx-source'],

When run I have an error

Uncaught TypeError: Cannot read properties of undefined (reading 'columnNumber')
    at getPathToSource (getPathToSource.js:12:1)
    at handleClick (ClickToComponent.js:43:1)

Thank you very much!

Set `z-index` of FloatingOverlay contextmenu to maximum possible

Cool lib, discovered it's using Floating UI 😄

Describe the bug
Right now if the webpage has positioned elements, the context menu can be obscured beneath them.

Screen Shot 2022-04-27 at 8 58 39 am

It may be a good idea to set the z-index of the FloatingOverlay to 2147483647 to ensure it's always above everything else. (In fact, FloatingOverlay maybe should do that by default?)

To Reproduce
Right click

Desktop (please complete the following information):

  • OS: macOS
  • Browser Chrome
  • Version 100

Additional context
Add any other context about the problem here.

Option+Click doesn't work with material-ui components: "Couldn't find a React instance for the element"

Describe the bug
Option+Right-click works to open the context menu and then go to a selected component.

However, just Option+Click doesn't do anything despite showing the green border around the hovered element. This appears to only be a problem with material UI styled elements.

To Reproduce
This is a private product, so I can't share any useful code. However, the problem might be with the fact that we use MaterialUI's ("@material-ui/core": "^4.12.2",) makeStyles() for styling our components. That might mess up the logic for how you're finding the target component.

Screen Shot 2022-05-11 at 10 21 54 AM

Expected behavior
It should open the target component's file in VSCode as desired.

Desktop (please complete the following information):

  • OS: MacOS
  • Browser Chrome
  • Version 101.0.4951.54 (Official Build) (x86_64)

Adding support for jetbrains IDEs ( or any other IDE with web protocol support )

Is your feature request related to a problem? Please describe.
Adding support to open components in any code editor that supports web protocol.

Describe the solution you'd like
I suggest adding more presets but also allowing developers to provide their handler.

Additional context
I would be happy to send a pull request for this.

Try find parent when couldn't find a React instance ( has source) for the element

export function getSourceForElement(
  /**
   * @type {HTMLElement}
   */
  element
) {
  const instance = getReactInstanceForElement(element)
  const source = getSourceForInstance(instance)

  if (source) return source

  console.warn("Couldn't find a React instance for the element", element)
}

Now in getSourceForElement, when we can't find source of an element, we just return undefined.

Can we try to find a parent React instance which has a source?

Hijacks default right click behavior (can't view native context menu)

Describe the bug
Right now this component hijacks the right click event, making the native context menu impossible to view. From the readme, it looks like this should require a modifier key as well.

This should require, or support the option to require, a modifier to open the context menu on right click

To Reproduce
Steps to reproduce the behavior:

  1. Right click
  2. The click to component menu opens instead of the native context menu

Expected behavior
There should be a way to view the native context menu as well (either with a modifier to show the click-to-react-component menu, or a modifier to show the native context menu.

Desktop (please complete the following information):

  • OS: macOS 12.3.1
  • Browser Chome
  • Version 100.0.4896.127

Production build still contains un-used bundle

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Add analyze package
  2. Build for Analyze

Expected behavior
There shouldn't be @floating-ui here.

I would suggest turn on sideEffect=false to support tree sharking

Screenshots
Screen Shot 2022-06-14 at 5 22 21 PM

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

How does it work under the hood?

  1. In development, frameworks like CRA, Next.js, etc. all include file metadata (e.g. fileName, lineNumber, columNumber) when transforming JSX. (Link babel plugin here)
  2. On hover or right-click, click-to-react-component grabs the React renderer & finds the Fiber node associated with the DOM element (e.g. $0['__reactFiber$fq4qzh0im06'])
  3. This fiber node has a __debugSource value that contains the file metadata from babel.
  4. This file metadata is turned into a URL & launches your editor: https://code.visualstudio.com/docs/editor/command-line#_opening-vs-code-with-urls

Error when runs from WSL

Paths are not working with WSL.

To Reproduce
Steps to reproduce the behavior:

  1. Create a project with Vite inside WSL
  2. Opened it on VS Code using the Remote - WSL extension.
  3. Install click-to-component and add the configs
  4. Run de project
  5. Click on the secondary button and show the context menu with components
    image
  6. Click on component
  7. Show an error on VSCode
    image
  8. If click on [Yes] button, show this message
    image
  9. This is the message that shows the console in Chrome
    image

Expected behavior
Open in VSCode without error

Desktop:

  • OS: Windows 10 21H2
  • Browser: Chrome
  • Version: Version 100.0.4896.127 (Official Build) (64-bit)
  • WSL: Version 2

Couldn't find a React instance for the element (Not using CRA)

Describe the bug
I have tried using the package with a custom webpack config on a monorepo, but I can't seem to get it to work.
I tried in projects that I used CRA and the package works perfectly.

To Reproduce
Steps to reproduce the behavior:

  1. Go to any component
  2. Click on option + click or option + right-click

Expected behavior
Is to see my component in vscode

Additional context
if someone wants to fork and help me fix the problem would be nice
https://github.com/leonelmeque/todo-app-monorepo

Module not found: Can't resolve

Module not found: Can't resolve 'click-to-react-component'

I am trying this awesome tool, but can not use it as a package. For now, I put src files in my components folder.

If I try import from package directly, I will meet resolve error like above.

Don't know why, seems others do not have this problem.

My webpack is [email protected]

TypeError: Cannot read properties of undefined (reading 'columnNumber')

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots

image

Desktop (please complete the following information):

  • OS: windows

image

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context

Next.js v13.1.6-canary.3
react 18

Add support for a custom onClick for ClickToComponent

Is your feature request related to a problem? Please describe.

  1. Support click-to-component in web environments like Replit
  2. Add custom logic to run before editor is opened

Describe the solution you'd like

Make <ClickToComponent /> accept an onClick callback that would get the element, component, file path, etc. as arguments.

Describe alternatives you've considered

Intercepting navigation events or patching window.open: both seem fragile and miss information about the target HTMLElement.

Source is undefined

Describe the bug
In a next js app. If you option click a component it says "Uncaught TypeError: source is undefined"

image

To Reproduce
Steps to reproduce the behavior:

  1. Go to the application
  2. Option click an element

Expected behavior
Open the source in the editor

Screenshots
image

Desktop (please complete the following information):

  • OS: Latest OSX
  • Browser Firefox
  • Version 101.0b9

Cannot find module './src/ClickToComponent' or its corresponding type declarations.

Hey everyone :)
I encountered a small TypeScript problem when working with react-click-to-component:

Describe the bug
Running the typescript compiler with "skipLibCheck": false will result in the following error:

node_modules/click-to-react-component/src/types.d.ts:1:34 - error TS2307: Cannot find module './src/ClickToComponent' or its corresponding type declarations.

To Reproduce
Steps to reproduce the behavior:

  1. Setup a new React project with TypeScript and use
  2. Make sure "skipLibCheck" is set to false
  3. Run the TypeScript compiler

Expected behavior
No TSC errors should occur.

Screenshots
image

Additional context
I guess this happens, because the path reference inside of types.d.ts does not exist. Since this path should be resolved relative to the current file, it looks for a src dir inside of src and will not find that.

A possible fix would be to move types.d.ts to the root directory, or to fix the path.

Not working with React Server Components (RSCs) in Next.js

To Reproduce
Steps to reproduce the behavior:

  1. Create a Next.js 14+ application
  2. Create a page with some components under it
  3. Create a normal component and use it in the page
  4. Create a client only component and use it in the page
  5. The package only works with client only components

Expected behavior
Next.js 14+ components are RSCs by default.
It should work with both client components and server components.

Additional context
This looks like a React issue as __debugSource and __debugOwner are always null for RSCs.

Support for antd components

We are using antd (Ant design) UI library in our project. So when we try to click on an antd component it's throwing the below attached error.

It would be great if ClickToComponent works on top of antd components.

To recreate our problem:

  1. npm install antd
  2. Import any of the antd components in your project and try to click on them.

Screenshot 2022-07-05 at 10 48 24 AM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.