diff --git a/docusaurus.config.js b/docusaurus.config.js
index 87c6df43d8..330720bd97 100644
--- a/docusaurus.config.js
+++ b/docusaurus.config.js
@@ -86,6 +86,20 @@ module.exports = {
},
},
favicon: 'img/meta/favicon-96x96.png',
+ /**
+ * Copies the reader's saved framework onto `` before the page paints, so
+ * framework tabs and playgrounds can show it before the scripts load. The key
+ * is `STORAGE_KEY` in `src/utils/frameworks.ts`, and the styles that read the
+ * attribute are in `FrameworkSwitcher` and `FrameworkTabs`.
+ */
+ headTags: [
+ {
+ tagName: 'script',
+ attributes: {},
+ innerHTML:
+ "try{var f=localStorage.getItem('docusaurus.tab.framework');f&&document.documentElement.setAttribute('data-saved-framework',f)}catch(e){}",
+ },
+ ],
presets: [
[
'@docusaurus/preset-classic',
diff --git a/e2e/playground.e2e.ts b/e2e/playground.e2e.ts
index a589595c4f..bacdc99c35 100644
--- a/e2e/playground.e2e.ts
+++ b/e2e/playground.e2e.ts
@@ -106,6 +106,26 @@ test.describe('framework choice', () => {
await expect(frameworkTab(page.locator('.playground').first(), 'React')).toHaveAttribute('aria-selected', 'true');
});
+ test('is shown before the page loads its scripts', async ({ page }) => {
+ await page.addInitScript(() => {
+ // Demo frames share the origin, so only the page itself saves the pick.
+ if (window === window.top) {
+ localStorage.setItem('docusaurus.tab.framework', 'react');
+ }
+ });
+ // Without its bundles, the page stays as the server rendered it.
+ await page.route('**/assets/js/**', (route) => route.abort());
+ await page.goto('utilities/gestures');
+
+ // The selected look is the only cue before hydration, since `aria-selected` still names the server's default.
+ const docsTabs = docsFrameworkTabs(page).first();
+ await expect(docsTabs.getByRole('tab', { name: 'React', exact: true })).toHaveCSS('font-weight', '500');
+ await expect(docsTabs.getByRole('tab', { name: 'JavaScript', exact: true })).toHaveCSS('font-weight', '400');
+ await expect(page.locator('[role=tabpanel][data-framework=react]').first()).toBeVisible();
+ await expect(page.locator('[role=tabpanel][data-framework=javascript]').first()).toBeHidden();
+ await expect(frameworkTab(page.locator('.playground').first(), 'React')).toHaveCSS('font-weight', '500');
+ });
+
test('disables a framework the playground has no code for, and skips it with the arrow keys', async ({ page }) => {
const playground = await openChildStatePlayground(page);
diff --git a/src/components/global/FrameworkSwitcher/index.tsx b/src/components/global/FrameworkSwitcher/index.tsx
index da6b54c9a0..f99ea2caab 100644
--- a/src/components/global/FrameworkSwitcher/index.tsx
+++ b/src/components/global/FrameworkSwitcher/index.tsx
@@ -10,10 +10,11 @@
import React, { useRef, type KeyboardEvent } from 'react';
import clsx from 'clsx';
+import useIsBrowser from '@docusaurus/useIsBrowser';
import ToggleButton from '../ToggleButton';
-import styles from './styles.module.css';
+import styles from './styles.module.scss';
export interface FrameworkOption {
value: string;
@@ -30,6 +31,12 @@ interface Props {
options: readonly FrameworkOption[];
selected: string;
onSelect: (value: string) => void;
+ /**
+ * Whether `selected` is the reader's saved framework once the page's scripts
+ * read it. The server can't read it, so until the scripts load, the stylesheet
+ * shows the saved framework instead.
+ */
+ followsSavedFramework?: boolean;
className?: string;
}
@@ -48,8 +55,9 @@ function keepInPlace(element: HTMLElement | null, update: () => void) {
}
}
-export default function FrameworkSwitcher({ options, selected, onSelect, className }: Props) {
+export default function FrameworkSwitcher({ options, selected, onSelect, followsSavedFramework, className }: Props) {
const buttons = useRef<(HTMLButtonElement | null)[]>([]);
+ const isBrowser = useIsBrowser();
// One tab must be reachable with the Tab key, even if none is selected.
const focusable = options.some((option) => option.value === selected)
@@ -84,7 +92,12 @@ export default function FrameworkSwitcher({ options, selected, onSelect, classNa
};
return (
-
+
{options.map((option, index) => (
+ /**
+ * The server can't read the reader's saved framework, so until the page's
+ * scripts load, `data-framework-pending` lets the stylesheet show it instead.
+ */
+
-
+
{tabs.map((tab) => (
/**
@@ -89,6 +95,7 @@ export default function FrameworkTabs({ children, defaultValue, className }: Pro
:last-child {
- margin-bottom: 0;
-}
diff --git a/src/components/global/FrameworkTabs/styles.module.scss b/src/components/global/FrameworkTabs/styles.module.scss
new file mode 100644
index 0000000000..14b03acdd5
--- /dev/null
+++ b/src/components/global/FrameworkTabs/styles.module.scss
@@ -0,0 +1,40 @@
+@use '../../../css/mixins';
+
+/* Matches the spacing of Docusaurus's tabs. */
+.container {
+ margin-bottom: var(--ifm-leading);
+}
+
+/* Scrolls sideways on narrow screens, as the playground toolbar does. */
+.switcher {
+ overflow-x: auto;
+}
+
+/* Matches the gap between Docusaurus's tabs and their panels in `src/css/theme/Tabs.scss`. */
+.panel {
+ margin-top: 0.75rem;
+}
+
+.panel > :last-child {
+ margin-bottom: 0;
+}
+
+/*
+ * The server renders the default framework's panel. Until the page's scripts
+ * load, a group marked `data-framework-pending` shows the reader's saved framework
+ * instead, if it has a panel for it. Its switcher does the same for the buttons.
+ */
+@include mixins.each-saved-framework using ($saved, $shown) {
+ $offers: ':has(> [data-framework="#{$shown}"])';
+ @if $saved != $shown {
+ $offers: '#{$offers}:not(:has(> [data-framework="#{$saved}"]))';
+ }
+
+ :global(html[data-saved-framework='#{$saved}']) .container[data-framework-pending]#{$offers} > .panel {
+ display: none;
+
+ &[data-framework='#{$shown}'] {
+ display: block;
+ }
+ }
+}
diff --git a/src/components/global/Playground/index.tsx b/src/components/global/Playground/index.tsx
index a66e15de6f..5c4866af11 100644
--- a/src/components/global/Playground/index.tsx
+++ b/src/components/global/Playground/index.tsx
@@ -123,12 +123,14 @@ function PlaygroundExample({
*/
const [pickedTarget, setPickedTarget] = useState
(null);
+ /**
+ * A default framework wins over the stored choice, so a page written for
+ * one framework, such as the React navigation guide, always opens on it.
+ */
+ const opensOnDefault = defaultFramework !== undefined && code[defaultFramework] !== undefined;
+
const getUsageTarget = (): UsageTarget => {
- /**
- * A default framework wins over the stored choice, so a page written for
- * one framework, such as the React navigation guide, always opens on it.
- */
- if (defaultFramework && code[defaultFramework] !== undefined) {
+ if (opensOnDefault) {
return pickedTarget ?? defaultFramework;
}
@@ -548,7 +550,12 @@ function PlaygroundExample({
-
+
`.
+@mixin each-saved-framework {
+ @each $framework in angular, angular-standalone, javascript, react, vue {
+ @content($framework, $framework);
+ }
+
+ @content(angular-standalone, angular);
+}
diff --git a/src/utils/frameworks.spec.ts b/src/utils/frameworks.spec.ts
new file mode 100644
index 0000000000..ec3457de49
--- /dev/null
+++ b/src/utils/frameworks.spec.ts
@@ -0,0 +1,28 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it, vi } from 'vitest';
+
+// Needs the Docusaurus app to load, and these tests only read constants.
+vi.mock('@docusaurus/theme-common', () => ({}));
+
+import { FRAMEWORKS, STORAGE_KEY } from './frameworks';
+
+/*
+ * The stylesheets and the inline script in `docusaurus.config.js` show the
+ * reader's saved framework before the page's scripts load, so they can't import
+ * these values and repeat them instead.
+ */
+const read = (path: string) => readFileSync(new URL(path, import.meta.url), 'utf8');
+
+describe('frameworks outside the page scripts', () => {
+ it('lists every framework in the `each-saved-framework` mixin', () => {
+ const list = read('../css/_mixins.scss').match(
+ /@mixin each-saved-framework \{\s*@each \$framework in ([^{]+)\{/
+ )?.[1];
+
+ expect(list?.split(',').map((framework) => framework.trim())).toEqual(FRAMEWORKS.map(({ value }) => value));
+ });
+
+ it('reads the same storage key in the inline script', () => {
+ expect(read('../../docusaurus.config.js')).toContain(`localStorage.getItem('${STORAGE_KEY}')`);
+ });
+});
diff --git a/src/utils/frameworks.ts b/src/utils/frameworks.ts
index 5891f8edc4..446f5ef1ee 100644
--- a/src/utils/frameworks.ts
+++ b/src/utils/frameworks.ts
@@ -25,9 +25,10 @@ const ANGULAR_STANDALONE: Framework = 'angular-standalone';
/**
* The key Docusaurus stores `` under. A translation's
- * pages still use those tabs, so keeping the key keeps them in sync too.
+ * pages still use those tabs, so keeping the key keeps them in sync too. The
+ * inline script in `docusaurus.config.js` reads it before the page paints.
*/
-const STORAGE_KEY = 'docusaurus.tab.framework';
+export const STORAGE_KEY = 'docusaurus.tab.framework';
function isFramework(value: string): boolean {
return FRAMEWORKS.some((framework) => framework.value === value);