-
-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy path_Sortable.svelte
More file actions
97 lines (92 loc) · 2.66 KB
/
_Sortable.svelte
File metadata and controls
97 lines (92 loc) · 2.66 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
<DataTable
sortable
bind:sort
bind:sortDirection
onSMUIDataTableSorted={handleSort}
table$aria-label="User list"
style="width: 100%;"
>
<Head>
<Row>
<!--
Note: whatever you supply to "columnId" is
appended with "-status-label" and used as an ID
for the hidden label that describes the sort
status to screen readers.
You can localize those labels with the
"sortAscendingAriaLabel" and
"sortDescendingAriaLabel" props on the DataTable.
-->
<Cell numeric columnId="id">
<!-- For numeric columns, icon comes first. -->
<IconButton class="material-icons">arrow_upward</IconButton>
<Label>ID</Label>
</Cell>
<Cell columnId="name" style="width: 100%;">
<Label>Name</Label>
<!-- For non-numeric columns, icon comes second. -->
<IconButton class="material-icons">arrow_upward</IconButton>
</Cell>
<Cell columnId="username">
<Label>Username</Label>
<IconButton class="material-icons">arrow_upward</IconButton>
</Cell>
<Cell columnId="email">
<Label>Email</Label>
<IconButton class="material-icons">arrow_upward</IconButton>
</Cell>
<!-- You can turn off sorting for a column. -->
<Cell sortable={false}>Website</Cell>
</Row>
</Head>
<Body>
{#each items as item (item.id)}
<Row>
<Cell numeric>{item.id}</Cell>
<Cell>{item.name}</Cell>
<Cell>{item.username}</Cell>
<Cell>{item.email}</Cell>
<Cell>{item.website}</Cell>
</Row>
{/each}
</Body>
</DataTable>
<script lang="ts">
import DataTable, {
Head,
Body,
Row,
Cell,
Label,
SortValue,
} from '@smui/data-table';
import IconButton from '@smui/icon-button';
type User = {
id: number;
name: string;
username: string;
email: string;
website: string;
};
let items: User[] = $state([]);
let sort: keyof User = $state('id');
let sortDirection: Lowercase<keyof typeof SortValue> = $state('ascending');
if (typeof fetch !== 'undefined') {
fetch(
'https://gist.githubusercontent.com/hperrin/e24a4ebd9afdf2a8c283338ae5160a62/raw/dcbf8e6382db49b0dcab70b22f56b1cc444f26d4/users.json',
)
.then((response) => response.json())
.then((json) => (items = json));
}
function handleSort() {
items.sort((a, b) => {
const [aVal, bVal] = [a[sort], b[sort]][
sortDirection === 'ascending' ? 'slice' : 'reverse'
]();
if (typeof aVal === 'string' && typeof bVal === 'string') {
return aVal.localeCompare(bVal);
}
return Number(aVal) - Number(bVal);
});
}
</script>