├── .babelrc ├── .changeset ├── README.md ├── config.json ├── loose-states-rescue.md └── spicy-ants-push.md ├── .editorconfig ├── .github ├── CODEOWNERS └── workflows │ ├── preview-site.yml │ ├── release.yml │ ├── snapshot.yml │ └── validate.yml ├── .gitignore ├── .husky └── pre-commit ├── .nvmrc ├── .prettierignore ├── .prettierrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── bin └── cli.cjs ├── cypress.config.mjs ├── cypress ├── e2e │ ├── editor.cy.ts │ ├── keymaps.cy.ts │ ├── scope.cy.ts │ ├── smoke.cy.ts │ ├── snippets.cy.ts │ ├── toolbar.cy.ts │ └── urlHandling.cy.ts ├── projects │ ├── basic │ │ ├── components.js │ │ ├── playroom.config.js │ │ ├── serve.json │ │ ├── snippets.js │ │ └── useScope.js │ ├── themed │ │ ├── components.js │ │ ├── playroom.config.js │ │ ├── serve.json │ │ ├── snippets.js │ │ └── themes.js │ └── typescript │ │ ├── components.ts │ │ ├── components │ │ ├── Bar.tsx │ │ ├── Foo.tsx │ │ └── styles.ts │ │ ├── playroom.config.js │ │ ├── serve.json │ │ ├── snippets.ts │ │ └── tsconfig.json ├── support │ ├── commands.js │ ├── e2e.js │ └── utils.ts └── tsconfig.json ├── eslint.config.mjs ├── images ├── demo.gif ├── favicon-inverted.png ├── favicon.png ├── logo-inverted.png ├── logo.ai └── logo.png ├── lib ├── .npmignore ├── build.js ├── defaultModules │ ├── FrameComponent.js │ ├── snippets.js │ ├── themes.js │ └── useScope.js ├── getStaticTypes.js ├── getStaticTypes.test.ts ├── index.js ├── makeDefaultWebpackConfig.js ├── makeWebpackConfig.js ├── provideDefaultConfig.js └── start.js ├── package.json ├── pnpm-lock.yaml ├── scripts └── postCommitStatus.js ├── src ├── .npmignore ├── Playroom │ ├── Box │ │ └── Box.tsx │ ├── Button │ │ ├── Button.css.ts │ │ └── Button.tsx │ ├── CatchErrors │ │ ├── CatchErrors.css.ts │ │ └── CatchErrors.tsx │ ├── CodeEditor │ │ ├── CodeEditor.css.ts │ │ ├── CodeEditor.tsx │ │ ├── CodeMirror2.tsx │ │ └── keymaps │ │ │ ├── comment.ts │ │ │ ├── complete.ts │ │ │ ├── cursors.ts │ │ │ ├── lines.ts │ │ │ ├── types.ts │ │ │ └── wrap.ts │ ├── Frame.tsx │ ├── Frames │ │ ├── Frames.css.ts │ │ ├── Frames.tsx │ │ ├── Iframe.tsx │ │ ├── frameSrc.d.ts │ │ └── frameSrc.js │ ├── FramesPanel │ │ ├── CheckmarkSvg.tsx │ │ ├── FramesPanel.css.ts │ │ └── FramesPanel.tsx │ ├── Heading │ │ ├── Heading.css.ts │ │ └── Heading.tsx │ ├── Inline │ │ ├── Inline.css.ts │ │ └── Inline.tsx │ ├── Logo │ │ └── Logo.tsx │ ├── Playroom.css.ts │ ├── Playroom.tsx │ ├── Preview.css.ts │ ├── Preview.tsx │ ├── PreviewPanel │ │ ├── CopyButton.tsx │ │ ├── PreviewPanel.tsx │ │ ├── ThemeSelector.css.ts │ │ └── ThemeSelector.tsx │ ├── RenderCode │ │ └── RenderCode.js │ ├── SettingsPanel │ │ ├── SettingsPanel.css.ts │ │ └── SettingsPanel.tsx │ ├── Snippets │ │ ├── SearchField │ │ │ ├── SearchField.css.ts │ │ │ └── SearchField.tsx │ │ ├── Snippets.css.ts │ │ └── Snippets.tsx │ ├── SplashScreen │ │ ├── SplashScreen.css.ts │ │ └── SplashScreen.tsx │ ├── Stack │ │ ├── Stack.css.ts │ │ └── Stack.tsx │ ├── StatusMessage │ │ ├── StatusMessage.css.ts │ │ └── StatusMessage.tsx │ ├── Strong │ │ ├── Strong.css.ts │ │ └── Strong.tsx │ ├── Text │ │ ├── Text.css.ts │ │ └── Text.tsx │ ├── Toolbar │ │ ├── Toolbar.css.ts │ │ └── Toolbar.tsx │ ├── ToolbarItem │ │ ├── ToolbarItem.css.ts │ │ └── ToolbarItem.tsx │ ├── ToolbarPanel │ │ ├── ToolbarPanel.css.ts │ │ └── ToolbarPanel.tsx │ ├── WindowPortal │ │ └── index.tsx │ ├── constants.ts │ ├── icons │ │ ├── AddIcon.tsx │ │ ├── ChevronIcon.css.ts │ │ ├── ChevronIcon.tsx │ │ ├── ColorModeDarkIcon.tsx │ │ ├── ColorModeLightIcon.tsx │ │ ├── ColorModeSystemIcon.tsx │ │ ├── DismissIcon.tsx │ │ ├── EditorBottomIcon.tsx │ │ ├── EditorRightIcon.tsx │ │ ├── EditorUndockedIcon.tsx │ │ ├── FramesIcon.tsx │ │ ├── PlayIcon.tsx │ │ ├── SettingsIcon.tsx │ │ ├── ShareIcon.tsx │ │ ├── ThemesIcon.tsx │ │ ├── TickIcon.tsx │ │ └── WidthsIcon.tsx │ ├── palettes.ts │ ├── sprinkles.css.ts │ └── vars.css.ts ├── StoreContext │ └── StoreContext.tsx ├── components.js ├── config.ts ├── frame.js ├── frameComponent.js ├── index.d.ts ├── index.js ├── preview.js ├── render.js ├── snippets.js ├── themes.js ├── useScope.js └── utils │ ├── compileJsx.test.ts │ ├── compileJsx.ts │ ├── componentsToHints.test.ts │ ├── componentsToHints.ts │ ├── cursor.test.ts │ ├── cursor.ts │ ├── formatting.test.ts │ ├── formatting.ts │ ├── params.ts │ └── usePreviewUrl.ts ├── tsconfig.json └── utils ├── index.d.ts └── index.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-typescript", 4 | "@babel/preset-env", 5 | ["@babel/preset-react", { "runtime": "automatic" }] 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@3.0.3/schema.json", 3 | "changelog": [ 4 | "@changesets/changelog-github", 5 | { "repo": "seek-oss/playroom" } 6 | ], 7 | "commit": false, 8 | "access": "public", 9 | "baseBranch": "master", 10 | "privatePackages": { "version": false, "tag": false }, 11 | "snapshot": { "useCalculatedVersion": true } 12 | } 13 | -------------------------------------------------------------------------------- /.changeset/loose-states-rescue.md: -------------------------------------------------------------------------------- 1 | --- 2 | 'playroom': minor 3 | --- 4 | 5 | Improve snippets search ranking algorithm. 6 | Results are now sorted primarily by the `group` property over the `name` property, making it easier to see related snippets together. 7 | 8 | Replace [`fuzzy`] dependency with [`fuse.js`] to enable result sorting. 9 | 10 | [`fuzzy`]: https://github.com/mattyork/fuzzy?tab=readme-ov-file 11 | [`fuse.js`]: https://github.com/krisk/fuse 12 | -------------------------------------------------------------------------------- /.changeset/spicy-ants-push.md: -------------------------------------------------------------------------------- 1 | --- 2 | 'playroom': minor 3 | --- 4 | 5 | Refactor layout. 6 | 7 | Improve the code editor show/hide animation. 8 | Prevent code contents from being searchable when the editor is hidden. 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.snap] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/about-codeowners/ for more info 2 | # Each line is a file pattern followed by one or more owners. 3 | 4 | # These owners will be the default owners for everything in the repo. 5 | * @seek-oss/playroom-maintainers 6 | -------------------------------------------------------------------------------- /.github/workflows/preview-site.yml: -------------------------------------------------------------------------------- 1 | name: Preview site 2 | 3 | on: 4 | push: 5 | branches-ignore: 6 | - master 7 | 8 | jobs: 9 | preview: 10 | name: Build & deploy 11 | runs-on: ubuntu-latest 12 | env: 13 | CI: true 14 | steps: 15 | - name: Checkout Repo 16 | uses: actions/checkout@v4 17 | 18 | - name: Set up pnpm 19 | uses: pnpm/action-setup@v3 20 | 21 | - name: Set up Node.js 22 | uses: actions/setup-node@v4 23 | with: 24 | node-version-file: '.nvmrc' 25 | cache: 'pnpm' 26 | 27 | - name: Install Dependencies 28 | run: pnpm i 29 | 30 | - name: Build 31 | run: pnpm build:themed 32 | 33 | - name: Deploy to surge 34 | run: pnpm deploy-preview -d playroom--${GITHUB_SHA}.surge.sh 35 | env: 36 | SURGE_LOGIN: ${{ secrets.SURGE_LOGIN }} 37 | SURGE_TOKEN: ${{ secrets.SURGE_TOKEN }} 38 | 39 | - name: Update PR status 40 | run: pnpm post-commit-status 41 | env: 42 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 43 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | release: 10 | name: Publish to npm 11 | runs-on: ubuntu-latest 12 | env: 13 | CI: true 14 | steps: 15 | - name: Checkout Repo 16 | uses: actions/checkout@v4 17 | with: 18 | # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits 19 | fetch-depth: 0 20 | token: ${{ secrets.SEEK_OSS_CI_GITHUB_TOKEN }} 21 | 22 | - name: Set up pnpm 23 | uses: pnpm/action-setup@v3 24 | 25 | - name: Set up Node.js 26 | uses: actions/setup-node@v4 27 | with: 28 | node-version-file: '.nvmrc' 29 | cache: 'pnpm' 30 | 31 | - name: Install Dependencies 32 | run: pnpm i 33 | 34 | - name: Create Release Pull Request or Publish to npm 35 | uses: changesets/action@v1 36 | with: 37 | version: pnpm run version 38 | publish: pnpm release 39 | env: 40 | GITHUB_TOKEN: ${{ secrets.SEEK_OSS_CI_GITHUB_TOKEN }} 41 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 42 | -------------------------------------------------------------------------------- /.github/workflows/snapshot.yml: -------------------------------------------------------------------------------- 1 | name: Snapshot 2 | 3 | on: workflow_dispatch 4 | 5 | jobs: 6 | release: 7 | name: Publish snapshot version 8 | runs-on: ubuntu-latest 9 | env: 10 | CI: true 11 | steps: 12 | - name: Check out repo 13 | uses: actions/checkout@v4 14 | with: 15 | # This makes Actions fetch all Git history for semantic-release 16 | fetch-depth: 0 17 | token: ${{ secrets.GITHUB_TOKEN }} 18 | 19 | - name: Set up pnpm 20 | uses: pnpm/action-setup@v3 21 | 22 | - name: Set up Node.js 23 | uses: actions/setup-node@v4 24 | with: 25 | node-version-file: '.nvmrc' 26 | cache: 'pnpm' 27 | 28 | - name: Install dependencies 29 | run: pnpm i 30 | 31 | - name: Publish 32 | uses: seek-oss/changesets-snapshot@v0 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 36 | -------------------------------------------------------------------------------- /.github/workflows/validate.yml: -------------------------------------------------------------------------------- 1 | name: Validate 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | strategy: 8 | matrix: 9 | os: [ubuntu-latest, macos-latest] 10 | name: Lint & Test 11 | runs-on: ${{ matrix.os }} 12 | env: 13 | CI: true 14 | steps: 15 | - name: Checkout Repo 16 | uses: actions/checkout@v4 17 | 18 | - name: Set up pnpm 19 | uses: pnpm/action-setup@v3 20 | 21 | - name: Set up Node.js 22 | uses: actions/setup-node@v4 23 | with: 24 | node-version-file: '.nvmrc' 25 | 26 | - name: Get pnpm store directory 27 | id: pnpm-cache 28 | shell: bash 29 | run: | 30 | echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT 31 | 32 | - name: Cache node modules 33 | uses: actions/cache@v4 34 | with: 35 | path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} 36 | key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} 37 | restore-keys: | 38 | ${{ runner.os }}-pnpm-store- 39 | 40 | - name: Cache Cypress binary 41 | id: cypress-cache 42 | uses: actions/cache@v4 43 | with: 44 | path: ~/.cache/Cypress 45 | key: cypress-${{ runner.os }}-cypress-${{ hashFiles('**/pnpm-lock.yaml') }} 46 | restore-keys: | 47 | cypress-${{ runner.os }}-cypress- 48 | 49 | - name: Install Dependencies 50 | run: | 51 | pnpm install 52 | pnpm exec cypress install 53 | 54 | - name: Lint 55 | run: pnpm lint 56 | 57 | - name: Test 58 | run: pnpm test 59 | 60 | - name: Cypress 61 | run: | 62 | pnpm cypress:verify 63 | pnpm cypress 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | cypress/videos/ 3 | cypress/screenshots/ 4 | cypress/plugins/ 5 | cypress/fixtures/ 6 | node_modules/ 7 | package-lock.json 8 | yarn.lock 9 | *.log 10 | .DS_Store 11 | .vscode/ 12 | .idea/ 13 | .eslintcache 14 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | pnpm exec lint-staged 2 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 20.19.0 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | cypress/plugins/ 2 | cypress/fixtures/ 3 | dist 4 | pnpm-lock.yaml 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 SEEK 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /bin/cli.cjs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | const path = require('path'); 3 | const url = require('url'); 4 | 5 | const commandLineArgs = require('command-line-args'); 6 | const commandLineUsage = require('command-line-usage'); 7 | const findUp = require('find-up'); 8 | 9 | const lib = require('../lib'); 10 | 11 | const showUsage = () => { 12 | console.log( 13 | commandLineUsage([ 14 | { 15 | header: 'playroom', 16 | content: 17 | 'Code-oriented component design tool.\n\nUsage: playroom [options...]', 18 | }, 19 | { 20 | header: 'Commands', 21 | content: [ 22 | { name: 'start', summary: 'Start a local playroom.' }, 23 | { 24 | name: 'build', 25 | summary: 'Build a playroom for production.', 26 | }, 27 | { name: 'help', summary: 'Show this usage guide.' }, 28 | ], 29 | }, 30 | { 31 | header: 'Options', 32 | optionList: [ 33 | { 34 | name: 'config', 35 | typeLabel: '{underline path}', 36 | description: 'Path to a config file.', 37 | }, 38 | ], 39 | }, 40 | ]) 41 | ); 42 | }; 43 | 44 | (async () => { 45 | const args = commandLineArgs([ 46 | { name: 'command', defaultOption: true, defaultValue: 'start' }, 47 | { name: 'config' }, 48 | { name: 'help', type: Boolean }, 49 | ]); 50 | 51 | if (args.command === 'help' || args.help) { 52 | return showUsage(); 53 | } 54 | 55 | const cwd = process.cwd(); 56 | const configPath = args.config 57 | ? path.resolve(cwd, args.config) 58 | : await findUp( 59 | ['playroom.config.js', 'playroom.config.mjs', 'playroom.config.cjs'], 60 | { cwd } 61 | ); 62 | 63 | if (!configPath) { 64 | console.error( 65 | 'Please add a playroom.config.js to the root of your project.' 66 | ); 67 | process.exit(1); 68 | } 69 | 70 | const { default: config } = await import(url.pathToFileURL(configPath)); 71 | 72 | const playroom = lib({ 73 | cwd: path.dirname(configPath), 74 | ...config, 75 | }); 76 | 77 | if (playroom.hasOwnProperty(args.command)) { 78 | playroom[args.command]((err) => { 79 | if (err) { 80 | console.error(err); 81 | process.exit(1); 82 | } 83 | }); 84 | } else { 85 | showUsage(); 86 | process.exit(1); 87 | } 88 | })(); 89 | -------------------------------------------------------------------------------- /cypress.config.mjs: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'cypress'; 2 | 3 | export default defineConfig({ 4 | defaultCommandTimeout: 10000, 5 | video: false, 6 | e2e: {}, 7 | }); 8 | -------------------------------------------------------------------------------- /cypress/e2e/editor.cy.ts: -------------------------------------------------------------------------------- 1 | import dedent from 'dedent'; 2 | 3 | import { 4 | formatCode, 5 | typeCode, 6 | assertFirstFrameContains, 7 | assertCodePaneContains, 8 | assertCodePaneLineCount, 9 | loadPlayroom, 10 | } from '../support/utils'; 11 | 12 | describe('Editor', () => { 13 | beforeEach(() => { 14 | loadPlayroom(); 15 | }); 16 | 17 | it('renders to frame', () => { 18 | typeCode(''); 19 | assertFirstFrameContains('Foo'); 20 | 21 | typeCode(''); 22 | assertFirstFrameContains('Foo\nBar'); 23 | }); 24 | 25 | it('autocompletes', () => { 26 | typeCode('', 150); 27 | assertFirstFrameContains('Foo'); 28 | assertCodePaneContains(''); 29 | }); 30 | 31 | it('formats', () => { 32 | typeCode(''); 33 | assertCodePaneLineCount(1); 34 | formatCode(); 35 | assertCodePaneLineCount(6); 36 | }); 37 | 38 | it('formats css in a style block', () => { 39 | typeCode( 40 | '\n 50 | `); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /cypress/e2e/scope.cy.ts: -------------------------------------------------------------------------------- 1 | import { 2 | typeCode, 3 | assertFirstFrameContains, 4 | loadPlayroom, 5 | } from '../support/utils'; 6 | 7 | describe('useScope', () => { 8 | beforeEach(() => { 9 | loadPlayroom(); 10 | }); 11 | 12 | it('works', () => { 13 | typeCode('{{}hello()} {{}world()}'); 14 | assertFirstFrameContains('HELLO WORLD'); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /cypress/e2e/smoke.cy.ts: -------------------------------------------------------------------------------- 1 | import { 2 | assertPreviewContains, 3 | getPreviewFrames, 4 | loadPlayroom, 5 | } from '../support/utils'; 6 | 7 | describe('Smoke', () => { 8 | it('frames are interactive', () => { 9 | loadPlayroom(); 10 | getPreviewFrames().first().click('center'); 11 | }); 12 | 13 | it('preview mode loads correctly', () => { 14 | cy.visit( 15 | 'http://localhost:9000/preview#?code=N4Igxg9gJgpiBcIA8AxCEB8r1YEIEMAnAei2LUyXJxAF8g' 16 | ); 17 | 18 | assertPreviewContains('Foo\nFoo\nBar'); 19 | }); 20 | 21 | it('preview mode works with TypeScript components', () => { 22 | cy.visit( 23 | 'http://localhost:9002/preview#?code=N4Igxg9gJgpiBcIA8AxCEB8r1YEIEMAnAei2LUyXJxAF8g' 24 | ); 25 | 26 | assertPreviewContains('Foo\nFoo\nBar'); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /cypress/e2e/snippets.cy.ts: -------------------------------------------------------------------------------- 1 | import dedent from 'dedent'; 2 | 3 | import { isMac } from '../../src/utils/formatting'; 4 | import { 5 | typeCode, 6 | assertFirstFrameContains, 7 | assertCodePaneContains, 8 | assertCodePaneLineCount, 9 | selectSnippetByIndex, 10 | filterSnippets, 11 | toggleSnippets, 12 | assertSnippetCount, 13 | assertSnippetsSearchFieldIsVisible, 14 | mouseOverSnippet, 15 | loadPlayroom, 16 | } from '../support/utils'; 17 | 18 | describe('Snippets', () => { 19 | beforeEach(() => { 20 | loadPlayroom(); 21 | typeCode('
Initial code'); 22 | }); 23 | 24 | it('driven with mouse', () => { 25 | // Open and format for insertion point 26 | toggleSnippets(); 27 | assertSnippetsSearchFieldIsVisible(); 28 | assertCodePaneLineCount(8); 29 | 30 | // Browse snippetlist 31 | assertSnippetCount(5); 32 | mouseOverSnippet(0); 33 | assertFirstFrameContains('Initial code\nFoo\nFoo'); 34 | mouseOverSnippet(1); 35 | assertFirstFrameContains('Initial code\nFoo\nRed Foo'); 36 | mouseOverSnippet(2); 37 | assertFirstFrameContains('Initial code\nBar\nBar'); 38 | 39 | // Close without persisting 40 | toggleSnippets(); 41 | assertCodePaneContains('
Initial code
'); 42 | assertCodePaneLineCount(1); 43 | 44 | // Re-open and persist 45 | toggleSnippets(); 46 | mouseOverSnippet(3); 47 | assertFirstFrameContains('Initial code\nBar\nBlue Bar'); 48 | selectSnippetByIndex(3).click(); 49 | assertFirstFrameContains('Initial code\nBar\nBlue Bar'); 50 | assertCodePaneLineCount(7); 51 | assertCodePaneContains(dedent` 52 |
53 | Initial{" "} 54 | 55 | codeBlue Bar 56 | 57 |
\n 58 | `); 59 | typeCode('cursor position'); 60 | assertCodePaneContains(dedent` 61 |
62 | Initial{" "} 63 | 64 | codeBlue Barcursor position 65 | 66 |
\n 67 | `); 68 | }); 69 | 70 | it('driven with keyboard', () => { 71 | // Open and format for insertion point 72 | typeCode(`${isMac() ? '{cmd}' : '{ctrl}'}k`); 73 | assertSnippetsSearchFieldIsVisible(); 74 | assertCodePaneLineCount(8); 75 | filterSnippets('{esc}'); 76 | assertCodePaneLineCount(1, true); 77 | typeCode(`${isMac() ? '{cmd}' : '{ctrl}'}k`); 78 | assertSnippetsSearchFieldIsVisible(); 79 | assertCodePaneLineCount(8); 80 | 81 | // Browse snippetlist 82 | assertSnippetCount(5); 83 | filterSnippets('{downarrow}'); 84 | assertFirstFrameContains('Initial code\nFoo\nFoo'); 85 | filterSnippets('{downarrow}'); 86 | assertFirstFrameContains('Initial code\nFoo\nRed Foo'); 87 | filterSnippets('{downarrow}'); 88 | assertFirstFrameContains('Initial code\nBar\nBar'); 89 | 90 | // Close without persisting 91 | filterSnippets('{esc}'); 92 | assertCodePaneContains('
Initial code
'); 93 | assertCodePaneLineCount(1, true); 94 | 95 | // Re-open and persist 96 | typeCode(`${isMac() ? '{cmd}' : '{ctrl}'}k`); 97 | filterSnippets('{downarrow}{downarrow}{downarrow}{downarrow}{enter}'); 98 | assertFirstFrameContains('Initial code\nBar\nBlue Bar'); 99 | assertCodePaneLineCount(7); 100 | assertCodePaneContains(dedent` 101 |
102 | Initial{" "} 103 | 104 | codeBlue Bar 105 | 106 |
\n 107 | `); 108 | typeCode('cursor position'); 109 | assertCodePaneContains(dedent` 110 |
111 | Initial{" "} 112 | 113 | codeBlue Barcursor position 114 | 115 |
\n 116 | `); 117 | }); 118 | 119 | it('snippets preview code is disabled while snippet pane is closing', () => { 120 | toggleSnippets(); 121 | toggleSnippets(); 122 | 123 | // Mouse over snippet while snippet panel is closing 124 | mouseOverSnippet(0); 125 | 126 | assertCodePaneContains(dedent` 127 |
Initial code
128 | `); 129 | 130 | assertFirstFrameContains('Initial code'); 131 | 132 | typeCode('
test'); 133 | 134 | assertCodePaneContains(dedent` 135 |
Initial code
test
136 | `); 137 | 138 | assertFirstFrameContains('Initial code\ntest'); 139 | }); 140 | }); 141 | -------------------------------------------------------------------------------- /cypress/e2e/toolbar.cy.ts: -------------------------------------------------------------------------------- 1 | import type { PlayroomProps } from '../../src/Playroom/Playroom'; 2 | import { 3 | assertFramesMatch, 4 | assertPreviewContains, 5 | typeCode, 6 | gotoPreview, 7 | loadPlayroom, 8 | getResetButton, 9 | selectWidthPreference, 10 | } from '../support/utils'; 11 | 12 | describe('Toolbar', () => { 13 | beforeEach(() => { 14 | loadPlayroom(); 15 | }); 16 | 17 | it('filter widths', () => { 18 | const frames: PlayroomProps['widths'] = [ 19 | 320, 20 | 375, 21 | 768, 22 | 1024, 23 | 'Fit to window', 24 | ]; 25 | const widthIndexToSelect = 1; 26 | 27 | assertFramesMatch(frames); 28 | selectWidthPreference(frames[widthIndexToSelect]); 29 | assertFramesMatch([frames[widthIndexToSelect]]); 30 | 31 | getResetButton().click(); 32 | assertFramesMatch(frames); 33 | }); 34 | 35 | it('preview', () => { 36 | typeCode(''); 37 | 38 | gotoPreview(); 39 | 40 | assertPreviewContains('Foo\nFoo\nBar'); 41 | }); 42 | 43 | it('copy to clipboard', () => { 44 | const copySpy = cy.spy(); 45 | 46 | cy.visit( 47 | 'http://localhost:9000/#?code=N4Igxg9gJgpiBcIA8AxCEB8r1YEIEMAnAei2LUyXJxAF8g' 48 | ); 49 | 50 | cy.document() 51 | .then((doc) => { 52 | cy.stub(doc, 'execCommand', (args) => { 53 | if (args === 'copy') { 54 | copySpy(); 55 | return true; 56 | } 57 | }); 58 | }) 59 | .findByRole('button', { name: /Copy Playroom link/i }) 60 | .click(); 61 | 62 | cy.then(() => expect(copySpy).to.have.been.called); 63 | }); 64 | }); 65 | -------------------------------------------------------------------------------- /cypress/e2e/urlHandling.cy.ts: -------------------------------------------------------------------------------- 1 | import { 2 | assertFirstFrameContains, 3 | assertCodePaneContains, 4 | assertFramesMatch, 5 | } from '../support/utils'; 6 | 7 | describe('URL handling', () => { 8 | describe('where paramType is hash', () => { 9 | it('code', () => { 10 | cy.visit( 11 | 'http://localhost:9000/#?code=N4Igxg9gJgpiBcIA8AxCEB8r1YEIEMAnAei2LUyXJxAF8g' 12 | ); 13 | 14 | assertFirstFrameContains('Foo\nFoo\nBar'); 15 | assertCodePaneContains(''); 16 | }); 17 | 18 | it('widths', () => { 19 | cy.visit( 20 | 'http://localhost:9000/#?code=N4Ig7glgJgLgFgZxALgNoGYDsBWANJgNgA4BdAXyA' 21 | ); 22 | 23 | assertFramesMatch([375, 768]); 24 | }); 25 | 26 | it('title', () => { 27 | cy.visit( 28 | 'http://localhost:9000/#?code=N4Ig7glgJgLgFgZxALgNoF0A0IYRgGwFMUQAVQhGEAXyA' 29 | ); 30 | 31 | cy.title().should('eq', 'Test | Playroom'); 32 | }); 33 | 34 | it('editor hidden', () => { 35 | cy.visit( 36 | 'http://localhost:9000/#?code=N4IgpgJglgLg9gJwBJQhMA7EAuGCCuYAvkA' 37 | ); 38 | 39 | cy.get('textarea').should('not.be.focused'); 40 | cy.get('.CodeMirror-code').should('be.hidden'); 41 | }); 42 | }); 43 | 44 | describe('where paramType is search', () => { 45 | it('code', () => { 46 | cy.visit( 47 | 'http://localhost:9001/?code=N4Igxg9gJgpiBcIA8AxCEB8r1YEIEMAnAei2LUyXJxAF8g' 48 | ); 49 | 50 | assertFirstFrameContains('Foo\nFoo\nBar'); 51 | assertCodePaneContains(''); 52 | }); 53 | 54 | it('widths and themes', () => { 55 | cy.visit( 56 | 'http://localhost:9001/?code=N4Ig7glgJgLgFgZxALgNoGYDsBWANJgNgA4BdAXyA' 57 | ); 58 | 59 | assertFramesMatch([ 60 | ['themeOne', 375], 61 | ['themeTwo', 375], 62 | ['themeOne', 768], 63 | ['themeTwo', 768], 64 | ]); 65 | }); 66 | 67 | it('title', () => { 68 | cy.visit( 69 | 'http://localhost:9001/?code=N4Ig7glgJgLgFgZxALgNoF0A0IYRgGwFMUQAVQhGEAXyA' 70 | ); 71 | 72 | cy.title().should('eq', 'Test | Playroom'); 73 | }); 74 | 75 | it('editor hidden', () => { 76 | cy.visit( 77 | 'http://localhost:9001/?code=N4IgpgJglgLg9gJwBJQhMA7EAuGCCuYAvkA' 78 | ); 79 | 80 | cy.get('textarea').should('not.be.focused'); 81 | cy.get('.CodeMirror-code').should('be.hidden'); 82 | }); 83 | }); 84 | }); 85 | -------------------------------------------------------------------------------- /cypress/projects/basic/components.js: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types'; 2 | 3 | const withPropTypes = (component) => { 4 | component.propTypes = { 5 | color: PropTypes.oneOf(['red', 'blue']), 6 | children: PropTypes.node, 7 | }; 8 | 9 | return component; 10 | }; 11 | const parent = { 12 | border: '1px solid currentColor', 13 | padding: '10px 10px 10px 15px', 14 | }; 15 | 16 | export const Foo = withPropTypes(({ color = 'black', children }) => ( 17 |
18 | Foo{children ?
{children}
: null} 19 |
20 | )); 21 | 22 | export const Bar = withPropTypes(({ color = 'black', children }) => ( 23 |
24 | Bar{children ?
{children}
: null} 25 |
26 | )); 27 | -------------------------------------------------------------------------------- /cypress/projects/basic/playroom.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | components: './components', 3 | scope: './useScope', 4 | snippets: './snippets', 5 | outputPath: './dist', 6 | openBrowser: false, 7 | port: 9000, 8 | storageKey: 'playroom-example-basic', 9 | }; 10 | -------------------------------------------------------------------------------- /cypress/projects/basic/serve.json: -------------------------------------------------------------------------------- 1 | { 2 | "cleanUrls": ["!/frame.html"] 3 | } 4 | -------------------------------------------------------------------------------- /cypress/projects/basic/snippets.js: -------------------------------------------------------------------------------- 1 | export default [ 2 | { 3 | group: 'Foo', 4 | name: 'Default', 5 | code: 'Foo', 6 | }, 7 | { 8 | group: 'Foo', 9 | name: 'Red', 10 | code: 'Red Foo', 11 | }, 12 | { 13 | group: 'Bar', 14 | name: 'Default', 15 | code: 'Bar', 16 | }, 17 | { 18 | group: 'Bar', 19 | name: 'Blue', 20 | code: 'Blue Bar', 21 | }, 22 | { 23 | group: 'Scope', 24 | name: 'hello world', 25 | code: '{hello()} {world()}', 26 | }, 27 | ]; 28 | -------------------------------------------------------------------------------- /cypress/projects/basic/useScope.js: -------------------------------------------------------------------------------- 1 | export default () => ({ 2 | hello: () => 'HELLO', 3 | world: () => 'WORLD', 4 | }); 5 | -------------------------------------------------------------------------------- /cypress/projects/themed/components.js: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types'; 2 | 3 | const withPropTypes = (component) => { 4 | component.propTypes = { 5 | color: PropTypes.oneOf(['red', 'blue']), 6 | children: PropTypes.node, 7 | }; 8 | 9 | return component; 10 | }; 11 | const parent = { 12 | border: '1px solid currentColor', 13 | padding: '10px 10px 10px 15px', 14 | }; 15 | 16 | export const Foo = withPropTypes(({ color = 'black', children }) => ( 17 |
18 | Foo{children ?
{children}
: null} 19 |
20 | )); 21 | 22 | export const Bar = withPropTypes(({ color = 'black', children }) => ( 23 |
24 | Bar{children ?
{children}
: null} 25 |
26 | )); 27 | -------------------------------------------------------------------------------- /cypress/projects/themed/playroom.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | components: './components', 3 | snippets: './snippets', 4 | themes: './themes', 5 | outputPath: './dist', 6 | openBrowser: false, 7 | paramType: 'search', 8 | port: 9001, 9 | storageKey: 'playroom-example-themed', 10 | }; 11 | -------------------------------------------------------------------------------- /cypress/projects/themed/serve.json: -------------------------------------------------------------------------------- 1 | { 2 | "cleanUrls": ["!/frame.html"] 3 | } 4 | -------------------------------------------------------------------------------- /cypress/projects/themed/snippets.js: -------------------------------------------------------------------------------- 1 | export default [ 2 | { 3 | group: 'Foo', 4 | name: 'Default', 5 | code: 'Foo', 6 | }, 7 | { 8 | group: 'Foo', 9 | name: 'Red', 10 | code: 'Red Foo', 11 | }, 12 | { 13 | group: 'Bar', 14 | name: 'Default', 15 | code: 'Bar', 16 | }, 17 | { 18 | group: 'Bar', 19 | name: 'Blue', 20 | code: 'Blue Bar', 21 | }, 22 | ]; 23 | -------------------------------------------------------------------------------- /cypress/projects/themed/themes.js: -------------------------------------------------------------------------------- 1 | export const themeOne = { name: 'one' }; 2 | export const themeTwo = { name: 'two' }; 3 | -------------------------------------------------------------------------------- /cypress/projects/typescript/components.ts: -------------------------------------------------------------------------------- 1 | export { Foo } from './components/Foo'; 2 | export { Bar } from './components/Bar'; 3 | -------------------------------------------------------------------------------- /cypress/projects/typescript/components/Bar.tsx: -------------------------------------------------------------------------------- 1 | import type React from 'react'; 2 | 3 | import { parent } from './styles'; 4 | 5 | type Props = { 6 | color: 'red' | 'blue' | 'black'; 7 | children: React.ReactNode; 8 | }; 9 | 10 | export const Bar: React.FC = ({ color = 'black', children }) => ( 11 |
12 | Bar{children ?
{children}
: null} 13 |
14 | ); 15 | -------------------------------------------------------------------------------- /cypress/projects/typescript/components/Foo.tsx: -------------------------------------------------------------------------------- 1 | import type React from 'react'; 2 | 3 | import { parent } from './styles'; 4 | 5 | type Props = { 6 | color: 'red' | 'blue' | 'black'; 7 | children: React.ReactNode; 8 | }; 9 | 10 | export const Foo: React.FC = ({ color = 'black', children }) => ( 11 |
12 | Foo{children ?
{children}
: null} 13 |
14 | ); 15 | -------------------------------------------------------------------------------- /cypress/projects/typescript/components/styles.ts: -------------------------------------------------------------------------------- 1 | export const parent = { 2 | border: '4px solid currentColor', 3 | padding: '10px 10px 10px 15px', 4 | }; 5 | -------------------------------------------------------------------------------- /cypress/projects/typescript/playroom.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | components: './components.ts', 3 | snippets: './snippets.ts', 4 | outputPath: './dist', 5 | openBrowser: false, 6 | port: 9002, 7 | storageKey: 'playroom-example-typescript', 8 | webpackConfig: () => ({ 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.tsx?$/, 13 | exclude: /node_modules/, 14 | use: [ 15 | { 16 | loader: require.resolve('babel-loader'), 17 | options: { 18 | babelrc: false, 19 | presets: [ 20 | require.resolve('@babel/preset-env'), 21 | [ 22 | require.resolve('@babel/preset-react'), 23 | { runtime: 'automatic' }, 24 | ], 25 | require.resolve('@babel/preset-typescript'), 26 | ], 27 | }, 28 | }, 29 | ], 30 | }, 31 | ], 32 | }, 33 | }), 34 | }; 35 | -------------------------------------------------------------------------------- /cypress/projects/typescript/serve.json: -------------------------------------------------------------------------------- 1 | { 2 | "cleanUrls": ["!/frame.html"] 3 | } 4 | -------------------------------------------------------------------------------- /cypress/projects/typescript/snippets.ts: -------------------------------------------------------------------------------- 1 | export default [ 2 | { 3 | group: 'Foo', 4 | name: 'Default', 5 | code: 'Foo', 6 | }, 7 | { 8 | group: 'Foo', 9 | name: 'Red', 10 | code: 'Red Foo', 11 | }, 12 | { 13 | group: 'Bar', 14 | name: 'Default', 15 | code: 'Bar', 16 | }, 17 | { 18 | group: 'Bar', 19 | name: 'Blue', 20 | code: 'Blue Bar', 21 | }, 22 | ]; 23 | -------------------------------------------------------------------------------- /cypress/projects/typescript/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "noEmit": true, 4 | "skipLibCheck": true, 5 | "moduleResolution": "node", 6 | "module": "es2022", 7 | "allowImportingTsExtensions": true, 8 | "allowSyntheticDefaultImports": true, 9 | "esModuleInterop": true, 10 | "isolatedModules": true, 11 | "resolveJsonModule": true, 12 | "strict": true, 13 | "forceConsistentCasingInFileNames": true, 14 | "jsx": "react-jsx", 15 | "lib": ["dom", "es2022"], 16 | "target": "es2022" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /cypress/support/commands.js: -------------------------------------------------------------------------------- 1 | import '@testing-library/cypress/add-commands'; 2 | 3 | Cypress.Commands.add( 4 | 'getFromPreviewFrame', 5 | { prevSubject: 'element' }, 6 | ($iframe, selector) => 7 | new Promise((resolve) => { 8 | $iframe.on('load', () => { 9 | resolve($iframe.contents().find(selector)); 10 | }); 11 | }) 12 | ); 13 | -------------------------------------------------------------------------------- /cypress/support/e2e.js: -------------------------------------------------------------------------------- 1 | require('./commands'); 2 | -------------------------------------------------------------------------------- /cypress/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "types": ["cypress", "@testing-library/cypress"], 5 | "isolatedModules": false 6 | }, 7 | "include": [ 8 | "**/*", // override the include from the root tsconfig 9 | "../src/index.d.ts" // contains definitions for global variables 10 | ], 11 | "exclude": [] // override the exclude from the root tsconfig 12 | } 13 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'eslint/config'; 2 | import eslintConfigSeek from 'eslint-config-seek'; 3 | 4 | export default defineConfig([ 5 | ...eslintConfigSeek, 6 | { 7 | rules: { 8 | 'import-x/order': [ 9 | 'error', 10 | { 11 | 'newlines-between': 'always', 12 | alphabetize: { order: 'asc' }, 13 | groups: [ 14 | 'builtin', 15 | 'external', 16 | 'internal', 17 | 'parent', 18 | 'sibling', 19 | 'index', 20 | ], 21 | pathGroups: [ 22 | { 23 | pattern: '*.css', 24 | group: 'index', 25 | position: 'after', 26 | patternOptions: { matchBase: true }, 27 | }, 28 | ], 29 | }, 30 | ], 31 | }, 32 | }, 33 | { 34 | files: ['bin/**/*.cjs', 'lib/**/*.js'], 35 | rules: { 36 | 'no-console': 0, 37 | 'no-process-exit': 0, 38 | }, 39 | }, 40 | { 41 | ignores: ['**/dist'], 42 | }, 43 | { 44 | languageOptions: { 45 | globals: { 46 | __PLAYROOM_GLOBAL__CONFIG__: true, 47 | __PLAYROOM_GLOBAL__STATIC_TYPES__: true, 48 | }, 49 | }, 50 | }, 51 | ]); 52 | -------------------------------------------------------------------------------- /images/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seek-oss/playroom/e69f69896cf6c57a5a45a61330d9f4ea6c99bc97/images/demo.gif -------------------------------------------------------------------------------- /images/favicon-inverted.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seek-oss/playroom/e69f69896cf6c57a5a45a61330d9f4ea6c99bc97/images/favicon-inverted.png -------------------------------------------------------------------------------- /images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seek-oss/playroom/e69f69896cf6c57a5a45a61330d9f4ea6c99bc97/images/favicon.png -------------------------------------------------------------------------------- /images/logo-inverted.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seek-oss/playroom/e69f69896cf6c57a5a45a61330d9f4ea6c99bc97/images/logo-inverted.png -------------------------------------------------------------------------------- /images/logo.ai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seek-oss/playroom/e69f69896cf6c57a5a45a61330d9f4ea6c99bc97/images/logo.ai -------------------------------------------------------------------------------- /images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seek-oss/playroom/e69f69896cf6c57a5a45a61330d9f4ea6c99bc97/images/logo.png -------------------------------------------------------------------------------- /lib/.npmignore: -------------------------------------------------------------------------------- 1 | *.test.* 2 | 3 | -------------------------------------------------------------------------------- /lib/build.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack'); 2 | 3 | const makeWebpackConfig = require('./makeWebpackConfig'); 4 | const noop = () => {}; 5 | 6 | module.exports = async (config, callback = noop) => { 7 | const webpackConfig = await makeWebpackConfig(config, { production: true }); 8 | 9 | webpack(webpackConfig, (err, stats) => { 10 | // https://webpack.js.org/api/node/#error-handling 11 | if (err) { 12 | const errorMessage = [err.stack || err, err.details] 13 | .filter(Boolean) 14 | .join('/n/n'); 15 | return callback(errorMessage); 16 | } 17 | 18 | if (stats.hasErrors()) { 19 | const info = stats.toJson(); 20 | return callback(info.errors.map((error) => error.message).join('\n\n')); 21 | } 22 | 23 | return callback(); 24 | }); 25 | }; 26 | -------------------------------------------------------------------------------- /lib/defaultModules/FrameComponent.js: -------------------------------------------------------------------------------- 1 | export default ({ children }) => <>{children}; 2 | -------------------------------------------------------------------------------- /lib/defaultModules/snippets.js: -------------------------------------------------------------------------------- 1 | export default []; 2 | -------------------------------------------------------------------------------- /lib/defaultModules/themes.js: -------------------------------------------------------------------------------- 1 | export const __PLAYROOM__NO_THEME__ = null; 2 | -------------------------------------------------------------------------------- /lib/defaultModules/useScope.js: -------------------------------------------------------------------------------- 1 | export default () => {}; 2 | -------------------------------------------------------------------------------- /lib/getStaticTypes.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | 4 | const findUp = require('find-up'); 5 | const { glob } = require('tinyglobby'); 6 | const ts = require('typescript'); 7 | 8 | const stringRegex = /^"(.*)"$/; 9 | const parsePropType = (propType) => { 10 | if (propType.name === 'enum' && propType.value && propType.value.length > 0) { 11 | return propType.value 12 | .filter(({ value }) => stringRegex.test(value)) 13 | .map(({ value }) => value.replace(stringRegex, '$1')); 14 | } 15 | return []; 16 | }; 17 | 18 | /** 19 | * Modified from https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore?tab=readme-ov-file#_keyby. 20 | * Only supports arrays and expects a `key` to be provided. 21 | */ 22 | const keyBy = (array = [], key) => 23 | array.reduce( 24 | (previousValue, currentValue) => ({ 25 | ...previousValue, 26 | [currentValue[key]]: currentValue, 27 | }), 28 | {} 29 | ); 30 | 31 | const mapValues = (object, callback) => 32 | Object.fromEntries( 33 | Object.entries(object).map(([key, value]) => [key, callback(value)]) 34 | ); 35 | 36 | module.exports = async (playroomConfig) => { 37 | const { 38 | cwd, 39 | typeScriptFiles = ['**/*.{ts,tsx}', '!**/node_modules'], 40 | reactDocgenTypescriptConfig = {}, 41 | } = playroomConfig; 42 | 43 | const tsConfigPath = await findUp('tsconfig.json', { cwd }); 44 | 45 | if (!tsConfigPath) { 46 | return {}; 47 | } 48 | 49 | const { config, error } = ts.readConfigFile(tsConfigPath, (filename) => 50 | // eslint-disable-next-line no-sync 51 | fs.readFileSync(filename, 'utf8') 52 | ); 53 | 54 | if (error) { 55 | console.error('Error reading tsConfig file.'); 56 | throw error; 57 | } 58 | 59 | const basePath = path.dirname(tsConfigPath); 60 | const { options, errors } = ts.parseJsonConfigFileContent( 61 | config, 62 | ts.sys, 63 | basePath, 64 | {}, 65 | tsConfigPath 66 | ); 67 | 68 | if (errors && errors.length) { 69 | console.error('Error parsing tsConfig file.'); 70 | throw errors[0]; 71 | } 72 | 73 | try { 74 | const files = await glob(typeScriptFiles, { cwd, absolute: true }); 75 | const types = require('react-docgen-typescript') 76 | .withCompilerOptions( 77 | { 78 | ...options, 79 | noErrorTruncation: true, 80 | }, 81 | { 82 | propFilter: { 83 | skipPropsWithName: ['children'], 84 | }, 85 | shouldExtractValuesFromUnion: true, 86 | shouldExtractLiteralValuesFromEnum: true, 87 | shouldRemoveUndefinedFromOptional: true, 88 | ...reactDocgenTypescriptConfig, 89 | } 90 | ) 91 | .parse(files); 92 | const typesByDisplayName = keyBy(types, 'displayName'); 93 | const parsedTypes = mapValues(typesByDisplayName, (component) => 94 | mapValues(component.props || {}, (prop) => parsePropType(prop.type)) 95 | ); 96 | 97 | return parsedTypes; 98 | } catch (err) { 99 | console.error('Error parsing static types.'); 100 | console.error(err); 101 | return {}; 102 | } 103 | }; 104 | -------------------------------------------------------------------------------- /lib/getStaticTypes.test.ts: -------------------------------------------------------------------------------- 1 | import { resolve } from 'node:path'; 2 | 3 | // @ts-expect-error No types 4 | import getStaticTypes from './getStaticTypes'; 5 | 6 | describe('getStaticTypes', () => { 7 | it('should get static types from typescript components', async () => { 8 | const result = await getStaticTypes({ 9 | cwd: resolve(__dirname, '../cypress/projects/typescript'), 10 | }); 11 | 12 | expect(result).toMatchInlineSnapshot(` 13 | { 14 | "Bar": { 15 | "color": [ 16 | "red", 17 | "blue", 18 | "black", 19 | ], 20 | }, 21 | "Foo": { 22 | "color": [ 23 | "red", 24 | "blue", 25 | "black", 26 | ], 27 | }, 28 | } 29 | `); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | const provideDefaultConfig = require('./provideDefaultConfig'); 2 | 3 | module.exports = (userConfig) => { 4 | const config = provideDefaultConfig(userConfig); 5 | 6 | return { 7 | start: (callback) => { 8 | const start = require('./start'); 9 | start(config, callback); 10 | }, 11 | build: (callback) => { 12 | const build = require('./build'); 13 | build(config, callback); 14 | }, 15 | }; 16 | }; 17 | -------------------------------------------------------------------------------- /lib/makeDefaultWebpackConfig.js: -------------------------------------------------------------------------------- 1 | module.exports = (playroomConfig) => ({ 2 | module: { 3 | rules: [ 4 | { 5 | test: /\.jsx?$/, 6 | include: playroomConfig.cwd, 7 | exclude: /node_modules/, 8 | use: [ 9 | { 10 | loader: require.resolve('babel-loader'), 11 | options: { 12 | presets: [ 13 | require.resolve('@babel/preset-env'), 14 | [ 15 | require.resolve('@babel/preset-react'), 16 | { runtime: 'automatic' }, 17 | ], 18 | ], 19 | }, 20 | }, 21 | ], 22 | }, 23 | ], 24 | }, 25 | }); 26 | -------------------------------------------------------------------------------- /lib/provideDefaultConfig.js: -------------------------------------------------------------------------------- 1 | const { execSync } = require('child_process'); 2 | 3 | const readPackage = require('read-pkg-up'); 4 | 5 | /** 6 | * @returns {string | null} The current git branch name, or null if no branch is found 7 | */ 8 | const getGitBranch = () => { 9 | try { 10 | return execSync('git branch --show-current').toString().trim(); 11 | } catch { 12 | return null; 13 | } 14 | }; 15 | 16 | const generateStorageKey = () => { 17 | const pkg = readPackage.sync(); 18 | const packageName = (pkg && pkg.packageJson && pkg.packageJson.name) || null; 19 | const branchName = getGitBranch(); 20 | 21 | const packageLabel = packageName ? `package:${packageName}` : null; 22 | const branchLabel = branchName ? `branch:${branchName}` : null; 23 | 24 | return ['playroom', packageLabel, branchLabel].filter(Boolean).join('__'); 25 | }; 26 | 27 | module.exports = ({ storageKey, ...restConfig }) => ({ 28 | port: 9000, 29 | openBrowser: true, 30 | storageKey: storageKey || generateStorageKey(), 31 | baseUrl: '', 32 | paramType: 'hash', 33 | ...restConfig, 34 | }); 35 | -------------------------------------------------------------------------------- /lib/start.js: -------------------------------------------------------------------------------- 1 | const portfinder = require('portfinder'); 2 | const webpack = require('webpack'); 3 | const WebpackDevServer = require('webpack-dev-server'); 4 | 5 | const makeWebpackConfig = require('./makeWebpackConfig'); 6 | 7 | module.exports = async (config, callback) => { 8 | const webpackConfig = await makeWebpackConfig( 9 | { ...config, baseUrl: '' }, 10 | { 11 | production: false, 12 | infrastructureLogging: { 13 | level: 'none', 14 | }, 15 | stats: { 16 | errorDetails: true, 17 | }, 18 | } 19 | ); 20 | const { port, openBrowser } = config; 21 | 22 | portfinder.getPort({ port }, function (portErr, availablePort) { 23 | if (portErr) { 24 | console.error('portErr: ', portErr); 25 | return; 26 | } 27 | const webpackDevServerConfig = { 28 | hot: true, 29 | port: availablePort, 30 | open: openBrowser, 31 | devMiddleware: { 32 | stats: false, 33 | }, 34 | client: { 35 | overlay: false, 36 | }, 37 | compress: true, 38 | static: { 39 | watch: { ignored: /node_modules/ }, 40 | }, 41 | // Added to prevent Webpack HMR from breaking when iframeSandbox option is used 42 | // See: https://github.com/webpack/webpack-dev-server/issues/1604 43 | allowedHosts: 'all', 44 | headers: { 45 | 'Access-Control-Allow-Origin': '*', 46 | }, 47 | }; 48 | 49 | const compiler = webpack(webpackConfig); 50 | const devServer = new WebpackDevServer(webpackDevServerConfig, compiler); 51 | 52 | devServer.startCallback(() => { 53 | if (typeof callback === 'function') { 54 | callback(); 55 | } 56 | }); 57 | }); 58 | }; 59 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "playroom", 3 | "version": "0.43.1", 4 | "description": "Design with code, powered by your own component library", 5 | "main": "utils/index.js", 6 | "types": "utils/index.d.ts", 7 | "bin": { 8 | "playroom": "bin/cli.cjs" 9 | }, 10 | "files": [ 11 | "CHANGELOG.md", 12 | ".babelrc", 13 | "images", 14 | "lib", 15 | "src", 16 | "utils" 17 | ], 18 | "scripts": { 19 | "cypress": "start-server-and-test build-and-serve:all '9000|9001|9002' 'cypress run'", 20 | "cypress:dev": "start-server-and-test start:all '9000|9001|9002' 'cypress open --browser chrome --e2e'", 21 | "cypress:verify": "cypress verify", 22 | "start": "pnpm start:basic", 23 | "start:basic": "./bin/cli.cjs start --config cypress/projects/basic/playroom.config.js", 24 | "build:basic": "./bin/cli.cjs build --config cypress/projects/basic/playroom.config.js", 25 | "serve:basic": "PORT=9000 serve --config ../serve.json --no-request-logging cypress/projects/basic/dist", 26 | "start:themed": "./bin/cli.cjs start --config cypress/projects/themed/playroom.config.js", 27 | "build:themed": "./bin/cli.cjs build --config cypress/projects/themed/playroom.config.js", 28 | "serve:themed": "PORT=9001 serve --config ../serve.json --no-request-logging cypress/projects/themed/dist", 29 | "start:typescript": "./bin/cli.cjs start --config cypress/projects/typescript/playroom.config.js", 30 | "build:typescript": "./bin/cli.cjs build --config cypress/projects/typescript/playroom.config.js", 31 | "serve:typescript": "PORT=9002 serve --config ../serve.json --no-request-logging cypress/projects/typescript/dist", 32 | "start:all": "concurrently 'npm:start:*(!all)'", 33 | "build:all": "concurrently 'npm:build:*(!all)'", 34 | "serve:all": "concurrently 'npm:serve:*(!all)'", 35 | "build-and-serve:all": "pnpm build:all && pnpm serve:all", 36 | "lint": "concurrently 'npm:lint:*'", 37 | "lint:eslint": "NODE_OPTIONS=--max_old_space_size=8192 eslint --cache .", 38 | "lint:prettier": "prettier --list-different '**/*.{js,md,ts,tsx}'", 39 | "lint:tsc": "tsc --noEmit", 40 | "lint:cypress": "tsc --project cypress/tsconfig.json", 41 | "format": "pnpm lint:eslint --fix && prettier --write '**/*.{js,md,ts,tsx}'", 42 | "version": "changeset version", 43 | "release": "changeset publish", 44 | "test": "jest src lib", 45 | "post-commit-status": "node scripts/postCommitStatus.js", 46 | "deploy-preview": "surge -p ./cypress/projects/themed/dist", 47 | "prepare": "husky", 48 | "changeset": "changeset" 49 | }, 50 | "lint-staged": { 51 | "**/*.{js,ts,tsx}": [ 52 | "eslint" 53 | ], 54 | "**/*.{js,md,ts,tsx}": [ 55 | "prettier --write" 56 | ] 57 | }, 58 | "repository": { 59 | "type": "git", 60 | "url": "https://github.com/seek-oss/playroom.git" 61 | }, 62 | "author": "SEEK", 63 | "license": "MIT", 64 | "bugs": { 65 | "url": "https://github.com/seek-oss/playroom/issues" 66 | }, 67 | "homepage": "https://github.com/seek-oss/playroom#readme", 68 | "dependencies": { 69 | "@babel/core": "^7.20.5", 70 | "@babel/parser": "^7.23.4", 71 | "@babel/preset-env": "^7.20.2", 72 | "@babel/preset-react": "^7.18.6", 73 | "@babel/preset-typescript": "^7.18.6", 74 | "@soda/friendly-errors-webpack-plugin": "^1.8.1", 75 | "@types/base64-url": "^2.2.0", 76 | "@types/codemirror": "^5.60.5", 77 | "@types/prettier": "^2.7.1", 78 | "@types/react": "^18.0.0 || ^19.0.0", 79 | "@types/react-dom": "^18.0.0 || ^19.0.0", 80 | "@vanilla-extract/css": "^1.9.2", 81 | "@vanilla-extract/css-utils": "^0.1.3", 82 | "@vanilla-extract/dynamic": "^2.1.2", 83 | "@vanilla-extract/sprinkles": "^1.5.1", 84 | "@vanilla-extract/webpack-plugin": "^2.3.6", 85 | "babel-loader": "^9.1.0", 86 | "classnames": "^2.3.2", 87 | "clsx": "^2.1.1", 88 | "codemirror": "^5.65.10", 89 | "command-line-args": "^5.2.1", 90 | "command-line-usage": "^6.1.3", 91 | "copy-to-clipboard": "^3.3.3", 92 | "css-loader": "^6.7.2", 93 | "dedent": "^1.5.1", 94 | "find-up": "^5.0.0", 95 | "fuse.js": "^7.1.0", 96 | "history": "^5.3.0", 97 | "html-webpack-plugin": "^5.5.0", 98 | "localforage": "^1.10.0", 99 | "lz-string": "^1.5.0", 100 | "memoize-one": "^6.0.0", 101 | "mini-css-extract-plugin": "^2.7.2", 102 | "parse-prop-types": "^0.3.0", 103 | "portfinder": "^1.0.32", 104 | "prettier": "^2.8.1", 105 | "prop-types": "^15.8.1", 106 | "re-resizable": "^6.11.2", 107 | "react-docgen-typescript": "^2.2.2", 108 | "react-helmet": "^6.1.0", 109 | "react-transition-group": "^4.4.5", 110 | "read-pkg-up": "^7.0.1", 111 | "scope-eval": "^1.0.0", 112 | "sucrase": "^3.34.0", 113 | "tinyglobby": "^0.2.12", 114 | "typescript": ">=5.0.0", 115 | "use-debounce": "^10.0.0", 116 | "webpack": "^5.75.0", 117 | "webpack-dev-server": "^5.0.2", 118 | "webpack-merge": "^5.8.0" 119 | }, 120 | "devDependencies": { 121 | "@actions/core": "^1.10.0", 122 | "@changesets/changelog-github": "^0.5.1", 123 | "@changesets/cli": "^2.28.1", 124 | "@octokit/rest": "^19.0.5", 125 | "@testing-library/cypress": "^10.0.3", 126 | "@types/jest": "^29.2.4", 127 | "@types/node": "^18.11.9", 128 | "@types/react-helmet": "^6.1.6", 129 | "@types/react-transition-group": "^4.4.10", 130 | "concurrently": "^9.1.2", 131 | "cypress": "^13.6.6", 132 | "eslint": "^9.23.0", 133 | "eslint-config-seek": "^14.4.0", 134 | "husky": "^9.1.7", 135 | "jest": "^29.3.1", 136 | "lint-staged": "^15.5.0", 137 | "react": "^19.0.0", 138 | "react-dom": "^19.0.0", 139 | "serve": "^14.1.2", 140 | "start-server-and-test": "^2.0.11", 141 | "surge": "^0.24.6" 142 | }, 143 | "peerDependencies": { 144 | "react": "^18 || ^19", 145 | "react-dom": "^18 || ^19" 146 | }, 147 | "engines": { 148 | "node": ">=18.12.0" 149 | }, 150 | "packageManager": "pnpm@10.6.5", 151 | "pnpm": { 152 | "onlyBuiltDependencies": [ 153 | "cypress", 154 | "esbuild" 155 | ] 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /scripts/postCommitStatus.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-console */ 2 | const core = require('@actions/core'); 3 | 4 | const writeSummary = async ({ title, link }) => { 5 | core.summary.addHeading(title, 3); 6 | core.summary.addLink(link, link); 7 | 8 | await core.summary.write(); 9 | }; 10 | 11 | (async () => { 12 | try { 13 | console.log('Posting commit status to GitHub...'); 14 | 15 | const { GITHUB_TOKEN, GITHUB_SHA } = process.env; 16 | 17 | if (!GITHUB_TOKEN || !GITHUB_SHA) { 18 | throw new Error( 19 | 'GITHUB_TOKEN and GITHUB_SHA environment variables must be present' 20 | ); 21 | } 22 | 23 | const { Octokit } = require('@octokit/rest'); 24 | const octokit = new Octokit({ 25 | auth: GITHUB_TOKEN, 26 | }); 27 | 28 | const previewUrl = `https://playroom--${GITHUB_SHA}.surge.sh`; 29 | 30 | await octokit.repos.createCommitStatus({ 31 | owner: 'seek-oss', 32 | repo: 'playroom', 33 | sha: GITHUB_SHA, 34 | state: 'success', 35 | context: 'Preview Site', 36 | target_url: previewUrl, 37 | description: 'The preview for this PR has been successfully deployed', 38 | }); 39 | 40 | console.log('Successfully posted commit status to GitHub'); 41 | 42 | await writeSummary({ 43 | title: 'Preview published', 44 | link: previewUrl, 45 | }); 46 | } catch (err) { 47 | console.error(err); 48 | process.exit(1); // eslint-disable-line no-process-exit 49 | } 50 | })(); 51 | -------------------------------------------------------------------------------- /src/.npmignore: -------------------------------------------------------------------------------- 1 | *.test.* 2 | 3 | -------------------------------------------------------------------------------- /src/Playroom/Box/Box.tsx: -------------------------------------------------------------------------------- 1 | import clsx, { type ClassValue } from 'clsx'; 2 | import { forwardRef, type AllHTMLAttributes, type ElementType } from 'react'; 3 | 4 | import { sprinkles, type Sprinkles } from '../sprinkles.css'; 5 | 6 | interface BoxProps 7 | extends Omit< 8 | AllHTMLAttributes, 9 | 'width' | 'height' | 'className' | 'data' 10 | >, 11 | Sprinkles { 12 | className?: ClassValue; 13 | component?: ElementType; 14 | } 15 | 16 | export const Box = forwardRef( 17 | ({ component = 'div', className, ...restProps }, ref) => { 18 | const atomProps: Record = {}; 19 | 20 | for (const key in restProps) { 21 | if (sprinkles.properties.has(key as keyof Sprinkles)) { 22 | atomProps[key] = restProps[key as keyof typeof restProps]; 23 | delete restProps[key as keyof typeof restProps]; 24 | } 25 | } 26 | 27 | const classes = clsx(className, sprinkles({ ...atomProps })); 28 | const Component = component; 29 | 30 | return ; 31 | } 32 | ); 33 | -------------------------------------------------------------------------------- /src/Playroom/Button/Button.css.ts: -------------------------------------------------------------------------------- 1 | import { style, createVar } from '@vanilla-extract/css'; 2 | import { calc } from '@vanilla-extract/css-utils'; 3 | 4 | import { sprinkles, colorPaletteVars } from '../sprinkles.css'; 5 | import { vars } from '../vars.css'; 6 | 7 | export const reset = style([ 8 | sprinkles({ 9 | boxSizing: 'border-box', 10 | border: 0, 11 | margin: 'none', 12 | padding: 'none', 13 | appearance: 'none', 14 | userSelect: 'none', 15 | position: 'relative', 16 | cursor: 'pointer', 17 | display: 'flex', 18 | placeItems: 'center', 19 | }), 20 | { 21 | background: 'transparent', 22 | outline: 'none', 23 | textDecoration: 'none', 24 | whiteSpace: 'nowrap', 25 | textOverflow: 'ellipsis', 26 | height: vars.touchableSize, 27 | WebkitTapHighlightColor: 'transparent', 28 | }, 29 | ]); 30 | 31 | const highlightColor = createVar(); 32 | 33 | export const base = style([ 34 | sprinkles({ 35 | borderRadius: 'large', 36 | paddingY: 'none', 37 | paddingX: 'large', 38 | font: 'standard', 39 | }), 40 | { 41 | vars: { 42 | [highlightColor]: 'currentColor', 43 | }, 44 | color: highlightColor, 45 | border: `1px solid ${colorPaletteVars.foreground.neutralSoft}`, 46 | height: calc(vars.grid).multiply(9).toString(), 47 | ':hover': { 48 | vars: { 49 | [highlightColor]: colorPaletteVars.foreground.accent, 50 | }, 51 | borderColor: highlightColor, 52 | }, 53 | ':active': { 54 | transform: 'scale(0.98)', 55 | }, 56 | '::after': { 57 | content: '', 58 | position: 'absolute', 59 | transform: 'translateY(-50%)', 60 | minHeight: vars.touchableSize, 61 | minWidth: vars.touchableSize, 62 | left: calc(vars.grid).multiply(2).negate().toString(), 63 | right: calc(vars.grid).multiply(2).negate().toString(), 64 | height: '100%', 65 | top: '50%', 66 | }, 67 | selectors: { 68 | [`&:focus:not(:active):not(:hover):not([disabled])`]: { 69 | boxShadow: colorPaletteVars.shadows.focus, 70 | }, 71 | }, 72 | }, 73 | ]); 74 | 75 | export const positive = style({ 76 | vars: { 77 | [highlightColor]: `${colorPaletteVars.foreground.positive} !important`, 78 | }, 79 | borderColor: highlightColor, 80 | }); 81 | 82 | export const iconContainer = style([ 83 | sprinkles({ position: 'relative', paddingLeft: 'small' }), 84 | { 85 | top: '1px', 86 | }, 87 | ]); 88 | -------------------------------------------------------------------------------- /src/Playroom/Button/Button.tsx: -------------------------------------------------------------------------------- 1 | import classnames from 'classnames'; 2 | import type { ElementType, AllHTMLAttributes, ReactElement } from 'react'; 3 | 4 | import * as styles from './Button.css'; 5 | 6 | interface BaseProps { 7 | as?: ElementType; 8 | tone?: 'positive'; 9 | icon?: ReactElement; 10 | } 11 | 12 | interface ButtonProps 13 | extends Omit, 'as'>, 14 | BaseProps {} 15 | 16 | interface LinkProps 17 | extends Omit, 'as'>, 18 | BaseProps {} 19 | 20 | type Props = ButtonProps | LinkProps; 21 | 22 | export const Button = ({ 23 | as: ButtonComponent = 'button', 24 | children, 25 | icon, 26 | tone, 27 | ...props 28 | }: Props) => ( 29 | 36 | {children} 37 | {icon ? {icon} : null} 38 | 39 | ); 40 | -------------------------------------------------------------------------------- /src/Playroom/CatchErrors/CatchErrors.css.ts: -------------------------------------------------------------------------------- 1 | import { sprinkles } from '../sprinkles.css'; 2 | 3 | export const root = sprinkles({ 4 | position: 'fixed', 5 | inset: 0, 6 | overflow: 'auto', 7 | padding: 'xxlarge', 8 | }); 9 | -------------------------------------------------------------------------------- /src/Playroom/CatchErrors/CatchErrors.tsx: -------------------------------------------------------------------------------- 1 | import { Component, type ErrorInfo, type ReactNode } from 'react'; 2 | 3 | import { Strong } from '../Strong/Strong'; 4 | import { Text } from '../Text/Text'; 5 | 6 | import * as styles from './CatchErrors.css'; 7 | 8 | interface Props { 9 | code?: string; 10 | children: ReactNode; 11 | } 12 | interface State { 13 | invalidCode: string | null; 14 | error: Error | null; 15 | errorInfo: ErrorInfo | null; 16 | } 17 | export default class CatchErrors extends Component { 18 | state: State = { 19 | error: null, 20 | invalidCode: null, 21 | errorInfo: null, 22 | }; 23 | 24 | componentDidCatch(error: Error, errorInfo: ErrorInfo) { 25 | const { code = null } = this.props; 26 | this.setState({ invalidCode: code, error, errorInfo }); 27 | } 28 | 29 | render() { 30 | const { invalidCode, error, errorInfo } = this.state; 31 | const { code, children } = this.props; 32 | 33 | if (code !== invalidCode || !error) { 34 | return children; 35 | } 36 | 37 | // Ensure the stack only contains user-provided components 38 | const componentStack = 39 | errorInfo?.componentStack 40 | ?.split('\n') 41 | .filter((line: string) => /RenderCode/.test(line)) 42 | .map((line: string) => line.replace(/ \(created by .*/g, '')) ?? []; 43 | 44 | // Ignore the RenderCode container component 45 | const lines = componentStack.slice(0, componentStack.length - 1); 46 | 47 | return ( 48 |
49 | 50 | {error.message} 51 | {lines.map((line, i) => ( 52 | {line} 53 | ))} 54 | 55 |
56 | ); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Playroom/CodeEditor/keymaps/complete.ts: -------------------------------------------------------------------------------- 1 | import CodeMirror, { type Editor } from 'codemirror'; 2 | 3 | export const completeAfter = (cm: Editor, predicate?: () => boolean) => { 4 | if (!predicate || predicate()) { 5 | setTimeout(() => { 6 | if (!cm.state.completionActive) { 7 | cm.showHint({ completeSingle: false }); 8 | } 9 | }, 100); 10 | } 11 | 12 | return CodeMirror.Pass; 13 | }; 14 | 15 | export const completeIfAfterLt = (cm: Editor) => 16 | completeAfter(cm, () => { 17 | const cur = cm.getCursor(); 18 | // eslint-disable-next-line new-cap 19 | return cm.getRange(CodeMirror.Pos(cur.line, cur.ch - 1), cur) === '<'; 20 | }); 21 | 22 | export const completeIfInTag = (cm: Editor) => 23 | completeAfter(cm, () => { 24 | const tok = cm.getTokenAt(cm.getCursor()); 25 | if ( 26 | tok.type === 'string' && 27 | (!/['"]/.test(tok.string.charAt(tok.string.length - 1)) || 28 | tok.string.length === 1) 29 | ) { 30 | return false; 31 | } 32 | const inner = CodeMirror.innerMode(cm.getMode(), tok.state).state; 33 | return inner.tagName; 34 | }); 35 | -------------------------------------------------------------------------------- /src/Playroom/CodeEditor/keymaps/cursors.ts: -------------------------------------------------------------------------------- 1 | import CodeMirror, { type Editor, Pos } from 'codemirror'; 2 | 3 | import 'codemirror/addon/search/searchcursor'; 4 | 5 | import type { Direction, Selection } from './types'; 6 | 7 | function wordAt(cm: Editor, pos: CodeMirror.Position) { 8 | let start = pos.ch; 9 | let end = start; 10 | const line = cm.getLine(pos.line); 11 | 12 | // Move `start` back to the beginning of the word 13 | while (start && CodeMirror.isWordChar(line.charAt(start - 1))) { 14 | --start; 15 | } 16 | 17 | // Move `end` to the end of the word 18 | while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) { 19 | ++end; 20 | } 21 | 22 | return { 23 | from: new Pos(pos.line, start), 24 | to: new Pos(pos.line, end), 25 | word: line.slice(start, end), 26 | }; 27 | } 28 | 29 | function rangeIsAlreadySelected( 30 | ranges: CodeMirror.Range[], 31 | checkRange: Pick 32 | ) { 33 | for (const range of ranges) { 34 | const startsFromStart = 35 | CodeMirror.cmpPos(range.from(), checkRange.from()) === 0; 36 | const endsAtEnd = CodeMirror.cmpPos(range.to(), checkRange.to()) === 0; 37 | 38 | if (startsFromStart && endsAtEnd) { 39 | return true; 40 | } 41 | } 42 | 43 | return false; 44 | } 45 | 46 | export const selectNextOccurrence = (cm: Editor) => { 47 | const from = cm.getCursor('from'); 48 | const to = cm.getCursor('to'); 49 | 50 | // If the selections are the same as last time this 51 | // ran, we're still in full word mode 52 | let fullWord = cm.state.selectNextFindFullWord === cm.listSelections(); 53 | 54 | // If this is just a cursor, rather than a selection 55 | if (CodeMirror.cmpPos(from, to) === 0) { 56 | const word = wordAt(cm, from); 57 | 58 | // And there's no actual word at that cursor, then do nothing 59 | if (!word.word) { 60 | return; 61 | } 62 | 63 | // Otherwise select the word and enter full word mode 64 | cm.setSelection(word.from, word.to); 65 | fullWord = true; 66 | } else { 67 | const text = cm.getRange(from, to); 68 | const query = fullWord ? new RegExp(`\\b${text}\\b`) : text; 69 | let cur = cm.getSearchCursor(query, to); 70 | let found = cur.findNext(); 71 | 72 | // If we didn't find any occurrence in the rest of the 73 | // document, start again at the start 74 | if (!found) { 75 | cur = cm.getSearchCursor(query, new Pos(cm.firstLine(), 0)); 76 | found = cur.findNext(); 77 | } 78 | 79 | // If we still didn't find anything, or we re-discover a selection 80 | // we already have, then do nothing 81 | if (!found || rangeIsAlreadySelected(cm.listSelections(), cur)) { 82 | return; 83 | } 84 | 85 | cm.addSelection(cur.from(), cur.to()); 86 | } 87 | 88 | if (fullWord) { 89 | cm.state.selectNextFindFullWord = cm.listSelections(); 90 | } 91 | }; 92 | 93 | function addCursorToSelection(cm: Editor, dir: Direction) { 94 | const ranges = cm.listSelections(); 95 | const newRanges: Selection[] = []; 96 | 97 | const linesToMove = dir === 'up' ? -1 : 1; 98 | 99 | for (const range of ranges) { 100 | const newAnchor = cm.findPosV(range.anchor, linesToMove, 'line'); 101 | const newHead = cm.findPosV(range.head, linesToMove, 'line'); 102 | 103 | newRanges.push(range); 104 | newRanges.push({ anchor: newAnchor, head: newHead }); 105 | } 106 | 107 | cm.setSelections(newRanges); 108 | } 109 | 110 | export const addCursorToPrevLine = (cm: Editor) => 111 | addCursorToSelection(cm, 'up'); 112 | export const addCursorToNextLine = (cm: Editor) => 113 | addCursorToSelection(cm, 'down'); 114 | -------------------------------------------------------------------------------- /src/Playroom/CodeEditor/keymaps/lines.ts: -------------------------------------------------------------------------------- 1 | import CodeMirror, { type Editor, Pos } from 'codemirror'; 2 | 3 | import type { Direction, Selection } from './types'; 4 | type RangeMethod = Extract; 5 | 6 | const directionToMethod: Record = { 7 | up: 'to', 8 | down: 'from', 9 | }; 10 | 11 | type ContentUpdate = [string, [CodeMirror.Position, CodeMirror.Position?]]; 12 | 13 | const getNewPosition = ( 14 | range: CodeMirror.Range, 15 | direction: Direction, 16 | extraLines: number 17 | ) => { 18 | const currentLine = range[directionToMethod[direction]]().line; 19 | 20 | const newLine = direction === 'up' ? currentLine + 1 : currentLine; 21 | return new Pos(newLine + extraLines, 0); 22 | }; 23 | 24 | const moveByLines = (range: CodeMirror.Range, lines: number) => { 25 | const anchor = new Pos(range.anchor.line + lines, range.anchor.ch); 26 | const head = new Pos(range.head.line + lines, range.head.ch); 27 | 28 | return { anchor, head }; 29 | }; 30 | 31 | export const duplicateLine = (direction: Direction) => (cm: Editor) => { 32 | const ranges = cm.listSelections(); 33 | 34 | const contentUpdates: ContentUpdate[] = []; 35 | const newSelections: Selection[] = []; 36 | 37 | // To keep the selections in the right spot, we need to track how many additional 38 | // lines have been introduced to the document (in multicursor mode). 39 | let newLinesSoFar = 0; 40 | 41 | for (const range of ranges) { 42 | const newLineCount = range.to().line - range.from().line + 1; 43 | const existingContent = cm.getRange( 44 | new Pos(range.from().line, 0), 45 | new Pos(range.to().line) 46 | ); 47 | 48 | const newContentParts = [existingContent, '\n']; 49 | 50 | // Copy up on the last line has some unusual behaviour 51 | if (range.to().line === cm.lastLine() && direction === 'up') { 52 | newContentParts.reverse(); 53 | } 54 | 55 | const newContent = newContentParts.join(''); 56 | 57 | contentUpdates.push([ 58 | newContent, 59 | [getNewPosition(range, direction, newLinesSoFar)], 60 | ]); 61 | 62 | // Copy up doesn't always handle its cursors correctly 63 | if (direction === 'up') { 64 | newSelections.push(moveByLines(range, newLinesSoFar)); 65 | } 66 | 67 | newLinesSoFar += newLineCount; 68 | } 69 | 70 | cm.operation(function () { 71 | for (const [newContent, [start, end]] of contentUpdates) { 72 | cm.replaceRange(newContent, start, end, '+swapLine'); 73 | } 74 | 75 | // Shift the selection up by one line to match the moved content 76 | cm.setSelections(newSelections); 77 | }); 78 | }; 79 | 80 | export const swapLineUp = function (cm: Editor) { 81 | if (cm.isReadOnly()) { 82 | return CodeMirror.Pass; 83 | } 84 | 85 | // We need to keep track of the current bottom of the block 86 | // to make sure we're not overwriting lines 87 | let lastLine = cm.firstLine() - 1; 88 | 89 | const rangesToMove: Array<{ from: number; to: number }> = []; 90 | const newSels: Selection[] = []; 91 | 92 | for (const range of cm.listSelections()) { 93 | // Include one line above the current range 94 | const from = range.from().line - 1; 95 | let to = range.to().line; 96 | 97 | // Shift the selection up by one line 98 | newSels.push({ 99 | anchor: new Pos(range.anchor.line - 1, range.anchor.ch), 100 | head: new Pos(range.head.line - 1, range.head.ch), 101 | }); 102 | 103 | // If we've accidentally run over to the start of the 104 | // next line, then go back up one 105 | if (range.to().ch === 0 && !range.empty()) { 106 | --to; 107 | } 108 | 109 | // If the one-line-before-current-range is after the last line, put 110 | // the start and end lines in the list of lines to move 111 | if (from > lastLine) { 112 | rangesToMove.push({ from, to }); 113 | // If the ranges overlap, update the last range in the list 114 | // to include both ranges 115 | } else if (rangesToMove.length) { 116 | rangesToMove[rangesToMove.length - 1].to = to; 117 | } 118 | 119 | // Move the last line to the end of the current range 120 | lastLine = to; 121 | } 122 | 123 | cm.operation(function () { 124 | for (const range of rangesToMove) { 125 | const { from, to } = range; 126 | const line = cm.getLine(from); 127 | cm.replaceRange('', new Pos(from, 0), new Pos(from + 1, 0), '+swapLine'); 128 | 129 | if (to > cm.lastLine()) { 130 | cm.replaceRange( 131 | `\n${line}`, 132 | new Pos(cm.lastLine()), 133 | undefined, 134 | '+swapLine' 135 | ); 136 | } else { 137 | cm.replaceRange(`${line}\n`, new Pos(to, 0), undefined, '+swapLine'); 138 | } 139 | } 140 | 141 | cm.setSelections(newSels); 142 | cm.scrollIntoView(null); 143 | }); 144 | }; 145 | 146 | export const swapLineDown = function (cm: Editor) { 147 | if (cm.isReadOnly()) { 148 | return CodeMirror.Pass; 149 | } 150 | 151 | const ranges = cm.listSelections(); 152 | const rangesToMove: Array<{ from: number; to: number }> = []; 153 | 154 | let firstLine = cm.lastLine() + 1; 155 | 156 | for (const range of [...ranges].reverse()) { 157 | let from = range.to().line + 1; 158 | const to = range.from().line; 159 | 160 | if (range.to().ch === 0 && !range.empty()) { 161 | from--; 162 | } 163 | 164 | if (from < firstLine) { 165 | rangesToMove.push({ from, to }); 166 | } else if (rangesToMove.length) { 167 | rangesToMove[rangesToMove.length - 1].to = to; 168 | } 169 | 170 | firstLine = to; 171 | } 172 | 173 | cm.operation(function () { 174 | for (const range of rangesToMove) { 175 | const { from, to } = range; 176 | const line = cm.getLine(from); 177 | if (from === cm.lastLine()) { 178 | cm.replaceRange('', new Pos(from - 1), new Pos(from), '+swapLine'); 179 | } else { 180 | cm.replaceRange( 181 | '', 182 | new Pos(from, 0), 183 | new Pos(from + 1, 0), 184 | '+swapLine' 185 | ); 186 | } 187 | 188 | cm.replaceRange(`${line}\n`, new Pos(to, 0), undefined, '+swapLine'); 189 | } 190 | cm.scrollIntoView(null); 191 | }); 192 | }; 193 | -------------------------------------------------------------------------------- /src/Playroom/CodeEditor/keymaps/types.ts: -------------------------------------------------------------------------------- 1 | import type { Editor } from 'codemirror'; 2 | 3 | export type Direction = 'up' | 'down'; 4 | 5 | export type Selection = Parameters[0][number]; 6 | -------------------------------------------------------------------------------- /src/Playroom/CodeEditor/keymaps/wrap.ts: -------------------------------------------------------------------------------- 1 | import { type Editor, Pos } from 'codemirror'; 2 | 3 | import type { Selection } from './types'; 4 | 5 | interface TagRange { 6 | from: CodeMirror.Position; 7 | to: CodeMirror.Position; 8 | multiLine: boolean; 9 | existingIndent: number; 10 | } 11 | 12 | export const wrapInTag = (cm: Editor) => { 13 | const newSelections: Selection[] = []; 14 | const tagRanges: TagRange[] = []; 15 | 16 | let linesAdded = 0; 17 | 18 | for (const range of cm.listSelections()) { 19 | const from = range.from(); 20 | let to = range.to(); 21 | 22 | const isMultiLineSelection = to.line !== from.line; 23 | 24 | if (to.line !== from.line && to.ch === 0) { 25 | to = new Pos(to.line - 1); 26 | } 27 | 28 | const existingContent = cm.getRange(from, to); 29 | const existingIndent = 30 | existingContent.length - existingContent.trimStart().length; 31 | 32 | tagRanges.push({ 33 | from, 34 | to, 35 | multiLine: isMultiLineSelection, 36 | existingIndent, 37 | }); 38 | 39 | const startCursorCharacterPosition = 40 | from.ch + 1 + (isMultiLineSelection ? existingIndent : 0); 41 | const newStartCursor = new Pos( 42 | from.line + linesAdded, 43 | startCursorCharacterPosition 44 | ); 45 | 46 | const newEndCursor = isMultiLineSelection 47 | ? new Pos(to.line + linesAdded + 2, from.ch + existingIndent + 2) 48 | : new Pos(to.line + linesAdded, to.ch + 4); 49 | 50 | if (isMultiLineSelection) { 51 | linesAdded += 2; 52 | } 53 | 54 | newSelections.push({ anchor: newStartCursor, head: newStartCursor }); 55 | newSelections.push({ anchor: newEndCursor, head: newEndCursor }); 56 | } 57 | 58 | cm.operation(() => { 59 | for (const range of [...tagRanges].reverse()) { 60 | const existingContent = cm.getRange(range.from, range.to); 61 | 62 | if (range.multiLine) { 63 | const formattedExistingContent = existingContent 64 | .split('\n') 65 | .map((line, idx) => { 66 | const indentLevel = ' '.repeat((idx === 0 ? range.from.ch : 0) + 2); 67 | return `${indentLevel}${line}`; 68 | }) 69 | .join('\n'); 70 | 71 | const openTagIndentLevel = ' '.repeat(range.existingIndent); 72 | const closeTagIndentLevel = ' '.repeat( 73 | range.from.ch + range.existingIndent 74 | ); 75 | 76 | cm.replaceRange( 77 | `${openTagIndentLevel}<>\n${formattedExistingContent}\n${closeTagIndentLevel}`, 78 | range.from, 79 | range.to 80 | ); 81 | } else { 82 | cm.replaceRange(`<>${existingContent}`, range.from, range.to); 83 | } 84 | } 85 | 86 | cm.setSelections(newSelections); 87 | }); 88 | }; 89 | -------------------------------------------------------------------------------- /src/Playroom/Frame.tsx: -------------------------------------------------------------------------------- 1 | import type { ReactNode } from 'react'; 2 | 3 | import { useParams } from '../utils/params'; 4 | 5 | import CatchErrors from './CatchErrors/CatchErrors'; 6 | // @ts-expect-error 7 | import RenderCode from './RenderCode/RenderCode'; 8 | 9 | interface FrameProps { 10 | themes: Record; 11 | components: any[]; 12 | FrameComponent: React.ComponentType<{ 13 | themeName: string | null; 14 | theme: string; 15 | children?: ReactNode; 16 | }>; 17 | } 18 | export default function Frame({ 19 | themes, 20 | components, 21 | FrameComponent, 22 | }: FrameProps) { 23 | const { themeName, code } = useParams((rawParams) => { 24 | const rawThemeName = rawParams.get('themeName'); 25 | const rawCode = rawParams.get('code'); 26 | 27 | return { 28 | themeName: rawThemeName || '', 29 | code: rawCode || '', 30 | }; 31 | }); 32 | 33 | const resolvedThemeName = 34 | themeName === '__PLAYROOM__NO_THEME__' ? null : themeName; 35 | const resolvedTheme = resolvedThemeName ? themes[resolvedThemeName] : null; 36 | 37 | return ( 38 | 39 | 40 | 41 | 42 | 43 | ); 44 | } 45 | -------------------------------------------------------------------------------- /src/Playroom/Frames/Frames.css.ts: -------------------------------------------------------------------------------- 1 | import { createVar, style } from '@vanilla-extract/css'; 2 | 3 | import { sprinkles } from '../sprinkles.css'; 4 | 5 | export const root = style([ 6 | sprinkles({ 7 | height: 'full', 8 | width: 'full', 9 | boxSizing: 'border-box', 10 | display: 'flex', 11 | gap: 'gutter', 12 | padding: 'gutter', 13 | textAlign: 'center', 14 | overflow: 'auto', 15 | }), 16 | { 17 | justifyContent: 'safe center', 18 | }, 19 | ]); 20 | 21 | export const frameWidth = createVar(); 22 | 23 | export const frameContainer = style([ 24 | sprinkles({ 25 | position: 'relative', 26 | height: 'full', 27 | textAlign: 'left', 28 | display: 'flex', 29 | flexDirection: 'column', 30 | }), 31 | { 32 | flexShrink: 0, 33 | width: frameWidth, 34 | }, 35 | ]); 36 | 37 | export const frame = sprinkles({ 38 | border: 0, 39 | flexGrow: 1, 40 | width: 'full', 41 | height: 'full', 42 | }); 43 | 44 | export const frameBorder = style([ 45 | sprinkles({ 46 | position: 'absolute', 47 | inset: 0, 48 | boxShadow: 'small', 49 | transition: 'medium', 50 | pointerEvents: 'none', 51 | }), 52 | { 53 | selectors: { 54 | [`${frameContainer}:not(:hover) &`]: { 55 | opacity: 0.8, 56 | }, 57 | }, 58 | }, 59 | ]); 60 | 61 | const frameNameHeight = '30px'; 62 | export const frameName = style([ 63 | sprinkles({ 64 | display: 'flex', 65 | alignItems: 'center', 66 | transition: 'medium', 67 | }), 68 | { 69 | flex: `0 0 ${frameNameHeight}`, 70 | height: frameNameHeight, 71 | marginBottom: '-10px', 72 | selectors: { 73 | [`${frameContainer}:not(:hover) &`]: { 74 | opacity: 0.3, 75 | }, 76 | }, 77 | }, 78 | ]); 79 | -------------------------------------------------------------------------------- /src/Playroom/Frames/Frames.tsx: -------------------------------------------------------------------------------- 1 | import { assignInlineVars } from '@vanilla-extract/dynamic'; 2 | import { useRef } from 'react'; 3 | 4 | import playroomConfig from '../../config'; 5 | import { compileJsx } from '../../utils/compileJsx'; 6 | import { Box } from '../Box/Box'; 7 | import type { PlayroomProps } from '../Playroom'; 8 | import { Strong } from '../Strong/Strong'; 9 | import { Text } from '../Text/Text'; 10 | 11 | import Iframe from './Iframe'; 12 | import frameSrc from './frameSrc'; 13 | 14 | import * as styles from './Frames.css'; 15 | 16 | interface FramesProps { 17 | code: string; 18 | themes: PlayroomProps['themes']; 19 | widths: PlayroomProps['widths']; 20 | } 21 | 22 | export default function Frames({ code, themes, widths }: FramesProps) { 23 | const scrollingPanelRef = useRef(null); 24 | const renderCode = useRef(''); 25 | 26 | const frames = widths.flatMap((width) => 27 | themes.map((theme) => ({ 28 | theme, 29 | width, 30 | widthName: `${width}${/\d$/.test(width.toString()) ? 'px' : ''}`, 31 | })) 32 | ); 33 | 34 | try { 35 | renderCode.current = compileJsx(code); 36 | } catch {} 37 | 38 | return ( 39 |
40 | {frames.map((frame) => ( 41 |
49 | 50 |