From 30b422b89c6c27bb3c47cf69a48ccb73563b5a88 Mon Sep 17 00:00:00 2001 From: Mykola Ptushchuk Date: Wed, 30 Oct 2024 16:32:11 +0200 Subject: [PATCH] docs(storybook): Grid support for stories --- .storybook/addons/withGrid.jsx | 78 ++++++++++++++++++++++++++++++++++ .storybook/preview.js | 8 +++- 2 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 .storybook/addons/withGrid.jsx diff --git a/.storybook/addons/withGrid.jsx b/.storybook/addons/withGrid.jsx new file mode 100644 index 00000000..96744800 --- /dev/null +++ b/.storybook/addons/withGrid.jsx @@ -0,0 +1,78 @@ +import React, { useEffect, useRef } from "react"; + +const GRID = [ + { + value: false, + title: "Grid: Off", + }, + { + value: true, + title: "Grid: On", + }, +]; + +export const gridType = { + grid: { + name: "Grid", + description: "Global grid for components", + defaultValue: GRID[0].value, + toolbar: { + title: "Grid", + items: GRID, + dynamicTitle: true, + }, + }, +}; + +const removeGridFromDocs = () => { + document.querySelectorAll(".docs-story").forEach((docStory) => { + docStory.classList.remove("u-baseline-grid"); + }); +}; + +const removeGridFromStory = () => { + document.body.classList.remove("u-baseline-grid"); +}; + +const clearGrid = () => { + removeGridFromStory(); + removeGridFromDocs(); +}; + +const addGridToDocs = () => { + removeGridFromStory(); + document.querySelectorAll(".docs-story").forEach((docStory) => { + docStory.classList.add("u-baseline-grid"); + }); +}; + +const addGridToStory = () => { + removeGridFromDocs(); + document.body.classList.add("u-baseline-grid"); +}; + +export const WithGridProvider = (Story, context) => { + const { + viewMode, + globals: { grid }, + } = context; + const isDocs = viewMode === "docs"; + const gridRef = useRef(false); + + useEffect(() => { + if (gridRef.current !== grid) { + if (grid) { + if (isDocs) { + addGridToDocs(); + } else { + addGridToStory(); + } + } else { + clearGrid(); + } + gridRef.current = grid; + } + }, [grid, isDocs]); + + return ; +}; diff --git a/.storybook/preview.js b/.storybook/preview.js index cf4ca618..8880f5ee 100644 --- a/.storybook/preview.js +++ b/.storybook/preview.js @@ -1,16 +1,20 @@ import { themes } from "@storybook/theming"; import "vanilla-framework/scss/build.scss"; import { themeType, WithThemeProvider } from "./addons/withTheme"; +import { gridType, WithGridProvider } from "./addons/withGrid"; export const parameters = { docs: { theme: themes.vanillaish, }, backgrounds: { + grid: { + disable: true, + }, disable: true, }, }; -export const decorators = [WithThemeProvider]; +export const decorators = [WithThemeProvider, WithGridProvider]; -export const globalTypes = themeType; +export const globalTypes = { ...themeType, ...gridType };