Code Monkey home page Code Monkey logo

playroom's Introduction

Playroom

Playroom

npm Build Status


Playroom Demo

Simultaneously design across a variety of themes and screen sizes, powered by JSX and your own component library.

Playroom allows you to create a zero-install code-oriented design environment, built into a standalone bundle that can be deployed alongside your existing design system documentation.

  • Iterate on your designs in the final medium.
  • Create quick mock-ups and interactive prototypes with real code.
  • Exercise and evaluate the flexibility of your design system.
  • Share your work with others by simply copying the URL.

Demos

Braid Design System (Themed)

Bumbag

Overdrive

Cubes (Themed)

Mesh Design System (Themed)

Mística Design System (Themed)

Shopify Polaris

Agriculture Design System

Send us a PR if you'd like to be in this list!

Getting Started

$ npm install --save-dev playroom

Add the following scripts to your package.json:

{
  "scripts": {
    "playroom:start": "playroom start",
    "playroom:build": "playroom build"
  }
}

Add a playroom.config.js file to the root of your project:

module.exports = {
  components: './src/components',
  outputPath: './dist/playroom',

  // Optional:
  title: 'My Awesome Library',
  themes: './src/themes',
  snippets: './playroom/snippets.js',
  frameComponent: './playroom/FrameComponent.js',
  scope: './playroom/useScope.js',
  widths: [320, 768, 1024],
  port: 9000,
  openBrowser: true,
  paramType: 'search', // default is 'hash'
  exampleCode: `
    <Button>
      Hello World!
    </Button>
  `,
  baseUrl: '/playroom/',
  webpackConfig: () => ({
    // Custom webpack config goes here...
  }),
  iframeSandbox: 'allow-scripts',
  defaultVisibleWidths: [
    // subset of widths to display on first load
  ],
  defaultVisibleThemes: [
    // subset of themes to display on first load
  ],
};

Note: port and openBrowser options will be set to 9000 and true (respectively) by default whenever they are omitted from the config above.

Your components file is expected to export a single object or a series of named exports. For example:

export { default as Text } from '../Text'; // Re-exporting a default export
export { Button } from '../Button'; // Re-exporting a named export
// etc...

The iframeSandbox option can be used to set the sandbox attribute on Playroom's iframe. A minimum of allow-scripts is required for Playroom to work.

Now that your project is configured, you can start a local development server:

$ npm run playroom:start

To build your assets for production:

$ npm run playroom:build

Snippets

Playroom allows you to quickly insert predefined snippets of code, providing live previews across themes and viewports as you navigate the list. These snippets can be configured via a snippets file that looks like this:

export default [
  {
    group: 'Button',
    name: 'Strong',
    code: `
      <Button weight="strong">
        Button
      </Button>
    `,
  },
  // etc...
];

Custom Frame Component

If your components need to be nested within custom provider components, you can provide a custom React component file via the frameComponent option, which is a path to a file that exports a component. For example, if your component library has multiple themes:

import React from 'react';
import { ThemeProvider } from '../path/to/your/theming-system';

export default function FrameComponent({ theme, children }) {
  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}

Custom Scope

You can provide extra variables within the scope of your JSX via the scope option, which is a path to a file that exports a useScope Hook that returns a scope object. For example, if you wanted to expose a context-based theme variable to consumers of your Playroom:

import { useTheme } from '../path/to/your/theming-system';

export default function useScope() {
  return {
    theme: useTheme(),
  };

Theme Support

If your component library has multiple themes, you can customise Playroom to render every theme simultaneously via the themes configuration option.

Similar to your components file, your themes file is expected to export a single object or a series of named exports. For example:

export { themeA } from './themeA';
export { themeB } from './themeB';
// etc...

TypeScript Support

If a tsconfig.json file is present in your project, static prop types are parsed using react-docgen-typescript to provide better autocompletion in the Playroom editor.

By default, all .ts and .tsx files in the current working directory are included, excluding node_modules.

If you need to customise this behaviour, you can provide a typeScriptFiles option in playroom.config.js, which is an array of globs.

module.exports = {
  // ...
  typeScriptFiles: ['src/components/**/*.{ts,tsx}', '!**/node_modules'],
};

If you need to customise the parser options, you can provide a reactDocgenTypescriptConfig option in playroom.config.js.

For example:

module.exports = {
  // ...
  reactDocgenTypescriptConfig: {
    propFilter: (prop, component) => {
      // ...
    },
  },
};

ESM Support

Playroom supports loading ESM configuration files. By default, Playroom will look for a playroom config file with either a .js, .mjs or .cjs file extension.

Storybook Integration

If you are interested in integrating Playroom into Storybook, check out storybook-addon-playroom.

License

MIT.

playroom's People

Contributors

askoufis avatar benjervis avatar brunnerlivio avatar chardos avatar eps1lon avatar etaoins avatar felixhabib avatar github-actions[bot] avatar grncdr avatar httpete-ire avatar jackhurley23 avatar jesstelford avatar jxom avatar loliver avatar maraisr avatar marijnbrosens avatar markdalgleish avatar mattcompiles avatar michaeltaranto avatar mihkeleidast avatar mrm007 avatar nib-bturner avatar nwalters512 avatar parshap avatar pascalduez avatar pmc-a avatar rbardini avatar ryanhatfield avatar seek-oss-ci avatar yceballost 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  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

playroom's Issues

Hard to Reset

When developing the playroom it is really hard to reset the the code to the exampleCode. It would be nice if there was a sure fire way of resetting the playroom instance. Refreshing doesn't do anything because of the URL. but clearing the URL doesn't seems to work either.

EDIT: You can usually reset the state by deleting all the code and refreshing, but I seemed to be in a state where even doing that didn't reset the code

TypeScript Auto Complete

It will be super helpful to have the props as autocomplete options. Something like VSCode's. You could probably even use there implementation since most of it is distributed as npm packages.

It should be able to work with:

  • Plain old Prop Types
  • Typescript (autocomplete would work amazing)

You could also use parse the JSDoc annotations to get descriptions for the props too.

If not an autocomplete interface it could as just live as another window that pops up and uses reactdocgen to make props table

Runs out of memory during build

I'm using playroom as part of a design system and encountered an issue with playroom running out of memory. We recently added a SVG icon component, which includes ~190 possible SVGs which are about 186kb when loaded all at once.

I've verified the entry file we pass to playroom is all correct, but now playroom runs out of JS memory while building. I haven't had a chance to look at the source yet, but if anyone has any ideas where this might be happening I could use the help.

Thanks!

<--- Last few GCs --->

[45624:0x102644000]    30303 ms: Mark-sweep 1388.1 (1424.9) -> 1388.1 (1425.9) MB, 994.5 / 0.0 ms  (average mu = 0.075, current mu = 0.001) allocation failure scavenge might not succeed
[45624:0x102644000]    31351 ms: Mark-sweep 1389.0 (1425.9) -> 1389.1 (1426.4) MB, 1045.9 / 0.0 ms  (average mu = 0.038, current mu = 0.002) allocation failure scavenge might not succeed


<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x3480c84dbe3d]
Security context: 0x060a8e21e6e1 <JSObject>
    1: /* anonymous */ [0x60a436a8181] [/Users/node_modules/acorn/dist/acorn.js:~2169] [pc=0x3480c8d17244](this=0x060a50986ea9 <Parser map = 0x60acb469039>,refDestructuringErrors=0x060a3b4026f1 <undefined>)
    2: arguments adaptor frame: 0->1
    3: /* anonymous */ [0x60a436a84b9] [/Users/node_modules/acorn/dist/acorn.j...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0x10003b1db node::Abort() [/Users/node/v10.15.1/bin/node]
 2: 0x10003b3e5 node::OnFatalError(char const*, char const*) [/Usersv10.15.1/bin/node]
 3: 0x1001a86b5 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Usersnode/v10.15.1/bin/node]
 4: 0x100573ad2 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/node/v10.15.1/bin/node]
 5: 0x1005765a5 v8::internal::Heap::CheckIneffectiveMarkCompact(unsigned long, double) [/Users/node/v10.15.1/bin/node]
 6: 0x10057244f v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/Users/node/v10.15.1/bin/node]
 7: 0x100570624 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/Users/node/v10.15.1/bin/node]
 8: 0x10057cebc v8::internal::Heap::AllocateRawWithLigthRetry(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [/Users/node/v10.15.1/bin/node]
 9: 0x10057cf3f v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [/Users/node/v10.15.1/bin/node]
10: 0x10054c884 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [/Users/node/v10.15.1/bin/node]
11: 0x1007d4894 v8::internal::Runtime_AllocateInNewSpace(int, v8::internal::Object**, v8::internal::Isolate*) [/Users/node/v10.15.1/bin/node]
12: 0x3480c84dbe3d
13: 0x3480c8d17244
error Command failed with signal "SIGABRT".

React Hooks support

Hey there,

We're migrating all of our Recompose based components to Hooks over the next week or so and I've noticed we get the good old Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call) error when using hooks based components.

Happy to supply a PR once I'm finished our refactoring work.

Cheers.

Upgrade to codemirror2

Every time I install I get this

warning "playroom > [email protected]" has incorrect peer dependency "react@>=15.5 <16".
warning "playroom > [email protected]" has incorrect peer dependency "react-dom@>=15.5 <16".

react-codemirror doesn't seem to have been published in 2 years and depends on an old version of react. playroom itself uses

    "react-dom": "^16.5.2",

So this is where the mismatch comes from. A possible solution would be to upgrade to https://www.npmjs.com/package/react-codemirror2, which allows newer versions of react

    "react": ">=15.5 <=16.x",

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

[feature-request] Prettier... in-the-browser!

Feature request: Have an auto-format, or format button that runs prettier over the code block in-the-browser!

If you're anything like me, you tend to do this; make code change, cmd+ctrl+l, cmd+s. Or in other terms, auto-format then save. Which has quite shamefully caused me to become a lazy developer.

Most online based IDE-esk tools have a similar feature:

sorry, I thought most have it, but turns out neither, TypeScript playground, astexplorer or codepen have this feature 🤷‍♂


If ya'll agree to something like this, I'd be more than happy to attempt at raising a PR that add's this feature.

Configuring how image paths are resolved in Playroom

Hi,

  1. I use Next.js for my application, so I need to write <img src="/image.jpeg"> and background-image: url("/image.jpeg") to display an image stored at public/image.jpeg relative to the project root. (reference to docs on this)

  2. However, Playroom appears to resolve <img> src paths and background-image: url(...) paths from the root of the project. I need to use either <img src="public/image.jpeg"/> or background-image: url('public/image.jpeg') to display the image stored at public/image.jpeg

  3. This makes the paths for my images in the Playroom environment incompatible with the paths that images need to resolve properly in the Next.js environment.

Ideally, I would like all image paths starting with / to resolve to paths starting with /public in the Playroom environment. For example, /image.jpeg would resolve to /public/image.jpeg

What's the best way to accomplish this?

Error Reporting

I started to get errors trying to build my playroom. The program in now way tells you what the errors are. They do not appear in the browser console or the output. The only thing i can see is:

screen shot 2018-11-22 at 9 41 18 pm

I am at a loss at to how to debug this easily.

Prop Type Descriptions

React docgen also parses descriptions of props. It would be really cool if Playroom could display this.

Ways to use:

  1. When autocompleting a prop playroom could show the description and allowed strings for each prop. Here is what it looks like in VSCode

screen shot 2018-12-06 at 1 07 09 am

  1. On hover you could display the same information. And even the type

screen shot 2018-12-06 at 1 10 08 am

Support for multiple component sources

Currently in my playroom.config.js, I am only able to specify a single directory for my components:

module.exports = {
  components: './components/src/',
...
}

However, it would be useful that I could point to a number of component sources by passing an array of paths like this:

module.exports = {
  components: [
  './components/src/',
  './additional-components/src/'
 ],
...
}

Customize filteredPropTypes in options config

Here is where className and children are ignored:

#4 (comment)

I would like to ignore more props that are being injected by libraries like material UI such as classes, and innerRef

I wouldn't mind taking a stab at a PR. Anyone have an idea of an ideal API you'd like to see for this?

Thanks for the great library 🚀

Modify Head

It would be nice to have a way to include things in the head of the page.

For example here i need to include a company font icon hosted on an internal CDN. Something like storybook's preview-head.html would be perfect

Typescript

Project architecture

src/components/index.ts:

export * from './button'; 
export * from './input'; 

src/components/button/index.ts:

export {Button, IProps as IButtonProps} from './Button.tsx';

and the Button is a mere React component.

Playroom

playroom.config.js

module.exports = {
	components: './src/components',
	outputPath: './dist/playroom',
	webpackConfig: () => ({
		module: {
			rules: [
				{
					test: /\.tsx?$/,
					use: [{ loader: 'ts-loader' }]
				}
			]
		}
	})
};

Error

When running playroom start, it produces this error:

$ lerna run --parallel start --scope @myProject/myPackage
lerna notice cli v3.6.0
lerna info filter [ '@myProject/myPackage' ]
lerna info Executing command in 1 package: "yarn run start"
@myProject/myPackage: $ playroom start
@myProject/myPackage: (node:55112) UnhandledPromiseRejectionWarning: /Users/marais/Sites/myProject/packages/myPackage/src/components/index.ts:1
@myProject/myPackage: (function (exports, require, module, __filename, __dirname) { export * from './button';
@myProject/myPackage:                                                               ^^^^^^
@myProject/myPackage: SyntaxError: Unexpected token export
@myProject/myPackage:     at new Script (vm.js:83:7)
@myProject/myPackage:     at createScript (vm.js:267:10)
@myProject/myPackage:     at Object.runInThisContext (vm.js:319:10)
@myProject/myPackage:     at Module._compile (internal/modules/cjs/loader.js:685:28)
@myProject/myPackage:     at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)
@myProject/myPackage:     at Module.load (internal/modules/cjs/loader.js:620:32)
@myProject/myPackage:     at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
@myProject/myPackage:     at Function.Module._load (internal/modules/cjs/loader.js:552:3)
@myProject/myPackage:     at Module.require (internal/modules/cjs/loader.js:658:17)
@myProject/myPackage:     at require (internal/modules/cjs/helpers.js:22:18)
@myProject/myPackage: (node:55112) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
@myProject/myPackage: (node:55112) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
lerna success run Ran npm script 'start' in 1 package in 1.1s:
lerna success - @myProject/myPackage
✨  Done in 1.63s.

Question

Is there a way to make the this work?

Component directory cannot be resolved

Im using CRA + TypeScript and wanted to test out playroom but immediately run into this error:
(node:39309) UnhandledPromiseRejectionWarning: Error: Cannot find module './src/Components'

playroom.config.js

module.exports = {
  components: './src/Components',
  outputPath: './build/playroom',
  typeScriptFiles: [
    'src/Components/**/*.{ts,tsx}',
    '!**/node_modules',
  ],
};

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": [
    "src"
  ]
}

Any ideas about this? 😞

Trying out integrations with Typescript, Monaco Editor, React hooks, and React Box (my own thing)

Hi, Firstly thanks for this super awesome tool. I really loved how simple it is and how simply it works.

I just wanted to share a fork, https://github.com/nksaraf/playroom, that I have been working on for my own use cases. You can see examples of some of the cool things that managed to work in playroom at the end of this comment.

So I integrated the Monaco editor and migrated some of the core Playroom react code to Typescript and hooks because I found it easier to work with. The last and probably the collest thing I was able to make work was being able to use React hooks and that means probably all of React's functionality from the playroom editor. The JSX is still formatted and interpreted correctly even if its has multiple parents tags because we wrap it in a fragment. And no return statement is necessary so its kinda svelte-ish in its look and simplicity. It makes a lot of cool stuff possible. You can also import your own hooks with your components, no additional code is required (probably should add config though). I also have tried useEffect and fetched data all correctly.

All of this works on its own just like the old playroom. But another cool integration that I made is with this library I wrote https://github.com/nksaraf/react-box (not yet published). But its essentially some React primitives (mainly the Box) that wrap functionality from styled-components, styled-system, framer-motion to allow styling and animations declaratively through just props. And with hooks, now writing almost anything should be possible treating the playroom as a functional components. I have deployed this integration at https://playroom.now.sh if anyone wants to give it a try.

Also, if the contributors would want to discuss integrating some of this with the playroom library, I would love to make a pull request but I probably broke a lot of the CI/CD stuff because I am not well versed on it. (Sorry, I am not certain of what the process for this is because this is my first time contributing to open source).

Also @markdalgleish loved your talk on design systems, would love to hear what you think about some of this.

PS: There are still a lot of any's in my typescript but I was just trying to make it work. I haven't got intellisense to work correctly with the user types in Monaco, but I see a path where the types generated by react-docgen can be put into a .d.ts file and fed into the monaco editor that I did with the React types which worked.

Here are some examples of things that becomes possible. You can directly use the links and play around with the code thanks to the sandboxing and how the creators made the code part of the url!

React hooks

Hooks in Playroom Demo

playroom link - hooks

Animation and stlying props with @nksaraf/react-box

Animations with Framer Motion in Playroom Demo

playroom link - animation and styling

Data fetching with useEffect

Data fetching in Playroom Demo

playroom link - Data fetching

Forms with Formik

Forms with Formik Demo

playroom link - Forms with Formik

Missing styles in build vs start

Hi there,

I'm having all sorts of issues that I can't seem to pin down with my built assets not retaining a portion of their styles, using styled-components.

Eg:
screen shot 2018-11-29 at 4 34 21 pm

vs

screen shot 2018-11-29 at 4 35 45 pm

My webpack config as is follows:

  webpackConfig: () => ({
    module: {
      rules: [
        {
          test: /\.js$/,
          loader: 'babel-loader',
          query: {
            plugins: ['lodash'],
            presets: [
              '@babel/preset-react',
              [
                '@babel/preset-env',
                {
                  targets: ['last 2 versions', 'ie >= 11']
                }
              ]
            ]
          },
          exclude: [
            /node_modules\/(?!(@anz)\/).*/
          ]
        },
        {
          test: /\.(otf|ttf|eot|woff(2)?)(\?[a-z0-9=&.]+)?$/,
          loader: 'file-loader'
        },
        {
          test: /\.(jpe?g|png|gif|svg|ico)$/,
          loader: 'file-loader?name=assets/[name].[ext]',
          exclude: '/node_modules/'
        }
      ]
    },
    resolve: {
      extensions: ['.js', '.jsx', '.json']
    }
  })

and frame component is:

import React from 'react'
import { StyleSheetManager } from 'styled-components'

export default ({ children, frameWindow }) => (
  <StyleSheetManager target={frameWindow.document.head}>
    {children}
  </StyleSheetManager>
)

Everything works perfectly using start but the built assets seem to lose some of their font-family, padding, and margin, while color and border seem to stay attached somehow. No webpack errors in the terminal while building, and the generated style tags in each frame's head are empty in build, but full of expected classes etc in start.

0.11.2 breaks webpackConfig.resolve.extensions

Hello,

Since upgrading to 0.11.2, webpackConfig.resolve.extensions is not taken into account anymore.

I have components importing files without specifying the extension, and the file can either be .ts or .json, and webpackConfig.resolve.extensions is set to ['.tsx', '.ts', '.js', '.json'].

It works fine with 0.11.1, but not with 0.11.2 (or 0.11.3).

Thanks in advance!

Code can break out of the iframe and modify parent page (XSS)

It is currently possible to access window.parent inside of the render iframes which allows a malicious actor to take advantage of XSS or some accidentally dodgy code to crash the Playroom environment.

Is it within the scope of this project to guard against these sorts of problems?

Example

<div>
	{window.parent.document.body.innerHTML = '<h1>You\'ve been hacked lol</h1>'}
</div>

https://seek-oss.github.io/braid-design-system/playroom/#?code=N4Igxg9gJgpiBcIA8AhCAPAfAHQHbAHcBLXKCAgOgAcBDAJxlwBcKywBXAW0ZYCNoAnhRK4YdABIAVALIAZAAQBeeQHIkACwCMmAJoR22bCoBuMebxiN56mmADWMKPIA2EZ0gD0WzCoC+ntCwQXyA

Potential fixes

Adding sandbox="allow-scripts" to the iframe component fixes this issue at the cost of completely breaking HMR.

I tried evaling the code in a worker but I don't think React components are structured-clonable

Maybe it's possible to use realms-shim with a bit of work?

Can't get build to output files

Hi again,

Everything is working with yarn run playroom:start but I can't get yarn run playroom:build to output actual files, have my outputPath set to './dist/playroom' and my webpackConfig is as per below:

  webpackConfig: () => ({
    module: {
      rules: [
        {
          test: /\.js$/,
          loader: 'babel-loader',
          query: {
            plugins: ['lodash'],
            presets: [
              '@babel/preset-react',
              [
                '@babel/preset-env',
                {
                  targets: ['last 2 versions', 'ie >= 11']
                }
              ]
            ]
          },
          exclude: [
            /node_modules\/(?!(@anz)\/).*/
          ]
        },
        {
          test: /\.(otf|ttf|eot|woff(2)?)(\?[a-z0-9=&.]+)?$/,
          loader: 'file-loader'
        },
        {
          test: /\.(jpe?g|png|gif|svg|ico)$/,
          loader: 'file-loader?name=assets/[name].[ext]',
          exclude: '/node_modules/'
        }
      ]
    },
    resolve: {
      extensions: ['.js', '.jsx', '.json']
    }
  })

Anything obvious in there that I've missed? I've looked at the examples again today but it seems to work similarly to them.

Bug: toolBar icon fails

When I click the toolbar icon to move the editor to a separate window a blank window pops up and rendering itself goes white too.

The editor console has no errors. But the rendering has a bunch of errors

Here is the stack trace

index.js?dd39:7 Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules
    at eval (webpack-internal:///../../../../playroom/src/Playroom/WindowPortal/index.js:35:20)
    at Array.forEach (<anonymous>)
    at copyStyles (webpack-internal:///../../../../playroom/src/Playroom/WindowPortal/index.js:34:37)
    at WindowPortal.eval [as createWindow] (webpack-internal:///../../../../playroom/src/Playroom/WindowPortal/index.js:70:7)
    at WindowPortal.componentDidMount (webpack-internal:///../../../../playroom/src/Playroom/WindowPortal/index.js:88:12)
    at commitLifeCycles (webpack-internal:///../../../../playroom/node_modules/react-dom/cjs/react-dom.development.js:15255:22)
    at commitAllLifeCycles (webpack-internal:///../../../../playroom/node_modules/react-dom/cjs/react-dom.development.js:16523:7)
    at HTMLUnknownElement.callCallback (webpack-internal:///../../../../playroom/node_modules/react-dom/cjs/react-dom.development.js:149:14)
    at Object.invokeGuardedCallbackDev (webpack-internal:///../../../../playroom/node_modules/react-dom/cjs/react-dom.development.js:199:16)
    at invokeGuardedCallback (webpack-internal:///../../../../playroom/node_modules/react-dom/cjs/react-dom.development.js:256:31)
(anonymous) @ index.js?dd39:7
copyStyles @ index.js?dd39:6
(anonymous) @ index.js?dd39:64
componentDidMount @ index.js?dd39:41
commitLifeCycles @ react-dom.development.js?bffb:15255
commitAllLifeCycles @ react-dom.development.js?bffb:16523
callCallback @ react-dom.development.js?bffb:149
invokeGuardedCallbackDev @ react-dom.development.js?bffb:199
invokeGuardedCallback @ react-dom.development.js?bffb:256
commitRoot @ react-dom.development.js?bffb:16677
completeRoot @ react-dom.development.js?bffb:18069
performWorkOnRoot @ react-dom.development.js?bffb:17997
performWork @ react-dom.development.js?bffb:17901
performSyncWork @ react-dom.development.js?bffb:17873
interactiveUpdates$1 @ react-dom.development.js?bffb:18164
interactiveUpdates @ react-dom.development.js?bffb:2217
dispatchInteractiveEvent @ react-dom.development.js?bffb:4916
react-dom.development.js?bffb:15123 The above error occurred in the <WindowPortal> component:
    in WindowPortal (created by Playroom)
    in div (created by Playroom)
    in Playroom

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js?bffb:15123
logError @ react-dom.development.js?bffb:15157
update.callback @ react-dom.development.js?bffb:15902
callCallback @ react-dom.development.js?bffb:11194
commitUpdateEffects @ react-dom.development.js?bffb:11233
commitUpdateQueue @ react-dom.development.js?bffb:11221
commitLifeCycles @ react-dom.development.js?bffb:15290
commitAllLifeCycles @ react-dom.development.js?bffb:16523
callCallback @ react-dom.development.js?bffb:149
invokeGuardedCallbackDev @ react-dom.development.js?bffb:199
invokeGuardedCallback @ react-dom.development.js?bffb:256
commitRoot @ react-dom.development.js?bffb:16677
completeRoot @ react-dom.development.js?bffb:18069
performWorkOnRoot @ react-dom.development.js?bffb:17997
performWork @ react-dom.development.js?bffb:17901
performSyncWork @ react-dom.development.js?bffb:17873
interactiveUpdates$1 @ react-dom.development.js?bffb:18164
interactiveUpdates @ react-dom.development.js?bffb:2217
dispatchInteractiveEvent @ react-dom.development.js?bffb:4916
react-dom.development.js?bffb:210 Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://fb.me/react-crossorigin-error for more information.
    at Object.invokeGuardedCallbackDev (react-dom.development.js?bffb:210)
    at invokeGuardedCallback (react-dom.development.js?bffb:256)
    at commitRoot (react-dom.development.js?bffb:16677)
    at completeRoot (react-dom.development.js?bffb:18069)
    at performWorkOnRoot (react-dom.development.js?bffb:17997)
    at performWork (react-dom.development.js?bffb:17901)
    at performSyncWork (react-dom.development.js?bffb:17873)
    at interactiveUpdates$1 (react-dom.development.js?bffb:18164)
    at interactiveUpdates (react-dom.development.js?bffb:2217)
    at dispatchInteractiveEvent (react-dom.development.js?bffb:4916)
invokeGuardedCallbackDev @ react-dom.development.js?bffb:210
invokeGuardedCallback @ react-dom.development.js?bffb:256
commitRoot @ react-dom.development.js?bffb:16677
completeRoot @ react-dom.development.js?bffb:18069
performWorkOnRoot @ react-dom.development.js?bffb:17997
performWork @ react-dom.development.js?bffb:17901
performSyncWork @ react-dom.development.js?bffb:17873
interactiveUpdates$1 @ react-dom.development.js?bffb:18164
interactiveUpdates @ react-dom.development.js?bffb:2217
dispatchInteractiveEvent @ react-dom.development.js?bffb:4916
react-dom.development.js?bffb:520 Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in Playroom
warningWithoutStack @ react-dom.development.js?bffb:520
warnAboutUpdateOnUnmounted @ react-dom.development.js?bffb:16263
scheduleWorkToRoot @ react-dom.development.js?bffb:17508
scheduleWork @ react-dom.development.js?bffb:17548
enqueueSetState @ react-dom.development.js?bffb:11695
Component.setState @ react.development.js?a626:373
(anonymous) @ Playroom.js?cbaf:108
(anonymous) @ Playroom.js?cbaf:174

There is another error below this one but it looks to just be because this first error happened

Custom webpack + load css

Hello everyone.

First of all I'd say thank you for this project. I'm currently implement for both components library in my company and people are quite happy with it!

Although I'm having some issues to setup for the second library (which uses material-ui as core base).

First case: no custom config

If I just create playroom.config.js:

module.exports = {
  components: './src/index.js',
  outputPath: './public/playroom',
  title: 'Internal Component Library',
  frameComponent: './.playroom/FragmentComponent.js',
  widths: [320, 375, 768, 1024],
  port: 9000,
  openBrowser: false,
  exampleCode: `
    <Button>
      Hello World!
    </Button>
  `,
};

and try to yarn playroom start, I got an error:

$ /Users/raulmelo/projects/youngcapital/internal-component-library/node_modules/.bin/playroom start


 ERROR  Failed to compile with 1 errors                                                                                              10:59:19 AM

 error  in ./node_modules/react-dates/lib/css/_datepicker.css

Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.or
g/concepts#loaders
> .PresetDateRangePicker_panel {
|   padding: 0 22px 11px
| }

 @ ./src/custom/Form/components/DateRange/DateRange.js 43:0-46
 @ ./src/custom/Form/components/DateRange/index.js
 @ ./src/custom/Form/components/Input/Input.js
 @ ./src/custom/Form/components/Input/index.js
 @ ./src/custom/Form/components/index.js
 @ ./src/custom/Form/index.js
 @ ./src/custom/index.js
 @ ./src/index.js
 @ ./node_modules/playroom/src/Playroom/components.js
 @ ./node_modules/playroom/src/Playroom/Frame.js
 @ ./node_modules/playroom/src/frame.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/frame.js

Ok, that's fine and clear. It's only about using correct loaders, right?

Second case: Add CSS loader

Easy task, you guys provide a webpackConfig function, right? Then I just add it:

module.exports = {
  components: './src/index.js',
  outputPath: './public/playroom',
  title: 'Internal Component Library',
  frameComponent: './.playroom/FragmentComponent.js',
  widths: [320, 375, 768, 1024],
  port: 9000,
  openBrowser: false,
  exampleCode: `
    <Button>
      Hello World!
    </Button>
  `,
  webpackConfig: () => ({
    module: {
      rules: [
        {
          test: /\.css$/,
          loaders: [
            'style-loader',
            'css-loader',
            {
              loader: 'postcss-loader',
              options: { plugins: () => [require('autoprefixer')()] },
            },
          ],
        },
      ],
    },
  }),
};

And now I got:

in ./src/custom/ICLModal/components/ModalFooter.js

Module parse failed: Unexpected token (9:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
| const ModalFooter = ({ classes, onClickButton, buttonTitle, children, className, ButtonProps }) => (
>   <div className={classnames(classes.modalFooter__root, className)}>
|     {children || (
|       <Button color="secondary" variant="contained" onClick={onClickButton} {...ButtonProps}>

 @ ./src/custom/ICLModal/components/index.js 2:0-55 2:0-55
 @ ./src/custom/ICLModal/index.js
 @ ./src/custom/index.js
 @ ./src/index.js
 @ ./node_modules/playroom/src/Playroom/components.js
 @ ./node_modules/playroom/src/Playroom/Frame.js
 @ ./node_modules/playroom/src/frame.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/frame.js

error  in ./src/custom/Form/components/Checkbox/Checkbox.js

Module parse failed: Unexpected token (9:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
| class ICLCheckbox extends React.PureComponent {
>   state = {
|     selectedList: [],
|   };

 @ ./src/custom/Form/components/Checkbox/index.js 1:0-37 1:0-37
 @ ./src/custom/Form/components/index.js
 @ ./src/custom/Form/index.js
 @ ./src/custom/index.js
 @ ./src/index.js
 @ ./node_modules/playroom/src/Playroom/components.js
 @ ./node_modules/playroom/src/Playroom/Frame.js
 @ ./node_modules/playroom/src/frame.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/frame.js

Ok, it looks my config is not been merged. Not problem, I can add my own js loader.

Third case: add JS loader (and final situation)

const path = require('path');

const commonIncludes = [path.resolve(__dirname, './'), path.resolve(__dirname, './src')];

module.exports = {
  components: './src/index.js',
  outputPath: './public/playroom',
  title: 'Internal Component Library',
  frameComponent: './.playroom/FragmentComponent.js',
  widths: [320, 375, 768, 1024],
  port: 9000,
  openBrowser: false,
  exampleCode: `
    <Button>
      Hello World!
    </Button>
  `,
  webpackConfig: () => ({
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          include: commonIncludes,
          exclude: /node_modules/,
          use: {
            loader: require.resolve('babel-loader'),
            options: {
              presets: [
                require.resolve('@babel/preset-env'),
                require.resolve('@babel/preset-react'),
              ],
            },
          },
        },
        {
          test: /\.css$/,
          loaders: [
            'style-loader',
            'css-loader',
            {
              loader: 'postcss-loader',
              options: { plugins: () => [require('autoprefixer')()] },
            },
          ],
        },
      ],
    },
  }),
};

By adding this piece of config, js part works fine, but then I have finally the issue I need some help:

yarn playroom start
yarn run v1.17.3
warning package.json: No license field
$ /Users/raulmelo/projects/youngcapital/internal-component-library/node_modules/.bin/playroom start


 ERROR  Failed to compile with 2 errors                                                                                              11:07:17 AM

 error  in ./node_modules/codemirror/lib/codemirror.css

Module build failed (from ./node_modules/playroom/node_modules/css-loader/index.js):
Unknown word (1:1)

> 1 | var content = require("!!../../css-loader/dist/cjs.js!../../postcss-loader/src/index.js??ref--8-2!./codemirror.css");
    | ^
  2 | 
  3 | if (typeof content === 'string') {
  4 |   content = [[module.id, content, '']];


 @ ./node_modules/codemirror/lib/codemirror.css 2:14-197 21:1-42:3 22:19-202
 @ ./node_modules/playroom/src/Playroom/Playroom.js
 @ ./node_modules/playroom/src/index.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/index.js

 error  in ./node_modules/codemirror/theme/neo.css

Module build failed (from ./node_modules/playroom/node_modules/css-loader/index.js):
Unknown word (1:1)

> 1 | var content = require("!!../../css-loader/dist/cjs.js!../../postcss-loader/src/index.js??ref--8-2!./neo.css");
    | ^
  2 | 
  3 | if (typeof content === 'string') {
  4 |   content = [[module.id, content, '']];


 @ ./node_modules/codemirror/theme/neo.css 2:14-190 21:1-42:3 22:19-195
 @ ./node_modules/playroom/src/Playroom/Playroom.js
 @ ./node_modules/playroom/src/index.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/index.js

I tried to solve that issue by including node_modules in css rule, didn't work. Also tried to google and it most of suggestion were "Yee, I fix the loader order to style-loader <- css-loader <- postcss-loader and it works, but as you can see it's already in this way.

If I completely exclude node_modules, I have a different issue:

in ./node_modules/react-dates/lib/css/_datepicker.css

Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.or
g/concepts#loaders
> .PresetDateRangePicker_panel {
|   padding: 0 22px 11px
| }

 @ ./src/custom/Form/components/DateRange/DateRange.js 15:0-45
 @ ./src/custom/Form/components/DateRange/index.js
 @ ./src/custom/Form/components/Input/Input.js
 @ ./src/custom/Form/components/Input/index.js
 @ ./src/custom/Form/components/index.js
 @ ./src/custom/Form/index.js
 @ ./src/custom/index.js
 @ ./src/index.js
 @ ./node_modules/playroom/src/Playroom/components.js
 @ ./node_modules/playroom/src/Playroom/Frame.js
 @ ./node_modules/playroom/src/frame.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/frame.js

Which makes sense, because inside my component I have:

// bla bla
import 'react-dates/lib/css/_datepicker.css';

Do you have any suggestion how can I handle it?

Cheers.

SVG support webpack config

Hi,

I was trying to have a component that imports an svg and then displays that within the component, svg isn't handled by default in playroom webpack config so thought it would just be a case of including it in custom config and that would be merged with playrooms webpack config

  webpackConfig: () => ({
    module: {
      rules: [
        {
          test: /\.svg$/,
          loader: 'svg-inline-loader',
        },
      ],
    },
  }),

But this seems to overwrite the playroom webpack config and errors appear about being unable to handle .js files

Got an error `Element type is invalid` when using custom component

Hi ✋, I've been trying Playroom for my custom components, but got this error after run yarn playroom:start

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `RenderCode`.

I tried using built-in components, like div, button, etc. worked well, but got an error for my custom component.

This is my playroom.config.js looks like:

// playroom.config.js
module.exports = {
  components: './src/components',
  outputPath: './dist/playroom',

  // Optional:
  title: 'Component Library',
  widths: [375],
  port: 9000,
  openBrowser: true,
};

./src/components.js

module.exports = {
  Button: require('../components/Button'),
};

../components/Button

import React from 'react';

const Button = ({ children }) => (
  <button style={{ backgroundColor: 'green', color: '#FFF' }}>
    {children}
  </button>
);

export default Button;

I checked the RenderCode.js, scopeEval returning an object indeed, but it works for built-in component. Did I miss something? Thanks

Props Spread and inline props don't work together

Summary

I can use prop spreading in playroom e.g.

{ (props = { a: 'b', c: 'd' }) && null }

<Button {...props}>Click Me</Button>

I can use inline (regular) props too:

<Button a="b" c="d">Click Me</Button>

I cannot use both at the same time:

{ (props = { a: 'b', c: 'd' }) && null }

<Button {...props} e="f">Click Me</Button>

This doesn't work regardless of whether or not:

  • you spread first, then use regular props
  • you use regular props then spread
  • your regular props and spread props contain the same props

Additional challenges

Note that spreading inside an inline object also does not work:

<Button {...({ ...props, e: 'f' })}>Click Me</Button>

Current Workaround

Either I don't use spreads ( :( ) or I've been doing this:

{ (props = { a: 'b', c: 'd' }) && null }

<Button {...(Object.assign({}, props, { e: 'f' })}>Click Me</Button>

Which is noticeably verbose

React Native support

At first glance it does not seem that playroom supports react native. What would need to be in place for this to work on mobile / are there alternatives?

Multiple example code

Instead of only being able to have one template page (example) it would be useful to be able to pick from multiple options

Why does it show `Unexpected token`?

When I setup playroom for my react project, I get below error but I don't know why.

image

This is my configuration:

const path = require('path');

module.exports = {
  components: './src/app/components/Commons/TextButton.tsx',
  outputPath: './dist/playroom',

  // Optional:
  title: 'POS Awesome Library',
  // themes: './src/themes',
  // frameComponent: './playroom/FrameComponent.js',
  widths: [320, 375, 768, 1024],
  port: 9000,
  openBrowser: true,
  exampleCode: `
    <TextButton text="Hello" />
  `,
  webpackConfig: () => ({
    // Custom webpack config goes here...
    module: {
      rules: [
        // .ts, .tsx
        {
          test: /\.tsx?$/,
          use: [
            {
              loader: 'babel-loader',
              options: { plugins: ['react-hot-loader/babel'] }
            },
            'ts-loader'
          ].filter(Boolean)
        }
      ]
    },
    resolve: {
      extensions: ['.js', '.ts', '.tsx'],
      alias: {
        app: path.resolve(__dirname, 'src', 'app'),
        '@ap-components': path.resolve(__dirname, 'src', 'app', 'components'),
        '@ap-actions': path.resolve(__dirname, 'src', 'app', 'actions'),
        '@ap-containers': path.resolve(__dirname, 'src', 'app', 'containers'),
        '@ap-reducers': path.resolve(__dirname, 'src', 'app', 'reducers'),
        '@ap-utils': path.resolve(__dirname, 'src', 'app', 'utils'),
        '@ap-icons': path.resolve(__dirname, 'src', 'app', 'icons'),
        '@ap-assets': path.resolve(__dirname, 'src', 'assets'),
        '@ap-models': path.resolve(__dirname, 'src', 'app', 'models')
      }
    }
  })
};

Styled-jsx support?

Hi guys, I'm trying to use styled-jsx with playroom and don't know really well where to start to make this possible. is there any doc that I can read to make it happen? Thanks!

Props autocomplete for components with declaration files

I was super impressed by the presentation at React Amsterdam 2019 and immediately started playing with some ideas. After some little experiments I was already pretty satisfied. The biggest issue right now is missing props autocomplete. The problem is that the props are not defined in an actual TypeScript file but in a declarations file. It seems like react-docgen-typescript can't detect components in those properly.

It's not really important to get this working from the typescript declarations. Those are pretty complicated and we already have this information available from another source. My question is if I should rather work on making react-docgen-typescript work with declaration files or work on an API for playroom so that I can inject prop types from arbitrary sources. Essentially allowing plugins for typescript, flow or prop-types.

URL Shortening

Putting this here as i'll probably implement this, but, It would be nice to have an ability to copy a shortURL (instead of base64 links) for pasting in Slack/etc.

I was pairing with another dev the other day and we passed 4-5 links back and forth taking over our slack convo with huge link blocks. (I ended up just using bit.ly, but it would be nice if I could copy a short-link right from the playroom)

Trying out snippets

// playroom.config.js

module.exports = {
  title: 'Playroom',
  outputPath: './dist',
  components: '...',
  snippets: './snippets/index.js',
};
// ./snippets/index.js

import React from 'react';
import { Button } from '...';

export default [
  {
    group: 'Button',
    name: 'Test',
    code: <Button>Test</Button>,
  },
];
TypeError: snippet.split is not a function

Support state

It'd be great if users could make their designs stateful.

My thinking is that we could do this in a code-oriented way by allowing usage of React hooks like this:

const [ firstName, setFirstName ] = useState('');
const [ lastName, setLastName ] = useState('');

<TextField label="First name" value={name} onChange=(event => setFirstName(event.target.value)} />
<TextField label="Last name" value={name} onChange=(event => setLastName(event.target.value)} />

For this to work, we'd need to treat the last n number of JSX elements as an implicitly returned fragment, i.e. behind the scenes we'd turn it into a component that looks like this:

() => {
  const [ firstName, setFirstName ] = useState('');
  const [ lastName, setLastName ] = useState('');

  return (
    <React.Fragment>
      <TextField label="First name" value={name} onChange=(event => setFirstName(event.target.value)} />
      <TextField label="Last name" value={name} onChange=(event => setName(event.target.value)} />
    </React.Fragment>
  );
};

Getting RenderCode(...) error

Tried setting this up for a create-react-app build. npm run playroom:start compiles but all the frames give me the following error:

RenderCode(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Running the regular app with just a plain text component works just fine so I'm not suspecting an issue on that end.

This is my playroom.config.js

module.exports = {
    components: './src/components',
    outputPath: './dist/playroom',
  
    // Optional:
    title: 'My Awesome Library',
    widths: [320, 375, 768, 1024],
    port: 9000,
    openBrowser: true,
  };

Here is what I get.
image

I'm completely stuck on this. Any idea what might be causing this issue?

Question regarding component exports

I believe I may be misunderstanding the methods for importing components. I've noticed if I define a components as shown below:

// src/components/Button/Button.js
import React from 'react'
const Button = props => <button {...props} />
export default Button
// src/components/Text/Text.js
import React from 'react'
export const Text = props => <p {...props} />

and my components file looks like

const Button = require('./Button/Button')
const { Text } = require('./Text/Text')

module.exports = {
  Text,
  Button,
  // etc...
}

only the Text component will work. The button component is throwing an error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `RenderCode`.

It seems I can use named exports just fine but using a default export gives me an error. Is there a correct way to use a default-exported component? Below are links to the demo repo and a live demo.

Links

sample repository
live demo

Seems can't parse JSX syntax

Seems the webpack can't parse JSX syntax. On a minimalist example I get following error in JS console:

index.js:1 Uncaught Error: Module parse failed: Unexpected token (45:2)
You may need an appropriate loader to handle this file type.
| 
| render(
>   <Playroom
|     themes={themes}
|     components={components}
    at eval (index.js:1)
    at Object../node_modules/playroom/src/index.js (main.js:96)
    at __webpack_require__ (main.js:20)
    at main.js:84
    at main.js:87

CodeMirror is not defined

Hey mate, love that you've open sourced this.

I'm getting an error out of the gate with CodeMirror not recognising itself inside show-hint.js and was hoping this is an easy thing to fix.

Error stack below:

Uncaught ReferenceError: CodeMirror is not defined
    at eval (show-hint.js?7c1c:12)
    at Module.eval (show-hint.js?7c1c:6)
    at eval (show-hint.js:496)
    at Module../node_modules/playroom/src/Playroom/codemirror/show-hint.js (main.js:3123)
    at __webpack_require__ (main.js:20)
    at eval (Playroom.js?4070:27)
    at Module.eval (Playroom.js?4070:22)
    at eval (Playroom.js:437)
    at Module../node_modules/playroom/src/Playroom/Playroom.js (main.js:3053)
    at __webpack_require__ (main.js:20)

Cheers.

Ignore .babelrc / Babel 6 compatibility?

👋

Loving this so far, thanks for the awesome work you're doing with Playroom.

Overview

I've installed it into an existing project. The project uses it's own .babelrc and webpack.config.js.

I have written a dummy component, and pointed playroom at it:

// playroom/components.js

const React = require('react');

module.exports = {
  Button: ({ children }) => <button>{children}</button>,
};
// playroom.config.js

module.exports = {
  components: './playroom/components',
  outputPath: './playroom/dist',
  title: 'My Playroom',
  widths: [320, 375, 768, 1024],
  exampleCode: `
    <Button>
      Hello World!
    </Button>
  `,
};

This component doesn't require any fancy processing, so I've not added custom webpack config.

The Issue

When I run playroom:start, it appears to use babel by default. It also appears to use my .babelrc by default.

My .babelrc includes some plugins/presets that are compatible with Babel 6 but not 7.

I get the following error:

 ERROR  Failed to compile with 1 errors

 error  in ./playroom/components.js

Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Plugin/Preset files are not allowed to export objects, only functions. In /Users/xxx/xxx/xxx/my-babel-6-preset/lib/index.js

Expected

I figured it would be nice if this could either respect my babel config and support babel 6, OR allow me to ignore my babel config, and provide newer, separate config for Playroom's babelling?

Cannot create ErrorBoundary Component

Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):

SyntaxError: ErrorBoundary.js: Support for the experimental syntax 'classProperties' isn't currently enabled:

static getDerivedStateFromError = error => ({ hasError: true, error });

Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.

Please tell me how to either add that plugin to the webpackConfig: () => ({ }) or please add that plugin to the default build - in fact I encourage keeping up to date with CRA's webpack config.

Doesn't work keeps asking for subscription

I can't get it to work for free I get this message

You don't have an active subscription. Please go to our website to subscribe. Once finished, click here to reload.
Click here to login as a different user.

Can't load CSS

I can't get Playroom to properly load css files from my project.

By default, I get the following error:

 ERROR  Failed to compile with 1 errors                                                          12:03:24 PM

 error  in ./node_modules/typeface-exo-2/index.css

Module parse failed: Unexpected character '@' (2:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| /* exo-2-100normal - latin */
> @font-face {
|   font-family: 'Exo 2';
|   font-style: normal;

 @ ./app/theme.js 7:0-24
 @ ./playroom/themes.js
 @ ./node_modules/playroom/src/themes.js
 @ ./node_modules/playroom/src/frame.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/frame.js

And if I add the css loader to playroom.config.js, I get this other error.

        {
          test: /\.css$/,
          use: [require.resolve("style-loader"), require.resolve("css-loader")],
        },
 ERROR  Failed to compile with 2 errors                                                          12:00:49 PM

 error  in ./node_modules/codemirror/lib/codemirror.css

Syntax Error: CssSyntaxError

(1:1) Unknown word

> 1 | var api = require("!../../style-loader/dist/runtime/injectStylesIntoStyleTag.js");
    | ^
  2 |             var content = require("!!../../css-loader/dist/cjs.js!./codemirror.css");
  3 |



 @ ./node_modules/codemirror/lib/codemirror.css 2:26-144 22:4-35:5 25:25-143
 @ ./node_modules/playroom/src/Playroom/CodeEditor/CodeEditor.tsx
 @ ./node_modules/playroom/src/Playroom/Playroom.tsx
 @ ./node_modules/playroom/src/index.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/index.js

 error  in ./node_modules/codemirror/theme/neo.css

Syntax Error: CssSyntaxError

(1:1) Unknown word

> 1 | var api = require("!../../style-loader/dist/runtime/injectStylesIntoStyleTag.js");
    | ^
  2 |             var content = require("!!../../css-loader/dist/cjs.js!./neo.css");
  3 |



 @ ./node_modules/codemirror/theme/neo.css 2:26-137 22:4-35:5 25:25-136
 @ ./node_modules/playroom/src/Playroom/CodeEditor/CodeEditor.tsx
 @ ./node_modules/playroom/src/Playroom/Playroom.tsx
 @ ./node_modules/playroom/src/index.js
 @ multi webpack-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./node_modules/playroom/src/index.js


It appears Playroom isn't properly merging the webpack config or something. However, there's certainly a possibility I'm doing something wrong.

Missing dependency: webpack-dev-server

After running yarn add --dev playroom and adding the two scripts to my package.json, I get the following error:

$ yarn playroom:start
yarn run v1.17.3
$ playroom start
ℹ 「wds」: Project is running at http://localhost:12345/
ℹ 「wds」: webpack output is served from undefined
ℹ 「wds」: Content not from webpack is served from /Users/npresta/wave/src/lighthouse
Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`


 ERROR  Failed to compile with 11 errors                                                                                                     2:44:32 PM

This dependency was not found:

* webpack-dev-server/client?http://localhost:12345 in multi webpack-dev-server/client?http://localhost:12345 webpack/hot/dev-server ./node_modules/playroom/src/frame.js, multi (webpack)-dev-server/client?http://localhost (webpack)/hot/dev-server.js webpack-dev-server/client?http://localhost:12345 webpack/hot/dev-server ./node_modules/playroom/src/frame.js and 2 others

To install it, you can run: npm install --save webpack-dev-server/client?http://localhost:12345

here is my playroom.config.js:

module.exports = {
  components: './src/lighthouse.ts',
  outputPath: './dist/playroom',

  // Optional:
  title: 'Lighthouse Component Library',
  widths: [320, 375, 768, 1024],
  port: 12345,
  openBrowser: true,
  exampleCode: `
    <WaveButton>
      Hello World!
    </WaveButton>
  `,
};

I'm somewhat confused by the error message (about missing webpack-dev-server) given that yarn thinks it's installed:

$ yarn why webpack-dev-server
yarn why v1.17.3
[1/4] 🤔  Why do we have the module "webpack-dev-server"...?
[2/4] 🚚  Initialising dependency graph...
[3/4] 🔍  Finding dependency...
[4/4] 🚡  Calculating file sizes...
=> Found "[email protected]"
info Reasons this module exists
   - "playroom" depends on it
   - Hoisted from "playroom#webpack-dev-server"
✨  Done in 0.98s.

The project itself ("lighthouse") doesn't actually use webpack-dev-server and uses webpack-serve instead. If I explicitly install yarn add --dev [email protected] the error goes away.

I would've thought that explicitly adding webpack-dev-server to playroom's dependencies would be enough, but it isn't in this case. I'm not sure why.

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.