"use client"; import { TOGGLE_LINK_COMMAND } from "@lexical/link"; import { INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND } from "@lexical/list"; import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"; import { INSERT_HORIZONTAL_RULE_COMMAND } from "@lexical/react/LexicalHorizontalRuleNode"; import { $patchStyleText } from "@lexical/selection"; import { $deleteTableColumnAtSelection, $deleteTableRowAtSelection, $getTableCellNodeFromLexicalNode, $getTableCellNodeRect, $getTableNodeFromLexicalNodeOrThrow, $getTableRowNodeFromTableCellNodeOrThrow, $insertTableColumnAtSelection, $insertTableRowAtSelection, $isTableCellNode, $isTableRowNode, $isTableSelection, $mergeCells, $unmergeCell, INSERT_TABLE_COMMAND, type TableCellNode, type TableRowNode, } from "@lexical/table"; import { Button } from "@suphark/ui/components/shared/button/button"; import { SimpleDialog } from "@suphark/ui/components/shared/simple-dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@suphark/ui/components/ui/dropdown-menu"; import { Field, FieldError, FieldLabel } from "@suphark/ui/components/ui/field"; import { Input } from "@suphark/ui/components/ui/input"; import { Separator } from "@suphark/ui/components/ui/separator"; import { cn } from "@suphark/ui/lib/utils"; import { $getSelection, $isElementNode, $isRangeSelection, $isTextNode, CAN_REDO_COMMAND, CAN_UNDO_COMMAND, COMMAND_PRIORITY_CRITICAL, FORMAT_ELEMENT_COMMAND, FORMAT_TEXT_COMMAND, REDO_COMMAND, UNDO_COMMAND, } from "lexical"; import { AlignCenter, AlignJustify, AlignLeft, AlignRight, Bold, ChevronDown, Columns3, Italic, List, ListOrdered, Minus, PaintBucket, Plus, Redo, Rows3, StretchVertical, TableCellsMerge, TableCellsSplit, Table as TableIcon, Type as TypeIcon, Underline as UnderlineIcon, Undo, } from "lucide-react"; import { type FormEvent, type ReactNode, useCallback, useEffect, useId, useState } from "react"; import { ActionDelete, ActionLink } from "../../shared/semantic-icons"; import { type RichTextText, useRichTextText } from "../rich-text-text"; import { fill, normalizeLinkUrl } from "../rich-text-utils"; export const ToolbarButton = ({ onClick, active = false, disabled = false, children, label, }: { onClick: () => void; active?: boolean; disabled?: boolean; children: ReactNode; /** ชื่อปุ่ม — Button ของแพ็กเกจแสดงเป็น tooltip ให้เอง */ label: string; }) => ( ); const TRIGGER_CLASS = "h-8 gap-1 px-2 text-muted-foreground hover:text-foreground"; function MenuTrigger({ label, children }: { label: string; children: ReactNode }) { return ( } > {children} ); } function getFontSizeFromStyle(style: string): string { const match = style.match(/font-size:\s*([0-9.]+)\s*(pt|px)?/i); if (!match?.[1]) return "12"; const value = Number.parseFloat(match[1]); if (!Number.isFinite(value)) return "12"; const unit = match[2]?.toLowerCase(); const size = unit === "px" ? Math.round(value * 0.75) : Math.round(value); return size.toString(); } function setFontSizeInStyle(style: string, size: string | null): string { const declarations = style .split(";") .map((part) => part.trim()) .filter(Boolean) .filter((part) => !part.toLowerCase().startsWith("font-size:")); if (size) { declarations.push(`font-size: ${size}pt`); } return declarations.join("; "); } type TableCellTarget = "cell" | "row" | "column"; type TableVerticalAlign = "top" | "middle" | "bottom"; const FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 30, 36, 48, 60, 72]; // สีพื้นช่องตารางเป็นค่าในเนื้อเอกสาร (ส่งออกเป็น HTML/อีเมล) จึงเป็นสีคงที่ ไม่ใช่ token ของธีม const TABLE_COLORS = [ { key: "colorClear", value: null }, { key: "colorGray", value: "#f1f5f9" }, { key: "colorBlue", value: "#dbeafe" }, { key: "colorGreen", value: "#dcfce7" }, { key: "colorYellow", value: "#fef3c7" }, { key: "colorRed", value: "#fee2e2" }, { key: "colorPurple", value: "#ede9fe" }, ] as const satisfies ReadonlyArray<{ key: keyof RichTextText; value: string | null }>; const ROW_HEIGHTS = [ { key: "rowNormal", value: undefined }, { key: "rowTall", value: 56 }, { key: "rowExtraTall", value: 80 }, ] as const satisfies ReadonlyArray<{ key: keyof RichTextText; value: number | undefined }>; const TABLE_VERTICAL_ALIGNMENTS = [ { key: "alignTop", value: "top" }, { key: "alignMiddle", value: "middle" }, { key: "alignBottom", value: "bottom" }, ] as const satisfies ReadonlyArray<{ key: keyof RichTextText; value: TableVerticalAlign }>; const TABLE_TARGETS = ["cell", "row", "column"] as const satisfies ReadonlyArray; function uniqueCells(cells: Array): TableCellNode[] { const cellMap = new Map(); for (const cell of cells) { if (cell) cellMap.set(cell.getKey(), cell); } return Array.from(cellMap.values()); } function getSelectedTableCells(): TableCellNode[] { const selection = $getSelection(); if ($isTableSelection(selection)) { return uniqueCells( selection .getNodes() .map((node) => ($isTableCellNode(node) ? node : $getTableCellNodeFromLexicalNode(node))), ); } if (!$isRangeSelection(selection)) return []; const selectedCells = selection .getNodes() .map((node) => ($isTableCellNode(node) ? node : $getTableCellNodeFromLexicalNode(node))); selectedCells.push($getTableCellNodeFromLexicalNode(selection.anchor.getNode())); selectedCells.push($getTableCellNodeFromLexicalNode(selection.focus.getNode())); return uniqueCells(selectedCells); } function getRowsForCells(cells: TableCellNode[]): TableRowNode[] { const rowMap = new Map(); for (const cell of cells) { const row = $getTableRowNodeFromTableCellNodeOrThrow(cell); rowMap.set(row.getKey(), row); } return Array.from(rowMap.values()); } function getColumnCellsForCells(cells: TableCellNode[]): TableCellNode[] { const selectedColumns = new Set(); const tableMap = new Map>(); for (const cell of cells) { const rect = $getTableCellNodeRect(cell); if (!rect) continue; for (let index = rect.columnIndex; index < rect.columnIndex + rect.colSpan; index += 1) { selectedColumns.add(index); } const table = $getTableNodeFromLexicalNodeOrThrow(cell); tableMap.set(table.getKey(), table); } const columnCells: TableCellNode[] = []; for (const table of tableMap.values()) { for (const row of table.getChildren()) { if (!$isTableRowNode(row)) continue; for (const node of row.getChildren()) { if (!$isTableCellNode(node)) continue; const rect = $getTableCellNodeRect(node); if (!rect) continue; const inSelectedColumn = Array.from(selectedColumns).some( (index) => index >= rect.columnIndex && index < rect.columnIndex + rect.colSpan, ); if (inSelectedColumn) columnCells.push(node); } } } return uniqueCells(columnCells); } function getCellsForTarget(target: TableCellTarget): TableCellNode[] { const cells = getSelectedTableCells(); if (target === "cell") return cells; if (target === "row") { return uniqueCells( getRowsForCells(cells).flatMap((row) => row.getChildren().filter($isTableCellNode)), ); } return getColumnCellsForCells(cells); } function applyFontSizeToTableCells(cells: TableCellNode[], size: string | null) { const visit = (node: ReturnType[number]) => { if ($isTextNode(node)) { node.setStyle(setFontSizeInStyle(node.getStyle(), size)); return; } if ($isElementNode(node)) { for (const child of node.getChildren()) { visit(child); } } }; for (const cell of cells) { for (const child of cell.getChildren()) { visit(child); } } } /** กล่องแทรกลิงก์/ตาราง (แทน window.prompt — webview บางตัวปิดทิ้ง และกรอกผิดแก้ไม่ได้) */ function InsertDialog({ kind, onClose, onInsertLink, onInsertTable, t, }: { kind: "link" | "table" | null; onClose: () => void; onInsertLink: (url: string) => void; onInsertTable: (rows: string, columns: string) => void; t: RichTextText; }) { const id = useId(); const [url, setUrl] = useState(""); const [rows, setRows] = useState("3"); const [columns, setColumns] = useState("3"); const [invalid, setInvalid] = useState(false); // เปิดใหม่ = เริ่มค่าใหม่ useEffect(() => { if (kind) { setUrl(""); setRows("3"); setColumns("3"); setInvalid(false); } }, [kind]); const submit = (event: FormEvent) => { event.preventDefault(); event.stopPropagation(); // editor อยู่ในฟอร์มของแอป — ไม่ให้ submit ฟอร์มนอก if (kind === "link") { const normalized = normalizeLinkUrl(url); if (!normalized) { setInvalid(true); return; } onInsertLink(normalized); } else if (kind === "table") { onInsertTable(rows, columns); } onClose(); }; return ( !open && onClose()} title={kind === "table" ? t.tableTitle : t.linkTitle} size="sm" >
{kind === "link" ? ( {t.linkUrl} { setUrl(e.target.value); setInvalid(false); }} /> {invalid && {t.linkInvalid}} ) : (
{t.tableRows} setRows(e.target.value)} /> {t.tableColumns} setColumns(e.target.value)} />
)}
); } export function ToolbarPlugin() { const [editor] = useLexicalComposerContext(); const t = useRichTextText(); const [canUndo, setCanUndo] = useState(false); const [canRedo, setCanRedo] = useState(false); const [isBold, setIsBold] = useState(false); const [isItalic, setIsItalic] = useState(false); const [isUnderline, setIsUnderline] = useState(false); const [fontSize, setFontSize] = useState("12"); const [isTable, setIsTable] = useState(false); const [insertKind, setInsertKind] = useState<"link" | "table" | null>(null); const updateToolbar = useCallback(() => { const selection = $getSelection(); if ($isTableSelection(selection)) { setIsTable(true); return; } if ($isRangeSelection(selection)) { setIsBold(selection.hasFormat("bold")); setIsItalic(selection.hasFormat("italic")); setIsUnderline(selection.hasFormat("underline")); const node = selection.getNodes()[0]; if (node && $isTextNode(node)) { setFontSize(getFontSizeFromStyle(node.getStyle())); } const cellNode = $getTableCellNodeFromLexicalNode(selection.anchor.getNode()); setIsTable(cellNode !== null); } else { setIsTable(false); } }, []); useEffect(() => { return editor.registerUpdateListener(({ editorState }) => { editorState.read(() => { updateToolbar(); }); }); }, [editor, updateToolbar]); useEffect(() => { return editor.registerCommand( CAN_UNDO_COMMAND, (payload) => { setCanUndo(payload); return false; }, COMMAND_PRIORITY_CRITICAL, ); }, [editor]); useEffect(() => { return editor.registerCommand( CAN_REDO_COMMAND, (payload) => { setCanRedo(payload); return false; }, COMMAND_PRIORITY_CRITICAL, ); }, [editor]); const applyTableBackground = (target: TableCellTarget, color: string | null) => { editor.update(() => { for (const cell of getCellsForTarget(target)) { cell.setBackgroundColor(color); } }); }; const applyTableVerticalAlign = (target: TableCellTarget, align: TableVerticalAlign) => { editor.update(() => { for (const cell of getCellsForTarget(target)) { cell.setVerticalAlign(align === "top" ? undefined : align); } }); }; const setSelectedRowsHeight = (height: number | undefined) => { editor.update(() => { for (const row of getRowsForCells(getSelectedTableCells())) { row.setHeight(height); } }); }; const mergeSelectedTableCells = () => { editor.update(() => { const cells = getSelectedTableCells(); if (cells.length > 1) { $mergeCells(cells); } }); }; const unmergeSelectedTableCell = () => { editor.update(() => { $unmergeCell(); }); }; const applyFontSize = (size: string | null) => { editor.update(() => { const selection = $getSelection(); const tableCells = $isTableSelection(selection) ? getSelectedTableCells() : []; if (tableCells.length > 0) { applyFontSizeToTableCells(tableCells, size); setFontSize(size ?? "12"); return; } if ($isRangeSelection(selection)) { $patchStyleText(selection, { "font-size": size ? `${size}pt` : null, }); setFontSize(size ?? "12"); } }); }; const targetLabel = (target: TableCellTarget) => t[target]; return (
editor.dispatchCommand(UNDO_COMMAND, undefined)} disabled={!canUndo} label={t.undo} > editor.dispatchCommand(REDO_COMMAND, undefined)} disabled={!canRedo} label={t.redo} >
{fontSize} {FONT_SIZES.map((size) => ( applyFontSize(size.toString())} className={cn(fontSize === size.toString() && "bg-accent")} > {fill(t.fontSizeValue, { size })} ))} applyFontSize(null)}> {t.resetFontSize}
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "bold")} active={isBold} label={t.bold} > editor.dispatchCommand(FORMAT_TEXT_COMMAND, "italic")} active={isItalic} label={t.italic} > editor.dispatchCommand(FORMAT_TEXT_COMMAND, "underline")} active={isUnderline} label={t.underline} >
editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, "left")} > {t.alignLeft} editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, "center")} > {t.alignCenter} editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, "right")} > {t.alignRight} editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, "justify")} > {t.justify} editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined)} > {t.bulletList} editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined)} > {t.orderedList}
setInsertKind("link")}> {t.insertLink} setInsertKind("table")}> {t.insertTable} editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, undefined)} > {t.horizontalRule} {isTable && ( } > {t.table} { editor.update(() => { $insertTableRowAtSelection(); }); }} > {t.addRow} { editor.update(() => { $insertTableColumnAtSelection(); }); }} > {t.addColumn} {t.mergeCells} {t.unmergeCell}
{t.color}
{TABLE_TARGETS.map((target) => (
{targetLabel(target)}
{TABLE_COLORS.map((color) => { const label = fill(t.colorSwatch, { target: targetLabel(target), color: t[color.key], }); return ( ); })}
))}
{t.verticalAlign}
{TABLE_TARGETS.map((target) => (
{targetLabel(target)}
{TABLE_VERTICAL_ALIGNMENTS.map((align) => ( ))}
))}
{t.rowHeight}
{ROW_HEIGHTS.map((height) => ( ))}
{ editor.update(() => { $deleteTableRowAtSelection(); }); }} > {t.deleteRow} { editor.update(() => { $deleteTableColumnAtSelection(); }); }} > {t.deleteColumn}
)}
{ setInsertKind(null); editor.focus(); }} onInsertLink={(url) => editor.dispatchCommand(TOGGLE_LINK_COMMAND, url)} onInsertTable={(rows, columns) => editor.dispatchCommand(INSERT_TABLE_COMMAND, { columns, includeHeaders: false, rows }) } t={t} />
); }