Skip to content

The VS Code of video editing, built for agents.

TypeScript

Add stroke and shadow support in JSX and runtime

konstantin-paulus2374c33baab6
diff --git a/packages/jsx/src/index.ts b/packages/jsx/src/index.ts
index 173b682f..b8b849de 100644
--- a/packages/jsx/src/index.ts
+++ b/packages/jsx/src/index.ts
@@ -58,9 +58,13 @@ export type {
SceneProps,
SequenceProps,
ShaderPaintProps,
+ ShadowProps,
SolidPaintProps,
SourceProps,
StageProps,
+ StrokeCap,
+ StrokeJoin,
+ StrokeProps,
SurfacePaintProps,
SurfaceProps,
TextProps,
diff --git a/packages/jsx/src/jsx-runtime.ts b/packages/jsx/src/jsx-runtime.ts
index 1cc734a1..b9971913 100644
--- a/packages/jsx/src/jsx-runtime.ts
+++ b/packages/jsx/src/jsx-runtime.ts
@@ -33,9 +33,11 @@ import type {
SceneProps,
SequenceProps,
ShaderPaintProps,
+ ShadowProps,
SolidPaintProps,
SourceProps,
StageProps,
+ StrokeProps,
SurfacePaintProps,
SurfaceProps,
TextProps,
@@ -82,6 +84,8 @@ export declare namespace JSX {
linearGradientPaint: GradientPaintProps & SourceProps;
radialGradientPaint: GradientPaintProps & SourceProps;
colorStop: ColorStopProps & SourceProps;
+ stroke: StrokeProps & SourceProps;
+ shadow: ShadowProps & SourceProps;
htmlPaint: HtmlPaintProps & SourceProps;
html: HtmlProps & SourceProps;
shaderPaint: ShaderPaintProps & SourceProps;
diff --git a/packages/jsx/src/source.ts b/packages/jsx/src/source.ts
index 20645000..17701ac3 100644
--- a/packages/jsx/src/source.ts
+++ b/packages/jsx/src/source.ts
@@ -103,6 +103,8 @@ export const COMPOSITION_TAGS = [
"linearGradientPaint",
"radialGradientPaint",
"colorStop",
+ "stroke",
+ "shadow",
"htmlPaint",
"html",
"shaderPaint",
diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.ts
index 288e9bd1..0f47250b 100644
--- a/packages/jsx/src/types.ts
+++ b/packages/jsx/src/types.ts
@@ -14,6 +14,12 @@ export type Time = number | `${number}f` | `${string}:${string}`;
export type Fit = "cover" | "contain" | "fill";
+/** How a stroke turns a corner: the canvas `lineJoin` values. */
+export type StrokeJoin = "miter" | "round" | "bevel";
+
+/** How a stroke ends an open path: the canvas `lineCap` values. */
+export type StrokeCap = "butt" | "round" | "square";
+
/**
* Easing for the segment from a keyframe to the next one: a named preset or
* an explicit descriptor. `cubicBezier(x1,y1,x2,y2)` takes CSS-style control
@@ -145,7 +151,10 @@ export type PatchProps = {
*/
offsetX?: Animatable<number>;
offsetY?: Animatable<number>;
- /** Box size, px. Defaults to the parent's size. Animatable. */
+ /**
+ * Box size, px. Defaults to the parent's size. Animatable. On a `<stroke>`
+ * `width` is the line width instead, px (default 1).
+ */
width?: Animatable<number>;
height?: Animatable<number>;
/** Rotation in degrees. Animatable. */
@@ -154,6 +163,14 @@ export type PatchProps = {
opacity?: Animatable<number>;
/** Uniform corner radius, px. Animatable. */
cornerRadius?: Animatable<number>;
+ /** Blur radius of a `<shadow>`, px. Default 0. Animatable. */
+ blur?: Animatable<number>;
+ /** How a `<stroke>` turns corners. Default "miter". */
+ join?: StrokeJoin;
+ /** How a `<stroke>` ends open paths (text glyphs). Default "butt". */
+ cap?: StrokeCap;
+ /** Miter length limit of a `<stroke>`, as a ratio of its width. Default 10. */
+ miterLimit?: number;
/** Parent-timeline time at which the node begins. Default 0. */
start?: Time;
/** Parent-timeline time at which the node ends. Alternative to `sourceOut`. */
@@ -214,7 +231,7 @@ export type PatchProps = {
/** CSS weights 100–900, or "normal" / "bold". */
fontWeight?: number | "normal" | "bold";
fontStyle?: "normal" | "italic";
- /** Any CSS color: the glyph color on `<Text>`, the paint color on paints and color stops. Animatable. */
+ /** Any CSS color: the glyph color on `<Text>`, the paint color on paints, strokes, shadows and color stops. Animatable. */
color?: Animatable<string>;
/** Horizontal alignment of glyphs within the box. Default "left". */
textAlign?: "left" | "center" | "right";
@@ -305,10 +322,28 @@ export type GroupProps = CommonProps & Pick<PatchProps, "fill"> & {
};
export type RectProps = CommonProps & Pick<PatchProps, "fill"> & {
- /** Paint children (`<SolidPaint>`, `<LinearGradientPaint>`, `<RadialGradientPaint>`). */
+ /**
+ * Paint children (`<SolidPaint>`, `<LinearGradientPaint>`,
+ * `<RadialGradientPaint>`), plus `<Stroke>` and `<Shadow>` children.
+ */
children?: SolidJSX.Element;
};
+/**
+ * `<stroke>` — an outline of the parent's box (or glyphs), a sub-entity like a
+ * paint: `color`/`opacity` are its paint, `width`/`join`/`cap`/`miterLimit`
+ * its line style. Several stack in document order, later ones on top.
+ */
+export type StrokeProps = Required<Pick<PatchProps, "color">> &
+ Pick<PatchProps, "opacity" | "width" | "join" | "cap" | "miterLimit">;
+
+/**
+ * `<shadow>` — a drop shadow beneath the parent's box (or glyphs): a blurred,
+ * offset copy of its silhouette in `color`. Several stack in document order.
+ */
+export type ShadowProps = Required<Pick<PatchProps, "color">> &
+ Pick<PatchProps, "opacity" | "blur" | "offsetX" | "offsetY">;
+
export type SolidPaintProps = Required<Pick<PatchProps, "color">> & Pick<PatchProps, "opacity">;
export type GradientPaintProps = Pick<PatchProps, "opacity"> & {
@@ -324,14 +359,14 @@ export type ColorStopProps = Required<Pick<PatchProps, "offset" | "color">> &
export type VideoProps = CommonProps &
Required<Pick<PatchProps, "src">> &
Pick<PatchProps, "objectFit" | "volume" | "muted" | "syncTo"> & {
- /** Paint children, stacked over the media paint created by `src`. */
+ /** Paint children, stacked over the media paint created by `src`; `<Stroke>` and `<Shadow>` children. */
children?: SolidJSX.Element;
};
export type ImageProps = CommonProps &
Required<Pick<PatchProps, "src">> &
Pick<PatchProps, "objectFit"> & {
- /** Paint children, stacked over the media paint created by `src`. */
+ /** Paint children, stacked over the media paint created by `src`; `<Stroke>` and `<Shadow>` children. */
children?: SolidJSX.Element;
};
@@ -379,7 +414,10 @@ export type TextProps = CommonProps &
PatchProps,
"fontFamily" | "fontSize" | "fontWeight" | "fontStyle" | "color" | "textAlign" | "textBaseline"
> & {
- /** The text content. Required. */
+ /**
+ * The text content, required; alongside it, paint, `<Stroke>` and
+ * `<Shadow>` children styling the glyphs.
+ */
children: SolidJSX.Element;
};
diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.ts
index a4f256be..92c329a1 100644
--- a/packages/reconciler/src/document.ts
+++ b/packages/reconciler/src/document.ts
@@ -10,6 +10,7 @@ import {
Assets,
Audio,
Background,
+ Blur,
Chars,
ClipsContent,
createEntity,
@@ -25,7 +26,6 @@ import {
getEntityTree,
getParentEntity,
getParentNode,
- isPaintEntity,
isText,
ItemIndex,
Muted,
@@ -50,11 +50,16 @@ import {
Rotation,
Scene,
Selected,
+ Shadow,
Source,
SourceIn,
SourceOut,
setCameraMatrix,
Start,
+ Stroke,
+ StrokeCap,
+ StrokeJoin,
+ StrokeStyle,
TextAlign,
TextBaseline,
TextStyle,
@@ -198,6 +203,18 @@ const PAINT_TYPES: Record<string, PaintType> = {
radialGradientPaint: PaintType.RADIAL_GRADIENT,
};
+const STROKE_JOINS: Record<string, StrokeJoin> = {
+ miter: StrokeJoin.MITER,
+ round: StrokeJoin.ROUND,
+ bevel: StrokeJoin.BEVEL,
+};
+
+const STROKE_CAPS: Record<string, StrokeCap> = {
+ butt: StrokeCap.BUTT,
+ round: StrokeCap.ROUND,
+ square: StrokeCap.SQUARE,
+};
+
const SCALE_MODES: Record<string, ScaleModeType> = {
cover: ScaleModeType.COVER,
contain: ScaleModeType.FIT,
@@ -355,14 +372,28 @@ export class RuntimeDocument implements ProjectDocument<HostNode> {
break;
}
case 'colorStop': {
- // Position only; `color`/`opacity` add Color/Opacity like anywhere else.
entity = createEntity(this.world);
entity.add(ColorStop);
break;
}
+ case 'stroke': {
+ entity = createEntity(this.world);
+ entity.add(Stroke);
+ entity.add(Paint);
+ entity.set(Paint, { value: PaintType.SOLID });
+ entity.add(Color);
+ entity.add(StrokeStyle);
+ break;
+ }
+ case 'shadow': {
+ entity = createEntity(this.world);
+ entity.add(Shadow);
+ entity.add(Color);
+ break;
+ }
default:
throw new Error(
- `<${tag}> is not supported yet (only <stage>, <scene>, <group>, <sequence>, <rect>, <text>, <video>, <image>, <audio>, <solidPaint>, <linearGradientPaint>, <radialGradientPaint> and <colorStop>).`,
+ `<${tag}> is not supported yet (only <stage>, <scene>, <group>, <sequence>, <rect>, <text>, <video>, <image>, <audio>, <solidPaint>, <linearGradientPaint>, <radialGradientPaint>, <colorStop>, <stroke> and <shadow>).`,
);
}
@@ -473,10 +504,43 @@ export class RuntimeDocument implements ProjectDocument<HostNode> {
case 'width':
case 'height': {
const size = toNumber(value);
+ if (entity.has(Stroke)) {
+ // A stroke's width is its line width; it has no box.
+ if (name === 'width') entity.set(StrokeStyle, { width: size ?? 1 });
+ return;
+ }
if (size === undefined) return;
resizeEntity(this.world, entity, { [name]: size });
return;
}
+ case 'join': {
+ if (!entity.has(Stroke)) return;
+ const join = typeof value === 'string' ? STROKE_JOINS[value] : undefined;
+ entity.set(StrokeStyle, { join: join ?? StrokeJoin.MITER });
+ return;
+ }
+ case 'cap': {
+ if (!entity.has(Stroke)) return;
+ const cap = typeof value === 'string' ? STROKE_CAPS[value] : undefined;
+ entity.set(StrokeStyle, { cap: cap ?? StrokeCap.BUTT });
+ return;
+ }
+ case 'miterLimit': {
+ if (!entity.has(Stroke)) return;
+ entity.set(StrokeStyle, { miterLimit: toNumber(value) ?? 10 });
+ return;
+ }
+ case 'blur': {
+ const blur = toNumber(value);
+ if (blur === undefined) {
+ entity.remove(Blur);
+ return;
+ }
+
+ entity.add(Blur);
+ entity.set(Blur, { value: blur });
+ return;
+ }
case 'start':
case 'end':
case 'sourceIn':
@@ -655,9 +719,6 @@ export class RuntimeDocument implements ProjectDocument<HostNode> {
if (parent.entity === node.entity) return;
- if (isText(parent.entity) && !isPaintEntity(node.entity)) {
- throw new Error('<text> only takes text and paint children.');
- }
if (getParentEntity(node.entity) !== parent.entity) {
// appendChild only takes top-level entities, so a move between two
diff --git a/packages/reconciler/src/elements.ts b/packages/reconciler/src/elements.ts
index 3c5bebf5..66351acf 100644
--- a/packages/reconciler/src/elements.ts
+++ b/packages/reconciler/src/elements.ts
@@ -31,7 +31,9 @@ import type {
SceneProps,
SequenceProps,
ShaderPaintProps,
+ ShadowProps,
SolidPaintProps,
+ StrokeProps,
SurfacePaintProps,
SurfaceProps,
TextProps,
@@ -88,6 +90,8 @@ export const SolidPaint = hostElement<SolidPaintProps>("SolidPaint");
export const LinearGradientPaint = hostElement<GradientPaintProps>("LinearGradientPaint");
export const RadialGradientPaint = hostElement<GradientPaintProps>("RadialGradientPaint");
export const ColorStop = hostElement<ColorStopProps>("ColorStop");
+export const Stroke = hostElement<StrokeProps>("Stroke");
+export const Shadow = hostElement<ShadowProps>("Shadow");
export const HtmlPaint = hostElement<HtmlPaintProps>("HtmlPaint");
export const Html = hostElement<HtmlProps>("Html");
export const ShaderPaint = hostElement<ShaderPaintProps>("ShaderPaint");
diff --git a/packages/reconciler/src/patch.ts b/packages/reconciler/src/patch.ts
index 3a97656d..0ccdbf8d 100644
--- a/packages/reconciler/src/patch.ts
+++ b/packages/reconciler/src/patch.ts
@@ -23,6 +23,10 @@ export const PATCH_PROP_KEYS = Object.keys({
rotation: true,
opacity: true,
cornerRadius: true,
+ blur: true,
+ join: true,
+ cap: true,
+ miterLimit: true,
start: true,
end: true,
sourceIn: true,
diff --git a/packages/runtime/MIGRATION.md b/packages/runtime/MIGRATION.md
index f0e9db36..28dc410b 100644
--- a/packages/runtime/MIGRATION.md
+++ b/packages/runtime/MIGRATION.md
@@ -145,6 +145,8 @@ apps/web now depends on `@diffusionstudio/runtime` and `@diffusionstudio/koota-s
**The active entity is a document property too.** `active?: boolean` in `PatchProps` (picked into `SceneProps` only for now; the scene restriction is a single assertion in `setActive` and goes when it goes), listed in `PATCH_PROP_KEYS`. The `ActiveScene` world trait is gone; `Active` is a tag on the entity, so it dies with the entity (no clearing in `removeNode`) and comes back from `<scene active>` on remount. Two invariants live in `world/observers.ts`, so they hold whichever path adds the tag: `onAdd(Active)` strips it from every other holder (last wins), and `onAdd(ChildOf('*'))` strips it when the new parent is not the stage (root only). The ChildOf half is what catches a nested `<rect active>` from a file, because Solid sets props before insertion while the entity is still a stage child; the cost is that such a rect first steals the tag and then loses it, so a file saying `active` on a scene and on something nested inside it ends with nothing active until the mount fallback below. `DocumentEditor.activate(entity | null)` is the editor route (trait via `setActive`, `active: false` reported for the one it left, `true` for the new one); overlays use it, the encoder calls `setActive` directly (headless, nothing to report), `useActiveScene()` reads `useQuery(Active)[0]`. `pages/editor.tsx` activates the first root scene through the editor after a mount that produced no active entity, so a project without one gets it written into the file and it sticks. A file naming two active scenes keeps both until the next `activate` cleans up; the document does not report edits.
+ **`<stroke>` and `<shadow>` are hosted** (`StrokeProps`/`ShadowProps` in `@diffusionstudio/jsx`, `stroke`/`shadow` in `IntrinsicElements` and `COMPOSITION_TAGS`, `Stroke`/`Shadow` components in the reconciler), as sub-entity children of any geometry (`<rect>`, `<text>`, `<video>`, `<image>`; a `<text>` takes them next to its text nodes, alongside paints), stacking in document order. A stroke is `Stroke` + `Paint(SOLID)` + `Color` + `StrokeStyle`: `color`/`opacity` are its paint, `width` (the line width, since a stroke has no box: `setProperty('width')` branches on `Stroke` instead of resizing), `join` (`miter`/`round`/`bevel`), `cap` (`butt`/`round`/`square`) and `miterLimit` fill `StrokeStyle`, an unset one falling back to the trait's default. A shadow is `Shadow` + `Color`, with `opacity`, `blur` (new in `PatchProps`, writes the `Blur` trait), `offsetX`/`offsetY` (the same `Offset` trait a node's render offset uses). Two runtime changes came with it: **`StrokeStyle` moved from the stroked node onto the stroke sub-entity**, so each stroke has its own width/join/cap (`Computed.strokeWidth` and the `stroke.width` keyframe target are per stroke; `utils/stroke.ts` has `applyStrokeStyle`, which the render system and the text renderer call per stroke, and `findWidestStroke`, whose silhouette a stroked text's shadow takes), and `Cache.fills` excludes `Stroke` entities, since a stroke's `Paint` is what its outline is drawn with, not a fill of its parent (bitecs collected them into both). Not built yet: gradient strokes in JSX (`<stroke>` is solid only; the runtime still renders a stroke entity carrying a gradient `Paint` with `ColorStop` children).
+
**Left stale on purpose** (deferred to a docs/examples pass): all eight `examples/*.tsx` still open with `<rect scene="...">` and no `<stage>`, so `tsc -p examples --noEmit` fails on them; `reference/jsx/{scene,roots}.md` still describes the pre-`<stage>` model where a mount grafts roots into an existing document; and `reference/jsx/{audio-sync,video,audio,elements}.md` still document `key` as the `syncTo` target. Deliberately not half-migrated: `reference/jsx` is stale as a whole, and patching the `key` rows alone would hide that.
## Remaining work (suggested order)
diff --git a/packages/runtime/src/actions/cache.ts b/packages/runtime/src/actions/cache.ts
index 1abcb1e3..c70aaa33 100644
--- a/packages/runtime/src/actions/cache.ts
+++ b/packages/runtime/src/actions/cache.ts
@@ -66,9 +66,10 @@ export function rebuildCaches(world: World, entity: Entity, parent: Entity | nul
}
// A geometry carrying Paint is not a fill of its parent: that is its own
- // intrinsic paint (see getIntrinsicPaint).
- if (entity.has(Paint) && !entity.has(Geometry)) {
- cache.fills[pid] = collect(Paint, Not(Geometry), ChildOf(parent))
+ // intrinsic paint (see getIntrinsicPaint). Nor is a stroke: its Paint is
+ // what the outline is drawn with.
+ if (entity.has(Paint) && !entity.has(Geometry) && !entity.has(Stroke)) {
+ cache.fills[pid] = collect(Paint, Not(Geometry), Not(Stroke), ChildOf(parent))
.sort(sortByItemIndex);
}
diff --git a/packages/runtime/src/systems/render.ts b/packages/runtime/src/systems/render.ts
index 27f14a17..8df5235f 100644
--- a/packages/runtime/src/systems/render.ts
+++ b/packages/runtime/src/systems/render.ts
@@ -14,12 +14,12 @@ import { cubicBezier } from 'animejs';
import { store } from '../world/store';
import {
COMPOSITE_OPERATIONS, EffectType, GeometryType, PaintType, ScaleModeType,
- StrokeCap, StrokeJoin, TransitionType,
+ TransitionType,
} from '../constants';
import {
ChildOf, Hidden, Culled, Generating, Interactive, IsMask,
ClipsContent, Geometry, Group, Paint, Color, Caption, ScaleMode, Shader,
- BlendMode, Effect, StrokeStyle, AssetId, Transition, MixedCornerRadius,
+ BlendMode, Effect, AssetId, Transition, MixedCornerRadius,
LocalTransform, WorldTransform, Computed, Cache,
HtmlHostHandle, SurfaceHostHandle,
Mode, Time, FrameRate, Camera, Background, RenderSurface, Assets,
@@ -29,6 +29,7 @@ import {
import { getParentNode } from '../queries/hierarchy';
import { getViewMatrix } from '../queries/camera';
import { colorToHex } from '../utils/color';
+import { applyStrokeStyle } from '../utils/stroke';
import { renderText } from '../utils/text';
import { getTransitionWindow } from '../utils/transition';
import { getIntrinsicPaint } from '../utils/time';
@@ -497,16 +498,10 @@ function renderStrokes(world: World, entity: Entity): void {
const strokes = store(world, Cache).strokes[eid];
if (!strokes) return;
- const strokeStyle = store(world, StrokeStyle);
const computed = store(world, Computed);
const blendMode = store(world, BlendMode);
const paintStore = store(world, Paint);
- ctx.lineWidth = computed.strokeWidth[eid]!;
- ctx.lineJoin = StrokeJoin[strokeStyle.join[eid] ?? 0]!.toLocaleLowerCase() as CanvasLineJoin;
- ctx.lineCap = StrokeCap[strokeStyle.cap[eid] ?? 0]!.toLocaleLowerCase() as CanvasLineCap;
- ctx.miterLimit = strokeStyle.miterLimit[eid] ?? 3;
-
for (const stroke of strokes) {
if (stroke.has(Hidden)) continue;
const sid = stroke.id();
@@ -518,6 +513,7 @@ function renderStrokes(world: World, entity: Entity): void {
ctx.globalCompositeOperation = COMPOSITE_OPERATIONS[bi]!;
}
+ applyStrokeStyle(ctx, world, stroke);
ctx.globalAlpha = savedAlpha * computed.opacity[sid]!;
const paintType = paintStore.value[sid];
diff --git a/packages/runtime/src/traits/node.ts b/packages/runtime/src/traits/node.ts
index b39ab3f4..d4b5e73e 100644
--- a/packages/runtime/src/traits/node.ts
+++ b/packages/runtime/src/traits/node.ts
@@ -40,8 +40,9 @@ export const IsMask = trait();
// sub-entities in ChildOf queries).
export const Shadow = trait();
-// Tag for stroke sub-entities (distinguishes them from the StrokeStyle trait
-// on the parent in ChildOf queries).
+// Tag for stroke sub-entities: the entity is the stroke's paint (Paint/Color/
+// Opacity/BlendMode like a fill; a missing Paint reads as solid) and carries
+// its own StrokeStyle.
export const Stroke = trait();
export const Hidden = trait();
diff --git a/packages/runtime/src/traits/style.ts b/packages/runtime/src/traits/style.ts
index 882c77c6..126869af 100644
--- a/packages/runtime/src/traits/style.ts
+++ b/packages/runtime/src/traits/style.ts
@@ -44,6 +44,9 @@ export const Effect = trait({
// cross-fade.
export const ColorStop = trait({ offset: 0 });
+// How a stroke sub-entity is drawn: line width, joins, caps. Lives on the
+// stroke itself (next to its Paint/Color/Opacity), so each stroke of a node
+// has its own width. Absent means a 1px miter/butt line.
export const StrokeStyle = trait({
width: 1,
join: StrokeJoin.MITER as StrokeJoin,
diff --git a/packages/runtime/src/utils/index.ts b/packages/runtime/src/utils/index.ts
index 198f68fc..a89f8649 100644
--- a/packages/runtime/src/utils/index.ts
+++ b/packages/runtime/src/utils/index.ts
@@ -5,6 +5,7 @@ export * from './color';
export * from './text';
export * from './live-mounts';
export * from './sort';
+export * from './stroke';
export * from './text-motion';
export * from './time';
export * from './transition';
diff --git a/packages/runtime/src/utils/stroke.ts b/packages/runtime/src/utils/stroke.ts
new file mode 100644
index 00000000..977979ea
--- /dev/null
+++ b/packages/runtime/src/utils/stroke.ts
@@ -0,0 +1,47 @@
+/* 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/. */
+
+import { store } from '../world/store';
+import { StrokeCap, StrokeJoin } from '../constants';
+import { StrokeStyle, Computed, Hidden } from '../traits';
+
+import type { Entity, World } from 'koota';
+
+type Ctx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+
+/**
+ * Sets the context's line style from a stroke sub-entity's StrokeStyle. The
+ * width comes from Computed (animatable); a stroke without the trait draws
+ * as the trait's defaults.
+ */
+export function applyStrokeStyle(ctx: Ctx, world: World, stroke: Entity): void {
+ const style = store(world, StrokeStyle);
+ const sid = stroke.id();
+
+ ctx.lineWidth = store(world, Computed).strokeWidth[sid] ?? 1;
+ ctx.lineJoin = StrokeJoin[style.join[sid] ?? StrokeJoin.MITER]!.toLowerCase() as CanvasLineJoin;
+ ctx.lineCap = StrokeCap[style.cap[sid] ?? StrokeCap.BUTT]!.toLowerCase() as CanvasLineCap;
+ ctx.miterLimit = style.miterLimit[sid] ?? 10;
+}
+
+/**
+ * The visible stroke of `strokes` drawn widest, or null when none is: what a
+ * shadow of a stroked shape takes its silhouette from.
+ */
+export function findWidestStroke(world: World, strokes: Entity[]): Entity | null {
+ const computed = store(world, Computed);
+ let widest: Entity | null = null;
+ let width = -Infinity;
+
+ for (const stroke of strokes) {
+ if (stroke.has(Hidden)) continue;
+ const value = computed.strokeWidth[stroke.id()] ?? 1;
+ if (value > width) {
+ width = value;
+ widest = stroke;
+ }
+ }
+
+ return widest;
+}
diff --git a/packages/runtime/src/utils/text.ts b/packages/runtime/src/utils/text.ts
index 1f572fee..d14dbddd 100644
--- a/packages/runtime/src/utils/text.ts
+++ b/packages/runtime/src/utils/text.ts
@@ -6,16 +6,17 @@
import { store } from '../world/store';
import {
- COMPOSITE_OPERATIONS, PaintType, FontStyle, StrokeCap, StrokeJoin,
+ COMPOSITE_OPERATIONS, PaintType, FontStyle,
TextAlign, TextBaseline, TextCase,
} from '../constants';
import {
- Size, Hidden, Paint, Color, Blur, Offset, Opacity, BlendMode, StrokeStyle,
+ Size, Hidden, Paint, Color, Blur, Offset, Opacity, BlendMode,
Chars, TextStyle, TextRange, TextCache, Cache, Computed, Camera,
RenderSurface, Root,
} from '../traits';
import { clamp } from '../math/common';
import { colorToHex } from './color';
+import { applyStrokeStyle, findWidestStroke } from './stroke';
import { createLinearGradient, createRadialGradient } from '../systems/gradients';
import type { Entity, World } from 'koota';
@@ -144,16 +145,6 @@ function applyFont(ctx: Ctx, world: World, entity: Entity, ranges: Entity[]) {
ctx.letterSpacing = `${spacing}px`;
}
-function applyStroke(ctx: Ctx, world: World, entity: Entity) {
- const stroke = store(world, StrokeStyle);
- const eid = entity.id();
-
- ctx.lineWidth = stroke.width[eid] ?? 1;
- ctx.lineJoin = StrokeJoin[stroke.join[eid] ?? 0]!.toLocaleLowerCase() as CanvasLineJoin;
- ctx.lineCap = StrokeCap[stroke.cap[eid] ?? 0]!.toLocaleLowerCase() as CanvasLineCap;
- ctx.miterLimit = stroke.miterLimit[eid] ?? 3;
-}
-
function shapeTokens(world: World, entity: Entity): void {
const computed = store(world, Computed);
const textStyle = store(world, TextStyle);
@@ -306,11 +297,12 @@ function renderTokens(ctx: Ctx, world: World, entity: Entity): void {
for (const word of words) {
applyFont(ctx, world, entity, word.ranges);
- const strokes = getStrokes(world, entity, word.ranges);
const shadows = getShadows(world, entity, word.ranges);
- if (strokes.length) {
- applyStroke(ctx, world, entity);
+ // A stroked word's shadow is the widest stroke's silhouette.
+ const widest = findWidestStroke(world, getStrokes(world, entity, word.ranges));
+ if (widest !== null) {
+ applyStrokeStyle(ctx, world, widest);
}
// Draw shadows first (if any)
@@ -325,7 +317,7 @@ function renderTokens(ctx: Ctx, world: World, entity: Entity): void {
ctx.fillStyle = colorToHex(colorStore.value[sid] ?? 0x000000);
ctx.globalAlpha = savedAlpha * (opacityStore.value[sid] ?? 1);
- if (strokes.length) {
+ if (widest !== null) {
ctx.strokeText(word.chars, word.x, word.y);
} else {
ctx.fillText(word.chars, word.x, word.y);
@@ -352,7 +344,6 @@ function renderTokens(ctx: Ctx, world: World, entity: Entity): void {
if (!strokes.length) continue;
applyFont(ctx, world, entity, word.ranges);
- applyStroke(ctx, world, entity);
const w = computed.width[eid]!;
const h = computed.height[eid]!;
@@ -368,6 +359,7 @@ function renderTokens(ctx: Ctx, world: World, entity: Entity): void {
ctx.globalCompositeOperation = COMPOSITE_OPERATIONS[blendMode]!;
}
ctx.globalAlpha = savedAlpha * (opacityStore.value[sid] ?? 1);
+ applyStrokeStyle(ctx, world, stroke);
const paintType = paintStore.value[sid];
if (paintType === PaintType.LINEAR_GRADIENT) {