@ecomcx/ecomweb-editor 1.31.0 → 1.33.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 (91) 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/bindings.ts +1 -1
  5. package/src/locales/en/block-desc.ts +2 -0
  6. package/src/locales/en/block-style.ts +7 -4
  7. package/src/locales/en/block-titles.ts +2 -0
  8. package/src/locales/en/blocks.ts +12 -3
  9. package/src/locales/en/columns.ts +12 -0
  10. package/src/locales/en/controls.ts +21 -0
  11. package/src/locales/en/hints.ts +289 -1
  12. package/src/locales/en/index.ts +5 -2
  13. package/src/locales/en/layout.ts +32 -0
  14. package/src/locales/en/legacy.ts +1 -1
  15. package/src/locales/en/library.ts +38 -0
  16. package/src/locales/en/parts.ts +12 -0
  17. package/src/locales/en/placeholders.ts +12 -1
  18. package/src/locales/en/presets.ts +6 -0
  19. package/src/locales/en/v2.ts +21 -0
  20. package/src/locales/vi/attrs.ts +10 -0
  21. package/src/locales/vi/background.ts +17 -0
  22. package/src/locales/vi/bindings.ts +1 -1
  23. package/src/locales/vi/block-desc.ts +2 -0
  24. package/src/locales/vi/block-style.ts +7 -4
  25. package/src/locales/vi/block-titles.ts +2 -0
  26. package/src/locales/vi/blocks.ts +12 -3
  27. package/src/locales/vi/columns.ts +12 -0
  28. package/src/locales/vi/controls.ts +21 -0
  29. package/src/locales/vi/hints.ts +290 -2
  30. package/src/locales/vi/index.ts +5 -2
  31. package/src/locales/vi/layout.ts +32 -0
  32. package/src/locales/vi/legacy.ts +1 -1
  33. package/src/locales/vi/library.ts +38 -0
  34. package/src/locales/vi/parts.ts +12 -0
  35. package/src/locales/vi/placeholders.ts +12 -1
  36. package/src/locales/vi/presets.ts +6 -0
  37. package/src/locales/vi/v2.ts +21 -0
  38. package/src/shared/panel-store.ts +3 -3
  39. package/src/shared/patterns.ts +3 -52
  40. package/src/shared/style-panel.tsx +2 -2
  41. package/src/shared/types.ts +2 -0
  42. package/src/v2/blocks/columns-inspector.tsx +210 -0
  43. package/src/v2/blocks/form.tsx +4 -4
  44. package/src/v2/blocks/index.ts +10 -4
  45. package/src/v2/blocks/inline-style.ts +1 -1
  46. package/src/v2/blocks/layout.tsx +211 -44
  47. package/src/v2/blocks/media.tsx +22 -13
  48. package/src/v2/blocks/resize.tsx +172 -4
  49. package/src/v2/blocks/text.tsx +14 -7
  50. package/src/v2/blocks/theme.tsx +63 -19
  51. package/src/v2/blocks/tools.tsx +50 -5
  52. package/src/v2/blocks/widgets.tsx +44 -16
  53. package/src/v2/canvas/block-list.tsx +23 -3
  54. package/src/v2/canvas/canvas-css.ts +70 -4
  55. package/src/v2/canvas/canvas.tsx +22 -5
  56. package/src/v2/canvas/dnd.ts +34 -3
  57. package/src/v2/canvas/move-animation.ts +94 -0
  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 +6 -1
  61. package/src/v2/core/structure.ts +2 -1
  62. package/src/v2/editor.css +238 -9
  63. package/src/v2/editor.tsx +8 -2
  64. package/src/v2/ui/attr-form.tsx +59 -12
  65. package/src/v2/ui/attr-hints.ts +140 -9
  66. package/src/v2/ui/background-panel.tsx +65 -21
  67. package/src/v2/ui/bindings.tsx +3 -0
  68. package/src/v2/ui/block-icons.tsx +152 -0
  69. package/src/v2/ui/block-menu.ts +22 -0
  70. package/src/v2/ui/block-style-panel.tsx +14 -3
  71. package/src/v2/ui/color-field.tsx +74 -9
  72. package/src/v2/ui/divider-panel.tsx +58 -0
  73. package/src/v2/ui/group-width.tsx +38 -0
  74. package/src/v2/ui/icon-picker.tsx +51 -0
  75. package/src/v2/ui/inserter.tsx +61 -12
  76. package/src/v2/ui/inspector.tsx +48 -16
  77. package/src/v2/ui/layout-panel.tsx +5 -47
  78. package/src/v2/ui/list-view.tsx +81 -7
  79. package/src/v2/ui/motion-panel.tsx +2 -1
  80. package/src/v2/ui/parts-panel.tsx +164 -0
  81. package/src/v2/ui/pattern-library.tsx +228 -0
  82. package/src/v2/ui/preset-bar.tsx +83 -0
  83. package/src/v2/ui/style-controls.tsx +65 -15
  84. package/src/v2/ui/style-supports.ts +1 -1
  85. package/src/v2/ui/style-tab.tsx +127 -41
  86. package/src/v2/ui/toolbar.tsx +52 -13
  87. package/src/v2/ui/unit-controls.tsx +88 -39
  88. package/src/locales/en/patterns.ts +0 -50
  89. package/src/locales/vi/patterns.ts +0 -50
  90. package/src/shared/patterns-kit.ts +0 -7
  91. package/src/shared/patterns-library.ts +0 -172
@@ -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
+
@@ -0,0 +1,83 @@
1
+ import { Check, ChevronDown, RotateCcw, Save, Star, Trash2 } from "lucide-react";
2
+ import { useEffect, useRef, useState, useSyncExternalStore } from "react";
3
+ import { blockControls } from "../../shared/panel-store";
4
+ import { applyStyle, ensurePresets, onPresetsChange, pickStyle, presetsSnapshot, sameStyle, setPresets, styleKeys, type BlockPresetMap } from "../core/block-presets";
5
+ import type { BNode } from "../core/model";
6
+ import { useEditor } from "../context";
7
+ import { useMsgs } from "../i18n";
8
+ import { cx } from "./style-controls";
9
+
10
+ /**
11
+ * Hàng "Kiểu" dưới tên khối: chọn kiểu đặt sẵn của loại khối (toàn website), báo "(đã chỉnh)" khi kiểu đang dùng đã bị sửa,
12
+ * lưu kiểu hiện tại thành kiểu mới, đặt làm mặc định khi chèn khối mới, về mặc định. Chỉ đụng thuộc tính kiểu — nội dung giữ nguyên.
13
+ */
14
+ export function PresetBar({ block, setAttrs }: { block: BNode; setAttrs(a: Record<string, unknown>): void }) {
15
+ const { host } = useEditor();
16
+ const t = useMsgs("presets");
17
+ const map = useSyncExternalStore(onPresetsChange, presetsSnapshot, presetsSnapshot);
18
+ useEffect(() => ensurePresets(host.blockPresets?.load), [host]);
19
+ const [open, setOpen] = useState(false);
20
+ const [naming, setNaming] = useState<string | null>(null);
21
+ const [busy, setBusy] = useState(false);
22
+ const ref = useRef<HTMLDivElement>(null);
23
+ useEffect(() => {
24
+ if (!open) return;
25
+ const out = (e: MouseEvent) => { if (!ref.current?.contains(e.target as Node)) { setOpen(false); setNaming(null); } };
26
+ document.addEventListener("mousedown", out, true);
27
+ return () => document.removeEventListener("mousedown", out, true);
28
+ }, [open]);
29
+ if (!host.blockPresets) return null;
30
+ const keys = styleKeys(block.type, blockControls());
31
+ const cur = pickStyle(block.attrs, keys);
32
+ const entry = map?.[block.type] ?? {};
33
+ const presets = entry.presets ?? [];
34
+ const def = entry.default ?? {};
35
+ const match = presets.find((p) => sameStyle(cur, pickStyle(p.attrs, keys)));
36
+ const isDefault = !match && sameStyle(cur, pickStyle(def, keys));
37
+ const label = match ? match.name : t.default;
38
+ const edited = !match && !isDefault;
39
+ const canSave = !!host.blockPresets.save;
40
+
41
+ const save = async (next: BlockPresetMap) => {
42
+ setBusy(true);
43
+ try { setPresets((await host.blockPresets!.save!(next as Record<string, unknown>)) as BlockPresetMap); }
44
+ finally { setBusy(false); }
45
+ };
46
+ const withEntry = (patch: Partial<typeof entry>) => ({ ...(map ?? {}), [block.type]: { ...entry, ...patch } });
47
+ const apply = (style: Record<string, unknown>) => { setAttrs(applyStyle(keys, pickStyle(style, keys))); setOpen(false); };
48
+
49
+ return (
50
+ <div className="ecx-preset" ref={ref}>
51
+ <span className="ecx-field-label">{t.label}</span>
52
+ <div className="ecx-preset-row">
53
+ <button type="button" className={cx("ecx-preset-btn", open && "is-open")} aria-haspopup="menu" aria-expanded={open} onClick={() => setOpen(!open)}>
54
+ <span>{label}{edited && <em className="ecx-preset-edited"> {t.edited}</em>}</span><ChevronDown className="ecx-icon" />
55
+ </button>
56
+ <button type="button" className="ecx-preset-reset" title={t.toDefault} aria-label={t.toDefault} disabled={isDefault} onClick={() => apply(def)}><RotateCcw className="ecx-icon" /></button>
57
+ </div>
58
+ {open && (
59
+ <div className="ecx-preset-menu" role="menu">
60
+ <div className="ecx-pop-title">{t.presets}</div>
61
+ <button type="button" role="menuitemradio" aria-checked={isDefault} className="ecx-preset-item" onClick={() => apply(def)}>{t.default}{isDefault && <Check className="ecx-icon" />}</button>
62
+ {presets.map((p) => (
63
+ <div key={p.name} className="ecx-preset-line">
64
+ <button type="button" role="menuitemradio" aria-checked={match === p} className="ecx-preset-item" onClick={() => apply(p.attrs)}>{p.name}{match === p && <Check className="ecx-icon" />}</button>
65
+ {canSave && <button type="button" className="ecx-preset-del" title={t.remove} aria-label={`${t.remove}: ${p.name}`} disabled={busy} onClick={() => save(withEntry({ presets: presets.filter((x) => x !== p) }))}><Trash2 className="ecx-icon" /></button>}
66
+ </div>
67
+ ))}
68
+ {canSave && <>
69
+ <hr />
70
+ {naming === null
71
+ ? <button type="button" className="ecx-preset-item" disabled={busy} onClick={() => setNaming("")}><Save className="ecx-icon" />{t.saveNew}</button>
72
+ : <form className="ecx-preset-name" onSubmit={(e) => { e.preventDefault(); const name = naming.trim().slice(0, 60); if (!name) return; save(withEntry({ presets: [...presets.filter((x) => x.name !== name), { name, attrs: cur }] })).then(() => { setNaming(null); setOpen(false); }); }}>
73
+ <input className="ecx-input" autoFocus value={naming} maxLength={60} placeholder={t.namePlaceholder} onChange={(e) => setNaming(e.target.value)} />
74
+ <button type="submit" className="ecx-btn ecx-btn-primary" disabled={busy || !naming.trim()}>{t.save}</button>
75
+ </form>}
76
+ <button type="button" className="ecx-preset-item" disabled={busy} onClick={() => save(withEntry({ default: Object.keys(cur).length ? cur : undefined })).then(() => setOpen(false))}><Star className="ecx-icon" />{t.makeDefault}</button>
77
+ <p className="ecx-pop-hint">{t.defaultHint}</p>
78
+ </>}
79
+ </div>
80
+ )}
81
+ </div>
82
+ );
83
+ }
@@ -1,10 +1,10 @@
1
1
  import type { Device } from "@ecomcx/ecomweb-content";
2
- import { ChevronRight } from "lucide-react";
3
- import { useState, type ComponentType, type ReactNode } from "react";
2
+ import { ChevronRight, Monitor, RotateCcw, Smartphone, Tablet } from "lucide-react";
3
+ import { createContext, useContext, useState, type ComponentType, type ReactNode } from "react";
4
4
  import { useEditor } from "../context";
5
5
  import { useMsgs } from "../i18n";
6
6
 
7
- /** Thành phần chung của tab Kiểu dáng (cùng một giao diện cho mọi mục). */
7
+ /** Thành phần chung của bảng cài đặt (cùng một giao diện cho mọi mục). */
8
8
  export const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
9
9
  export type Icon = ComponentType<{ className?: string }>;
10
10
 
@@ -18,33 +18,84 @@ export function Seg<T extends string>({ value, options, onChange, label }: { val
18
18
  </div>
19
19
  );
20
20
  }
21
- export function Row({ label, children, device }: { label: string; children: ReactNode; device?: Device }) {
21
+
22
+ /** Cụm 3 icon khổ màn hình cạnh nhãn: ô này chỉnh riêng theo khổ; bấm = đổi khổ của cả trình soạn (khung soạn co lại theo). */
23
+ export function DeviceSwitch() {
24
+ const { ui } = useEditor();
25
+ const t = useMsgs("controls");
26
+ const items: Array<["desktop" | "tablet" | "mobile", Icon, string]> = [["desktop", Monitor, t.desktop], ["tablet", Tablet, t.tablet], ["mobile", Smartphone, t.mobile]];
27
+ return (
28
+ <span className="ecx-row-devices" role="group" aria-label={t.device}>
29
+ {items.map(([d, I, title]) => (
30
+ <button key={d} type="button" title={title} aria-label={title} aria-pressed={ui.device === d} className={cx(ui.device === d && "is-active")} onClick={() => ui.setDevice(d)}><I className="ecx-icon" /></button>
31
+ ))}
32
+ </span>
33
+ );
34
+ }
35
+
36
+ /**
37
+ * Một ô của bảng: nhãn bên trái; bên phải là cụm khổ màn hình (ô chỉnh theo khổ — có `device`) và nút ↶ về mặc định (khi đã đổi — có `onReset`).
38
+ * `extra`: nút nhỏ thêm cạnh nhãn (vd xích 4 cạnh).
39
+ */
40
+ export function Row({ label, children, device, onReset, extra }: { label: ReactNode; children: ReactNode; device?: Device; onReset?(): void; extra?: ReactNode }) {
22
41
  const t = useMsgs("controls");
23
42
  return (
24
43
  <div className="ecx-style-row">
25
- <span className="ecx-field-label">{label}{device && device !== "base" && <em className="ecx-device-tag">{device === "tablet" ? t.tablet : t.mobile}</em>}</span>
44
+ <span className="ecx-row-head">
45
+ <span className="ecx-field-label">{label}</span>
46
+ {onReset && <button type="button" className="ecx-row-reset" title={t.reset} aria-label={`${t.reset}: ${typeof label === "string" ? label : ""}`} onClick={onReset}><RotateCcw className="ecx-icon" /></button>}
47
+ <span className="ecx-row-tools">{extra}{device !== undefined && <DeviceSwitch />}</span>
48
+ </span>
26
49
  {children}
27
50
  </div>
28
51
  );
29
52
  }
53
+
54
+ /** Công tắc trạng thái ngay trong một mục (Thường / Rê chuột), như bảng của các bộ khối lớn. */
55
+ export function StateTabs({ value, onChange }: { value: "normal" | "hover"; onChange(v: "normal" | "hover"): void }) {
56
+ const t = useMsgs("controls");
57
+ return (
58
+ <div role="tablist" className="ecx-seg is-text ecx-state-tabs">
59
+ {(["normal", "hover"] as const).map((v) => (
60
+ <button key={v} type="button" role="tab" aria-selected={value === v} className={cx("ecx-seg-btn", value === v && "is-active")} onClick={() => onChange(v)}>{v === "normal" ? t.stateNormal : t.stateHover}</button>
61
+ ))}
62
+ </div>
63
+ );
64
+ }
65
+
66
+ /** Đếm thứ tự mục trong một bảng: mục đầu mở sẵn, còn lại gập (như bảng của các bộ khối lớn: thấy hết tên mục trong một màn hình). */
67
+ const SectionIndex = createContext<{ n: number } | null>(null);
68
+ export function SectionGroup({ children }: { children: ReactNode }) {
69
+ return <SectionIndex.Provider value={{ n: 0 }}>{children}</SectionIndex.Provider>;
70
+ }
71
+ // Mục người dùng đã mở / gập: nhớ theo tên trong phiên soạn (đổi sang khối khác vẫn giữ)
72
+ const remembered = new Map<string, boolean>();
73
+
30
74
  /**
31
- * Một mục của tab Kiểu dáng: tiêu đề bấm để thu / mở (mũi tên), dấu chấm khi mục có giá trị, nút đặt lại,
32
- * phần "Thêm tuỳ chọn" cho thiết lập ít dùng (tự mở khi đã có giá trị).
75
+ * Một mục: tiêu đề bấm để thu / mở, chấm khi mục có giá trị, nút đặt lại, phần "Thêm tuỳ chọn" cho thiết lập ít dùng.
76
+ * Mặc định: mục đầu của bảng (trong SectionGroup) và mục đã có giá trị thì mở; còn lại gập. `summary`: một dòng hiện khi gập.
33
77
  */
34
- export function Section({ title, children, more, defaultOpen = true, modified, onReset, moreOpen }: {
35
- title: string; children?: ReactNode; more?: ReactNode; defaultOpen?: boolean; modified?: boolean; onReset?(): void; moreOpen?: boolean;
78
+ export function Section({ title, children, more, defaultOpen, modified, onReset, moreOpen, summary, head }: {
79
+ title: string; children?: ReactNode; more?: ReactNode; defaultOpen?: boolean; modified?: boolean; onReset?(): void; moreOpen?: boolean; summary?: ReactNode;
80
+ /** Phần tử đặt trước tiêu đề (vd công tắc "Hiện" của một phần khối). */
81
+ head?: ReactNode;
36
82
  }) {
37
- const { labels } = useEditor();
38
- const [open, setOpen] = useState(defaultOpen);
83
+ const group = useContext(SectionIndex);
84
+ const [index] = useState(() => (group ? group.n++ : 0));
85
+ const [open, setOpenState] = useState(() => remembered.get(title) ?? defaultOpen ?? (!group || index === 0 || !!modified));
86
+ const setOpen = (v: boolean) => { remembered.set(title, v); setOpenState(v); };
39
87
  const [showMore, setShowMore] = useState(!!moreOpen);
40
88
  const t = useMsgs("controls");
41
89
  return (
42
- <section className="ecx-style-section">
90
+ <section className={cx("ecx-style-section", open && "is-open")}>
43
91
  <div className="ecx-style-section-head">
92
+ {head}
44
93
  <button type="button" className="ecx-style-section-toggle" aria-expanded={open} onClick={() => setOpen(!open)}>
45
- <ChevronRight className={cx("ecx-icon ecx-icon-sm ecx-chevron", open && "is-open")} aria-hidden />{title}{modified && <span className="ecx-dot" aria-label={t.modified} />}
94
+ <span className="ecx-style-section-title">{title}{modified && <span className="ecx-dot" aria-label={t.modified} />}</span>
95
+ {!open && summary && <span className="ecx-style-section-summary">{summary}</span>}
96
+ <ChevronRight className={cx("ecx-icon ecx-icon-sm ecx-chevron", open && "is-open")} aria-hidden />
46
97
  </button>
47
- {modified && onReset && <button type="button" className="ecx-link-btn" onClick={onReset}>{t.reset}</button>}
98
+ {open && modified && onReset && <button type="button" className="ecx-link-btn" onClick={onReset}>{t.reset}</button>}
48
99
  </div>
49
100
  {open && (
50
101
  <div className="ecx-style-section-body">
@@ -55,4 +106,3 @@ export function Section({ title, children, more, defaultOpen = true, modified, o
55
106
  </section>
56
107
  );
57
108
  }
58
-
@@ -13,7 +13,7 @@ const CORE: Record<string, StyleGroup[]> = {
13
13
  spacer: MINIMAL, pageBreak: ["visibility"], customHtml: MINIMAL, shortcode: MINIMAL, audio: MINIMAL,
14
14
  horizontalRule: ["color", "spacing", "border", "visibility"],
15
15
  image: MEDIA, gallery: MEDIA, video: MEDIA, youtube: MEDIA, embed: MEDIA, featuredImage: MEDIA, siteLogo: MEDIA, avatar: MEDIA,
16
- icon: ["color", "spacing", "motion", "visibility"],
16
+ icon: ["color", "spacing", "hover", "motion", "visibility"],
17
17
  socialLinks: ["color", "spacing", "motion", "visibility"],
18
18
  // Màu nút (Thường / Rê chuột) ở mục Nút riêng (core-controls) — không lặp nhóm Màu chung (dữ liệu cũ có màu vẫn hiện để sửa)
19
19
  button: NO_BACKGROUND.filter((g) => g !== "color"),