@ecomcx/ecomweb-editor 1.25.3 → 1.26.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.
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.0",
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,25 @@ 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
+ widthDefault: "Text column",
62
+ widthWide: "Wide",
63
+ widthFull: "Full width",
45
64
  devices: "Device",
46
65
  deviceDesktop: "Desktop",
47
66
  deviceTablet: "Tablet",
@@ -119,6 +138,8 @@ export const v2 = {
119
138
  deleteRow: "Delete row",
120
139
  deleteColumn: "Delete column",
121
140
  mergeRight: "Merge with cell on the right",
141
+ mergeCells: "Merge selected cells",
142
+ clearCells: "Clear cell contents",
122
143
  mergeDown: "Merge with cell below",
123
144
  splitCell: "Split cell",
124
145
  toolbarHint: "Select a block to show its tools here",
@@ -184,4 +205,5 @@ export const v2 = {
184
205
  choiceSelect: "— Select —",
185
206
  choiceMissing: "(missing)",
186
207
  openInNewTab: "Open in new tab",
208
+ countdownNoTarget: "No end time yet — set “Target” in the sidebar (until then the website does not show this block)",
187
209
  };
@@ -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,25 @@ 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
+ widthDefault: "Theo cột chữ",
62
+ widthWide: "Rộng",
63
+ widthFull: "Toàn trang",
45
64
  devices: "Thiết bị",
46
65
  deviceDesktop: "Máy tính",
47
66
  deviceTablet: "Máy tính bảng",
@@ -119,6 +138,8 @@ export const v2 = {
119
138
  deleteRow: "Xoá hàng",
120
139
  deleteColumn: "Xoá cột",
121
140
  mergeRight: "Gộp với ô bên phải",
141
+ mergeCells: "Gộp các ô đã chọn",
142
+ clearCells: "Xoá nội dung ô",
122
143
  mergeDown: "Gộp với ô bên dưới",
123
144
  splitCell: "Tách ô",
124
145
  toolbarHint: "Chọn một khối để hiện công cụ của khối ở đây",
@@ -184,4 +205,5 @@ export const v2 = {
184
205
  choiceSelect: "— Chọn —",
185
206
  choiceMissing: "(không còn)",
186
207
  openInNewTab: "Mở trong tab mới",
208
+ 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
209
  };
@@ -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
  },
@@ -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
+ }
@@ -52,6 +52,11 @@ 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?: { run(task: string, text: string, opts?: { language?: string; instruction?: string }): Promise<string> };
55
60
  }
56
61
 
57
62
  /** 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
@@ -326,3 +326,13 @@ body.is-dragging, body.is-dragging * { cursor: grabbing !important; user-select:
326
326
  .ecx-toolbar .ecx-tool { height: 40px; min-width: 38px; }
327
327
  .ecx-movers .ecx-tool { height: 20px; min-width: 30px; }
328
328
  }
329
+
330
+ /* Hộp kết quả AI */
331
+ .ecx-ai-body { padding: 12px 16px 16px; display: flex; flex-direction: column; gap: 10px; }
332
+ .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; }
333
+ .ecx-ai-text p { margin: 0 0 .6em; } .ecx-ai-text p:last-child { margin: 0; }
334
+ .ecx-ai-wait { margin: 0; color: var(--ecx-ed-muted, #667085); animation: ecx-ai-pulse 1.2s ease-in-out infinite; }
335
+ .ecx-ai-error { margin: 0; color: #b42318; }
336
+ .ecx-ai-note { margin: 0; font-size: 12px; color: var(--ecx-ed-muted, #667085); }
337
+ @keyframes ecx-ai-pulse { 50% { opacity: .45; } }
338
+ @media (prefers-reduced-motion: reduce) { .ecx-ai-wait { animation: none; } }
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,72 @@
1
+ import { Sparkles } from "lucide-react";
2
+ import { 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 } 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={<Sparkles className="ecx-icon" />}>
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
+ }
@@ -47,12 +47,13 @@ export function useInsertOptions(): InsertOption[] {
47
47
  }, [registry, version, hidden, host.scope]);
48
48
  }
49
49
 
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. */
50
+ /** 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
51
  export function rankOptions(list: InsertOption[], query: string): InsertOption[] {
52
52
  const q = norm(query.trim());
53
53
  if (!q) return list;
54
54
  const score = (i: InsertOption) => {
55
55
  const title = norm(i.title);
56
+ if (title === q) return 4; // "/anh" → Ảnh trước Ảnh bìa, Ảnh + chữ
56
57
  if (title.startsWith(q)) return 3;
57
58
  if (title.split(/\s+/).some((w) => w.startsWith(q))) return 2;
58
59
  const words = [...title.split(/\s+/), ...norm(i.keywords).split(/\s+/)];
@@ -209,6 +210,8 @@ export function InserterPanel({ onInserted, onClose }: { onInserted?(): void; on
209
210
  const parentType = loc?.ancestors.length ? store.block(loc.ancestors[loc.ancestors.length - 1])?.type ?? null : null;
210
211
  const options = all.filter((o) => canContain(parentType, o.type));
211
212
  const panelRef = useRef<HTMLDivElement>(null);
213
+ // 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
214
+ useEffect(() => { panelRef.current?.querySelector<HTMLInputElement>("input")?.focus({ preventScroll: true }); }, []);
212
215
  // 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
216
  useEffect(() => {
214
217
  if (!onClose) return;
@@ -240,7 +243,11 @@ export function InserterPanel({ onInserted, onClose }: { onInserted?(): void; on
240
243
  ctx.prefs.countInsert(o.type);
241
244
  const cur = store.currentIds[store.currentIds.length - 1];
242
245
  // Đ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 });
246
+ const curLoc = cur ? store.locate(cur) : null;
247
+ const curBlock = cur ? store.block(cur) : null;
248
+ // Đ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
249
+ if (curLoc && curBlock && Array.isArray(curBlock.content) && curBlock.content.length === 0 && canContain(curBlock.type, node.type)) store.insert(curLoc.docId, cur, 0, [node]);
250
+ else if (cur && curLoc) store.insertAfter(cur, [node], { replaceEmpty: cur !== lastInserted.current });
244
251
  else {
245
252
  const docId = store.activeDocId;
246
253
  store.insert(docId, null, store.getState().docs[docId].blocks.length, [node]);
@@ -75,7 +75,7 @@ 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
81
  useEffect(() => {
@@ -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">