@ecomcx/ecomweb-editor 1.18.0 → 1.19.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 (87) hide show
  1. package/package.json +25 -7
  2. package/src/index.ts +26 -25
  3. package/src/{ask.tsx → legacy/ask.tsx} +2 -2
  4. package/src/{blockMeta.ts → legacy/block-meta.ts} +1 -1
  5. package/src/{blocks.tsx → legacy/blocks.tsx} +8 -32
  6. package/src/{content.ts → legacy/content.ts} +1 -1
  7. package/src/{handle.tsx → legacy/drag-handle.tsx} +3 -3
  8. package/src/{dynamic.tsx → legacy/dynamic.tsx} +7 -3
  9. package/src/{Editor.tsx → legacy/editor.tsx} +9 -9
  10. package/src/{extensions.ts → legacy/extensions.ts} +1 -1
  11. package/src/legacy/insert-pattern.ts +13 -0
  12. package/src/{inserter.tsx → legacy/inserter.tsx} +6 -5
  13. package/src/{inspector.tsx → legacy/inspector.tsx} +7 -7
  14. package/src/{layoutUi.tsx → legacy/layout-ui.tsx} +6 -5
  15. package/src/{layout.tsx → legacy/layout.tsx} +2 -2
  16. package/src/{media.ts → legacy/media.ts} +1 -1
  17. package/src/{nodes.tsx → legacy/nodes.tsx} +2 -2
  18. package/src/{outline.tsx → legacy/outline.tsx} +4 -4
  19. package/src/legacy/panels.ts +22 -0
  20. package/src/{rank.ts → legacy/rank.ts} +2 -2
  21. package/src/{registry.ts → legacy/registry.ts} +1 -1
  22. package/src/{handles.tsx → legacy/resize-handles.tsx} +1 -1
  23. package/src/{styleattr.ts → legacy/style-attr.ts} +15 -1
  24. package/src/{synced.tsx → legacy/synced.tsx} +2 -2
  25. package/src/{toolbar.tsx → legacy/toolbar.tsx} +7 -7
  26. package/src/{unknown.tsx → legacy/unknown.tsx} +1 -1
  27. package/src/shared/block-defs.ts +38 -0
  28. package/src/shared/color-swatch.tsx +19 -0
  29. package/src/{panels.ts → shared/panel-store.ts} +4 -21
  30. package/src/{patterns.ts → shared/patterns.ts} +0 -12
  31. package/src/{stylepanel.tsx → shared/style-panel.tsx} +2 -2
  32. package/src/{types.ts → shared/types.ts} +2 -0
  33. package/src/v2/blocks/compat.tsx +51 -0
  34. package/src/v2/blocks/index.ts +42 -0
  35. package/src/v2/blocks/layout.tsx +281 -0
  36. package/src/v2/blocks/media-actions.tsx +76 -0
  37. package/src/v2/blocks/media.tsx +234 -0
  38. package/src/v2/blocks/resize.tsx +111 -0
  39. package/src/v2/blocks/text.tsx +149 -0
  40. package/src/v2/blocks/theme.tsx +293 -0
  41. package/src/v2/blocks/tools.tsx +72 -0
  42. package/src/v2/canvas/block-list.tsx +216 -0
  43. package/src/v2/canvas/canvas-css.ts +131 -0
  44. package/src/v2/canvas/canvas.tsx +379 -0
  45. package/src/v2/canvas/dnd.ts +192 -0
  46. package/src/v2/context.tsx +146 -0
  47. package/src/v2/core/bindings.ts +64 -0
  48. package/src/v2/core/clipboard.ts +238 -0
  49. package/src/v2/core/host.ts +80 -0
  50. package/src/v2/core/model.ts +157 -0
  51. package/src/v2/core/ops.ts +151 -0
  52. package/src/v2/core/patterns.ts +10 -0
  53. package/src/v2/core/registry.ts +135 -0
  54. package/src/v2/core/store.ts +804 -0
  55. package/src/v2/core/structure.ts +106 -0
  56. package/src/v2/core/tables.ts +194 -0
  57. package/src/v2/editor.css +310 -0
  58. package/src/v2/editor.tsx +288 -0
  59. package/src/v2/index.ts +28 -0
  60. package/src/v2/labels.ts +341 -0
  61. package/src/v2/prefs.ts +69 -0
  62. package/src/v2/text/paste.ts +75 -0
  63. package/src/v2/text/rich-schema.ts +96 -0
  64. package/src/v2/text/rich-text.tsx +512 -0
  65. package/src/v2/ui/attr-form.tsx +182 -0
  66. package/src/v2/ui/attr-hints.ts +109 -0
  67. package/src/v2/ui/bindings.tsx +91 -0
  68. package/src/v2/ui/block-descriptions.ts +34 -0
  69. package/src/v2/ui/color-field.tsx +17 -0
  70. package/src/v2/ui/doc-title.tsx +45 -0
  71. package/src/v2/ui/inserter.tsx +300 -0
  72. package/src/v2/ui/inspector.tsx +85 -0
  73. package/src/v2/ui/layout-panel.tsx +159 -0
  74. package/src/v2/ui/list-view.tsx +65 -0
  75. package/src/v2/ui/options.tsx +242 -0
  76. package/src/v2/ui/style-controls.tsx +57 -0
  77. package/src/v2/ui/style-tab.tsx +158 -0
  78. package/src/v2/ui/toolbar.tsx +397 -0
  79. package/src/v2/ui/unit-controls.tsx +99 -0
  80. /package/src/{basic.tsx → legacy/basic.tsx} +0 -0
  81. /package/src/{blockops.ts → legacy/block-ops.ts} +0 -0
  82. /package/src/{boundary.tsx → legacy/boundary.tsx} +0 -0
  83. /package/src/{editor.css → legacy/editor.css} +0 -0
  84. /package/src/{insert.ts → legacy/insert.ts} +0 -0
  85. /package/src/{labels.ts → shared/labels.ts} +0 -0
  86. /package/src/{paste.ts → shared/paste.ts} +0 -0
  87. /package/src/{util.ts → shared/util.ts} +0 -0
@@ -0,0 +1,234 @@
1
+ import { embedInfo, isSafeUrl } from "@ecomcx/ecomweb-content";
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 } from "react";
4
+ import { useEditor } from "../context";
5
+ import type { BlockEditProps, BlockType } from "../core/registry";
6
+ import { RichText } from "../text/rich-text";
7
+ import { BoundText, useBindingPreview } from "../ui/bindings";
8
+ import { ImageHandle } from "./resize";
9
+ import { MediaActions, mediaAttrs, useFileDrop } from "./media-actions";
10
+ import type { MediaItem, MediaKind } from "../../shared/types";
11
+
12
+ const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
13
+ const safe = (u: unknown) => (typeof u === "string" && isSafeUrl(u) ? u : "");
14
+
15
+ /** Ô trống của khối media: chọn từ thư viện hoặc dán đường dẫn. */
16
+ function MediaPlaceholder({ blockId, kind, icon: Icon, title, blockProps }: { blockId: string; kind: MediaKind; icon: typeof ImageIcon; title: string; blockProps: BlockEditProps["blockProps"] }) {
17
+ const { store, labels } = useEditor();
18
+ const select = (items: MediaItem[]) => store.setAttrs([blockId], mediaAttrs(kind, items));
19
+ const drop = useFileDrop(kind, select);
20
+ return (
21
+ <div {...blockProps} {...drop.props} className={cx(blockProps.className, "ecx-media-placeholder", drop.over && "is-drop-target")}>
22
+ <span className="ecx-placeholder-title"><Icon className="ecx-icon" />{title}</span>
23
+ <p className="ecx-placeholder-hint">{labels.dropHint[kind] ?? labels.dropHint.file}</p>
24
+ <MediaActions kind={kind} onSelect={select} onUrl={kind === "gallery" ? undefined : (url) => store.setAttrs([blockId], { src: url })} />
25
+ </div>
26
+ );
27
+ }
28
+
29
+ function ImageEdit({ block, blockProps, setAttrs, editable, labels, selected }: BlockEditProps) {
30
+ const a = block.attrs;
31
+ const bSrc = useBindingPreview(block, "src"), bAlt = useBindingPreview(block, "alt"), bCap = useBindingPreview(block, "caption");
32
+ const src = bSrc.bound ? safe(bSrc.value) : safe(a.src);
33
+ 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>;
34
+ if (!src) return <MediaPlaceholder blockId={block.id} kind="image" icon={ImageIcon} title={labels.image} blockProps={blockProps} />;
35
+ const cls = cx("ecx-image cms-image", a.align && `ecx-align-${a.align} align${a.align}`);
36
+ return (
37
+ <figure {...blockProps} className={cx(blockProps.className, cls)} style={{ ...(blockProps.style ?? {}), position: "relative" }}>
38
+ {selected && editable && <ImageHandle blockId={block.id} />}
39
+ <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} />
40
+ {bCap.bound ? <BoundText tagName="figcaption" preview={bCap} /> : (a.caption || editable) && (
41
+ <RichText blockId={block.id} field="caption" tagName="figcaption" value={String(a.caption ?? "")} onChange={(v) => setAttrs({ caption: v })} placeholder={labels.caption} editable={editable} />
42
+ )}
43
+ </figure>
44
+ );
45
+ }
46
+
47
+ function GalleryEdit({ block, blockProps, labels }: BlockEditProps) {
48
+ const images = (Array.isArray(block.attrs.images) ? block.attrs.images : []) as Array<{ src: string; alt?: string }>;
49
+ if (!images.length) return <MediaPlaceholder blockId={block.id} kind="gallery" icon={Images} title="Gallery" blockProps={blockProps} />;
50
+ const cols = Math.min(6, Math.max(1, Number(block.attrs.columns) || 3));
51
+ void labels;
52
+ return (
53
+ <figure {...blockProps} className={cx(blockProps.className, "ecx-gallery cms-gallery", `ecx-gallery-columns-${cols}`)} style={{ display: "grid", gap: 8, gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}>
54
+ {images.map((im, i) => <figure key={i} className="ecx-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>)}
55
+ </figure>
56
+ );
57
+ }
58
+
59
+ function VideoEdit({ block, blockProps, labels }: BlockEditProps) {
60
+ const src = safe(block.attrs.src);
61
+ if (!src) return <MediaPlaceholder blockId={block.id} kind="video" icon={Video} title="Video" blockProps={blockProps} />;
62
+ void labels;
63
+ return <figure {...blockProps} className={cx(blockProps.className, "ecx-video cms-video")}><video src={src} controls preload="metadata" style={{ width: "100%", pointerEvents: "none" }} /></figure>;
64
+ }
65
+
66
+ function AudioEdit({ block, blockProps }: BlockEditProps) {
67
+ const src = safe(block.attrs.src);
68
+ if (!src) return <MediaPlaceholder blockId={block.id} kind="audio" icon={Music} title="Audio" blockProps={blockProps} />;
69
+ return <figure {...blockProps} className={cx(blockProps.className, "ecx-audio cms-audio")}><audio src={src} controls preload="metadata" style={{ width: "100%", pointerEvents: "none" }} /></figure>;
70
+ }
71
+
72
+ function FileEdit({ block, blockProps }: BlockEditProps) {
73
+ const src = safe(block.attrs.src);
74
+ if (!src) return <MediaPlaceholder blockId={block.id} kind="file" icon={FileIcon} title="File" blockProps={blockProps} />;
75
+ 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>;
76
+ }
77
+
78
+ function YoutubeEdit({ block, blockProps, setAttrs, labels }: BlockEditProps) {
79
+ const m = String(block.attrs.src ?? "").match(/(?:v=|youtu\.be\/|embed\/)([\w-]{11})/);
80
+ const [draft, setDraft] = useState("");
81
+ if (!m) {
82
+ const vi = labels.lang === "vi";
83
+ return (
84
+ <div {...blockProps} className={cx(blockProps.className, "ecx-media-placeholder")}>
85
+ <span className="ecx-placeholder-title"><Play className="ecx-icon" />YouTube</span>
86
+ <p className="ecx-placeholder-hint">{vi ? "Dán đường dẫn video YouTube (youtube.com/watch?v=… hoặc youtu.be/…)." : "Paste a YouTube link (youtube.com/watch?v=… or youtu.be/…)."}</p>
87
+ <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() }); }}>
88
+ <input className="ecx-input" type="url" placeholder="https://youtu.be/…" value={draft} onChange={(e) => setDraft(e.target.value)} aria-label="YouTube URL" />
89
+ <button type="submit" className="ecx-btn ecx-btn-primary">{vi ? "Nhúng" : "Embed"}</button>
90
+ </form>
91
+ </div>
92
+ );
93
+ }
94
+ return (
95
+ <div {...blockProps} className={cx(blockProps.className, "ecx-youtube embed")}>
96
+ {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"}
97
+ </div>
98
+ );
99
+ }
100
+
101
+ function EmbedEdit({ block, blockProps, setAttrs, labels }: BlockEditProps) {
102
+ const url = String(block.attrs.url ?? "");
103
+ const info = embedInfo(url);
104
+ const [draft, setDraft] = useState(url);
105
+ if (!url) {
106
+ return (
107
+ <div {...blockProps} className={cx(blockProps.className, "ecx-media-placeholder")}>
108
+ <span className="ecx-placeholder-title"><Globe className="ecx-icon" />{labels.embed}</span>
109
+ <form className="ecx-media-actions" contentEditable={false} onMouseDown={(e) => e.stopPropagation()} onSubmit={(e) => { e.preventDefault(); if (isSafeUrl(draft)) setAttrs({ url: draft.trim() }); }}>
110
+ <input className="ecx-input" type="url" placeholder="https://…" value={draft} onChange={(e) => setDraft(e.target.value)} aria-label={labels.embed} />
111
+ <button type="submit" className="ecx-btn">{labels.apply}</button>
112
+ </form>
113
+ </div>
114
+ );
115
+ }
116
+ return (
117
+ <figure {...blockProps} className={cx(blockProps.className, "ecx-embed", info && `ecx-embed-${info.provider}`)}>
118
+ <div className="ecx-embed-preview"><Globe className="ecx-icon" /> {info?.provider ?? ""} <span className="ecx-embed-url">{url}</span></div>
119
+ {typeof block.attrs.caption === "string" && block.attrs.caption && <figcaption>{block.attrs.caption}</figcaption>}
120
+ </figure>
121
+ );
122
+ }
123
+
124
+ function HtmlEdit({ block, blockProps, setAttrs, selected, editable }: BlockEditProps) {
125
+ const html = String(block.attrs.html ?? "");
126
+ return (
127
+ <div {...blockProps} className={cx(blockProps.className, "ecx-html-block")}>
128
+ {selected && editable
129
+ ? <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} />
130
+ // 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ị)
131
+ : html ? <iframe className="ecx-html-preview" sandbox="" srcDoc={html} title="HTML" /> : <span className="ecx-placeholder-title"><Code2 className="ecx-icon" />HTML</span>}
132
+ </div>
133
+ );
134
+ }
135
+
136
+ /** Mạng xã hội hỗ trợ (cùng danh sách với website — theme-sdk). */
137
+ const SOCIAL: Array<[string, string]> = [
138
+ ["facebook", "Facebook"], ["zalo", "Zalo"], ["messenger", "Messenger"], ["youtube", "YouTube"], ["tiktok", "TikTok"], ["instagram", "Instagram"], ["x", "X"],
139
+ ["threads", "Threads"], ["linkedin", "LinkedIn"], ["telegram", "Telegram"], ["pinterest", "Pinterest"], ["github", "GitHub"], ["email", "Email"], ["website", "Website"],
140
+ ];
141
+ const socialName = (s: string) => SOCIAL.find(([v]) => v === s)?.[1] ?? s;
142
+ type SocialLink = { service: string; url: string; label?: string };
143
+ const linksOf = (a: Record<string, unknown>) => (Array.isArray(a.links) ? a.links : []) as SocialLink[];
144
+
145
+ function SocialEdit({ block, blockProps, labels }: BlockEditProps) {
146
+ const links = linksOf(block.attrs).filter((l) => l.url);
147
+ const a = block.attrs;
148
+ if (!links.length) {
149
+ return (
150
+ <div {...(blockProps as object)} className={cx(blockProps.className, "ecx-placeholder-block")}>
151
+ <span className="ecx-placeholder-title"><Share2 className="ecx-icon" /> {labels.lang === "vi" ? "Mạng xã hội" : "Social links"}</span>
152
+ <span className="ecx-placeholder-summary">{labels.lang === "vi" ? "Thêm liên kết ở bảng cài đặt bên phải." : "Add links in the settings panel."}</span>
153
+ </div>
154
+ );
155
+ }
156
+ return (
157
+ <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")}>
158
+ {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>)}
159
+ </ul>
160
+ );
161
+ }
162
+
163
+ /** Danh sách liên kết mạng xã hội trong bảng cài đặt: chọn mạng, dán địa chỉ, đổi thứ tự, xoá. */
164
+ function SocialInspector({ attrs, setAttrs, labels }: BlockEditProps) {
165
+ const links = linksOf(attrs);
166
+ const vi = labels.lang === "vi";
167
+ const save = (next: SocialLink[]) => setAttrs({ links: next });
168
+ const patch = (i: number, p: Partial<SocialLink>) => save(links.map((l, k) => (k === i ? { ...l, ...p } : l)));
169
+ const move = (i: number, d: -1 | 1) => { const n = [...links]; [n[i], n[i + d]] = [n[i + d], n[i]]; save(n); };
170
+ return (
171
+ <div className="ecx-social-editor" role="group" aria-label={vi ? "Liên kết mạng xã hội" : "Social links"}>
172
+ <span className="ecx-field-label">{vi ? "Liên kết" : "Links"}</span>
173
+ {links.map((l, i) => (
174
+ <div key={i} className="ecx-social-row" data-social-row={i}>
175
+ <select className="ecx-input" aria-label={vi ? `Mạng ${i + 1}` : `Network ${i + 1}`} value={l.service} onChange={(e) => patch(i, { service: e.target.value })}>
176
+ {SOCIAL.map(([v, n]) => <option key={v} value={v}>{n}</option>)}
177
+ </select>
178
+ <input className="ecx-input" type="url" aria-label={vi ? `Địa chỉ ${i + 1}` : `URL ${i + 1}`} placeholder={l.service === "email" ? "mailto:ban@congty.vn" : "https://…"} value={l.url}
179
+ aria-invalid={!!l.url && !isSafeUrl(l.url) || undefined} onChange={(e) => patch(i, { url: e.target.value.trim() })} />
180
+ <span className="ecx-social-row-tools">
181
+ <button type="button" className="ecx-tool" aria-label={vi ? "Lên" : "Up"} disabled={i === 0} onClick={() => move(i, -1)}><ArrowUp className="ecx-icon ecx-icon-sm" /></button>
182
+ <button type="button" className="ecx-tool" aria-label={vi ? "Xuống" : "Down"} disabled={i === links.length - 1} onClick={() => move(i, 1)}><ArrowDown className="ecx-icon ecx-icon-sm" /></button>
183
+ <button type="button" className="ecx-tool" aria-label={vi ? "Xoá liên kết" : "Remove link"} onClick={() => save(links.filter((_, k) => k !== i))}><X className="ecx-icon ecx-icon-sm" /></button>
184
+ </span>
185
+ </div>
186
+ ))}
187
+ <button type="button" className="ecx-btn" onClick={() => save([...links, { service: SOCIAL.find(([v]) => !links.some((l) => l.service === v))?.[0] ?? "website", url: "" }])}>
188
+ <Plus className="ecx-icon ecx-icon-sm" /> {vi ? "Thêm liên kết" : "Add link"}
189
+ </button>
190
+ </div>
191
+ );
192
+ }
193
+
194
+ function TocEdit({ block, blockProps, labels }: BlockEditProps) {
195
+ return (
196
+ <nav {...(blockProps as object)} className={cx(blockProps.className, "ecx-toc")}>
197
+ <p className="ecx-toc-title">{String(block.attrs.title || (labels.lang === "vi" ? "Mục lục" : "Contents"))}</p>
198
+ <TocItems maxLevel={Math.min(4, Math.max(2, Number(block.attrs.maxLevel) || 3))} />
199
+ </nav>
200
+ );
201
+ }
202
+
203
+ /** Mục lục xem trước: tiêu đề của tài liệu đang soạn. */
204
+ function TocItems({ maxLevel }: { maxLevel: number }) {
205
+ const { store } = useEditor();
206
+ const doc = store.getState().docs[store.activeDocId];
207
+ const items: Array<{ level: number; text: string }> = [];
208
+ const walk = (list: typeof doc.blocks) => list.forEach((b) => {
209
+ 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("") });
210
+ if (b.content) walk(b.content);
211
+ });
212
+ if (doc) walk(doc.blocks);
213
+ return <ol>{items.map((h, i) => <li key={i} style={h.level > 2 ? { marginLeft: `${h.level - 2}em` } : undefined}>{h.text || "…"}</li>)}</ol>;
214
+ }
215
+
216
+ export function mediaBlocks(): BlockType[] {
217
+ const media = { src: { type: "url" as const, control: "media" as const }, mediaId: { type: "json" as const }, caption: { type: "string" as const } };
218
+ return [
219
+ {
220
+ name: "image", title: "Ảnh", icon: ImageIcon, category: "media", keywords: "anh hinh image photo", kind: "atom", edit: ImageEdit,
221
+ 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"] } },
222
+ supports: { style: true, anchor: true, className: true, blockStyle: true }, summary: (a) => a.alt || a.src,
223
+ },
224
+ { name: "gallery", title: "Gallery", icon: Images, category: "media", keywords: "gallery bo suu tap nhieu anh album", kind: "atom", edit: GalleryEdit, attributes: { images: { type: "json", default: [] }, columns: { type: "integer", default: 3, min: 1, max: 6 }, caption: { type: "string" } }, supports: { style: true, anchor: true, className: true } },
225
+ { 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" } }, supports: { style: true, anchor: true } },
226
+ { 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" } }, supports: { style: true, anchor: true } },
227
+ { 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 } },
228
+ { name: "youtube", title: "YouTube", icon: Play, category: "embed", keywords: "video youtube", kind: "atom", edit: YoutubeEdit, attributes: { src: { type: "url" }, start: { type: "integer" } }, supports: { style: true, anchor: true } },
229
+ { 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 },
230
+ { 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" } } },
231
+ { 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 } },
232
+ { 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 } },
233
+ ];
234
+ }
@@ -0,0 +1,111 @@
1
+ import { useCallback, useLayoutEffect, useRef, useState } from "react";
2
+ import { useEditor, useEditorState } from "../context";
3
+ import type { BNode } from "../core/model";
4
+
5
+ /** Khối hoặc khối con của nó đang được chọn / gõ (hiện tay nắm đổi cỡ). */
6
+ export function useActiveWithin(id: string) {
7
+ const { store } = useEditor();
8
+ return useEditorState(useCallback((s) => {
9
+ const cur = s.selection.ids.length ? s.selection.ids : s.selection.editing ? [s.selection.editing] : [];
10
+ return cur.some((c) => c === id || !!store.locate(c)?.ancestors.includes(id));
11
+ }, [id, store]));
12
+ }
13
+
14
+ /**
15
+ * Tay nắm giữa các cột: kéo đổi tỉ lệ hai cột kề nhau (độ rộng lưu theo %, tổng 100) — một lần kéo là một bước hoàn tác.
16
+ * Đặt tuyệt đối trong khối cột nên không ảnh hưởng bố cục flex.
17
+ */
18
+ export function ColumnHandles({ block }: { block: BNode }) {
19
+ const { store, labels } = useEditor();
20
+ const ref = useRef<HTMLSpanElement>(null);
21
+ const [gaps, setGaps] = useState<Array<{ left: number; top: number; height: number }>>([]);
22
+ const cols = block.content ?? [];
23
+ useLayoutEffect(() => {
24
+ const host = ref.current?.parentElement;
25
+ if (!host) return;
26
+ const hr = host.getBoundingClientRect();
27
+ const els = Array.from(host.children).filter((c) => (c as HTMLElement).dataset.type === "column") as HTMLElement[];
28
+ const next = els.slice(0, -1).map((el, i) => {
29
+ const a = el.getBoundingClientRect(), b = els[i + 1].getBoundingClientRect();
30
+ // Cột xuống dòng (màn hẹp): không có khe ngang
31
+ if (Math.abs(a.top - b.top) > 4) return null;
32
+ 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
+ }).filter(Boolean) as Array<{ left: number; top: number; height: number }>;
34
+ setGaps((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));
35
+ });
36
+ const start = (i: number, e: React.PointerEvent) => {
37
+ e.preventDefault();
38
+ e.stopPropagation();
39
+ const host = ref.current!.parentElement!;
40
+ const els = Array.from(host.children).filter((c) => (c as HTMLElement).dataset.type === "column") as HTMLElement[];
41
+ const total = els.reduce((s, el) => s + el.getBoundingClientRect().width, 0);
42
+ const widths = els.map((el) => (el.getBoundingClientRect().width / total) * 100);
43
+ const a = els[i].getBoundingClientRect(), b = els[i + 1].getBoundingClientRect();
44
+ const pair = widths[i] + widths[i + 1];
45
+ const handle = e.currentTarget as HTMLElement;
46
+ handle.setPointerCapture(e.pointerId);
47
+ const move = (ev: PointerEvent) => {
48
+ const ratio = Math.min(0.9, Math.max(0.1, (ev.clientX - a.left) / (b.right - a.left)));
49
+ const wa = Math.round(pair * ratio), wb = Math.round(pair - pair * ratio);
50
+ const ids = cols.map((c) => c.id);
51
+ store.batch(() => {
52
+ widths.forEach((w, k) => {
53
+ const val = k === i ? wa : k === i + 1 ? wb : Math.round(w);
54
+ store.setAttrs([ids[k]], { width: val });
55
+ });
56
+ });
57
+ };
58
+ const up = () => { handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up); store.breakMerge(); };
59
+ handle.addEventListener("pointermove", move);
60
+ handle.addEventListener("pointerup", up);
61
+ };
62
+ return (
63
+ <span ref={ref} className="ecx-col-handles" contentEditable={false} aria-hidden="true">
64
+ {gaps.map((g, i) => (
65
+ <span key={i} className="ecx-col-handle" style={{ left: g.left, top: g.top, height: g.height }} title={labels.resize}
66
+ data-ecx-col-handle={i} onPointerDown={(e) => start(i, e)} onMouseDown={(e) => e.stopPropagation()} />
67
+ ))}
68
+ </span>
69
+ );
70
+ }
71
+
72
+ /** Tay nắm góc phải dưới của ảnh: kéo đổi bề rộng (giữ tỉ lệ), không vượt khung. */
73
+ export function ImageHandle({ blockId }: { blockId: string }) {
74
+ const { store, labels } = useEditor();
75
+ const ref = useRef<HTMLSpanElement>(null);
76
+ const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
77
+ // Đặt đúng góc của ảnh (ảnh có thể hẹp hơn khung figure), đo lại khi ảnh tải xong / đổi cỡ
78
+ useLayoutEffect(() => {
79
+ const img = ref.current?.parentElement?.querySelector("img");
80
+ if (!img) return;
81
+ const measure = () => setPos((p) => {
82
+ const next = { left: img.offsetLeft + img.offsetWidth, top: img.offsetTop + img.offsetHeight };
83
+ return p && p.left === next.left && p.top === next.top ? p : next;
84
+ });
85
+ measure();
86
+ const ro = new ResizeObserver(measure);
87
+ ro.observe(img);
88
+ img.addEventListener("load", measure);
89
+ return () => { ro.disconnect(); img.removeEventListener("load", measure); };
90
+ }, []);
91
+ const start = (e: React.PointerEvent) => {
92
+ e.preventDefault();
93
+ e.stopPropagation();
94
+ const handle = e.currentTarget as HTMLElement;
95
+ const img = handle.parentElement?.querySelector("img");
96
+ if (!img) return;
97
+ const r = img.getBoundingClientRect();
98
+ const max = handle.parentElement!.parentElement?.getBoundingClientRect().width ?? Infinity;
99
+ const ratio = img.naturalWidth && img.naturalHeight ? img.naturalHeight / img.naturalWidth : r.height / r.width;
100
+ handle.setPointerCapture(e.pointerId);
101
+ const move = (ev: PointerEvent) => {
102
+ const w = Math.round(Math.min(max, Math.max(48, ev.clientX - r.left)));
103
+ store.setAttrs([blockId], { width: w, height: Math.round(w * ratio) || undefined });
104
+ };
105
+ const up = () => { handle.removeEventListener("pointermove", move); handle.removeEventListener("pointerup", up); store.breakMerge(); };
106
+ handle.addEventListener("pointermove", move);
107
+ handle.addEventListener("pointerup", up);
108
+ };
109
+ 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
+ onPointerDown={start} onMouseDown={(e) => e.stopPropagation()} />;
111
+ }
@@ -0,0 +1,149 @@
1
+ import { Code, Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, List, ListChecks, ListOrdered, Pilcrow, Quote, SquareCode, TextQuote, Type } from "lucide-react";
2
+ import type { CSSProperties } from "react";
3
+ import { InnerBlocks } from "../canvas/block-list";
4
+ import { inlineText, makeBlock, type BNode } from "../core/model";
5
+ import { flatten } from "../core/ops";
6
+ import type { BlockEditProps, BlockTransform, BlockType } from "../core/registry";
7
+ import { RichText } from "../text/rich-text";
8
+ import { BoundText, useBindingPreview } from "../ui/bindings";
9
+
10
+ const align = (a: Record<string, unknown>): CSSProperties | undefined => (typeof a.textAlign === "string" ? { textAlign: a.textAlign as CSSProperties["textAlign"] } : undefined);
11
+ const HEADING_ICONS = [Heading1, Heading1, Heading2, Heading3, Heading4, Heading5, Heading6];
12
+
13
+ function ParagraphEdit({ block, blockProps, editable, labels }: BlockEditProps) {
14
+ const bound = useBindingPreview(block, "content");
15
+ if (bound.bound) return <BoundText tagName="p" preview={bound} blockProps={blockProps} style={align(block.attrs)} />;
16
+ return <RichText blockId={block.id} value={block.inline} tagName="p" blockProps={blockProps} style={align(block.attrs)} placeholder={labels.typeSlash} editable={editable} />;
17
+ }
18
+
19
+ function HeadingEdit({ block, blockProps, editable, labels }: BlockEditProps) {
20
+ const level = Math.min(6, Math.max(1, Number(block.attrs.level) || 2));
21
+ const bound = useBindingPreview(block, "content");
22
+ if (bound.bound) return <BoundText tagName={`h${level}`} preview={bound} blockProps={blockProps} style={align(block.attrs)} />;
23
+ return <RichText blockId={block.id} value={block.inline} tagName={`h${level}`} blockProps={blockProps} style={align(block.attrs)} placeholder={labels.heading} placeholderAlways editable={editable} />;
24
+ }
25
+
26
+ function CodeEdit({ block, blockProps, editable, labels }: BlockEditProps) {
27
+ const lang = typeof block.attrs.language === "string" ? block.attrs.language : undefined;
28
+ return (
29
+ <pre {...blockProps}>
30
+ <RichText blockId={block.id} value={block.inline} tagName="code" className={lang ? `language-${lang}` : undefined} multiline plain placeholder={labels.codeBlock} placeholderAlways editable={editable} />
31
+ </pre>
32
+ );
33
+ }
34
+
35
+ function PreformattedEdit({ block, blockProps, editable, labels }: BlockEditProps) {
36
+ return <RichText blockId={block.id} value={block.inline} tagName="pre" className="ecx-pre" blockProps={blockProps} breakOnEnter placeholder={labels.preformatted} placeholderAlways editable={editable} />;
37
+ }
38
+
39
+ function PullquoteEdit({ block, blockProps, editable, labels, setAttrs }: BlockEditProps) {
40
+ return (
41
+ <figure {...blockProps} className={`${blockProps.className} ecx-pullquote`}>
42
+ <blockquote><RichText blockId={block.id} value={block.inline} tagName="p" placeholder={labels.pullquote} placeholderAlways editable={editable} /></blockquote>
43
+ <RichText blockId={block.id} field="citation" tagName="figcaption" value={String(block.attrs.citation ?? "")} onChange={(v) => setAttrs({ citation: v })} placeholder={labels.caption} editable={editable} />
44
+ </figure>
45
+ );
46
+ }
47
+
48
+ function ListEdit({ block, blockProps }: BlockEditProps) {
49
+ const Tag = block.type === "orderedList" ? "ol" : "ul";
50
+ const start = Number(block.attrs.start);
51
+ return (
52
+ <Tag {...(blockProps as object)} className={`${blockProps.className}${block.type === "taskList" ? " ecx-task-list task-list" : ""}`} start={Tag === "ol" && start > 1 ? start : undefined}>
53
+ <InnerBlocks parent={block} appender="none" />
54
+ </Tag>
55
+ );
56
+ }
57
+
58
+ function ListItemEdit({ block, blockProps }: BlockEditProps) {
59
+ return <li {...(blockProps as object)}><InnerBlocks parent={block} appender="none" /></li>;
60
+ }
61
+
62
+ function TaskItemEdit({ block, blockProps, setAttrs, editable }: BlockEditProps) {
63
+ return (
64
+ <li {...(blockProps as object)} className={`${blockProps.className} ecx-task-item task-item`}>
65
+ <input type="checkbox" checked={!!block.attrs.checked} disabled={!editable} onChange={(e) => setAttrs({ checked: e.target.checked || undefined })} contentEditable={false} />{" "}
66
+ <InnerBlocks parent={block} appender="none" />
67
+ </li>
68
+ );
69
+ }
70
+
71
+ function QuoteEdit({ block, blockProps }: BlockEditProps) {
72
+ return <blockquote {...blockProps}><InnerBlocks parent={block} /></blockquote>;
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Đổi loại khối
77
+ // ---------------------------------------------------------------------------
78
+ /** Gom chữ của các khối (đoạn, tiêu đề, mục danh sách) — đổi loại giữ chữ. */
79
+ const textsOf = (blocks: BNode[]) => blocks.flatMap((b) => flatten([b]).filter((x) => x.inline)).map((x) => x.inline!);
80
+ const toTextBlocks = (type: string, attrs: Record<string, unknown> = {}): BlockTransform["convert"] => (blocks) => textsOf(blocks).map((inline) => makeBlock(type, attrs, inline));
81
+ const toList = (type: "bulletList" | "orderedList"): BlockTransform["convert"] => (blocks) => [makeBlock(type, {}, textsOf(blocks).map((inline) => makeBlock("listItem", {}, [makeBlock("paragraph", {}, inline)])))];
82
+ const toQuote: BlockTransform["convert"] = (blocks) => [makeBlock("blockquote", {}, textsOf(blocks).map((inline) => makeBlock("paragraph", {}, inline)))];
83
+ const toCode: BlockTransform["convert"] = (blocks) => [makeBlock("codeBlock", {}, textsOf(blocks).map((i) => inlineText(i)).join("\n"))];
84
+
85
+ const textTransforms = (except: string): BlockTransform[] => [
86
+ { to: "paragraph", convert: toTextBlocks("paragraph"), multiple: true },
87
+ ...[1, 2, 3, 4].map((level) => ({ to: "heading", title: `H${level}`, convert: toTextBlocks("heading", { level }), multiple: true })),
88
+ { to: "bulletList", convert: toList("bulletList"), multiple: true },
89
+ { to: "orderedList", convert: toList("orderedList"), multiple: true },
90
+ { to: "blockquote", convert: toQuote, multiple: true },
91
+ { to: "codeBlock", convert: toCode, multiple: true },
92
+ { to: "preformatted", convert: toTextBlocks("preformatted") },
93
+ ].filter((t) => t.to !== except || t.to === "heading");
94
+
95
+ export function textBlocks(): BlockType[] {
96
+ return [
97
+ {
98
+ name: "paragraph", title: "Đoạn văn", icon: Pilcrow, category: "text", keywords: "doan van text paragraph p", kind: "text", edit: ParagraphEdit,
99
+ attributes: { textAlign: { type: "string", enum: ["left", "center", "right", "justify"] } },
100
+ supports: { style: true, anchor: true, className: true }, transforms: textTransforms("paragraph"),
101
+ },
102
+ {
103
+ name: "heading", title: "Tiêu đề", icon: Heading2, category: "text", keywords: "tieu de heading h1 h2 h3 h4", kind: "text", edit: HeadingEdit,
104
+ attributes: { level: { type: "integer", default: 2, min: 1, max: 6 }, textAlign: { type: "string", enum: ["left", "center", "right", "justify"] } },
105
+ create: (attrs) => makeBlock("heading", { level: 2, ...attrs }),
106
+ variations: [1, 2, 3, 4, 5, 6].map((level) => ({ name: `h${level}`, title: `H${level}`, icon: HEADING_ICONS[level], keywords: `h${level}`, attrs: { level }, isActive: (a) => Number(a.level) === level })),
107
+ supports: { style: true, anchor: true, className: true }, transforms: textTransforms("heading"),
108
+ summary: (a) => `H${a.level ?? 2}`,
109
+ },
110
+ {
111
+ name: "bulletList", title: "Danh sách", icon: List, category: "text", keywords: "danh sach list bullet ul", kind: "container", edit: ListEdit,
112
+ create: () => makeBlock("bulletList", {}, [makeBlock("listItem", {}, [makeBlock("paragraph")])]),
113
+ supports: { style: true, anchor: true, className: true }, transforms: textTransforms("bulletList"),
114
+ },
115
+ {
116
+ name: "orderedList", title: "Danh sách số", icon: ListOrdered, category: "text", keywords: "danh sach so ordered number ol", kind: "container", edit: ListEdit,
117
+ attributes: { start: { type: "integer", default: 1, min: 1 } },
118
+ create: () => makeBlock("orderedList", {}, [makeBlock("listItem", {}, [makeBlock("paragraph")])]),
119
+ supports: { style: true, anchor: true, className: true }, transforms: textTransforms("orderedList"),
120
+ },
121
+ { name: "listItem", title: "Mục danh sách", icon: List, kind: "container", edit: ListItemEdit, hidden: true },
122
+ {
123
+ name: "taskList", title: "Danh sách việc", icon: ListChecks, category: "text", keywords: "viec can lam todo task checklist", kind: "container", edit: ListEdit,
124
+ create: () => makeBlock("taskList", {}, [makeBlock("taskItem", { checked: false }, [makeBlock("paragraph")])]),
125
+ },
126
+ { name: "taskItem", title: "Việc", icon: ListChecks, kind: "container", edit: TaskItemEdit, hidden: true, attributes: { checked: { type: "boolean", default: false } } },
127
+ {
128
+ name: "blockquote", title: "Trích dẫn", icon: Quote, category: "text", keywords: "trich dan quote blockquote", kind: "container", edit: QuoteEdit,
129
+ create: () => makeBlock("blockquote", {}, [makeBlock("paragraph")]),
130
+ supports: { style: true, anchor: true, className: true, blockStyle: true },
131
+ transforms: [{ to: "paragraph", convert: toTextBlocks("paragraph"), multiple: true }, { to: "pullquote", convert: (b) => [makeBlock("pullquote", {}, textsOf(b)[0] ?? [])] }],
132
+ },
133
+ {
134
+ name: "codeBlock", title: "Mã nguồn", icon: SquareCode, category: "text", keywords: "ma code nguon", kind: "text", edit: CodeEdit, multiline: true, plain: true,
135
+ attributes: { language: { type: "string", label: "Ngôn ngữ" } },
136
+ transforms: [{ to: "paragraph", convert: (b) => textsOf(b).map((i) => makeBlock("paragraph", {}, inlineText(i))) }, { to: "preformatted", convert: toTextBlocks("preformatted") }],
137
+ },
138
+ {
139
+ name: "preformatted", title: "Định dạng sẵn", icon: Code, category: "text", keywords: "dinh dang san preformatted pre khoang trang", kind: "text", edit: PreformattedEdit,
140
+ supports: { style: true, anchor: true, className: true }, transforms: textTransforms("preformatted"),
141
+ },
142
+ {
143
+ name: "pullquote", title: "Trích dẫn nổi bật", icon: TextQuote, category: "text", keywords: "trich dan noi bat pullquote", kind: "text", edit: PullquoteEdit,
144
+ attributes: { citation: { type: "string" } }, supports: { style: true, anchor: true, className: true },
145
+ transforms: [{ to: "blockquote", convert: toQuote }, { to: "paragraph", convert: toTextBlocks("paragraph") }],
146
+ },
147
+ ];
148
+ }
149
+ export const TextIcon = Type;