dsh-codex-subscription 3.2.6 → 3.2.8

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.
@@ -25,6 +25,8 @@ window.__ModuleLoader__.load({
25
25
  marker: "M5 16l9-12 7 5-9 12-7-5zM5 16l-3 4 6 1M12 7l7 5",
26
26
  image: "M4 4h16v16H4zM4 16l5-5 4 4 3-3 4 4M15 8h.01",
27
27
  close: "M6 6l12 12M18 6L6 18",
28
+ play: "M8 5l11 7-11 7z",
29
+ pause: "M9 5v14m6-14v14",
28
30
  stop: "M6 6h12v12H6z",
29
31
  pen: "M4 17c3-7 12-15 12-11S4 19 8 19s10-10 10-6-6 8-2 7l4-3",
30
32
  eraser: "M4 14l9-10 7 7-9 10H9l-5-5zM8 10l7 7M11 21h10",
@@ -1180,120 +1182,126 @@ window.__ModuleLoader__.load({
1180
1182
  "#34c759",
1181
1183
  "#0088ff"
1182
1184
  ];
1183
- function SketchControls({ t, navigation, picturesOpen, setPicturesOpen, disabled, tool, brush, chooseBrush, chooseTool, shapesOpen, setShapesOpen, fillShape, setFillShape, selected, editObject, selection, setTextEdit, stability, setStability, eraser, setEraser, color, pickColor }) {
1185
+ function SketchControls({ t, navigation, picturesOpen, setPicturesOpen, disabled, tool, brush, chooseBrush, chooseTool, shapesOpen, setShapesOpen, fillShape, setFillShape, selected, editObject, selection, setTextEdit, stability, setStability, eraser, setEraser, color, pickColor, sizeControl }) {
1184
1186
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1185
1187
  className: "codexSketchControls",
1186
- children: [
1187
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1188
- type: "button",
1189
- className: "codexSketchPicturesToggle",
1190
- "aria-expanded": picturesOpen,
1191
- onClick: () => setPicturesOpen((value) => !value),
1192
- children: t("sketchPictures")
1193
- }),
1194
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchViewControls, {
1195
- navigation,
1196
- t
1197
- }),
1198
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchToolPicker, {
1199
- t,
1200
- disabled,
1201
- tool,
1202
- brush,
1203
- chooseBrush,
1204
- chooseTool,
1205
- shapesOpen,
1206
- setShapesOpen
1207
- }),
1208
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1209
- className: "codexLayerBrush",
1210
- children: [
1211
- ["rectangle", "circle"].includes(tool) ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1212
- type: "checkbox",
1213
- disabled,
1214
- checked: fillShape,
1215
- onChange: (event) => setFillShape(event.target.checked)
1216
- }), t("sketchFill")] }) : null,
1217
- selected ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1218
- className: "codexSketchObjectActions",
1219
- children: [
1220
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1221
- disabled,
1222
- onClick: () => editObject({}, "duplicate"),
1223
- children: t("sketchObjectDuplicate")
1224
- }),
1225
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1226
- disabled,
1227
- onClick: () => editObject({}, "delete"),
1228
- children: t("sketchObjectDelete")
1229
- }),
1230
- selected.shape === "text" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1231
- disabled,
1232
- onClick: () => setTextEdit({
1233
- selection,
1234
- value: selected.text
1235
- }),
1236
- children: t("sketchText")
1237
- }) : null
1238
- ]
1239
- }) : null,
1240
- tool === "pen" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
1241
- className: "codexSketchStability",
1242
- children: [t("sketchStability"), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("select", {
1243
- "aria-label": t("sketchStability"),
1244
- value: stability,
1188
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchToolPicker, {
1189
+ t,
1190
+ disabled,
1191
+ tool,
1192
+ brush,
1193
+ chooseBrush,
1194
+ chooseTool,
1195
+ shapesOpen,
1196
+ setShapesOpen
1197
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1198
+ className: "codexSketchOptions",
1199
+ children: [
1200
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1201
+ type: "button",
1202
+ className: "codexSketchPicturesToggle",
1203
+ "aria-expanded": picturesOpen,
1204
+ onClick: () => setPicturesOpen((value) => !value),
1205
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(WorkspaceIcon, {
1206
+ name: "image",
1207
+ size: 16
1208
+ }), t("sketchPictures")]
1209
+ }),
1210
+ sizeControl,
1211
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1212
+ className: "codexLayerBrush",
1213
+ children: [
1214
+ ["rectangle", "circle"].includes(tool) ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1215
+ type: "checkbox",
1245
1216
  disabled,
1246
- onChange: (event) => setStability(Number(event.target.value)),
1217
+ checked: fillShape,
1218
+ onChange: (event) => setFillShape(event.target.checked)
1219
+ }), t("sketchFill")] }) : null,
1220
+ selected ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1221
+ className: "codexSketchObjectActions",
1247
1222
  children: [
1248
- 0,
1249
- 25,
1250
- 50,
1251
- 75
1252
- ].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
1253
- value,
1254
- children: t(`sketchStability${value}`)
1223
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1224
+ disabled,
1225
+ onClick: () => editObject({}, "duplicate"),
1226
+ children: t("sketchObjectDuplicate")
1227
+ }),
1228
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1229
+ disabled,
1230
+ onClick: () => editObject({}, "delete"),
1231
+ children: t("sketchObjectDelete")
1232
+ }),
1233
+ selected.shape === "text" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1234
+ disabled,
1235
+ onClick: () => setTextEdit({
1236
+ selection,
1237
+ value: selected.text
1238
+ }),
1239
+ children: t("sketchText")
1240
+ }) : null
1241
+ ]
1242
+ }) : null,
1243
+ tool === "pen" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
1244
+ className: "codexSketchStability",
1245
+ children: [t("sketchStability"), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("select", {
1246
+ "aria-label": t("sketchStability"),
1247
+ value: stability,
1248
+ disabled,
1249
+ onChange: (event) => setStability(Number(event.target.value)),
1250
+ children: [
1251
+ 0,
1252
+ 25,
1253
+ 50,
1254
+ 75
1255
+ ].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
1256
+ value,
1257
+ children: t(`sketchStability${value}`)
1258
+ }, value))
1259
+ })]
1260
+ }) : null,
1261
+ tool === "eraser" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1262
+ className: "codexSketchSegment",
1263
+ role: "group",
1264
+ "aria-label": t("sketchEraserMode"),
1265
+ children: ["pixel", "stroke"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1266
+ type: "button",
1267
+ "aria-pressed": eraser === value,
1268
+ disabled,
1269
+ onClick: () => setEraser(value),
1270
+ children: t(`sketchErase_${value}`)
1255
1271
  }, value))
1256
- })]
1257
- }) : null,
1258
- tool === "eraser" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1259
- className: "codexSketchSegment",
1260
- role: "group",
1261
- "aria-label": t("sketchEraserMode"),
1262
- children: ["pixel", "stroke"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1263
- type: "button",
1264
- "aria-pressed": eraser === value,
1265
- disabled,
1266
- onClick: () => setEraser(value),
1267
- children: t(`sketchErase_${value}`)
1268
- }, value))
1269
- }) : null
1270
- ]
1271
- }),
1272
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1273
- className: "codexSketchPalette",
1274
- role: "group",
1275
- "aria-label": t("sketchColor"),
1276
- children: [PALETTE.map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1277
- type: "button",
1278
- className: "codexSketchSwatch",
1279
- style: { "--swatch": value },
1280
- "aria-label": `${t("sketchColor")} ${value}`,
1281
- "aria-pressed": (selected?.color ?? color) === value,
1282
- disabled,
1283
- onClick: () => pickColor(value)
1284
- }, value)), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
1285
- className: "codexSketchCustom",
1286
- title: t("sketchColor"),
1287
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { style: { background: color } }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1288
- type: "color",
1289
- "aria-label": t("sketchColor"),
1290
- value: color,
1272
+ }) : null
1273
+ ]
1274
+ }),
1275
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1276
+ className: "codexSketchPalette",
1277
+ role: "group",
1278
+ "aria-label": t("sketchColor"),
1279
+ children: [PALETTE.map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1280
+ type: "button",
1281
+ className: "codexSketchSwatch",
1282
+ style: { "--swatch": value },
1283
+ "aria-label": `${t("sketchColor")} ${value}`,
1284
+ "aria-pressed": (selected?.color ?? color) === value,
1291
1285
  disabled,
1292
- onChange: (event) => pickColor(event.target.value)
1286
+ onClick: () => pickColor(value)
1287
+ }, value)), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
1288
+ className: "codexSketchCustom",
1289
+ title: t("sketchColor"),
1290
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { style: { background: color } }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1291
+ type: "color",
1292
+ "aria-label": t("sketchColor"),
1293
+ value: color,
1294
+ disabled,
1295
+ onChange: (event) => pickColor(event.target.value)
1296
+ })]
1293
1297
  })]
1294
- })]
1295
- })
1296
- ]
1298
+ }),
1299
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchViewControls, {
1300
+ navigation,
1301
+ t
1302
+ })
1303
+ ]
1304
+ })]
1297
1305
  });
1298
1306
  }
1299
1307
  //#endregion
@@ -2660,97 +2668,364 @@ window.__ModuleLoader__.load({
2660
2668
  return out;
2661
2669
  }
2662
2670
  //#endregion
2663
- //#region src/sketch-commands.js
2664
- const MAX_SKETCH_POINTS = 2e5;
2665
- const stale = (message) => Object.assign(Error(message), { code: "SKETCH_STALE" });
2666
- const SKETCH_COMMAND_HELP = {
2667
- coordinates: "Assign short meaningful stroke id values for later edits. Text uses two opposite box corners and text content; width is font size in pixels, automatic fitting within the box. Arrow uses two endpoints. Normalized x/y in [0,1]; width is canvas pixels. Read documentId and revision before editing.",
2668
- shapes: "line: exactly two endpoints; rectangle/circle (ellipse alias accepted): exactly two opposite bounding-box corners (circle draws an ellipse within that box); polygon: three or more vertices, closed automatically; pen: ordered path points. bezier: start point, then groups of control1/control2/end; use 4 points for one cubic curve, max 64 segments. Prefer bezier for smooth designed curves instead of many pen samples. fill:true closes and fills the curve. fill:true fills rectangle/circle/polygon. Layers and strokes paint in list order, later ones on top. All commands needed for drawing are described here; no source-code search is required.",
2669
- guide: "How to draw well here. 1) Plan first: list the parts, the drawing order (back to front) and the rough position and size as fractions of the canvas; keep the plan short. 2) Work big to small and verify after every stage (apply returns progress; look:true or preview shows the result): silhouette and big colour areas, then form and shading, then outlines and small details. 3) Place by measuring, not by eye: with a reference use measure (palette, regions, points, scan) to get exact colours, sizes and edge positions; without one use preview grid and keep proportions (an 8-head figure for realistic bodies, 5–6 heads for anime, a larger head for cute). 4) Depth: every form gets five tones, a highlight, light, half-tone, form shadow and a reflected-light edge; shadows are tinted (blue, purple, teal), never pure black; use 4–8 stop gradients with hue shifts, blur for glow, haze and soft shadows. 5) Build limbs and hair as long tapered shapes (a few overlapping bezier or path shapes), cover joints with rounded shapes, draw the face last on top of the head: eyes (iris, pupil, highlight, lashes), brows, nose and mouth with the right size and spacing, check them with preview box zoomed in. 6) Group related shapes on one layer (hair, face, clothes, background) so they can be adjusted or hidden. 7) Undo a stage that made things worse instead of painting over it. 8) Repeated details (strands, pleats, stars) can be generated by a short script and sent as one svg command. 9) Refine region by region (see below). 10) Stop when the error of every region stops falling or the zoomed previews look right; do not add detail that the picture does not have. When the whole picture is roughly right, do refinement passes region by region instead of stopping: split the picture into its parts (for a figure: head and face, each mass of hair, torso, each arm, each leg, shoes and small accessories). For every part, call preview mode side with box set to that part and grid on (zoomed up to 3x) and look at reference and drawing next to each other, then measure with box on the same part and use scan along an edge to read exact positions; list the three biggest differences (edge position, size, colour, missing detail), fix them with targeted object updates or a replacement shape, and check progress. A part is done when its error stops falling or the zoomed pair looks the same; then go to the next part. Make at least one pass over every part before you finish, and never end with the first full draft.",
2670
- commands: {
2671
- preset: "triangle/diamond/star: {op:\"stroke\",id:\"badge\",shape:\"star\",points:[{x:0.1,y:0.1},{x:0.3,y:0.3}],color:\"#ffcc00\",fill:true}. Two opposite box corners; stored as editable polygon. Inspect objectId for one object without repeating full help.",
2672
- stroke: "{op:\"stroke\",layer:1,shape:\"pen|line|arrow|text|rectangle|circle|polygon|bezier\",color:\"#rrggbb\",width:2,opacity:1,fill:false,points:[{x:0.1,y:0.1},...]}. Optional on any stroke: blend:\"multiply|screen|overlay|soft-light|hard-light|color-dodge|color-burn|darken|lighten|lighter\" (shadows multiply, glows screen or lighter; blends with what is already painted on the same layer; a whole layer can blend with the layers under it: {op:\"layer\",action:\"blend\",id:2,value:\"multiply\"}, value normal to clear) and clip:{shape:\"polygon|bezier|rectangle|circle\",points:[...]} keeps the stroke inside that shape, so shading and highlights stay inside the form they shade (clip.shape none removes it). Optional on filled shapes: gradient:{type:\"linear\",x1:0,y1:0,x2:0,y2:1,stops:[{offset:0,color:\"#ffcc66\"},{offset:1,color:\"#ff6644\",opacity:0.8}]} or {type:\"radial\",cx:0.5,cy:0.5,r:0.5,stops:[...]} (coordinates relative to the shape's own box, so moving or scaling the object keeps it); blur:12 softens any stroke by that many canvas pixels (glow, shadow, haze). Patch gradient:{type:\"none\"} or blur:0 to remove.",
2673
- layer: "Add: {op:\"layer\",action:\"add\",value:\"name\"}; optional id is the NEW unique integer ID, otherwise allocated automatically. after is the existing insertion anchor, defaults to active layer. Other actions: {op:\"layer\",action:\"select|rename|visible|duplicate|up|down|delete|clear\",id:1,value:\"name\"}; id targets an existing layer.",
2674
- curve: "Prefer {op:\"stroke\",shape:\"bezier\",start:{x:0,y:0},segments:[{control1:{x:0.2,y:0},control2:{x:0.8,y:1},end:{x:1,y:1}}],color:\"#123456\"}. Each segment has exactly two controls and an endpoint; no point counting required. Legacy points arrays still accepted. Do not provide both forms.",
2675
- object: "{op:\"object\",layer:1,id:\"title\",action:\"update|duplicate|delete\",patch:{color:\"#0088ff\",text:\"Title\"},transform:{dx:0.05,dy:0,scaleX:1,scaleY:1}}. All patch and transform fields optional. Inspect returns object IDs and bounds. Prefer targeted edits over redrawing layers.",
2676
- resize: "{op:\"resize\",ratio:\"1:1|4:3|3:4|16:9|9:16\"}",
2677
- svg: "{op:\"svg\",svg:\"<svg viewBox=\\\"0 0 1024 768\\\">...</svg>\",layer:1}. Fastest way to draw: send a whole scene as SVG (path with M L H V C S Q T A Z, rect, circle, ellipse, line, polyline, polygon, g, use, transform, fill/stroke/opacity, style=\"...\"); it becomes native editable strokes. The viewBox must match the canvas size (use the width and height from inspect; 4:3 is 1024x768). mix-blend-mode on an element becomes blend, and clip-path=\"url(#id)\" with a clipPath holding one path, rect, circle, ellipse or polygon becomes clip (use the same clipPath for all the shading of a form). Linear and radial gradients on filled shapes are kept as real gradients (fill=\"url(#id)\", objectBoundingBox or userSpaceOnUse, gradientTransform, stop-opacity); a gradient on a stroke line is flattened to its average color. A filter with feGaussianBlur becomes a soft edge on each shape it covers (glows, shadows, haze, depth of field); other filter effects are ignored with a warning. Text, image, mask, pattern and CSS classes are refused. Coordinates outside the canvas are clamped. One svg command may hold up to 200000 characters."
2678
- },
2679
- measure: "Action measure (not a command): {action:\"measure\",runId,documentId,columns:6,rows:8,box:{x:0,y:0,width:1,height:1},points:[{x:0.5,y:0.3}],palette:8,regions:8,scan:{x1:0,y1:0.5,x2:1,y2:0.5}} compares the drawing with the reference picture and returns error (0 = identical, percent of the colour range), the worst cells (box in 0..1, error, reference and drawing colour as #rrggbb, tone = how much lighter (+) or darker (-) the drawing is than the reference, 0..255; cells:true returns every cell instead of the worst ten, a full colour-error map you can work through), for points the reference and drawing colour there, with palette the main colours of the reference (share of the area), with regions where each main colour sits (share, centre, box that holds most of it), and with scan a ruler laid along a line: the colour runs of the reference and of your drawing along it, with their start and end positions, so you can place edges exactly (scan a row across the hair, a column through the body). box limits it to one part. Every apply also returns progress (error now, error before, three worst cells), so you can see whether a stage helped. Fix the worst cell first, read exact colours from the reference instead of guessing.",
2680
- undo: "Action undo: {action:\"undo\",runId,documentId,revision (optional),steps:1} takes back the last batches you applied (one per apply) and returns the new revision. Use it when a stage made things worse instead of painting over it.",
2681
- preview: "Action preview: {action:\"preview\",mode:\"side|diff\",compare:true,grid:true,box:{x:0.3,y:0.1,width:0.4,height:0.3}}. mode side puts the reference and your drawing next to each other; mode diff adds a difference heat map (dark = matches, blue to red = increasingly different in brightness, colour or edges); compare blends both 50/50; grid labels canvas pixels; box zooms into one part (normalised x,y,width,height) so you can check eyes, hands, edges. Apply with look:true returns the side-by-side picture with the result.",
2682
- limits: {
2683
- strokes: MAX_SKETCH_STROKES,
2684
- pointsPerStroke: MAX_STROKE_POINTS,
2685
- pointsTotal: MAX_SKETCH_POINTS,
2686
- commandsPerBatch: 256,
2687
- svgCharacters: MAX_SVG_CHARACTERS
2671
+ //#region src/sketch-replay.js
2672
+ const MAX_REPLAY_STATES = 2e3;
2673
+ const strokeOrders = /* @__PURE__ */ new WeakMap();
2674
+ function recordReplayStrokeOrder(doc, strokes) {
2675
+ if (strokes.length > 1 && strokes.some((item) => item.layer !== strokes[0].layer)) strokeOrders.set(doc, strokes);
2676
+ }
2677
+ function recordReplayState(states, doc) {
2678
+ if (states.at(-1) === doc) return;
2679
+ states.push(doc);
2680
+ if (states.length > 2e3) states.splice(0, states.length - MAX_REPLAY_STATES);
2681
+ }
2682
+ function appendedStrokes(before, after) {
2683
+ for (const layer of before.layers) {
2684
+ const next = after.layers.find((item) => item.id === layer.id);
2685
+ if (!next || next.image !== layer.image || layer.strokes.length > next.strokes.length || layer.strokes !== next.strokes && layer.strokes.some((stroke, i) => stroke !== next.strokes[i])) return void 0;
2686
+ }
2687
+ const added = [];
2688
+ for (const layer of after.layers) {
2689
+ const old = before.layers.find((item) => item.id === layer.id)?.strokes.length ?? 0;
2690
+ for (let i = old; i < layer.strokes.length; i++) added.push({
2691
+ layer: layer.id,
2692
+ stroke: layer.strokes[i]
2693
+ });
2694
+ }
2695
+ const order = strokeOrders.get(after);
2696
+ if (order?.length === added.length) {
2697
+ const additions = new Map(added.map(({ stroke, layer }) => [stroke, layer]));
2698
+ if (order.every(({ stroke, layer }) => additions.get(stroke) === layer)) return order;
2699
+ }
2700
+ return added;
2701
+ }
2702
+ function replaySteps(states) {
2703
+ const steps = [];
2704
+ for (let index = 1; index < states.length; index++) {
2705
+ const before = states[index - 1], after = states[index];
2706
+ if (before === after) continue;
2707
+ const added = appendedStrokes(before, after);
2708
+ steps.push(added?.length ? {
2709
+ type: "draw",
2710
+ before,
2711
+ after,
2712
+ added
2713
+ } : {
2714
+ type: "jump",
2715
+ before,
2716
+ after,
2717
+ added: []
2718
+ });
2688
2719
  }
2720
+ return steps;
2721
+ }
2722
+ const lengthOf = (stroke, width, height) => {
2723
+ const points = stroke.points;
2724
+ let total = 0;
2725
+ for (let i = 1; i < points.length; i++) total += Math.hypot((points[i].x - points[i - 1].x) * width, (points[i].y - points[i - 1].y) * height);
2726
+ return total;
2689
2727
  };
2690
- const finite = (value, min, max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
2691
- function applySketchCommands(source, commands, report) {
2692
- if (!Array.isArray(commands) || !commands.length || commands.length > 256) throw Error("Expected 1–256 commands");
2693
- let doc = identifyObjects(source);
2694
- commands = expandSvgCommands(commands, doc, report);
2695
- for (let command of commands) {
2696
- if (!command || typeof command !== "object") throw Error("Invalid command");
2697
- if (command.op === "stroke") command = expandSketchPreset(command);
2698
- if (command.op === "resize") {
2699
- doc = resizeSketch(doc, command.ratio);
2700
- continue;
2728
+ const OUTLINE_SHARE = .3;
2729
+ const paths = /* @__PURE__ */ new WeakMap();
2730
+ function strokePath(stroke) {
2731
+ const [first, last] = [stroke.points[0], stroke.points.at(-1)];
2732
+ if (!first || stroke.shape === "text" || stroke.shape === "eraser") return void 0;
2733
+ switch (stroke.shape) {
2734
+ case "line":
2735
+ case "arrow": return [first, last];
2736
+ case "bezier": return flattenSketchCurve(stroke, 1024, 1024);
2737
+ case "polygon": return [...stroke.points, first];
2738
+ case "rectangle": return [
2739
+ first,
2740
+ {
2741
+ x: last.x,
2742
+ y: first.y
2743
+ },
2744
+ last,
2745
+ {
2746
+ x: first.x,
2747
+ y: last.y
2748
+ },
2749
+ first
2750
+ ];
2751
+ case "circle": {
2752
+ const cx = (first.x + last.x) / 2, cy = (first.y + last.y) / 2, rx = Math.abs(last.x - first.x) / 2, ry = Math.abs(last.y - first.y) / 2;
2753
+ return Array.from({ length: 49 }, (_, i) => ({
2754
+ x: cx + rx * Math.cos(i / 48 * Math.PI * 2),
2755
+ y: cy + ry * Math.sin(i / 48 * Math.PI * 2)
2756
+ }));
2701
2757
  }
2702
- if (command.op === "layer") {
2703
- if (![
2704
- "add",
2705
- "select",
2706
- "rename",
2707
- "visible",
2708
- "duplicate",
2709
- "up",
2710
- "down",
2711
- "delete",
2712
- "clear",
2713
- "blend"
2714
- ].includes(command.action)) throw Error("Unknown layer action");
2715
- if (command.action === "add") {
2716
- const id = command.id ?? doc.nextId, after = command.after ?? doc.active;
2717
- if (!Number.isSafeInteger(id) || id < 1 || id === Number.MAX_SAFE_INTEGER || doc.layers.some((l) => l.id === id)) throw Error("New layer id must be a unique positive integer; omit id to allocate automatically");
2718
- const next = changeSketchLayer(doc, "add", after);
2719
- if (next === doc) throw Error(doc.layers.length >= 8 ? "Cannot add layer: the board already has 8 layers, the most it holds. Draw on an existing layer, or delete or merge one first." : "Cannot add layer: after must be the id of an existing layer");
2720
- doc = {
2721
- ...next,
2722
- active: id,
2723
- nextId: Math.max(next.nextId, id + 1),
2724
- layers: next.layers.map((l) => l.id === next.active ? {
2725
- ...l,
2726
- id,
2727
- name: String(command.value ?? "").trim().slice(0, 40)
2728
- } : l)
2729
- };
2730
- continue;
2758
+ default: return stroke.points;
2759
+ }
2760
+ }
2761
+ function partialStroke(stroke, fraction) {
2762
+ if (fraction >= 1) return stroke;
2763
+ if (!(fraction > 0)) return {
2764
+ ...stroke,
2765
+ opacity: 0
2766
+ };
2767
+ const filled = stroke.fill && stroke.shape !== "pen";
2768
+ if (filled && !stroke.gradient && fraction >= OUTLINE_SHARE && stroke.shape !== "text") {
2769
+ const reveal = (fraction - OUTLINE_SHARE) / (1 - OUTLINE_SHARE);
2770
+ const stops = [
2771
+ {
2772
+ offset: 0,
2773
+ color: stroke.color
2774
+ },
2775
+ {
2776
+ offset: reveal,
2777
+ color: stroke.color
2778
+ },
2779
+ {
2780
+ offset: Math.min(1, reveal + .002),
2781
+ color: stroke.color,
2782
+ opacity: 0
2783
+ },
2784
+ {
2785
+ offset: 1,
2786
+ color: stroke.color,
2787
+ opacity: 0
2731
2788
  }
2732
- const next = changeSketchLayer(doc, command.action, command.id ?? doc.active, command.value);
2733
- if (next === doc) throw Error("Layer action unavailable; inspect the document first");
2734
- doc = next;
2735
- continue;
2736
- }
2737
- if (command.op === "object") {
2738
- const layer = doc.layers.find((l) => l.id === (command.layer ?? doc.active)), index = layer?.strokes.findIndex((s) => s.id === command.id);
2739
- if (!layer?.visible || index < 0 || index === void 0) throw Error("Object missing or hidden; inspect again");
2740
- const strokes = layer.strokes.slice(), original = strokes[index];
2741
- if (command.action === "delete") strokes.splice(index, 1);
2742
- else if (command.action === "duplicate") strokes.splice(index + 1, 0, {
2743
- ...original,
2744
- id: crypto.randomUUID(),
2745
- points: original.points.map((p) => ({ ...p }))
2746
- });
2747
- else if (command.action === "update") {
2748
- const patch = command.patch ?? {};
2749
- if (Object.keys(patch).some((k) => ![
2750
- "color",
2751
- "width",
2752
- "opacity",
2753
- "fill",
2789
+ ];
2790
+ return {
2791
+ ...stroke,
2792
+ gradient: {
2793
+ type: "linear",
2794
+ x1: 0,
2795
+ y1: 0,
2796
+ x2: 0,
2797
+ y2: 1,
2798
+ stops
2799
+ }
2800
+ };
2801
+ }
2802
+ let measured = paths.get(stroke);
2803
+ if (!measured) {
2804
+ const path = strokePath(stroke);
2805
+ const lengths = path?.slice(1).map((point, i) => Math.hypot(point.x - path[i].x, point.y - path[i].y));
2806
+ measured = {
2807
+ path,
2808
+ lengths,
2809
+ total: lengths?.reduce((sum, value) => sum + value, 0)
2810
+ };
2811
+ paths.set(stroke, measured);
2812
+ }
2813
+ const { path, lengths, total } = measured;
2814
+ if (!path || path.length < 2) return {
2815
+ ...stroke,
2816
+ opacity: (stroke.opacity ?? 1) * Math.max(0, fraction)
2817
+ };
2818
+ const share = filled ? fraction / OUTLINE_SHARE : fraction;
2819
+ let remaining = total * Math.max(0, share);
2820
+ const points = [path[0]];
2821
+ for (let i = 0; i < lengths.length; i++) {
2822
+ if (remaining >= lengths[i]) {
2823
+ points.push(path[i + 1]);
2824
+ remaining -= lengths[i];
2825
+ continue;
2826
+ }
2827
+ const part = lengths[i] ? remaining / lengths[i] : 0;
2828
+ points.push({
2829
+ x: path[i].x + (path[i + 1].x - path[i].x) * part,
2830
+ y: path[i].y + (path[i + 1].y - path[i].y) * part
2831
+ });
2832
+ break;
2833
+ }
2834
+ if (points.length < 2) return {
2835
+ ...stroke,
2836
+ opacity: 0
2837
+ };
2838
+ const { gradient, blur, ...rest } = stroke;
2839
+ return filled ? {
2840
+ ...rest,
2841
+ shape: "pen",
2842
+ fill: false,
2843
+ width: Math.max(2, Math.min(3, stroke.width ?? 2)),
2844
+ opacity: .85,
2845
+ points
2846
+ } : {
2847
+ ...rest,
2848
+ shape: "pen",
2849
+ fill: false,
2850
+ points,
2851
+ ...blur ? { blur } : {}
2852
+ };
2853
+ }
2854
+ function strokeWeight(stroke, width = 1024, height = 1024) {
2855
+ if (stroke.fill && stroke.shape !== "pen") return 2.2;
2856
+ return .6 + Math.min(4, Math.sqrt(lengthOf(stroke, width, height)) / 8);
2857
+ }
2858
+ function planReplay(steps, duration, width = 1024, height = 1024) {
2859
+ const items = steps.map((step) => {
2860
+ const weights = step.added.map((item) => strokeWeight(item.stroke, width, height));
2861
+ return {
2862
+ step,
2863
+ weights,
2864
+ weight: weights.reduce((sum, value) => sum + value, 0)
2865
+ };
2866
+ });
2867
+ const total = items.reduce((sum, item) => sum + item.weight + 6, 0) || 1;
2868
+ let at = 0;
2869
+ return items.map(({ step, weights, weight }) => {
2870
+ const span = duration * (weight + 6) / total;
2871
+ const drawing = span - Math.min(span * .12, 500);
2872
+ let cursor = at;
2873
+ const strokes = step.added.map((item, index) => {
2874
+ const own = drawing * weights[index] / weight;
2875
+ const entry = {
2876
+ ...item,
2877
+ start: cursor,
2878
+ end: cursor + own
2879
+ };
2880
+ cursor += own;
2881
+ return entry;
2882
+ });
2883
+ const planned = {
2884
+ step,
2885
+ start: at,
2886
+ end: at + span,
2887
+ strokes
2888
+ };
2889
+ at += span;
2890
+ return planned;
2891
+ });
2892
+ }
2893
+ function firstEndingAfter(items, time) {
2894
+ let low = 0, high = items.length;
2895
+ while (low < high) {
2896
+ const middle = low + high >>> 1;
2897
+ if (items[middle].end <= time) low = middle + 1;
2898
+ else high = middle;
2899
+ }
2900
+ return low;
2901
+ }
2902
+ function replayFrame(plan, time) {
2903
+ if (!plan.length) return void 0;
2904
+ const last = plan.at(-1);
2905
+ if (time >= last.end) return { doc: last.step.after };
2906
+ const item = plan[firstEndingAfter(plan, time)] ?? last;
2907
+ if (item.step.type === "jump" || !item.strokes.length) return { doc: time < item.start + (item.end - item.start) / 2 ? item.step.before : item.step.after };
2908
+ const next = firstEndingAfter(item.strokes, time);
2909
+ if (next === item.strokes.length) return { doc: item.step.after };
2910
+ const current = item.strokes[next];
2911
+ const fraction = Math.max(0, (time - current.start) / (current.end - current.start));
2912
+ const eased = fraction * fraction * (3 - 2 * fraction);
2913
+ const extras = /* @__PURE__ */ new Map();
2914
+ for (let index = 0; index <= next; index++) {
2915
+ const { layer, stroke } = item.strokes[index];
2916
+ const list = extras.get(layer) ?? [];
2917
+ list.push(index === next ? partialStroke(stroke, eased) : stroke);
2918
+ extras.set(layer, list);
2919
+ }
2920
+ const layers = item.step.after.layers.map((layer) => {
2921
+ const base = item.step.before.layers.find((old) => old.id === layer.id)?.strokes ?? [];
2922
+ const added = extras.get(layer.id);
2923
+ return {
2924
+ ...layer,
2925
+ strokes: added ? [...base, ...added] : base
2926
+ };
2927
+ });
2928
+ return {
2929
+ doc: {
2930
+ ...item.step.after,
2931
+ layers
2932
+ },
2933
+ moving: current.layer
2934
+ };
2935
+ }
2936
+ //#endregion
2937
+ //#region src/sketch-commands.js
2938
+ const MAX_SKETCH_POINTS = 2e5;
2939
+ const stale = (message) => Object.assign(Error(message), { code: "SKETCH_STALE" });
2940
+ const SKETCH_COMMAND_HELP = {
2941
+ coordinates: "Assign short meaningful stroke id values for later edits. Text uses two opposite box corners and text content; width is font size in pixels, automatic fitting within the box. Arrow uses two endpoints. Normalized x/y in [0,1]; width is canvas pixels. Read documentId and revision before editing.",
2942
+ shapes: "line: exactly two endpoints; rectangle/circle (ellipse alias accepted): exactly two opposite bounding-box corners (circle draws an ellipse within that box); polygon: three or more vertices, closed automatically; pen: ordered path points. bezier: start point, then groups of control1/control2/end; use 4 points for one cubic curve, max 64 segments. Prefer bezier for smooth designed curves instead of many pen samples. fill:true closes and fills the curve. fill:true fills rectangle/circle/polygon. Layers and strokes paint in list order, later ones on top. All commands needed for drawing are described here; no source-code search is required.",
2943
+ guide: "How to draw well here. 1) Plan first: list the parts, the drawing order (back to front) and the rough position and size as fractions of the canvas; keep the plan short. 2) Work big to small and verify after every stage (apply returns progress; look:true or preview shows the result): silhouette and big colour areas, then form and shading, then outlines and small details. 3) Place by measuring, not by eye: with a reference use measure (palette, regions, points, scan) to get exact colours, sizes and edge positions; without one use preview grid and keep proportions (an 8-head figure for realistic bodies, 5–6 heads for anime, a larger head for cute). 4) Depth: every form gets five tones, a highlight, light, half-tone, form shadow and a reflected-light edge; shadows are tinted (blue, purple, teal), never pure black; use 4–8 stop gradients with hue shifts, blur for glow, haze and soft shadows. 5) Build limbs and hair as long tapered shapes (a few overlapping bezier or path shapes), cover joints with rounded shapes, draw the face last on top of the head: eyes (iris, pupil, highlight, lashes), brows, nose and mouth with the right size and spacing, check them with preview box zoomed in. 6) Group related shapes on one layer (hair, face, clothes, background) so they can be adjusted or hidden. 7) Undo a stage that made things worse instead of painting over it. 8) Repeated details (strands, pleats, stars) can be generated by a short script and sent as one svg command. 9) Refine region by region (see below). 10) Stop when the error of every region stops falling or the zoomed previews look right; do not add detail that the picture does not have. When the whole picture is roughly right, do refinement passes region by region instead of stopping: split the picture into its parts (for a figure: head and face, each mass of hair, torso, each arm, each leg, shoes and small accessories). For every part, call preview mode side with box set to that part and grid on (zoomed up to 3x) and look at reference and drawing next to each other, then measure with box on the same part and use scan along an edge to read exact positions; list the three biggest differences (edge position, size, colour, missing detail), fix them with targeted object updates or a replacement shape, and check progress. A part is done when its error stops falling or the zoomed pair looks the same; then go to the next part. Make at least one pass over every part before you finish, and never end with the first full draft.",
2944
+ commands: {
2945
+ preset: "triangle/diamond/star: {op:\"stroke\",id:\"badge\",shape:\"star\",points:[{x:0.1,y:0.1},{x:0.3,y:0.3}],color:\"#ffcc00\",fill:true}. Two opposite box corners; stored as editable polygon. Inspect objectId for one object without repeating full help.",
2946
+ stroke: "{op:\"stroke\",layer:1,shape:\"pen|line|arrow|text|rectangle|circle|polygon|bezier\",color:\"#rrggbb\",width:2,opacity:1,fill:false,points:[{x:0.1,y:0.1},...]}. Optional on any stroke: blend:\"multiply|screen|overlay|soft-light|hard-light|color-dodge|color-burn|darken|lighten|lighter\" (shadows multiply, glows screen or lighter; blends with what is already painted on the same layer; a whole layer can blend with the layers under it: {op:\"layer\",action:\"blend\",id:2,value:\"multiply\"}, value normal to clear) and clip:{shape:\"polygon|bezier|rectangle|circle\",points:[...]} keeps the stroke inside that shape, so shading and highlights stay inside the form they shade (clip.shape none removes it). Optional on filled shapes: gradient:{type:\"linear\",x1:0,y1:0,x2:0,y2:1,stops:[{offset:0,color:\"#ffcc66\"},{offset:1,color:\"#ff6644\",opacity:0.8}]} or {type:\"radial\",cx:0.5,cy:0.5,r:0.5,stops:[...]} (coordinates relative to the shape's own box, so moving or scaling the object keeps it); blur:12 softens any stroke by that many canvas pixels (glow, shadow, haze). Patch gradient:{type:\"none\"} or blur:0 to remove.",
2947
+ layer: "Add: {op:\"layer\",action:\"add\",value:\"name\"}; optional id is the NEW unique integer ID, otherwise allocated automatically. after is the existing insertion anchor, defaults to active layer. Other actions: {op:\"layer\",action:\"select|rename|visible|duplicate|up|down|delete|clear\",id:1,value:\"name\"}; id targets an existing layer.",
2948
+ curve: "Prefer {op:\"stroke\",shape:\"bezier\",start:{x:0,y:0},segments:[{control1:{x:0.2,y:0},control2:{x:0.8,y:1},end:{x:1,y:1}}],color:\"#123456\"}. Each segment has exactly two controls and an endpoint; no point counting required. Legacy points arrays still accepted. Do not provide both forms.",
2949
+ object: "{op:\"object\",layer:1,id:\"title\",action:\"update|duplicate|delete\",patch:{color:\"#0088ff\",text:\"Title\"},transform:{dx:0.05,dy:0,scaleX:1,scaleY:1}}. All patch and transform fields optional. Inspect returns object IDs and bounds. Prefer targeted edits over redrawing layers.",
2950
+ resize: "{op:\"resize\",ratio:\"1:1|4:3|3:4|16:9|9:16\"}",
2951
+ svg: "{op:\"svg\",svg:\"<svg viewBox=\\\"0 0 1024 768\\\">...</svg>\",layer:1}. Fastest way to draw: send a whole scene as SVG (path with M L H V C S Q T A Z, rect, circle, ellipse, line, polyline, polygon, g, use, transform, fill/stroke/opacity, style=\"...\"); it becomes native editable strokes. The viewBox must match the canvas size (use the width and height from inspect; 4:3 is 1024x768). mix-blend-mode on an element becomes blend, and clip-path=\"url(#id)\" with a clipPath holding one path, rect, circle, ellipse or polygon becomes clip (use the same clipPath for all the shading of a form). Linear and radial gradients on filled shapes are kept as real gradients (fill=\"url(#id)\", objectBoundingBox or userSpaceOnUse, gradientTransform, stop-opacity); a gradient on a stroke line is flattened to its average color. A filter with feGaussianBlur becomes a soft edge on each shape it covers (glows, shadows, haze, depth of field); other filter effects are ignored with a warning. Text, image, mask, pattern and CSS classes are refused. Coordinates outside the canvas are clamped. One svg command may hold up to 200000 characters."
2952
+ },
2953
+ measure: "Action measure (not a command): {action:\"measure\",runId,documentId,columns:6,rows:8,box:{x:0,y:0,width:1,height:1},points:[{x:0.5,y:0.3}],palette:8,regions:8,scan:{x1:0,y1:0.5,x2:1,y2:0.5}} compares the drawing with the reference picture and returns error (0 = identical, percent of the colour range), the worst cells (box in 0..1, error, reference and drawing colour as #rrggbb, tone = how much lighter (+) or darker (-) the drawing is than the reference, 0..255; cells:true returns every cell instead of the worst ten, a full colour-error map you can work through), for points the reference and drawing colour there, with palette the main colours of the reference (share of the area), with regions where each main colour sits (share, centre, box that holds most of it), and with scan a ruler laid along a line: the colour runs of the reference and of your drawing along it, with their start and end positions, so you can place edges exactly (scan a row across the hair, a column through the body). box limits it to one part. Every apply also returns progress (error now, error before, three worst cells), so you can see whether a stage helped. Fix the worst cell first, read exact colours from the reference instead of guessing.",
2954
+ undo: "Action undo: {action:\"undo\",runId,documentId,revision (optional),steps:1} takes back the last batches you applied (one per apply) and returns the new revision. Use it when a stage made things worse instead of painting over it.",
2955
+ preview: "Action preview: {action:\"preview\",mode:\"side|diff\",compare:true,grid:true,box:{x:0.3,y:0.1,width:0.4,height:0.3}}. mode side puts the reference and your drawing next to each other; mode diff adds a difference heat map (dark = matches, blue to red = increasingly different in brightness, colour or edges); compare blends both 50/50; grid labels canvas pixels; box zooms into one part (normalised x,y,width,height) so you can check eyes, hands, edges. Apply with look:true returns the side-by-side picture with the result.",
2956
+ limits: {
2957
+ strokes: MAX_SKETCH_STROKES,
2958
+ pointsPerStroke: MAX_STROKE_POINTS,
2959
+ pointsTotal: MAX_SKETCH_POINTS,
2960
+ commandsPerBatch: 256,
2961
+ svgCharacters: MAX_SVG_CHARACTERS
2962
+ }
2963
+ };
2964
+ const finite = (value, min, max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
2965
+ function applySketchCommands(source, commands, report) {
2966
+ if (!Array.isArray(commands) || !commands.length || commands.length > 256) throw Error("Expected 1–256 commands");
2967
+ let doc = identifyObjects(source);
2968
+ commands = expandSvgCommands(commands, doc, report);
2969
+ const strokesInOrder = [];
2970
+ for (let command of commands) {
2971
+ if (!command || typeof command !== "object") throw Error("Invalid command");
2972
+ if (command.op === "stroke") command = expandSketchPreset(command);
2973
+ if (command.op === "resize") {
2974
+ doc = resizeSketch(doc, command.ratio);
2975
+ continue;
2976
+ }
2977
+ if (command.op === "layer") {
2978
+ if (![
2979
+ "add",
2980
+ "select",
2981
+ "rename",
2982
+ "visible",
2983
+ "duplicate",
2984
+ "up",
2985
+ "down",
2986
+ "delete",
2987
+ "clear",
2988
+ "blend"
2989
+ ].includes(command.action)) throw Error("Unknown layer action");
2990
+ if (command.action === "add") {
2991
+ const id = command.id ?? doc.nextId, after = command.after ?? doc.active;
2992
+ if (!Number.isSafeInteger(id) || id < 1 || id === Number.MAX_SAFE_INTEGER || doc.layers.some((l) => l.id === id)) throw Error("New layer id must be a unique positive integer; omit id to allocate automatically");
2993
+ const next = changeSketchLayer(doc, "add", after);
2994
+ if (next === doc) throw Error(doc.layers.length >= 8 ? "Cannot add layer: the board already has 8 layers, the most it holds. Draw on an existing layer, or delete or merge one first." : "Cannot add layer: after must be the id of an existing layer");
2995
+ doc = {
2996
+ ...next,
2997
+ active: id,
2998
+ nextId: Math.max(next.nextId, id + 1),
2999
+ layers: next.layers.map((l) => l.id === next.active ? {
3000
+ ...l,
3001
+ id,
3002
+ name: String(command.value ?? "").trim().slice(0, 40)
3003
+ } : l)
3004
+ };
3005
+ continue;
3006
+ }
3007
+ const next = changeSketchLayer(doc, command.action, command.id ?? doc.active, command.value);
3008
+ if (next === doc) throw Error("Layer action unavailable; inspect the document first");
3009
+ doc = next;
3010
+ continue;
3011
+ }
3012
+ if (command.op === "object") {
3013
+ const layer = doc.layers.find((l) => l.id === (command.layer ?? doc.active)), index = layer?.strokes.findIndex((s) => s.id === command.id);
3014
+ if (!layer?.visible || index < 0 || index === void 0) throw Error("Object missing or hidden; inspect again");
3015
+ const strokes = layer.strokes.slice(), original = strokes[index];
3016
+ if (command.action === "delete") strokes.splice(index, 1);
3017
+ else if (command.action === "duplicate") strokes.splice(index + 1, 0, {
3018
+ ...original,
3019
+ id: crypto.randomUUID(),
3020
+ points: original.points.map((p) => ({ ...p }))
3021
+ });
3022
+ else if (command.action === "update") {
3023
+ const patch = command.patch ?? {};
3024
+ if (Object.keys(patch).some((k) => ![
3025
+ "color",
3026
+ "width",
3027
+ "opacity",
3028
+ "fill",
2754
3029
  "text",
2755
3030
  "points",
2756
3031
  "gradient",
@@ -2854,6 +3129,10 @@ window.__ModuleLoader__.load({
2854
3129
  y: p.y
2855
3130
  }))
2856
3131
  };
3132
+ strokesInOrder.push({
3133
+ layer: layer.id,
3134
+ stroke
3135
+ });
2857
3136
  doc = {
2858
3137
  ...doc,
2859
3138
  layers: doc.layers.map((item) => item === layer ? {
@@ -2865,6 +3144,7 @@ window.__ModuleLoader__.load({
2865
3144
  const strokes = strokeCount(doc), points = doc.layers.reduce((n, l) => n + l.strokes.reduce((m, s) => m + s.points.length, 0), 0);
2866
3145
  if (strokes > 2e3) throw Error(`Sketch would hold ${strokes} strokes; the limit is ${MAX_SKETCH_STROKES}. Merge shapes or drop small details, then send this batch again`);
2867
3146
  if (points > 2e5) throw Error(`Sketch would hold ${points} points; the limit is ${MAX_SKETCH_POINTS}. Use fewer or simpler paths, then send this batch again`);
3147
+ recordReplayStrokeOrder(doc, strokesInOrder);
2868
3148
  return doc;
2869
3149
  }
2870
3150
  function createSketchCommandSession(adapter) {
@@ -3445,29 +3725,9 @@ window.__ModuleLoader__.load({
3445
3725
  return Math.max(1, Math.min(256, width + direction * 2));
3446
3726
  }
3447
3727
  //#endregion
3448
- //#region src/sketch-session-state.js
3449
- function createSketchSessionState() {
3450
- const ref = (current) => ({ current });
3451
- return {
3452
- doc: ref(createSketchLayers()),
3453
- undo: ref([]),
3454
- redo: ref([]),
3455
- images: ref(/* @__PURE__ */ new Map()),
3456
- timeline: ref([]),
3457
- saved: ref(null),
3458
- dirty: ref(false),
3459
- documentId: ref(crypto.randomUUID()),
3460
- documentRevision: ref(0),
3461
- restoreId: ref(null),
3462
- mounts: 0,
3463
- agentAdapter: ref({}),
3464
- agentSession: ref(null),
3465
- agentRun: ref(null)
3466
- };
3467
- }
3468
- //#endregion
3469
3728
  //#region src/sketch-layer-renderer.js
3470
3729
  const NO_IMAGES = /* @__PURE__ */ new Map();
3730
+ const movingSurfaces = /* @__PURE__ */ new WeakMap();
3471
3731
  const surface = (width, height) => {
3472
3732
  const c = document.createElement("canvas");
3473
3733
  c.width = width;
@@ -3483,11 +3743,8 @@ window.__ModuleLoader__.load({
3483
3743
  for (const layer of doc.layers) {
3484
3744
  if (!layer.visible) continue;
3485
3745
  let entry = cache.get(layer.id);
3486
- if (!entry || entry.surface.width !== size || entry.surface.height !== height) {
3487
- entry = {
3488
- surface: surface(size, height),
3489
- base: surface(size, height)
3490
- };
3746
+ if (!entry || entry.base.width !== size || entry.base.height !== height) {
3747
+ entry = { base: surface(size, height) };
3491
3748
  cache.set(layer.id, entry);
3492
3749
  }
3493
3750
  const moving = layer.id === activeLayer;
@@ -3509,11 +3766,16 @@ window.__ModuleLoader__.load({
3509
3766
  }
3510
3767
  context.globalCompositeOperation = layer.blend ?? "source-over";
3511
3768
  if (moving) {
3512
- const ctx = entry.surface.getContext("2d");
3769
+ let movingSurface = movingSurfaces.get(cache);
3770
+ if (!movingSurface || movingSurface.width !== size || movingSurface.height !== height) {
3771
+ movingSurface = surface(size, height);
3772
+ movingSurfaces.set(cache, movingSurface);
3773
+ }
3774
+ const ctx = movingSurface.getContext("2d");
3513
3775
  ctx.clearRect(0, 0, size, height);
3514
3776
  ctx.drawImage(entry.base, 0, 0);
3515
3777
  paintSketch(ctx, layer.strokes, size, true, height, layer.strokes.length - 1);
3516
- context.drawImage(entry.surface, 0, 0);
3778
+ context.drawImage(movingSurface, 0, 0);
3517
3779
  } else context.drawImage(entry.base, 0, 0);
3518
3780
  context.globalCompositeOperation = "source-over";
3519
3781
  }
@@ -3771,364 +4033,139 @@ window.__ModuleLoader__.load({
3771
4033
  const refresh = async () => setRows(await sketchDrafts("list"));
3772
4034
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3773
4035
  ref: host,
3774
- className: "codexSketchFiles",
3775
- onKeyDown: (e) => {
3776
- if (e.key === "Escape" && open) {
3777
- e.preventDefault();
3778
- e.stopPropagation();
3779
- setOpen(false);
3780
- }
3781
- },
3782
- children: [
3783
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3784
- type: "button",
3785
- disabled: disabled || working,
3786
- "aria-expanded": open,
3787
- onClick: () => {
3788
- setOpen(!open);
3789
- if (!open) run(refresh);
3790
- },
3791
- children: t("sketchFiles")
3792
- }),
3793
- extra,
3794
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
3795
- ref: input,
3796
- type: "file",
3797
- accept: SKETCH_FILE_ACCEPT,
3798
- hidden: true,
3799
- onChange: (e) => {
3800
- const file = e.target.files?.[0];
3801
- e.target.value = "";
3802
- if (file) run(async () => {
3803
- await importImage(file);
3804
- setOpen(false);
3805
- });
3806
- }
3807
- }),
3808
- open ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
3809
- className: "codexSketchFilePanel",
3810
- "aria-label": t("sketchFiles"),
3811
- children: [
3812
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3813
- className: "codexSketchFileActions",
3814
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3815
- type: "button",
3816
- disabled: disabled || working,
3817
- onClick: () => void run(async () => {
3818
- await fresh();
3819
- setName("");
3820
- setOpen(false);
3821
- }),
3822
- children: t("sketchNew")
3823
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3824
- type: "button",
3825
- disabled: disabled || working,
3826
- onClick: () => input.current.click(),
3827
- children: t("sketchImport")
3828
- })]
3829
- }),
3830
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
3831
- "aria-label": t("sketchDraftName"),
3832
- placeholder: t("sketchDraftName"),
3833
- value: name,
3834
- maxLength: 60,
3835
- onChange: (e) => setName(e.target.value)
3836
- }),
3837
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3838
- type: "button",
3839
- disabled: disabled || working,
3840
- onClick: () => void run(async () => {
3841
- await save(name);
3842
- await refresh();
3843
- }),
3844
- children: t("sketchSave")
3845
- }),
3846
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3847
- className: "codexSketchExportFormats codexSketchSegment",
3848
- role: "group",
3849
- "aria-label": t("sketchExportFormat"),
3850
- children: [["png", "PNG"], ["draft", t("sketchEditableFile")]].map(([value, label]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3851
- type: "button",
3852
- "aria-pressed": format === value,
3853
- disabled: disabled || working,
3854
- onClick: () => setFormat(value),
3855
- children: label
3856
- }, value))
3857
- }),
3858
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3859
- type: "button",
3860
- disabled: disabled || working || !hasContent,
3861
- onClick: () => void run(async () => {
3862
- await download(format);
3863
- setOpen(false);
3864
- }),
3865
- children: t("sketchDownload")
3866
- }),
3867
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: t("sketchFormatHint") }),
3868
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: t("sketchLocalDrafts") }),
3869
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3870
- className: "codexSketchDraftList",
3871
- children: rows.map((row) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3872
- type: "button",
3873
- disabled: disabled || working,
3874
- onClick: () => void run(async () => {
3875
- await load(row);
3876
- setName(row.name);
3877
- setOpen(false);
3878
- }),
3879
- children: row.name
3880
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3881
- type: "button",
3882
- disabled: disabled || working,
3883
- "aria-label": `${t("sketchDeleteDraft")} ${row.name}`,
3884
- onClick: () => {
3885
- if (remove !== row.id) {
3886
- setRemove(row.id);
3887
- return;
3888
- }
3889
- run(async () => {
3890
- await sketchDrafts("delete", row.id);
3891
- setRemove(null);
3892
- await refresh();
3893
- });
3894
- },
3895
- children: remove === row.id ? t("sketchDeleteConfirm") : t("sketchDeleteDraft")
3896
- })] }, row.id))
3897
- }),
3898
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3899
- type: "button",
3900
- onClick: () => setOpen(false),
3901
- children: t("sketchFileClose")
3902
- })
3903
- ]
3904
- }) : null
3905
- ]
3906
- });
3907
- }
3908
- //#endregion
3909
- //#region src/sketch-replay.js
3910
- const MAX_REPLAY_STATES = 2e3;
3911
- function recordReplayState(states, doc) {
3912
- if (states.at(-1) === doc) return;
3913
- states.push(doc);
3914
- if (states.length > 2e3) states.splice(0, states.length - MAX_REPLAY_STATES);
3915
- }
3916
- function appendedStrokes(before, after) {
3917
- for (const layer of before.layers) {
3918
- const next = after.layers.find((item) => item.id === layer.id);
3919
- if (!next || next.image !== layer.image || layer.strokes.length > next.strokes.length || layer.strokes.some((stroke, i) => stroke !== next.strokes[i])) return void 0;
3920
- }
3921
- const added = [];
3922
- for (const layer of after.layers) {
3923
- const old = before.layers.find((item) => item.id === layer.id)?.strokes.length ?? 0;
3924
- for (let i = old; i < layer.strokes.length; i++) added.push({
3925
- layer: layer.id,
3926
- stroke: layer.strokes[i]
3927
- });
3928
- }
3929
- return added;
3930
- }
3931
- function replaySteps(states) {
3932
- const steps = [];
3933
- for (let index = 1; index < states.length; index++) {
3934
- const before = states[index - 1], after = states[index];
3935
- if (before === after) continue;
3936
- const added = appendedStrokes(before, after);
3937
- steps.push(added?.length ? {
3938
- type: "draw",
3939
- before,
3940
- after,
3941
- added
3942
- } : {
3943
- type: "jump",
3944
- before,
3945
- after,
3946
- added: []
3947
- });
3948
- }
3949
- return steps;
3950
- }
3951
- const lengthOf = (stroke, width, height) => {
3952
- const points = stroke.points;
3953
- let total = 0;
3954
- for (let i = 1; i < points.length; i++) total += Math.hypot((points[i].x - points[i - 1].x) * width, (points[i].y - points[i - 1].y) * height);
3955
- return total;
3956
- };
3957
- const OUTLINE_SHARE = .3;
3958
- function strokePath(stroke) {
3959
- const [first, last] = [stroke.points[0], stroke.points.at(-1)];
3960
- if (!first || stroke.shape === "text" || stroke.shape === "eraser") return void 0;
3961
- switch (stroke.shape) {
3962
- case "line":
3963
- case "arrow": return [first, last];
3964
- case "bezier": return flattenSketchCurve(stroke, 1024, 1024);
3965
- case "polygon": return [...stroke.points, first];
3966
- case "rectangle": return [
3967
- first,
3968
- {
3969
- x: last.x,
3970
- y: first.y
3971
- },
3972
- last,
3973
- {
3974
- x: first.x,
3975
- y: last.y
3976
- },
3977
- first
3978
- ];
3979
- case "circle": {
3980
- const cx = (first.x + last.x) / 2, cy = (first.y + last.y) / 2, rx = Math.abs(last.x - first.x) / 2, ry = Math.abs(last.y - first.y) / 2;
3981
- return Array.from({ length: 49 }, (_, i) => ({
3982
- x: cx + rx * Math.cos(i / 48 * Math.PI * 2),
3983
- y: cy + ry * Math.sin(i / 48 * Math.PI * 2)
3984
- }));
3985
- }
3986
- default: return stroke.points;
3987
- }
3988
- }
3989
- function partialStroke(stroke, fraction) {
3990
- if (fraction >= 1) return stroke;
3991
- if (!(fraction > 0)) return {
3992
- ...stroke,
3993
- opacity: 0
3994
- };
3995
- const filled = stroke.fill && stroke.shape !== "pen";
3996
- if (filled && !stroke.gradient && fraction >= OUTLINE_SHARE && stroke.shape !== "text") {
3997
- const reveal = (fraction - OUTLINE_SHARE) / (1 - OUTLINE_SHARE);
3998
- const stops = [
3999
- {
4000
- offset: 0,
4001
- color: stroke.color
4002
- },
4003
- {
4004
- offset: reveal,
4005
- color: stroke.color
4006
- },
4007
- {
4008
- offset: Math.min(1, reveal + .002),
4009
- color: stroke.color,
4010
- opacity: 0
4011
- },
4012
- {
4013
- offset: 1,
4014
- color: stroke.color,
4015
- opacity: 0
4016
- }
4017
- ];
4018
- return {
4019
- ...stroke,
4020
- gradient: {
4021
- type: "linear",
4022
- x1: 0,
4023
- y1: 0,
4024
- x2: 0,
4025
- y2: 1,
4026
- stops
4027
- }
4028
- };
4029
- }
4030
- const path = strokePath(stroke);
4031
- if (!path || path.length < 2) return {
4032
- ...stroke,
4033
- opacity: (stroke.opacity ?? 1) * Math.max(0, fraction)
4034
- };
4035
- const share = filled ? fraction / OUTLINE_SHARE : fraction;
4036
- const lengths = path.slice(1).map((point, i) => Math.hypot(point.x - path[i].x, point.y - path[i].y));
4037
- let remaining = lengths.reduce((sum, value) => sum + value, 0) * Math.max(0, share);
4038
- const points = [path[0]];
4039
- for (let i = 0; i < lengths.length; i++) {
4040
- if (remaining >= lengths[i]) {
4041
- points.push(path[i + 1]);
4042
- remaining -= lengths[i];
4043
- continue;
4044
- }
4045
- const part = lengths[i] ? remaining / lengths[i] : 0;
4046
- points.push({
4047
- x: path[i].x + (path[i + 1].x - path[i].x) * part,
4048
- y: path[i].y + (path[i + 1].y - path[i].y) * part
4049
- });
4050
- break;
4051
- }
4052
- if (points.length < 2) return {
4053
- ...stroke,
4054
- opacity: 0
4055
- };
4056
- const { gradient, blur, ...rest } = stroke;
4057
- return filled ? {
4058
- ...rest,
4059
- shape: "pen",
4060
- fill: false,
4061
- width: Math.max(2, Math.min(3, stroke.width ?? 2)),
4062
- opacity: .85,
4063
- points
4064
- } : {
4065
- ...rest,
4066
- shape: "pen",
4067
- fill: false,
4068
- points,
4069
- ...blur ? { blur } : {}
4070
- };
4071
- }
4072
- function strokeWeight(stroke, width = 1024, height = 1024) {
4073
- if (stroke.fill && stroke.shape !== "pen") return 2.2;
4074
- return .6 + Math.min(4, Math.sqrt(lengthOf(stroke, width, height)) / 8);
4075
- }
4076
- function planReplay(steps, duration, width = 1024, height = 1024) {
4077
- const items = steps.map((step) => ({
4078
- step,
4079
- weight: step.type === "jump" ? 6 : step.added.reduce((sum, item) => sum + strokeWeight(item.stroke, width, height), 0) + 6
4080
- }));
4081
- const total = items.reduce((sum, item) => sum + item.weight, 0) || 1;
4082
- let at = 0;
4083
- return items.map(({ step, weight }) => {
4084
- const span = duration * weight / total;
4085
- const drawing = span - Math.min(span * .12, 500);
4086
- const drawWeight = step.added.reduce((sum, item) => sum + strokeWeight(item.stroke, width, height), 0) || 1;
4087
- let cursor = at;
4088
- const strokes = step.added.map((item) => {
4089
- const own = drawing * strokeWeight(item.stroke, width, height) / drawWeight;
4090
- const entry = {
4091
- ...item,
4092
- start: cursor,
4093
- end: cursor + own
4094
- };
4095
- cursor += own;
4096
- return entry;
4097
- });
4098
- const planned = {
4099
- step,
4100
- start: at,
4101
- end: at + span,
4102
- strokes
4103
- };
4104
- at += span;
4105
- return planned;
4106
- });
4107
- }
4108
- function replayFrame(plan, time) {
4109
- if (!plan.length) return void 0;
4110
- const last = plan.at(-1);
4111
- if (time >= last.end) return { doc: last.step.after };
4112
- const item = plan.find((entry) => time < entry.end) ?? last;
4113
- if (item.step.type === "jump" || !item.strokes.length) return { doc: time < item.start + (item.end - item.start) / 2 ? item.step.before : item.step.after };
4114
- const done = item.strokes.filter((entry) => time >= entry.end);
4115
- const current = item.strokes.find((entry) => time >= entry.start && time < entry.end);
4116
- const layers = item.step.after.layers.map((layer) => {
4117
- const base = item.step.before.layers.find((old) => old.id === layer.id)?.strokes ?? [];
4118
- const extra = [...done.filter((entry) => entry.layer === layer.id).map((entry) => entry.stroke)];
4119
- if (current?.layer === layer.id) extra.push(partialStroke(current.stroke, (time - current.start) / (current.end - current.start)));
4120
- return {
4121
- ...layer,
4122
- strokes: extra.length ? [...base, ...extra] : base
4123
- };
4124
- });
4125
- return {
4126
- doc: {
4127
- ...item.step.after,
4128
- layers
4036
+ className: "codexSketchFiles",
4037
+ onKeyDown: (e) => {
4038
+ if (e.key === "Escape" && open) {
4039
+ e.preventDefault();
4040
+ e.stopPropagation();
4041
+ setOpen(false);
4042
+ }
4129
4043
  },
4130
- moving: current?.layer
4131
- };
4044
+ children: [
4045
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4046
+ type: "button",
4047
+ disabled: disabled || working,
4048
+ "aria-expanded": open,
4049
+ onClick: () => {
4050
+ setOpen(!open);
4051
+ if (!open) run(refresh);
4052
+ },
4053
+ children: t("sketchFiles")
4054
+ }),
4055
+ extra,
4056
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
4057
+ ref: input,
4058
+ type: "file",
4059
+ accept: SKETCH_FILE_ACCEPT,
4060
+ hidden: true,
4061
+ onChange: (e) => {
4062
+ const file = e.target.files?.[0];
4063
+ e.target.value = "";
4064
+ if (file) run(async () => {
4065
+ await importImage(file);
4066
+ setOpen(false);
4067
+ });
4068
+ }
4069
+ }),
4070
+ open ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
4071
+ className: "codexSketchFilePanel",
4072
+ "aria-label": t("sketchFiles"),
4073
+ children: [
4074
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4075
+ className: "codexSketchFileActions",
4076
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4077
+ type: "button",
4078
+ disabled: disabled || working,
4079
+ onClick: () => void run(async () => {
4080
+ await fresh();
4081
+ setName("");
4082
+ setOpen(false);
4083
+ }),
4084
+ children: t("sketchNew")
4085
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4086
+ type: "button",
4087
+ disabled: disabled || working,
4088
+ onClick: () => input.current.click(),
4089
+ children: t("sketchImport")
4090
+ })]
4091
+ }),
4092
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
4093
+ "aria-label": t("sketchDraftName"),
4094
+ placeholder: t("sketchDraftName"),
4095
+ value: name,
4096
+ maxLength: 60,
4097
+ onChange: (e) => setName(e.target.value)
4098
+ }),
4099
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4100
+ type: "button",
4101
+ disabled: disabled || working,
4102
+ onClick: () => void run(async () => {
4103
+ await save(name);
4104
+ await refresh();
4105
+ }),
4106
+ children: t("sketchSave")
4107
+ }),
4108
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
4109
+ className: "codexSketchExportFormats codexSketchSegment",
4110
+ role: "group",
4111
+ "aria-label": t("sketchExportFormat"),
4112
+ children: [["png", "PNG"], ["draft", t("sketchEditableFile")]].map(([value, label]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4113
+ type: "button",
4114
+ "aria-pressed": format === value,
4115
+ disabled: disabled || working,
4116
+ onClick: () => setFormat(value),
4117
+ children: label
4118
+ }, value))
4119
+ }),
4120
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4121
+ type: "button",
4122
+ disabled: disabled || working || !hasContent,
4123
+ onClick: () => void run(async () => {
4124
+ await download(format);
4125
+ setOpen(false);
4126
+ }),
4127
+ children: t("sketchDownload")
4128
+ }),
4129
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: t("sketchFormatHint") }),
4130
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: t("sketchLocalDrafts") }),
4131
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
4132
+ className: "codexSketchDraftList",
4133
+ children: rows.map((row) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4134
+ type: "button",
4135
+ disabled: disabled || working,
4136
+ onClick: () => void run(async () => {
4137
+ await load(row);
4138
+ setName(row.name);
4139
+ setOpen(false);
4140
+ }),
4141
+ children: row.name
4142
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4143
+ type: "button",
4144
+ disabled: disabled || working,
4145
+ "aria-label": `${t("sketchDeleteDraft")} ${row.name}`,
4146
+ onClick: () => {
4147
+ if (remove !== row.id) {
4148
+ setRemove(row.id);
4149
+ return;
4150
+ }
4151
+ run(async () => {
4152
+ await sketchDrafts("delete", row.id);
4153
+ setRemove(null);
4154
+ await refresh();
4155
+ });
4156
+ },
4157
+ children: remove === row.id ? t("sketchDeleteConfirm") : t("sketchDeleteDraft")
4158
+ })] }, row.id))
4159
+ }),
4160
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4161
+ type: "button",
4162
+ onClick: () => setOpen(false),
4163
+ children: t("sketchFileClose")
4164
+ })
4165
+ ]
4166
+ }) : null
4167
+ ]
4168
+ });
4132
4169
  }
4133
4170
  //#endregion
4134
4171
  //#region src/sketch-replay.jsx
@@ -4155,13 +4192,12 @@ window.__ModuleLoader__.load({
4155
4192
  "video/webm"
4156
4193
  ];
4157
4194
  function SketchReplay({ states, current, images, name, onClose, t }) {
4195
+ const dialog = (0, react.useRef)(null);
4158
4196
  const canvas = (0, react.useRef)(null);
4159
4197
  const cache = (0, react.useRef)(/* @__PURE__ */ new Map());
4160
4198
  const clock = (0, react.useRef)({
4161
4199
  time: 0,
4162
- last: 0,
4163
- playing: true,
4164
- recorder: null
4200
+ capture: null
4165
4201
  });
4166
4202
  const [speed, setSpeed] = (0, react.useState)("normal");
4167
4203
  const [playing, setPlaying] = (0, react.useState)(true);
@@ -4179,6 +4215,11 @@ window.__ModuleLoader__.load({
4179
4215
  height
4180
4216
  ]);
4181
4217
  const total = plan.at(-1)?.end ?? 0;
4218
+ (0, react.useEffect)(() => {
4219
+ const node = dialog.current;
4220
+ node.showModal();
4221
+ return () => node.close();
4222
+ }, []);
4182
4223
  const paint = (time) => {
4183
4224
  const target = canvas.current;
4184
4225
  if (!target) return;
@@ -4187,54 +4228,76 @@ window.__ModuleLoader__.load({
4187
4228
  };
4188
4229
  (0, react.useEffect)(() => {
4189
4230
  clock.current.time = 0;
4190
- clock.current.last = 0;
4191
4231
  cache.current.clear();
4192
- let frame = 0;
4232
+ setProgress(0);
4233
+ }, [plan]);
4234
+ (0, react.useEffect)(() => {
4235
+ if (video || !total) return;
4236
+ const state = clock.current;
4237
+ if (!playing) {
4238
+ paint(state.time);
4239
+ return;
4240
+ }
4241
+ let frame = 0, last, lastPaint = -Infinity, lastProgress = -Infinity;
4193
4242
  const tick = (now) => {
4194
- const state = clock.current;
4195
- if (state.playing) {
4196
- state.time = Math.min(total, state.time + (state.last ? now - state.last : 0));
4197
- if (state.time >= total) {
4198
- state.playing = false;
4199
- setPlaying(false);
4200
- if (state.recorder) window.setTimeout(() => state.recorder?.stop(), 600);
4201
- }
4243
+ state.time = Math.min(total, state.time + (last === void 0 ? 0 : now - last));
4244
+ last = now;
4245
+ const finished = state.time >= total;
4246
+ if (finished || now - lastPaint >= 1e3 / 30 - 1) {
4247
+ paint(state.time);
4248
+ lastPaint = now;
4202
4249
  }
4203
- state.last = now;
4204
- paint(state.time);
4205
- setProgress(total ? state.time / total : 1);
4206
- frame = requestAnimationFrame(tick);
4250
+ if (finished || now - lastProgress >= 100) {
4251
+ setProgress(state.time / total);
4252
+ lastProgress = now;
4253
+ }
4254
+ if (finished) {
4255
+ setPlaying(false);
4256
+ const capture = state.capture;
4257
+ if (capture) capture.timer = setTimeout(() => endRecording(), 250);
4258
+ } else frame = requestAnimationFrame(tick);
4207
4259
  };
4208
4260
  frame = requestAnimationFrame(tick);
4209
4261
  return () => cancelAnimationFrame(frame);
4210
- }, [plan]);
4262
+ }, [
4263
+ plan,
4264
+ playing,
4265
+ video
4266
+ ]);
4211
4267
  (0, react.useEffect)(() => () => {
4212
4268
  if (video) URL.revokeObjectURL(video.url);
4213
4269
  }, [video]);
4214
- (0, react.useEffect)(() => () => {
4215
- if (clock.current.recorder?.state === "recording") {
4216
- clock.current.recorder.onstop = null;
4217
- clock.current.recorder.stop();
4270
+ (0, react.useEffect)(() => () => endRecording(true), []);
4271
+ function endRecording(discard = false) {
4272
+ const capture = clock.current.capture;
4273
+ if (!capture) return;
4274
+ clearTimeout(capture.timer);
4275
+ if (discard) {
4276
+ clock.current.capture = null;
4277
+ capture.recorder.onstop = null;
4218
4278
  }
4219
- }, []);
4279
+ if (capture.recorder.state !== "inactive") capture.recorder.stop();
4280
+ if (discard) for (const track of capture.stream.getTracks()) track.stop();
4281
+ }
4220
4282
  const toggle = () => {
4221
4283
  const state = clock.current;
4222
4284
  if (state.time >= total) {
4223
4285
  state.time = 0;
4224
4286
  cache.current.clear();
4287
+ setProgress(0);
4225
4288
  }
4226
- state.playing = !state.playing;
4227
- setPlaying(state.playing);
4289
+ setPlaying((value) => !value);
4228
4290
  };
4229
4291
  const seek = (value) => {
4230
4292
  clock.current.time = value * total;
4231
- clock.current.playing = false;
4232
4293
  setPlaying(false);
4233
4294
  cache.current.clear();
4295
+ paint(clock.current.time);
4296
+ setProgress(value);
4234
4297
  };
4235
4298
  const record = () => {
4236
4299
  if (recording) {
4237
- clock.current.recorder?.stop();
4300
+ endRecording();
4238
4301
  return;
4239
4302
  }
4240
4303
  const type = VIDEO_TYPES.find((item) => typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(item));
@@ -4244,15 +4307,25 @@ window.__ModuleLoader__.load({
4244
4307
  }
4245
4308
  setNote("");
4246
4309
  const chunks = [];
4247
- const recorder = new MediaRecorder(canvas.current.captureStream(30), {
4248
- mimeType: type,
4249
- videoBitsPerSecond: 8e6
4250
- });
4310
+ let stream, recorder;
4311
+ try {
4312
+ stream = canvas.current.captureStream(30);
4313
+ recorder = new MediaRecorder(stream, {
4314
+ mimeType: type,
4315
+ videoBitsPerSecond: 8e6
4316
+ });
4317
+ recorder.start(250);
4318
+ } catch {
4319
+ for (const track of stream?.getTracks() ?? []) track.stop();
4320
+ setNote(t("sketchReplayUnsupported"));
4321
+ return;
4322
+ }
4251
4323
  recorder.ondataavailable = (event) => {
4252
4324
  if (event.data.size) chunks.push(event.data);
4253
4325
  };
4254
4326
  recorder.onstop = () => {
4255
- clock.current.recorder = null;
4327
+ clock.current.capture = null;
4328
+ for (const track of stream.getTracks()) track.stop();
4256
4329
  setRecording(false);
4257
4330
  setVideo({
4258
4331
  url: URL.createObjectURL(new Blob(chunks, { type: "video/webm" })),
@@ -4260,67 +4333,61 @@ window.__ModuleLoader__.load({
4260
4333
  });
4261
4334
  };
4262
4335
  clock.current.time = 0;
4263
- clock.current.playing = true;
4264
4336
  cache.current.clear();
4265
- clock.current.recorder = recorder;
4337
+ clock.current.capture = {
4338
+ recorder,
4339
+ stream
4340
+ };
4341
+ paint(0);
4342
+ setProgress(0);
4266
4343
  setPlaying(true);
4267
4344
  setRecording(true);
4268
- recorder.start(250);
4269
4345
  };
4270
4346
  const stop = () => {
4271
- if (clock.current.recorder?.state === "recording") {
4272
- clock.current.recorder.onstop = null;
4273
- clock.current.recorder.stop();
4274
- clock.current.recorder = null;
4275
- setRecording(false);
4276
- }
4347
+ endRecording(true);
4277
4348
  onClose();
4278
4349
  };
4279
4350
  const clock0 = Math.round(progress * total / 1e3), clock1 = Math.round(total / 1e3);
4280
4351
  const mmss = (seconds) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
4281
- const icon = (path) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
4282
- viewBox: "0 0 24 24",
4283
- width: "18",
4284
- height: "18",
4285
- "aria-hidden": "true",
4286
- fill: "currentColor",
4287
- children: path
4288
- });
4289
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
4352
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("dialog", {
4353
+ ref: dialog,
4290
4354
  className: "codexSketchReplay",
4291
- role: "dialog",
4292
4355
  "aria-label": t("sketchReplayTitle"),
4356
+ onCancel: (event) => {
4357
+ event.preventDefault();
4358
+ event.stopPropagation();
4359
+ stop();
4360
+ },
4293
4361
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: t("sketchReplayTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
4294
4362
  type: "button",
4295
4363
  className: "codexSketchReplayClose",
4296
4364
  onClick: stop,
4297
4365
  "aria-label": t("sketchReplayClose"),
4298
- children: [icon(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M6.4 5 12 10.6 17.6 5 19 6.4 13.4 12 19 17.6 17.6 19 12 13.4 6.4 19 5 17.6 10.6 12 5 6.4z" })), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("sketchReplayClose") })]
4299
- })] }), video ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
4300
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
4301
- className: "codexSketchReplayStage",
4302
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("video", {
4303
- src: video.url,
4304
- controls: true,
4305
- autoPlay: true,
4306
- loop: true
4307
- })
4308
- }),
4309
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4310
- className: "codexSketchReplayBar",
4311
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
4312
- className: "codexSketchReplaySave",
4313
- href: video.url,
4314
- download: video.file,
4315
- children: t("sketchReplaySave")
4316
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4317
- type: "button",
4318
- onClick: () => setVideo(null),
4319
- children: t("sketchReplayAgain")
4320
- })]
4321
- }),
4322
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: t("sketchReplaySaveHint") })
4323
- ] }) : steps.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: t("sketchReplayEmpty") }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
4366
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(WorkspaceIcon, {
4367
+ name: "close",
4368
+ size: 18
4369
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("sketchReplayClose") })]
4370
+ })] }), video ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
4371
+ className: "codexSketchReplayStage",
4372
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("video", {
4373
+ src: video.url,
4374
+ controls: true,
4375
+ autoPlay: true,
4376
+ loop: true
4377
+ })
4378
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4379
+ className: "codexSketchReplayBar",
4380
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
4381
+ className: "codexSketchReplaySave",
4382
+ href: video.url,
4383
+ download: video.file,
4384
+ children: t("sketchReplaySave")
4385
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
4386
+ type: "button",
4387
+ onClick: () => setVideo(null),
4388
+ children: t("sketchReplayAgain")
4389
+ })]
4390
+ })] }) : steps.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: t("sketchReplayEmpty") }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
4324
4391
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
4325
4392
  className: "codexSketchReplayStage",
4326
4393
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("canvas", {
@@ -4342,7 +4409,10 @@ window.__ModuleLoader__.load({
4342
4409
  disabled: recording,
4343
4410
  onClick: toggle,
4344
4411
  "aria-label": playing ? t("sketchReplayPause") : t("sketchReplayPlay"),
4345
- children: playing ? icon(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M7 5h3.5v14H7zM13.5 5H17v14h-3.5z" })) : icon(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 5.2v13.6L19 12z" }))
4412
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WorkspaceIcon, {
4413
+ name: playing ? "pause" : "play",
4414
+ size: 18
4415
+ })
4346
4416
  }),
4347
4417
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
4348
4418
  className: "codexSketchReplayTime",
@@ -4377,6 +4447,7 @@ window.__ModuleLoader__.load({
4377
4447
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
4378
4448
  type: "button",
4379
4449
  className: "codexSketchReplayRecord",
4450
+ title: t("sketchReplayHint"),
4380
4451
  "data-recording": recording || void 0,
4381
4452
  onClick: record,
4382
4453
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", { "aria-hidden": "true" }), recording ? t("sketchReplayStopRecording") : t("sketchReplayRecord")]
@@ -4386,7 +4457,7 @@ window.__ModuleLoader__.load({
4386
4457
  note ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", {
4387
4458
  role: "alert",
4388
4459
  children: note
4389
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: t("sketchReplayHint") })
4460
+ }) : null
4390
4461
  ] })]
4391
4462
  });
4392
4463
  }
@@ -4426,7 +4497,6 @@ window.__ModuleLoader__.load({
4426
4497
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
4427
4498
  type: "range",
4428
4499
  "aria-label": label,
4429
- "aria-orientation": "vertical",
4430
4500
  min,
4431
4501
  max,
4432
4502
  value,
@@ -4540,163 +4610,6 @@ window.__ModuleLoader__.load({
4540
4610
  };
4541
4611
  }
4542
4612
  //#endregion
4543
- //#region src/rpc-contract.js
4544
- const CHANNEL = "/codex-subscription";
4545
- Object.freeze([
4546
- "status",
4547
- "login/start",
4548
- "login/status",
4549
- "login/submit",
4550
- "login/cancel",
4551
- "logout",
4552
- "account/select",
4553
- "account/remove",
4554
- "usage",
4555
- "usage/accounts",
4556
- "usage/history",
4557
- "usage/profile",
4558
- "diagnostics",
4559
- "preferences/status",
4560
- "preferences/models",
4561
- "preferences/update",
4562
- "default-model/status",
4563
- "default-model/select",
4564
- "default-model/reset",
4565
- "predictions/generate",
4566
- "runtime/status",
4567
- "runtime/install",
4568
- "runtime/remove",
4569
- "runtime/cancel",
4570
- "storage/status",
4571
- "storage/clear-forecast",
4572
- "voice/start",
4573
- "voice/stop",
4574
- "voice/status",
4575
- "voice/interrupt",
4576
- "voice/preview",
4577
- "voice/catalog",
4578
- "voice/native/probe",
4579
- "voice/native/start",
4580
- "voice/native/status",
4581
- "voice/native/control",
4582
- "voice/native/stop",
4583
- "remote/status",
4584
- "remote/enable",
4585
- "remote/disable",
4586
- "remote/pair",
4587
- "remote/clients",
4588
- "remote/revoke",
4589
- "reset-credit/inspect",
4590
- "reset-credit/prepare",
4591
- "reset-credit/consume",
4592
- "image/original/chunk",
4593
- "sketch/connect",
4594
- "sketch/poll",
4595
- "sketch/claim",
4596
- "sketch/result",
4597
- "sketch/disconnect"
4598
- ]);
4599
- function unwrap(response) {
4600
- if (!response?.ok) throw new Error(response?.error?.message ?? "Codex RPC failed");
4601
- return response.value;
4602
- }
4603
- //#endregion
4604
- //#region src/sketch-agent-client.js
4605
- function connectSketchAgent(rpc, sessionId, execute, report, pollDelay = () => 350) {
4606
- let stopped = false, token, timer, attempts = 0, failures = 0, pending = false;
4607
- const call = (endpoint, payload) => rpc.call(CHANNEL, `sketch/${endpoint}`, {
4608
- sessionId,
4609
- token,
4610
- ...payload
4611
- }).then(unwrap);
4612
- const poll = async () => {
4613
- if (stopped || pending) return;
4614
- pending = true;
4615
- try {
4616
- const tasks = await call("poll");
4617
- for (const task of tasks) {
4618
- if (stopped) break;
4619
- if (task.cancelled) {
4620
- report("Sketch operation interrupted; completed strokes are preserved.");
4621
- continue;
4622
- }
4623
- let value, error;
4624
- try {
4625
- if (task.expiresAt < Date.now() || !await call("claim", { id: task.id })) throw Error("Sketch command expired or cancelled; inspect before retrying");
4626
- if (stopped) break;
4627
- value = await execute(task.request);
4628
- } catch (cause) {
4629
- error = cause.message;
4630
- }
4631
- await call("result", {
4632
- id: task.id,
4633
- value,
4634
- error
4635
- });
4636
- }
4637
- } catch (error) {
4638
- if (!stopped) {
4639
- if (++failures > 5) {
4640
- report(`${error.message}; reconnect failed. Reopen this session to retry.`);
4641
- return;
4642
- }
4643
- report(`${error.message}; reconnecting. Inspect recentRequests before retrying a write.`);
4644
- if (token) call("disconnect").catch(() => {});
4645
- token = void 0;
4646
- timer = setTimeout(connect, Math.min(1e4, 1e3 * 2 ** (failures - 1)));
4647
- }
4648
- return;
4649
- } finally {
4650
- pending = false;
4651
- }
4652
- failures = 0;
4653
- if (!stopped) timer = setTimeout(poll, pollDelay());
4654
- };
4655
- const connect = () => {
4656
- if (stopped || pending) return;
4657
- pending = true;
4658
- call("connect").then((value) => {
4659
- pending = false;
4660
- token = value.token;
4661
- attempts = 0;
4662
- if (stopped) call("disconnect").catch(() => {});
4663
- else poll();
4664
- }, (error) => {
4665
- pending = false;
4666
- if (stopped) return;
4667
- const leaseConflict = /Another board is connected/.test(error.message);
4668
- if (++attempts < (leaseConflict ? 8 : 3)) timer = setTimeout(connect, Math.min(3e3, 500 * attempts));
4669
- else report(error.message);
4670
- });
4671
- };
4672
- const wake = () => {
4673
- if (stopped || pending) return;
4674
- clearTimeout(timer);
4675
- attempts = 0;
4676
- failures = 0;
4677
- token ? poll() : connect();
4678
- };
4679
- const visible = () => {
4680
- if (document.visibilityState === "visible") wake();
4681
- };
4682
- if (typeof window !== "undefined") {
4683
- window.addEventListener("online", wake);
4684
- window.addEventListener("focus", wake);
4685
- document.addEventListener("visibilitychange", visible);
4686
- }
4687
- connect();
4688
- return () => {
4689
- stopped = true;
4690
- clearTimeout(timer);
4691
- if (typeof window !== "undefined") {
4692
- window.removeEventListener("online", wake);
4693
- window.removeEventListener("focus", wake);
4694
- document.removeEventListener("visibilitychange", visible);
4695
- }
4696
- if (token) call("disconnect").catch(() => {});
4697
- };
4698
- }
4699
- //#endregion
4700
4613
  //#region src/sketch-measure.js
4701
4614
  const hex = (r, g, b) => "#" + [
4702
4615
  r,
@@ -4947,10 +4860,8 @@ window.__ModuleLoader__.load({
4947
4860
  }
4948
4861
  //#endregion
4949
4862
  //#region src/sketch-studio.jsx
4950
- function SketchStudio({ open, agentEnabled, onOpen, onClose, attachSketch, enabled, t, incoming, sessionId, rpc, sessionState, bridgeManaged = false, onAgentReady, onAgentError }) {
4951
- const localSession = (0, react.useRef)(null);
4952
- localSession.current ??= sessionState ?? createSketchSessionState();
4953
- const { doc, undo, redo, images, timeline, saved, dirty, documentId, documentRevision, agentAdapter, agentSession, agentRun } = localSession.current;
4863
+ function SketchStudio({ open, agentEnabled, onOpen, onClose, attachSketch, enabled, t, incoming, sessionId, sessionState, onAgentReady, onAgentError, onAgentState, visible = true }) {
4864
+ const { doc, undo, redo, images, timeline, saved, dirty, documentId, documentRevision, agentAdapter, agentSession, agentRun } = sessionState;
4954
4865
  const dialog = (0, react.useRef)(null), canvas = (0, react.useRef)(null), cache = (0, react.useRef)(/* @__PURE__ */ new Map());
4955
4866
  const active = (0, react.useRef)(null), frame = (0, react.useRef)(null), updateUi = (0, react.useRef)(false);
4956
4867
  const [agentState, setAgentState] = (0, react.useState)(agentRun.current?.state ?? "idle");
@@ -5025,7 +4936,7 @@ window.__ModuleLoader__.load({
5025
4936
  if (frame.current !== null) return;
5026
4937
  frame.current = requestAnimationFrame(() => {
5027
4938
  frame.current = null;
5028
- paint();
4939
+ if (dialog.current?.open) paint();
5029
4940
  if (updateUi.current) {
5030
4941
  updateUi.current = false;
5031
4942
  redraw((value) => value + 1);
@@ -5055,13 +4966,16 @@ window.__ModuleLoader__.load({
5055
4966
  dialog.current.showModal();
5056
4967
  canvas.current.width = doc.current.width ?? 1024;
5057
4968
  paint();
5058
- } else dialog.current?.close();
4969
+ } else {
4970
+ dialog.current?.close();
4971
+ setReplayOpen(false);
4972
+ }
5059
4973
  }, [open]);
5060
4974
  (0, react.useEffect)(() => () => {
5061
4975
  cancelAnimationFrame(frame.current);
5062
4976
  cache.current.clear();
5063
4977
  }, []);
5064
- const { save, saveChanges, fresh, load, importImage, restore } = createSketchDocumentLifecycle(localSession.current, {
4978
+ const { save, saveChanges, fresh, load, importImage, restore } = createSketchDocumentLifecycle(sessionState, {
5065
4979
  sessionId,
5066
4980
  t,
5067
4981
  schedule,
@@ -5071,7 +4985,6 @@ window.__ModuleLoader__.load({
5071
4985
  setTextEdit,
5072
4986
  setRecovered
5073
4987
  });
5074
- (0, react.useEffect)(() => localSession.current.retain?.(), []);
5075
4988
  (0, react.useEffect)(() => {
5076
4989
  let live = true;
5077
4990
  setHydrated(false);
@@ -5144,7 +5057,7 @@ window.__ModuleLoader__.load({
5144
5057
  busy
5145
5058
  ]);
5146
5059
  const keyDown = (event) => {
5147
- if (event.target.closest("input,textarea,select,[contenteditable=true]") || event.isComposing || busy || active.current) return;
5060
+ if (replayOpen || event.target.closest("input,textarea,select,[contenteditable=true]") || event.isComposing || busy || active.current) return;
5148
5061
  if (!navigation.shortcuts) return;
5149
5062
  if (navigation.keyDown(event)) return;
5150
5063
  if (agentRun.current?.locked) return;
@@ -5244,6 +5157,7 @@ window.__ModuleLoader__.load({
5244
5157
  changed: (state) => {
5245
5158
  setAgentState(state);
5246
5159
  setNoticeHidden(false);
5160
+ onAgentState?.(state);
5247
5161
  },
5248
5162
  available: () => enabled && agentEnabled,
5249
5163
  open: () => onOpen(),
@@ -5392,7 +5306,7 @@ window.__ModuleLoader__.load({
5392
5306
  });
5393
5307
  (0, react.useEffect)(() => {
5394
5308
  if (!enabled || !agentEnabled || !hydrated) return;
5395
- const api = Object.freeze({
5309
+ onAgentReady(Object.freeze({
5396
5310
  version: 2,
5397
5311
  sessionId,
5398
5312
  execute: (request) => agentRun.current.execute(request),
@@ -5403,50 +5317,18 @@ window.__ModuleLoader__.load({
5403
5317
  report: (error) => setError(error ? error.message || t("sketchFailed") : ""),
5404
5318
  exportFile: (value) => agentAdapter.current.export(value)
5405
5319
  })
5406
- });
5407
- if (bridgeManaged) {
5408
- onAgentReady?.(api);
5409
- return () => onAgentReady?.(void 0);
5410
- }
5411
- window.dshSketchAgent = api;
5412
- return () => {
5413
- if (window.dshSketchAgent === api) delete window.dshSketchAgent;
5414
- };
5320
+ }));
5321
+ return () => onAgentReady(void 0);
5415
5322
  }, [
5416
5323
  enabled,
5417
5324
  agentEnabled,
5418
- rpc,
5419
5325
  sessionId,
5420
5326
  hydrated,
5421
- bridgeManaged,
5422
5327
  onAgentReady
5423
5328
  ]);
5424
5329
  (0, react.useEffect)(() => {
5425
- if (!enabled || !agentEnabled) {
5426
- if (agentRun.current.locked) agentRun.current.stop();
5427
- return;
5428
- }
5429
- if (bridgeManaged || !rpc || !sessionId || !hydrated) return;
5430
- let live = true;
5431
- const disconnect = connectSketchAgent(rpc, sessionId, (request) => {
5432
- if (!live) throw Error("Sketch session disconnected");
5433
- return agentRun.current.execute(request);
5434
- }, (message) => {
5435
- agentRun.current.fail();
5436
- setError(message);
5437
- }, () => agentRun.current.locked ? 350 : 2e3);
5438
- return () => {
5439
- live = false;
5440
- disconnect();
5441
- };
5442
- }, [
5443
- enabled,
5444
- agentEnabled,
5445
- rpc,
5446
- sessionId,
5447
- hydrated,
5448
- bridgeManaged
5449
- ]);
5330
+ if ((!enabled || !agentEnabled) && agentRun.current.locked) agentRun.current.stop();
5331
+ }, [enabled, agentEnabled]);
5450
5332
  const attach = () => {
5451
5333
  if (!enabled) return;
5452
5334
  return runFile(async () => {
@@ -5481,7 +5363,7 @@ window.__ModuleLoader__.load({
5481
5363
  link.remove();
5482
5364
  setTimeout(() => URL.revokeObjectURL(url), 1e4);
5483
5365
  };
5484
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [enabled && agentEnabled && !open && !noticeHidden ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchRunStatus, {
5366
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [enabled && agentEnabled && visible && !open && !noticeHidden ? (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchRunStatus, {
5485
5367
  state: agentState,
5486
5368
  floating: true,
5487
5369
  t,
@@ -5492,7 +5374,7 @@ window.__ModuleLoader__.load({
5492
5374
  agentRun.current.resume();
5493
5375
  },
5494
5376
  onDismiss: () => setNoticeHidden(true)
5495
- }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("dialog", {
5377
+ }), document.body) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("dialog", {
5496
5378
  ref: dialog,
5497
5379
  className: "codexSketchDialog codexSketchStudio codexLayerStudio",
5498
5380
  "aria-label": t("sketchTitle"),
@@ -5542,6 +5424,10 @@ window.__ModuleLoader__.load({
5542
5424
  onClick: close,
5543
5425
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WorkspaceIcon, { name: "close" })
5544
5426
  }),
5427
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5428
+ className: "codexSketchHeading",
5429
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: t("sketchTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "Beta" })]
5430
+ }),
5545
5431
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchFiles, {
5546
5432
  save,
5547
5433
  load,
@@ -5552,18 +5438,19 @@ window.__ModuleLoader__.load({
5552
5438
  disabled: agentLocked || busy,
5553
5439
  t,
5554
5440
  runOperation: runFile,
5555
- extra: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
5441
+ extra: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
5556
5442
  type: "button",
5443
+ className: "codexSketchReplayToggle",
5557
5444
  disabled: agentLocked || busy || !timeline.current.length,
5558
5445
  title: t("sketchReplayTitle"),
5446
+ "aria-label": t("sketchReplayTitle"),
5559
5447
  onClick: () => setReplayOpen(true),
5560
- children: t("sketchReplay")
5448
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(WorkspaceIcon, {
5449
+ name: "play",
5450
+ size: 15
5451
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("sketchReplay") })]
5561
5452
  })
5562
5453
  }),
5563
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5564
- className: "codexSketchHeading",
5565
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: t("sketchTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "Beta" })]
5566
- }),
5567
5454
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5568
5455
  className: "codexSketchUtility",
5569
5456
  children: [
@@ -5620,8 +5507,14 @@ window.__ModuleLoader__.load({
5620
5507
  name: "layers",
5621
5508
  size: 18
5622
5509
  }),
5623
- t("sketchLayers"),
5624
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: doc.current.layers.length })
5510
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
5511
+ className: "codexSketchLayersLabel",
5512
+ children: t("sketchLayers")
5513
+ }),
5514
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
5515
+ className: "codexSketchLayersCount",
5516
+ children: doc.current.layers.length
5517
+ })
5625
5518
  ]
5626
5519
  })
5627
5520
  ]
@@ -5663,7 +5556,7 @@ window.__ModuleLoader__.load({
5663
5556
  })]
5664
5557
  }) : null,
5665
5558
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5666
- className: `codexLayerBody ${layersOpen ? "withLayers" : ""}`,
5559
+ className: "codexLayerBody",
5667
5560
  children: [
5668
5561
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("canvas", {
5669
5562
  tabIndex: 0,
@@ -5832,38 +5725,6 @@ window.__ModuleLoader__.load({
5832
5725
  strokeWidth: ".002"
5833
5726
  })]
5834
5727
  }) : null,
5835
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchSizeControl, {
5836
- label: t(opacityMode ? "sketchFlow" : selected?.shape === "text" || tool === "text" ? "sketchTextSize" : "sketchWidth"),
5837
- mode: opacityMode ? "opacity" : "size",
5838
- modes: showOpacity ? [{
5839
- value: "size",
5840
- label: t(selected?.shape === "text" || tool === "text" ? "sketchTextSize" : "sketchSizeShort")
5841
- }, {
5842
- value: "opacity",
5843
- label: t("sketchFlow")
5844
- }] : void 0,
5845
- onModeChange: setSizeMode,
5846
- min: opacityMode ? 5 : 1,
5847
- max: opacityMode ? 100 : 256,
5848
- suffix: opacityMode ? "%" : "",
5849
- value: opacityMode ? (selected?.opacity ?? flow / 100) * 100 : selected?.width ?? width,
5850
- disabled: agentLocked || busy,
5851
- onStart: () => {
5852
- if (selected) {
5853
- checkpoint();
5854
- sizeGesture.current = true;
5855
- }
5856
- },
5857
- onEnd: () => {
5858
- sizeGesture.current = false;
5859
- },
5860
- onChange: (value) => {
5861
- if (opacityMode) if (selected) editObject({ opacity: value / 100 });
5862
- else setFlow(value);
5863
- else if (selected) editObject({ width: value });
5864
- else setWidth(value);
5865
- }
5866
- }),
5867
5728
  textEdit ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
5868
5729
  className: "codexSketchTextEditor",
5869
5730
  onSubmit: (event) => {
@@ -5942,7 +5803,7 @@ window.__ModuleLoader__.load({
5942
5803
  change,
5943
5804
  t
5944
5805
  }) : null,
5945
- replayOpen && dialog.current ? (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchReplay, {
5806
+ open && replayOpen && dialog.current ? (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchReplay, {
5946
5807
  states: timeline.current,
5947
5808
  current: doc.current,
5948
5809
  images: images.current,
@@ -5981,7 +5842,39 @@ window.__ModuleLoader__.load({
5981
5842
  eraser,
5982
5843
  setEraser,
5983
5844
  color,
5984
- pickColor
5845
+ pickColor,
5846
+ sizeControl: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchSizeControl, {
5847
+ label: t(opacityMode ? "sketchFlow" : selected?.shape === "text" || tool === "text" ? "sketchTextSize" : "sketchWidth"),
5848
+ mode: opacityMode ? "opacity" : "size",
5849
+ modes: showOpacity ? [{
5850
+ value: "size",
5851
+ label: t(selected?.shape === "text" || tool === "text" ? "sketchTextSize" : "sketchSizeShort")
5852
+ }, {
5853
+ value: "opacity",
5854
+ label: t("sketchFlow")
5855
+ }] : void 0,
5856
+ onModeChange: setSizeMode,
5857
+ min: opacityMode ? 5 : 1,
5858
+ max: opacityMode ? 100 : 256,
5859
+ suffix: opacityMode ? "%" : "",
5860
+ value: opacityMode ? (selected?.opacity ?? flow / 100) * 100 : selected?.width ?? width,
5861
+ disabled: agentLocked || busy,
5862
+ onStart: () => {
5863
+ if (selected) {
5864
+ checkpoint();
5865
+ sizeGesture.current = true;
5866
+ }
5867
+ },
5868
+ onEnd: () => {
5869
+ sizeGesture.current = false;
5870
+ },
5871
+ onChange: (value) => {
5872
+ if (opacityMode) if (selected) editObject({ opacity: value / 100 });
5873
+ else setFlow(value);
5874
+ else if (selected) editObject({ width: value });
5875
+ else setWidth(value);
5876
+ }
5877
+ })
5985
5878
  }),
5986
5879
  error ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
5987
5880
  className: "codexSketchHint",
@@ -5998,22 +5891,15 @@ window.__ModuleLoader__.load({
5998
5891
  //#endregion
5999
5892
  exports.SKETCH_CSS = `
6000
5893
 
6001
- .codexSketchSizeModes{display:flex;flex-direction:column;gap:3px}.codexSketchSizeModes button{font-size:11px;padding:4px 6px;border-radius:10px;color:var(--sketch-muted)}.codexSketchSizeModes button[aria-pressed=true]{background:var(--sketch-line);color:var(--sketch-fg)}
6002
-
6003
- .codexSketchSizeControl{position:absolute;left:10px;top:50%;transform:translateY(-50%);z-index:2;display:flex;flex-direction:column;align-items:center;gap:10px;padding:12px 6px;border:1px solid var(--sketch-line);border-radius:24px;background:var(--sketch-glass);backdrop-filter:blur(18px);box-shadow:0 3px 14px #0001}
6004
- .codexSketchSizeControl>span{font-size:10px;color:var(--sketch-muted);max-width:42px;text-align:center}.codexSketchSizeControl output{font-size:11px;font-variant-numeric:tabular-nums;color:var(--sketch-muted)}
6005
- .codexSketchSizeControl input{writing-mode:vertical-lr;direction:rtl;width:28px;height:150px;appearance:none;background:transparent;cursor:ns-resize;touch-action:none}
6006
- .codexSketchSizeControl input::-webkit-slider-runnable-track{width:4px;border-radius:4px;background:var(--sketch-line)}
6007
- .codexSketchSizeControl input::-webkit-slider-thumb{appearance:none;width:20px;height:20px;margin-left:-8px;border-radius:50%;background:var(--sketch-fg);border:2px solid var(--sketch-bg);box-shadow:0 1px 5px #0004}
5894
+ .codexSketchSizeControl,.codexSketchSizeModes{display:flex;align-items:center;gap:4px}.codexSketchSizeControl{gap:8px;color:var(--sketch-muted);font-size:11px}.codexSketchSizeControl input{width:76px;margin:0;accent-color:var(--sketch-accent)}.codexSketchSizeControl output{min-width:25px;font-variant-numeric:tabular-nums}.codexSketchSizeModes button{padding:3px 6px;border-radius:6px}.codexSketchSizeModes button[aria-pressed=true]{background:var(--sketch-line);color:var(--sketch-fg)}
6008
5895
  .codexSketchSelection{position:absolute;width:min(100cqw,calc(100cqh * var(--sketch-ratio,1)));height:auto;aspect-ratio:var(--sketch-ratio);pointer-events:none;overflow:visible}
6009
- .codexSketchShapeMenu{position:absolute;bottom:65px;display:grid;grid-template-columns:1fr 1fr;padding:8px;border:1px solid var(--sketch-line);border-radius:14px;background:var(--sketch-bg);box-shadow:0 8px 24px #0003;z-index:5}.codexSketchShapeMenu button{min-height:40px;padding:8px 14px}
5896
+ .codexSketchShapeMenu{position:absolute;bottom:calc(100% + 8px);display:grid;grid-template-columns:1fr 1fr;padding:8px;border:1px solid var(--sketch-line);border-radius:14px;background:var(--sketch-bg);box-shadow:0 8px 24px #0003;z-index:5}.codexSketchShapeMenu button{min-height:40px;padding:8px 14px}
6010
5897
  .codexSketchTextEditor{position:absolute;z-index:4;left:50%;top:50%;transform:translate(-50%,-50%);display:flex;flex-wrap:wrap;gap:8px;width:min(320px,80%);padding:12px;background:var(--sketch-bg);border:1px solid var(--sketch-line);border-radius:12px;box-shadow:0 6px 24px #0003}.codexSketchTextEditor textarea{width:100%;min-height:72px;resize:vertical;background:transparent;color:inherit;border:1px solid var(--sketch-line);border-radius:8px;padding:8px;font:inherit}.codexSketchTextEditor button{padding:6px 10px;border-radius:8px;background:var(--sketch-line)}
6011
5898
  .codexSketchObjectActions{display:flex;gap:8px}.codexSketchObjectActions button{padding:6px 8px;border-radius:8px;background:var(--sketch-line)}
6012
- .codexLayerBrush>select{background:var(--sketch-bg);color:inherit;border:1px solid var(--sketch-line);border-radius:8px;padding:6px}
6013
5899
 
6014
- .codexSketchBackgroundStatus{position:fixed;top:16px;left:50%;transform:translateX(-50%);z-index:1000;display:flex;gap:8px;align-items:center;padding:6px 10px;border-radius:12px;background:var(--dsw-alias-bg-layer-1,#f5f5f7);color:var(--dsw-alias-label-primary,#202124);border:1px solid #8883;box-shadow:0 4px 16px #0002;font:12px system-ui}.codexSketchBackgroundStatus button{color:inherit;background:none;border:0;cursor:pointer}
5900
+ .codexSketchBackgroundStatus{position:fixed;top:max(56px, env(safe-area-inset-top));left:50%;transform:translateX(-50%);z-index:30;display:flex;gap:8px;align-items:center;padding:6px 10px;border-radius:12px;background:var(--dsw-alias-bg-layer-1,#f5f5f7);color:var(--dsw-alias-label-primary,#202124);border:1px solid #8883;box-shadow:0 4px 16px #0002;font:12px system-ui}.codexSketchBackgroundStatus button{color:inherit;background:none;border:0;cursor:pointer}
6015
5901
  .codexSketchAgentStatus{display:flex;align-items:center;justify-content:center;gap:8px;min-height:24px;color:var(--sketch-muted);font-size:12px}.codexSketchAgentStatus button{min-height:30px;padding:4px 10px;border-radius:16px;background:var(--sketch-line)}.codexSketchAgentStatus{align-self:center;max-width:100%;min-height:34px;padding:0 6px;flex-wrap:wrap}.codexSketchBackgroundStatus button{min-height:30px;display:inline-flex;align-items:center;gap:5px}.codexSketchAgentStatus .codexSketchStop,.codexSketchBackgroundStatus .codexSketchStop{font-weight:500;background:var(--sketch-line,#8882);border-radius:16px;padding:4px 10px}
6016
- .codexSketchDialog{--sketch-bg:var(--dsw-alias-bg-layer-1,#f5f5f7);--sketch-fg:var(--dsw-alias-label-primary,#202124);--sketch-muted:var(--dsw-alias-label-secondary,#727279);--sketch-line:var(--dsw-alias-border-l2,#8883);--sketch-glass:color-mix(in srgb,var(--sketch-bg) 90%,transparent);box-sizing:border-box;width:min(1280px,calc(100vw - 24px));height:94dvh;max-height:94dvh;margin:auto;padding:10px;border:1px solid var(--sketch-line);border-radius:18px;background:var(--sketch-bg);color:var(--sketch-fg);box-shadow:0 24px 90px #0004;overflow:hidden;font:13px/1.4 system-ui}
5902
+ .codexSketchDialog{--sketch-bg:var(--dsw-alias-bg-layer-1,#f5f5f7);--sketch-fg:var(--dsw-alias-label-primary,#202124);--sketch-muted:var(--dsw-alias-label-secondary,#727279);--sketch-line:var(--dsw-alias-border-l2,#8883);--sketch-accent:var(--dsw-alias-state-business-primary,#0a84ff);--sketch-glass:color-mix(in srgb,var(--sketch-bg) 90%,transparent);box-sizing:border-box;width:min(1280px,calc(100vw - 24px));height:94dvh;max-height:94dvh;margin:auto;padding:10px;border:1px solid var(--sketch-line);border-radius:18px;background:var(--sketch-bg);color:var(--sketch-fg);box-shadow:0 24px 90px #0004;overflow:hidden;font:13px/1.4 system-ui}
6017
5903
  .codexSketchDialog[open]{display:flex;flex-direction:column;gap:8px}
6018
5904
  .codexSketchDialog::backdrop{background:#0005;backdrop-filter:blur(12px)}
6019
5905
  .codexSketchDialog *{box-sizing:border-box}
@@ -6021,37 +5907,36 @@ window.__ModuleLoader__.load({
6021
5907
  .codexSketchDialog button:disabled{opacity:.35;cursor:default}
6022
5908
  .codexSketchDialog .codexSketchConfirm:disabled{background:color-mix(in srgb,var(--sketch-fg) 12%,transparent);color:var(--sketch-muted);opacity:1}
6023
5909
  .codexSketchDialog .codexSketchSwatch::before{box-shadow:0 0 0 1px color-mix(in srgb,var(--sketch-fg) 28%,transparent)}
6024
- .codexSketchDialog button:focus-visible,.codexSketchCustom:focus-within,.codexSketchDialog input:focus-visible{outline:2px solid #0a84ff;outline-offset:3px}
6025
- .codexSketchTop{display:flex;align-items:center;justify-content:space-between;gap:8px}
5910
+ .codexSketchDialog button:focus-visible,.codexSketchCustom:focus-within,.codexSketchDialog input:focus-visible{outline:2px solid var(--sketch-accent);outline-offset:3px}
5911
+ .codexSketchTop{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 2px 4px}
6026
5912
  .codexSketchHeading{display:flex;align-items:center;gap:8px;flex:1}.codexSketchHeading strong{font-size:16px;font-weight:600}.codexSketchHeading>span{font-size:10px;color:var(--sketch-muted);border:1px solid var(--sketch-line);border-radius:6px;padding:1px 5px}
6027
5913
  .codexSketchRound{width:44px;height:44px;border-radius:50%}
6028
- .codexSketchTop>.codexSketchRound,.codexSketchLayersToggle,.codexSketchHistory{background:var(--sketch-glass)!important;border:1px solid var(--sketch-line)!important;box-shadow:0 2px 8px #0001;backdrop-filter:blur(16px)}
6029
- .codexSketchDialog .codexSketchConfirm{min-height:44px;padding:0 16px;border-radius:24px;background:#0a84ff;color:#fff;font-weight:600}
5914
+ .codexSketchTop>.codexSketchRound,.codexSketchLayersToggle,.codexSketchHistory{border:1px solid var(--sketch-line)!important}
5915
+ .codexSketchDialog .codexSketchConfirm{min-height:44px;padding:0 16px;border-radius:24px;background:var(--sketch-accent);color:#fff;font-weight:600}
6030
5916
  .codexSketchUtility{display:flex;justify-content:space-between;align-items:center;margin:0;gap:8px}
6031
- .codexSketchHistory{display:flex;border-radius:24px;padding:0 2px}.codexSketchLayersToggle{height:44px;border-radius:24px;padding:0 10px}.codexSketchLayersToggle>span{font-variant-numeric:tabular-nums;color:var(--sketch-muted)}
5917
+ .codexSketchHistory{display:flex;border-radius:24px;padding:0 2px}.codexSketchLayersToggle{height:44px;border-radius:24px;padding:0 10px}.codexSketchLayersCount{font-variant-numeric:tabular-nums;color:var(--sketch-muted)}
6032
5918
  .codexSketchDialog button:hover:not(:disabled){filter:brightness(.94)}
6033
- .codexLayerBody{position:relative;display:grid;place-items:center;min-width:0;min-height:0;flex:1;container-type:size}
5919
+ .codexLayerBody{position:relative;display:grid;place-items:center;min-width:0;min-height:0;flex:1;container-type:size;padding:8px;border-radius:12px;background:color-mix(in srgb,var(--sketch-fg) 4%,var(--sketch-bg))}
6034
5920
  .codexLayerStudio canvas{display:block;width:min(100cqw,calc(100cqh * var(--sketch-ratio,1)));height:auto;aspect-ratio:var(--sketch-ratio,1);background:white;border-radius:4px;outline:1px solid #0001;box-shadow:0 2px 12px #0002;touch-action:none;cursor:crosshair}
6035
- .codexSketchControls{display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:8px;width:100%;max-width:100%;margin:0;padding:4px 8px;border:1px solid var(--sketch-line);border-radius:14px;background:var(--sketch-glass);box-shadow:0 5px 20px #0001;backdrop-filter:blur(18px)}
6036
- .codexSketchPill{display:flex;gap:4px;justify-content:center}.codexSketchPill button{min-width:46px;min-height:48px;flex-direction:column;gap:3px;padding:3px 5px;border-radius:10px}.codexSketchPill button>span{font-size:11px}
5921
+ .codexSketchControls{display:grid;justify-items:center;gap:4px;padding:2px 6px 4px}.codexSketchOptions{display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:4px 10px;width:100%;padding-top:4px;border-top:1px solid var(--sketch-line)}.codexSketchPicturesToggle{min-height:32px;padding:0 6px;border-radius:8px}
5922
+ .codexSketchPill{position:relative;display:flex;gap:4px;justify-content:center;padding:2px 4px;border:1px solid var(--sketch-line);border-radius:14px;background:var(--sketch-glass)}.codexSketchPill button{min-width:44px;min-height:43px;flex-direction:column;gap:2px;padding:3px 5px;border-radius:10px}.codexSketchPill button>span{font-size:11px}
6037
5923
  .codexSketchPill button[aria-pressed=true],.codexSketchSegment button[aria-pressed=true]{background:color-mix(in srgb,var(--sketch-fg) 9%,transparent);box-shadow:inset 0 0 0 1px var(--sketch-line)}
6038
5924
  .codexLayerBrush{display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:10px;margin:0}
6039
- .codexSketchWidth{display:flex;align-items:center;gap:10px;color:var(--sketch-muted);font-size:11px}.codexSketchWidth input{width:80px;min-height:32px;accent-color:#0a84ff}.codexSketchWidth output{width:20px;font-variant-numeric:tabular-nums}
6040
5925
  .codexSketchSegment{display:flex;padding:2px;border-radius:12px;background:color-mix(in srgb,var(--sketch-fg) 5%,transparent)}.codexSketchSegment button{min-height:40px;padding:0 10px;border-radius:10px;font-size:11px}
6041
5926
  .codexSketchPalette{display:flex;align-items:center;justify-content:center;gap:4px}
6042
5927
  .codexSketchDialog .codexSketchSwatch{position:relative;width:32px;height:40px;border-radius:50%;background:transparent}
6043
5928
  .codexSketchSwatch::before{content:'';width:20px;height:20px;border-radius:50%;background:var(--swatch);box-shadow:inset 0 0 0 1px #8884}
6044
- .codexSketchSwatch[aria-pressed=true]::after{content:'';position:absolute;inset:3px;border:2px solid #0a84ff;border-radius:50%}
5929
+ .codexSketchSwatch[aria-pressed=true]::after{content:'';position:absolute;inset:3px;border:2px solid var(--sketch-accent);border-radius:50%}
6045
5930
  .codexSketchCustom{position:relative;display:grid;place-items:center;width:36px;height:36px;margin:2px;border-radius:50%;background:conic-gradient(#ff3936,#ffcc00,#34c759,#0088ff,#a855f7,#ff3936);cursor:pointer}.codexSketchCustom span{width:24px;height:24px;border:3px solid var(--sketch-bg);border-radius:50%}.codexSketchCustom input{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer}
6046
5931
  .codexSketchHint{max-width:460px;margin:10px auto 0;text-align:center;color:var(--sketch-muted);font-size:11px;line-height:1.5}.codexSketchHint[role=alert]{color:var(--dsw-alias-state-error-primary,#e44)}
6047
5932
  .codexSketchLayers{position:absolute;top:0;right:0;width:216px;max-height:100%;overflow:auto;padding:12px;border:1px solid var(--sketch-line);border-radius:20px;background:var(--sketch-glass);backdrop-filter:blur(24px);box-shadow:0 10px 40px #0003;z-index:2}
6048
5933
  .codexSketchLayers header{display:flex;align-items:center;justify-content:space-between}.codexSketchLayers header button{height:40px;width:40px;border-radius:50%;font-size:22px}
6049
- .codexLayerList{max-height:180px;overflow:auto}.codexLayerRow{display:flex;align-items:center;border-radius:12px;margin:3px 0}.codexLayerRow[data-active=true]{background:color-mix(in srgb,#0a84ff 14%,transparent)}.codexLayerRow button{min-height:40px;padding:0 8px}.codexLayerRow button:last-child{flex:1;justify-content:flex-start;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
5934
+ .codexLayerList{max-height:180px;overflow:auto}.codexLayerRow{display:flex;align-items:center;border-radius:12px;margin:3px 0}.codexLayerRow[data-active=true]{background:color-mix(in srgb,var(--sketch-accent) 14%,transparent)}.codexLayerRow button{min-height:40px;padding:0 8px}.codexLayerRow button:last-child{flex:1;justify-content:flex-start;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
6050
5935
  .codexSketchLayerLabel{display:block;color:var(--sketch-muted);font-size:11px;margin:10px 0 4px}.codexSketchLayers input{width:100%;padding:8px 10px;min-height:38px;font:inherit;color:inherit;background:color-mix(in srgb,var(--sketch-fg) 5%,transparent);border:1px solid var(--sketch-line);border-radius:10px}
6051
5936
  .codexLayerActions{display:grid;grid-template-columns:1fr 1fr;gap:4px;margin-top:8px}.codexLayerActions button{min-height:40px;border-radius:10px;font-size:11px;justify-content:flex-start}.codexSketchClearLayer{width:100%;min-height:40px;margin-top:8px;border-top:1px solid var(--sketch-line)!important;color:var(--dsw-alias-state-error-primary,#e44)!important;font-size:11px!important}
6052
5937
  .codexSketchRatio{height:40px;max-width:80px;padding:0 6px;border:1px solid var(--sketch-line);border-radius:10px;background:var(--sketch-bg);color:var(--sketch-fg);font:inherit;color-scheme:light dark}
6053
- @media(max-width:760px){.codexSketchDialog{width:calc(100vw - 12px);height:97dvh;max-height:97dvh;padding:6px;border-radius:14px}.codexSketchHeading{display:none}.codexSketchTop{gap:4px}.codexSketchUtility{flex:1;justify-content:center;gap:4px}.codexSketchRound{width:36px;height:40px}.codexSketchHistory{padding:0}.codexSketchLayersToggle{padding:0 8px;height:40px}.codexSketchLayersToggle svg,.codexSketchConfirm svg{display:none}.codexSketchDialog .codexSketchConfirm{padding:0 10px;min-height:40px}.codexSketchControls{gap:2px 8px;padding:3px}.codexSketchPill{gap:0}.codexSketchPill button{min-width:44px}.codexSketchPalette{gap:0}.codexSketchWidth>span{display:none}.codexSketchWidth input{width:74px}.codexSketchLayers{width:min(216px,90%);max-height:100%;padding:8px}.codexLayerList{max-height:100px}}
6054
- @media(prefers-reduced-transparency:reduce){.codexSketchControls,.codexSketchLayers{background:var(--sketch-bg);backdrop-filter:none}.codexSketchDialog::backdrop{backdrop-filter:none;background:#0009}}
5938
+ @media(max-width:760px){.codexSketchDialog{width:calc(100vw - 12px);height:97dvh;max-height:97dvh;padding:6px;border-radius:14px}.codexSketchHeading{display:none}.codexSketchTop{gap:4px}.codexSketchUtility{flex:1;justify-content:center;gap:4px}.codexSketchRound{width:36px;height:40px}.codexSketchHistory{padding:0}.codexSketchLayersToggle{padding:0 8px;height:40px}.codexSketchLayersToggle svg,.codexSketchConfirm svg{display:none}.codexSketchDialog .codexSketchConfirm{padding:0 10px;min-height:40px}.codexSketchControls{padding:0}.codexSketchOptions{gap:2px 6px}.codexSketchPill{gap:0}.codexSketchPill button{min-width:44px}.codexSketchPalette{gap:0}.codexSketchLayers{width:min(216px,90%);max-height:100%;padding:8px}.codexLayerList{max-height:100px}}
5939
+ @media(prefers-reduced-transparency:reduce){.codexSketchLayers{background:var(--sketch-bg);backdrop-filter:none}.codexSketchDialog::backdrop{backdrop-filter:none;background:#0009}}
6055
5940
  @media(prefers-contrast:more){.codexSketchDialog{--sketch-line:currentColor}.codexSketchControls,.codexSketchLayers{background:var(--sketch-bg)}}
6056
5941
  .codexSketchFiles>button{height:40px;padding:0 10px;border:1px solid var(--sketch-line);border-radius:12px;background:var(--sketch-glass)}
6057
5942
  .codexSketchFilePanel{position:absolute;z-index:5;top:64px;left:12px;width:min(330px,calc(100% - 24px));max-height:calc(100% - 100px);overflow:auto;padding:14px;border:1px solid var(--sketch-line);border-radius:16px;background:var(--sketch-bg);box-shadow:0 12px 40px #0004;display:flex;flex-direction:column;gap:10px}
@@ -6062,29 +5947,31 @@ window.__ModuleLoader__.load({
6062
5947
  .codexSketchDraftList{max-height:220px;overflow:auto}.codexSketchDraftList>div{display:flex;gap:6px;margin-bottom:6px}.codexSketchDraftList button:first-child{flex:1;min-width:0;justify-content:flex-start;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
6063
5948
  .codexSketchStability{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--sketch-muted)}.codexSketchStability select{height:32px;border:1px solid var(--sketch-line);border-radius:8px;background:var(--sketch-bg);color:var(--sketch-fg);font:inherit}
6064
5949
  @media(max-width:760px){.codexSketchTop{gap:2px}.codexSketchUtility{gap:2px}.codexSketchRound{width:32px}.codexSketchLayersToggle{padding:0 6px}.codexSketchFiles>button{padding:0 6px}.codexSketchRatio{max-width:65px}.codexSketchPill button{min-width:42px}.codexSketchDialog .codexSketchConfirm{padding:0 8px}.codexSketchTop{flex-shrink:0}}
5950
+ @media(max-width:480px){.codexSketchTop{flex-wrap:wrap}.codexSketchUtility{flex:none;margin-left:auto}.codexSketchReplayToggle span,.codexSketchLayersLabel{display:none}.codexSketchDialog .codexSketchLayersToggle svg{display:block}}
5951
+ @media(max-width:360px){.codexSketchPill button{min-width:36px;padding:3px 4px}.codexSketchPill button>span{display:none}}
6065
5952
 
6066
5953
  .codexLayerBody{overflow:hidden}.codexLayerStudio canvas{cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Ccircle cx='12' cy='12' r='7' fill='none' stroke='white' stroke-width='3'/%3E%3Ccircle cx='12' cy='12' r='7' fill='none' stroke='%23333' stroke-width='1'/%3E%3C/svg%3E") 12 12,crosshair}
6067
5954
  .codexSketchDialog .codexSketchSwatch{width:32px;height:32px;padding:0;border-radius:50%;corner-shape:round}.codexSketchSwatch::before{width:22px;height:22px;flex-shrink:0;border-radius:50%;corner-shape:round;clip-path:circle(50%)}.codexSketchSwatch[aria-pressed=true]::after{inset:1px;border:1.5px solid var(--sketch-fg);border-radius:50%;corner-shape:round}.codexSketchCustom{width:30px;height:30px;margin:1px 4px;corner-shape:round;clip-path:circle(50%)}.codexSketchCustom span{width:22px;height:22px;border-width:2px;corner-shape:round}
6068
- .codexSketchPictures{position:absolute;left:0;top:0;z-index:3;background:var(--sketch-bg);border:1px solid var(--sketch-line);border-radius:12px;padding:10px;width:160px;max-height:100%;overflow:auto}.codexSketchPictures header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}.codexSketchPictures>div{display:flex;gap:5px;align-items:center;padding:4px;border:1px solid transparent;border-radius:8px}.codexSketchPictures>div[data-active=true]{border-color:#0a84ff}.codexSketchPictures img{width:90px;height:65px;object-fit:contain}.codexSketchPictures small{color:var(--sketch-muted)}
6069
- .codexSketchViewControls{display:flex;gap:2px;align-items:center}.codexSketchViewControls button{min-height:32px;padding:0 7px;border-radius:8px}.codexSketchKeyPanel{position:absolute;overflow:auto;overscroll-behavior:contain;padding:12px;border:1px solid var(--sketch-line);border-radius:14px;background:var(--sketch-bg);z-index:5;box-shadow:0 8px 30px #0003;scrollbar-width:thin}.codexSketchKeyPanel header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}.codexSketchKeyPanel header button{width:28px;height:28px;border-radius:8px;font-size:20px}.codexSketchKeyPanel label{display:flex;align-items:center;justify-content:space-between;min-height:32px;gap:8px}.codexSketchKeysEnabled{padding-bottom:8px;border-bottom:1px solid var(--sketch-line)}.codexSketchKeysEnabled input{margin:0;accent-color:#0a84ff}.codexSketchKeyGrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 16px;margin:10px 0}.codexSketchKeyPanel input:not([type=checkbox]){width:52px;min-width:0;border:1px solid var(--sketch-line);border-radius:6px;color:inherit;background:color-mix(in srgb,var(--sketch-fg) 4%,transparent);padding:4px;text-align:center;font:inherit}.codexSketchKeyPanel p,.codexSketchKeyPanel small{display:block;color:var(--sketch-muted);font-size:11px;line-height:1.5;margin:0}.codexSketchKeyPanel small{border-top:1px solid var(--sketch-line);padding-top:8px}@media(max-width:380px){.codexSketchKeyGrid{grid-template-columns:1fr}}.codexSketchControls{position:static}
5955
+ .codexSketchPictures{position:absolute;left:0;top:0;z-index:3;background:var(--sketch-bg);border:1px solid var(--sketch-line);border-radius:12px;padding:10px;width:160px;max-height:100%;overflow:auto}.codexSketchPictures header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}.codexSketchPictures>div{display:flex;gap:5px;align-items:center;padding:4px;border:1px solid transparent;border-radius:8px}.codexSketchPictures>div[data-active=true]{border-color:var(--sketch-accent)}.codexSketchPictures img{width:90px;height:65px;object-fit:contain}.codexSketchPictures small{color:var(--sketch-muted)}
5956
+ .codexSketchViewControls{display:flex;gap:2px;align-items:center}.codexSketchViewControls button{min-height:32px;padding:0 7px;border-radius:8px}.codexSketchKeyPanel{position:absolute;overflow:auto;overscroll-behavior:contain;padding:12px;border:1px solid var(--sketch-line);border-radius:14px;background:var(--sketch-bg);z-index:5;box-shadow:0 8px 30px #0003;scrollbar-width:thin}.codexSketchKeyPanel header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}.codexSketchKeyPanel header button{width:28px;height:28px;border-radius:8px;font-size:20px}.codexSketchKeyPanel label{display:flex;align-items:center;justify-content:space-between;min-height:32px;gap:8px}.codexSketchKeysEnabled{padding-bottom:8px;border-bottom:1px solid var(--sketch-line)}.codexSketchKeysEnabled input{margin:0;accent-color:var(--sketch-accent)}.codexSketchKeyGrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 16px;margin:10px 0}.codexSketchKeyPanel input:not([type=checkbox]){width:52px;min-width:0;border:1px solid var(--sketch-line);border-radius:6px;color:inherit;background:color-mix(in srgb,var(--sketch-fg) 4%,transparent);padding:4px;text-align:center;font:inherit}.codexSketchKeyPanel p,.codexSketchKeyPanel small{display:block;color:var(--sketch-muted);font-size:11px;line-height:1.5;margin:0}.codexSketchKeyPanel small{border-top:1px solid var(--sketch-line);padding-top:8px}@media(max-width:380px){.codexSketchKeyGrid{grid-template-columns:1fr}}
6070
5957
 
6071
5958
  .codexSketchCursor{position:fixed;left:0;top:0;z-index:100;pointer-events:none;border:1px solid #222;border-radius:50%;corner-shape:round;box-shadow:0 0 0 1px #fff;box-sizing:border-box}.codexSketchCursor[hidden]{display:none}
6072
5959
 
6073
5960
  .codexSketchFiles{display:flex;gap:6px;align-items:center}.codexSketchFiles>button:disabled{opacity:.45}
6074
- .codexSketchReplay{position:absolute;inset:0;z-index:20;display:flex;flex-direction:column;align-items:center;gap:12px;padding:14px 18px 16px;background:var(--sketch-bg);border-radius:inherit;overflow:hidden}
5961
+ .codexSketchReplay{position:fixed;inset:0;margin:auto;box-sizing:border-box;width:min(1280px,calc(100vw - 24px));height:94dvh;max-width:none;max-height:none;padding:14px 18px 16px;background:var(--sketch-bg);color:var(--sketch-fg);border:1px solid var(--sketch-line);border-radius:inherit;overflow:hidden}.codexSketchReplay[open]{display:flex;flex-direction:column;align-items:center;gap:12px}
6075
5962
  .codexSketchReplay>header{display:flex;width:100%;align-items:center;justify-content:space-between;font-size:15px}
6076
5963
  .codexSketchDialog .codexSketchReplayClose{min-height:36px;padding:0 14px 0 10px;border-radius:18px;background:color-mix(in srgb,var(--sketch-fg) 7%,transparent);font-size:13px}
6077
5964
  .codexSketchReplayStage{flex:1;min-height:0;width:100%;display:flex;align-items:center;justify-content:center;container-type:size}
6078
5965
  .codexSketchReplayStage canvas,.codexSketchReplayStage video{max-width:100%;max-height:100%;border-radius:10px;background:#fff;box-shadow:0 0 0 1px var(--sketch-line),0 10px 36px #0002}
6079
5966
  .codexSketchReplayBar{display:flex;flex-wrap:wrap;width:100%;max-width:820px;align-items:center;justify-content:center;gap:10px;padding:8px 12px;border-radius:26px;background:color-mix(in srgb,var(--sketch-fg) 5%,transparent)}
6080
- .codexSketchReplayBar input[type=range]{flex:1;min-width:140px;height:22px;accent-color:#0a84ff}
5967
+ .codexSketchReplayBar input[type=range]{flex:1;min-width:140px;height:22px;accent-color:var(--sketch-accent)}
6081
5968
  .codexSketchDialog .codexSketchReplayBar>button{min-height:36px;padding:0 14px;border-radius:18px;background:color-mix(in srgb,var(--sketch-fg) 8%,transparent);font-size:13px}
6082
- .codexSketchDialog .codexSketchReplayBar .codexSketchReplayPlay{width:40px;height:40px;min-height:40px;padding:0;border-radius:50%;background:#0a84ff;color:#fff}
5969
+ .codexSketchDialog .codexSketchReplayBar .codexSketchReplayPlay{width:40px;height:40px;min-height:40px;padding:0;border-radius:50%;background:var(--sketch-accent);color:#fff}
6083
5970
  .codexSketchReplayTime{min-width:78px;font-variant-numeric:tabular-nums;color:var(--sketch-muted);font-size:12px}
6084
5971
  .codexSketchReplayRecord i{width:10px;height:10px;border-radius:50%;background:#ff3b30}
6085
5972
  .codexSketchDialog .codexSketchReplayRecord[data-recording]{background:#ff3b30;color:#fff}.codexSketchReplayRecord[data-recording] i{background:#fff;border-radius:2px}
6086
5973
  .codexSketchReplay small{color:var(--sketch-muted);text-align:center}
6087
- .codexSketchReplaySave{display:inline-flex;align-items:center;min-height:36px;padding:0 18px;border-radius:18px;background:#0a84ff;color:#fff;font-size:13px;font-weight:600;text-decoration:none}
5974
+ .codexSketchReplaySave{display:inline-flex;align-items:center;min-height:36px;padding:0 18px;border-radius:18px;background:var(--sketch-accent);color:#fff;font-size:13px;font-weight:600;text-decoration:none}
6088
5975
  `;
6089
5976
  exports.SketchStudio = SketchStudio;
6090
5977
  return module.exports;