Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Studio: a stroke along a mask's edge (#269)

riverisbuilding847280877082
diff --git a/.changeset/mask-stroke.md b/.changeset/mask-stroke.md
new file mode 100644
index 0000000..ac701e3
--- /dev/null
+++ b/.changeset/mask-stroke.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Studio: a mask can have a stroke. In the inspector's Mask section, add one and pick its color, its width and where it lies against the mask's edge: inside, center or outside. It follows every shape, inverted ones too, scales with the clip or layer, and shows the same in the preview and the export. It is plain CSS: an SVG filter that draws the stroke, plus one mask layer for the part past the edge. Safari does not load this kind of filter, so a preview in Safari shows no stroke. For a center or outside stroke, the extra mask layer still applies there: the band past the mask's edge where the stroke would be shows the picture instead. The desktop app, Chrome and exports draw the stroke.
diff --git a/packages/openfilm/studio/ui/src/components/inspector-look.tsx b/packages/openfilm/studio/ui/src/components/inspector-look.tsx
index 08916e2..313c138 100644
--- a/packages/openfilm/studio/ui/src/components/inspector-look.tsx
+++ b/packages/openfilm/studio/ui/src/components/inspector-look.tsx
@@ -21,7 +21,8 @@ import {
type FadeSide, type InnerShadow, type PlacedStroke, type Shadow, type StrokePosition, type StrokeStyle,
} from '@/lib/clip-look';
import {
- MASK_FIELDS, MASK_SHAPES, fadeIn, maskDefault, maskOf, maskOwned, withFade, withMask, type Mask, type MaskBox, type MaskShape,
+ MASK_FIELDS, MASK_SHAPES, MASK_STROKE_POSITIONS, fadeIn, maskCss, maskDefault, maskOf, maskOwned, maskStrokeOf, withFade,
+ type Mask, type MaskBox, type MaskShape, type MaskStroke, type MaskStrokePosition,
} from '@/lib/clip-mask';
import type { MaskSession } from '@/lib/stage-mask';
import { previewSettled, type Look, type LookEdit, type LookRead, type LookSet } from '@/lib/look';
@@ -288,7 +289,8 @@ export function MaskSection({
const [editing, setEditing] = React.useState(false);
const canEdit = Boolean(onEditMask && target && look.n === 1);
- const write = (next: Mask | null): LookEdit => (read) => withMask(read('mask-image'), read('mask-composite'), next, mbox) ?? {};
+ /* the shape's stroke (a filter) is drawn again with it */
+ const write = (next: Mask | null): LookEdit => (read) => maskCss(read, next, mbox) ?? {};
const edit = (fn: (m: Mask) => Mask): LookEdit => (read) => {
const m = maskOf(read('mask-image'), read('mask-composite'), mbox);
return m ? write(fn(m))(read) : {};
@@ -318,7 +320,7 @@ export function MaskSection({
React.useEffect(() => {
if (!onEditMask) return;
if (!maskKey || !targetKey) { onEditMask(null); return; }
- const put = (m: Mask): LookEdit => (read) => withMask(read('mask-image'), read('mask-composite'), m, boxRef.current) ?? {};
+ const put = (m: Mask): LookEdit => (read) => maskCss(read, m, boxRef.current) ?? {};
onEditMask({
target: JSON.parse(targetKey) as MaskSession['target'],
mask: JSON.parse(maskKey) as Mask,
@@ -426,12 +428,80 @@ export function MaskSection({
onRevert={() => look.revert()}
/>
) : null}
+ <MaskStrokeFields look={look} t={t} box={mbox} />
</>
) : null}
</Section>
);
}
+/* a new stroke, px on the stage */
+const MASK_STROKE_PX = 4;
+
+/**
+ * The mask's stroke (lib/clip-mask maskCss): along the shape's edge, inside, across or outside it, in a color. Its
+ * width is in px on the stage, kept as % of the box's shorter side (as the feather), so it scales with the box.
+ */
+function MaskStrokeFields({ look, t, box }: { look: Look; t: T; box: MaskBox | null }) {
+ const short = box ? Math.min(box.w, box.h) : 100;
+ const stroke = look.common((read) => maskStrokeOf(read('filter')));
+ /* a filter written by hand takes no stroke from here */
+ const readable = look.common((read) => filterParts(read('filter')) != null) !== false;
+ const edit = (part: (now: MaskStroke) => Partial<MaskStroke>): LookEdit => (read) => {
+ const m = maskOf(read('mask-image'), read('mask-composite'), box);
+ if (!m) return {};
+ const now = maskStrokeOf(read('filter')) ?? { width: (MASK_STROKE_PX / short) * 100, color: '#ffffff', position: 'center' as const };
+ return maskCss(read, m, box, { ...now, ...part(now) }) ?? {};
+ };
+ const remove: LookEdit = (read) => {
+ const m = maskOf(read('mask-image'), read('mask-composite'), box);
+ return m ? maskCss(read, m, box, null) ?? {} : {};
+ };
+ const pxOfWidth = (w: number) => round((w / 100) * short, 1);
+ const width = (apply: FieldApply): LookEdit => edit((now) => ({ width: (Math.max(0, apply(pxOfWidth(now.width))) / short) * 100 }));
+ if (stroke === null || (!stroke && !readable)) return null;
+ return (
+ <>
+ <SubLabel aside={stroke ? (
+ <SectionAction label={t('inspector.effectRemove')} onClick={() => look.commit(remove)}><Minus size={12} /></SectionAction>
+ ) : (
+ <SectionAction label={t('inspector.strokeAdd')} onClick={() => look.commit(edit(() => ({})))}><Plus size={12} /></SectionAction>
+ )}>
+ {t('inspector.stroke')}
+ </SubLabel>
+ {stroke && stroke !== MIXED ? (
+ <>
+ <ColorField
+ label={t('inspector.strokeColor')}
+ value={look.common((read) => maskStrokeOf(read('filter'))?.color ?? '')}
+ onPreview={(c) => look.preview(edit(() => ({ color: c })))}
+ onCommit={(c) => look.commit(edit(() => ({ color: c })))}
+ />
+ <Row>
+ <SelectField
+ label={t('inspector.strokePosition')}
+ value={look.common((read) => maskStrokeOf(read('filter'))?.position ?? 'center')}
+ options={MASK_STROKE_POSITIONS.map((p) => ({ value: p, label: t(`inspector.strokePositions.${p}`) }))}
+ onCommit={(v) => look.commit(edit(() => ({ position: v as MaskStrokePosition })))}
+ />
+ <NumField
+ label={t('inspector.strokeWidth')}
+ prefix={<span className="block h-[7px] w-[9px] rounded-[1.5px] border-[1.5px]" style={{ borderColor: 'currentColor' }} />}
+ value={look.common((read) => { const w = maskStrokeOf(read('filter'))?.width; return w == null ? undefined : pxOfWidth(w); })}
+ unit="px"
+ min={0}
+ max={1000}
+ onPreview={(_, apply) => look.preview(width(apply))}
+ onCommit={(_, apply) => look.commit(width(apply))}
+ onRevert={() => look.revert()}
+ />
+ </Row>
+ </>
+ ) : null}
+ </>
+ );
+}
+
/* ───────────────────────────── appearance ───────────────────────────── */
/** Opacity (`opacity`) and blending (`mix-blend-mode`), with names people use; `children` adds fills. */
diff --git a/packages/openfilm/studio/ui/src/lib/clip-look.ts b/packages/openfilm/studio/ui/src/lib/clip-look.ts
index b565065..6103a2b 100644
--- a/packages/openfilm/studio/ui/src/lib/clip-look.ts
+++ b/packages/openfilm/studio/ui/src/lib/clip-look.ts
@@ -157,6 +157,15 @@ export function filterParts(v: string | undefined): { name: string; args: string
const joinFilter = (parts: { name: string; args: string }[]) => (parts.length ? parts.map((p) => `${p.name}(${p.args})`).join(' ') : null);
+/** The id of the SVG filter that draws a mask's stroke (lib/clip-mask): `url("data:…#openfilm-mask-stroke")`. */
+export const MASK_STROKE_ID = 'openfilm-mask-stroke';
+/**
+ * Whether a filter function is a mask's stroke: the panel's own (an SVG in a data URL, with its id), kept last so no
+ * adjustment tints it. A filter of the page's own, `url(#…)`, is not.
+ */
+export const isMaskStroke = (p: { name: string; args: string }) => p.name === 'url'
+ && /^["']?data:image\/svg\+xml,/.test(p.args) && new RegExp(`#${MASK_STROKE_ID}["']?$`).test(p.args);
+
/** A number or a percentage as a factor (`1.1`, `110%`). */
const factorOf = (args: string) => (/^-?\d*\.?\d+%$/.test(args) ? Number(args.slice(0, -1)) / 100 : /^-?\d*\.?\d+$/.test(args) ? Number(args) : NaN);
@@ -202,8 +211,9 @@ export function adjustOf(filter: string | undefined): Record<AdjustKey, number |
}
/**
- * The filter with one adjustment set (the function in place where it was, a new one before any shadow so the shadow
- * is not tinted), or taken out at 0. Null: no filter left. Functions the panel has no control for are kept as written.
+ * The filter with one adjustment set (the function in place where it was, a new one before any shadow or mask stroke
+ * so they are not tinted), or taken out at 0. Null: no filter left. Functions the panel has no control for are kept as
+ * written.
*/
export function withAdjust(filter: string | undefined, key: AdjustKey, n: number): string | null {
const parts = filterParts(filter);
@@ -215,7 +225,7 @@ export function withAdjust(filter: string | undefined, key: AdjustKey, n: number
if (args == null) parts.splice(at, 1);
else parts[at] = { name, args };
} else if (args != null) {
- const shadow = parts.findIndex((p) => p.name === 'drop-shadow');
+ const shadow = parts.findIndex((p) => p.name === 'drop-shadow' || isMaskStroke(p));
parts.splice(shadow < 0 ? parts.length : shadow, 0, { name, args });
}
return joinFilter(parts);
@@ -259,7 +269,7 @@ export function shadowOf(filter: string | undefined): Shadow | null | undefined
return part ? shadowArgs(part.args) : undefined;
}
-/** The filter with its drop shadow set (last, after the adjustments) or taken out (null). Null: no filter left. */
+/** The filter with its drop shadow set (after the adjustments, before a mask's stroke) or taken out (null). Null: no filter left. */
export function withShadow(filter: string | undefined, shadow: Shadow | null): string | null {
const parts = filterParts(filter);
if (!parts) return filter ?? null;
@@ -267,7 +277,8 @@ export function withShadow(filter: string | undefined, shadow: Shadow | null): s
if (at >= 0) parts.splice(at, 1);
if (shadow) {
const args = `${round(shadow.x, 1)}px ${round(shadow.y, 1)}px ${round(Math.max(0, shadow.blur), 1)}px ${shadow.color}`;
- parts.splice(at >= 0 ? at : parts.length, 0, { name: 'drop-shadow', args });
+ const stroke = parts.findIndex(isMaskStroke);
+ parts.splice(at >= 0 ? at : stroke >= 0 ? stroke : parts.length, 0, { name: 'drop-shadow', args });
}
return joinFilter(parts);
}
@@ -282,6 +293,7 @@ function filterOwned(filter: string): boolean {
if (seen.has(p.name)) return false;
seen.add(p.name);
if (p.name === 'drop-shadow') { if (!shadowArgs(p.args)) return false; continue; }
+ if (isMaskStroke(p)) continue;
const key = ADJUST_KEYS.find((k) => FILTER_FN[k] === p.name);
if (!key || !known.has(p.name) || !Number.isFinite(adjustValue(key, p.args))) return false;
}
diff --git a/packages/openfilm/studio/ui/src/lib/clip-mask.test.ts b/packages/openfilm/studio/ui/src/lib/clip-mask.test.ts
index 466861f..b220252 100644
--- a/packages/openfilm/studio/ui/src/lib/clip-mask.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/clip-mask.test.ts
@@ -1,13 +1,19 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
- MASK_SHAPES, clampMask, fadeIn, maskDefault, maskLayersOf, maskOf, maskOwned, maskStackCss, maskStackOf, shapeLayers,
- withFade, withMask, type Mask,
+ MASK_SHAPES, MASK_STROKE_POSITIONS, clampMask, fadeIn, maskCss, maskDefault, maskLayersOf, maskOf, maskOwned, maskStackCss,
+ maskStackOf, maskStrokeOf, shapeLayers, withFade, type Mask, type MaskBox, type MaskStroke,
} from './clip-mask.ts';
-import { cropCss, fadeCss, withDeclarations, declared } from './clip-look.ts';
+import { adjustOf, cropCss, fadeCss, ownedDeclaration, shadowOf, withAdjust, withDeclarations, withShadow, declared } from './clip-look.ts';
const BOX = { w: 1920, h: 1080 };
+/** The two mask properties with the shape set, as the panel writes them (maskCss), with no filter. */
+const withMask = (maskImage: string | undefined, maskComposite: string | undefined, mask: Mask | null, box?: MaskBox | null) => {
+ const css = maskCss((p) => (p === 'mask-image' ? maskImage : p === 'mask-composite' ? maskComposite : undefined), mask, box);
+ return css && { 'mask-image': css['mask-image'], 'mask-composite': css['mask-composite'] };
+};
+
const css = (m: Mask, box = BOX) => maskStackCss([], shapeLayers(m, box));
const near = (a: Mask, b: Mask, tol = 0.06) => {
assert.equal(a.shape, b.shape);
@@ -170,3 +176,103 @@ test('a new shape keeps the last one\'s place, and only what it has', () => {
test('a new mask has a hard edge, whatever its shape: feathering is the person\'s to add', () => {
for (const shape of MASK_SHAPES) assert.equal(maskDefault(shape, BOX).feather, 0, shape);
});
+
+/* ── a stroke along the edge ── */
+
+const reader = (props: Record<string, string | null | undefined>) => (p: string) => props[p] ?? undefined;
+const STROKE: MaskStroke = { width: 0.5, color: '#ff3b30', position: 'center' };
+
+test('a stroke is a filter drawn over the picture, and a mask layer for what is past the edge', () => {
+ const m = { ...maskDefault('ellipse', BOX), w: 40, h: 60 };
+ const css = maskCss(reader({}), m, BOX, STROKE)!;
+ assert.match(css.filter!, /^url\("data:image\/svg\+xml,%3Csvg xmlns='http:\/\/www.w3.org\/2000\/svg'%3E%3Cfilter id='openfilm-mask-stroke' x='0' y='0' width='1' height='1' primitiveUnits='objectBoundingBox'/);
+ assert.match(css.filter!, /feImage href='data:image\/svg\+xml;base64,[A-Za-z0-9+/=]+'/);
+ assert.ok(css.filter!.endsWith(`#openfilm-mask-stroke")`));
+ assert.deepEqual(maskStrokeOf(css.filter!), STROKE);
+ /* across the edge: one more layer, added above the shape */
+ const layers = maskLayersOf(css['mask-image']!);
+ assert.equal(layers.length, 2);
+ assert.match(layers[0]!, /^url\("data:image\/svg\+xml,/);
+ assert.equal(css['mask-composite'], 'add, intersect');
+ near(maskOf(css['mask-image']!, css['mask-composite']!, BOX)!, clampMask(m, BOX));
+ /* inside: nothing past the edge, the mask as it was */
+ const inside = maskCss(reader({}), m, BOX, { ...STROKE, position: 'inside' })!;
+ assert.equal(maskLayersOf(inside['mask-image']!).length, 1);
+ assert.equal(inside['mask-composite'], null);
+});
+
+test('every shape, inverted or not, keeps its stroke as written, in any position', () => {
+ for (const box of [BOX, { w: 1080, h: 1920 }]) {
+ for (const shape of MASK_SHAPES) {
+ for (const invert of [false, true]) {
+ for (const position of MASK_STROKE_POSITIONS) {
+ const m = clampMask({ shape, x: 40, y: 55, w: 30, h: 25, rotate: 20, feather: 0, radius: shape === 'rect' ? 3 : 0, invert }, box);
+ const stroke = { width: 1.25, color: '#00000080', position };
+ const css = maskCss(reader({}), m, box, stroke)!;
+ assert.deepEqual(maskStrokeOf(css.filter!), stroke, `${shape} ${position}`);
+ const back = maskOf(css['mask-image']!, css['mask-composite']!, box)!;
+ /* a line reads back as a point on it (see above) */
+ near(shape === 'linear' || shape === 'mirror' ? { ...back, x: m.x, y: m.y } : back, m);
+ /* an override's style value holds at most 2000 characters (src/film-doc.mjs) */
+ for (const v of Object.values(css)) assert.ok((v ?? '').length <= 2000, `${shape} ${position}: ${(v ?? '').length}`);
+ }
+ }
+ }
+ }
+});
+
+test('the shape changed, its stroke goes with it; the mask taken off, the stroke too', () => {
+ const m = maskDefault('star', BOX);
+ const first = maskCss(reader({ filter: 'brightness(1.2)' }), m, BOX, STROKE)!;
+ assert.match(first.filter!, /^brightness\(1\.2\) url\(/);
+ const moved = maskCss(reader(first), { ...m, x: 30 }, BOX)!;
+ assert.deepEqual(maskStrokeOf(moved.filter!), STROKE);
+ assert.notEqual(moved.filter, first.filter);
+ assert.equal(maskOf(moved['mask-image']!, moved['mask-composite']!, BOX)!.x, 30);
+ const off = maskCss(reader(moved), null, BOX)!;
+ assert.deepEqual(off, { 'mask-image': null, 'mask-composite': null, filter: 'brightness(1.2)' });
+ /* no stroke, no filter written */
+ assert.equal('filter' in maskCss(reader({}), m, BOX)!, false);
+ /* the stroke taken away alone */
+ assert.equal(maskCss(reader(first), m, BOX, null)!.filter, 'brightness(1.2)');
+});
+
+test('the filter controls keep a mask stroke last, and say it is theirs', () => {
+ const css = maskCss(reader({}), maskDefault('ellipse', BOX), BOX, STROKE)!;
+ const adjusted = withAdjust(css.filter!, 'contrast', 20)!;
+ assert.match(adjusted, /^contrast\(1\.2\) url\(/);
+ assert.equal(adjustOf(adjusted).contrast, 20);
+ const shadowed = withShadow(adjusted, { x: 0, y: 4, blur: 8, color: '#000' })!;
+ assert.match(shadowed, /^contrast\(1\.2\) drop-shadow\(0px 4px 8px #000\) url\(/);
+ assert.ok(shadowOf(shadowed));
+ assert.deepEqual(maskStrokeOf(shadowed), STROKE);
+ assert.equal(ownedDeclaration('filter', shadowed, () => undefined), true);
+});
+
+test('faded edges and a stroked shape share mask-image: the stroke stays with the shape', () => {
+ const m = maskDefault('ellipse', BOX);
+ const css = maskCss(reader({}), m, BOX, { ...STROKE, position: 'outside' })!;
+ const fade = { sides: { left: true, right: false, top: false, bottom: false }, size: 20 };
+ const faded = withFade(css['mask-image']!, css['mask-composite']!, fade)!;
+ assert.equal(maskLayersOf(faded['mask-image']!).length, 3);
+ assert.equal(faded['mask-composite'], 'intersect, add, intersect');
+ const stack = maskStackOf(faded['mask-image']!, faded['mask-composite']!, BOX);
+ assert.deepEqual(stack.fade, fade);
+ near(stack.shape!, clampMask(m, BOX));
+ assert.equal(maskOwned('mask-image', faded['mask-image']!, (p) => (p === 'mask-composite' ? faded['mask-composite']! : undefined)), true);
+ /* the shape moved under the fade: the stroke's layer drawn again, the fade kept */
+ const moved = maskCss(reader({ ...faded, filter: css.filter }), { ...m, y: 20 }, BOX)!;
+ assert.equal(maskLayersOf(moved['mask-image']!)[0], maskLayersOf(faded['mask-image']!)[0]);
+ assert.equal(maskStackOf(moved['mask-image']!, moved['mask-composite']!, BOX).shape!.y, 20);
+});
+
+test('a stroke filter that is not readable, or a filter written by hand, takes no stroke', () => {
+ assert.equal(maskStrokeOf('url("data:image/svg+xml,%3Csvg/%3E#openfilm-mask-stroke")'), null);
+ /* a filter of the page's own with that id is the page's: kept as written */
+ const own = 'url(#openfilm-mask-stroke)';
+ assert.equal(maskStrokeOf(own), undefined);
+ assert.equal(maskCss(reader({ filter: own }), maskDefault('ellipse', BOX), BOX, STROKE)!.filter!.startsWith(`${own} url("data:`), true);
+ assert.equal(maskStrokeOf('blur(2px)'), undefined);
+ const css = maskCss(reader({ filter: 'blur(2px' }), maskDefault('ellipse', BOX), BOX, STROKE)!;
+ assert.equal('filter' in css, false);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/clip-mask.ts b/packages/openfilm/studio/ui/src/lib/clip-mask.ts
index 775a519..2c64b33 100644
--- a/packages/openfilm/studio/ui/src/lib/clip-mask.ts
+++ b/packages/openfilm/studio/ui/src/lib/clip-mask.ts
@@ -33,10 +33,12 @@
* layers after, every layer intersecting the ones below it (mask layers composite from the bottom up), so each hides
* what it hides. `mask-composite` is then one `intersect`, or a list when an inverted shape needs its `exclude`.
*
+ * A stroke along the mask's edge is drawn by a filter, since a mask only hides (see "a stroke along the edge" below).
+ *
* Anything else in `mask-image` (written by hand, or by an agent) is a custom mask: shown as such, never rewritten,
* the raw CSS (Advanced) has it.
*/
-import { fadeCss, fadeOf, type Fade } from './clip-look.ts';
+import { MASK_STROKE_ID, fadeCss, fadeOf, filterParts, isMaskStroke, type Fade } from './clip-look.ts';
export type MaskShape = 'linear' | 'mirror' | 'ellipse' | 'rect' | 'star' | 'heart';
export const MASK_SHAPES: readonly MaskShape[] = ['linear', 'mirror', 'ellipse', 'rect', 'star', 'heart'];
@@ -72,7 +74,7 @@ export const MASK_FIELDS: Record<MaskShape, { size: 'box' | 'band' | null; rotat
};
/** One `mask-image` layer and how it composites with the layers below it. */
-export interface MaskLayer { image: string; op: 'intersect' | 'exclude' }
+export interface MaskLayer { image: string; op: 'intersect' | 'exclude' | 'add' }
/* ───────────── numbers ───────────── */
@@ -221,8 +223,10 @@ export const HEART_D = 'M0 1C-.55 .62 -1 .22 -1 -.32C-1 -.72 -.72 -1 -.45 -1C-.2
/** The blur that feathers an SVG rect: its standard deviation is the feather over this. */
const BLUR_PER_FEATHER = 3;
-/** `url("data:image/svg+xml,…")`: only what a URL or the attribute around it cannot hold is escaped. */
-const svgUrl = (svg: string) => `url("data:image/svg+xml,${svg.replace(/[%#<>"]/g, (c) => encodeURIComponent(c))}")`;
+/** An SVG in a data URL: only what a URL or the attribute around it cannot hold is escaped. */
+const svgData = (svg: string) => `data:image/svg+xml,${svg.replace(/[%#<>"]/g, (c) => encodeURIComponent(c))}`;
+/** `url("data:image/svg+xml,…")`. */
+const svgUrl = (svg: string) => `url("${svgData(svg)}")`;
function svgOf(u: U, body: string): string {
return svgUrl(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${fmt(u.W)} ${fmt(u.H)}' preserveAspectRatio='none'>${body}</svg>`);
@@ -469,10 +473,11 @@ export function maskStackOf(maskImage: string | undefined, maskComposite: string
/* a shape is the last one to three layers; what is above it has to be faded edges, intersected */
for (const len of [3, 2, 1]) {
if (len > n) continue;
- const head = layers.slice(0, n - len);
- const tail = layers.slice(n - len);
- const shape = shapeOfLayers(tail, ops.slice(n - len), u);
+ const shape = shapeOfLayers(layers.slice(n - len), ops.slice(n - len), u);
if (!shape) continue;
+ /* a stroke's outer part, added right above the shape, goes with it */
+ const from = n - len - 1 >= 0 && ops[n - len - 1] === 'add' && strokeLayer(layers[n - len - 1]!) ? n - len - 1 : n - len;
+ const head = layers.slice(0, from);
if (head.length && ops.slice(0, head.length).some((op) => op !== 'intersect')) continue;
const fade = head.length ? fadeOf(head.join(', '), 'intersect') : undefined;
if (fade === null) continue;
@@ -480,7 +485,10 @@ export function maskStackOf(maskImage: string | undefined, maskComposite: string
fade,
shape,
fadeLayers: head,
- shapeLayers: tail.map((image, i) => ({ image, op: ops[n - len + i] === 'exclude' ? 'exclude' : 'intersect' })),
+ shapeLayers: layers.slice(from).map((image, i) => {
+ const op = ops[from + i];
+ return { image, op: op === 'exclude' ? 'exclude' : op === 'add' ? 'add' : 'intersect' };
+ }),
};
}
const fade = fadeOf(maskImage, maskComposite);
@@ -510,15 +518,6 @@ export function fadeIn(maskImage: string | undefined, maskComposite: string | un
return maskStackOf(maskImage, maskComposite).fade;
}
-/** The properties with the shape set (null: taken off), the faded edges kept as written; null when it is a custom mask. */
-export function withMask(
- maskImage: string | undefined, maskComposite: string | undefined, mask: Mask | null, box?: MaskBox | null,
-): { 'mask-image': string | null; 'mask-composite': string | null } | null {
- const now = maskStackOf(maskImage, maskComposite, box);
- if (now.shape === null) return null;
- return maskStackCss(now.fadeLayers, mask ? shapeLayers(clampMask(mask, box), box) : []);
-}
-
/** The properties with the faded edges set (null: taken off), the shape kept as written; null when it is a custom mask. */
export function withFade(
maskImage: string | undefined, maskComposite: string | undefined, fade: Fade | null,
@@ -534,3 +533,182 @@ export function maskOwned(prop: string, value: string, all: (p: string) => strin
if (prop === 'mask-composite') return maskStackOf(all('mask-image'), value).shape !== null && maskLayersOf(all('mask-image')).length > 0;
return false;
}
+
+/* ───────────── a stroke along the edge ───────────── */
+
+/*
+ * A stroke `width` wide (% of the box's shorter side, as the feather) along the shape's edge (the middle of its
+ * feather): inside it, across it or outside it — the side the picture shows on being the inside, so an inverted
+ * shape's inside is around it.
+ *
+ * A mask only hides, and nothing else in a box's own CSS paints over its picture, so the stroke is an SVG filter,
+ * `url("data:image/svg+xml,…#openfilm-mask-stroke")`, last in `filter`, laying an image of the stroke over the
+ * picture. The image is an SVG in the box's proportions, as the mask's own (its viewBox in units,
+ * `preserveAspectRatio='none'`), placed over the whole box (`primitiveUnits='objectBoundingBox'`), so the stroke
+ * scales with the box as the mask does. It is base64: the only way Chromium loads an image inside a filter that is
+ * itself a data URL. WebKit loads no such filter: there no stroke is drawn, and the mask layer below lets the picture
+ * show past the edge as far as the stroke would reach.
+ *
+ * A filter is drawn before the mask, which then hides what is past the edge: the stroke's outer part is let through
+ * by one more mask layer, added right above the shape's layers (`mask-composite: add`). The filter draws that part
+ * opaque and the layer in the stroke's color, so a see-through color shows nothing of the picture.
+ * Both images say what they draw on their root, `data-stroke='<position> <width> <color>'`: what is read back.
+ */
+
+export type MaskStrokePosition = 'inside' | 'center' | 'outside';
+export const MASK_STROKE_POSITIONS: readonly MaskStrokePosition[] = ['inside', 'center', 'outside'];
+
+export interface MaskStroke {
+ /** % of the box's shorter side. */
+ width: number;
+ color: string;
+ position: MaskStrokePosition;
+}
+
+/** A color as an SVG attribute can hold it (no quote, no markup), else white. */
+const safeColor = (c: string) => (/^[#\w(),.%\s-]+$/.test(c.trim()) ? c.trim() : '#ffffff');
+
+/** The color without its transparency: hex or rgb() / rgba(); anything else is taken as it is. */
+function opaqueOf(color: string): string {
+ const c = color.trim();
+ const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(c);
+ if (hex) {
+ const h = hex[1]!;
+ return h.length === 4 ? `#${h.slice(0, 3)}` : h.length === 8 ? `#${h.slice(0, 6)}` : c;
+ }
+ const rgb = /^rgba?\(\s*([^,\s]+)[,\s]+([^,\s]+)[,\s]+([^,\s/)]+)/i.exec(c);
+ return rgb ? `rgb(${rgb[1]}, ${rgb[2]}, ${rgb[3]})` : c;
+}
+
+/** The shape as one SVG element, `id='s'`, in units: what the stroke follows. A line's side or a band is a polygon far past the box. */
+function shapeElement(m: Mask, u: U): string {
+ const px = (m.x / 100) * u.W;
+ const py = (m.y / 100) * u.H;
+ switch (m.shape) {
+ case 'linear':
+ case 'mirror': {
+ /* along the gradient's line (d) and across it (e); the picture shows before the line, or within the band */
+ const d = dirOf(m.rotate);
+ const e = { x: -d.y, y: d.x };
+ const far = 10 * (u.W + u.H);
+ const [a, b] = m.shape === 'linear' ? [-far, 0] : [-m.h / 2, m.h / 2];
+ const at = (s: number, k: number) => `${fmt(px + d.x * s + e.x * k)},${fmt(py + d.y * s + e.y * k)}`;
+ return `<polygon id='s' points='${at(a, -far)} ${at(b, -far)} ${at(b, far)} ${at(a, far)}'/>`;
+ }
+ case 'ellipse':
+ return `<ellipse id='s' cx='${fmt(px)}' cy='${fmt(py)}' rx='${fmt(((m.w / 2) / 100) * u.W)}' ry='${fmt(((m.h / 2) / 100) * u.H)}'/>`;
+ case 'rect': {
+ const wu = (m.w / 100) * u.W;
+ const hu = (m.h / 100) * u.H;
+ const r = Math.min(m.radius, wu / 2, hu / 2);
+ return `<rect id='s' transform='translate(${fmt(px)} ${fmt(py)}) rotate(${fmt(m.rotate)})' x='${fmt(-wu / 2, 3)}' y='${fmt(-hu / 2, 3)}' width='${fmt(wu, 3)}' height='${fmt(hu, 3)}'${r > 0 ? ` rx='${fmt(r)}'` : ''}/>`;
+ }
+ default: {
+ /* the path placed in units here, not by a transform: a stroke scaled across and down unevenly would not be even */
+ const sx = ((m.w / 100) * u.W) / 2;
+ const sy = ((m.h / 100) * u.H) / 2;
+ const a = (m.rotate * Math.PI) / 180;
+ const cos = Math.cos(a);
+ const sin = Math.sin(a);
+ let held: number | null = null;
+ let d = '';
+ for (const tok of (m.shape === 'star' ? STAR_D : HEART_D).match(/[a-z]|-?\d*\.?\d+/gi) ?? []) {
+ if (/[a-z]/i.test(tok)) { d += tok; continue; }
+ if (held == null) { held = Number(tok); continue; }
+ const x = held * sx;
+ const y = Number(tok) * sy;
+ held = null;
+ d += `${/[\d]$/.test(d) ? ' ' : ''}${fmt(px + x * cos - y * sin)} ${fmt(py + x * sin + y * cos)}`;
+ }
+ return `<path id='s' d='${d}'/>`;
+ }
+ }
+}
+
+/** How far the stroke reaches in from the edge and out past it (units). */
+function strokeReach(s: MaskStroke): [inner: number, outer: number] {
+ const w = Math.max(0, s.width);
+ return s.position === 'inside' ? [w, 0] : s.position === 'outside' ? [0, w] : [w / 2, w / 2];
+}
+
+/**
+ * The stroke as an SVG over the box: both parts for the filter (the outer one opaque), or the outer part, in its
+ * color, for the mask layer. Each part is a stroke twice its reach on the edge, cut to its side in the filter.
+ */
+function strokeSvg(m: Mask, s: MaskStroke, u: U, outerOnly: boolean): string {
+ const [inner, outer] = strokeReach(s);
+ const color = safeColor(s.color);
+ const inside = "clip-path='url(#i)'";
+ const outside = "mask='url(#o)'";
+ const [innerSide, outerSide] = m.invert ? [outside, inside] : [inside, outside];
+ const part = (reach: number, paint: string, side: string, more = '') => `<use href='#s' fill='none' stroke='${paint}' stroke-width='${fmt(reach * 2)}'${side ? ` ${side}` : ''}${more}/>`;
+ const both = !outerOnly && inner > 0 && outer > 0;
+ /* the two parts meet at the edge, each smoothed there: added (not one over the other), no seam shows between them */
+ const parts = (!outerOnly && inner > 0 ? part(inner, color, innerSide) : '')
+ /* the mask's layer is added to the shape's, which shows all inside: it goes across the edge, so the two overlap */
+ + (outer > 0 ? part(outer, outerOnly ? color : opaqueOf(color), outerOnly ? '' : outerSide, both ? " style='mix-blend-mode:plus-lighter'" : '') : '');
+ const [x, y, w, h] = [-u.W, -u.H, 3 * u.W, 3 * u.H].map((n) => fmt(n));
+ const defs = shapeElement(m, u)
+ + (parts.includes('#i') ? "<clipPath id='i'><use href='#s'/></clipPath>" : '')
+ + (parts.includes('#o') ? `<mask id='o' maskUnits='userSpaceOnUse' x='${x}' y='${y}' width='${w}' height='${h}'><rect x='${x}' y='${y}' width='${w}' height='${h}' fill='#fff'/><use href='#s'/></mask>` : '');
+ return `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${fmt(u.W)} ${fmt(u.H)}' preserveAspectRatio='none' data-stroke='${s.position} ${fmt(Math.max(0, s.width))} ${color}'><defs>${defs}</defs>${parts}</svg>`;
+}
+
+/** The filter function that draws the stroke (the last in `filter`). */
+function strokeFilter(m: Mask, s: MaskStroke, u: U): string {
+ const image = `data:image/svg+xml;base64,${btoa(strokeSvg(m, s, u, false))}`;
+ const svg = `<svg xmlns='http://www.w3.org/2000/svg'><filter id='${MASK_STROKE_ID}' x='0' y='0' width='1' height='1' primitiveUnits='objectBoundingBox' color-interpolation-filters='sRGB'>`
+ + `<feImage href='${image}' x='0' y='0' width='1' height='1' preserveAspectRatio='none'/><feComposite in2='SourceGraphic'/></filter></svg>`;
+ return `url("${svgData(svg)}#${MASK_STROKE_ID}")`;
+}
+
+const STROKE_RE = /\sdata-stroke='(inside|center|outside) (\d*\.?\d+) ([^']+)'/;
+
+/** Whether a mask layer is a stroke's outer part (as strokeSvg writes it). */
+function strokeLayer(layer: string): boolean {
+ const svg = svgText(layer);
+ return Boolean(svg && STROKE_RE.test(svg));
+}
+
+/** The mask's stroke, from `filter`: undefined when there is none, null when there is one that cannot be read. */
+export function maskStrokeOf(filter: string | undefined): MaskStroke | null | undefined {
+ const part = filterParts(filter)?.find(isMaskStroke);
+ if (!part) return undefined;
+ const url = /^(["']?)data:image\/svg\+xml,(.*)#[\w-]+\1$/s.exec(part.args);
+ let svg = '';
+ try { svg = url ? decodeURIComponent(url[2]!) : ''; } catch { return null; }
+ const image = /href='data:image\/svg\+xml;base64,([A-Za-z0-9+/=]+)'/.exec(svg);
+ let inner = '';
+ try { inner = image ? atob(image[1]!) : ''; } catch { return null; }
+ const m = STROKE_RE.exec(inner);
+ return m ? { position: m[1] as MaskStrokePosition, width: Number(m[2]), color: m[3]! } : null;
+}
+
+/**
+ * Everything a mask writes, from the properties as they are (`read`): `mask-image` and `mask-composite` with the shape
+ * set (null: taken off) and the faded edges kept as written, and — when there is a stroke, or was — `filter` with the
+ * stroke drawn for that shape last, its other functions kept. `stroke`: the stroke to set (null: none); undefined keeps
+ * the one there is. Null when it is a custom mask. A filter the panel cannot read gets no stroke.
+ */
+export function maskCss(
+ read: (prop: string) => string | undefined, mask: Mask | null, box?: MaskBox | null, stroke?: MaskStroke | null,
+): Record<'mask-image' | 'mask-composite', string | null> & { filter?: string | null } | null {
+ const now = maskStackOf(read('mask-image'), read('mask-composite'), box);
+ if (now.shape === null) return null;
+ const u = unitsOf(box);
+ const m = mask ? clampMask(mask, box) : null;
+ const filter = read('filter');
+ const parts = filterParts(filter);
+ const was = parts?.find(isMaskStroke);
+ const want = stroke === undefined ? maskStrokeOf(filter) ?? null : stroke;
+ const s = m && want && want.width > 0 && parts ? want : null;
+ const layers = m ? shapeLayers(m, box) : [];
+ if (m && s && strokeReach(s)[1] > 0) layers.unshift({ image: svgUrl(strokeSvg(m, s, u, true)), op: 'add' });
+ const css: Record<'mask-image' | 'mask-composite', string | null> & { filter?: string | null } = maskStackCss(now.fadeLayers, layers);
+ if (parts && (was || s)) {
+ const kept = parts.filter((p) => !isMaskStroke(p)).map((p) => `${p.name}(${p.args})`);
+ if (m && s) kept.push(strokeFilter(m, s, u));
+ css.filter = kept.length ? kept.join(' ') : null;
+ }
+ return css;
+}