@suphark/ui 0.25.0 → 0.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/package.json +1 -2
  3. package/src/components/app-shell/command-palette.tsx +8 -1
  4. package/src/components/data-table/data-table-sortable.tsx +154 -0
  5. package/src/components/data-table/data-table-toolbar.tsx +33 -4
  6. package/src/components/data-table/data-table.tsx +30 -142
  7. package/src/components/data-table/use-data-table.ts +8 -5
  8. package/src/components/design-system/design-system-showcase.tsx +63 -15
  9. package/src/components/pwa/pull-to-refresh.tsx +21 -1
  10. package/src/components/shared/action-menu.tsx +25 -6
  11. package/src/components/shared/auth-parts.tsx +5 -3
  12. package/src/components/shared/button/base/action-button.tsx +7 -14
  13. package/src/components/shared/button/base/link-button.tsx +5 -14
  14. package/src/components/shared/button/confirm-action-button.tsx +17 -3
  15. package/src/components/shared/chat-thread.tsx +7 -0
  16. package/src/components/shared/client-redirect.tsx +16 -1
  17. package/src/components/shared/form/date-time-picker.tsx +150 -0
  18. package/src/components/shared/form/form-field-autocomplete.tsx +93 -0
  19. package/src/components/shared/form/form-field-input.tsx +23 -81
  20. package/src/components/shared/form/number-input.tsx +19 -2
  21. package/src/components/shared/form/tags-input.tsx +7 -2
  22. package/src/components/shared/form/time-picker.tsx +34 -124
  23. package/src/components/shared/month-stepper.tsx +10 -4
  24. package/src/components/shared/row-actions.tsx +9 -3
  25. package/src/components/shared/settings-layout.tsx +17 -6
  26. package/src/components/shared/step-form.tsx +25 -4
  27. package/src/components/shared/time/client-date-formatter.tsx +2 -1
  28. package/src/components/shared/tree-view.tsx +6 -2
  29. package/src/components/shared/ui-text.tsx +3 -0
  30. package/src/components/ui/input.tsx +1 -1
  31. package/src/components/ui/native-select.tsx +1 -1
  32. package/src/components/ui/select.tsx +1 -1
  33. package/src/components/ui/textarea.tsx +1 -1
  34. package/src/hooks/use-table-search-params.ts +10 -2
  35. package/src/hooks/use-ticker.ts +11 -5
  36. package/src/index.ts +1 -1
  37. package/src/lib/formatters.ts +1 -1
  38. package/src/lib/month.ts +14 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,66 @@
2
2
 
3
3
  รูปแบบตาม [Keep a Changelog](https://keepachangelog.com/) · semver: patch = หน้าตา/บั๊ก, minor = component/prop ใหม่, major = เปลี่ยน/ลบ props
4
4
 
5
+ ## [0.26.0] — 2026-10-03
6
+
7
+ ปิดงานค้างจากผลรีวิว + prop ที่ DueBell ขอ — เพิ่มอย่างเดียว
8
+
9
+ ### Added
10
+
11
+ - `NumberInput`: `inputRef` (ref ของช่องที่พิมพ์ — focus เองได้) และ `autoFocus` (คำขอจาก DueBell)
12
+ - `TimePicker`: `roundToStep` — ปัดนาทีที่พิมพ์ลงตาม `minuteStep` (เช่น step 60 + พิมพ์ 14:30 → 14:00); ค่าเริ่มต้นเก็บตามที่พิมพ์เหมือนเดิม (คำขอจาก DueBell)
13
+
14
+ ### Changed
15
+
16
+ - **ช่องกรอกใช้ขนาดตัวอักษรตามบทบาท `text-body`** (16px มือถือ / 15px จอกว้าง) — `Input`, `Textarea`, `SelectTrigger`, `NativeSelect` (+ `NumberInput`, `TagsInput`): เดิม `text-base md:text-sm` = 14px บนจอกว้าง เล็กกว่าข้อความรอบข้าง 1px และ `text-body` ที่แอปใส่ให้ช่องได้ผลแค่มือถือ (pi-done ต้องเติม `md:text-body` เอง 19 จุด — ลบได้แล้ว); `SelectTrigger`/`NativeSelect` เดิม 14px แม้บนมือถือ (iOS ซูมเมื่อโฟกัส) — แก้ไฟล์ shadcn 4 ไฟล์เป็นข้อยกเว้น (เพิ่มในรายการคืนไฟล์หลัง `shadcn add --overwrite` ใน CLAUDE.md); `className` ของแอปยังแทนได้ (`cn` รู้จักคลาสตามบทบาท)
17
+ - ปุ่ม `ActionButton`/`LinkButton` ที่มี tooltip ไม่สร้าง `TooltipProvider` ต่อปุ่มแล้ว (ตาราง 50 แถว = 100+ provider) — ใช้ `delay={0}` ที่ trigger แทน หน้าตา/จังหวะเหมือนเดิม
18
+ - `DesignSystemShowcase`: แท็บอื่นนอกจาก "ภาพรวม" โหลดแบบ lazy เมื่อเปิดแท็บ (เดิม import ทุกแท็บ ~1 MB) — ลิงก์ข้ามแท็บไปหัวข้อรอแท็บโหลดเสร็จก่อนเลื่อน
19
+ - ลบ dependency `cn` ที่ไม่ได้ใช้ (แอปไม่ต้องติดตั้งเพิ่ม)
20
+ - docs: agent-rules — barrel ที่ client import ห้าม re-export schema ของ zod (ค่า) ให้ export แค่ type (DueBell −18% ต่อหน้า); `ChartConfig` ใช้เฉพาะค่าที่แอปกำหนดเอง (ค่าถูกเขียนลง `<style>` ตรง ๆ)
21
+ - CI: `permissions: contents: read` (+ `pull-requests: read` ให้ gitleaks) — GITHUB_TOKEN อ่านได้อย่างเดียว; pin action ด้วย commit SHA (checkout v4.4.0, gitleaks-action v2.3.9, pnpm/action-setup v4.3.0, setup-node v4.4.0)
22
+ - showcase: `/components/[slug]` โหลด demo แบบ `next/dynamic` ต่อ slug (`src/docs/demos.tsx` + `DemoView`) — เดิมทุกหน้าโหลด demo ทั้ง 129 ตัว (~409 kB gzip ต่อหน้า เช่น `/components/badge` พก recharts)
23
+ - showcase: demo `code-block`/`secret-reveal` ใช้ค่า `example_…` แทน `sk_live_…` (ไม่ให้ secret scanner แจ้งเตือนผิด)
24
+ - showcase: `@suphark/auth-client` ^0.1.7 → **^0.6.1** (แก้ open redirect ใน `safeNextPath` ของ handler `/auth/login|callback|logout` — ทดสอบ `/auth/logout?next=/%09/evil.com` แล้วไม่ออกนอกโดเมน); breaking ระหว่างทาง (ลบ Prisma adapter, เปลี่ยนชื่อ `ACCESS_DENIED`) ไม่กระทบ showcase
25
+
26
+ ## [0.25.1] — 2026-10-02
27
+
28
+ แก้ตามผลรีวิว codebase (bug / security / performance) — ไม่เปลี่ยน props
29
+
30
+ ### Fixed
31
+
32
+ - **`NumberInput`**: input ซ่อนของ Base UI (ที่ส่งค่าใน FormData) ได้ `step` ไปด้วย → browser ปฏิเสธค่าทศนิยม/ค่าที่ไม่ลง step นับจาก `min` แล้ว **บล็อก submit เงียบ ๆ** (เช่น 1500.5 เมื่อ step=1, 150 เมื่อ min=0 step=100 — DueBell เจอ) → input ซ่อนใช้ `step="any"` (ปุ่ม −/+ ยังเลื่อนตาม `step`; min/max ยังตรวจ)
33
+ - **`TimePicker`**: พิมพ์ผิดรูปแบบแล้วกดส่ง ฟอร์มเคยส่งค่าเดิมไปเงียบ ๆ → ช่องเป็น invalid จริง (`setCustomValidity`, ข้อความ `UiText.time.invalid`) ฟอร์มไม่ส่งจนแก้
34
+ - **`DateTimePicker`**: แยกไฟล์ (`form/date-time-picker.tsx`); ข้อความวัน/เวลาและค่าใน input ซ่อนคำนวณหลัง hydrate (เดิม server UTC กับ browser ต่างกัน 7 ชม. = hydration mismatch เมื่อมีค่าเริ่มต้น); **`name` ส่ง `"YYYY-MM-DDTHH:mm+07:00"` (มี offset)** แทนค่าที่ไม่มีโซนเวลา → `new Date(formData.get(name))` บน server ได้เวลาที่ถูก (เดิมคลาด 7 ชม.)
35
+ - `TimeColumns`: เลื่อนเฉพาะในคอลัมน์ (เดิม `scrollIntoView` เลื่อนทั้งหน้าทุกครั้งที่เลือก)
36
+ - **`MonthStepper` / `useMonthCursor`**: "เดือนนี้" คิดตามเวลาไทย (`Asia/Bangkok`) ให้ server กับ browser ตรงกัน — เดิมช่วง 00:00–06:59 ของวันที่ 1 ทุกเดือน server (UTC) เห็นเดือนก่อน = hydration mismatch; `currentMonthKey(now?, timeZone?)` รับโซนเวลาได้ (ไม่ส่ง = เครื่องเหมือนเดิม)
37
+ - **`StepForm`**: ดับเบิลคลิกปุ่มส่ง/ถัดไปเคยเรียก `onSubmit` 2 ครั้ง หรือข้ามหน้าตรวจทาน (คลิกที่สองตกที่ปุ่ม "ส่ง" ตำแหน่งเดิม) → กันซ้ำแบบ synchronous + ไม่นับคลิกภายใน 500 ms หลังเปลี่ยนขั้น; input ซ่อนของ Base UI ผิด → โฟกัสช่องที่มองเห็นของมันเอง (เดิมโฟกัสช่องแรกของขั้น)
38
+ - **`RowActions` / `ConfirmActionButton`**: action ที่คืน `FormState` `{ ok: false, error }` (ไม่ได้ throw) เคยถูกถือว่าสำเร็จ (ปิด dialog + refresh ไม่มีข้อความ) → toast error + คง dialog ไว้ (`failedResult`)
39
+ - **`ActionMenu`**: รายการที่มี `href` + `confirm` เคยไปเลยโดยไม่ถาม → ถามก่อนแล้วค่อยไป; `onClick` ที่ throw/reject แสดง toast และคง dialog ไว้ (เดิม unhandled rejection เงียบ)
40
+ - `ChatThread`: `onSend` ล้มเหลว = toast + คงข้อความในช่องไว้ให้ลองใหม่
41
+ - `CommandPalette`: คีย์ลัดเทียบ `e.code` — แป้นภาษาไทย Ctrl+K ใช้ได้แล้ว (เดิม `e.key` = "า")
42
+ - `SettingsLayout`: มือถือกด "กลับ" แล้วคืนโฟกัสไปหัวข้อเดิม (เดิมหลุดไป body); จอกว้างไม่ย้ายโฟกัสไปหัวข้อ (เดิมย้ายแค่ครั้งแรก)
43
+ - `TagsInput`: วางหลายค่าแทรกที่ cursor ของข้อความที่พิมพ์ค้าง (เดิมทิ้งข้อความนั้น)
44
+ - `ProviderButtons`: ปุ่มที่ `pendingId` ตรงแสดง spinner และกดซ้ำไม่ได้ (รวมแบบ `href`)
45
+ - `useTicker`: subscribe คงที่ข้าม render — เดิมสมัครใหม่ทุก render ทำให้ "x นาทีที่แล้ว" ไม่อัปเดตถ้า parent render บ่อยกว่า interval
46
+ - `useTableSearchParams`: setter หลายตัวติดกัน (เช่น setFilter แล้ว setSort) ต่อจากค่าที่เพิ่งตั้ง (เดิมตัวหลังทับตัวแรก)
47
+ - `useDataTable`: sync `columnFilters` ตามค่า (เดิมตามตัวอ้างอิง → array literal ทำให้ render ซ้ำ + ทับตัวกรองที่ผู้ใช้เพิ่งเลือก)
48
+
49
+ ### Security
50
+
51
+ - `ClientRedirect`: รับเฉพาะ http(s)/path — ปฏิเสธ `javascript:`/`data:` (`location.replace` ไม่มีตัวกันแบบ `<a href>`/router)
52
+ - showcase: `/login` ใช้ `safeNextPath` (`src/lib/safe-next.ts`) กัน open redirect `next=/%09/evil.com` (WHATWG URL ตัด tab → `//evil.com`); production (`VERCEL_ENV=production`) ที่ไม่มี env ของ Pi Auth หรือตั้ง `PI_AUTH_DISABLED` = build ล้ม แทนเปิดเว็บสาธารณะเงียบ ๆ — ตัว `safeNextPath` ของ `@suphark/auth-client` แก้ใน repo auth แล้ว (0.6.1 รอ publish)
53
+
54
+ ### Performance
55
+
56
+ - **`DataTable`**: ส่วนลากเรียง (dnd-kit ~16 kB gzip) แยกเป็น `data-table-sortable.tsx` โหลดแบบ lazy เฉพาะเมื่อส่ง `onReorder` — เดิมทุกตารางพกไปด้วย
57
+ - **`FormFieldInput`**: variant `autocomplete` (cmdk + Radix Dialog ที่ cmdk พ่วงมา) แยกเป็น `form-field-autocomplete.tsx` โหลดแบบ lazy — เดิมทุกฟอร์มที่ใช้ช่องข้อความธรรมดาพก cmdk
58
+ - `DataTable` ช่องค้นหา: ส่งให้ตารางเมื่อหยุดพิมพ์ 250 ms (Enter = ทันที) — เดิมกรอง/เรียง/render ทุกแถว (และ `router.replace` ถ้าผูก URL) ทุกตัวอักษร
59
+ - `TimePicker` ไม่พา react-day-picker มาด้วยแล้ว (แยก `DateTimePicker`); import locale ตรงไฟล์ (`date-fns/locale/th`, `date-fns/locale/en-US`, `react-day-picker/locale/th`) — dev server ไม่ต้อง compile locale ทั้ง ~700 ไฟล์
60
+ - `PullToRefresh`: ติดตั้ง `touchmove` แบบ non-passive เฉพาะตอนจอมือถือ + หน้าอยู่บนสุด (เดิมติดตลอด → browser ต้องรอ JS ก่อนเลื่อนทุกครั้ง)
61
+ - `TreeView`: `expandedIds` แบบ controlled ไม่ทำให้ memo ของแถวคำนวณใหม่ทุก render
62
+ - showcase: หน้า number-input อธิบาย step ตามพฤติกรรมใหม่
63
+ - tests 12 กรณี (`fixes-0-25-1.test.tsx`, `lazy-parts.test.tsx` + StepForm/NumberInput ใน `inputs-0-25.test.tsx`)
64
+
5
65
  ## [0.25.0] — 2026-10-02
6
66
 
7
67
  input ใหม่ตามแผนจาก shadcnstudio.com — เพิ่มอย่างเดียว
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suphark/ui",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Design system กลางของ Suphark apps: shadcn/ui (base-nova, Base UI, Tailwind v4) + shared components + token/ฟอนต์ Noto Sans Thai Looped — ส่งเป็น source ให้แอป Next transpile เอง",
@@ -72,7 +72,6 @@
72
72
  "class-variance-authority": "^0.7.1",
73
73
  "clsx": "^2.1.1",
74
74
  "cmdk": "^1.1.1",
75
- "cn": "^0.3.0",
76
75
  "date-fns": "^4.4.0",
77
76
  "embla-carousel-react": "^8.6.0",
78
77
  "input-otp": "^1.5.0",
@@ -148,8 +148,15 @@ export function CommandPalette({
148
148
  useEffect(() => {
149
149
  if (!shortcut) return;
150
150
  const key = shortcut.toLowerCase();
151
+ // เทียบตำแหน่งปุ่ม (e.code) สำหรับตัวอักษร/ตัวเลข — แป้นไทย Ctrl+K ให้ e.key = "า" แต่ e.code ยังเป็น "KeyK"
152
+ const code = /^[a-z]$/.test(key)
153
+ ? `Key${key.toUpperCase()}`
154
+ : /^\d$/.test(key)
155
+ ? `Digit${key}`
156
+ : null;
151
157
  const onKey = (e: KeyboardEvent) => {
152
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === key) {
158
+ const matches = e.key.toLowerCase() === key || (code !== null && e.code === code);
159
+ if ((e.metaKey || e.ctrlKey) && matches) {
153
160
  e.preventDefault();
154
161
  setOpenRef.current(!openRef.current);
155
162
  }
@@ -0,0 +1,154 @@
1
+ "use client";
2
+
3
+ /**
4
+ * ส่วนลากเรียงแถวของ DataTable (dnd-kit) — แยกไฟล์และโหลดแบบ lazy เฉพาะเมื่อส่ง `onReorder`
5
+ * เดิม import ที่ data-table.tsx ทำให้ทุกตารางพก dnd-kit (~16 kB gzip) แม้แทบไม่มีตารางไหนลากเรียง
6
+ */
7
+ import {
8
+ closestCenter,
9
+ DndContext,
10
+ type DragEndEvent,
11
+ KeyboardSensor,
12
+ PointerSensor,
13
+ useSensor,
14
+ useSensors,
15
+ } from "@dnd-kit/core";
16
+ import {
17
+ arrayMove,
18
+ SortableContext,
19
+ sortableKeyboardCoordinates,
20
+ useSortable,
21
+ verticalListSortingStrategy,
22
+ } from "@dnd-kit/sortable";
23
+ import { CSS } from "@dnd-kit/utilities";
24
+ import { TableCell, TableRow } from "@suphark/ui/components/ui/table";
25
+ import { cn } from "@suphark/ui/lib/utils";
26
+ import { flexRender, type Row, type Table } from "@tanstack/react-table";
27
+ import type { CSSProperties, ReactNode } from "react";
28
+ import { toast } from "sonner";
29
+
30
+ interface RowStyleProps<TData> {
31
+ enableColumnResizing?: boolean;
32
+ getRowClassName?: (row: Row<TData>) => string;
33
+ stickyEdgeColumns?: boolean;
34
+ }
35
+
36
+ function DraggableRow<TData>({
37
+ row,
38
+ enableColumnResizing,
39
+ getRowClassName,
40
+ stickyEdgeColumns,
41
+ }: RowStyleProps<TData> & { row: Row<TData> }) {
42
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
43
+ id: row.id,
44
+ });
45
+
46
+ const style: CSSProperties = {
47
+ transform: CSS.Transform.toString(transform),
48
+ transition,
49
+ opacity: isDragging ? 0.8 : 1,
50
+ zIndex: isDragging ? 1 : 0,
51
+ position: "relative",
52
+ };
53
+
54
+ return (
55
+ <TableRow
56
+ ref={setNodeRef}
57
+ style={style}
58
+ data-state={row.getIsSelected() && "selected"}
59
+ className={cn(stickyEdgeColumns && "group/row", getRowClassName?.(row))}
60
+ >
61
+ {row.getVisibleCells().map((cell) => {
62
+ const isDndColumn = cell.column.id === "dnd-handle";
63
+ return (
64
+ <TableCell
65
+ key={cell.id}
66
+ {...(isDndColumn ? { ...attributes, ...listeners } : {})}
67
+ style={{
68
+ width: enableColumnResizing ? cell.column.getSize() : undefined,
69
+ }}
70
+ className={cn(
71
+ stickyEdgeColumns &&
72
+ cell.column.id === "select" &&
73
+ "sticky left-0 z-10 bg-card group-hover/row:bg-muted group-data-[state=selected]/row:bg-muted",
74
+ stickyEdgeColumns &&
75
+ cell.column.id === "actions" &&
76
+ "sticky right-0 z-10 bg-card group-hover/row:bg-muted group-data-[state=selected]/row:bg-muted",
77
+ )}
78
+ >
79
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
80
+ </TableCell>
81
+ );
82
+ })}
83
+ </TableRow>
84
+ );
85
+ }
86
+
87
+ /** แถวที่ลากได้ (อยู่ใน TableBody) */
88
+ export function SortableTableRows<TData>({
89
+ rows,
90
+ ...rowProps
91
+ }: RowStyleProps<TData> & { rows: Row<TData>[] }) {
92
+ return (
93
+ <SortableContext items={rows.map((row) => row.id)} strategy={verticalListSortingStrategy}>
94
+ {rows.map((row) => (
95
+ <DraggableRow key={row.id} row={row} {...rowProps} />
96
+ ))}
97
+ </SortableContext>
98
+ );
99
+ }
100
+
101
+ /** DndContext + sensor + คำนวณลำดับใหม่ (ครอบตารางทั้งตัว) */
102
+ export function SortableTableProvider<TData>({
103
+ table,
104
+ data,
105
+ getRowId,
106
+ onReorder,
107
+ children,
108
+ }: {
109
+ table: Table<TData>;
110
+ data: TData[];
111
+ getRowId?: (row: TData) => string;
112
+ onReorder: (data: TData[]) => void;
113
+ children: ReactNode;
114
+ }) {
115
+ const sensors = useSensors(
116
+ useSensor(PointerSensor, {
117
+ activationConstraint: {
118
+ distance: 5,
119
+ },
120
+ }),
121
+ useSensor(KeyboardSensor, {
122
+ coordinateGetter: sortableKeyboardCoordinates,
123
+ }),
124
+ );
125
+
126
+ function handleDragEnd(event: DragEndEvent) {
127
+ const state = table.getState();
128
+ const isFiltered = state.columnFilters.length > 0 || state.globalFilter;
129
+ const isSorted = state.sorting.length > 0;
130
+
131
+ if (isFiltered || isSorted) {
132
+ toast.warning("Cannot reorder while filtering or sorting is active.");
133
+ return;
134
+ }
135
+
136
+ const { active, over } = event;
137
+ if (over && active.id !== over.id) {
138
+ const idOf = (item: TData) =>
139
+ getRowId ? getRowId(item) : (item as { id?: string | number }).id;
140
+ const oldIndex = data.findIndex((item) => idOf(item) === active.id);
141
+ const newIndex = data.findIndex((item) => idOf(item) === over.id);
142
+
143
+ if (oldIndex !== -1 && newIndex !== -1) {
144
+ onReorder(arrayMove(data, oldIndex, newIndex));
145
+ }
146
+ }
147
+ }
148
+
149
+ return (
150
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
151
+ {children}
152
+ </DndContext>
153
+ );
154
+ }
@@ -21,6 +21,7 @@ import {
21
21
  import type { Table } from "@tanstack/react-table";
22
22
  import { Search, SlidersHorizontal, X } from "lucide-react";
23
23
  import type React from "react";
24
+ import { useEffect, useRef, useState } from "react";
24
25
  import type { FacetedFilterConfig } from ".";
25
26
  import { DataTableFacetedFilter } from "./data-table-faceted-filter";
26
27
  import { DataTableViewOptions } from "./data-table-view-option";
@@ -43,6 +44,31 @@ export function DataTableToolbar<TData>({
43
44
  preservedFilterIds = [],
44
45
  }: DataTableToolbarProps<TData>) {
45
46
  const globalFilter = table.getState().globalFilter;
47
+ // ค้นหา: เก็บข้อความในช่องเอง แล้วส่งให้ตารางเมื่อหยุดพิมพ์ 250 ms — เดิมกรอง/เรียง/render ทุกแถวทุกตัวอักษร
48
+ // (และถ้าแอปผูก globalFilter กับ URL = router.replace ทุกตัวอักษร)
49
+ const [searchDraft, setSearchDraft] = useState<string>((globalFilter as string) ?? "");
50
+ const committed = useRef<string>((globalFilter as string) ?? "");
51
+ useEffect(() => {
52
+ // ค่าเปลี่ยนจากข้างนอก (ล้างตัวกรอง / URL) → ตามให้ตรง
53
+ const external = (globalFilter as string) ?? "";
54
+ if (external !== committed.current) {
55
+ committed.current = external;
56
+ setSearchDraft(external);
57
+ }
58
+ }, [globalFilter]);
59
+ useEffect(() => {
60
+ if (searchDraft === committed.current) return;
61
+ const timer = setTimeout(() => {
62
+ committed.current = searchDraft;
63
+ table.setGlobalFilter(searchDraft);
64
+ }, 250);
65
+ return () => clearTimeout(timer);
66
+ }, [searchDraft, table]);
67
+ const commitSearch = (value: string) => {
68
+ setSearchDraft(value);
69
+ committed.current = value;
70
+ table.setGlobalFilter(value);
71
+ };
46
72
  const preservedFilterIdSet = new Set(preservedFilterIds);
47
73
  const userColumnFilters = table
48
74
  .getState()
@@ -88,15 +114,18 @@ export function DataTableToolbar<TData>({
88
114
  name="table-search"
89
115
  autoComplete="off"
90
116
  placeholder={globalFilterPlaceholder}
91
- value={(globalFilter as string) ?? ""}
92
- onChange={(event) => table.setGlobalFilter(String(event.target.value))}
117
+ value={searchDraft}
118
+ onChange={(event) => setSearchDraft(event.target.value)}
119
+ onKeyDown={(event) => {
120
+ if (event.key === "Enter") commitSearch(searchDraft);
121
+ }}
93
122
  />
94
- {!!globalFilter && (
123
+ {!!searchDraft && (
95
124
  <InputGroupAddon align="inline-end">
96
125
  <InputGroupButton
97
126
  variant="ghost"
98
127
  aria-label="ล้างคำค้นหา"
99
- onClick={() => table.setGlobalFilter("")}
128
+ onClick={() => commitSearch("")}
100
129
  >
101
130
  <X aria-hidden="true" className="size-4" />
102
131
  </InputGroupButton>
@@ -1,22 +1,5 @@
1
1
  "use client";
2
2
 
3
- import {
4
- closestCenter,
5
- DndContext,
6
- type DragEndEvent,
7
- KeyboardSensor,
8
- PointerSensor,
9
- useSensor,
10
- useSensors,
11
- } from "@dnd-kit/core";
12
- import {
13
- arrayMove,
14
- SortableContext,
15
- sortableKeyboardCoordinates,
16
- useSortable,
17
- verticalListSortingStrategy,
18
- } from "@dnd-kit/sortable";
19
- import { CSS } from "@dnd-kit/utilities";
20
3
  import {
21
4
  TableBody,
22
5
  TableCell,
@@ -26,72 +9,22 @@ import {
26
9
  Table as UiTable,
27
10
  } from "@suphark/ui/components/ui/table";
28
11
  import { cn } from "@suphark/ui/lib/utils";
29
- import { flexRender, type Row } from "@tanstack/react-table";
30
- import type { CSSProperties } from "react";
12
+ import { flexRender } from "@tanstack/react-table";
31
13
  import * as React from "react";
32
- import { toast } from "sonner";
33
14
  import { DataTablePagination } from "./data-table-pagination";
34
15
  import { DataTableToolbar } from "./data-table-toolbar";
35
16
  import type { DataTableProps } from "./types";
36
17
  import { useDataTable } from "./use-data-table";
37
18
 
38
- interface DraggableRowProps<TData> {
39
- row: Row<TData>;
40
- enableColumnResizing?: boolean;
41
- getRowClassName?: (row: Row<TData>) => string;
42
- stickyEdgeColumns?: boolean;
43
- }
44
-
45
- function DraggableRow<TData>({
46
- row,
47
- enableColumnResizing,
48
- getRowClassName,
49
- stickyEdgeColumns,
50
- }: DraggableRowProps<TData>) {
51
- const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
52
- id: row.id,
53
- });
54
-
55
- const style: CSSProperties = {
56
- transform: CSS.Transform.toString(transform),
57
- transition,
58
- opacity: isDragging ? 0.8 : 1,
59
- zIndex: isDragging ? 1 : 0,
60
- position: "relative",
61
- };
62
-
63
- return (
64
- <TableRow
65
- ref={setNodeRef}
66
- style={style}
67
- data-state={row.getIsSelected() && "selected"}
68
- className={cn(stickyEdgeColumns && "group/row", getRowClassName?.(row))}
69
- >
70
- {row.getVisibleCells().map((cell) => {
71
- const isDndColumn = cell.column.id === "dnd-handle";
72
- return (
73
- <TableCell
74
- key={cell.id}
75
- {...(isDndColumn ? { ...attributes, ...listeners } : {})}
76
- style={{
77
- width: enableColumnResizing ? cell.column.getSize() : undefined,
78
- }}
79
- className={cn(
80
- stickyEdgeColumns &&
81
- cell.column.id === "select" &&
82
- "sticky left-0 z-10 bg-card group-hover/row:bg-muted group-data-[state=selected]/row:bg-muted",
83
- stickyEdgeColumns &&
84
- cell.column.id === "actions" &&
85
- "sticky right-0 z-10 bg-card group-hover/row:bg-muted group-data-[state=selected]/row:bg-muted",
86
- )}
87
- >
88
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
89
- </TableCell>
90
- );
91
- })}
92
- </TableRow>
93
- );
94
- }
19
+ // ส่วนลากเรียง (dnd-kit) โหลดเฉพาะตารางที่ส่ง onReorder
20
+ // (React.lazy ทิ้ง generic ของ TData — cast กลับเป็นชนิดของต้นฉบับ)
21
+ type SortableModule = typeof import("./data-table-sortable");
22
+ const SortableTableProvider = React.lazy(() =>
23
+ import("./data-table-sortable").then((m) => ({ default: m.SortableTableProvider })),
24
+ ) as unknown as SortableModule["SortableTableProvider"];
25
+ const SortableTableRows = React.lazy(() =>
26
+ import("./data-table-sortable").then((m) => ({ default: m.SortableTableRows })),
27
+ ) as unknown as SortableModule["SortableTableRows"];
95
28
 
96
29
  /**
97
30
  * DataTable
@@ -181,51 +114,7 @@ export function DataTable<TData, TValue>({
181
114
  enableRowSelection,
182
115
  });
183
116
 
184
- const sensors = useSensors(
185
- useSensor(PointerSensor, {
186
- activationConstraint: {
187
- distance: 5,
188
- },
189
- }),
190
- useSensor(KeyboardSensor, {
191
- coordinateGetter: sortableKeyboardCoordinates,
192
- }),
193
- );
194
-
195
- function handleDragEnd(event: DragEndEvent) {
196
- if (!onReorder) return;
197
-
198
- const state = table.getState();
199
- const isFiltered = state.columnFilters.length > 0 || state.globalFilter;
200
- const isSorted = state.sorting.length > 0;
201
-
202
- if (isFiltered || isSorted) {
203
- toast.warning("Cannot reorder while filtering or sorting is active.");
204
- return;
205
- }
206
-
207
- const { active, over } = event;
208
- if (over && active.id !== over.id) {
209
- const oldIndex = data.findIndex((item) => {
210
- const id = getRowId ? getRowId(item) : (item as { id?: string | number }).id;
211
- return id === active.id;
212
- });
213
- const newIndex = data.findIndex((item) => {
214
- const id = getRowId ? getRowId(item) : (item as { id?: string | number }).id;
215
- return id === over.id;
216
- });
217
-
218
- if (oldIndex !== -1 && newIndex !== -1) {
219
- const newData = arrayMove(data, oldIndex, newIndex);
220
- onReorder(newData);
221
- }
222
- }
223
- }
224
-
225
- const tableRows = table.getRowModel().rows;
226
- const rowIds = React.useMemo(() => tableRows.map((row) => row.id), [tableRows]);
227
-
228
- const tableContent = (
117
+ const renderTable = (sortable: boolean) => (
229
118
  <UiTable
230
119
  className={cn(
231
120
  "w-full border-collapse",
@@ -292,18 +181,13 @@ export function DataTable<TData, TValue>({
292
181
  </TableRow>
293
182
  ))
294
183
  ) : table.getRowModel().rows?.length ? (
295
- onReorder ? (
296
- <SortableContext items={rowIds} strategy={verticalListSortingStrategy}>
297
- {table.getRowModel().rows.map((row) => (
298
- <DraggableRow
299
- key={row.id}
300
- row={row}
301
- enableColumnResizing={enableColumnResizing}
302
- getRowClassName={getRowClassName}
303
- stickyEdgeColumns={stickyEdgeColumns}
304
- />
305
- ))}
306
- </SortableContext>
184
+ sortable ? (
185
+ <SortableTableRows
186
+ rows={table.getRowModel().rows}
187
+ enableColumnResizing={enableColumnResizing}
188
+ getRowClassName={getRowClassName}
189
+ stickyEdgeColumns={stickyEdgeColumns}
190
+ />
307
191
  ) : (
308
192
  table.getRowModel().rows.map((row) => (
309
193
  <TableRow
@@ -374,15 +258,19 @@ export function DataTable<TData, TValue>({
374
258
  <>
375
259
  <div className="overflow-x-auto rounded-lg border bg-card shadow-sm max-sm:-mx-2 max-sm:rounded-none max-sm:border-x-0">
376
260
  {onReorder ? (
377
- <DndContext
378
- sensors={sensors}
379
- collisionDetection={closestCenter}
380
- onDragEnd={handleDragEnd}
381
- >
382
- {tableContent}
383
- </DndContext>
261
+ // ระหว่างโหลดส่วนลากเรียง แสดงตารางปกติไปก่อน (ลากไม่ได้ชั่วคราว)
262
+ <React.Suspense fallback={renderTable(false)}>
263
+ <SortableTableProvider
264
+ table={table}
265
+ data={data}
266
+ getRowId={getRowId}
267
+ onReorder={onReorder}
268
+ >
269
+ {renderTable(true)}
270
+ </SortableTableProvider>
271
+ </React.Suspense>
384
272
  ) : (
385
- tableContent
273
+ renderTable(false)
386
274
  )}
387
275
  </div>
388
276
  {showPagination && (
@@ -66,12 +66,15 @@ export function useDataTable<TData, TValue>({
66
66
  columnFiltersProp ?? initialColumnFilters,
67
67
  );
68
68
 
69
- // Sync with prop if provided
69
+ // Sync with prop if provided — เทียบด้วยค่าเหมือน sorting/pagination: ผู้เรียกมักส่ง array literal ใหม่ทุก render
70
+ // ถ้าผูกกับตัวอ้างอิง effect จะรันทุก render → render ซ้ำ + ล้าง memo ของ row model + ทับตัวกรองที่ผู้ใช้เพิ่งเลือก
71
+ const columnFiltersKey = columnFiltersProp ? JSON.stringify(columnFiltersProp) : undefined;
70
72
  React.useEffect(() => {
71
- if (columnFiltersProp !== undefined) {
72
- setColumnFilters(columnFiltersProp);
73
- }
74
- }, [columnFiltersProp]);
73
+ if (columnFiltersKey === undefined) return;
74
+ setColumnFilters((current) =>
75
+ JSON.stringify(current) === columnFiltersKey ? current : JSON.parse(columnFiltersKey),
76
+ );
77
+ }, [columnFiltersKey]);
75
78
  const [sorting, setSorting] = React.useState<SortingState>(
76
79
  () => sortingProp ?? (initialState?.sorting as SortingState | undefined) ?? [],
77
80
  );