Skip to content

The VS Code of video editing, built for agents.

TypeScript

Enhance text editing capabilities in the editor

konstantin-paulusd9384e189b7d
diff --git a/apps/desktop/src/edit.ts b/apps/desktop/src/edit.ts
index a07e16aa..72c68437 100644
--- a/apps/desktop/src/edit.ts
+++ b/apps/desktop/src/edit.ts
@@ -33,11 +33,17 @@ export interface SourceContext {
onWrite?: (file: string) => void;
}
-/** Overwrites props of the element named by `source` (a `SOURCE_ATTR` value). */
+/**
+ * Overwrites props of the element named by `source` (a `SOURCE_ATTR` value),
+ * and — for a `<text>` — what it says. `text` is its literal content, which is
+ * its children rather than a prop and so arrives on its own; an element that
+ * only says something new comes with no props at all.
+ */
export interface SourceSet {
kind: "set";
source: string;
props: Record<string, PropValue>;
+ text?: string;
}
/**
@@ -271,6 +277,24 @@ function jsxText(text: string): string {
return /^[^\s{}<>&][^\n{}<>&]*[^\s{}<>&]$|^[^\s{}<>&]$/.test(text) ? text : `{${JSON.stringify(text)}}`;
}
+/**
+ * Replaces what an element says between its tags; a self-closing one is opened
+ * up around the new text. Everything outside the body keeps its bytes, so an
+ * element that says something else is otherwise the element it was.
+ */
+function setText(sourceFile: SourceFile, tag: JsxTag, text: string): void {
+ const element = elementOf(tag);
+ const content = text ? jsxText(text) : "";
+
+ if (element.isKind(SyntaxKind.JsxSelfClosingElement)) {
+ const opening = element.getText().replace(/\s*\/>$/, ">");
+ sourceFile.replaceText([element.getStart(), element.getEnd()], `${opening}${content}</${tagName(tag)}>`);
+ return;
+ }
+
+ sourceFile.replaceText([element.getOpeningElement().getEnd(), element.getClosingElement().getStart()], content);
+}
+
// ---------------------------------------------------------------------------
// Layout
@@ -796,6 +820,19 @@ class SourceWriter {
wrote = true;
}
+ // What the element says, after its props: same rules as a prop, and
+ // only a `<text>` has anything to say.
+ if (edit.text !== undefined) {
+ const tag = findTag(sourceFile, locator);
+ if (!tag) skipped.push(edit.source);
+ else if (inLoop(tag)) skipped.push(`${edit.source} (loop)`);
+ else if (!isTextTag(tag)) skipped.push(`${edit.source} (text)`);
+ else {
+ setText(sourceFile, tag, edit.text);
+ wrote = true;
+ }
+ }
+
// Named only once something was written: failing to write to an
// element is no reason to touch the file.
const tag = wrote ? findTag(sourceFile, locator) : undefined;
diff --git a/apps/web/src/components/sidebar-right/inspector/inspector.tsx b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
index 1236d966..4b261a05 100644
--- a/apps/web/src/components/sidebar-right/inspector/inspector.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
@@ -29,7 +29,7 @@ import { ExportPanel } from "./export";
import { LayoutPanel } from "./layout";
// import { TransformSettings } from "./transform";
// import { CaptionSettings } from "./caption-settings";
-// import { TextPanel } from "./text";
+import { TextPanel } from "./text";
// import { FillsSettings } from "./fills";
// import { StrokesSettings } from "./strokes";
// import { ShadowsSettings } from "./shadows";
@@ -145,9 +145,9 @@ export function Inspector() {
<CaptionSettings selection={nodes()} />
</Show> */}
- {/* <Show when={includesTarget("text", "caption")}>
+ <Show when={includesTarget("text", "caption")}>
<TextPanel selection={nodes()} />
- </Show> */}
+ </Show>
{/* <Show when={includesTarget("shape", "text", "scene", "caption")}>
<FillsSettings selection={nodes()} />
diff --git a/apps/web/src/components/sidebar-right/inspector/text.tsx b/apps/web/src/components/sidebar-right/inspector/text.tsx
index 99395dac..802e78d7 100644
--- a/apps/web/src/components/sidebar-right/inspector/text.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/text.tsx
@@ -16,19 +16,45 @@ import {
SelectPortal,
} from '@/components/ui/select';
import { ControlledTextField } from '@/components/ui/text-field';
-import { getLocalFonts, getWebFonts, loadWebFont, WebFonts, FONT_WEIGHTS } from '../../engine/font';
-import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuGroupLabel, DropdownMenuPortal, DropdownMenuSeparator, DropdownMenuTrigger } from '../../ui/dropdown-menu';
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuGroupLabel,
+ DropdownMenuPortal,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Button } from '@/components/ui/button';
import { cx } from '@/lib/cva';
-import { Button } from '../../ui/button';
import { toast } from 'somoto';
import { usePermissionState } from '@/hooks/use-permission';
-import { useEntityState, TextAlign, TextBaseline, useEntityTag, isText, isCaption, ToolType, addComponent, removeComponent, setComponent } from '@/components/engine';
-import { useEngine } from '@/context/engine';
-import { useECS } from '@/context/ecs';
-
+import { useHas, useTrait, useWorld } from '@diffusionstudio/koota-solid';
+import {
+ Chars,
+ Computed,
+ FONT_WEIGHTS,
+ Size,
+ TextAlign,
+ TextBaseline,
+ TextStyle,
+ Tool,
+ ToolType,
+ WebFonts,
+ getWebFonts,
+ isCaption,
+ isText,
+ loadWebFont,
+} from '@diffusionstudio/runtime';
+import { getLocalFonts } from '@/engine/fonts';
+import { useDerived, useEditor, useTool } from '@/engine/hooks';
+import { removeKeyframeTrack, syncKeyframe } from '@/engine/keyframes';
+
+import type { Entity } from 'koota';
type TextPanelProps = {
- selection: Set<number>;
+ selection: Entity[];
};
const RESIZE_MODE_ITEMS = [
@@ -44,50 +70,90 @@ const RESIZE_MODE_ITEMS = [
},
] as const;
+/**
+ * Typography: what a `<text>` says and how its glyphs are set. Every value is
+ * a prop of the element (`fontFamily`, `fontSize`, `fontWeight`, `leading`,
+ * `letterSpacing`, `textAlign`, `textBaseline`) except the content itself,
+ * which is the element's children and goes through `editor.editText`.
+ *
+ * Which font a text is set in is written out plainly; the modifiers around it
+ * (leading, spacing, alignment) are unset at their default, so a file says
+ * only what its text does differently. Hovering a family or a weight previews
+ * it on the trait alone, which the picker undoes on close: a preview is not
+ * an edit, and nothing about it belongs in the file.
+ *
+ * A text with no box sizes itself to its glyphs, so "Grow" is `width`/`height`
+ * being authored at all rather than a prop of its own.
+ */
export function TextPanel(props: TextPanelProps) {
- const { world } = useEngine();
- const { selectedTool } = useECS();
- const c = world.components;
- const eid = () => props.selection.values().next().value!;
+ const world = useWorld();
+ const editor = useEditor();
+ const tool = useTool();
+ const entity = () => props.selection[0]!;
+
+ const style = useTrait(entity, TextStyle);
+ const chars = useTrait(entity, Chars);
+ const hasSize = useHas(entity, Size);
+
+ const fontFamily = () => style()?.fontFamily ?? 'Inter';
+ const fontWeight = () => style()?.fontWeight ?? '400';
+ const fontSize = () => style()?.fontSize ?? 16;
+ const leading = () => style()?.leading ?? 1;
+ const letterSpacing = () => style()?.letterSpacing ?? 0;
+ const textAlign = () => style()?.textAlign ?? TextAlign.LEFT;
+ const textBaseline = () => style()?.textBaseline ?? TextBaseline.TOP;
+
+ // The box a switch to "fixed" pins, which the glyphs are sizing right now.
+ const width = useDerived(() => entity().get(Computed)?.width ?? 0);
+ const height = useDerived(() => entity().get(Computed)?.height ?? 0);
- const [fontWeight, setFontWeight] = createSignal(c.TextStyle.fontWeight[eid()] ?? '400');
- const [fontFamily, setFontFamily] = createSignal(c.TextStyle.fontFamily[eid()] ?? 'Inter');
const [availableWeights, setAvailableWeights] = createSignal<string[]>([]);
- const textContent = useEntityState(c.Chars, eid, 'Text');
- const fontSize = useEntityState(c.TextStyle.fontSize, eid, 16);
- const leading = useEntityState(c.TextStyle.leading, eid, 1);
- const textAlign = useEntityState(c.TextStyle.textAlign, eid, TextAlign.LEFT);
- const textBaseline = useEntityState(c.TextStyle.textBaseline, eid, TextBaseline.TOP);
- const letterSpacing = useEntityState(c.TextStyle.letterSpacing, eid, 0);
- const sizeTag = useEntityTag(c.Size, eid);
+ const resizeMode = createMemo(() => (hasSize() ? 'fixed' : 'auto'));
+ const textSelected = createMemo(() => isText(entity()) && !isCaption(entity()));
- const resizeMode = createMemo(() => sizeTag() ? 'fixed' : 'auto');
- const textSelected = createMemo(() => isText(world, eid()) && !isCaption(world, eid()));
+ const weightOptions = createMemo(() => {
+ const weights = availableWeights();
+ if (!weights.length) return ALL_FONT_WEIGHTS;
+ return ALL_FONT_WEIGHTS.filter(w => weights.includes(w.value));
+ });
+
+ /** Writes a family or weight to the trait alone, for the picker to show. */
+ const previewFont = (params: { fontFamily?: string; fontWeight?: string }) => {
+ entity().add(TextStyle);
+ entity().set(TextStyle, params);
+ };
const handleFontFamilyChange = (family: string) => {
- setComponent(world, eid(), c.TextStyle, { fontFamily: family });
- setFontFamily(c.TextStyle.fontFamily[eid()] ?? 'Inter');
+ editor.editProperty(entity(), 'fontFamily', family);
if (family in WebFonts) {
- loadWebFont(world, family as keyof typeof WebFonts);
+ void loadWebFont(world, family as keyof typeof WebFonts);
}
};
const handleFontWeightChange = (weight: string) => {
- setComponent(world, eid(), c.TextStyle, { fontWeight: weight });
- setFontWeight(c.TextStyle.fontWeight[eid()] ?? '400');
+ // Authored as a CSS number, which is the only spelling the prop takes
+ // besides the "normal"/"bold" keywords the panel does not offer.
+ editor.editProperty(entity(), 'fontWeight', Number(weight));
};
- const weightOptions = createMemo(() => {
- const weights = availableWeights();
- if (!weights.length) return ALL_FONT_WEIGHTS;
- return ALL_FONT_WEIGHTS.filter(w => weights.includes(w.value));
- });
-
const handleResizeModeChange = (mode: 'auto' | 'fixed') => {
- if (mode === 'fixed') addComponent(world, eid(), c.Size);
- else removeComponent(world, eid(), c.Size);
+ if (mode === 'fixed') {
+ // Pinned at what the glyphs came to, so the switch changes nothing yet.
+ const [w, h] = [Math.round(width()), Math.round(height())];
+ syncKeyframe(world, editor, entity(), 'width', w);
+ editor.editProperty(entity(), 'width', w);
+ syncKeyframe(world, editor, entity(), 'height', h);
+ editor.editProperty(entity(), 'height', h);
+ return;
+ }
+
+ // A box the glyphs decide is no box to keyframe.
+ removeKeyframeTrack(world, editor, entity(), 'width');
+ removeKeyframeTrack(world, editor, entity(), 'height');
+ editor.editProperty(entity(), 'width', false);
+ editor.editProperty(entity(), 'height', false);
};
return (
@@ -95,20 +161,20 @@ export function TextPanel(props: TextPanelProps) {
<Show when={textSelected()}>
<ControlRow label="Content" contentClass="flex flex-col">
<GrowingTextArea
- value={textContent()}
+ value={chars()?.value ?? ''}
maxRows={8}
- onInput={(v) => setComponent(world, eid(), c.Chars, v)}
- focused={selectedTool() === ToolType.TEXT_EDIT}
- onFocus={() => (world.selection.tool = ToolType.TEXT_EDIT)}
- onBlur={() => (world.selection.tool = ToolType.MOVE)}
+ onInput={(v) => editor.editText(entity(), v)}
+ focused={tool() === ToolType.TEXT_EDIT}
+ onFocus={() => world.set(Tool, { value: ToolType.TEXT_EDIT })}
+ onBlur={() => world.set(Tool, { value: ToolType.MOVE })}
/>
</ControlRow>
</Show>
<ControlRow label="Font">
<FontDropdown
- eid={eid()}
family={fontFamily()}
+ onPreview={(family) => previewFont({ fontFamily: family })}
onFamilyChange={handleFontFamilyChange}
onWeightsChange={setAvailableWeights}
/>
@@ -123,7 +189,7 @@ export function TextPanel(props: TextPanelProps) {
itemComponent={itemProps => (
<SelectItem
item={itemProps.item}
- onPointerEnter={() => (c.TextStyle.fontWeight[eid()] = itemProps.item.rawValue)}
+ onPointerEnter={() => previewFont({ fontWeight: itemProps.item.rawValue })}
>
{weightOptions().find(w => w.value === itemProps.item.rawValue)?.label}
</SelectItem>
@@ -135,14 +201,14 @@ export function TextPanel(props: TextPanelProps) {
</SelectValue>
</SelectTrigger>
<SelectPortal>
- <SelectContent onCloseAutoFocus={() => (c.TextStyle.fontWeight[eid()] = fontWeight())} />
+ <SelectContent onCloseAutoFocus={() => previewFont({ fontWeight: fontWeight() })} />
</SelectPortal>
</Select>
<ControlledTextField
class="flex-1"
value={fontSize()}
- onNumber={(v) => setComponent(world, eid(), c.TextStyle, { fontSize: v })}
+ onNumber={(v) => editor.editProperty(entity(), 'fontSize', v)}
step={1}
min={1}
autoSelect
@@ -158,7 +224,7 @@ export function TextPanel(props: TextPanelProps) {
<ControlledTextField
icon={<Icon name="text.line-height" />}
value={Math.round(leading() * 100)}
- onNumber={(v) => setComponent(world, eid(), c.TextStyle, { leading: v / 100 })}
+ onNumber={(v) => editor.editProperty(entity(), 'leading', v === 100 ? false : v / 100)}
unit="%"
step={1}
min={0}
@@ -169,9 +235,9 @@ export function TextPanel(props: TextPanelProps) {
/>
<ControlledTextField
icon={<Icon name="text.letter-spacing" />}
- value={Math.round(letterSpacing() * 100)}
- onNumber={(v) => setComponent(world, eid(), c.TextStyle, { letterSpacing: v / 100 })}
- unit="%"
+ value={letterSpacing()}
+ onNumber={(v) => editor.editProperty(entity(), 'letterSpacing', v === 0 ? false : v)}
+ unit="px"
step={1}
min={-1200}
max={1200}
@@ -192,14 +258,14 @@ export function TextPanel(props: TextPanelProps) {
<ControlRow label="Align" contentClass="flex gap-2">
<SegmentedIconTabs
class="flex-1"
- value={() => HORIZONTAL_ALIGN_TABS[textAlign() ?? TextAlign.LEFT]?.value ?? 'left'}
- onChange={(v) => setComponent(world, eid(), c.TextStyle, { textAlign: HORIZONTAL_ALIGN_MAP[v as any] })}
+ value={() => HORIZONTAL_ALIGNS[textAlign()] ?? 'left'}
+ onChange={(v) => editor.editProperty(entity(), 'textAlign', v === 'left' ? false : v)}
items={HORIZONTAL_ALIGN_TABS}
/>
<SegmentedIconTabs
class="flex-1"
- value={() => VERTICAL_ALIGN_TABS[textBaseline() ?? TextBaseline.TOP]?.value ?? 'top'}
- onChange={(v) => setComponent(world, eid(), c.TextStyle, { textBaseline: VERTICAL_ALIGN_MAP[v as any] })}
+ value={() => VERTICAL_ALIGNS[textBaseline()] ?? 'top'}
+ onChange={(v) => editor.editProperty(entity(), 'textBaseline', v === 'top' ? false : v)}
items={VERTICAL_ALIGN_TABS}
/>
</ControlRow>
@@ -208,16 +274,13 @@ export function TextPanel(props: TextPanelProps) {
}
type FontDropdownProps = {
- eid: number;
family: string;
+ onPreview(family: string): void;
onFamilyChange(family: string): void;
onWeightsChange(weights: string[]): void;
};
function FontDropdown(props: FontDropdownProps) {
- const { world } = useEngine();
- const c = world.components;
-
const [webfonts] = createSignal(getWebFonts());
const [fontQuery, setFontQuery] = createSignal('');
const fontsPermission = usePermissionState('local-fonts');
@@ -265,18 +328,10 @@ function FontDropdown(props: FontDropdownProps) {
return fonts.filter((f) => f.family.toLowerCase().includes(q));
});
- const handlePointerEnter = (family: string) => {
- setComponent(world, props.eid, c.TextStyle, { fontFamily: family });
- };
-
- const handleSelect = (family: string) => {
- props.onFamilyChange(family);
- };
-
const handleOpenChange = () => {
setFontQuery('');
-
- setComponent(world, props.eid, c.TextStyle, { fontFamily: props.family });
+ // Whatever was hovered last goes; the selection is the only edit.
+ props.onPreview(props.family);
};
const handleGrantAccess = async () => {
@@ -331,8 +386,8 @@ function FontDropdown(props: FontDropdownProps) {
<LazyFontItem
family={font.family}
checked={props.family === font.family}
- onPointerEnter={handlePointerEnter}
- onSelect={handleSelect}
+ onPointerEnter={props.onPreview}
+ onSelect={props.onFamilyChange}
>
{font.family}
</LazyFontItem>
@@ -359,8 +414,8 @@ function FontDropdown(props: FontDropdownProps) {
<LazyFontItem
family={font.family}
checked={props.family === font.family}
- onPointerEnter={handlePointerEnter}
- onSelect={handleSelect}
+ onPointerEnter={props.onPreview}
+ onSelect={props.onFamilyChange}
>
{font.family}
</LazyFontItem>
@@ -488,20 +543,23 @@ const HORIZONTAL_ALIGN_TABS = [
{ value: 'right', label: 'Align right', icon: 'text.align-right' },
] as const;
-const HORIZONTAL_ALIGN_MAP: Record<string, TextAlign> = {
- left: TextAlign.LEFT,
- center: TextAlign.CENTER,
- right: TextAlign.RIGHT,
-};
-
const VERTICAL_ALIGN_TABS = [
{ value: 'top', label: 'Align top', icon: 'text.align-top' },
{ value: 'middle', label: 'Align middle', icon: 'text.align-middle' },
{ value: 'bottom', label: 'Align bottom', icon: 'text.align-bottom' },
] as const;
-const VERTICAL_ALIGN_MAP: Record<string, TextBaseline> = {
- top: TextBaseline.TOP,
- middle: TextBaseline.MIDDLE,
- bottom: TextBaseline.BOTTOM,
+// The trait's enum in the prop's vocabulary, which is what a tab is worth.
+const HORIZONTAL_ALIGNS: Record<TextAlign, string> = {
+ [TextAlign.LEFT]: 'left',
+ [TextAlign.CENTER]: 'center',
+ [TextAlign.RIGHT]: 'right',
+};
+
+const VERTICAL_ALIGNS: Record<TextBaseline, string> = {
+ [TextBaseline.TOP]: 'top',
+ [TextBaseline.MIDDLE]: 'middle',
+ [TextBaseline.BOTTOM]: 'bottom',
+ // No tab offers a first-line baseline; it reads as the top one.
+ [TextBaseline.ALPHABETIC]: 'top',
};
diff --git a/apps/web/src/engine/editor.ts b/apps/web/src/engine/editor.ts
index fa860ab9..97dc6597 100644
--- a/apps/web/src/engine/editor.ts
+++ b/apps/web/src/engine/editor.ts
@@ -34,6 +34,17 @@ export interface PropEdit {
value: PropValue;
}
+/**
+ * What a `<text>` says, changed. Its content is its children rather than a
+ * prop, so it travels as an edit of its own; `value` is the literal the file
+ * gets between the tags.
+ */
+export interface TextEdit {
+ kind: 'text';
+ source: string;
+ value: string;
+}
+
/**
* An element the editor added. The entity already exists in the world when
* this is reported, stamped with the pending `source`; whoever writes it to
@@ -101,7 +112,7 @@ export interface UnrollEdit {
iterations: LoopIteration[];
}
-export type EntityEdit = PropEdit | InsertEdit | MoveEdit | RemoveEdit | UnrollEdit;
+export type EntityEdit = PropEdit | TextEdit | InsertEdit | MoveEdit | RemoveEdit | UnrollEdit;
/**
* Sources of elements the editor created that no write has named yet. Shaped
@@ -167,6 +178,21 @@ export class DocumentEditor {
this.reportEdit(entity, name, value);
}
+ /**
+ * Writes what a `<text>` says to the document and reports it. Settled
+ * first for the same reason a prop is: one iteration of a loop cannot say
+ * something the others do not.
+ */
+ public editText(entity: Entity, text: string): void {
+ this.document.setText(entity, text);
+ this.settle(entity);
+ const source = entity.get(Source)?.value;
+
+ if (source) {
+ this.sink?.({ kind: 'text', source, value: text });
+ }
+ }
+
/**
* Reports an edit whose change the editor already made itself. An entity a
* loop rendered is settled first (see `settle`): its element is every
diff --git a/apps/web/src/engine/fonts.ts b/apps/web/src/engine/fonts.ts
new file mode 100644
index 00000000..936c3cb5
--- /dev/null
+++ b/apps/web/src/engine/fonts.ts
@@ -0,0 +1,72 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * The half of the font story that needs a browser the runtime cannot assume:
+ * the machine's own families, behind the Local Font Access API. Web fonts and
+ * loading live in `@diffusionstudio/runtime` (`getWebFonts`, `loadWebFont`),
+ * which the CLI shares.
+ */
+
+import { FontStyle } from '@diffusionstudio/runtime';
+
+import type { FontSources } from '@diffusionstudio/runtime';
+
+interface LocalFont {
+ family: string;
+ fullName: string;
+ postscriptName: string;
+ style: string;
+}
+
+/**
+ * Every family installed on the machine, grouped by family. Requires the Local
+ * Font Access API and a granted permission; the caller handles the rejection.
+ */
+export async function getLocalFonts(): Promise<FontSources[]> {
+ const families = new Map<string, LocalFont[]>();
+
+ for (const font of (await window.queryLocalFonts()) as LocalFont[]) {
+ const variants = families.get(font.family);
+ if (variants) variants.push(font);
+ else families.set(font.family, [font]);
+ }
+
+ return [...families].map(([family, fonts]) => ({
+ family,
+ variants: fonts.map((font) => ({
+ family,
+ source: `local('${font.fullName}'), local('${font.postscriptName}')`,
+ weight: matchFontWeight(font.style),
+ style: matchFontStyle(font.style),
+ })),
+ }));
+}
+
+/** The style a local font names itself in, as the runtime spells it. */
+function matchFontStyle(style: string): FontStyle {
+ if (/oblique/i.test(style)) return FontStyle.OBLIQUE;
+ if (/italic/i.test(style)) return FontStyle.ITALIC;
+ return FontStyle.NORMAL;
+}
+
+/**
+ * The CSS weight a local font's style name comes to. Ordered so the longer
+ * names win: "extrabold" is not a bold, and "extralight" is not a light.
+ */
+function matchFontWeight(weight: string): string {
+ const matches: [RegExp, string][] = [
+ [/black|heavy/i, '900'],
+ [/extrabold|ultrabold/i, '800'],
+ [/semibold|demibold/i, '600'],
+ [/bold|strong/i, '700'],
+ [/medium/i, '500'],
+ [/normal|regular|book|plain/i, '400'],
+ [/extralight|ultralight/i, '200'],
+ [/thin|hairline/i, '100'],
+ [/light/i, '300'],
+ ];
+
+ return matches.find(([pattern]) => pattern.test(weight))?.[1] ?? '400';
+}
diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.ts
index 53656795..f04748e3 100644
--- a/apps/web/src/engine/index.ts
+++ b/apps/web/src/engine/index.ts
@@ -11,6 +11,7 @@ export * from './editor';
export * from './traits';
export * from './input';
export * from './hud';
+export * from './fonts';
export * from './library';
export * from './asset-actions';
export * from './keyframes';
diff --git a/apps/web/src/projects/edits.ts b/apps/web/src/projects/edits.ts
index dc9c2a5a..a553db90 100644
--- a/apps/web/src/projects/edits.ts
+++ b/apps/web/src/projects/edits.ts
@@ -35,6 +35,10 @@ class EditWriter {
private inserts = new Map<string, InsertEdit>();
private moves = new Map<string, MoveEdit>();
private pending = new Map<string, InsertEdit['props']>();
+ // What a `<text>` says, by element. Its own map rather than a prop: the
+ // file spells it between the tags, and the last value is the only one
+ // worth writing, same as a prop's.
+ private texts = new Map<string, string>();
private removes = new Set<string>();
// Pending sources a write is out for: edits to them wait for the answer.
private inflight = new Set<string>();
@@ -73,6 +77,12 @@ class EditWriter {
} else {
this.moves.set(edit.source, edit);
}
+ } else if (edit.kind === 'text') {
+ // What an element still waiting to be inserted says is part of how
+ // it is inserted, the way a prop of it is.
+ const insert = this.inserts.get(edit.source);
+ if (insert) insert.text = edit.value;
+ else this.texts.set(edit.source, edit.value);
} else {
// A prop of an element still waiting to be inserted is part of how
// it is inserted.
@@ -120,6 +130,7 @@ class EditWriter {
for (const source of doomed) {
this.inserts.delete(source);
this.pending.delete(source);
+ this.texts.delete(source);
this.moves.delete(source);
}
@@ -147,7 +158,7 @@ class EditWriter {
private flush(): void {
this.timer = undefined;
- if (!this.unrolls.size && !this.inserts.size && !this.moves.size && !this.pending.size && !this.removes.size) return;
+ if (!this.unrolls.size && !this.inserts.size && !this.moves.size && !this.pending.size && !this.texts.size && !this.removes.size) return;
// Anything addressed through an element whose insert is still out
// waits for its name: edits to it, and inserts or moves under or
@@ -156,6 +167,7 @@ class EditWriter {
const heldInserts = new Map([...this.inserts].filter(([, insert]) => waits(insert.parent) || waits(insert.before)));
const heldMoves = new Map([...this.moves].filter(([source, move]) => waits(source) || waits(move.parent) || waits(move.before)));
const held = new Map([...this.pending].filter(([source]) => waits(source)));
+ const heldTexts = new Map([...this.texts].filter(([source]) => waits(source)));
const heldRemoves = new Set([...this.removes].filter(waits));
const edits: SourceEdit[] = [
// First: the copies an unroll makes are what the rest is addressed to.
@@ -181,9 +193,15 @@ class EditWriter {
parent,
...(before === undefined ? {} : { before }),
})),
- ...[...this.pending]
- .filter(([source]) => !held.has(source))
- .map(([source, props]): SourceEdit => ({ kind: 'set', source, props })),
+ // One `set` per element, whatever it changed: a prop, its text, or both.
+ ...[...new Set([...this.pending.keys(), ...this.texts.keys()])]
+ .filter((source) => !held.has(source) && !heldTexts.has(source))
+ .map((source): SourceEdit => ({
+ kind: 'set',
+ source,
+ props: this.pending.get(source) ?? {},
+ ...(this.texts.has(source) ? { text: this.texts.get(source)! } : {}),
+ })),
// Last: cutting an unnamed element moves the positions of everything
// after it, and nothing above is addressed to what is being removed.
...[...this.removes]
@@ -202,6 +220,7 @@ class EditWriter {
this.inserts = heldInserts;
this.moves = heldMoves;
this.pending = held;
+ this.texts = heldTexts;
this.removes = heldRemoves;
writeProject(this.dir, edits)
@@ -243,6 +262,13 @@ class EditWriter {
this.pending.delete(source);
if (next) this.pending.set(next, { ...this.pending.get(next), ...props });
}
+ for (const source of [...this.texts.keys()]) {
+ const next = rename(source);
+ if (next === source) continue;
+ const text = this.texts.get(source)!;
+ this.texts.delete(source);
+ if (next) this.texts.set(next, text);
+ }
for (const [source, insert] of [...this.inserts]) {
const parent = rename(insert.parent);
if (parent === undefined) {
@@ -282,7 +308,7 @@ class EditWriter {
this.inflight = new Set();
// What was held back has its names now.
- if (this.inserts.size || this.moves.size || this.pending.size || this.removes.size) this.schedule();
+ if (this.inserts.size || this.moves.size || this.pending.size || this.texts.size || this.removes.size) this.schedule();
}
}
diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.ts
index 36a1a0e9..15c45ba9 100644
--- a/packages/reconciler/src/document.ts
+++ b/packages/reconciler/src/document.ts
@@ -593,6 +593,29 @@ export class RuntimeDocument implements ProjectDocument<HostNode> {
return !isSceneNode(node);
}
+ /**
+ * Replaces everything a `<text>` says. Its children rather than a prop, so
+ * an editor changing it comes here instead of through `setProperty`. The
+ * text nodes the reconciler holds keep their identity — the first says all
+ * of it and the rest say nothing — so a render that later updates one of
+ * them still lands where it did. An entity holding none (a text drawn on
+ * the canvas, whose element is not written yet) gets `Chars` alone.
+ */
+ public setText(entity: Entity, text: string): void {
+ const parts = textParts(entity);
+
+ if (parts.length === 0) {
+ entity.add(Chars);
+ entity.set(Chars, { value: text });
+ return;
+ }
+
+ for (const [index, part] of parts.entries()) {
+ part.text = index === 0 ? text : '';
+ }
+ syncChars(entity);
+ }
+
public setProperty(node: HostNode, name: string, value: unknown): void {
if (!isSceneNode(node)) return;
const { entity } = node;
@@ -792,7 +815,16 @@ export class RuntimeDocument implements ProjectDocument<HostNode> {
if (name === 'width') entity.set(StrokeStyle, { width: size ?? 1 });
return;
}
- if (size === undefined) return;
+ if (size === undefined) {
+ // A text is the one element whose box is optional: with
+ // neither bound authored it sizes itself to its glyphs
+ // again. Size holds both, so it only goes when both are.
+ const other = name === 'width' ? 'height' : 'width';
+ if (isText(entity) && toNumber(entity.get(Authored)?.props[other]) === undefined) {
+ entity.remove(Size);
+ }
+ return;
+ }
resizeEntity(this.world, entity, { [name]: size });
syncSurfaceSize(this.world, entity);
return;
diff --git a/packages/runtime/MIGRATION.md b/packages/runtime/MIGRATION.md
index 6c363699..1fbc0a6f 100644
--- a/packages/runtime/MIGRATION.md
+++ b/packages/runtime/MIGRATION.md
@@ -75,7 +75,8 @@ Done:
| Draw tools + toolbar (armed tool is the `Tool` world trait) | `components/canvas/draw-overlay.tsx` |
| Input, HUD, camera, alignment | `engine/input/`, `engine/hud/`, `engine/align.ts` |
| Project config (per-scene export settings in package.json) | `engine/project-config.ts` |
-| Panels: header, background, scene template, asset info, time, appearance, alignment, export, layout | `components/sidebar-right/inspector/` |
+| Panels: header, background, scene template, asset info, time, appearance, alignment, export, layout, text | `components/sidebar-right/inspector/` |
+| Local font families (web fonts and loading are the runtime's) | `engine/fonts.ts` (`getLocalFonts`) |
Hosted JSX surface is `COMPOSITION_TAGS` (`packages/jsx/src/source.ts`): the structural tags, the media tags, `<captions>`, the paint family, `<stroke>`, `<shadow>`, `<effect>`, `<animation>`, `<keyframeTrack>`/`<keyframe>`, `<html>`/`<surface>`. `mask` is a `<rect>` prop, not a tag.
@@ -86,8 +87,12 @@ Conventions worth repeating when migrating the next panel:
- `syncKeyframe` after a prop write keeps an existing track in step, since the motion system would otherwise overwrite the edit next tick. **Exception:** `width`/`height` sync *before* the write, because the document's handler is `resizeEntity`, which syncs the track itself and would mint an unsourced keyframe first. The canvas resize in `engine/input/interactions.ts` has the same gap, unfixed.
- State with no JSX spelling (`KeepAspectRatio`, `ClipsContent`, `Skew`) is written to the trait alone and does not survive a recompile. Giving any of them a prop is a separate decision; a lock snapshot would then have to come from the authored size, not from whatever `Size` holds at mount.
- Panels still on bitecs import the diamond from `components/ui/keyframe-bitecs.tsx` until they move.
+- What a `<text>` says is its children, not a prop, so it travels as its own edit end to end: `editor.editText` -> `TextEdit` -> the writer's `SourceSet.text` -> `RuntimeDocument.setText`. The document keeps the reconciler's text nodes: the first says all of it and the rest say nothing, so a project that later re-renders one of them still lands.
+- A text is the one element whose box is optional (`Size` absent = sized to its glyphs), so the text panel's "Grow" toggle is `width`/`height` being authored at all. Unsetting a bound drops `Size` only once neither is left, which is why the toggle writes `width` before `height`.
-Still on bitecs: transform, caption-settings, text, fills, strokes, shadows, effects, animations, transition, masks, audio, interpolation panels; the timeline's keyframe layer; the whole timeline UI.
+Still on bitecs: transform, caption-settings, fills, strokes, shadows, effects, animations, transition, masks, audio, interpolation panels; the timeline's keyframe layer; the whole timeline UI.
+
+Two deliberate departures from the old text panel: `letterSpacing` is shown in px (the trait's unit and the prop's; the bitecs panel showed the same number as a percentage), and the font a text is set in — family, weight, size — is written out plainly rather than unset at its default, since a font is what a text *is* and not a modifier of it. `<captions>` has no host yet, so the caption half of the panel is unreachable and was carried over as it stood.
**Left stale on purpose** (deferred to a docs/examples pass): the eight `examples/*.tsx` still open with `<rect scene="...">` and no `<stage>`, so `tsc -p examples --noEmit` fails on them, and `reference/jsx/*` still describes the pre-`<stage>` model and `key` as the `syncTo` target. `reference/jsx` is stale as a whole; patching rows piecemeal would hide that.