openmaic-custom/tests/lib/utils/iframe.test.ts
wyuc dcf8a63333
fix(generation): make outline type changes take effect (interactive/PBL no longer downgraded to slide) (#772)
* feat(generation): changeOutlineType total constructor for valid type switches

Switching a scene outline's type in the editor only flipped `type` and left
the new type without its required config, so applyOutlineFallbacks silently
downgraded interactive/pbl back to slide. changeOutlineType returns a new
outline that strips foreign per-type config and seeds the target type's
required config from the shared fields, valid by construction.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* i18n(generation): keys for interactive widget kind and PBL project config

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(editor): make outline type changes take effect with config forms

TypePill now builds a valid outline via changeOutlineType (replace, not
partial-merge) so a type switch drops stale config and seeds the new type's
required config — no longer silently downgraded to slide by applyOutlineFallbacks.
Adds InteractiveConfigDisclosure (widget kind + concept) and PblConfigDisclosure
(topic / description / target skills), mirroring QuizConfigDisclosure, so users
can configure interactive and PBL scenes that previously had no input UI.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): move type-specific config under the type pill

The quiz/interactive/PBL config disclosure rendered as a detached chip at the
bottom-left of the card, reading like a stray key point. Pin it to the
bottom-right of the key-points row instead, so it sits directly under the
TypePill it configures (type top-right -> its config bottom-right, same edge),
with key points flowing on the left.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): cascade type config as a connected segment left of the type pill

Replace the standalone config chip with a cascading control in the header: the
type-specific config (quiz count / interactive widget kind / PBL project) renders
as a themed segment joined to the left of the TypePill, the two clipped into one
rounded pill split by a hairline divider. Reads as a single 'config › type'
cascade and groups the config with the selector it refines.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): address cross-review — preserve widget config, drop stale fields

- changeOutlineType: preserve an existing procedural-skill widget config
  instead of replacing it with a seeded simulation (codex P2 — task-engine
  fields were silently dropped on Interactive re-select).
- InteractiveConfigDisclosure.setWidgetType: reset widgetOutline to the shared
  concept only, so switching widget kind drops the previous kind's fields
  (claude P2 — language/gameType/etc. leaked across kinds).
- i18n locale-coverage test now also checks ko-KR and pt-BR.
- Drop a redundant WidgetType cast; add tests for procedural-skill preservation
  and pbl targetSkills dedupe/cap.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): round 2 cross-review nits — procedural-skill label + skill a11y

- InteractiveConfigDisclosure: when an outline carries a preserved
  procedural-skill widget, surface it as the current (selected) kind with its
  own label instead of mislabeling it 'Simulation', and make a same-kind
  re-select a no-op so its task-engine fields are never silently clobbered.
- PBL target-skill remove button uses a dedicated removeSkill aria-label.
- Add widgetProceduralSkill / removeSkill i18n keys (8 locales) + test coverage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(generation): make re-selecting the current outline type a no-op

changeOutlineType rebuilt the outline on every type-menu click, so re-selecting
the already-current type dropped fields it doesn't re-seed — legacy
interactiveConfig, or a partial pblConfig whose projectTopic is empty — turning a
harmless click into data loss. Short-circuit same-type selections to return the
outline untouched (codex P2).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(format): prettier --write files left unformatted on main

These 14 agent/edit files (not part of this PR's feature) fail the repo-wide
`prettier . --check` in the required Lint job — they landed on main unformatted,
turning main's CI (and therefore this PR after a branch update) red. Formatting
them here unblocks the required check; pure formatting, no logic changes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(lint): suppress intentional set-state-in-effect in reasoning timer

The reasoning timer does a deliberate one-shot setState in its effect to show
the right elapsed value before the first 1s interval tick. main's CI fails the
required Lint job on the new react-hooks/set-state-in-effect rule here; suppress
it with a justification (no behavior change). Unblocks the required check.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 17:48:07 +08:00

137 lines
6.0 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { patchHtmlForIframe } from '@/lib/utils/iframe';
describe('patchHtmlForIframe', () => {
it('injects the storage shim and sizing CSS after <head>', () => {
const out = patchHtmlForIframe(
'<!DOCTYPE html><html><head><title>t</title></head><body></body></html>',
);
expect(out).toContain('data-iframe-storage-shim');
expect(out).toContain('data-iframe-patch');
});
it('runs the storage shim before the page scripts', () => {
const html =
'<!DOCTYPE html><html><head><script>window.__x = localStorage.getItem("k");</script></head><body></body></html>';
const out = patchHtmlForIframe(html);
// The shim must appear before the page's own <script> so storage is safe by then.
expect(out.indexOf('data-iframe-storage-shim')).toBeLessThan(out.indexOf('window.__x'));
});
it('the shim provides a working in-memory storage when the real one throws', () => {
// Execute the injected shim against a fake window whose localStorage getter
// throws (mirroring a null-origin sandboxed iframe), then assert the shim
// installed a usable in-memory store.
const out = patchHtmlForIframe('<html><head></head><body></body></html>');
const shim = out.match(/<script data-iframe-storage-shim>([\s\S]*?)<\/script>/)?.[1];
expect(shim).toBeTruthy();
const win: Record<string, unknown> = {};
Object.defineProperty(win, 'localStorage', {
configurable: true,
get() {
throw new Error('sandboxed');
},
});
Object.defineProperty(win, 'sessionStorage', {
configurable: true,
get() {
throw new Error('sandboxed');
},
});
new Function('window', shim as string)(win);
const ls = win.localStorage as Storage;
expect(ls.getItem('missing')).toBeNull();
ls.setItem('a', '1');
expect(ls.getItem('a')).toBe('1');
expect(ls.length).toBe(1);
ls.removeItem('a');
expect(ls.getItem('a')).toBeNull();
});
it('falls back to prepending when there is no <head>', () => {
const out = patchHtmlForIframe('<div>no head</div>');
// The error-capture shim is injected first, so it leads the prepended block.
expect(out.startsWith('\n<script data-iframe-error-shim>')).toBe(true);
});
it('injects the error-capture shim before the storage shim and page scripts', () => {
const html = '<!DOCTYPE html><html><head><script>boom()</script></head><body></body></html>';
const out = patchHtmlForIframe(html);
expect(out).toContain('data-iframe-error-shim');
// error shim runs first → before storage shim → before page scripts, so it
// catches errors from everything that follows.
expect(out.indexOf('data-iframe-error-shim')).toBeLessThan(
out.indexOf('data-iframe-storage-shim'),
);
expect(out.indexOf('data-iframe-storage-shim')).toBeLessThan(out.indexOf('boom()'));
});
it('the error shim posts runtime errors (onerror / resource / rejection / console.error) to the parent', () => {
const out = patchHtmlForIframe('<html><head></head><body></body></html>');
const shim = out.match(/<script data-iframe-error-shim>([\s\S]*?)<\/script>/)?.[1];
expect(shim).toBeTruthy();
const posts: Array<[Record<string, unknown>, string]> = [];
const handlers: Record<string, (e: unknown) => void> = {};
const win = {
parent: { postMessage: (m: Record<string, unknown>, o: string) => posts.push([m, o]) },
addEventListener: (t: string, cb: (e: unknown) => void) => {
handlers[t] = cb;
},
console: { error: (..._args: unknown[]) => {} },
};
new Function('window', shim as string)(win);
handlers.error({ message: 'JSON.parse boom', filename: 'p.html', lineno: 12 });
expect(posts[0][0]).toMatchObject({ kind: 'runtime-error', errorKind: 'error' });
expect(posts[0][0].message).toContain('JSON.parse boom');
expect(posts[0][1]).toBe('*');
handlers.error({ target: { src: 'https://cdn/katex.js' } });
expect(String(posts[1][0].message)).toContain('Failed to load resource');
handlers.unhandledrejection({ reason: { message: 'rej' } });
expect(posts[2][0]).toMatchObject({ errorKind: 'unhandledrejection' });
win.console.error('console boom');
expect(posts[3][0]).toMatchObject({ errorKind: 'console.error' });
expect(String(posts[3][0].message)).toContain('console boom');
});
it('the error shim buffers errors and re-emits them on a parent replay request', () => {
// Guards the subscribe-after-insert race: a page that throws synchronously
// while srcDoc parses may post before the parent subscribes. The shim must
// re-emit the whole buffer when the parent asks, so nothing is lost.
const out = patchHtmlForIframe('<html><head></head><body></body></html>');
const shim = out.match(/<script data-iframe-error-shim>([\s\S]*?)<\/script>/)?.[1];
const posts: Array<[Record<string, unknown>, string]> = [];
const handlers: Record<string, (e: unknown) => void> = {};
const win = {
parent: { postMessage: (m: Record<string, unknown>, o: string) => posts.push([m, o]) },
addEventListener: (t: string, cb: (e: unknown) => void) => {
handlers[t] = cb;
},
console: { error: (..._args: unknown[]) => {} },
};
new Function('window', shim as string)(win);
// Two errors fire "before the parent subscribed".
handlers.error({ message: 'first boom' });
handlers.unhandledrejection({ reason: { message: 'second boom' } });
expect(posts).toHaveLength(2);
// Parent now subscribes and requests a replay.
handlers.message({ data: { __maicErrorReplayRequest: true } });
expect(posts).toHaveLength(4);
expect(String(posts[2][0].message)).toContain('first boom');
expect(String(posts[3][0].message)).toContain('second boom');
expect(posts[2][0]).toMatchObject({ kind: 'runtime-error', errorKind: 'error' });
// An unrelated message must NOT trigger a replay.
handlers.message({ data: { foo: 1 } });
expect(posts).toHaveLength(4);
});
});