@mgamadeus/ddd-design-studio 0.4.1 → 0.5.0

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.
@@ -0,0 +1,860 @@
1
+ 'use client';
2
+
3
+ // src/canvas/deviceViewport.ts
4
+ var FRAME_GAP = 48;
5
+ var FRAME_LABEL_HEIGHT = 40;
6
+ var MINIMUM_VIEWPORT_WIDTH = 240;
7
+ var MAXIMUM_VIEWPORT_WIDTH = 3840;
8
+ var MAX_PAGE_CANVAS_HEIGHT = 8e3;
9
+ var isResponsiveBoard = (board) => Boolean(board?.isResponsive && (board.frames?.elements?.length ?? 0) > 0);
10
+ var framesOf = (board) => board?.frames?.elements ?? [];
11
+ var viewportOfDevice = (device) => ({
12
+ width: device.width ?? 0,
13
+ height: device.height ?? 0,
14
+ deviceKey: device.deviceKey ?? null
15
+ });
16
+ var initialViewportForBoard = (board, current) => {
17
+ if (!isResponsiveBoard(board)) return null;
18
+ if (current) return current;
19
+ const firstFrame = framesOf(board)[0];
20
+ return { width: firstFrame.width ?? 0, height: firstFrame.height ?? 0, deviceKey: firstFrame.deviceKey ?? null };
21
+ };
22
+ var rotateViewport = (viewport, devices) => {
23
+ const rotated = { width: viewport.height, height: viewport.width };
24
+ const matchingDevice = devices.find((device) => device.width === rotated.width && device.height === rotated.height);
25
+ return { ...rotated, deviceKey: matchingDevice?.deviceKey ?? null };
26
+ };
27
+ var viewportWithWidth = (viewport, width) => ({
28
+ width: Math.round(Math.max(MINIMUM_VIEWPORT_WIDTH, Math.min(MAXIMUM_VIEWPORT_WIDTH, width))),
29
+ height: viewport.height,
30
+ deviceKey: null
31
+ });
32
+ var viewportLabel = (viewport, devices) => {
33
+ const device = viewport.deviceKey ? devices.find((candidate) => candidate.deviceKey === viewport.deviceKey) : void 0;
34
+ return `${device?.label ?? (viewport.deviceKey ?? "Free width")} \xB7 ${viewport.width} \xD7 ${viewport.height}`;
35
+ };
36
+ var pageHeightAtWidth = (board, width, viewportHeight) => {
37
+ const frames = framesOf(board).filter((frame) => (frame.pageHeight ?? 0) > 0 && (frame.width ?? 0) > 0);
38
+ const exactFrame = frames.find((frame) => frame.width === width);
39
+ if (exactFrame) return Math.max(viewportHeight, exactFrame.pageHeight ?? 0);
40
+ if (frames.length === 0) return viewportHeight * 3;
41
+ const nearestFrame = frames.reduce(
42
+ (nearest, frame) => Math.abs((frame.width ?? 0) - width) < Math.abs((nearest.width ?? 0) - width) ? frame : nearest
43
+ );
44
+ return Math.max(viewportHeight, Math.round((nearestFrame.pageHeight ?? 0) * (nearestFrame.width ?? 1) / Math.max(1, width)));
45
+ };
46
+ var frameCanvasHeight = (frame, mode) => {
47
+ const viewportHeight = frame.height ?? 0;
48
+ if (mode === "viewport") return viewportHeight;
49
+ return Math.min(MAX_PAGE_CANVAS_HEIGHT, Math.max(viewportHeight, frame.pageHeight ?? viewportHeight));
50
+ };
51
+ var boardCanvasSize = (board, mode) => {
52
+ if (!isResponsiveBoard(board)) return { width: board.width ?? 390, height: board.height ?? 844 };
53
+ const frames = framesOf(board);
54
+ const width = frames.reduce((sum, frame) => sum + (frame.width ?? 0), 0) + FRAME_GAP * (frames.length - 1);
55
+ const height = FRAME_LABEL_HEIGHT + Math.max(...frames.map((frame) => frameCanvasHeight(frame, mode)));
56
+ return { width, height };
57
+ };
58
+ var viewportOfComment = (comment) => comment.viewportWidth ? { width: comment.viewportWidth, height: comment.viewportHeight ?? comment.viewportWidth, deviceKey: comment.deviceKey ?? null } : null;
59
+ var isPinInViewport = (comment, viewport) => {
60
+ const commentViewport = viewportOfComment(comment);
61
+ if (!viewport) return commentViewport === null;
62
+ return commentViewport !== null && commentViewport.width === viewport.width;
63
+ };
64
+ var viewportReferenceText = (viewport) => `${viewport.width}x${viewport.height}${viewport.deviceKey ? ` ${viewport.deviceKey}` : ""}`;
65
+
66
+ // src/canvas/designReference.ts
67
+ var DESIGN_REFERENCE_PREFIX = "[design-ref]";
68
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
69
+ var buildDesignReference = (input) => {
70
+ const fields = [
71
+ `${DESIGN_REFERENCE_PREFIX} ${oneLine(input.projectName)} \u203A ${oneLine(input.canvasName)} \u203A ${oneLine(input.boardTitle)}`,
72
+ ...input.boardCode ? [`code ${oneLine(input.boardCode)}`] : [],
73
+ `file ${input.boardKey}`,
74
+ `canvas ${input.projectKey}/${input.canvasKey}`,
75
+ `v${input.contentHash ? input.contentHash.slice(0, 7) : "?"}`,
76
+ `theme ${input.themeReference || "none"}`,
77
+ ...input.viewport ? [`viewport ${viewportReferenceText(input.viewport)}`] : []
78
+ ];
79
+ if (input.region) {
80
+ const { x, y, width, height } = input.region;
81
+ fields.push(`region ${Math.round(x)},${Math.round(y)},${Math.round(width)},${Math.round(height)}`);
82
+ }
83
+ if (input.comment) {
84
+ const position = input.comment.x != null && input.comment.y != null ? ` at ${Math.round(input.comment.x)},${Math.round(input.comment.y)}` : "";
85
+ fields.push(`comment ${input.comment.id}${position}`);
86
+ }
87
+ fields.push(input.url);
88
+ const lines = [fields.join(" \xB7 ")];
89
+ for (const commentLine of input.comment?.lines ?? []) {
90
+ if (commentLine.trim()) lines.push(`comment: ${oneLine(commentLine)}`);
91
+ }
92
+ if (input.note?.trim()) lines.push(`note: ${oneLine(input.note)}`);
93
+ return lines.join("\n");
94
+ };
95
+ var buildBoardDeepLink = (pageUrl, boardKey, themeId, mode, viewport) => {
96
+ const url = new URL(pageUrl);
97
+ url.search = "";
98
+ url.hash = "";
99
+ url.searchParams.set("board", boardKey);
100
+ if (themeId) {
101
+ url.searchParams.set("theme", themeId);
102
+ url.searchParams.set("mode", mode);
103
+ }
104
+ if (viewport) url.searchParams.set("vp", viewport);
105
+ return url.toString().replace(/%2C/gi, ",").replace(/%3A/gi, ":");
106
+ };
107
+ var copyTextToClipboard = async (text) => {
108
+ if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
109
+ try {
110
+ await navigator.clipboard.writeText(text);
111
+ return true;
112
+ } catch {
113
+ }
114
+ }
115
+ if (typeof document === "undefined") return false;
116
+ const textarea = document.createElement("textarea");
117
+ textarea.value = text;
118
+ textarea.setAttribute("readonly", "");
119
+ textarea.style.position = "fixed";
120
+ textarea.style.opacity = "0";
121
+ document.body.appendChild(textarea);
122
+ textarea.select();
123
+ const isCopied = document.execCommand("copy");
124
+ textarea.remove();
125
+ return isCopied;
126
+ };
127
+
128
+ // src/canvas/boardKey.ts
129
+ var boardCodeOf = (boardKey) => boardKey.replace(/(?:\.dc)?\.html$/, "");
130
+
131
+ // src/canvas/boardCode.ts
132
+ var CODE_PARAM = "code";
133
+ var normalizeBoardCode = (code) => code.toUpperCase().replace(/[^A-Z0-9]/g, "");
134
+ var codeParts = (code) => code.trim().toUpperCase().split(/[\s-]+/).filter(Boolean);
135
+ var boardCodeMatches = (typedCode, boardCode) => {
136
+ const typed = normalizeBoardCode(typedCode);
137
+ if (!typed || !boardCode) return false;
138
+ const parts = codeParts(boardCode);
139
+ return parts.some((_, index) => parts.slice(index).join("") === typed);
140
+ };
141
+ var codeBelongsToCanvas = (typedCode, canvasCode) => {
142
+ const typed = normalizeBoardCode(typedCode);
143
+ if (!typed || !canvasCode) return false;
144
+ const parts = codeParts(canvasCode);
145
+ return parts.some((_, index) => {
146
+ const prefix = parts.slice(index).join("");
147
+ return typed.length > prefix.length && typed.startsWith(prefix);
148
+ });
149
+ };
150
+ var boardCodeUrlValue = (code) => codeParts(code).join("-");
151
+ var buildBoardCodeLink = (canvasPageUrl, code, themeId, mode) => {
152
+ const url = new URL(canvasPageUrl);
153
+ url.search = "";
154
+ url.hash = "";
155
+ url.searchParams.set(CODE_PARAM, boardCodeUrlValue(code));
156
+ if (themeId) {
157
+ url.searchParams.set("theme", themeId);
158
+ url.searchParams.set("mode", mode);
159
+ }
160
+ return url.toString().replace(/%3A/gi, ":");
161
+ };
162
+ var findBoardForCode = (boards, typedCode) => {
163
+ const byCode = boards.filter((board) => boardCodeMatches(typedCode, board.code));
164
+ if (byCode.length > 0) return byCode.length === 1 ? byCode[0] : null;
165
+ const typed = typedCode.trim().toLowerCase();
166
+ const byName = boards.filter((board) => board.boardKey && boardCodeOf(board.boardKey).toLowerCase() === typed);
167
+ return byName.length === 1 ? byName[0] : null;
168
+ };
169
+
170
+ // src/canvas/designTheme.ts
171
+ var splitThemeReference = (themeReference) => {
172
+ const reference = (themeReference ?? "").trim();
173
+ if (!reference) return null;
174
+ for (const mode of ["light", "dark"]) {
175
+ if (reference.endsWith(`:${mode}`)) return { themeId: reference.slice(0, -(mode.length + 1)), mode };
176
+ }
177
+ return { themeId: reference, mode: "light" };
178
+ };
179
+ var buildThemeReference = (themeId, mode) => mode === "dark" ? `${themeId}:dark` : themeId;
180
+
181
+ // src/provider/texts.ts
182
+ var DEFAULT_DESIGN_STUDIO_TEXTS = {
183
+ referencesCopied: (count) => count > 1 ? `References copied (${count})` : "Reference copied",
184
+ boardsUpdated: (count) => count === 1 ? "1 board updated" : `${count} boards updated`,
185
+ showUpdatedBoard: "Show",
186
+ canvasUpToDate: "Canvas is up to date",
187
+ reload: "Reload (R)",
188
+ thumbnailsFailed: "Thumbnails failed \xB7 try again",
189
+ thumbnailsWaitingForRenderer: (themeLabel) => `Thumbnails for ${themeLabel} are waiting for the renderer`,
190
+ thumbnailsRendering: (themeLabel) => `Thumbnails for ${themeLabel} are being rendered`,
191
+ thumbnailsFallbackThemeLabel: "this look",
192
+ thumbnailsMissing: (count) => count === 1 ? "1 board has no thumbnail in this look yet; it appears as soon as it is rendered." : `${count} boards have no thumbnail in this look yet; they appear as soon as they are rendered.`,
193
+ thumbnailsLastError: (error) => `Last error: ${error}`,
194
+ themeWithoutDarkMode: "This theme has no dark mode",
195
+ thumbnailMissing: "No thumbnail yet",
196
+ thumbnailLoading: "Loading\u2026",
197
+ sitePageMissing: (path) => `No page for ${path}`,
198
+ siteExternalLink: (href) => `External link, not followed: ${href}`,
199
+ openAsWebsite: "Open as website",
200
+ referenceNotePlaceholder: "What should change? (optional, goes into the reference)",
201
+ boardCodeNotFound: (code) => `No board has the code ${code}`,
202
+ boardLinkCopied: (code) => `Link to ${code} copied`,
203
+ copyBoardLink: "Copy link"
204
+ };
205
+ var resolveDesignStudioTexts = (texts) => {
206
+ if (!texts) return DEFAULT_DESIGN_STUDIO_TEXTS;
207
+ const defined = Object.fromEntries(Object.entries(texts).filter(([, value]) => value !== void 0));
208
+ return { ...DEFAULT_DESIGN_STUDIO_TEXTS, ...defined };
209
+ };
210
+
211
+ // src/provider/DesignStudioProvider.tsx
212
+ import { createContext, useContext, useMemo } from "react";
213
+ import { jsx } from "react/jsx-runtime";
214
+ var DesignStudioContext = createContext(null);
215
+ var DesignStudioProvider = ({ environment, children }) => /* @__PURE__ */ jsx(DesignStudioContext.Provider, { value: environment, children });
216
+ var useDesignStudio = () => {
217
+ const environment = useContext(DesignStudioContext);
218
+ if (!environment) {
219
+ throw new Error("The design studio needs a DesignStudioProvider above it");
220
+ }
221
+ return environment;
222
+ };
223
+ var useDesignStudioApi = () => useDesignStudio().api;
224
+ var useDesignStudioComponents = () => useDesignStudio().components;
225
+ var useDesignStudioRouter = () => useDesignStudio().router;
226
+ var useDesignStudioPaths = () => useDesignStudio().paths;
227
+ var useDesignStudioNotify = () => useDesignStudio().notify;
228
+ var useDesignStudioTexts = () => {
229
+ const { texts } = useDesignStudio();
230
+ return useMemo(() => resolveDesignStudioTexts(texts), [texts]);
231
+ };
232
+
233
+ // src/utils/cx.ts
234
+ import { clsx } from "clsx";
235
+ import { twMerge } from "tailwind-merge";
236
+ var cx = (...inputs) => twMerge(clsx(inputs));
237
+
238
+ // src/canvas/BoardComments.tsx
239
+ import { normalizeDddError } from "@mgamadeus/ddd-web/api";
240
+ import { Bot, CheckCircle2, ClipboardCopy, Flag, History, Hourglass, MapPin, RotateCcw, Trash2 } from "lucide-react";
241
+ import { useState } from "react";
242
+ import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
243
+ var buildCommentThreads = (comments) => {
244
+ const repliesByRootId = /* @__PURE__ */ new Map();
245
+ for (const comment of comments) {
246
+ if (comment.parentDesignStudioCommentId != null) {
247
+ const replies = repliesByRootId.get(comment.parentDesignStudioCommentId) ?? [];
248
+ replies.push(comment);
249
+ repliesByRootId.set(comment.parentDesignStudioCommentId, replies);
250
+ }
251
+ }
252
+ let pinNumber = 0;
253
+ return comments.filter((comment) => comment.parentDesignStudioCommentId == null).map((root) => ({
254
+ root,
255
+ replies: repliesByRootId.get(Number(root.id)) ?? [],
256
+ pinNumber: root.x != null && root.y != null ? ++pinNumber : null
257
+ }));
258
+ };
259
+ var errorMessage = (error) => normalizeDddError(error, "Request failed").message;
260
+ var CommentLine = ({ comment, isOwn, writesAllowed }) => {
261
+ const { api, components, formatDateTime, notify } = useDesignStudio();
262
+ const { Button } = components;
263
+ const [deleteComment, { isLoading: isDeleting }] = api.useDeleteCommentMutation();
264
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
265
+ /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-1.5 text-xs text-muted-foreground", children: [
266
+ comment.authorKind === "AGENT" && /* @__PURE__ */ jsx2(Bot, { className: "size-3.5 text-brand-emphasis", "aria-label": "Agent" }),
267
+ /* @__PURE__ */ jsx2("span", { className: "font-semibold text-foreground", children: comment.authorName ?? "Unknown" }),
268
+ /* @__PURE__ */ jsxs("span", { children: [
269
+ "\xB7 ",
270
+ formatDateTime(comment.changeHistory?.createdTime)
271
+ ] }),
272
+ isOwn && /* @__PURE__ */ jsx2(
273
+ Button,
274
+ {
275
+ variant: "ghost",
276
+ size: "icon-sm",
277
+ className: "ml-auto size-6",
278
+ "aria-label": "Delete comment",
279
+ disabled: !writesAllowed || isDeleting,
280
+ onClick: () => deleteComment({ designStudioCommentId: Number(comment.id) }).unwrap().catch((error) => notify.error(errorMessage(error))),
281
+ children: /* @__PURE__ */ jsx2(Trash2, { className: "size-3.5" })
282
+ }
283
+ )
284
+ ] }),
285
+ /* @__PURE__ */ jsx2("p", { className: "text-sm whitespace-pre-wrap break-words", children: comment.text })
286
+ ] });
287
+ };
288
+ var ThreadCard = ({
289
+ thread,
290
+ onCopyReference,
291
+ isHighlighted,
292
+ onHighlight,
293
+ authAccountId,
294
+ writesAllowed,
295
+ hasBoardChangedSince,
296
+ isExpiring,
297
+ onSelectViewport
298
+ }) => {
299
+ const { root, replies, pinNumber } = thread;
300
+ const rootViewport = viewportOfComment(root);
301
+ const [replyText, setReplyText] = useState("");
302
+ const { api, components, notify } = useDesignStudio();
303
+ const { Badge, Button, Textarea } = components;
304
+ const [createReply, { isLoading: isReplying }] = api.useReplyToCommentMutation();
305
+ const [resolveThread, { isLoading: isResolving }] = api.useResolveCommentMutation();
306
+ const [reopenThread, { isLoading: isReopening }] = api.useReopenCommentMutation();
307
+ const [patchComment, { isLoading: isPatching }] = api.usePatchCommentMutation();
308
+ const [keepThread, { isLoading: isKeeping }] = api.useKeepCommentMutation();
309
+ const designStudioCommentId = Number(root.id);
310
+ const sendReply = async () => {
311
+ try {
312
+ await createReply({
313
+ designStudioCommentId,
314
+ body: { text: replyText }
315
+ }).unwrap();
316
+ setReplyText("");
317
+ } catch (error) {
318
+ notify.error(errorMessage(error));
319
+ }
320
+ };
321
+ return (
322
+ // biome-ignore lint/a11y/useSemanticElements: an article that highlights its pin on hover / focus, not a control
323
+ /* @__PURE__ */ jsxs(
324
+ "article",
325
+ {
326
+ className: cx(
327
+ "space-y-3 rounded-2xl bg-card p-4 shadow-surface-raised ring-1 ring-foreground/5",
328
+ root.isResolved && "opacity-70",
329
+ isHighlighted && "ring-2 ring-brand"
330
+ ),
331
+ onMouseEnter: onHighlight,
332
+ onFocus: onHighlight,
333
+ role: "group",
334
+ "aria-label": `Comment thread${pinNumber ? ` ${pinNumber}` : ""}`,
335
+ children: [
336
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-1.5", children: [
337
+ pinNumber !== null ? /* @__PURE__ */ jsxs(Badge, { className: "bg-primary text-primary-foreground", children: [
338
+ /* @__PURE__ */ jsx2(MapPin, { "aria-hidden": true }),
339
+ " ",
340
+ pinNumber
341
+ ] }) : /* @__PURE__ */ jsx2(Badge, { variant: "outline", children: "Board" }),
342
+ rootViewport && /* @__PURE__ */ jsxs(
343
+ "button",
344
+ {
345
+ type: "button",
346
+ className: "rounded-full bg-tint px-2 py-0.5 text-xs font-medium text-muted-foreground tabular-nums hover:bg-tint-strong hover:text-foreground disabled:cursor-default",
347
+ title: "Pinned in this viewport: show the board in it",
348
+ disabled: !onSelectViewport,
349
+ onClick: () => onSelectViewport?.(rootViewport),
350
+ children: [
351
+ rootViewport.width,
352
+ " \xD7 ",
353
+ rootViewport.height,
354
+ rootViewport.deviceKey ? ` \xB7 ${rootViewport.deviceKey}` : ""
355
+ ]
356
+ }
357
+ ),
358
+ root.isDecision && /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "border-transparent bg-success/15 text-success", children: [
359
+ /* @__PURE__ */ jsx2(Flag, { "aria-hidden": true }),
360
+ " Decision"
361
+ ] }),
362
+ root.isResolved && /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "border-transparent bg-tint text-muted-foreground", children: [
363
+ "Resolved",
364
+ root.resolvedByName ? ` by ${root.resolvedByName}` : ""
365
+ ] }),
366
+ hasBoardChangedSince && /* @__PURE__ */ jsxs(
367
+ Badge,
368
+ {
369
+ variant: "outline",
370
+ className: "border-transparent bg-warning/15 text-warning",
371
+ title: "The board file is another version than the one this thread was written on",
372
+ children: [
373
+ /* @__PURE__ */ jsx2(History, { "aria-hidden": true }),
374
+ " Board changed since"
375
+ ]
376
+ }
377
+ ),
378
+ isExpiring && /* @__PURE__ */ jsxs(
379
+ Badge,
380
+ {
381
+ variant: "outline",
382
+ className: "border-transparent bg-tint text-muted-foreground",
383
+ title: "Idle threads are deleted; \u201CKeep\u201D or any reply postpones that",
384
+ children: [
385
+ /* @__PURE__ */ jsx2(Hourglass, { "aria-hidden": true }),
386
+ " Expires soon"
387
+ ]
388
+ }
389
+ )
390
+ ] }),
391
+ /* @__PURE__ */ jsx2(CommentLine, { comment: root, isOwn: authAccountId !== null && root.authorAccountId === authAccountId, writesAllowed }),
392
+ replies.map((reply) => /* @__PURE__ */ jsx2("div", { className: "border-l-2 border-border pl-3", children: /* @__PURE__ */ jsx2(
393
+ CommentLine,
394
+ {
395
+ comment: reply,
396
+ isOwn: authAccountId !== null && reply.authorAccountId === authAccountId,
397
+ writesAllowed
398
+ }
399
+ ) }, String(reply.id))),
400
+ /* @__PURE__ */ jsx2(
401
+ Textarea,
402
+ {
403
+ value: replyText,
404
+ onChange: (event) => setReplyText(event.target.value),
405
+ placeholder: "Reply\u2026",
406
+ rows: 2,
407
+ "aria-label": "Reply",
408
+ disabled: !writesAllowed
409
+ }
410
+ ),
411
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
412
+ /* @__PURE__ */ jsx2(Button, { size: "sm", variant: "outline", disabled: !writesAllowed || !replyText.trim() || isReplying, onClick: sendReply, children: "Reply" }),
413
+ /* @__PURE__ */ jsxs(
414
+ Button,
415
+ {
416
+ size: "sm",
417
+ variant: "outline",
418
+ disabled: !writesAllowed || isPatching,
419
+ "aria-pressed": Boolean(root.isDecision),
420
+ onClick: () => patchComment({
421
+ designStudioCommentId,
422
+ body: { isDecision: !root.isDecision }
423
+ }).unwrap().catch((error) => notify.error(errorMessage(error))),
424
+ children: [
425
+ /* @__PURE__ */ jsx2(Flag, {}),
426
+ " ",
427
+ root.isDecision ? "Not a decision" : "Decision"
428
+ ]
429
+ }
430
+ ),
431
+ /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", onClick: () => onCopyReference(thread), "aria-label": "Copy for agent", children: [
432
+ /* @__PURE__ */ jsx2(ClipboardCopy, {}),
433
+ " Copy for agent"
434
+ ] }),
435
+ isExpiring && /* @__PURE__ */ jsx2(
436
+ Button,
437
+ {
438
+ size: "sm",
439
+ variant: "outline",
440
+ disabled: !writesAllowed || isKeeping,
441
+ onClick: () => keepThread({ designStudioCommentId }).unwrap().catch((error) => notify.error(errorMessage(error))),
442
+ children: "Keep"
443
+ }
444
+ ),
445
+ root.isResolved ? /* @__PURE__ */ jsxs(
446
+ Button,
447
+ {
448
+ size: "sm",
449
+ variant: "outline",
450
+ className: "ml-auto",
451
+ disabled: !writesAllowed || isReopening,
452
+ onClick: () => reopenThread({ designStudioCommentId }).unwrap().catch((error) => notify.error(errorMessage(error))),
453
+ children: [
454
+ /* @__PURE__ */ jsx2(RotateCcw, {}),
455
+ " Reopen"
456
+ ]
457
+ }
458
+ ) : /* @__PURE__ */ jsxs(
459
+ Button,
460
+ {
461
+ size: "sm",
462
+ variant: "outline",
463
+ className: "ml-auto",
464
+ disabled: !writesAllowed || isResolving,
465
+ onClick: async () => {
466
+ try {
467
+ await resolveThread({
468
+ designStudioCommentId,
469
+ body: { replyText: replyText.trim() ? replyText : null }
470
+ }).unwrap();
471
+ setReplyText("");
472
+ } catch (error) {
473
+ notify.error(errorMessage(error));
474
+ }
475
+ },
476
+ children: [
477
+ /* @__PURE__ */ jsx2(CheckCircle2, {}),
478
+ " Resolve"
479
+ ]
480
+ }
481
+ )
482
+ ] })
483
+ ]
484
+ }
485
+ )
486
+ );
487
+ };
488
+ var BoardComments = ({
489
+ projectKey,
490
+ canvasKey,
491
+ board,
492
+ threads,
493
+ pendingPin,
494
+ onClearPendingPin,
495
+ highlightedCommentId,
496
+ onHighlightComment,
497
+ writesAllowed,
498
+ showResolved,
499
+ onShowResolvedChange,
500
+ pinHint,
501
+ onCopyThreadReference,
502
+ onSelectViewport
503
+ }) => {
504
+ const [text, setText] = useState("");
505
+ const [isDecision, setIsDecision] = useState(false);
506
+ const { api, components, notify, useCurrentAccountId } = useDesignStudio();
507
+ const { Button, Checkbox, Label, Textarea } = components;
508
+ const [createComment, { isLoading }] = api.useCreateCommentMutation();
509
+ const authAccountId = useCurrentAccountId();
510
+ const { data: expiringData } = api.useExpiringCommentsQuery();
511
+ const expiringCommentIds = new Set(
512
+ (expiringData?.designStudioComments.elements ?? []).map((comment) => Number(comment.id))
513
+ );
514
+ const visibleThreads = showResolved ? threads : threads.filter((thread) => !thread.root.isResolved);
515
+ const resolvedCount = threads.length - threads.filter((thread) => !thread.root.isResolved).length;
516
+ const addComment = async () => {
517
+ try {
518
+ await createComment({
519
+ projectKey,
520
+ canvasKey,
521
+ boardKey: board.boardKey ?? "",
522
+ body: {
523
+ text,
524
+ x: pendingPin?.x ?? null,
525
+ y: pendingPin?.y ?? null,
526
+ viewportWidth: pendingPin?.viewport?.width ?? null,
527
+ viewportHeight: pendingPin?.viewport?.height ?? null,
528
+ deviceKey: pendingPin?.viewport?.deviceKey ?? null,
529
+ isDecision
530
+ }
531
+ }).unwrap();
532
+ setText("");
533
+ setIsDecision(false);
534
+ onClearPendingPin();
535
+ } catch (error) {
536
+ notify.error(errorMessage(error));
537
+ }
538
+ };
539
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
540
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
541
+ /* @__PURE__ */ jsx2(Label, { htmlFor: "design-comment-text", className: "flex items-center gap-1.5", children: pendingPin ? /* @__PURE__ */ jsxs(Fragment, { children: [
542
+ /* @__PURE__ */ jsx2(MapPin, { className: "size-4 text-brand-emphasis", "aria-hidden": true }),
543
+ " Comment at the placed pin"
544
+ ] }) : "New comment on the board" }),
545
+ /* @__PURE__ */ jsx2(
546
+ Textarea,
547
+ {
548
+ id: "design-comment-text",
549
+ value: text,
550
+ onChange: (event) => setText(event.target.value),
551
+ placeholder: pendingPin ? "What should change here?" : `Comment\u2026 (${pinHint})`,
552
+ rows: 3,
553
+ disabled: !writesAllowed
554
+ }
555
+ ),
556
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
557
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
558
+ /* @__PURE__ */ jsx2(
559
+ Checkbox,
560
+ {
561
+ id: "design-comment-decision",
562
+ checked: isDecision,
563
+ onCheckedChange: (checked) => setIsDecision(checked === true),
564
+ disabled: !writesAllowed
565
+ }
566
+ ),
567
+ /* @__PURE__ */ jsx2(Label, { htmlFor: "design-comment-decision", className: "font-normal", children: "Decision" })
568
+ ] }),
569
+ pendingPin && /* @__PURE__ */ jsx2(Button, { size: "sm", variant: "ghost", onClick: onClearPendingPin, children: "Remove pin" }),
570
+ /* @__PURE__ */ jsx2(Button, { size: "sm", className: "ml-auto", disabled: !writesAllowed || !text.trim() || isLoading || !board.boardKey, onClick: addComment, children: "Comment" })
571
+ ] })
572
+ ] }),
573
+ resolvedCount > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
574
+ /* @__PURE__ */ jsx2(
575
+ Checkbox,
576
+ {
577
+ id: "design-comment-show-resolved",
578
+ checked: showResolved,
579
+ onCheckedChange: (checked) => onShowResolvedChange(checked === true)
580
+ }
581
+ ),
582
+ /* @__PURE__ */ jsxs(Label, { htmlFor: "design-comment-show-resolved", className: "font-normal text-muted-foreground", children: [
583
+ "Show ",
584
+ resolvedCount,
585
+ " resolved"
586
+ ] })
587
+ ] }),
588
+ visibleThreads.length === 0 && /* @__PURE__ */ jsx2("p", { className: "text-sm text-muted-foreground", children: "No open comments on this board." }),
589
+ visibleThreads.map((thread) => /* @__PURE__ */ jsx2(
590
+ ThreadCard,
591
+ {
592
+ thread,
593
+ onCopyReference: onCopyThreadReference,
594
+ onSelectViewport,
595
+ isHighlighted: highlightedCommentId === Number(thread.root.id),
596
+ onHighlight: () => onHighlightComment(Number(thread.root.id)),
597
+ authAccountId,
598
+ writesAllowed,
599
+ hasBoardChangedSince: Boolean(thread.root.contentHash && board.contentHash) && thread.root.contentHash !== board.contentHash,
600
+ isExpiring: expiringCommentIds.has(Number(thread.root.id))
601
+ },
602
+ String(thread.root.id)
603
+ ))
604
+ ] });
605
+ };
606
+
607
+ // src/canvas/ViewportControls.tsx
608
+ import { RotateCw, Smartphone } from "lucide-react";
609
+ import { useRef } from "react";
610
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
611
+ var ViewportToolbar = ({
612
+ devices,
613
+ viewport,
614
+ hiddenPinCount,
615
+ showsDeviceFrame,
616
+ onShowsDeviceFrameChange,
617
+ onViewportChange
618
+ }) => {
619
+ const { components } = useDesignStudio();
620
+ const { Button } = components;
621
+ return /* @__PURE__ */ jsxs2("div", { className: "flex flex-wrap items-center gap-2 border-b border-border px-5 py-2 text-sm", children: [
622
+ /* @__PURE__ */ jsxs2("label", { className: "flex items-center gap-2", children: [
623
+ /* @__PURE__ */ jsx3("span", { className: "sr-only", children: "Device" }),
624
+ /* @__PURE__ */ jsxs2(
625
+ "select",
626
+ {
627
+ className: "h-8 rounded-lg border border-border bg-card px-2 text-sm",
628
+ value: viewport.deviceKey ?? "",
629
+ onChange: (event) => {
630
+ const device = devices.find((candidate) => candidate.deviceKey === event.target.value);
631
+ if (device) onViewportChange(viewportOfDevice(device));
632
+ },
633
+ children: [
634
+ viewport.deviceKey === null && /* @__PURE__ */ jsx3("option", { value: "", children: "Free width" }),
635
+ devices.map((device) => /* @__PURE__ */ jsxs2("option", { value: device.deviceKey ?? "", children: [
636
+ device.label,
637
+ " \xB7 ",
638
+ device.width,
639
+ " \xD7 ",
640
+ device.height
641
+ ] }, device.deviceKey ?? ""))
642
+ ]
643
+ }
644
+ )
645
+ ] }),
646
+ /* @__PURE__ */ jsxs2(
647
+ Button,
648
+ {
649
+ variant: "outline",
650
+ size: "sm",
651
+ "aria-label": "Rotate (landscape / portrait)",
652
+ onClick: () => onViewportChange(rotateViewport(viewport, devices)),
653
+ children: [
654
+ /* @__PURE__ */ jsx3(RotateCw, {}),
655
+ " Rotate"
656
+ ]
657
+ }
658
+ ),
659
+ /* @__PURE__ */ jsx3("span", { className: "text-muted-foreground tabular-nums", children: viewportLabel(viewport, devices) }),
660
+ /* @__PURE__ */ jsxs2(
661
+ Button,
662
+ {
663
+ variant: showsDeviceFrame ? "default" : "outline",
664
+ size: "sm",
665
+ "aria-pressed": showsDeviceFrame,
666
+ onClick: () => onShowsDeviceFrameChange(!showsDeviceFrame),
667
+ children: [
668
+ /* @__PURE__ */ jsx3(Smartphone, {}),
669
+ " Device frame"
670
+ ]
671
+ }
672
+ ),
673
+ hiddenPinCount > 0 && /* @__PURE__ */ jsxs2("span", { className: "ml-auto text-xs text-muted-foreground", children: [
674
+ hiddenPinCount,
675
+ " open pin(s) in other widths \u2014 pick their size in the comment list"
676
+ ] })
677
+ ] });
678
+ };
679
+ var WidthDragHandle = ({ scale, width, onWidthChange }) => {
680
+ const dragStartRef = useRef(null);
681
+ return /* @__PURE__ */ jsx3(
682
+ "button",
683
+ {
684
+ type: "button",
685
+ "aria-label": `Viewport width ${width} px: drag to change`,
686
+ className: "absolute top-1/2 -right-6 z-30 h-24 w-3 -translate-y-1/2 cursor-ew-resize touch-none rounded-full bg-foreground/40 hover:bg-foreground/70",
687
+ onPointerDown: (event) => {
688
+ event.currentTarget.setPointerCapture(event.pointerId);
689
+ dragStartRef.current = { clientX: event.clientX, width };
690
+ },
691
+ onPointerMove: (event) => {
692
+ const dragStart = dragStartRef.current;
693
+ if (!dragStart) return;
694
+ onWidthChange(dragStart.width + (event.clientX - dragStart.clientX) / Math.max(0.05, scale));
695
+ },
696
+ onPointerUp: () => {
697
+ dragStartRef.current = null;
698
+ },
699
+ onKeyDown: (event) => {
700
+ if (event.key === "ArrowLeft") onWidthChange(width - 10);
701
+ if (event.key === "ArrowRight") onWidthChange(width + 10);
702
+ }
703
+ }
704
+ );
705
+ };
706
+
707
+ // src/canvas/useCheckedContentUrl.ts
708
+ import { useEffect, useState as useState2 } from "react";
709
+ var MAX_CONCURRENT_LOADS = 2;
710
+ var RETRY_DELAYS_MS = [2e3, 5e3, 15e3, 3e4];
711
+ var MAX_REMEMBERED_URLS = 24;
712
+ var loadedUrls = /* @__PURE__ */ new Set();
713
+ var rememberLoadedUrl = (url) => {
714
+ loadedUrls.delete(url);
715
+ loadedUrls.add(url);
716
+ while (loadedUrls.size > MAX_REMEMBERED_URLS) {
717
+ const oldestUrl = loadedUrls.values().next().value;
718
+ if (oldestUrl === void 0) break;
719
+ loadedUrls.delete(oldestUrl);
720
+ }
721
+ };
722
+ var wasContentUrlLoaded = (url) => Boolean(url && loadedUrls.has(url));
723
+ var activeLoads = 0;
724
+ var waitingLoads = [];
725
+ var acquireLoadSlot = () => new Promise((resolve) => {
726
+ if (activeLoads < MAX_CONCURRENT_LOADS) {
727
+ activeLoads += 1;
728
+ resolve();
729
+ return;
730
+ }
731
+ waitingLoads.push(() => {
732
+ activeLoads += 1;
733
+ resolve();
734
+ });
735
+ });
736
+ var releaseLoadSlot = () => {
737
+ activeLoads -= 1;
738
+ waitingLoads.shift()?.();
739
+ };
740
+ var loadUrl = async (url, signal) => {
741
+ await acquireLoadSlot();
742
+ try {
743
+ if (signal.aborted) return false;
744
+ const response = await fetch(url, { signal, credentials: "omit", referrerPolicy: "no-referrer" });
745
+ if (!response.ok) return false;
746
+ await response.blob();
747
+ return true;
748
+ } catch {
749
+ return false;
750
+ } finally {
751
+ releaseLoadSlot();
752
+ }
753
+ };
754
+ var useCheckedContentUrl = (url) => {
755
+ const [checkedUrl, setCheckedUrl] = useState2(
756
+ () => url && loadedUrls.has(url) ? url : void 0
757
+ );
758
+ useEffect(() => {
759
+ if (!url) {
760
+ setCheckedUrl(void 0);
761
+ return;
762
+ }
763
+ if (loadedUrls.has(url)) {
764
+ rememberLoadedUrl(url);
765
+ setCheckedUrl(url);
766
+ return;
767
+ }
768
+ setCheckedUrl(void 0);
769
+ const abortController = new AbortController();
770
+ let retryTimer;
771
+ let attempt = 0;
772
+ const tryLoad = async () => {
773
+ const isLoaded = await loadUrl(url, abortController.signal);
774
+ if (abortController.signal.aborted) return;
775
+ if (isLoaded) {
776
+ rememberLoadedUrl(url);
777
+ setCheckedUrl(url);
778
+ return;
779
+ }
780
+ const delay = RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)];
781
+ attempt += 1;
782
+ retryTimer = setTimeout(tryLoad, delay);
783
+ };
784
+ void tryLoad();
785
+ return () => {
786
+ abortController.abort();
787
+ if (retryTimer) clearTimeout(retryTimer);
788
+ };
789
+ }, [url]);
790
+ return checkedUrl;
791
+ };
792
+ var useImageRetry = (url) => {
793
+ const [attempt, setAttempt] = useState2(0);
794
+ const [isFailed, setIsFailed] = useState2(false);
795
+ const [previousUrl, setPreviousUrl] = useState2(url);
796
+ if (url !== previousUrl) {
797
+ setPreviousUrl(url);
798
+ setAttempt(0);
799
+ setIsFailed(false);
800
+ }
801
+ useEffect(() => {
802
+ if (!isFailed) return;
803
+ const retryTimer = setTimeout(
804
+ () => {
805
+ setIsFailed(false);
806
+ setAttempt((previousAttempt) => previousAttempt + 1);
807
+ },
808
+ RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)]
809
+ );
810
+ return () => clearTimeout(retryTimer);
811
+ }, [isFailed, attempt]);
812
+ return { imageKey: `${url ?? ""}#${attempt}`, isFailed, onError: () => setIsFailed(true) };
813
+ };
814
+
815
+ export {
816
+ FRAME_GAP,
817
+ FRAME_LABEL_HEIGHT,
818
+ isResponsiveBoard,
819
+ framesOf,
820
+ initialViewportForBoard,
821
+ viewportWithWidth,
822
+ pageHeightAtWidth,
823
+ frameCanvasHeight,
824
+ boardCanvasSize,
825
+ viewportOfComment,
826
+ isPinInViewport,
827
+ DESIGN_REFERENCE_PREFIX,
828
+ buildDesignReference,
829
+ buildBoardDeepLink,
830
+ copyTextToClipboard,
831
+ boardCodeOf,
832
+ CODE_PARAM,
833
+ normalizeBoardCode,
834
+ boardCodeMatches,
835
+ codeBelongsToCanvas,
836
+ boardCodeUrlValue,
837
+ buildBoardCodeLink,
838
+ findBoardForCode,
839
+ splitThemeReference,
840
+ buildThemeReference,
841
+ DEFAULT_DESIGN_STUDIO_TEXTS,
842
+ resolveDesignStudioTexts,
843
+ DesignStudioProvider,
844
+ useDesignStudio,
845
+ useDesignStudioApi,
846
+ useDesignStudioComponents,
847
+ useDesignStudioRouter,
848
+ useDesignStudioPaths,
849
+ useDesignStudioNotify,
850
+ useDesignStudioTexts,
851
+ cx,
852
+ buildCommentThreads,
853
+ BoardComments,
854
+ ViewportToolbar,
855
+ WidthDragHandle,
856
+ wasContentUrlLoaded,
857
+ useCheckedContentUrl,
858
+ useImageRetry
859
+ };
860
+ //# sourceMappingURL=chunk-NCMXGWLC.js.map