@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,13 +1,14 @@
1
1
  import { blockShell, embedInfo, isSafeUrl } from "@ecomcx/ecomweb-content";
2
2
  import { ArrowDown, ArrowUp, Code2, File as FileIcon, Image as ImageIcon, Images, ListTree, Music, Plus, Share2, Video, Play, Globe, X } from "lucide-react";
3
- import { useState, type CSSProperties } from "react";
3
+ import { useState, type CSSProperties, type ReactNode } from "react";
4
4
  import { useEditor } from "../context";
5
5
  import { AiAltButton } from "../ui/ai";
6
6
  import type { BlockEditProps, BlockType } from "../core/registry";
7
7
  import { RichText } from "../text/rich-text";
8
8
  import { BoundText, useBindingPreview } from "../ui/bindings";
9
9
  import { ImageHandle } from "./resize";
10
- import { MediaActions, mediaAttrs, useFileDrop } from "./media-actions";
10
+ import { mediaAttrs } from "../ui/media-actions";
11
+ import { LinkPlaceholder, MediaPlaceholder } from "../ui/placeholders";
11
12
  import type { MediaItem, MediaKind } from "../../shared/types";
12
13
  import { useMsgs } from "../i18n";
13
14
  import { format } from "../../i18n";
@@ -15,48 +16,44 @@ import { format } from "../../i18n";
15
16
  const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
16
17
  const safe = (u: unknown) => (typeof u === "string" && isSafeUrl(u) ? u : "");
17
18
 
18
- /** Ô trống của khối media: chọn từ thư viện hoặc dán đường dẫn. */
19
- function MediaPlaceholder({ blockId, kind, icon: Icon, title, blockProps }: { blockId: string; kind: MediaKind; icon: typeof ImageIcon; title: string; blockProps: BlockEditProps["blockProps"] }) {
20
- const { store, labels } = useEditor();
21
- const select = (items: MediaItem[]) => store.setAttrs([blockId], mediaAttrs(kind, items));
22
- const drop = useFileDrop(kind, select);
23
- return (
24
- <div {...blockProps} {...drop.props} className={cx(blockProps.className, "ecx-media-placeholder", drop.over && "is-drop-target")}>
25
- <span className="ecx-placeholder-title"><Icon className="ecx-icon" />{title}</span>
26
- <p className="ecx-placeholder-hint">{labels.dropHint[kind] ?? labels.dropHint.file}</p>
27
- <MediaActions kind={kind} onSelect={select} onUrl={kind === "gallery" ? undefined : (url) => store.setAttrs([blockId], { src: url })} />
28
- </div>
29
- );
19
+ /** Ô trống của khối media: vùng kéo thả + Tải lên / Thư viện / URL (bộ ô giữ chỗ dùng chung). */
20
+ function MediaDrop({ blockId, kind, blockProps }: { blockId: string; kind: MediaKind; blockProps: BlockEditProps["blockProps"] }) {
21
+ const { store } = useEditor();
22
+ return <MediaPlaceholder kind={kind} blockProps={blockProps} onSelect={(items) => store.setAttrs([blockId], mediaAttrs(kind, items))} onUrl={kind === "gallery" ? undefined : (url) => store.setAttrs([blockId], { src: url })} />;
30
23
  }
31
24
 
32
25
  function ImageAiTools({ attrs, setAttrs }: BlockEditProps) { return <AiAltButton attrs={attrs} setAttrs={setAttrs} />; }
33
26
 
34
- function ImageEdit({ block, blockProps, setAttrs, editable, labels, selected }: BlockEditProps) {
27
+ function ImageEdit({ block, blockProps, setAttrs, editable, selected }: BlockEditProps) {
35
28
  const a = block.attrs;
29
+ const tp = useMsgs("placeholders");
36
30
  const bSrc = useBindingPreview(block, "src"), bAlt = useBindingPreview(block, "alt"), bCap = useBindingPreview(block, "caption");
37
31
  const src = bSrc.bound ? safe(bSrc.value) : safe(a.src);
38
32
  if (bSrc.bound && !src) return <figure {...blockProps} className={cx(blockProps.className, "ecx-image cms-image")}><BoundText tagName="div" className="ecx-bound-media" preview={bSrc} /></figure>;
39
- if (!src) return <MediaPlaceholder blockId={block.id} kind="image" icon={ImageIcon} title={labels.image} blockProps={blockProps} />;
33
+ if (!src) return <MediaDrop blockId={block.id} kind="image" blockProps={blockProps} />;
40
34
  const cls = blockShell("image", a)!.className;
41
35
  return (
42
36
  <figure {...blockProps} className={cx(blockProps.className, cls)} style={{ ...(blockProps.style ?? {}), position: "relative" }}>
43
37
  {selected && editable && <ImageHandle blockId={block.id} />}
44
38
  <img src={src} alt={bAlt.bound ? bAlt.value ?? "" : String(a.alt ?? "")} data-ecx-bound={bSrc.bound ? "" : undefined} title={bSrc.bound ? bSrc.label : undefined} width={Number(a.width) || undefined} height={Number(a.height) || undefined} draggable={false} style={Number(a.width) ? { width: Number(a.width), maxWidth: "100%", height: "auto" } : undefined} />
45
39
  {bCap.bound ? <BoundText tagName="figcaption" preview={bCap} /> : (a.caption || editable) && (
46
- <RichText blockId={block.id} field="caption" tagName="figcaption" value={String(a.caption ?? "")} onChange={(v) => setAttrs({ caption: v })} placeholder={labels.caption} editable={editable} />
40
+ <RichText blockId={block.id} field="caption" tagName="figcaption" value={String(a.caption ?? "")} onChange={(v) => setAttrs({ caption: v })} placeholder={tp.caption} editable={editable} />
47
41
  )}
48
42
  </figure>
49
43
  );
50
44
  }
51
45
 
52
- function GalleryEdit({ block, blockProps, labels }: BlockEditProps) {
46
+ function GalleryEdit({ block, blockProps, setAttrs, editable, selected }: BlockEditProps) {
53
47
  const images = (Array.isArray(block.attrs.images) ? block.attrs.images : []) as Array<{ src: string; alt?: string }>;
54
- if (!images.length) return <MediaPlaceholder blockId={block.id} kind="gallery" icon={Images} title="Gallery" blockProps={blockProps} />;
48
+ const tp = useMsgs("placeholders");
49
+ if (!images.length) return <MediaDrop blockId={block.id} kind="gallery" blockProps={blockProps} />;
55
50
  const cols = Math.min(6, Math.max(1, Number(block.attrs.columns) || 3));
56
- void labels;
51
+ const add = (items: MediaItem[]) => setAttrs({ images: [...images, ...((mediaAttrs("gallery", items).images ?? []) as typeof images)] });
57
52
  return (
58
- <figure {...blockProps} className={cx(blockProps.className, blockShell("gallery", block.attrs)!.className)} style={{ ...(blockProps.style ?? {}), ...(blockShell("gallery", block.attrs)!.style as CSSProperties) }}>
59
- {images.map((im, i) => <figure key={i} className="ecx-gallery-item cms-gallery-item" style={{ margin: 0 }}><img src={safe(im.src)} alt={im.alt ?? ""} draggable={false} style={{ width: "100%", height: "100%", objectFit: "cover", aspectRatio: "1" }} /></figure>)}
53
+ <figure {...blockProps} className={cx(blockProps.className, blockShell("gallery", block.attrs)!.className, (block.attrs.layout === "masonry" || block.attrs.imageCrop === false) && "is-natural")} style={{ ...(blockProps.style ?? {}), ...(blockShell("gallery", block.attrs)!.style as CSSProperties) }}>
54
+ {images.map((im, i) => <figure key={i} className="ecx-gallery-item cms-gallery-item" style={{ margin: 0 }}><img src={safe(im.src)} alt={im.alt ?? ""} draggable={false} style={block.attrs.layout === "masonry" || block.attrs.imageCrop === false ? { width: "100%", height: "auto", display: "block" } : { width: "100%", height: "100%", objectFit: "cover", aspectRatio: "1" }} /></figure>)}
55
+ {/* Có ảnh rồi vẫn còn ô "+" cuối lưới để thêm tiếp (chỉ khi đang chọn: website không có ô này) */}
56
+ {editable && selected && <MediaPlaceholder kind="gallery" compact title={tp.addImage} icon={Plus} className="ecx-gallery-add" onSelect={add} />}
60
57
  {block.attrs.caption ? <figcaption className="ecx-gallery-caption cms-gallery-caption" style={{ gridColumn: "1 / -1" }}>{String(block.attrs.caption)}</figcaption> : null}
61
58
  </figure>
62
59
  );
@@ -64,61 +61,40 @@ function GalleryEdit({ block, blockProps, labels }: BlockEditProps) {
64
61
 
65
62
  function VideoEdit({ block, blockProps, labels }: BlockEditProps) {
66
63
  const src = safe(block.attrs.src);
67
- if (!src) return <MediaPlaceholder blockId={block.id} kind="video" icon={Video} title="Video" blockProps={blockProps} />;
64
+ if (!src) return <MediaDrop blockId={block.id} kind="video" blockProps={blockProps} />;
68
65
  void labels;
69
66
  return <figure {...blockProps} className={cx(blockProps.className, "ecx-video cms-video")}><video src={src} controls preload="metadata" style={{ width: "100%", pointerEvents: "none" }} /></figure>;
70
67
  }
71
68
 
72
69
  function AudioEdit({ block, blockProps }: BlockEditProps) {
73
70
  const src = safe(block.attrs.src);
74
- if (!src) return <MediaPlaceholder blockId={block.id} kind="audio" icon={Music} title="Audio" blockProps={blockProps} />;
71
+ if (!src) return <MediaDrop blockId={block.id} kind="audio" blockProps={blockProps} />;
75
72
  return <figure {...blockProps} className={cx(blockProps.className, "ecx-audio cms-audio")}><audio src={src} controls preload="metadata" style={{ width: "100%", pointerEvents: "none" }} /></figure>;
76
73
  }
77
74
 
78
75
  function FileEdit({ block, blockProps }: BlockEditProps) {
79
76
  const src = safe(block.attrs.src);
80
- if (!src) return <MediaPlaceholder blockId={block.id} kind="file" icon={FileIcon} title="File" blockProps={blockProps} />;
77
+ if (!src) return <MediaDrop blockId={block.id} kind="file" blockProps={blockProps} />;
81
78
  return <div {...blockProps} className={cx(blockProps.className, "ecx-file cms-file")}><span className="ecx-file-link cms-file-link">{String(block.attrs.name || src)}</span></div>;
82
79
  }
83
80
 
84
- function YoutubeEdit({ block, blockProps, setAttrs, labels }: BlockEditProps) {
85
- const m = String(block.attrs.src ?? "").match(/(?:v=|youtu\.be\/|embed\/)([\w-]{11})/);
86
- const [draft, setDraft] = useState("");
87
- const t = useMsgs("blocks"); // hook phải gọi trước mọi return sớm (đổi số hook khi dán link → React #300)
88
- if (!m) {
89
- return (
90
- <div {...blockProps} className={cx(blockProps.className, "ecx-media-placeholder")}>
91
- <span className="ecx-placeholder-title"><Play className="ecx-icon" />YouTube</span>
92
- <p className="ecx-placeholder-hint">{t.pasteAYoutubeLink}</p>
93
- <form className="ecx-media-actions" contentEditable={false} onMouseDown={(e) => e.stopPropagation()} onSubmit={(e) => { e.preventDefault(); if (/(?:v=|youtu\.be\/|embed\/)[\w-]{11}/.test(draft)) setAttrs({ src: draft.trim() }); }}>
94
- <input className="ecx-input" type="url" placeholder="https://youtu.be/…" value={draft} onChange={(e) => setDraft(e.target.value)} aria-label="YouTube URL" />
95
- <button type="submit" className="ecx-btn ecx-btn-primary">{t.embed}</button>
96
- </form>
97
- </div>
98
- );
99
- }
81
+ const YT = /(?:v=|youtu\.be\/|embed\/)([\w-]{11})/; // cùng mẫu với website (theme-sdk)
82
+ function YoutubeEdit({ block, blockProps, setAttrs }: BlockEditProps) {
83
+ const m = String(block.attrs.src ?? "").match(YT);
84
+ const tp = useMsgs("placeholders");
85
+ if (!m) return <LinkPlaceholder blockProps={blockProps} icon={Play} title={tp.pasteToEmbed} label="YouTube URL" validate={(u) => YT.test(u)} onSubmit={(src) => setAttrs({ src })} />;
100
86
  return (
101
87
  <div {...blockProps} className={cx(blockProps.className, "ecx-youtube embed")}>
102
- {m ? <img src={`https://i.ytimg.com/vi/${m[1]}/hqdefault.jpg`} alt="YouTube" draggable={false} style={{ width: "100%", aspectRatio: "16/9", objectFit: "cover" }} /> : "YouTube"}
88
+ <img src={`https://i.ytimg.com/vi/${m[1]}/hqdefault.jpg`} alt="YouTube" draggable={false} style={{ width: "100%", aspectRatio: "16/9", objectFit: "cover" }} />
103
89
  </div>
104
90
  );
105
91
  }
106
92
 
107
- function EmbedEdit({ block, blockProps, setAttrs, labels }: BlockEditProps) {
93
+ function EmbedEdit({ block, blockProps, setAttrs }: BlockEditProps) {
108
94
  const url = String(block.attrs.url ?? "");
109
95
  const info = embedInfo(url);
110
- const [draft, setDraft] = useState(url);
111
- if (!url) {
112
- return (
113
- <div {...blockProps} className={cx(blockProps.className, "ecx-media-placeholder")}>
114
- <span className="ecx-placeholder-title"><Globe className="ecx-icon" />{labels.embed}</span>
115
- <form className="ecx-media-actions" contentEditable={false} onMouseDown={(e) => e.stopPropagation()} onSubmit={(e) => { e.preventDefault(); if (isSafeUrl(draft)) setAttrs({ url: draft.trim() }); }}>
116
- <input className="ecx-input" type="url" placeholder="https://…" value={draft} onChange={(e) => setDraft(e.target.value)} aria-label={labels.embed} />
117
- <button type="submit" className="ecx-btn">{labels.apply}</button>
118
- </form>
119
- </div>
120
- );
121
- }
96
+ const tp = useMsgs("placeholders");
97
+ if (!url) return <LinkPlaceholder blockProps={blockProps} icon={Globe} title={tp.pasteToEmbed} hint={tp.embedHint} embed onSubmit={(u) => setAttrs({ url: u })} />;
122
98
  const shell = blockShell("embed", block.attrs); // vỏ dùng chung với website
123
99
  return (
124
100
  <figure {...blockProps} className={cx(blockProps.className, shell?.className ?? "ecx-embed")} style={{ ...(blockProps.style ?? {}), ...(shell?.style as CSSProperties | undefined) }}>
@@ -128,14 +104,27 @@ function EmbedEdit({ block, blockProps, setAttrs, labels }: BlockEditProps) {
128
104
  );
129
105
  }
130
106
 
131
- function HtmlEdit({ block, blockProps, setAttrs, selected, editable }: BlockEditProps) {
107
+ /** HTML: chuyển Mã / Xem trước ngay trên khối (mã trống → ô gõ mã luôn hiện). */
108
+ const htmlPreview = new Set<string>();
109
+ function HtmlEdit({ block, blockProps, setAttrs, editable }: BlockEditProps) {
132
110
  const html = String(block.attrs.html ?? "");
111
+ const tp = useMsgs("placeholders");
112
+ const [, bump] = useState(0);
113
+ const preview = !!html && (htmlPreview.has(block.id) || !editable);
114
+ const show = (p: boolean) => { if (p) htmlPreview.add(block.id); else htmlPreview.delete(block.id); bump((n) => n + 1); };
133
115
  return (
134
116
  <div {...blockProps} className={cx(blockProps.className, blockShell("customHtml", block.attrs)!.className)}>
135
- {selected && editable
136
- ? <textarea className="ecx-code-input" value={html} rows={Math.min(20, Math.max(4, html.split("\n").length + 1))} onChange={(e) => setAttrs({ html: e.target.value })} onMouseDown={(e) => e.stopPropagation()} aria-label="HTML" spellCheck={false} />
117
+ {editable && (
118
+ <div className="ecx-ph-tabs" role="tablist" contentEditable={false} onMouseDown={(e) => e.stopPropagation()}>
119
+ <Code2 className="ecx-icon" aria-hidden /> HTML
120
+ <button type="button" role="tab" aria-selected={!preview} className={cx("ecx-ph-tab", !preview && "is-active")} onClick={() => show(false)}>{tp.htmlCode}</button>
121
+ <button type="button" role="tab" aria-selected={preview} disabled={!html} className={cx("ecx-ph-tab", preview && "is-active")} onClick={() => show(true)}>{tp.htmlPreview}</button>
122
+ </div>
123
+ )}
124
+ {preview
137
125
  // Xem trước trong iframe không cho chạy script (HTML do người khác soạn không chạy được trong trang quản trị)
138
- : html ? <iframe className="ecx-html-preview" sandbox="" srcDoc={html} title="HTML" /> : <span className="ecx-placeholder-title"><Code2 className="ecx-icon" />HTML</span>}
126
+ ? <iframe className="ecx-html-preview" sandbox="" srcDoc={html} title="HTML" />
127
+ : <textarea className="ecx-code-input" value={html} placeholder={tp.htmlPlaceholder} rows={Math.min(20, Math.max(4, html.split("\n").length + 1))} readOnly={!editable} onChange={(e) => setAttrs({ html: e.target.value })} onMouseDown={(e) => e.stopPropagation()} aria-label="HTML" spellCheck={false} />}
139
128
  </div>
140
129
  );
141
130
  }
@@ -149,21 +138,30 @@ const socialName = (s: string) => SOCIAL.find(([v]) => v === s)?.[1] ?? s;
149
138
  type SocialLink = { service: string; url: string; label?: string };
150
139
  const linksOf = (a: Record<string, unknown>) => (Array.isArray(a.links) ? a.links : []) as SocialLink[];
151
140
 
152
- function SocialEdit({ block, blockProps, labels }: BlockEditProps) {
153
- const t = useMsgs("blocks");
154
- const links = linksOf(block.attrs).filter((l) => l.url);
141
+ function SocialEdit({ block, blockProps, setAttrs, editable }: BlockEditProps) {
142
+ const tp = useMsgs("placeholders");
143
+ const all = linksOf(block.attrs);
144
+ const links = all.filter((l) => l.url);
155
145
  const a = block.attrs;
156
- if (!links.length) {
157
- return (
158
- <div {...(blockProps as object)} className={cx(blockProps.className, "ecx-placeholder-block")}>
159
- <span className="ecx-placeholder-title"><Share2 className="ecx-icon" /> {t.socialLinks}</span>
160
- <span className="ecx-placeholder-summary">{t.addLinksInThe}</span>
161
- </div>
162
- );
163
- }
146
+ const [adding, setAdding] = useState(false);
147
+ const [service, setService] = useState("facebook");
148
+ // Bấm "+" chọn mạng và dán link ngay trên khối (danh sách đầy đủ vẫn ở bảng cài đặt)
149
+ const adder = editable && (adding || !links.length) ? (
150
+ <span className="ecx-social-add" contentEditable={false} onMouseDown={(e) => e.stopPropagation()}>
151
+ {!adding ? <button type="button" className="ecx-add-item" onClick={() => setAdding(true)}><Plus className="ecx-icon ecx-icon-sm" aria-hidden />{tp.socialAdd}</button> : (
152
+ <form className="ecx-ph-row" onSubmit={(e) => { e.preventDefault(); const url = String(new FormData(e.currentTarget).get("url") ?? "").trim(); if (!url || !isSafeUrl(url)) return; setAttrs({ links: [...all, { service, url }] }); setAdding(false); }}>
153
+ <select className="ecx-input" aria-label={tp.socialNetwork} value={service} onChange={(e) => setService(e.target.value)}>{SOCIAL.map(([v, n]) => <option key={v} value={v}>{n}</option>)}</select>
154
+ <input className="ecx-input" name="url" type="url" aria-label={tp.link} placeholder={service === "email" ? "mailto:ban@congty.vn" : "https://…"} autoFocus />
155
+ <button type="submit" className="ecx-btn ecx-btn-primary">OK</button>
156
+ </form>
157
+ )}
158
+ </span>
159
+ ) : null;
160
+ if (!links.length) return <div {...(blockProps as object)} className={cx(blockProps.className, "ecx-media-placeholder ecx-ph-inline")} data-ecx-placeholder="social"><span className="ecx-ph-title"><Share2 className="ecx-icon" />{adder}</span></div>;
164
161
  return (
165
162
  <ul {...(blockProps as object)} className={cx(blockProps.className, "ecx-social", `is-${a.size ?? "medium"}`, typeof a.align === "string" && `is-${a.align}`, !!a.showLabels && "has-labels")}>
166
163
  {links.map((l, i) => <li key={i}><a className={`ecx-social-${l.service}`} title={l.label || socialName(l.service)} onClick={(e) => e.preventDefault()}>{l.label || socialName(l.service)}</a></li>)}
164
+ {adder ? <li className="ecx-ph-add">{adder}</li> : editable && <li className="ecx-ph-add"><button type="button" className="ecx-add-item" contentEditable={false} aria-label={tp.socialAdd} title={tp.socialAdd} onMouseDown={(e) => e.stopPropagation()} onClick={() => setAdding(true)}><Plus className="ecx-icon ecx-icon-sm" aria-hidden /></button></li>}
167
165
  </ul>
168
166
  );
169
167
  }
@@ -203,7 +201,7 @@ function SocialInspector({ attrs, setAttrs, labels }: BlockEditProps) {
203
201
  function GalleryInspector({ attrs, setAttrs }: BlockEditProps) {
204
202
  const t = useMsgs("blocks");
205
203
  const { host } = useEditor();
206
- type Img = { src: string; alt?: string; width?: number; height?: number; id?: number | string };
204
+ type Img = { src: string; alt?: string; width?: number; height?: number; id?: number | string; href?: string };
207
205
  const images = (Array.isArray(attrs.images) ? attrs.images : []) as Img[];
208
206
  const save = (next: Img[]) => setAttrs({ images: next });
209
207
  const patch = (i: number, p: Partial<Img>) => save(images.map((im, k) => (k === i ? { ...im, ...p } : im)));
@@ -220,6 +218,7 @@ function GalleryInspector({ attrs, setAttrs }: BlockEditProps) {
220
218
  <div key={`${i}-${im.src}`} className="ecx-social-row" data-gallery-row={i}>
221
219
  <img src={isSafeUrl(im.src) ? im.src : ""} alt="" width={36} height={36} style={{ objectFit: "cover", borderRadius: 4, flex: "none" }} />
222
220
  <input className="ecx-input" type="text" aria-label={format(t.imageAltN, { n: i + 1 })} placeholder={t.imageAltN.replace("{n}", String(i + 1))} value={im.alt ?? ""} onChange={(e) => patch(i, { alt: e.target.value })} />
221
+ <input className="ecx-input" type="url" inputMode="url" aria-label={format(t.imageLinkN, { n: i + 1 })} placeholder={t.imageLink} value={im.href ?? ""} onChange={(e) => patch(i, { href: e.target.value || undefined })} />
223
222
  <span className="ecx-social-row-tools">
224
223
  <button type="button" className="ecx-tool" aria-label={t.up} disabled={i === 0} onClick={() => move(i, -1)}><ArrowUp className="ecx-icon ecx-icon-sm" /></button>
225
224
  <button type="button" className="ecx-tool" aria-label={t.down} disabled={i === images.length - 1} onClick={() => move(i, 1)}><ArrowDown className="ecx-icon ecx-icon-sm" /></button>
@@ -232,27 +231,38 @@ function GalleryInspector({ attrs, setAttrs }: BlockEditProps) {
232
231
  );
233
232
  }
234
233
 
235
- function TocEdit({ block, blockProps, labels }: BlockEditProps) {
234
+ function TocEdit({ block, blockProps }: BlockEditProps) {
236
235
  const t = useMsgs("blocks");
236
+ const tp = useMsgs("placeholders");
237
+ const a = block.attrs;
238
+ const min = Math.min(6, Math.max(2, Number(a.minLevel) || 2));
239
+ const max = Math.min(6, Math.max(min, Number(a.maxLevel) || 3));
240
+ const title = String(a.title || t.contents);
241
+ const list = <TocItems minLevel={min} maxLevel={max} listStyle={String(a.listStyle ?? "numbers")} columns={Number(a.columns) || 1} empty={<p className="ecx-placeholder-hint ecx-ph-note" contentEditable={false}>{tp.tocHint.replace("{n}", String(max))}</p>} />;
242
+ // Khung soạn luôn mở danh sách (kể cả "bắt đầu thu gọn") để thấy được nội dung
237
243
  return (
238
- <nav {...(blockProps as object)} className={cx(blockProps.className, "ecx-toc")}>
239
- <p className="ecx-toc-title">{String(block.attrs.title || (t.contents))}</p>
240
- <TocItems maxLevel={Math.min(4, Math.max(2, Number(block.attrs.maxLevel) || 3))} />
244
+ <nav {...(blockProps as object)} className={cx(blockProps.className, "ecx-toc", a.smoothScroll === true && "is-smooth")}>
245
+ {a.collapsible === true
246
+ ? <details className="ecx-toc-details" open><summary className="ecx-toc-title" onClick={(e) => e.preventDefault()}>{title}</summary>{list}</details>
247
+ : <>{a.showTitle !== false && <p className="ecx-toc-title">{title}</p>}{list}</>}
241
248
  </nav>
242
249
  );
243
250
  }
244
251
 
245
- /** Mục lục xem trước: tiêu đề của tài liệu đang soạn. */
246
- function TocItems({ maxLevel }: { maxLevel: number }) {
252
+ /** Mục lục xem trước: tiêu đề của tài liệu đang soạn (cùng lớp CSS với website). */
253
+ function TocItems({ minLevel, maxLevel, listStyle, columns, empty }: { minLevel: number; maxLevel: number; listStyle: string; columns: number; empty?: ReactNode }) {
247
254
  const { store } = useEditor();
248
255
  const doc = store.getState().docs[store.activeDocId];
249
256
  const items: Array<{ level: number; text: string }> = [];
250
257
  const walk = (list: typeof doc.blocks) => list.forEach((b) => {
251
- if (b.type === "heading" && Number(b.attrs.level) >= 2 && Number(b.attrs.level) <= maxLevel) items.push({ level: Number(b.attrs.level), text: (b.inline ?? []).map((n) => n.text ?? "").join("") });
258
+ if (b.type === "heading" && Number(b.attrs.level) >= minLevel && Number(b.attrs.level) <= maxLevel) items.push({ level: Number(b.attrs.level), text: (typeof b.attrs.tocTitle === "string" && b.attrs.tocTitle.trim()) || (b.inline ?? []).map((n) => n.text ?? "").join("") });
252
259
  if (b.content) walk(b.content);
253
260
  });
254
261
  if (doc) walk(doc.blocks);
255
- return <ol>{items.map((h, i) => <li key={i} style={h.level > 2 ? { marginLeft: `${h.level - 2}em` } : undefined}>{h.text || "…"}</li>)}</ol>;
262
+ if (!items.length && empty) return <>{empty}</>;
263
+ const List = listStyle === "bullets" || listStyle === "none" ? "ul" : "ol";
264
+ const cols = Math.min(3, Math.max(1, columns));
265
+ return <List className={cx("ecx-toc-list", listStyle === "none" && "is-plain", cols > 1 && `has-cols-${cols}`)}>{items.map((h, i) => <li key={i} style={h.level > minLevel ? { marginLeft: `${h.level - minLevel}em` } : undefined}>{h.text || "…"}</li>)}</List>;
256
266
  }
257
267
 
258
268
  export function mediaBlocks(): BlockType[] {
@@ -263,7 +273,7 @@ export function mediaBlocks(): BlockType[] {
263
273
  attributes: { ...media, alt: { type: "string", control: "textarea" }, title: { type: "string" }, width: { type: "number" }, height: { type: "number" }, size: { type: "string", default: "large" }, align: { type: "string", enum: ["left", "right", "center", "wide", "full"] }, href: { type: "url" }, linkTarget: { type: "string", enum: ["_self", "_blank"] }, lightbox: { type: "boolean", default: false } },
264
274
  supports: { style: true, anchor: true, className: true, blockStyle: true }, summary: (a) => a.alt || a.src,
265
275
  },
266
- { name: "gallery", title: "Gallery", icon: Images, category: "media", keywords: "gallery bo suu tap nhieu anh album", kind: "atom", edit: GalleryEdit, inspector: GalleryInspector, attributes: { images: { type: "json", default: [] }, columns: { type: "integer", default: 3, min: 1, max: 6 }, caption: { type: "string" }, linkTo: { type: "string", enum: ["none", "media"], default: "media" }, imageCrop: { type: "boolean", default: true }, lightbox: { type: "boolean", default: false } }, supports: { style: true, anchor: true, className: true } },
276
+ { name: "gallery", title: "Gallery", icon: Images, category: "media", keywords: "gallery bo suu tap nhieu anh album", kind: "atom", edit: GalleryEdit, inspector: GalleryInspector, attributes: { layout: { type: "string", enum: ["grid", "masonry"], default: "grid" }, images: { type: "json", default: [] }, columns: { type: "integer", default: 3, min: 1, max: 6 }, caption: { type: "string" }, linkTo: { type: "string", enum: ["none", "media"], default: "media" }, imageCrop: { type: "boolean", default: true }, lightbox: { type: "boolean", default: false } }, supports: { style: true, anchor: true, className: true } },
267
277
  { name: "video", title: "Video", icon: Video, category: "media", keywords: "video mp4 phim", kind: "atom", edit: VideoEdit, attributes: { ...media, name: { type: "string" }, mime: { type: "string" }, poster: { type: "url", control: "media" }, autoplay: { type: "boolean", default: false }, loop: { type: "boolean", default: false }, muted: { type: "boolean", default: false }, controls: { type: "boolean", default: true }, playsInline: { type: "boolean", default: true }, preload: { type: "string", enum: ["none", "metadata", "auto"], default: "metadata" } }, supports: { style: true, anchor: true } },
268
278
  { name: "audio", title: "Âm thanh", icon: Music, category: "media", keywords: "am thanh audio nhac mp3 podcast", kind: "atom", edit: AudioEdit, attributes: { ...media, name: { type: "string" }, mime: { type: "string" }, autoplay: { type: "boolean", default: false }, loop: { type: "boolean", default: false }, preload: { type: "string", enum: ["none", "metadata", "auto"], default: "metadata" } }, supports: { style: true, anchor: true } },
269
279
  { name: "file", title: "Tệp", icon: FileIcon, category: "media", keywords: "tep file pdf tai xuong download tai lieu", kind: "atom", edit: FileEdit, attributes: { ...media, name: { type: "string" }, mime: { type: "string" }, size: { type: "number" }, embed: { type: "boolean", default: true }, download: { type: "boolean" } }, supports: { style: true, anchor: true } },
@@ -271,6 +281,6 @@ export function mediaBlocks(): BlockType[] {
271
281
  { name: "embed", title: "Nhúng", icon: Globe, category: "embed", keywords: "nhung embed youtube vimeo tiktok facebook twitter x instagram spotify google map", kind: "atom", edit: EmbedEdit, attributes: { url: { type: "url" }, caption: { type: "string" } }, supports: { style: true, anchor: true }, summary: (a) => a.url },
272
282
  { name: "customHtml", title: "HTML tuỳ chỉnh", icon: Code2, category: "widgets", keywords: "html tuy chinh custom code", kind: "atom", edit: HtmlEdit, attributes: { html: { type: "string", control: "textarea" } } },
273
283
  { name: "socialLinks", title: "Mạng xã hội", icon: Share2, category: "widgets", keywords: "mang xa hoi social facebook zalo youtube tiktok", kind: "atom", edit: SocialEdit, inspector: SocialInspector, attributes: { links: { type: "json", default: [] }, size: { type: "string", enum: ["small", "medium", "large"], default: "medium" }, align: { type: "string", enum: ["left", "center", "right"] }, showLabels: { type: "boolean", default: false } }, supports: { style: true, anchor: true, className: true } },
274
- { name: "tableOfContents", title: "Mục lục", icon: ListTree, category: "widgets", keywords: "muc luc table of contents toc", kind: "atom", edit: TocEdit, attributes: { title: { type: "string" }, maxLevel: { type: "integer", default: 3, min: 2, max: 4 } }, supports: { style: true, anchor: true } },
284
+ { name: "tableOfContents", title: "Mục lục", icon: ListTree, category: "widgets", keywords: "muc luc table of contents toc", kind: "atom", edit: TocEdit, attributes: { title: { type: "string" }, minLevel: { type: "integer", default: 2, min: 2, max: 6 }, maxLevel: { type: "integer", default: 3, min: 2, max: 6 }, collapsible: { type: "boolean", default: false }, startCollapsed: { type: "boolean", default: false }, listStyle: { type: "string", enum: ["numbers", "bullets", "none"], default: "numbers" }, columns: { type: "integer", default: 1, min: 1, max: 3 }, smoothScroll: { type: "boolean", default: false }, highlight: { type: "boolean", default: false }, showTitle: { type: "boolean", default: true } }, supports: { style: true, anchor: true } },
275
285
  ];
276
286
  }
@@ -1,6 +1,12 @@
1
1
  import { useCallback, useLayoutEffect, useRef, useState } from "react";
2
+ import { normalizeStyle, type BlockStyle } from "@ecomcx/ecomweb-content";
2
3
  import { useEditor, useEditorState } from "../context";
4
+ import { hideSpacingViz, showSpacingViz } from "../canvas/spacing-viz";
3
5
  import type { BNode } from "../core/model";
6
+ import { labelsLegacy } from "../../shared/labels";
7
+
8
+ /** Thả tay nắm: focus về khung soạn để ⌘Z / Delete… thuộc về trình soạn ngay. */
9
+ const focusCanvas = (el: HTMLElement) => el.ownerDocument.querySelector<HTMLElement>(".ecx-canvas-root")?.focus({ preventScroll: true });
4
10
 
5
11
  /** Khối hoặc khối con của nó đang được chọn / gõ (hiện tay nắm đổi cỡ). */
6
12
  export function useActiveWithin(id: string) {
@@ -20,7 +26,7 @@ export function ColumnHandles({ block }: { block: BNode }) {
20
26
  const ref = useRef<HTMLSpanElement>(null);
21
27
  const [gaps, setGaps] = useState<Array<{ left: number; top: number; height: number }>>([]);
22
28
  const cols = block.content ?? [];
23
- useLayoutEffect(() => {
29
+ const measure = () => {
24
30
  const host = ref.current?.parentElement;
25
31
  if (!host) return;
26
32
  const hr = host.getBoundingClientRect();
@@ -32,7 +38,16 @@ export function ColumnHandles({ block }: { block: BNode }) {
32
38
  return { left: (a.right + b.left) / 2 - hr.left, top: Math.min(a.top, b.top) - hr.top, height: Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top) };
33
39
  }).filter(Boolean) as Array<{ left: number; top: number; height: number }>;
34
40
  setGaps((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));
35
- });
41
+ };
42
+ useLayoutEffect(measure);
43
+ // Đổi khổ màn hình / thu nhỏ khung: cột có thể xuống dòng mà không vẽ lại → đo lại, không để tay kéo nằm ngoài khung (tràn ngang)
44
+ useLayoutEffect(() => {
45
+ const host = ref.current?.parentElement;
46
+ if (!host) return;
47
+ const ro = new ResizeObserver(measure);
48
+ ro.observe(host);
49
+ return () => ro.disconnect();
50
+ }, []);
36
51
  const start = (i: number, e: React.PointerEvent) => {
37
52
  e.preventDefault();
38
53
  e.stopPropagation();
@@ -44,9 +59,12 @@ export function ColumnHandles({ block }: { block: BNode }) {
44
59
  const pair = widths[i] + widths[i + 1];
45
60
  const handle = e.currentTarget as HTMLElement;
46
61
  handle.setPointerCapture(e.pointerId);
62
+ handle.classList.add("is-dragging");
47
63
  const move = (ev: PointerEvent) => {
48
64
  const ratio = Math.min(0.9, Math.max(0.1, (ev.clientX - a.left) / (b.right - a.left)));
49
65
  const wa = Math.round(pair * ratio), wb = Math.round(pair - pair * ratio);
66
+ // Nhãn % hai bên tay nắm khi đang kéo
67
+ handle.dataset.left = `${wa}%`; handle.dataset.right = `${wb}%`;
50
68
  const ids = cols.map((c) => c.id);
51
69
  store.batch(() => {
52
70
  widths.forEach((w, k) => {
@@ -55,7 +73,7 @@ export function ColumnHandles({ block }: { block: BNode }) {
55
73
  });
56
74
  });
57
75
  };
58
- const up = () => { handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up); store.breakMerge(); };
76
+ const up = () => { handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up); handle.classList.remove("is-dragging"); store.breakMerge(); focusCanvas(handle); };
59
77
  handle.addEventListener("pointermove", move);
60
78
  handle.addEventListener("pointerup", up);
61
79
  };
@@ -102,10 +120,160 @@ export function ImageHandle({ blockId }: { blockId: string }) {
102
120
  const w = Math.round(Math.min(max, Math.max(48, ev.clientX - r.left)));
103
121
  store.setAttrs([blockId], { width: w, height: Math.round(w * ratio) || undefined });
104
122
  };
105
- const up = () => { handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up); store.breakMerge(); };
123
+ const up = () => { handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up); store.breakMerge(); focusCanvas(handle); };
106
124
  handle.addEventListener("pointermove", move);
107
125
  handle.addEventListener("pointerup", up);
108
126
  };
109
127
  return <span ref={ref} className="ecx-image-handle" contentEditable={false} title={labels.resize} style={pos ? { left: pos.left - 7, top: pos.top - 7 } : { visibility: "hidden" }}
110
128
  onPointerDown={start} onMouseDown={(e) => e.stopPropagation()} />;
111
129
  }
130
+
131
+ /** Kéo mép dưới để đổi chiều cao khối (Khoảng trống): ghi `attrs.height` = "NNpx". Dùng chung kiểu tay nắm của dải đệm. */
132
+ export function HeightHandle({ blockId }: { blockId: string }) {
133
+ const { store, ui, labels } = useEditor();
134
+ const start = (e: React.PointerEvent) => {
135
+ e.preventDefault();
136
+ e.stopPropagation();
137
+ const handle = e.currentTarget as HTMLElement;
138
+ const el = ui.blockEl(blockId);
139
+ if (!el) return;
140
+ const h0 = el.getBoundingClientRect().height, y0 = e.clientY;
141
+ handle.setPointerCapture(e.pointerId);
142
+ handle.classList.add("is-dragging");
143
+ const move = (ev: PointerEvent) => store.setAttrs([blockId], { height: `${Math.max(8, Math.round(h0 + ev.clientY - y0))}px` });
144
+ const up = () => {
145
+ handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up);
146
+ handle.classList.remove("is-dragging"); store.breakMerge(); focusCanvas(handle);
147
+ };
148
+ handle.addEventListener("pointermove", move);
149
+ handle.addEventListener("pointerup", up);
150
+ };
151
+ return (
152
+ <span className="ecx-pad-handles" contentEditable={false} aria-hidden="true">
153
+ <span className="ecx-pad-handle is-bottom" title={labels.resize} onPointerDown={start} onMouseDown={(e) => e.stopPropagation()} />
154
+ </span>
155
+ );
156
+ }
157
+
158
+ /**
159
+ * Vùng kéo đệm / lề trên, dưới của khối bố cục đang chọn (Nhóm, Bộ cột, Cột): vùng rộng hết khối, cao bằng giá trị thật; kéo đổi giá trị
160
+ * của khổ màn hình đang xem (lưu px, giữ các cạnh khác); rê / kéo thì vùng được tô kèm số px — như ô Đệm / Lề ở bảng bên phải.
161
+ */
162
+ export function PaddingHandles({ blockId }: { blockId: string }) {
163
+ const { store, ui, labels: v2 } = useEditor();
164
+ const L = labelsLegacy(v2.lang);
165
+ const ref = useRef<HTMLSpanElement>(null);
166
+ // Cỡ thật (px) của đệm / lề trên, dưới: vùng kéo cao đúng bằng nó (tối thiểu 8px) — kéo ở bất kỳ đâu trong vùng
167
+ const [px, setPx] = useState({ pt: 0, pb: 0, mt: 0, mb: 0 });
168
+ useLayoutEffect(() => {
169
+ const el = ui.blockEl(blockId);
170
+ if (!el) return;
171
+ const cs = el.ownerDocument.defaultView!.getComputedStyle(el), n = (k: string) => Math.round(parseFloat(cs.getPropertyValue(k)) || 0);
172
+ const next = { pt: n("padding-top"), pb: n("padding-bottom"), mt: n("margin-top"), mb: n("margin-bottom") };
173
+ setPx((p) => (p.pt === next.pt && p.pb === next.pb && p.mt === next.mt && p.mb === next.mb ? p : next));
174
+ });
175
+ const start = (kind: "padding" | "margin", side: "top" | "bottom", e: React.PointerEvent) => {
176
+ e.preventDefault();
177
+ e.stopPropagation();
178
+ const handle = e.currentTarget as HTMLElement;
179
+ const el = ui.blockEl(blockId);
180
+ if (!el) return;
181
+ const startPx = parseFloat(el.ownerDocument.defaultView!.getComputedStyle(el).getPropertyValue(`${kind}-${side}`)) || 0;
182
+ const y0 = e.clientY;
183
+ const device = ui.device === "desktop" ? "base" : ui.device;
184
+ handle.setPointerCapture(e.pointerId);
185
+ handle.classList.add("is-dragging");
186
+ const move = (ev: PointerEvent) => {
187
+ // Đệm dưới / lề dưới: kéo xuống là tăng; đệm trên: kéo xuống tăng; lề trên: kéo lên tăng
188
+ const d = ev.clientY - y0;
189
+ const px = Math.max(0, Math.round(startPx + (kind === "margin" && side === "top" ? -d : d)));
190
+ const node = store.block(blockId);
191
+ if (!node) return;
192
+ const style = (normalizeStyle(node.attrs.style) ?? {}) as BlockStyle & Record<"padding" | "margin", Record<string, unknown> | undefined>;
193
+ const cur = style[kind]?.[device];
194
+ const sides = typeof cur === "object" && cur ? { ...(cur as Record<string, string>) } : typeof cur === "string" ? { top: cur, right: cur, bottom: cur, left: cur } : {};
195
+ sides[side] = `${px}px`;
196
+ store.setAttrs([blockId], { style: normalizeStyle({ ...style, [kind]: { ...(style[kind] ?? {}), [device]: sides } }) ?? undefined });
197
+ requestAnimationFrame(() => showSpacingViz(ui.blockEl(blockId), kind, [side]));
198
+ };
199
+ const up = () => {
200
+ handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up);
201
+ handle.classList.remove("is-dragging"); hideSpacingViz(ui.canvasDoc); store.breakMerge(); focusCanvas(handle);
202
+ };
203
+ handle.addEventListener("pointermove", move);
204
+ handle.addEventListener("pointerup", up);
205
+ };
206
+ const zones = [
207
+ ["padding", "top", { top: 0, height: Math.max(8, px.pt) }],
208
+ ["padding", "bottom", { bottom: 0, height: Math.max(8, px.pb) }],
209
+ ["margin", "top", { top: -Math.max(8, px.mt), height: Math.max(8, px.mt) }],
210
+ ["margin", "bottom", { bottom: -Math.max(8, px.mb), height: Math.max(8, px.mb) }],
211
+ ] as const;
212
+ return (
213
+ <span ref={ref} className="ecx-pad-handles" contentEditable={false} aria-hidden="true">
214
+ {zones.map(([kind, side, pos]) => (
215
+ <span key={kind + side} className={`ecx-pad-zone is-${kind} is-${side}`} style={pos} title={kind === "padding" ? L.style_padding : L.style_margin} data-ecx-zone={`${kind}-${side}`}
216
+ onPointerDown={(e) => start(kind, side, e)} onMouseDown={(e) => e.stopPropagation()}
217
+ onPointerEnter={() => showSpacingViz(ui.blockEl(blockId), kind, [side])}
218
+ onPointerLeave={(e) => { if (!(e.currentTarget as HTMLElement).classList.contains("is-dragging")) hideSpacingViz(ui.canvasDoc); }} />
219
+ ))}
220
+ </span>
221
+ );
222
+ }
223
+
224
+ /**
225
+ * Tay kéo độ rộng nội dung bên trong của Nhóm: hai tay ở hai mép vùng nội dung (khối con đầu tiên); kéo vào / ra là đổi độ rộng đối xứng,
226
+ * số px hiện cạnh tay khi kéo. Kéo hết cỡ ra mép = về "Hết khối". Lưu vào `contentWidth` như ô ở bảng Cài đặt.
227
+ */
228
+ export function ContentWidthHandles({ blockId }: { blockId: string }) {
229
+ const { store, ui } = useEditor();
230
+ const [box, setBox] = useState<{ left: number; right: number; max: number } | null>(null);
231
+ const [drag, setDrag] = useState<number | null>(null);
232
+ /** Đo theo giá trị ràng buộc (max-width của khối con), không theo kích thước khối con — hàng ngang / lưới / xếp dọc làm khối con co theo chữ. */
233
+ const measure = () => {
234
+ const el = ui.blockEl(blockId), kid = el?.querySelector(":scope > [data-ecx-block]") as HTMLElement | null;
235
+ if (!el || !kid) return null;
236
+ const win = el.ownerDocument.defaultView!, cs = win.getComputedStyle(el), g = el.getBoundingClientRect();
237
+ const padL = parseFloat(cs.paddingLeft) || 0, max = Math.round(g.width - padL - (parseFloat(cs.paddingRight) || 0));
238
+ const mwRaw = win.getComputedStyle(kid).maxWidth, mw = mwRaw.endsWith("px") ? parseFloat(mwRaw) : NaN;
239
+ const width = Math.min(max, Number.isFinite(mw) ? Math.round(mw) : max);
240
+ const left = Math.round(padL + (max - width) / 2);
241
+ return { left, right: left + width, max, width };
242
+ };
243
+ useLayoutEffect(() => {
244
+ const m = measure();
245
+ setBox((p) => (!m ? null : p && p.left === m.left && p.right === m.right && p.max === m.max ? p : { left: m.left, right: m.right, max: m.max }));
246
+ });
247
+ const start = (dir: 1 | -1, e: React.PointerEvent) => {
248
+ e.preventDefault(); e.stopPropagation();
249
+ const handle = e.currentTarget as HTMLElement, m = measure();
250
+ if (!m) return;
251
+ const x0 = e.clientX;
252
+ handle.setPointerCapture(e.pointerId);
253
+ handle.classList.add("is-dragging");
254
+ const move = (ev: PointerEvent) => {
255
+ const w = Math.min(m.max, Math.max(240, Math.round(m.width + 2 * dir * (ev.clientX - x0))));
256
+ const node = store.block(blockId);
257
+ if (!node) return;
258
+ setDrag(w);
259
+ store.setAttrs([blockId], { constrained: undefined, contentWidth: w >= m.max ? undefined : `${w}px` });
260
+ };
261
+ const up = () => {
262
+ handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up);
263
+ handle.classList.remove("is-dragging"); setDrag(null); store.breakMerge(); focusCanvas(handle);
264
+ };
265
+ handle.addEventListener("pointermove", move);
266
+ handle.addEventListener("pointerup", up);
267
+ };
268
+ if (!box) return null;
269
+ return (
270
+ <span className="ecx-cw-handles" contentEditable={false} aria-hidden="true">
271
+ {([["left", box.left, -1], ["right", box.right, 1]] as const).map(([side, x, dir]) => (
272
+ <span key={side} className={`ecx-cw-handle is-${side}`} style={{ left: x }} data-ecx-zone={`content-width-${side}`}
273
+ onPointerDown={(e) => start(dir === 1 ? 1 : -1, e)} onMouseDown={(e) => e.stopPropagation()}>
274
+ {drag !== null && <span className="ecx-cw-tip">{drag}px</span>}
275
+ </span>
276
+ ))}
277
+ </span>
278
+ );
279
+ }