diff --git a/.babelrc.js b/.babelrc.js index 8559a138..25da7069 100644 --- a/.babelrc.js +++ b/.babelrc.js @@ -1,16 +1,17 @@ module.exports = { presets: [ - "@babel/preset-env", - "@babel/preset-typescript", - "@babel/preset-react", + ['@babel/preset-env', { targets: { node: 'current' } }], + '@babel/preset-typescript', + '@babel/preset-react', ], env: { esm: { presets: [ [ - "@babel/preset-env", + '@babel/preset-env', { modules: false, + targets: { node: 'current' }, }, ], ], diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..ffb9b945 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,21 @@ +name: Test + +on: [push] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Use Node.js 14.x + uses: actions/setup-node@v1 + with: + node-version: 14.x + + - name: Install dependencies + uses: bahmutov/npm-install@v1 + + - name: Run tests + run: | + yarn test diff --git a/.gitignore b/.gitignore index a951d51d..6d39ddac 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,7 @@ node_modules/ storybook-static/ build-storybook.log .DS_Store -.env \ No newline at end of file +.env +.cache +stories/design-system +yarn-error.log \ No newline at end of file diff --git a/.prettierrc b/.prettierrc index 0967ef42..d033feea 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1 +1,8 @@ -{} +{ + "printWidth": 100, + "tabWidth": 2, + "bracketSpacing": true, + "trailingComma": "es5", + "singleQuote": true, + "arrowParens": "always" +} diff --git a/.storybook/main.js b/.storybook/main.js index 4f864dc0..528997c4 100644 --- a/.storybook/main.js +++ b/.storybook/main.js @@ -3,5 +3,5 @@ module.exports = { "../stories/**/*.stories.mdx", "../stories/**/*.stories.@(js|jsx|ts|tsx)", ], - addons: ["../preset.js", "@storybook/addon-essentials"], + addons: ["@storybook/addon-essentials"], }; diff --git a/README.md b/README.md index 04d1737c..c69dc82c 100644 --- a/README.md +++ b/README.md @@ -1,114 +1,197 @@ -# Storybook Addon Kit +# Storybook Test Runner -Simplify the creation of Storybook addons +Storybook test runner turns all of your stories into executable tests. -- 📝 Live-editing in development -- ⚛️ React/JSX support -- 📦 Transpiling and bundling with Babel -- 🏷 Plugin metadata -- 🚢 Release management with [Auto](https://github.com/intuit/auto) -- 🧺 Boilerplate and sample code -- 🛄 ESM support -- 🛂 TypeScript by default with option to eject to JS +## Table of Contents -## Getting Started +- [1. Features](#features) +- [2. Getting Started](#getting-started) +- [3. Configuration](#configuration) +- [3. Running against a deployed Storybook](#running-against-a-deployed-storybook) +- [4. Running in CI](#running-in-ci) +- [5. Troubleshooting](#troubleshooting) +- [6. Future work](#future-work) -Click the **Use this template** button to get started. +## Features -![](https://user-images.githubusercontent.com/321738/125058439-8d9ef880-e0aa-11eb-9211-e6d7be812959.gif) +- ⚡️ Zero config setup +- 💨 Smoke test all stories +- ▶️ Test stories with play functions +- 🏃 Test your stories in parallel in a headless browser +- 👷 Get feedback from error with a link directly to the story +- 🐛 Debug them visually and interactively in a live browser with [addon-interactions](https://storybook.js.org/docs/react/essentials/interactions) +- 🎭 Powered by [Jest](https://jestjs.io/) and [Playwright](https://playwright.dev/) +- 👀 Watch mode, filters, and the conveniences you'd expect -Clone your repository and install dependencies. +## Getting started -```sh -yarn -``` - -### Development scripts - -- `yarn start` runs babel in watch mode and starts Storybook -- `yarn build` build and package your addon code - -### Switch from TypeScript to JavaScript - -Don't want to use TypeScript? We offer a handy eject command: `yarn eject-ts` - -This will convert all code to JS. It is a destructive process, so we recommended running this before you start writing any code. +1. Install the test runner and the interactions addon in Storybook: -## What's included? - -![Demo](https://user-images.githubusercontent.com/42671/107857205-e7044380-6dfa-11eb-8718-ad02e3ba1a3f.gif) - -The addon code lives in `src`. It demonstrates all core addon related concepts. The three [UI paradigms](https://storybook.js.org/docs/react/addons/addon-types#ui-based-addons) - -- `src/Tool.js` -- `src/Panel.js` -- `src/Tab.js` - -Which, along with the addon itself, are registered in `src/preset/manager.js`. +```jsx +yarn add @storybook/test-runner -D +``` -Managing State and interacting with a story: +
+ 1.1 Optional instructions to install the Interactions addon for visual debugging of play functions + + ```jsx + yarn add @storybook/addon-interactions @storybook/jest @storybook/testing-library -D + ``` + + Then add it to your `.storybook/main.js` config and enable debugging: + + ```jsx + module.exports = { + stories: ['@storybook/addon-interactions'], + features: { + interactionsDebugger: true, + } + }; + ``` +
+ +2. Add a `test-storybook` script to your package.json + +```json +{ + "scripts": { + "test-storybook": "test-storybook" + } +} +``` -- `src/withGlobals.js` & `src/Tool.js` demonstrates how to use `useGlobals` to manage global state and modify the contents of a Story. -- `src/withRoundTrip.js` & `src/Panel.js` demonstrates two-way communication using channels. -- `src/Tab.js` demonstrates how to use `useParameter` to access the current story's parameters. +3. Run Storybook (the test runner runs against a running Storybook instance): -Your addon might use one or more of these patterns. Feel free to delete unused code. Update `src/preset/manager.js` and `src/preset/preview.js` accordingly. +```jsx +yarn storybook +``` -Lastly, configure you addon name in `src/constants.js`. +4. Run the test runner: -### Metadata +```jsx +yarn test-storybook +``` -Storybook addons are listed in the [catalog](https://storybook.js.org/addons) and distributed via npm. The catalog is populated by querying npm's registry for Storybook-specific metadata in `package.json`. This project has been configured with sample data. Learn more about available options in the [Addon metadata docs](https://storybook.js.org/docs/react/addons/addon-catalog#addon-metadata). +> **NOTE:** The runner assumes that your Storybook is running on port `6006`. If you're running Storybook in another port, set the TARGET_URL before running your command like: +>```jsx +>TARGET_URL=http://localhost:9009 yarn test-storybook +>``` + +## Configuration + +The test runner is based on [Jest](https://jestjs.io/) and will accept the [CLI options](https://jestjs.io/docs/cli) that Jest does, like `--watch`, `--marWorkers`, etc. + +The test runner works out of the box, but you can override its Jest configuration by adding a `test-runner-jest.config.js` that sets up your environment in the root folder of your project. + +```js +// test-runner-jest.config.js +module.exports = { + cacheDirectory: 'node_modules/.cache/storybook/test-runner', + testMatch: ['**/*.stories.[jt]s(x)?'], + transform: { + '^.+\\.stories\\.[jt]sx?$': '@storybook/test-runner/playwright/transform', + '^.+\\.[jt]sx?$': 'babel-jest', + }, + preset: 'jest-playwright-preset', + testEnvironment: '@storybook/test-runner/playwright/custom-environment.js', + testEnvironmentOptions: { + 'jest-playwright': { + browsers: ['chromium', 'firefox', 'webkit'], // run tests against all browsers + }, + }, +}; +``` -## Release Management +The runner uses [jest-playwright](https://github.com/playwright-community/jest-playwright) and you can pass [testEnvironmentOptions](https://github.com/playwright-community/jest-playwright#configuration) to further configure it, such as how it's done above to run tests against all browsers instead of just chromium. -### Setup +## Running against a deployed Storybook -This project is configured to use [auto](https://github.com/intuit/auto) for release management. It generates a changelog and pushes it to both GitHub and npm. Therefore, you need to configure access to both: +By default, the test runner assumes that you're running it against a locally served Storybook. +If you want to define a target url so it runs against deployed Storybooks, you can do so by passing the `TARGET_URL` environment variable: -- [`NPM_TOKEN`](https://docs.npmjs.com/creating-and-viewing-access-tokens#creating-access-tokens) Create a token with both _Read and Publish_ permissions. -- [`GH_TOKEN`](https://github.com/settings/tokens) Create a token with the `repo` scope. +```bash +TARGET_URL=https://the-storybook-url-here.com yarn test-storybook +``` -Then open your `package.json` and edit the following fields: +## Running in CI + +### Running against deployed Storybooks on Github Actions deployment + +On Github actions, once services like Vercel, Netlify and others do deployment run, they follow a pattern of emitting a `deployment_status` event containing the newly generated URL under `deployment_status.target_url`. Here's an example of an action to run tests based on that: + +```yml +name: Storybook Tests +on: deployment_status +jobs: + test: + timeout-minutes: 60 + runs-on: ubuntu-latest + if: github.event.deployment_status.state == 'success' + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v2 + with: + node-version: '14.x' + - name: Install dependencies + run: yarn + - name: Run Storybook tests + run: yarn test-storybook + env: + TARGET_URL: '${{ github.event.deployment_status.target_url }}' +``` -- `name` -- `author` -- `repository` +### Running againts locally built Storybooks in CI -#### Local +In order to build and run tests against your Storybook in CI, you might need to use a combination of commands involving the [concurrently](https://www.npmjs.com/package/concurrently), [http-server](https://www.npmjs.com/package/http-server) and [wait-on](https://www.npmjs.com/package/wait-on) libraries. Here's a recipe that does the following: Storybook is built and served locally, and once it is ready, the test runner will run against it. -To use `auto` locally create a `.env` file at the root of your project and add your tokens to it: +```json +{ + "test-storybook:ci": "concurrently -k -s first -n \"SB,TEST\" -c \"magenta,blue\" \"yarn build-storybook && npx http-server storybook-static --port 6006 --silent\" \"wait-on tcp:6006 && yarn test-storybook\"" +} +``` -```bash -GH_TOKEN= -NPM_TOKEN= +And then you can essentially run `test-storybook:ci` in your CI: + +```yml +name: Storybook Tests +on: push +jobs: + test: + timeout-minutes: 60 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v2 + with: + node-version: '14.x' + - name: Install dependencies + run: yarn + - name: Run Storybook tests + run: yarn test-storybook:ci ``` -Lastly, **create labels on GitHub**. You’ll use these labels in the future when making changes to the package. -```bash -npx auto create-labels -``` +## Troubleshooting -If you check on GitHub, you’ll now see a set of labels that `auto` would like you to use. Use these to tag future pull requests. +#### The test runner seems flaky and keeps timing out -#### GitHub Actions +If your tests are timing out with `Timeout - Async callback was not invoked within the 15000 ms timeout specified by jest.setTimeout`, it might be that playwright couldn't handle to test the amount of stories you have in your project. Maybe you have a large amount of stories or your CI has a really low RAM configuration. -This template comes with GitHub actions already set up to publish your addon anytime someone pushes to your repository. +In either way, to fix it you should limit the amount of workers that run in parallel by passing the [--maxWorkers](https://jestjs.io/docs/cli#--maxworkersnumstring) option to your command: -Go to `Settings > Secrets`, click `New repository secret`, and add your `NPM_TOKEN`. +```json +{ + "test-storybook:ci": "concurrently -k -s first -n \"SB,TEST\" -c \"magenta,blue\" \"yarn build-storybook && npx http-server storybook-static --port 6006 --silent\" \"wait-on tcp:6006 && yarn test-storybook --maxWorkers=2\"" +} +``` -### Creating a releasing +#### Adding the test runner to other CI environments -To create a release locally you can run the following command, otherwise the GitHub action will make the release for you. +As the test runner is based on playwright, depending on your CI setup you might need to use specific docker images or other configuration. In that case, you can refer to the [Playwright CI docs](https://playwright.dev/docs/ci) for more information. -```sh -yarn release -``` +## Future work -That will: +Future plans involve adding support for the following features: -- Build and package the addon code -- Bump the version -- Push a release to GitHub and npm -- Push a changelog to GitHub +- 🧪 Custom test functions +- 📄 Run addon reports diff --git a/bin/test-storybook.js b/bin/test-storybook.js new file mode 100644 index 00000000..06bc18ac --- /dev/null +++ b/bin/test-storybook.js @@ -0,0 +1,65 @@ +#!/usr/bin/env node +//@ts-check +'use strict'; + +const urlExists = require('url-exists'); + +// Do this as the first thing so that any code reading it knows the right env. +process.env.BABEL_ENV = 'test'; +process.env.NODE_ENV = 'test'; +process.env.PUBLIC_URL = ''; + +// Makes the script crash on unhandled rejections instead of silently +// ignoring them. In the future, promise rejections that are not handled will +// terminate the Node.js process with a non-zero exit code. +process.on('unhandledRejection', err => { + throw err; +}); + +function sanitizeURL(url) { + let finalURL = url + // prepend URL protocol if not there + if (finalURL.indexOf("http://") === -1 && finalURL.indexOf("https://") === -1) { + finalURL = 'http://' + finalURL; + } + + // remove iframe.html if present + finalURL = finalURL.replace(/iframe.html\s*$/, ""); + + // add forward slash at the end if not there + if (finalURL.slice(-1) !== '/') { + finalURL = finalURL + '/'; + } + + return finalURL; +} + +const targetURL = sanitizeURL(process.env.TARGET_URL || `http://localhost:6006`); + +urlExists(targetURL, function (err, exists) { + if (!exists) { + console.error(`[test-storybook] It seems that your Storybook instance is not running at: ${targetURL}. Are you sure it's running?`) + process.exit(1) + } + + executeJestPlaywright() +}); + +function executeJestPlaywright() { + const fs = require('fs'); + const path = require('path'); + + const jest = require('jest'); + let argv = process.argv.slice(2); + + const jestConfigPath = fs.existsSync('test-runner-jest.config.js') + ? 'test-runner-jest.config.js' + : path.resolve(__dirname, '../test-runner-jest.config.js') + + argv.push( + '--config', + jestConfigPath + ); + + jest.run(argv); +} diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 00000000..851b11be --- /dev/null +++ b/jest.config.js @@ -0,0 +1,3 @@ +module.exports = { + testMatch: ['**/*.test.ts'], +}; diff --git a/jsdom-jest.config.js b/jsdom-jest.config.js new file mode 100644 index 00000000..6dbbf297 --- /dev/null +++ b/jsdom-jest.config.js @@ -0,0 +1,15 @@ +module.exports = { + cacheDirectory: '.cache/jest', + testMatch: ['**/*.stories.[jt]s?(x)'], + moduleNameMapper: { + // non-js files + '\\.(jpg|jpeg|png|apng|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': + '/mocks/fileMock.js', + '\\.(css|scss|stylesheet)$': '/mocks/styleMock.js', + }, + transform: { + '^.+\\.stories\\.[jt]sx?$': './jsdom/transform', + '^.+\\.[jt]sx?$': 'babel-jest', + }, + testEnvironment: 'jest-environment-jsdom', +}; diff --git a/jsdom/transform.js b/jsdom/transform.js new file mode 100644 index 00000000..5f94fd02 --- /dev/null +++ b/jsdom/transform.js @@ -0,0 +1,20 @@ +const { transform: babelTransform } = require('@babel/core'); +const { transformJsdom } = require('../dist/cjs/jsdom/transformJsdom'); + +module.exports = { + process(src, filename, config) { + const csfTest = transformJsdom(src); + + const result = babelTransform(csfTest, { + filename, + babelrc: false, + configFile: false, + presets: [ + ['@babel/preset-env', { targets: { node: 'current' } }], + '@babel/preset-typescript', + '@babel/preset-react', + ], + }); + return result ? result.code : src; + }, +}; diff --git a/mocks/fileMock.js b/mocks/fileMock.js new file mode 100644 index 00000000..105ff497 --- /dev/null +++ b/mocks/fileMock.js @@ -0,0 +1 @@ +module.exports = 'file-stub'; diff --git a/mocks/htmlMock.js b/mocks/htmlMock.js new file mode 100644 index 00000000..0062fcfe --- /dev/null +++ b/mocks/htmlMock.js @@ -0,0 +1 @@ +module.exports = '

HTML Mock

'; diff --git a/mocks/styleMock.js b/mocks/styleMock.js new file mode 100644 index 00000000..f053ebf7 --- /dev/null +++ b/mocks/styleMock.js @@ -0,0 +1 @@ +module.exports = {}; diff --git a/package.json b/package.json index 61dd1891..e5bbe7ea 100644 --- a/package.json +++ b/package.json @@ -1,24 +1,31 @@ { - "name": "storybook-addon-kit", + "name": "@storybook/test-runner", "version": "0.0.0", - "description": "everything you need to build a Storybook addon", + "description": "Test runner for Storybook stories", "keywords": [ "storybook-addons", - "style", - "test" + "test", + "runner", + "jest", + "testing-library", + "playwright" ], "repository": { "type": "git", - "url": "https://github.com/storybookjs/storybook-addon-kit" + "url": "https://github.com/storybookjs/test-runner" }, - "author": "winkerVSbecks", + "author": "shilman", "license": "MIT", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", "types": "dist/ts/index.d.ts", "files": [ + "bin", "dist/**/*", "README.md", + "playwright", + "jsdom", + "mocks", "*.js", "*.d.ts" ], @@ -31,13 +38,16 @@ "prebuild": "yarn clean", "build": "concurrently \"yarn buildBabel\" \"yarn buildTsc\"", "build:watch": "concurrently \"yarn buildBabel:esm -- --watch\" \"yarn buildTsc -- --watch\"", - "test": "echo \"Error: no test specified\" && exit 1", + "test": "jest", "storybook": "start-storybook -p 6006", "start": "concurrently \"yarn build:watch\" \"yarn storybook -- --no-manager-cache --quiet\"", "build-storybook": "build-storybook", - "prerelease": "zx scripts/prepublish-checks.mjs", "release": "yarn build && auto shipit", - "eject-ts": "zx scripts/eject-typescript.mjs" + "test-storybook:jsdom": "jest --no-cache --config ./jsdom-jest.config.js -i", + "test-storybook:playwright": "jest --no-cache --config ./test-runner-jest.config.js" + }, + "bin": { + "test-storybook": "./bin/test-storybook.js" }, "devDependencies": { "@babel/cli": "^7.12.1", @@ -45,48 +55,52 @@ "@babel/preset-env": "^7.12.1", "@babel/preset-react": "^7.12.5", "@babel/preset-typescript": "^7.13.0", - "@storybook/addon-essentials": "^6.2.9", - "@storybook/react": "^6.2.9", + "@babel/template": "^7.14.5", + "@babel/types": "^7.14.8", + "@jest/types": "^27.0.6", + "@storybook/addon-essentials": "^6.3.5", + "@storybook/react": "^6.3.5", + "@storybook/testing-react": "^0.0.21", + "@testing-library/dom": "^8.1.0", + "@testing-library/react": "^12.0.0", + "@testing-library/user-event": "^13.2.1", + "@types/jest": "^27.0.3", + "@types/node": "^16.4.1", "auto": "^10.3.0", + "babel-jest": "^27.0.6", "babel-loader": "^8.1.0", "boxen": "^5.0.1", "concurrently": "^6.2.0", "dedent": "^0.7.0", + "jest": "^27.0.6", + "jest-environment-jsdom": "^27.0.6", "prettier": "^2.3.1", "prop-types": "^15.7.2", "react": "^17.0.1", "react-dom": "^17.0.1", "rimraf": "^3.0.2", + "ts-jest": "^27.0.4", "typescript": "^4.2.4", "zx": "^1.14.1" }, - "peerDependencies": { - "@storybook/addons": "^6.2.9", - "@storybook/api": "^6.2.9", - "@storybook/components": "^6.2.9", - "@storybook/core-events": "^6.2.9", - "@storybook/theming": "^6.2.9", - "react": "^16.8.0 || ^17.0.0", - "react-dom": "^16.8.0 || ^17.0.0" - }, - "peerDependenciesMeta": { - "react": { - "optional": true - }, - "react-dom": { - "optional": true - } - }, "publishConfig": { "access": "public" }, "storybook": { - "displayName": "Addon Kit", - "supportedFrameworks": [ - "react", - "vue", - "angular" + "displayName": "Storybook test runner", + "unsupportedFrameworks": [ + "react-native" ], "icon": "https://user-images.githubusercontent.com/321738/63501763-88dbf600-c4cc-11e9-96cd-94adadc2fd72.png" + }, + "dependencies": { + "@storybook/csf": "0.0.2--canary.87bc651.0", + "@storybook/csf-tools": "^6.4.0", + "jest-playwright-preset": "^1.7.0", + "playwright": "^1.14.0", + "url-exists": "^1.0.3" + }, + "peerDependencies": { + "jest": ">=26.6.3" } } diff --git a/playwright/custom-environment.js b/playwright/custom-environment.js new file mode 100644 index 00000000..40b08bf3 --- /dev/null +++ b/playwright/custom-environment.js @@ -0,0 +1,139 @@ +require('regenerator-runtime/runtime'); +const PlaywrightEnvironment = require('jest-playwright-preset/lib/PlaywrightEnvironment').default; + +const sanitizeURL = (url) => { + let finalURL = url + // prepend URL protocol if not there + if (finalURL.indexOf("http://") === -1 && finalURL.indexOf("https://") === -1) { + finalURL = 'http://' + finalURL; + } + + // remove iframe.html if present + finalURL = finalURL.replace(/iframe.html\s*$/, ""); + + // add forward slash at the end if not there + if (finalURL.slice(-1) !== '/') { + finalURL = finalURL + '/'; + } + + return finalURL; +} + +class CustomEnvironment extends PlaywrightEnvironment { + async setup() { + await super.setup(); + const page = this.global.page; + const start = new Date(); + const targetURL = sanitizeURL(process.env.TARGET_URL || `http://localhost:6006`); + + const referenceURL = process.env.REFERENCE_URL && sanitizeURL(process.env.REFERENCE_URL); + + if ('TARGET_URL' in process.env && !process.env.TARGET_URL) { + console.log(`Received TARGET_URL but with a falsy value: ${process.env.TARGET_URL + }, will fallback to ${targetURL} instead.`) + } + + await page.goto(`${targetURL}iframe.html`, { waitUntil: 'load' }).catch((err) => { + if (err.message?.includes('ERR_CONNECTION_REFUSED')) { + const errorMessage = `Could not access the Storybook instance at ${targetURL}. Are you sure it's running?\n\n${err.message}`; + throw new Error(errorMessage) + } + + throw err; + }); // FIXME: configure + console.log(`page loaded in ${new Date() - start}ms.`); + + // if we ever want to log something from the browser to node + await page.exposeBinding('logToPage', (_, message) => console.log(message)); + + await page.addScriptTag({ + content: ` + class StorybookTestRunnerError extends Error { + constructor(storyId, hasPlayFn, errorMessage) { + super(errorMessage); + this.name = 'StorybookTestRunnerError'; + const storyUrl = \`${referenceURL || targetURL}?path=/story/\${storyId}\`; + const finalStoryUrl = storyUrl + (hasPlayFn ? '&addonPanel=storybook/interactions/panel' : ''); + + this.message = \`\nAn error occurred in the following story:\n\${finalStoryUrl}\n\nMessage:\n \${errorMessage}\`; + } + } + + async function __throwError(storyId, errorMessage) { + throw new StorybookTestRunnerError(storyId, errorMessage); + } + + async function __waitForElement(selector) { + return new Promise((resolve, reject) => { + + const timeout = setTimeout(() => { + reject(); + }, 10000); + + if (document.querySelector(selector)) { + clearTimeout(timeout); + return resolve(document.querySelector(selector)); + } + + const observer = new MutationObserver(mutations => { + if (document.querySelector(selector)) { + clearTimeout(timeout); + resolve(document.querySelector(selector)); + observer.disconnect(); + } + }); + + observer.observe(document.body, { + childList: true, + subtree: true + }); + }); + } + + async function __test(storyId, hasPlayFn) { + try { + await __waitForElement('#root'); + } catch(err) { + const message = \`Timed out waiting for Storybook to load after 10 seconds. Are you sure the Storybook is running correctly in that URL?\n\n\nHTML: \${document.body.innerHTML}\`; + throw new StorybookTestRunnerError(storyId, hasPlayFn, message); + } + + const channel = window.__STORYBOOK_ADDONS_CHANNEL__; + if(!channel) { + throw new StorybookTestRunnerError( + storyId, + hasPlayFn, + 'The test runner could not access the Storybook channel. Are you sure the Storybook is running correctly in that URL?' + ); + } + + return new Promise((resolve, reject) => { + channel.on('storyRendered', () => resolve(document.getElementById('root'))); + channel.on('storyUnchanged', () => resolve(document.getElementById('root'))); + channel.on('storyErrored', ({ description }) => reject( + new StorybookTestRunnerError(storyId, hasPlayFn, description)) + ); + channel.on('storyThrewException', (error) => reject( + new StorybookTestRunnerError(storyId, hasPlayFn, error.message)) + ); + channel.on('storyMissing', (id) => id === storyId && reject( + new StorybookTestRunnerError(storyId, hasPlayFn, 'The story was missing when trying to access it.')) + ); + + channel.emit('setCurrentStory', { storyId }); + }); + }; + `, + }); + } + + async teardown() { + await super.teardown(); + } + + async handleTestEvent(event) { + await super.handleTestEvent(event); + } +} + +module.exports = CustomEnvironment; diff --git a/playwright/global-setup.js b/playwright/global-setup.js new file mode 100644 index 00000000..4c7686f5 --- /dev/null +++ b/playwright/global-setup.js @@ -0,0 +1,6 @@ +// global-setup.js +const { globalSetup: playwrightGlobalSetup } = require('jest-playwright-preset'); + +module.exports = async function globalSetup(globalConfig) { + return playwrightGlobalSetup(globalConfig); +}; diff --git a/playwright/global-teardown.js b/playwright/global-teardown.js new file mode 100644 index 00000000..f0335486 --- /dev/null +++ b/playwright/global-teardown.js @@ -0,0 +1,7 @@ +// global-teardown.js +const { globalTeardown: playwrightGlobalTeardown } = require('jest-playwright-preset'); + +module.exports = async function globalTeardown(globalConfig) { + // Your global teardown + await playwrightGlobalTeardown(globalConfig); +}; diff --git a/playwright/transform.js b/playwright/transform.js new file mode 100644 index 00000000..f07b9988 --- /dev/null +++ b/playwright/transform.js @@ -0,0 +1,20 @@ +const { transform: babelTransform } = require('@babel/core'); +const { transformPlaywright } = require('../dist/cjs/playwright/transformPlaywright'); + +module.exports = { + process(src, filename, config) { + const csfTest = transformPlaywright(src); + + const result = babelTransform(csfTest, { + filename, + babelrc: false, + configFile: false, + presets: [ + ['@babel/preset-env', { targets: { node: 'current' } }], + '@babel/preset-typescript', + '@babel/preset-react', + ], + }); + return result ? result.code : src; + }, +}; diff --git a/scripts/eject-typescript.mjs b/scripts/eject-typescript.mjs deleted file mode 100644 index c9edb47e..00000000 --- a/scripts/eject-typescript.mjs +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env zx - -// Copy TS files and delete src -await $`cp -r ./src ./srcTS`; -await $`rm -rf ./src`; -await $`mkdir ./src`; - -// Convert TS code to JS -await $`babel --no-babelrc --presets @babel/preset-typescript ./srcTS -d ./src --extensions \".js,.jsx,.ts,.tsx\" --ignore "./srcTS/typings.d.ts"`; - -// Format the newly created .js files -await $`prettier --write ./src`; - -// Add in minimal files required for the TS build setup -await $`touch ./src/dummy.ts`; -await $`printf "export {};" >> ./src/dummy.ts`; - -await $`touch ./src/typings.d.ts`; -await $`printf 'declare module "global";' >> ./src/typings.d.ts`; - -// Clean up -await $`rm -rf ./srcTS`; - -console.log( - chalk.green.bold` -TypeScript Ejection complete!`, - chalk.green` -Addon code converted with JS. The TypeScript build setup is still available in case you want to adopt TypeScript in the future. -` -); diff --git a/scripts/prepublish-checks.mjs b/scripts/prepublish-checks.mjs deleted file mode 100644 index c53f3c06..00000000 --- a/scripts/prepublish-checks.mjs +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env zx - -const packageJson = require("../package.json"); -const boxen = require("boxen"); -const dedent = require("dedent"); - -const name = packageJson.name; -const displayName = packageJson.storybook.displayName; - -let exitCode = 0; -$.verbose = false; - -/** - * Check that meta data has been updated - */ -if (name.includes("addon-kit") || displayName.includes("Addon Kit")) { - console.error( - boxen( - dedent` - ${chalk.red.bold("Missing metadata")} - - ${chalk.red(dedent`Your package name and/or displayName includes default values from the Addon Kit. - The addon gallery filters out all such addons. - - Please configure appropriate metadata before publishing your addon. For more info, see: - https://storybook.js.org/docs/react/addons/addon-catalog#addon-metadata`)}`, - { padding: 1, borderColor: "red" } - ) - ); - - exitCode = 1; -} - -/** - * Check that README has been updated - */ -const readmeTestStrings = - "# Storybook Addon Kit|Click the \\*\\*Use this template\\*\\* button to get started.|https://user-images.githubusercontent.com/42671/106809879-35b32000-663a-11eb-9cdc-89f178b5273f.gif"; - -if ((await $`cat README.md | grep -E ${readmeTestStrings}`.exitCode) == 0) { - console.error( - boxen( - dedent` - ${chalk.red.bold("README not updated")} - - ${chalk.red(dedent`You are using the default README.md file that comes with the addon kit. - Please update it to provide info on what your addon does and how to use it.`)} - `, - { padding: 1, borderColor: "red" } - ) - ); - - exitCode = 1; -} - -process.exit(exitCode); diff --git a/src/Panel.tsx b/src/Panel.tsx deleted file mode 100644 index 3f7236fc..00000000 --- a/src/Panel.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import React from "react"; -import { useAddonState, useChannel } from "@storybook/api"; -import { AddonPanel } from "@storybook/components"; -import { ADDON_ID, EVENTS } from "./constants"; -import { PanelContent } from "./components/PanelContent"; - -interface PanelProps { - active: boolean; -} - -export const Panel: React.FC = (props) => { - // https://storybook.js.org/docs/react/addons/addons-api#useaddonstate - const [results, setState] = useAddonState(ADDON_ID, { - danger: [], - warning: [], - }); - - // https://storybook.js.org/docs/react/addons/addons-api#usechannel - const emit = useChannel({ - [EVENTS.RESULT]: (newResults) => setState(newResults), - }); - - return ( - - { - emit(EVENTS.REQUEST); - }} - clearData={() => { - emit(EVENTS.CLEAR); - }} - /> - - ); -}; diff --git a/src/Tab.tsx b/src/Tab.tsx deleted file mode 100644 index 1cfc887e..00000000 --- a/src/Tab.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import React from "react"; -import { useParameter } from "@storybook/api"; -import { PARAM_KEY } from "./constants"; -import { TabContent } from "./components/TabContent"; - -interface TabProps { - active: boolean; -} - -export const Tab: React.FC = ({ active }) => { - // https://storybook.js.org/docs/react/addons/addons-api#useparameter - const paramData = useParameter(PARAM_KEY, ""); - - return active ? : null; -}; diff --git a/src/Tool.tsx b/src/Tool.tsx deleted file mode 100644 index c5d39b60..00000000 --- a/src/Tool.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import React, { useCallback } from "react"; -import { useGlobals } from "@storybook/api"; -import { Icons, IconButton } from "@storybook/components"; -import { TOOL_ID } from "./constants"; - -export const Tool = () => { - const [{ myAddon }, updateGlobals] = useGlobals(); - - const toggleMyTool = useCallback( - () => - updateGlobals({ - myAddon: myAddon ? undefined : true, - }), - [myAddon] - ); - - return ( - - {/* - Checkout https://next--storybookjs.netlify.app/official-storybook/?path=/story/basics-icon--labels - for the full list of icons - */} - - - ); -}; diff --git a/src/components/List.tsx b/src/components/List.tsx deleted file mode 100644 index aa896219..00000000 --- a/src/components/List.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import React, { Fragment, useState } from "react"; -import { styled, themes, convert } from "@storybook/theming"; -import { Icons, IconsProps } from "@storybook/components"; - -const ListWrapper = styled.ul({ - listStyle: "none", - fontSize: 14, - padding: 0, - margin: 0, -}); - -const Wrapper = styled.div({ - display: "flex", - width: "100%", - borderBottom: `1px solid ${convert(themes.normal).appBorderColor}`, - "&:hover": { - background: convert(themes.normal).background.hoverable, - }, -}); - -const Icon = styled(Icons)({ - height: 10, - width: 10, - minWidth: 10, - color: convert(themes.normal).color.mediumdark, - marginRight: 10, - transition: "transform 0.1s ease-in-out", - alignSelf: "center", - display: "inline-flex", -}); - -const HeaderBar = styled.div({ - padding: convert(themes.normal).layoutMargin, - paddingLeft: convert(themes.normal).layoutMargin - 3, - background: "none", - color: "inherit", - textAlign: "left", - cursor: "pointer", - borderLeft: "3px solid transparent", - width: "100%", - - "&:focus": { - outline: "0 none", - borderLeft: `3px solid ${convert(themes.normal).color.secondary}`, - }, -}); - -const Description = styled.div({ - padding: convert(themes.normal).layoutMargin, - marginBottom: convert(themes.normal).layoutMargin, - fontStyle: "italic", -}); - -type Item = { - title: string; - description: string; -}; - -interface ListItemProps { - item: Item; -} - -export const ListItem: React.FC = ({ item }) => { - const [open, onToggle] = useState(false); - - return ( - - - onToggle(!open)} role="button"> - - {item.title} - - - {open ? {item.description} : null} - - ); -}; - -interface ListProps { - items: Item[]; -} - -export const List: React.FC = ({ items }) => ( - - {items.map((item, idx) => ( - - ))} - -); diff --git a/src/components/PanelContent.tsx b/src/components/PanelContent.tsx deleted file mode 100644 index 9fcfb5ff..00000000 --- a/src/components/PanelContent.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import React, { Fragment } from "react"; -import { styled, themes, convert } from "@storybook/theming"; -import { TabsState, Placeholder, Button } from "@storybook/components"; -import { List } from "./List"; - -export const RequestDataButton = styled(Button)({ - marginTop: "1rem", -}); - -type Results = { - danger: any[]; - warning: any[]; -}; - -interface PanelContentProps { - results: Results; - fetchData: () => void; - clearData: () => void; -} - -/** - * Checkout https://github.com/storybookjs/storybook/blob/next/addons/jest/src/components/Panel.tsx - * for a real world example - */ -export const PanelContent: React.FC = ({ - results, - fetchData, - clearData, -}) => ( - -
- - - Addons can gather details about how a story is rendered. This is panel - uses a tab pattern. Click the button below to fetch data for the other - two tabs. - - - - Request data - - - - Clear data - - - -
-
- -
-
- -
-
-); diff --git a/src/components/TabContent.tsx b/src/components/TabContent.tsx deleted file mode 100644 index 78ee9612..00000000 --- a/src/components/TabContent.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import React from "react"; -import { styled } from "@storybook/theming"; -import { Title, Source, Link } from "@storybook/components"; - -const TabWrapper = styled.div(({ theme }) => ({ - background: theme.background.content, - padding: "4rem 20px", - minHeight: "100vh", - boxSizing: "border-box", -})); - -const TabInner = styled.div({ - maxWidth: 768, - marginLeft: "auto", - marginRight: "auto", -}); - -interface TabContentProps { - code: string; -} - -export const TabContent: React.FC = ({ code }) => ( - - - My Addon -

- Your addon can create a custom tab in Storybook. For example, the - official{" "} - - @storybook/addon-docs - {" "} - uses this pattern. -

-

- You have full control over what content is being rendered here. You can - use components from{" "} - - @storybook/components - {" "} - to match the look and feel of Storybook, for example the{" "} - <Source /> component below. Or build a completely - custom UI. -

- -
-
-); diff --git a/src/constants.ts b/src/constants.ts deleted file mode 100644 index d7ef8e45..00000000 --- a/src/constants.ts +++ /dev/null @@ -1,11 +0,0 @@ -export const ADDON_ID = "storybook/my-addon"; -export const TOOL_ID = `${ADDON_ID}/tool`; -export const PANEL_ID = `${ADDON_ID}/panel`; -export const TAB_ID = `${ADDON_ID}/tab`; -export const PARAM_KEY = `myAddonParameter`; - -export const EVENTS = { - RESULT: `${ADDON_ID}/result`, - REQUEST: `${ADDON_ID}/request`, - CLEAR: `${ADDON_ID}/clear`, -}; diff --git a/src/csf/transformCsf.ts b/src/csf/transformCsf.ts new file mode 100644 index 00000000..8fef29b7 --- /dev/null +++ b/src/csf/transformCsf.ts @@ -0,0 +1,127 @@ +/* eslint-disable no-underscore-dangle */ +import { loadCsf } from '@storybook/csf-tools'; +import * as t from '@babel/types'; +import generate from '@babel/generator'; +import { toId, storyNameFromExport } from '@storybook/csf'; +import dedent from 'ts-dedent'; + +const logger = console; + +export interface TestContext { + storyExport?: t.Identifier; + name: t.Literal; + title: t.Literal; + id: t.Literal; + hasPlayFn?: t.BooleanLiteral; +} +type FilePrefixer = () => t.Statement[]; +type TestPrefixer = (context: TestContext) => t.Statement[]; +const JEST_GLOBAL_REGEX = /(before|after)(All|Each)$/; + +interface TransformOptions { + clearBody?: boolean; + filePrefixer?: FilePrefixer; + testPrefixer?: TestPrefixer; + insertTestIfEmpty?: boolean; +} + +const prefixFunction = ( + key: string, + title: string, + input: t.Expression, + testPrefixer?: TestPrefixer +) => { + const clone = t.cloneDeepWithoutLoc(input); + const name = storyNameFromExport(key); + const context: TestContext = { + storyExport: t.identifier(key), + name: t.stringLiteral(name), // FIXME .name annotation + title: t.stringLiteral(title), // FIXME: auto-title + id: t.stringLiteral(toId(title, name)), + hasPlayFn: t.booleanLiteral(!!input), + }; + + // instead, let's just make the prefixer return the function + const result = testPrefixer(context); + const stmt = result[1] as t.ExpressionStatement; + return stmt.expression; +}; + +const makePlayTest = ( + key: string, + title: string, + metaOrStoryPlay: t.Node, + testPrefix?: TestPrefixer +): t.Statement[] => { + return [ + t.expressionStatement( + t.callExpression(t.identifier('it'), [ + t.stringLiteral(!!metaOrStoryPlay ? 'play-test' : 'smoke-test'), + prefixFunction(key, title, metaOrStoryPlay as t.Expression, testPrefix), + ]) + ), + ]; +}; + +const makeDescribe = (key: string, tests: t.Statement[]): t.Statement | null => { + return t.expressionStatement( + t.callExpression(t.identifier('describe'), [ + t.stringLiteral(key), + t.arrowFunctionExpression([], t.blockStatement(tests)), + ]) + ); +}; + +export const transformCsf = ( + code: string, + { filePrefixer, clearBody = false, testPrefixer, insertTestIfEmpty }: TransformOptions = {} +) => { + const csf = loadCsf(code, { defaultTitle: 'FIXME' }); + csf.parse(); + + const storyExports = Object.keys(csf._stories); + const title = csf.meta.title; + + const storyPlays = storyExports.reduce((acc, key) => { + const annotations = csf._storyAnnotations[key]; + if (annotations?.play) { + acc[key] = annotations.play; + } + return acc; + }, {} as Record); + const playTests = storyExports + .map((key: string) => { + let tests: t.Statement[] = []; + tests = [...tests, ...makePlayTest(key, title, storyPlays[key], testPrefixer)]; + + if (tests.length) { + return makeDescribe(key, tests); + } + return null; + }) + .filter(Boolean); + + const allTests = playTests; + + let result = ''; + + // FIXME: insert between imports + if (filePrefixer) { + const { code: prefixCode } = generate(t.program(filePrefixer()), {}); + result = `${prefixCode}\n`; + } + if (!clearBody) result = `${result}${code}\n`; + if (allTests.length) { + const describe = makeDescribe(csf.meta.title, allTests); + const { code: describeCode } = generate(describe, {}); + result = dedent` + ${result} + if (!require.main) { + ${describeCode} + } + `; + } else if (insertTestIfEmpty) { + result = `describe('${csf.meta.title}', () => { it('no-op', () => {}) });`; + } + return result; +}; diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index 644402ab..00000000 --- a/src/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -if (module && module.hot && module.hot.decline) { - module.hot.decline(); -} - -// make it work with --isolatedModules -export default {}; diff --git a/src/jsdom/index.ts b/src/jsdom/index.ts new file mode 100644 index 00000000..66d198f4 --- /dev/null +++ b/src/jsdom/index.ts @@ -0,0 +1,14 @@ +import { transform as babelTransform } from '@babel/core'; +import { transformJsdom } from './transformJsdom'; + +export const process = (src: string, filename: string, config: any) => { + const csfTest = transformJsdom(src); + + const result = babelTransform(csfTest, { + filename, + babelrc: false, + configFile: false, + presets: ['@babel/preset-env', '@babel/preset-typescript', '@babel/preset-react'], + }); + return result ? result.code : src; +}; diff --git a/src/jsdom/transformJsdom.test.ts b/src/jsdom/transformJsdom.test.ts new file mode 100644 index 00000000..49dac20f --- /dev/null +++ b/src/jsdom/transformJsdom.test.ts @@ -0,0 +1,43 @@ +import dedent from 'ts-dedent'; +import { transformJsdom } from './transformJsdom'; + +// @ts-ignore +expect.addSnapshotSerializer({ + print: (val: any) => val, + test: (val: any) => true, +}); + +describe('transformJsdom', () => { + it('basic', () => { + expect( + transformJsdom(dedent` + export default { title: 'foo/bar' }; + export const A = () => {}; + `) + ).toMatchInlineSnapshot(` + import { render, screen } from "@testing-library/react"; + import { composeStory } from "@storybook/testing-react"; + export default { title: 'foo/bar' }; + export const A = () => {}; + + if (!require.main) { + describe("foo/bar", () => { + describe("A", () => { + it("smoke-test", async () => { + const Composed = await composeStory(A, exports.default); + const { + container + } = render(); + + if (Composed.play) { + await Composed.play({ + canvasElement: container + }); + } + }); + }); + }); + } + `); + }); +}); diff --git a/src/jsdom/transformJsdom.ts b/src/jsdom/transformJsdom.ts new file mode 100644 index 00000000..b6ae05cc --- /dev/null +++ b/src/jsdom/transformJsdom.ts @@ -0,0 +1,29 @@ +import template from '@babel/template'; +import { transformCsf } from '../csf/transformCsf'; + +const filePrefixer = template(` + import { render, screen } from "@testing-library/react"; + import { composeStory } from "@storybook/testing-react"; +`); + +const testPrefixer = template( + ` + console.log({ id: %%id%%, title: %%title%%, name: %%name%%, storyExport: %%storyExport%%, hasPlayFn: %%hasPlayFn%%}); + async () => { + const Composed = await composeStory(%%storyExport%%, exports.default); + const { container } = render(); + if(Composed.play) { + await Composed.play({ canvasElement: container }); + } + } + `, + { + plugins: ['jsx'], + } +); + +export const transformJsdom = (src: string) => { + // @ts-ignore + const result = transformCsf(src, { filePrefixer, testPrefixer, insertTestIfEmpty: true }); + return result; +}; diff --git a/src/playwright/index.ts b/src/playwright/index.ts new file mode 100644 index 00000000..a930c11e --- /dev/null +++ b/src/playwright/index.ts @@ -0,0 +1,14 @@ +import { transform as babelTransform } from '@babel/core'; +import { transformPlaywright } from './transformPlaywright'; + +export const process = (src: string, filename: string, config: any) => { + const csfTest = transformPlaywright(src); + + const result = babelTransform(csfTest, { + filename, + babelrc: false, + configFile: false, + presets: ['@babel/preset-env', '@babel/preset-typescript', '@babel/preset-react'], + }); + return result ? result.code : src; +}; diff --git a/src/playwright/transformPlaywright.test.ts b/src/playwright/transformPlaywright.test.ts new file mode 100644 index 00000000..ebd7be46 --- /dev/null +++ b/src/playwright/transformPlaywright.test.ts @@ -0,0 +1,77 @@ +import dedent from 'ts-dedent'; +import { transformPlaywright } from './transformPlaywright'; + +expect.addSnapshotSerializer({ + print: (val: any) => val.trim(), + test: (val: any) => true, +}); + +describe('Playwright', () => { + it('should generate a play test when the story has a play function', () => { + expect( + transformPlaywright(dedent` + export default { title: 'foo/bar' }; + export const A = () => {}; + A.play = () => {}; + `) + ).toMatchInlineSnapshot(` + if (!require.main) { + describe("foo/bar", () => { + describe("A", () => { + it("play-test", async () => { + page.on('pageerror', err => { + page.evaluate(({ + id, + err + }) => __throwError(id, err), { + id: "foo-bar--a", + err: err.message + }); + }); + return page.evaluate(({ + id, + hasPlayFn + }) => __test(id, hasPlayFn), { + id: "foo-bar--a", + hasPlayFn: true + }); + }); + }); + }); + } + `); + }); + it('should generate a smoke test when story does not have a play function', () => { + expect( + transformPlaywright(dedent` + export default { title: 'foo/bar' }; + export const A = () => {}; + `) + ).toMatchInlineSnapshot(` + if (!require.main) { + describe("foo/bar", () => { + describe("A", () => { + it("smoke-test", async () => { + page.on('pageerror', err => { + page.evaluate(({ + id, + err + }) => __throwError(id, err), { + id: "foo-bar--a", + err: err.message + }); + }); + return page.evaluate(({ + id, + hasPlayFn + }) => __test(id, hasPlayFn), { + id: "foo-bar--a", + hasPlayFn: false + }); + }); + }); + }); + } + `); + }); +}); diff --git a/src/playwright/transformPlaywright.ts b/src/playwright/transformPlaywright.ts new file mode 100644 index 00000000..b87b8083 --- /dev/null +++ b/src/playwright/transformPlaywright.ts @@ -0,0 +1,30 @@ +import template from '@babel/template'; +import { transformCsf } from '../csf/transformCsf'; + +const testPrefixer = template( + ` + console.log({ id: %%id%%, title: %%title%%, name: %%name%%, storyExport: %%storyExport%% }); + async () => { + page.on('pageerror', (err) => { + page.evaluate(({ id, err }) => __throwError(id, err), { id: %%id%%, err: err.message }); + }); + + return page.evaluate(({ id, hasPlayFn }) => __test(id, hasPlayFn), { + id: %%id%%, + hasPlayFn: %%hasPlayFn%%, + }); + } + `, + { + plugins: ['jsx'], + } +); +export const transformPlaywright = (src: string) => { + const result = transformCsf(src, { + // @ts-ignore + testPrefixer, + insertTestIfEmpty: true, + clearBody: true, + }); + return result; +}; diff --git a/src/preset/manager.ts b/src/preset/manager.ts deleted file mode 100644 index 5c1845f8..00000000 --- a/src/preset/manager.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { addons, types } from "@storybook/addons"; - -import { ADDON_ID, TOOL_ID, PANEL_ID } from "../constants"; -import { Tool } from "../Tool"; -import { Panel } from "../Panel"; -import { Tab } from "../Tab"; - -// Register the addon -addons.register(ADDON_ID, () => { - // Register the tool - addons.add(TOOL_ID, { - type: types.TOOL, - title: "My addon", - match: ({ viewMode }) => !!(viewMode && viewMode.match(/^(story|docs)$/)), - render: Tool, - }); - - // Register the panel - addons.add(PANEL_ID, { - type: types.PANEL, - title: "My addon", - match: ({ viewMode }) => viewMode === "story", - render: Panel, - }); - - // Register the tab - addons.add(PANEL_ID, { - type: types.TAB, - title: "My addon", - //👇 Checks the current route for the story - route: ({ storyId }) => `/myaddon/${storyId}`, - //👇 Shows the Tab UI element in myaddon view mode - match: ({ viewMode }) => viewMode === "myaddon", - render: Tab, - }); -}); diff --git a/src/preset/preview.ts b/src/preset/preview.ts deleted file mode 100644 index b2ba7343..00000000 --- a/src/preset/preview.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A decorator is a way to wrap a story in extra “rendering” functionality. Many addons define decorators - * in order to augment stories: - * - with extra rendering - * - gather details about how a story is rendered - * - * When writing stories, decorators are typically used to wrap stories with extra markup or context mocking. - * - * https://storybook.js.org/docs/react/writing-stories/decorators#gatsby-focus-wrapper - */ -import { withGlobals } from "../withGlobals"; -import { withRoundTrip } from "../withRoundTrip"; - -export const decorators = [withGlobals, withRoundTrip]; diff --git a/src/typings.d.ts b/src/typings.d.ts deleted file mode 100644 index 3563aeb2..00000000 --- a/src/typings.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module "global"; diff --git a/src/withGlobals.ts b/src/withGlobals.ts deleted file mode 100644 index df134f15..00000000 --- a/src/withGlobals.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { StoryFn as StoryFunction, StoryContext } from "@storybook/addons"; -import { useEffect, useGlobals } from "@storybook/addons"; - -export const withGlobals = (StoryFn: StoryFunction, context: StoryContext) => { - const [{ myAddon }] = useGlobals(); - // Is the addon being used in the docs panel - const isInDocs = context.viewMode === "docs"; - - useEffect(() => { - // Execute your side effect here - // For example, to manipulate the contents of the preview - const selectorId = isInDocs - ? `#anchor--${context.id} .docs-story` - : `#root`; - - displayToolState(selectorId, { - myAddon, - isInDocs, - }); - }, [myAddon]); - - return StoryFn(); -}; - -function displayToolState(selector: string, state: any) { - const rootElement = document.querySelector(selector); - let preElement = rootElement.querySelector("pre"); - - if (!preElement) { - preElement = document.createElement("pre"); - preElement.style.setProperty("margin-top", "2rem"); - preElement.style.setProperty("padding", "1rem"); - preElement.style.setProperty("background-color", "#eee"); - preElement.style.setProperty("border-radius", "3px"); - preElement.style.setProperty("max-width", "600px"); - rootElement.appendChild(preElement); - } - - preElement.innerText = `This snippet is injected by the withGlobals decorator. -It updates as the user interacts with the ⚡ tool in the toolbar above. - -${JSON.stringify(state, null, 2)} -`; -} diff --git a/src/withRoundTrip.ts b/src/withRoundTrip.ts deleted file mode 100644 index b90b36f7..00000000 --- a/src/withRoundTrip.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { StoryFn as StoryFunction, useChannel } from "@storybook/addons"; -import { STORY_CHANGED } from "@storybook/core-events"; -import { EVENTS } from "./constants"; - -export const withRoundTrip = (storyFn: StoryFunction) => { - const emit = useChannel({ - [EVENTS.REQUEST]: () => { - emit(EVENTS.RESULT, { - danger: [ - { - title: "Panels are the most common type of addon in the ecosystem", - description: - "For example the official @storybook/actions and @storybook/a11y use this pattern", - }, - { - title: - "You can specify a custom title for your addon panel and have full control over what content it renders", - description: - "@storybook/components offers components to help you addons with the look and feel of Storybook itself", - }, - ], - warning: [ - { - title: - 'This tabbed UI pattern is a popular option to display "test" reports.', - description: - "It's used by @storybook/addon-jest and @storybook/addon-a11y. @storybook/components offers this and other components to help you quickly build an addon", - }, - ], - }); - }, - [STORY_CHANGED]: () => { - emit(EVENTS.RESULT, { - danger: [], - warning: [], - }); - }, - [EVENTS.CLEAR]: () => { - emit(EVENTS.RESULT, { - danger: [], - warning: [], - }); - }, - }); - return storyFn(); -}; diff --git a/stories/Button.stories.js b/stories/Button.stories.js deleted file mode 100644 index 60bc6cdf..00000000 --- a/stories/Button.stories.js +++ /dev/null @@ -1,39 +0,0 @@ -import React from "react"; -import { Button } from "./Button"; - -export default { - title: "Example/Button", - component: Button, - parameters: { - myAddonParameter: ` - - a.id} /> - -`, - }, -}; - -const Template = (args) =>