fix : warning from tailwindcss

This commit is contained in:
2026-09-20 00:55:57 +07:00 Unverified
parent 7c10b2c995
commit cd72f1fa5f
14 changed files with 499 additions and 209 deletions
+349 -155
View File
@@ -17,7 +17,14 @@ import Spreadsheet, {
type RowIndicatorProps,
type SpreadsheetRef,
} from "react-spreadsheet";
import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type KeyboardEvent,
} from "react";
import {
closestCenter,
DndContext,
@@ -90,8 +97,8 @@ const sameAxisCollision: CollisionDetection = (args) => {
const axis = String(args.active.id).split(":", 1)[0];
return closestCenter({
...args,
droppableContainers: args.droppableContainers.filter(
(container) => String(container.id).startsWith(`${axis}:`),
droppableContainers: args.droppableContainers.filter((container) =>
String(container.id).startsWith(`${axis}:`),
),
});
};
@@ -103,13 +110,23 @@ function movedIndex(current: number, from: number, to: number): number {
return current;
}
function LiteralDataViewer({ cell }: { cell?: { value?: unknown; backgroundColor?: string } }) {
function LiteralDataViewer({
cell,
}: {
cell?: { value?: unknown; backgroundColor?: string };
}) {
return (
<div
className="Spreadsheet__data-viewer Spreadsheet__data-viewer--preserve-breaks size-full"
style={cell?.backgroundColor ? { backgroundColor: cell.backgroundColor } : undefined}
style={
cell?.backgroundColor
? { backgroundColor: cell.backgroundColor }
: undefined
}
>
<RichTextContent html={normalizeExtraRichText(String(cell?.value ?? ""))} />
<RichTextContent
html={normalizeExtraRichText(String(cell?.value ?? ""))}
/>
</div>
);
}
@@ -153,14 +170,25 @@ function EditableColumnIndicator({
selected,
onRename,
}: ColumnIndicatorProps & { id: string; onRename: (column: number) => void }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({
id,
strategy: horizontalListSortingStrategy,
});
return (
<th
ref={setNodeRef}
className={cn("Spreadsheet__header", selected && "Spreadsheet__header--selected", isDragging && "opacity-60")}
className={cn(
"Spreadsheet__header",
selected && "Spreadsheet__header--selected",
isDragging && "opacity-60",
)}
style={{ transform: CSS.Transform.toString(transform), transition }}
>
<Button
@@ -187,15 +215,32 @@ function EditableColumnIndicator({
);
}
function SortableRowIndicator({ id, row, label, selected, onSelect }: RowIndicatorProps & { id: string }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
function SortableRowIndicator({
id,
row,
label,
selected,
onSelect,
}: RowIndicatorProps & { id: string }) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({
id,
strategy: verticalListSortingStrategy,
});
return (
<th
ref={setNodeRef}
className={cn("Spreadsheet__header", selected && "Spreadsheet__header--selected", isDragging && "opacity-60")}
className={cn(
"Spreadsheet__header",
selected && "Spreadsheet__header--selected",
isDragging && "opacity-60",
)}
style={{ transform: CSS.Transform.toString(transform), transition }}
>
<Button
@@ -235,7 +280,9 @@ export function ExtraSheetEditor({
}) {
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
);
const spreadsheetRef = useRef<SpreadsheetRef>(null);
const [active, setActive] = useState<Point>({ row: 0, column: 0 });
@@ -248,49 +295,68 @@ export function ExtraSheetEditor({
const [originalCellDraft, setOriginalCellDraft] = useState("");
const [stylePatch, setStylePatch] = useState<RichTextStylePatch>({});
const [selectedCount, setSelectedCount] = useState(1);
const [history, setHistory] = useState<SheetHistory>({ items: [value], index: 0, value });
const [history, setHistory] = useState<SheetHistory>({
items: [value],
index: 0,
value,
});
const selectedPointsRef = useRef<Point[]>([active]);
const matrix = useMemo(() => extraSheetToMatrix(value), [value]);
const activeColumn = value.columns[active.column];
const activeRow = value.rows[active.row];
const canUndo = history.index > 0;
const canRedo = history.index < history.items.length - 1;
const sortableIds = useMemo(() => [
...value.columns.map((column) => columnDragId(column.id)),
...value.rows.map((row) => rowDragId(row.id)),
], [value.columns, value.rows]);
const sortableIds = useMemo(
() => [
...value.columns.map((column) => columnDragId(column.id)),
...value.rows.map((row) => rowDragId(row.id)),
],
[value.columns, value.rows],
);
if (history.value !== value) {
setHistory(history.items[history.index] === value
? { ...history, value }
: { items: [value], index: 0, value });
setHistory(
history.items[history.index] === value
? { ...history, value }
: { items: [value], index: 0, value },
);
}
const commitSheet = useCallback((next: ExtraSheet) => {
if (JSON.stringify(next) === JSON.stringify(value)) return;
setHistory((current) => {
const items = [...current.items.slice(0, current.index + 1), next]
.slice(-SHEET_HISTORY_LIMIT);
return { items, index: items.length - 1, value: next };
});
onChange(next);
}, [onChange, value]);
const commitSheet = useCallback(
(next: ExtraSheet) => {
if (JSON.stringify(next) === JSON.stringify(value)) return;
setHistory((current) => {
const items = [
...current.items.slice(0, current.index + 1),
next,
].slice(-SHEET_HISTORY_LIMIT);
return { items, index: items.length - 1, value: next };
});
onChange(next);
},
[onChange, value],
);
const travel = useCallback((direction: -1 | 1) => {
const index = history.index + direction;
const next = history.items[index];
if (!next) return;
setHistory((current) => ({ ...current, index, value: next }));
onChange(next);
const point = {
row: Math.min(active.row, next.rows.length - 1),
column: Math.min(active.column, next.columns.length - 1),
};
setActive(point);
selectedPointsRef.current = [point];
setSelectedCount(1);
window.requestAnimationFrame(() => spreadsheetRef.current?.activate(point));
}, [active, history, onChange]);
const travel = useCallback(
(direction: -1 | 1) => {
const index = history.index + direction;
const next = history.items[index];
if (!next) return;
setHistory((current) => ({ ...current, index, value: next }));
onChange(next);
const point = {
row: Math.min(active.row, next.rows.length - 1),
column: Math.min(active.column, next.columns.length - 1),
};
setActive(point);
selectedPointsRef.current = [point];
setSelectedCount(1);
window.requestAnimationFrame(() =>
spreadsheetRef.current?.activate(point),
);
},
[active, history, onChange],
);
const activateOnly = useCallback((point: Point) => {
setActive(point);
@@ -299,45 +365,62 @@ export function ExtraSheetEditor({
window.requestAnimationFrame(() => spreadsheetRef.current?.activate(point));
}, []);
const moveRow = useCallback((from: number, to: number) => {
const next = moveExtraSheetRow(value, from, to);
if (next === value) return;
const point = { ...active, row: movedIndex(active.row, from, to) };
commitSheet(next);
activateOnly(point);
}, [active, activateOnly, commitSheet, value]);
const moveRow = useCallback(
(from: number, to: number) => {
const next = moveExtraSheetRow(value, from, to);
if (next === value) return;
const point = { ...active, row: movedIndex(active.row, from, to) };
commitSheet(next);
activateOnly(point);
},
[active, activateOnly, commitSheet, value],
);
const moveColumn = useCallback((from: number, to: number) => {
const next = moveExtraSheetColumn(value, from, to);
if (next === value) return;
const point = { ...active, column: movedIndex(active.column, from, to) };
commitSheet(next);
activateOnly(point);
}, [active, activateOnly, commitSheet, value]);
const moveColumn = useCallback(
(from: number, to: number) => {
const next = moveExtraSheetColumn(value, from, to);
if (next === value) return;
const point = { ...active, column: movedIndex(active.column, from, to) };
commitSheet(next);
activateOnly(point);
},
[active, activateOnly, commitSheet, value],
);
const handleDragEnd = useCallback(({ active: dragged, over }: DragEndEvent) => {
if (!over || dragged.id === over.id) return;
const draggedId = String(dragged.id);
const overId = String(over.id);
if (draggedId.startsWith("row:") && overId.startsWith("row:")) {
const from = value.rows.findIndex((row) => rowDragId(row.id) === draggedId);
const to = value.rows.findIndex((row) => rowDragId(row.id) === overId);
if (from !== -1 && to !== -1) moveRow(from, to);
}
if (draggedId.startsWith("column:") && overId.startsWith("column:")) {
const from = value.columns.findIndex((column) => columnDragId(column.id) === draggedId);
const to = value.columns.findIndex((column) => columnDragId(column.id) === overId);
if (from !== -1 && to !== -1) moveColumn(from, to);
}
}, [moveColumn, moveRow, value.columns, value.rows]);
const handleDragEnd = useCallback(
({ active: dragged, over }: DragEndEvent) => {
if (!over || dragged.id === over.id) return;
const draggedId = String(dragged.id);
const overId = String(over.id);
if (draggedId.startsWith("row:") && overId.startsWith("row:")) {
const from = value.rows.findIndex(
(row) => rowDragId(row.id) === draggedId,
);
const to = value.rows.findIndex((row) => rowDragId(row.id) === overId);
if (from !== -1 && to !== -1) moveRow(from, to);
}
if (draggedId.startsWith("column:") && overId.startsWith("column:")) {
const from = value.columns.findIndex(
(column) => columnDragId(column.id) === draggedId,
);
const to = value.columns.findIndex(
(column) => columnDragId(column.id) === overId,
);
if (from !== -1 && to !== -1) moveColumn(from, to);
}
},
[moveColumn, moveRow, value.columns, value.rows],
);
const handleSheetKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const target = event.target as HTMLElement;
if (target.closest("input, textarea, [contenteditable='true']")) return;
const key = event.key.toLowerCase();
const undo = (event.metaKey || event.ctrlKey) && !event.shiftKey && key === "z";
const redo = (event.metaKey || event.ctrlKey) && event.shiftKey && key === "z"
|| event.ctrlKey && !event.shiftKey && key === "y";
const undo =
(event.metaKey || event.ctrlKey) && !event.shiftKey && key === "z";
const redo =
((event.metaKey || event.ctrlKey) && event.shiftKey && key === "z") ||
(event.ctrlKey && !event.shiftKey && key === "y");
if (undo && canUndo) {
event.preventDefault();
travel(-1);
@@ -347,67 +430,93 @@ export function ExtraSheetEditor({
}
};
const normalizedLabel = columnLabel.trim().toLocaleLowerCase();
const labelInvalid = !normalizedLabel || value.columns.some((column, index) =>
index !== (renaming ? active.column : -1) &&
column.label.toLocaleLowerCase() === normalizedLabel,
);
const labelInvalid =
!normalizedLabel ||
value.columns.some(
(column, index) =>
index !== (renaming ? active.column : -1) &&
column.label.toLocaleLowerCase() === normalizedLabel,
);
const openAddColumn = () => {
setRenaming(false);
setColumnLabel(nextExtraSheetColumnLabel(value.columns));
setLabelDialogOpen(true);
};
const openRenameColumn = useCallback((columnIndex = active.column) => {
const column = value.columns[columnIndex];
if (!column) return;
setActive((current) => ({ ...current, column: columnIndex }));
setRenaming(true);
setColumnLabel(column.label);
setLabelDialogOpen(true);
}, [active.column, value.columns]);
const openRenameColumn = useCallback(
(columnIndex = active.column) => {
const column = value.columns[columnIndex];
if (!column) return;
setActive((current) => ({ ...current, column: columnIndex }));
setRenaming(true);
setColumnLabel(column.label);
setLabelDialogOpen(true);
},
[active.column, value.columns],
);
const saveColumnLabel = () => {
if (labelInvalid) return;
if (renaming) {
commitSheet({
...value,
columns: value.columns.map((column, index) =>
index === active.column ? { ...column, label: columnLabel.trim() } : column,
index === active.column
? { ...column, label: columnLabel.trim() }
: column,
),
});
} else {
const column = value.columns.length;
commitSheet(addExtraSheetColumn(
value,
columnLabel.trim(),
createId("extra-sheet-column"),
));
commitSheet(
addExtraSheetColumn(
value,
columnLabel.trim(),
createId("extra-sheet-column"),
),
);
activateOnly({ ...active, column });
}
setLabelDialogOpen(false);
};
const openCellEditorAt = useCallback((point: Point, content?: string) => {
setActive(point);
const column = value.columns[point.column];
const row = value.rows[point.row];
setCellDraft(normalizeExtraRichText(
content ?? (column && row ? row.cells[column.id] ?? "" : ""),
));
setOriginalCellDraft(normalizeExtraRichText(
content ?? (column && row ? row.cells[column.id] ?? "" : ""),
));
setStylePatch({});
setCellDialogOpen(true);
}, [value.columns, value.rows]);
const openCellEditorAt = useCallback(
(point: Point, content?: string) => {
setActive(point);
const column = value.columns[point.column];
const row = value.rows[point.row];
setCellDraft(
normalizeExtraRichText(
content ?? (column && row ? (row.cells[column.id] ?? "") : ""),
),
);
setOriginalCellDraft(
normalizeExtraRichText(
content ?? (column && row ? (row.cells[column.id] ?? "") : ""),
),
);
setStylePatch({});
setCellDialogOpen(true);
},
[value.columns, value.rows],
);
const openActiveCellEditor = () => openCellEditorAt(active);
const columnIndicator = useCallback((props: ColumnIndicatorProps) => (
<EditableColumnIndicator
{...props}
id={columnDragId(value.columns[props.column].id)}
onRename={openRenameColumn}
/>
), [openRenameColumn, value.columns]);
const rowIndicator = useCallback((props: RowIndicatorProps) => (
<SortableRowIndicator {...props} id={rowDragId(value.rows[props.row].id)} />
), [value.rows]);
const columnIndicator = useCallback(
(props: ColumnIndicatorProps) => (
<EditableColumnIndicator
{...props}
id={columnDragId(value.columns[props.column].id)}
onRename={openRenameColumn}
/>
),
[openRenameColumn, value.columns],
);
const rowIndicator = useCallback(
(props: RowIndicatorProps) => (
<SortableRowIndicator
{...props}
id={rowDragId(value.rows[props.row].id)}
/>
),
[value.rows],
);
return (
<div
@@ -416,7 +525,13 @@ export function ExtraSheetEditor({
onKeyDown={handleSheetKeyDown}
>
<div className="flex flex-wrap items-center gap-2">
<SimpleTooltip text={<>ย้อนกลับ <Kbd>Ctrl/⌘ Z</Kbd></>}>
<SimpleTooltip
text={
<>
ย้อนกลับ <Kbd>Ctrl/⌘ Z</Kbd>
</>
}
>
<Button
type="button"
variant="ghost"
@@ -428,7 +543,13 @@ export function ExtraSheetEditor({
<Undo2Icon />
</Button>
</SimpleTooltip>
<SimpleTooltip text={<>ทำซ้ำ <Kbd>Ctrl/⌘ Shift Z</Kbd></>}>
<SimpleTooltip
text={
<>
ทำซ้ำ <Kbd>Ctrl/⌘ Shift Z</Kbd>
</>
}
>
<Button
type="button"
variant="ghost"
@@ -453,16 +574,32 @@ export function ExtraSheetEditor({
<PlusIcon data-icon="inline-start" />
เพิ่มแถว
</Button>
<Button type="button" variant="outline" size="sm" onClick={openAddColumn}>
<Button
type="button"
variant="outline"
size="sm"
onClick={openAddColumn}
>
<PlusIcon data-icon="inline-start" />
เพิ่มคอลัมน์
</Button>
<Button type="button" variant="outline" size="sm" onClick={openActiveCellEditor}>
<Button
type="button"
variant="outline"
size="sm"
onClick={openActiveCellEditor}
>
<PencilIcon data-icon="inline-start" />
แก้ไข {selectedCount > 1 ? `${selectedCount} เซลล์` : "เซลล์"}
</Button>
<label className="relative">
<Button type="button" variant="outline" size="sm" render={<span />} nativeButton={false}>
<Button
type="button"
variant="outline"
size="sm"
render={<span />}
nativeButton={false}
>
<PaletteIcon data-icon="inline-start" />
สีพื้นหลัง {selectedCount > 1 ? `${selectedCount} เซลล์` : "เซลล์"}
</Button>
@@ -470,13 +607,16 @@ export function ExtraSheetEditor({
type="color"
aria-label="เลือกสีพื้นหลังเซลล์"
className="absolute inset-0 cursor-pointer opacity-0"
value={activeRow?.backgrounds?.[activeColumn?.id ?? ""] ?? DEFAULT_CELL_BACKGROUND}
value={
activeRow?.backgrounds?.[activeColumn?.id ?? ""] ??
DEFAULT_CELL_BACKGROUND
}
onChange={(event) => {
commitSheet(updateExtraSheetCells(
value,
selectedPointsRef.current,
{ backgroundColor: event.target.value },
));
commitSheet(
updateExtraSheetCells(value, selectedPointsRef.current, {
backgroundColor: event.target.value,
}),
);
}}
/>
</label>
@@ -484,11 +624,22 @@ export function ExtraSheetEditor({
type="button"
variant="ghost"
size="sm"
onClick={() => commitSheet(updateExtraSheetCells(value, selectedPointsRef.current, { backgroundColor: null }))}
onClick={() =>
commitSheet(
updateExtraSheetCells(value, selectedPointsRef.current, {
backgroundColor: null,
}),
)
}
>
ล้างสีพื้นหลัง
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setRemoveOpen(true)}>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setRemoveOpen(true)}
>
<Trash2Icon data-icon="inline-start" />
ลบตาราง
</Button>
@@ -497,12 +648,20 @@ export function ExtraSheetEditor({
<div
className="overflow-x-auto rounded-lg border"
onClickCapture={(event) => {
if ((event.target as HTMLElement).closest(".Spreadsheet__active-cell--view")) {
if (
(event.target as HTMLElement).closest(
".Spreadsheet__active-cell--view",
)
) {
event.stopPropagation();
}
}}
onDoubleClickCapture={(event) => {
if ((event.target as HTMLElement).closest(".Spreadsheet__cell, .Spreadsheet__active-cell")) {
if (
(event.target as HTMLElement).closest(
".Spreadsheet__cell, .Spreadsheet__active-cell",
)
) {
event.preventDefault();
event.stopPropagation();
openCellEditorAt(active);
@@ -536,11 +695,11 @@ export function ExtraSheetEditor({
setSelectedCount(range.size());
}
}}
onChange={(next) => commitSheet(matrixToExtraSheet(
value,
next as ExtraSheetMatrix,
createId,
))}
onChange={(next) =>
commitSheet(
matrixToExtraSheet(value, next as ExtraSheetMatrix, createId),
)
}
/>
</SortableContext>
</DndContext>
@@ -561,23 +720,48 @@ export function ExtraSheetEditor({
onChange={setCellDraft}
showBubbleMenu={false}
formatWholeContent={selectedCount > 1}
onFormatChange={(patch) => setStylePatch((current) => ({ ...current, ...patch }))}
onFormatChange={(patch) =>
setStylePatch((current) => ({ ...current, ...patch }))
}
/>
<DialogFooter showCloseButton>
<Button type="button" onClick={() => {
const contentUnchanged = richTextContentSignature(cellDraft)
=== richTextContentSignature(originalCellDraft);
if (selectedCount > 1 && contentUnchanged) {
if (Object.keys(stylePatch).length > 0) {
commitSheet(styleExtraSheetCells(value, selectedPointsRef.current, stylePatch));
<Button
type="button"
onClick={() => {
const contentUnchanged =
richTextContentSignature(cellDraft) ===
richTextContentSignature(originalCellDraft);
if (selectedCount > 1 && contentUnchanged) {
if (Object.keys(stylePatch).length > 0) {
commitSheet(
styleExtraSheetCells(
value,
selectedPointsRef.current,
stylePatch,
),
);
}
} else {
commitSheet(
selectedCount > 1
? updateExtraSheetCells(
value,
selectedPointsRef.current,
{ value: cellDraft },
)
: updateExtraSheetCell(
value,
active.row,
active.column,
cellDraft,
),
);
}
} else {
commitSheet(selectedCount > 1
? updateExtraSheetCells(value, selectedPointsRef.current, { value: cellDraft })
: updateExtraSheetCell(value, active.row, active.column, cellDraft));
}
setCellDialogOpen(false);
}}>บันทึกเซลล์</Button>
setCellDialogOpen(false);
}}
>
บันทึกเซลล์
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
@@ -585,12 +769,18 @@ export function ExtraSheetEditor({
<Dialog open={labelDialogOpen} onOpenChange={setLabelDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{renaming ? "แก้ไขชื่อคอลัมน์" : "เพิ่มคอลัมน์"}</DialogTitle>
<DialogDescription>ตั้งชื่อที่ใช้อธิบายข้อมูลในคอลัมน์นี้</DialogDescription>
<DialogTitle>
{renaming ? "แก้ไขชื่อคอลัมน์" : "เพิ่มคอลัมน์"}
</DialogTitle>
<DialogDescription>
ตั้งชื่อที่ใช้อธิบายข้อมูลในคอลัมน์นี้
</DialogDescription>
</DialogHeader>
<FieldGroup>
<Field data-invalid={labelInvalid || undefined}>
<FieldLabel htmlFor="extra-sheet-column-label">ชื่อคอลัมน์</FieldLabel>
<FieldLabel htmlFor="extra-sheet-column-label">
ชื่อคอลัมน์
</FieldLabel>
<Input
id="extra-sheet-column-label"
value={columnLabel}
@@ -604,7 +794,11 @@ export function ExtraSheetEditor({
</Field>
</FieldGroup>
<DialogFooter showCloseButton>
<Button type="button" disabled={labelInvalid} onClick={saveColumnLabel}>
<Button
type="button"
disabled={labelInvalid}
onClick={saveColumnLabel}
>
{renaming ? "บันทึกชื่อ" : "เพิ่มคอลัมน์"}
</Button>
</DialogFooter>