Skip to content

Commit

Permalink
chore(storybook): fix code loading on docs pages [CSS-1070]
Browse files Browse the repository at this point in the history
  • Loading branch information
castastrophe committed Dec 10, 2024
1 parent b8d2dc1 commit 7c8c3cc
Show file tree
Hide file tree
Showing 11 changed files with 137 additions and 272 deletions.
5 changes: 5 additions & 0 deletions .changeset/famous-comics-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@spectrum-css/preview": patch
---

Fix an issue where "show code" was blocking loading in Storybook docs pages [CSS-1070]
70 changes: 34 additions & 36 deletions .storybook/decorators/language.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { makeDecorator, useEffect } from "@storybook/preview-api";
import { fetchContainers } from "./helpers.js";
/* global Typekit */

/**
* @type import('@storybook/csf').DecoratorFunction<import('@storybook/web-components').WebComponentsFramework>
Expand All @@ -17,48 +16,47 @@ export const withLanguageWrapper = makeDecorator({
viewMode,
} = context;

const currentKitId = window.currentKitId;

useEffect(() => {
const isNotEnglish = lang && lang !== "en-US";
let hasChanged = false;
for (const container of fetchContainers(id, viewMode === "docs")) {
if (container.lang !== lang) {
container.lang = lang;
hasChanged = true;
}
}

if (window.FontsLoading === true) return;
if (!hasChanged) return;

// If it is US-language or unset use the rok6rmo Adobe font web project id (smaller size),
// otherwise use the mge7bvf kit with all the language settings (larger size)
const kitId = isNotEnglish ? "mge7bvf" : "rok6rmo";
const config = {
kitId,
async: true,
scriptTimeout: 3000,
// https://github.com/typekit/webfontloader?tab=readme-ov-file#configuration
loading: function() {},
fontactive: function(familyName) {
console.log(`Font ${familyName} active`);
},
fontinactive: function(familyName) {
console.log(`Font ${familyName} inactive`);
},
active: function() {
console.log(`Font loaded [id: ${kitId}]`);
const kitId = lang && lang !== "en-US" ? "mge7bvf" : "rok6rmo";

// Fire a custom event to indicate the Adobe Fonts have loaded
document.dispatchEvent(new CustomEvent("typekit-loaded", { detail: { kitId } }));
},
}
if (currentKitId === kitId) return;

if (typeof window.Typekit !== "undefined") {
// If the kitId is the same as the one already loaded, do nothing
if (window.Typekit.config?.kitId !== kitId) {
window.Typekit.load(config);
}
}
else {
try {
window.Typekit = Typekit.load(config);
} catch (e) {/* empty */}
}
try {
window.Typekit.load({
kitId,
async: true,
scriptTimeout: 3000,
// https://github.com/typekit/webfontloader?tab=readme-ov-file#configuration
loading: function() {
window.FontsLoading = true;
},
active: function() {
window.FontsLoading = false;
window.currentKitId = this.kitId;
console.log(`Font loaded [id: ${this.kitId}]`);

for (const container of fetchContainers(id, viewMode === "docs")) {
container.lang = lang;
}
}, [lang]);
// Fire a custom event to indicate the Adobe Fonts have loaded
document.dispatchEvent(new CustomEvent("typekit-loaded", { detail: { kitId: this.kitId } }));

},
});
} catch (e) {/* empty */}
}, [lang, currentKitId, window]);

return StoryFn(context);
},
Expand Down
13 changes: 2 additions & 11 deletions .storybook/decorators/testing-preview.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { FORCE_RE_RENDER } from '@storybook/core-events';
import { addons, makeDecorator, useCallback } from "@storybook/preview-api";
import { makeDecorator, useCallback } from "@storybook/preview-api";
import isChromatic from "chromatic/isChromatic";

/**
Expand All @@ -21,17 +20,9 @@ export const withTestingPreviewWrapper = makeDecorator({
window.isChromatic = typeof isChromatic === "function" && isChromatic() === true ? isChromatic : () => testingPreview && viewMode !== "docs";
};

// Function that will update the global value and trigger a UI refresh.
const refreshAndUpdateGlobal = () => {
init();

// Invokes Storybook's addon API method (with the FORCE_RE_RENDER) event to trigger a UI refresh
addons.getChannel().emit(FORCE_RE_RENDER);
};

init();

useCallback(() => refreshAndUpdateGlobal(), [testingPreview]);
useCallback(() => init(), [testingPreview]);

return StoryFn(context);
},
Expand Down
4 changes: 3 additions & 1 deletion .storybook/decorators/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,9 @@ export const Variants = ({

return (args, context) => {
// Fetch any docs configurations from the context to use for VRT
const { argTypes = {}, parameters = {} } = context;
const { argTypes = {}, parameters = {}, viewMode } = context;

if (viewMode === "docs") return Template(args, context);

const height = parameters?.docs?.story?.height;
const width = parameters?.docs?.story?.width;
Expand Down
52 changes: 35 additions & 17 deletions .storybook/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,20 @@ export default {
staticDirs: ["./assets", "./assets/images"],
addons: [
{
name: "@storybook/addon-essentials",
// Supported booleans: actions, controls, docs, toolbars, measure, outline.
options: {
// Don't need viewports b/c the medium/large contexts are used to support scaling.
viewport: false,
// Don't need backgrounds b/c this is handled by the color contexts.
backgrounds: false,
// Configure separately
docs: false,
},
name: "@storybook/addon-controls",
options: {},
},
{
name: "@storybook/addon-toolbars",
options: {},
},
{
name: "@storybook/addon-measure",
options: {},
},
{
name: "@storybook/addon-outline",
options: {},
},
{
name: "@storybook/addon-docs",
Expand All @@ -49,10 +53,14 @@ export default {
transcludeMarkdown: true,
},
},
// https://github.com/storybookjs/storybook/tree/next/code/addons/a11y
"@storybook/addon-a11y",
{
name: "@storybook/addon-actions",
options: {},
},
// https://www.npmjs.com/package/@whitespace/storybook-addon-html
"@whitespace/storybook-addon-html",
// https://github.com/storybookjs/storybook/tree/next/code/addons/a11y
"@storybook/addon-a11y",
// https://storybook.js.org/addons/@etchteam/storybook-addon-status
"@etchteam/storybook-addon-status",
// https://github.com/storybookjs/storybook/tree/next/code/addons/interactions
Expand All @@ -72,10 +80,20 @@ export default {

return mergeConfig(config, {
publicDir: "./assets",
// Add dependencies to pre-optimization
optimizeDeps: {
include: [
"@whitespace/storybook-addon-html",
"@storybook/blocks",
"@storybook/theming",
"@storybook/components",
],
},
build: {
sourcemap: configType === "DEVELOPMENT",
manifest: true,
minify: configType === "PRODUCTION",
cssCodeSplit: false,
},
css: {
devSourcemap: configType === "DEVELOPMENT",
Expand All @@ -85,18 +103,18 @@ export default {
}
});
},
framework: {
name: "@storybook/web-components-vite",
framework: "@storybook/web-components-vite",
typescript: {
// Overrides the default Typescript configuration to allow multi-package components to be documented via Autodocs.
reactDocgen: 'react-docgen',
check: false,
},
features: {
/* Code splitting flag; load stories on-demand */
storyStoreV7: true,
/* Builds stories.json to help with on-demand loading */
buildStoriesJson: true,
},
docs: {
defaultName: "Docs",
},
refs: {
"web-components": {
title: "Spectrum web components",
Expand Down
2 changes: 0 additions & 2 deletions .storybook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"@etchteam/storybook-addon-status": "^5.0.0",
"@storybook/addon-a11y": "^8.4.7",
"@storybook/addon-actions": "^8.4.7",
"@storybook/addon-console": "^3.0.0",
"@storybook/addon-designs": "^8.0.4",
"@storybook/addon-docs": "^8.4.7",
"@storybook/addon-essentials": "^8.4.7",
Expand All @@ -51,7 +50,6 @@
"@storybook/core-events": "^8.4.7",
"@storybook/manager-api": "^8.4.7",
"@storybook/preview-api": "^8.4.7",
"@storybook/testing-library": "^0.2.2",
"@storybook/theming": "^8.4.7",
"@storybook/web-components-vite": "^8.4.7",
"@whitespace/storybook-addon-html": "^6.1.1",
Expand Down
60 changes: 38 additions & 22 deletions .storybook/preview-head.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,43 @@
<link rel="preconnect" href="https://use.typekit.net" crossorigin />

<!-- This is the script that attempts to pre-load the typekit fonts -->
<script src="https://use.typekit.net/rok6rmo.js" id="typekit" type="text/javascript" async></script>
<script>
try {
window.Typekit = Typekit.load({
kitId: "rok6rmo",
async: true,
scriptTimeout: 3000,
// https://github.com/typekit/webfontloader?tab=readme-ov-file#configuration
loading: function() {},
fontactive: function(familyName) {
console.log(`Font ${familyName} active`);
},
fontinactive: function(familyName) {
console.log(`Font ${familyName} inactive`);
},
active: function() {
console.log(`Font loaded [id: ${kitId}]`);
<script>
window.global = window;

// Fire a custom event to indicate the Adobe Fonts have loaded
document.dispatchEvent(new CustomEvent("typekit-loaded", { detail: { kitId } }));
},
});
} catch (e) {}
let d = false;

const tk = document.createElement("script");
tk.src = "//use.typekit.net/rok6rmo.js";
tk.type = "text/javascript";
tk.async = "true";
tk.onload = tk.onreadystatechange = function () {
const rs = this.readyState;
if (d || (rs && rs != "complete" && rs != "loaded")) return;
d = true;

try {
Typekit.load({
kitId: "rok6rmo",
async: true,
scriptTimeout: 3000,
// https://github.com/typekit/webfontloader?tab=readme-ov-file#configuration
loading: function() {
window.FontsLoading = true;
},
active: function() {
window.FontsLoading = false;
window.currentKitId = this.kitId;
console.log(`Font loaded [id: ${this.kitId}]`);

// Fire a custom event to indicate the Adobe Fonts have loaded
document.dispatchEvent(new CustomEvent("typekit-loaded", { detail: { kitId: this.kitId } }));
},
});
} catch (e) {
console.log(e);
}
};

const s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(tk, s);
</script>
28 changes: 5 additions & 23 deletions .storybook/preview.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { setConsoleOptions } from "@storybook/addon-console";

import {
withActions,
withArgEvents,
Expand All @@ -22,19 +22,6 @@ import {

import "./assets/base.css";

window.global = window;

const panelExclude = setConsoleOptions({}).panelExclude || [];
setConsoleOptions({
panelExclude: [
...panelExclude,
/deprecated/,
/TypeError/,
/postcss/,
/stylelint/,
],
});

/** @type import('@storybook/types').StorybookParameters & import('@storybook/types').API_Layout */
export const parameters = {
layout: "centered",
Expand Down Expand Up @@ -75,30 +62,25 @@ export const parameters = {
root: "[data-html-preview]:first-of-type",
removeComments: true,
prettier: {
tabWidth: 4,
tabWidth: 2,
useTabs: false,
htmlWhitespaceSensitivity: "ignore",
},
highlighter: {
showLineNumbers: true,
wrapLines: true,
},
},
docs: {
defaultName: "Docs",
page: DocumentationTemplate,
story: { inline: true },
source: {
type: "dynamic",
language: "html",
format: "html",
excludeDecorators: true,
},
},
status: {
statuses: {
migrated: {
background: "#f0f0f0",
color: "#444",
description: "Migrated to the latest tokens.",
},
deprecated: {
background: "rgb(211,21,16)",
color: "#fff",
Expand Down
2 changes: 1 addition & 1 deletion .storybook/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"build": {
"configurations": {
"ci": {
"commands": ["cross-env NODE_OPTIONS=\"--no-warnings\" storybook build --config-dir ."]
"commands": ["cross-env NODE_OPTIONS=\"--no-warnings\" storybook build --test --config-dir ."]
},
"docs": {
"commands": [
Expand Down
Loading

0 comments on commit 7c8c3cc

Please sign in to comment.