From e368d154e9a15fb290d432e169af6df1e6b2f984 Mon Sep 17 00:00:00 2001 From: Maxim <39025497+mnik01@users.noreply.github.com> Date: Sat, 24 Feb 2024 08:56:13 +0000 Subject: [PATCH] wip --- README.md | 271 +--------------------- package.json | 30 ++- src/OutlineCSS.ts | 400 +++++++++++++++++++++++++++++++++ src/Panel.tsx | 36 --- src/Tab.tsx | 15 -- src/Tool.tsx | 75 ++++--- src/components/List.tsx | 181 ++++++++------- src/components/TooltipList.tsx | 35 +++ src/constants.ts | 6 +- src/helpers.ts | 28 +++ src/manager.ts | 47 +--- src/options.ts | 17 ++ src/preview.ts | 17 +- src/processCSS.ts | 74 ++++++ src/stories/Button.tsx | 3 +- src/stories/button.css | 16 ++ src/types.ts | 5 + src/withGlobals.ts | 79 ++----- 18 files changed, 809 insertions(+), 526 deletions(-) create mode 100644 src/OutlineCSS.ts delete mode 100644 src/Panel.tsx delete mode 100644 src/Tab.tsx create mode 100644 src/components/TooltipList.tsx create mode 100644 src/helpers.ts create mode 100644 src/options.ts create mode 100644 src/processCSS.ts create mode 100644 src/types.ts diff --git a/README.md b/README.md index a2c309b..42b7625 100644 --- a/README.md +++ b/README.md @@ -1,269 +1,16 @@ - - -# Storybook Addon Kit ([demo](https://main--601ada52c3d4040021afdc30.chromatic.com)) - -Simplify the creation of Storybook addons - -- ๐Ÿ“ Live-editing in development -- โš›๏ธ React/JSX support -- ๐Ÿ“ฆ Transpiling and bundling with [tsup](https://tsup.egoist.dev/) -- ๐Ÿท 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 - -### Migrating from Storybook 6.x to 7 - -Note, if you're looking to upgrade your addon from Storybook 6.x to 7, please refer to the [migration guide](https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#70-addon-authors-changes). The major changes are: - -- `register.js` was removed -- No more default export from `@storybook/addons` -- `@storybook/api` has been split into `@storybook/preview-api` and `@storybook/manager-api` - -Skip this section if you're bootstrapping a new addon. - -## Getting Started - -Click the **Use this template** button to get started. - -![](https://user-images.githubusercontent.com/321738/125058439-8d9ef880-e0aa-11eb-9211-e6d7be812959.gif) - -Clone your repository and install dependencies. - -```sh -npm install -``` - - - -### Development scripts - -- `npm run start` runs babel in watch mode and starts Storybook -- `npm run build` build and package your addon code - -### Switch from TypeScript to JavaScript - -Don't want to use TypeScript? We offer a handy eject command: `npm run 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. - -## 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.tsx` -- `src/Panel.tsx` -- `src/Tab.tsx` - -Which, along with the addon itself, are registered in `src/manager.ts`. - -Managing State and interacting with a story: - -- `src/withGlobals.ts` & `src/Tool.tsx` demonstrates how to use `useGlobals` to manage global state and modify the contents of a Story. -- `src/withRoundTrip.ts` & `src/Panel.tsx` demonstrates two-way communication using channels. -- `src/Tab.tsx` demonstrates how to use `useParameter` to access the current story's parameters. - -Your addon might use one or more of these patterns. Feel free to delete unused code. Update `src/manager.ts` and `src/preview.ts` accordingly. - -Lastly, configure you addon name in `src/constants.ts`. - -### Bundling - -Addons can interact with a Storybook project in multiple ways. It is recommended to familiarize yourself with [the basics](https://storybook.js.org/docs/react/addons/introduction) before getting started. - -- Manager entries are used to add UI or behavior to the Storybook manager UI. -- Preview entries are used to add UI or behavior to the preview iframe where stories are rendered. -- Presets are used to modify the Storybook configuration, similar to how [users can configure their `main.ts` configurations](https://storybook.js.org/docs/react/api/main-config). - -Since each of these places represents a different environment with different features and modules, it is also recommended to split and build your modules accordingly. This addon-kit comes with a preconfigured [bundling configuration](./tsup.config.ts) that supports this split, and you are free to modify and extend it as needed. - -You can define which modules match which environments in the [`package.json#bundler`](./package.json) property: - -- `exportEntries` is a list of module entries that users can manually import from anywhere they need to. For example, you could have decorators that users need to import into their `preview.ts` file or utility functions that can be used in their `main.ts` files. -- `managerEntries` is a list of module entries meant only for the manager UI. These modules will be bundled to ESM and won't include types since they are mostly loaded by Storybook directly. -- `previewEntries` is a list of module entries meant only for the preview UI. These modules will be bundled to ESM and won't include types since they are mostly loaded by Storybook directly. - -Manager and preview entries are only used in the browser so they only output ESM modules. Export entries could be used both in the browser and in Node depending on their use case, so they both output ESM and CJS modules. - -#### Globalized packages - -Storybook provides a predefined set of packages that are available in the manager UI and the preview UI. In the final bundle of your addon, these packages should not be included. Instead, the imports should stay in place, allowing Storybook to replace those imports with the actual packages during the Storybook build process. - -The list of packages differs between the manager and the preview, which is why there is a slight difference between `managerEntries` and `previewEntries`. Most notably, `react` and `react-dom` are prebundled in the manager but not in the preview. This means that your manager entries can use React to build UI without bundling it or having a direct reference to it. Therefore, it is safe to have React as a `devDependency` even though you are using it in production. _Requiring React as a peer dependency would unnecessarily force your users to install React._ - -An exception to this rule is if you are using React to inject UI into the preview, which does not come prebundled with React. In such cases, you need to move `react` and `react-dom` to a peer dependency. However, we generally advise against this pattern since it would limit the usage of your addon to React-based Storybooks. - -### Metadata - -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). - -## Documentation - -To help the community use your addon and understand its capabilities, please document it thoroughly. - -To get started, replace this README with the content in this sample template, modeled after how essential addons (like [Actions](https://storybook.js.org/docs/essentials/actions)) are documented. Then update the content to describe your addon. - -### Sample documentation template - -````md -# My Addon +# Storybook Addon Render Modes ## Installation -First, install the package. - -```sh -npm install --save-dev my-addon -``` - -Then, register it as an addon in `.storybook/main.js`. - -```js -// .storybook/main.ts - -// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) -import type { StorybookConfig } from '@storybook/your-framework'; - -const config: StorybookConfig = { - // ...rest of config - addons: [ - '@storybook/addon-essentials' - 'my-addon', // ๐Ÿ‘ˆ register the addon here - ], -}; - -export default config; -``` - -## Usage - -The primary way to use this addon is to define the `exampleParameter` parameter. You can do this the -component level, as below, to affect all stories in the file, or you can do it for a single story. - -```js -// Button.stories.ts - -// Replace your-framework with the name of your framework -import type { Meta } from '@storybook/your-framework'; - -import { Button } from './Button'; - -const meta: Meta = { - component: Button, - parameters: { - myAddon: { - exampleParameter: true, - // See API section below for available parameters - } - } -}; - -export default meta; -``` - -Another way to use the addon is... - -## API - -### Parameters - -This addon contributes the following parameters to Storybook, under the `myAddon` namespace: - -#### `disable` - -Type: `boolean` - -Disable this addon's behavior. This parameter is most useful to allow overriding at more specific -levels. For example, if this parameter is set to true at the project level, it could then be -re-enabled by setting it to false at the meta (component) or story level. - -### Options - -When registering this addon, you can configure it with the following options, which are passed when -registering the addon, like so: - -```ts -// .storybook/main.ts - -// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) -import type { StorybookConfig } from '@storybook/your-framework'; - -const config: StorybookConfig = { - // ...rest of config - addons: [ - '@storybook/essentials', - { - name: 'my-addon', - options: { - // ๐Ÿ‘ˆ options for my-addon go here - }, - }, - ], -}; - -export default config; -``` - -#### `useExperimentalBehavior` - -Type: `boolean` - -Enable experimental behavior to... - -```` - -## Release Management - -### Setup - -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: - -- [`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. - -Then open your `package.json` and edit the following fields: - -- `name` -- `author` -- `repository` - -#### Local - -To use `auto` locally create a `.env` file at the root of your project and add your tokens to it: - -```bash -GH_TOKEN= -NPM_TOKEN= -``` - -Lastly, **create labels on GitHub**. Youโ€™ll use these labels in the future when making changes to the package. - -```bash -npx auto create-labels -``` - -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. - -#### GitHub Actions - -This template comes with GitHub actions already set up to publish your addon anytime someone pushes to your repository. - -Go to `Settings > Secrets`, click `New repository secret`, and add your `NPM_TOKEN`. - -### Creating a release +1. Package installation +`pnpm add -D TODO` -To create a release locally you can run the following command, otherwise the GitHub action will make the release for you. +2. Addon registration +TODO -```sh -npm run release -``` +## Features -That will: +Rendering modes support: -- Build and package the addon code -- Bump the version -- Push a release to GitHub and npm -- Push a changelog to GitHub +- [ ] prefers-reduced-motion +- [ ] print diff --git a/package.json b/package.json index 0add362..87c3471 100644 --- a/package.json +++ b/package.json @@ -1,17 +1,20 @@ { - "name": "storybook-addon-kit", - "version": "0.0.0", - "description": "everything you need to build a Storybook addon", + "name": "storybook-addon-render-modes", + "version": "0.0.1", + "description": "Storybook addon that adds ability to change render mode of a story", "keywords": [ - "storybook-addons" + "storybook-addons", + "storybook-addon-render-modes", + "render-modes", + "prefers-reduced-motion" ], "repository": { "type": "git", - "url": "https://github.com/storybookjs/storybook-addon-kit" + "url": "https://github.com/mnik01/rendering-modes" }, "type": "module", "license": "MIT", - "author": "package-author", + "author": "Maxim Nikonov", "exports": { ".": { "types": "./dist/index.d.ts", @@ -47,6 +50,17 @@ "storybook": "storybook dev -p 6006", "build-storybook": "storybook build" }, + "peerDependencies": { + "@storybook/blocks": "^7.0.0", + "@storybook/components": "^7.0.0", + "@storybook/core-events": "^7.0.0", + "@storybook/manager-api": "^7.0.0", + "@storybook/preview-api": "^7.0.0", + "@storybook/theming": "^7.0.0", + "@storybook/types": "^7.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, "devDependencies": { "@storybook/addon-essentials": "8.0.0-beta.2", "@storybook/addon-interactions": "8.0.0-beta.2", @@ -100,9 +114,9 @@ ] }, "storybook": { - "displayName": "Addon Kit", + "displayName": "Render Modes", "supportedFrameworks": [ - "supported-frameworks" + "react" ], "icon": "https://user-images.githubusercontent.com/321738/63501763-88dbf600-c4cc-11e9-96cd-94adadc2fd72.png" } diff --git a/src/OutlineCSS.ts b/src/OutlineCSS.ts new file mode 100644 index 0000000..bf9f958 --- /dev/null +++ b/src/OutlineCSS.ts @@ -0,0 +1,400 @@ +import { dedent } from 'ts-dedent'; + +export default function outlineCSS(selector: string) { + return dedent/* css */ ` + ${selector} body { + outline: 1px solid #2980b9 !important; + } + + ${selector} article { + outline: 1px solid #3498db !important; + } + + ${selector} nav { + outline: 1px solid #0088c3 !important; + } + + ${selector} aside { + outline: 1px solid #33a0ce !important; + } + + ${selector} section { + outline: 1px solid #66b8da !important; + } + + ${selector} header { + outline: 1px solid #99cfe7 !important; + } + + ${selector} footer { + outline: 1px solid #cce7f3 !important; + } + + ${selector} h1 { + outline: 1px solid #162544 !important; + } + + ${selector} h2 { + outline: 1px solid #314e6e !important; + } + + ${selector} h3 { + outline: 1px solid #3e5e85 !important; + } + + ${selector} h4 { + outline: 1px solid #449baf !important; + } + + ${selector} h5 { + outline: 1px solid #c7d1cb !important; + } + + ${selector} h6 { + outline: 1px solid #4371d0 !important; + } + + ${selector} main { + outline: 1px solid #2f4f90 !important; + } + + ${selector} address { + outline: 1px solid #1a2c51 !important; + } + + ${selector} div { + outline: 1px solid #036cdb !important; + } + + ${selector} p { + outline: 1px solid #ac050b !important; + } + + ${selector} hr { + outline: 1px solid #ff063f !important; + } + + ${selector} pre { + outline: 1px solid #850440 !important; + } + + ${selector} blockquote { + outline: 1px solid #f1b8e7 !important; + } + + ${selector} ol { + outline: 1px solid #ff050c !important; + } + + ${selector} ul { + outline: 1px solid #d90416 !important; + } + + ${selector} li { + outline: 1px solid #d90416 !important; + } + + ${selector} dl { + outline: 1px solid #fd3427 !important; + } + + ${selector} dt { + outline: 1px solid #ff0043 !important; + } + + ${selector} dd { + outline: 1px solid #e80174 !important; + } + + ${selector} figure { + outline: 1px solid #ff00bb !important; + } + + ${selector} figcaption { + outline: 1px solid #bf0032 !important; + } + + ${selector} table { + outline: 1px solid #00cc99 !important; + } + + ${selector} caption { + outline: 1px solid #37ffc4 !important; + } + + ${selector} thead { + outline: 1px solid #98daca !important; + } + + ${selector} tbody { + outline: 1px solid #64a7a0 !important; + } + + ${selector} tfoot { + outline: 1px solid #22746b !important; + } + + ${selector} tr { + outline: 1px solid #86c0b2 !important; + } + + ${selector} th { + outline: 1px solid #a1e7d6 !important; + } + + ${selector} td { + outline: 1px solid #3f5a54 !important; + } + + ${selector} col { + outline: 1px solid #6c9a8f !important; + } + + ${selector} colgroup { + outline: 1px solid #6c9a9d !important; + } + + ${selector} button { + outline: 1px solid #da8301 !important; + } + + ${selector} datalist { + outline: 1px solid #c06000 !important; + } + + ${selector} fieldset { + outline: 1px solid #d95100 !important; + } + + ${selector} form { + outline: 1px solid #d23600 !important; + } + + ${selector} input { + outline: 1px solid #fca600 !important; + } + + ${selector} keygen { + outline: 1px solid #b31e00 !important; + } + + ${selector} label { + outline: 1px solid #ee8900 !important; + } + + ${selector} legend { + outline: 1px solid #de6d00 !important; + } + + ${selector} meter { + outline: 1px solid #e8630c !important; + } + + ${selector} optgroup { + outline: 1px solid #b33600 !important; + } + + ${selector} option { + outline: 1px solid #ff8a00 !important; + } + + ${selector} output { + outline: 1px solid #ff9619 !important; + } + + ${selector} progress { + outline: 1px solid #e57c00 !important; + } + + ${selector} select { + outline: 1px solid #e26e0f !important; + } + + ${selector} textarea { + outline: 1px solid #cc5400 !important; + } + + ${selector} details { + outline: 1px solid #33848f !important; + } + + ${selector} summary { + outline: 1px solid #60a1a6 !important; + } + + ${selector} command { + outline: 1px solid #438da1 !important; + } + + ${selector} menu { + outline: 1px solid #449da6 !important; + } + + ${selector} del { + outline: 1px solid #bf0000 !important; + } + + ${selector} ins { + outline: 1px solid #400000 !important; + } + + ${selector} img { + outline: 1px solid #22746b !important; + } + + ${selector} iframe { + outline: 1px solid #64a7a0 !important; + } + + ${selector} embed { + outline: 1px solid #98daca !important; + } + + ${selector} object { + outline: 1px solid #00cc99 !important; + } + + ${selector} param { + outline: 1px solid #37ffc4 !important; + } + + ${selector} video { + outline: 1px solid #6ee866 !important; + } + + ${selector} audio { + outline: 1px solid #027353 !important; + } + + ${selector} source { + outline: 1px solid #012426 !important; + } + + ${selector} canvas { + outline: 1px solid #a2f570 !important; + } + + ${selector} track { + outline: 1px solid #59a600 !important; + } + + ${selector} map { + outline: 1px solid #7be500 !important; + } + + ${selector} area { + outline: 1px solid #305900 !important; + } + + ${selector} a { + outline: 1px solid #ff62ab !important; + } + + ${selector} em { + outline: 1px solid #800b41 !important; + } + + ${selector} strong { + outline: 1px solid #ff1583 !important; + } + + ${selector} i { + outline: 1px solid #803156 !important; + } + + ${selector} b { + outline: 1px solid #cc1169 !important; + } + + ${selector} u { + outline: 1px solid #ff0430 !important; + } + + ${selector} s { + outline: 1px solid #f805e3 !important; + } + + ${selector} small { + outline: 1px solid #d107b2 !important; + } + + ${selector} abbr { + outline: 1px solid #4a0263 !important; + } + + ${selector} q { + outline: 1px solid #240018 !important; + } + + ${selector} cite { + outline: 1px solid #64003c !important; + } + + ${selector} dfn { + outline: 1px solid #b4005a !important; + } + + ${selector} sub { + outline: 1px solid #dba0c8 !important; + } + + ${selector} sup { + outline: 1px solid #cc0256 !important; + } + + ${selector} time { + outline: 1px solid #d6606d !important; + } + + ${selector} code { + outline: 1px solid #e04251 !important; + } + + ${selector} kbd { + outline: 1px solid #5e001f !important; + } + + ${selector} samp { + outline: 1px solid #9c0033 !important; + } + + ${selector} var { + outline: 1px solid #d90047 !important; + } + + ${selector} mark { + outline: 1px solid #ff0053 !important; + } + + ${selector} bdi { + outline: 1px solid #bf3668 !important; + } + + ${selector} bdo { + outline: 1px solid #6f1400 !important; + } + + ${selector} ruby { + outline: 1px solid #ff7b93 !important; + } + + ${selector} rt { + outline: 1px solid #ff2f54 !important; + } + + ${selector} rp { + outline: 1px solid #803e49 !important; + } + + ${selector} span { + outline: 1px solid #cc2643 !important; + } + + ${selector} br { + outline: 1px solid #db687d !important; + } + + ${selector} wbr { + outline: 1px solid #db175b !important; + }`; +} \ No newline at end of file diff --git a/src/Panel.tsx b/src/Panel.tsx deleted file mode 100644 index 76c7bcd..0000000 --- a/src/Panel.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import React from "react"; -import { useAddonState, useChannel } from "@storybook/manager-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 49c7e27..0000000 --- a/src/Tab.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import React from "react"; -import { useParameter } from "@storybook/manager-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 index 4385d57..62e76c5 100644 --- a/src/Tool.tsx +++ b/src/Tool.tsx @@ -1,38 +1,55 @@ -import React, { memo, useCallback, useEffect } from "react"; -import { useGlobals, useStorybookApi } from "@storybook/manager-api"; -import { Icons, IconButton } from "@storybook/components"; -import { ADDON_ID, PARAM_KEY, TOOL_ID } from "./constants"; +import React, { memo } from 'react'; +import * as options from "./options"; +import type { WithHideFn } from "./types"; +import { useGlobals, useStorybookApi } from '@storybook/manager-api'; +import { IconButton, WithTooltip } from '@storybook/components'; +import { ADDON_ID, PARAM_KEY, TOOL_ID } from './constants'; +import { TooltipList } from "./components/TooltipList"; +import { Globals } from '@storybook/types'; export const Tool = memo(function MyAddonSelector() { const [globals, updateGlobals] = useGlobals(); - const api = useStorybookApi(); - const isActive = [true, "true"].includes(globals[PARAM_KEY]); + const toggle = + (id: keyof Globals, value: Globals[typeof id]) => + updateGlobals({ + [id]: value ? value : undefined, + }); - const toggleMyTool = useCallback(() => { - updateGlobals({ - [PARAM_KEY]: !isActive, - }); - }, [isActive]); - - useEffect(() => { - api.setAddonShortcut(ADDON_ID, { - label: "Toggle Measure [O]", - defaultShortcut: ["O"], - actionName: "outline", - showInMenu: false, - action: toggleMyTool, - }); - }, [toggleMyTool, api]); + const createItems = ({ onHide }: WithHideFn) => + options.keys.map((id) => ({ + id, + title: id, + right: ( + + ), + })); return ( - } > - - + + + + + + ); -}); +}); \ No newline at end of file diff --git a/src/components/List.tsx b/src/components/List.tsx index d3d6cfa..f97ffd5 100644 --- a/src/components/List.tsx +++ b/src/components/List.tsx @@ -1,95 +1,118 @@ -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, -}); +import React, { FunctionComponent, ReactNode, ComponentProps } from "react"; +import { styled } from "@storybook/theming"; +import { transparentize } from "polished"; -const Wrapper = styled.div({ - display: "flex", - width: "100%", - borderBottom: `1px solid ${convert(themes.normal).appBorderColor}`, - "&:hover": { - background: convert(themes.normal).background.hoverable, - }, -}); +export interface TitleProps {} -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 Title = styled((props: TitleProps) => )( + ({ theme }) => ({ + color: theme.color.defaultText, + fontWeight: theme.typography.weight.regular, + }) +); -const HeaderBar = styled.div({ - padding: convert(themes.normal).layoutMargin, - paddingLeft: convert(themes.normal).layoutMargin - 3, - background: "none", - color: "inherit", +export interface RightProps {} + +const Right = styled.span( + { + "& svg": { + transition: "all 200ms ease-out", + opacity: 0, + height: 12, + width: 12, + margin: "3px 0", + verticalAlign: "top", + }, + "& path": { + fill: "inherit", + }, + }, + () => ({}) +); + +const Center = styled.span({ + flex: 1, textAlign: "left", - cursor: "pointer", - borderLeft: "3px solid transparent", - width: "100%", + display: "inline-flex", - "&:focus": { - outline: "0 none", - borderLeft: `3px solid ${convert(themes.normal).color.secondary}`, + "& > * + *": { + paddingLeft: 10, }, }); -const Description = styled.div({ - padding: convert(themes.normal).layoutMargin, - marginBottom: convert(themes.normal).layoutMargin, - fontStyle: "italic", +export interface CenterTextProps {} + +const CenterText = styled.span({ + flex: 1, + textAlign: "center", }); -type Item = { - title: string; - description: string; -}; +export interface LeftProps {} -interface ListItemProps { - item: Item; -} +const Left = styled.span(({ theme }) => ({})); -export const ListItem: React.FC = ({ item }) => { - const [open, onToggle] = useState(false); - - return ( - - - onToggle(!open)} role="button"> - - {item.title} - - - {open ? {item.description} : null} - - ); -}; +export interface ItemProps {} + +const Item = styled.div(({ theme }) => ({ + alignItems: "center", + color: transparentize(0.5, theme.color.defaultText), + cursor: 'default', + display: "flex", + fontSize: theme.typography.size.s1, + justifyContent: "space-between", + lineHeight: "18px", + padding: "7px 15px", + textDecoration: "none", + transition: "all 150ms ease-out", + + "& > * + *": { + paddingLeft: 10, + }, + + "&:hover": { + background: theme.background.hoverable, + }, + + "&:hover svg": { + opacity: 1, + }, +})); -interface ListProps { - items: Item[]; +export interface ListItemProps + extends Omit, "title"> { + loading?: boolean; + left?: ReactNode; + title?: ReactNode; + center?: ReactNode; + right?: ReactNode; } -export const List: React.FC = ({ items }) => ( - - {items.map((item, idx) => ( - - ))} - +const ListItem: FunctionComponent = ({ + loading, + left, + title, + center, + right, + ...rest +}) => ( + + {left && {left}} + {title || center ? ( +
+ {title && {title}} + {center && {center}} +
+ ) : null} + {right && {right}} +
); + +ListItem.defaultProps = { + loading: false, + left: null, + title: Loading state, + center: null, + right: null, +}; + +export default ListItem; \ No newline at end of file diff --git a/src/components/TooltipList.tsx b/src/components/TooltipList.tsx new file mode 100644 index 0000000..8717b77 --- /dev/null +++ b/src/components/TooltipList.tsx @@ -0,0 +1,35 @@ +import React, { FunctionComponent } from "react"; +import { styled } from "@storybook/theming"; +import ListItem, { ListItemProps } from "./List"; + +const List = styled.div<{}>( + { + minWidth: 180, + overflow: "hidden", + overflowY: "auto", + maxHeight: 13.5 * 32, // 11.5 items + }, + ({ theme }) => ({ + borderRadius: theme.appBorderRadius * 2, + }) +); + +export interface ItemProps extends ListItemProps { + id: string; +} + +export interface TooltipListProps { + items: ItemProps[]; +} + +const Item: FunctionComponent = (props) => ( + +); + +export const TooltipList: FunctionComponent = ({ items }) => ( + + {items.map(({ ...p }) => ( + + ))} + +); \ No newline at end of file diff --git a/src/constants.ts b/src/constants.ts index d7ef8e4..62b16da 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1,8 +1,6 @@ -export const ADDON_ID = "storybook/my-addon"; +export const ADDON_ID = "storybook/render-modes"; 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 PARAM_KEY = `rederModesParameter`; export const EVENTS = { RESULT: `${ADDON_ID}/result`, diff --git a/src/helpers.ts b/src/helpers.ts new file mode 100644 index 0000000..7ee86c0 --- /dev/null +++ b/src/helpers.ts @@ -0,0 +1,28 @@ +import { global } from '@storybook/global'; + +export const clearStyles = (selector: string | string[]) => { + const selectors = Array.isArray(selector) ? selector : [selector]; + selectors.forEach(clearStyle); +}; + +const clearStyle = (input: string | string[]) => { + const selector = typeof input === 'string' ? input : input.join(''); + const element = global.document.getElementById(selector); + if (element && element.parentElement) { + element.parentElement.removeChild(element); + } +}; + +export const addOutlineStyles = (selector: string, css: string) => { + const existingStyle = global.document.getElementById(selector); + if (existingStyle) { + if (existingStyle.innerHTML !== css) { + existingStyle.innerHTML = css; + } + } else { + const style = global.document.createElement('style'); + style.setAttribute('id', selector); + style.innerHTML = css; + global.document.head.appendChild(style); + } +}; \ No newline at end of file diff --git a/src/manager.ts b/src/manager.ts index 630bf6e..a6c25bf 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -1,36 +1,11 @@ -import { addons, types } from "@storybook/manager-api"; -import { ADDON_ID, TOOL_ID, PANEL_ID, TAB_ID } from "./constants"; -import { Tool } from "./Tool"; -import { Panel } from "./Panel"; -import { Tab } from "./Tab"; - -/** - * Note: if you want to use JSX in this file, rename it to `manager.tsx` - * and update the entry prop in tsup.config.ts to use "src/manager.tsx", - */ - -// 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(TAB_ID, { - type: types.TAB, - title: "My addon", - render: Tab, - }); -}); +import { addons, types } from '@storybook/manager-api'; +import { ADDON_ID, TOOL_ID } from './constants'; +import { Tool } from './Tool'; + +// @ts-expect-error idk why deprecated +addons.register(ADDON_ID, () => addons.add(TOOL_ID, { + type: types.TOOL, + title: 'Render Modes', + match: ({ viewMode }) => !!(viewMode && viewMode.match(/^(story|docs)$/)), + render: Tool, +})); \ No newline at end of file diff --git a/src/options.ts b/src/options.ts new file mode 100644 index 0000000..e8949a8 --- /dev/null +++ b/src/options.ts @@ -0,0 +1,17 @@ +export const title = 'Emulate CSS User Preferences' + +export const features = { + "prefers-color-scheme": ["light", "dark"], + "prefers-constrast": ["no-preference", "less", "more", "custom"], + "prefers-reduced-data": ["no-preference", "reduce"], + "prefers-reduced-motion": ["no-preference", "reduce"], + "prefers-reduced-transparency": ["no-preference", "reduce"], +} as const; + +export const defaultOption = 'system default' + +export const keys = Object.keys(features) as Array + +export const entries = Object.entries(features) as [keyof Features, Features[keyof Features]][] + +export type Features = typeof features; \ No newline at end of file diff --git a/src/preview.ts b/src/preview.ts index 6e4b884..ebc5ec4 100644 --- a/src/preview.ts +++ b/src/preview.ts @@ -1,3 +1,4 @@ +import * as options from "./options"; /** * A decorator is a way to wrap a story in extra โ€œrenderingโ€ functionality. Many addons define decorators * in order to augment stories: @@ -8,7 +9,7 @@ * * https://storybook.js.org/docs/react/writing-stories/decorators */ -import type { Renderer, ProjectAnnotations } from "@storybook/types"; +import type { Renderer, ProjectAnnotations, GlobalTypes } from "@storybook/types"; import { PARAM_KEY } from "./constants"; import { withGlobals } from "./withGlobals"; import { withRoundTrip } from "./withRoundTrip"; @@ -26,3 +27,17 @@ const preview: ProjectAnnotations = { }; export default preview; + +export const globalTypes = Object.entries(options.features).reduce( + (globalTypes: GlobalTypes, [name, value]) => + Object.assign(globalTypes, { + [name]: { + name, + type: { + name: "enum", + value, + }, + }, + } as unknown as GlobalTypes), + {} +); \ No newline at end of file diff --git a/src/processCSS.ts b/src/processCSS.ts new file mode 100644 index 0000000..ef32412 --- /dev/null +++ b/src/processCSS.ts @@ -0,0 +1,74 @@ + +import { Globals } from "@storybook/types"; +import * as options from "./options"; + +/** Recursively process CSS and transform media queries based on feature flags. */ +export function processCSS( + containers, + features, +) { + for (const target of containers) { + if (target instanceof CSSMediaRule) { + /** Initial value, regardless of present transformations. */ + let initialMediaText = getMediaText(target); + + /** Current value, to be transformed */ + let currentMediaText = initialMediaText; + + let feature; + for (feature in features) { + const value = features[feature]; + + // only transform conditions when a feature is defined and detected + if (value !== undefined && currentMediaText.includes(feature)) { + // replace boolean uses of the feature + // @ts-expect-error idk + for (const alternate of options.features[feature]) { + if (value === alternate) { + currentMediaText = currentMediaText.replace( + `(${feature}: ${alternate})`, + "all" + ); + } else { + currentMediaText = currentMediaText.replace( + `(${feature}: ${alternate})`, + "not all" + ); + } + } + + // replace boolean uses of the feature + currentMediaText = currentMediaText.replace( + `(${feature})`, + value === "no-preference" ? "not all" : "all" + ); + } + } + + // update the media text if the value has changed + if (currentMediaText !== target.media.mediaText) { + console.log(1) + target.media.mediaText = currentMediaText; + } + console.log(2) + } else if ("cssRules" in target) { + processCSS(target.cssRules, features); + } + } +} + +/** Returns the initial text of a Media Rule, regardless of transformations. */ +const getMediaText = (target) => { + let conditionText = conditionTextMap.get(target); + + if (conditionText) return conditionText; + + conditionTextMap.set(target, (conditionText = target.media.mediaText)); + + return conditionText; +}; + +/** WeakMap used to store initial text of Media Rules. */ +const conditionTextMap = new WeakMap(); + +export type CSSContainer = CSSStyleSheet | CSSMediaRule | CSSRule; \ No newline at end of file diff --git a/src/stories/Button.tsx b/src/stories/Button.tsx index c33be6e..3062f21 100644 --- a/src/stories/Button.tsx +++ b/src/stories/Button.tsx @@ -34,11 +34,12 @@ export const Button = ({ label, ...props }: ButtonProps) => { + console.log() const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary'; return (