From f6346ad3591d27cbf359f375d71708835c642ee9 Mon Sep 17 00:00:00 2001 From: Aqib Nawab Date: Wed, 18 Nov 2026 11:10:56 +0500 Subject: [PATCH] Add the HTML and CSS preview block A lesson can write a fenced `preview` block and the reader draws it as a small browser window, with the code beside it (split) or hidden (preview). Optional sliders and dropdowns fill {{name}} placeholders in the HTML and CSS, so a learner can change one value and see the result and the code change together. The example is drawn in an iframe with sandbox="" and a default-src 'none' content policy, with links switched off. The source is refused when it contains script tags, event attributes, embedded content, link, meta, base, @import, javascript: addresses or web addresses. An invalid fence fails when the course is validated. Adds the spec and remark plugin (shared), the HtmlPreview block (web and desktop through the shared lesson blocks), the allowlist entry, the course source validator hook, unit tests, and a short doc. --- docs/html-preview-block.md | 39 ++++ frontend/src/shared/html-preview/spec.ts | 184 ++++++++++++++++++ .../src/shared/mdx/component-allowlist.ts | 1 + frontend/src/shared/mdx/reader-plugins.ts | 3 +- .../src/shared/mdx/remark-html-preview.ts | 37 ++++ frontend/tests/unit/mdx/html-preview.test.ts | 41 ++++ packages/learning-ui/contracts.json | 3 +- .../learn/content-blocks/html-preview.tsx | 183 +++++++++++++++++ .../components/learn/content-blocks/index.ts | 1 + packages/learning-ui/src/lesson-blocks.tsx | 3 +- .../src/shared/html-preview/spec.ts | 184 ++++++++++++++++++ server/scripts/validate-course-source.ts | 3 +- server/src/shared/html-preview/spec.ts | 183 +++++++++++++++++ server/src/shared/mdx/component-allowlist.ts | 1 + server/src/shared/mdx/reader-plugins.ts | 3 +- server/src/shared/mdx/remark-html-preview.ts | 36 ++++ .../unit/shared/mdx/html-preview.test.ts | 135 +++++++++++++ 17 files changed, 1035 insertions(+), 5 deletions(-) create mode 100644 docs/html-preview-block.md create mode 100644 frontend/src/shared/html-preview/spec.ts create mode 100644 frontend/src/shared/mdx/remark-html-preview.ts create mode 100644 frontend/tests/unit/mdx/html-preview.test.ts create mode 100644 packages/learning-ui/src/components/learn/content-blocks/html-preview.tsx create mode 100644 packages/learning-ui/src/shared/html-preview/spec.ts create mode 100644 server/src/shared/html-preview/spec.ts create mode 100644 server/src/shared/mdx/remark-html-preview.ts create mode 100644 server/tests/unit/shared/mdx/html-preview.test.ts diff --git a/docs/html-preview-block.md b/docs/html-preview-block.md new file mode 100644 index 000000000..57ea6ee21 --- /dev/null +++ b/docs/html-preview-block.md @@ -0,0 +1,39 @@ +# HTML and CSS preview block + +A lesson can show real HTML and CSS in a window that looks like a small browser, with the code beside it or hidden. Write a fenced block with the language `preview`. + +```` +```preview +title: Padding and margin +mode: split +height: 260 +address: practice-page.html +slider: pad | Padding | 0 | 60 | 2 | 20 | px +select: shape | Corners | 0px,8px,24px | 8px +---html +

Hello

+---css +.card { padding: {{pad}}; border-radius: {{shape}}; } +``` +```` + +| Setting | Meaning | +|---|---| +| `mode: split` | Code on the left, browser on the right, with a Hide code button. | +| `mode: preview` | The browser alone, no code. | +| `height` | Browser height in pixels, 120 to 700 (default 280). | +| `address` | Text in the fake address bar. | +| `slider: name \| label \| min \| max \| step \| start \| unit` | A slider. `{{name}}` in the HTML or CSS becomes the value plus the unit. | +| `select: name \| label \| a,b,c \| start` | A dropdown. `{{name}}` becomes the chosen option. | +| `---html`, `---css` | The page body and the style sheet. The CSS is shown as `styles.css`. | + +## How it works + +- `server/src/shared/html-preview/spec.ts` parses and checks the fence. `server/src/shared/mdx/remark-html-preview.ts` turns it into an `HtmlPreview` element. An invalid fence throws, so it is caught when the course is validated or compiled. +- `packages/learning-ui/src/components/learn/content-blocks/html-preview.tsx` draws it, in the web reader and the desktop app. + +## Safety + +The example is read-only author content, never learner input. It is drawn in an iframe with `sandbox=""` (no scripts, no forms, no popups, no same-origin access), a content policy of `default-src 'none'` (no network), and links switched off. The source is also refused when it contains script tags, `on...=` attributes, iframe, link, meta, base, `@import`, `javascript:` addresses, or web addresses in `src`, `href` or `url()`. Images must be `data:` images. The check runs when the course is parsed and again when the block is drawn. + +Not covered: the frame is its own small window, so `vh`, `vw`, `position: fixed` and `position: sticky` behave as in a real browser inside it. It cannot show the page `title` or `head` content. diff --git a/frontend/src/shared/html-preview/spec.ts b/frontend/src/shared/html-preview/spec.ts new file mode 100644 index 000000000..4484db170 --- /dev/null +++ b/frontend/src/shared/html-preview/spec.ts @@ -0,0 +1,184 @@ +// GENERATED from server/src/shared — do not edit here. Run `pnpm sync-shared` in server/. +/** + * Contract for the HTML and CSS preview block (the ```preview fence in a lesson). + * + * The author writes read-only HTML and CSS. The reader draws it in a sandboxed + * frame that looks like a small browser window, next to the code or on its own. + * This file is pure: the remark plugin and the component both use it, so the two + * always agree on what a valid example is. + * + * Fence format: + * + * ```preview + * title: Same words, with CSS + * mode: split (split = code beside the browser, preview = browser only) + * height: 280 (browser height in pixels, 120 to 700) + * address: practice-page (text shown in the address bar) + * slider: pad | Padding | 0 | 60 | 2 | 20 | px + * select: display | display | block,inline,none | block + * ---html + *

Hello

+ * ---css + * h1 { padding: {{pad}}; } + * ``` + * + * A control name used as {{name}} in the HTML or CSS is replaced by the current + * value, so the learner sees real code change when they move a control. + */ + +export type PreviewMode = "split" | "preview"; + +export type PreviewControl = + | { type: "range"; name: string; label: string; min: number; max: number; step: number; value: number; unit: string } + | { type: "select"; name: string; label: string; options: string[]; value: string }; + +export type HtmlPreviewSpec = { + title: string; + mode: PreviewMode; + height: number; + address: string; + html: string; + css: string; + controls: PreviewControl[]; +}; + +export const PREVIEW_MIN_HEIGHT = 120; +export const PREVIEW_MAX_HEIGHT = 700; +export const PREVIEW_DEFAULT_HEIGHT = 280; +export const PREVIEW_MAX_SOURCE = 12000; + +const NAME = /^[a-z][a-z0-9-]{0,23}$/; + +/** What the preview frame will refuse to draw. The sandbox and the page policy block these too. */ +const FORBIDDEN: Array<[RegExp, string]> = [ + [/<\s*script/i, "script tags"], + [/<\s*(iframe|object|embed|frame|frameset|applet)/i, "embedded content tags"], + [/<\s*(link|meta|base)\b/i, "link, meta and base tags"], + [/\son[a-z]+\s*=/i, "event handler attributes such as onclick"], + [/javascript\s*:/i, "javascript: addresses"], + [/@import/i, "@import"], + [/expression\s*\(/i, "CSS expressions"], + [/(?:src|href|action|poster|srcset)\s*=\s*["']?\s*(?:https?:)?\/\//i, "web addresses in src or href"], + [/url\(\s*["']?\s*(?:https?:)?\/\//i, "web addresses in CSS url()"], + [/url\(\s*["']?\s*(?!data:image\/)(?!#)[a-z]+:/i, "url() addresses other than data images"], +]; + +export function findForbiddenPreviewContent(source: string): string | null { + for (const [pattern, label] of FORBIDDEN) { + if (pattern.test(source)) return label; + } + return null; +} + +function parseNumber(value: string, label: string): number { + const n = Number(value.trim()); + if (!Number.isFinite(n)) throw new Error(`preview control "${label}": "${value.trim()}" is not a number`); + return n; +} + +function parseControl(kind: "slider" | "select", rest: string): PreviewControl { + const parts = rest.split("|").map((part) => part.trim()); + const name = parts[0] ?? ""; + if (!NAME.test(name)) throw new Error(`preview control name "${name}" must be lowercase letters, digits or hyphens, starting with a letter`); + if (kind === "slider") { + if (parts.length < 6) throw new Error(`preview slider "${name}" needs: name | label | min | max | step | start | unit`); + const min = parseNumber(parts[2]!, name); + const max = parseNumber(parts[3]!, name); + const step = parseNumber(parts[4]!, name); + const value = parseNumber(parts[5]!, name); + if (!(min < max) || step <= 0 || value < min || value > max) throw new Error(`preview slider "${name}" has an invalid range`); + return { type: "range", name, label: parts[1] || name, min, max, step, value, unit: parts[6] ?? "" }; + } + if (parts.length < 4) throw new Error(`preview select "${name}" needs: name | label | option1,option2 | start`); + const options = parts[2]!.split(",").map((option) => option.trim()).filter(Boolean); + if (options.length < 2 || options.length > 8) throw new Error(`preview select "${name}" needs 2 to 8 options`); + const value = parts[3]!; + if (!options.includes(value)) throw new Error(`preview select "${name}" start value "${value}" is not one of its options`); + return { type: "select", name, label: parts[1] || name, options, value }; +} + +/** Parse the body of a ```preview fence. Throws an Error with a plain message when it is invalid. */ +export function parseHtmlPreviewFence(body: string): HtmlPreviewSpec { + const lines = body.replace(/\r\n/g, "\n").split("\n"); + const spec: HtmlPreviewSpec = { title: "", mode: "split", height: PREVIEW_DEFAULT_HEIGHT, address: "index.html", html: "", css: "", controls: [] }; + let section: "head" | "html" | "css" = "head"; + const html: string[] = []; + const css: string[] = []; + for (const line of lines) { + const marker = /^---\s*(html|css)\s*$/i.exec(line); + if (marker) { + section = marker[1]!.toLowerCase() as "html" | "css"; + continue; + } + if (section === "html") html.push(line); + else if (section === "css") css.push(line); + else { + if (!line.trim()) continue; + const m = /^([a-z]+)\s*:\s*(.*)$/i.exec(line.trim()); + if (!m) throw new Error(`preview: cannot read the line "${line.trim()}" above ---html`); + const key = m[1]!.toLowerCase(); + const value = m[2]!.trim(); + if (key === "title") spec.title = value; + else if (key === "address") spec.address = value.slice(0, 60); + else if (key === "mode") { + if (value !== "split" && value !== "preview") throw new Error(`preview mode must be "split" or "preview", not "${value}"`); + spec.mode = value; + } else if (key === "height") { + const n = parseNumber(value, "height"); + spec.height = Math.min(PREVIEW_MAX_HEIGHT, Math.max(PREVIEW_MIN_HEIGHT, Math.round(n))); + } else if (key === "slider" || key === "select") spec.controls.push(parseControl(key, value)); + else throw new Error(`preview: unknown setting "${key}"`); + } + } + spec.html = html.join("\n").replace(/^\n+|\s+$/g, ""); + spec.css = css.join("\n").replace(/^\n+|\s+$/g, ""); + if (!spec.html) throw new Error("preview needs an ---html section"); + if (spec.html.length + spec.css.length > PREVIEW_MAX_SOURCE) throw new Error(`preview source is longer than ${PREVIEW_MAX_SOURCE} characters`); + const names = new Set(); + for (const control of spec.controls) { + if (names.has(control.name)) throw new Error(`preview control "${control.name}" is defined twice`); + names.add(control.name); + } + const bad = findForbiddenPreviewContent(`${spec.html}\n${spec.css}`); + if (bad) throw new Error(`preview cannot contain ${bad}`); + return spec; +} + +export function previewDefaults(controls: PreviewControl[]): Record { + const values: Record = {}; + for (const control of controls) { + values[control.name] = control.type === "range" ? String(control.value) : control.value; + } + return values; +} + +export function controlText(control: PreviewControl, value: string): string { + return control.type === "range" ? `${value}${control.unit}` : value; +} + +/** Replace {{name}} with the current control value (with its unit for sliders). */ +export function fillPreviewTemplate(source: string, controls: PreviewControl[], values: Record): string { + return source.replace(/\{\{\s*([a-z][a-z0-9-]*)\s*\}\}/g, (match, name: string) => { + const control = controls.find((candidate) => candidate.name === name); + if (!control) return match; + const value = values[name] ?? (control.type === "range" ? String(control.value) : control.value); + return controlText(control, value); + }); +} + +const POLICY = + "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; form-action 'none'; base-uri 'none'"; + +/** The complete document drawn inside the sandboxed frame. */ +export function buildPreviewDocument(html: string, css: string): string { + return [ + "", + '', + ``, + '', + '', + "", + ``, + `${html}`, + ].join(""); +} diff --git a/frontend/src/shared/mdx/component-allowlist.ts b/frontend/src/shared/mdx/component-allowlist.ts index f7320b7b3..2f1e1110f 100644 --- a/frontend/src/shared/mdx/component-allowlist.ts +++ b/frontend/src/shared/mdx/component-allowlist.ts @@ -52,6 +52,7 @@ export const MDX_COMPONENT_NAMES = [ "TraceRequest", "TraceStep", "InteractiveCanvas", + "HtmlPreview", "Lab", "EcosystemGallery", "GoDeeper", diff --git a/frontend/src/shared/mdx/reader-plugins.ts b/frontend/src/shared/mdx/reader-plugins.ts index dd0fcb5e1..fffb1083f 100644 --- a/frontend/src/shared/mdx/reader-plugins.ts +++ b/frontend/src/shared/mdx/reader-plugins.ts @@ -10,5 +10,6 @@ import { remarkChecklist } from "./remark-checklist"; import { remarkLearningLog } from "./remark-learning-log"; import { remarkDiagram } from "./remark-diagram"; import { remarkMermaid } from "./remark-mermaid"; +import { remarkHtmlPreview } from "./remark-html-preview"; -export const readerRemarkPlugins = [remarkChecklist, remarkLearningLog, remarkDiagram, remarkMermaid]; +export const readerRemarkPlugins = [remarkChecklist, remarkLearningLog, remarkHtmlPreview, remarkDiagram, remarkMermaid]; diff --git a/frontend/src/shared/mdx/remark-html-preview.ts b/frontend/src/shared/mdx/remark-html-preview.ts new file mode 100644 index 000000000..c76dca155 --- /dev/null +++ b/frontend/src/shared/mdx/remark-html-preview.ts @@ -0,0 +1,37 @@ +// GENERATED from server/src/shared — do not edit here. Run `pnpm sync-shared` in server/. +/** + * Remark plugin that turns ```preview fences into + * nodes in the MDX + * tree. The fence format is documented in ../html-preview/spec.ts. An invalid + * fence throws, so the mistake is caught when the course is imported or + * compiled and never reaches a learner. + */ +import type { Code, Root } from "mdast"; +import { visit } from "unist-util-visit"; +import { parseHtmlPreviewFence } from "../html-preview/spec"; + +export function remarkHtmlPreview(): (tree: Root) => void { + return (tree: Root) => { + visit(tree, "code", (node: Code, index, parent) => { + if (node.lang !== "preview") return; + if (!parent || index == null) return; + const spec = parseHtmlPreviewFence(node.value); + const attribute = (name: string, value: string) => ({ type: "mdxJsxAttribute", name, value }); + const mdxNode: Record = { + type: "mdxJsxFlowElement", + name: "HtmlPreview", + attributes: [ + attribute("title", spec.title), + attribute("mode", spec.mode), + attribute("height", String(spec.height)), + attribute("address", spec.address), + attribute("html", spec.html), + attribute("css", spec.css), + attribute("controls", JSON.stringify(spec.controls)), + ], + children: [], + }; + parent.children.splice(index, 1, mdxNode as unknown as Code); + }); + }; +} diff --git a/frontend/tests/unit/mdx/html-preview.test.ts b/frontend/tests/unit/mdx/html-preview.test.ts new file mode 100644 index 000000000..f31a4af30 --- /dev/null +++ b/frontend/tests/unit/mdx/html-preview.test.ts @@ -0,0 +1,41 @@ +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { HtmlPreview } from "@buildment/learning-ui/components/learn/content-blocks/html-preview"; +import { sharedLessonBlocks } from "@buildment/learning-ui/lesson-blocks"; + +const controls = JSON.stringify([ + { type: "range", name: "pad", label: "Padding", min: 0, max: 60, step: 2, value: 20, unit: "px" }, +]); + +const draw = (props: Parameters[0]) => renderToStaticMarkup(createElement(HtmlPreview, props)); + +describe("HtmlPreview", () => { + it("is registered as a lesson block", () => { + expect(sharedLessonBlocks.HtmlPreview).toBe(HtmlPreview); + }); + + it("draws the code beside a sandboxed browser frame", () => { + const html = draw({ title: "Padding", mode: "split", height: "240", address: "page.html", html: "

Hello

", css: "p { padding: {{pad}}; }", controls }); + expect(html).toContain(" { + const html = draw({ title: "Look", mode: "preview", html: "

Hello

" }); + expect(html).toContain(" { + const html = draw({ title: "Bad", html: "" }); + expect(html).not.toContain(" +
+ {name} +
+ +
+          {code}
+        
+
+ + ); +} + +/** + * A read-only HTML and CSS example drawn in a sandboxed frame that looks like a + * small browser window. The frame has no scripts, no network and no way to + * leave the page. The code is shown beside it (mode "split") or hidden (mode + * "preview"). Optional controls change a value in the code and redraw it. + */ +export function HtmlPreview({ title, mode: modeProp, height: heightProp, address, html = "", css = "", controls: controlsText }: HtmlPreviewProps) { + const mode: PreviewMode = modeProp === "preview" ? "preview" : "split"; + const controls = useMemo(() => readControls(controlsText), [controlsText]); + const [values, setValues] = useState>(() => previewDefaults(controls)); + const [showCode, setShowCode] = useState(true); + const baseId = useId(); + + const rawHeight = Number(heightProp); + const height = Number.isFinite(rawHeight) + ? Math.min(PREVIEW_MAX_HEIGHT, Math.max(PREVIEW_MIN_HEIGHT, Math.round(rawHeight))) + : PREVIEW_DEFAULT_HEIGHT; + + const shownHtml = fillPreviewTemplate(html, controls, values); + const shownCss = fillPreviewTemplate(css, controls, values); + const problem = findForbiddenPreviewContent(`${shownHtml}\n${shownCss}`); + const srcDoc = useMemo(() => (problem ? "" : buildPreviewDocument(shownHtml, shownCss)), [problem, shownHtml, shownCss]); + + const codeVisible = mode === "split" && showCode; + const label = title || "Browser preview"; + + return ( +
+
+
+

Example

+ {title ?

{title}

: null} +
+ {mode === "split" ? ( + + ) : null} +
+ +
+ {codeVisible ? ( +
+ + {shownCss ? : null} +
+ ) : null} + +
+
+ + {problem ? ( +

+ This example cannot be shown because it contains {problem}. +

+ ) : ( + ", "embedded content tags"], + ['', "link, meta and base tags"], + ['

', "event handler attributes such as onclick"], + ['x', "javascript: addresses"], + ["", "@import"], + ['', "web addresses in src or href"], + ['

', "web addresses in CSS url()"], + ])("refuses %s", (source, label) => { + expect(findForbiddenPreviewContent(source)).toBe(label); + }); + + it("allows plain markup, anchors and data images", () => { + expect(findForbiddenPreviewContent('xx

y

')).toBeNull(); + }); +}); + +describe("templates and the frame document", () => { + const { controls } = parseHtmlPreviewFence(FENCE); + + it("fills {{name}} with the current value and the slider unit", () => { + expect(fillPreviewTemplate("a {{pad}} b {{shape}} c {{other}}", controls, { pad: "30", shape: "24px" })).toBe("a 30px b 24px c {{other}}"); + expect(previewDefaults(controls)).toEqual({ pad: "20", shape: "8px" }); + }); + + it("builds a document with a locked-down policy and an escaped style end tag", () => { + const doc = buildPreviewDocument("

x

", "p{color:red}"); + expect(doc).toContain("Content-Security-Policy"); + expect(doc).toContain("default-src 'none'"); + expect(doc).toContain("<\\/style>