Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.14): image filter gallery — 8 presets, intensity slider, all-renderer pipeline (D4)

Ashiq Hussain Mir3d21d0e41d50
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec7203f..e3f9d01 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,35 @@
All notable changes to Canvix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+## [0.14.3] — 2026-11-05
+
+### Added
+
+- **Daily-driver depth, part 4 — the image filter gallery (D4).**
+ The context toolbar's "Filter tint (soon)" stub is gone: image
+ elements now carry a filter preset + intensity, rendered live in
+ the editor, in video exports, and approximated in SVG exports.
+ - **Eight presets** — Original, Mono (grayscale), Warm, Cool,
+ Vintage (sepia-lerp + black-lift), Blur (3-pass box ≈ gaussian),
+ Sharpen (3×3 unsharp) and Vignette (radial falloff) — as a chip
+ grid in the new **Filters** popover, each chip a live preview
+ canvas of the element's own image, plus an intensity slider.
+ - **One pixel pipeline, every renderer** (`src/lib/image-filters.ts`):
+ the editor rides the existing Konva cache pipeline; the video
+ exporter pre-bakes pixels through a Konva-exact twin (and now
+ exports flips/rotation for image elements too — a parity gap
+ closed while here); SVG exports emit real filter primitives
+ (`feColorMatrix`/`feComponentTransfer`/`feConvolveMatrix`/
+ `feGaussianBlur`, vignette as a clipped radial-gradient overlay)
+ with each approximation documented in the module header. Adjust
+ (brightness/contrast/saturation) now renders in exports as well
+ — previously editor-only.
+ - **Persistent + safe**: `filter`/`filterIntensity` live on the
+ element (undo/redo, collab, autosave all just work); pasted
+ elements whitelist the preset id and clamp intensity (junk
+ resets to none, never throws); `update_element` (MCP) patches
+ images' adjustments and filter fields too.
+
## [0.14.2] — 2026-11-04
### Added
diff --git a/package.json b/package.json
index d900d52..0aa09fa 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.14.2",
+ "version": "0.14.3",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsx
index 56b63cd..ec95d3e 100644
--- a/src/components/editor/PropertiesBar.tsx
+++ b/src/components/editor/PropertiesBar.tsx
@@ -1,6 +1,6 @@
'use client'
-import { useState, useSyncExternalStore } from 'react'
+import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
import {
Bold, Italic, Underline, Strikethrough, CaseUpper, AlignLeft, AlignCenter, AlignRight,
AlignJustify, Minus, Plus, LetterText, Percent, Sparkles, Move, CopyPlus, Trash2,
@@ -9,7 +9,7 @@ import {
AlignHorizontalJustifyStart, AlignHorizontalJustifyCenter, AlignHorizontalJustifyEnd,
FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,
Layers, SquareDashed, Crop, Spline, Table2, Rows3, Columns3, Trash, Upload, ExternalLink,
- Music, Film, Play, Repeat, Volume2, VolumeX, SlidersHorizontal, Activity, Puzzle, LayoutGrid,
+ Music, Film, Play, Repeat, Volume2, VolumeX, SlidersHorizontal, Activity, Puzzle, LayoutGrid, Wand2,
} from 'lucide-react'
import { useEditorStore, selectedElements, currentPageData } from '@/store/editor-store'
import type { AudioElement, EmbedElement, FrameElement, ImageElement, LineElement, PluginElement, ShapeElement, StickerElement, TableElement, TextElement, VideoElement, AnyElement, FrameShape } from '@/lib/types'
@@ -21,6 +21,8 @@ import { getPluginSystemState, subscribePluginSystem } from '@/lib/plugins/rende
import { applyDesignAction } from '@/lib/design-actions'
import { FontDropdown } from './toolbar/FontDropdown'
import { ColorMenu } from './toolbar/ColorMenu'
+import { IMAGE_FILTER_PRESETS, applyPresetToImageData, isImageFilterId, clampFilterIntensity } from '@/lib/image-filters'
+import { useLoadedImage } from './canvas/use-loaded-image'
import { ToolbarPopover, SliderRow, IconTile } from './toolbar/popover-kit'
import { BgRemoverButton, MagicEraserPopover, EnhanceButton } from './ImageAI'
@@ -340,7 +342,7 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm
<MagicEraserPopover el={image} />
<EnhanceButton el={image} />
<Divider />
- <ColorMenu value="#FFFFFF" onChange={() => undefined} title="Filter tint (soon)" />
+ <ImageFilterPopover el={image} ids={ids} />
<ToolbarPopover trigger={(open) => (
<button className="cv-tbtn" data-active={open} aria-label="Transparency" title="Transparency">
<Percent size={14} />
@@ -791,6 +793,88 @@ function ImageAdjustPopover({ el, ids }: { el: ImageElement; ids: string[] }) {
)
}
+/** v0.14 (D4): the filter gallery — preset chips with live previews
+ * of the element's own image + an intensity slider. Replaces the old
+ * "Filter tint (soon)" stub. */
+function ImageFilterPopover({ el, ids }: { el: ImageElement; ids: string[] }) {
+ const update = useEditorStore((s) => s.updateElements)
+ const updateLive = useEditorStore((s) => s.updateElementsLive)
+ const image = useLoadedImage(el.src)
+ const active = isImageFilterId(el.filter) ? el.filter : 'none'
+ const intensity = clampFilterIntensity(el.filterIntensity)
+ return (
+ <ToolbarPopover
+ width={268}
+ trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open || active !== 'none'} aria-label="Filters" title="Filters">
+ <Wand2 size={14} /> <span className="text-[12px] hidden lg:inline">Filters</span>
+ </button>
+ )}
+ >
+ <div className="grid grid-cols-4 gap-1.5 mb-2.5">
+ {IMAGE_FILTER_PRESETS.map((p) => (
+ <button
+ key={p.id}
+ title={p.hint}
+ aria-label={`Filter ${p.label}`}
+ aria-pressed={active === p.id}
+ onClick={() => update(ids, { filter: p.id, filterIntensity: p.id === 'none' ? 100 : intensity })}
+ className={cn(
+ 'rounded-lg overflow-hidden border transition-colors',
+ active === p.id ? 'border-[#7630D7] bg-white/[0.13]' : 'border-white/10 hover:border-white/25'
+ )}
+ >
+ <FilterThumb image={image} preset={p.id} intensity={intensity} />
+ <div className="text-[10px] text-white/80 py-1 text-center leading-none">{p.label}</div>
+ </button>
+ ))}
+ </div>
+ {active !== 'none' && (
+ <SliderRow label="Intensity" value={intensity} min={0} max={100} step={1}
+ onChange={(v) => updateLive(ids, { filterIntensity: v })}
+ onCommit={() => update(ids, { filterIntensity: el.filterIntensity ?? 100 })} />
+ )}
+ </ToolbarPopover>
+ )
+}
+
+/** tiny live preview — the preset applied to the element's own image */
+function FilterThumb({ image, preset, intensity }: { image: HTMLImageElement | null; preset: string; intensity: number }) {
+ const ref = useRef<HTMLCanvasElement>(null)
+ useEffect(() => {
+ const canvas = ref.current
+ if (!canvas) return
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return
+ const w = 56
+ const h = 40
+ canvas.width = w
+ canvas.height = h
+ ctx.clearRect(0, 0, w, h)
+ if (!image) return
+ // cover-crop the source into the thumb
+ const sr = image.naturalWidth / image.naturalHeight
+ const tr = w / h
+ let sw = image.naturalWidth
+ let sh = image.naturalHeight
+ let sx = 0
+ let sy = 0
+ if (sr > tr) {
+ sw = image.naturalHeight * tr
+ sx = (image.naturalWidth - sw) / 2
+ } else {
+ sh = image.naturalWidth / tr
+ sy = (image.naturalHeight - sh) / 2
+ }
+ ctx.drawImage(image, sx, sy, sw, sh, 0, 0, w, h)
+ if (preset === 'none' || intensity <= 0) return
+ const data = ctx.getImageData(0, 0, w, h)
+ applyPresetToImageData(data, preset, intensity / 100)
+ ctx.putImageData(data, 0, 0)
+ }, [image, preset, intensity])
+ return <canvas ref={ref} className="block w-full aspect-[7/5] bg-white/[0.06]" />
+}
+
function SliderRowMini({ label, value, min, max, onChange, onCommit }: { label: string; value: number; min: number; max: number; onChange: (v: number) => void; onCommit: () => void }) {
return (
<div className="flex items-center gap-2 px-2 shrink-0 w-[150px]">
diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsx
index 34ac240..912aff7 100644
--- a/src/components/editor/canvas/element-node.tsx
+++ b/src/components/editor/canvas/element-node.tsx
@@ -24,6 +24,7 @@ import { isLine, withAlpha, type GradientFill } from '@/lib/types'
import { elementGradientProps } from '@/lib/editor-utils'
import { useEditorStore } from '@/store/editor-store'
import { useLoadedImage } from './use-loaded-image'
+import { isImageFilterId, clampFilterIntensity, applyPresetToImageData } from '@/lib/image-filters'
import { CurvedTextNode, EmbedNode, FrameNode, TableNode, type TableCellRef } from './v06-nodes'
import { PluginNode } from './PluginNode'
@@ -96,15 +97,24 @@ function ImageNode({ el, common }: { el: ImageElement; common: Record<string, un
const bright = (el.brightness ?? 0) / 100 // konva Brighten: -0.5..0.5 approx
const contrast = el.contrast ?? 0
const sat = el.saturation ?? 0
- const needsFilters = bright !== 0 || contrast !== 0 || sat !== 0
+ // v0.14 (D4): filter-gallery preset rides the same cached pipeline
+ const preset = isImageFilterId(el.filter) ? el.filter : 'none'
+ const intensity = clampFilterIntensity(el.filterIntensity) / 100
+ const needsFilters = bright !== 0 || contrast !== 0 || sat !== 0 || (preset !== 'none' && intensity > 0)
useEffect(() => {
const node = nodeRef.current
if (!node || !image) return
- const filters: Array<typeof Konva.Filters.Brighten> = []
+ const filters: Konva.Filter[] = []
if (bright !== 0) filters.push(Konva.Filters.Brighten)
if (contrast !== 0) filters.push(Konva.Filters.Contrast)
if (sat !== 0) filters.push(Konva.Filters.HSL)
+ if (preset !== 'none' && intensity > 0) {
+ // pure pixel kernel as a Konva filter (no `this` needed)
+ const id = preset
+ const t = intensity
+ filters.push((imageData: ImageData) => applyPresetToImageData(imageData, id, t))
+ }
node.filters(filters)
node.brightness(bright)
node.contrast(contrast)
@@ -112,7 +122,7 @@ function ImageNode({ el, common }: { el: ImageElement; common: Record<string, un
if (filters.length) node.cache()
else node.clearCache()
node.getLayer()?.batchDraw()
- }, [image, bright, contrast, sat])
+ }, [image, bright, contrast, sat, preset, intensity])
return (
<KonvaImage
diff --git a/src/lib/clipboard/system-clipboard.test.ts b/src/lib/clipboard/system-clipboard.test.ts
index 077626c..a6dbc3b 100644
--- a/src/lib/clipboard/system-clipboard.test.ts
+++ b/src/lib/clipboard/system-clipboard.test.ts
@@ -33,6 +33,25 @@ function textEl(overrides: Record<string, unknown> = {}): Record<string, unknown
}
}
+/** v0.14 (D4): image factory for filter-field sanitizing tests */
+function imageEl(overrides: Record<string, unknown> = {}) {
+ return {
+ type: 'image',
+ id: 'im1',
+ x: 0,
+ y: 0,
+ width: 200,
+ height: 150,
+ rotation: 0,
+ opacity: 1,
+ visible: true,
+ locked: false,
+ src: 'data:image/png;base64,AAAA',
+ radius: 12,
+ ...overrides,
+ }
+}
+
describe('envelope round-trip', () => {
it('serialize → parse survives with identical content', () => {
const els = [textEl() as unknown as AnyElement]
@@ -88,6 +107,35 @@ describe('sanitizePastedElements — the untrusted-input gauntlet', () => {
expect(rec.fontSize).toBe(32)
})
+ it('v0.14 (D4): image filter fields are whitelisted + clamped', () => {
+ const out = sanitizePastedElements([
+ imageEl({ filter: 'vintage', filterIntensity: 80 }),
+ ])
+ const rec = out[0] as unknown as Record<string, unknown>
+ expect(rec.filter).toBe('vintage')
+ expect(rec.filterIntensity).toBe(80)
+ })
+
+ it('v0.14 (D4): junk preset ids reset to none, hostile intensity clamps', () => {
+ const out = sanitizePastedElements([
+ imageEl({ filter: 'EVIL<script>', filterIntensity: 1e9 }),
+ imageEl({ filter: 42, filterIntensity: 'hot' }),
+ imageEl({ filter: '__proto__' }),
+ ])
+ for (const el of out) {
+ const rec = el as unknown as Record<string, unknown>
+ expect(rec.filter).toBe('none')
+ expect(rec.filterIntensity).toBe(100)
+ }
+ })
+
+ it('v0.14 (D4): negative/NaN intensity falls back to the 100 default', () => {
+ const out = sanitizePastedElements([imageEl({ filter: 'warm', filterIntensity: -20 })])
+ const rec = out[0] as unknown as Record<string, unknown>
+ expect(rec.filter).toBe('warm')
+ expect(rec.filterIntensity).toBe(0) // -20 clamps to 0, not 100 (finite input is clamped, not defaulted)
+ })
+
it('caps the element count', () => {
const many = Array.from({ length: MAX_PASTE_ELEMENTS + 200 }, () => textEl({ id: 'x' }))
expect(sanitizePastedElements(many)).toHaveLength(MAX_PASTE_ELEMENTS)
diff --git a/src/lib/clipboard/system-clipboard.ts b/src/lib/clipboard/system-clipboard.ts
index 35c4ab7..907c605 100644
--- a/src/lib/clipboard/system-clipboard.ts
+++ b/src/lib/clipboard/system-clipboard.ts
@@ -17,6 +17,7 @@
// ─────────────────────────────────────────────────────────────
import type { AnyElement, ElementType } from '@/lib/types'
+import { isImageFilterId, clampFilterIntensity } from '@/lib/image-filters'
export const CANVIX_MIME = 'application/x-canvix'
@@ -104,6 +105,12 @@ export function sanitizePastedElements(raw: unknown): AnyElement[] {
if (typeof s.locked !== 'boolean') s.locked = false
const opacity = typeof s.opacity === 'number' ? s.opacity : 1
s.opacity = Math.min(1, Math.max(0, opacity))
+ // v0.14 (D4): image filter fields are whitelisted + clamped — a
+ // pasted 'EVIL' preset id or a 1e9 intensity never enters the store
+ if (s.type === 'image') {
+ s.filter = isImageFilterId(s.filter) ? s.filter : 'none'
+ s.filterIntensity = clampFilterIntensity(s.filterIntensity)
+ }
// groups carry children through the same gauntlet
if (s.type === 'group' && Array.isArray(s.children)) {
s.children = sanitizePastedElements(s.children)
diff --git a/src/lib/image-filters.test.ts b/src/lib/image-filters.test.ts
new file mode 100644
index 0000000..cd17596
--- /dev/null
+++ b/src/lib/image-filters.test.ts
@@ -0,0 +1,368 @@
+// Unit tests for the v0.14 (D4) image filter pipeline:
+// 1. every preset is a t=0 no-op ('none' always is)
+// 2. each preset's pixel math matches its documented formula
+// 3. hostile inputs (junk ids, NaN, out-of-range intensity) never
+// throw and never change pixels
+// 4. the adjustment path reproduces Konva's own math (the video
+// exporter pre-bakes pixels with it — it must match the editor)
+// 5. the SVG approximation emits the right primitives per preset
+//
+// Node environment: ImageData is duck-typed (the kernels only touch
+// .data/.width/.height — same shape the browser hands us).
+
+import { describe, it, expect } from 'vitest'
+import {
+ IMAGE_FILTER_PRESETS,
+ isImageFilterId,
+ clampFilterIntensity,
+ applyPresetToImageData,
+ applyAdjustmentsToImageData,
+ imageHasFilters,
+ svgImageFilterParts,
+ type SvgFilterSink,
+} from './image-filters'
+
+interface FakeImageData {
+ data: Uint8ClampedArray
+ width: number
+ height: number
+}
+
+function img(w: number, h: number, fill: (x: number, y: number) => [number, number, number]): FakeImageData {
+ const data = new Uint8ClampedArray(w * h * 4)
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const i = (y * w + x) * 4
+ const [r, g, b] = fill(x, y)
+ data[i] = r
+ data[i + 1] = g
+ data[i + 2] = b
+ data[i + 3] = 255
+ }
+ }
+ return { data, width: w, height: h }
+}
+
+function solid(w: number, h: number, rgb: [number, number, number]): FakeImageData {
+ return img(w, h, () => rgb)
+}
+
+function asImageData(d: FakeImageData): ImageData {
+ return d as unknown as ImageData
+}
+
+function px(d: FakeImageData, x: number, y: number): [number, number, number] {
+ const i = (y * d.width + x) * 4
+ return [d.data[i], d.data[i + 1], d.data[i + 2]]
+}
+
+describe('isImageFilterId / clampFilterIntensity', () => {
+ it('accepts exactly the shipped preset ids', () => {
+ for (const p of IMAGE_FILTER_PRESETS) expect(isImageFilterId(p.id)).toBe(true)
+ expect(isImageFilterId('none')).toBe(true)
+ })
+
+ it('rejects junk, prototypes and non-strings', () => {
+ expect(isImageFilterId('EVIL<script>')).toBe(false)
+ expect(isImageFilterId('__proto__')).toBe(false)
+ expect(isImageFilterId('')).toBe(false)
+ expect(isImageFilterId(42)).toBe(false)
+ expect(isImageFilterId(null)).toBe(false)
+ expect(isImageFilterId(undefined)).toBe(false)
+ expect(isImageFilterId({ id: 'warm' })).toBe(false)
+ })
+
+ it('clamps intensity into 0..100 with 100 as the fallback', () => {
+ expect(clampFilterIntensity(undefined)).toBe(100)
+ expect(clampFilterIntensity(NaN)).toBe(100)
+ expect(clampFilterIntensity(Infinity)).toBe(100)
+ expect(clampFilterIntensity('80' as unknown as number)).toBe(100)
+ expect(clampFilterIntensity(-5)).toBe(0)
+ expect(clampFilterIntensity(250)).toBe(100)
+ expect(clampFilterIntensity(80)).toBe(80)
+ })
+})
+
+describe('applyPresetToImageData — no-op guarantees', () => {
+ it("'none' never changes pixels", () => {
+ const d = solid(4, 4, [200, 100, 50])
+ const before = new Uint8ClampedArray(d.data)
+ applyPresetToImageData(asImageData(d), 'none', 1)
+ expect([...d.data]).toEqual([...before])
+ })
+
+ it('t=0 is a no-op for every preset', () => {
+ for (const p of IMAGE_FILTER_PRESETS) {
+ const d = solid(4, 4, [200, 100, 50])
+ const before = new Uint8ClampedArray(d.data)
+ applyPresetToImageData(asImageData(d), p.id, 0)
+ expect([...d.data], `preset ${p.id}`).toEqual([...before])
+ }
+ })
+
+ it('hostile inputs never throw and never change pixels', () => {
+ const d = solid(4, 4, [10, 20, 30])
+ const before = new Uint8ClampedArray(d.data)
+ expect(() => applyPresetToImageData(asImageData(d), 'EVIL', 1)).not.toThrow()
+ expect(() => applyPresetToImageData(asImageData(d), 'none', NaN)).not.toThrow()
+ expect(() => applyPresetToImageData(asImageData(d), '__proto__', 5)).not.toThrow()
+ expect([...d.data]).toEqual([...before])
+ })
+})
+
+describe('applyPresetToImageData — pixel math', () => {
+ it('grayscale lerps to luma (0.299/0.587/0.114)', () => {
+ const d = solid(2, 2, [255, 0, 0]) // pure red
+ applyPresetToImageData(asImageData(d), 'grayscale', 1)
+ const [r, g, b] = px(d, 0, 0)
+ expect(r).toBeGreaterThan(70)
+ expect(r).toBeLessThan(82)
+ expect(r).toBe(g)
+ expect(g).toBe(b)
+ })
+
+ it('grayscale intensity interpolates monotonically', () => {
+ const at = (t: number) => {
+ const d = solid(2, 2, [255, 0, 0])
+ applyPresetToImageData(asImageData(d), 'grayscale', t)
+ return px(d, 0, 0)[0]
+ }
+ expect(at(0)).toBe(255)
+ expect(at(0.5)).toBeGreaterThan(at(1))
+ expect(at(0.25)).toBeGreaterThan(at(0.5))
+ })
+
+ it('warm heats red up and blue down; cool is the mirror', () => {
+ const w = solid(2, 2, [128, 128, 128])
+ applyPresetToImageData(asImageData(w), 'warm', 1)
+ const [wr, wg, wb] = px(w, 0, 0)
+ expect(wr).toBeGreaterThan(140) // 128*1.14 ≈ 146
+ expect(wb).toBeLessThan(120) // 128*0.86 ≈ 110
+
+ const c = solid(2, 2, [128, 128, 128])
+ applyPresetToImageData(asImageData(c), 'cool', 1)
+ const [cr, , cb] = px(c, 0, 0)
+ expect(cb).toBeGreaterThan(cr)
+ expect(cr).toBeLessThan(120)
+ })
+
+ it('vintage lifts blacks and warms whites', () => {
+ const d = img(2, 2, (x) => (x === 0 ? [0, 0, 0] : [255, 255, 255]))
+ applyPresetToImageData(asImageData(d), 'vintage', 1)
+ const black = px(d, 0, 0)
+ const white = px(d, 1, 0)
+ expect(black[0]).toBeGreaterThanOrEqual(15) // lifted from 0
+ expect(black[1]).toBeGreaterThanOrEqual(15)
+ expect(white[0]).toBeGreaterThan(white[2]) // warm tint
+ expect(white[0]).toBe(255) // still bright
+ })
+
+ it('blur spreads a hot center and stays sub-pixel-honest', () => {
+ const d = img(5, 5, (x, y) => (x === 2 && y === 2 ? [255, 255, 255] : [0, 0, 0]))
+ applyPresetToImageData(asImageData(d), 'blur', 1)
+ const center = px(d, 2, 2)[0]
+ const neighbor = px(d, 1, 2)[0]
+ expect(center).toBeLessThan(255)
+ expect(neighbor).toBeGreaterThan(0)
+
+ // sub-pixel radius (t < 1/12) is an honest no-op
+ const tiny = img(5, 5, (x, y) => (x === 2 && y === 2 ? [255, 255, 255] : [0, 0, 0]))
+ const before = new Uint8ClampedArray(tiny.data)
+ applyPresetToImageData(asImageData(tiny), 'blur', 0.05)
+ expect([...tiny.data]).toEqual([...before])
+ })
+
+ it('sharpen leaves flat regions alone and boosts edges', () => {
+ const d = img(6, 2, (x) => (x < 3 ? [0, 0, 0] : [255, 255, 255]))
+ applyPresetToImageData(asImageData(d), 'sharpen', 1)
+ // deep flat zones untouched
+ expect(px(d, 0, 0)[0]).toBe(0)
+ expect(px(d, 5, 0)[0]).toBe(255)
+ // the boundary overshoots (unsharp ringing)
+ const leftOfEdge = px(d, 2, 0)[0]
+ const rightOfEdge = px(d, 3, 0)[0]
+ expect(leftOfEdge).toBeLessThan(60) // darker than 0? clamped at 0 for pure step; allow 0
+ expect(rightOfEdge).toBe(255)
+ })
+
+ it('vignette darkens corners more than the center', () => {
+ const d = solid(9, 9, [128, 128, 128])
+ applyPresetToImageData(asImageData(d), 'vignette', 1)
+ const center = px(d, 4, 4)[0]
+ const corner = px(d, 0, 0)[0]
+ expect(center).toBe(128) // exact center: distance 0 → factor 1
+ expect(corner).toBeLessThan(110) // corner: factor 1 - 0.8 ≈ 0.2 → ~26
+ })
+})
+
+describe('applyAdjustmentsToImageData — Konva-exact math', () => {
+ it('brightness ±100 clamps to white/black', () => {
+ const up = solid(2, 2, [128, 100, 60])
+ applyAdjustmentsToImageData(asImageData(up), 100, 0, 0)
+ expect(px(up, 0, 0)).toEqual([255, 255, 255])
+
+ const dn = solid(2, 2, [128, 100, 60])
+ applyAdjustmentsToImageData(asImageData(dn), -100, 0, 0)
+ expect(px(dn, 0, 0)).toEqual([0, 0, 0])
+ })
+
+ it('contrast pushes darks down and lights up (slope = ((c+100)/100)²)', () => {
+ const d = img(2, 1, (x) => (x === 0 ? [64, 64, 64] : [192, 192, 192]))
+ applyAdjustmentsToImageData(asImageData(d), 0, 100, 0) // slope 4
+ expect(px(d, 0, 0)[0]).toBe(0) // (64/255-.5)*4+.5 < 0 → clamp
+ expect(px(d, 1, 0)[0]).toBe(255) // (192/255-.5)*4+.5 > 1 → clamp
+ })
+
+ it('saturation keeps pure primaries and grays (Konva HSL matrix)', () => {
+ const d = img(2, 1, (x) => (x === 0 ? [255, 0, 0] : [128, 128, 128]))
+ applyAdjustmentsToImageData(asImageData(d), 0, 0, 100)
+ expect(px(d, 0, 0)).toEqual([255, 0, 0])
+ expect(px(d, 1, 0)).toEqual([128, 128, 128])
+ })
+
+ it('desaturation drains a primary toward gray', () => {
+ const d = solid(1, 1, [255, 0, 0])
+ applyAdjustmentsToImageData(asImageData(d), 0, 0, -100) // s = -1
+ const [r, g, b] = px(d, 0, 0)
+ expect(r).toBeLessThan(80) // 0.299-0.701 = -0.402 → clamped low
+ expect(g).toBeGreaterThan(100) // 0.587+0.587 = 1.174 → high
+ expect(b).toBeGreaterThan(100)
+ })
+
+ it('all-zero adjustments are a byte-exact no-op', () => {
+ const d = solid(3, 3, [17, 200, 99])
+ const before = new Uint8ClampedArray(d.data)
+ applyAdjustmentsToImageData(asImageData(d), 0, 0, 0)
+ expect([...d.data]).toEqual([...before])
+ })
+})
+
+describe('imageHasFilters', () => {
+ it('is false for a clean element and true for any active surface', () => {
+ expect(imageHasFilters({})).toBe(false)
+ expect(imageHasFilters({ filter: 'none', filterIntensity: 100 })).toBe(false)
+ expect(imageHasFilters({ filter: 'junk-id' })).toBe(false) // unknown id reads as none
+ expect(imageHasFilters({ brightness: 1 })).toBe(true)
+ expect(imageHasFilters({ contrast: -1 })).toBe(true)
+ expect(imageHasFilters({ saturation: 1 })).toBe(true)
+ expect(imageHasFilters({ filter: 'vintage' })).toBe(true)
+ expect(imageHasFilters({ filter: 'vintage', filterIntensity: 0 })).toBe(false)
+ })
+})
+
+describe('svgImageFilterParts — approximation primitives', () => {
+ function sink(): { s: SvgFilterSink; defs: string[]; n: number } {
+ const defs: string[] = []
+ let n = 0
+ return {
+ s: { defs: (m) => defs.push(m), nextId: (p) => `${p}-${++n}` },
+ defs,
+ get n() {
+ return n
+ },
+ }
+ }
+ const bounds = { x: 10, y: 20, w: 300, h: 200 }
+
+ it('emits nothing for a clean element', () => {
+ const { s, defs } = sink()
+ const r = svgImageFilterParts({}, s, bounds)
+ expect(r.attr).toBe('')
+ expect(r.overlay).toBe('')
+ expect(defs).toEqual([])
+ })
+
+ it('brightness folds into one feComponentTransfer (slope 1, intercept 0.5)', () => {
+ const { s, defs } = sink()
+ const r = svgImageFilterParts({ brightness: 50 }, s, bounds)
+ expect(r.attr).toContain('filter="url(#imgf-1)"')
+ expect(defs.join('\n')).toContain('feComponentTransfer')
+ expect(defs.join('\n')).toContain('slope="1"')
+ expect(defs.join('\n')).toContain('intercept="0.5"')
+ expect(r.overlay).toBe('')
+ })
+
+ it('contrast slope = ((c+100)/100)², recentered around 0.5', () => {
+ const { s, defs } = sink()
+ svgImageFilterParts({ contrast: 100 }, s, bounds)
+ const m = defs.join('\n')
+ expect(m).toContain('slope="4"')
+ expect(m).toContain('intercept="-1.5"') // 0.5 - 0.5*4
+ })
+
+ it('saturation emits Konva HSL matrix values', () => {
+ const { s, defs } = sink()
+ svgImageFilterParts({ saturation: -50 }, s, bounds)
+ const m = defs.join('\n')
+ expect(m).toContain('feColorMatrix')
+ // rr = 0.299 + 0.701*(-0.5) = -0.052
+ expect(m).toContain('-0.051') // JS rounds -51.5 toward +Infinity
+ })
+
+ it('blur σ = gaussian equivalent of the 3-pass box stack', () => {
+ const { s, defs } = sink()
+ svgImageFilterParts({ filter: 'blur', filterIntensity: 100 }, s, bounds)
+ const m = defs.join('\n')
+ expect(m).toContain('feGaussianBlur')
+ // r=6 → σ = sqrt(3*(169-1)/12) = sqrt(42) ≈ 6.481
+ expect(m).toContain('stdDeviation="6.481"')
+ expect(m).toContain('edgeMode="duplicate"')
+ })
+
+ it('sharpen emits the same rounded 3×3 kernel', () => {
+ const { s, defs } = sink()
+ svgImageFilterParts({ filter: 'sharpen', filterIntensity: 80 }, s, bounds)
+ const m = defs.join('\n')
+ expect(m).toContain('feConvolveMatrix')
+ expect(m).toContain('kernel="0 -0.72 0 -0.72 3.88 -0.72 0 -0.72 0"')
+ })
+
+ it('grayscale/warm/cool/vintage emit color matrices (linear = exact)', () => {
+ for (const id of ['grayscale', 'warm', 'cool', 'vintage'] as const) {
+ const { s, defs } = sink()
+ svgImageFilterParts({ filter: id, filterIntensity: 100 }, s, bounds)
+ expect(defs.join('\n'), id).toContain('feColorMatrix')
+ }
+ // vintage also fades: slope < 1 + lift > 0
+ const v = sink()
+ svgImageFilterParts({ filter: 'vintage' }, v.s, bounds)
+ const vm = v.defs.join('\n')
+ expect(vm).toContain('slope="0.88"')
+ expect(vm).toContain('intercept="0.071"') // 18/255
+ })
+
+ it('vignette renders as a clipped gradient overlay, not a filter', () => {
+ const { s, defs } = sink()
+ const r = svgImageFilterParts({ filter: 'vignette', filterIntensity: 60 }, s, bounds)
+ expect(r.attr).toBe('') // no filter primitives
+ expect(r.overlay).toContain('<rect')
+ expect(r.overlay).toContain('fill="url(#vgn-')
+ const m = defs.join('\n')
+ expect(m).toContain('radialGradient')
+ expect(m).toContain('stop-opacity="0.104"') // 0.8*0.6*0.5^2.2
+ expect(m).toContain('stop-opacity="0.48"') // 0.8*0.6*1^2.2
+ })
+
+ it('overlay carries caller attributes (clip/transform parity)', () => {
+ const { s } = sink()
+ const r = svgImageFilterParts({ filter: 'vignette' }, s, bounds, ' clip-path="url(#c1)" transform="rotate(5 160 120)"')
+ expect(r.overlay).toContain('clip-path="url(#c1)"')
+ expect(r.overlay).toContain('transform="rotate(5 160 120)"')
+ })
+
+ it('intensity 0 emits nothing even for an active preset', () => {
+ const { s, defs } = sink()
+ const r = svgImageFilterParts({ filter: 'blur', filterIntensity: 0 }, s, bounds)
+ expect(r.attr).toBe('')
+ expect(r.overlay).toBe('')
+ expect(defs).toEqual([])
+ })
+
+ it('junk filter ids degrade to nothing (readers validated; belt+braces)', () => {
+ const { s, defs } = sink()
+ const r = svgImageFilterParts({ filter: 'EVIL<script>' }, s, bounds)
+ expect(r.attr).toBe('')
+ expect(r.overlay).toBe('')
+ expect(defs).toEqual([])
+ })
+})
diff --git a/src/lib/image-filters.ts b/src/lib/image-filters.ts
new file mode 100644
index 0000000..11fb217
--- /dev/null
+++ b/src/lib/image-filters.ts
@@ -0,0 +1,505 @@
+/**
+ * v0.14 (D4): the image filter gallery — one pure pixel pipeline that
+ * every renderer shares.
+ *
+ * editor canvas → Konva filter wrappers (node.cache() pipeline)
+ * video export → renderFilteredCanvas() pre-bakes pixels
+ * SVG export → svgImageFilterParts() approximates with filter
+ * primitives (documented where approximate)
+ * toolbar chips → renderFilteredCanvas() on a tiny preview canvas
+ *
+ * The element contract (ImageElement): `filter` is a preset id from
+ * IMAGE_FILTER_PRESETS ('none' = untouched) and `filterIntensity` is
+ * 0..100 (default 100). Both are optional for older documents; every
+ * reader normalizes through isImageFilterId()/clampFilterIntensity()
+ * so a hostile paste or MCP patch can never smuggle junk in.
+ *
+ * Adjustments (brightness/contrast/saturation, -100..100) live in the
+ * same pipeline BEFORE the preset, in the exact order the editor has
+ * always applied them: Brighten → Contrast → HSL → preset. The canvas
+ * path reproduces Konva's own math bit-for-bit (the formulas below are
+ * copied from konva/lib/filters) so the two renderers agree.
+ */
+
+// ── presets ───────────────────────────────────────────────────
+
+export interface ImageFilterPreset {
+ id: string
+ label: string
+ /** one-line UI hint (title attr) */
+ hint: string
+}
+
+export const IMAGE_FILTER_PRESETS: readonly ImageFilterPreset[] = [
+ { id: 'none', label: 'Original', hint: 'No filter' },
+ { id: 'grayscale', label: 'Mono', hint: 'Classic black & white' },
+ { id: 'warm', label: 'Warm', hint: 'Golden-hour warmth' },
+ { id: 'cool', label: 'Cool', hint: 'Bluish shadows' },
+ { id: 'vintage', label: 'Vintage', hint: 'Faded warm print' },
+ { id: 'blur', label: 'Blur', hint: 'Soft gaussian blur' },
+ { id: 'sharpen', label: 'Sharpen', hint: 'Crisper edges' },
+ { id: 'vignette', label: 'Vignette', hint: 'Darkened corners' },
+] as const
+
+const PRESET_IDS = new Set(IMAGE_FILTER_PRESETS.map((p) => p.id))
+
+/** unknown input → boolean (never throws; the sanitizer + MCP patcher
+ * both lean on this to keep junk out of the element) */
+export function isImageFilterId(v: unknown): v is string {
+ return typeof v === 'string' && PRESET_IDS.has(v)
+}
+
+/** 0..100, default 100; NaN/∞/junk fall back to the default */
+export function clampFilterIntensity(v: unknown): number {
+ const n = typeof v === 'number' && Number.isFinite(v) ? v : 100
+ return Math.min(100, Math.max(0, Math.round(n)))
+}
+
+// ── the pixel kernels ─────────────────────────────────────────
+
+function clamp255(v: number): number {
+ return v < 0 ? 0 : v > 255 ? 255 : v
+}
+
+/** intensity t (0..1) lerp helper: (1-t)·a + t·b */
+function lerp(a: number, b: number, t: number): number {
+ return a + (b - a) * t
+}
+
+/**
+ * Apply ONE preset to ImageData in place. t = 0 (and 'none') are
+ * guaranteed no-ops — the callers rely on that to skip caching work.
+ * Unknown ids are silently ignored (defense in depth: readers have
+ * already validated, this never throws on hostile input).
+ */
+export function applyPresetToImageData(data: ImageData, id: string, tRaw: number): void {
+ const t = Math.min(1, Math.max(0, Number.isFinite(tRaw) ? tRaw : 0))
+ if (t <= 0 || id === 'none') return
+ const px = data.data
+ const w = data.width
+ const h = data.height
+
+ if (id === 'grayscale') {
+ for (let i = 0; i < px.length; i += 4) {
+ const lum = 0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2]
+ px[i] = clamp255(lerp(px[i], lum, t))
+ px[i + 1] = clamp255(lerp(px[i + 1], lum, t))
+ px[i + 2] = clamp255(lerp(px[i + 2], lum, t))
+ }
+ return
+ }
+
+ if (id === 'warm' || id === 'cool') {
+ const wr = id === 'warm' ? 1.14 : 0.88
+ const wb = id === 'warm' ? 0.86 : 1.12
+ const wg = id === 'warm' ? 1.03 : 0.97
+ for (let i = 0; i < px.length; i += 4) {
+ px[i] = clamp255(lerp(px[i], px[i] * wr, t))
+ px[i + 1] = clamp255(lerp(px[i + 1], px[i + 1] * wg, t))
+ px[i + 2] = clamp255(lerp(px[i + 2], px[i + 2] * wb, t))
+ }
+ return
+ }
+
+ if (id === 'vintage') {
+ // faded warm print: sepia-lerp (0.6 of full sepia), then lift the
+ // blacks + slightly flatten contrast — all affine, so the SVG
+ // approximation can reproduce it exactly
+ const ts = 0.6 * t
+ const slope = 1 - 0.12 * t
+ const lift = 18 * t
+ for (let i = 0; i < px.length; i += 4) {
+ const r = px[i]
+ const g = px[i + 1]
+ const b = px[i + 2]
+ const sr = 0.393 * r + 0.769 * g + 0.194 * b
+ const sg = 0.349 * r + 0.686 * g + 0.168 * b
+ const sb = 0.272 * r + 0.534 * g + 0.131 * b
+ px[i] = clamp255((lerp(r, sr, ts) - lift * 0) * slope + lift)
+ px[i + 1] = clamp255(lerp(g, sg, ts) * slope + lift)
+ px[i + 2] = clamp255(lerp(b, sb, ts) * slope + lift * 0.9)
+ }
+ return
+ }
+
+ if (id === 'blur') {
+ // three box passes ≈ gaussian; radius scales with intensity.
+ // sub-pixel radii are an honest no-op (no jump at low intensity)
+ const radius = Math.round(6 * t)
+ if (radius < 1) return
+ boxBlurPass(px, w, h, radius, true) // horizontal
+ boxBlurPass(px, w, h, radius, false) // vertical
+ boxBlurPass(px, w, h, radius, true)
+ boxBlurPass(px, w, h, radius, false)
+ return
+ }
+
+ if (id === 'sharpen') {
+ // 3×3 unsharp kernel; edges clamp like feConvolveMatrix duplicate
+ const k = 0.9 * t
+ if (k <= 0) return
+ const src = new Uint8ClampedArray(px)
+ for (let y = 0; y < h; y++) {
+ const yUp = y > 0 ? y - 1 : 0
+ const yDn = y < h - 1 ? y + 1 : h - 1
+ for (let x = 0; x < w; x++) {
+ const xL = x > 0 ? x - 1 : 0
+ const xR = x < w - 1 ? x + 1 : w - 1
+ const i = (y * w + x) * 4
+ for (let c = 0; c < 3; c++) {
+ const up = src[(yUp * w + x) * 4 + c]
+ const dn = src[(yDn * w + x) * 4 + c]
+ const lf = src[(y * w + xL) * 4 + c]
+ const rt = src[(y * w + xR) * 4 + c]
+ const me = src[i + c]
+ px[i + c] = clamp255(me + k * (4 * me - up - dn - lf - rt))
+ }
+ }
+ }
+ return
+ }
+
+ if (id === 'vignette') {
+ const cx = (w - 1) / 2
+ const cy = (h - 1) / 2
+ const maxD = Math.sqrt(cx * cx + cy * cy)
+ if (maxD <= 0) return
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const dx = (x - cx) / maxD
+ const dy = (y - cy) / maxD
+ const d2 = dx * dx + dy * dy // normalized 0..1, 1 at corners
+ const f = 1 - 0.8 * t * Math.pow(d2, 1.1)
+ const i = (y * w + x) * 4
+ px[i] = clamp255(px[i] * f)
+ px[i + 1] = clamp255(px[i + 1] * f)
+ px[i + 2] = clamp255(px[i + 2] * f)
+ }
+ }
+ return
+ }
+ // unknown id: no-op (readers validate; this is the last line of defense)
+}
+
+/** one axis of an in-place box blur (edge clamp = duplicate) */
+function boxBlurPass(px: Uint8ClampedArray, w: number, h: number, r: number, horizontal: boolean): void {
+ const src = new Uint8ClampedArray(px)
+ const len = horizontal ? w : h
+ const outer = horizontal ? h : w
+ const win = r * 2 + 1
+ for (let o = 0; o < outer; o++) {
+ for (let c = 0; c < 3; c++) {
+ let sum = 0
+ // seed: clamped window around index 0
+ for (let k = -r; k <= r; k++) {
+ const idx = Math.min(len - 1, Math.max(0, k))
+ sum += horizontal ? src[(o * w + idx) * 4 + c] : src[(idx * w + o) * 4 + c]
+ }
+ for (let i = 0; i < len; i++) {
+ const dst = horizontal ? (o * w + i) * 4 + c : (i * w + o) * 4 + c
+ px[dst] = sum / win
+ const addI = Math.min(len - 1, i + r + 1)
+ const subI = Math.max(0, i - r)
+ sum += (horizontal ? src[(o * w + addI) * 4 + c] : src[(addI * w + o) * 4 + c])
+ sum -= (horizontal ? src[(o * w + subI) * 4 + c] : src[(subI * w + o) * 4 + c])
+ }
+ }
+ }
+}
+
+// ── adjustments (Konva-exact, for the canvas pre-render path) ──
+
+/**
+ * Apply brightness/contrast/saturation in the exact order and math the
+ * editor's Konva pipeline uses (Brighten → Contrast → HSL; formulas
+ * copied from konva/lib/filters). Values are the element's -100..100
+ * scale; 0s are no-ops.
+ */
+export function applyAdjustmentsToImageData(
+ data: ImageData,
+ brightness: number,
+ contrast: number,
+ saturation: number
+): void {
+ const b = Number.isFinite(brightness) ? brightness : 0
+ const c = Number.isFinite(contrast) ? contrast : 0
+ const s = Number.isFinite(saturation) ? saturation / 100 : 0
+ const px = data.data
+ const add = (b / 100) * 255
+ const adjust = Math.pow((c + 100) / 100, 2)
+ // Konva HSL with hue=0, luminance=0 (vsu=s, vsw=0)
+ const rr = 0.299 + 0.701 * s
+ const rg = 0.587 - 0.587 * s
+ const rb = 0.114 - 0.114 * s
+ const gr = 0.299 - 0.299 * s
+ const gg = 0.587 + 0.413 * s
+ const gb = 0.114 - 0.114 * s
+ const br = 0.299 - 0.3 * s
+ const bg = 0.587 - 0.588 * s
+ const bb = 0.114 + 0.886 * s
+ const noAdjust = b === 0 && c === 0
+ const noSat = s === 0 // s=0 matrix would still map colors to luma — Konva loads HSL only when needed
+ if (noAdjust && noSat) return
+ for (let i = 0; i < px.length; i += 4) {
+ let v0 = px[i] + add // Brighten
+ let v1 = px[i + 1] + add
+ let v2 = px[i + 2] + add
+ if (!noAdjust) {
+ // Contrast (normalized around 0.5)
+ v0 = ((v0 / 255 - 0.5) * adjust + 0.5) * 255
+ v1 = ((v1 / 255 - 0.5) * adjust + 0.5) * 255
+ v2 = ((v2 / 255 - 0.5) * adjust + 0.5) * 255
+ }
+ if (!noSat) {
+ // HSL saturation matrix
+ const r = v0
+ const g = v1
+ const bl = v2
+ v0 = rr * r + rg * g + rb * bl
+ v1 = gr * r + gg * g + gb * bl
+ v2 = br * r + bg * g + bb * bl
+ }
+ px[i] = clamp255(v0)
+ px[i + 1] = clamp255(v1)
+ px[i + 2] = clamp255(v2)
+ }
+}
+
+// ── canvas pre-render (video export + toolbar chips) ──────────
+
+const filteredCache = new WeakMap<object, Map<string, HTMLCanvasElement>>()
+
+export interface FilterElementLike {
+ brightness?: number
+ contrast?: number
+ saturation?: number
+ filter?: string
+ filterIntensity?: number
+}
+
+/** true when ANY filter/adjustment would change pixels (skip work otherwise) */
+export function imageHasFilters(el: FilterElementLike): boolean {
+ const preset = isImageFilterId(el.filter) ? el.filter : 'none'
+ const t = clampFilterIntensity(el.filterIntensity) / 100
+ return (
+ (el.brightness ?? 0) !== 0 ||
+ (el.contrast ?? 0) !== 0 ||
+ (el.saturation ?? 0) !== 0 ||
+ (preset !== 'none' && t > 0)
+ )
+}
+
+/**
+ * Draw `source` to a canvas of `w`×`h` with the element's adjustments +
+ * preset applied — the pixel-exact twin of the editor's Konva output.
+ * Results are memoized per (source, params, size) so per-page rebuilds
+ * in the video exporter don't re-bake pixels.
+ */
+export function renderFilteredCanvas(
+ el: FilterElementLike,
+ source: CanvasImageSource & object,
+ w: number,
+ h: number
+): HTMLCanvasElement {
+ const preset = isImageFilterId(el.filter) ? el.filter : 'none'
+ const intensity = clampFilterIntensity(el.filterIntensity)
+ const key = `${w}x${h}|${el.brightness ?? 0}|${el.contrast ?? 0}|${el.saturation ?? 0}|${preset}|${intensity}`
+ let bySize = filteredCache.get(source)
+ if (!bySize) {
+ bySize = new Map()
+ filteredCache.set(source, bySize)
+ }
+ const hit = bySize.get(key)
+ if (hit) return hit
+
+ const canvas = document.createElement('canvas')
+ canvas.width = Math.max(1, Math.round(w))
+ canvas.height = Math.max(1, Math.round(h))
+ const ctx = canvas.getContext('2d', { willReadFrequently: true })
+ if (!ctx) return canvas
+ ctx.drawImage(source, 0, 0, canvas.width, canvas.height)
+ if (imageHasFilters(el)) {
+ const data = ctx.getImageData(0, 0, canvas.width, canvas.height)
+ applyAdjustmentsToImageData(data, el.brightness ?? 0, el.contrast ?? 0, el.saturation ?? 0)
+ applyPresetToImageData(data, preset, intensity / 100)
+ ctx.putImageData(data, 0, 0)
+ }
+ bySize.set(key, canvas)
+ return canvas
+}
+
+// ── SVG export approximation ──────────────────────────────────
+
+export interface SvgFilterSink {
+ /** push a `<filter>…</filter>` (or gradient) definition */
+ defs: (markup: string) => void
+ /** allocate a unique id */
+ nextId: (prefix: string) => string
+}
+
+export interface SvgImageFilterResult {
+ /** ` filter="url(#id)"` to append to the <image> tag ('' when none) */
+ attr: string
+ /**
+ * Extra markup to emit AFTER the image (the vignette overlay, which
+ * is a clipped gradient rect, not a filter primitive — an honest
+ * approximation documented in the module header).
+ */
+ overlay: string
+}
+
+/**
+ * SVG approximation of the element's full filter stack
+ * (adjustments + preset). Runs inside svg-export's image case.
+ *
+ * Fidelity notes (documented approximations):
+ * - brightness/contrast → feComponentTransfer linear (exact)
+ * - saturation → feColorMatrix with Konva's HSL matrix (exact)
+ * - grayscale/warm/cool/vintage → linear color matrices (exact);
+ * vintage's black-lift rides the same feComponentTransfer pass
+ * - sharpen → feConvolveMatrix with the same 3×3 kernel (exact)
+ * - blur → feGaussianBlur with σ = the gaussian equivalent of
+ * the kernel's 3-pass box stack (exact variance match; the box
+ * stack itself is the approximation of a true gaussian)
+ * - vignette → clipped radial-gradient overlay rect (alpha-over
+ * compositing matches the kernel's multiply falloff shape, stops
+ * approximate the d^2.2 curve)
+ */
+export function svgImageFilterParts(
+ el: FilterElementLike,
+ sink: SvgFilterSink,
+ bounds: { x: number; y: number; w: number; h: number },
+ /** extra attributes for the vignette overlay rect (clip-path /
+ * transform — whatever the caller's image tag carries) */
+ overlayAttrs = ''
+): SvgImageFilterResult {
+ const preset = isImageFilterId(el.filter) ? el.filter : 'none'
+ const t = clampFilterIntensity(el.filterIntensity) / 100
+ const b = el.brightness ?? 0
+ const c = el.contrast ?? 0
+ const s = el.saturation ?? 0
+ const needBase = b !== 0 || c !== 0 || s !== 0
+ const needPreset = preset !== 'none' && t > 0 && preset !== 'vignette'
+ const needVignette = preset === 'vignette' && t > 0
+
+ if (!needBase && !needPreset && !needVignette) return { attr: '', overlay: '' }
+
+ const id = sink.nextId('imgf')
+ const primitives: string[] = []
+
+ if (needBase) {
+ const adjust = Math.pow((c + 100) / 100, 2)
+ // Brighten + Contrast fold into one linear transfer per channel
+ // (normalized 0..1): v' = slope·v + intercept with
+ // slope = ((c+100)/100)², intercept = 0.5 - 0.5·slope + b/100
+ const slope = adjust
+ const intercept = 0.5 - 0.5 * adjust + b / 100
+ primitives.push(
+ ` <feComponentTransfer>\n` +
+ ['R', 'G', 'B']
+ .map((ch) => ` <feFunc${ch} type="linear" slope="${round(slope)}" intercept="${round(intercept)}" />`)
+ .join('\n') +
+ `\n </feComponentTransfer>`
+ )
+ if (s !== 0) {
+ // Konva HSL saturation matrix, hue=0/luminance=0
+ const m = [
+ round(0.299 + 0.701 * (s / 100)), round(0.587 - 0.587 * (s / 100)), round(0.114 - 0.114 * (s / 100)), 0, 0,
+ round(0.299 - 0.299 * (s / 100)), round(0.587 + 0.413 * (s / 100)), round(0.114 - 0.114 * (s / 100)), 0, 0,
+ round(0.299 - 0.3 * (s / 100)), round(0.587 - 0.588 * (s / 100)), round(0.114 + 0.886 * (s / 100)), 0, 0,
+ 0, 0, 0, 1, 0,
+ ]
+ primitives.push(` <feColorMatrix type="matrix" values="${m.join(' ')}" />`)
+ }
+ }
+
+ if (preset === 'grayscale') {
+ // exact linear lerp-to-luma: (1-t)·I + t·Luma
+ const k = 1 - t
+ const m = [
+ round(k + 0.299 * t), round(0.587 * t), round(0.114 * t), 0, 0,
+ round(0.299 * t), round(k + 0.587 * t), round(0.114 * t), 0, 0,
+ round(0.299 * t), round(0.587 * t), round(k + 0.114 * t), 0, 0,
+ 0, 0, 0, 1, 0,
+ ]
+ primitives.push(` <feColorMatrix type="matrix" values="${m.join(' ')}" />`)
+ } else if (preset === 'warm' || preset === 'cool') {
+ const wr = preset === 'warm' ? 1.14 : 0.88
+ const wg = preset === 'warm' ? 1.03 : 0.97
+ const wb = preset === 'warm' ? 0.86 : 1.12
+ const k = 1 - t
+ const m = [
+ round(k + wr * t), 0, 0, 0, 0,
+ 0, round(k + wg * t), 0, 0, 0,
+ 0, 0, round(k + wb * t), 0, 0,
+ 0, 0, 0, 1, 0,
+ ]
+ primitives.push(` <feColorMatrix type="matrix" values="${m.join(' ')}" />`)
+ } else if (preset === 'vintage') {
+ // sepia lerp (0.6t) then fade slope/lift — affine, exact
+ const ts = 0.6 * t
+ const k = 1 - ts
+ const m = [
+ round(k + 0.393 * ts), round(0.769 * ts), round(0.194 * ts), 0, 0,
+ round(0.349 * ts), round(k + 0.686 * ts), round(0.168 * ts), 0, 0,
+ round(0.272 * ts), round(0.534 * ts), round(k + 0.131 * ts), 0, 0,
+ 0, 0, 0, 1, 0,
+ ]
+ primitives.push(` <feColorMatrix type="matrix" values="${m.join(' ')}" />`)
+ const slope = 1 - 0.12 * t
+ const lift = (18 * t) / 255
+ primitives.push(
+ ` <feComponentTransfer>\n` +
+ ['R', 'G', 'B']
+ .map((ch, i) => ` <feFunc${ch} type="linear" slope="${round(slope)}" intercept="${round(i === 2 ? lift * 0.9 : lift)}" />`)
+ .join('\n') +
+ `\n </feComponentTransfer>`
+ )
+ } else if (preset === 'blur') {
+ // σ of the pixel kernel's 3-pass box stack: sqrt(3·((2r+1)²−1)/12)
+ const r = Math.round(6 * t)
+ const sigma = Math.sqrt((3 * ((2 * r + 1) * (2 * r + 1) - 1)) / 12)
+ primitives.push(` <feGaussianBlur stdDeviation="${round(sigma)}" edgeMode="duplicate" />`)
+ } else if (preset === 'sharpen') {
+ // same 3×3 kernel as the pixel path, rounded once, used everywhere
+ const k = round(0.9 * t)
+ const center = round(1 + 4 * 0.9 * t)
+ primitives.push(
+ ` <feConvolveMatrix order="3" preserveAlpha="true" edgeMode="duplicate" divisor="1" kernel="0 ${-k} 0 ${-k} ${center} ${-k} 0 ${-k} 0" />`
+ )
+ }
+
+ let attr = ''
+ if (primitives.length) {
+ sink.defs(
+ ` <filter id="${id}" color-interpolation-filters="sRGB" x="-20%" y="-20%" width="140%" height="140%">\n${primitives.join('\n')}\n </filter>`
+ )
+ attr = ` filter="url(#${id})"`
+ }
+
+ let overlay = ''
+ if (needVignette) {
+ const gid = sink.nextId('vgn')
+ const { x, y, w, h } = bounds
+ const cx = x + w / 2
+ const cy = y + h / 2
+ const r = Math.sqrt(w * w + h * h) / 2
+ // stops approximate the kernel's (1 - 0.8t·d^2.2) falloff
+ const a = (d: number) => round(0.8 * t * Math.pow(d, 2.2))
+ sink.defs(
+ ` <radialGradient id="${gid}" gradientUnits="userSpaceOnUse" cx="${round(cx)}" cy="${round(cy)}" r="${round(r)}">\n` +
+ ` <stop offset="0" stop-color="#000000" stop-opacity="0" />\n` +
+ ` <stop offset="0.5" stop-color="#000000" stop-opacity="${a(0.5)}" />\n` +
+ ` <stop offset="0.75" stop-color="#000000" stop-opacity="${a(0.75)}" />\n` +
+ ` <stop offset="1" stop-color="#000000" stop-opacity="${a(1)}" />\n` +
+ ` </radialGradient>`
+ )
+ overlay = ` <rect x="${x}" y="${y}" width="${w}" height="${h}"${overlayAttrs} fill="url(#${gid})" />`
+ }
+
+ return { attr, overlay }
+}
+
+function round(v: number): number {
+ return Math.round(v * 1000) / 1000
+}
diff --git a/src/lib/mcp/tools.ts b/src/lib/mcp/tools.ts
index b67a34c..6dc8ab5 100644
--- a/src/lib/mcp/tools.ts
+++ b/src/lib/mcp/tools.ts
@@ -8,6 +8,7 @@ import type { NextRequest } from 'next/server'
import { db } from '@/lib/db'
import { safeFetch } from './ssrf-guard'
import { FONTS } from '@/lib/editor-utils'
+import { isImageFilterId } from '@/lib/image-filters'
import { exportPageToSVG } from '@/lib/svg-export'
import { magicAnimatePage, clearPageAnimations } from '@/lib/animations'
import { hasProvider, getZAI, recordUsage, rateLimit } from '@/lib/ai/provider'
@@ -1105,7 +1106,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {
const COMMON_KEYS = new Set(['x', 'y', 'width', 'height', 'rotation', 'opacity', 'visible', 'locked', 'name'])
const TEXT_KEYS = new Set([...COMMON_KEYS, 'text', 'fontSize', 'fontFamily', 'bold', 'italic', 'underline', 'strike', 'uppercase', 'fill', 'align', 'lineHeight', 'letterSpacing', 'curve'])
const SHAPE_KEYS = new Set([...COMMON_KEYS, 'fill', 'stroke', 'strokeWidth', 'cornerRadius'])
-const IMAGE_KEYS = new Set([...COMMON_KEYS, 'src', 'radius'])
+const IMAGE_KEYS = new Set([...COMMON_KEYS, 'src', 'radius', 'brightness', 'contrast', 'saturation', 'filter', 'filterIntensity'])
const TABLE_KEYS = new Set([...COMMON_KEYS, 'rows', 'cols', 'cells', 'colWidths', 'rowHeight', 'borderColor', 'borderWidth', 'headerFill', 'textColor', 'fontSize', 'fontFamily'])
const FRAME_KEYS = new Set([...COMMON_KEYS, 'frameShape', 'src', 'radius'])
const EMBED_KEYS = new Set([...COMMON_KEYS, 'url', 'title', 'tint'])
@@ -1162,6 +1163,17 @@ function sanitizePatch(patch: Record<string, unknown>, el: AnyElement, pageW: nu
case 'src':
out.src = isHttpsUrl(value) || (typeof value === 'string' && value.startsWith('data:image/')) ? value : ((el as { src?: string }).src ?? '')
break
+ case 'brightness':
+ case 'contrast':
+ case 'saturation':
+ out[key] = clamp(asNumber(value, 0), -100, 100)
+ break
+ case 'filterIntensity':
+ out.filterIntensity = clamp(asNumber(value, 100), 0, 100)
+ break
+ case 'filter':
+ out.filter = isImageFilterId(value) ? value : 'none'
+ break
case 'url':
out.url = isHttpsUrl(value) ? value : ((el as { url?: string }).url ?? '')
break
diff --git a/src/lib/svg-export.ts b/src/lib/svg-export.ts
index 82f020c..bbf1836 100644
--- a/src/lib/svg-export.ts
+++ b/src/lib/svg-export.ts
@@ -27,6 +27,7 @@ import type {
TextElement,
GroupElement,
} from '@/lib/types'
+import { svgImageFilterParts } from '@/lib/image-filters'
import { arcForCurve, embedLayout, frameClipPathD, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'
import type { PluginElement } from '@/lib/types'
import { getRenderEntry, renderKey } from '@/lib/plugins/renderer-cache'
@@ -420,7 +421,19 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {
const transform = [fx, fy, im.rotation ? `rotate(${im.rotation} ${cxImg} ${cyImg})` : '']
.filter(Boolean)
.join(' ')
- return ` <image href="${esc(href)}" x="${im.x}" y="${im.y}" width="${im.width}" height="${im.height}"${clipId ? ` clip-path="url(#${clipId})"` : ''}${transform ? ` transform="${transform}"` : ''}${opacityAttr(im)}${shadowAttrs(im, ctx)} preserveAspectRatio="none" />`
+ // v0.14 (D4): adjustments + filter preset as SVG filter primitives
+ // (documented approximations — see lib/image-filters.ts); the
+ // vignette preset renders as a clipped radial-gradient overlay
+ // riding the same clip + transform as the image
+ const filt = svgImageFilterParts(
+ im,
+ { defs: (markup) => ctx.defs.push(markup), nextId: refId },
+ { x: im.x, y: im.y, w: im.width, h: im.height },
+ `${clipId ? ` clip-path="url(#${clipId})"` : ''}${transform ? ` transform="${transform}"` : ''}`
+ )
+ const image = ` <image href="${esc(href)}" x="${im.x}" y="${im.y}" width="${im.width}" height="${im.height}"${clipId ? ` clip-path="url(#${clipId})"` : ''}${transform ? ` transform="${transform}"` : ''}${filt.attr}${opacityAttr(im)}${shadowAttrs(im, ctx)} preserveAspectRatio="none" />`
+ return filt.overlay ? `${image}
+${filt.overlay}` : image
}
case 'sticker': {
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 357745e..674290f 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -177,6 +177,12 @@ export interface ImageElement extends BaseElement {
brightness?: number // -100..100
contrast?: number // -100..100
saturation?: number // -100..100
+ /** v0.14 (D4): filter-gallery preset id — see lib/image-filters.ts
+ * ('none' or undefined = untouched; readers validate via
+ * isImageFilterId() so hostile pastes can't smuggle junk in) */
+ filter?: string
+ /** preset strength 0..100 (default 100) */
+ filterIntensity?: number
}
export interface StickerElement extends BaseElement {
@@ -571,6 +577,8 @@ export function createImageElement(
brightness: 0,
contrast: 0,
saturation: 0,
+ filter: 'none',
+ filterIntensity: 100,
...init,
}
}
diff --git a/src/lib/video-export.ts b/src/lib/video-export.ts
index ddf1295..0a021fe 100644
--- a/src/lib/video-export.ts
+++ b/src/lib/video-export.ts
@@ -13,6 +13,7 @@
import Konva from 'konva'
import type { AnyElement, AudioElement, ImageElement, PageData, PluginElement, VideoElement } from '@/lib/types'
+import { imageHasFilters, renderFilteredCanvas } from '@/lib/image-filters'
import { animateElementAt, pageHoldDuration } from '@/lib/animations'
import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'
import { awaitRender, renderKey } from '@/lib/plugins/renderer-cache'
@@ -290,14 +291,24 @@ function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>):
}
case 'image': {
const im = el as ImageElement
+ // v0.14 (D4): adjustments + filter preset are pre-baked into the
+ // bitmap (pixel-exact twin of the editor's Konva pipeline) — and
+ // while here, flips/rotation finally export too (parity fix)
+ const img = images.get(im.src)
+ const bitmap = img && imageHasFilters(im) ? renderFilteredCanvas(im, img, im.width, im.height) : img
const node = new Konva.Image({
id: im.id,
x: im.x,
y: im.y,
width: im.width,
height: im.height,
- image: images.get(im.src) ?? undefined,
+ image: bitmap ?? undefined,
cornerRadius: im.radius,
+ scaleX: im.flipH ? -1 : 1,
+ scaleY: im.flipV ? -1 : 1,
+ offsetX: im.flipH ? im.width : 0,
+ offsetY: im.flipV ? im.height : 0,
+ rotation: im.rotation ?? 0,
})
return node
}
diff --git a/tests/e2e/image-filters.spec.ts b/tests/e2e/image-filters.spec.ts
new file mode 100644
index 0000000..90446be
--- /dev/null
+++ b/tests/e2e/image-filters.spec.ts
@@ -0,0 +1,253 @@
+import { test, expect, type Page } from '@playwright/test'
+import { readFileSync } from 'node:fs'
+
+/**
+ * v0.14 (D4): the image filter gallery — acceptance.
+ *
+ * 1. preset chips render LIVE previews of the element's own image
+ * (the pixel pipeline runs in the popover, not a static sprite)
+ * 2. clicking a preset lands in the document (API truth: filter +
+ * filterIntensity), the intensity slider adjusts it, and the
+ * main canvas re-renders with different pixels
+ * 3. the filter persists across a reload (stored in the element)
+ * 4. the exported SVG carries the approximation primitives AND the
+ * D1 media inlining (filters + portable exports compose)
+ * 5. a second design's mixed-preset images each export their own
+ * primitive (per-element filters, no cross-contamination)
+ *
+ * Register budget: ONE registration per run (the second test logs in
+ * with the shared account — the PR #26 discipline).
+ */
+
+// an 8×8 solid-red PNG (75 bytes)
+const RED_PNG_B64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEklEQVR4nGP4z8CAFWEXHbQSACj/P8Fu7N9hAAAAAElFTkSuQmCC'
+
+function imageEl(id: string, x: number, overrides: Record<string, unknown> = {}) {
+ return {
+ id,
+ type: 'image',
+ name: `filter target ${id}`,
+ x,
+ y: 120,
+ width: 240,
+ height: 180,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ src: `data:image/png;base64,${RED_PNG_B64}`,
+ radius: 0,
+ naturalWidth: 8,
+ naturalHeight: 8,
+ brightness: 0,
+ contrast: 0,
+ saturation: 0,
+ ...overrides,
+ }
+}
+
+// tests in this file run sequentially — the first test to register
+// publishes its credentials; the second logs in instead (5/h/IP budget)
+let SHARED_ACCOUNT: { username: string; password: string } | null = null
+
+async function register(page: Page, tag: string): Promise<string> {
+ const username = `d4_${tag}_${Date.now().toString(36)}`
+ const password = `D4-E2e-${username}-17!q`
+ const res = await page.request.post('/api/auth/register', { data: { username, password } })
+ expect(res.status(), `register ${username}`).toBeLessThan(300)
+ if (!SHARED_ACCOUNT) SHARED_ACCOUNT = { username, password }
+ return username
+}
+
+async function createDesign(page: Page, name: string, elements: unknown[]): Promise<string> {
+ const res = await page.request.post('/api/designs', {
+ data: { name, width: 1080, height: 720, pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements }] },
+ })
+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)
+ return ((await res.json()) as { id: string }).id
+}
+
+async function openEditor(page: Page, designId: string) {
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+}
+
+interface DocImage {
+ id: string
+ filter?: string
+ filterIntensity?: number
+}
+
+async function docImages(page: Page, designId: string): Promise<DocImage[]> {
+ const res = await page.request.get(`/api/designs/${designId}`)
+ expect(res.status()).toBe(200)
+ const doc = (await res.json()) as { pages: { elements: DocImage[] }[] }
+ return doc.pages[0].elements.filter((e) => e.id)
+}
+
+/** the main Konva canvas as a data URL (pixel truth). Scoped to the
+ * workspace <main> — toolbar popovers (filter thumbs!) render their
+ * own canvases EARLIER in DOM order, so a bare querySelector('canvas')
+ * would snapshot a 56×40 thumb instead of the stage. */
+async function canvasSnapshot(page: Page): Promise<string> {
+ return page.evaluate(() => {
+ const scope = document.querySelector('main[aria-label="Design canvas"]')
+ const canvases = Array.from((scope ?? document).querySelectorAll('canvas'))
+ // the stage canvas is by far the largest in the workspace
+ const biggest = canvases.reduce<HTMLCanvasElement | null>(
+ (best, c) => (!best || c.width * c.height > best.width * best.height ? c : best),
+ null
+ )
+ return biggest ? biggest.toDataURL() : ''
+ })
+}
+
+test.describe('Image filters (v0.14 D4)', () => {
+ test.setTimeout(150_000)
+
+ test('preset chips preview live → apply persists → intensity → canvas pixels → SVG export', async ({ page }) => {
+ const username = await register(page, 'main')
+ const design = await createDesign(page, `cvx_d4_${username}`, [imageEl('img_d4_main', 420)])
+ await openEditor(page, design)
+
+ // select the image through the layers tab (Konva is DOM-opaque)
+ await page.getByRole('button', { name: 'Tools', exact: true }).click()
+ await page.getByRole('button', { name: 'Layers', exact: true }).click()
+ await page.getByText('filter target img_d4_main', { exact: true }).click()
+
+ // open the gallery (the old "Filter tint (soon)" stub is gone)
+ await page.getByRole('button', { name: 'Filters', exact: true }).click()
+ const popover = page.locator('.cv-pop').last()
+ await expect(popover).toBeVisible()
+
+ // 8 preset chips, Original first, none of the old stub anywhere
+ for (const label of ['Original', 'Mono', 'Warm', 'Cool', 'Vintage', 'Blur', 'Sharpen', 'Vignette']) {
+ await expect(popover.getByRole('button', { name: `Filter ${label}` })).toBeVisible()
+ }
+
+ // the chips render LIVE previews: Mono's thumb pixels differ from
+ // Original's (the pixel pipeline runs on the element's own image)
+ const thumbUrls = await popover.evaluate(() => {
+ const out: Record<string, string> = {}
+ for (const btn of Array.from(document.querySelectorAll('.cv-pop button[aria-label^="Filter "]'))) {
+ const label = btn.getAttribute('aria-label')!.slice('Filter '.length)
+ const canvas = btn.querySelector('canvas')
+ out[label] = canvas ? canvas.toDataURL() : ''
+ }
+ return out
+ })
+ expect(thumbUrls.Original, 'Original thumb rendered').not.toBe('')
+ expect(thumbUrls.Mono).not.toBe('')
+ expect(thumbUrls.Mono, 'Mono preview differs from Original (red → gray)').not.toBe(thumbUrls.Original)
+
+ // the main canvas is stable before the filter (no idle animation)
+ const before1 = await canvasSnapshot(page)
+ await page.waitForTimeout(700)
+ const before2 = await canvasSnapshot(page)
+ const canvasWasStable = before1 === before2 && before1 !== ''
+
+ // apply Mono → lands in the document (API truth)
+ await popover.getByRole('button', { name: 'Filter Mono' }).click()
+ await expect
+ .poll(async () => {
+ const imgs = await docImages(page, design)
+ return imgs.find((e) => e.id === 'img_d4_main')?.filter
+ }, { timeout: 20_000 })
+ .toBe('grayscale')
+ const applied = (await docImages(page, design)).find((e) => e.id === 'img_d4_main')
+ expect(applied?.filterIntensity).toBe(100)
+
+ // the main canvas re-rendered with different pixels
+ if (canvasWasStable) {
+ await expect
+ .poll(() => canvasSnapshot(page), { timeout: 15_000 })
+ .not.toBe(before2)
+ }
+
+ // the chip shows the active state
+ await expect(popover.getByRole('button', { name: 'Filter Mono' })).toHaveAttribute('aria-pressed', 'true')
+
+ // intensity slider → 40
+ const slider = popover.locator('input[aria-label="Intensity slider"]')
+ await slider.fill('40')
+ await slider.dispatchEvent('pointerup')
+ await expect
+ .poll(async () => {
+ const imgs = await docImages(page, design)
+ return imgs.find((e) => e.id === 'img_d4_main')?.filterIntensity
+ }, { timeout: 20_000 })
+ .toBe(40)
+
+ // reload — the filter persists (stored in the element)
+ await openEditor(page, design)
+ await page.getByRole('button', { name: 'Tools', exact: true }).click()
+ await page.getByRole('button', { name: 'Layers', exact: true }).click()
+ await page.getByText('filter target img_d4_main', { exact: true }).click()
+ await page.getByRole('button', { name: 'Filters', exact: true }).click()
+ const popover2 = page.locator('.cv-pop').last()
+ await expect(popover2.getByRole('button', { name: 'Filter Mono' })).toHaveAttribute('aria-pressed', 'true')
+ // and the intensity round-tripped
+ await expect(popover2.locator('input[aria-label="Intensity"]')).toHaveValue('40')
+
+ // close the popover first — its full-screen backdrop covers the
+ // Download button (the click would be intercepted)
+ await page.mouse.click(30, 700)
+
+ // export SVG → the grayscale approximation primitive is in the
+ // file (and the image itself still inlines as a data URL — D1)
+ await page.getByRole('button', { name: 'Download', exact: true }).click()
+ await page.getByRole('button', { name: /^SVG\b/ }).click()
+ const [download] = await Promise.all([
+ page.waitForEvent('download'),
+ page.getByRole('button', { name: /Download 1 SVG/i }).click(),
+ ])
+ const svg = readFileSync((await download.path())!, 'utf8')
+ expect(svg).toContain('feColorMatrix') // grayscale ≈ luma matrix
+ expect(svg).toContain('data:image/png;base64,') // D1 inlining intact
+
+ // back in the editor: Original resets the element (reopen the
+ // gallery — the export dialog and the closed popover are gone)
+ // the dialog auto-closes after the export (observed end state,
+ // never toast timing)
+ await expect(page.getByRole('button', { name: 'Close' })).toBeHidden({ timeout: 10_000 })
+ await page.getByRole('button', { name: 'Filters', exact: true }).click()
+ const popover3 = page.locator('.cv-pop').last()
+ await popover3.getByRole('button', { name: 'Filter Original' }).click()
+ await expect
+ .poll(async () => {
+ const imgs = await docImages(page, design)
+ return imgs.find((e) => e.id === 'img_d4_main')?.filter
+ }, { timeout: 20_000 })
+ .toBe('none')
+ })
+
+ test('mixed-preset designs export per-element primitives', async ({ page }) => {
+ // shared account (no second registration — the PR #26 discipline)
+ expect(SHARED_ACCOUNT, 'a prior test registered the shared account').not.toBeNull()
+ const login = await page.request.post('/api/auth/login', {
+ data: { username: SHARED_ACCOUNT!.username, password: SHARED_ACCOUNT!.password },
+ })
+ expect(login.status(), 'login as the shared account').toBeLessThan(300)
+
+ const design = await createDesign(page, `cvx_d4_mix_${SHARED_ACCOUNT!.username}`, [
+ imageEl('img_d4_blur', 60, { filter: 'blur', filterIntensity: 90 }),
+ imageEl('img_d4_warm', 360, { filter: 'warm', filterIntensity: 70 }),
+ imageEl('img_d4_vig', 660, { filter: 'vignette', filterIntensity: 60 }),
+ ])
+ await openEditor(page, design)
+
+ await page.getByRole('button', { name: 'Download', exact: true }).click()
+ await page.getByRole('button', { name: /^SVG\b/ }).click()
+ const [download] = await Promise.all([
+ page.waitForEvent('download'),
+ page.getByRole('button', { name: /Download 1 SVG/i }).click(),
+ ])
+ const svg = readFileSync((await download.path())!, 'utf8')
+ expect(svg).toContain('feGaussianBlur') // blur el
+ expect(svg).toContain('feColorMatrix') // warm el
+ expect(svg).toContain('radialGradient') // vignette overlay
+ expect(svg).toContain('stop-opacity') // …with real falloff stops
+ })
+})