@ecomcx/ecomweb-editor 1.32.0 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/package.json +3 -3
  2. package/src/locales/en/attrs.ts +2 -1
  3. package/src/locales/en/background.ts +5 -0
  4. package/src/locales/en/bindings.ts +5 -1
  5. package/src/locales/en/block-desc.ts +5 -11
  6. package/src/locales/en/block-style.ts +17 -6
  7. package/src/locales/en/block-titles.ts +38 -15
  8. package/src/locales/en/blocks.ts +37 -6
  9. package/src/locales/en/columns.ts +1 -0
  10. package/src/locales/en/controls.ts +1 -1
  11. package/src/locales/en/hints.ts +315 -12
  12. package/src/locales/en/index.ts +3 -1
  13. package/src/locales/en/layout.ts +13 -0
  14. package/src/locales/en/motion.ts +16 -0
  15. package/src/locales/en/palette.ts +8 -0
  16. package/src/locales/en/parts.ts +2 -1
  17. package/src/locales/en/pattern-overrides.ts +14 -0
  18. package/src/locales/en/placeholders.ts +9 -3
  19. package/src/locales/en/v2.ts +2 -0
  20. package/src/locales/vi/attrs.ts +3 -2
  21. package/src/locales/vi/background.ts +5 -0
  22. package/src/locales/vi/bindings.ts +5 -1
  23. package/src/locales/vi/block-desc.ts +8 -14
  24. package/src/locales/vi/block-style.ts +18 -7
  25. package/src/locales/vi/block-titles.ts +48 -25
  26. package/src/locales/vi/blocks.ts +37 -6
  27. package/src/locales/vi/columns.ts +1 -0
  28. package/src/locales/vi/controls.ts +1 -1
  29. package/src/locales/vi/hints.ts +315 -12
  30. package/src/locales/vi/index.ts +3 -1
  31. package/src/locales/vi/layout.ts +13 -0
  32. package/src/locales/vi/motion.ts +16 -0
  33. package/src/locales/vi/palette.ts +8 -0
  34. package/src/locales/vi/parts.ts +2 -1
  35. package/src/locales/vi/pattern-overrides.ts +14 -0
  36. package/src/locales/vi/placeholders.ts +10 -4
  37. package/src/locales/vi/v2.ts +2 -0
  38. package/src/v2/blocks/columns-inspector.tsx +11 -2
  39. package/src/v2/blocks/index.ts +9 -6
  40. package/src/v2/blocks/layout-options.tsx +80 -0
  41. package/src/v2/blocks/layout.tsx +349 -106
  42. package/src/v2/blocks/media.tsx +51 -21
  43. package/src/v2/blocks/resize.tsx +50 -19
  44. package/src/v2/blocks/social-icons.ts +22 -0
  45. package/src/v2/blocks/text.tsx +12 -50
  46. package/src/v2/blocks/theme.tsx +62 -29
  47. package/src/v2/blocks/tools.tsx +24 -2
  48. package/src/v2/blocks/widgets.tsx +84 -28
  49. package/src/v2/canvas/block-list.tsx +36 -5
  50. package/src/v2/canvas/canvas-css.ts +95 -7
  51. package/src/v2/canvas/canvas.tsx +65 -9
  52. package/src/v2/canvas/dnd.ts +7 -0
  53. package/src/v2/canvas/variation-picker.tsx +63 -0
  54. package/src/v2/context.tsx +48 -0
  55. package/src/v2/core/bindings.ts +6 -1
  56. package/src/v2/core/block-presets.ts +10 -0
  57. package/src/v2/core/clipboard.ts +5 -5
  58. package/src/v2/core/host.ts +3 -1
  59. package/src/v2/core/model.ts +6 -6
  60. package/src/v2/core/registry.ts +15 -0
  61. package/src/v2/core/store.ts +9 -9
  62. package/src/v2/core/structure.ts +1 -3
  63. package/src/v2/editor.css +74 -0
  64. package/src/v2/editor.tsx +22 -7
  65. package/src/v2/text/rich-text.tsx +20 -5
  66. package/src/v2/ui/ai-markdown.ts +52 -0
  67. package/src/v2/ui/ai.tsx +81 -14
  68. package/src/v2/ui/attr-form.tsx +45 -7
  69. package/src/v2/ui/attr-hints.ts +151 -19
  70. package/src/v2/ui/background-panel.tsx +22 -0
  71. package/src/v2/ui/bg-video-preview.tsx +7 -0
  72. package/src/v2/ui/bindings.tsx +9 -1
  73. package/src/v2/ui/block-icons.tsx +3 -10
  74. package/src/v2/ui/block-live-preview.tsx +21 -0
  75. package/src/v2/ui/block-style-panel.tsx +3 -1
  76. package/src/v2/ui/command-palette.tsx +125 -0
  77. package/src/v2/ui/icon-picker.tsx +88 -21
  78. package/src/v2/ui/icon-svg.tsx +21 -0
  79. package/src/v2/ui/inserter.tsx +72 -17
  80. package/src/v2/ui/inspector.tsx +12 -6
  81. package/src/v2/ui/layout-panel.tsx +1 -1
  82. package/src/v2/ui/motion-panel.tsx +22 -13
  83. package/src/v2/ui/option-thumbs.tsx +81 -0
  84. package/src/v2/ui/pattern-library.tsx +2 -1
  85. package/src/v2/ui/pattern-overrides.tsx +67 -0
  86. package/src/v2/ui/placeholders.tsx +21 -2
  87. package/src/v2/ui/preset-bar.tsx +5 -5
  88. package/src/v2/ui/style-supports.ts +2 -3
  89. package/src/v2/ui/style-tab.tsx +83 -20
  90. package/src/v2/ui/toolbar.tsx +40 -6
  91. package/src/v2/ui/transform-panel.tsx +77 -0
@@ -593,19 +593,19 @@ export class EditorStore {
593
593
  const b = loc.block;
594
594
  const docId = loc.docId;
595
595
  // Khối chứa bị khoá thêm khối: Enter không tạo khối mới
596
- const newParent = loc.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0 ? this.locate(loc.parent.id)?.parent?.id ?? null : loc.parent?.id ?? null;
596
+ const newParent = loc.parent && (loc.parent.type === "listItem") && loc.index === 0 ? this.locate(loc.parent.id)?.parent?.id ?? null : loc.parent?.id ?? null;
597
597
  if (!this.canInsertInto(newParent)) return;
598
598
  let inline = b.inline!;
599
599
  if (selectionEnd > offset) inline = joinInline(splitInline(inline, offset)[0], splitInline(inline, selectionEnd)[1]);
600
600
  const len = inlineLength(inline);
601
- const item = loc.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0 ? this.locate(loc.parent.id) : null;
601
+ const item = loc.parent && (loc.parent.type === "listItem") && loc.index === 0 ? this.locate(loc.parent.id) : null;
602
602
 
603
603
  if (item) {
604
604
  // Mục danh sách trống: thụt ra (lồng) hoặc thoát khỏi danh sách
605
605
  if (!len && item.block.content!.length === 1) return this.outdentItem(item.block.id, true);
606
606
  const [before, after] = splitInline(inline, offset);
607
607
  const para = makeBlock("paragraph", {}, after);
608
- const newItem = makeBlock(item.block.type, item.block.type === "taskItem" ? { checked: false } : {}, [para]);
608
+ const newItem = makeBlock(item.block.type, {}, [para]);
609
609
  const blocks = this.state.docs[docId].blocks;
610
610
  let next = mapBlock(blocks, id, (x) => ({ ...x, inline: before }));
611
611
  next = insertBlocks(next, item.parent!.id, item.index + 1, [newItem]);
@@ -640,7 +640,7 @@ export class EditorStore {
640
640
  const blocks = this.state.docs[docId].blocks;
641
641
  const b = loc.block;
642
642
  // Khối không xoá được (khoá): Backspace ở đầu chỉ đưa con trỏ về khối chữ trước
643
- if (!this.canRemove(id) || (loc.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0 && !this.canRemove(loc.parent.id))) {
643
+ if (!this.canRemove(id) || (loc.parent && (loc.parent.type === "listItem") && loc.index === 0 && !this.canRemove(loc.parent.id))) {
644
644
  const order = flatten(blocks).filter((x) => x.inline);
645
645
  const prev = order[order.findIndex((x) => x.id === id) - 1];
646
646
  if (prev) this.focusText(prev.id, -1);
@@ -648,7 +648,7 @@ export class EditorStore {
648
648
  }
649
649
 
650
650
  // Đầu mục danh sách: nối vào mục trước, hoặc (mục đầu) thụt ra
651
- if (loc.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0) {
651
+ if (loc.parent && (loc.parent.type === "listItem") && loc.index === 0) {
652
652
  const item = this.locate(loc.parent.id)!;
653
653
  const prevItem = item.index > 0 ? item.parent!.content![item.index - 1] : null;
654
654
  if (!prevItem) return this.outdentItem(item.block.id, true);
@@ -730,7 +730,7 @@ export class EditorStore {
730
730
  blocks = mapBlock(blocks, prev.id, (pi) => {
731
731
  const kids = pi.content ?? [];
732
732
  const last = kids[kids.length - 1];
733
- if (last && (last.type === "bulletList" || last.type === "orderedList" || last.type === "taskList")) {
733
+ if (last && (last.type === "bulletList" || last.type === "orderedList")) {
734
734
  return { ...pi, content: [...kids.slice(0, -1), { ...last, content: [...last.content!, loc.block] }] };
735
735
  }
736
736
  return { ...pi, content: [...kids, makeBlock(listType, {}, [loc.block])] };
@@ -744,7 +744,7 @@ export class EditorStore {
744
744
  const loc = this.locate(itemId);
745
745
  if (!loc || !loc.parent || !this.canMove(itemId) || !this.canRemove(itemId)) return false;
746
746
  const list = this.locate(loc.parent.id)!;
747
- const outerItem = list.parent && (list.parent.type === "listItem" || list.parent.type === "taskItem") ? this.locate(list.parent.id) : null;
747
+ const outerItem = list.parent && (list.parent.type === "listItem") ? this.locate(list.parent.id) : null;
748
748
  const docId = loc.docId;
749
749
  const firstId = loc.block.content![0].id;
750
750
  const caret: Caret = this.lastCaret && this.lastCaret.id === firstId ? this.lastCaret : { id: firstId, offset: 0 };
@@ -765,9 +765,9 @@ export class EditorStore {
765
765
  }
766
766
 
767
767
  /** Khối chứa thoát ra được bằng Enter ở đoạn trống cuối / Backspace ở đầu. */
768
- const ESCAPE_CONTAINERS = new Set(["blockquote", "callout", "pullquote", "details"]);
768
+ const ESCAPE_CONTAINERS = new Set(["blockquote", "details"]);
769
769
  /** Enter ở cuối khối này tạo khối gì. */
770
- const SPLIT_AS: Record<string, string> = { heading: "paragraph", codeBlock: "paragraph", preformatted: "paragraph" };
770
+ const SPLIT_AS: Record<string, string> = { heading: "paragraph", codeBlock: "paragraph" };
771
771
 
772
772
  const firstText = (b: BNode): string | null => (b.inline ? b.id : b.content ? (b.content.map(firstText).find(Boolean) ?? null) : null);
773
773
  const firstTextDeep = (b: BNode): BNode | null => {
@@ -26,8 +26,6 @@ const RULES: Record<string, StructureRule> = {
26
26
  bulletList: { allowedChildren: ["listItem"], wrapChildrenWith: "listItem", removeWhenEmpty: true },
27
27
  orderedList: { allowedChildren: ["listItem"], wrapChildrenWith: "listItem", removeWhenEmpty: true },
28
28
  listItem: { parents: ["bulletList", "orderedList"], wrapSelfWith: "bulletList", required: p, firstChild: "paragraph" },
29
- taskList: { allowedChildren: ["taskItem"], wrapChildrenWith: "taskItem", removeWhenEmpty: true },
30
- taskItem: { parents: ["taskList"], wrapSelfWith: "taskList", required: p, firstChild: "paragraph" },
31
29
  // Bộ cột rỗng (vừa chèn, chưa chọn bố cục) giữ lại như bảng rỗng: trình soạn hiện lưới chọn bố cục cột
32
30
  columns: { allowedChildren: ["column"], wrapChildrenWith: "column" },
33
31
  column: { parents: ["columns"], wrapSelfWith: "columns" },
@@ -41,7 +39,7 @@ const RULES: Record<string, StructureRule> = {
41
39
  };
42
40
 
43
41
  /** Mục danh sách / việc chỉ nhận chữ và danh sách lồng: khối lớn (bảng, ảnh, nhóm…) chèn mới thì phải ra ngoài danh sách. */
44
- export const leavesItem = (parentType: string | null | undefined, child: string) => (parentType === "listItem" || parentType === "taskItem") && !/^(paragraph|bulletList|orderedList|taskList)$/.test(child);
42
+ export const leavesItem = (parentType: string | null | undefined, child: string) => (parentType === "listItem") && !/^(paragraph|bulletList|orderedList)$/.test(child);
45
43
 
46
44
  const extra = new Map<string, StructureRule>();
47
45
  export function setStructureRule(type: string, rule: StructureRule | null) {
package/src/v2/editor.css CHANGED
@@ -372,6 +372,8 @@ body.is-dragging, body.is-dragging * { cursor: grabbing !important; user-select:
372
372
  .ecx-state-tabs .ecx-seg-btn.is-active { background: var(--ecx-ed-panel); color: var(--ecx-ed-accent); box-shadow: 0 1px 2px rgb(14 40 58 / .12); }
373
373
  .ecx-seg.is-text { display: flex; flex-wrap: wrap; width: 100%; }
374
374
  .ecx-seg.is-text .ecx-seg-btn { flex: 1 1 auto; font: 500 12.5px var(--ecx-ed-font); white-space: nowrap; }
375
+ .ecx-css-input { font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; resize: vertical; }
376
+ .ecx-field-warn { margin: 4px 0 0; padding-left: 16px; color: #b45309; font-size: 12px; }
375
377
  .ecx-field-help { display: block; margin-top: 4px; font-size: 12px; line-height: 1.4; color: var(--ecx-ed-muted); }
376
378
  .ecx-range-row { display: flex; align-items: center; gap: 10px; }
377
379
  .ecx-range-row input[type=range] { flex: 1; accent-color: var(--ecx-ed-accent); }
@@ -529,6 +531,14 @@ body.is-dragging .ecx-section-adder { display: none; }
529
531
  .ecx-icon-pop { position: absolute; z-index: 25; top: calc(100% + 6px); left: 0; right: 0; display: flex; flex-direction: column; gap: 8px; padding: 10px; border: 1px solid var(--ecx-ed-line); border-radius: 10px; background: var(--ecx-ed-panel); box-shadow: var(--ecx-ed-shadow); animation: ecx-pop .1s linear; }
530
532
  .ecx-icon-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; max-height: 220px; overflow: auto; }
531
533
  .ecx-icon-cell { display: grid; place-items: center; aspect-ratio: 1; border: 1px solid transparent; border-radius: 7px; background: none; color: var(--ecx-ed-fg); cursor: pointer; }
534
+ .ecx-icon-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--ecx-ed-line); }
535
+ .ecx-icon-tab { flex: 1; padding: 6px 8px; border: 0; border-bottom: 2px solid transparent; background: none; color: var(--ecx-ed-muted, inherit); font: 600 12px var(--ecx-ui-font); cursor: pointer; }
536
+ .ecx-icon-tab.is-active { color: var(--ecx-ed-accent); border-bottom-color: var(--ecx-ed-accent); }
537
+ .ecx-icon-cell-text { font-size: 10px; line-height: 1.1; padding: 2px; text-align: center; }
538
+ .ecx-icon-svg { display: flex; flex-direction: column; gap: 8px; }
539
+ .ecx-icon-svg textarea { font: 12px/1.4 ui-monospace, monospace; resize: vertical; }
540
+ .ecx-icon-svg-row { display: flex; align-items: center; gap: 12px; }
541
+ .ecx-icon-svg-preview { margin-left: auto; display: grid; place-items: center; width: 40px; height: 40px; border: 1px dashed var(--ecx-ed-line); border-radius: 8px; }
532
542
  .ecx-icon-cell:hover { background: var(--ecx-ed-subtle); }
533
543
  .ecx-icon-cell.is-active { border-color: var(--ecx-ed-accent); background: var(--ecx-ed-accent-soft); color: var(--ecx-ed-accent); }
534
544
 
@@ -576,6 +586,8 @@ body.is-dragging .ecx-section-adder { display: none; }
576
586
 
577
587
  /* Hàng sửa một mục của danh sách (chữ; icon + liên kết + xoá) */
578
588
  .ecx-item-row { display: flex; flex-direction: column; gap: 4px; padding: 8px; border: 1px solid var(--ecx-ed-line); border-radius: 8px; }
589
+ .ecx-item-colors { grid-column: 1 / -1; display: flex; gap: 6px; }
590
+ .ecx-item-colors > * { flex: 1; min-width: 0; }
579
591
  .ecx-item-row-sub { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 28px; gap: 4px; align-items: center; }
580
592
 
581
593
  .ecx-quick-colors { display: flex; flex-wrap: wrap; gap: 8px; padding: 8px; max-width: 200px; }
@@ -592,3 +604,65 @@ body.is-dragging .ecx-section-adder { display: none; }
592
604
  .ecx-textshadow { display: grid; gap: 10px; margin-top: 10px; }
593
605
  .ecx-textshadow-row { display: grid; gap: 4px; font-size: 12px; color: var(--ecx-ed-muted, #5d6a75); }
594
606
  .ecx-textshadow-row .ecx-range { width: 100%; }
607
+
608
+ /* Bố cục chọn sẵn: thẻ có hình thu nhỏ (bảng phải + ô chọn lúc vừa chèn) */
609
+ .ecx-layout-section { margin-bottom: 12px; }
610
+ .ecx-variations { display: grid; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); gap: 8px; margin-top: 6px; }
611
+ .ecx-variation { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 8px 6px 6px; border: 1px solid var(--ecx-ed-line); border-radius: 8px; background: var(--ecx-ed-panel); color: var(--ecx-ed-fg); font: 12px/1.25 var(--ecx-ed-font); cursor: pointer; transition: border-color .05s linear; }
612
+ .ecx-variation:hover { border-color: var(--ecx-ed-accent); }
613
+ .ecx-variation.is-active { border-color: var(--ecx-ed-accent); background: var(--ecx-ed-accent-soft); box-shadow: 0 0 0 1px var(--ecx-ed-accent); }
614
+ .ecx-vthumb { width: 100%; height: auto; display: block; }
615
+ .ecx-vthumb rect { fill: color-mix(in srgb, currentColor 18%, transparent); }
616
+ .ecx-vthumb rect.is-box, .ecx-vthumb polygon.is-box { fill: transparent; stroke: color-mix(in srgb, currentColor 32%, transparent); stroke-width: 1.2; }
617
+ .ecx-vthumb .is-accent { fill: var(--ecx-ed-accent); stroke: none; }
618
+ .ecx-vthumb rect.is-box.is-accent { fill: transparent; stroke: var(--ecx-ed-accent); }
619
+ .ecx-vthumb path.is-line { fill: none; stroke: var(--ecx-ed-accent); stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
620
+
621
+ /* Mục con đang chọn (Icon List…): hàng được tô, chỉ hàng này mở icon / liên kết */
622
+ .ecx-item-row.is-active { border-color: var(--ecx-ed-accent); background: var(--ecx-ed-accent-soft); }
623
+ .ecx-item-row-head { display: flex; align-items: center; gap: 6px; }
624
+ .ecx-item-row-head .ecx-input { flex: 1; min-width: 0; }
625
+ .ecx-item-n { flex: none; width: 20px; height: 20px; border-radius: 50%; background: var(--ecx-ed-subtle); color: var(--ecx-ed-muted); font: 600 11px/20px var(--ecx-ed-font); text-align: center; }
626
+ .ecx-item-row.is-active .ecx-item-n { background: var(--ecx-ed-accent); color: #fff; }
627
+
628
+ /* Xem trước thật của khối ở bảng chèn */
629
+ .ecx-block-preview { width: 320px; }
630
+ .ecx-block-preview-live { grid-column: 1 / -1; position: relative; height: 190px; overflow: hidden; border: 1px solid var(--ecx-ed-line); border-radius: 8px; background: #fff; pointer-events: none; }
631
+ .ecx-block-preview-live-inner { transform-origin: 0 0; }
632
+ /* Chọn icon ngay trên thanh công cụ của khối: lưới icon nằm trong menu thả (Dropdown) */
633
+ .ecx-tool-icon-pop { display: grid; gap: 8px; width: 288px; padding: 8px; }
634
+ .ecx-tool-icon-pop .ecx-icon-grid { max-height: 220px; overflow: auto; }
635
+
636
+ /* Hộp Viết bằng AI: gợi ý nhanh, tuỳ chọn giọng văn / độ dài, kết quả đúng dạng sẽ chèn */
637
+ .ecx-ai-chips { display: flex; flex-wrap: wrap; gap: 6px; }
638
+ .ecx-ai-opts { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
639
+ .ecx-ai-opt { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--ecx-ed-muted, #667085); }
640
+ .ecx-ai-text h2, .ecx-ai-text h3, .ecx-ai-text h4 { margin: .9em 0 .35em; line-height: 1.3; } .ecx-ai-text h2 { font-size: 1.15em; } .ecx-ai-text h3, .ecx-ai-text h4 { font-size: 1.05em; }
641
+ .ecx-ai-text h2:first-child, .ecx-ai-text h3:first-child { margin-top: 0; }
642
+ .ecx-ai-text ul, .ecx-ai-text ol { margin: 0 0 .6em; padding-left: 1.3em; }
643
+
644
+ /* Ô chọn bằng hình (thẻ icon hai lớp): hiệu ứng chuyển động, bóng, khung icon… */
645
+ .ecx-pick-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; width: 100%; }
646
+ .ecx-pick { display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 6px 4px 5px; border: 1px solid var(--ecx-ed-line); border-radius: 8px; background: var(--ecx-ed-panel); color: var(--ecx-ed-fg); font: inherit; font-size: 11px; line-height: 1.2; cursor: pointer; transition: border-color .05s linear, background .05s linear; }
647
+ .ecx-pick:hover { border-color: var(--ecx-ed-accent); }
648
+ .ecx-pick.is-active { border-color: var(--ecx-ed-accent); background: var(--ecx-ed-accent-soft); box-shadow: inset 0 0 0 1px var(--ecx-ed-accent); }
649
+ .ecx-pick:focus-visible { outline: 2px solid var(--ecx-ed-accent); outline-offset: 1px; }
650
+ .ecx-pick-thumb { width: 100%; max-width: 72px; height: auto; }
651
+ .ecx-pick-thumb .is-solid { fill: var(--ecx-ed-accent); }
652
+ .ecx-pick-thumb .is-ghost { fill: color-mix(in srgb, var(--ecx-ed-accent) 14%, transparent); stroke: var(--ecx-ed-accent); stroke-width: 1.2; stroke-dasharray: 3 2.5; }
653
+ .ecx-pick-thumb .is-arrow { stroke: var(--ecx-ed-fg); stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; opacity: .7; }
654
+ .ecx-pick-thumb .is-glyph { fill: #fff; }
655
+ .ecx-pick-label { max-width: 100%; overflow-wrap: anywhere; text-align: center; }
656
+
657
+ /* Bảng lệnh */
658
+ .ecx-palette-backdrop { position: fixed; inset: 0; z-index: 90; display: flex; justify-content: center; align-items: flex-start; padding-top: 12vh; background: rgb(15 23 42 / .35); }
659
+ .ecx-palette { width: min(640px, calc(100vw - 24px)); max-height: 70vh; display: flex; flex-direction: column; border: 1px solid var(--ecx-ed-line); border-radius: 14px; background: var(--ecx-ed-panel); box-shadow: 0 24px 60px rgb(15 23 42 / .28); overflow: hidden; font: 14px var(--ecx-ui-font); color: var(--ecx-ed-fg); }
660
+ .ecx-palette-input { display: flex; align-items: center; gap: 10px; padding: 0 14px; border-bottom: 1px solid var(--ecx-ed-line); }
661
+ .ecx-palette-input input { flex: 1; min-width: 0; height: 52px; border: 0; outline: 0; background: transparent; font: inherit; font-size: 15px; color: inherit; }
662
+ .ecx-palette-list { overflow: auto; padding: 6px; }
663
+ .ecx-palette-group { padding: 8px 10px 4px; font-size: 11px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--ecx-ed-muted, #6b7785); }
664
+ .ecx-palette-item { display: flex; align-items: center; justify-content: space-between; gap: 12px; width: 100%; padding: 9px 10px; border: 0; border-radius: 8px; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
665
+ .ecx-palette-item.is-active { background: var(--ecx-ed-accent-soft); color: var(--ecx-ed-accent); }
666
+ .ecx-palette-item kbd { font: 11px ui-monospace, monospace; padding: 2px 6px; border: 1px solid var(--ecx-ed-line); border-radius: 5px; color: var(--ecx-ed-muted, #6b7785); }
667
+ .ecx-palette-empty { margin: 0; padding: 20px; text-align: center; color: var(--ecx-ed-muted, #6b7785); }
668
+ .ecx-palette-foot { padding: 8px 14px; border-top: 1px solid var(--ecx-ed-line); font-size: 12px; color: var(--ecx-ed-muted, #6b7785); }
package/src/v2/editor.tsx CHANGED
@@ -1,7 +1,7 @@
1
- import { ensurePresets } from "./core/block-presets";
1
+ import { ensurePresets, localBlockPresets } from "./core/block-presets";
2
2
  import type { RichNode } from "@ecomcx/ecomweb-content";
3
- import { normalizeContent } from "@ecomcx/ecomweb-content";
4
- import { ListTree, Monitor, Plus, Redo2, Smartphone, Tablet, Undo2, X, PanelRight, ZoomOut } from "lucide-react";
3
+ import { normalizeContent, CONTENT_VERSION } from "@ecomcx/ecomweb-content";
4
+ import { Command as CommandIcon, ListTree, Monitor, Plus, Redo2, Smartphone, Tablet, Undo2, X, PanelRight, ZoomOut } from "lucide-react";
5
5
  import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
6
6
  import { coreBlockTypes, registerCoreBlocks } from "./blocks";
7
7
  import { registeredPatterns, syncPluginBlocks } from "./blocks/compat";
@@ -11,6 +11,7 @@ import { Canvas, type Device } from "./canvas/canvas";
11
11
  import { EditorContext, EditorUi, useEditor, useEditorState, useUiTick, type EditorContextValue } from "./context";
12
12
  import type { EditorHost } from "./core/host";
13
13
  import { InserterPanel, InserterPopover } from "./ui/inserter";
14
+ import { CommandPalette } from "./ui/command-palette";
14
15
  import { SectionAdder } from "./ui/section-adder";
15
16
  import { AiWrite } from "./ui/ai";
16
17
  import { labelsV2, type V2Labels } from "./labels";
@@ -43,7 +44,7 @@ export function splitContent(value: unknown): { blocks: BNode[]; extra: Array<{
43
44
  }
44
45
  /** Khối → nội dung lưu (ContentDoc chuẩn của CMS). */
45
46
  export function contentFromBlocks(blocks: BNode[], extra: Array<{ type: string; data: unknown; id?: string }> = []) {
46
- return { version: 1, blocks: [{ type: "richtext", data: docFromBlocks(blocks) }, ...extra] };
47
+ return { version: CONTENT_VERSION, blocks: [{ type: "richtext", data: docFromBlocks(blocks) }, ...extra] };
47
48
  }
48
49
 
49
50
  export interface EditorProviderProps {
@@ -93,6 +94,7 @@ export function EditorProvider({ store: given, value, kind, title, host = {}, la
93
94
  store.setFrame("frame");
94
95
  }, [frame, store]);
95
96
  const ui = useMemo(() => new EditorUi(), []);
97
+ ui.currentIds = () => store.currentIds;
96
98
  const ownPrefs = useMemo(() => (givenPrefs ? null : new PrefsStore(prefsStorage)), [givenPrefs, prefsStorage]);
97
99
  const prefs = givenPrefs ?? ownPrefs!;
98
100
  // Đang mở trình soạn: focus không ở ô nhập nào (vd Tab ra khỏi khung soạn) thì Backspace / ⌘← / ⌘→ là lệnh quay lại /
@@ -109,7 +111,7 @@ export function EditorProvider({ store: given, value, kind, title, host = {}, la
109
111
  // Khối của plugin (registerBlock) + mẫu có sẵn của lõi
110
112
  useEffect(() => syncPluginBlocks(registry), [registry]);
111
113
  // Kiểu đặt sẵn / mặc định khi chèn: nạp ngay khi mở trình soạn (khối chèn đầu tiên đã nhận mặc định)
112
- useEffect(() => ensurePresets(host.blockPresets?.load), [host]);
114
+ useEffect(() => ensurePresets((host.blockPresets ?? localBlockPresets).load), [host]);
113
115
  useEffect(() => { registerCoreBindingSources(allLabels.lang); }, [allLabels.lang]);
114
116
  useEffect(() => { if (!registeredPatterns().some((p) => p.name.startsWith("core/"))) registerCorePatterns(allLabels.lang); }, [allLabels.lang]);
115
117
  const ctx: EditorContextValue = useMemo(() => ({ store, registry, host, labels: allLabels, ui, prefs }), [store, registry, host, allLabels, ui, prefs]);
@@ -181,8 +183,12 @@ export function BlockEditor({ className, onSave, header, actions, menuExtra, can
181
183
 
182
184
  function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefore, defaultDevice, blockStyles, saveHandle, onDirtyChange }: Pick<BlockEditorProps, "saveHandle" | "onDirtyChange" | "className" | "onSave" | "header" | "actions" | "menuExtra" | "canvasBefore" | "defaultDevice" | "blockStyles">) {
183
185
  const ctx = useEditor();
186
+ const previewRender = (value: { version: number; blocks: unknown[] }) => <EditorProvider value={value} kind="pattern-preview" registry={ctx.registry} labels={ctx.labels} host={{ ...ctx.host, documents: undefined, ai: undefined }}><Canvas preview /></EditorProvider>;
187
+ ctx.ui.renderPreview = previewRender;
184
188
  const { store, labels } = ctx;
185
189
  const p = usePrefs(ctx.prefs);
190
+ const [palette, setPalette] = useState(false);
191
+ const [inserterQuery, setInserterQuery] = useState<string | undefined>(undefined);
186
192
  const [left, setLeft] = useState<"inserter" | "list" | null>(() => (ctx.prefs.get().showListView ? "list" : null));
187
193
  useEffect(() => { ctx.ui.browseAll = () => setLeft("inserter"); return () => { ctx.ui.browseAll = null; }; }, [ctx.ui]);
188
194
  // Điện thoại: bảng bên phải mở đè lên canvas nên mặc định đóng (mở bằng nút ở thanh trên)
@@ -218,6 +224,10 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
218
224
  const onKey = (e: KeyboardEvent) => {
219
225
  const mod = e.metaKey || e.ctrlKey;
220
226
  if (mod && e.key.toLowerCase() === "s") { e.preventDefault(); void saveRef.current(); }
227
+ // Bảng lệnh: ⌘⇧P luôn mở; ⌘K chỉ khi không đang gõ chữ (trong ô chữ ⌘K là chèn liên kết)
228
+ const t = e.target as HTMLElement | null;
229
+ const typing = !!t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));
230
+ if (mod && ((e.shiftKey && e.key.toLowerCase() === "p") || (!e.shiftKey && !e.altKey && e.key.toLowerCase() === "k" && !typing))) { e.preventDefault(); setPalette(true); }
221
231
  // ⌘⇧⌥M: đổi soạn trực quan ↔ soạn mã
222
232
  if (mod && e.shiftKey && e.altKey && e.code === "KeyM") { e.preventDefault(); ctx.prefs.set({ mode: ctx.prefs.get().mode === "code" ? "visual" : "code" }); }
223
233
  };
@@ -235,10 +245,11 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
235
245
  <div className="ecx-topbar-start">
236
246
  {header}
237
247
  {!p.distractionFree && <ToolButton label={labels.addBlock} active={left === "inserter"} className="ecx-tool-primary" onClick={() => setLeft(left === "inserter" ? null : "inserter")}>{left === "inserter" ? <X className="ecx-icon" /> : <Plus className="ecx-icon" />}</ToolButton>}
248
+ {!p.distractionFree && <ToolButton label={`${labels.commandPalette} (${/Mac|iPhone|iPad/.test(typeof navigator === "undefined" ? "" : navigator.platform) ? "⌘⇧P" : "Ctrl+Shift+P"})`} onClick={() => setPalette(true)}><CommandIcon className="ecx-icon" /></ToolButton>}
238
249
  <ToolButton label={labels.undo} disabled={!store.canUndo} onClick={() => store.undo()}><Undo2 className="ecx-icon" /></ToolButton>
239
250
  <ToolButton label={labels.redo} disabled={!store.canRedo} onClick={() => store.redo()}><Redo2 className="ecx-icon" /></ToolButton>
240
251
  {!p.distractionFree && <ToolButton label={labels.listView} active={left === "list"} onClick={() => setLeft(left === "list" ? null : "list")}><ListTree className="ecx-icon" /></ToolButton>}
241
- {!p.distractionFree && p.mode === "visual" && <PatternLibraryButton renderPreview={(value) => <EditorProvider value={value} kind="pattern-preview" registry={ctx.registry} labels={ctx.labels} host={{ ...ctx.host, documents: undefined, ai: undefined }}><Canvas /></EditorProvider>} />}
252
+ {!p.distractionFree && p.mode === "visual" && <PatternLibraryButton renderPreview={previewRender} />}
242
253
  <FrameToggle />
243
254
  {p.mode === "visual" && <ZoomToggle />}
244
255
  </div>
@@ -254,10 +265,14 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
254
265
  )}
255
266
  </div>
256
267
  </div>
268
+ <CommandPalette open={palette} onClose={() => setPalette(false)} actions={{
269
+ save: () => void saveRef.current(), toggleList: () => setLeft((l) => (l === "list" ? null : "list")), toggleSettings: () => setRight((r) => !r),
270
+ openInserter: (q) => { setInserterQuery(q); setLeft("inserter"); },
271
+ }} />
257
272
  {error && <div className="ecx-notice is-error" role="alert">{error}</div>}
258
273
  {p.fixedToolbar && p.mode === "visual" && <div className="ecx-fixed-toolbar"><BlockToolbar placement="fixed" /></div>}
259
274
  <div className="ecx-body">
260
- {left && !p.distractionFree && <aside className="ecx-left">{left === "inserter" ? <InserterPanel onClose={() => setLeft(null)} onInserted={() => { /* Điện thoại: bảng đè lên canvas nên chèn xong thì đóng để tiếp tục soạn */ if (window.innerWidth <= 640) setLeft(null); }} /> : <ListView onClose={() => setLeft(null)} />}</aside>}
275
+ {left && !p.distractionFree && <aside className="ecx-left">{left === "inserter" ? <InserterPanel key={inserterQuery ?? ""} initialQuery={inserterQuery} onClose={() => setLeft(null)} onInserted={() => { /* Điện thoại: bảng đè lên canvas nên chèn xong thì đóng để tiếp tục soạn */ if (window.innerWidth <= 640) setLeft(null); }} /> : <ListView onClose={() => setLeft(null)} />}</aside>}
261
276
  <main className="ecx-main">{p.mode === "code" ? <CodeEditor /> : <Canvas before={canvasBefore} />}</main>
262
277
  {right && !p.distractionFree && <aside className="ecx-right"><Inspector blockStyles={blockStyles} /></aside>}
263
278
  </div>
@@ -77,6 +77,7 @@ export function RichText(props: RichTextProps) {
77
77
  v.updateState(next);
78
78
  syncEmpty(v);
79
79
  if (!tr.docChanged || tr.getMeta("external")) return;
80
+ ui.fresh.delete(propsRef.current.blockId);
80
81
  const inline = docToInline(next.doc);
81
82
  lastValue.current = inline;
82
83
  const p = propsRef.current;
@@ -94,14 +95,29 @@ export function RichText(props: RichTextProps) {
94
95
  handlePaste: (v, event) => (propsRef.current.onChange ? false : pasteIntoBlock(ctx, propsRef.current.blockId, v, event)),
95
96
  handleDOMEvents: {
96
97
  // Kéo chuột từ ô này sang khối chữ khác → chọn chữ qua nhiều khối
98
+ // Chữ mẫu chưa sửa: nhả chuột xong mà chỉ có con trỏ (không kéo chọn) → chọn hết để gõ là thay
99
+ mouseup: (v) => {
100
+ const p = propsRef.current;
101
+ if (ui.fresh.has(p.blockId) && v.state.selection.empty && v.state.doc.content.size > 0) setTimeout(() => { if (ui.fresh.has(p.blockId) && v.hasFocus() && v.state.selection.empty) v.dispatch(v.state.tr.setSelection(TextSelection.create(v.state.doc, 0, v.state.doc.content.size))); }, 0);
102
+ return false;
103
+ },
97
104
  mousedown: (v, e) => {
98
105
  const p = propsRef.current;
106
+ // Ô trống: bấm chỗ nào (kể cả giữa chữ gợi ý) con trỏ cũng về đầu ô — không để trình duyệt tự đặt theo toạ độ chuột lên chữ gợi ý
107
+ if (e.button === 0 && !e.shiftKey && !e.metaKey && !e.ctrlKey && v.state.doc.content.size === 0 && v.editable) {
108
+ e.preventDefault();
109
+ v.focus();
110
+ v.dispatch(v.state.tr.setSelection(TextSelection.create(v.state.doc, 0)));
111
+ return true;
112
+ }
99
113
  if (e.button === 0 && !e.shiftKey && !p.onChange && !p.field) trackRangeDrag(store, v, p.blockId);
100
114
  return false;
101
115
  },
102
116
  focus: () => {
103
117
  const p = propsRef.current;
104
118
  ui.activeRich = viewKey(p.blockId, p.field);
119
+ // Chữ mẫu của khối vừa chèn: chọn hết ở lần bấm đầu (sau khi chuột đặt con trỏ) để gõ là thay
120
+ if (ui.fresh.has(p.blockId) && viewRef.current) { const v = viewRef.current; setTimeout(() => { if (ui.fresh.has(p.blockId) && v.hasFocus() && v.state.doc.content.size > 0) v.dispatch(v.state.tr.setSelection(TextSelection.create(v.state.doc, 0, v.state.doc.content.size))); }, 0); }
105
121
  store.setEditing(p.blockId);
106
122
  ui.bump();
107
123
  return false;
@@ -201,10 +217,10 @@ function syncSelection(view: EditorView | undefined): EditorState | null {
201
217
  function atStart(view: EditorView) { const s = view.state.selection; return s.empty && s.from === 0; }
202
218
  function atEnd(view: EditorView) { const s = view.state.selection; return s.empty && s.from === view.state.doc.content.size; }
203
219
 
204
- /** Mục danh sách chứa khối chữ (khối chữ là con đầu của listItem/taskItem). */
220
+ /** Mục danh sách chứa khối chữ (khối chữ là con đầu của listItem). */
205
221
  function listItemOf(store: EditorStore, blockId: string): BNode | null {
206
222
  const loc = store.locate(blockId);
207
- return loc?.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0 ? loc.parent : null;
223
+ return loc?.parent && (loc.parent.type === "listItem") && loc.index === 0 ? loc.parent : null;
208
224
  }
209
225
 
210
226
  /** Ô gõ kế bên theo thứ tự trên khung soạn (đi xuyên qua header/footer lồng nhau). */
@@ -302,10 +318,10 @@ function richKeymap(store: EditorStore, ui: EditorUi, pr: PropsRef, keepCaret: (
302
318
  dispatch?.(state.tr.insertText("\n"));
303
319
  return true;
304
320
  }
305
- // "---" + Enter → đường kẻ
321
+ // "---" + Enter → khoảng cách có đường kẻ (Spacer)
306
322
  const blk = store.block(p.blockId);
307
323
  if (blk?.type === "paragraph" && state.doc.textContent === "---") {
308
- const hr = makeBlock("horizontalRule");
324
+ const hr = makeBlock("spacer", { height: "md", line: true });
309
325
  const para = makeBlock("paragraph");
310
326
  now(() => store.replace(p.blockId, [hr, para], { select: { ids: [], editing: para.id }, caret: { id: para.id, offset: 0 } }));
311
327
  return true;
@@ -391,7 +407,6 @@ const PREFIX_RULES: Array<{ re: RegExp; make(rest: RichNode[]): { blocks: BNode[
391
407
  })),
392
408
  { re: /^[-*+]$/, make: (rest) => { const p = makeBlock("paragraph", {}, rest); return { blocks: [makeBlock("bulletList", {}, [makeBlock("listItem", {}, [p])])], focus: p }; } },
393
409
  { re: /^1[.)]$/, make: (rest) => { const p = makeBlock("paragraph", {}, rest); return { blocks: [makeBlock("orderedList", {}, [makeBlock("listItem", {}, [p])])], focus: p }; } },
394
- { re: /^\[ ?\]$/, make: (rest) => { const p = makeBlock("paragraph", {}, rest); return { blocks: [makeBlock("taskList", {}, [makeBlock("taskItem", { checked: false }, [p])])], focus: p }; } },
395
410
  { re: /^>$/, make: (rest) => { const p = makeBlock("paragraph", {}, rest); return { blocks: [makeBlock("blockquote", {}, [p])], focus: p }; } },
396
411
  ];
397
412
 
@@ -0,0 +1,52 @@
1
+ import type { RichNode } from "@ecomcx/ecomweb-content";
2
+
3
+ /**
4
+ * Chữ AI trả về → khối dạng lưu. AI hay trả markdown nhẹ (## tiêu đề, - danh sách, **đậm**) dù được dặn trả chữ thuần:
5
+ * thay vì chèn nguyên ký hiệu `##` / `**` vào trang, ta đọc chúng thành tiêu đề, danh sách, chữ đậm / nghiêng thật.
6
+ * Chỉ nhận các dấu đơn giản; mọi thứ khác (bảng, mã, ảnh, HTML) giữ là chữ thường — không bao giờ sinh khối nguy hiểm.
7
+ */
8
+ const text = (t: string, marks?: Array<{ type: string }>): RichNode => ({ type: "text", text: t, ...(marks ? { marks } : {}) });
9
+
10
+ /** Chữ đậm / nghiêng trong một dòng: **đậm**, *nghiêng*; dấu lẻ loi giữ nguyên (không đọc `_` để khỏi phá tên_có_gạch_dưới). */
11
+ export function inlineNodes(src: string): RichNode[] {
12
+ const out: RichNode[] = [];
13
+ const re = /\*\*(?=\S)([\s\S]*?\S)\*\*|\*(?=\S)([^*]*?\S)\*/g;
14
+ let last = 0;
15
+ for (let m = re.exec(src); m; m = re.exec(src)) {
16
+ if (m.index > last) out.push(text(src.slice(last, m.index)));
17
+ out.push(m[1] != null ? text(m[1], [{ type: "bold" }]) : text(m[2], [{ type: "italic" }]));
18
+ last = m.index + m[0].length;
19
+ }
20
+ if (last < src.length) out.push(text(src.slice(last)));
21
+ return out.filter((n) => n.text !== "");
22
+ }
23
+
24
+ const para = (s: string): RichNode => ({ type: "paragraph", content: inlineNodes(s) });
25
+ const item = (s: string): RichNode => ({ type: "listItem", content: [para(s)] });
26
+
27
+ export function markdownToNodes(raw: string): RichNode[] {
28
+ const nodes: RichNode[] = [];
29
+ let list: RichNode | null = null;
30
+ let buf: string[] = [];
31
+ const flush = () => { if (buf.length) { nodes.push(para(buf.join(" "))); buf = []; } };
32
+ const closeList = () => { list = null; };
33
+ for (const line0 of raw.replace(/\r/g, "").split("\n")) {
34
+ const line = line0.trim();
35
+ if (!line) { flush(); closeList(); continue; }
36
+ const h = /^(#{1,6})\s+(.+?)\s*#*$/.exec(line);
37
+ if (h) { flush(); closeList(); nodes.push({ type: "heading", attrs: { level: Math.min(4, Math.max(2, h[1].length)) }, content: inlineNodes(h[2]) }); continue; }
38
+ const ul = /^(?:[-*•+])\s+(.+)$/.exec(line);
39
+ const ol = /^\d{1,3}[.)]\s+(.+)$/.exec(line);
40
+ if (ul || ol) {
41
+ flush();
42
+ const type = ul ? "bulletList" : "orderedList";
43
+ if (!list || (list as RichNode).type !== type) { list = { type, content: [] }; nodes.push(list); }
44
+ (list as RichNode).content!.push(item((ul ?? ol)![1]));
45
+ continue;
46
+ }
47
+ closeList();
48
+ buf.push(line);
49
+ }
50
+ flush();
51
+ return nodes;
52
+ }
package/src/v2/ui/ai.tsx CHANGED
@@ -4,6 +4,8 @@ import { useEditor } from "../context";
4
4
  import type { RichNode } from "@ecomcx/ecomweb-content";
5
5
  import { fromRich, inlineText, makeBlock, type BNode } from "../core/model";
6
6
  import { Modal } from "./options";
7
+ import { markdownToNodes } from "./ai-markdown";
8
+ import { useMsgs } from "../i18n";
7
9
  import { Dropdown, MenuItem, ToolButton } from "./toolbar";
8
10
 
9
11
  type Job = { task: string; label: string; language?: string; instruction?: string };
@@ -88,49 +90,114 @@ export function AiAltButton({ attrs, setAttrs }: { attrs: Record<string, unknown
88
90
  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>;
89
91
  }
90
92
 
93
+ const TONES = ["auto", "friendly", "pro", "sell"] as const;
94
+ const LENGTHS = ["short", "medium", "long"] as const;
95
+ type Tone = (typeof TONES)[number];
96
+ type Length = (typeof LENGTHS)[number];
97
+ const TONE_HINT: Record<Tone, string> = { auto: "", friendly: "Tone: friendly and warm.", pro: "Tone: professional and precise.", sell: "Tone: persuasive, benefit-led, no exaggeration." };
98
+ const LENGTH_HINT: Record<Length, string> = { short: "Length: 1-2 short paragraphs.", medium: "Length: 3-4 paragraphs.", long: "Length: a full section of about 300-400 words with short H2/H3 headings." };
99
+
100
+ /** Lời nhắc đầy đủ gửi AI: yêu cầu của người dùng + giọng văn / độ dài / định dạng đã chọn. */
101
+ function composePrompt(prompt: string, o: { tone: Tone; length: Length; structured: boolean }) {
102
+ const hints = [TONE_HINT[o.tone], LENGTH_HINT[o.length], o.structured ? "Format: use '## ' for section headings, '- ' for bullet lists and **bold** for key words, only where they help." : "Format: plain paragraphs only."].filter(Boolean);
103
+ return `${prompt.trim()}\n\n${hints.join(" ")}`;
104
+ }
105
+
106
+ /** Lỗi từ máy chủ → câu người dùng hiểu và làm theo được (kèm thông báo gốc ngắn để dễ báo lỗi). */
107
+ function friendlyError(msg: string, t: Record<string, string>) {
108
+ if (/not_configured|chưa được bật|chưa bật|not configured|thiếu nhà cung cấp/i.test(msg)) return t.aiwErrOff;
109
+ if (/429|too.?fast|quá nhanh|too many/i.test(msg)) return t.aiwErrBusy;
110
+ return `${t.aiwErrOther}${msg ? ` (${msg.slice(0, 160)})` : ""}`;
111
+ }
112
+
113
+ /** Vẽ cây khối AI trả về (tiêu đề, đoạn, danh sách, đậm / nghiêng) đúng như sẽ chèn — không hiện ký hiệu markdown. */
114
+ function NodesView({ nodes }: { nodes: RichNode[] }) {
115
+ const inline = (n: RichNode, i: number): React.ReactNode => {
116
+ let el: React.ReactNode = n.text ?? "";
117
+ for (const m of n.marks ?? []) el = m.type === "bold" ? <strong>{el}</strong> : m.type === "italic" ? <em>{el}</em> : el;
118
+ return <span key={i}>{el}</span>;
119
+ };
120
+ const block = (n: RichNode, i: number): React.ReactNode => {
121
+ const kids = (n.content ?? []);
122
+ switch (n.type) {
123
+ case "heading": { const L = (`h${Math.min(4, Math.max(2, Number(n.attrs?.level) || 2))}`) as "h2"; return <L key={i}>{kids.map(inline)}</L>; }
124
+ case "bulletList": return <ul key={i}>{kids.map(block)}</ul>;
125
+ case "orderedList": return <ol key={i}>{kids.map(block)}</ol>;
126
+ case "listItem": return <li key={i}>{kids.map((k, j) => (k.type === "paragraph" ? <span key={j}>{(k.content ?? []).map(inline)}</span> : block(k, j)))}</li>;
127
+ default: return <p key={i}>{kids.map(inline)}</p>;
128
+ }
129
+ };
130
+ return <>{nodes.map(block)}</>;
131
+ }
132
+
133
+ const countWords = (nodes: RichNode[]): number => nodes.reduce((n, x) => n + (x.text ? x.text.trim().split(/\s+/).filter(Boolean).length : 0) + countWords(x.content ?? []), 0);
134
+
91
135
  /**
92
- * 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).
93
- * Một bước hoàn tác; không tự chèn khi chưa bấm.
136
+ * Lệnh /ai: hộp "Viết bằng AI" — gõ yêu cầu (hoặc chọn gợi ý), chọn giọng văn / độ dài, xem kết quả đúng dạng sẽ chèn
137
+ * (tiêu đề, danh sách, chữ đậm thật), rồi chèn (thay khối chứa "/ai" nếu gọi từ lệnh gạch chéo). Một bước hoàn tác; không tự chèn khi chưa bấm.
94
138
  */
95
139
  export function AiWrite() {
96
140
  const { host, labels, store, ui } = useEditor();
141
+ const t = useMsgs("blocks") as Record<string, string>;
97
142
  const [at, setAt] = useState<{ blockId?: string; docId: string; parentId: string | null; index: number } | null>(null);
98
143
  const [prompt, setPrompt] = useState("");
144
+ const [tone, setTone] = useState<Tone>("auto");
145
+ const [length, setLength] = useState<Length>("medium");
146
+ const [structured, setStructured] = useState(true);
99
147
  const [state, setState] = useState<{ loading: boolean; text?: string; nodes?: RichNode[]; error?: string }>({ loading: false });
100
148
  useEffect(() => { ui.openAiWrite = (a) => { setAt(a); setPrompt(""); setState({ loading: false }); }; return () => { ui.openAiWrite = null; }; }, [ui]);
101
149
  if (!at || !host.ai) return null;
102
150
  const run = async () => {
103
- if (!prompt.trim()) return;
151
+ if (!prompt.trim() || state.loading) return;
104
152
  setState({ loading: true });
153
+ const full = composePrompt(prompt, { tone, length, structured });
105
154
  try {
106
- const r = host.ai!.write ? await host.ai!.write(prompt.trim()) : { text: await host.ai!.run("write", prompt.trim(), {}) };
107
- setState({ loading: false, text: r.text, nodes: Array.isArray(r.nodes) && r.nodes.length ? r.nodes as RichNode[] : undefined });
108
- } catch (e) { setState({ loading: false, error: (e as Error).message }); }
155
+ const r = host.ai!.write ? await host.ai!.write(full) : { text: await host.ai!.run("write", full, {}) };
156
+ const text = (r.text ?? "").trim();
157
+ // Khối dạng lưu của máy chủ (nếu có) thắng; không có thì đọc markdown nhẹ trong chữ AI trả về
158
+ const nodes = Array.isArray(r.nodes) && r.nodes.length ? (r.nodes as RichNode[]) : markdownToNodes(text);
159
+ if (!nodes.length) throw new Error("");
160
+ setState({ loading: false, text, nodes });
161
+ } catch (e) { setState({ loading: false, error: friendlyError((e as Error).message ?? "", t) }); }
109
162
  };
110
- const paragraphs = (state.text ?? "").split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
111
163
  const insert = () => {
112
- if (!paragraphs.length) return;
113
- // Có khối dạng lưu (tiêu đề, danh sách) thì chèn đúng khối; ứng dụng cũ chỉ trả chữ → mỗi đoạn một khối đoạn văn
114
- const nodes = state.nodes ? state.nodes.map(fromRich) : paragraphs.map((p) => makeBlock("paragraph", {}, p));
164
+ if (!state.nodes?.length) return;
165
+ const nodes = state.nodes.map(fromRich);
115
166
  store.batch(() => {
116
167
  if (at.blockId && store.block(at.blockId)) store.replace(at.blockId, nodes);
117
168
  else store.insert(at.docId, at.parentId, at.index, nodes);
118
169
  });
119
170
  setAt(null);
120
171
  };
172
+ const examples = [t.aiwEx1, t.aiwEx2, t.aiwEx3, t.aiwEx4];
173
+ const toneLabel: Record<Tone, string> = { auto: t.aiwToneAuto, friendly: t.aiwToneFriendly, pro: t.aiwTonePro, sell: t.aiwToneSell };
174
+ const lenLabel: Record<Length, string> = { short: t.aiwLenShort, medium: t.aiwLenMedium, long: t.aiwLenLong };
121
175
  return (
122
176
  <Modal title={labels.aiWrite} onClose={() => setAt(null)} wide>
123
177
  <div className="ecx-ai-body" data-ecx-ai-write>
124
- <textarea className="ecx-input" rows={3} value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder={labels.aiWritePrompt} data-ai-write-prompt
178
+ <textarea className="ecx-input" rows={3} autoFocus value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder={labels.aiWritePrompt} data-ai-write-prompt
125
179
  onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); void run(); } }} />
180
+ {!prompt && !state.text && (
181
+ <div className="ecx-ai-chips" role="group" aria-label={t.aiwTryTitle}>
182
+ {examples.map((x) => <button key={x} type="button" className="ecx-chip" onClick={() => setPrompt(x)}>{x}</button>)}
183
+ </div>
184
+ )}
185
+ <div className="ecx-ai-opts">
186
+ <label className="ecx-ai-opt"><span>{t.aiwTone}</span>
187
+ <select className="ecx-input" value={tone} onChange={(e) => setTone(e.target.value as Tone)}>{TONES.map((k) => <option key={k} value={k}>{toneLabel[k]}</option>)}</select></label>
188
+ <label className="ecx-ai-opt"><span>{t.aiwLength}</span>
189
+ <select className="ecx-input" value={length} onChange={(e) => setLength(e.target.value as Length)}>{LENGTHS.map((k) => <option key={k} value={k}>{lenLabel[k]}</option>)}</select></label>
190
+ </div>
191
+ <label className="ecx-check"><input type="checkbox" checked={structured} onChange={(e) => setStructured(e.target.checked)} />{t.aiwStructured}</label>
126
192
  {state.loading && <p className="ecx-ai-wait" role="status">{labels.aiWorking}</p>}
127
193
  {state.error && <p className="ecx-ai-error" role="alert">{state.error}</p>}
128
- {state.text && <div className="ecx-ai-text" data-ecx-ai-result>{paragraphs.map((p, i) => <p key={i}>{p}</p>)}</div>}
194
+ {state.nodes && <div className="ecx-ai-text" data-ecx-ai-result aria-label={t.aiwPreview}><NodesView nodes={state.nodes} /></div>}
195
+ {state.nodes && <p className="ecx-ai-note">{countWords(state.nodes)} {t.aiwWords}</p>}
129
196
  <p className="ecx-ai-note">{labels.aiNote}</p>
130
197
  <div className="ecx-popover-actions">
131
198
  <button type="button" className="ecx-btn" onClick={() => setAt(null)}>{labels.cancel}</button>
132
- <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>
133
- {state.text && <button type="button" className="ecx-btn ecx-btn-primary" onClick={insert} data-ai-write-insert>{labels.aiInsert}</button>}
199
+ <button type="button" className="ecx-btn" onClick={() => void run()} disabled={state.loading || !prompt.trim()} data-ai-write-run>{state.nodes ? labels.aiRetry : labels.aiWriteRun}</button>
200
+ {state.nodes && <button type="button" className="ecx-btn ecx-btn-primary" onClick={insert} data-ai-write-insert>{labels.aiInsert}</button>}
134
201
  </div>
135
202
  </div>
136
203
  </Modal>