@overtone-art/canvas-editor-core 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -354,8 +354,10 @@ var TextWrapManager = class {
354
354
  text.dirty = true;
355
355
  text.setCoords();
356
356
  this.canvas.requestRenderAll();
357
- this.events.emit("layer:modified", { layerId });
358
- if (save) this.history.save();
357
+ if (save) {
358
+ this.events.emit("layer:modified", { layerId });
359
+ this.history.save();
360
+ }
359
361
  return true;
360
362
  }
361
363
  };
@@ -638,4 +640,4 @@ export {
638
640
  exportSVG,
639
641
  exportDataURL
640
642
  };
641
- //# sourceMappingURL=chunk-XNGPX7FG.mjs.map
643
+ //# sourceMappingURL=chunk-TP527WVQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/text-fit.ts","../src/text-wrap-split.ts","../src/masks/space.ts","../src/text-wrap.ts","../src/displacement.ts","../src/export.ts"],"sourcesContent":["import { Point } from 'fabric';\nimport type { FabricObject } from 'fabric';\n\n/**\n * Fitting a text layer's box to the letters inside it.\n *\n * A `Textbox`'s `width` is a **wrap width** somebody authored, not the width of\n * the glyphs, and fabric is explicit that it stays that way: \"Unlike superclass's\n * version of this function, Textbox does not update its width.\" So the box only\n * ever ratchets *up*, and only when a word physically cannot fit — raise a 48px\n * font to 96px inside a 200px box and the selection frame does not move, and\n * dropping the size back leaves the box at whatever width it grew to.\n *\n * Two things need the same measurement: this, and the pattern engine (a tile\n * stepped by the box rather than the run leaves transparent padding between\n * every repeat).\n */\n\n/**\n * Slack left when a box is measured down to its run, so a float rounding error\n * cannot push the widest line into a new wrap on the next layout pass.\n */\nexport const TEXT_FIT_SLACK = 0.5;\n\n/** Box width used to measure a run that is not allowed to wrap. */\nconst MEASURE_WIDTH = 100_000;\n\n/** How far each attempt overshoots while bracketing a width that does not wrap. */\nconst GROWTH_FACTOR = 1.1;\n\n/**\n * Caps on the widening search. A run whose layout never settles has to exit and\n * leave the box a little wide, not spin — this runs on the typing path.\n */\nconst GROWTH_TRIES = 8;\nconst SEARCH_TRIES = 24;\n\n/** The text-shaped surface of an object whose box can be wider than its art. */\nexport interface TextSource extends FabricObject {\n text: string;\n width: number;\n textAlign?: string;\n calcTextWidth?: () => number;\n initDimensions?: () => void;\n /** Lines as laid out. More of them than the author typed means a soft wrap. */\n _textLines?: unknown[];\n /** Set while the run follows a curve, which owns the box instead. */\n path?: FabricObject | null;\n}\n\n/** Width the run wants on one line, measured against a box wide enough not to wrap. */\nfunction unwrappedWidth(text: TextSource): number {\n const authored = text.width;\n try {\n text.set({ width: MEASURE_WIDTH });\n text.initDimensions?.();\n const measured = text.calcTextWidth?.() ?? authored;\n return Number.isFinite(measured) && measured > 0 ? measured : authored;\n } finally {\n text.set({ width: authored });\n text.initDimensions?.();\n }\n}\n\n/** The object as text, or null. Only text carries a box wider than what it paints. */\nexport function asText(object: FabricObject | null | undefined): TextSource | null {\n if (!object) return null;\n const text = object as TextSource;\n return typeof text.text === 'string' && typeof text.calcTextWidth === 'function' ? text : null;\n}\n\n/**\n * What a text object paints inside its box, unscaled: the run's width, and how\n * far the run's centre sits from the box's.\n *\n * `calcTextWidth` reports the widest wrapped line — the run's real footprint —\n * and `textAlign` says where in the box that run sits.\n */\nexport function textInk(text: TextSource): { width: number; dx: number } {\n const boxWidth = Math.max(0, text.width ?? 0);\n const measured = text.calcTextWidth?.() ?? boxWidth;\n const width = Math.max(1, Math.min(boxWidth, Number.isFinite(measured) ? measured : boxWidth));\n const slack = (boxWidth - width) / 2;\n const align = text.textAlign ?? 'left';\n if (align.includes('center')) return { width, dx: 0 };\n const flip = text.flipX ? -1 : 1;\n // Right-aligned text hugs the right edge, so its centre is right of the box's;\n // left and justify both start at the left edge.\n return { width, dx: flip * (align.includes('right') ? slack : -slack) };\n}\n\n/** Lay the run out at `width` and report whether anything soft-wrapped. */\nfunction wrapsAt(text: TextSource, width: number): boolean {\n text.set({ width });\n text.initDimensions?.();\n // Newlines the author typed are lines fabric must produce; anything beyond\n // that count is the box breaking the run on its own.\n const authored = text.text.split('\\n').length;\n return (text._textLines?.length ?? 0) > authored;\n}\n\n/**\n * Narrowest width from `fitted` up that the run does not soft-wrap in, leaving\n * the box laid out at it.\n *\n * `calcTextWidth` reports what a line *renders* at, with its trailing space\n * trimmed, while fabric decides where to wrap with the infix spaces counted —\n * so a box fitted to the rendered width can be a hair too narrow and break the\n * run anyway. The gap grows with the number of spaces and with `charSpacing`,\n * so no constant slack covers it; the width fabric agrees to is searched for\n * instead of guessed.\n */\nfunction widenPastSoftWrap(text: TextSource, fitted: number): number {\n // The common case, and the only pass a single-word run or a box that already\n // holds its text ever pays — this runs on every keystroke.\n if (!wrapsAt(text, fitted)) return fitted;\n\n // Bracket a width that holds the run, then close in on the narrowest one.\n let low = fitted;\n let high = fitted;\n let bracketed = false;\n for (let tries = 0; tries < GROWTH_TRIES; tries += 1) {\n low = high;\n high = high * GROWTH_FACTOR + 1;\n if (!wrapsAt(text, high)) {\n bracketed = true;\n break;\n }\n }\n // Still wrapping at the widest width tried: take it rather than keep going.\n if (!bracketed) return high;\n\n for (let tries = 0; tries < SEARCH_TRIES && high - low > TEXT_FIT_SLACK; tries += 1) {\n const mid = (low + high) / 2;\n if (wrapsAt(text, mid)) low = mid;\n else high = mid;\n }\n // `high` is the bound known to hold the run; `low` is known to break it.\n if (text.width !== high) wrapsAt(text, high);\n return high;\n}\n\n/**\n * Put the box back at `width` after a probe was abandoned partway through.\n *\n * The restore's own failure is dropped rather than thrown: it runs while an\n * exception is already on its way out, and replacing that one with this one\n * would bury the fault that actually broke the layout.\n */\nfunction restoreWidth(text: TextSource, width: number): void {\n try {\n text.set({ width });\n text.initDimensions?.();\n } catch {\n // Nothing better to offer than the width itself, which is set either way.\n }\n}\n\n/**\n * Whether the box is already the narrowest width that holds its run, and so has\n * nothing to search for.\n *\n * Worth asking because {@link widenPastSoftWrap} settles a hair ABOVE the width\n * `calcTextWidth` reports, which is the width the cheap check below compares\n * against — so a settled multi-word box looks perpetually a hair off and would\n * re-run the whole search on every keystroke, deriving the width it already has.\n *\n * Both halves are load-bearing. Holding the run alone would call any box that\n * fits \"settled\", and a box left far too wide by a font-size drop would then\n * never shrink; breaking a slack narrower is what says it is not also too wide.\n *\n * Leaves the box laid out at `width` either way.\n */\nfunction isSettled(text: TextSource, width: number): boolean {\n // Already wrapping: not settled, and `wrapsAt` has left the box at `width`.\n if (wrapsAt(text, width)) return false;\n const tight = wrapsAt(text, width - TEXT_FIT_SLACK);\n wrapsAt(text, width);\n return tight;\n}\n\n/**\n * Fit a text layer's box to the run it holds, leaving the letters where they\n * were on screen.\n *\n * The box becomes **auto-width**: it follows the run in both directions, so\n * raising the font size or opening up the letter spacing widens the frame\n * instead of silently breaking the line, and lowering them again takes the width\n * back — which fabric never does on its own, since `Textbox` only ratchets its\n * width up and only when a word cannot fit at all.\n *\n * Line breaks stay under the author's control through the text itself: the run\n * is measured per hard newline, so `One\\nTwo` stays two lines. What goes away is\n * *soft* wrapping, which in an editor whose text tool opens at a fixed 200px box\n * was mostly accidental anyway.\n *\n * Curved text is skipped — `TextCurveManager` owns that box and sizes it to the\n * glyphs along the path, which this would fight.\n *\n * Returns whether anything changed, so a caller can skip a history checkpoint.\n */\nexport function fitTextWidth(object: FabricObject | null | undefined): boolean {\n const text = asText(object);\n if (!text || text.path) return false;\n\n const authored = text.width;\n try {\n const before = textInk(text);\n const fitted = unwrappedWidth(text) + TEXT_FIT_SLACK;\n // A hair either way is the slack itself, not an edit worth a history step.\n if (Math.abs(fitted - authored) < TEXT_FIT_SLACK) return false;\n\n // Only a box sitting just above the naive fit can be the settled one, since\n // the search never lands past its first bracket step. Screening on that costs\n // no layout at all and skips the probes for a box that is simply the wrong\n // size — including every single-word run, which can never soft-wrap and so\n // could never have come back settled.\n const nearFit = authored > fitted && authored <= fitted * GROWTH_FACTOR + 1;\n if (nearFit && isSettled(text, authored)) return false;\n\n // Keep the run put: shrinking the box moves its centre, and with it every\n // alignment except centre. The ink offset is what that move has to cancel.\n const centre = text.getCenterPoint();\n const settled = widenPastSoftWrap(text, fitted);\n const after = textInk(text);\n const shift = (before.dx - after.dx) * (text.scaleX ?? 1);\n const radians = ((text.angle ?? 0) * Math.PI) / 180;\n const moved = new Point(\n centre.x + shift * Math.cos(radians),\n centre.y + shift * Math.sin(radians),\n );\n text.setPositionByOrigin(moved, 'center', 'center');\n text.setCoords();\n text.dirty = true;\n // Measured against where the box actually settled, not where the first guess\n // put it: widening past a soft wrap can land back on the authored width, and\n // reporting that as a change would checkpoint an edit that never happened.\n return Math.abs(settled - authored) >= TEXT_FIT_SLACK;\n } catch (error) {\n // Every probe above leaves the box at a trial width and undoes it on the\n // next line; a throw in between strands it there — narrower than its run,\n // which is the soft wrap this file exists to keep out. Same discipline as\n // `unwrappedWidth`'s `finally`, applied to the searches it feeds.\n restoreWidth(text, authored);\n throw error;\n }\n}\n","/**\n * Word splitting for `wrap: 'pre-wrap'`.\n *\n * Fabric splits a line on `/[ \\t\\r]/` and rejoins the pieces with a single\n * `' '`, then suppresses that space at a soft break — which is why a wrapped\n * continuation line loses the indentation the author typed. Attaching each\n * run of whitespace to the word that FOLLOWS it moves that whitespace inside a\n * token, where nothing can drop it. One character is held back per token\n * because fabric re-inserts exactly one space between tokens.\n *\n * Pure and fabric-free on purpose: the API mirrors this function against\n * `fabric/node` for the print renderer, and the two are locked together by\n * matching fixture tables in both repos.\n */\nconst WHITESPACE = /[ \\t\\r]/;\n\nexport function preWrapWordSplit(value: string): string[] {\n const tokens: string[] = [];\n let index = 0;\n let first = true;\n\n while (index < value.length) {\n let space = '';\n while (index < value.length && WHITESPACE.test(value[index])) {\n space += value[index];\n index += 1;\n }\n let word = '';\n while (index < value.length && !WHITESPACE.test(value[index])) {\n word += value[index];\n index += 1;\n }\n // Nothing precedes the first token, so it keeps every space it was given.\n tokens.push((first ? space : space.slice(1)) + word);\n first = false;\n }\n\n return tokens.length > 0 ? tokens : [''];\n}\n","import { util } from 'fabric';\nimport type { FabricObject, Group, TMat2D } from 'fabric';\n\n/**\n * Coordinate-space plumbing for mask stacks.\n *\n * A fabric `clipPath` lives in one of two spaces, and the mask stack uses both:\n *\n * - **host space** (`absolutePositioned: false`) — the clip is drawn inside the\n * host object's own transform, so it follows every move, scale and rotation\n * of the layer for free. This is what a *linked* mask wants.\n * - **canvas space** (`absolutePositioned: true`) — the clip ignores the host's\n * transform, so the artwork slides underneath a mask that stays put. This is\n * what an *unlinked* mask wants.\n *\n * A stack composes into a single group, so one unlinked mask forces the whole\n * stack into canvas space; the linked entries are then re-fitted from the host's\n * transform. `toCanvasSpace` / `toHostSpace` are the conversions that migration\n * between the two regimes needs, and they are exact for scale, rotation and skew\n * because they compose matrices rather than copying left/top.\n */\n\nexport function matrixOf(object: FabricObject): TMat2D {\n return object.calcTransformMatrix();\n}\n\n/** Overwrite an object's transform with `matrix`, keeping its own dimensions. */\nexport function applyMatrix(object: FabricObject, matrix: TMat2D): void {\n const decomposed = util.qrDecompose(matrix);\n object.set({\n flipX: false,\n flipY: false,\n originX: 'center',\n originY: 'center',\n left: decomposed.translateX,\n top: decomposed.translateY,\n scaleX: decomposed.scaleX,\n scaleY: decomposed.scaleY,\n angle: decomposed.angle,\n skewX: decomposed.skewX,\n skewY: 0,\n });\n object.setCoords();\n}\n\n/** Host-space geometry → canvas-space, for the same on-screen result. */\nexport function toCanvasSpace(object: FabricObject, host: FabricObject): void {\n applyMatrix(object, util.multiplyTransformMatrices(matrixOf(host), matrixOf(object)));\n}\n\n/** Canvas-space geometry → host-space, for the same on-screen result. */\nexport function toHostSpace(object: FabricObject, host: FabricObject): void {\n applyMatrix(\n object,\n util.multiplyTransformMatrices(util.invertTransform(matrixOf(host)), matrixOf(object)),\n );\n}\n\n/**\n * The mask's transform expressed relative to its host, so a linked mask can be\n * re-derived after the host moves. Stored on the entry, not recomputed from the\n * live objects: by the time the host has moved, the old relationship is gone.\n */\nexport function relativeMatrix(object: FabricObject, host: FabricObject): TMat2D {\n return util.multiplyTransformMatrices(util.invertTransform(matrixOf(host)), matrixOf(object));\n}\n\n/** Re-place a linked mask from the host's current transform and a stored `rel`. */\nexport function applyRelativeMatrix(object: FabricObject, host: FabricObject, rel: TMat2D): void {\n applyMatrix(object, util.multiplyTransformMatrices(matrixOf(host), rel));\n}\n\n/**\n * Fabric types `clipPath` with a looser prop set than the objects the editor\n * builds, so reading a clip back out needs a narrowing step. Every clip this\n * module reads is one it composed from real objects in the first place.\n */\nexport function asObject(clip: NonNullable<FabricObject['clipPath']>): FabricObject {\n return clip as FabricObject;\n}\n\n/** Narrow a persisted `rel` array back to a transform matrix. */\nexport function toMatrix(values: number[] | undefined): TMat2D | null {\n if (!values || values.length !== 6 || values.some((value) => !Number.isFinite(value)))\n return null;\n return [values[0], values[1], values[2], values[3], values[4], values[5]];\n}\n\n/** Scale an object so its unrotated box covers `box`, centred on it. */\nexport function fitToBox(\n object: FabricObject,\n box: { left: number; top: number; width: number; height: number },\n zoom = 1,\n): void {\n const width = Math.max(1, box.width) * zoom;\n const height = Math.max(1, box.height) * zoom;\n object.set({\n originX: 'center',\n originY: 'center',\n angle: 0,\n skewX: 0,\n skewY: 0,\n left: box.left + box.width / 2,\n top: box.top + box.height / 2,\n scaleX: width / Math.max(1, object.width ?? 1),\n scaleY: height / Math.max(1, object.height ?? 1),\n });\n object.setCoords();\n}\n\n/**\n * Pull a composed clip group back apart into standalone objects in the space the\n * group itself was in.\n *\n * `removeAll` already restores each child's own transform on the way out — the\n * group rebases children when it takes them in, and reverses that when it lets\n * them go. Folding the group's matrix back in on top (as one would with a v5-era\n * group) double-counts it, which stays invisible while a mask sits at the origin\n * and moves it twice as far as it should the moment one does not.\n *\n * The group passed in is emptied.\n */\nexport function unwrapGroup(group: Group): FabricObject[] {\n const children = group.removeAll();\n for (const child of children) child.setCoords();\n return children;\n}\n","import { Rect } from 'fabric';\nimport type { Canvas, FabricObject } from 'fabric';\nimport type { Layer, LayerManager } from './layer';\nimport type { HistoryManager } from './history';\nimport type { EventEmitter } from './events';\nimport type { EditorEvents, LayerMeta, TextOverflow, TextWrapMode } from './types';\nimport { asText, fitTextWidth, type TextSource } from './text-fit';\nimport { preWrapWordSplit } from './text-wrap-split';\nimport { asObject, toHostSpace } from './masks/space';\n\n/** Both properties as they apply to a layer, defaults filled in. */\nexport interface TextWrapState {\n wrap: TextWrapMode;\n overflow: TextOverflow;\n}\n\n/** A Textbox, plus the wrapping levers fabric does not put on FabricObject. */\ninterface WrappableText extends TextSource {\n splitByGrapheme?: boolean;\n wordSplit?: (value: string) => string[];\n}\n\n/**\n * Fabric names `wordSplit` as an override point, so pre-wrap is an own-property\n * shadow of the prototype method rather than a patched prototype: two layers on\n * one canvas can be in different modes.\n */\nfunction patchWordSplit(text: WrappableText): void {\n if (Object.prototype.hasOwnProperty.call(text, 'wordSplit')) return;\n Object.defineProperty(text, 'wordSplit', {\n value: preWrapWordSplit,\n configurable: true,\n writable: true,\n });\n}\n\nfunction unpatchWordSplit(text: WrappableText): void {\n if (Object.prototype.hasOwnProperty.call(text, 'wordSplit')) {\n delete text.wordSplit;\n }\n}\n\nexport function readTextWrap(meta: LayerMeta | undefined): TextWrapState {\n return { wrap: meta?.wrap ?? 'none', overflow: meta?.overflow ?? 'visible' };\n}\n\n/** Builds the clip rect. A parameter because a Node renderer's `Rect` (from\n * `fabric/node`) and the browser's `Rect` (from `fabric`) are different\n * classes — a clip built by one does not render on the other's canvas. */\ntype RectFactory = (options: Record<string, unknown>) => FabricObject;\n\n/**\n * The box, as a clip, in the layer's own frame.\n *\n * A top-level clipPath's coordinates are the object's own, centred on it and\n * unaffected by its scale, so this is sized to the unscaled dimensions — the\n * same rule `MaskPresetManager.buildClip` follows. That invariant holds only at\n * the top level: nested under another clip the frame is the parent's, and\n * `derive` converts into it. Height is the text height, which IS the content\n * height for a Textbox, so only the width ever clips anything.\n *\n * A fresh Rect per derive, and derive runs on the typing path — cheap, since\n * `objectCaching: false` means there is no backing canvas to retain. If it ever\n * shows up in a profile, the move is to resize the clip already installed\n * rather than to build a second one.\n */\nfunction boxClip(text: WrappableText, makeRect: RectFactory): FabricObject {\n return makeRect({\n width: Math.max(1, text.width ?? 1),\n height: Math.max(1, text.height ?? 1),\n originX: 'center',\n originY: 'center',\n left: 0,\n top: 0,\n objectCaching: false,\n });\n}\n\n/**\n * Does a mask already own this layer's clipPath? Read from meta, not the object.\n *\n * Deliberately blind to `PatternManager`, which strips a layer's clip for the\n * duration of a pattern: meta still says \"masked\" while the object carries no\n * clip at all, so the box clip becomes a no-op until the pattern is removed.\n * That is the safe way round — no clip beats taking a slot the pattern is using\n * — so do not \"fix\" this by asking the object what it currently holds.\n */\nfunction hasMask(meta: LayerMeta): boolean {\n return !!meta.maskPreset || (meta.maskStack?.length ?? 0) > 0;\n}\n\n/**\n * The renderer-agnostic half of {@link TextWrapManager.derive}: the fabric\n * state a wrap mode implies once the box's width is already settled.\n *\n * Deliberately does NOT touch width — re-fitting here would let a Node\n * renderer, which sees only the serialized state and never `meta.wrapWidth`,\n * shift a box the browser already fitted at authoring time. Width is the\n * manager's job (`fitTextWidth` for `'none'`, `meta.wrapWidth` restore for\n * everything else); this only sets the levers fabric does not serialize on\n * its own (`wordSplit`) or that depend on the box the manager just settled\n * (the clip). Call it AFTER any width decision, never before — the clip below\n * is sized to `text.width`/`text.height` as they stand when this runs.\n */\nexport function applyTextWrapToObject(\n object: FabricObject,\n meta: LayerMeta | undefined,\n makeRect: RectFactory = (options) => new Rect(options),\n): void {\n const text = asText(object) as WrappableText | null;\n if (!text) return;\n\n const state = readTextWrap(meta);\n\n // A curved run follows a path built for the box the curve manager sized;\n // re-deriving here would fight it. The mode stays stored and applies again\n // when the curve is cleared.\n if (!text.path) {\n text.set({ splitByGrapheme: state.wrap === 'break-all' });\n if (state.wrap === 'pre-wrap') patchWordSplit(text);\n else unpatchWordSplit(text);\n // `splitByGrapheme` is not one of fabric's `textLayoutProperties`, so the\n // `set` above did not re-lay the run out on its own, and neither does\n // patching `wordSplit` (an own-property override, not a tracked prop) —\n // a layer already at its current width, with no width change to trigger\n // fabric's own relayout, would otherwise keep lines laid out under the\n // PREVIOUS split function.\n text.initDimensions?.();\n }\n\n // Installed even on curved text: a curve owns the box, not the clip.\n const clip = state.overflow === 'hidden' ? boxClip(text, makeRect) : undefined;\n if (meta && hasMask(meta)) {\n const host = text.clipPath;\n if (host) {\n // A nested clip is drawn in its PARENT clip's frame, not the layer's:\n // fabric replays every entry in `parentClipPaths` before applying the\n // child's own transform (`Object.createClipPathLayer`). The mask group\n // lays itself out around its geometry, so that frame coincides with the\n // layer's only for a centred mask — which is why presets and default-fit\n // masks look right. Left unconverted, the box clip is displaced by the\n // whole of the mask's transform: an offset mask that covers the run\n // completely starts cutting it, and an unlinked one (composed in canvas\n // space, so the offset is the layer's full distance from the origin)\n // carries the clip clear of the text, which disappears outright.\n //\n // Re-expressing it relative to the mask is the same conversion a linked\n // mask needs when it joins a canvas-space stack, so it uses the same\n // helper rather than new matrix maths. `asObject` is the narrowing step\n // that module already carries for fabric's looser `clipPath` typing.\n if (clip) toHostSpace(clip, asObject(host));\n host.clipPath = clip;\n }\n } else {\n text.clipPath = clip;\n }\n}\n\n/**\n * How a text layer breaks its lines, and whether it paints past its box.\n *\n * `meta` is the authoring record; what actually renders — and what a print\n * pipeline that never reads `meta` sees — is the fabric state derived here:\n * `width`, `splitByGrapheme` and `clipPath`, all of which fabric serializes on\n * its own. That is the same division `TextCurveManager` draws between\n * `meta.curve` and the `path` it installs.\n */\nexport class TextWrapManager {\n /**\n * Typing changes the run the box was fitted to, so an auto-width layer has to\n * re-fit. No history entry: fabric records the edit when editing exits, and a\n * save per keystroke would bury every earlier step.\n */\n private readonly onTextChanged = (event: { target?: FabricObject }) => {\n const layer = event.target ? this.layers.findByObject(event.target) : undefined;\n if (!layer) return;\n this.refresh(layer.id, false);\n };\n\n /**\n * Both mask owners — the preset manager and every mask-stack mutation —\n * install their clip straight onto `clipPath`, dropping whatever was there,\n * and neither knows this layer had a box clip. Re-deriving on the one event\n * they both announce puts it back where it now belongs: nested under the new\n * mask, or at the top level when the last mask leaves. Waiting for the next\n * keystroke instead would leave a layer that should clip inside its box\n * serialized unclipped — which is what the print renderer reads.\n */\n private readonly onMasksChanged = ({ target }: { target: string }) => {\n // `refresh` ignores an id that is not a text layer, so the whole-design\n // mask target passes through it harmlessly.\n this.refresh(target);\n };\n\n constructor(\n private canvas: Canvas,\n private layers: LayerManager,\n private history: HistoryManager,\n private events: EventEmitter<EditorEvents>,\n ) {\n this.canvas.on('text:changed', this.onTextChanged);\n this.events.on('masks:changed', this.onMasksChanged);\n }\n\n dispose(): void {\n this.canvas.off('text:changed', this.onTextChanged);\n this.events.off('masks:changed', this.onMasksChanged);\n }\n\n /** Both properties for a text layer, or null when it is not text. */\n get(layerId: string): TextWrapState | null {\n const layer = this.layers.get(layerId);\n if (!layer || !asText(layer.fabricObject)) return null;\n return readTextWrap(layer.meta);\n }\n\n apply(layerId: string, wrap: TextWrapMode, save = true): boolean {\n const layer = this.layers.get(layerId);\n const text = layer ? asText(layer.fabricObject) : null;\n if (!layer || !text) return false;\n if (wrap === 'none') {\n // Parked before anything widens the box, so the authored width is the one\n // that comes back — and only on the way IN, or a second call would park\n // the fitted width over it.\n //\n // Never from a curved box: `TextCurveManager` widened that one to fit the\n // path and is holding the real authored width in `meta.curveWidth`. Park\n // here and uncurving later would restore the curve's width as if the\n // author had chosen it.\n const curved = !!text.path;\n if (layer.meta.wrapWidth === undefined && !curved) {\n layer.meta.wrapWidth = text.width ?? 0;\n }\n }\n layer.meta.wrap = wrap;\n return this.derive(layerId, save);\n }\n\n setOverflow(layerId: string, overflow: TextOverflow, save = true): boolean {\n const layer = this.layers.get(layerId);\n if (!layer || !asText(layer.fabricObject)) return false;\n layer.meta.overflow = overflow;\n return this.derive(layerId, save);\n }\n\n /** Back to the defaults: auto-width, unclipped. */\n clear(layerId: string, save = true): boolean {\n const layer = this.layers.get(layerId);\n if (!layer || !asText(layer.fabricObject)) return false;\n delete layer.meta.overflow;\n return this.apply(layerId, 'none', save);\n }\n\n /** Re-derive from the stored mode — after a text, font or size change. */\n refresh(layerId: string, save = false): boolean {\n const layer = this.layers.get(layerId);\n if (!layer || !asText(layer.fabricObject)) return false;\n return this.derive(layerId, save);\n }\n\n /**\n * Re-derive every text layer — used after a state restore.\n *\n * Recursive because a template inserts as a group of real child layers, and\n * text inside one would otherwise keep whatever box it was restored with.\n */\n refreshAll(): void {\n const visit = (layers: Layer[]): void => {\n for (const layer of layers) {\n if (asText(layer.fabricObject)) this.refresh(layer.id);\n if (layer.children.length > 0) visit(layer.children);\n }\n };\n visit(this.layers.getAll());\n }\n\n private derive(layerId: string, save: boolean): boolean {\n const layer = this.layers.get(layerId);\n const text = layer ? (asText(layer.fabricObject) as WrappableText | null) : null;\n if (!layer || !text) return false;\n\n const state = readTextWrap(layer.meta);\n\n // A curved run follows a path built for the box the curve manager sized;\n // re-deriving here would fight it. The mode stays stored and applies again\n // when the curve is cleared. This is the layer-dependent half of the mode:\n // `meta.wrapWidth` is a layer authoring record with no fabric equivalent,\n // and re-fitting is never something a renderer that only sees the already-\n // fitted serialized width should redo — both stay here rather than moving\n // into `applyTextWrapToObject`.\n if (!text.path) {\n if (state.wrap === 'none') {\n fitTextWidth(text);\n } else if (layer.meta.wrapWidth !== undefined) {\n text.set({ width: layer.meta.wrapWidth });\n delete layer.meta.wrapWidth;\n }\n }\n\n // The rest — split mode and the overflow clip — is object-only and shared\n // with the Node renderer, which derives it from the very same `meta` on a\n // freshly restored object with no editor around it. Called after the width\n // decision above so the clip is sized to the box that decision just chose.\n applyTextWrapToObject(text, layer.meta);\n\n text.dirty = true;\n text.setCoords();\n this.canvas.requestRenderAll();\n this.events.emit('layer:modified', { layerId });\n if (save) this.history.save();\n return true;\n }\n}\n","import type { MockupDisplacement, MockupDisplacementChannel } from './types';\n\nconst CHANNEL_INDEX: Record<MockupDisplacementChannel, number> = {\n red: 0,\n green: 1,\n blue: 2,\n alpha: 3,\n};\n\nfunction finiteScale(value: number | undefined, fallback: number, label: string): number {\n const resolved = value ?? fallback;\n if (!Number.isFinite(resolved)) throw new Error(`${label} must be finite`);\n return resolved;\n}\n\nfunction sample(\n source: Uint8ClampedArray,\n width: number,\n height: number,\n x: number,\n y: number,\n channel: number,\n): number {\n const clampedX = Math.max(0, Math.min(width - 1, x));\n const clampedY = Math.max(0, Math.min(height - 1, y));\n const x0 = Math.floor(clampedX);\n const y0 = Math.floor(clampedY);\n const x1 = Math.min(width - 1, x0 + 1);\n const y1 = Math.min(height - 1, y0 + 1);\n const tx = clampedX - x0;\n const ty = clampedY - y0;\n const top =\n source[(y0 * width + x0) * 4 + channel] * (1 - tx) +\n source[(y0 * width + x1) * 4 + channel] * tx;\n const bottom =\n source[(y1 * width + x0) * 4 + channel] * (1 - tx) +\n source[(y1 * width + x1) * 4 + channel] * tx;\n return top * (1 - ty) + bottom * ty;\n}\n\n/**\n * Warp RGBA pixels with an equally sized channel map. A channel value of 128\n * is neutral; 0 and 255 move by the configured negative/positive maximum.\n */\nexport function displaceRgba(\n source: Uint8ClampedArray,\n map: Uint8ClampedArray,\n width: number,\n height: number,\n options: Omit<MockupDisplacement, 'image'>,\n): Uint8ClampedArray {\n if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) {\n throw new Error('Displacement dimensions must be positive integers');\n }\n const expectedLength = width * height * 4;\n if (source.length !== expectedLength || map.length !== expectedLength) {\n throw new Error('Displacement source and map must match the requested dimensions');\n }\n\n const scaleX = finiteScale(options.scaleX, 10, 'Displacement scaleX');\n const scaleY = finiteScale(options.scaleY, 10, 'Displacement scaleY');\n const channelX = CHANNEL_INDEX[options.channelX ?? 'red'];\n const channelY = CHANNEL_INDEX[options.channelY ?? 'green'];\n const output = new Uint8ClampedArray(expectedLength);\n\n for (let y = 0; y < height; y += 1) {\n for (let x = 0; x < width; x += 1) {\n const offset = (y * width + x) * 4;\n const sourceX = x + ((map[offset + channelX] - 128) / 127) * scaleX;\n const sourceY = y + ((map[offset + channelY] - 128) / 127) * scaleY;\n for (let channel = 0; channel < 4; channel += 1) {\n output[offset + channel] = Math.round(\n sample(source, width, height, sourceX, sourceY, channel),\n );\n }\n }\n }\n return output;\n}\n","import { StaticCanvas } from 'fabric';\nimport type { Canvas, FabricObject, ImageFormat } from 'fabric';\nimport type { MockupConfig, MockupPrintArea } from './types';\nimport { displaceRgba } from './displacement';\n\nexport interface PngExportOptions {\n multiplier?: number;\n format?: ImageFormat;\n quality?: number;\n}\n\nexport interface CoverPlacement {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\nexport function computePrintAreaClip(\n area: MockupPrintArea,\n scaleX: number,\n scaleY: number,\n targetWidth: number,\n targetHeight: number,\n): MockupPrintArea {\n const left = Math.max(0, Math.min(targetWidth, area.left * scaleX));\n const top = Math.max(0, Math.min(targetHeight, area.top * scaleY));\n const right = Math.max(left, Math.min(targetWidth, (area.left + area.width) * scaleX));\n const bottom = Math.max(top, Math.min(targetHeight, (area.top + area.height) * scaleY));\n return { left, top, width: right - left, height: bottom - top };\n}\n\n/** Object-fit: cover geometry, exported for deterministic preview/composite tests. */\nexport function computeCoverPlacement(\n sourceWidth: number,\n sourceHeight: number,\n targetWidth: number,\n targetHeight: number,\n): CoverPlacement {\n if (sourceWidth <= 0 || sourceHeight <= 0 || targetWidth <= 0 || targetHeight <= 0) {\n throw new Error('Cover dimensions must be positive');\n }\n const scale = Math.max(targetWidth / sourceWidth, targetHeight / sourceHeight);\n const width = sourceWidth * scale;\n const height = sourceHeight * scale;\n return {\n left: (targetWidth - width) / 2,\n top: (targetHeight - height) / 2,\n width,\n height,\n };\n}\n\nfunction canvasElementToBlob(\n output: HTMLCanvasElement,\n format: ImageFormat,\n quality: number,\n): Promise<Blob> {\n const mime = format === 'jpeg' ? 'image/jpeg' : `image/${format}`;\n return new Promise<Blob>((resolve, reject) => {\n output.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error(`Failed to export ${format}`))),\n mime,\n quality,\n );\n });\n}\n\nexport async function exportPNG(canvas: Canvas, options: PngExportOptions = {}): Promise<Blob> {\n const { multiplier = 1, format = 'png' as ImageFormat, quality = 1 } = options;\n const output = canvas.toCanvasElement(multiplier);\n return canvasElementToBlob(output, format, quality);\n}\n\n/** Render cloned objects without mutating the live editor canvas. */\nexport async function exportIsolatedPNG(\n source: Canvas,\n objects: FabricObject[],\n options: PngExportOptions & {\n width?: number;\n height?: number;\n backgroundColor?: string;\n backgroundImage?: FabricObject | null;\n cloneObjects?: boolean;\n } = {},\n): Promise<Blob> {\n const element = source.lowerCanvasEl.ownerDocument.createElement('canvas');\n const canvas = new StaticCanvas(element, {\n width: options.width ?? source.getWidth(),\n height: options.height ?? source.getHeight(),\n backgroundColor: options.backgroundColor || undefined,\n });\n try {\n const clones =\n options.cloneObjects === false\n ? objects\n : await Promise.all(objects.map((object) => object.clone()));\n if (clones.length) canvas.add(...clones);\n if (options.backgroundImage) canvas.backgroundImage = await options.backgroundImage.clone();\n canvas.requestRenderAll();\n // Awaited, not returned: `finally` would otherwise dispose the canvas while\n // the export is still reading from it.\n return await exportPNG(canvas as unknown as Canvas, options);\n } finally {\n canvas.dispose();\n }\n}\n\n/**\n * Render just the print-area rectangle, on transparency.\n *\n * This is the file a print provider receives: the design alone, cropped to the\n * printable rectangle, with no garment behind it and no canvas background baked\n * in — so it is rendered from cloned objects rather than off the live canvas.\n */\nexport async function exportPrintArea(\n source: Canvas,\n area: MockupPrintArea,\n options: PngExportOptions = {},\n): Promise<Blob> {\n const { multiplier = 1, format = 'png' as ImageFormat, quality = 1 } = options;\n const width = source.getWidth();\n const height = source.getHeight();\n const clip = computePrintAreaClip(\n area,\n multiplier,\n multiplier,\n width * multiplier,\n height * multiplier,\n );\n if (clip.width <= 0 || clip.height <= 0) {\n throw new Error('Print area does not overlap the canvas');\n }\n\n const element = source.lowerCanvasEl.ownerDocument.createElement('canvas');\n const canvas = new StaticCanvas(element, { width, height });\n try {\n const clones = await Promise.all(source.getObjects().map((object) => object.clone()));\n if (clones.length) canvas.add(...clones);\n canvas.requestRenderAll();\n const rendered = canvas.toCanvasElement(multiplier);\n const output = rendered.ownerDocument.createElement('canvas');\n output.width = Math.max(1, Math.round(clip.width));\n output.height = Math.max(1, Math.round(clip.height));\n const context = output.getContext('2d');\n if (!context) throw new Error('2D canvas context is unavailable');\n context.drawImage(rendered, -clip.left, -clip.top);\n // Awaited, not returned: `finally` would dispose the canvas mid-read.\n return await canvasElementToBlob(output, format, quality);\n } finally {\n canvas.dispose();\n }\n}\n\n/** Rasterize the browser mockup preview together with the transparent design. */\nexport async function exportMockup(\n canvas: Canvas,\n mockup: MockupConfig,\n options: PngExportOptions = {},\n): Promise<Blob> {\n const { multiplier = 1, format = 'png' as ImageFormat, quality = 1 } = options;\n const design = canvas.toCanvasElement(multiplier);\n const output = design.ownerDocument.createElement('canvas');\n output.width = design.width;\n output.height = design.height;\n const context = output.getContext('2d');\n if (!context) throw new Error('2D canvas context is unavailable');\n\n const loadImage = (url: string) =>\n new Promise<HTMLImageElement>((resolve, reject) => {\n const element = new Image();\n element.crossOrigin = 'anonymous';\n element.onload = () => resolve(element);\n element.onerror = () => reject(new Error(`Failed to load mockup image: ${url}`));\n element.src = url;\n });\n const drawCover = (\n image: HTMLImageElement,\n targetContext: CanvasRenderingContext2D = context,\n ) => {\n const placement = computeCoverPlacement(\n image.naturalWidth || image.width,\n image.naturalHeight || image.height,\n output.width,\n output.height,\n );\n targetContext.drawImage(\n image,\n placement.left,\n placement.top,\n placement.width,\n placement.height,\n );\n };\n\n // Full-size scratch buffers, released explicitly in the finally below: a\n // detached canvas element can hold its backing store well past its last\n // reference, and a 4K mockup allocates three of them per export.\n const scratch: HTMLCanvasElement[] = [design];\n try {\n drawCover(await loadImage(mockup.image));\n let compositedDesign: CanvasImageSource = design;\n if (mockup.displacement) {\n const sourceContext = design.getContext('2d');\n if (!sourceContext) throw new Error('2D design context is unavailable');\n const mapCanvas = design.ownerDocument.createElement('canvas');\n scratch.push(mapCanvas);\n mapCanvas.width = design.width;\n mapCanvas.height = design.height;\n const mapContext = mapCanvas.getContext('2d');\n if (!mapContext) throw new Error('2D displacement-map context is unavailable');\n drawCover(await loadImage(mockup.displacement.image), mapContext);\n\n const warped = design.ownerDocument.createElement('canvas');\n scratch.push(warped);\n warped.width = design.width;\n warped.height = design.height;\n const warpedContext = warped.getContext('2d');\n if (!warpedContext) throw new Error('2D displaced-design context is unavailable');\n let sourcePixels: Uint8ClampedArray;\n let mapPixels: Uint8ClampedArray;\n try {\n sourcePixels = sourceContext.getImageData(0, 0, design.width, design.height).data;\n mapPixels = mapContext.getImageData(0, 0, design.width, design.height).data;\n } catch (error) {\n throw new Error('Failed to apply mockup displacement map; verify image CORS access', {\n cause: error,\n });\n }\n const pixels = displaceRgba(sourcePixels, mapPixels, design.width, design.height, {\n ...mockup.displacement,\n scaleX: (mockup.displacement.scaleX ?? 10) * multiplier,\n scaleY: (mockup.displacement.scaleY ?? 10) * multiplier,\n });\n const imageData = warpedContext.createImageData(design.width, design.height);\n imageData.data.set(pixels);\n warpedContext.putImageData(imageData, 0, 0);\n compositedDesign = warped;\n }\n context.save();\n if (mockup.printArea && mockup.clipToPrintArea !== false) {\n const clip = computePrintAreaClip(\n mockup.printArea,\n output.width / canvas.getWidth(),\n output.height / canvas.getHeight(),\n output.width,\n output.height,\n );\n context.beginPath();\n context.rect(clip.left, clip.top, clip.width, clip.height);\n context.clip();\n }\n context.globalAlpha = Math.max(0, Math.min(1, mockup.designOpacity ?? 1));\n context.globalCompositeOperation =\n !mockup.designBlendMode || mockup.designBlendMode === 'normal'\n ? 'source-over'\n : mockup.designBlendMode;\n context.drawImage(compositedDesign, 0, 0);\n context.restore();\n\n if (mockup.overlay) {\n context.save();\n context.globalAlpha = Math.max(0, Math.min(1, mockup.overlay.opacity ?? 1));\n context.globalCompositeOperation =\n mockup.overlay.blendMode === 'normal'\n ? 'source-over'\n : (mockup.overlay.blendMode ?? 'multiply');\n drawCover(await loadImage(mockup.overlay.image));\n context.restore();\n }\n return await canvasElementToBlob(output, format, quality);\n } finally {\n for (const element of scratch) {\n element.width = 0;\n element.height = 0;\n }\n }\n}\n\nexport function exportSVG(canvas: Canvas): string {\n return canvas.toSVG();\n}\n\nexport function exportDataURL(canvas: Canvas, format: ImageFormat = 'png', multiplier = 1): string {\n return canvas.toDataURL({ format, multiplier });\n}\n"],"mappings":";AAAA,SAAS,aAAa;AAsBf,IAAM,iBAAiB;AAG9B,IAAM,gBAAgB;AAGtB,IAAM,gBAAgB;AAMtB,IAAM,eAAe;AACrB,IAAM,eAAe;AAgBrB,SAAS,eAAe,MAA0B;AAChD,QAAM,WAAW,KAAK;AACtB,MAAI;AACF,SAAK,IAAI,EAAE,OAAO,cAAc,CAAC;AACjC,SAAK,iBAAiB;AACtB,UAAM,WAAW,KAAK,gBAAgB,KAAK;AAC3C,WAAO,OAAO,SAAS,QAAQ,KAAK,WAAW,IAAI,WAAW;AAAA,EAChE,UAAE;AACA,SAAK,IAAI,EAAE,OAAO,SAAS,CAAC;AAC5B,SAAK,iBAAiB;AAAA,EACxB;AACF;AAGO,SAAS,OAAO,QAA4D;AACjF,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,OAAO;AACb,SAAO,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,kBAAkB,aAAa,OAAO;AAC5F;AASO,SAAS,QAAQ,MAAiD;AACvE,QAAM,WAAW,KAAK,IAAI,GAAG,KAAK,SAAS,CAAC;AAC5C,QAAM,WAAW,KAAK,gBAAgB,KAAK;AAC3C,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,UAAU,OAAO,SAAS,QAAQ,IAAI,WAAW,QAAQ,CAAC;AAC7F,QAAM,SAAS,WAAW,SAAS;AACnC,QAAM,QAAQ,KAAK,aAAa;AAChC,MAAI,MAAM,SAAS,QAAQ,EAAG,QAAO,EAAE,OAAO,IAAI,EAAE;AACpD,QAAM,OAAO,KAAK,QAAQ,KAAK;AAG/B,SAAO,EAAE,OAAO,IAAI,QAA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/export.ts"],"sourcesContent":["import { Point } from 'fabric';\nimport type { FabricObject } from 'fabric';\n\n/**\n * Fitting a text layer's box to the letters inside it.\n *\n * A `Textbox`'s `width` is a **wrap width** somebody authored, not the width of\n * the glyphs, and fabric is explicit that it stays that way: \"Unlike superclass's\n * version of this function, Textbox does not update its width.\" So the box only\n * ever ratchets *up*, and only when a word physically cannot fit — raise a 48px\n * font to 96px inside a 200px box and the selection frame does not move, and\n * dropping the size back leaves the box at whatever width it grew to.\n *\n * Two things need the same measurement: this, and the pattern engine (a tile\n * stepped by the box rather than the run leaves transparent padding between\n * every repeat).\n */\n\n/**\n * Slack left when a box is measured down to its run, so a float rounding error\n * cannot push the widest line into a new wrap on the next layout pass.\n */\nexport const TEXT_FIT_SLACK = 0.5;\n\n/** Box width used to measure a run that is not allowed to wrap. */\nconst MEASURE_WIDTH = 100_000;\n\n/** How far each attempt overshoots while bracketing a width that does not wrap. */\nconst GROWTH_FACTOR = 1.1;\n\n/**\n * Caps on the widening search. A run whose layout never settles has to exit and\n * leave the box a little wide, not spin — this runs on the typing path.\n */\nconst GROWTH_TRIES = 8;\nconst SEARCH_TRIES = 24;\n\n/** The text-shaped surface of an object whose box can be wider than its art. */\nexport interface TextSource extends FabricObject {\n text: string;\n width: number;\n textAlign?: string;\n calcTextWidth?: () => number;\n initDimensions?: () => void;\n /** Lines as laid out. More of them than the author typed means a soft wrap. */\n _textLines?: unknown[];\n /** Set while the run follows a curve, which owns the box instead. */\n path?: FabricObject | null;\n}\n\n/** Width the run wants on one line, measured against a box wide enough not to wrap. */\nfunction unwrappedWidth(text: TextSource): number {\n const authored = text.width;\n try {\n text.set({ width: MEASURE_WIDTH });\n text.initDimensions?.();\n const measured = text.calcTextWidth?.() ?? authored;\n return Number.isFinite(measured) && measured > 0 ? measured : authored;\n } finally {\n text.set({ width: authored });\n text.initDimensions?.();\n }\n}\n\n/** The object as text, or null. Only text carries a box wider than what it paints. */\nexport function asText(object: FabricObject | null | undefined): TextSource | null {\n if (!object) return null;\n const text = object as TextSource;\n return typeof text.text === 'string' && typeof text.calcTextWidth === 'function' ? text : null;\n}\n\n/**\n * What a text object paints inside its box, unscaled: the run's width, and how\n * far the run's centre sits from the box's.\n *\n * `calcTextWidth` reports the widest wrapped line — the run's real footprint —\n * and `textAlign` says where in the box that run sits.\n */\nexport function textInk(text: TextSource): { width: number; dx: number } {\n const boxWidth = Math.max(0, text.width ?? 0);\n const measured = text.calcTextWidth?.() ?? boxWidth;\n const width = Math.max(1, Math.min(boxWidth, Number.isFinite(measured) ? measured : boxWidth));\n const slack = (boxWidth - width) / 2;\n const align = text.textAlign ?? 'left';\n if (align.includes('center')) return { width, dx: 0 };\n const flip = text.flipX ? -1 : 1;\n // Right-aligned text hugs the right edge, so its centre is right of the box's;\n // left and justify both start at the left edge.\n return { width, dx: flip * (align.includes('right') ? slack : -slack) };\n}\n\n/** Lay the run out at `width` and report whether anything soft-wrapped. */\nfunction wrapsAt(text: TextSource, width: number): boolean {\n text.set({ width });\n text.initDimensions?.();\n // Newlines the author typed are lines fabric must produce; anything beyond\n // that count is the box breaking the run on its own.\n const authored = text.text.split('\\n').length;\n return (text._textLines?.length ?? 0) > authored;\n}\n\n/**\n * Narrowest width from `fitted` up that the run does not soft-wrap in, leaving\n * the box laid out at it.\n *\n * `calcTextWidth` reports what a line *renders* at, with its trailing space\n * trimmed, while fabric decides where to wrap with the infix spaces counted —\n * so a box fitted to the rendered width can be a hair too narrow and break the\n * run anyway. The gap grows with the number of spaces and with `charSpacing`,\n * so no constant slack covers it; the width fabric agrees to is searched for\n * instead of guessed.\n */\nfunction widenPastSoftWrap(text: TextSource, fitted: number): number {\n // The common case, and the only pass a single-word run or a box that already\n // holds its text ever pays — this runs on every keystroke.\n if (!wrapsAt(text, fitted)) return fitted;\n\n // Bracket a width that holds the run, then close in on the narrowest one.\n let low = fitted;\n let high = fitted;\n let bracketed = false;\n for (let tries = 0; tries < GROWTH_TRIES; tries += 1) {\n low = high;\n high = high * GROWTH_FACTOR + 1;\n if (!wrapsAt(text, high)) {\n bracketed = true;\n break;\n }\n }\n // Still wrapping at the widest width tried: take it rather than keep going.\n if (!bracketed) return high;\n\n for (let tries = 0; tries < SEARCH_TRIES && high - low > TEXT_FIT_SLACK; tries += 1) {\n const mid = (low + high) / 2;\n if (wrapsAt(text, mid)) low = mid;\n else high = mid;\n }\n // `high` is the bound known to hold the run; `low` is known to break it.\n if (text.width !== high) wrapsAt(text, high);\n return high;\n}\n\n/**\n * Put the box back at `width` after a probe was abandoned partway through.\n *\n * The restore's own failure is dropped rather than thrown: it runs while an\n * exception is already on its way out, and replacing that one with this one\n * would bury the fault that actually broke the layout.\n */\nfunction restoreWidth(text: TextSource, width: number): void {\n try {\n text.set({ width });\n text.initDimensions?.();\n } catch {\n // Nothing better to offer than the width itself, which is set either way.\n }\n}\n\n/**\n * Whether the box is already the narrowest width that holds its run, and so has\n * nothing to search for.\n *\n * Worth asking because {@link widenPastSoftWrap} settles a hair ABOVE the width\n * `calcTextWidth` reports, which is the width the cheap check below compares\n * against — so a settled multi-word box looks perpetually a hair off and would\n * re-run the whole search on every keystroke, deriving the width it already has.\n *\n * Both halves are load-bearing. Holding the run alone would call any box that\n * fits \"settled\", and a box left far too wide by a font-size drop would then\n * never shrink; breaking a slack narrower is what says it is not also too wide.\n *\n * Leaves the box laid out at `width` either way.\n */\nfunction isSettled(text: TextSource, width: number): boolean {\n // Already wrapping: not settled, and `wrapsAt` has left the box at `width`.\n if (wrapsAt(text, width)) return false;\n const tight = wrapsAt(text, width - TEXT_FIT_SLACK);\n wrapsAt(text, width);\n return tight;\n}\n\n/**\n * Fit a text layer's box to the run it holds, leaving the letters where they\n * were on screen.\n *\n * The box becomes **auto-width**: it follows the run in both directions, so\n * raising the font size or opening up the letter spacing widens the frame\n * instead of silently breaking the line, and lowering them again takes the width\n * back — which fabric never does on its own, since `Textbox` only ratchets its\n * width up and only when a word cannot fit at all.\n *\n * Line breaks stay under the author's control through the text itself: the run\n * is measured per hard newline, so `One\\nTwo` stays two lines. What goes away is\n * *soft* wrapping, which in an editor whose text tool opens at a fixed 200px box\n * was mostly accidental anyway.\n *\n * Curved text is skipped — `TextCurveManager` owns that box and sizes it to the\n * glyphs along the path, which this would fight.\n *\n * Returns whether anything changed, so a caller can skip a history checkpoint.\n */\nexport function fitTextWidth(object: FabricObject | null | undefined): boolean {\n const text = asText(object);\n if (!text || text.path) return false;\n\n const authored = text.width;\n try {\n const before = textInk(text);\n const fitted = unwrappedWidth(text) + TEXT_FIT_SLACK;\n // A hair either way is the slack itself, not an edit worth a history step.\n if (Math.abs(fitted - authored) < TEXT_FIT_SLACK) return false;\n\n // Only a box sitting just above the naive fit can be the settled one, since\n // the search never lands past its first bracket step. Screening on that costs\n // no layout at all and skips the probes for a box that is simply the wrong\n // size — including every single-word run, which can never soft-wrap and so\n // could never have come back settled.\n const nearFit = authored > fitted && authored <= fitted * GROWTH_FACTOR + 1;\n if (nearFit && isSettled(text, authored)) return false;\n\n // Keep the run put: shrinking the box moves its centre, and with it every\n // alignment except centre. The ink offset is what that move has to cancel.\n const centre = text.getCenterPoint();\n const settled = widenPastSoftWrap(text, fitted);\n const after = textInk(text);\n const shift = (before.dx - after.dx) * (text.scaleX ?? 1);\n const radians = ((text.angle ?? 0) * Math.PI) / 180;\n const moved = new Point(\n centre.x + shift * Math.cos(radians),\n centre.y + shift * Math.sin(radians),\n );\n text.setPositionByOrigin(moved, 'center', 'center');\n text.setCoords();\n text.dirty = true;\n // Measured against where the box actually settled, not where the first guess\n // put it: widening past a soft wrap can land back on the authored width, and\n // reporting that as a change would checkpoint an edit that never happened.\n return Math.abs(settled - authored) >= TEXT_FIT_SLACK;\n } catch (error) {\n // Every probe above leaves the box at a trial width and undoes it on the\n // next line; a throw in between strands it there — narrower than its run,\n // which is the soft wrap this file exists to keep out. Same discipline as\n // `unwrappedWidth`'s `finally`, applied to the searches it feeds.\n restoreWidth(text, authored);\n throw error;\n }\n}\n","/**\n * Word splitting for `wrap: 'pre-wrap'`.\n *\n * Fabric splits a line on `/[ \\t\\r]/` and rejoins the pieces with a single\n * `' '`, then suppresses that space at a soft break — which is why a wrapped\n * continuation line loses the indentation the author typed. Attaching each\n * run of whitespace to the word that FOLLOWS it moves that whitespace inside a\n * token, where nothing can drop it. One character is held back per token\n * because fabric re-inserts exactly one space between tokens.\n *\n * Pure and fabric-free on purpose: the API mirrors this function against\n * `fabric/node` for the print renderer, and the two are locked together by\n * matching fixture tables in both repos.\n */\nconst WHITESPACE = /[ \\t\\r]/;\n\nexport function preWrapWordSplit(value: string): string[] {\n const tokens: string[] = [];\n let index = 0;\n let first = true;\n\n while (index < value.length) {\n let space = '';\n while (index < value.length && WHITESPACE.test(value[index])) {\n space += value[index];\n index += 1;\n }\n let word = '';\n while (index < value.length && !WHITESPACE.test(value[index])) {\n word += value[index];\n index += 1;\n }\n // Nothing precedes the first token, so it keeps every space it was given.\n tokens.push((first ? space : space.slice(1)) + word);\n first = false;\n }\n\n return tokens.length > 0 ? tokens : [''];\n}\n","import { util } from 'fabric';\nimport type { FabricObject, Group, TMat2D } from 'fabric';\n\n/**\n * Coordinate-space plumbing for mask stacks.\n *\n * A fabric `clipPath` lives in one of two spaces, and the mask stack uses both:\n *\n * - **host space** (`absolutePositioned: false`) — the clip is drawn inside the\n * host object's own transform, so it follows every move, scale and rotation\n * of the layer for free. This is what a *linked* mask wants.\n * - **canvas space** (`absolutePositioned: true`) — the clip ignores the host's\n * transform, so the artwork slides underneath a mask that stays put. This is\n * what an *unlinked* mask wants.\n *\n * A stack composes into a single group, so one unlinked mask forces the whole\n * stack into canvas space; the linked entries are then re-fitted from the host's\n * transform. `toCanvasSpace` / `toHostSpace` are the conversions that migration\n * between the two regimes needs, and they are exact for scale, rotation and skew\n * because they compose matrices rather than copying left/top.\n */\n\nexport function matrixOf(object: FabricObject): TMat2D {\n return object.calcTransformMatrix();\n}\n\n/** Overwrite an object's transform with `matrix`, keeping its own dimensions. */\nexport function applyMatrix(object: FabricObject, matrix: TMat2D): void {\n const decomposed = util.qrDecompose(matrix);\n object.set({\n flipX: false,\n flipY: false,\n originX: 'center',\n originY: 'center',\n left: decomposed.translateX,\n top: decomposed.translateY,\n scaleX: decomposed.scaleX,\n scaleY: decomposed.scaleY,\n angle: decomposed.angle,\n skewX: decomposed.skewX,\n skewY: 0,\n });\n object.setCoords();\n}\n\n/** Host-space geometry → canvas-space, for the same on-screen result. */\nexport function toCanvasSpace(object: FabricObject, host: FabricObject): void {\n applyMatrix(object, util.multiplyTransformMatrices(matrixOf(host), matrixOf(object)));\n}\n\n/** Canvas-space geometry → host-space, for the same on-screen result. */\nexport function toHostSpace(object: FabricObject, host: FabricObject): void {\n applyMatrix(\n object,\n util.multiplyTransformMatrices(util.invertTransform(matrixOf(host)), matrixOf(object)),\n );\n}\n\n/**\n * The mask's transform expressed relative to its host, so a linked mask can be\n * re-derived after the host moves. Stored on the entry, not recomputed from the\n * live objects: by the time the host has moved, the old relationship is gone.\n */\nexport function relativeMatrix(object: FabricObject, host: FabricObject): TMat2D {\n return util.multiplyTransformMatrices(util.invertTransform(matrixOf(host)), matrixOf(object));\n}\n\n/** Re-place a linked mask from the host's current transform and a stored `rel`. */\nexport function applyRelativeMatrix(object: FabricObject, host: FabricObject, rel: TMat2D): void {\n applyMatrix(object, util.multiplyTransformMatrices(matrixOf(host), rel));\n}\n\n/**\n * Fabric types `clipPath` with a looser prop set than the objects the editor\n * builds, so reading a clip back out needs a narrowing step. Every clip this\n * module reads is one it composed from real objects in the first place.\n */\nexport function asObject(clip: NonNullable<FabricObject['clipPath']>): FabricObject {\n return clip as FabricObject;\n}\n\n/** Narrow a persisted `rel` array back to a transform matrix. */\nexport function toMatrix(values: number[] | undefined): TMat2D | null {\n if (!values || values.length !== 6 || values.some((value) => !Number.isFinite(value)))\n return null;\n return [values[0], values[1], values[2], values[3], values[4], values[5]];\n}\n\n/** Scale an object so its unrotated box covers `box`, centred on it. */\nexport function fitToBox(\n object: FabricObject,\n box: { left: number; top: number; width: number; height: number },\n zoom = 1,\n): void {\n const width = Math.max(1, box.width) * zoom;\n const height = Math.max(1, box.height) * zoom;\n object.set({\n originX: 'center',\n originY: 'center',\n angle: 0,\n skewX: 0,\n skewY: 0,\n left: box.left + box.width / 2,\n top: box.top + box.height / 2,\n scaleX: width / Math.max(1, object.width ?? 1),\n scaleY: height / Math.max(1, object.height ?? 1),\n });\n object.setCoords();\n}\n\n/**\n * Pull a composed clip group back apart into standalone objects in the space the\n * group itself was in.\n *\n * `removeAll` already restores each child's own transform on the way out — the\n * group rebases children when it takes them in, and reverses that when it lets\n * them go. Folding the group's matrix back in on top (as one would with a v5-era\n * group) double-counts it, which stays invisible while a mask sits at the origin\n * and moves it twice as far as it should the moment one does not.\n *\n * The group passed in is emptied.\n */\nexport function unwrapGroup(group: Group): FabricObject[] {\n const children = group.removeAll();\n for (const child of children) child.setCoords();\n return children;\n}\n","import { Rect } from 'fabric';\nimport type { Canvas, FabricObject } from 'fabric';\nimport type { Layer, LayerManager } from './layer';\nimport type { HistoryManager } from './history';\nimport type { EventEmitter } from './events';\nimport type { EditorEvents, LayerMeta, TextOverflow, TextWrapMode } from './types';\nimport { asText, fitTextWidth, type TextSource } from './text-fit';\nimport { preWrapWordSplit } from './text-wrap-split';\nimport { asObject, toHostSpace } from './masks/space';\n\n/** Both properties as they apply to a layer, defaults filled in. */\nexport interface TextWrapState {\n wrap: TextWrapMode;\n overflow: TextOverflow;\n}\n\n/** A Textbox, plus the wrapping levers fabric does not put on FabricObject. */\ninterface WrappableText extends TextSource {\n splitByGrapheme?: boolean;\n wordSplit?: (value: string) => string[];\n}\n\n/**\n * Fabric names `wordSplit` as an override point, so pre-wrap is an own-property\n * shadow of the prototype method rather than a patched prototype: two layers on\n * one canvas can be in different modes.\n */\nfunction patchWordSplit(text: WrappableText): void {\n if (Object.prototype.hasOwnProperty.call(text, 'wordSplit')) return;\n Object.defineProperty(text, 'wordSplit', {\n value: preWrapWordSplit,\n configurable: true,\n writable: true,\n });\n}\n\nfunction unpatchWordSplit(text: WrappableText): void {\n if (Object.prototype.hasOwnProperty.call(text, 'wordSplit')) {\n delete text.wordSplit;\n }\n}\n\nexport function readTextWrap(meta: LayerMeta | undefined): TextWrapState {\n return { wrap: meta?.wrap ?? 'none', overflow: meta?.overflow ?? 'visible' };\n}\n\n/** Builds the clip rect. A parameter because a Node renderer's `Rect` (from\n * `fabric/node`) and the browser's `Rect` (from `fabric`) are different\n * classes — a clip built by one does not render on the other's canvas. */\ntype RectFactory = (options: Record<string, unknown>) => FabricObject;\n\n/**\n * The box, as a clip, in the layer's own frame.\n *\n * A top-level clipPath's coordinates are the object's own, centred on it and\n * unaffected by its scale, so this is sized to the unscaled dimensions — the\n * same rule `MaskPresetManager.buildClip` follows. That invariant holds only at\n * the top level: nested under another clip the frame is the parent's, and\n * `derive` converts into it. Height is the text height, which IS the content\n * height for a Textbox, so only the width ever clips anything.\n *\n * A fresh Rect per derive, and derive runs on the typing path — cheap, since\n * `objectCaching: false` means there is no backing canvas to retain. If it ever\n * shows up in a profile, the move is to resize the clip already installed\n * rather than to build a second one.\n */\nfunction boxClip(text: WrappableText, makeRect: RectFactory): FabricObject {\n return makeRect({\n width: Math.max(1, text.width ?? 1),\n height: Math.max(1, text.height ?? 1),\n originX: 'center',\n originY: 'center',\n left: 0,\n top: 0,\n objectCaching: false,\n });\n}\n\n/**\n * Does a mask already own this layer's clipPath? Read from meta, not the object.\n *\n * Deliberately blind to `PatternManager`, which strips a layer's clip for the\n * duration of a pattern: meta still says \"masked\" while the object carries no\n * clip at all, so the box clip becomes a no-op until the pattern is removed.\n * That is the safe way round — no clip beats taking a slot the pattern is using\n * — so do not \"fix\" this by asking the object what it currently holds.\n */\nfunction hasMask(meta: LayerMeta): boolean {\n return !!meta.maskPreset || (meta.maskStack?.length ?? 0) > 0;\n}\n\n/**\n * The renderer-agnostic half of {@link TextWrapManager.derive}: the fabric\n * state a wrap mode implies once the box's width is already settled.\n *\n * Deliberately does NOT touch width — re-fitting here would let a Node\n * renderer, which sees only the serialized state and never `meta.wrapWidth`,\n * shift a box the browser already fitted at authoring time. Width is the\n * manager's job (`fitTextWidth` for `'none'`, `meta.wrapWidth` restore for\n * everything else); this only sets the levers fabric does not serialize on\n * its own (`wordSplit`) or that depend on the box the manager just settled\n * (the clip). Call it AFTER any width decision, never before — the clip below\n * is sized to `text.width`/`text.height` as they stand when this runs.\n */\nexport function applyTextWrapToObject(\n object: FabricObject,\n meta: LayerMeta | undefined,\n makeRect: RectFactory = (options) => new Rect(options),\n): void {\n const text = asText(object) as WrappableText | null;\n if (!text) return;\n\n const state = readTextWrap(meta);\n\n // A curved run follows a path built for the box the curve manager sized;\n // re-deriving here would fight it. The mode stays stored and applies again\n // when the curve is cleared.\n if (!text.path) {\n text.set({ splitByGrapheme: state.wrap === 'break-all' });\n if (state.wrap === 'pre-wrap') patchWordSplit(text);\n else unpatchWordSplit(text);\n // `splitByGrapheme` is not one of fabric's `textLayoutProperties`, so the\n // `set` above did not re-lay the run out on its own, and neither does\n // patching `wordSplit` (an own-property override, not a tracked prop) —\n // a layer already at its current width, with no width change to trigger\n // fabric's own relayout, would otherwise keep lines laid out under the\n // PREVIOUS split function.\n text.initDimensions?.();\n }\n\n // Installed even on curved text: a curve owns the box, not the clip.\n const clip = state.overflow === 'hidden' ? boxClip(text, makeRect) : undefined;\n if (meta && hasMask(meta)) {\n const host = text.clipPath;\n if (host) {\n // A nested clip is drawn in its PARENT clip's frame, not the layer's:\n // fabric replays every entry in `parentClipPaths` before applying the\n // child's own transform (`Object.createClipPathLayer`). The mask group\n // lays itself out around its geometry, so that frame coincides with the\n // layer's only for a centred mask — which is why presets and default-fit\n // masks look right. Left unconverted, the box clip is displaced by the\n // whole of the mask's transform: an offset mask that covers the run\n // completely starts cutting it, and an unlinked one (composed in canvas\n // space, so the offset is the layer's full distance from the origin)\n // carries the clip clear of the text, which disappears outright.\n //\n // Re-expressing it relative to the mask is the same conversion a linked\n // mask needs when it joins a canvas-space stack, so it uses the same\n // helper rather than new matrix maths. `asObject` is the narrowing step\n // that module already carries for fabric's looser `clipPath` typing.\n if (clip) toHostSpace(clip, asObject(host));\n host.clipPath = clip;\n }\n } else {\n text.clipPath = clip;\n }\n}\n\n/**\n * How a text layer breaks its lines, and whether it paints past its box.\n *\n * `meta` is the authoring record; what actually renders — and what a print\n * pipeline that never reads `meta` sees — is the fabric state derived here:\n * `width`, `splitByGrapheme` and `clipPath`, all of which fabric serializes on\n * its own. That is the same division `TextCurveManager` draws between\n * `meta.curve` and the `path` it installs.\n */\nexport class TextWrapManager {\n /**\n * Typing changes the run the box was fitted to, so an auto-width layer has to\n * re-fit. No history entry: fabric records the edit when editing exits, and a\n * save per keystroke would bury every earlier step.\n */\n private readonly onTextChanged = (event: { target?: FabricObject }) => {\n const layer = event.target ? this.layers.findByObject(event.target) : undefined;\n if (!layer) return;\n this.refresh(layer.id, false);\n };\n\n /**\n * Both mask owners — the preset manager and every mask-stack mutation —\n * install their clip straight onto `clipPath`, dropping whatever was there,\n * and neither knows this layer had a box clip. Re-deriving on the one event\n * they both announce puts it back where it now belongs: nested under the new\n * mask, or at the top level when the last mask leaves. Waiting for the next\n * keystroke instead would leave a layer that should clip inside its box\n * serialized unclipped — which is what the print renderer reads.\n */\n private readonly onMasksChanged = ({ target }: { target: string }) => {\n // `refresh` ignores an id that is not a text layer, so the whole-design\n // mask target passes through it harmlessly.\n this.refresh(target);\n };\n\n constructor(\n private canvas: Canvas,\n private layers: LayerManager,\n private history: HistoryManager,\n private events: EventEmitter<EditorEvents>,\n ) {\n this.canvas.on('text:changed', this.onTextChanged);\n this.events.on('masks:changed', this.onMasksChanged);\n }\n\n dispose(): void {\n this.canvas.off('text:changed', this.onTextChanged);\n this.events.off('masks:changed', this.onMasksChanged);\n }\n\n /** Both properties for a text layer, or null when it is not text. */\n get(layerId: string): TextWrapState | null {\n const layer = this.layers.get(layerId);\n if (!layer || !asText(layer.fabricObject)) return null;\n return readTextWrap(layer.meta);\n }\n\n apply(layerId: string, wrap: TextWrapMode, save = true): boolean {\n const layer = this.layers.get(layerId);\n const text = layer ? asText(layer.fabricObject) : null;\n if (!layer || !text) return false;\n if (wrap === 'none') {\n // Parked before anything widens the box, so the authored width is the one\n // that comes back — and only on the way IN, or a second call would park\n // the fitted width over it.\n //\n // Never from a curved box: `TextCurveManager` widened that one to fit the\n // path and is holding the real authored width in `meta.curveWidth`. Park\n // here and uncurving later would restore the curve's width as if the\n // author had chosen it.\n const curved = !!text.path;\n if (layer.meta.wrapWidth === undefined && !curved) {\n layer.meta.wrapWidth = text.width ?? 0;\n }\n }\n layer.meta.wrap = wrap;\n return this.derive(layerId, save);\n }\n\n setOverflow(layerId: string, overflow: TextOverflow, save = true): boolean {\n const layer = this.layers.get(layerId);\n if (!layer || !asText(layer.fabricObject)) return false;\n layer.meta.overflow = overflow;\n return this.derive(layerId, save);\n }\n\n /** Back to the defaults: auto-width, unclipped. */\n clear(layerId: string, save = true): boolean {\n const layer = this.layers.get(layerId);\n if (!layer || !asText(layer.fabricObject)) return false;\n delete layer.meta.overflow;\n return this.apply(layerId, 'none', save);\n }\n\n /** Re-derive from the stored mode — after a text, font or size change. */\n refresh(layerId: string, save = false): boolean {\n const layer = this.layers.get(layerId);\n if (!layer || !asText(layer.fabricObject)) return false;\n return this.derive(layerId, save);\n }\n\n /**\n * Re-derive every text layer — used after a state restore.\n *\n * Recursive because a template inserts as a group of real child layers, and\n * text inside one would otherwise keep whatever box it was restored with.\n */\n refreshAll(): void {\n const visit = (layers: Layer[]): void => {\n for (const layer of layers) {\n if (asText(layer.fabricObject)) this.refresh(layer.id);\n if (layer.children.length > 0) visit(layer.children);\n }\n };\n visit(this.layers.getAll());\n }\n\n private derive(layerId: string, save: boolean): boolean {\n const layer = this.layers.get(layerId);\n const text = layer ? (asText(layer.fabricObject) as WrappableText | null) : null;\n if (!layer || !text) return false;\n\n const state = readTextWrap(layer.meta);\n\n // A curved run follows a path built for the box the curve manager sized;\n // re-deriving here would fight it. The mode stays stored and applies again\n // when the curve is cleared. This is the layer-dependent half of the mode:\n // `meta.wrapWidth` is a layer authoring record with no fabric equivalent,\n // and re-fitting is never something a renderer that only sees the already-\n // fitted serialized width should redo — both stay here rather than moving\n // into `applyTextWrapToObject`.\n if (!text.path) {\n if (state.wrap === 'none') {\n fitTextWidth(text);\n } else if (layer.meta.wrapWidth !== undefined) {\n text.set({ width: layer.meta.wrapWidth });\n delete layer.meta.wrapWidth;\n }\n }\n\n // The rest — split mode and the overflow clip — is object-only and shared\n // with the Node renderer, which derives it from the very same `meta` on a\n // freshly restored object with no editor around it. Called after the width\n // decision above so the clip is sized to the box that decision just chose.\n applyTextWrapToObject(text, layer.meta);\n\n text.dirty = true;\n text.setCoords();\n this.canvas.requestRenderAll();\n // A refresh reconstructs derived Fabric-only state after restore or another\n // manager replaced the clip. It is not a user edit: restore already\n // notifies React through `layers:changed`, and the manager that replaced a\n // mask already announced its own modification. Emitting here turned every\n // restore into a phantom layer write.\n if (save) {\n this.events.emit('layer:modified', { layerId });\n this.history.save();\n }\n return true;\n }\n}\n","import type { MockupDisplacement, MockupDisplacementChannel } from './types';\n\nconst CHANNEL_INDEX: Record<MockupDisplacementChannel, number> = {\n red: 0,\n green: 1,\n blue: 2,\n alpha: 3,\n};\n\nfunction finiteScale(value: number | undefined, fallback: number, label: string): number {\n const resolved = value ?? fallback;\n if (!Number.isFinite(resolved)) throw new Error(`${label} must be finite`);\n return resolved;\n}\n\nfunction sample(\n source: Uint8ClampedArray,\n width: number,\n height: number,\n x: number,\n y: number,\n channel: number,\n): number {\n const clampedX = Math.max(0, Math.min(width - 1, x));\n const clampedY = Math.max(0, Math.min(height - 1, y));\n const x0 = Math.floor(clampedX);\n const y0 = Math.floor(clampedY);\n const x1 = Math.min(width - 1, x0 + 1);\n const y1 = Math.min(height - 1, y0 + 1);\n const tx = clampedX - x0;\n const ty = clampedY - y0;\n const top =\n source[(y0 * width + x0) * 4 + channel] * (1 - tx) +\n source[(y0 * width + x1) * 4 + channel] * tx;\n const bottom =\n source[(y1 * width + x0) * 4 + channel] * (1 - tx) +\n source[(y1 * width + x1) * 4 + channel] * tx;\n return top * (1 - ty) + bottom * ty;\n}\n\n/**\n * Warp RGBA pixels with an equally sized channel map. A channel value of 128\n * is neutral; 0 and 255 move by the configured negative/positive maximum.\n */\nexport function displaceRgba(\n source: Uint8ClampedArray,\n map: Uint8ClampedArray,\n width: number,\n height: number,\n options: Omit<MockupDisplacement, 'image'>,\n): Uint8ClampedArray {\n if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) {\n throw new Error('Displacement dimensions must be positive integers');\n }\n const expectedLength = width * height * 4;\n if (source.length !== expectedLength || map.length !== expectedLength) {\n throw new Error('Displacement source and map must match the requested dimensions');\n }\n\n const scaleX = finiteScale(options.scaleX, 10, 'Displacement scaleX');\n const scaleY = finiteScale(options.scaleY, 10, 'Displacement scaleY');\n const channelX = CHANNEL_INDEX[options.channelX ?? 'red'];\n const channelY = CHANNEL_INDEX[options.channelY ?? 'green'];\n const output = new Uint8ClampedArray(expectedLength);\n\n for (let y = 0; y < height; y += 1) {\n for (let x = 0; x < width; x += 1) {\n const offset = (y * width + x) * 4;\n const sourceX = x + ((map[offset + channelX] - 128) / 127) * scaleX;\n const sourceY = y + ((map[offset + channelY] - 128) / 127) * scaleY;\n for (let channel = 0; channel < 4; channel += 1) {\n output[offset + channel] = Math.round(\n sample(source, width, height, sourceX, sourceY, channel),\n );\n }\n }\n }\n return output;\n}\n","import { StaticCanvas } from 'fabric';\nimport type { Canvas, FabricObject, ImageFormat } from 'fabric';\nimport type { MockupConfig, MockupPrintArea } from './types';\nimport { displaceRgba } from './displacement';\n\nexport interface PngExportOptions {\n multiplier?: number;\n format?: ImageFormat;\n quality?: number;\n}\n\nexport interface CoverPlacement {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\nexport function computePrintAreaClip(\n area: MockupPrintArea,\n scaleX: number,\n scaleY: number,\n targetWidth: number,\n targetHeight: number,\n): MockupPrintArea {\n const left = Math.max(0, Math.min(targetWidth, area.left * scaleX));\n const top = Math.max(0, Math.min(targetHeight, area.top * scaleY));\n const right = Math.max(left, Math.min(targetWidth, (area.left + area.width) * scaleX));\n const bottom = Math.max(top, Math.min(targetHeight, (area.top + area.height) * scaleY));\n return { left, top, width: right - left, height: bottom - top };\n}\n\n/** Object-fit: cover geometry, exported for deterministic preview/composite tests. */\nexport function computeCoverPlacement(\n sourceWidth: number,\n sourceHeight: number,\n targetWidth: number,\n targetHeight: number,\n): CoverPlacement {\n if (sourceWidth <= 0 || sourceHeight <= 0 || targetWidth <= 0 || targetHeight <= 0) {\n throw new Error('Cover dimensions must be positive');\n }\n const scale = Math.max(targetWidth / sourceWidth, targetHeight / sourceHeight);\n const width = sourceWidth * scale;\n const height = sourceHeight * scale;\n return {\n left: (targetWidth - width) / 2,\n top: (targetHeight - height) / 2,\n width,\n height,\n };\n}\n\nfunction canvasElementToBlob(\n output: HTMLCanvasElement,\n format: ImageFormat,\n quality: number,\n): Promise<Blob> {\n const mime = format === 'jpeg' ? 'image/jpeg' : `image/${format}`;\n return new Promise<Blob>((resolve, reject) => {\n output.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error(`Failed to export ${format}`))),\n mime,\n quality,\n );\n });\n}\n\nexport async function exportPNG(canvas: Canvas, options: PngExportOptions = {}): Promise<Blob> {\n const { multiplier = 1, format = 'png' as ImageFormat, quality = 1 } = options;\n const output = canvas.toCanvasElement(multiplier);\n return canvasElementToBlob(output, format, quality);\n}\n\n/** Render cloned objects without mutating the live editor canvas. */\nexport async function exportIsolatedPNG(\n source: Canvas,\n objects: FabricObject[],\n options: PngExportOptions & {\n width?: number;\n height?: number;\n backgroundColor?: string;\n backgroundImage?: FabricObject | null;\n cloneObjects?: boolean;\n } = {},\n): Promise<Blob> {\n const element = source.lowerCanvasEl.ownerDocument.createElement('canvas');\n const canvas = new StaticCanvas(element, {\n width: options.width ?? source.getWidth(),\n height: options.height ?? source.getHeight(),\n backgroundColor: options.backgroundColor || undefined,\n });\n try {\n const clones =\n options.cloneObjects === false\n ? objects\n : await Promise.all(objects.map((object) => object.clone()));\n if (clones.length) canvas.add(...clones);\n if (options.backgroundImage) canvas.backgroundImage = await options.backgroundImage.clone();\n canvas.requestRenderAll();\n // Awaited, not returned: `finally` would otherwise dispose the canvas while\n // the export is still reading from it.\n return await exportPNG(canvas as unknown as Canvas, options);\n } finally {\n canvas.dispose();\n }\n}\n\n/**\n * Render just the print-area rectangle, on transparency.\n *\n * This is the file a print provider receives: the design alone, cropped to the\n * printable rectangle, with no garment behind it and no canvas background baked\n * in — so it is rendered from cloned objects rather than off the live canvas.\n */\nexport async function exportPrintArea(\n source: Canvas,\n area: MockupPrintArea,\n options: PngExportOptions = {},\n): Promise<Blob> {\n const { multiplier = 1, format = 'png' as ImageFormat, quality = 1 } = options;\n const width = source.getWidth();\n const height = source.getHeight();\n const clip = computePrintAreaClip(\n area,\n multiplier,\n multiplier,\n width * multiplier,\n height * multiplier,\n );\n if (clip.width <= 0 || clip.height <= 0) {\n throw new Error('Print area does not overlap the canvas');\n }\n\n const element = source.lowerCanvasEl.ownerDocument.createElement('canvas');\n const canvas = new StaticCanvas(element, { width, height });\n try {\n const clones = await Promise.all(source.getObjects().map((object) => object.clone()));\n if (clones.length) canvas.add(...clones);\n canvas.requestRenderAll();\n const rendered = canvas.toCanvasElement(multiplier);\n const output = rendered.ownerDocument.createElement('canvas');\n output.width = Math.max(1, Math.round(clip.width));\n output.height = Math.max(1, Math.round(clip.height));\n const context = output.getContext('2d');\n if (!context) throw new Error('2D canvas context is unavailable');\n context.drawImage(rendered, -clip.left, -clip.top);\n // Awaited, not returned: `finally` would dispose the canvas mid-read.\n return await canvasElementToBlob(output, format, quality);\n } finally {\n canvas.dispose();\n }\n}\n\n/** Rasterize the browser mockup preview together with the transparent design. */\nexport async function exportMockup(\n canvas: Canvas,\n mockup: MockupConfig,\n options: PngExportOptions = {},\n): Promise<Blob> {\n const { multiplier = 1, format = 'png' as ImageFormat, quality = 1 } = options;\n const design = canvas.toCanvasElement(multiplier);\n const output = design.ownerDocument.createElement('canvas');\n output.width = design.width;\n output.height = design.height;\n const context = output.getContext('2d');\n if (!context) throw new Error('2D canvas context is unavailable');\n\n const loadImage = (url: string) =>\n new Promise<HTMLImageElement>((resolve, reject) => {\n const element = new Image();\n element.crossOrigin = 'anonymous';\n element.onload = () => resolve(element);\n element.onerror = () => reject(new Error(`Failed to load mockup image: ${url}`));\n element.src = url;\n });\n const drawCover = (\n image: HTMLImageElement,\n targetContext: CanvasRenderingContext2D = context,\n ) => {\n const placement = computeCoverPlacement(\n image.naturalWidth || image.width,\n image.naturalHeight || image.height,\n output.width,\n output.height,\n );\n targetContext.drawImage(\n image,\n placement.left,\n placement.top,\n placement.width,\n placement.height,\n );\n };\n\n // Full-size scratch buffers, released explicitly in the finally below: a\n // detached canvas element can hold its backing store well past its last\n // reference, and a 4K mockup allocates three of them per export.\n const scratch: HTMLCanvasElement[] = [design];\n try {\n drawCover(await loadImage(mockup.image));\n let compositedDesign: CanvasImageSource = design;\n if (mockup.displacement) {\n const sourceContext = design.getContext('2d');\n if (!sourceContext) throw new Error('2D design context is unavailable');\n const mapCanvas = design.ownerDocument.createElement('canvas');\n scratch.push(mapCanvas);\n mapCanvas.width = design.width;\n mapCanvas.height = design.height;\n const mapContext = mapCanvas.getContext('2d');\n if (!mapContext) throw new Error('2D displacement-map context is unavailable');\n drawCover(await loadImage(mockup.displacement.image), mapContext);\n\n const warped = design.ownerDocument.createElement('canvas');\n scratch.push(warped);\n warped.width = design.width;\n warped.height = design.height;\n const warpedContext = warped.getContext('2d');\n if (!warpedContext) throw new Error('2D displaced-design context is unavailable');\n let sourcePixels: Uint8ClampedArray;\n let mapPixels: Uint8ClampedArray;\n try {\n sourcePixels = sourceContext.getImageData(0, 0, design.width, design.height).data;\n mapPixels = mapContext.getImageData(0, 0, design.width, design.height).data;\n } catch (error) {\n throw new Error('Failed to apply mockup displacement map; verify image CORS access', {\n cause: error,\n });\n }\n const pixels = displaceRgba(sourcePixels, mapPixels, design.width, design.height, {\n ...mockup.displacement,\n scaleX: (mockup.displacement.scaleX ?? 10) * multiplier,\n scaleY: (mockup.displacement.scaleY ?? 10) * multiplier,\n });\n const imageData = warpedContext.createImageData(design.width, design.height);\n imageData.data.set(pixels);\n warpedContext.putImageData(imageData, 0, 0);\n compositedDesign = warped;\n }\n context.save();\n if (mockup.printArea && mockup.clipToPrintArea !== false) {\n const clip = computePrintAreaClip(\n mockup.printArea,\n output.width / canvas.getWidth(),\n output.height / canvas.getHeight(),\n output.width,\n output.height,\n );\n context.beginPath();\n context.rect(clip.left, clip.top, clip.width, clip.height);\n context.clip();\n }\n context.globalAlpha = Math.max(0, Math.min(1, mockup.designOpacity ?? 1));\n context.globalCompositeOperation =\n !mockup.designBlendMode || mockup.designBlendMode === 'normal'\n ? 'source-over'\n : mockup.designBlendMode;\n context.drawImage(compositedDesign, 0, 0);\n context.restore();\n\n if (mockup.overlay) {\n context.save();\n context.globalAlpha = Math.max(0, Math.min(1, mockup.overlay.opacity ?? 1));\n context.globalCompositeOperation =\n mockup.overlay.blendMode === 'normal'\n ? 'source-over'\n : (mockup.overlay.blendMode ?? 'multiply');\n drawCover(await loadImage(mockup.overlay.image));\n context.restore();\n }\n return await canvasElementToBlob(output, format, quality);\n } finally {\n for (const element of scratch) {\n element.width = 0;\n element.height = 0;\n }\n }\n}\n\nexport function exportSVG(canvas: Canvas): string {\n return canvas.toSVG();\n}\n\nexport function exportDataURL(canvas: Canvas, format: ImageFormat = 'png', multiplier = 1): string {\n return canvas.toDataURL({ format, multiplier });\n}\n"],"mappings":";AAAA,SAAS,aAAa;AAsBf,IAAM,iBAAiB;AAG9B,IAAM,gBAAgB;AAGtB,IAAM,gBAAgB;AAMtB,IAAM,eAAe;AACrB,IAAM,eAAe;AAgBrB,SAAS,eAAe,MAA0B;AAChD,QAAM,WAAW,KAAK;AACtB,MAAI;AACF,SAAK,IAAI,EAAE,OAAO,cAAc,CAA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