@ecomcx/ecomweb-editor 1.18.0 → 1.20.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 +150 -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 +324 -0
  58. package/src/v2/editor.tsx +288 -0
  59. package/src/v2/index.ts +28 -0
  60. package/src/v2/labels.ts +349 -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 +129 -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 +402 -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
@@ -1,7 +1,7 @@
1
1
  import { Mark, Node } from "@tiptap/core";
2
2
  import { NodeViewWrapper, ReactNodeViewRenderer, type ReactNodeViewProps } from "@tiptap/react";
3
3
  import { labelsOf } from "./nodes";
4
- import { cx } from "./util";
4
+ import { cx } from "../shared/util";
5
5
 
6
6
  /**
7
7
  * Khối / định dạng mà trình soạn không hiểu (plugin đã tắt hoặc chưa cài): giữ NGUYÊN dữ liệu gốc trong thuộc tính `raw`,
@@ -0,0 +1,38 @@
1
+ import type { BlockDefinition } from "@ecomcx/ecomweb-content";
2
+ import type { LucideIcon } from "lucide-react";
3
+ import type { ComponentType, ReactNode } from "react";
4
+
5
+ /**
6
+ * Kho khối của plugin (defineBlock + registerBlock) — không phụ thuộc trình soạn nào: bản TipTap (1.x) và bản cây khối (v2)
7
+ * cùng đọc. Panel plugin (registerBlockPanel) cũng nằm ở đây.
8
+ */
9
+ export interface BlockEditProps {
10
+ attrs: Record<string, any>;
11
+ setAttrs(attrs: Record<string, unknown>): void;
12
+ selected: boolean;
13
+ /** Nội dung bên trong (khối có content "inline"/"blocks") — đặt vào chỗ muốn người dùng gõ. */
14
+ children?: ReactNode;
15
+ }
16
+
17
+ export interface RegisterBlockOptions {
18
+ /** Biểu tượng trong slash menu và khung khối. */
19
+ icon?: LucideIcon;
20
+ /** Xem trước tuỳ chỉnh trong trình soạn; không có → khung chung + form cài đặt sinh từ attributes. */
21
+ edit?: ComponentType<BlockEditProps>;
22
+ /** Dịch nhãn ("%khoá%" → chữ theo ngôn ngữ admin) — admin truyền vào. */
23
+ translate?(text: string): string;
24
+ /** Khối chứa khối khác: nội dung có sẵn khi chèn (mặc định một đoạn văn trống). */
25
+ initialContent?(): Array<Record<string, unknown>>;
26
+ }
27
+
28
+ const blocks = new Map<string, BlockDefinition>();
29
+ const options = new Map<string, RegisterBlockOptions>();
30
+ const listeners = new Set<() => void>();
31
+
32
+ export function storeBlockDefinition(def: BlockDefinition, opts: RegisterBlockOptions) { blocks.set(def.name, def); options.set(def.name, opts); listeners.forEach((l) => l()); }
33
+ export function dropBlockDefinition(name: string) { if (blocks.delete(name)) { options.delete(name); listeners.forEach((l) => l()); } }
34
+ export const blockDefinition = (name: string) => blocks.get(name);
35
+ export const blockOptions = (name: string): RegisterBlockOptions => options.get(name) ?? {};
36
+ /** Khối đang đăng ký (để chuẩn hoá + nâng phiên bản khi mở bài). */
37
+ export const registeredBlocks = (): BlockDefinition[] => [...blocks.values()];
38
+ export function onBlockDefinitionsChange(l: () => void) { listeners.add(l); return () => { listeners.delete(l); }; }
@@ -0,0 +1,19 @@
1
+ import type { CSSProperties } from "react";
2
+
3
+ /** Ô "chưa chọn màu": nền trắng gạch chéo đỏ (không phải màu đen của ô chọn màu trình duyệt). */
4
+ const EMPTY: CSSProperties = { background: "linear-gradient(to top right, transparent calc(50% - 1px), #d92d20 calc(50% - 1px), #d92d20 calc(50% + 1px), transparent calc(50% + 1px)), #fff" };
5
+
6
+ /**
7
+ * Ô màu tự chọn: hiện đúng màu đang đặt, chưa đặt thì hiện ô gạch chéo; bấm mở bảng chọn màu của trình duyệt.
8
+ * (`<input type=color>` không có trạng thái "trống" — luôn hiện đen #000000 làm người dùng tưởng đã đặt màu đen.)
9
+ */
10
+ export function ColorSwatchInput({ value, onChange, label, className, size = 26 }: { value?: string; onChange(hex: string): void; label: string; className?: string; size?: number }) {
11
+ const hex = value && /^#[0-9a-f]{6}$/i.test(value) ? value : undefined;
12
+ return (
13
+ <label className={className} title={hex ?? label} data-empty={hex ? undefined : ""}
14
+ style={{ position: "relative", display: "inline-block", width: size, height: size, flex: "none", borderRadius: 6, border: "1px solid rgb(0 0 0 / .18)", cursor: "pointer", overflow: "hidden", ...(hex ? { background: hex } : EMPTY) }}>
15
+ <input type="color" aria-label={label} value={hex ?? "#ffffff"} onChange={(e) => onChange(e.target.value)}
16
+ style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer", border: 0, padding: 0 }} />
17
+ </label>
18
+ );
19
+ }
@@ -1,6 +1,5 @@
1
- import { Extension } from "@tiptap/core";
1
+ /** Kho panel plugin (registerBlockPanel) — không phụ thuộc trình soạn: bản 1.x và v2 cùng đọc. */
2
2
  import type { ComponentType } from "react";
3
- import { registerEditorExtension, unregisterEditorExtension } from "./registry";
4
3
 
5
4
  /** Props của panel plugin trong tab "Khối". */
6
5
  export interface BlockPanelProps {
@@ -29,29 +28,13 @@ export interface BlockPanel {
29
28
  component: ComponentType<BlockPanelProps>;
30
29
  }
31
30
 
31
+
32
32
  const panels = new Map<string, BlockPanel>();
33
33
  const listeners = new Set<() => void>();
34
34
  let snapshot: BlockPanel[] = [];
35
35
  const changed = () => { snapshot = [...panels.values()].sort((a, b) => (a.order ?? 10) - (b.order ?? 10)); listeners.forEach((l) => l()); };
36
-
37
- /** Thêm panel vào tab "Khối" (BlockInspector) cho một số loại khối hoặc mọi khối. */
38
- export function registerBlockPanel(panel: BlockPanel) {
39
- panels.set(panel.id, panel);
40
- if (panel.attributes && panel.blocks?.length) {
41
- const attrs = Object.fromEntries(Object.entries(panel.attributes).map(([k, spec]) => [k, { default: spec.default ?? null, renderHTML: () => ({}), parseHTML: () => spec.default ?? null }]));
42
- registerEditorExtension({
43
- name: `panel:${panel.id}`,
44
- extensions: [Extension.create({ name: `cmsPanel_${panel.id.replace(/[^\w]/g, "_")}`, addGlobalAttributes: () => [{ types: panel.blocks!, attributes: attrs }] })],
45
- });
46
- }
47
- changed();
48
- }
49
-
50
- export function unregisterBlockPanel(id: string) {
51
- if (!panels.delete(id)) return;
52
- unregisterEditorExtension(`panel:${id}`);
53
- changed();
54
- }
36
+ export function storePanel(panel: BlockPanel) { panels.set(panel.id, panel); changed(); }
37
+ export function dropPanel(id: string) { const had = panels.delete(id); if (had) changed(); return had; }
55
38
 
56
39
  /** Panel áp dụng cho một loại khối. */
57
40
  export const blockPanelsFor = (type: string) => snapshot.filter((p) => !p.blocks || p.blocks.includes(type));
@@ -1,4 +1,3 @@
1
- import type { Editor as TiptapEditor } from "@tiptap/core";
2
1
  import { normalizeContent } from "@ecomcx/ecomweb-content";
3
2
 
4
3
  /**
@@ -39,17 +38,6 @@ export function patternNodes(p: Pattern): Array<Record<string, unknown>> {
39
38
  return ((main?.data as { content?: Array<Record<string, unknown>> } | undefined)?.content ?? []);
40
39
  }
41
40
 
42
- /** Chèn mẫu dưới khối đang chọn (dòng trống đang có con trỏ → thay dòng đó). */
43
- export function insertPattern(editor: TiptapEditor, p: Pattern) {
44
- const nodes = p.synced && p.ref ? [{ type: "syncedPattern", attrs: { ref: p.ref } }] : patternNodes(p);
45
- if (!nodes.length) return false;
46
- const { $from, empty } = editor.state.selection;
47
- if (empty && $from.depth > 0 && $from.parent.type.name === "paragraph" && $from.parent.content.size === 0)
48
- return editor.chain().focus().insertContentAt({ from: $from.before(), to: $from.after() }, nodes).run();
49
- const after = $from.depth > 0 ? $from.after(1) : editor.state.doc.content.size;
50
- return editor.chain().focus().insertContentAt(after, nodes).run();
51
- }
52
-
53
41
  // ---------------------------------------------------------------------------
54
42
  // Mẫu có sẵn của lõi (dựng bằng bộ khối cơ bản — mọi theme hiển thị được)
55
43
  // ---------------------------------------------------------------------------
@@ -3,6 +3,7 @@ import { Link2, Link2Off, Monitor, MoreVertical, Smartphone, Tablet } from "luci
3
3
  import { useEffect, useId, useRef, useState, type ReactNode } from "react";
4
4
  import type { EditorLabels } from "./labels";
5
5
  import { cx } from "./util";
6
+ import { ColorSwatchInput } from "./color-swatch";
6
7
 
7
8
  type Style = BlockStyle & Record<string, any>;
8
9
  type Section = "typography" | "color" | "spacing" | "border" | "visibility";
@@ -56,14 +57,13 @@ function Seg<T extends string>({ value, options, onChange, label }: { value: T |
56
57
 
57
58
  /** Ô màu: preset của theme (ô vuông) + bảng chọn màu + bỏ màu. */
58
59
  function ColorField({ value, onChange, label, t, colors = COLORS }: { value?: string; onChange(v: string | undefined): void; label: string; t: EditorLabels; colors?: string[] }) {
59
- const hex = value && /^#[0-9a-f]{6}$/i.test(value) ? value : "#000000";
60
60
  return (
61
61
  <div className="cms-ed-color" role="group" aria-label={label}>
62
62
  {colors.map((c) => (
63
63
  <button key={c} type="button" title={c} aria-label={`${label}: ${c}`} aria-pressed={value === c} className={cx("cms-ed-swatch", value === c && "is-active")}
64
64
  style={{ background: `var(--ecx-color-${c})` }} onClick={() => onChange(value === c ? undefined : c)} />
65
65
  ))}
66
- <input type="color" value={hex} aria-label={`${label}: ${t.customColor}`} onChange={(e) => onChange(e.target.value)} />
66
+ <ColorSwatchInput value={value} onChange={onChange} label={`${label}: ${t.customColor}`} size={22} />
67
67
  {value && <button type="button" className="cms-ed-text-btn" onClick={() => onChange(undefined)}>{t.noColor}</button>}
68
68
  </div>
69
69
  );
@@ -31,6 +31,8 @@ export interface MediaProvider {
31
31
  pick(options: { kind: MediaKind; multiple: boolean }): Promise<MediaItem[]>;
32
32
  /** Lấy lại thông tin một file (để đổi cỡ ảnh đã chèn). */
33
33
  get?(id: MediaItem["id"]): Promise<MediaItem | null>;
34
+ /** Tải tệp lên thư viện media (nút "Tải lên", kéo thả tệp vào khối). Không có → chỉ chọn từ thư viện / URL. */
35
+ upload?(files: File[]): Promise<MediaItem[]>;
34
36
  }
35
37
 
36
38
  /** Một lệnh chèn trong slash menu ("/"). */
@@ -0,0 +1,51 @@
1
+ import { Blocks } from "lucide-react";
2
+ import type { ComponentType } from "react";
3
+ import { blockOptions, onBlockDefinitionsChange, registeredBlocks, type BlockEditProps as V1EditProps } from "../../shared/block-defs";
4
+ import { InnerBlocks } from "../canvas/block-list";
5
+ import { fromRich, makeBlock } from "../core/model";
6
+ import type { BlockEditProps, BlockTypeRegistry } from "../core/registry";
7
+ import { RichText } from "../text/rich-text";
8
+
9
+ const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
10
+
11
+ /** Phần xem trước của khối plugin viết cho bản 1.x (attrs, setAttrs, selected, children) chạy trong v2. */
12
+ function wrapV1Edit(Edit: ComponentType<V1EditProps>): ComponentType<BlockEditProps> {
13
+ return function PluginEdit({ block, attrs, setAttrs, blockProps, selected, editable }: BlockEditProps) {
14
+ const children = block.content
15
+ ? <InnerBlocks parent={block} />
16
+ : block.inline ? <RichText blockId={block.id} value={block.inline} tagName="div" editable={editable} /> : undefined;
17
+ return <div {...blockProps} className={cx(blockProps.className, "ecx-plugin-block")}><Edit attrs={attrs} setAttrs={setAttrs} selected={selected}>{children}</Edit></div>;
18
+ };
19
+ }
20
+
21
+ /**
22
+ * Khối plugin đăng ký bằng registerBlock(defineBlock(...)) → khối v2 (form cài đặt tự sinh, xem trước của plugin nếu có).
23
+ * Plugin cài sau khi mở trình soạn vẫn hiện (theo dõi thay đổi). Trả về hàm huỷ theo dõi.
24
+ */
25
+ export function syncPluginBlocks(registry: BlockTypeRegistry): () => void {
26
+ // Chỉ thêm / cập nhật khối do chính đồng bộ này tạo: khối lõi của v2 (cùng tên với khối 1.x như templatePart, cover) giữ nguyên
27
+ const synced = new Set<string>();
28
+ const sync = () => {
29
+ for (const def of registeredBlocks()) {
30
+ if (registry.get(def.name) && !synced.has(def.name)) continue;
31
+ synced.add(def.name);
32
+ const o = blockOptions(def.name);
33
+ const t = o.translate ?? ((s: string) => s);
34
+ registry.registerDefinition(def, {
35
+ title: t(def.title),
36
+ description: def.description ? t(def.description) : undefined,
37
+ icon: o.icon ?? Blocks,
38
+ edit: o.edit ? wrapV1Edit(o.edit) : undefined,
39
+ create: (attrs) => {
40
+ const defaults = Object.fromEntries(Object.entries(def.attributes).filter(([, s]) => s.default !== undefined).map(([k, s]) => [k, s.default]));
41
+ const content = def.content === "blocks" ? (o.initialContent?.() ?? [{ type: "paragraph" }]).map((n) => fromRich(n as never)) : undefined;
42
+ return makeBlock(def.name, { ...defaults, ...attrs }, content);
43
+ },
44
+ });
45
+ }
46
+ };
47
+ sync();
48
+ return onBlockDefinitionsChange(sync);
49
+ }
50
+
51
+ export { registeredPatterns, onPatternsChange, type Pattern } from "../../shared/patterns";
@@ -0,0 +1,42 @@
1
+ import type { V2Labels } from "../labels";
2
+ import type { BlockType, BlockTypeRegistry } from "../core/registry";
3
+ import { layoutBlocks } from "./layout";
4
+ import { mediaBlocks } from "./media";
5
+ import { textBlocks } from "./text";
6
+ import { themeBlocks } from "./theme";
7
+
8
+ /** Tên khối theo ngôn ngữ giao diện (khối có nhãn trong bộ chữ). */
9
+ const TITLE_KEYS: Partial<Record<string, keyof V2Labels>> = {
10
+ paragraph: "paragraph", heading: "heading", bulletList: "list", orderedList: "orderedList", blockquote: "quote", codeBlock: "codeBlock",
11
+ preformatted: "preformatted", horizontalRule: "separator", image: "image", group: "groupBlock", columns: "columns", column: "column", buttons: "buttons",
12
+ button: "button", spacer: "spacer", callout: "callout", details: "details", table: "table", templatePart: "templatePart", syncedPattern: "syncedPattern",
13
+ pullquote: "pullquote", cover: "cover", customHtml: "html", embed: "embed",
14
+ };
15
+
16
+ const EN_TITLES: Record<string, string> = {
17
+ taskList: "To-do list", taskItem: "To-do", listItem: "List item", mediaText: "Media & text", tableRow: "Row", tableCell: "Cell", tableHeader: "Header cell",
18
+ gallery: "Gallery", video: "Video", audio: "Audio", file: "File", youtube: "YouTube", socialLinks: "Social links", tableOfContents: "Table of contents",
19
+ siteTitle: "Site title", siteLogo: "Site logo", siteTagline: "Tagline", navigation: "Navigation", search: "Search", languageSwitcher: "Language switcher",
20
+ copyright: "Copyright", postTitle: "Post title", postContent: "Post content", postExcerpt: "Excerpt", featuredImage: "Featured image", postDate: "Date",
21
+ postAuthor: "Author", postTerms: "Terms", comments: "Comments", query: "Query loop", postTemplate: "Post template", pagination: "Pagination", queryEmpty: "No results",
22
+ };
23
+
24
+ export function coreBlockTypes(labels: V2Labels): BlockType[] {
25
+ return [...textBlocks(), ...layoutBlocks(), ...mediaBlocks(), ...themeBlocks()].map((t) => {
26
+ const key = TITLE_KEYS[t.name];
27
+ const title = key ? String(labels[key]) : labels.lang === "en" ? EN_TITLES[t.name] ?? t.title : t.title;
28
+ // Biến thể đứng riêng (Hàng ngang / Xếp dọc / Lưới) theo ngôn ngữ
29
+ const VAR_EN: Record<string, string> = { "group/row": "Row", "group/stack": "Stack", "group/grid": "Grid" };
30
+ const variations = labels.lang === "en" && t.variations ? t.variations.map((v) => (VAR_EN[`${t.name}/${v.name}`] ? { ...v, title: VAR_EN[`${t.name}/${v.name}`] } : v)) : t.variations;
31
+ return { ...t, title, variations };
32
+ });
33
+ }
34
+
35
+ /** Đăng ký bộ khối lõi (ứng dụng có thể bỏ bớt khối không dùng bằng registry.unregister). */
36
+ export function registerCoreBlocks(registry: BlockTypeRegistry, labels: V2Labels, opts: { dynamic?: boolean } = {}) {
37
+ const dynamicNames = new Set(themeBlocks().map((t) => t.name));
38
+ for (const t of coreBlockTypes(labels)) {
39
+ // Khối giao diện chỉ hiện trong trình chèn khi soạn template / trang dựng bằng khối (vẫn vẽ được nếu nội dung có sẵn)
40
+ registry.register(dynamicNames.has(t.name) && !opts.dynamic ? { ...t, hidden: true } : t);
41
+ }
42
+ }
@@ -0,0 +1,281 @@
1
+ import { colorCss, spacingValue } from "@ecomcx/ecomweb-content";
2
+ import { ChevronsUpDown, Columns2, Columns3, Columns4, Info, LayoutPanelLeft, Minus, MousePointerClick, PanelTop, RectangleHorizontal, Square, Table2, Image as ImageIcon } from "lucide-react";
3
+ import type { CSSProperties } from "react";
4
+ import { InnerBlocks } from "../canvas/block-list";
5
+ import { makeBlock } from "../core/model";
6
+ import type { BlockEditProps, BlockType } from "../core/registry";
7
+ import { RichText } from "../text/rich-text";
8
+ import { BoundText, useBindingPreview } from "../ui/bindings";
9
+ import { useEditor } from "../context";
10
+ import { ButtonsTools, ColumnsTools, TableTools, addColumnTo } from "./tools";
11
+ import { ColumnHandles, useActiveWithin } from "./resize";
12
+ import { layoutFor, layoutKind } from "../ui/layout-panel";
13
+ import { normalizeStyle, type BlockStyle } from "@ecomcx/ecomweb-content";
14
+ import { ToolButton } from "../ui/toolbar";
15
+ import { MediaActions, useFileDrop } from "./media-actions";
16
+ import type { MediaItem } from "../../shared/types";
17
+ import { LayoutGrid, Rows3, Columns3 as RowIcon } from "lucide-react";
18
+
19
+ const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
20
+ const PADDING: Record<string, string> = { none: "0", small: "0.75rem", medium: "1.5rem", large: "3rem" };
21
+ const TONES: Record<string, string> = { info: "#2563eb", success: "#16a34a", warning: "#d97706", danger: "#dc2626" };
22
+ const merge = (bp: BlockEditProps["blockProps"], className: string, style?: CSSProperties) => ({ ...bp, className: cx(bp.className, className), style: { ...(bp.style ?? {}), ...style } });
23
+
24
+ function GroupEdit({ block, blockProps }: BlockEditProps) {
25
+ const a = block.attrs;
26
+ const bg = colorCss(a.background), fg = colorCss(a.textColor);
27
+ const pad = PADDING[a.padding as string] ?? (bg ? PADDING.medium : undefined);
28
+ return (
29
+ <div {...merge(blockProps, cx("ecx-group cms-group", a.padding && `ecx-group-${a.padding} cms-group-${a.padding}`), { background: bg, color: fg, padding: pad, borderRadius: bg ? 12 : undefined })}>
30
+ <InnerBlocks parent={block} />
31
+ </div>
32
+ );
33
+ }
34
+
35
+ /** Thanh công cụ của nhóm: đổi nhanh Nhóm / Hàng ngang / Xếp dọc / Lưới (giữ các kiểu dáng khác). */
36
+ function GroupLayoutTools({ attrs, setAttrs, labels }: BlockEditProps) {
37
+ const style: BlockStyle = normalizeStyle(attrs.style) ?? {};
38
+ const kind = layoutKind(style.layout);
39
+ const vi = labels.lang === "vi";
40
+ const items: Array<["flow" | "row" | "stack" | "grid", typeof Square, string]> = [["flow", Square, vi ? "Nhóm" : "Group"], ["row", RowIcon, vi ? "Hàng ngang" : "Row"], ["stack", Rows3, vi ? "Xếp dọc" : "Stack"], ["grid", LayoutGrid, vi ? "Lưới" : "Grid"]];
41
+ return (
42
+ <>
43
+ {items.map(([k, I, label]) => (
44
+ <ToolButton key={k} label={label} active={kind === k} onClick={() => setAttrs({ style: normalizeStyle({ ...style, layout: layoutFor(k, style.layout) }) })}><I className="ecx-icon" /></ToolButton>
45
+ ))}
46
+ </>
47
+ );
48
+ }
49
+ const groupWith = (layout?: BlockStyle["layout"], kids = 1) => makeBlock("group", layout ? { style: { layout } } : {}, Array.from({ length: kids }, () => makeBlock("paragraph")));
50
+
51
+ function ColumnsEdit({ block, blockProps, editable, labels }: BlockEditProps) {
52
+ const { store } = useEditor();
53
+ const a = block.attrs;
54
+ const stack = a.stack !== false;
55
+ const active = useActiveWithin(block.id);
56
+ const alignItems = a.verticalAlign === "center" ? "center" : a.verticalAlign === "bottom" ? "flex-end" : "flex-start";
57
+ return (
58
+ <div {...merge(blockProps, cx("ecx-columns cms-columns", a.verticalAlign && `ecx-columns-${a.verticalAlign}`, stack && "is-stack"), { display: "flex", flexWrap: stack ? "wrap" : "nowrap", gap: "1.5rem", alignItems, position: "relative" })}>
59
+ <InnerBlocks parent={block} appender="none" />
60
+ {active && editable && block.content!.length > 1 && <ColumnHandles block={block} />}
61
+ {active && editable && block.content!.length < 6 && store.canInsertInto(block.id) && (
62
+ <button type="button" className="ecx-add-column" contentEditable={false} title={labels.lang === "vi" ? "Thêm cột" : "Add column"} aria-label={labels.lang === "vi" ? "Thêm cột" : "Add column"}
63
+ onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); }} onClick={() => addColumnTo(store, block)}>+</button>
64
+ )}
65
+ </div>
66
+ );
67
+ }
68
+
69
+ function ColumnEdit({ block, blockProps }: BlockEditProps) {
70
+ const w = Number(block.attrs.width) > 0 ? Number(block.attrs.width) : 1;
71
+ return (
72
+ <div {...merge(blockProps, "ecx-column cms-column", { flex: `${w} 1 0`, minWidth: "min(100%, 14rem)" })}>
73
+ <InnerBlocks parent={block} />
74
+ </div>
75
+ );
76
+ }
77
+
78
+ function ButtonsEdit({ block, blockProps }: BlockEditProps) {
79
+ return <div {...merge(blockProps, cx("ecx-buttons-group", block.attrs.align && `is-${block.attrs.align}`))}><InnerBlocks parent={block} appender="none" /></div>;
80
+ }
81
+
82
+ function ButtonEdit({ block, blockProps, setAttrs, editable, labels }: BlockEditProps) {
83
+ const a = block.attrs;
84
+ const variant = a.variant === "secondary" || a.variant === "outline" ? a.variant : "primary";
85
+ const bound = useBindingPreview(block, "text");
86
+ const look: CSSProperties = variant === "outline"
87
+ ? { border: "1px solid var(--ecx-button-bg, var(--cms-button-bg, var(--primary, currentColor)))", color: "var(--ecx-button-bg, var(--cms-button-bg, var(--primary, inherit)))" }
88
+ : variant === "secondary"
89
+ ? { background: "var(--ecx-button-secondary-bg, var(--cms-button-secondary-bg, rgba(127,127,127,.15)))", color: "inherit" }
90
+ : { background: "var(--ecx-button-bg, var(--cms-button-bg, var(--primary, #18181b)))", color: "var(--ecx-button-fg, var(--cms-button-fg, #fff))" };
91
+ return (
92
+ <span {...merge(blockProps, cx("ecx-button cms-button", `ecx-button-${variant} cms-button-${variant}`), { display: "inline-block", padding: "0.6em 1.2em", borderRadius: 8, fontWeight: 600, lineHeight: 1.2, ...look })}>
93
+ {bound.bound ? <BoundText preview={bound} /> : <RichText blockId={block.id} field="text" tagName="span" value={String(a.text ?? "")} onChange={(v) => setAttrs({ text: v })} placeholder={labels.buttonText} placeholderAlways editable={editable} />}
94
+ </span>
95
+ );
96
+ }
97
+
98
+ function SpacerEdit({ block, blockProps }: BlockEditProps) {
99
+ return <div {...merge(blockProps, "ecx-spacer", { height: spacingValue(block.attrs.height ?? "lg") ?? "1.5rem" })} aria-hidden="true" />;
100
+ }
101
+
102
+ function SeparatorEdit({ blockProps }: BlockEditProps) {
103
+ return <hr {...(blockProps as object)} />;
104
+ }
105
+
106
+ function CalloutEdit({ block, blockProps, setAttrs, editable }: BlockEditProps) {
107
+ const tone = TONES[block.attrs.tone as string] ? (block.attrs.tone as string) : "info";
108
+ return (
109
+ <div {...merge(blockProps, cx("ecx-callout cms-callout", `ecx-callout-${tone} cms-callout-${tone}`), { borderLeft: `4px solid ${TONES[tone]}`, background: `color-mix(in srgb, ${TONES[tone]} 8%, transparent)`, padding: "0.75rem 1rem", borderRadius: 8 })} role="note">
110
+ <RichText blockId={block.id} field="title" tagName="p" className="ecx-callout-title cms-callout-title" style={{ margin: 0, fontWeight: 600 }} value={String(block.attrs.title ?? "")} onChange={(v) => setAttrs({ title: v })} placeholder="…" editable={editable} />
111
+ <InnerBlocks parent={block} />
112
+ </div>
113
+ );
114
+ }
115
+
116
+ function DetailsEdit({ block, blockProps, setAttrs, editable }: BlockEditProps) {
117
+ return (
118
+ <details {...(merge(blockProps, "ecx-details") as object)} open>
119
+ <summary onClick={(e) => e.preventDefault()}>
120
+ <RichText blockId={block.id} field="summary" tagName="span" value={String(block.attrs.summary ?? "")} onChange={(v) => setAttrs({ summary: v })} placeholder="…" placeholderAlways editable={editable} />
121
+ </summary>
122
+ <InnerBlocks parent={block} />
123
+ </details>
124
+ );
125
+ }
126
+
127
+ function CoverEdit({ block, blockProps, setAttrs, labels }: BlockEditProps) {
128
+ const a = block.attrs;
129
+ const src = typeof a.src === "string" ? a.src : "";
130
+ const { host } = useEditor();
131
+ const select = (items: MediaItem[]) => setAttrs({ src: items[0].url, alt: items[0].alt || undefined, mediaId: items[0].id });
132
+ const drop = useFileDrop("image", select);
133
+ // Chưa có ảnh lẫn màu: chỗ chọn ảnh nền hoặc màu nền (không để khối trắng trơn vô hình)
134
+ if (!src && !a.overlay) {
135
+ const vi = labels.lang === "vi";
136
+ return (
137
+ <div {...merge(blockProps, cx("ecx-media-placeholder ecx-cover-placeholder", drop.over && "is-drop-target"))} {...drop.props}>
138
+ <span className="ecx-placeholder-title"><ImageIcon className="ecx-icon" />{vi ? "Ảnh bìa" : "Cover"}</span>
139
+ <p className="ecx-placeholder-hint">{vi ? "Chọn ảnh nền (kéo thả, tải lên, thư viện) hoặc một màu nền:" : "Pick a background image (drop, upload, library) or a colour:"}</p>
140
+ <MediaActions kind="image" onSelect={select} onUrl={(url) => setAttrs({ src: url })} />
141
+ <div className="ecx-chip-row" contentEditable={false} onMouseDown={(e) => e.stopPropagation()}>
142
+ {Object.entries(host.presets?.colors ?? { primary: "#1a597b", black: "#111", muted: "#757575" }).map(([name, c]) => (
143
+ <button key={name} type="button" className="ecx-chip ecx-chip-swatch" title={name} aria-label={`${vi ? "Màu nền" : "Background"}: ${name}`} style={{ background: c }} onClick={() => setAttrs({ overlay: name, opacity: 100 })} />
144
+ ))}
145
+ </div>
146
+ </div>
147
+ );
148
+ }
149
+ const overlay = colorCss(a.overlay) ?? (src ? "#000" : undefined);
150
+ return (
151
+ <div {...merge(blockProps, cx("ecx-cover", a.contentAlign && a.contentAlign !== "center" && `is-${a.contentAlign}`, a.fixed && src && "is-fixed"), { minHeight: spacingValue(a.minHeight ?? "400px") })}>
152
+ {src && <img className="ecx-cover-img" src={src} alt={String(a.alt ?? "")} draggable={false} />}
153
+ {overlay && <span className="ecx-cover-overlay" aria-hidden="true" style={{ background: overlay, opacity: Math.min(100, Math.max(0, Number(a.opacity ?? 50))) / 100 }} />}
154
+ <div className="ecx-cover-inner"><InnerBlocks parent={block} /></div>
155
+ </div>
156
+ );
157
+ }
158
+
159
+ function MediaTextEdit({ block, blockProps }: BlockEditProps) {
160
+ const a = block.attrs;
161
+ const width = Math.min(80, Math.max(20, Number(a.width) || 50));
162
+ return (
163
+ <div {...merge(blockProps, cx("ecx-media-text", a.position === "right" && "is-right", a.verticalAlign && a.verticalAlign !== "center" && `is-${a.verticalAlign}`, a.stack !== false && "is-stack"), { ["--ecx-media-width" as string]: `${width}%` } as CSSProperties)}>
164
+ <figure className="ecx-media-text-media" style={{ margin: 0 }}>{typeof a.src === "string" && a.src ? <img src={a.src} alt={String(a.alt ?? "")} draggable={false} /> : <MediaPick blockId={block.id} />}</figure>
165
+ <div className="ecx-media-text-content"><InnerBlocks parent={block} /></div>
166
+ </div>
167
+ );
168
+ }
169
+
170
+ /** Ô chọn ảnh dùng chung (ảnh bìa, ảnh + chữ). */
171
+ /** Chỗ chọn ảnh trong khối (ảnh + chữ…): tải lên / thư viện / URL, kéo thả tệp. */
172
+ export function MediaPick({ blockId }: { blockId: string }) {
173
+ const { store, labels } = useEditor();
174
+ const select = (items: MediaItem[]) => store.setAttrs([blockId], { src: items[0].url, alt: items[0].alt || undefined, mediaId: items[0].id });
175
+ const drop = useFileDrop("image", select);
176
+ return (
177
+ <div className={cx("ecx-media-placeholder ecx-media-pick", drop.over && "is-drop-target")} {...drop.props}>
178
+ <span className="ecx-placeholder-title"><ImageIcon className="ecx-icon" />{labels.image}</span>
179
+ <MediaActions kind="image" compact onSelect={select} onUrl={(url) => store.setAttrs([blockId], { src: url })} />
180
+ </div>
181
+ );
182
+ }
183
+
184
+ function TableEdit({ block, blockProps }: BlockEditProps) {
185
+ return (
186
+ <div {...merge(blockProps, "ecx-table table-wrap")}>
187
+ <table className={block.attrs.fixed ? "is-fixed" : undefined}><tbody><InnerBlocks parent={block} appender="none" /></tbody></table>
188
+ </div>
189
+ );
190
+ }
191
+ function RowEdit({ block, blockProps }: BlockEditProps) {
192
+ return <tr {...(blockProps as object)}><InnerBlocks parent={block} appender="none" /></tr>;
193
+ }
194
+ function CellEdit({ block, blockProps }: BlockEditProps) {
195
+ const Tag = block.type === "tableHeader" ? "th" : "td";
196
+ const span = (n: unknown) => (Number(n) > 1 ? Number(n) : undefined);
197
+ return <Tag {...(blockProps as object)} colSpan={span(block.attrs.colspan)} rowSpan={span(block.attrs.rowspan)}><InnerBlocks parent={block} appender="none" /></Tag>;
198
+ }
199
+
200
+ const col = (width?: number) => makeBlock("column", width ? { width } : {}, [makeBlock("paragraph")]);
201
+ const columns = (...widths: number[]) => makeBlock("columns", {}, widths.map((w) => col(w)));
202
+ const cell = (header = false) => makeBlock(header ? "tableHeader" : "tableCell", {}, [makeBlock("paragraph")]);
203
+
204
+ export function layoutBlocks(): BlockType[] {
205
+ return [
206
+ {
207
+ name: "group", title: "Nhóm", icon: Square, category: "design", keywords: "nhom group khung section container", kind: "container", edit: GroupEdit,
208
+ attributes: { background: { type: "string", control: "color" }, textColor: { type: "string", control: "color" }, padding: { type: "string", enum: ["none", "small", "medium", "large"], default: "medium" } },
209
+ create: (attrs) => makeBlock("group", attrs ?? {}, [makeBlock("paragraph")]),
210
+ toolbar: GroupLayoutTools,
211
+ variations: [
212
+ { name: "row", title: "Hàng ngang", standalone: true, icon: RowIcon, keywords: "hang ngang row flex xep ngang", create: () => groupWith(layoutFor("row"), 2) },
213
+ { name: "stack", title: "Xếp dọc", standalone: true, icon: Rows3, keywords: "xep doc stack flex cot", create: () => groupWith(layoutFor("stack"), 2) },
214
+ { name: "grid", title: "Lưới", standalone: true, icon: LayoutGrid, keywords: "luoi grid o cot", create: () => groupWith(layoutFor("grid"), 3) },
215
+ ],
216
+ supports: { style: true, anchor: true, className: true, blockStyle: true },
217
+ transforms: [{ to: "columns", convert: (b) => [makeBlock("columns", {}, b.flatMap((g) => g.content ?? []).map((c) => makeBlock("column", {}, [c])))] }],
218
+ },
219
+ {
220
+ name: "columns", title: "Cột", icon: Columns2, category: "design", keywords: "cot columns bo cuc layout", kind: "container", edit: ColumnsEdit,
221
+ attributes: { verticalAlign: { type: "string", enum: ["top", "center", "bottom"] }, stack: { type: "boolean", default: true } },
222
+ create: () => columns(1, 1), contextToolbar: ColumnsTools,
223
+ variations: [
224
+ { name: "50-50", title: "50 / 50", icon: Columns2, create: () => columns(1, 1) },
225
+ { name: "33-33-33", title: "33 / 33 / 33", icon: Columns3, create: () => columns(1, 1, 1) },
226
+ { name: "30-70", title: "30 / 70", icon: LayoutPanelLeft, create: () => columns(30, 70) },
227
+ { name: "70-30", title: "70 / 30", icon: LayoutPanelLeft, create: () => columns(70, 30) },
228
+ { name: "25x4", title: "25 / 25 / 25 / 25", icon: Columns4, create: () => columns(1, 1, 1, 1) },
229
+ ],
230
+ supports: { style: true, anchor: true, className: true },
231
+ },
232
+ { name: "column", title: "Cột", icon: RectangleHorizontal, kind: "container", edit: ColumnEdit, hidden: true, attributes: { width: { type: "number", min: 1, max: 100 } }, create: () => col(), supports: { style: true } },
233
+ {
234
+ name: "buttons", title: "Nút", icon: MousePointerClick, category: "design", keywords: "nut button cta lien ket", kind: "container", edit: ButtonsEdit,
235
+ attributes: { align: { type: "string", enum: ["left", "center", "right", "space-between"] } },
236
+ create: () => makeBlock("buttons", {}, [makeBlock("button", { variant: "primary" })]), contextToolbar: ButtonsTools,
237
+ supports: { style: true, anchor: true, className: true },
238
+ },
239
+ {
240
+ name: "button", title: "Nút", icon: MousePointerClick, kind: "atom", edit: ButtonEdit, hidden: true,
241
+ attributes: { text: { type: "string" }, href: { type: "url" }, target: { type: "string", enum: ["_self", "_blank"] }, rel: { type: "string" }, variant: { type: "string", enum: ["primary", "secondary", "outline"], default: "primary" } },
242
+ create: (attrs) => makeBlock("button", { variant: "primary", ...attrs }),
243
+ supports: { style: true, className: true }, summary: (a) => a.text,
244
+ },
245
+ {
246
+ name: "spacer", title: "Khoảng trống", icon: ChevronsUpDown, category: "design", keywords: "khoang trong spacer cach", kind: "atom", edit: SpacerEdit,
247
+ attributes: { height: { type: "string", default: "lg" } }, summary: (a) => a.height,
248
+ },
249
+ { name: "horizontalRule", title: "Đường kẻ", icon: Minus, category: "design", keywords: "duong ke divider hr separator", kind: "atom", edit: SeparatorEdit, supports: { style: true, className: true, blockStyle: true } },
250
+ {
251
+ name: "callout", title: "Hộp lưu ý", icon: Info, category: "design", keywords: "luu y callout thong bao canh bao note", kind: "container", edit: CalloutEdit,
252
+ attributes: { tone: { type: "string", enum: ["info", "success", "warning", "danger"], default: "info" }, title: { type: "string" } },
253
+ create: () => makeBlock("callout", { tone: "info" }, [makeBlock("paragraph")]), supports: { style: true, anchor: true, className: true },
254
+ },
255
+ {
256
+ name: "details", title: "Chi tiết", icon: PanelTop, category: "text", keywords: "chi tiet details accordion faq hoi dap an hien", kind: "container", edit: DetailsEdit,
257
+ attributes: { summary: { type: "string" }, open: { type: "boolean", default: false } },
258
+ create: () => makeBlock("details", {}, [makeBlock("paragraph")]), supports: { style: true, anchor: true, className: true },
259
+ },
260
+ {
261
+ name: "cover", title: "Ảnh bìa", icon: ImageIcon, category: "media", keywords: "anh bia cover banner hero", kind: "container", edit: CoverEdit,
262
+ attributes: { src: { type: "url", control: "media" }, alt: { type: "string" }, overlay: { type: "string", control: "color" }, opacity: { type: "integer", default: 50, min: 0, max: 100 }, minHeight: { type: "string", default: "400px" }, contentAlign: { type: "string", enum: ["top", "center", "bottom"], default: "center" }, fixed: { type: "boolean", default: false } },
263
+ create: () => makeBlock("cover", { opacity: 50, minHeight: "400px" }, [makeBlock("heading", { level: 2, textAlign: "center" })]),
264
+ supports: { style: true, anchor: true, className: true },
265
+ },
266
+ {
267
+ name: "mediaText", title: "Ảnh + chữ", icon: LayoutPanelLeft, category: "media", keywords: "anh chu media text", kind: "container", edit: MediaTextEdit,
268
+ attributes: { src: { type: "url", control: "media" }, alt: { type: "string" }, position: { type: "string", enum: ["left", "right"], default: "left" }, width: { type: "integer", default: 50, min: 20, max: 80 }, verticalAlign: { type: "string", enum: ["top", "center", "bottom"], default: "center" }, stack: { type: "boolean", default: true } },
269
+ create: () => makeBlock("mediaText", {}, [makeBlock("paragraph")]), supports: { style: true, anchor: true, className: true },
270
+ },
271
+ {
272
+ name: "table", title: "Bảng", icon: Table2, category: "text", keywords: "bang table", kind: "container", edit: TableEdit,
273
+ attributes: { footer: { type: "boolean", default: false }, fixed: { type: "boolean", default: false } },
274
+ create: () => makeBlock("table", {}, [0, 1, 2].map((r) => makeBlock("tableRow", {}, [cell(r === 0), cell(r === 0), cell(r === 0)]))), contextToolbar: TableTools,
275
+ supports: { style: true, anchor: true, className: true, blockStyle: true },
276
+ },
277
+ { name: "tableRow", title: "Hàng", icon: Table2, kind: "container", edit: RowEdit, hidden: true },
278
+ { name: "tableCell", title: "Ô", icon: Table2, kind: "container", edit: CellEdit, hidden: true, attributes: { colspan: { type: "integer", default: 1 }, rowspan: { type: "integer", default: 1 } } },
279
+ { name: "tableHeader", title: "Ô tiêu đề", icon: Table2, kind: "container", edit: CellEdit, hidden: true, attributes: { colspan: { type: "integer", default: 1 }, rowspan: { type: "integer", default: 1 } } },
280
+ ];
281
+ }
@@ -0,0 +1,76 @@
1
+ import { isSafeUrl } from "@ecomcx/ecomweb-content";
2
+ import { Link2, Upload } from "lucide-react";
3
+ import { useRef, useState, type DragEvent, type ReactNode } from "react";
4
+ import type { MediaItem, MediaKind } from "../../shared/types";
5
+ import { useEditor } from "../context";
6
+
7
+ const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
8
+ const ACCEPT: Record<MediaKind, string> = { image: "image/*", gallery: "image/*", video: "video/*", audio: "audio/*", file: "" };
9
+
10
+ /** Thuộc tính ghi vào khối từ tệp media đã chọn / tải lên. */
11
+ export function mediaAttrs(kind: MediaKind, items: MediaItem[]): Record<string, unknown> {
12
+ if (kind === "gallery") return { images: items.map((m) => ({ src: m.url, alt: m.alt, width: m.width ?? undefined, height: m.height ?? undefined, id: m.id })) };
13
+ const m = items[0];
14
+ return { src: m.url, alt: kind === "image" ? m.alt || undefined : undefined, name: kind !== "image" ? m.fileName : undefined, mime: m.mimeType, mediaId: m.id, width: kind === "image" ? m.width ?? undefined : undefined, height: kind === "image" ? m.height ?? undefined : undefined };
15
+ }
16
+
17
+ /**
18
+ * Chọn media ngay trên khối: Tải lên (có thể kéo thả tệp vào cả vùng), Thư viện, Chèn từ URL. Dùng cho ảnh, gallery,
19
+ * video, âm thanh, tệp, ảnh bìa, ảnh + chữ.
20
+ */
21
+ export function MediaActions({ kind, onSelect, onUrl, compact, extra }: { kind: MediaKind; onSelect(items: MediaItem[]): void; onUrl?(url: string): void; compact?: boolean; extra?: ReactNode }) {
22
+ const { host, labels } = useEditor();
23
+ const file = useRef<HTMLInputElement>(null);
24
+ const [busy, setBusy] = useState(false);
25
+ const [showUrl, setShowUrl] = useState(!host.media);
26
+ const [url, setUrl] = useState("");
27
+ const [error, setError] = useState<string | null>(null);
28
+ const upload = async (files: File[]) => {
29
+ if (!files.length || !host.media?.upload) return;
30
+ setBusy(true); setError(null);
31
+ try { const items = await host.media.upload(kind === "gallery" ? files : files.slice(0, 1)); if (items.length) onSelect(items); }
32
+ catch (e) { setError((e as Error).message); }
33
+ finally { setBusy(false); }
34
+ };
35
+ const pick = async () => { const items = await host.media!.pick({ kind, multiple: kind === "gallery" }); if (items.length) onSelect(items); };
36
+ return (
37
+ <div className={cx("ecx-media-actions", compact && "is-compact")} contentEditable={false} onMouseDown={(e) => e.stopPropagation()}>
38
+ <div className="ecx-media-buttons">
39
+ {host.media?.upload && <button type="button" className="ecx-btn ecx-btn-primary" disabled={busy} onClick={() => file.current?.click()}><Upload className="ecx-icon ecx-icon-sm" />{busy ? labels.uploading : labels.upload}</button>}
40
+ {host.media && <button type="button" className="ecx-btn" onClick={pick}>{labels.mediaLibrary}</button>}
41
+ {onUrl && host.media && <button type="button" className="ecx-btn ecx-btn-ghost" aria-expanded={showUrl} onClick={() => setShowUrl(!showUrl)}><Link2 className="ecx-icon ecx-icon-sm" />{labels.insertFromUrl}</button>}
42
+ {extra}
43
+ </div>
44
+ {onUrl && showUrl && (
45
+ <form onSubmit={(e) => { e.preventDefault(); if (isSafeUrl(url.trim())) onUrl(url.trim()); }}>
46
+ <input className="ecx-input" type="url" placeholder="https://…" value={url} onChange={(e) => setUrl(e.target.value)} aria-label={labels.imageUrl} />
47
+ <button type="submit" className="ecx-btn">{labels.apply}</button>
48
+ </form>
49
+ )}
50
+ {error && <p className="ecx-media-error" role="alert">{error}</p>}
51
+ <input ref={file} type="file" hidden accept={ACCEPT[kind] || undefined} multiple={kind === "gallery"} onChange={(e) => { void upload([...(e.target.files ?? [])]); e.target.value = ""; }} />
52
+ </div>
53
+ );
54
+ }
55
+
56
+ /** Kéo thả tệp từ máy vào vùng của khối → tải lên. */
57
+ export function useFileDrop(kind: MediaKind, onSelect: (items: MediaItem[]) => void) {
58
+ const { host } = useEditor();
59
+ const [over, setOver] = useState(false);
60
+ if (!host.media?.upload) return { over: false, props: {} };
61
+ const hasFiles = (e: DragEvent) => [...e.dataTransfer.types].includes("Files");
62
+ return {
63
+ over,
64
+ props: {
65
+ onDragOver: (e: DragEvent) => { if (!hasFiles(e)) return; e.preventDefault(); setOver(true); },
66
+ onDragLeave: () => setOver(false),
67
+ onDrop: async (e: DragEvent) => {
68
+ if (!hasFiles(e)) return;
69
+ e.preventDefault(); setOver(false);
70
+ const files = [...e.dataTransfer.files];
71
+ const items = await host.media!.upload!(kind === "gallery" ? files : files.slice(0, 1));
72
+ if (items.length) onSelect(items);
73
+ },
74
+ },
75
+ };
76
+ }