Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docusaurus.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ module.exports = {
},
},
favicon: 'img/meta/favicon-96x96.png',
/**
* Copies the reader's saved framework onto `<html>` 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',
Expand Down
20 changes: 20 additions & 0 deletions e2e/playground.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
20 changes: 17 additions & 3 deletions src/components/global/FrameworkSwitcher/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}

Expand All @@ -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)
Expand Down Expand Up @@ -84,14 +92,20 @@ export default function FrameworkSwitcher({ options, selected, onSelect, classNa
};

return (
<div role="tablist" aria-label="Framework" className={clsx(styles.switcher, className)}>
<div
role="tablist"
aria-label="Framework"
className={clsx(styles.switcher, className)}
data-framework-pending={followsSavedFramework && !isBrowser ? '' : undefined}
>
{options.map((option, index) => (
<ToggleButton
key={option.value}
ref={(button) => {
buttons.current[index] = button;
}}
role="tab"
data-framework={option.value}
id={option.tabId}
aria-controls={option.panelId}
aria-selected={option.value === selected}
Expand Down
3 changes: 0 additions & 3 deletions src/components/global/FrameworkSwitcher/styles.module.css

This file was deleted.

27 changes: 27 additions & 0 deletions src/components/global/FrameworkSwitcher/styles.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@use '../../../css/mixins';

.switcher {
display: flex;
}

/*
* The server renders the default framework as selected. Until the page's scripts
* load, a switcher marked `data-framework-pending` selects the reader's saved framework
* instead, if it offers that framework.
*/
@include mixins.each-saved-framework using ($saved, $shown) {
$offers: ':has([data-framework="#{$shown}"]:not(:disabled))';
@if $saved != $shown {
$offers: '#{$offers}:not(:has([data-framework="#{$saved}"]:not(:disabled)))';
}

:global(html[data-saved-framework='#{$saved}']) .switcher[data-framework-pending]#{$offers} {
[aria-selected='true'] {
@include mixins.toggle-button-unselected;
}

[data-framework='#{$shown}'] {
@include mixins.toggle-button-selected;
}
}
}
13 changes: 10 additions & 3 deletions src/components/global/FrameworkTabs/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@

import React, { Children, isValidElement, useId, type ReactElement, type ReactNode } from 'react';
import clsx from 'clsx';
import useIsBrowser from '@docusaurus/useIsBrowser';
import type { Props as TabItemProps } from '@theme/TabItem';
import { FRAMEWORKS, useFrameworkChoice } from '@site/src/utils/frameworks';

import FrameworkSwitcher from '../FrameworkSwitcher';

import styles from './styles.module.css';
import styles from './styles.module.scss';

interface Props {
children: ReactNode;
Expand Down Expand Up @@ -75,11 +76,16 @@ export default function FrameworkTabs({ children, defaultValue, className }: Pro

const { selected, select } = useFrameworkChoice(values);
const shown = selected ?? defaultValue ?? values[0];
const isBrowser = useIsBrowser();

return (
<div className={clsx(styles.container, className)}>
/**
* 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.
*/
<div className={clsx(styles.container, className)} data-framework-pending={isBrowser ? undefined : ''}>
<div className={styles.switcher}>
<FrameworkSwitcher options={tabs} selected={shown} onSelect={select} />
<FrameworkSwitcher options={tabs} selected={shown} onSelect={select} followsSavedFramework />
</div>
{tabs.map((tab) => (
/**
Expand All @@ -89,6 +95,7 @@ export default function FrameworkTabs({ children, defaultValue, className }: Pro
<div
key={tab.value}
role="tabpanel"
data-framework={tab.value}
id={tab.panelId}
aria-labelledby={tab.tabId}
hidden={tab.value !== shown}
Expand Down
18 changes: 0 additions & 18 deletions src/components/global/FrameworkTabs/styles.module.css

This file was deleted.

40 changes: 40 additions & 0 deletions src/components/global/FrameworkTabs/styles.module.scss
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
19 changes: 13 additions & 6 deletions src/components/global/Playground/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,14 @@ function PlaygroundExample({
*/
const [pickedTarget, setPickedTarget] = useState<UsageTarget | null>(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;
}

Expand Down Expand Up @@ -548,7 +550,12 @@ function PlaygroundExample({
<div className={`playground__container ${showConsole ? 'playground__container--has-console' : ''}`}>
<div className="playground__control-toolbar">
<div className="playground__control-group">
<FrameworkSwitcher options={frameworkOptions} selected={usageTarget} onSelect={pickFramework} />
<FrameworkSwitcher
options={frameworkOptions}
selected={usageTarget}
onSelect={pickFramework}
followsSavedFramework={!opensOnDefault}
/>
</div>
<div className="playground__control-group">
<ToggleButton
Expand Down
28 changes: 25 additions & 3 deletions src/css/_mixins.scss
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,12 @@
align-items: center;
padding: 6px 10px;

color: var(--toggle-button-color);
background-color: transparent;
@include toggle-button-unselected;
border: none;
border-radius: 100px;

font-family: inherit;
font-size: 12px;
font-weight: 400;
line-height: normal;

appearance: none;
Expand Down Expand Up @@ -76,6 +74,14 @@
}
}

/// The look of a toggle button that isn't selected. `toggle-button` includes it;
/// include it on its own only to undo `toggle-button-selected`.
@mixin toggle-button-unselected {
background-color: transparent;
color: var(--toggle-button-color);
font-weight: 400;
}

@mixin toggle-button-selected {
background-color: var(--toggle-button-selected-background);
color: var(--toggle-button-selected-color);
Expand All @@ -88,3 +94,19 @@
outline: 2px solid var(--ifm-link-color);
outline-offset: -2px;
}

/// Runs its block for each framework a reader can save, with the framework a
/// group shows for it, the way `useFrameworkChoice` picks: the same one, or
/// Angular for a saved Angular (Standalone) where a group has no Standalone. The
/// list matches `FRAMEWORKS` in `src/utils/frameworks.ts`.
///
/// The framework tabs and playgrounds use it to show the reader's saved
/// framework before the page's scripts load, from the attribute the inline
/// script in `docusaurus.config.js` sets on `<html>`.
@mixin each-saved-framework {
Comment thread
brandyscarney marked this conversation as resolved.
Resolved
@each $framework in angular, angular-standalone, javascript, react, vue {
@content($framework, $framework);
}

@content(angular-standalone, angular);
}
28 changes: 28 additions & 0 deletions src/utils/frameworks.spec.ts
Original file line number Diff line number Diff line change
@@ -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}')`);
});
});
5 changes: 3 additions & 2 deletions src/utils/frameworks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ const ANGULAR_STANDALONE: Framework = 'angular-standalone';

/**
* The key Docusaurus stores `<Tabs groupId="framework">` 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);
Expand Down
Loading