@thekestongroup/ui 0.2.1 → 0.3.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.
- package/README.md +90 -32
- package/dist/components/Age/Age.vue.d.ts +19 -0
- package/dist/components/AppShell/AppShell.vue.d.ts +108 -0
- package/dist/components/Avatar/Avatar.vue.d.ts +34 -0
- package/dist/components/AvatarGroup/AvatarGroup.vue.d.ts +25 -0
- package/dist/components/Badge/Badge.vue.d.ts +41 -0
- package/dist/components/Breadcrumb/Breadcrumb.vue.d.ts +39 -0
- package/dist/components/Button/Button.vue.d.ts +69 -0
- package/dist/components/Calendar/Calendar.vue.d.ts +34 -0
- package/dist/components/Card/Card.vue.d.ts +56 -0
- package/dist/components/Checkbox/Checkbox.vue.d.ts +40 -0
- package/dist/components/Checklist/Checklist.vue.d.ts +18 -0
- package/dist/components/Chip/Chip.vue.d.ts +44 -0
- package/dist/components/Divider/Divider.vue.d.ts +36 -0
- package/dist/components/{ToastItem.vue.d.ts → FormField/FieldMessage.vue.d.ts} +10 -2
- package/dist/components/FormField/FormField.vue.d.ts +61 -0
- package/dist/components/Header/Header.vue.d.ts +104 -0
- package/dist/components/InfoTip/InfoTip.vue.d.ts +20 -0
- package/dist/components/Input/Input.vue.d.ts +56 -0
- package/dist/components/InputCode/InputCode.vue.d.ts +53 -0
- package/dist/components/InputDate/InputDate.vue.d.ts +49 -0
- package/dist/components/InputNumber/InputNumber.vue.d.ts +44 -0
- package/dist/components/InputPassword/InputPassword.vue.d.ts +51 -0
- package/dist/components/InputRichText/InputRichText.vue.d.ts +44 -0
- package/dist/components/Link/Link.vue.d.ts +39 -0
- package/dist/components/Notification/Notification.vue.d.ts +62 -0
- package/dist/components/Notification/NotificationPane.vue.d.ts +38 -0
- package/dist/components/Notification/Toaster.vue.d.ts +51 -0
- package/dist/components/Notification/notification.samples.d.ts +3 -0
- package/dist/components/Notification/notifications.d.ts +115 -0
- package/dist/components/PageHeader/PageHeader.vue.d.ts +43 -0
- package/dist/components/Popover/Popover.vue.d.ts +83 -0
- package/dist/components/Popover/popover.d.ts +16 -0
- package/dist/components/Progress/Progress.vue.d.ts +26 -0
- package/dist/components/RadioGroup/RadioGroup.vue.d.ts +45 -0
- package/dist/components/RelativeTime/RelativeTime.vue.d.ts +22 -0
- package/dist/components/Select/Select.vue.d.ts +110 -0
- package/dist/components/Sidebar/Sidebar.vue.d.ts +106 -0
- package/dist/components/Sidebar/sidebar.d.ts +10 -0
- package/dist/components/Slideover/Slideover.vue.d.ts +125 -0
- package/dist/components/Spinner/Spinner.vue.d.ts +30 -0
- package/dist/components/StatTile/StatTile.vue.d.ts +46 -0
- package/dist/components/SummaryList/SummaryList.vue.d.ts +62 -0
- package/dist/components/Switch/Switch.vue.d.ts +39 -0
- package/dist/components/Table/Table.vue.d.ts +82 -0
- package/dist/components/Table/table.d.ts +36 -0
- package/dist/components/Tooltip/Tooltip.vue.d.ts +46 -0
- package/dist/index.d.ts +89 -25
- package/dist/keston-ui.js +4963 -14785
- package/dist/lib/cn.d.ts +4 -0
- package/dist/lib/dates.d.ts +27 -0
- package/dist/lib/initials.d.ts +2 -0
- package/dist/lib/parseDate.d.ts +44 -0
- package/dist/lib/useNow.d.ts +3 -0
- package/package.json +53 -24
- package/src/components/.gitkeep +0 -0
- package/src/components/Age/Age.stories.ts +24 -0
- package/src/components/Age/Age.vue +56 -0
- package/src/components/AppShell/AppShell.stories.ts +124 -0
- package/src/components/AppShell/AppShell.vue +212 -0
- package/src/components/Avatar/Avatar.stories.ts +56 -0
- package/src/components/Avatar/Avatar.vue +118 -0
- package/src/components/AvatarGroup/AvatarGroup.stories.ts +47 -0
- package/src/components/AvatarGroup/AvatarGroup.vue +97 -0
- package/src/components/Badge/Badge.stories.ts +92 -0
- package/src/components/Badge/Badge.vue +67 -0
- package/src/components/Breadcrumb/Breadcrumb.stories.ts +58 -0
- package/src/components/Breadcrumb/Breadcrumb.vue +109 -0
- package/src/components/Button/Button.mdx +79 -0
- package/src/components/Button/Button.stories.ts +207 -0
- package/src/components/Button/Button.vue +266 -0
- package/src/components/Calendar/Calendar.stories.ts +51 -0
- package/src/components/Calendar/Calendar.vue +364 -0
- package/src/components/Card/Card.stories.ts +109 -0
- package/src/components/Card/Card.vue +115 -0
- package/src/components/Checkbox/Checkbox.stories.ts +102 -0
- package/src/components/Checkbox/Checkbox.vue +102 -0
- package/src/components/Checklist/Checklist.stories.ts +67 -0
- package/src/components/Checklist/Checklist.vue +38 -0
- package/src/components/Chip/Chip.stories.ts +71 -0
- package/src/components/Chip/Chip.vue +86 -0
- package/src/components/Divider/Divider.stories.ts +57 -0
- package/src/components/Divider/Divider.vue +58 -0
- package/src/components/FormField/FieldMessage.vue +81 -0
- package/src/components/FormField/FormField.stories.ts +55 -0
- package/src/components/FormField/FormField.vue +160 -0
- package/src/components/Header/Header.stories.ts +168 -0
- package/src/components/Header/Header.vue +232 -0
- package/src/components/InfoTip/InfoTip.stories.ts +63 -0
- package/src/components/InfoTip/InfoTip.vue +50 -0
- package/src/components/Input/Input.stories.ts +206 -0
- package/src/components/Input/Input.vue +90 -0
- package/src/components/InputCode/InputCode.stories.ts +85 -0
- package/src/components/InputCode/InputCode.vue +145 -0
- package/src/components/InputDate/InputDate.stories.ts +58 -0
- package/src/components/InputDate/InputDate.vue +258 -0
- package/src/components/InputNumber/InputNumber.stories.ts +63 -0
- package/src/components/InputNumber/InputNumber.vue +109 -0
- package/src/components/InputPassword/InputPassword.stories.ts +105 -0
- package/src/components/InputPassword/InputPassword.vue +132 -0
- package/src/components/InputRichText/InputRichText.stories.ts +100 -0
- package/src/components/InputRichText/InputRichText.vue +194 -0
- package/src/components/Link/Link.stories.ts +73 -0
- package/src/components/Link/Link.vue +56 -0
- package/src/components/Notification/Notification.stories.ts +196 -0
- package/src/components/Notification/Notification.vue +136 -0
- package/src/components/Notification/NotificationPane.vue +187 -0
- package/src/components/Notification/Toaster.vue +446 -0
- package/src/components/Notification/notification.samples.ts +45 -0
- package/src/components/Notification/notifications.test.ts +99 -0
- package/src/components/Notification/notifications.ts +172 -0
- package/src/components/PageHeader/PageHeader.stories.ts +79 -0
- package/src/components/PageHeader/PageHeader.vue +66 -0
- package/src/components/Popover/Popover.stories.ts +135 -0
- package/src/components/Popover/Popover.vue +192 -0
- package/src/components/Popover/popover.ts +20 -0
- package/src/components/Progress/Progress.stories.ts +74 -0
- package/src/components/Progress/Progress.vue +75 -0
- package/src/components/RadioGroup/RadioGroup.stories.ts +90 -0
- package/src/components/RadioGroup/RadioGroup.vue +132 -0
- package/src/components/RelativeTime/RelativeTime.stories.ts +74 -0
- package/src/components/RelativeTime/RelativeTime.vue +51 -0
- package/src/components/Select/Select.mdx +202 -0
- package/src/components/Select/Select.stories.ts +223 -0
- package/src/components/Select/Select.vue +630 -0
- package/src/components/Sidebar/Sidebar.stories.ts +192 -0
- package/src/components/Sidebar/Sidebar.vue +382 -0
- package/src/components/Sidebar/sidebar.ts +20 -0
- package/src/components/Slideover/Slideover.stories.ts +225 -0
- package/src/components/Slideover/Slideover.vue +365 -0
- package/src/components/Spinner/Spinner.stories.ts +79 -0
- package/src/components/Spinner/Spinner.vue +97 -0
- package/src/components/StatTile/StatTile.stories.ts +75 -0
- package/src/components/StatTile/StatTile.vue +89 -0
- package/src/components/SummaryList/SummaryList.stories.ts +103 -0
- package/src/components/SummaryList/SummaryList.vue +127 -0
- package/src/components/Switch/Switch.stories.ts +100 -0
- package/src/components/Switch/Switch.vue +96 -0
- package/src/components/Table/Table.stories.ts +206 -0
- package/src/components/Table/Table.vue +220 -0
- package/src/components/Table/table.test.ts +65 -0
- package/src/components/Table/table.ts +70 -0
- package/src/components/Tooltip/Tooltip.stories.ts +57 -0
- package/src/components/Tooltip/Tooltip.vue +86 -0
- package/src/examples/AppPages.stories.ts +500 -0
- package/src/examples/FormLayout.stories.ts +185 -0
- package/src/examples/KestonIdPages.stories.ts +415 -0
- package/src/examples/SchoolPages.stories.ts +665 -0
- package/src/index.ts +114 -36
- package/src/lib/cn.ts +4 -0
- package/src/lib/dates.test.ts +68 -0
- package/src/lib/dates.ts +86 -0
- package/src/lib/initials.ts +8 -0
- package/src/lib/parseDate.test.ts +331 -0
- package/src/lib/parseDate.ts +561 -0
- package/src/lib/useNow.ts +20 -0
- package/src/styles/theme.css +101 -0
- package/dist/components/AppLauncher.vue.d.ts +0 -10
- package/dist/components/Avatar.vue.d.ts +0 -16
- package/dist/components/Button.vue.d.ts +0 -27
- package/dist/components/Checkbox.vue.d.ts +0 -18
- package/dist/components/CloseButton.vue.d.ts +0 -6
- package/dist/components/Dialog.vue.d.ts +0 -23
- package/dist/components/Drawer.vue.d.ts +0 -34
- package/dist/components/DropdownMenu.vue.d.ts +0 -21
- package/dist/components/DropdownMenuItem.vue.d.ts +0 -19
- package/dist/components/DropdownMenuSeparator.vue.d.ts +0 -6
- package/dist/components/Input.vue.d.ts +0 -14
- package/dist/components/Label.vue.d.ts +0 -16
- package/dist/components/NotificationsMenu.vue.d.ts +0 -3
- package/dist/components/Popover.vue.d.ts +0 -23
- package/dist/components/ProfileSwitcher.vue.d.ts +0 -24
- package/dist/components/Select.vue.d.ts +0 -28
- package/dist/components/Separator.vue.d.ts +0 -11
- package/dist/components/ToastRenderer.vue.d.ts +0 -3
- package/dist/components/Toaster.vue.d.ts +0 -3
- package/dist/components/Tooltip.vue.d.ts +0 -23
- package/dist/components/TopBar.vue.d.ts +0 -34
- package/dist/favicon-old.svg +0 -1
- package/dist/favicon.svg +0 -1
- package/dist/keston-ui.cjs +0 -15
- package/dist/lib/toast.d.ts +0 -29
- package/dist/lib/types.d.ts +0 -5
- package/src/components/AppLauncher.vue +0 -63
- package/src/components/Avatar.vue +0 -51
- package/src/components/Button.vue +0 -54
- package/src/components/Checkbox.vue +0 -47
- package/src/components/CloseButton.vue +0 -24
- package/src/components/Dialog.vue +0 -65
- package/src/components/Drawer.vue +0 -202
- package/src/components/DropdownMenu.vue +0 -41
- package/src/components/DropdownMenuItem.vue +0 -28
- package/src/components/DropdownMenuSeparator.vue +0 -12
- package/src/components/Input.vue +0 -21
- package/src/components/Label.vue +0 -15
- package/src/components/NotificationsMenu.vue +0 -115
- package/src/components/Popover.vue +0 -46
- package/src/components/ProfileSwitcher.vue +0 -113
- package/src/components/Select.vue +0 -97
- package/src/components/Separator.vue +0 -30
- package/src/components/ToastItem.vue +0 -158
- package/src/components/ToastRenderer.vue +0 -113
- package/src/components/Toaster.vue +0 -11
- package/src/components/Tooltip.vue +0 -48
- package/src/components/TopBar.vue +0 -52
- package/src/lib/toast.ts +0 -95
- package/src/lib/types.ts +0 -5
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import { computed, useId, type HTMLAttributes } from 'vue'
|
|
3
|
+
import { SwitchRoot, SwitchThumb } from 'reka-ui'
|
|
4
|
+
import { cn } from '../../lib/cn'
|
|
5
|
+
import FieldMessage, { type FieldStatus } from '../FormField/FieldMessage.vue'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Turns a setting on or off straight away, with no Save button, e.g. "Email
|
|
9
|
+
* me when an application arrives". For an answer that's sent with a form,
|
|
10
|
+
* use Checkbox.
|
|
11
|
+
*
|
|
12
|
+
* As the change saves immediately, it can show how that went: `status`
|
|
13
|
+
* 'loading' with "Saving…", then 'success' or 'error'.
|
|
14
|
+
*/
|
|
15
|
+
export interface SwitchProps {
|
|
16
|
+
/** Visible label, beside the switch. Pressing it flips the switch too. */
|
|
17
|
+
label: string
|
|
18
|
+
/** More detail, in smaller text under the label. */
|
|
19
|
+
description?: string
|
|
20
|
+
/** Error message. Overrides `status` and `statusText`. */
|
|
21
|
+
errorText?: string
|
|
22
|
+
/** Colours the status text: e.g. 'loading' while the change saves. */
|
|
23
|
+
status?: FieldStatus
|
|
24
|
+
/** Message under the switch, e.g. "Saving…" or "Couldn't save. Try again." */
|
|
25
|
+
statusText?: string
|
|
26
|
+
/** Name for native form submission. */
|
|
27
|
+
name?: string
|
|
28
|
+
disabled?: boolean
|
|
29
|
+
class?: HTMLAttributes['class']
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const props = defineProps<SwitchProps>()
|
|
33
|
+
|
|
34
|
+
/** On or off. */
|
|
35
|
+
const model = defineModel<boolean>({ default: false })
|
|
36
|
+
|
|
37
|
+
const id = useId()
|
|
38
|
+
const controlId = `${id}-control`
|
|
39
|
+
const descriptionId = `${id}-description`
|
|
40
|
+
const statusId = `${id}-status`
|
|
41
|
+
|
|
42
|
+
const currentStatus = computed(() => (props.errorText ? 'error' : props.status))
|
|
43
|
+
const currentStatusText = computed(() => props.errorText || props.statusText)
|
|
44
|
+
|
|
45
|
+
const describedBy = computed(
|
|
46
|
+
() => [props.description && descriptionId, currentStatusText.value && statusId].filter(Boolean).join(' ') || undefined
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
// Pressing anywhere in the text (the description, or the gap between it and
|
|
50
|
+
// the label) acts like pressing the label. The description isn't inside the
|
|
51
|
+
// <label>, which would make it part of the accessible name; it stays the
|
|
52
|
+
// description (aria-describedby). The label already presses the control
|
|
53
|
+
// itself, so it's skipped here. Keyboard use is unchanged.
|
|
54
|
+
function pressControl(event: MouseEvent, id: string) {
|
|
55
|
+
if ((event.target as Element).closest('label')) return
|
|
56
|
+
document.getElementById(id)?.click()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// 36 × 20px track, level with the label's first line; the 16px thumb slides
|
|
60
|
+
// 16px. Off is a mid grey, dark enough to see against the page.
|
|
61
|
+
const track = [
|
|
62
|
+
'inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full p-0.5 transition-colors',
|
|
63
|
+
'bg-black/45 not-disabled:hover:bg-black/55 data-[state=checked]:bg-primary data-[state=checked]:hover:bg-primary',
|
|
64
|
+
'disabled:cursor-not-allowed',
|
|
65
|
+
'outline-2 outline-offset-2 outline-transparent focus-visible:outline-focus'
|
|
66
|
+
]
|
|
67
|
+
const thumb = 'size-4 rounded-full bg-white shadow-sm transition-transform data-[state=checked]:translate-x-4 motion-reduce:transition-none'
|
|
68
|
+
</script>
|
|
69
|
+
|
|
70
|
+
<template>
|
|
71
|
+
<div :class="cn('flex flex-col gap-1.5 text-black', disabled && 'opacity-40', props.class)">
|
|
72
|
+
<div class="flex items-start gap-2">
|
|
73
|
+
<SwitchRoot
|
|
74
|
+
:id="controlId"
|
|
75
|
+
v-model="model"
|
|
76
|
+
:name="name"
|
|
77
|
+
:disabled="disabled"
|
|
78
|
+
:aria-invalid="currentStatus === 'error' || undefined"
|
|
79
|
+
:aria-describedby="describedBy"
|
|
80
|
+
:class="track"
|
|
81
|
+
>
|
|
82
|
+
<SwitchThumb :class="thumb" />
|
|
83
|
+
</SwitchRoot>
|
|
84
|
+
<div
|
|
85
|
+
:class="cn('flex min-w-0 flex-col gap-0.5', disabled ? 'cursor-not-allowed' : 'cursor-pointer')"
|
|
86
|
+
@click="pressControl($event, controlId)"
|
|
87
|
+
>
|
|
88
|
+
<label :for="controlId" :class="cn('text-sm', disabled ? 'cursor-not-allowed' : 'cursor-pointer')">{{ label }}</label>
|
|
89
|
+
<p v-if="description" :id="descriptionId" class="text-xs text-black/65">
|
|
90
|
+
{{ description }}
|
|
91
|
+
</p>
|
|
92
|
+
</div>
|
|
93
|
+
</div>
|
|
94
|
+
<FieldMessage :id="statusId" :status="currentStatus" :text="currentStatusText" />
|
|
95
|
+
</div>
|
|
96
|
+
</template>
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import type { Meta, StoryObj } from "@storybook/vue3-vite";
|
|
2
|
+
import { ref } from "vue";
|
|
3
|
+
import { Ellipsis } from "@lucide/vue";
|
|
4
|
+
import Badge from "../Badge/Badge.vue";
|
|
5
|
+
import Button from "../Button/Button.vue";
|
|
6
|
+
import Card from "../Card/Card.vue";
|
|
7
|
+
import Table, { type TableProps } from "./Table.vue";
|
|
8
|
+
import type { TableColumn, TableSort } from "./table";
|
|
9
|
+
|
|
10
|
+
type Applicant = {
|
|
11
|
+
id: number;
|
|
12
|
+
name: string;
|
|
13
|
+
year: string;
|
|
14
|
+
applied: Date;
|
|
15
|
+
score: number | null;
|
|
16
|
+
status: "Offered" | "Interview" | "Waiting list" | "Declined";
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const statusColors = { Offered: "green", Interview: "blue", "Waiting list": "yellow", Declined: "basic" } as const;
|
|
20
|
+
|
|
21
|
+
const applicants: Applicant[] = [
|
|
22
|
+
{ id: 1, name: "Amelia Clarke", year: "Year 7", applied: new Date(2026, 9, 3), score: 87, status: "Offered" },
|
|
23
|
+
{ id: 2, name: "Noah Patel", year: "Year 9", applied: new Date(2026, 9, 12), score: 74, status: "Interview" },
|
|
24
|
+
{ id: 3, name: "Isla Hughes", year: "Year 12", applied: new Date(2026, 8, 28), score: null, status: "Waiting list" },
|
|
25
|
+
{ id: 4, name: "Leo Okafor", year: "Year 7", applied: new Date(2026, 9, 19), score: 91, status: "Offered" },
|
|
26
|
+
{ id: 5, name: "Freya Lewis", year: "Year 10", applied: new Date(2026, 9, 7), score: 62, status: "Declined" },
|
|
27
|
+
{ id: 6, name: "Arjun Shah", year: "Year 8", applied: new Date(2026, 9, 21), score: 79, status: "Interview" },
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
const columns: TableColumn<Applicant>[] = [
|
|
31
|
+
{ key: "name", label: "Applicant", sortable: true, rowHeader: true },
|
|
32
|
+
{ key: "year", label: "Year group", sortable: true },
|
|
33
|
+
{ key: "applied", label: "Applied", sortable: true },
|
|
34
|
+
{ key: "score", label: "Score", sortable: true, align: "end" },
|
|
35
|
+
{ key: "status", label: "Status", sortable: true },
|
|
36
|
+
{ key: "actions", label: "Actions", hideLabel: true, align: "end" },
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
const date = (d: Date) => d.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
|
|
40
|
+
|
|
41
|
+
const meta = {
|
|
42
|
+
title: "Components/Data/Table",
|
|
43
|
+
// A generic component, which Meta<typeof Table> can't describe, so the args are typed by its props.
|
|
44
|
+
component: Table as any,
|
|
45
|
+
tags: ["autodocs"],
|
|
46
|
+
parameters: { backgrounds: { disable: true } },
|
|
47
|
+
argTypes: { size: { options: ["md", "sm"], control: { type: "inline-radio" } } },
|
|
48
|
+
args: {
|
|
49
|
+
columns: columns as TableColumn[],
|
|
50
|
+
rows: applicants,
|
|
51
|
+
rowKey: "id",
|
|
52
|
+
caption: "Applications for September 2027",
|
|
53
|
+
size: "md",
|
|
54
|
+
loading: false,
|
|
55
|
+
stickyHeader: false,
|
|
56
|
+
showCaption: false,
|
|
57
|
+
},
|
|
58
|
+
decorators: [() => ({ template: '<div class="bg-background p-6"><story /></div>' })],
|
|
59
|
+
render: (args) => ({
|
|
60
|
+
components: { Table, Card, Badge, Button, Ellipsis },
|
|
61
|
+
setup: () => ({ args, statusColors, date }),
|
|
62
|
+
template: `
|
|
63
|
+
<Card padding="none">
|
|
64
|
+
<Table v-bind="args">
|
|
65
|
+
<template #cell-applied="{ value }">{{ date(value) }}</template>
|
|
66
|
+
<template #cell-score="{ value }">{{ value ?? '—' }}</template>
|
|
67
|
+
<template #cell-status="{ value }"><Badge size="sm" :color="statusColors[value]">{{ value }}</Badge></template>
|
|
68
|
+
<template #cell-actions="{ row }">
|
|
69
|
+
<Button variant="ghost" size="sm" square :aria-label="'More for ' + row.name"><Ellipsis /></Button>
|
|
70
|
+
</template>
|
|
71
|
+
</Table>
|
|
72
|
+
</Card>`,
|
|
73
|
+
}),
|
|
74
|
+
} satisfies Meta<TableProps>;
|
|
75
|
+
|
|
76
|
+
export default meta;
|
|
77
|
+
type Story = StoryObj<typeof meta>;
|
|
78
|
+
|
|
79
|
+
/** Playground. Click a heading to sort: ascending, descending, then back to the original order. */
|
|
80
|
+
export const Default: Story = {};
|
|
81
|
+
|
|
82
|
+
/** Plain text cells, no slots: the simplest table. */
|
|
83
|
+
export const Simple: Story = {
|
|
84
|
+
args: {
|
|
85
|
+
columns: [
|
|
86
|
+
{ key: "name", label: "Class", rowHeader: true },
|
|
87
|
+
{ key: "teacher", label: "Teacher" },
|
|
88
|
+
{ key: "room", label: "Room" },
|
|
89
|
+
{ key: "students", label: "Students", align: "end" },
|
|
90
|
+
],
|
|
91
|
+
rows: [
|
|
92
|
+
{ name: "8Y/En1", teacher: "Ms Rahman", room: "E12", students: 28 },
|
|
93
|
+
{ name: "8Y/En2", teacher: "Mr Blissett", room: "E14", students: 27 },
|
|
94
|
+
{ name: "8Y/Ma1", teacher: "Mrs Okoro", room: "M3", students: 30 },
|
|
95
|
+
],
|
|
96
|
+
rowKey: "name",
|
|
97
|
+
caption: "Year 8 classes",
|
|
98
|
+
},
|
|
99
|
+
render: (args) => ({
|
|
100
|
+
components: { Table, Card },
|
|
101
|
+
setup: () => ({ args }),
|
|
102
|
+
template: `<Card padding="none"><Table v-bind="args" /></Card>`,
|
|
103
|
+
}),
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** In a titled Card: the card names the section, the caption names the table. */
|
|
107
|
+
export const InCard: Story = {
|
|
108
|
+
render: (args) => ({
|
|
109
|
+
components: { Table, Card, Badge, Button },
|
|
110
|
+
setup: () => ({ args, statusColors, date }),
|
|
111
|
+
template: `
|
|
112
|
+
<Card title="Applications" description="6 for September 2027" padding="none" :ui="{ header: 'px-4 pt-4 sm:px-6 sm:pt-6' }">
|
|
113
|
+
<template #actions><Button size="sm">Export</Button></template>
|
|
114
|
+
<Table v-bind="args" :columns="args.columns.slice(0, 5)">
|
|
115
|
+
<template #cell-applied="{ value }">{{ date(value) }}</template>
|
|
116
|
+
<template #cell-score="{ value }">{{ value ?? '—' }}</template>
|
|
117
|
+
<template #cell-status="{ value }"><Badge size="sm" :color="statusColors[value]">{{ value }}</Badge></template>
|
|
118
|
+
</Table>
|
|
119
|
+
</Card>`,
|
|
120
|
+
}),
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/** size="sm": 8px above and below each cell, for dense tables. */
|
|
124
|
+
export const Small: Story = { args: { size: "sm" } };
|
|
125
|
+
|
|
126
|
+
/** A footer row for totals, in a `<tfoot>`. */
|
|
127
|
+
export const WithTotals: Story = {
|
|
128
|
+
args: {
|
|
129
|
+
columns: [
|
|
130
|
+
{ key: "item", label: "Item", rowHeader: true },
|
|
131
|
+
{ key: "qty", label: "Qty", align: "end" },
|
|
132
|
+
{ key: "amount", label: "Amount", align: "end" },
|
|
133
|
+
],
|
|
134
|
+
rows: [
|
|
135
|
+
{ item: "Autumn term fees", qty: 1, amount: "£6,450.00" },
|
|
136
|
+
{ item: "Lunches", qty: 62, amount: "£186.00" },
|
|
137
|
+
{ item: "Geography trip", qty: 1, amount: "£45.00" },
|
|
138
|
+
],
|
|
139
|
+
rowKey: "item",
|
|
140
|
+
caption: "Invoice INV-2027-0142",
|
|
141
|
+
},
|
|
142
|
+
render: (args) => ({
|
|
143
|
+
components: { Table, Card },
|
|
144
|
+
setup: () => ({ args }),
|
|
145
|
+
template: `
|
|
146
|
+
<Card padding="none" class="max-w-lg">
|
|
147
|
+
<Table v-bind="args">
|
|
148
|
+
<template #footer>
|
|
149
|
+
<tr><th scope="row" class="text-left">Total</th><td></td><td class="text-right tabular-nums">£6,681.00</td></tr>
|
|
150
|
+
</template>
|
|
151
|
+
</Table>
|
|
152
|
+
</Card>`,
|
|
153
|
+
}),
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/** A long table that scrolls inside a fixed height, keeping the header in view. */
|
|
157
|
+
export const StickyHeader: Story = {
|
|
158
|
+
args: {
|
|
159
|
+
stickyHeader: true,
|
|
160
|
+
class: "max-h-72",
|
|
161
|
+
rows: Array.from({ length: 24 }, (_, i) => ({ ...applicants[i % 6], id: i + 1 })),
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
/** No rows yet, with a custom empty message. */
|
|
166
|
+
export const Empty: Story = {
|
|
167
|
+
args: { rows: [] },
|
|
168
|
+
render: (args) => ({
|
|
169
|
+
components: { Table, Card, Button },
|
|
170
|
+
setup: () => ({ args }),
|
|
171
|
+
template: `
|
|
172
|
+
<Card padding="none">
|
|
173
|
+
<Table v-bind="args">
|
|
174
|
+
<template #empty>
|
|
175
|
+
<div class="flex flex-col items-center gap-3">
|
|
176
|
+
<span>No applications yet.</span>
|
|
177
|
+
<Button size="sm">Share the application form</Button>
|
|
178
|
+
</div>
|
|
179
|
+
</template>
|
|
180
|
+
</Table>
|
|
181
|
+
</Card>`,
|
|
182
|
+
}),
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/** Loading with no rows shows a spinner; with rows (refreshing) dims them. */
|
|
186
|
+
export const Loading: Story = { args: { rows: [], loading: true } };
|
|
187
|
+
|
|
188
|
+
/** manualSort: the table only reports the sort, e.g. to fetch sorted rows from the server. */
|
|
189
|
+
export const ManualSort: Story = {
|
|
190
|
+
render: (args) => ({
|
|
191
|
+
components: { Table, Card },
|
|
192
|
+
setup() {
|
|
193
|
+
const sort = ref<TableSort | null>({ key: "name", direction: "asc" });
|
|
194
|
+
return { args, sort, date };
|
|
195
|
+
},
|
|
196
|
+
template: `
|
|
197
|
+
<div class="flex flex-col gap-3">
|
|
198
|
+
<p class="text-sm">sort: <code>{{ JSON.stringify(sort) }}</code> (rows not re-ordered)</p>
|
|
199
|
+
<Card padding="none">
|
|
200
|
+
<Table v-bind="args" :columns="args.columns.slice(0, 4)" v-model:sort="sort" manual-sort>
|
|
201
|
+
<template #cell-applied="{ value }">{{ date(value) }}</template>
|
|
202
|
+
</Table>
|
|
203
|
+
</Card>
|
|
204
|
+
</div>`,
|
|
205
|
+
}),
|
|
206
|
+
};
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
<script setup lang="ts" generic="Row extends Record<string, any>">
|
|
2
|
+
import { computed, onBeforeUnmount, onMounted, ref, useId, type HTMLAttributes } from 'vue'
|
|
3
|
+
import { ArrowDown, ArrowUp, ChevronsUpDown } from '@lucide/vue'
|
|
4
|
+
import { cn } from '../../lib/cn'
|
|
5
|
+
import Spinner from '../Spinner/Spinner.vue'
|
|
6
|
+
import { nextSort, sortRows, type TableColumn, type TableSort } from './table'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Rows of data with column headings: applicants, classes, invoices.
|
|
10
|
+
*
|
|
11
|
+
* No border or background of its own: put it in a `<Card padding="none">`,
|
|
12
|
+
* which gives the white panel, and the table runs to its edges.
|
|
13
|
+
*
|
|
14
|
+
* Cells show `row[column.key]` as text. For anything else (a Badge, a link,
|
|
15
|
+
* a menu) use the slot `#cell-{key}`, which gets `{ row, value, index }`.
|
|
16
|
+
*
|
|
17
|
+
* Sorting: mark columns `sortable`. The table sorts the rows itself; with
|
|
18
|
+
* `manualSort` it only reports the sort (`v-model:sort`) so you can sort on
|
|
19
|
+
* the server.
|
|
20
|
+
*
|
|
21
|
+
* Slots: cell-{key}, header-{key}, empty, footer (rows for a `<tfoot>`,
|
|
22
|
+
* e.g. totals), caption.
|
|
23
|
+
*/
|
|
24
|
+
export interface TableProps<Row = Record<string, any>> {
|
|
25
|
+
columns: TableColumn<Row>[]
|
|
26
|
+
rows: Row[]
|
|
27
|
+
/** Unique field on each row, or a function returning one. Used to keep rows stable when sorting. */
|
|
28
|
+
rowKey?: keyof Row & string | ((row: Row, index: number) => string | number)
|
|
29
|
+
/**
|
|
30
|
+
* What the table shows, e.g. "Applications for September 2027". The
|
|
31
|
+
* table's accessible name. Hidden unless `showCaption`.
|
|
32
|
+
*/
|
|
33
|
+
caption?: string
|
|
34
|
+
showCaption?: boolean
|
|
35
|
+
/** Shown when there are no rows. */
|
|
36
|
+
emptyText?: string
|
|
37
|
+
/** Show a spinner (no rows yet), or dim the rows (refreshing). */
|
|
38
|
+
loading?: boolean
|
|
39
|
+
/** md (default) 12px above and below each cell, sm 8px for dense tables. */
|
|
40
|
+
size?: 'sm' | 'md'
|
|
41
|
+
/** Keep the header row in view while the table scrolls. Give the table a max height (`class="max-h-96"`). */
|
|
42
|
+
stickyHeader?: boolean
|
|
43
|
+
/** Don't sort the rows: just update `sort`, e.g. to sort on the server. */
|
|
44
|
+
manualSort?: boolean
|
|
45
|
+
class?: HTMLAttributes['class']
|
|
46
|
+
ui?: {
|
|
47
|
+
table?: HTMLAttributes['class']
|
|
48
|
+
header?: HTMLAttributes['class']
|
|
49
|
+
row?: HTMLAttributes['class']
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const props = withDefaults(defineProps<TableProps<Row>>(), {
|
|
54
|
+
emptyText: 'Nothing to show.',
|
|
55
|
+
size: 'md'
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
const sort = defineModel<TableSort | null>('sort', { default: null })
|
|
59
|
+
|
|
60
|
+
defineSlots<
|
|
61
|
+
{
|
|
62
|
+
caption?(): unknown
|
|
63
|
+
empty?(): unknown
|
|
64
|
+
footer?(): unknown
|
|
65
|
+
} & {
|
|
66
|
+
[key: `cell-${string}`]: ((props: { row: Row; value: any; index: number }) => unknown) | undefined
|
|
67
|
+
} & {
|
|
68
|
+
[key: `header-${string}`]: ((props: { column: TableColumn<Row> }) => unknown) | undefined
|
|
69
|
+
}
|
|
70
|
+
>()
|
|
71
|
+
|
|
72
|
+
const captionId = `${useId()}-caption`
|
|
73
|
+
|
|
74
|
+
const shownRows = computed(() => (props.manualSort ? props.rows : sortRows(props.rows, props.columns, sort.value)))
|
|
75
|
+
|
|
76
|
+
function keyOf(row: Row, index: number) {
|
|
77
|
+
if (typeof props.rowKey === 'function') return props.rowKey(row, index)
|
|
78
|
+
if (props.rowKey) return row[props.rowKey] as string | number
|
|
79
|
+
return index
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function ariaSort(column: TableColumn<Row>) {
|
|
83
|
+
if (!column.sortable) return undefined
|
|
84
|
+
if (sort.value?.key !== column.key) return 'none'
|
|
85
|
+
return sort.value.direction === 'asc' ? 'ascending' : 'descending'
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const cellPadding = computed(() => (props.size === 'sm' ? 'px-4 py-2' : 'px-4 py-3'))
|
|
89
|
+
|
|
90
|
+
function columnClasses(column: TableColumn<Row>) {
|
|
91
|
+
return cn(column.align === 'end' && 'text-right', column.nowrap !== false && 'whitespace-nowrap', column.class)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const focusRing =
|
|
95
|
+
'outline-2 outline-offset-1 outline-transparent focus-visible:outline-focus forced-colors:not-focus-visible:outline-0'
|
|
96
|
+
|
|
97
|
+
// Inside the edge, so a Card's rounded corners (which clip) don't cut it off.
|
|
98
|
+
const scrollRing =
|
|
99
|
+
'outline-2 -outline-offset-2 outline-transparent focus-visible:outline-focus forced-colors:not-focus-visible:outline-0'
|
|
100
|
+
|
|
101
|
+
// A wrapper that scrolls needs to be focusable, so keyboard users can scroll
|
|
102
|
+
// it, and named, so they know what they're scrolling. Only when it scrolls.
|
|
103
|
+
const scroller = ref<HTMLElement>()
|
|
104
|
+
const scrolls = ref(false)
|
|
105
|
+
let observer: ResizeObserver | undefined
|
|
106
|
+
function measure() {
|
|
107
|
+
const el = scroller.value
|
|
108
|
+
if (el) scrolls.value = el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 1
|
|
109
|
+
}
|
|
110
|
+
onMounted(() => {
|
|
111
|
+
measure()
|
|
112
|
+
observer = new ResizeObserver(measure)
|
|
113
|
+
if (scroller.value) {
|
|
114
|
+
observer.observe(scroller.value)
|
|
115
|
+
if (scroller.value.firstElementChild) observer.observe(scroller.value.firstElementChild)
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
onBeforeUnmount(() => observer?.disconnect())
|
|
119
|
+
</script>
|
|
120
|
+
|
|
121
|
+
<template>
|
|
122
|
+
<div
|
|
123
|
+
ref="scroller"
|
|
124
|
+
:class="cn('relative overflow-auto', scrolls && scrollRing, props.class)"
|
|
125
|
+
:tabindex="scrolls ? 0 : undefined"
|
|
126
|
+
:role="scrolls ? 'region' : undefined"
|
|
127
|
+
:aria-labelledby="scrolls && (caption || $slots.caption) ? captionId : undefined"
|
|
128
|
+
:aria-label="scrolls && !caption && !$slots.caption ? 'Table' : undefined"
|
|
129
|
+
>
|
|
130
|
+
<table
|
|
131
|
+
:class="cn('w-full border-separate border-spacing-0 text-left text-sm text-black', ui?.table)"
|
|
132
|
+
:aria-busy="loading || undefined"
|
|
133
|
+
>
|
|
134
|
+
<caption v-if="caption || $slots.caption" :id="captionId" :class="showCaption ? 'px-4 pt-4 pb-2 text-left text-base font-bold' : 'sr-only'">
|
|
135
|
+
<slot name="caption">{{ caption }}</slot>
|
|
136
|
+
</caption>
|
|
137
|
+
|
|
138
|
+
<thead :class="cn(stickyHeader && 'sticky top-0 z-10 bg-white', ui?.header)">
|
|
139
|
+
<tr>
|
|
140
|
+
<th
|
|
141
|
+
v-for="column in columns"
|
|
142
|
+
:key="column.key"
|
|
143
|
+
scope="col"
|
|
144
|
+
:aria-sort="ariaSort(column)"
|
|
145
|
+
:class="cn('border-b border-black/15 font-bold text-black/65', cellPadding, columnClasses(column))"
|
|
146
|
+
>
|
|
147
|
+
<slot :name="`header-${column.key}`" :column="column">
|
|
148
|
+
<span v-if="column.hideLabel" class="sr-only">{{ column.label }}</span>
|
|
149
|
+
<button
|
|
150
|
+
v-else-if="column.sortable"
|
|
151
|
+
type="button"
|
|
152
|
+
:class="
|
|
153
|
+
cn(
|
|
154
|
+
'-mx-1 inline-flex cursor-pointer items-center gap-1 rounded px-1 font-bold hover:text-black',
|
|
155
|
+
column.align === 'end' && 'flex-row-reverse',
|
|
156
|
+
sort?.key === column.key && 'text-black',
|
|
157
|
+
focusRing
|
|
158
|
+
)
|
|
159
|
+
"
|
|
160
|
+
@click="sort = nextSort(sort, column.key)"
|
|
161
|
+
>
|
|
162
|
+
{{ column.label }}
|
|
163
|
+
<ArrowUp v-if="sort?.key === column.key && sort.direction === 'asc'" class="size-4 shrink-0" aria-hidden="true" />
|
|
164
|
+
<ArrowDown v-else-if="sort?.key === column.key" class="size-4 shrink-0" aria-hidden="true" />
|
|
165
|
+
<ChevronsUpDown v-else class="size-4 shrink-0 text-black/40" aria-hidden="true" />
|
|
166
|
+
</button>
|
|
167
|
+
<template v-else>{{ column.label }}</template>
|
|
168
|
+
</slot>
|
|
169
|
+
</th>
|
|
170
|
+
</tr>
|
|
171
|
+
</thead>
|
|
172
|
+
|
|
173
|
+
<tbody :class="cn(loading && shownRows.length && 'opacity-50 transition-opacity')">
|
|
174
|
+
<tr v-if="!shownRows.length">
|
|
175
|
+
<td :colspan="columns.length" class="px-4 py-8 text-center text-black/65">
|
|
176
|
+
<span v-if="loading" class="inline-flex items-center gap-2">
|
|
177
|
+
<Spinner size="sm" />
|
|
178
|
+
Loading…
|
|
179
|
+
</span>
|
|
180
|
+
<slot v-else name="empty">{{ emptyText }}</slot>
|
|
181
|
+
</td>
|
|
182
|
+
</tr>
|
|
183
|
+
<tr v-for="(row, index) in shownRows" :key="keyOf(row, index)" :class="cn('group/row', ui?.row)">
|
|
184
|
+
<component
|
|
185
|
+
:is="column.rowHeader ? 'th' : 'td'"
|
|
186
|
+
v-for="column in columns"
|
|
187
|
+
:key="column.key"
|
|
188
|
+
:scope="column.rowHeader ? 'row' : undefined"
|
|
189
|
+
:class="
|
|
190
|
+
cn(
|
|
191
|
+
'border-b border-black/15 align-middle group-last/row:border-b-0',
|
|
192
|
+
column.rowHeader ? 'font-bold' : 'font-normal',
|
|
193
|
+
column.align === 'end' && 'tabular-nums',
|
|
194
|
+
cellPadding,
|
|
195
|
+
columnClasses(column)
|
|
196
|
+
)
|
|
197
|
+
"
|
|
198
|
+
>
|
|
199
|
+
<slot :name="`cell-${column.key}`" :row="row" :value="row[column.key]" :index="index">
|
|
200
|
+
{{ row[column.key] ?? '' }}
|
|
201
|
+
</slot>
|
|
202
|
+
</component>
|
|
203
|
+
</tr>
|
|
204
|
+
</tbody>
|
|
205
|
+
|
|
206
|
+
<!-- Footer cells get the same padding and a top border, so totals line up. -->
|
|
207
|
+
<tfoot
|
|
208
|
+
v-if="$slots.footer"
|
|
209
|
+
:class="
|
|
210
|
+
cn(
|
|
211
|
+
'font-bold *:*:border-t *:*:border-black/15',
|
|
212
|
+
size === 'sm' ? '*:*:px-4 *:*:py-2' : '*:*:px-4 *:*:py-3'
|
|
213
|
+
)
|
|
214
|
+
"
|
|
215
|
+
>
|
|
216
|
+
<slot name="footer" />
|
|
217
|
+
</tfoot>
|
|
218
|
+
</table>
|
|
219
|
+
</div>
|
|
220
|
+
</template>
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { nextSort, sortRows, type TableColumn } from './table'
|
|
3
|
+
|
|
4
|
+
type Row = { name: string; year: string; count?: number | null; date?: Date }
|
|
5
|
+
|
|
6
|
+
const rows: Row[] = [
|
|
7
|
+
{ name: 'noah', year: 'Year 10', count: 3 },
|
|
8
|
+
{ name: 'Amelia', year: 'Year 2', count: null },
|
|
9
|
+
{ name: 'zara', year: 'Year 7', count: 12 },
|
|
10
|
+
{ name: 'Ben', year: 'Year 7', count: 3 },
|
|
11
|
+
]
|
|
12
|
+
const columns: TableColumn<Row>[] = [
|
|
13
|
+
{ key: 'name', label: 'Name' },
|
|
14
|
+
{ key: 'year', label: 'Year' },
|
|
15
|
+
{ key: 'count', label: 'Count' },
|
|
16
|
+
{ key: 'joined', label: 'Joined', sortValue: (row) => row.date },
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
const names = (list: Row[]) => list.map((row) => row.name)
|
|
20
|
+
|
|
21
|
+
describe('sortRows', () => {
|
|
22
|
+
it('returns a copy in the original order without a sort', () => {
|
|
23
|
+
const result = sortRows(rows, columns, null)
|
|
24
|
+
expect(result).toEqual(rows)
|
|
25
|
+
expect(result).not.toBe(rows)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('ignores an unknown column', () => {
|
|
29
|
+
expect(sortRows(rows, columns, { key: 'nope', direction: 'asc' })).toEqual(rows)
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it('sorts text ignoring case', () => {
|
|
33
|
+
expect(names(sortRows(rows, columns, { key: 'name', direction: 'asc' }))).toEqual(['Amelia', 'Ben', 'noah', 'zara'])
|
|
34
|
+
expect(names(sortRows(rows, columns, { key: 'name', direction: 'desc' }))).toEqual(['zara', 'noah', 'Ben', 'Amelia'])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('sorts numbers in text naturally, and keeps ties in order', () => {
|
|
38
|
+
expect(names(sortRows(rows, columns, { key: 'year', direction: 'asc' }))).toEqual(['Amelia', 'zara', 'Ben', 'noah'])
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('sorts numbers, with empty values last both ways', () => {
|
|
42
|
+
expect(names(sortRows(rows, columns, { key: 'count', direction: 'asc' }))).toEqual(['noah', 'Ben', 'zara', 'Amelia'])
|
|
43
|
+
expect(names(sortRows(rows, columns, { key: 'count', direction: 'desc' }))).toEqual(['zara', 'noah', 'Ben', 'Amelia'])
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('uses sortValue, e.g. for dates', () => {
|
|
47
|
+
const dated = [
|
|
48
|
+
{ name: 'b', year: '', date: new Date(2026, 5, 1) },
|
|
49
|
+
{ name: 'a', year: '', date: new Date(2025, 0, 1) },
|
|
50
|
+
]
|
|
51
|
+
expect(names(sortRows(dated, columns, { key: 'joined', direction: 'asc' }))).toEqual(['a', 'b'])
|
|
52
|
+
})
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
describe('nextSort', () => {
|
|
56
|
+
it('cycles ascending, descending, unsorted', () => {
|
|
57
|
+
expect(nextSort(null, 'name')).toEqual({ key: 'name', direction: 'asc' })
|
|
58
|
+
expect(nextSort({ key: 'name', direction: 'asc' }, 'name')).toEqual({ key: 'name', direction: 'desc' })
|
|
59
|
+
expect(nextSort({ key: 'name', direction: 'desc' }, 'name')).toBeNull()
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('starts ascending on a different column', () => {
|
|
63
|
+
expect(nextSort({ key: 'name', direction: 'desc' }, 'year')).toEqual({ key: 'year', direction: 'asc' })
|
|
64
|
+
})
|
|
65
|
+
})
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
export type SortDirection = 'asc' | 'desc'
|
|
2
|
+
|
|
3
|
+
export interface TableSort {
|
|
4
|
+
key: string
|
|
5
|
+
direction: SortDirection
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface TableColumn<Row = Record<string, unknown>> {
|
|
9
|
+
/** Field on each row, and the name of the cell slot (`#cell-{key}`). */
|
|
10
|
+
key: string
|
|
11
|
+
/** Header text. */
|
|
12
|
+
label: string
|
|
13
|
+
/**
|
|
14
|
+
* Visually hide the header (it's still read out), e.g. for an actions
|
|
15
|
+
* column. The label is still required.
|
|
16
|
+
*/
|
|
17
|
+
hideLabel?: boolean
|
|
18
|
+
/** start (default) or end. Use end for numbers, so the digits line up. */
|
|
19
|
+
align?: 'start' | 'end'
|
|
20
|
+
/** Let people sort by this column. */
|
|
21
|
+
sortable?: boolean
|
|
22
|
+
/** What to sort by, when it isn't `row[key]` (e.g. a date's timestamp). */
|
|
23
|
+
sortValue?: (row: Row) => unknown
|
|
24
|
+
/** The row's heading: its first cell is a `<th scope="row">`. One column at most. */
|
|
25
|
+
rowHeader?: boolean
|
|
26
|
+
/** Keep the text on one line. Default true; turn off for long text. */
|
|
27
|
+
nowrap?: boolean
|
|
28
|
+
/** Extra classes for this column's header and cells, e.g. a width. */
|
|
29
|
+
class?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const collator = new Intl.Collator('en-GB', { numeric: true, sensitivity: 'base' })
|
|
33
|
+
|
|
34
|
+
function compare(a: unknown, b: unknown): number {
|
|
35
|
+
// Empty values go last, whichever way the column is sorted.
|
|
36
|
+
const aEmpty = a === null || a === undefined || a === ''
|
|
37
|
+
const bEmpty = b === null || b === undefined || b === ''
|
|
38
|
+
if (aEmpty || bEmpty) return aEmpty === bEmpty ? 0 : aEmpty ? 1 : -1
|
|
39
|
+
if (typeof a === 'number' && typeof b === 'number') return a - b
|
|
40
|
+
if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime()
|
|
41
|
+
if (typeof a === 'boolean' && typeof b === 'boolean') return Number(a) - Number(b)
|
|
42
|
+
return collator.compare(String(a), String(b))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Sorts a copy of `rows`. Stable, so rows that tie keep their order. Text
|
|
47
|
+
* sorts naturally ("Year 2" before "Year 10") and ignores case; empty values
|
|
48
|
+
* go last in both directions.
|
|
49
|
+
*/
|
|
50
|
+
export function sortRows<Row>(rows: readonly Row[], columns: readonly TableColumn<Row>[], sort?: TableSort | null): Row[] {
|
|
51
|
+
const column = sort && columns.find((c) => c.key === sort.key)
|
|
52
|
+
if (!sort || !column) return [...rows]
|
|
53
|
+
const value = column.sortValue ?? ((row: Row) => (row as Record<string, unknown>)[column.key])
|
|
54
|
+
const sign = sort.direction === 'asc' ? 1 : -1
|
|
55
|
+
return rows
|
|
56
|
+
.map((row, index) => ({ row, index, value: value(row) }))
|
|
57
|
+
.sort((a, b) => {
|
|
58
|
+
const aEmpty = a.value === null || a.value === undefined || a.value === ''
|
|
59
|
+
const bEmpty = b.value === null || b.value === undefined || b.value === ''
|
|
60
|
+
const result = aEmpty || bEmpty ? compare(a.value, b.value) : sign * compare(a.value, b.value)
|
|
61
|
+
return result || a.index - b.index
|
|
62
|
+
})
|
|
63
|
+
.map((entry) => entry.row)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Clicking a header: ascending, then descending, then back to unsorted. */
|
|
67
|
+
export function nextSort(current: TableSort | null | undefined, key: string): TableSort | null {
|
|
68
|
+
if (current?.key !== key) return { key, direction: 'asc' }
|
|
69
|
+
return current.direction === 'asc' ? { key, direction: 'desc' } : null
|
|
70
|
+
}
|