Giter VIP home page Giter VIP logo

react-view's People

Contributors

anelook avatar biossun avatar dependabot[bot] avatar github-actions[bot] avatar mattdaly avatar mynockspit avatar raunofreiberg avatar taifen avatar tajo avatar wilf312 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  avatar  avatar  avatar

react-view's Issues

Copy URL button does not seem to work

I assume that the Copy URL button should work the same as it does in baseweb.design.

Although, out of the box, the code does not seem to be added as a parameter to the URL in the first place, hence the copy URL button has no effect.


I think this is the relevant logic: https://github.com/uber/baseweb/blob/b642d1bd81214dacb8ce05ad4aea1871e482a273/documentation-site/components/yard/index.tsx#L56.

Although, since react-view has no knowledge of a router and Storybook uses an iframe, I don't know if it's possible.

Boolean props that default to undefined can’t be explicitly set to false

Let’s say I have a component which accepts an optional Boolean prop:

export const MyComponent = ({ shouldDoSomething = undefined }: { shouldDoSomething?: boolean; }) => {
  return (<div>{shouldDoSomething ? 'should do the thing!' : 'should not do the thing'}</div>;
}

If I set up an example for this using react-view, I can’t ever set shouldDoSomething to false, with this configuration:

const propConfig = {
  shouldDoTheThing: {
    type: PropTypes.Boolean,
    description:
      'Should do the thing or not?',
    value: true,
  }
};

If I configure my component example to explicitly set shouldDoTheThing to false, react-view simply omits that prop from the code editor example (and in React Dev Tools you can see the prop is missing; setting it explicitly there works).

Maximum call stack size exceeded when using React.forwardRef

Defining enum props without exporting an enum object

First off, the library is really nice 👍

I'm trying it out and I'm wondering if there is a way to define knobs for props as enums without using the enum object pattern?

e.g. instead of using SIZE.default as in the button example, just use the string 'default'?

We use string literal unions in TypeScript for enum props so we don't export enum objects, we instead rely on the compiler to check the correct strings are being supplied.

It doesn't look like it's currently possible in knob.tsx. If no enumName is provided it uses the prop name as the name of the enum.

I know it's possible to get around this by using useView and creating a custom Knobs component - but it would be nice to re-use Knobs given how much it does out of the box.

Does not work with latest Next.js

Hey 👋

Trying to set this up for our design system but unfortunately, the simple example from the docs gives me this error:

image

I have a set up a repo with a minimal example where only react-view is installed and Next.js is configured to Webpack 5 (the errors appear on Webpack 4 as well)

I'm kinda lost on this one so help would be appreciated @tajo 🙏

Thank you

Can't resolve 'fs'. in next js@11

While Compiling, the following error occurs,

error - ./node_modules/@babel/core/lib/transformation/normalize-file.js:9:0
Module not found: Can't resolve 'fs'
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

same as #50 and #67

Latest version v2.3.4 in registry.npmjs.org is different from v2.3.4 release in github

Hello,

While updating to the latest version of the library I've noticed that some of the changes are missing in the registry, https://registry.npmjs.org/react-view/-/react-view-2.3.4.tgz and https://github.com/uber/react-view/archive/v2.3.4.zip are not the same.

In particular,
when you look at this file code-generator, you can see that the latest fix is not there.
For a reference, here is the change that was released in v2.3.4 https://github.com/uber/react-view/blob/master/src/code-generator.ts#L110

Could you check it please?

Have a great day,
Olena

Dependency version issue

With yarn, getting this error when trying to use react-view.

miksu/prettier is a dependency but this is seems like it could be a versioning issue

Module not found: Error: Can't resolve 'linguist-languages/data/JSX' in '[PROJECT_PATH]/node_modules/@miksu/prettier/lib/language-js'

IE11 support?

Is there plan to support IE11 in the near future?

Support for TypeScript code snippets with knobs

Hi Team,

We are using your library for live code editor with knobs and our application is written in TypeScript.
We want to use the live code editor in TypeScript instead of JavaScript that should work with knobs as well.

Is this possible for you to add TypeScript support in your library?
Is this something that's on your roadmap?

If you can consider our use case and you want to add TypeScript support in full mode, we are happy to contribute as well.

knobs don't update

related to #19

I am using this configuration

import * as React from "react";
import { EuiPopover, EuiButton } from "@elastic/eui";

export default () => {
  const [isOpen, setIsOpen] = React.useState(true);
  return (
    <EuiPopover
      isOpen={isOpen}
      anchorPosition="downCenter"
      panelPaddingSize="m"
      display="inlineBlock"
      button={
        <EuiButton
          iconType="arrowDown"
          iconSide="right"
          onClick={() => setIsOpen(!isOpen)}
        >
          Show popover
        </EuiButton>
      }
    >
      <div style={{ width: "300px" }}>
        Popover content that’s wider than the default
        width
      </div>
    </EuiPopover>
  );
}

state of isOpen prop is controlled by EuiButton but it does update the rendered component but the state of toggle remains the same. Also there are no code changes within the editor.

Hnet com-image (2)

Nested dependency is packaged and published through github which is a potential security risk

Hi react-view team, could you help with this?

I'm looking to use this library in my firm. As part of the process to use this library internally, react-view and it's dependencies need to be onboarded as a security measure. Our onboarding process does not allow dependencies to be resolved through github and instead must come through trusted repos like npm.

I've made a proposed solution in this prettier dependency that is causing the issue, please take a look at this pr I made for this dependency. tajo/prettier#1

Thanks,
Daniel

Make `props.value` accept JSX

I've recently been writing a lot of "stringified JSX", which can become quite hard to maintain.

Would it be possible to provide props.value or initialCode as JSX?

For example:

const config = {
	initialCode: () => {
		const [flag, setFlag] = useState(false);
		const handleClick = () => setFlag(true);

		return (
			<div>
				<Button onClick={handleClick}>Set flag</Button>
			</div>
		);
	},
	scope: { Button },
};

<hr />

Possibly related or duplicate of #10?

PropTypes.Object does not behave as expected.

I cannot seem to get Object props to work properly. When I enter an object into the text input, I always get an error popup reading:

TypeError: Property expression of JSXExpressionContainer expected node to be of a type ["Expression","JSXEmptyExpression"] but instead got "BlockStatement"

In order to ensure the problem isn't on my end, I forked the CodeSandbox example in the README:
https://codesandbox.io/s/react-view-useview-basic-usage-ygizd
I added a new prop, called "foo" with type of PropTypes.Object. When an object (i.e. {hello: 'world'}) is entered into the knob, it gives an error.

I have tested this on Firefox 71.0 and Chrome 78.

It is possible I am simply using this incorrectly, but none of the examples show how to use an Object knob. The only place I can see an Object prop used in the codebase is in code-generator.test.ts.

Allow variables inside the function body

currently variables inside the function body are only made available when they are passed to the component itself and are mentioned stateful:true , no support for other type of variables is found

Add support for numeric literal types

We have a component with a size prop of numeric literal type.
size?: 14 | 20 | 24 | 32 | 48;

It would be nice to have native support for a knob that can take in a list of values. We already have a documentation tool that tells us the possible values for literal types. We want the same behavior as Enum PropType but currently Enum only works with string literal type.

Option to disable editing in Editor

Is your feature request related to a problem? Please Describe.
I have a use-case where I wanted to disable the editing in the Editor component but currently this is not supported.

Describe the solution you'd like
A prop named enabled or something similar, that can be used to change the state of the Editor.

Missing Undefined check in React.useState()

Problem

Currently, there is missing undefined check in React.useState().
Check here :

react-view/src/ast.ts

Lines 228 to 231 in fed53e0

if (
valueNode.type === 'StringLiteral' ||
valueNode.type === 'BooleanLiteral'
) {

Since we are not passing any argument in React.useState(), it's not rendering appropriate content.

Example Code

const [initialCode, setInitialCode] = React.useState("");
const {compilerProps, errorProps, editorProps} = useView({
    initialCode
  });

React.useEffect(() => {
setInitialCode(`() => {
      const [content, setContent] = React.useState(); // not passing any argument
      const text: string = "Hey";
      return <h2>{text}</h2>;
    }`)
});

How to change the theme?

How to change the theme like baseUI? For example, replace the in the ActionButton component with the in your own component library? thank you very much!

Feature Request: Multiple PropTypes for a prop

I am using react-view for live(interactive) component documentation. I feel that there are cases where a prop can accept multiple types of values or a mixture of values. I don't know this is available or not. (if it is please tell me otherwise is it possible to add this feature)

Example 1

For a Select component if I take an array of objects as options prop then I have to set type to PropTypes.Array but I want to set it to PropTypes.Array(PropTypes.object) so it can be aligned with my internal propTypes.

Example 2

For the same Select component, I will internally use empty string for single select and empty array for multiselect. In this condition, I have a value prop that can either PropTypes.string or PropTypes.Array(PropTypes.String) according to type of select.

Use with webpack & gatsby

Hi there, i've tried to install react-view in a Gatsby project and i'm running into issues with I'm guessing webpack and babel:

This dependency was not found:
* fs in ./node_modules/convert-source-map/index.js, ./node_modules/react-view/node_modules/@babel/core/lib/transformation/normalize-file.js

Stackoverflow suggests adding this to the Webpack config:

node: {
      fs: 'empty'
    }

Which doesn't seem to solve it, is there anything i'm missing? Relatively new to webpack sorry.

Would you consider supporting multiple statements?

I want use JSS in my project demos, It's used as follows:

import React from 'react'
import {createUseStyles} from 'react-jss'

const useStyles = createUseStyles({
  box: {
    color: 'red'
  }
})

export default function Box({ children }) {
  const classes = useStyles()
  return <div className={classes.box}>Hello</div>
}

But currently React View does not support writing multiple statements.

First, we add a return before the first statement, and we will delete export default, and modify the variable declaration statement, leaving only the initial value part.

This will make the above demo code error.

I wonder if it is possible to simply replace the export default statement with a return statement. If there is no export default statement in the code, then convert the last statement to a return statement.

If you think this is feasible, then I can implement it and submit a pull request.

`fs` not found in `react-view` node_modules

I am trying to use react-view's View component to make editable stories for my components. I have installed the react-view using yarn add react-view. But as soon as I create a component, it is giving following errors.

ERROR in ./node_modules/react-view/node_modules/@babel/core/lib/transformation/normalize-file.js
Module not found: Error: Can't resolve 'fs' in '/Users/adityaagarwal/projects/ais-components/node_modules/react-view/node_modules/@babel/core/lib/transformation'
 @ ./node_modules/react-view/node_modules/@babel/core/lib/transformation/normalize-file.js 9:38-51
 @ ./node_modules/react-view/node_modules/@babel/core/lib/transformation/index.js
 @ ./node_modules/react-view/node_modules/@babel/core/lib/transform.js
 @ ./node_modules/react-view/node_modules/@babel/core/lib/index.js
 @ ./node_modules/react-view/dist/es/ui/compiler.js
 @ ./node_modules/react-view/dist/es/index.js
 @ ./stories/button/editable-button.js
 @ ./stories/button/button.stories.js
 @ ./stories sync ^\.\/(?:(?:|\/|(?:(?:(?!(?:|\/)\.).)*?)\/)(?!\.)(?=.)[^\/]*?\.stories\.(js|jsx|ts|tsx|mdx))$
 @ ./.storybook/generated-entry.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./node_modules/@storybook/addon-docs/dist/frameworks/common/config.js ./node_modules/@storybook/addon-docs/dist/frameworks/react/config.js ./.storybook/preview.js ./.storybook/generated-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=true

The following is my editable component code:

import React from 'react';
import { View, PropTypes } from 'react-view';
import Button from '../../src/button';

export default () => (
  <View
    componentName="Button"
    props={{
      text: {
        value: 'Click Me',
        type: PropTypes.String,
        description: 'Text inside the button',
      },
      onClick: {
        value: () => alert('button is clicked'),
        type: PropTypes.Function,
        description: 'Function called when button is clicked',
      },
      isDisabled: {
        value: false,
        type: PropTypes.Boolean,
        description: 'Button is disabled or not',
      },
    }}
    scope={{
      Button,
    }}
    imports={{
      'your-component': {
        default: 'Button',
      },
    }}
  />
);

I have tried installing fs module externally but it didn't work.

docs: Advance examples

First of all kudos to all the contributors for creating such an awesome library. While creating a component demo I stumbled upon the baseweb's component demo which has that cool tab layout. It would be great if the docs include how to create that custom tab layout and use custom components like radio, checkbox etc in place of defaults.

Error while styling the playground components

 <Error msg={params.errorProps.msg} isPopup
        overrides={{
            style: {
              color: '#892C21',
            },
        }}
      />

I tried changing the default theme of the playground components such as error message, checkboxes, sliders but faced errors. Is there something wrong with my implementation.

Screenshot 2020-05-22 at 1 27 29 AM

even setting up className renders error

Things to improve

  • in our baseweb application you can hover over component names in the editor and get a tooltip with flow types, we use extract-react-types-loader and the flexibility of prism-react-renderer to do that, solidify this API, add examples (including typescript)
  • overall better support for typescript, propTypes, should be possible to add the type information into knob tooltips
  • performance improvements, consider using sucrase as a primary compiler while keeping babel around for error messages, prettier and other less performance sensitive things, ideally we should be able to remove debounce and keep all actions (nearly) instant,
    Concurrent Mode should also help
  • bundle size, react-view packs some big dependencies, we should be able to trim them down
  • full-screen mode, some components have a lot of props and it's hard to see all playground components in a single view-port
  • better documentation for advanced APIs customProps and provider, maybe explaning better how to parse ASTs and build them from scratch (the code generation part)
  • better documentation around how react-view works internally
  • prettier is now forked since it requires raw values in the AST + it's including unnecessary language extensions by default, let's figure out what to do about it ... maybe trim it even more and introduce some prettier-light version?

build: Not able to server render.

Hi I am trying to integrate react-view in docusaurus. While running the dev server fs not found issue was there. I fixed it by chain the webpack config.

 node: {
          fs: 'empty',
        },

Unfortunately while building the prod build which is server rendered. I am getting fs error as it's been set to empty.

On useView knobProps don't change if config change

In my project, I'm using useView the problem is that the prop parameter is dynamic, initially, it's an empty object and only then it will be an object with all the props.

const [props, setProps] = React.useState({});


React.useEffect(() => {
    // eslint-disable-next-line unicorn/consistent-function-scoping
    const aux = require('./code/button/demos/exampleKnobs');
    setProps(aux.exampleKnobs.props);
}, []);

const { knobProps } = useView({ props });

from what I understand there is no useEffect that listens for config changes to reset knobsProps.

I try to add something like that to reset settings but keep new props (NOT previous object):

  useEffect(() => {
      dispatch({
          type: Action.Reset,
          payload: {
              code: initialCode,
              props: config.props,
              providerValue: provider.value,
          },
      });
  }, [config.props]);

Another option is to return the function to updateProps, which can receive an object or updateAll which can receive new configurations.

Support for installing with npm

Support for installing with npm

Will you support installing with npm? I am having difficulty installing:

Steps to recreate:

  1. Create a new project in an empty directory with npm init
  2. run npm i -D react-view

Expected behavior

A successful install.

Actual behavior:

Throws an error with the output:

npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall chmod
npm ERR! enoent ENOENT: no such file or directory, chmod '<REDACTED>/node_modules/@miksu/prettier/bin/prettier.js'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!    /<REDACTED>/.npm/_logs/2019-12-05T20_40_29_878Z-debug.log

Attempted fix

I attempted to fix this by running npm i -D @miksu/prettier but the install fails with the same output as above.

VSCode snippets string prop parsed as variable

Hey!

Is it possible for the VSCode snippet to also take into account string enums, instead of objects?

Currently the output of variant prop as:

variant: {
	value: 'primary',
	defaultValue: 'primary',
	type: PropTypes.Enum,
	description: 'Changes the look of the button',
	options: ['primary', 'ghost', 'alert', 'negative', 'fog', 'dark'],
},

would produce the following:

<Button
  variant={primary}
...

Instead, I would want it to respect the options passed in as strings and produce:

<Button
  variant="primary"
...

Thanks!

Some strings are not permissible enum keys

In my application, I am using an enum to allow the user to select between several possible strings, some of which contain - characters. Here is an example of an enum I might have:

options: {
    ['left']: 'left',
    ['top-left']: 'top-left',
    etc...
}

If I then select 'top-left', this will fail the error: ReferenceError: left is not defined

Here's a demo forked from your CodeSandbox:

https://codesandbox.io/s/react-view-useview-basic-usage-kmze8

Select 'compact-broken' to see the error.

So it seems like only strings that would be valid JS identifiers work as enum keys. This means nothing containing -, nothing starting with a number, nothing starting with (, etc.

I believe this can be fixed by accessing enums using bracket notation rather than dot notation.

EDIT: Or, at least, using bracket notation would solve my problem. There are some things that might need to be escaped.

React useRef hook code not generated

We are facing a issue where our component requires a ref to be passed to the component. We are passing ref to useView via the scope property.

scope={{
  ref: React.createRef(),
}}

const {compilerProps, editorProps, errorProps, knobProps} = useView({
  componentName,
  imports: { ... },
  onUpdate(params) { ... },
  props: propsProp as Record<string, TProp>,
  scope,
});

But auto generated editorProps.code code does not contain the useRef hook.

const ref = React.useRef(null);

I deep dived inside the useView code. Inside getCode -> getAstReactHooks, only React.useState template being used to auto generate useState hook. Do we need useRef template here as well based on if scope contains a ref?

Unable to use additional presets

Hi , I am trying to use babel plugin-proposal-decorator

Following is the code snippet I am trying to use

export default () => {
    const params = useView({
        initialCode: code,
        scope: {},
        onUpdate: console.log
    });
    const presets = {
        plugins: [[require("@babel/plugin-proposal-decorators"), {legacy: true}]]
    };
    return (
        <React.Fragment>
            <Compiler {...params.compilerProps} presets={[presets]} />
            <Editor {...params.editorProps} language="tsx" />
            <Error {...params.errorProps} />
        </React.Fragment>
    );
};


Basically I am trying to use autobind decorator for my react class components passed as initial code to useView hook.

Can someone help here?

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.