@ecomcx/ecomweb-editor 1.25.3 → 1.26.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecomcx/ecomweb-editor",
3
- "version": "1.25.3",
3
+ "version": "1.26.1",
4
4
  "description": "Trình soạn nội dung dạng khối của CMS — dùng độc lập trong mọi dự án React (1.x: TipTap; ./v2: cây khối, khung soạn iframe, sửa header/footer tại chỗ).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  "*.css"
30
30
  ],
31
31
  "peerDependencies": {
32
- "@ecomcx/ecomweb-content": "^1.19.0",
32
+ "@ecomcx/ecomweb-content": "^1.20.0",
33
33
  "react": ">=18",
34
34
  "react-dom": ">=18"
35
35
  },
@@ -45,7 +45,7 @@
45
45
  "prosemirror-view": "1.42.7"
46
46
  },
47
47
  "devDependencies": {
48
- "@ecomcx/ecomweb-content": "^1.19.0",
48
+ "@ecomcx/ecomweb-content": "^1.20.0",
49
49
  "@playwright/test": "1.53.0",
50
50
  "@types/react": "19.2.2",
51
51
  "@types/react-dom": "19.2.2",
@@ -30,6 +30,7 @@ export const attrs = {
30
30
  minHeight: "Min height",
31
31
  contentAlign: "Content position",
32
32
  fixed: "Fixed background",
33
+ constrained: "Keep inner content at text-column width",
33
34
  position: "Media position",
34
35
  columns: "Columns",
35
36
  footer: "Footer row",
@@ -42,6 +42,33 @@ export const v2 = {
42
42
  alignLeft: "Align left",
43
43
  alignCenter: "Align center",
44
44
  alignRight: "Align right",
45
+ width: "Width",
46
+ ai: "AI",
47
+ aiRewrite: "Rewrite to read better",
48
+ aiShorten: "Shorten",
49
+ aiExpand: "Make longer",
50
+ aiFix: "Fix spelling & grammar",
51
+ aiSummarize: "Summarize",
52
+ aiTranslateEn: "Translate to English",
53
+ aiTranslateVi: "Translate to Vietnamese",
54
+ aiCustom: "Other request…",
55
+ aiCustomPrompt: "What should the AI do with this text?",
56
+ aiWorking: "AI is writing…",
57
+ aiNote: "Check before using — AI can be wrong. You can still undo after replacing (⌘Z).",
58
+ aiReplace: "Replace",
59
+ aiInsertBelow: "Insert below",
60
+ aiRetry: "Try again",
61
+ aiWrite: "Write with AI",
62
+ aiWriteHint: "AI writes paragraphs from your request",
63
+ aiWritePrompt: "What should the AI write? E.g. a short intro to a tea shop, 3 sentences",
64
+ aiWriteRun: "Write",
65
+ aiInsert: "Insert into post",
66
+ aiAlt: "Generate image description (alt) with AI",
67
+ aiAltNoMedia: "Pick the image from the media library first",
68
+ aiAltDone: "Description filled in",
69
+ widthDefault: "Text column",
70
+ widthWide: "Wide",
71
+ widthFull: "Full width",
45
72
  devices: "Device",
46
73
  deviceDesktop: "Desktop",
47
74
  deviceTablet: "Tablet",
@@ -119,6 +146,8 @@ export const v2 = {
119
146
  deleteRow: "Delete row",
120
147
  deleteColumn: "Delete column",
121
148
  mergeRight: "Merge with cell on the right",
149
+ mergeCells: "Merge selected cells",
150
+ clearCells: "Clear cell contents",
122
151
  mergeDown: "Merge with cell below",
123
152
  splitCell: "Split cell",
124
153
  toolbarHint: "Select a block to show its tools here",
@@ -184,4 +213,5 @@ export const v2 = {
184
213
  choiceSelect: "— Select —",
185
214
  choiceMissing: "(missing)",
186
215
  openInNewTab: "Open in new tab",
216
+ countdownNoTarget: "No end time yet — set “Target” in the sidebar (until then the website does not show this block)",
187
217
  };
@@ -30,6 +30,7 @@ export const attrs = {
30
30
  minHeight: "Cao tối thiểu",
31
31
  contentAlign: "Vị trí chữ",
32
32
  fixed: "Cố định khi cuộn",
33
+ constrained: "Giữ chữ bên trong theo bề rộng cột chữ",
33
34
  position: "Vị trí ảnh",
34
35
  columns: "Số cột",
35
36
  footer: "Hàng cuối là chân bảng",
@@ -42,6 +42,33 @@ export const v2 = {
42
42
  alignLeft: "Căn trái",
43
43
  alignCenter: "Căn giữa",
44
44
  alignRight: "Căn phải",
45
+ width: "Độ rộng",
46
+ ai: "AI",
47
+ aiRewrite: "Viết lại cho hay hơn",
48
+ aiShorten: "Rút gọn",
49
+ aiExpand: "Viết dài hơn",
50
+ aiFix: "Sửa chính tả, ngữ pháp",
51
+ aiSummarize: "Tóm tắt",
52
+ aiTranslateEn: "Dịch sang tiếng Anh",
53
+ aiTranslateVi: "Dịch sang tiếng Việt",
54
+ aiCustom: "Yêu cầu khác…",
55
+ aiCustomPrompt: "Bạn muốn AI làm gì với đoạn này?",
56
+ aiWorking: "AI đang viết…",
57
+ aiNote: "Kiểm tra lại trước khi dùng — AI có thể sai. Thay thế xong vẫn hoàn tác được (⌘Z).",
58
+ aiReplace: "Thay thế",
59
+ aiInsertBelow: "Chèn bên dưới",
60
+ aiRetry: "Thử lại",
61
+ aiWrite: "Viết bằng AI",
62
+ aiWriteHint: "AI viết đoạn văn từ yêu cầu của bạn",
63
+ aiWritePrompt: "Bạn muốn AI viết gì? Ví dụ: giới thiệu ngắn về cửa hàng trà, 3 câu",
64
+ aiWriteRun: "Viết",
65
+ aiInsert: "Chèn vào bài",
66
+ aiAlt: "Tạo mô tả ảnh (alt) bằng AI",
67
+ aiAltNoMedia: "Chọn ảnh từ thư viện media trước",
68
+ aiAltDone: "Đã điền mô tả",
69
+ widthDefault: "Theo cột chữ",
70
+ widthWide: "Rộng",
71
+ widthFull: "Toàn trang",
45
72
  devices: "Thiết bị",
46
73
  deviceDesktop: "Máy tính",
47
74
  deviceTablet: "Máy tính bảng",
@@ -119,6 +146,8 @@ export const v2 = {
119
146
  deleteRow: "Xoá hàng",
120
147
  deleteColumn: "Xoá cột",
121
148
  mergeRight: "Gộp với ô bên phải",
149
+ mergeCells: "Gộp các ô đã chọn",
150
+ clearCells: "Xoá nội dung ô",
122
151
  mergeDown: "Gộp với ô bên dưới",
123
152
  splitCell: "Tách ô",
124
153
  toolbarHint: "Chọn một khối để hiện công cụ của khối ở đây",
@@ -184,4 +213,5 @@ export const v2 = {
184
213
  choiceSelect: "— Chọn —",
185
214
  choiceMissing: "(không còn)",
186
215
  openInNewTab: "Mở trong tab mới",
216
+ countdownNoTarget: "Chưa chọn thời điểm kết thúc — đặt ở ô “Thời điểm” bên phải (khi chưa đặt, website không hiện khối này)",
187
217
  };
@@ -160,9 +160,11 @@ function ShortcodeEdit({ block, blockProps }: BlockEditProps) {
160
160
  return <div {...(merge(blockProps, "ecx-shortcode", { fontFamily: "monospace", opacity: 0.8 }) as object)}>[{String(block.attrs.name || "shortcode")}]</div>;
161
161
  }
162
162
 
163
- function CountdownEdit({ block, blockProps }: BlockEditProps) {
163
+ function CountdownEdit({ block, blockProps, labels }: BlockEditProps) {
164
164
  const a = block.attrs;
165
- return <div {...(merge(blockProps, "ecx-countdown", { textAlign: "center" }) as object)}>{a.label ? <p style={{ margin: 0 }}>{String(a.label)}</p> : null}<strong>{a.target ? String(a.target) : "00 : 00 : 00 : 00"}</strong></div>;
165
+ // Thiếu / sai thời điểm: website không vẽ khối → trong trình soạn nói rõ, không để khối "mất tích" im lặng
166
+ if (!Number.isFinite(Date.parse(String(a.target ?? "")))) return <div {...(merge(blockProps, "ecx-countdown ecx-placeholder-block", {}) as object)}>{a.label ? <strong>{String(a.label)}</strong> : null}<span>{labels.countdownNoTarget}</span></div>;
167
+ return <div {...(merge(blockProps, "ecx-countdown", { textAlign: "center" }) as object)}>{a.label ? <p style={{ margin: 0 }}>{String(a.label)}</p> : null}<strong>{String(a.target)}</strong></div>;
166
168
  }
167
169
 
168
170
  function RatingEdit({ block, blockProps }: BlockEditProps) {
@@ -250,7 +252,7 @@ export function layoutBlocks(): BlockType[] {
250
252
  return [
251
253
  {
252
254
  name: "group", title: "Nhóm", icon: Square, category: "design", keywords: "nhom group khung section container", kind: "container", edit: GroupEdit,
253
- attributes: { background: { type: "string", control: "color" }, textColor: { type: "string", control: "color" }, padding: { type: "string", enum: ["none", "small", "medium", "large"], default: "medium" } },
255
+ attributes: { background: { type: "string", control: "color" }, textColor: { type: "string", control: "color" }, padding: { type: "string", enum: ["none", "small", "medium", "large"], default: "medium" }, constrained: { type: "boolean", default: false } },
254
256
  create: (attrs) => makeBlock("group", attrs ?? {}, [makeBlock("paragraph")]),
255
257
  toolbar: GroupLayoutTools,
256
258
  variations: [
@@ -334,7 +336,7 @@ export function layoutBlocks(): BlockType[] {
334
336
  },
335
337
  {
336
338
  name: "cover", title: "Ảnh bìa", icon: ImageIcon, category: "media", keywords: "anh bia cover banner hero", kind: "container", edit: CoverEdit,
337
- 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 } },
339
+ 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 }, constrained: { type: "boolean", default: false } },
338
340
  create: () => makeBlock("cover", { opacity: 50, minHeight: "400px" }, [makeBlock("heading", { level: 2, textAlign: "center" })]),
339
341
  supports: { style: true, anchor: true, className: true },
340
342
  },
@@ -2,6 +2,7 @@ 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
3
  import { useState, type CSSProperties } from "react";
4
4
  import { useEditor } from "../context";
5
+ import { AiAltButton } from "../ui/ai";
5
6
  import type { BlockEditProps, BlockType } from "../core/registry";
6
7
  import { RichText } from "../text/rich-text";
7
8
  import { BoundText, useBindingPreview } from "../ui/bindings";
@@ -28,6 +29,8 @@ function MediaPlaceholder({ blockId, kind, icon: Icon, title, blockProps }: { bl
28
29
  );
29
30
  }
30
31
 
32
+ function ImageAiTools({ attrs, setAttrs }: BlockEditProps) { return <AiAltButton attrs={attrs} setAttrs={setAttrs} />; }
33
+
31
34
  function ImageEdit({ block, blockProps, setAttrs, editable, labels, selected }: BlockEditProps) {
32
35
  const a = block.attrs;
33
36
  const bSrc = useBindingPreview(block, "src"), bAlt = useBindingPreview(block, "alt"), bCap = useBindingPreview(block, "caption");
@@ -256,7 +259,7 @@ export function mediaBlocks(): BlockType[] {
256
259
  const media = { src: { type: "url" as const, control: "media" as const }, mediaId: { type: "json" as const }, caption: { type: "string" as const } };
257
260
  return [
258
261
  {
259
- name: "image", title: "Ảnh", icon: ImageIcon, category: "media", keywords: "anh hinh image photo", kind: "atom", edit: ImageEdit,
262
+ name: "image", title: "Ảnh", icon: ImageIcon, category: "media", keywords: "anh hinh image photo", kind: "atom", edit: ImageEdit, toolbar: ImageAiTools,
260
263
  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 } },
261
264
  supports: { style: true, anchor: true, className: true, blockStyle: true }, summary: (a) => a.alt || a.src,
262
265
  },
@@ -1,4 +1,4 @@
1
- import { normalizeStyle, styleClass } from "@ecomcx/ecomweb-content";
1
+ import { normalizeStyle, styleClass, widthClass } from "@ecomcx/ecomweb-content";
2
2
  import { Component, memo, useCallback, useContext, useEffect, useMemo, useRef, type ErrorInfo, type MouseEvent, type ReactElement, type ReactNode } from "react";
3
3
  import { DocScopeProvider, LoopPostContext, useDocScope, useEditor, useEditorState } from "../context";
4
4
  import { ServerBlock } from "./server-block";
@@ -42,6 +42,11 @@ export function useBlockProps(block: BNode, state: { selected: boolean; editing:
42
42
  const rich = target.closest<HTMLElement>("[data-ecx-rich]");
43
43
  if (rich && rich.isContentEditable && !e.shiftKey) return; // bấm vào chữ: ProseMirror đặt con trỏ, focus báo đang gõ
44
44
  if (target.closest("input, textarea, select, button, [contenteditable=true]") && !e.shiftKey) return;
45
+ // Bấm vào phần đệm của ô bảng: con trỏ vào chữ trong ô (như bấm vào ô của Word / WordPress), không chọn cả ô
46
+ if ((block.type === "tableCell" || block.type === "tableHeader") && !e.shiftKey && !e.metaKey && !e.ctrlKey) {
47
+ const text = block.content?.find((b) => b.inline);
48
+ if (text) { e.preventDefault(); store.focusText(text.id, -1); return; }
49
+ }
45
50
  e.preventDefault();
46
51
  // Chọn khối: rời ô gõ, đưa focus về khung soạn (phím Delete, ⌘C… thuộc về vùng chọn khối)
47
52
  const active = own.ownerDocument.activeElement as HTMLElement | null;
@@ -67,6 +72,7 @@ export function useBlockProps(block: BNode, state: { selected: boolean; editing:
67
72
  state.editing && "is-editing",
68
73
  state.mode === "disabled" && "is-locked",
69
74
  style && styleClass(style),
75
+ widthClass(block.type, a),
70
76
  typeof a.blockStyle === "string" && `ecx-is-${a.blockStyle}`,
71
77
  typeof a.className === "string" && a.className,
72
78
  ),
@@ -14,23 +14,41 @@ body.ecx-canvas-body { padding: 0; }
14
14
  .ecx-edit-link:hover { background: var(--ecx-ui, #1a597b); color: #fff; }
15
15
  /* HTML do website vẽ (khối theme/plugin): các lớp hiệu ứng "ẩn tới khi JS chạy" thường gặp luôn ở trạng thái cuối. Theme nên đặt trạng thái ẩn dưới html.ecx-js (chỉ có khi JS chạy) để khỏi phụ thuộc đoán tên lớp. */
16
16
  .ecx-server-html [class*="stagger"], .ecx-server-html [class*="reveal"], .ecx-server-html [class*="animate"], .ecx-server-html [class*="fade-"], .ecx-server-html [class*="aos"], .ecx-server-html [data-aos] { opacity: 1 !important; visibility: visible !important; transform: none !important; animation: none !important; transition: none !important; }
17
- .ecx-canvas-root { min-height: 100vh; padding: 2rem clamp(1rem, 4vw, 3rem) 40vh; box-sizing: border-box; outline: none; }
18
- .ecx-canvas-root > * { max-width: var(--ecx-content-width, 760px); margin-left: auto; margin-right: auto; }
17
+ .ecx-canvas-root { min-height: 100vh; padding: 52px clamp(1rem, 4vw, 3rem) 40vh; box-sizing: border-box; outline: none; }
18
+ /* --ecx-canvas-col: bề rộng cột của khung soạn; KHÔNG đổi --ecx-content-width (nhóm "giữ chữ theo cột" của nội dung dùng biến đó) */
19
+ .ecx-canvas-root > * { max-width: var(--ecx-canvas-col, var(--ecx-content-width, 760px)); margin-left: auto; margin-right: auto; }
19
20
  /* Mặc định của trình soạn: độ ưu tiên chỉ bằng "1 class" (:where) — đứng sau dòng trên nên thắng nó, nhưng CSS theme nạp sau (vd .ecx-template > * { max-width: 960px }) thắng lại, như trên website */
20
21
  :where(.ecx-canvas-root) > :is(.ecx-nested, .ecx-cover, [data-type="columns"], .ecx-align-wide) { max-width: var(--ecx-wide-width, 1200px); }
21
- .ecx-canvas-root > .ecx-align-full { max-width: none; }
22
+ .ecx-canvas-root.ecx-canvas-root > .ecx-align-full { max-width: none; }
22
23
  /* Header/footer trong template: mặc định rộng hết (cùng mức ưu tiên — theme giới hạn bề rộng phần con của template thì canvas theo) */
23
24
  :where(.ecx-canvas-root) > .ecx-template-part { max-width: none; }
24
- .ecx-canvas-root.is-wide > * { max-width: var(--ecx-wide-width, 1120px); }
25
+ /* Template rộng (full-width / canvas có sẵn): như website — chữ vẫn ở cột chữ, khối Rộng / Toàn trang mới tràn ra */
26
+ .ecx-canvas-root.is-wide { --ecx-canvas-col: var(--ecx-content-width, 760px); }
25
27
  /* Template (theme dựng bằng khối): website không giới hạn bề rộng khối con và không có lề soạn — canvas làm y hệt, theme tự quyết bằng CSS của nó
26
28
  (chỉ đổi giá trị mặc định của biến, nên CSS theme vẫn thắng nếu có đặt max-width cho .ecx-template > *). */
27
- .ecx-canvas-root.ecx-template, .ecx-canvas-root.entry-content { --ecx-content-width: none; --ecx-wide-width: none; padding-left: 0; padding-right: 0; padding-top: 0; }
29
+ .ecx-canvas-root.ecx-template, .ecx-canvas-root.entry-content { --ecx-canvas-col: none; padding-left: 0; padding-right: 0; }
30
+ /* padding-top 52px (canvas mặc định + template) = chỗ cho thanh công cụ nổi (44px + 8) trên khối đầu: thiếu chỗ thì thanh đè lên chữ, bấm vào khối trúng nút của thanh.
31
+ Bài (.entry-content): ô tiêu đề nằm trên khối đầu nên đã đủ chỗ — giữ 0 như website (thêm khoảng làm khung bao của trang bài lệch so với lúc mở) */
32
+ .ecx-canvas-root.entry-content { padding-top: 0; }
33
+ /* Vùng bài của template full-width / canvas có sẵn (.ecx-layout-constrained): cột chữ + lề hai bên như website */
34
+ .ecx-canvas-root.ecx-canvas-root.ecx-layout-constrained { --ecx-canvas-col: var(--ecx-content-width, 760px); padding-left: var(--ecx-gutter, 1.25rem); padding-right: var(--ecx-gutter, 1.25rem); }
35
+ .ecx-canvas-root.ecx-layout-constrained > :is(.ecx-nested, .ecx-cover, [data-type="columns"]):not(.ecx-align-wide, .ecx-align-full) { max-width: var(--ecx-canvas-col); }
36
+ :where(.ecx-canvas-root.ecx-template, .ecx-canvas-root.entry-content) > :is(.ecx-nested, .ecx-cover, [data-type="columns"]) { max-width: none; }
37
+ /* Khối "Rộng" / "Toàn trang" (align wide/full): bề rộng và lề âm do style.css của @ecomcx/ecomweb-content (như website), canvas chỉ bỏ giới hạn */
38
+ :where(.ecx-canvas-root.ecx-template, .ecx-canvas-root.entry-content) > :is(.ecx-align-wide, .ecx-align-full) { max-width: none; }
39
+ /* Lề tự căn giữa của khung soạn (.ecx-canvas-root > * margin auto) không được đè lề âm của khối rộng / toàn trang */
40
+ .ecx-canvas-root > :is(.ecx-align-wide, .ecx-align-full) { margin-left: calc((100% - var(--_w, 100%)) / 2); margin-right: calc((100% - var(--_w, 100%)) / 2); }
28
41
  /* Soạn bài / trang trong khung của website (class entry-content do PostContent đặt): bề rộng cột do theme quyết định, không phải 760px của trình soạn */
29
42
 
30
43
  .ecx-block { position: relative; scroll-margin: 80px; }
31
44
  .ecx-block:focus { outline: none; }
32
45
  .ecx-block:not([data-ecx-rich]):hover:not(:has(.ecx-block:hover)) { outline: 1px solid color-mix(in srgb, var(--ecx-ui) 40%, transparent); outline-offset: 3px; }
33
46
  .ecx-block.is-selected { outline: 2px solid var(--ecx-ui) !important; outline-offset: 3px; }
47
+ /* Ô bảng đang chọn (một hoặc cả vùng): tô màu như bôi đen, không viền (viền ô chồng lên viền bảng) */
48
+ .ecx-block.is-selected:is([data-type="tableCell"], [data-type="tableHeader"]) { outline: none !important; box-shadow: inset 0 0 0 9999px color-mix(in srgb, var(--ecx-ui) 16%, transparent); }
49
+ .ecx-block.is-selected:is([data-type="tableCell"], [data-type="tableHeader"], [data-type="tableRow"])::after { display: none; }
50
+ /* Đang kéo bôi vùng ô: tắt bôi chữ của trình duyệt (chỉ tô ô) */
51
+ .ecx-cell-selecting, .ecx-cell-selecting * { user-select: none !important; -webkit-user-select: none !important; caret-color: transparent; }
34
52
  /* Nhãn loại khối (chỉ khi chọn, khối cấp thường; khối lồng đã có .ecx-nested-label). Không đổi bố cục: absolute, không nhận chuột */
35
53
  .ecx-block.is-selected:not(.ecx-nested):not(.ecx-column)[data-type]::after { content: attr(data-ecx-title); position: absolute; left: -2px; top: -3px; transform: translateY(-100%); padding: 1px 8px; border-radius: 4px 4px 0 0; background: var(--ecx-ui); color: #fff; font: 600 11px/1.7 var(--ecx-ui-font); letter-spacing: 0; text-transform: none; white-space: nowrap; pointer-events: none; z-index: 5; }
36
54
  .ecx-block.is-selected[data-ecx-title=""]::after { content: none; }
@@ -42,7 +60,9 @@ pre [data-ecx-rich], pre[data-ecx-rich] { white-space: pre-wrap; }
42
60
  [data-ecx-rich][data-empty]:not([data-placeholder-always]):not(:focus)::before { content: none; }
43
61
  [data-ecx-rich][data-empty] { position: relative; }
44
62
  /* min(100%, …) = 0 trong khung co theo nội dung (nút) → dùng độ dài chữ gợi ý, chặn tràn bằng max-width */
45
- [data-ecx-rich][data-empty][data-placeholder] { min-width: calc(var(--ecx-ph, 0) * .6em); max-width: 100%; }
63
+ /* Chỉ ô chữ dạng span (nút, nhãn…): đoạn văn trống KHÔNG đặt max-width — luật này ưu tiên cao hơn cột chữ của khung soạn,
64
+ đoạn trống sẽ rộng hết khung và lệch khỏi cột (gõ chữ vào mới nhảy về) */
65
+ span[data-ecx-rich][data-empty][data-placeholder] { min-width: calc(var(--ecx-ph, 0) * .6em); max-width: 100%; }
46
66
  span[data-ecx-rich][data-empty][data-placeholder] { display: inline-block; vertical-align: top; }
47
67
  [data-ecx-rich][data-empty][data-placeholder] { min-width: 0; } /* ô lưới/flex trống không bị chữ gợi ý (nowrap) đẩy rộng hơn khung */
48
68
  [data-ecx-rich][data-empty][data-placeholder]::before { white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
@@ -53,7 +73,7 @@ span[data-ecx-rich][data-empty][data-placeholder] { display: inline-block; verti
53
73
  .ecx-block.is-locked { pointer-events: none; }
54
74
  .ecx-block.is-locked .ecx-nested:not(.is-locked), .ecx-block.is-locked [data-ecx-editable-doc] { pointer-events: auto; }
55
75
 
56
- .ecx-default-appender { cursor: text; color: #5d6a75; margin: 0; padding: .25em 0; }
76
+ .ecx-default-appender { cursor: text; color: #5d6a75; margin-top: 0; margin-bottom: 0; padding: .25em 0; } /* lề trái/phải auto như khối khác (thẳng cột chữ) */
57
77
  .ecx-default-appender:focus { outline: none; }
58
78
  .ecx-appender { display: flex; align-items: center; justify-content: center; width: 100%; min-height: 44px; margin: 0; border: 1px dashed color-mix(in srgb, currentColor 30%, transparent); border-radius: 4px; background: transparent; color: inherit; font: 600 20px/1 var(--ecx-ui-font); cursor: pointer; opacity: .6; }
59
79
  .ecx-appender:hover { opacity: 1; border-color: var(--ecx-ui); color: var(--ecx-ui); }
@@ -103,6 +123,8 @@ body.is-dragging, body.is-dragging * { cursor: grabbing !important; user-select:
103
123
  .ecx-doc-title { margin-top: 0; }
104
124
  .ecx-doc-title-input { display: block; width: 100%; margin: 0; padding: 0; border: 0; outline: none; resize: none; overflow: hidden; background: transparent; color: inherit; font: inherit; letter-spacing: inherit; line-height: inherit; text-align: inherit; }
105
125
  .ecx-doc-title-input::placeholder { color: inherit; opacity: .35; }
126
+ /* Theme thường tạo kiểu mọi ô nhập (textarea { border; padding } textarea:focus { outline }) — ô tiêu đề không được mang khung ô nhập */
127
+ .ecx-doc-title .ecx-doc-title-input, .ecx-doc-title .ecx-doc-title-input:focus { border: 0; border-radius: 0; outline: none; box-shadow: none; padding: 0; background: transparent; min-height: 0; }
106
128
  .ecx-col-handles { position: absolute; inset: 0; pointer-events: none; z-index: 6; }
107
129
  .ecx-col-handle { position: absolute; width: 12px; margin-left: -6px; cursor: col-resize; pointer-events: auto; touch-action: none; }
108
130
  .ecx-col-handle::after { content: ""; position: absolute; left: 5px; top: 0; bottom: 0; width: 2px; background: var(--ecx-ui); opacity: .35; border-radius: 1px; }
@@ -11,6 +11,8 @@ import { applyDocumentAttrs } from "./document-attrs";
11
11
  import { wrapperNodes } from "./wrapper-props";
12
12
  import { makeBlock, type BNode } from "../core/model";
13
13
  import { flatten, topLevelOrdered } from "../core/ops";
14
+ import { useTableRangeSelect } from "./table-select";
15
+ import { clearCells, deleteRow, selectedCellRect, tableContext } from "../core/tables";
14
16
  import { insertSibling, now, richViews } from "../text/rich-text";
15
17
 
16
18
  export type Device = "desktop" | "tablet" | "mobile";
@@ -33,6 +35,8 @@ const SRC_DOC = `<!doctype html><html><head><meta charset="utf-8"><meta name="vi
33
35
  export const ZOOM_OUT = 0.5;
34
36
  /** Khổ "Máy tính" luôn vẽ rộng ít nhất bằng này (> 1024 để CSS tablet của website không áp lên); chỗ hẹp hơn thì thu nhỏ vừa khung thay vì vẽ hẹp. */
35
37
  export const DESKTOP_MIN_WIDTH = 1100;
38
+ /** Thu nhỏ dưới tỉ lệ này thì chữ quá nhỏ để đọc / gõ (máy thật là điện thoại, tablet dọc): vẽ đúng bề rộng khung, không thu. */
39
+ export const MIN_FIT = 0.6;
36
40
 
37
41
  export function Canvas({ device = "desktop", className, contentClassName = "ecx-content", before, after }: CanvasProps) {
38
42
  const { ui, labels } = useEditor();
@@ -69,7 +73,8 @@ export function Canvas({ device = "desktop", className, contentClassName = "ecx-
69
73
  useUiTick();
70
74
  const width = DEVICE_WIDTH[device];
71
75
  // Thu nhỏ: khung soạn vẽ ở cỡ gấp đôi rồi thu còn một nửa → thấy cả trang, toạ độ kéo thả / thanh công cụ tự tính theo tỉ lệ
72
- const fit = !width && wrapW > 0 && wrapW < DESKTOP_MIN_WIDTH ? wrapW / DESKTOP_MIN_WIDTH : 1;
76
+ const ratio = !width && wrapW > 0 && wrapW < DESKTOP_MIN_WIDTH ? wrapW / DESKTOP_MIN_WIDTH : 1;
77
+ const fit = ratio >= MIN_FIT ? ratio : 1;
73
78
  const zoom = (ui.zoomOut ? ZOOM_OUT : 1) * fit;
74
79
  const style = zoom === 1 ? { width: width ? `${width}px` : "100%" }
75
80
  : { width: width ? `${width}px` : `${100 / zoom}%`, height: `${100 / zoom}%`, transform: `scale(${zoom})`, transformOrigin: width ? "top center" : "top left", flex: "none" };
@@ -105,6 +110,7 @@ function CanvasRoot({ doc, contentClassName, before, after }: { doc: Document; c
105
110
  useCanvasStyles(doc);
106
111
  useCanvasKeys(doc);
107
112
  useCanvasEvents(doc);
113
+ useTableRangeSelect(doc);
108
114
  const hasRange = useRangeHighlight(doc);
109
115
  return (
110
116
  <div className={["ecx-canvas-root", contentClassName, host.canvasContentClass, focus && "is-focus-mode", spotlight && "is-spotlight", ui.zoomOut && "is-zoomed-out", hasRange && "has-text-range"].filter(Boolean).join(" ")} data-ecx-doc={activeId} tabIndex={-1}
@@ -251,9 +257,11 @@ function useCanvasKeys(doc: Document) {
251
257
  // Ô gõ (ProseMirror) đã xử lý phím này
252
258
  if (e.defaultPrevented) return;
253
259
  const outer = fromTree(e);
254
- if (e.target instanceof Element && e.target.ownerDocument !== doc && !outer) return; // phím của trang ngoài ngoài Cây khối: không phải của khung soạn
255
260
  const mod = e.metaKey || e.ctrlKey;
256
261
  const k = e.key.toLowerCase();
262
+ // Vừa bấm nút trên thanh đầu (Lưu, Hoàn tác…): focus ở trang ngoài (nút Lưu tắt sau khi lưu → focus về body) — ⌘Z/⌘Y vẫn là của trình soạn
263
+ const fromTopbar = mod && (k === "z" || k === "y") && e.target instanceof Element && e.target.ownerDocument !== doc && !typing(e.target) && (!!e.target.closest(".ecx-topbar") || e.target === e.target.ownerDocument.body);
264
+ if (e.target instanceof Element && e.target.ownerDocument !== doc && !outer && !fromTopbar) return; // phím của trang ngoài ngoài Cây khối: không phải của khung soạn
257
265
  if (mod && k === "z") { e.preventDefault(); if (e.shiftKey) store.redo(); else store.undo(); return; }
258
266
  if (mod && k === "y") { e.preventDefault(); store.redo(); return; }
259
267
  if (typing(outer ? (e.target as Element) : doc.activeElement)) return;
@@ -301,6 +309,24 @@ function useCanvasKeys(doc: Document) {
301
309
  }
302
310
  if (!ids.length) return;
303
311
  if (e.altKey && e.key === "F10") { e.preventDefault(); ui.focusToolbar(); return; }
312
+ // Ô / hàng của bảng: Delete xoá NỘI DUNG ô (xoá khối ô làm bảng lệch), xoá hàng bằng thao tác hàng; Esc chọn cả bảng
313
+ const cells = selectedCellRect(store, ids);
314
+ const rows = !cells && ids.every((id) => store.block(id)?.type === "tableRow") ? ids : null;
315
+ if (cells || rows) {
316
+ if (e.key === "Backspace" || e.key === "Delete") {
317
+ e.preventDefault();
318
+ if (cells) clearCells(store, cells.table, ids);
319
+ else store.batch(() => { for (const id of [...rows!].reverse()) { const first = store.block(id)?.content?.[0]; const ctx = first && tableContext(store, first.id); if (ctx) deleteRow(store, ctx); } });
320
+ return;
321
+ }
322
+ if (e.key === "Escape") { e.preventDefault(); const t = cells?.table.id ?? store.locate(ids[0])?.parent?.id; if (t) store.select([t], { editing: null }); return; }
323
+ }
324
+ // Khối nằm trong ô bảng (đoạn văn trong ô sau khi thôi gõ): Esc chọn cả bảng
325
+ if (e.key === "Escape" && ids.length === 1) {
326
+ const loc = store.locate(ids[0]);
327
+ const table = loc && [...loc.ancestors].reverse().find((a) => store.block(a)?.type === "table");
328
+ if (table) { e.preventDefault(); store.select([table], { editing: null }); return; }
329
+ }
304
330
  if (e.key === "Backspace" || e.key === "Delete") { e.preventDefault(); store.remove(ids); return; }
305
331
  if (e.key === "Escape") { e.preventDefault(); store.clearSelection(); ui.openInserter(null); return; }
306
332
  if (e.key === "Enter" && ids.length === 1) {
@@ -55,6 +55,7 @@ function begin(ctx: EditorContextValue, e: ReactPointerEvent, src: Source) {
55
55
  window.removeEventListener("blur", cancel);
56
56
  ui.canvasDoc?.removeEventListener("pointermove", move);
57
57
  ui.canvasDoc?.removeEventListener("pointerup", up);
58
+ ui.canvasDoc?.removeEventListener("keydown", key, true);
58
59
  document.body.classList.remove("is-dragging");
59
60
  ui.canvasDoc?.body.classList.remove("is-dragging");
60
61
  for (const id of src.ids) ui.blockEl(id)?.classList.remove("is-dragging-source");
@@ -87,6 +88,7 @@ function begin(ctx: EditorContextValue, e: ReactPointerEvent, src: Source) {
87
88
  document.addEventListener("keydown", key, true);
88
89
  ui.canvasDoc?.addEventListener("pointermove", move);
89
90
  ui.canvasDoc?.addEventListener("pointerup", up);
91
+ ui.canvasDoc?.addEventListener("keydown", key, true); // focus thường nằm trong iframe khung soạn (vừa bấm khối) → Escape bắn ở đó
90
92
 
91
93
  function autoScroll(c: EditorContextValue, y: number) {
92
94
  const f = c.ui.canvasFrame?.getBoundingClientRect();
@@ -0,0 +1,74 @@
1
+ import { useEffect } from "react";
2
+ import { useEditor } from "../context";
3
+ import { cellRect, cellTable, cellsInRect } from "../core/tables";
4
+
5
+ const CELL = '[data-type="tableCell"], [data-type="tableHeader"]';
6
+
7
+ /**
8
+ * Bôi đen vùng ô của bảng như WordPress / Google Docs: kéo chuột từ ô này sang ô khác, hoặc Shift+bấm ô khác khi đang ở trong
9
+ * một ô của cùng bảng → chọn mọi ô trong hình chữ nhật (ô gộp được nới trọn). Chọn xong: thanh công cụ có Gộp ô / Xoá nội dung.
10
+ */
11
+ export function useTableRangeSelect(doc: Document) {
12
+ const { store } = useEditor();
13
+ useEffect(() => {
14
+ let anchor: string | null = null;
15
+ let inRange = false;
16
+ const cellOf = (t: EventTarget | null) => (t instanceof (doc.defaultView as unknown as typeof globalThis).Element ? (t as Element).closest<HTMLElement>(CELL) : null);
17
+ const selectRange = (a: string, b: string) => {
18
+ const ta = cellTable(store, a), tb = cellTable(store, b);
19
+ if (!ta || !tb || ta.table.id !== tb.table.id) return false;
20
+ const rect = cellRect(ta.table, a, b);
21
+ if (!rect) return false;
22
+ (doc.activeElement as HTMLElement | null)?.blur?.();
23
+ doc.getSelection()?.removeAllRanges();
24
+ store.select(cellsInRect(ta.table, rect).map((c) => c.id), { editing: null });
25
+ doc.querySelector<HTMLElement>(".ecx-canvas-root")?.focus({ preventScroll: true });
26
+ return true;
27
+ };
28
+ /** Ô của chỗ đang gõ / đang chọn (mốc cho Shift+bấm). */
29
+ const currentCell = () => {
30
+ const s = store.getState().selection;
31
+ const id = s.editing ?? s.ids[0];
32
+ if (!id) return null;
33
+ const loc = store.locate(id);
34
+ if (!loc) return null;
35
+ for (const x of [id, ...[...loc.ancestors].reverse()]) if (cellTable(store, x)) return x;
36
+ return null;
37
+ };
38
+ const down = (e: MouseEvent) => {
39
+ if (e.button !== 0) return;
40
+ const cell = cellOf(e.target);
41
+ anchor = cell?.dataset.ecxBlock ?? null;
42
+ inRange = false;
43
+ head = null;
44
+ if (!cell || !e.shiftKey) return;
45
+ const from = currentCell();
46
+ if (from && from !== anchor && selectRange(from, anchor!)) { e.preventDefault(); e.stopPropagation(); anchor = from; }
47
+ };
48
+ let head: string | null = null;
49
+ const move = (e: MouseEvent) => {
50
+ if (!anchor) return;
51
+ // Lúc kéo bôi chữ, e.target vẫn là phần tử bắt đầu kéo → lấy ô dưới con trỏ
52
+ const cell = cellOf(doc.elementFromPoint(e.clientX, e.clientY))?.dataset.ecxBlock;
53
+ if (cell && (cell !== anchor || inRange) && cell !== head && selectRange(anchor, cell)) {
54
+ head = cell;
55
+ if (!inRange) { inRange = true; doc.documentElement.classList.add("ecx-cell-selecting"); }
56
+ }
57
+ if (inRange) {
58
+ // Đang bôi theo ô: trình duyệt không được bôi chữ song song (vệt bôi chữ nhảy qua các ô), ô gõ không đổi thành dải chữ
59
+ e.preventDefault();
60
+ e.stopPropagation();
61
+ doc.getSelection()?.removeAllRanges();
62
+ }
63
+ };
64
+ const up = (e: MouseEvent) => {
65
+ if (inRange) { e.stopPropagation(); doc.getSelection()?.removeAllRanges(); }
66
+ doc.documentElement.classList.remove("ecx-cell-selecting");
67
+ anchor = null; head = null; inRange = false;
68
+ };
69
+ doc.addEventListener("mousedown", down, true);
70
+ doc.addEventListener("mousemove", move, true);
71
+ doc.addEventListener("mouseup", up, true);
72
+ return () => { doc.removeEventListener("mousedown", down, true); doc.removeEventListener("mousemove", move, true); doc.removeEventListener("mouseup", up, true); };
73
+ }, [doc, store]);
74
+ }
@@ -42,6 +42,8 @@ export class EditorUi {
42
42
  activeRich: string | null = null;
43
43
  /** Mở hộp sửa liên kết cho ô gõ (khoá richViews). */
44
44
  openLink: ((viewKey: string) => void) | null = null;
45
+ /** Mở hộp "Viết bằng AI": chèn ở vị trí (khối chứa lệnh /ai thì thay khối đó). */
46
+ openAiWrite: ((at: { blockId?: string; docId: string; parentId: string | null; index: number }) => void) | null = null;
45
47
 
46
48
  subscribe = (l: () => void) => { this.listeners.add(l); return () => { this.listeners.delete(l); }; };
47
49
  getTick = () => this.tick;
@@ -52,6 +52,15 @@ export interface EditorHost {
52
52
  /** Bài thật cho "Danh sách bài" theo thiết lập của khối (soạn thấy đúng bài sẽ hiện). Không có → dynamic.posts. */
53
53
  queryPosts?(query: QueryArgs): Promise<DynamicPost[]>;
54
54
  createPattern?(content: SavedContent): Promise<{ ref: number; synced: boolean } | null>;
55
+ /**
56
+ * Trợ lý AI (ứng dụng gọi nhà cung cấp, trình soạn chỉ gửi chữ và nhận chữ). Không có → không hiện menu AI.
57
+ * `task`: rewrite | shorten | expand | fix | summarize | translate | custom. Lỗi: ném Error có thông báo cho người dùng.
58
+ */
59
+ ai?: {
60
+ run(task: string, text: string, opts?: { language?: string; instruction?: string }): Promise<string>;
61
+ /** Mô tả (alt) cho ảnh trong thư viện media; không có = khối Ảnh không hiện nút AI. */
62
+ altText?(mediaId: number, language?: string): Promise<string>;
63
+ };
55
64
  }
56
65
 
57
66
  /** Nội dung lưu (ContentDoc của @ecomcx/ecomweb-content). */
@@ -192,3 +192,72 @@ export function normalizeTable(table: BNode): BNode {
192
192
  for (const x of g.cells) filled += x.rs * x.cs;
193
193
  return (table.content ?? []).length === h && filled === h * w ? table : fromGrid(table, g);
194
194
  }
195
+
196
+ // ---------------------------------------------------------------------------
197
+ // Vùng ô (bôi đen nhiều ô: kéo chuột / Shift+bấm) — như chọn ô của WordPress / Google Docs
198
+ // ---------------------------------------------------------------------------
199
+ export interface CellRect { r0: number; c0: number; r1: number; c1: number }
200
+
201
+ /** Bảng chứa ô (khối tableCell / tableHeader) + id ô. */
202
+ export function cellTable(store: EditorStore, cellId: string): { table: BNode; docId: string } | null {
203
+ const cell = store.locate(cellId);
204
+ if (!cell || (cell.block.type !== "tableCell" && cell.block.type !== "tableHeader")) return null;
205
+ const row = cell.parent && store.locate(cell.parent.id);
206
+ return row?.parent?.type === "table" ? { table: row.parent, docId: cell.docId } : null;
207
+ }
208
+
209
+ /** Hình chữ nhật nhỏ nhất phủ hai ô, nới ra cho tới khi không cắt ngang ô gộp nào. */
210
+ export function cellRect(table: BNode, aId: string, bId: string): CellRect | null {
211
+ const g = toGrid(table);
212
+ const a = g.cells.find((x) => x.node.id === aId), b = g.cells.find((x) => x.node.id === bId);
213
+ if (!a || !b) return null;
214
+ const r: CellRect = { r0: Math.min(a.r, b.r), c0: Math.min(a.c, b.c), r1: Math.max(a.r + a.rs, b.r + b.rs) - 1, c1: Math.max(a.c + a.cs, b.c + b.cs) - 1 };
215
+ for (let changed = true; changed;) {
216
+ changed = false;
217
+ for (const x of g.cells) {
218
+ const inter = x.r <= r.r1 && x.r + x.rs - 1 >= r.r0 && x.c <= r.c1 && x.c + x.cs - 1 >= r.c0;
219
+ if (!inter) continue;
220
+ const n = { r0: Math.min(r.r0, x.r), c0: Math.min(r.c0, x.c), r1: Math.max(r.r1, x.r + x.rs - 1), c1: Math.max(r.c1, x.c + x.cs - 1) };
221
+ if (n.r0 !== r.r0 || n.c0 !== r.c0 || n.r1 !== r.r1 || n.c1 !== r.c1) { Object.assign(r, n); changed = true; }
222
+ }
223
+ }
224
+ return r;
225
+ }
226
+
227
+ /** Ô nằm trong vùng (theo thứ tự hàng rồi cột). */
228
+ export function cellsInRect(table: BNode, rect: CellRect): BNode[] {
229
+ return toGrid(table).cells.filter((x) => x.r >= rect.r0 && x.r <= rect.r1 && x.c >= rect.c0 && x.c <= rect.c1)
230
+ .sort((a, b) => a.r - b.r || a.c - b.c).map((x) => x.node);
231
+ }
232
+
233
+ /** Vùng của các ô đang chọn (cùng một bảng) — null nếu không phải. */
234
+ export function selectedCellRect(store: EditorStore, ids: string[]): { table: BNode; docId: string; rect: CellRect } | null {
235
+ if (!ids.length) return null;
236
+ const t = cellTable(store, ids[0]);
237
+ if (!t || ids.some((id) => cellTable(store, id)?.table.id !== t.table.id)) return null;
238
+ let rect: CellRect | null = null;
239
+ for (const id of ids) {
240
+ const r = cellRect(t.table, ids[0], id);
241
+ if (!r) return null;
242
+ rect = rect ? { r0: Math.min(rect.r0, r.r0), c0: Math.min(rect.c0, r.c0), r1: Math.max(rect.r1, r.r1), c1: Math.max(rect.c1, r.c1) } : r;
243
+ }
244
+ return { ...t, rect: rect! };
245
+ }
246
+
247
+ /** Gộp cả vùng thành một ô (ô trên-trái giữ lại, nội dung các ô khác nối vào theo thứ tự). */
248
+ export function mergeRange(store: EditorStore, table: BNode, docId: string, rect: CellRect) {
249
+ const g = toGrid(table);
250
+ const inside = g.cells.filter((x) => x.r >= rect.r0 && x.r <= rect.r1 && x.c >= rect.c0 && x.c <= rect.c1).sort((a, b) => a.r - b.r || a.c - b.c);
251
+ if (inside.length < 2) return;
252
+ const [keep, ...rest] = inside;
253
+ const merged: GridCell = { ...keep, node: rest.reduce((n, x) => absorb(n, x.node), keep.node), rs: rect.r1 - rect.r0 + 1, cs: rect.c1 - rect.c0 + 1 };
254
+ g.cells = g.cells.filter((x) => !inside.includes(x)).concat(merged);
255
+ replaceTable(store, { table, row: 0, col: 0, docId }, fromGrid(table, g), merged.node);
256
+ }
257
+
258
+ /** Xoá chữ trong các ô (giữ ô, mỗi ô còn một đoạn trống). */
259
+ export function clearCells(store: EditorStore, table: BNode, ids: string[]) {
260
+ const set = new Set(ids);
261
+ const next = { ...table, content: (table.content ?? []).map((row) => ({ ...row, content: (row.content ?? []).map((c) => (set.has(c.id) ? { ...c, content: [makeBlock("paragraph")] } : c)) })) };
262
+ store.replace(table.id, [next], { select: { ids: [], editing: null } });
263
+ }
package/src/v2/editor.css CHANGED
@@ -62,6 +62,7 @@
62
62
  .ecx-tool-primary:hover:not(:disabled) { background: var(--ecx-ed-accent-hover); color: var(--ecx-ed-accent-fg); }
63
63
  .ecx-tool-primary.is-active { background: var(--ecx-ed-fg); color: var(--ecx-ed-panel); }
64
64
  .ecx-tool-text { font-weight: 500; white-space: nowrap; color: inherit; }
65
+ .ecx-tool-text:has(> .ecx-icon) { display: inline-flex; align-items: center; gap: 4px; }
65
66
  .ecx-tool-group { display: flex; align-items: center; }
66
67
  .ecx-tool:active:not(:disabled) { transform: scale(.97); }
67
68
 
@@ -326,3 +327,13 @@ body.is-dragging, body.is-dragging * { cursor: grabbing !important; user-select:
326
327
  .ecx-toolbar .ecx-tool { height: 40px; min-width: 38px; }
327
328
  .ecx-movers .ecx-tool { height: 20px; min-width: 30px; }
328
329
  }
330
+
331
+ /* Hộp kết quả AI */
332
+ .ecx-ai-body { padding: 12px 16px 16px; display: flex; flex-direction: column; gap: 10px; }
333
+ .ecx-ai-text { max-height: 50vh; overflow: auto; padding: 10px 12px; border: 1px solid var(--ecx-ed-line); border-radius: 8px; background: var(--ecx-ed-subtle, rgba(127,127,127,.06)); font-size: 14px; line-height: 1.6; }
334
+ .ecx-ai-text p { margin: 0 0 .6em; } .ecx-ai-text p:last-child { margin: 0; }
335
+ .ecx-ai-wait { margin: 0; color: var(--ecx-ed-muted, #667085); animation: ecx-ai-pulse 1.2s ease-in-out infinite; }
336
+ .ecx-ai-error { margin: 0; color: #b42318; }
337
+ .ecx-ai-note { margin: 0; font-size: 12px; color: var(--ecx-ed-muted, #667085); }
338
+ @keyframes ecx-ai-pulse { 50% { opacity: .45; } }
339
+ @media (prefers-reduced-motion: reduce) { .ecx-ai-wait { animation: none; } }
package/src/v2/editor.tsx CHANGED
@@ -10,6 +10,7 @@ import { Canvas, type Device } from "./canvas/canvas";
10
10
  import { EditorContext, EditorUi, useEditor, useEditorState, useUiTick, type EditorContextValue } from "./context";
11
11
  import type { EditorHost } from "./core/host";
12
12
  import { InserterPanel, InserterPopover } from "./ui/inserter";
13
+ import { AiWrite } from "./ui/ai";
13
14
  import { labelsV2, type V2Labels } from "./labels";
14
15
  import { localesVersion, onLocalesChange } from "../i18n";
15
16
  import { blocksFromDoc, docFromBlocks, type BNode } from "./core/model";
@@ -292,6 +293,7 @@ export function EditorOverlays() {
292
293
  <>
293
294
  <BlockToolbar />
294
295
  <InserterPopover />
296
+ <AiWrite />
295
297
  <DropIndicator />
296
298
  <LiveRegion />
297
299
  </>
package/src/v2/prefs.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { useSyncExternalStore } from "react";
1
+ import { useMemo, useSyncExternalStore } from "react";
2
2
 
3
3
  /**
4
4
  * Tuỳ chọn của trình soạn — cách trình soạn hiển thị cho người đang dùng (không đổi nội dung, không đổi website).
@@ -64,6 +64,14 @@ export class PrefsStore {
64
64
  countInsert(type: string) { this.set({ insertCounts: { ...this.prefs.insertCounts, [type]: (this.prefs.insertCounts[type] ?? 0) + 1 } }); }
65
65
  }
66
66
 
67
+ /** Màn hình hẹp (điện thoại): thanh công cụ nổi đè lên dòng đang gõ và tràn mép → luôn ghim trên cùng (như WordPress trên điện thoại). */
68
+ export const NARROW_QUERY = "(max-width: 640px)";
69
+ const narrowMq = typeof matchMedia === "function" ? matchMedia(NARROW_QUERY) : null;
70
+ const subscribeNarrow = (l: () => void) => { narrowMq?.addEventListener("change", l); return () => narrowMq?.removeEventListener("change", l); };
71
+ const isNarrow = () => !!narrowMq?.matches;
72
+
67
73
  export function usePrefs(store: PrefsStore): EditorPrefs {
68
- return useSyncExternalStore(store.subscribe, store.get, store.get);
74
+ const prefs = useSyncExternalStore(store.subscribe, store.get, store.get);
75
+ const narrow = useSyncExternalStore(subscribeNarrow, isNarrow, () => false);
76
+ return useMemo(() => (narrow && !prefs.fixedToolbar ? { ...prefs, fixedToolbar: true } : prefs), [prefs, narrow]);
69
77
  }
@@ -244,7 +244,6 @@ function richKeymap(store: EditorStore, ui: EditorUi, pr: PropsRef, keepCaret: (
244
244
  // Tuỳ chọn "Giữ con trỏ trong khối": mũi tên ở đầu/cuối khối không nhảy sang khối khác
245
245
  const nav = (view: EditorView, dir: -1 | 1) => !keepCaret() && focusNeighbor(store, ui, view, dir);
246
246
  const textMode = () => !pr.current.onChange;
247
- const mark = (name: string) => (state: EditorState, dispatch?: EditorView["dispatch"]) => (state.schema.marks[name] ? toggleMark(state.schema.marks[name])(state, dispatch) : false);
248
247
  const slashKey = (key: string) => () => (ui.inserter?.mode === "slash" && ui.inserter.blockId === pr.current.blockId && ui.inserterKey ? ui.inserterKey(key) : false);
249
248
  /** Lệnh dùng vùng chọn mới nhất (đọc lại từ DOM). */
250
249
  const fresh = (cmd: (state: EditorState, dispatch: EditorView["dispatch"] | undefined, view: EditorView | undefined) => boolean) =>
@@ -252,6 +251,8 @@ function richKeymap(store: EditorStore, ui: EditorUi, pr: PropsRef, keepCaret: (
252
251
  const s = syncSelection(view) ?? state;
253
252
  return cmd(s, view ? view.dispatch.bind(view) : dispatch, view);
254
253
  };
254
+ // Đọc lại vùng chọn từ DOM trước khi đổi định dạng: Shift+End rồi ⌘B ngay (<50ms) thì ProseMirror chưa kịp nhận vùng chọn → chỉ đặt storedMarks
255
+ const mark = (name: string) => fresh((state, dispatch) => (state.schema.marks[name] ? toggleMark(state.schema.marks[name])(state, dispatch) : false));
255
256
  return keymap({
256
257
  ArrowDown: (_s, _d, view) => slashKey("ArrowDown")() || (!!view && view.endOfTextblock("down") && nav(view, 1)),
257
258
  ArrowUp: (_s, _d, view) => slashKey("ArrowUp")() || (!!view && view.endOfTextblock("up") && nav(view, -1)),
@@ -0,0 +1,134 @@
1
+ import { Sparkles } from "lucide-react";
2
+ import { useEffect, useState } from "react";
3
+ import { useEditor } from "../context";
4
+ import { inlineText, makeBlock, type BNode } from "../core/model";
5
+ import { Modal } from "./options";
6
+ import { Dropdown, MenuItem, ToolButton } from "./toolbar";
7
+
8
+ type Job = { task: string; label: string; language?: string; instruction?: string };
9
+
10
+ /**
11
+ * Menu AI trên thanh công cụ của khối chữ: viết lại, rút gọn, mở rộng, sửa chính tả, tóm tắt, dịch, yêu cầu khác.
12
+ * Kết quả hiện trong hộp xem trước — người dùng chọn Thay thế / Chèn bên dưới / Huỷ (một bước hoàn tác).
13
+ */
14
+ export function AiTools({ block }: { block: BNode }) {
15
+ const { host, labels, store } = useEditor();
16
+ const [job, setJob] = useState<Job | null>(null);
17
+ const [state, setState] = useState<{ loading: boolean; text?: string; error?: string }>({ loading: false });
18
+ if (!host.ai || !block.inline) return null;
19
+ const source = inlineText(block.inline);
20
+ const run = async (j: Job) => {
21
+ setJob(j); setState({ loading: true });
22
+ try { setState({ loading: false, text: await host.ai!.run(j.task, source, { language: j.language, instruction: j.instruction }) }); }
23
+ catch (e) { setState({ loading: false, error: (e as Error).message }); }
24
+ };
25
+ const ask = () => { const instruction = window.prompt(labels.aiCustomPrompt)?.trim(); if (instruction) void run({ task: "custom", label: labels.aiCustom, instruction }); };
26
+ const paragraphs = (text: string) => text.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
27
+ const apply = (mode: "replace" | "below") => {
28
+ const parts = paragraphs(state.text ?? "");
29
+ if (!parts.length) return;
30
+ const loc = store.locate(block.id);
31
+ if (!loc) return;
32
+ store.batch(() => {
33
+ if (mode === "replace") {
34
+ store.replace(block.id, [{ ...block, inline: [{ type: "text", text: parts[0] }] }, ...parts.slice(1).map((p) => makeBlock("paragraph", {}, p))]);
35
+ } else {
36
+ store.insert(loc.docId, loc.parent?.id ?? null, loc.index + 1, parts.map((p) => makeBlock("paragraph", {}, p)));
37
+ }
38
+ });
39
+ setJob(null);
40
+ };
41
+ const items: Job[] = [
42
+ { task: "rewrite", label: labels.aiRewrite }, { task: "shorten", label: labels.aiShorten }, { task: "expand", label: labels.aiExpand },
43
+ { task: "fix", label: labels.aiFix }, { task: "summarize", label: labels.aiSummarize },
44
+ { task: "translate", label: labels.aiTranslateEn, language: "English" }, { task: "translate", label: labels.aiTranslateVi, language: "Vietnamese" },
45
+ ];
46
+ return (
47
+ <>
48
+ <Dropdown label={labels.ai} trigger={<span className="ecx-tool-text"><Sparkles className="ecx-icon" />AI</span>}>
49
+ {(close) => <>
50
+ {items.map((j) => <MenuItem key={j.label} label={j.label} onClick={() => { close(); void run(j); }} />)}
51
+ <MenuItem label={labels.aiCustom} onClick={() => { close(); ask(); }} />
52
+ </>}
53
+ </Dropdown>
54
+ {job && (
55
+ <Modal title={`${labels.ai}: ${job.label}`} onClose={() => setJob(null)} wide>
56
+ <div className="ecx-ai-body" data-ecx-ai-result>
57
+ {state.loading && <p className="ecx-ai-wait" role="status">{labels.aiWorking}</p>}
58
+ {state.error && <p className="ecx-ai-error" role="alert">{state.error}</p>}
59
+ {state.text && <div className="ecx-ai-text">{paragraphs(state.text).map((p, i) => <p key={i}>{p}</p>)}</div>}
60
+ <p className="ecx-ai-note">{labels.aiNote}</p>
61
+ <div className="ecx-popover-actions">
62
+ <button type="button" className="ecx-btn" onClick={() => setJob(null)}>{labels.cancel}</button>
63
+ {state.text && <button type="button" className="ecx-btn" onClick={() => apply("below")} data-ai-apply="below">{labels.aiInsertBelow}</button>}
64
+ {state.text && <button type="button" className="ecx-btn ecx-btn-primary" onClick={() => apply("replace")} data-ai-apply="replace">{labels.aiReplace}</button>}
65
+ {state.error && <button type="button" className="ecx-btn ecx-btn-primary" onClick={() => void run(job)}>{labels.aiRetry}</button>}
66
+ </div>
67
+ </div>
68
+ </Modal>
69
+ )}
70
+ </>
71
+ );
72
+ }
73
+
74
+ /** Khối Ảnh: nút "Tạo mô tả (alt) bằng AI" trên thanh công cụ (ảnh phải chọn từ thư viện media để biết mediaId). */
75
+ export function AiAltButton({ attrs, setAttrs }: { attrs: Record<string, unknown>; setAttrs(a: Record<string, unknown>): void }) {
76
+ const { host, labels } = useEditor();
77
+ const [busy, setBusy] = useState(false);
78
+ if (!host.ai?.altText) return null;
79
+ const id = Number(attrs.mediaId);
80
+ const run = async () => {
81
+ if (!Number.isFinite(id) || id <= 0) { window.alert(labels.aiAltNoMedia); return; }
82
+ setBusy(true);
83
+ try { setAttrs({ alt: (await host.ai!.altText!(id, labels.lang === "vi" ? "Vietnamese" : "English")).trim() }); }
84
+ catch (e) { window.alert((e as Error).message); }
85
+ finally { setBusy(false); }
86
+ };
87
+ return <ToolButton label={labels.aiAlt} onClick={() => void run()} disabled={busy} data-ai-alt><Sparkles className="ecx-icon" /><span className="ecx-tool-text">Alt</span></ToolButton>;
88
+ }
89
+
90
+ /**
91
+ * Lệnh /ai: hộp "Viết bằng AI" — gõ yêu cầu, xem kết quả, rồi chèn (thay khối chứa "/ai" nếu gọi từ lệnh gạch chéo).
92
+ * Một bước hoàn tác; không tự chèn khi chưa bấm.
93
+ */
94
+ export function AiWrite() {
95
+ const { host, labels, store, ui } = useEditor();
96
+ const [at, setAt] = useState<{ blockId?: string; docId: string; parentId: string | null; index: number } | null>(null);
97
+ const [prompt, setPrompt] = useState("");
98
+ const [state, setState] = useState<{ loading: boolean; text?: string; error?: string }>({ loading: false });
99
+ useEffect(() => { ui.openAiWrite = (a) => { setAt(a); setPrompt(""); setState({ loading: false }); }; return () => { ui.openAiWrite = null; }; }, [ui]);
100
+ if (!at || !host.ai) return null;
101
+ const run = async () => {
102
+ if (!prompt.trim()) return;
103
+ setState({ loading: true });
104
+ try { setState({ loading: false, text: await host.ai!.run("write", prompt.trim(), {}) }); }
105
+ catch (e) { setState({ loading: false, error: (e as Error).message }); }
106
+ };
107
+ const paragraphs = (state.text ?? "").split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
108
+ const insert = () => {
109
+ if (!paragraphs.length) return;
110
+ const nodes = paragraphs.map((p) => makeBlock("paragraph", {}, p));
111
+ store.batch(() => {
112
+ if (at.blockId && store.block(at.blockId)) store.replace(at.blockId, nodes);
113
+ else store.insert(at.docId, at.parentId, at.index, nodes);
114
+ });
115
+ setAt(null);
116
+ };
117
+ return (
118
+ <Modal title={labels.aiWrite} onClose={() => setAt(null)} wide>
119
+ <div className="ecx-ai-body" data-ecx-ai-write>
120
+ <textarea className="ecx-input" rows={3} value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder={labels.aiWritePrompt} data-ai-write-prompt
121
+ onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); void run(); } }} />
122
+ {state.loading && <p className="ecx-ai-wait" role="status">{labels.aiWorking}</p>}
123
+ {state.error && <p className="ecx-ai-error" role="alert">{state.error}</p>}
124
+ {state.text && <div className="ecx-ai-text" data-ecx-ai-result>{paragraphs.map((p, i) => <p key={i}>{p}</p>)}</div>}
125
+ <p className="ecx-ai-note">{labels.aiNote}</p>
126
+ <div className="ecx-popover-actions">
127
+ <button type="button" className="ecx-btn" onClick={() => setAt(null)}>{labels.cancel}</button>
128
+ <button type="button" className="ecx-btn" onClick={() => void run()} disabled={state.loading || !prompt.trim()} data-ai-write-run>{state.text ? labels.aiRetry : labels.aiWriteRun}</button>
129
+ {state.text && <button type="button" className="ecx-btn ecx-btn-primary" onClick={insert} data-ai-write-insert>{labels.aiInsert}</button>}
130
+ </div>
131
+ </div>
132
+ </Modal>
133
+ );
134
+ }
@@ -1,10 +1,10 @@
1
1
  import { leavesItem } from "../core/structure";
2
2
  import { blockDescription } from "./block-descriptions";
3
- import { Blocks } from "lucide-react";
3
+ import { Blocks, Sparkles } from "lucide-react";
4
4
  import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentType } from "react";
5
5
  import { norm } from "../../shared/util";
6
6
  import { useEditor, useUiTick, type InserterRequest } from "../context";
7
- import { cloneBlock, inlineLength, type BNode } from "../core/model";
7
+ import { cloneBlock, inlineLength, makeBlock, type BNode } from "../core/model";
8
8
  import type { BlockType } from "../core/registry";
9
9
  import { canContain } from "../core/structure";
10
10
  import { startDragNew } from "../canvas/dnd";
@@ -23,11 +23,13 @@ export interface InsertOption {
23
23
  /** Loại khối gốc (kiểm tra chỗ đặt được). */
24
24
  type: string;
25
25
  create(): BNode;
26
+ /** Lệnh riêng thay vì chèn khối (vd "ai-write" mở hộp Viết bằng AI). */
27
+ action?: "ai-write";
26
28
  }
27
29
 
28
30
  /** Các lựa chọn chèn: khối + biến thể có hàm tạo riêng (cột 30/70…). */
29
31
  export function useInsertOptions(): InsertOption[] {
30
- const { registry, prefs, host } = useEditor();
32
+ const { registry, prefs, host, labels } = useEditor();
31
33
  const hidden = usePrefs(prefs).hiddenBlockTypes;
32
34
  const [version, setVersion] = useState(registry.getVersion());
33
35
  useEffect(() => registry.subscribe(() => setVersion(registry.getVersion())), [registry]);
@@ -43,16 +45,18 @@ export function useInsertOptions(): InsertOption[] {
43
45
  out.push({ key: `${t.name}/${v.name}`, title: v.standalone ? v.title : `${t.title} ${v.title}`, description: v.description, icon: v.icon ?? t.icon, keywords: `${t.keywords ?? ""} ${v.keywords ?? ""}`, category: t.category ?? "other", type: t.name, create: v.create });
44
46
  }
45
47
  }
48
+ if (host.ai) out.push({ key: "ai-write", title: labels.aiWrite, description: labels.aiWriteHint, icon: Sparkles, keywords: "ai viet write gpt claude tro ly", category: "text", type: "paragraph", create: () => makeBlock("paragraph"), action: "ai-write" });
46
49
  return out;
47
- }, [registry, version, hidden, host.scope]);
50
+ }, [registry, version, hidden, host.scope, host.ai, labels]);
48
51
  }
49
52
 
50
- /** Lọc + xếp hạng: tên bắt đầu bằng chữ gõ > một từ trong tên > từ khoá; tiếng Việt không dấu. */
53
+ /** Lọc + xếp hạng: tên trùng hẳn > tên bắt đầu bằng chữ gõ > một từ trong tên > từ khoá; tiếng Việt không dấu. */
51
54
  export function rankOptions(list: InsertOption[], query: string): InsertOption[] {
52
55
  const q = norm(query.trim());
53
56
  if (!q) return list;
54
57
  const score = (i: InsertOption) => {
55
58
  const title = norm(i.title);
59
+ if (title === q) return 4; // "/anh" → Ảnh trước Ảnh bìa, Ảnh + chữ
56
60
  if (title.startsWith(q)) return 3;
57
61
  if (title.split(/\s+/).some((w) => w.startsWith(q))) return 2;
58
62
  const words = [...title.split(/\s+/), ...norm(i.keywords).split(/\s+/)];
@@ -66,6 +70,11 @@ export function rankOptions(list: InsertOption[], query: string): InsertOption[]
66
70
  /** Chèn một lựa chọn theo yêu cầu (slash: thay đoạn "/…"; nút "+": vào vị trí). */
67
71
  export function applyInsert(ctx: ReturnType<typeof useEditor>, req: InserterRequest, opt: InsertOption) {
68
72
  const { store, ui, prefs } = ctx;
73
+ if (opt.action === "ai-write") {
74
+ ui.openInserter(null);
75
+ ui.openAiWrite?.({ blockId: req.mode === "slash" ? req.blockId : undefined, docId: req.docId, parentId: req.parentId ?? null, index: req.index ?? 0 });
76
+ return;
77
+ }
69
78
  const node = opt.create();
70
79
  prefs.countInsert(opt.type);
71
80
  if (req.mode === "slash" && req.blockId) {
@@ -209,6 +218,8 @@ export function InserterPanel({ onInserted, onClose }: { onInserted?(): void; on
209
218
  const parentType = loc?.ancestors.length ? store.block(loc.ancestors[loc.ancestors.length - 1])?.type ?? null : null;
210
219
  const options = all.filter((o) => canContain(parentType, o.type));
211
220
  const panelRef = useRef<HTMLDivElement>(null);
221
+ // Mở bảng (nút Thêm khối) → focus vào ô tìm của bảng như WordPress; người dùng bàn phím gõ tìm ngay, Tab đi trong bảng
222
+ useEffect(() => { panelRef.current?.querySelector<HTMLInputElement>("input")?.focus({ preventScroll: true }); }, []);
212
223
  // Escape đóng bảng (khi focus đang ở bảng hoặc chưa ở đâu cả; đang gõ trong khung soạn thì Escape thuộc về khung soạn)
213
224
  useEffect(() => {
214
225
  if (!onClose) return;
@@ -240,7 +251,11 @@ export function InserterPanel({ onInserted, onClose }: { onInserted?(): void; on
240
251
  ctx.prefs.countInsert(o.type);
241
252
  const cur = store.currentIds[store.currentIds.length - 1];
242
253
  // Đoạn trống đang chọn mà chính lần chèn trước vừa tạo thì giữ lại (chèn tiếp ra sau nó); đoạn trống của người dùng thì thay như WordPress
243
- if (cur && store.locate(cur)) store.insertAfter(cur, [node], { replaceEmpty: cur !== lastInserted.current });
254
+ const curLoc = cur ? store.locate(cur) : null;
255
+ const curBlock = cur ? store.block(cur) : null;
256
+ // Đang chọn khối chứa còn trống (Nhóm, Cột… vừa tạo): chèn VÀO trong nó — chèn ra sau thì phải kéo vào thêm một bước
257
+ if (curLoc && curBlock && Array.isArray(curBlock.content) && curBlock.content.length === 0 && canContain(curBlock.type, node.type)) store.insert(curLoc.docId, cur, 0, [node]);
258
+ else if (cur && curLoc) store.insertAfter(cur, [node], { replaceEmpty: cur !== lastInserted.current });
244
259
  else {
245
260
  const docId = store.activeDocId;
246
261
  store.insert(docId, null, store.getState().docs[docId].blocks.length, [node]);
@@ -75,16 +75,19 @@ export function MoreMenu({ extra }: { extra?: (close: () => void) => ReactNode }
75
75
  }
76
76
 
77
77
  /** Hộp thoại dùng chung (Esc / bấm nền để đóng, giữ focus trong hộp). */
78
- function Modal({ title, onClose, children, wide }: { title: string; onClose(): void; children: ReactNode; wide?: boolean }) {
78
+ export function Modal({ title, onClose, children, wide }: { title: string; onClose(): void; children: ReactNode; wide?: boolean }) {
79
79
  const ref = useRef<HTMLDivElement>(null);
80
80
  const { labels } = useEditor();
81
+ // onClose qua ref: người gọi hay truyền hàm mới mỗi lần vẽ — chạy lại effect mỗi phím gõ sẽ trả focus về chỗ cũ (ô nhập trong hộp mất focus)
82
+ const closeRef = useRef(onClose);
83
+ closeRef.current = onClose;
81
84
  useEffect(() => {
82
85
  const prev = document.activeElement as HTMLElement | null;
83
- ref.current?.querySelector<HTMLElement>("button, input, [tabindex]")?.focus();
84
- const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); onClose(); } };
86
+ ref.current?.querySelector<HTMLElement>("textarea, input, button, [tabindex]")?.focus();
87
+ const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeRef.current(); } };
85
88
  document.addEventListener("keydown", onKey, true);
86
89
  return () => { document.removeEventListener("keydown", onKey, true); prev?.focus?.(); };
87
- }, [onClose]);
90
+ }, []);
88
91
  return (
89
92
  <div className="ecx-modal-backdrop" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
90
93
  <div ref={ref} className={cx("ecx-modal", wide && "is-wide")} role="dialog" aria-modal="true" aria-label={title}>
@@ -1,7 +1,10 @@
1
- import { StickyNote, Keyboard, AlignCenter, AlignLeft, AlignRight, ArrowUpLeft, Bold, ChevronDown, ChevronUp, Code, Copy, CopyPlus, GripVertical, IndentDecrease, IndentIncrease, Italic, Link2, Link2Off, MoreVertical, PanelTop, Strikethrough, Trash2, Underline, Ungroup, Group as GroupIcon, Blocks, ArrowUpToLine, ArrowDownToLine, Shapes, Lock, Subscript, Superscript, Highlighter } from "lucide-react";
1
+ import { WIDE_BLOCKS } from "@ecomcx/ecomweb-content";
2
+ import { clearCells, mergeRange, selectedCellRect } from "../core/tables";
3
+ import { AiTools } from "./ai";
4
+ import { Eraser, TableCellsMerge, StickyNote, Keyboard, MoveHorizontal, Maximize2, RectangleHorizontal, AlignCenter, AlignLeft, AlignRight, ArrowUpLeft, Bold, ChevronDown, ChevronUp, Code, Copy, CopyPlus, GripVertical, IndentDecrease, IndentIncrease, Italic, Link2, Link2Off, MoreVertical, PanelTop, Strikethrough, Trash2, Underline, Ungroup, Group as GroupIcon, Blocks, ArrowUpToLine, ArrowDownToLine, Shapes, Lock, Subscript, Superscript, Highlighter } from "lucide-react";
2
5
  import { TextSelection } from "prosemirror-state";
3
6
  import type { EditorView } from "prosemirror-view";
4
- import { useEffect, useLayoutEffect, useRef, useState, type ComponentType, type ReactNode } from "react";
7
+ import { useEffect, useLayoutEffect, useRef, useState, type ComponentType, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
5
8
  import { createPortal } from "react-dom";
6
9
  import { serializeBlocks } from "../core/clipboard";
7
10
 
@@ -92,7 +95,10 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
92
95
  // Đo vị trí SAU khi DOM của khung soạn cập nhật (khối vừa tạo chưa có DOM lúc vẽ thanh công cụ)
93
96
  const [rect, setRect] = useState<DOMRect | null>(null);
94
97
  useLayoutEffect(() => {
95
- const r = unionRect(ids.map((id) => ui.blockRect(id)));
98
+ // Trong bảng: thanh công cụ neo theo cả bảng (như WordPress) — neo theo ô thì thanh đè lên hàng phía trên
99
+ const loc0 = ids[0] ? store.locate(ids[0]) : null;
100
+ const table = loc0 ? [...loc0.ancestors].reverse().find((a) => store.block(a)?.type === "table") : undefined;
101
+ const r = table ? ui.blockRect(table) : unionRect(ids.map((id) => ui.blockRect(id)));
96
102
  setRect((prev) => (prev && r && prev.x === r.x && prev.y === r.y && prev.width === r.width && prev.height === r.height ? prev : r));
97
103
  });
98
104
  const nodes = ids.map((id) => store.block(id)).filter(Boolean) as BNode[];
@@ -117,11 +123,22 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
117
123
  const listItem = parent && (parent.type === "listItem" || parent.type === "taskItem") && loc.index === 0 ? parent : null;
118
124
  const transforms = sameType ? (type?.transforms ?? []).filter((t) => nodes.length === 1 || t.multiple) : [];
119
125
  const height = 44;
120
- const top = fixed || !rect || !frame ? 0 : Math.round(Math.max(frame.top + 4, rect.top - height - 8));
121
- const left = fixed || !rect || !frame ? 0 : Math.round(Math.max(frame.left + 4, Math.min(rect.left, frame.right - Math.min(420, window.innerWidth - 8))));
126
+ // Trên khối; không đủ chỗ (khối sát mép trên khung) thì xuống dưới khối nếu còn chỗ — không đè lên dòng chữ đang gõ
127
+ const above = rect && frame ? rect.top - height - 8 : 0;
128
+ const below = rect && frame && above < frame.top + 4 && rect.bottom + 8 + height <= frame.bottom - 4 ? rect.bottom + 8 : null;
129
+ const top = fixed || !rect || !frame ? 0 : Math.round(below ?? Math.max(frame.top + 4, above));
130
+ // Bề ngang theo KHUNG SOẠN (khổ Điện thoại 390px hẹp hơn cửa sổ): thanh dài hơn khung thì cuộn ngang trong khung, không tràn ra ngoài
131
+ const maxW = frame ? Math.max(120, frame.width - 8) : undefined;
132
+ const left = fixed || !rect || !frame ? 0 : Math.round(Math.max(frame.left + 4, Math.min(rect.left, frame.right - 4 - Math.min(420, maxW!))));
122
133
  const editProps = { block: first, attrs: first.attrs, setAttrs: (a: Record<string, unknown>) => store.setAttrs(ids, a), blockProps: null as never, selected: true, editable: true, labels };
123
134
  const Extra = sameType && nodes.length === 1 ? type?.toolbar : undefined;
124
135
  const hasAlign = sameType && !!type?.attributes?.textAlign;
136
+ // Độ rộng (như alignwide/alignfull của WP): chỉ khối cấp cao nhất — khối lồng trong nhóm/cột theo bề rộng của khối cha
137
+ const hasWidth = sameType && !parent && WIDE_BLOCKS.includes(first.type);
138
+ // Vùng ô đang bôi đen (không gõ chữ): gộp cả vùng / xoá nội dung
139
+ const cellRange = sel.ids.length ? selectedCellRect(store, sel.ids) : null;
140
+ const cellSel = cellRange ? { ...cellRange, many: sel.ids.length > 1 } : null;
141
+ const width = first.attrs.align === "wide" || first.attrs.align === "full" ? (first.attrs.align as string) : "";
125
142
 
126
143
  const doTransform = (t: BlockTransform) => {
127
144
  const res = t.convert(ordered.map((id) => store.block(id)!));
@@ -171,7 +188,7 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
171
188
 
172
189
  return (
173
190
  <>
174
- <div className={fixed ? "ecx-toolbar is-fixed" : "ecx-toolbar"} role="toolbar" aria-label={type?.title ?? first.type} style={fixed ? undefined : { top, left }} data-block={first.id}
191
+ <div className={fixed ? "ecx-toolbar is-fixed" : "ecx-toolbar"} role="toolbar" aria-label={type?.title ?? first.type} style={fixed ? undefined : { top, left, maxWidth: maxW }} data-block={first.id}
175
192
  onKeyDown={(e) => {
176
193
  // Bàn phím trên thanh công cụ: ←/→ đi giữa các nút, Esc quay về khối
177
194
  const buttons = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>(":scope > .ecx-tool-group button:not(:disabled), :scope > .ecx-tool-group .ecx-dropdown > button"));
@@ -219,6 +236,22 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
219
236
  ))}
220
237
  </div>
221
238
  )}
239
+ {cellSel && (
240
+ <div className="ecx-tool-group" data-ecx-cell-tools>
241
+ {cellSel.many && <ToolButton label={labels.mergeCells} className="ecx-tool-wide" onClick={() => mergeRange(store, cellSel.table, cellSel.docId, cellSel.rect)}><TableCellsMerge className="ecx-icon" /><span className="ecx-tool-text">{labels.mergeCells}</span></ToolButton>}
242
+ <ToolButton label={labels.clearCells} onClick={() => clearCells(store, cellSel.table, ids)}><Eraser className="ecx-icon" /></ToolButton>
243
+ </div>
244
+ )}
245
+ {hasWidth && (
246
+ <div className="ecx-tool-group">
247
+ <Dropdown label={labels.width} trigger={<span className="ecx-tool-text" data-ecx-width={width || "default"}>{width === "full" ? <Maximize2 className="ecx-icon" /> : width === "wide" ? <MoveHorizontal className="ecx-icon" /> : <RectangleHorizontal className="ecx-icon" />}</span>}>
248
+ {(close) => ([["", RectangleHorizontal, labels.widthDefault], ["wide", MoveHorizontal, labels.widthWide], ["full", Maximize2, labels.widthFull]] as const).map(([v, I, l]) => (
249
+ <MenuItem key={v || "default"} icon={I} label={(v === width ? "✓ " : "") + l} onClick={() => { close(); if (v !== width) store.setAttrs(ids, { align: v || undefined }); }} />
250
+ ))}
251
+ </Dropdown>
252
+ </div>
253
+ )}
254
+ {nodes.length === 1 && first.inline && !type?.plain && ctx.host.ai && <div className="ecx-tool-group"><AiTools block={first} /></div>}
222
255
  {view && !type?.plain && !type?.multiline && <MarkTools view={view} onLink={() => setLink(ui.activeRich ?? sel.editing)} />}
223
256
  {listItem && (
224
257
  <div className="ecx-tool-group">
@@ -227,7 +260,7 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
227
260
  </div>
228
261
  )}
229
262
  {Extra && <div className="ecx-tool-group"><Extra {...editProps} /></div>}
230
- {nodes.length === 1 && contextTools(loc.ancestors, first.id)}
263
+ {(nodes.length === 1 || cellSel) && contextTools(loc.ancestors, first.id)}
231
264
  {nested && <div className="ecx-tool-group"><ToolButton label={labels.editOriginal} className="ecx-tool-wide" onClick={() => store.enterFocus(nested)}><PanelTop className="ecx-icon" /><span className="ecx-tool-text">{labels.editOriginal}</span></ToolButton></div>}
232
265
  <div className="ecx-tool-group">
233
266
  <Dropdown label={labels.more} trigger={<MoreVertical className="ecx-icon" />}>
@@ -380,6 +413,16 @@ export function DropIndicator() {
380
413
  }
381
414
 
382
415
  /** Hộp khoá khối: không cho di chuyển / xoá; khối chứa: khoá bố cục bên trong hoặc chỉ cho sửa nội dung. */
416
+ /** Tab / Shift+Tab xoay vòng trong hộp thoại (tự chuyển focus — WebKit mặc định không Tab tới nút nên focus thoát ra ngoài). */
417
+ function trapTab(e: ReactKeyboardEvent<HTMLElement>) {
418
+ if (e.key !== "Tab") return;
419
+ const items = [...e.currentTarget.querySelectorAll<HTMLElement>('button:not([disabled]), input:not([disabled]), select, textarea, a[href], [tabindex]:not([tabindex="-1"])')];
420
+ if (!items.length) return;
421
+ e.preventDefault();
422
+ const i = items.indexOf(e.target as HTMLElement);
423
+ items[(i + (e.shiftKey ? -1 : 1) + items.length) % items.length].focus();
424
+ }
425
+
383
426
  function LockDialog({ block, onClose }: { block: BNode; onClose(): void }) {
384
427
  const { store, labels } = useEditor();
385
428
  const lock = (block.attrs.lock as { move?: boolean; remove?: boolean } | undefined) ?? {};
@@ -389,7 +432,7 @@ function LockDialog({ block, onClose }: { block: BNode; onClose(): void }) {
389
432
  store.setAttrs([block.id], { lock: next.move || next.remove ? next : undefined });
390
433
  };
391
434
  return (
392
- <div className="ecx-modal-backdrop" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }} onKeyDown={(e) => { if (e.key === "Escape") onClose(); }}>
435
+ <div className="ecx-modal-backdrop" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }} onKeyDown={(e) => { if (e.key === "Escape") onClose(); else trapTab(e); }}>
393
436
  <div className="ecx-modal" role="dialog" aria-modal="true" aria-label={labels.lockTitle}>
394
437
  <header className="ecx-modal-header"><h2>{labels.lockTitle}</h2></header>
395
438
  <div className="ecx-lock-body">