@ecomcx/ecomweb-editor 1.30.0 → 1.32.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.
Files changed (95) hide show
  1. package/package.json +3 -3
  2. package/src/locales/en/attrs.ts +10 -0
  3. package/src/locales/en/background.ts +17 -0
  4. package/src/locales/en/block-desc.ts +1 -0
  5. package/src/locales/en/block-style.ts +7 -4
  6. package/src/locales/en/block-titles.ts +1 -0
  7. package/src/locales/en/blocks.ts +10 -2
  8. package/src/locales/en/columns.ts +12 -0
  9. package/src/locales/en/controls.ts +21 -0
  10. package/src/locales/en/hints.ts +215 -1
  11. package/src/locales/en/index.ts +6 -2
  12. package/src/locales/en/layout.ts +32 -0
  13. package/src/locales/en/legacy.ts +1 -1
  14. package/src/locales/en/library.ts +38 -0
  15. package/src/locales/en/parts.ts +12 -0
  16. package/src/locales/en/placeholders.ts +104 -0
  17. package/src/locales/en/presets.ts +6 -0
  18. package/src/locales/en/v2.ts +21 -0
  19. package/src/locales/vi/attrs.ts +10 -0
  20. package/src/locales/vi/background.ts +17 -0
  21. package/src/locales/vi/block-desc.ts +1 -0
  22. package/src/locales/vi/block-style.ts +7 -4
  23. package/src/locales/vi/block-titles.ts +1 -0
  24. package/src/locales/vi/blocks.ts +10 -2
  25. package/src/locales/vi/columns.ts +12 -0
  26. package/src/locales/vi/controls.ts +21 -0
  27. package/src/locales/vi/hints.ts +216 -2
  28. package/src/locales/vi/index.ts +6 -2
  29. package/src/locales/vi/layout.ts +32 -0
  30. package/src/locales/vi/legacy.ts +1 -1
  31. package/src/locales/vi/library.ts +38 -0
  32. package/src/locales/vi/parts.ts +12 -0
  33. package/src/locales/vi/placeholders.ts +103 -0
  34. package/src/locales/vi/presets.ts +6 -0
  35. package/src/locales/vi/v2.ts +21 -0
  36. package/src/shared/panel-store.ts +3 -3
  37. package/src/shared/patterns.ts +3 -52
  38. package/src/shared/style-panel.tsx +2 -2
  39. package/src/shared/types.ts +2 -0
  40. package/src/v2/blocks/columns-inspector.tsx +210 -0
  41. package/src/v2/blocks/compat.tsx +91 -5
  42. package/src/v2/blocks/form.tsx +7 -4
  43. package/src/v2/blocks/index.ts +10 -4
  44. package/src/v2/blocks/inline-style.ts +1 -1
  45. package/src/v2/blocks/layout.tsx +305 -83
  46. package/src/v2/blocks/media.tsx +91 -81
  47. package/src/v2/blocks/resize.tsx +172 -4
  48. package/src/v2/blocks/text.tsx +60 -22
  49. package/src/v2/blocks/theme.tsx +83 -17
  50. package/src/v2/blocks/tools.tsx +50 -5
  51. package/src/v2/blocks/widgets.tsx +85 -20
  52. package/src/v2/canvas/block-list.tsx +21 -6
  53. package/src/v2/canvas/canvas-css.ts +139 -7
  54. package/src/v2/canvas/canvas.tsx +20 -3
  55. package/src/v2/canvas/dnd.ts +34 -3
  56. package/src/v2/canvas/move-animation.ts +94 -0
  57. package/src/v2/canvas/server-block.tsx +7 -4
  58. package/src/v2/canvas/spacing-viz.ts +51 -0
  59. package/src/v2/core/block-presets.ts +68 -0
  60. package/src/v2/core/host.ts +14 -0
  61. package/src/v2/core/registry.ts +3 -1
  62. package/src/v2/core/structure.ts +4 -2
  63. package/src/v2/editor.css +244 -11
  64. package/src/v2/editor.tsx +8 -2
  65. package/src/v2/index.ts +3 -0
  66. package/src/v2/ui/ai.tsx +9 -5
  67. package/src/v2/ui/attr-form.tsx +42 -13
  68. package/src/v2/ui/attr-hints.ts +104 -6
  69. package/src/v2/ui/background-panel.tsx +65 -21
  70. package/src/v2/ui/block-icons.tsx +152 -0
  71. package/src/v2/ui/block-menu.ts +22 -0
  72. package/src/v2/ui/block-style-panel.tsx +14 -3
  73. package/src/v2/ui/color-field.tsx +74 -9
  74. package/src/v2/ui/divider-panel.tsx +58 -0
  75. package/src/v2/ui/group-width.tsx +38 -0
  76. package/src/v2/ui/icon-picker.tsx +51 -0
  77. package/src/v2/ui/inserter.tsx +51 -7
  78. package/src/v2/ui/inspector.tsx +48 -16
  79. package/src/v2/ui/layout-panel.tsx +5 -47
  80. package/src/v2/ui/list-view.tsx +81 -7
  81. package/src/v2/{blocks → ui}/media-actions.tsx +4 -3
  82. package/src/v2/ui/motion-panel.tsx +2 -1
  83. package/src/v2/ui/parts-panel.tsx +164 -0
  84. package/src/v2/ui/pattern-library.tsx +228 -0
  85. package/src/v2/ui/placeholders.tsx +205 -0
  86. package/src/v2/ui/preset-bar.tsx +83 -0
  87. package/src/v2/ui/style-controls.tsx +65 -15
  88. package/src/v2/ui/style-supports.ts +1 -1
  89. package/src/v2/ui/style-tab.tsx +127 -41
  90. package/src/v2/ui/toolbar.tsx +59 -16
  91. package/src/v2/ui/unit-controls.tsx +88 -39
  92. package/src/locales/en/patterns.ts +0 -50
  93. package/src/locales/vi/patterns.ts +0 -50
  94. package/src/shared/patterns-kit.ts +0 -7
  95. package/src/shared/patterns-library.ts +0 -172
@@ -1,16 +1,18 @@
1
- import { ChevronDown, ChevronRight, GripVertical, Lock, Blocks } from "lucide-react";
1
+ import { ChevronDown, ChevronRight, GripVertical, Lock, Blocks, MoreVertical, X, EyeOff } from "lucide-react";
2
2
  import { useCallback, useState } from "react";
3
3
  import { startDrag } from "../canvas/dnd";
4
4
  import { useEditor, useEditorState } from "../context";
5
5
  import { inlineText, type BNode } from "../core/model";
6
6
  import type { BlockType } from "../core/registry";
7
7
  import { cx } from "./attr-form";
8
+ import { isHidden } from "./block-menu";
8
9
 
9
10
  // ---------------------------------------------------------------------------
10
11
  // Cây khối
11
12
  // ---------------------------------------------------------------------------
12
13
  /** Tên hiển thị của một khối trong cây: loại + đoạn chữ đầu. */
13
14
  export function blockLabel(node: BNode, type: BlockType | undefined): string {
15
+ if (typeof node.attrs.customName === "string" && node.attrs.customName) return node.attrs.customName;
14
16
  const text = node.inline ? inlineText(node.inline).trim() : node.content?.find((c) => c.inline && inlineText(c.inline).trim()) ? inlineText(node.content.find((c) => c.inline && inlineText(c.inline).trim())!.inline).trim() : "";
15
17
  const summary = type?.summary?.(node.attrs);
16
18
  const base = type?.title ?? node.type;
@@ -18,16 +20,77 @@ export function blockLabel(node: BNode, type: BlockType | undefined): string {
18
20
  return extra ? `${base} · ${extra.slice(0, 40)}` : base;
19
21
  }
20
22
 
21
- export function ListView() {
23
+ /** Cột trái "Cây khối": tab Cây khối / Dàn ý (tiêu đề + số chữ) và nút đóng. */
24
+ export function ListView({ onClose }: { onClose?(): void }) {
22
25
  const { labels } = useEditor();
26
+ const [tab, setTab] = useState<"tree" | "outline">("tree");
23
27
  const activeId = useEditorState((s) => s.focus[s.focus.length - 1] ?? s.rootId);
24
28
  const doc = useEditorState(useCallback((s) => s.docs[activeId], [activeId]));
25
29
  if (!doc) return null;
26
30
  return (
27
- <div className="ecx-listview" role="tree" aria-label={labels.listView}>
28
- {doc.blocks.map((b, i) => <ListRow key={b.id} node={b} depth={0} first={i === 0} />)}
29
- {!doc.blocks.length && <p className="ecx-muted ecx-list-empty">{labels.listEmpty}</p>}
30
-
31
+ <>
32
+ <div className="ecx-tabs ecx-left-tabs">
33
+ <div className="ecx-tablist" role="tablist">
34
+ <button type="button" role="tab" aria-selected={tab === "tree"} className={tab === "tree" ? "is-active" : undefined} onClick={() => setTab("tree")}>{labels.listView}</button>
35
+ <button type="button" role="tab" aria-selected={tab === "outline"} className={tab === "outline" ? "is-active" : undefined} onClick={() => setTab("outline")}>{labels.outline}</button>
36
+ </div>
37
+ {onClose && <button type="button" className="ecx-left-close" aria-label={labels.close} title={labels.close} onClick={onClose}><X className="ecx-icon" /></button>}
38
+ </div>
39
+ {tab === "outline" ? <Outline blocks={doc.blocks} /> : (
40
+ <div className="ecx-listview" role="tree" aria-label={labels.listView}>
41
+ {doc.blocks.map((b, i) => <ListRow key={b.id} node={b} depth={0} first={i === 0} />)}
42
+ {!doc.blocks.length && <p className="ecx-muted ecx-list-empty">{labels.listEmpty}</p>}
43
+ </div>
44
+ )}
45
+ </>
46
+ );
47
+ }
48
+
49
+ /** Thống kê chữ + dàn ý tiêu đề của tài liệu (như tab Outline của WordPress): báo cấp tiêu đề nhảy cóc, tiêu đề trống. */
50
+ export function outlineOf(blocks: BNode[]) {
51
+ const heads: Array<{ id: string; level: number; text: string; skipped: boolean }> = [];
52
+ let text = "";
53
+ let prev = 0;
54
+ const walk = (list: BNode[]) => list.forEach((b) => {
55
+ if (b.inline) {
56
+ const t = inlineText(b.inline);
57
+ text += ` ${t}`;
58
+ if (b.type === "heading") {
59
+ const level = Number(b.attrs.level) || 2;
60
+ heads.push({ id: b.id, level, text: t.trim(), skipped: prev > 0 && level > prev + 1 });
61
+ prev = level;
62
+ }
63
+ }
64
+ if (b.content) walk(b.content);
65
+ });
66
+ walk(blocks);
67
+ const words = text.trim() ? text.trim().split(/\s+/).length : 0;
68
+ return { heads, words, chars: text.replace(/\s+/g, "").length, minutes: Math.max(1, Math.ceil(words / 200)) };
69
+ }
70
+
71
+ function Outline({ blocks }: { blocks: BNode[] }) {
72
+ const { store, ui, labels } = useEditor();
73
+ const o = outlineOf(blocks);
74
+ return (
75
+ <div className="ecx-outline">
76
+ <dl className="ecx-outline-stats">
77
+ <div><dt>{labels.outlineChars}</dt><dd>{o.chars.toLocaleString()}</dd></div>
78
+ <div><dt>{labels.outlineWords}</dt><dd>{o.words.toLocaleString()}</dd></div>
79
+ <div><dt>{labels.outlineTime}</dt><dd>{o.minutes} {labels.outlineMinutes}</dd></div>
80
+ </dl>
81
+ {o.heads.length ? (
82
+ <ul className="ecx-outline-heads">
83
+ {o.heads.map((h) => (
84
+ <li key={h.id} style={{ paddingLeft: (h.level - 1) * 12 }}>
85
+ <button type="button" onClick={() => { store.select([h.id], { editing: null }); ui.blockEl(h.id)?.scrollIntoView({ block: "center", behavior: "smooth" }); }}>
86
+ <span className="ecx-outline-level">H{h.level}</span>
87
+ <span className={cx(!h.text && "ecx-muted")}>{h.text || labels.outlineEmpty}</span>
88
+ {h.skipped && <em className="ecx-outline-warn">{labels.outlineSkipped}</em>}
89
+ </button>
90
+ </li>
91
+ ))}
92
+ </ul>
93
+ ) : <p className="ecx-muted">{labels.outlineNone}</p>}
31
94
  </div>
32
95
  );
33
96
  }
@@ -46,6 +109,13 @@ function ListRow({ node, depth, first }: { node: BNode; depth: number; first?: b
46
109
  const nestedBlocks = useEditorState(useCallback((s) => (nestedId ? s.docs[nestedId]?.blocks ?? null : null), [nestedId]));
47
110
  const kids = node.content ?? nestedBlocks ?? [];
48
111
  const hasKids = kids.length > 0;
112
+ // Menu ⋮ / chuột phải của dòng = menu khối dùng chung (chọn khối trước, như WordPress); khối trong phần dùng chung lồng thì không
113
+ const openMenu = (x: number, y: number) => {
114
+ if (!store.locate(node.id)) return;
115
+ if (!selected) store.select([node.id], { editing: null });
116
+ const ids = store.getState().selection.ids.includes(node.id) ? store.getState().selection.ids : [node.id];
117
+ ui.openContextMenu({ x, y, ids });
118
+ };
49
119
  return (
50
120
  <div role="treeitem" aria-selected={selected} aria-expanded={hasKids ? open : undefined} aria-level={depth + 1}>
51
121
  <div className={cx("ecx-list-row", selected && "is-selected", nestedId && "is-nested")} style={{ paddingLeft: 8 + depth * 14 }} data-block={node.id}
@@ -56,11 +126,15 @@ function ListRow({ node, depth, first }: { node: BNode; depth: number; first?: b
56
126
  if (e.shiftKey) store.selectRange(node.id);
57
127
  else store.select([node.id], { editing: null });
58
128
  ui.blockEl(node.id)?.scrollIntoView({ block: "nearest", behavior: "smooth" });
59
- }}>
129
+ }}
130
+ onContextMenu={(e) => { e.preventDefault(); openMenu(e.clientX, e.clientY); }}>
60
131
  {hasKids ? <button type="button" className="ecx-twisty" aria-label={open ? ctx.labels.collapse : ctx.labels.expand} onClick={(e) => { e.stopPropagation(); setOpen(!open); }}>{open ? <ChevronDown className="ecx-icon" /> : <ChevronRight className="ecx-icon" />}</button> : <span className="ecx-twisty" />}
61
132
  <Icon className="ecx-icon" />
62
133
  <span className="ecx-list-title">{blockLabel(node, type)}</span>
134
+ {isHidden(node) && <EyeOff className="ecx-icon ecx-icon-sm" aria-label={ctx.labels.hidden} />}
63
135
  {!!(node.attrs.lock || node.attrs.templateLock) && <Lock className="ecx-icon ecx-icon-sm" aria-label={ctx.labels.locked} />}
136
+ <button type="button" className="ecx-list-menu" aria-label={ctx.labels.options} title={ctx.labels.options} tabIndex={-1}
137
+ onClick={(e) => { e.stopPropagation(); const r = e.currentTarget.getBoundingClientRect(); openMenu(r.left, r.bottom + 4); }}><MoreVertical className="ecx-icon" /></button>
64
138
  <span className="ecx-list-drag" onPointerDown={(e) => { e.stopPropagation(); startDrag(ctx, e, [node.id]); }} title={ctx.labels.drag}><GripVertical className="ecx-icon" /></span>
65
139
  </div>
66
140
  {hasKids && open && <div role="group">{kids.map((k) => <ListRow key={k.id} node={k} depth={depth + 1} />)}</div>}
@@ -19,7 +19,7 @@ export function mediaAttrs(kind: MediaKind, items: MediaItem[]): Record<string,
19
19
  * Chọn media ngay trên khối: Tải lên (có thể kéo thả tệp vào cả vùng), Thư viện, Chèn từ URL. Dùng cho ảnh, gallery,
20
20
  * video, âm thanh, tệp, ảnh bìa, ảnh + chữ.
21
21
  */
22
- export function MediaActions({ kind, onSelect, onUrl, compact, extra }: { kind: MediaKind; onSelect(items: MediaItem[]): void; onUrl?(url: string): void; compact?: boolean; extra?: ReactNode }) {
22
+ export function MediaActions({ kind, onSelect, onUrl, compact, extra, accept }: { kind: MediaKind; onSelect(items: MediaItem[]): void; onUrl?(url: string): void; compact?: boolean; extra?: ReactNode; accept?: string }) {
23
23
  const { host, labels } = useEditor();
24
24
  const file = useRef<HTMLInputElement>(null);
25
25
  const [busy, setBusy] = useState(false);
@@ -49,7 +49,7 @@ export function MediaActions({ kind, onSelect, onUrl, compact, extra }: { kind:
49
49
  </form>
50
50
  )}
51
51
  {error && <p className="ecx-media-error" role="alert">{error}</p>}
52
- <input ref={file} type="file" hidden accept={ACCEPT[kind] || undefined} multiple={kind === "gallery"} onChange={(e) => { void upload([...(e.target.files ?? [])]); e.target.value = ""; }} />
52
+ <input ref={file} type="file" hidden accept={accept ?? (ACCEPT[kind] || undefined)} multiple={kind === "gallery"} onChange={(e) => { void upload([...(e.target.files ?? [])]); e.target.value = ""; }} />
53
53
  </div>
54
54
  );
55
55
  }
@@ -64,7 +64,8 @@ export function useFileDrop(kind: MediaKind, onSelect: (items: MediaItem[]) => v
64
64
  over,
65
65
  props: {
66
66
  onDragOver: (e: DragEvent) => { if (!hasFiles(e)) return; e.preventDefault(); setOver(true); },
67
- onDragLeave: () => setOver(false),
67
+ // Rời sang phần tử con vẫn ở trong vùng: giữ trạng thái (không nhấp nháy)
68
+ onDragLeave: (e: DragEvent) => { if (!(e.currentTarget as Node).contains(e.relatedTarget as Node | null)) setOver(false); },
68
69
  onDrop: async (e: DragEvent) => {
69
70
  if (!hasFiles(e)) return;
70
71
  e.preventDefault(); setOver(false);
@@ -46,13 +46,14 @@ export function MotionPanel({ type, style: raw, onChange }: { type: string; styl
46
46
  if (preview) window.setTimeout(() => previewMotion(blockId ? ui.blockEl(blockId) : null, merged?.motion), 120);
47
47
  };
48
48
 
49
+ const ct = useMsgs("controls");
49
50
  const coreIn = MOTION_IN as readonly string[];
50
51
  const isPlugin = !!m.in && !coreIn.includes(m.in);
51
52
  const groups = new Map<string, typeof plugin>();
52
53
  for (const e of plugin) groups.set(e.group ?? t.plugin, [...(groups.get(e.group ?? t.plugin) ?? []), e]);
53
54
 
54
55
  return (
55
- <Section title={t.title} defaultOpen={!!style.motion} modified={!!style.motion} onReset={() => onChange(normalizeStyle({ ...style, motion: undefined }) ?? null)}>
56
+ <Section title={t.title} defaultOpen={false} modified={!!style.motion} summary={m.in ? (t.in as Record<string, string>)[m.in] ?? m.in : ct.noMotion} onReset={() => onChange(normalizeStyle({ ...style, motion: undefined }) ?? null)}>
56
57
  <Row label={t.scroll}>
57
58
  <div className="ecx-chip-row" role="radiogroup" aria-label={t.scroll}>
58
59
  <button type="button" role="radio" aria-checked={!m.in} className={cx("ecx-chip", !m.in && "is-active")} onClick={() => set({ in: undefined, duration: undefined, delay: undefined, repeat: undefined, stagger: undefined })}>{t.none}</button>
@@ -0,0 +1,164 @@
1
+ import { normalizeParts, normalizeStyle, partsFor, type BlockStyle, type Device, type PartProp, type PartSpec, type PartValue } from "@ecomcx/ecomweb-content";
2
+ import { AlignCenter, AlignLeft, AlignRight } from "lucide-react";
3
+ import { useState } from "react";
4
+ import { blockControls } from "../../shared/panel-store";
5
+ import { labelsLegacy } from "../../shared/labels";
6
+ import { useEditor } from "../context";
7
+ import { useMsgs } from "../i18n";
8
+ import { ColorInput } from "./color-field";
9
+ import { GradientField } from "./layout-panel";
10
+ import { Row, Section, Seg, cx } from "./style-controls";
11
+ import { byStep } from "./style-tab";
12
+ import { FourInput, SpacingControl, UnitInput } from "./unit-controls";
13
+
14
+ type Style = BlockStyle & Record<string, any>;
15
+ const RESPONSIVE = new Set(["padding", "margin", "fontSize", "lineHeight", "letterSpacing", "textAlign", "width", "minHeight"]);
16
+ const WEIGHTS = ["400", "500", "600", "700", "800"];
17
+ const SHADOWS = ["sm", "md", "lg", "xl"];
18
+
19
+ /** Nhãn phần: "%part.box%" → chữ theo ngôn ngữ của trình soạn; nhãn của plugin dịch qua host.translate. */
20
+ function usePartLabel() {
21
+ const { host } = useEditor();
22
+ const t = useMsgs("parts") as Record<string, string>;
23
+ return (label: string) => { const m = /^%part\.(\w+)%$/.exec(label); return m ? t[m[1]] ?? m[1] : host.translate ? host.translate(label) : label; };
24
+ }
25
+
26
+ /** Phần tử của phần trong khung soạn (để tô vùng đệm / lề đúng phần đó). */
27
+ const partEl = (blockEl: HTMLElement | null, spec: PartSpec) => {
28
+ if (!blockEl) return null;
29
+ const suffix = spec.selector.slice(11).trim();
30
+ if (!suffix) return blockEl;
31
+ try { return blockEl.querySelector<HTMLElement>(suffix.startsWith(">") ? `:scope ${suffix}` : suffix); } catch { return null; }
32
+ };
33
+
34
+ /**
35
+ * Các mục của tab Kiểu dáng theo PHẦN của khối (content PartSpec): Khung, Icon, Tiêu đề… — mỗi phần một bộ kiểu dáng đầy đủ,
36
+ * công tắc "Hiện", thẻ Thường / Rê chuột (rê lên cả khối). Lưu ở attrs.parts; CSS sinh bằng controlsCss (khung soạn = website).
37
+ */
38
+ export function PartsSections({ blockId, type, attrs, setAttrs, device }: { blockId: string; type: string; attrs: Record<string, unknown>; setAttrs(a: Record<string, unknown>): void; device: Device }) {
39
+ const parts = partsFor(blockControls(), type);
40
+ const label = usePartLabel();
41
+ if (!parts.length) return null;
42
+ const values = normalizeParts(attrs.parts) ?? {};
43
+ const write = (name: string, v: PartValue | undefined) => {
44
+ const next = { ...values };
45
+ if (v && Object.keys(v).length) next[name] = v; else delete next[name];
46
+ setAttrs({ parts: Object.keys(next).length ? next : undefined });
47
+ };
48
+ return <>{parts.map(([name, spec]) => <PartSection key={name} blockId={blockId} name={name} spec={spec} title={label(spec.label)} value={values[name] ?? {}} onChange={(v) => write(name, v)} device={device} />)}</>;
49
+ }
50
+
51
+ function PartSection({ blockId, spec, title, value, onChange, device }: { blockId: string; name: string; spec: PartSpec; title: string; value: PartValue; onChange(v: PartValue | undefined): void; device: Device }) {
52
+ const { ui } = useEditor();
53
+ const t = useMsgs("parts") as Record<string, string>;
54
+ const [state, setState] = useState<"normal" | "hover" | "active">("normal");
55
+ const states = (["normal", ...(spec.hover ? ["hover"] : []), ...(spec.active ? ["active"] : [])] as Array<"normal" | "hover" | "active">);
56
+ const shown = !value.hidden;
57
+ const modified = !!(value.style || value.hover || value.active || value.hidden);
58
+ const toggle = spec.toggle ? (
59
+ <input type="checkbox" role="switch" className="ecx-switch" checked={shown} title={t.show} aria-label={`${t.show}: ${title}`}
60
+ onChange={() => onChange({ ...value, hidden: shown ? true : undefined })} />
61
+ ) : undefined;
62
+ const key = state === "normal" ? "style" : state;
63
+ const style = (value[key] ?? {}) as Style;
64
+ const setStyle = (next: Style) => onChange({ ...value, [key]: normalizeStyle(next) });
65
+ return (
66
+ <Section title={title} head={toggle} modified={modified} onReset={() => onChange(value.hidden ? { hidden: true } : undefined)} defaultOpen={undefined}>
67
+ {!shown ? <p className="ecx-muted">{t.hiddenNote}</p> : <>
68
+ {states.length > 1 && (
69
+ <div className="ecx-seg is-text ecx-state-tabs" role="tablist">
70
+ {states.map((s) => <button key={s} type="button" role="tab" aria-selected={state === s} className={cx("ecx-seg-btn", state === s && "is-active")} onClick={() => setState(s)}>{t[s]}</button>)}
71
+ </div>
72
+ )}
73
+ <PartControls props={spec.props} style={style} onChange={setStyle} device={device} hover={state !== "normal"} target={() => partEl(ui.blockEl(blockId), spec)} />
74
+ </>}
75
+ </Section>
76
+ );
77
+ }
78
+
79
+ /** Ô của một phần theo nhóm thuộc tính khai (typography, color, background, border, radius, shadow, padding, margin, size, iconSize). */
80
+ function PartControls({ props, style, onChange, device, hover, target }: { props: readonly PartProp[]; style: Style; onChange(s: Style): void; device: Device; hover: boolean; target(): HTMLElement | null }) {
81
+ const { host, labels: v2 } = useEditor();
82
+ const L = labelsLegacy(v2.lang);
83
+ const fonts = host.presets?.fonts ? Object.keys(host.presets.fonts) : ["body", "heading", "mono"];
84
+ const t = useMsgs("parts") as Record<string, string>;
85
+ const ct = useMsgs("controls");
86
+ const sizes = host.presets?.fontSizes ? byStep(Object.keys(host.presets.fontSizes)) : ["sm", "md", "lg", "xl", "2xl"];
87
+ const spaces = host.presets?.spacing ? ["0", ...byStep(Object.keys(host.presets.spacing))] : ["0", "xs", "sm", "md", "lg", "xl", "2xl"];
88
+ const get = (k: string): any => (RESPONSIVE.has(k) ? style[k]?.[device] : style[k]);
89
+ const set = (k: string, v: unknown) => {
90
+ const next: Style = { ...style };
91
+ if (RESPONSIVE.has(k)) { const r = { ...(style[k] ?? {}) }; if (v === undefined || v === null || v === "") delete r[device]; else r[device] = v; next[k] = Object.keys(r).length ? r : undefined; }
92
+ else next[k] = v === "" ? undefined : v;
93
+ onChange(next);
94
+ };
95
+ const reset = (k: string) => () => set(k, undefined);
96
+ const has = (k: string) => get(k) !== undefined;
97
+ const dev = (k: string) => (RESPONSIVE.has(k) ? device : undefined);
98
+ // Rê chuột: chỉ nhóm đổi được khi rê (màu, nền, viền, bóng)
99
+ const p = hover ? props.filter((x) => ["color", "background", "border", "shadow"].includes(x)) : props;
100
+ const labels = { vertical: ct.vertical, horizontal: ct.horizontal, top: ct.sideTop, right: ct.sideRight, bottom: ct.sideBottom, left: ct.sideLeft, link: ct.linkSides, unlink: ct.unlinkSides };
101
+ // Gạch chân: đặt được cả ở trạng thái rê chuột (liên kết "không gạch, rê mới gạch")
102
+ const decoration = props.includes("typography") && (
103
+ <Row label={L.style_decoration} onReset={has("textDecoration") ? reset("textDecoration") : undefined}>
104
+ <Seg label={L.style_decoration} value={style.textDecoration} onChange={(v) => set("textDecoration", v)} options={[["none", "—", L.none], ["underline", "U̲", L.underlineText], ["line-through", "S̶", L.strikeText]]} />
105
+ </Row>
106
+ );
107
+ return (
108
+ <>
109
+ {hover && decoration}
110
+ {p.includes("typography") && <>
111
+ {decoration}
112
+ <Row label={t.fontSize} device={dev("fontSize")} onReset={has("fontSize") ? reset("fontSize") : undefined}>
113
+ <Seg label={t.fontSize} value={get("fontSize")} onChange={(v) => set("fontSize", v)} options={sizes.map((v) => [v, v.toUpperCase(), v] as [string, string, string])} />
114
+ <UnitInput label={t.fontSize} value={sizes.includes(get("fontSize")) ? undefined : get("fontSize")} units={["px", "rem", "em"]} max={96} onChange={(v) => set("fontSize", v)} />
115
+ </Row>
116
+ <Row label={t.weight} onReset={has("fontWeight") ? reset("fontWeight") : undefined}>
117
+ <Seg label={t.weight} value={style.fontWeight} onChange={(v) => set("fontWeight", v)} options={WEIGHTS.map((w) => [w, w, w] as [string, string, string])} />
118
+ </Row>
119
+ <Row label={t.align} device={dev("textAlign")} onReset={has("textAlign") ? reset("textAlign") : undefined}>
120
+ <Seg label={t.align} value={get("textAlign")} onChange={(v) => set("textAlign", v)} options={[["left", AlignLeft, t.left], ["center", AlignCenter, t.center], ["right", AlignRight, t.right]]} />
121
+ </Row>
122
+ <Row label={L.style_lineHeight} device={dev("lineHeight")} onReset={has("lineHeight") ? reset("lineHeight") : undefined}>
123
+ <input className="ecx-input" type="number" min={0.8} max={3} step={0.05} placeholder="1.5" aria-label={L.style_lineHeight} value={get("lineHeight") ?? ""} onChange={(e) => set("lineHeight", e.target.value === "" ? undefined : Number(e.target.value))} />
124
+ </Row>
125
+ <Row label={L.style_transform} onReset={has("textTransform") ? reset("textTransform") : undefined}>
126
+ <Seg label={L.style_transform} value={style.textTransform} onChange={(v) => set("textTransform", v)} options={[["none", "—", L.none], ["uppercase", "AB", L.upper], ["lowercase", "ab", L.lower], ["capitalize", "Ab", L.capitalize]]} />
127
+ </Row>
128
+ <Row label={L.style_fontFamily} onReset={has("fontFamily") ? reset("fontFamily") : undefined}>
129
+ <select className="ecx-input" value={style.fontFamily ?? ""} aria-label={L.style_fontFamily} onChange={(e) => set("fontFamily", e.target.value || undefined)}>
130
+ <option value="">{L.default}</option>
131
+ {fonts.map((f) => <option key={f} value={f}>{(L as unknown as Record<string, string>)[`font_${f}`] ?? f}</option>)}
132
+ </select>
133
+ </Row>
134
+ <Row label={L.style_letterSpacing} device={dev("letterSpacing")} onReset={has("letterSpacing") ? reset("letterSpacing") : undefined}>
135
+ <UnitInput label={L.style_letterSpacing} value={get("letterSpacing")} units={["px", "em"]} max={10} onChange={(v) => set("letterSpacing", v)} />
136
+ </Row>
137
+ </>}
138
+ {p.includes("iconSize") && <Row label={t.iconSize} device={dev("fontSize")} onReset={has("fontSize") ? reset("fontSize") : undefined}>
139
+ <UnitInput label={t.iconSize} value={get("fontSize")} units={["px", "rem", "em"]} max={160} onChange={(v) => set("fontSize", v)} />
140
+ </Row>}
141
+ {p.includes("color") && <ColorInput label={props.includes("iconSize") ? t.iconColor : t.color} value={style.color?.text} onChange={(v) => set("color", { ...style.color, text: v })} />}
142
+ {p.includes("color") && !hover && <Row label={t.textGradient} onReset={has("textGradient") ? reset("textGradient") : undefined}><GradientField value={style.textGradient} onChange={(v) => set("textGradient", v)} /></Row>}
143
+ {p.includes("background") && <ColorInput label={t.background} value={style.color?.background} onChange={(v) => set("color", { ...style.color, background: v })} />}
144
+ {p.includes("background") && !hover && <Row label={t.gradient} onReset={has("gradient") ? reset("gradient") : undefined}><GradientField value={style.gradient} onChange={(v) => set("gradient", v)} /></Row>}
145
+ {p.includes("border") && <>
146
+ <FourInput label={t.borderWidth} keys={["top", "right", "bottom", "left"]} keyLabels={{ top: ct.sideTop, right: ct.sideRight, bottom: ct.sideBottom, left: ct.sideLeft }} value={style.border?.width} units={["px"]} max={20} onReset={style.border?.width ? () => set("border", { ...style.border, width: undefined }) : undefined} onChange={(v) => set("border", { style: "solid", ...style.border, width: v })} />
147
+ <Row label={L.style_borderStyle} onReset={style.border?.style && style.border.style !== "solid" ? () => set("border", { ...style.border, style: "solid" }) : undefined}>
148
+ <Seg label={L.style_borderStyle} value={style.border?.style} onChange={(v) => set("border", { ...style.border, style: v })} options={[["solid", "—", L.border_solid], ["dashed", "- -", L.border_dashed], ["dotted", "···", L.border_dotted]]} />
149
+ </Row>
150
+ <ColorInput label={t.borderColor} value={style.border?.color} onChange={(v) => set("border", { ...style.border, color: v })} />
151
+ </>}
152
+ {p.includes("radius") && <FourInput label={t.radius} corners keys={["topLeft", "topRight", "bottomRight", "bottomLeft"]} keyLabels={{ topLeft: ct.cornerTopLeft, topRight: ct.cornerTopRight, bottomRight: ct.cornerBottomRight, bottomLeft: ct.cornerBottomLeft }} value={style.radius} units={["px", "%", "rem"]} max={80} onReset={has("radius") ? reset("radius") : undefined} onChange={(v) => set("radius", v)} />}
153
+ {p.includes("shadow") && <Row label={t.shadow} onReset={has("shadow") ? reset("shadow") : undefined}>
154
+ <Seg label={t.shadow} value={style.shadow} onChange={(v) => set("shadow", v)} options={[["none", "0", t.none], ...SHADOWS.map((s) => [s, s.toUpperCase(), s] as [string, string, string])]} />
155
+ </Row>}
156
+ {p.includes("size") && <>
157
+ <Row label={t.width} device={dev("width")} onReset={has("width") ? reset("width") : undefined}><UnitInput label={t.width} value={get("width")} units={["px", "%", "rem"]} max={600} onChange={(v) => set("width", v)} /></Row>
158
+ <Row label={t.height} device={dev("minHeight")} onReset={has("minHeight") ? reset("minHeight") : undefined}><UnitInput label={t.height} value={get("minHeight")} units={["px", "rem"]} max={600} onChange={(v) => set("minHeight", v)} /></Row>
159
+ </>}
160
+ {p.includes("padding") && <SpacingControl kind="padding" device={device} label={t.padding} steps={spaces} value={get("padding")} onChange={(v) => set("padding", v)} onReset={has("padding") ? reset("padding") : undefined} labels={labels} vizTarget={target} />}
161
+ {p.includes("margin") && <SpacingControl kind="margin" device={device} label={t.margin} steps={spaces} value={get("margin")} onChange={(v) => set("margin", v)} onReset={has("margin") ? reset("margin") : undefined} labels={labels} vizTarget={target} />}
162
+ </>
163
+ );
164
+ }
@@ -0,0 +1,228 @@
1
+ import { LayoutTemplate, Search, Sparkles, X } from "lucide-react";
2
+ import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
3
+ import { norm } from "../../shared/util";
4
+ import { labelsLegacy } from "../../shared/labels";
5
+ import { useEditor } from "../context";
6
+ import { fromRich, type BNode } from "../core/model";
7
+ import { onPatternsChange, registeredPatterns, type Pattern } from "../core/patterns";
8
+ import { patternNodes } from "../../shared/patterns";
9
+ import { useMsgs } from "../i18n";
10
+ import { cx } from "./attr-form";
11
+
12
+ type Scheme = "light" | "dark" | "brand";
13
+ type RichNode = Record<string, unknown> & { type: string; attrs?: Record<string, unknown>; content?: RichNode[]; text?: string };
14
+
15
+ /** Trang dựng sẵn = chuỗi mẫu của thư viện (tên mẫu thiếu thì bỏ qua). */
16
+ const PAGES: Array<{ id: string; patterns: string[] }> = [
17
+ { id: "home", patterns: ["core/hero-split", "core/logos", "core/feat-grid6", "core/stats-band", "core/test3", "core/cta-band"] },
18
+ { id: "home2", patterns: ["core/hero-gradient", "core/feat-cards4", "core/steps3", "core/price2", "core/faq2", "core/cta-split"] },
19
+ { id: "about", patterns: ["core/hero-minimal", "core/text-cols", "core/stats4", "core/team4", "core/cta-band"] },
20
+ { id: "services", patterns: ["core/hero-badge", "core/feat-alt", "core/steps-v", "core/price-table", "core/faq5", "core/cta-contact"] },
21
+ { id: "contact", patterns: ["core/hero-minimal", "core/contact-split", "core/contact-cards", "core/faq2"] },
22
+ { id: "team", patterns: ["core/team-intro", "core/team4", "core/test-big", "core/cta-band"] },
23
+ ];
24
+
25
+ /** Kiểu màu: bọc mỗi mẫu trong một Nhóm có nền / chữ (sáng = giữ nguyên). */
26
+ function withScheme(nodes: RichNode[], scheme: Scheme): RichNode[] {
27
+ if (scheme === "light" || !nodes.length) return nodes;
28
+ const color = scheme === "dark" ? { background: "#0f1b24", text: "#ffffff" } : { background: "primary", text: "#ffffff" };
29
+ return [{ type: "group", attrs: { align: "full", style: { color, padding: { base: { top: "xl", bottom: "xl" } } } }, content: nodes }];
30
+ }
31
+
32
+ // ---------------------------------------------------------------------------------------------------- chữ do AI viết
33
+ const TEXT_ATTRS = ["text", "title", "summary", "label", "quote", "name", "role", "subtitle", "buttonText", "placeholder"];
34
+ /** Chữ của mẫu theo thứ tự đọc (nút văn bản + thuộc tính chữ) — để AI viết lại cùng số lượng. */
35
+ export function patternTexts(nodes: RichNode[]): string[] {
36
+ const out: string[] = [];
37
+ const walk = (n: RichNode) => {
38
+ if (n.type === "text" && typeof n.text === "string" && n.text.trim()) out.push(n.text);
39
+ for (const k of TEXT_ATTRS) { const v = n.attrs?.[k]; if (typeof v === "string" && v.trim()) out.push(v); }
40
+ n.content?.forEach(walk);
41
+ };
42
+ nodes.forEach(walk);
43
+ return out;
44
+ }
45
+ /** Thay chữ theo đúng thứ tự `patternTexts` (thiếu phần tử thì giữ chữ cũ). */
46
+ export function replaceTexts(nodes: RichNode[], next: string[]): RichNode[] {
47
+ let i = 0;
48
+ const take = (old: string) => { const v = next[i++]; return typeof v === "string" && v.trim() ? v.slice(0, 400) : old; };
49
+ const walk = (n: RichNode): RichNode => {
50
+ const copy: RichNode = { ...n };
51
+ if (n.type === "text" && typeof n.text === "string" && n.text.trim()) copy.text = take(n.text);
52
+ if (n.attrs) { copy.attrs = { ...n.attrs }; for (const k of TEXT_ATTRS) { const v = n.attrs[k]; if (typeof v === "string" && v.trim()) copy.attrs[k] = take(v); } }
53
+ if (n.content) copy.content = n.content.map(walk);
54
+ return copy;
55
+ };
56
+ return nodes.map(walk);
57
+ }
58
+
59
+ interface Business { name: string; industry: string; about: string; tone: string }
60
+ const BIZ_KEY = "ecx-pattern-ai";
61
+ const loadBiz = (): Business => { try { return { name: "", industry: "", about: "", tone: "friendly", ...JSON.parse(localStorage.getItem(BIZ_KEY) ?? "{}") }; } catch { return { name: "", industry: "", about: "", tone: "friendly" }; } };
62
+
63
+ // ---------------------------------------------------------------------------------------------------- xem trước
64
+ /** Vẽ nội dung (định dạng lưu) bằng khung soạn ở chế độ chỉ xem — tầng editor truyền xuống (ui không import editor). */
65
+ export type RenderPreview = (value: { version: number; blocks: unknown[] }) => ReactNode;
66
+
67
+ /** Xem trước thật: vẽ mẫu bằng chính khung soạn (chỉ xem), rộng 1200px rồi thu nhỏ vừa thẻ; chỉ vẽ khi thẻ cuộn tới. */
68
+ function Preview({ nodes, height, render }: { nodes: RichNode[]; height: number; render: RenderPreview }) {
69
+ const box = useRef<HTMLDivElement>(null);
70
+ const [seen, setSeen] = useState(false);
71
+ const [scale, setScale] = useState(0.25);
72
+ useEffect(() => {
73
+ const el = box.current;
74
+ if (!el) return;
75
+ const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { rootMargin: "200px" });
76
+ io.observe(el);
77
+ const ro = new ResizeObserver(() => setScale(el.clientWidth / 1200));
78
+ ro.observe(el);
79
+ return () => { io.disconnect(); ro.disconnect(); };
80
+ }, []);
81
+ const value = useMemo(() => ({ version: 1, blocks: [{ type: "richtext", data: { type: "doc", content: nodes } }] }), [nodes]);
82
+ return (
83
+ <div ref={box} className="ecx-lib-preview" style={{ height }} aria-hidden="true">
84
+ {seen && (
85
+ <div className="ecx-lib-preview-inner" style={{ width: 1200, transform: `scale(${scale})`, height: height / scale }}>
86
+ {render(value)}
87
+ </div>
88
+ )}
89
+ </div>
90
+ );
91
+ }
92
+
93
+ // ---------------------------------------------------------------------------------------------------- hộp thư viện
94
+ export function PatternLibraryButton({ renderPreview }: { renderPreview: RenderPreview }) {
95
+ const t = useMsgs("library");
96
+ const [open, setOpen] = useState(false);
97
+ return (
98
+ <>
99
+ <button type="button" className="ecx-btn ecx-lib-open" onClick={() => setOpen(true)} aria-haspopup="dialog"><LayoutTemplate className="ecx-icon" />{t.open}</button>
100
+ {open && <PatternLibrary renderPreview={renderPreview} onClose={() => setOpen(false)} />}
101
+ </>
102
+ );
103
+ }
104
+
105
+ export function PatternLibrary({ onClose, renderPreview }: { onClose(): void; renderPreview: RenderPreview }) {
106
+ const ctx = useEditor();
107
+ const { store, labels, host } = ctx;
108
+ const t = useMsgs("library") as Record<string, string>;
109
+ const legacy = labelsLegacy(labels.lang) as unknown as Record<string, string>;
110
+ const all = useSyncExternalStore(onPatternsChange, registeredPatterns, registeredPatterns);
111
+ const [mode, setMode] = useState<"design" | "ai">("design");
112
+ const [tab, setTab] = useState<"patterns" | "pages">("patterns");
113
+ const [cat, setCat] = useState("all");
114
+ const [query, setQuery] = useState("");
115
+ const [scheme, setScheme] = useState<Scheme>("light");
116
+ const [biz, setBiz] = useState<Business>(loadBiz);
117
+ const [filled, setFilled] = useState<Record<string, RichNode[]>>({});
118
+ const [busy, setBusy] = useState(false);
119
+ const [error, setError] = useState<string | null>(null);
120
+ const dialog = useRef<HTMLDivElement>(null);
121
+ useEffect(() => { dialog.current?.querySelector<HTMLElement>("input, button")?.focus(); }, []);
122
+
123
+ const byName = useMemo(() => new Map(all.map((p) => [p.name, p])), [all]);
124
+ const nodesOf = (p: Pattern): RichNode[] => filled[p.name] ?? (patternNodes(p) as RichNode[]);
125
+ const cats = useMemo(() => [...new Set(all.map((p) => p.category))], [all]);
126
+ const q = norm(query.trim());
127
+ const patterns = all.filter((p) => (cat === "all" || p.category === cat) && (!q || norm(`${p.title} ${p.keywords ?? ""} ${p.category}`).includes(q)));
128
+ const pages = PAGES.map((pg) => ({ ...pg, list: pg.patterns.map((n) => byName.get(n)).filter(Boolean) as Pattern[] })).filter((pg) => pg.list.length && (cat === "all" || pg.id === cat) && (!q || norm(t[`page_${pg.id}`] ?? pg.id).includes(q)));
129
+ const catName = (c: string) => legacy[`cat_${c}`] ?? c;
130
+
131
+ const insert = (nodes: RichNode[]) => {
132
+ const blocks: BNode[] = withScheme(nodes, scheme).map((n) => fromRich(n as never));
133
+ if (!blocks.length) return;
134
+ const cur = store.currentIds[store.currentIds.length - 1];
135
+ const docId = store.activeDocId;
136
+ if (cur && store.locate(cur)) store.insertAfter(cur, blocks, { focus: false });
137
+ else store.insert(docId, null, store.getState().docs[docId].blocks.length, blocks, { focus: false });
138
+ store.select([blocks[0].id]);
139
+ onClose();
140
+ };
141
+
142
+ /** AI viết chữ cho các mẫu đang hiện (tối đa 8 mẫu một lần, chạy song song), giữ nguyên bố cục. */
143
+ const fill = async () => {
144
+ if (!host.ai) return;
145
+ try { localStorage.setItem(BIZ_KEY, JSON.stringify(biz)); } catch { /* chế độ riêng tư */ }
146
+ setBusy(true); setError(null);
147
+ const list = (tab === "pages" ? pages.flatMap((pg) => pg.list) : patterns).filter((p, i, a) => a.indexOf(p) === i).slice(0, 8);
148
+ const brief = `${t.aiBrief}\n- ${t.aiName}: ${biz.name}\n- ${t.aiIndustry}: ${biz.industry}\n- ${t.aiAbout}: ${biz.about}\n- ${t.aiTone}: ${t[`tone_${biz.tone}`] ?? biz.tone}`;
149
+ const results = await Promise.allSettled(list.map(async (p) => {
150
+ const base = patternNodes(p) as RichNode[];
151
+ const texts = patternTexts(base);
152
+ if (!texts.length) return [p.name, base] as const;
153
+ const out = await host.ai!.run("custom", JSON.stringify(texts), { language: labels.lang, instruction: brief });
154
+ const json = out.slice(out.indexOf("["), out.lastIndexOf("]") + 1);
155
+ const next = JSON.parse(json);
156
+ if (!Array.isArray(next)) throw new Error("bad");
157
+ return [p.name, replaceTexts(base, next.map(String))] as const;
158
+ }));
159
+ const ok = results.flatMap((r) => (r.status === "fulfilled" ? [r.value] : []));
160
+ setFilled((f) => ({ ...f, ...Object.fromEntries(ok) }));
161
+ if (ok.length < list.length) setError(t.aiFailed);
162
+ setBusy(false);
163
+ };
164
+
165
+ return (
166
+ <div className="ecx-modal-backdrop ecx-lib-backdrop" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }} onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); onClose(); } }}>
167
+ <div ref={dialog} className="ecx-lib" role="dialog" aria-modal="true" aria-label={t.title}>
168
+ <aside className="ecx-lib-side">
169
+ <div className="ecx-lib-mode" role="radiogroup" aria-label={t.title}>
170
+ <button type="button" role="radio" aria-checked={mode === "design"} className={cx(mode === "design" && "is-active")} onClick={() => setMode("design")}>{t.byDesign}</button>
171
+ {host.ai && <button type="button" role="radio" aria-checked={mode === "ai"} className={cx(mode === "ai" && "is-active")} onClick={() => setMode("ai")}><Sparkles className="ecx-icon" />{t.withAi}</button>}
172
+ </div>
173
+ <div className="ecx-tabs" role="tablist">
174
+ <button type="button" role="tab" aria-selected={tab === "patterns"} className={cx(tab === "patterns" && "is-active")} onClick={() => { setTab("patterns"); setCat("all"); }}>{t.patterns}</button>
175
+ <button type="button" role="tab" aria-selected={tab === "pages"} className={cx(tab === "pages" && "is-active")} onClick={() => { setTab("pages"); setCat("all"); }}>{t.pages}</button>
176
+ </div>
177
+ <nav className="ecx-lib-cats" aria-label={t.categories}>
178
+ <button type="button" aria-current={cat === "all" || undefined} onClick={() => setCat("all")}>{t.all}</button>
179
+ {(tab === "patterns" ? cats.map((c) => [c, catName(c)] as const) : PAGES.map((pg) => [pg.id, t[`page_${pg.id}`] ?? pg.id] as const)).map(([id, name]) => (
180
+ <button key={id} type="button" aria-current={cat === id || undefined} onClick={() => setCat(id)}>{name}</button>
181
+ ))}
182
+ </nav>
183
+ <div className="ecx-lib-scheme">
184
+ <span>{t.scheme}</span>
185
+ <div role="radiogroup" aria-label={t.scheme}>
186
+ {(["light", "dark", "brand"] as const).map((s) => <button key={s} type="button" role="radio" aria-checked={scheme === s} aria-label={t[`scheme_${s}`]} title={t[`scheme_${s}`]} className={cx(`is-${s}`, scheme === s && "is-active")} onClick={() => setScheme(s)} />)}
187
+ </div>
188
+ </div>
189
+ </aside>
190
+ <section className="ecx-lib-main">
191
+ <header className="ecx-lib-bar">
192
+ <label className="ecx-lib-search"><Search className="ecx-icon" /><input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={tab === "patterns" ? t.searchPatterns : t.searchPages} aria-label={tab === "patterns" ? t.searchPatterns : t.searchPages} /></label>
193
+ <span className="ecx-muted">{(tab === "patterns" ? patterns.length : pages.length)} {tab === "patterns" ? t.countPatterns : t.countPages}</span>
194
+ <button type="button" className="ecx-lib-close" aria-label={labels.close} onClick={onClose}><X className="ecx-icon" /></button>
195
+ </header>
196
+ {mode === "ai" && (
197
+ <form className="ecx-lib-ai" onSubmit={(e) => { e.preventDefault(); void fill(); }}>
198
+ <label>{t.aiName}<input className="ecx-input" value={biz.name} onChange={(e) => setBiz({ ...biz, name: e.target.value })} required maxLength={80} /></label>
199
+ <label>{t.aiIndustry}<input className="ecx-input" value={biz.industry} onChange={(e) => setBiz({ ...biz, industry: e.target.value })} maxLength={80} /></label>
200
+ <label className="is-wide">{t.aiAbout}<textarea className="ecx-input" rows={2} value={biz.about} onChange={(e) => setBiz({ ...biz, about: e.target.value })} maxLength={500} /></label>
201
+ <label>{t.aiTone}<select className="ecx-input" value={biz.tone} onChange={(e) => setBiz({ ...biz, tone: e.target.value })}>{["friendly", "professional", "luxury", "youthful"].map((x) => <option key={x} value={x}>{t[`tone_${x}`]}</option>)}</select></label>
202
+ <button type="submit" className="ecx-btn ecx-btn-primary" disabled={busy}><Sparkles className="ecx-icon" />{busy ? t.aiWorking : t.aiRun}</button>
203
+ {error && <p className="ecx-lib-error" role="alert">{error}</p>}
204
+ </form>
205
+ )}
206
+ <div className={cx("ecx-lib-grid", tab === "pages" && "is-pages")}>
207
+ {tab === "patterns" ? patterns.map((p) => (
208
+ <div key={p.name} role="button" tabIndex={0} className="ecx-lib-card" data-pattern={p.name} aria-label={p.title} onClick={() => insert(nodesOf(p))} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); insert(nodesOf(p)); } }}>
209
+ <Preview nodes={withScheme(nodesOf(p), scheme)} height={200} render={renderPreview} />
210
+ <span className="ecx-lib-card-name">{p.title}<em>{catName(p.category)}</em></span>
211
+ </div>
212
+ )) : pages.map((pg) => {
213
+ const nodes = pg.list.flatMap(nodesOf);
214
+ return (
215
+ <div key={pg.id} role="button" tabIndex={0} className="ecx-lib-card" data-page={pg.id} aria-label={t[`page_${pg.id}`] ?? pg.id} onClick={() => insert(nodes)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); insert(nodes); } }}>
216
+ <Preview nodes={withScheme(nodes, scheme)} height={420} render={renderPreview} />
217
+ <span className="ecx-lib-card-name">{t[`page_${pg.id}`] ?? pg.id}<em>{pg.list.length} {t.sections}</em></span>
218
+ </div>
219
+ );
220
+ })}
221
+ {(tab === "patterns" ? !patterns.length : !pages.length) && <p className="ecx-muted">{labels.noResults}</p>}
222
+ </div>
223
+ </section>
224
+ </div>
225
+ </div>
226
+ );
227
+ }
228
+