feat: add display and sort methods in header object

This commit is contained in:
albert 2020-10-21 23:39:25 +02:00
commit 2ad9072abd

View file

@ -1,7 +1,7 @@
<script> <script>
/** /**
* Specify the data table headers * Specify the data table headers
* @type {{key: string; value: string;}[]} [headers=[]] * @type {{key: string; value: string; display?: (item) => string; sort?: (a, b) => number}[]} [headers=[]]
*/ */
export let headers = []; export let headers = [];
@ -85,7 +85,12 @@
}; };
const dispatch = createEventDispatcher(); const dispatch = createEventDispatcher();
const tableSortable = writable(sortable); const tableSortable = writable(sortable);
const sortHeader = writable({ id: null, key: null, sortDirection: "none" }); const sortHeader = writable({
id: null,
key: null,
sort: undefined,
sortDirection: "none",
});
const headerItems = writable([]); const headerItems = writable([]);
const thKeys = derived(headerItems, () => const thKeys = derived(headerItems, () =>
headers headers
@ -123,7 +128,10 @@
if ($sortHeader.sortDirection === "none") { if ($sortHeader.sortDirection === "none") {
sortedRows = rows; sortedRows = rows;
} else { } else {
sortedRows = [...rows].sort((a, b) => { sortedRows = [...rows].sort(
$sortHeader.sort
? $sortHeader.sort
: (a, b) => {
const itemA = ascending ? a[sortKey] : b[sortKey]; const itemA = ascending ? a[sortKey] : b[sortKey];
const itemB = ascending ? b[sortKey] : a[sortKey]; const itemB = ascending ? b[sortKey] : a[sortKey];
@ -134,7 +142,8 @@
return itemA return itemA
.toString() .toString()
.localeCompare(itemB.toString(), "en", { numeric: true }); .localeCompare(itemB.toString(), "en", { numeric: true });
}); }
);
} }
} }
</script> </script>
@ -181,6 +190,7 @@
sortHeader.set({ sortHeader.set({
id: sortDirection === 'none' ? null : $thKeys[header.key], id: sortDirection === 'none' ? null : $thKeys[header.key],
key: header.key, key: header.key,
sort: header.sort,
sortDirection, sortDirection,
}); });
}}" }}"
@ -231,7 +241,9 @@
dispatch('click:cell', cell); dispatch('click:cell', cell);
}}" }}"
> >
<slot name="cell" row="{row}" cell="{cell}">{cell.value}</slot> <slot name="cell" row="{row}" cell="{cell}">
{headers[j].display ? headers[j].display(cell.value) : cell.value}
</slot>
</TableCell> </TableCell>
{/each} {/each}
</TableRow> </TableRow>