Skip to content
Draft
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
2 changes: 1 addition & 1 deletion src/components/global/Playground/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import angular_example_component_ts from './angular/example_component_ts.md';
| `devicePreview` | Renders the demo inside a device frame. Refer to [Device Frame](#show-example-within-a-device-frame-iphonepixel-5). |
| `showConsole` | Shows a console below the demo with anything the demo logs through `console.log`, `console.warn`, or `console.error`. |
| `includeIonContent` | Wraps the StackBlitz example in `ion-app` and `ion-content`. Defaults to `true`. Refer to [Ejecting](#ejecting-from-ionappioncontent-boilerplate). |
| `defaultFramework` | Framework tab to select when the reader has not picked one. Defaults to Angular when available. |
| `defaultFramework` | Framework tab to select when the reader has not picked one. The pick is shared with the docs' `<Tabs groupId="framework">`, so choosing a framework in either one selects it in the other. Defaults to Angular when available. |
| `title` | Title of the generated StackBlitz project. |
| `description` | Description of the generated StackBlitz project. |

Expand Down
117 changes: 55 additions & 62 deletions src/components/global/Playground/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import Link from '@docusaurus/Link';
import useBaseUrl from '@docusaurus/useBaseUrl';
import './playground.css';
import { EditorOptions, openAngularEditor, openHtmlEditor, openReactEditor, openVueEditor } from './stackblitz.utils';
import { useColorMode } from '@docusaurus/theme-common';
import { useColorMode, useStorageSlot } from '@docusaurus/theme-common';
import { CodeSnippets, ConsoleItem, Mode, UsageTarget } from './playground.types';
import { type Framework, FRAMEWORK_GROUP_ID, getFrameworkLabel } from '@site/src/utils/frameworks';

import Tooltip from '../Tooltip';
import PlaygroundTabs from '../PlaygroundTabs';
Expand Down Expand Up @@ -79,15 +80,16 @@ const CodeBlockButton = ({
}) => {
const buttonRef = useRef<HTMLButtonElement>(null);
const langValue = UsageTarget[language];
const label = getFrameworkLabel(langValue);

return (
<ControlButton
isSelected={usageTarget === langValue}
handleClick={() => {
setAndSaveUsageTarget(langValue, buttonRef.current);
}}
title={`Show ${language} code`}
label={language}
title={`Show ${label} code`}
label={label}
disabled={disabled}
ref={buttonRef}
/>
Expand Down Expand Up @@ -258,28 +260,38 @@ export default function Playground({
return Mode.iOS;
};

const getDefaultUsageTarget = () => {
/**
* The framework is shared with the docs' framework tabs, which store the
* reader's choice under the same key. Picking a framework in either one
* updates the other, and the choice is kept across page loads.
*/
const [storedFramework, frameworkStorage] = useStorageSlot(FRAMEWORK_STORAGE_KEY);

const getUsageTarget = (): UsageTarget => {
/**
* If a default framework was specified and code exists for it, use that.
* The docs tabs have an Angular (Standalone) tab, which the playground
* shows as Angular.
*/
if (defaultFramework && code[defaultFramework] !== undefined) {
return defaultFramework;
const storedTarget = (
storedFramework === ANGULAR_STANDALONE_TAB ? UsageTarget.Angular : storedFramework
) as UsageTarget | null;

/**
* If the reader has picked a framework and there is code for it, use that.
*/
if (storedTarget && code[storedTarget] !== undefined) {
return storedTarget;
}

/**
* If there is a saved target from previously clicking the
* framework buttons, and there is code for it, use that.
* Otherwise, use the default framework if code exists for it.
*/
if (isBrowser) {
const storedTarget = localStorage.getItem(USAGE_TARGET_STORAGE_KEY) as UsageTarget | null;
if (storedTarget && code[storedTarget] !== undefined) {
return storedTarget;
}
if (defaultFramework && code[defaultFramework] !== undefined) {
return defaultFramework;
}

/**
* If there is no saved target, and Angular code is available,
* default to that.
* Otherwise, default to Angular when it is available.
*/
if (code[UsageTarget.Angular] !== undefined) {
return UsageTarget.Angular;
Expand All @@ -297,7 +309,7 @@ export default function Playground({
* or an explicit pixel value.
*/
const frameSize = FRAME_SIZES[size] || size;
const [usageTarget, setUsageTarget] = useState(getDefaultUsageTarget());
const usageTarget = getUsageTarget();
const [ionicMode, setIonicMode] = useState(getDefaultMode());
const [codeSnippets, setCodeSnippets] = useState<CodeSnippets>({});
const [renderIframes, setRenderIframes] = useState(false);
Expand Down Expand Up @@ -338,33 +350,27 @@ export default function Playground({
};

const setAndSaveUsageTarget = (target: UsageTarget, tab: HTMLElement | null) => {
setUsageTarget(target);

if (isBrowser) {
localStorage.setItem(USAGE_TARGET_STORAGE_KEY, target);

/**
* This prevents the scroll position from jumping around if
* there is a playground above this one with code that changes
* in length between frameworks.
*
* Note that we don't need this when changing the mode because
* the two mode iframes are always the same height.
*/
if (tab) {
blockElementScrollPositionUntilNextRender(tab);
}
/**
* This prevents the scroll position from jumping around if
* there is a playground or tabs above this one with code that
* changes in length between frameworks.
*
* Note that we don't need this when changing the mode because
* the two mode iframes are always the same height.
*/
if (tab) {
blockElementScrollPositionUntilNextRender(tab);
}

/**
* Tell other playgrounds on the page that the framework
* has updated, so they can sync up if they're in view.
*/
window.dispatchEvent(
new CustomEvent(USAGE_TARGET_UPDATED_EVENT, {
detail: target,
})
);
/**
* Angular (Standalone) in the docs tabs already shows Angular here,
* so keep it rather than switching those tabs to Angular.
*/
if (target === UsageTarget.Angular && storedFramework === ANGULAR_STANDALONE_TAB) {
return;
}

frameworkStorage.set(target);
};

/**
Expand Down Expand Up @@ -493,16 +499,9 @@ export default function Playground({
if (!event.isIntersecting) return;

/**
* Load the stored mode and/or usage target, if present
* from previously being toggled. Skip the usage target
* reset when defaultFramework is set, since the initial
* value is already correct and user tab clicks should
* be preserved.
* Load the stored mode, if present from previously being toggled.
*/
setIonicMode(getDefaultMode());
if (!defaultFramework) {
setUsageTarget(getDefaultUsageTarget());
}

/**
* If the iframes weren't already loaded, load them now.
Expand All @@ -524,16 +523,9 @@ export default function Playground({
}
};

const handleUsageTargetUpdated = (e: WindowEventMap['playground-usage-target-updated']) => {
const usageTarget = e.detail;
if (Object.values(UsageTarget).includes(usageTarget)) {
setUsageTarget(usageTarget); // don't use setAndSave to avoid infinite loop
}
};

/**
* When this playground is in view, listen for any other playgrounds
* on the page to switch their framework or mode, so this one can
* on the page to switch their mode, so this one can
* sync up to the same setting. This is needed because if the
* playground is already in view, the IntersectionObserver doesn't
* fire until the playground is scrolled off and back on the screen.
Expand All @@ -554,12 +546,10 @@ export default function Playground({
useEffect(() => {
if (isBrowser && isInView) {
window.addEventListener(MODE_UPDATED_EVENT, handleModeUpdated);
window.addEventListener(USAGE_TARGET_UPDATED_EVENT, handleUsageTargetUpdated);
}

return () => {
window.removeEventListener(MODE_UPDATED_EVENT, handleModeUpdated);
window.removeEventListener(USAGE_TARGET_UPDATED_EVENT, handleUsageTargetUpdated);
};
}, [isBrowser, isInView]);

Expand Down Expand Up @@ -995,7 +985,10 @@ const isFrameReady = (frame: HTMLIFrameElement | null) => {
return (frame.contentWindow as any).demoReady === true;
};

const USAGE_TARGET_STORAGE_KEY = 'playground_usage_target';
/**
* The key Docusaurus stores the selected tab under for the docs' framework tabs.
*/
const FRAMEWORK_STORAGE_KEY = `docusaurus.tab.${FRAMEWORK_GROUP_ID}`;
const ANGULAR_STANDALONE_TAB: Framework = 'angular-standalone';
const MODE_STORAGE_KEY = 'playground_mode';
const USAGE_TARGET_UPDATED_EVENT = 'playground-usage-target-updated';
const MODE_UPDATED_EVENT = 'playground-event-updated';
25 changes: 16 additions & 9 deletions src/components/global/Playground/playground.types.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import type { ReactElement } from 'react';
import type { Framework } from '@site/src/utils/frameworks';

export enum UsageTarget {
JavaScript = 'javascript',
Angular = 'angular',
React = 'react',
Vue = 'vue',
}
/**
* The frameworks a playground can show code for. Each value is one of the shared
* framework values, so picking one here selects it in the docs' framework tabs.
*/
export const UsageTarget = {
JavaScript: 'javascript',
Angular: 'angular',
React: 'react',
Vue: 'vue',
} as const satisfies Record<string, Framework>;

export type UsageTarget = (typeof UsageTarget)[keyof typeof UsageTarget];

export enum Mode {
iOS = 'ios',
Expand Down Expand Up @@ -34,13 +41,13 @@ export type CodeSnippets = Partial<Record<UsageTarget, ReactElement | Record<str
* without annotations and `event.detail` is checked.
*
* `console` is dispatched by the demo page inside the playground iframe, so it is
* listened for on that frame's `contentWindow`. The other two are dispatched on the
* page's own window to keep playgrounds on a page in sync.
* listened for on that frame's `contentWindow`. `playground-event-updated` is
* dispatched on the page's own window to keep the mode of playgrounds on a page in
* sync.
*/
declare global {
interface WindowEventMap {
console: CustomEvent<ConsoleItem>;
'playground-event-updated': CustomEvent<Mode>;
'playground-usage-target-updated': CustomEvent<UsageTarget>;
}
}
25 changes: 25 additions & 0 deletions src/utils/frameworks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* The frameworks a reader can pick in the docs' framework tabs and in playgrounds.
*
* Both store the pick under the same Docusaurus tab group, so choosing a framework
* in one selects it in the other. Import the values and labels from here rather
* than writing them out, so the two can't drift apart.
*/

/** The `groupId` of the docs' framework tabs. */
export const FRAMEWORK_GROUP_ID = 'framework';

/** Every framework value, with its label, sorted alphabetically by label as the tabs show them. */
export const FRAMEWORKS = [
{ value: 'angular', label: 'Angular' },
{ value: 'angular-standalone', label: 'Angular (Standalone)' },
{ value: 'javascript', label: 'JavaScript' },
{ value: 'react', label: 'React' },
{ value: 'vue', label: 'Vue' },
] as const;

export type Framework = (typeof FRAMEWORKS)[number]['value'];

export function getFrameworkLabel(framework: Framework): string {
return FRAMEWORKS.find((item) => item.value === framework)!.label;
}
Loading