@mgamadeus/ddd-design-studio 0.4.0 → 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.
package/dist/index.js CHANGED
@@ -1,29 +1,38 @@
1
1
  'use client';
2
2
  import {
3
+ BoardComments,
3
4
  CODE_PARAM,
4
5
  DEFAULT_DESIGN_STUDIO_TEXTS,
5
6
  DESIGN_REFERENCE_PREFIX,
6
7
  DesignStudioProvider,
8
+ ViewportToolbar,
9
+ WidthDragHandle,
7
10
  boardCodeMatches,
8
11
  boardCodeUrlValue,
9
12
  buildBoardCodeLink,
10
13
  buildBoardDeepLink,
14
+ buildCommentThreads,
11
15
  buildDesignReference,
12
16
  buildThemeReference,
13
17
  codeBelongsToCanvas,
14
18
  cx,
15
19
  findBoardForCode,
20
+ initialViewportForBoard,
21
+ isPinInViewport,
22
+ isResponsiveBoard,
16
23
  normalizeBoardCode,
17
24
  resolveDesignStudioTexts,
18
25
  splitThemeReference,
26
+ useCheckedContentUrl,
19
27
  useDesignStudio,
20
28
  useDesignStudioApi,
21
29
  useDesignStudioComponents,
22
30
  useDesignStudioNotify,
23
31
  useDesignStudioPaths,
24
32
  useDesignStudioRouter,
25
- useDesignStudioTexts
26
- } from "./chunk-YYKTDLFF.js";
33
+ useDesignStudioTexts,
34
+ viewportWithWidth
35
+ } from "./chunk-NCMXGWLC.js";
27
36
 
28
37
  // src/api/createDesignStudioApi.ts
29
38
  var DESIGN_STUDIO_TAG = "DesignStudio";
@@ -435,6 +444,361 @@ var DesignStudioReviewsScreen = ({
435
444
  /* @__PURE__ */ jsx3(StatusCallout, { icon: ClipboardCheck, title: "No reviews imported yet", description: emptyDescription })
436
445
  ] });
437
446
  };
447
+
448
+ // src/screens/DesignStudioSiteScreen.tsx
449
+ import { normalizeDddError as normalizeDddError3 } from "@mgamadeus/ddd-web/api";
450
+ import { ArrowLeft, MapPin, MapPinPlus, MessageSquare as MessageSquare2, X } from "lucide-react";
451
+ import { useCallback, useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
452
+
453
+ // src/site/siteNavigation.ts
454
+ var normalizeSitePath = (path) => {
455
+ const trimmed = path.trim();
456
+ if (/[?#]/.test(trimmed) || trimmed.includes("..") || trimmed.includes("//")) return null;
457
+ const segments = trimmed.split("/").filter((segment) => segment !== "" && segment !== ".");
458
+ return `/${segments.join("/")}`;
459
+ };
460
+ var sitePagesOf = (boards) => {
461
+ const pages = /* @__PURE__ */ new Map();
462
+ for (const board of boards) {
463
+ if (board.route && !pages.has(board.route)) pages.set(board.route, board);
464
+ }
465
+ return pages;
466
+ };
467
+ var startRouteOf = (pages, route) => {
468
+ const normalized = route !== null ? normalizeSitePath(route) : null;
469
+ if (normalized !== null && pages.has(normalized)) return normalized;
470
+ if (pages.has("/")) return "/";
471
+ return pages.keys().next().value ?? null;
472
+ };
473
+ var resolveSiteHref = (href, currentRoute, boards) => {
474
+ const trimmed = href.trim();
475
+ if (trimmed === "" || trimmed.startsWith("#")) return { kind: "anchor", hash: trimmed };
476
+ if (trimmed.startsWith("board:")) {
477
+ const boardKey = trimmed.slice("board:".length).split("#")[0];
478
+ const board2 = boards.find((candidate) => candidate.boardKey === boardKey);
479
+ return board2?.route ? { kind: "page", board: board2, route: board2.route, hash: null } : { kind: "missing", path: trimmed };
480
+ }
481
+ if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) || trimmed.startsWith("//")) return { kind: "external", href: trimmed };
482
+ const hashIndex = trimmed.indexOf("#");
483
+ const hash = hashIndex >= 0 ? trimmed.slice(hashIndex) : null;
484
+ const pathWithQuery = hashIndex >= 0 ? trimmed.slice(0, hashIndex) : trimmed;
485
+ const path = pathWithQuery.split("?")[0];
486
+ const absolutePath = path.startsWith("/") ? path : `${currentRoute.endsWith("/") ? currentRoute : currentRoute.slice(0, currentRoute.lastIndexOf("/") + 1)}${path}`;
487
+ const route = normalizeSitePath(absolutePath);
488
+ const board = route !== null ? sitePagesOf(boards).get(route) : void 0;
489
+ return board && route !== null ? { kind: "page", board, route, hash } : { kind: "missing", path: route ?? path };
490
+ };
491
+ var parseSiteFrameMessage = (data) => {
492
+ if (typeof data !== "object" || data === null) return null;
493
+ const message = data;
494
+ if (message.source !== "design-studio-site") return null;
495
+ if (message.type === "navigate" && typeof message.href === "string") return { type: "navigate", href: message.href };
496
+ if (message.type === "scroll" && typeof message.top === "number" && Number.isFinite(message.top)) {
497
+ return { type: "scroll", top: Math.max(0, Math.round(message.top)) };
498
+ }
499
+ if (message.type === "height" && typeof message.height === "number" && Number.isFinite(message.height)) {
500
+ return { type: "height", height: Math.max(1, Math.min(1e5, Math.round(message.height))) };
501
+ }
502
+ return null;
503
+ };
504
+
505
+ // src/screens/DesignStudioSiteScreen.tsx
506
+ import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
507
+ var DesignStudioSiteScreen = ({ projectKey, canvasKey, route }) => {
508
+ const { api, apiBaseUrl, components, notify, paths, router, useCanWrite } = useDesignStudio();
509
+ const texts = useDesignStudioTexts();
510
+ const { Button, Skeleton, StatusCallout } = components;
511
+ const { Link } = router;
512
+ const navigate = router.useNavigate?.();
513
+ const searchParams = router.useSearchParams();
514
+ const writesAllowed = useCanWrite();
515
+ const themeId = searchParams.get("theme");
516
+ const mode = searchParams.get("mode") === "dark" ? "dark" : "light";
517
+ const themeArgument = themeId ? buildThemeReference(themeId, mode) : void 0;
518
+ const { data, isLoading, error } = api.useCanvasQuery({
519
+ projectKey,
520
+ canvasKey,
521
+ ...themeArgument ? { theme: themeArgument } : {}
522
+ });
523
+ const { data: commentsData } = api.useCanvasCommentsQuery({ projectKey, canvasKey });
524
+ const canvas = data?.designStudioCanvasView;
525
+ const boards = useMemo2(() => canvas?.boards?.elements ?? [], [canvas]);
526
+ const devices = useMemo2(() => canvas?.devices?.elements ?? [], [canvas]);
527
+ const pages = useMemo2(() => sitePagesOf(boards), [boards]);
528
+ const currentRoute = startRouteOf(pages, route);
529
+ const board = currentRoute !== null ? pages.get(currentRoute) ?? null : null;
530
+ const [chosenViewport, setChosenViewport] = useState2(null);
531
+ const viewport = initialViewportForBoard(board, chosenViewport) ?? (board ? chosenViewport ?? { width: board.width ?? 390, height: board.height ?? 844, deviceKey: null } : null);
532
+ const [pageScrollTop, setPageScrollTop] = useState2(0);
533
+ const [showsDeviceFrame, setShowsDeviceFrame] = useState2(false);
534
+ const [isCommenting, setIsCommenting] = useState2(false);
535
+ const [isPlacingPin, setIsPlacingPin] = useState2(false);
536
+ const [pendingPin, setPendingPin] = useState2(null);
537
+ const [highlightedCommentId, setHighlightedCommentId] = useState2(null);
538
+ const [showResolved, setShowResolved] = useState2(false);
539
+ const frameRef = useRef2(null);
540
+ const stageRef = useRef2(null);
541
+ const [stageWidth, setStageWidth] = useState2(0);
542
+ const boardKey = board?.boardKey ?? null;
543
+ useEffect2(() => {
544
+ if (boardKey === null) return;
545
+ setPageScrollTop(0);
546
+ setPendingPin(null);
547
+ setIsPlacingPin(false);
548
+ }, [boardKey]);
549
+ useEffect2(() => {
550
+ const stage = stageRef.current;
551
+ if (!stage || typeof ResizeObserver === "undefined") return;
552
+ const observer = new ResizeObserver(() => setStageWidth(stage.clientWidth));
553
+ observer.observe(stage);
554
+ setStageWidth(stage.clientWidth);
555
+ return () => observer.disconnect();
556
+ }, []);
557
+ const goToRoute = useCallback(
558
+ (nextRoute) => {
559
+ if (!paths.site) return;
560
+ const query = themeId ? `?theme=${encodeURIComponent(themeId)}&mode=${mode}` : "";
561
+ const href = `${paths.site(projectKey, canvasKey, nextRoute)}${query}`;
562
+ if (navigate) navigate(href);
563
+ else if (typeof window !== "undefined") window.location.assign(href);
564
+ },
565
+ [paths, projectKey, canvasKey, themeId, mode, navigate]
566
+ );
567
+ useEffect2(() => {
568
+ const onMessage = (event) => {
569
+ if (!frameRef.current || event.source !== frameRef.current.contentWindow) return;
570
+ const message = parseSiteFrameMessage(event.data);
571
+ if (!message || currentRoute === null) return;
572
+ if (message.type === "scroll") {
573
+ setPageScrollTop(message.top);
574
+ return;
575
+ }
576
+ if (message.type === "height") return;
577
+ const target = resolveSiteHref(message.href, currentRoute, boards);
578
+ if (target.kind === "page") {
579
+ if (target.route !== currentRoute) goToRoute(target.route);
580
+ } else if (target.kind === "external") {
581
+ notify.info(texts.siteExternalLink(target.href));
582
+ } else if (target.kind === "missing") {
583
+ notify.info(texts.sitePageMissing(target.path));
584
+ }
585
+ };
586
+ window.addEventListener("message", onMessage);
587
+ return () => window.removeEventListener("message", onMessage);
588
+ });
589
+ const width = viewport?.width ?? 390;
590
+ const screenHeight = viewport?.height ?? 844;
591
+ const bezelPadding = showsDeviceFrame ? 24 : 0;
592
+ const scale = stageWidth > 0 ? Math.min(1, (stageWidth - 48) / (width + bezelPadding)) : 1;
593
+ const siteHtmlUrl = board?.htmlUrl ? `${board.htmlUrl}&site=1` : null;
594
+ const htmlUrl = useCheckedContentUrl(siteHtmlUrl ? `${apiBaseUrl}${siteHtmlUrl}` : void 0);
595
+ const threads = useMemo2(
596
+ () => buildCommentThreads(
597
+ (commentsData?.designStudioComments.elements ?? []).filter((comment) => comment.boardKey === boardKey)
598
+ ),
599
+ [commentsData, boardKey]
600
+ );
601
+ const shownViewport = board && isResponsiveBoard(board) ? viewport : null;
602
+ const pinnedThreads = threads.filter(
603
+ (thread) => thread.pinNumber !== null && (showResolved || !thread.root.isResolved) && isPinInViewport(thread.root, shownViewport)
604
+ );
605
+ const placePin = (event) => {
606
+ const rect = event.currentTarget.getBoundingClientRect();
607
+ setPendingPin({
608
+ x: Math.round((event.clientX - rect.left) / scale),
609
+ y: Math.round((event.clientY - rect.top) / scale + pageScrollTop),
610
+ viewport: shownViewport
611
+ });
612
+ setIsPlacingPin(false);
613
+ setIsCommenting(true);
614
+ };
615
+ if (error) {
616
+ return /* @__PURE__ */ jsx4(
617
+ StatusCallout,
618
+ {
619
+ tone: "destructive",
620
+ title: "The site could not be loaded",
621
+ description: normalizeDddError3(error, "Request failed").message
622
+ }
623
+ );
624
+ }
625
+ if (isLoading || !canvas) return /* @__PURE__ */ jsx4(Skeleton, { className: "h-[70vh] w-full rounded-2xl" });
626
+ if (currentRoute === null || !board || !viewport) {
627
+ return /* @__PURE__ */ jsx4(
628
+ StatusCallout,
629
+ {
630
+ title: "This canvas has no pages",
631
+ description: 'A board becomes a page with "route": "/path" in canvas.json or <meta name="design-route" content="/path"> in its file.'
632
+ }
633
+ );
634
+ }
635
+ const requestedRoute = route ? route : "/";
636
+ const isRequestedRouteMissing = requestedRoute !== currentRoute && route !== null && route !== "";
637
+ return /* @__PURE__ */ jsxs4("div", { className: "flex h-[calc(100dvh-4rem)] min-h-0 flex-col overflow-hidden rounded-3xl bg-card ring-1 ring-foreground/5", children: [
638
+ /* @__PURE__ */ jsxs4("header", { className: "flex flex-wrap items-center gap-2 border-b border-border px-4 py-2", children: [
639
+ /* @__PURE__ */ jsxs4(Link, { href: paths.canvas(projectKey, canvasKey), className: "flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground", children: [
640
+ /* @__PURE__ */ jsx4(ArrowLeft, { className: "size-4", "aria-hidden": true }),
641
+ " ",
642
+ canvas.label ?? canvasKey
643
+ ] }),
644
+ /* @__PURE__ */ jsx4("span", { className: "text-muted-foreground", children: "/" }),
645
+ /* @__PURE__ */ jsx4(
646
+ "select",
647
+ {
648
+ "aria-label": "Page",
649
+ className: "h-8 rounded-lg border border-border bg-card px-2 text-sm",
650
+ value: currentRoute,
651
+ onChange: (event) => goToRoute(event.target.value),
652
+ children: [...pages.entries()].map(([pageRoute, pageBoard]) => /* @__PURE__ */ jsxs4("option", { value: pageRoute, children: [
653
+ pageRoute,
654
+ " \xB7 ",
655
+ pageBoard.title ?? pageBoard.boardKey
656
+ ] }, pageRoute))
657
+ }
658
+ ),
659
+ isRequestedRouteMissing && /* @__PURE__ */ jsx4("span", { className: "text-xs text-warning", children: texts.sitePageMissing(requestedRoute) }),
660
+ /* @__PURE__ */ jsxs4("div", { className: "ml-auto flex items-center gap-2", children: [
661
+ /* @__PURE__ */ jsxs4(
662
+ Button,
663
+ {
664
+ variant: isPlacingPin ? "default" : "outline",
665
+ size: "sm",
666
+ disabled: !writesAllowed,
667
+ "aria-pressed": isPlacingPin,
668
+ onClick: () => setIsPlacingPin((placing) => !placing),
669
+ children: [
670
+ /* @__PURE__ */ jsx4(MapPinPlus, {}),
671
+ " ",
672
+ isPlacingPin ? "Click on the page\u2026" : "Add pin"
673
+ ]
674
+ }
675
+ ),
676
+ /* @__PURE__ */ jsxs4(
677
+ Button,
678
+ {
679
+ variant: isCommenting ? "default" : "outline",
680
+ size: "sm",
681
+ "aria-pressed": isCommenting,
682
+ onClick: () => setIsCommenting((open) => !open),
683
+ children: [
684
+ /* @__PURE__ */ jsx4(MessageSquare2, {}),
685
+ " ",
686
+ threads.filter((thread) => !thread.root.isResolved).length
687
+ ]
688
+ }
689
+ )
690
+ ] })
691
+ ] }),
692
+ /* @__PURE__ */ jsx4(
693
+ ViewportToolbar,
694
+ {
695
+ devices,
696
+ viewport,
697
+ hiddenPinCount: 0,
698
+ showsDeviceFrame,
699
+ onShowsDeviceFrameChange: setShowsDeviceFrame,
700
+ onViewportChange: setChosenViewport
701
+ }
702
+ ),
703
+ /* @__PURE__ */ jsxs4("div", { className: "flex min-h-0 flex-1", children: [
704
+ /* @__PURE__ */ jsx4("div", { ref: stageRef, className: "flex min-h-0 flex-1 items-start justify-center overflow-auto bg-tint p-6", children: /* @__PURE__ */ jsx4("div", { style: { width: (width + bezelPadding) * scale, height: (screenHeight + bezelPadding) * scale }, children: /* @__PURE__ */ jsxs4(
705
+ "div",
706
+ {
707
+ className: cx("relative origin-top-left", showsDeviceFrame && "rounded-[28px] bg-foreground p-3 shadow-surface-raised"),
708
+ style: { transform: scale !== 1 ? `scale(${scale})` : void 0, width: width + bezelPadding },
709
+ children: [
710
+ /* @__PURE__ */ jsxs4("div", { className: "relative overflow-hidden bg-card", style: { width, height: screenHeight }, children: [
711
+ htmlUrl && /* @__PURE__ */ jsx4(
712
+ "iframe",
713
+ {
714
+ ref: frameRef,
715
+ src: htmlUrl,
716
+ title: board.title ?? board.boardKey ?? "Page",
717
+ sandbox: "allow-scripts",
718
+ referrerPolicy: "no-referrer",
719
+ width,
720
+ height: screenHeight,
721
+ className: "absolute inset-0 border-0 bg-transparent"
722
+ },
723
+ htmlUrl
724
+ ),
725
+ isPlacingPin && /* @__PURE__ */ jsx4(
726
+ "button",
727
+ {
728
+ type: "button",
729
+ "aria-label": "Place the pin here",
730
+ className: "absolute inset-0 z-10 cursor-crosshair bg-brand/10",
731
+ onClick: placePin
732
+ }
733
+ ),
734
+ pinnedThreads.map((thread) => /* @__PURE__ */ jsx4(
735
+ "button",
736
+ {
737
+ type: "button",
738
+ "aria-label": `Comment ${thread.pinNumber}`,
739
+ onClick: () => {
740
+ setHighlightedCommentId(Number(thread.root.id));
741
+ setIsCommenting(true);
742
+ },
743
+ className: cx(
744
+ "absolute z-20 flex size-7 -translate-x-1/2 -translate-y-full items-center justify-center rounded-full rounded-bl-none text-xs font-bold shadow-surface-raised ring-2 ring-card",
745
+ thread.root.isResolved ? "bg-muted text-muted-foreground" : "bg-primary text-primary-foreground",
746
+ highlightedCommentId === Number(thread.root.id) && "scale-110 ring-brand"
747
+ ),
748
+ style: { left: thread.root.x ?? 0, top: (thread.root.y ?? 0) - pageScrollTop },
749
+ children: thread.pinNumber
750
+ },
751
+ String(thread.root.id)
752
+ )),
753
+ pendingPin && /* @__PURE__ */ jsx4(
754
+ "span",
755
+ {
756
+ className: "absolute z-20 flex size-7 -translate-x-1/2 -translate-y-full items-center justify-center rounded-full rounded-bl-none bg-brand text-card shadow-surface-raised ring-2 ring-card",
757
+ style: { left: pendingPin.x, top: pendingPin.y - pageScrollTop },
758
+ "aria-hidden": true,
759
+ children: /* @__PURE__ */ jsx4(MapPin, { className: "size-4" })
760
+ }
761
+ )
762
+ ] }),
763
+ /* @__PURE__ */ jsx4(
764
+ WidthDragHandle,
765
+ {
766
+ scale,
767
+ width,
768
+ onWidthChange: (nextWidth) => setChosenViewport(viewportWithWidth(viewport, nextWidth))
769
+ }
770
+ )
771
+ ]
772
+ }
773
+ ) }) }),
774
+ isCommenting && /* @__PURE__ */ jsxs4("aside", { className: "flex min-h-0 w-full max-w-[400px] flex-col border-l border-border", children: [
775
+ /* @__PURE__ */ jsxs4("div", { className: "flex items-center justify-between px-5 pt-4", children: [
776
+ /* @__PURE__ */ jsx4("p", { className: "text-sm font-semibold", children: board.title ?? board.boardKey }),
777
+ /* @__PURE__ */ jsx4(Button, { variant: "ghost", size: "icon", "aria-label": "Close comments", onClick: () => setIsCommenting(false), children: /* @__PURE__ */ jsx4(X, {}) })
778
+ ] }),
779
+ /* @__PURE__ */ jsx4("div", { className: "min-h-0 flex-1 overflow-y-auto px-5 py-4", children: /* @__PURE__ */ jsx4(
780
+ BoardComments,
781
+ {
782
+ projectKey,
783
+ canvasKey,
784
+ board,
785
+ threads,
786
+ pendingPin,
787
+ onClearPendingPin: () => setPendingPin(null),
788
+ highlightedCommentId,
789
+ onHighlightComment: setHighlightedCommentId,
790
+ writesAllowed,
791
+ showResolved,
792
+ onShowResolvedChange: setShowResolved,
793
+ pinHint: "\u201CAdd pin\u201D marks a spot on the page",
794
+ onCopyThreadReference: () => void 0,
795
+ onSelectViewport: isResponsiveBoard(board) ? setChosenViewport : void 0
796
+ }
797
+ ) })
798
+ ] })
799
+ ] })
800
+ ] });
801
+ };
438
802
  export {
439
803
  CODE_PARAM,
440
804
  DEFAULT_DESIGN_STUDIO_TEXTS,
@@ -444,6 +808,7 @@ export {
444
808
  DesignStudioProjectScreen,
445
809
  DesignStudioProvider,
446
810
  DesignStudioReviewsScreen,
811
+ DesignStudioSiteScreen,
447
812
  boardCodeMatches,
448
813
  boardCodeUrlValue,
449
814
  buildBoardCodeLink,