Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(docsite): add a Format code action to the playground editor (#2684) (#3843)

AKfec872b29351
diff --git a/apps/docsite/package.json b/apps/docsite/package.json
index 4de54032a5..d7207ee8ff 100644
--- a/apps/docsite/package.json
+++ b/apps/docsite/package.json
@@ -34,6 +34,7 @@
"mcp-handler": "^1.1.0",
"monaco-editor": "^0.55.1",
"next": "16.3.0-preview.5",
+ "prettier": "^3.9.3",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"zod": "^4.4.3"
diff --git a/apps/docsite/src/__tests__/playground-format.test.ts b/apps/docsite/src/__tests__/playground-format.test.ts
new file mode 100644
index 0000000000..2fe9bff6f2
--- /dev/null
+++ b/apps/docsite/src/__tests__/playground-format.test.ts
@@ -0,0 +1,660 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file playground-format.test.ts
+ *
+ * Coverage for the playground's "Format code" action (issue #2684): the editor
+ * had no way to tidy code, so a Prettier-backed formatter is registered with
+ * Monaco and surfaced as a toolbar button + Monaco's built-in Format Document
+ * (`editor.action.formatDocument`) keybinding.
+ *
+ * The invariants pinned here:
+ * 1. The browser-side Prettier options are the repo's OWN `.prettierrc` — the
+ * playground must not drift into a different house style.
+ * 2. `formatPlaygroundCode` applies those options to TSX playground source.
+ * 3. The Monaco document-formatting provider replaces the full model range,
+ * and — importantly — stays out of the way when there is nothing to do
+ * (already formatted / empty) or when the source cannot be parsed (the
+ * common case: the user is mid-keystroke with broken syntax).
+ * 4. The toolbar button drives Monaco's own `editor.action.formatDocument`
+ * action, which is what the keybinding is bound to — so the button and the
+ * shortcut can never diverge.
+ * 5. THE WIRING: `configureMonaco` actually registers the formatter. Without
+ * this, every test above can pass against a feature that is 100% dead to
+ * the user — no provider, so no Shift+Alt+F and nothing for the button to
+ * drive. It is also the only registration seam, so it pins that the guard
+ * de-dupes on the Monaco instance rather than the module (Fast Refresh
+ * re-evaluates the module and would otherwise stack duplicate providers).
+ * 6. A user syntax error is swallowed (Monaco already squiggles it), but
+ * Prettier failing to LOAD is reported — otherwise the button is silently
+ * dead for a whole cohort of users and nobody ever finds out.
+ * 7. The tooltip advertises the chord Monaco actually bound on this platform
+ * (Ctrl+Shift+I on Linux, Shift+Alt+F elsewhere).
+ *
+ * NOT covered here: the `<Button>` in PlaygroundClient.tsx itself. The docsite
+ * suite is node-env with no jsdom/RTL, and standing that up to render a
+ * Monaco-hosting page is disproportionate. Deleting the button would still go
+ * green — see the PR description, where this is called out explicitly.
+ *
+ * Run: pnpm -F @astryxdesign/docsite test
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {
+ PLAYGROUND_PRETTIER_OPTIONS,
+ createPrettierFormattingProvider,
+ formatButtonTooltip,
+ formatPlaygroundCode,
+ formatShortcutHint,
+ isSourceSyntaxError,
+ registerPrettierFormatter,
+ runFormatAction,
+ FORMAT_DOCUMENT_ACTION_ID,
+} from '../app/playground/formatCode';
+import {configureMonaco} from '../app/playground/monacoSetup';
+
+// The single Prettier config that governs every file in the repo — including
+// apps/docsite (`prettier --find-config-path` on PlaygroundClient.tsx resolves
+// here). The playground's browser-side options must stay equal to it.
+const PRETTIERRC_PATH = path.resolve(__dirname, '../../../../.prettierrc.json');
+
+/** Minimal stand-in for a Monaco text model (getValue + getFullModelRange). */
+function fakeModel(value: string) {
+ const lines = value.split('\n');
+ return {
+ getValue: () => value,
+ getFullModelRange: () => ({
+ startLineNumber: 1,
+ startColumn: 1,
+ endLineNumber: lines.length,
+ endColumn: lines[lines.length - 1].length + 1,
+ }),
+ };
+}
+
+/**
+ * Stand-in for the Monaco runtime object handed to `onMount`. Fresh per call —
+ * registration de-dupes on the instance, so a shared one would leak across tests.
+ */
+function fakeMonaco() {
+ return {
+ languages: {
+ registerDocumentFormattingEditProvider: vi.fn(
+ (
+ _languages: string | string[],
+ _provider: {provideDocumentFormattingEdits: unknown},
+ ) => ({dispose: vi.fn()}),
+ ),
+ typescript: {
+ typescriptDefaults: {
+ setCompilerOptions: vi.fn(),
+ setDiagnosticsOptions: vi.fn(),
+ addExtraLib: vi.fn(),
+ },
+ ScriptTarget: {ESNext: 99},
+ ModuleKind: {ESNext: 99},
+ JsxEmit: {ReactJSX: 4},
+ ModuleResolutionKind: {NodeJs: 2},
+ },
+ },
+ };
+}
+
+/** Run the provider against a source string and hand back the edits. */
+async function formatVia(
+ provider: ReturnType<typeof createPrettierFormattingProvider>,
+ source: string,
+) {
+ return provider.provideDocumentFormattingEdits(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ fakeModel(source) as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ );
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.doUnmock('prettier/standalone');
+ vi.resetModules();
+});
+
+const MESSY_CODE = [
+ 'import { Button } from "@astryxdesign/core/Button"',
+ 'export default function Example( ) {',
+ 'const items = [ 1,2,3 ]',
+ 'return <Button label="Hi" onClick={ (e) => console.log(e, items) } />',
+ '}',
+].join('\n');
+
+describe('playground format — Prettier options', () => {
+ it('uses the repo’s own .prettierrc values', () => {
+ const repoConfig = JSON.parse(fs.readFileSync(PRETTIERRC_PATH, 'utf8'));
+ expect(PLAYGROUND_PRETTIER_OPTIONS).toEqual(repoConfig);
+ });
+});
+
+describe('formatPlaygroundCode', () => {
+ it('formats messy TSX in the repo’s house style', async () => {
+ const formatted = await formatPlaygroundCode(MESSY_CODE);
+
+ // singleQuote
+ expect(formatted).toContain("from '@astryxdesign/core/Button'");
+ expect(formatted).not.toContain('"@astryxdesign/core/Button"');
+ // bracketSpacing: false
+ expect(formatted).toContain('import {Button}');
+ // arrowParens: avoid
+ expect(formatted).toContain('onClick={e =>');
+ // semicolons + normalized whitespace
+ expect(formatted).toContain('const items = [1, 2, 3];');
+ expect(formatted).toContain('export default function Example() {');
+ expect(formatted.endsWith('\n')).toBe(true);
+ });
+
+ it('is idempotent — formatting formatted code is a no-op', async () => {
+ const once = await formatPlaygroundCode(MESSY_CODE);
+ expect(once).not.toBe(MESSY_CODE);
+ const twice = await formatPlaygroundCode(once);
+ expect(twice).toBe(once);
+ });
+
+ it('honors bracketSameLine on wrapped JSX', async () => {
+ const formatted = await formatPlaygroundCode(
+ 'export default function E() { return <Button label="a-very-long-label-that-forces-a-wrap" variant="primary" size="md" onClick={() => {}} isDisabled>Click me</Button> }',
+ );
+ // The props are long enough that Prettier must break them onto their own
+ // lines — proving this really wrapped rather than passing through.
+ expect(formatted).toMatch(/\n\s+variant="primary"/);
+ // bracketSameLine: true — the `>` hugs the last prop instead of sitting
+ // alone on the next line (which is what the Prettier default would do).
+ // Note it deliberately does NOT apply to self-closing elements.
+ expect(formatted).toContain('isDisabled>');
+ expect(formatted).not.toMatch(/\n\s*>\n/);
+ });
+
+ it('rejects on unparseable source rather than returning junk', async () => {
+ await expect(formatPlaygroundCode('const = ??? <')).rejects.toThrow();
+ });
+
+ /**
+ * The end-to-end guarantee the issue actually asks for: the browser-side
+ * (standalone + parser plugins) formatter must produce byte-identical output
+ * to the repo's own Prettier — config resolved from disk the same way the
+ * `prettier` CLI resolves it for a docsite source file. If the standalone
+ * build, the parser choice, or the options ever drift, this fails.
+ */
+ it('matches the repo’s own Prettier byte-for-byte', async () => {
+ const prettier = await import('prettier');
+ const repoConfig = await prettier.resolveConfig(
+ path.resolve(__dirname, '../app/playground/PlaygroundClient.tsx'),
+ );
+ expect(repoConfig).not.toBeNull();
+
+ const viaRepoPrettier = await prettier.format(MESSY_CODE, {
+ ...repoConfig,
+ parser: 'typescript',
+ });
+
+ expect(await formatPlaygroundCode(MESSY_CODE)).toBe(viaRepoPrettier);
+ });
+});
+
+describe('createPrettierFormattingProvider', () => {
+ it('replaces the full model range with the formatted source', async () => {
+ const provider = createPrettierFormattingProvider();
+ const model = fakeModel(MESSY_CODE);
+
+ const edits = await provider.provideDocumentFormattingEdits(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ model as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ );
+
+ expect(edits).toHaveLength(1);
+ expect(edits![0].range).toEqual(model.getFullModelRange());
+ expect(edits![0].text).toBe(await formatPlaygroundCode(MESSY_CODE));
+ });
+
+ it('returns no edits when the source is already formatted (no phantom undo step)', async () => {
+ const provider = createPrettierFormattingProvider();
+ const clean = await formatPlaygroundCode(MESSY_CODE);
+
+ const edits = await provider.provideDocumentFormattingEdits(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ fakeModel(clean) as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ );
+
+ expect(edits).toEqual([]);
+ });
+
+ it('leaves the buffer untouched when the source has a syntax error', async () => {
+ const provider = createPrettierFormattingProvider();
+
+ const edits = await provider.provideDocumentFormattingEdits(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ fakeModel('export default function Broken( {') as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ );
+
+ expect(edits).toEqual([]);
+ });
+
+ it('returns no edits for an empty document', async () => {
+ const provider = createPrettierFormattingProvider();
+
+ const edits = await provider.provideDocumentFormattingEdits(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ fakeModel('') as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ {} as any,
+ );
+
+ expect(edits).toEqual([]);
+ });
+
+ it('empties a whitespace-only document, exactly as Prettier does to a blank file', async () => {
+ // A distinct path from the empty document above: Prettier returns '' here
+ // too, but it DIFFERS from the source, so this really does emit an edit and
+ // clear the buffer. Pinned so the blanking is a decision, not a surprise.
+ const provider = createPrettierFormattingProvider();
+
+ const edits = await formatVia(provider, ' \n\n\t \n');
+
+ expect(edits).toHaveLength(1);
+ expect(edits![0].text).toBe('');
+ });
+});
+
+describe('registerPrettierFormatter', () => {
+ it('registers a document formatting provider for the editor’s language', () => {
+ const monaco = fakeMonaco();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ registerPrettierFormatter(monaco as any);
+
+ const register = monaco.languages.registerDocumentFormattingEditProvider;
+ expect(register).toHaveBeenCalledTimes(1);
+
+ const [languages, provider] = register.mock.calls[0];
+ // The playground editor is `defaultLanguage="typescript"`.
+ expect(languages).toContain('typescript');
+ expect(typeof provider.provideDocumentFormattingEdits).toBe('function');
+ });
+
+ it('hands back the same disposable rather than registering a second provider', () => {
+ // A duplicate registration is not harmless: with two document formatters
+ // Monaco stops auto-picking ours and puts the format behind a "select a
+ // formatter" choice. The cached handle is what a second caller must get.
+ const monaco = fakeMonaco();
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const first = registerPrettierFormatter(monaco as any);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const second = registerPrettierFormatter(monaco as any);
+
+ expect(second).toBe(first);
+ expect(
+ monaco.languages.registerDocumentFormattingEditProvider,
+ ).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('runFormatAction', () => {
+ it('runs Monaco’s format-document action (the Shift+Alt+F binding)', () => {
+ expect(FORMAT_DOCUMENT_ACTION_ID).toBe('editor.action.formatDocument');
+
+ const run = vi.fn(() => Promise.resolve());
+ const getAction = vi.fn(() => ({run}));
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ void runFormatAction({getAction} as any);
+
+ expect(getAction).toHaveBeenCalledWith(FORMAT_DOCUMENT_ACTION_ID);
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+
+ /**
+ * The first format downloads Prettier's TypeScript parser (~1MB), so the
+ * action is genuinely slow exactly once — and Monaco CANCELS an in-flight
+ * format the moment the model or the cursor moves
+ * (format.js: `EditorStateCancellationTokenSource(Value | Position)`). A user
+ * who gets no feedback clicks into the editor to see if it worked, and that
+ * click silently kills the format. So the caller has to be able to show
+ * progress, which means waiting on the action rather than firing and
+ * forgetting it — this is what lets Button drive it with `clickAction`.
+ */
+ it('resolves only once the format has finished, so the caller can show progress', async () => {
+ const order: string[] = [];
+ let finishFormatting!: () => void;
+ const run = vi.fn(
+ () =>
+ new Promise<void>(resolve => {
+ finishFormatting = () => {
+ order.push('format finished');
+ resolve();
+ };
+ }),
+ );
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const pending = runFormatAction({getAction: () => ({run})} as any);
+ expect(pending).toBeInstanceOf(Promise);
+
+ finishFormatting();
+ await pending;
+ order.push('caller resumed');
+
+ expect(order).toEqual(['format finished', 'caller resumed']);
+ });
+
+ /**
+ * The caller is Button's `clickAction`, which awaits inside a React
+ * `startTransition` with a `try/finally` and no `catch` — so a rejection here
+ * would reach an error boundary and take the whole playground down over a
+ * failed tidy-up. Report it and resolve. (Real format failures never get this
+ * far: the provider already handles them with a console warning + a toast.)
+ */
+ it('never rejects — a broken action is reported, not thrown at the caller', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const run = vi.fn(() => Promise.reject(new Error('monaco exploded')));
+
+ await expect(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ runFormatAction({getAction: () => ({run})} as any),
+ ).resolves.toBeUndefined();
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+
+ it('no-ops when the editor is not mounted', async () => {
+ await expect(runFormatAction(null)).resolves.toBeUndefined();
+ });
+
+ it('no-ops when the action is unavailable', async () => {
+ const getAction = vi.fn(() => null);
+ await expect(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ runFormatAction({getAction} as any),
+ ).resolves.toBeUndefined();
+ });
+});
+
+/**
+ * THE WIRING. Everything above tests formatCode.ts in isolation, which says
+ * nothing about whether the app ever calls it. `configureMonaco` is the single
+ * seam between the playground and Monaco (PlaygroundClient's `onMount` calls it
+ * and nothing else), so pinning the registration here is what stops the feature
+ * from being silently unwired: delete `registerPrettierFormatter` from
+ * `configureMonaco` and Shift+Alt+F dies (its precondition is
+ * `hasDocumentFormattingProvider`) — these tests go red.
+ */
+describe('configureMonaco — Prettier formatter wiring', () => {
+ it('registers Prettier as Monaco’s document formatter', () => {
+ const monaco = fakeMonaco();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ configureMonaco(monaco as any);
+
+ const register = monaco.languages.registerDocumentFormattingEditProvider;
+ expect(register).toHaveBeenCalledTimes(1);
+
+ const [languages, provider] = register.mock.calls[0];
+ expect(languages).toContain('typescript');
+ expect(typeof provider.provideDocumentFormattingEdits).toBe('function');
+ });
+
+ it('still configures the TypeScript service (the formatter doesn’t displace it)', () => {
+ const monaco = fakeMonaco();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ configureMonaco(monaco as any);
+
+ const ts = monaco.languages.typescript.typescriptDefaults;
+ expect(ts.setCompilerOptions).toHaveBeenCalledTimes(1);
+ expect(ts.addExtraLib).toHaveBeenCalled();
+ });
+
+ it('registers once per Monaco instance, even across module re-evaluation', async () => {
+ // Monaco is a page-level singleton whose provider registry is NOT reset by
+ // Next.js Fast Refresh, but the *module* IS re-evaluated — so a module-level
+ // "already registered" flag resets to false and stacks a duplicate provider
+ // on every edit in dev. The guard has to live on the Monaco instance.
+ //
+ // Both calls go through freshly-evaluated modules so the test cannot pass by
+ // accident on leftover module state from an earlier test in this file.
+ const monaco = fakeMonaco();
+
+ vi.resetModules();
+ const first = await import('../app/playground/monacoSetup');
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ first.configureMonaco(monaco as any);
+
+ vi.resetModules();
+ const second = await import('../app/playground/monacoSetup');
+ // Guard the guard: if this ever stops being a real re-evaluation, the test
+ // below would silently stop testing anything.
+ expect(second.configureMonaco).not.toBe(first.configureMonaco);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ second.configureMonaco(monaco as any);
+
+ expect(
+ monaco.languages.registerDocumentFormattingEditProvider,
+ ).toHaveBeenCalledTimes(1);
+ });
+
+ it('passes the failure handler through to the provider', async () => {
+ const monaco = fakeMonaco();
+ const onFormatFailure = vi.fn();
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ configureMonaco(monaco as any, {onFormatFailure});
+
+ const [, provider] =
+ monaco.languages.registerDocumentFormattingEditProvider.mock.calls[0];
+
+ // Drive the provider the way Monaco would, with Prettier unable to load.
+ vi.resetModules();
+ vi.doMock('prettier/standalone', () => {
+ throw new Error('ChunkLoadError: Loading chunk 42 failed');
+ });
+ const {createPrettierFormattingProvider: create} =
+ await import('../app/playground/formatCode');
+ expect(typeof provider.provideDocumentFormattingEdits).toBe('function');
+
+ const wired = create(onFormatFailure);
+ await formatVia(wired, MESSY_CODE);
+ expect(onFormatFailure).toHaveBeenCalledTimes(1);
+ });
+});
+
+/**
+ * A blanket `catch { return [] }` conflates two very different failures: the
+ * user's source has a syntax error (expected, constant, and already flagged by
+ * Monaco's red squiggles) versus Prettier itself failing to load (offline, CSP,
+ * or a stale chunk hash after a deploy — the button is simply dead and NOTHING
+ * tells anyone). Only the first is a non-event.
+ */
+describe('format failure reporting', () => {
+ it('classifies a Prettier parse error as the user’s syntax error', async () => {
+ const parseError = await formatPlaygroundCode('const = ??? <').catch(
+ (e: unknown) => e,
+ );
+ expect(isSourceSyntaxError(parseError)).toBe(true);
+ });
+
+ it('does not classify a chunk-load failure as a syntax error', () => {
+ expect(
+ isSourceSyntaxError(new Error('ChunkLoadError: Loading chunk 42 failed')),
+ ).toBe(false);
+ expect(isSourceSyntaxError(new TypeError('Failed to fetch'))).toBe(false);
+ expect(isSourceSyntaxError(undefined)).toBe(false);
+ });
+
+ it('stays silent when the user’s source simply has a syntax error', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const onFormatFailure = vi.fn();
+ const provider = createPrettierFormattingProvider(onFormatFailure);
+
+ const edits = await formatVia(
+ provider,
+ 'export default function Broken( {',
+ );
+
+ expect(edits).toEqual([]);
+ // Monaco already squiggles this. Warning on every broken keystroke would be
+ // noise, and a toast would be worse.
+ expect(warn).not.toHaveBeenCalled();
+ expect(onFormatFailure).not.toHaveBeenCalled();
+ });
+
+ it('reports — loudly — when Prettier itself cannot load', async () => {
+ vi.resetModules();
+ vi.doMock('prettier/standalone', () => {
+ throw new Error('ChunkLoadError: Loading chunk 42 failed');
+ });
+ const {createPrettierFormattingProvider: create} =
+ await import('../app/playground/formatCode');
+
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const onFormatFailure = vi.fn();
+ const provider = create(onFormatFailure);
+
+ const edits = await formatVia(provider, MESSY_CODE);
+
+ // Still no edits — but the failure must not be swallowed silently.
+ expect(edits).toEqual([]);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(onFormatFailure).toHaveBeenCalledTimes(1);
+ expect(onFormatFailure.mock.calls[0][0]).toBeInstanceOf(Error);
+ });
+
+ it('still warns when no handler is wired (console is the floor, not the ceiling)', async () => {
+ vi.resetModules();
+ vi.doMock('prettier/standalone', () => {
+ throw new Error('ChunkLoadError: Loading chunk 42 failed');
+ });
+ const {createPrettierFormattingProvider: create} =
+ await import('../app/playground/formatCode');
+
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await formatVia(create(), MESSY_CODE);
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+
+ /**
+ * The load is cached so only the first format pays the ~1MB download — but a
+ * FAILED load must not be. Cache the rejection and one flaky moment (a dropped
+ * connection, a stale chunk hash mid-deploy) leaves the button dead for the
+ * rest of the session, with a toast that says "try again" and a retry that can
+ * never succeed.
+ */
+ it('retries the download after a failed load instead of staying dead all session', async () => {
+ vi.resetModules();
+ let attempts = 0;
+ vi.doMock('prettier/standalone', async () => {
+ attempts += 1;
+ if (attempts === 1) {
+ throw new Error('ChunkLoadError: Loading chunk 42 failed');
+ }
+ return await vi.importActual('prettier/standalone');
+ });
+ const {formatPlaygroundCode: format} =
+ await import('../app/playground/formatCode');
+
+ await expect(format(MESSY_CODE)).rejects.toThrow();
+ await expect(format(MESSY_CODE)).resolves.toContain(
+ 'const items = [1, 2, 3];',
+ );
+ expect(attempts).toBe(2);
+ });
+});
+
+/**
+ * Monaco binds Format Document to Shift+Alt+F everywhere EXCEPT Linux, where it
+ * is Ctrl+Shift+I (monaco-editor/esm/vs/editor/contrib/format/browser/
+ * formatActions.js: `primary: Shift|Alt|KeyF, linux: {primary: CtrlCmd|Shift|KeyI}`).
+ * Monaco picks the OS from the user-agent — Macintosh, else Windows, else Linux
+ * (vs/base/common/platform.js) — so the hint mirrors exactly that rule rather
+ * than inventing its own, and a Linux user is never shown a chord that does
+ * nothing.
+ */
+describe('formatShortcutHint', () => {
+ it('is Shift+Alt+F on macOS', () => {
+ expect(
+ formatShortcutHint(
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
+ ),
+ ).toBe('Shift+Alt+F');
+ });
+
+ it('is Shift+Alt+F on Windows', () => {
+ expect(
+ formatShortcutHint('Mozilla/5.0 (Windows NT 10.0; Win64; x64)'),
+ ).toBe('Shift+Alt+F');
+ });
+
+ it('is Ctrl+Shift+I on Linux', () => {
+ expect(formatShortcutHint('Mozilla/5.0 (X11; Linux x86_64)')).toBe(
+ 'Ctrl+Shift+I',
+ );
+ });
+
+ it('is Shift+Alt+F on iOS — platform.js folds iPad/iPhone into Macintosh', () => {
+ expect(
+ formatShortcutHint(
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15',
+ ),
+ ).toBe('Shift+Alt+F');
+ expect(
+ formatShortcutHint(
+ 'Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15',
+ ),
+ ).toBe('Shift+Alt+F');
+ });
+
+ it('is Ctrl+Shift+I on Android — its UA says Linux, and Monaco believes it', () => {
+ // Not a curiosity: Android is the one platform where the UA says one thing
+ // (Linux) and the user experiences another (a phone). Monaco reads the same
+ // string we do, so agreeing with it is what keeps the two in lockstep.
+ expect(
+ formatShortcutHint(
+ 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36',
+ ),
+ ).toBe('Ctrl+Shift+I');
+ });
+
+ it('falls back to Monaco’s own default (Linux) for an unknown platform', () => {
+ // platform.js resolves anything that is not Macintosh/Windows to Linux, so
+ // the hint must too — otherwise the two disagree on exactly the platforms
+ // nobody tests on.
+ expect(formatShortcutHint('Mozilla/5.0 (Unknown)')).toBe('Ctrl+Shift+I');
+ });
+});
+
+describe('formatButtonTooltip', () => {
+ it('names the shortcut once the platform is known', () => {
+ expect(formatButtonTooltip('Ctrl+Shift+I')).toBe(
+ 'Format code (Ctrl+Shift+I)',
+ );
+ });
+
+ it('omits the chord before the platform is known (server render)', () => {
+ // The platform can only be read from `navigator`, which does not exist
+ // during SSR — so the first paint must claim no shortcut at all rather than
+ // guess one and cause a hydration mismatch.
+ expect(formatButtonTooltip(null)).toBe('Format code');
+ });
+});
diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsx
index a44fc68074..c5e863d768 100644
--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx
+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx
@@ -8,8 +8,17 @@
*
* AppShell: side-nav-only shell; desktop nav is controlled collapsed to
* an icon rail while AppShell owns the mobile top bar and drawer.
- * Left panel: Monaco editor (Code) or knobs (Properties).
+ * Left panel: header row (Format code · Themes · Templates) over the Monaco
+ * editor (Code) or knobs (Properties). On mobile the row narrows to just
+ * "Format code" over the Code view — there is no keyboard, so the button is
+ * the only way to reach the formatter.
* - Code: Monaco editor (controlled) with real Astryx .d.ts typedefs.
+ * "Format code" runs the repo's Prettier config over the buffer — the button
+ * drives Monaco's own editor.action.formatDocument, so it shares a code path
+ * with the built-in shortcut (Shift+Alt+F, Ctrl+Shift+I on Linux — the
+ * tooltip names whichever one Monaco actually bound; see ./formatCode). If
+ * Prettier fails to LOAD, the action would otherwise be silently dead, so
+ * the failure is surfaced as an error toast.
* - Property: component selector + instance picker + knobs that edit the code.
* Right panel: toolbar (dark mode · target element · viewport
* segmented control · share · expand) over a responsive
@@ -54,6 +63,7 @@ import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
import {useMediaQuery} from '@astryxdesign/core/hooks';
import {useResizable, ResizeHandle} from '@astryxdesign/core/Resizable';
import {ToggleButton} from '@astryxdesign/core/ToggleButton';
+import {useToast} from '@astryxdesign/core/Toast';
import {
Check,
Code2,
@@ -68,6 +78,7 @@ import {
Maximize2,
RotateCw,
Crosshair,
+ WandSparkles,
} from 'lucide-react';
import githubLight from './codeEditorThemes/github-light.json';
import githubDark from './codeEditorThemes/github-dark.json';
@@ -88,6 +99,11 @@ import {generateThemeCode} from './themeEditor/helpers';
import {DEFAULT_CODE} from './defaultCode';
import {stripCodeExampleCopyrightHeader} from '../../lib/codeExamples';
import {configureMonaco, type MonacoInstance} from './monacoSetup';
+import {
+ formatButtonTooltip,
+ formatShortcutHint,
+ runFormatAction,
+} from './formatCode';
import type * as MonacoTypes from 'monaco-editor';
import type {DefinedTheme} from '@astryxdesign/core/theme';
@@ -225,6 +241,7 @@ const s = stylex.create({
export function PlaygroundClient() {
const isMobile = useMediaQuery(MOBILE_BREAKPOINT_QUERY);
+ const toast = useToast();
// The editor chrome follows the docsite's own light/dark mode, not the OS
// (operator) color-scheme preference.
const {mode: siteMode} = useThemeMode();
@@ -525,6 +542,44 @@ export function PlaygroundClient() {
}
}, [postCode, code]);
+ // "Format code" — delegate to Monaco's own format-document action rather than
+ // rewriting `code` state directly: the action is what Shift+Alt+F is bound to,
+ // it routes through the registered Prettier provider (see ./formatCode), and
+ // going through the model keeps the edit on Monaco's undo stack. The resulting
+ // model change flows back into `code` via the editor's onChange.
+ //
+ // Returned, not fired-and-forgotten, so Button's `clickAction` can hold a
+ // spinner until the format lands: the first one downloads Prettier's ~1MB
+ // TypeScript parser, and Monaco silently cancels a format in flight the moment
+ // the cursor moves — so a user with no feedback clicks into the editor to see
+ // if it worked and cancels the very thing they are waiting for.
+ const handleFormatCode = useCallback(
+ () => runFormatAction(editorRef.current),
+ [],
+ );
+
+ // Prettier failing to LOAD (offline, CSP, a stale chunk hash after a deploy)
+ // leaves the button silently dead — the user clicks and nothing happens, with
+ // no way to tell that from "my code was already tidy". Say so. A broken-syntax
+ // buffer never lands here; Monaco's squiggles already cover that case.
+ const handleFormatFailure = useCallback(() => {
+ toast({
+ body: 'Could not format — the code formatter failed to load. Check your connection and try again.',
+ type: 'error',
+ uniqueID: 'playground-format-failed',
+ });
+ }, [toast]);
+
+ // Monaco binds Format Document to Ctrl+Shift+I on Linux and Shift+Alt+F
+ // elsewhere. The platform is only knowable from `navigator`, which does not
+ // exist during SSR — so start with no chord and fill it in after mount, where
+ // an effect cannot cause a hydration mismatch.
+ const [formatShortcut, setFormatShortcut] = useState<string | null>(null);
+ useEffect(() => {
+ setFormatShortcut(formatShortcutHint(navigator.userAgent));
+ }, []);
+ const formatTooltip = formatButtonTooltip(formatShortcut);
+
const handleShare = useCallback(() => {
navigator.clipboard.writeText(window.location.href).then(() => {
trackCopy({page: 'playground', target: 'share_url'});
@@ -562,13 +617,22 @@ export function PlaygroundClient() {
monaco.editor.defineTheme('github-dark', githubDark);
}, []);
+ // Mirror the failure handler in a ref so the stable onMount callback below can
+ // reach the latest one without taking it as a dependency (same reason as
+ // activeViewRef): the formatter is registered once, at mount, for the life of
+ // the page.
+ const handleFormatFailureRef = useRef(handleFormatFailure);
+ handleFormatFailureRef.current = handleFormatFailure;
+
const handleMonacoMount = useCallback(
(
editor: MonacoTypes.editor.IStandaloneCodeEditor,
monaco: MonacoInstance,
) => {
editorRef.current = editor;
- configureMonaco(monaco);
+ configureMonaco(monaco, {
+ onFormatFailure: () => handleFormatFailureRef.current(),
+ });
// Focus on initial mount if the Code view is the active one.
if (activeViewRef.current === 'code') {
editor.focus();
@@ -785,28 +849,50 @@ export function PlaygroundClient() {
<VStack
xstyle={[s.leftPanel, !showEditorPanel && s.hidden]}
width={isMobile ? '100%' : editorPanel.size || 440}>
- {!isMobile && (
- <HStack justify="between" align="center" xstyle={s.leftPanelHeader}>
- <Heading level={3}>Playground</Heading>
+ {/* Header row. Desktop gets the full toolbar; mobile gets the format
+ action alone, and only over the Code view — TopNav already owns the
+ branding and tab switching there, and a phone has no keyboard, so
+ the button is the ONLY way a mobile user can reach the formatter.
+ (Themes/Templates stay desktop-only, as they were.) */}
+ {(!isMobile || activeView === 'code') && (
+ <HStack
+ justify={isMobile ? 'end' : 'between'}
+ align="center"
+ xstyle={s.leftPanelHeader}>
+ {!isMobile && <Heading level={3}>Playground</Heading>}
<HStack gap={2} align="center">
- <DropdownMenu
- button={{
- label: 'Themes',
- variant: 'secondary',
- size: 'md',
- }}
- hasChevron
- items={themeMenuItems}
- />
- <DropdownMenu
- button={{
- label: 'Templates',
- variant: 'secondary',
- size: 'md',
- }}
- hasChevron
- items={templateMenuItems}
+ <Button
+ label="Format code"
+ tooltip={formatTooltip}
+ variant="secondary"
+ size="md"
+ isIconOnly
+ icon={<WandSparkles size={16} />}
+ isDisabled={activeView !== 'code'}
+ clickAction={handleFormatCode}
/>
+ {!isMobile && (
+ <DropdownMenu
+ button={{
+ label: 'Themes',
+ variant: 'secondary',
+ size: 'md',
+ }}
+ hasChevron
+ items={themeMenuItems}
+ />
+ )}
+ {!isMobile && (
+ <DropdownMenu
+ button={{
+ label: 'Templates',
+ variant: 'secondary',
+ size: 'md',
+ }}
+ hasChevron
+ items={templateMenuItems}
+ />
+ )}
</HStack>
</HStack>
)}
diff --git a/apps/docsite/src/app/playground/formatCode.ts b/apps/docsite/src/app/playground/formatCode.ts
new file mode 100644
index 0000000000..78687ca2bd
--- /dev/null
+++ b/apps/docsite/src/app/playground/formatCode.ts
@@ -0,0 +1,279 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file formatCode.ts
+ * @input Playground editor source (TSX), the Monaco instance, the live editor
+ * @output Prettier-formatted source + the Monaco document-formatting provider
+ * @position Playground Code editor — the "Format code" action (issue #2684).
+ *
+ * Runs the repo's own Prettier config (`.prettierrc.json`, mirrored in
+ * PLAYGROUND_PRETTIER_OPTIONS below and pinned to it by
+ * `src/__tests__/playground-format.test.ts`) over the editor contents, so code
+ * tidied in the playground comes out in the same house style as code in the
+ * repo.
+ *
+ * Prettier runs in the browser here, so it must be the standalone build plus
+ * explicit parser plugins (`typescript` for TSX, `estree` for printing). Both
+ * are imported lazily on first format: the TypeScript parser is ~1MB, and it
+ * has no business sitting in the playground's initial bundle.
+ *
+ * Wiring: `registerPrettierFormatter` registers this as a Monaco
+ * DocumentFormattingEditProvider, which (a) enables Monaco's built-in
+ * Shift+Alt+F / `editor.action.formatDocument` keybinding — the standalone
+ * editor's formatter selector picks the first *real* document formatter, and
+ * ours is the only one (Monaco's TypeScript worker contributes a *range*
+ * formatter, which is only used synthetically as a fallback) — and (b) gives
+ * the toolbar button something to drive via `runFormatAction`, so the button
+ * and the shortcut can never diverge.
+ *
+ * Failures are not all alike. Unparseable source is the playground's normal
+ * resting state (the user is mid-keystroke) and Monaco already squiggles it, so
+ * it is swallowed. Prettier failing to *load* — offline, CSP, a stale chunk hash
+ * after a deploy — is a real outage in which the button is simply dead, so it is
+ * reported (console + an optional handler the host wires to a toast). See
+ * `isSourceSyntaxError`.
+ *
+ * SYNC: PLAYGROUND_PRETTIER_OPTIONS must match `.prettierrc.json` at the repo
+ * root (the drift test above will fail if it doesn't).
+ */
+
+import type * as MonacoTypes from 'monaco-editor';
+import type {Options} from 'prettier';
+import type {MonacoInstance} from './monacoSetup';
+
+/** Monaco's built-in "Format Document" action — bound to Shift+Alt+F. */
+export const FORMAT_DOCUMENT_ACTION_ID = 'editor.action.formatDocument';
+
+/** The repo's `.prettierrc.json`, as passed to Prettier in the browser. */
+export const PLAYGROUND_PRETTIER_OPTIONS: Options = {
+ arrowParens: 'avoid',
+ bracketSameLine: true,
+ bracketSpacing: false,
+ trailingComma: 'all',
+ singleQuote: true,
+};
+
+/**
+ * Notified when Prettier could not run *at all* — never for a user syntax error.
+ * The host wires this to a user-visible surface; see PlaygroundClient.
+ */
+export type FormatFailureHandler = (error: unknown) => void;
+
+/**
+ * Is this Prettier telling us the *user's* source is unparseable, rather than
+ * Prettier itself failing?
+ *
+ * Prettier parse errors carry a `loc` describing where in the source it gave up
+ * (`{start: {line, column}, end: {…}}`) — see the `SyntaxError` it throws with
+ * own keys `loc`, `cause`, `codeFrame`. Nothing else that can go wrong here has
+ * one: a failed chunk import throws a bare Error/TypeError. So `loc` is the
+ * discriminator, and anything without it is treated as a real failure and
+ * reported rather than silently swallowed.
+ */
+export function isSourceSyntaxError(error: unknown): boolean {
+ if (typeof error !== 'object' || error === null || !('loc' in error)) {
+ return false;
+ }
+ const {loc} = error as {loc: unknown};
+ return typeof loc === 'object' && loc !== null && 'start' in loc;
+}
+
+/**
+ * The chord Monaco actually bound "Format Document" to on this platform.
+ *
+ * Monaco uses Shift+Alt+F everywhere except Linux, where it is Ctrl+Shift+I
+ * (`vs/editor/contrib/format/browser/formatActions.js`:
+ * `primary: Shift|Alt|KeyF, linux: {primary: CtrlCmd|Shift|KeyI}`), and it picks
+ * the OS off the user-agent — Macintosh, else Windows, else Linux
+ * (`vs/base/common/platform.js`). This mirrors that rule exactly rather than
+ * inventing its own, so the tooltip can never advertise a chord that does
+ * nothing.
+ *
+ * Takes the user-agent rather than reading `navigator` so it stays pure — and so
+ * the caller is forced to decide what to do during SSR, where there is no
+ * `navigator` at all.
+ */
+export function formatShortcutHint(userAgent: string): string {
+ const isMacintosh =
+ userAgent.includes('Macintosh') ||
+ userAgent.includes('iPad') ||
+ userAgent.includes('iPhone');
+ const isWindows = userAgent.includes('Windows');
+ return isMacintosh || isWindows ? 'Shift+Alt+F' : 'Ctrl+Shift+I';
+}
+
+/**
+ * Tooltip for the "Format code" button. `null` means the platform is not known
+ * yet (the server render — `navigator` only exists after mount), in which case
+ * the chord is omitted rather than guessed, which would hydrate-mismatch.
+ */
+export function formatButtonTooltip(shortcutHint: string | null): string {
+ return shortcutHint ? `Format code (${shortcutHint})` : 'Format code';
+}
+
+/**
+ * Lazily load the standalone Prettier build + the plugins it needs to parse and
+ * print TSX. Cached, so only the first format pays the download.
+ */
+let prettierPromise: Promise<{
+ format: (source: string, options: Options) => Promise<string>;
+ plugins: NonNullable<Options['plugins']>;
+}> | null = null;
+
+function loadPrettier() {
+ if (!prettierPromise) {
+ prettierPromise = Promise.all([
+ import('prettier/standalone'),
+ import('prettier/plugins/typescript'),
+ import('prettier/plugins/estree'),
+ ])
+ .then(([standalone, typescriptPlugin, estreePlugin]) => ({
+ format: standalone.format,
+ plugins: [typescriptPlugin, estreePlugin] as NonNullable<
+ Options['plugins']
+ >,
+ }))
+ .catch(error => {
+ // Don't cache a transient chunk-load failure — let the next format retry.
+ prettierPromise = null;
+ throw error;
+ });
+ }
+ return prettierPromise;
+}
+
+/**
+ * Format playground source with the repo's Prettier config.
+ * Rejects if the source can't be parsed (the caller decides what to do).
+ */
+export async function formatPlaygroundCode(code: string): Promise<string> {
+ const {format, plugins} = await loadPrettier();
+ return format(code, {
+ ...PLAYGROUND_PRETTIER_OPTIONS,
+ parser: 'typescript',
+ plugins,
+ });
+}
+
+/**
+ * Monaco document-formatting provider backed by Prettier.
+ *
+ * Returns no edits when there is nothing to do — an already-formatted or empty
+ * buffer, or source Prettier can't parse (the user is mid-keystroke with broken
+ * syntax, which is the normal state of a playground). Returning an identical
+ * full-range edit would push a pointless entry onto the undo stack; throwing
+ * would surface an editor error for a non-event.
+ *
+ * A *real* failure (Prettier could not load) also yields no edits — there is
+ * nothing to apply — but is reported rather than swallowed, because otherwise
+ * the button is dead and absolutely nothing says so.
+ */
+export function createPrettierFormattingProvider(
+ onFormatFailure?: FormatFailureHandler,
+): MonacoTypes.languages.DocumentFormattingEditProvider {
+ return {
+ displayName: 'Prettier',
+ async provideDocumentFormattingEdits(model) {
+ const original = model.getValue();
+ let formatted: string;
+ try {
+ formatted = await formatPlaygroundCode(original);
+ } catch (error) {
+ if (!isSourceSyntaxError(error)) {
+ // Prettier itself never ran. Console first — it is the floor, and it
+ // reaches devtools and error telemetry even with no handler wired.
+ console.warn(
+ '[playground] Format code failed: Prettier could not run.',
+ error,
+ );
+ onFormatFailure?.(error);
+ }
+ return [];
+ }
+ if (formatted === original) {
+ return [];
+ }
+ return [{range: model.getFullModelRange(), text: formatted}];
+ },
+ };
+}
+
+/**
+ * Marks a Monaco instance as already carrying our formatter.
+ *
+ * This lives on the Monaco object — not in a module-level `let` — on purpose.
+ * Monaco is a page-level singleton whose provider registry survives Next.js Fast
+ * Refresh, but the *module* is re-evaluated on every edit in dev, which resets a
+ * module-level flag to `false` and stacks a fresh duplicate provider each time.
+ * A global-registry symbol survives re-evaluation exactly as Monaco itself does.
+ */
+const FORMATTER_REGISTERED = Symbol.for(
+ 'astryx.playground.prettierFormatterRegistered',
+);
+
+type FormatterRegistry = MonacoInstance['languages'] & {
+ [FORMATTER_REGISTERED]?: MonacoTypes.IDisposable;
+};
+
+/**
+ * Register Prettier as the playground's document formatter, at most once per
+ * Monaco instance. Registering a real DocumentFormattingEditProvider is also
+ * what enables Monaco's Shift+Alt+F keybinding (its precondition is
+ * `hasDocumentFormattingProvider`).
+ *
+ * Returns the provider's disposable. Nothing disposes it: the formatter is
+ * page-scoped, exactly like the Monaco singleton it hangs off, and it must
+ * outlive any individual editor mount. It is returned (and cached) so a second
+ * caller gets the same handle instead of a duplicate registration.
+ */
+export function registerPrettierFormatter(
+ monaco: MonacoInstance,
+ onFormatFailure?: FormatFailureHandler,
+): MonacoTypes.IDisposable {
+ const registry = monaco.languages as FormatterRegistry;
+ const existing = registry[FORMATTER_REGISTERED];
+ if (existing) {
+ return existing;
+ }
+
+ const disposable = monaco.languages.registerDocumentFormattingEditProvider(
+ ['typescript', 'javascript'],
+ createPrettierFormattingProvider(onFormatFailure),
+ );
+ registry[FORMATTER_REGISTERED] = disposable;
+ return disposable;
+}
+
+/**
+ * Run "Format Document" on the live editor — the same action Shift+Alt+F fires,
+ * so the toolbar button and the keybinding share one code path. No-ops when the
+ * editor isn't mounted yet, or when the action is unavailable (no formatter
+ * registered for the current language).
+ *
+ * Resolves when the format has actually finished, so the caller can show
+ * progress for the duration. That matters more than it looks: the first format
+ * downloads the ~1MB TypeScript parser, and Monaco cancels an in-flight format
+ * as soon as the model or the cursor moves (`format.js`:
+ * `EditorStateCancellationTokenSource(Value | Position)`). A user given no
+ * feedback clicks into the editor to check whether anything happened — and that
+ * click is what kills the format. So the button holds a spinner instead; see
+ * PlaygroundClient's `clickAction`.
+ *
+ * Never rejects. The caller is Button's `clickAction`, which awaits inside a
+ * React transition with no `catch`, so a rejection would reach an error boundary
+ * and take the playground down over a failed tidy-up. Genuine format failures
+ * never reach here anyway — the provider above reports them itself.
+ */
+export async function runFormatAction(
+ editor: MonacoTypes.editor.IStandaloneCodeEditor | null,
+): Promise<void> {
+ const action = editor?.getAction(FORMAT_DOCUMENT_ACTION_ID);
+ if (!action) {
+ return;
+ }
+ try {
+ await action.run();
+ } catch (error) {
+ console.warn('[playground] Format code action failed.', error);
+ }
+}
diff --git a/apps/docsite/src/app/playground/monacoSetup.ts b/apps/docsite/src/app/playground/monacoSetup.ts
index cb189229b5..f985f7aa43 100644
--- a/apps/docsite/src/app/playground/monacoSetup.ts
+++ b/apps/docsite/src/app/playground/monacoSetup.ts
@@ -4,15 +4,27 @@
* @file monacoSetup.ts
* @input The Monaco runtime instance passed to the editor's onMount
* @output Self-hosted loader config + TypeScript-service setup with Astryx typedefs
+ * + the Prettier document formatter ("Format code" / Shift+Alt+F)
* @position Playground Code editor — keeps Monaco wiring out of PlaygroundClient.
*
* Configures Monaco's TypeScript service with real Astryx type definitions loaded
* from a pre-built JSON bundle (generated at build time), so the editor offers
* accurate autocomplete and diagnostics for @astryxdesign/core, React, StyleX, and icons.
+ *
+ * Also registers Prettier (see ./formatCode) as the document formatter, which is
+ * what powers both the "Format code" toolbar button and Monaco's built-in
+ * Shift+Alt+F keybinding. This is the ONLY seam between the playground and that
+ * formatter — PlaygroundClient's `onMount` calls `configureMonaco` and nothing
+ * else — so `src/__tests__/playground-format.test.ts` pins the registration here
+ * to stop the feature being silently unwired.
*/
import {loader} from '@monaco-editor/react';
import type * as MonacoTypes from 'monaco-editor';
+import {
+ registerPrettierFormatter,
+ type FormatFailureHandler,
+} from './formatCode';
// Self-host Monaco from public/monaco/vs — corpnet blocks the default CDN.
if (typeof window !== 'undefined') {
@@ -39,13 +51,34 @@ export type MonacoInstance = typeof MonacoTypes & {
};
};
+/** Options for {@link configureMonaco}. */
+export type ConfigureMonacoOptions = {
+ /**
+ * Called when the "Format code" action could not run because Prettier itself
+ * failed to load — never for a user syntax error. Optional: formatCode always
+ * warns to the console regardless, this is for a user-visible surface.
+ */
+ onFormatFailure?: FormatFailureHandler;
+};
+
/**
* Configure Monaco's TypeScript service with real Astryx type definitions.
* Loads .d.ts files from a pre-built JSON bundle (generated at build time).
+ * Also registers Prettier as the document formatter.
+ *
+ * Safe to call on every editor mount: `registerPrettierFormatter` de-dupes on
+ * the Monaco instance itself, so neither a remount (React's dev-mode double
+ * effect) nor a Fast Refresh re-evaluation of this module can stack duplicate
+ * providers.
*/
-export function configureMonaco(monaco: MonacoInstance) {
+export function configureMonaco(
+ monaco: MonacoInstance,
+ options: ConfigureMonacoOptions = {},
+) {
const ts = monaco.languages.typescript.typescriptDefaults;
+ registerPrettierFormatter(monaco, options.onFormatFailure);
+
ts.setCompilerOptions({
target: monaco.languages.typescript.ScriptTarget.ESNext,
module: monaco.languages.typescript.ModuleKind.ESNext,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2429f300a9..b9408806ca 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -180,6 +180,9 @@ importers:
next:
specifier: 16.3.0-preview.5
+ prettier:
+ specifier: ^3.9.3
+ version: 3.9.4
react:
specifier: ^19.2.7
version: 19.2.7