forked from emdash-cms/emdash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContentList.tsx
More file actions
1212 lines (1154 loc) · 36 KB
/
Copy pathContentList.tsx
File metadata and controls
1212 lines (1154 loc) · 36 KB
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Badge,
Button,
Checkbox,
Dialog,
Input,
LinkButton,
Loader,
Select,
Tabs,
} from "@cloudflare/kumo";
import { plural } from "@lingui/core/macro";
import { useLingui } from "@lingui/react/macro";
import {
Plus,
Pencil,
Trash,
ArrowCounterClockwise,
ArrowSquareOut,
Copy,
MagnifyingGlass,
CaretUp,
CaretDown,
CaretUpDown,
Upload,
X,
} from "@phosphor-icons/react";
import { Link } from "@tanstack/react-router";
import * as React from "react";
import type { ContentAuthor, ContentDateField, ContentItem, TrashedContentItem } from "../lib/api";
import { useDebouncedValue } from "../lib/hooks.js";
import { contentUrl } from "../lib/url.js";
import { cn } from "../lib/utils";
import { CaretNext, CaretPrev } from "./ArrowIcons.js";
import {
BylineFilter,
EMPTY_BYLINE_FILTER,
isBylineFilterActive,
type BylineFilterState,
} from "./BylineFilter.js";
import {
ContentStatusBadge,
ContentStatusLabel,
isContentStatusState,
} from "./ContentStatusBadge.js";
import { LocaleSwitcher } from "./LocaleSwitcher";
import { RouterLinkButton } from "./RouterLinkButton.js";
/** Sortable content list columns. Maps to the server's order field whitelist. */
export type ContentListSortField = "title" | "status" | "locale" | "updatedAt";
export interface ContentListSort {
field: ContentListSortField;
direction: "asc" | "desc";
}
/** Status filter values. `"all"` clears the status filter. */
export type ContentStatusFilter = "all" | "published" | "draft" | "scheduled" | "archived";
/**
* Date-range filter state. `from`/`to` are raw `YYYY-MM-DD` values from the
* date inputs (empty string = unset); the parent converts them to UTC day
* boundaries before calling the API.
*/
export interface ContentDateFilter {
field: ContentDateField;
from: string;
to: string;
}
/** An empty (inactive) date filter, defaulting to the created-at column. */
export const EMPTY_DATE_FILTER: ContentDateFilter = { field: "createdAt", from: "", to: "" };
export interface ContentListProps {
collection: string;
collectionLabel: string;
items: ContentItem[];
trashedItems?: TrashedContentItem[];
isLoading?: boolean;
isTrashedLoading?: boolean;
onDelete?: (id: string) => void;
onDuplicate?: (id: string) => void;
onRestore?: (id: string) => void;
onPermanentDelete?: (id: string) => void;
onLoadMore?: () => void;
onLoadMoreTrashed?: () => void;
hasMore?: boolean;
hasMoreTrashed?: boolean;
trashedCount?: number;
/** i18n config — present when multiple locales are configured */
i18n?: { defaultLocale: string; locales: string[] };
/** Currently active locale filter */
activeLocale?: string;
/** Callback when locale filter changes */
onLocaleChange?: (locale: string) => void;
/** URL pattern for published content links (e.g. `/blog/{slug}`) */
urlPattern?: string;
/**
* Controlled sort state. When `onSortChange` is also provided, the column
* headers become sort controls that invoke it. Uncontrolled sort keeps
* the backward-compatible "static headers, server-default ordering"
* behavior for callers that haven't opted in yet.
*/
sort?: ContentListSort;
onSortChange?: (sort: ContentListSort) => void;
/**
* Total rows matching the current filters (ignoring pagination). When
* set, the pagination denominator reflects this stable count instead of
* growing as more API pages are fetched.
*/
total?: number;
/**
* When provided, search is performed server-side: the (debounced) query is
* reported here so the caller can refetch, and `items`/`total` are assumed
* to already reflect the filter. Without it, the list falls back to
* filtering the loaded page client-side (legacy behavior).
*/
onSearchChange?: (q: string) => void;
/**
* Filter controls. The whole bar is opt-in: it only renders when
* `onStatusFilterChange` is provided, keeping the component
* backward-compatible for callers that haven't wired filters yet. Each
* control renders independently based on the presence of its callback
* (and, for the author filter, a non-empty `authors` list).
*/
statusFilter?: ContentStatusFilter;
onStatusFilterChange?: (status: ContentStatusFilter) => void;
/** Authors who have content in this collection, for the author filter. */
authors?: ContentAuthor[];
/** Selected author id; empty string means "all authors". */
authorFilter?: string;
onAuthorFilterChange?: (authorId: string) => void;
/** Controlled date-range filter state. */
dateFilter?: ContentDateFilter;
onDateFilterChange?: (filter: ContentDateFilter) => void;
/** Controlled byline filter state. */
bylineFilter?: BylineFilterState;
onBylineFilterChange?: (filter: BylineFilterState) => void;
/**
* Bulk actions. Each is opt-in: the selection checkboxes only appear when at
* least one bulk handler is provided, and each toolbar button renders only
* when its handler is present. Handlers receive the selected entry ids and
* resolve with the ids that failed (empty array on full success); those
* rows stay selected so a partial failure can be retried.
*/
onBulkPublish?: BulkActionHandler;
onBulkUnpublish?: BulkActionHandler;
onBulkDelete?: BulkActionHandler;
}
type BulkActionHandler = (ids: string[]) => Promise<string[]>;
type ViewTab = "all" | "trash";
const PAGE_SIZE = 20;
function getItemTitle(item: { data: Record<string, unknown>; slug: string | null; id: string }) {
const rawTitle = item.data.title;
const rawName = item.data.name;
return (
(typeof rawTitle === "string" ? rawTitle : "") ||
(typeof rawName === "string" ? rawName : "") ||
item.slug ||
item.id
);
}
/**
* Content list view with table display and trash tab
*/
export function ContentList({
collection,
collectionLabel,
items,
trashedItems = [],
isLoading,
isTrashedLoading,
onDelete,
onDuplicate,
onRestore,
onPermanentDelete,
onLoadMore,
onLoadMoreTrashed,
hasMore,
hasMoreTrashed,
trashedCount = 0,
i18n,
activeLocale,
onLocaleChange,
urlPattern,
sort,
onSortChange,
total,
onSearchChange,
statusFilter = "all",
onStatusFilterChange,
authors,
authorFilter = "",
onAuthorFilterChange,
dateFilter = EMPTY_DATE_FILTER,
onDateFilterChange,
bylineFilter = EMPTY_BYLINE_FILTER,
onBylineFilterChange,
onBulkPublish,
onBulkUnpublish,
onBulkDelete,
}: ContentListProps) {
const { t } = useLingui();
const [activeTab, setActiveTab] = React.useState<ViewTab>("all");
const [searchQuery, setSearchQuery] = React.useState("");
const [page, setPage] = React.useState(0);
const [selectedIds, setSelectedIds] = React.useState<Set<string>>(() => new Set());
// Bulk selection is opt-in: the checkbox column + toolbar only render when
// the parent wired at least one bulk handler.
const bulkEnabled = !!(onBulkPublish || onBulkUnpublish || onBulkDelete);
// Server-side search mode: the caller refetches based on the (debounced)
// query, so `items`/`total` already reflect the filter and we must not
// re-filter client-side (that would re-introduce the "only matches the
// loaded page" bug for non-title columns).
const serverSearch = !!onSearchChange;
const debouncedSearch = useDebouncedValue(searchQuery, 300);
React.useEffect(() => {
if (onSearchChange) onSearchChange(debouncedSearch.trim());
}, [debouncedSearch, onSearchChange]);
// Reset page when search changes
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchQuery(e.target.value);
setPage(0);
};
const filteredItems = React.useMemo(() => {
if (serverSearch || !searchQuery) return items;
const query = searchQuery.toLowerCase();
return items.filter((item) => getItemTitle(item).toLowerCase().includes(query));
}, [items, searchQuery, serverSearch]);
// The query the current `items` reflect: server-side filtering lags behind
// typing by the debounce, so the empty-state message must use the debounced
// term; client-side filtering is immediate, so it uses the live query.
const activeSearch = serverSearch ? debouncedSearch.trim() : searchQuery;
// When the server reports a total, it's the source of truth for the
// denominator. In server-search mode that total already reflects the query,
// so we use it even while searching; in client mode an active query falls
// back to the filtered client count.
const effectiveTotal =
typeof total === "number" && (serverSearch || !searchQuery) ? total : filteredItems.length;
const totalPages = Math.max(1, Math.ceil(effectiveTotal / PAGE_SIZE));
// Clamp the current page in case filters collapse the count (user was on
// page 5 of 10, then typed a query narrowing to 1 page). Without clamping
// we'd render an empty table until the next refetch.
const clampedPage = Math.min(page, totalPages - 1);
const paginatedItems = filteredItems.slice(
clampedPage * PAGE_SIZE,
(clampedPage + 1) * PAGE_SIZE,
);
// Auto-fetch the next API page when the user is on a client page whose
// items haven't been loaded yet. Skip during client-side search because
// filtering can collapse `filteredItems` below the loaded count and
// trigger a spurious fetch.
//
// Safety: relies on `onLoadMore` being deduped against concurrent calls.
// The router wires this to TanStack Query's `fetchNextPage`, which is
// idempotent while a fetch is in flight.
React.useEffect(() => {
// In client-search mode we skip auto-fetch while a query is active
// (filtering can collapse the list). In server-search mode the loaded
// items already are the matches, so paging forward should keep fetching.
if (!hasMore || !onLoadMore || (!serverSearch && searchQuery)) return;
const loadedPages = Math.ceil(filteredItems.length / PAGE_SIZE);
if (clampedPage >= loadedPages - 1) {
onLoadMore();
}
}, [clampedPage, filteredItems.length, hasMore, onLoadMore, searchQuery, serverSearch]);
// Drop selections for rows that left the current result set (filter/locale
// change, deletion) so a bulk action never targets a now-hidden id.
React.useEffect(() => {
setSelectedIds((prev) => {
if (prev.size === 0) return prev;
const present = new Set(items.map((i) => i.id));
let changed = false;
const next = new Set<string>();
for (const id of prev) {
if (present.has(id)) next.add(id);
else changed = true;
}
return changed ? next : prev;
});
}, [items]);
const clearSelection = React.useCallback(() => setSelectedIds(new Set()), []);
const toggleOne = (id: string) =>
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
const pageIds = paginatedItems.map((i) => i.id);
const allPageSelected = pageIds.length > 0 && pageIds.every((id) => selectedIds.has(id));
const togglePage = () =>
setSelectedIds((prev) => {
const next = new Set(prev);
if (allPageSelected) for (const id of pageIds) next.delete(id);
else for (const id of pageIds) next.add(id);
return next;
});
const selectedCount = selectedIds.size;
const [bulkBusy, setBulkBusy] = React.useState(false);
const runBulk = (fn?: BulkActionHandler) => {
if (!fn || selectedCount === 0 || bulkBusy) return;
const ids = [...selectedIds];
setBulkBusy(true);
void (async () => {
try {
// Clear only after the batch settles, keeping the failed ids
// selected — a partial failure stays retryable instead of the
// selection vanishing while requests are still in flight.
const failedIds = await fn(ids);
setSelectedIds(new Set(failedIds));
} catch {
// Unexpected (non-per-item) error: keep the selection for a retry.
// The parent's mutation surfaces the error toast.
} finally {
setBulkBusy(false);
}
})();
};
const colSpan = (i18n ? 5 : 4) + (bulkEnabled ? 1 : 0);
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<h1 className="text-2xl font-semibold leading-tight">{collectionLabel}</h1>
{i18n && activeLocale && onLocaleChange && (
<LocaleSwitcher
locales={i18n.locales}
defaultLocale={i18n.defaultLocale}
value={activeLocale}
onChange={onLocaleChange}
size="sm"
/>
)}
</div>
<RouterLinkButton
to="/content/$collection/new"
params={{ collection }}
search={{ locale: activeLocale }}
icon={<Plus />}
>
{t`Add New`}
</RouterLinkButton>
</div>
{/* Search */}
{(serverSearch || items.length > 0) && (
<div className="relative max-w-sm">
<MagnifyingGlass className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-kumo-subtle" />
<Input
type="search"
placeholder={t`Search ${collectionLabel.toLowerCase()}...`}
aria-label={t`Search ${collectionLabel.toLowerCase()}`}
value={searchQuery}
onChange={handleSearchChange}
className="ps-9"
/>
</div>
)}
{/* Tabs */}
<Tabs
variant="underline"
value={activeTab}
onValueChange={(v) => {
if (v === "all" || v === "trash") setActiveTab(v);
}}
tabs={[
{ value: "all", label: t`All` },
{
value: "trash",
label: (
<span className="flex items-center gap-2">
<Trash className="h-4 w-4" aria-hidden="true" />
{t`Trash`}
{trashedCount > 0 && <Badge variant="secondary">{trashedCount}</Badge>}
</span>
),
},
]}
/>
{/* Content based on active tab */}
{activeTab === "all" ? (
<>
{/* Filters */}
{onStatusFilterChange && (
<FilterBar
statusFilter={statusFilter}
onStatusFilterChange={onStatusFilterChange}
authors={authors}
authorFilter={authorFilter}
onAuthorFilterChange={onAuthorFilterChange}
dateFilter={dateFilter}
onDateFilterChange={onDateFilterChange}
bylineFilter={bylineFilter}
onBylineFilterChange={onBylineFilterChange}
locale={activeLocale ?? undefined}
/>
)}
{/* Bulk action toolbar — appears once one or more rows are selected */}
{bulkEnabled && selectedCount > 0 && (
<div className="flex flex-wrap items-center gap-3 rounded-md border bg-kumo-tint/40 px-4 py-2">
<span className="text-sm font-medium">
{bulkBusy
? t`Working on ${selectedCount} items…`
: plural(selectedCount, { one: "# selected", other: "# selected" })}
</span>
<div className="flex flex-wrap items-center gap-2">
{onBulkPublish && (
<Button
size="sm"
variant="secondary"
disabled={bulkBusy}
onClick={() => runBulk(onBulkPublish)}
icon={<Upload />}
>
{t`Publish`}
</Button>
)}
{onBulkUnpublish && (
<Button
size="sm"
variant="secondary"
disabled={bulkBusy}
onClick={() => runBulk(onBulkUnpublish)}
>
{t`Set to draft`}
</Button>
)}
{onBulkDelete && (
<Dialog.Root disablePointerDismissal>
<Dialog.Trigger
render={(p) => (
<Button
{...p}
size="sm"
variant="destructive"
icon={<Trash />}
disabled={bulkBusy}
>
{t`Move to trash`}
</Button>
)}
/>
<Dialog className="p-6" size="sm">
<Dialog.Title className="text-lg font-semibold">{t`Move to Trash?`}</Dialog.Title>
<Dialog.Description className="text-kumo-subtle">
{plural(selectedCount, {
one: "Move # item to trash? You can restore it later.",
other: "Move # items to trash? You can restore them later.",
})}
</Dialog.Description>
<div className="mt-6 flex justify-end gap-2">
<Dialog.Close
render={(p) => (
<Button {...p} variant="secondary">
{t`Cancel`}
</Button>
)}
/>
<Dialog.Close
render={(p) => (
<Button
{...p}
variant="destructive"
onClick={() => runBulk(onBulkDelete)}
>
{t`Move to Trash`}
</Button>
)}
/>
</div>
</Dialog>
</Dialog.Root>
)}
<Button
size="sm"
variant="ghost"
icon={<X />}
disabled={bulkBusy}
onClick={clearSelection}
>
{t`Clear`}
</Button>
</div>
</div>
)}
{/* Table */}
<div className="rounded-md border bg-kumo-base overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b bg-kumo-tint/50">
{bulkEnabled && (
<th scope="col" className="w-10 px-4 py-3">
<Checkbox
checked={allPageSelected}
onCheckedChange={togglePage}
aria-label={t`Select all on this page`}
/>
</th>
)}
<SortableTh
field="title"
sort={sort}
onSortChange={onSortChange}
label={t`Title`}
/>
<SortableTh
field="status"
sort={sort}
onSortChange={onSortChange}
label={t`Status`}
/>
{i18n && (
<SortableTh
field="locale"
sort={sort}
onSortChange={onSortChange}
label={t`Locale`}
/>
)}
<SortableTh
field="updatedAt"
sort={sort}
onSortChange={onSortChange}
label={t`Date`}
/>
<th scope="col" className="px-4 py-3 text-end text-sm font-medium">
{t`Actions`}
</th>
</tr>
</thead>
<tbody className="divide-y divide-kumo-line">
{isLoading && items.length === 0 ? (
<tr>
<td colSpan={colSpan} className="px-4 py-8 text-center text-kumo-subtle">
<span className="inline-flex items-center gap-2">
<Loader size="sm" />
{t`Loading...`}
</span>
</td>
</tr>
) : items.length === 0 ? (
<tr>
<td colSpan={colSpan} className="px-4 py-8 text-center text-kumo-subtle">
{activeSearch ? (
t`No results for "${activeSearch}"`
) : (
<>
{t`No ${collectionLabel.toLowerCase()} yet.`}{" "}
<Link
to="/content/$collection/new"
params={{ collection }}
search={{ locale: activeLocale }}
className="text-kumo-link underline"
>
{t`Create your first one`}
</Link>
</>
)}
</td>
</tr>
) : paginatedItems.length === 0 ? (
<tr>
<td colSpan={colSpan} className="px-4 py-8 text-center text-kumo-subtle">
{t`No results for "${activeSearch}"`}
</td>
</tr>
) : (
paginatedItems.map((item) => (
<ContentListItem
key={item.id}
item={item}
collection={collection}
onDelete={onDelete}
onDuplicate={onDuplicate}
showLocale={!!i18n}
urlPattern={urlPattern}
selectable={bulkEnabled}
selected={selectedIds.has(item.id)}
onToggleSelect={toggleOne}
/>
))
)}
</tbody>
</table>
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between">
<span className="text-sm text-kumo-subtle">
{renderItemCount({
searchQuery: activeSearch,
filteredCount: filteredItems.length,
total,
hasMore,
serverSearch,
})}
</span>
<div className="flex items-center gap-2">
<Button
variant="outline"
shape="square"
disabled={clampedPage === 0}
onClick={() => setPage(clampedPage - 1)}
aria-label={t`Previous page`}
>
<CaretPrev className="h-4 w-4" aria-hidden="true" />
</Button>
<span className="text-sm">
{clampedPage + 1} / {totalPages}
</span>
<Button
variant="outline"
shape="square"
disabled={clampedPage >= totalPages - 1}
onClick={() => setPage(clampedPage + 1)}
aria-label={t`Next page`}
>
<CaretNext className="h-4 w-4" aria-hidden="true" />
</Button>
</div>
</div>
)}
{/* Load more */}
{hasMore && (
<div className="flex justify-center">
<Button variant="outline" onClick={onLoadMore} disabled={isLoading}>
{isLoading ? t`Loading...` : t`Load More`}
</Button>
</div>
)}
</>
) : (
<>
{/* Trash Table */}
<div className="rounded-md border bg-kumo-base overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b bg-kumo-tint/50">
<th scope="col" className="px-4 py-3 text-start text-sm font-medium">
{t`Title`}
</th>
<th scope="col" className="px-4 py-3 text-start text-sm font-medium">
{t`Deleted`}
</th>
<th scope="col" className="px-4 py-3 text-end text-sm font-medium">
{t`Actions`}
</th>
</tr>
</thead>
<tbody className="divide-y divide-kumo-line">
{isTrashedLoading && trashedItems.length === 0 ? (
<tr>
<td colSpan={3} className="px-4 py-8 text-center text-kumo-subtle">
<span className="inline-flex items-center gap-2">
<Loader size="sm" />
{t`Loading...`}
</span>
</td>
</tr>
) : trashedItems.length === 0 ? (
<tr>
<td colSpan={3} className="px-4 py-8 text-center text-kumo-subtle">
{t`Trash is empty`}
</td>
</tr>
) : (
trashedItems.map((item) => (
<TrashedListItem
key={item.id}
item={item}
onRestore={onRestore}
onPermanentDelete={onPermanentDelete}
/>
))
)}
</tbody>
</table>
</div>
{/* Load more trashed */}
{hasMoreTrashed && (
<div className="flex justify-center">
<Button variant="outline" onClick={onLoadMoreTrashed} disabled={isTrashedLoading}>
{isTrashedLoading ? t`Loading...` : t`Load More`}
</Button>
</div>
)}
</>
)}
</div>
);
}
interface FilterBarProps {
statusFilter: ContentStatusFilter;
onStatusFilterChange: (status: ContentStatusFilter) => void;
authors?: ContentAuthor[];
authorFilter: string;
onAuthorFilterChange?: (authorId: string) => void;
dateFilter: ContentDateFilter;
onDateFilterChange?: (filter: ContentDateFilter) => void;
bylineFilter: BylineFilterState;
onBylineFilterChange?: (filter: BylineFilterState) => void;
/** Locale the list is showing, so the byline picker offers matching rows. */
locale?: string;
}
/**
* Filter controls for the content list: status, author, byline, and a date
* range over a chosen timestamp column (#1288). All controls report changes to
* the parent, which owns the state and refetches. Filtering happens
* server-side, so it works across the whole collection rather than the loaded
* page.
*/
function FilterBar({
statusFilter,
onStatusFilterChange,
authors,
authorFilter,
onAuthorFilterChange,
dateFilter,
onDateFilterChange,
bylineFilter,
onBylineFilterChange,
locale,
}: FilterBarProps) {
const { t } = useLingui();
const showAuthorFilter = !!onAuthorFilterChange && !!authors && authors.length > 0;
const showDateFilter = !!onDateFilterChange;
const statusItems: Record<ContentStatusFilter, string> = {
all: t`All statuses`,
published: t`Publish`,
draft: t`Draft`,
scheduled: t`Scheduled`,
archived: t`Archived`,
};
const renderStatusLabel = (value: ContentStatusFilter) =>
value === "all" ? statusItems.all : <ContentStatusLabel state={value} />;
const dateFieldItems: Record<string, string> = {
createdAt: t`Created`,
updatedAt: t`Updated`,
publishedAt: t`Published`,
};
const hasActiveFilter =
statusFilter !== "all" ||
authorFilter !== "" ||
!!dateFilter.from ||
!!dateFilter.to ||
isBylineFilterActive(bylineFilter);
const handleClear = () => {
onStatusFilterChange("all");
onAuthorFilterChange?.("");
onDateFilterChange?.(EMPTY_DATE_FILTER);
// Clearing drops the selection but keeps the inferred-byline
// preference, which is a display choice rather than an active filter.
onBylineFilterChange?.({
...EMPTY_BYLINE_FILTER,
includeInferred: bylineFilter.includeInferred,
});
};
return (
<div className="flex flex-wrap items-end gap-3">
<Select
size="sm"
aria-label={t`Filter by status`}
value={statusFilter}
onValueChange={(v) => onStatusFilterChange((v as ContentStatusFilter) ?? "all")}
renderValue={(v) =>
renderStatusLabel(typeof v === "string" && Object.hasOwn(statusItems, v) ? v : "all")
}
items={statusItems}
>
{Object.entries(statusItems).map(([value]) => (
<Select.Option key={value} value={value}>
{renderStatusLabel(value as ContentStatusFilter)}
</Select.Option>
))}
</Select>
{showAuthorFilter && (
<Select
size="sm"
aria-label={t`Filter by author`}
value={authorFilter}
onValueChange={(v) => onAuthorFilterChange?.(v ?? "")}
items={{
"": t`All authors`,
...Object.fromEntries(authors.map((a) => [a.id, a.name || a.email])),
}}
>
<Select.Option value="">{t`All authors`}</Select.Option>
{authors.map((a) => (
<Select.Option key={a.id} value={a.id}>
{a.name || a.email}
</Select.Option>
))}
</Select>
)}
{onBylineFilterChange && (
<BylineFilter value={bylineFilter} onChange={onBylineFilterChange} locale={locale} />
)}
{showDateFilter && (
<div className="flex flex-wrap items-end gap-2">
<Select
size="sm"
aria-label={t`Date field to filter on`}
value={dateFilter.field}
onValueChange={(v) =>
onDateFilterChange?.({ ...dateFilter, field: (v as ContentDateField) ?? "createdAt" })
}
items={dateFieldItems}
>
{Object.entries(dateFieldItems).map(([value, label]) => (
<Select.Option key={value} value={value}>
{label}
</Select.Option>
))}
</Select>
<Input
type="date"
size="sm"
aria-label={t`From date`}
value={dateFilter.from}
max={dateFilter.to || undefined}
onChange={(e) => onDateFilterChange?.({ ...dateFilter, from: e.target.value })}
/>
<span className="pb-2 text-sm text-kumo-subtle">{t`to`}</span>
<Input
type="date"
size="sm"
aria-label={t`To date`}
value={dateFilter.to}
min={dateFilter.from || undefined}
onChange={(e) => onDateFilterChange?.({ ...dateFilter, to: e.target.value })}
/>
</div>
)}
{hasActiveFilter && (
<Button variant="ghost" size="sm" onClick={handleClear} icon={<X />}>
{t`Clear filters`}
</Button>
)}
</div>
);
}
interface SortableThProps {
field: ContentListSortField;
sort: ContentListSort | undefined;
onSortChange: ((sort: ContentListSort) => void) | undefined;
label: string;
}
/**
* Table header that doubles as a sort control when the parent opted in by
* passing `onSortChange`. When no callback is provided we fall back to a
* plain `<th>` so legacy callers (and screen readers) see exactly the same
* markup as before this change.
*
* The button's accessible name is just the column label — the sort state
* is conveyed via `aria-sort` on the <th>, which screen readers announce
* automatically. Adding a verbose aria-label would make each header re-read
* the sort instruction on every focus, which is noisy.
*/
function SortableTh({ field, sort, onSortChange, label }: SortableThProps) {
const isActive = sort?.field === field;
const direction = isActive ? sort?.direction : undefined;
if (!onSortChange) {
return (
<th scope="col" className="px-4 py-3 text-start text-sm font-medium">
{label}
</th>
);
}
const ariaSort: "ascending" | "descending" | "none" = isActive
? direction === "asc"
? "ascending"
: "descending"
: "none";
const handleClick = () => {
// Default to descending for a new column; toggle direction when
// clicking the already-active one.
if (isActive) {
onSortChange({ field, direction: direction === "asc" ? "desc" : "asc" });
} else {
onSortChange({ field, direction: "desc" });
}
};
const Icon = isActive ? (direction === "asc" ? CaretUp : CaretDown) : CaretUpDown;
return (
<th scope="col" aria-sort={ariaSort} className="px-4 py-3 text-start text-sm font-medium">
<button
type="button"
onClick={handleClick}
className={cn(
"inline-flex items-center gap-1 rounded text-kumo-default hover:text-kumo-link",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-kumo-brand",
)}
>
<span>{label}</span>
<Icon className="h-3 w-3" aria-hidden="true" />
</button>
</th>
);
}
/**
* Render the row-count line above pagination. The rules are:
* - A search query always wins — say how many matches there are. In
* server-search mode the server reports the full match count via `total`;
* `filteredCount` is only the loaded page, so it would undercount.
* - When the server reported a total, use it (no `+` suffix needed —
* we know the count).
* - Otherwise fall back to the pre-refactor behavior: loaded count,
* with `+` when there are more pages the user hasn't fetched yet.
*/
function renderItemCount({
searchQuery,
filteredCount,
total,
hasMore,
serverSearch,
}: {
searchQuery: string;
filteredCount: number;
total: number | undefined;
hasMore: boolean | undefined;
serverSearch: boolean;
}): string {
if (searchQuery) {
const matchCount = serverSearch && typeof total === "number" ? total : filteredCount;
return plural(matchCount, {
one: `# item matching "${searchQuery}"`,
other: `# items matching "${searchQuery}"`,
});
}
if (typeof total === "number") {
return plural(total, {
one: `# item`,
other: `# items`,
});
}
return plural(filteredCount, {
one: `#${hasMore ? "+" : ""} item`,
other: `#${hasMore ? "+" : ""} items`,
});
}
interface ContentListItemProps {
item: ContentItem;
collection: string;
onDelete?: (id: string) => void;
onDuplicate?: (id: string) => void;
showLocale?: boolean;
urlPattern?: string;
selectable?: boolean;
selected?: boolean;
onToggleSelect?: (id: string) => void;
}
function ContentListItem({
item,