Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import type { Meta, StoryObj } from "@storybook/react";
import { useState } from "react";
import { DataTable } from "./data-table";
import type { ColumnDef, SortingState } from "@tanstack/react-table";
import { Badge } from "../badge/badge";
import { Button } from "../button/button";
import { IconEdit, IconTrash } from "@humansignal/icons";
 
const meta: Meta<typeof DataTable> = {
  component: DataTable,
  title: "UI/DataTable",
  argTypes: {
    selectable: { control: "boolean" },
    enableSorting: { control: "boolean" },
  },
};
 
export default meta;
type Story = StoryObj<typeof DataTable>;
 
// Sample data
type User = {
  id: number;
  name: string;
  email: string;
  role: string;
  status: "active" | "inactive";
  lastActive: string;
};
 
const sampleData: User[] = [
  { id: 1, name: "John Doe", email: "john@example.com", role: "Admin", status: "active", lastActive: "2024-01-15" },
  { id: 2, name: "Jane Smith", email: "jane@example.com", role: "Editor", status: "active", lastActive: "2024-01-14" },
  {
    id: 3,
    name: "Bob Johnson",
    email: "bob@example.com",
    role: "Viewer",
    status: "inactive",
    lastActive: "2024-01-10",
  },
  {
    id: 4,
    name: "Alice Brown",
    email: "alice@example.com",
    role: "Editor",
    status: "active",
    lastActive: "2024-01-15",
  },
  {
    id: 5,
    name: "Charlie Wilson",
    email: "charlie@example.com",
    role: "Viewer",
    status: "active",
    lastActive: "2024-01-13",
  },
];
 
const baseColumns: ColumnDef<User>[] = [
  {
    accessorKey: "name",
    header: "Name",
    enableSorting: true,
  },
  {
    accessorKey: "email",
    header: "Email",
    enableSorting: true,
  },
  {
    accessorKey: "role",
    header: "Role",
    cell: ({ getValue }) => {
      const role = getValue() as string;
      return (
        <Badge variant={role === "Admin" ? "primary" : role === "Editor" ? "success" : "info"} size="small">
          {role}
        </Badge>
      );
    },
  },
  {
    accessorKey: "status",
    header: "Status",
    cell: ({ getValue }) => {
      const status = getValue() as string;
      return (
        <Badge variant={status === "active" ? "success" : "default"} size="small">
          {status}
        </Badge>
      );
    },
  },
  {
    accessorKey: "lastActive",
    header: "Last Active",
    enableSorting: true,
  },
];
 
/**
 * Basic DataTable
 *
 * Shows a simple table with data and columns.
 * Sorting is enabled with controlled state starting as empty (no sort applied).
 * Only columns with explicit `enableSorting: true` will be sortable (Name, Email, Last Active).
 */
export const Default: Story = {
  render: () => {
    const [sorting, setSorting] = useState<SortingState>([]);
 
    return (
      <DataTable data={sampleData} columns={baseColumns} enableSorting sorting={sorting} onSortingChange={setSorting} />
    );
  },
};
 
/**
 * Table with Sorting
 *
 * Default sorted by "name" ascending.
 * Click on sortable column headers to change sort direction.
 */
export const WithSorting: Story = {
  render: () => {
    const [sorting, setSorting] = useState<SortingState>([{ id: "name", desc: false }]);
 
    return (
      <div className="flex flex-col gap-4">
        <div className="p-4 bg-neutral-surface rounded-md">
          <p className="text-sm text-neutral-content-subtle">
            Click on column headers to sort. Current sort:{" "}
            {sorting.length > 0 ? `${sorting[0].id} (${sorting[0].desc ? "desc" : "asc"})` : "none"}
          </p>
        </div>
        <DataTable
          data={sampleData}
          columns={baseColumns}
          enableSorting
          sorting={sorting}
          onSortingChange={setSorting}
        />
      </div>
    );
  },
};
 
export const WithSelection: Story = {
  render: () => {
    const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
    const selectedCount = Object.keys(rowSelection).length;
 
    return (
      <div className="flex flex-col gap-4">
        <div className="p-4 bg-neutral-surface rounded-md">
          <p className="text-sm text-neutral-content-subtle">Selected rows: {selectedCount}</p>
        </div>
        <DataTable
          data={sampleData}
          columns={baseColumns}
          selectable
          rowSelection={rowSelection}
          onRowSelectionChange={setRowSelection}
        />
      </div>
    );
  },
};
 
export const WithRowClick: Story = {
  render: () => {
    const [clickedUser, setClickedUser] = useState<User | null>(null);
    const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
    const selectedCount = Object.keys(rowSelection).length;
 
    return (
      <div className="flex flex-col gap-4">
        <div className="p-4 bg-neutral-surface rounded-md flex justify-between items-center">
          <p className="text-sm text-neutral-content-subtle">
            {clickedUser ? `Last clicked: ${clickedUser.name}` : "Click on a row"}
          </p>
          <p className="text-sm text-neutral-content-subtle">Selected: {selectedCount}</p>
        </div>
        <DataTable
          data={sampleData}
          columns={baseColumns}
          selectable
          rowSelection={rowSelection}
          onRowSelectionChange={setRowSelection}
          onRowClick={(row) => setClickedUser(row ? row.original : null)}
        />
      </div>
    );
  },
};
 
export const WithActions: Story = {
  render: () => {
    const columnsWithActions: ColumnDef<User>[] = [
      ...baseColumns,
      {
        id: "actions",
        header: "Actions",
        cell: ({ row }) => (
          <div className="flex gap-2">
            <Button
              size="small"
              variant="neutral"
              look="outlined"
              leading={<IconEdit />}
              onClick={() => alert(`Edit ${row.original.name}`)}
            >
              Edit
            </Button>
            <Button
              size="small"
              variant="negative"
              look="outlined"
              leading={<IconTrash />}
              onClick={() => alert(`Delete ${row.original.name}`)}
            >
              Delete
            </Button>
          </div>
        ),
        meta: {
          noDivider: true,
        },
      },
    ];
 
    return <DataTable data={sampleData} columns={columnsWithActions} />;
  },
};
 
export const WithSortingAndSelection: Story = {
  render: () => {
    const [sorting, setSorting] = useState<SortingState>([]);
    const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
    const selectedCount = Object.keys(rowSelection).length;
 
    return (
      <div className="flex flex-col gap-4">
        <div className="p-4 bg-neutral-surface rounded-md flex justify-between items-center">
          <p className="text-sm text-neutral-content-subtle">
            Sort: {sorting.length > 0 ? `${sorting[0].id} (${sorting[0].desc ? "desc" : "asc"})` : "none"}
          </p>
          <p className="text-sm text-neutral-content-subtle">Selected: {selectedCount}</p>
        </div>
        <DataTable
          data={sampleData}
          columns={baseColumns}
          enableSorting
          selectable
          sorting={sorting}
          onSortingChange={setSorting}
          rowSelection={rowSelection}
          onRowSelectionChange={setRowSelection}
        />
      </div>
    );
  },
};
 
/**
 * Example with empty state when no data
 * Shows the default empty state with search icon and default messaging
 */
export const EmptyState: Story = {
  args: {
    data: [],
    columns: baseColumns,
    emptyState: {},
  },
};
 
/**
 * Custom Empty State with Actions
 *
 * Example showing a custom empty state with custom title, description, and action buttons.
 * Demonstrates how to provide interactive elements in the empty state.
 */
export const CustomEmptyStateWithActions: Story = {
  render: () => {
    return (
      <DataTable
        data={[]}
        columns={baseColumns}
        emptyState={{
          title: "No users found",
          description:
            "Get started by adding your first user to the system. You can import users or create them manually.",
          actions: (
            <div className="flex gap-2">
              <Button variant="primary" size="small" onClick={() => alert("Create user clicked")}>
                Create User
              </Button>
              <Button variant="neutral" look="outlined" size="small" onClick={() => alert("Import users clicked")}>
                Import Users
              </Button>
            </div>
          ),
        }}
      />
    );
  },
};
 
/**
 * Loading State
 *
 * Shows skeleton rows while data is loading.
 * Displays 5 skeleton rows by default (configurable with loadingRows prop).
 */
export const Loading: Story = {
  args: {
    data: [],
    columns: baseColumns,
    isLoading: true,
    loadingRows: 5,
  },
};
 
export const LargeDataset: Story = {
  render: () => {
    const [sorting, setSorting] = useState<SortingState>([]);
 
    // Generate 100 users
    const largeDataset = Array.from({ length: 100 }, (_, i) => ({
      id: i + 1,
      name: `User ${i + 1}`,
      email: `user${i + 1}@example.com`,
      role: ["Admin", "Editor", "Viewer"][i % 3],
      status: i % 3 === 0 ? ("inactive" as const) : ("active" as const),
      lastActive: new Date(2024, 0, (i % 30) + 1).toISOString().split("T")[0],
    }));
 
    return (
      <div className="flex flex-col gap-4">
        <div className="p-4 bg-neutral-surface rounded-md">
          <p className="text-sm text-neutral-content-subtle">
            Showing 100 users. Note: In production, you should use pagination or virtualization for large datasets.
          </p>
        </div>
        <div className="max-h-[500px] overflow-auto">
          <DataTable
            data={largeDataset}
            columns={baseColumns}
            enableSorting
            sorting={sorting}
            onSortingChange={setSorting}
            selectable
          />
        </div>
      </div>
    );
  },
};
 
export const CustomRowClassName: Story = {
  render: () => {
    return (
      <DataTable
        data={sampleData}
        columns={baseColumns}
        rowClassName={(row) => (row.original.status === "inactive" ? "opacity-50" : undefined)}
      />
    );
  },
};
 
export const WithColumnResizing: Story = {
  args: {
    data: sampleData,
    columns: baseColumns,
    cellSizesStorageKey: "storybook-table",
  },
};
 
export const FullFeatured: Story = {
  render: () => {
    const [sorting, setSorting] = useState<SortingState>([]);
    const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
    const selectedCount = Object.keys(rowSelection).length;
 
    const columnsWithActions: ColumnDef<User>[] = [
      ...baseColumns,
      {
        id: "actions",
        header: "Actions",
        cell: ({ row }) => (
          <div className="flex gap-2">
            <Button
              size="smaller"
              variant="neutral"
              look="outlined"
              leading={<IconEdit />}
              onClick={(e) => {
                e.stopPropagation();
                alert(`Edit ${row.original.name}`);
              }}
            >
              Edit
            </Button>
          </div>
        ),
        meta: {
          noDivider: true,
        },
      },
    ];
 
    return (
      <div className="flex flex-col gap-4">
        <div className="p-4 bg-neutral-surface rounded-md flex justify-between items-center">
          <p className="text-sm text-neutral-content-subtle">
            Sort: {sorting.length > 0 ? `${sorting[0].id} (${sorting[0].desc ? "desc" : "asc"})` : "none"}
          </p>
          <p className="text-sm text-neutral-content-subtle">Selected: {selectedCount}</p>
        </div>
        <DataTable
          data={sampleData}
          columns={columnsWithActions}
          enableSorting
          selectable
          sorting={sorting}
          onSortingChange={setSorting}
          rowSelection={rowSelection}
          onRowSelectionChange={setRowSelection}
          onRowClick={(row) => {
            if (row) {
              console.log("Row clicked:", row.original);
            }
          }}
          rowClassName={(row) => (row.original.status === "inactive" ? "opacity-50" : undefined)}
          cellSizesStorageKey="storybook-full-featured-table"
        />
      </div>
    );
  },
};
 
/**
 * Conditional Row Selection
 *
 * Use `isRowSelectable` to control which rows can be selected.
 * The checkbox will be hidden for non-selectable rows.
 *
 * In this example, inactive users cannot be selected.
 */
export const ConditionalRowSelection: Story = {
  render: () => {
    const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
    const selectedCount = Object.keys(rowSelection).length;
 
    return (
      <div className="flex flex-col gap-4">
        <div className="p-4 bg-neutral-surface rounded-md">
          <p className="text-sm text-neutral-content-subtle mb-2">
            Selected: <strong>{selectedCount}</strong> user{selectedCount !== 1 ? "s" : ""}
          </p>
          <p className="text-sm text-neutral-content-subtle">
            💡 Inactive users (Bob Johnson) cannot be selected - their checkbox is hidden
          </p>
        </div>
        <DataTable
          data={sampleData}
          columns={baseColumns}
          selectable
          rowSelection={rowSelection}
          onRowSelectionChange={setRowSelection}
          isRowSelectable={(row) => row.original.status === "active"}
        />
      </div>
    );
  },
};