diff --git a/TODO.md b/TODO.md new file mode 100644 index 000000000..1ffe7dc4e --- /dev/null +++ b/TODO.md @@ -0,0 +1,8 @@ +# Void View + +- Prepare templates for every component in production storage, with a renderer lookup at runtime. Keep page output selective: include only templates reachable from the dynamic components actually rendered on that page, including descendants that may appear on later renders. The prototype keeps the prepared templates in the generated server module. +- Store compiled source for dynamic components and their transitive dynamic children as separate chunks. Evaluate assembling page bundles on demand, preparing bundles during rendering, or another delivery strategy later. The prototype selects compiled source fragments and emits them inline during SSR; a static page needs neither View templates nor View JavaScript. + +## View styling TODO + +`@void/view` bundles static component styles and renders interpolated styles inside each Web Component instance. Instance styles currently duplicate CSS and incur browser parsing work. Defer deduplication and parsing optimizations for now; investigate React 19's stylesheet handling before committing to a solution. diff --git a/packages/view/package.json b/packages/view/package.json new file mode 100644 index 000000000..b1eea1ff4 --- /dev/null +++ b/packages/view/package.json @@ -0,0 +1,58 @@ +{ + "name": "@void/view", + "version": "1.9.1", + "description": "Compiled HTML and Web Component views for Void.", + "license": "MIT", + "files": [ + "dist" + ], + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "./jsx-runtime": { + "types": "./dist/jsx-runtime.d.mts", + "default": "./dist/jsx-runtime.mjs" + }, + "./plugin": { + "types": "./dist/plugin.d.mts", + "import": "./dist/plugin.mjs" + }, + "./server": { + "types": "./dist/server.d.mts", + "import": "./dist/server.mjs" + }, + "./client": { + "types": "./dist/client.d.mts", + "import": "./dist/client.mjs" + } + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "build": "vp pack", + "dev": "vp pack --watch", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "entities": "^9.0.0", + "lightningcss": "^1.33.0", + "magic-string": "catalog:", + "oxc-parser": "^0.156.0", + "pathslash": "catalog:" + }, + "devDependencies": { + "@types/node": "catalog:", + "typescript": "catalog:", + "vite": "catalog:", + "vite-plus": "catalog:", + "void": "workspace:*" + }, + "peerDependencies": { + "vite": "^8.0.0", + "void": "workspace:*" + } +} diff --git a/packages/view/src/client.ts b/packages/view/src/client.ts new file mode 100644 index 000000000..2d412d871 --- /dev/null +++ b/packages/view/src/client.ts @@ -0,0 +1,245 @@ +import type { ViewResult } from './index.ts'; +import { + attribute, + instanceStyles, + booleanAttributes, + type Binding, + type Initialize, + type Encoded, +} from './shared.ts'; +interface Host extends HTMLElement { + styles?: Map; + mount?: () => void; + refresh?: () => void; +} +let hydrating: Host | undefined; +class Fragment implements ViewResult { + readonly __view = true; + constructor(readonly create: () => DocumentFragment) {} +} +class SerializedHtml { + constructor(readonly html: string) {} +} +function decode(encoded: Encoded): unknown { + const [kind, value] = encoded; + if (kind === 'html') { + return new SerializedHtml(value); + } + if (kind === 'array') { + return value.map(decode); + } + if (kind === 'object') { + return Object.fromEntries(value.map(([key, item]) => [key, decode(item)])); + } + return kind === 'undefined' ? undefined : value; +} +function append(parent: Node, value: unknown): void { + if (value == null || typeof value === 'boolean') { + return; + } + if (Array.isArray(value)) { + for (const item of value) { + append(parent, item); + } + return; + } + if (value instanceof SerializedHtml) { + const template = document.createElement('template'); + template.innerHTML = value.html; + parent.appendChild(template.content); + return; + } + if (value instanceof Fragment) { + parent.appendChild(value.create()); + return; + } + if (value instanceof Node) { + parent.appendChild(value); + return; + } + if (typeof value !== 'string' && typeof value !== 'number') { + throw new Error('Invalid view child'); + } + parent.appendChild(document.createTextNode(String(value))); +} +export function component( + id: string, + _props: unknown, + initialize: Initialize, + dynamic: boolean, + styled = false, +): ViewResult { + if (!dynamic) { + return initialize((value) => value)() as ViewResult; + } + const host = hydrating?.localName === id ? hydrating : (document.createElement(id) as Host); + if (host === hydrating) { + hydrating = undefined; + } + let instance: string | undefined; + let style: import('./shared.ts').Style | undefined; + if (styled) { + const attribute = + host.getAttributeNames().find((name) => name.startsWith('data-vv-rid-')) ?? + 'data-vv-rid-' + crypto.randomUUID(); + host.setAttribute(attribute, ''); + const rid = attribute.slice('data-vv-rid-'.length); + instance = rid; + host.setAttribute('data-vv-cid-' + rid, ''); + host.styles = new Map(); + style = (key, css) => { + const element = host.styles!.get(key) ?? document.createElement('style'); + host.styles!.set(key, element); + element.textContent = instanceStyles(css, rid); + return element; + }; + } + let queued = false; + const draw = initialize( + (value) => { + try { + return value; + } finally { + if (!queued) { + queued = true; + queueMicrotask(() => { + queued = false; + if (host.isConnected) { + host.refresh?.(); + } + }); + } + } + }, + style, + instance, + ); + host.refresh = () => { + const content = document.createDocumentFragment(); + append(content, draw()); + host.replaceChildren(content); + }; + host.mount = () => { + host.refresh!(); + host.setAttribute('data-vv-ready', ''); + }; + host.mount(); + return host as unknown as ViewResult; +} +export function register(id: string, factory: (props: unknown) => unknown): void { + if (customElements.get(id)) { + return; + } + customElements.define( + id, + class extends HTMLElement { + connectedCallback() { + const host = this as Host; + if (host.mount || !this.hasAttribute('data-vv-props')) { + return; + } + const previous = hydrating; + hydrating = host; + try { + factory(decode(JSON.parse(this.getAttribute('data-vv-props')!))); + } finally { + hydrating = previous; + } + } + }, + ); +} +export function template( + id: string, + _html: string | null, + bindings: Array, + instance?: string, +): ViewResult { + return new Fragment(() => { + const source = document.getElementById(id); + if (!(source instanceof HTMLTemplateElement)) { + throw new Error(`Missing view template: ${id}`); + } + const fragment = source.content.cloneNode(true) as DocumentFragment; + if (instance) { + for (const element of fragment.querySelectorAll('[data-vv-i]')) { + element.removeAttribute('data-vv-i'); + element.setAttribute('data-vv-cid-' + instance, ''); + } + } + const slots = new Map( + Array.from(fragment.querySelectorAll('[data-vv-slot]'), (el) => [ + Number(el.getAttribute('data-vv-slot')), + el, + ]), + ); + const comments = document.createTreeWalker(fragment, NodeFilter.SHOW_COMMENT); + while (comments.nextNode()) { + const comment = comments.currentNode as Comment; + if (/^vv:\d+$/.test(comment.data)) { + slots.set(Number(comment.data.slice(3)), comment); + } + } + const elements = new Map( + Array.from(fragment.querySelectorAll('[data-vv-a]'), (el) => [ + Number(el.getAttribute('data-vv-a')), + el, + ]), + ); + function set(el: Element, name: string, value: unknown) { + // Share validation and boolean semantics with SSR. + attribute(name, value); + if (value == null || (booleanAttributes.has(name) && !value)) { + el.removeAttribute(name); + } else { + el.setAttribute(name, booleanAttributes.has(name) ? '' : String(value)); + } + if (name === 'value' && 'value' in el) { + (el as HTMLInputElement).value = String(value ?? ''); + } + if (name === 'checked' && 'checked' in el) { + (el as HTMLInputElement).checked = !!value; + } + } + const events = new Map>(); + function event(el: Element, name: string, value: unknown) { + if (!events.has(el)) { + events.set(el, new Map()); + } + events.get(el)!.set(name, value); + } + for (const [kind, key, name, value] of bindings) { + if (kind === 'child') { + const content = document.createDocumentFragment(); + append(content, value); + slots.get(key)!.replaceWith(content); + } else { + const el = elements.get(key)!; + if (kind === 'event') { + event(el, name, value); + } else if (kind === 'attr') { + set(el, name, value); + } else { + for (const [name, item] of Object.entries((value as object) ?? {})) { + if (/^on/i.test(name)) { + event(el, name.slice(2).toLowerCase(), item); + } else { + set(el, name, item); + } + } + } + } + } + for (const [element, handlers] of events) { + for (const [name, handler] of handlers) { + if (handler != null) { + element.addEventListener(name, handler as EventListener); + } + } + } + for (const el of elements.values()) { + el.removeAttribute('data-vv-a'); + } + return fragment; + }); +} diff --git a/packages/view/src/compiler.ts b/packages/view/src/compiler.ts new file mode 100644 index 000000000..e052581b0 --- /dev/null +++ b/packages/view/src/compiler.ts @@ -0,0 +1,694 @@ +import { createHash } from 'node:crypto'; +import { decodeHTML } from 'entities'; +import MagicString, { type SourceMap } from 'magic-string'; +import { parseSync } from 'oxc-parser'; +import { escapeHtml, voidTags } from './shared.ts'; +import { scopeStyles } from './styles.ts'; + +// Oxc's ESTree nodes have heterogeneous fields; all access is guarded by node kind. +// eslint-disable-next-line @typescript-eslint/no-explicit-any -- A structural ESTree cursor; fields are selected by node kind below. +export type AstNode = { type: string; start: number; end: number; [key: string]: any }; +type Node = AstNode; +export interface ComponentInfo { + name: string; + id: string; + node: Node; + dynamic: boolean; + scope?: string; + dynamicStyles: boolean; + styles: Array; + dependencies: Set; + callbacks: Set; + templates: Map; + defaultStatementStart?: number; + callbackArguments: Array<{ tag: string; name: string; value?: string; known: boolean }>; + callbackProps: Set; + propBindings: Map; +} +export interface ModuleInfo { + file: string; + source: string; + program: Node; + components: Array; + imports: Map; + exports: Map; + functions: Set; + stars: Array; +} +function children(node: Node): Array { + return Object.values(node) + .flatMap((value) => (Array.isArray(value) ? value : [value])) + .filter((value) => value && typeof value === 'object' && typeof value.type === 'string'); +} +function walk(node: Node, visit: (node: Node) => boolean | void): void { + if (visit(node) === false) { + return; + } + for (const child of children(node)) { + walk(child, visit); + } +} +export function bindingNames(node: Node): Array { + if (node.type === 'Identifier') { + return [node.name]; + } + if (node.type === 'MemberExpression') { + return bindingNames(node.object); + } + if (node.type === 'AssignmentPattern') { + return bindingNames(node.left); + } + if (node.type === 'RestElement') { + return bindingNames(node.argument); + } + if (node.type === 'ArrayPattern') { + return node.elements.flatMap((item: Node | null) => (item ? bindingNames(item) : [])); + } + if (node.type === 'ObjectPattern') { + return node.properties.flatMap((item: Node) => + bindingNames(item.type === 'RestElement' ? item : item.value), + ); + } + return []; +} +function tagName(node: Node): string { + if (node.type === 'JSXIdentifier') { + return node.name; + } + if (node.type === 'JSXMemberExpression') { + return `${tagName(node.object)}.${tagName(node.property)}`; + } + throw new Error('@void/view: JSX namespaces are not supported'); +} +export function analyze(source: string, file: string, identity = file): ModuleInfo { + const result = parseSync(file, source); + if (result.errors.length) { + throw new Error(`${file}: ${result.errors.map((error) => error.message).join('\n')}`); + } + const program = result.program as unknown as Node; + const info: ModuleInfo = { + file, + source, + program, + components: [], + imports: new Map(), + exports: new Map(), + functions: new Set(), + stars: [], + }; + for (const statement of program.body) { + const declaration = statement.declaration ?? statement; + if (declaration.type === 'FunctionDeclaration' && declaration.id) { + info.functions.add(declaration.id.name); + } + if (declaration.type === 'VariableDeclaration') { + for (const item of declaration.declarations) { + if (['ArrowFunctionExpression', 'FunctionExpression'].includes(item.init?.type)) { + info.functions.add(item.id.name); + } + } + } + } + const add = (node: Node, name: string) => { + let jsx = false; + let styled = false; + let dynamicStyles = false; + walk(node.body, (child) => { + if (child.type === 'JSXElement' || child.type === 'JSXFragment') { + jsx = true; + } + if (child.type === 'JSXElement' && child.openingElement.name.name === 'style') { + styled = true; + dynamicStyles ||= child.children.some( + (item: Node) => + item.type === 'JSXExpressionContainer' && + item.expression.type !== 'JSXEmptyExpression' && + !(item.expression.type === 'Literal' && typeof item.expression.value === 'string') && + !( + item.expression.type === 'TemplateLiteral' && item.expression.expressions.length === 0 + ), + ); + } + }); + if (!jsx && !/^[A-Z]/.test(name)) { + return; + } + if (node.async || node.generator) { + throw new Error(`${file}: view components must be synchronous`); + } + if (node.params.length > 1) { + throw new Error(`${file}: view components accept a single props argument`); + } + const id = `vv-${name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()}-${createHash( + 'sha256', + ) + .update(identity + ':' + name) + .digest('hex') + .slice(0, 8)}`; + const component: ComponentInfo = { + name, + id, + node, + dynamic: dynamicStyles, + dynamicStyles, + styles: [], + scope: styled ? `data-vv-cid-${id.slice(-8)}` : undefined, + dependencies: new Set(), + callbacks: new Set(), + templates: new Map(), + callbackArguments: [], + callbackProps: new Set(), + propBindings: new Map(), + }; + const param = + node.params[0]?.type === 'AssignmentPattern' ? node.params[0].left : node.params[0]; + if (param?.type === 'ObjectPattern') { + for (const property of param.properties) { + if (property.type === 'Property') { + for (const binding of bindingNames(property.value)) { + component.propBindings.set(binding, property.key.name ?? property.key.value); + } + } + } + } + const functions = new Set(info.functions); + walk(node.body, (child) => { + if (child.type === 'FunctionDeclaration' && child.id) { + functions.add(child.id.name); + } + if ( + child.type === 'VariableDeclarator' && + ['ArrowFunctionExpression', 'FunctionExpression'].includes(child.init?.type) + ) { + functions.add(child.id.name); + } + }); + walk(node.body, (child) => { + if (child.type !== 'JSXOpeningElement') { + return; + } + const tag = tagName(child.name); + const native = child.name.type === 'JSXIdentifier' && /^[a-z]/.test(tag); + if (!native) { + component.dependencies.add(tag); + } + for (const attr of child.attributes) { + if (attr.type === 'JSXSpreadAttribute') { + component.dynamic = true; + if (!native) { + component.callbacks.add(tag); + component.callbackArguments.push({ tag, name: '*', known: true }); + } + continue; + } + const name = tagName(attr.name); + const expression = attr.value?.expression; + const callback = + /^on/i.test(name) || + ['ArrowFunctionExpression', 'FunctionExpression'].includes(expression?.type) || + (expression?.type === 'Identifier' && functions.has(expression.name)); + if (!native) { + let value = expression?.type === 'Identifier' ? expression.name : undefined; + if ( + expression?.type === 'MemberExpression' && + expression.object.type === 'Identifier' && + expression.object.name === param?.name && + !expression.computed + ) { + value = source.slice(expression.start, expression.end); + component.propBindings.set(value, expression.property.name); + } + component.callbackArguments.push({ tag, name, value, known: callback }); + } + if (callback) { + component.dynamic = true; + if (!native) { + component.callbacks.add(tag); + } + } + } + }); + info.components.push(component); + }; + for (const statement of program.body) { + if (statement.type === 'ImportDeclaration' && statement.importKind !== 'type') { + for (const spec of statement.specifiers) { + if (spec.importKind !== 'type') { + info.imports.set(spec.local.name, { + source: statement.source.value, + imported: + spec.type === 'ImportDefaultSpecifier' ? 'default' : (spec.imported?.name ?? '*'), + }); + } + } + } + const declaration = statement.declaration ?? statement; + if (declaration.type === 'FunctionDeclaration') { + const name = declaration.id?.name ?? 'DefaultView'; + add(declaration, name); + if (statement.type.startsWith('Export')) { + info.exports.set(statement.type === 'ExportDefaultDeclaration' ? 'default' : name, name); + } + } else if (declaration.type === 'VariableDeclaration') { + for (const item of declaration.declarations) { + if ( + ['ArrowFunctionExpression', 'FunctionExpression'].includes(item.init?.type) && + item.id.type === 'Identifier' + ) { + add(item.init, item.id.name); + } + if (statement.type === 'ExportNamedDeclaration') { + info.exports.set(item.id.name, item.id.name); + } + } + } else if (statement.type === 'ExportDefaultDeclaration' && declaration.type === 'Identifier') { + info.exports.set('default', declaration.name); + } else if ( + statement.type === 'ExportDefaultDeclaration' && + declaration.type === 'ArrowFunctionExpression' + ) { + add(declaration, 'DefaultView'); + info.components.at(-1)!.defaultStatementStart = statement.start; + info.exports.set('default', 'DefaultView'); + } + if (statement.type === 'ExportNamedDeclaration') { + for (const spec of statement.specifiers ?? []) { + info.exports.set(spec.exported.name, spec.local.name); + if (statement.source && statement.exportKind !== 'type') { + info.imports.set(spec.local.name, { + source: statement.source.value, + imported: spec.local.name, + }); + } + } + } + if (statement.type === 'ExportAllDeclaration' && statement.exportKind !== 'type') { + info.stars.push(statement.source.value); + } + } + return info; +} +function jsxText(value: string): string { + const lines = decodeHTML(value).replace(/\r/g, '').split('\n'); + return lines + .map((line, index) => { + let text = line.replace(/\t/g, ' '); + if (index > 0) { + text = text.trimStart(); + } + if (index < lines.length - 1) { + text = text.trimEnd(); + } + return text; + }) + .filter(Boolean) + .join(' '); +} +export function compile( + info: ModuleInfo, + client: boolean, +): { code: string; map: SourceMap | null } { + const output = new MagicString(info.source); + const source = info.source; + const imports = `import { component as __vv_component, template as __vv_template, register as __vv_register } from '@void/view/${client ? 'client' : 'server'}';\n`; + if (!info.components.length) { + return { code: source, map: null }; + } + if (/\b__vv_\w*/.test(source)) { + throw new Error(`${info.file}: the __vv_ prefix is reserved by @void/view`); + } + for (const component of info.components) { + component.templates.clear(); + component.styles = []; + let styleIndex = 0; + const fn = component.node; + const state = new Set(); + for (const statement of fn.body.body ?? []) { + if (statement.type === 'VariableDeclaration' && statement.kind === 'let') { + for (const item of statement.declarations) { + for (const name of bindingNames(item.id)) { + state.add(name); + } + } + } + } + let templateIndex = 0; + function expr(node: Node, shadow = new Set(), rendering = true): string { + if (node.type === 'JSXElement' || node.type === 'JSXFragment') { + return jsx(node, shadow); + } + const edit = new MagicString(source.slice(node.start, node.end)); + function patch(current: Node, hidden: Set, inRender: boolean) { + if (current.type === 'JSXElement' || current.type === 'JSXFragment') { + edit.overwrite( + current.start - node.start, + current.end - node.start, + jsx(current, hidden), + ); + return; + } + let scoped = hidden; + if ( + ['ArrowFunctionExpression', 'FunctionExpression', 'FunctionDeclaration'].includes( + current.type, + ) + ) { + inRender = false; + } + if ( + [ + 'ArrowFunctionExpression', + 'FunctionExpression', + 'FunctionDeclaration', + 'BlockStatement', + 'CatchClause', + 'ForStatement', + 'ForOfStatement', + 'ForInStatement', + ].includes(current.type) + ) { + scoped = new Set(hidden); + const bindings: Array = [ + ...(current.params ?? []), + ...(current.param ? [current.param] : []), + ]; + const loop = current.init ?? current.left; + if (loop?.type === 'VariableDeclaration') { + bindings.push(...loop.declarations.map((item: Node) => item.id)); + } + if (current !== fn.body) { + for (const statement of current.body?.body ?? + (Array.isArray(current.body) ? current.body : [])) { + if (statement.type === 'VariableDeclaration') { + bindings.push(...statement.declarations.map((item: Node) => item.id)); + } + } + } + for (const binding of bindings) { + for (const name of bindingNames(binding)) { + scoped.add(name); + } + } + } + if (current.type === 'AssignmentExpression' || current.type === 'UpdateExpression') { + const target = current.left ?? current.argument; + const changed = bindingNames(target).some((name) => state.has(name) && !scoped.has(name)); + if (changed) { + if (inRender) { + throw new Error( + `${info.file}: update view state inside callbacks, not while rendering`, + ); + } + // Recurse into operands before wrapping, retaining expression result and evaluation order. + for (const child of children(current)) { + patch(child, scoped, inRender); + } + edit.prependLeft(current.start - node.start, '__vv_change('); + edit.appendRight(current.end - node.start, ')'); + return; + } + } + for (const child of children(current)) { + patch(child, scoped, inRender); + } + } + patch(node, shadow, rendering); + return edit.toString(); + } + function jsx(node: Node, shadow: Set): string { + const id = component.id + (templateIndex++ ? `-${templateIndex - 1}` : ''); + let key = 0; + const bindings: Array = []; + function slot(value: string, name = ''): string { + const index = key++; + bindings.push(`['child',${index},'',${value}]`); + return name ? `` : ``; + } + function child(n: Node, parent = ''): string { + if (n.type === 'JSXText') { + return escapeHtml(jsxText(n.value)); + } + if (n.type === 'JSXExpressionContainer') { + if (n.expression.type === 'JSXEmptyExpression') { + return ''; + } + return slot( + expr(n.expression, shadow), + n.expression.type === 'Identifier' && + n.expression.name === 'children' && + ![ + 'table', + 'thead', + 'tbody', + 'tfoot', + 'tr', + 'colgroup', + 'select', + 'optgroup', + ].includes(parent) + ? 'children' + : '', + ); + } + if (n.type === 'JSXSpreadChild') { + return slot(expr(n.expression, shadow)); + } + return element(n); + } + function element(n: Node): string { + if (n.type === 'JSXFragment') { + return n.children.map((item: Node) => child(item)).join(''); + } + const opening = n.openingElement; + const tag = tagName(opening.name); + if (opening.name.type !== 'JSXIdentifier' || !/^[a-z]/.test(tag)) { + const props = opening.attributes.map((attr: Node) => { + if (attr.type === 'JSXSpreadAttribute') { + return `...(${expr(attr.argument, shadow)})`; + } + const name = tagName(attr.name); + const value = !attr.value + ? 'true' + : attr.value.type === 'Literal' + ? JSON.stringify(decodeHTML(attr.value.value)) + : expr(attr.value.expression, shadow); + return `${JSON.stringify(name)}:${value}`; + }); + if (n.children.length) { + const values = n.children.flatMap((c: Node) => { + if (c.type === 'JSXText') { + const text = jsxText(c.value); + return text ? [JSON.stringify(text)] : []; + } + if (c.type === 'JSXExpressionContainer') { + return c.expression.type === 'JSXEmptyExpression' + ? [] + : [expr(c.expression, shadow)]; + } + return [expr(c, shadow)]; + }); + props.push(`children:${values.length === 1 ? values[0] : `[${values.join(',')}]`}`); + } + return slot(`${tag}({${props.join(',')}})`); + } + if (tag === 'style') { + if (opening.attributes.length) { + throw new Error(`${info.file}: component style blocks do not accept attributes`); + } + const expressions: Array = []; + const text = n.children + .map((item: Node) => { + if (item.type === 'JSXText') { + return decodeHTML(item.value); + } + const value = item.expression; + if (value?.type === 'JSXEmptyExpression') { + return ''; + } + if (value?.type === 'Literal' && typeof value.value === 'string') { + return value.value; + } + if (value?.type === 'TemplateLiteral') { + return value.quasis + .map((quasi: Node, index: number) => { + let text = quasi.value.cooked; + if (index < value.expressions.length) { + const marker = `__vv_expr${expressions.length}__`; + expressions.push(expr(value.expressions[index], shadow)); + text += marker; + } + return text; + }) + .join(''); + } + throw new Error(`${info.file}: use a template literal inside ', + ) + : undefined, + rid, + )(); + collect(content, components); + if (dynamic) { + components.add(id); + collect(props, components); + } + html = render(content); + } finally { + if (dynamic) { + depth--; + } + } + return new Html( + dynamic + ? `<${id}${rid ? ` data-vv-rid-${rid} data-vv-cid-${rid}` : ''}${root ? ` data-vv-props="${escapeHtml(JSON.stringify(encode(props)))}"` : ''}>${html}` + : html, + components, + ); +} +export function template( + _id: string, + html: string, + bindings: Array, + instance?: string, +): Html { + if (instance) { + html = html.replaceAll(' data-vv-i', ' data-vv-cid-' + instance); + } + const children = new Map(); + const components = new Set(); + const attrs = new Map>(); + function set(key: number, name: string, value: unknown) { + if (!attrs.has(key)) { + attrs.set(key, new Map()); + } + attrs.get(key)!.set(name, value); + } + for (const [kind, key, name, value] of bindings) { + if (kind === 'child') { + children.set(key, value); + collect(value, components); + } else if (kind === 'attr') { + set(key, name, value); + } else if (kind === 'spread') { + for (const [name, item] of Object.entries((value as object) ?? {})) { + if (!/^on/i.test(name)) { + set(key, name, item); + } + } + } + } + return new Html( + html + .replace(/ data-vv-a="(\d+)"/g, (_, key) => + [...(attrs.get(+key) ?? [])].map(([name, value]) => attribute(name, value)).join(''), + ) + .replace( + /<\/slot>|/g, + (_, slot, comment) => render(children.get(Number(slot ?? comment))), + ), + components, + ); +} +export function register(_id: string, _factory: (props: unknown) => unknown): void {} diff --git a/packages/view/src/shared.ts b/packages/view/src/shared.ts new file mode 100644 index 000000000..540055565 --- /dev/null +++ b/packages/view/src/shared.ts @@ -0,0 +1,50 @@ +export type Binding = readonly [ + kind: 'child' | 'attr' | 'event' | 'spread', + key: number, + name: string, + value: unknown, +]; +export type Change = (value: T) => T; +export type Style = (key: number, css: string) => unknown; +export type Initialize = (change: Change, style?: Style, instance?: string) => () => unknown; +export function instanceStyles(css: string, id: string): string { + return css + .replaceAll('data-vv-rid-vvINSTANCE', 'data-vv-rid-' + id) + .replaceAll('data-vv-cid-vvINSTANCE', 'data-vv-cid-' + id); +} +export const voidTags = /* @__PURE__ */ new Set( + 'area base br col embed hr img input link meta param source track wbr'.split(' '), +); +export function escapeHtml(value: unknown): string { + return String(value).replace( + /[&<>"']/g, + (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]!, + ); +} +export const booleanAttributes = new Set( + 'allowfullscreen async autofocus autoplay checked controls default defer disabled formnovalidate hidden inert ismap itemscope loop multiple muted nomodule novalidate open playsinline readonly required reversed selected'.split( + ' ', + ), +); +export function attribute(name: string, value: unknown): string { + if (!/^[a-zA-Z_:][\w:.-]*$/.test(name) || /^on/i.test(name) || name.startsWith('data-vv-')) { + throw new Error(`Unsafe view attribute: ${name}`); + } + if (value == null || (booleanAttributes.has(name) && !value)) { + return ''; + } + if (booleanAttributes.has(name)) { + return ` ${name}`; + } + if (typeof value === 'function' || typeof value === 'object') { + throw new Error(`View attribute ${name} must be a scalar`); + } + return ` ${name}="${escapeHtml(value)}"`; +} + +export type Encoded = + | ['html', string] + | ['undefined'] + | ['array', Array] + | ['object', Array<[string, Encoded]>] + | ['scalar', string | number | boolean | null]; diff --git a/packages/view/src/styles.ts b/packages/view/src/styles.ts new file mode 100644 index 000000000..eafeb1b0b --- /dev/null +++ b/packages/view/src/styles.ts @@ -0,0 +1,61 @@ +import { Features, transform, type Selector } from 'lightningcss'; + +/** Scope selectors at compile time. Static :root rules are global; instance rules stay in their host. */ +export function scopeStyles( + css: string, + attribute: string, + filename: string, + instance = false, +): string { + // Flatten nesting first so :root { .global {} } and :root .global {} take the same path. + const flattened = transform({ filename, code: Buffer.from(css), include: Features.Nesting }).code; + return transform({ + filename, + code: flattened, + minify: !instance, + visitor: { + Selector(selector) { + if (selector[0]?.type === 'pseudo-class' && selector[0].kind === 'root') { + if (!instance) { + return selector; + } + selector = selector.slice(1); + if (selector[0]?.type === 'combinator') { + selector = selector.slice(1); + } + } + const scoped: Selector = instance + ? [ + { type: 'attribute', name: 'data-vv-rid-vvINSTANCE' }, + ...(selector.length + ? [{ type: 'combinator' as const, value: 'descendant' as const }] + : []), + ] + : []; + let compound: Selector = []; + function flush() { + if (!compound.length) { + return; + } + const pseudo = compound.findIndex((part) => part.type === 'pseudo-element'); + compound.splice(pseudo < 0 ? compound.length : pseudo, 0, { + type: 'attribute', + name: instance ? 'data-vv-cid-vvINSTANCE' : attribute, + }); + scoped.push(...compound); + compound = []; + } + for (const part of selector) { + if (part.type === 'combinator') { + flush(); + scoped.push(part); + } else { + compound.push(part); + } + } + flush(); + return scoped; + }, + }, + }).code.toString(); +} diff --git a/packages/view/test/integration/view.test.ts b/packages/view/test/integration/view.test.ts new file mode 100644 index 000000000..abd7a25fd --- /dev/null +++ b/packages/view/test/integration/view.test.ts @@ -0,0 +1,379 @@ +import { execSync, spawn } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { Browser } from 'playwright'; +import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; +import { + killChild, + spawnPlaygroundServer, + startServer, +} from '../../../../test/integration-helpers.ts'; +import { launchPagesBrowser } from '../../../../test/pages-browser.ts'; + +const root = resolve(import.meta.dirname, '../../../..'); +for (const mode of ['dev', 'preview'] as const) { + describe(`view ${mode}`, () => { + let server: Awaited>; + let browser: Browser; + beforeAll(async () => { + if (mode === 'preview') { + execSync('vp run --filter ./playground/view build', { + cwd: root, + stdio: 'pipe', + timeout: 60_000, + }); + } + server = await startServer( + (port) => + mode === 'dev' + ? spawnPlaygroundServer(root, 'view', 'dev', port) + : spawn(process.execPath, ['dist/ssr/index.js'], { + cwd: resolve(root, 'playground/view'), + env: { ...process.env, PORT: String(port) }, + stdio: ['ignore', 'pipe', 'pipe'], + }), + 30_000, + ); + browser = await launchPagesBrowser(); + }, 60_000); + afterAll(async () => { + await browser?.close(); + if (server) { + await killChild(server.child); + } + }); + if (mode === 'dev') { + it('rebuilds the template and custom-element graph after editing a static component', async () => { + const file = resolve(root, 'playground/view/components/Label.tsx'); + const original = readFileSync(file, 'utf8'); + const page = await browser.newPage(); + try { + await page.goto(server.base); + await page.waitForSelector('vv-button[data-vv-ready]'); + expect(await page.locator('vv-label').count()).toBe(0); + writeFileSync( + file, + original + .replace('', ' {}}>') + .replace('font-weight: bold', 'font-weight: normal'), + ); + await page.waitForSelector('vv-label[data-vv-ready]', { timeout: 10_000 }); + await expect + .poll(() => + page + .locator('.label') + .first() + .evaluate((node) => getComputedStyle(node).fontWeight), + ) + .toBe('400'); + } finally { + writeFileSync(file, original); + await expect + .poll(async () => { + const response = await fetch(server.base); + return response.ok && !(await response.text()).includes(' { + const html = await (await fetch(server.base)).text(); + expect(html).toContain('Press me'); + expect(html).toContain('Count: 0'); + expect(html).toMatch(/