switched tanstack query

This commit is contained in:
John O'Keefe 2024-09-05 20:42:20 -04:00
parent d611ed8b3a
commit cbcb07d2f1
4 changed files with 215 additions and 131 deletions

View File

@ -2,32 +2,20 @@
import type {TableItem} from "../helperTypes/TableTypes"; import type {TableItem} from "../helperTypes/TableTypes";
import { tableItems } from "./GlobalVariablesAndHelperFunctions.svelte" import { tableItems } from "./GlobalVariablesAndHelperFunctions.svelte"
export function AddAnimeServiceToTable(tableItem: TableItem) { export function AddAnimeServiceToTable(animeItem: TableItem) {
let tableLoaded: TableItem[] tableItems.update((table) => {
tableItems.subscribe(value => tableLoaded = value) if (table.length === 0) {
console.log(tableLoaded.length) table.push(animeItem)
if(tableLoaded.length === 0) {
tableItems.update(table => {
table.push(tableItem)
return table
})
return
}
for (const [index, entry] of tableLoaded.entries()) {
console.log(entry)
if (entry.service === tableItem.service) {
tableItems.update(value => {
value[index] = tableItem
return value
})
} else { } else {
tableItems.update(table => { for (const [index, tableItem] of table.entries()) {
table.push(tableItem) if(tableItem.service === animeItem.service) {
table[index] = animeItem
return table
}
}
table.push(animeItem)
}
return table return table
}) })
} }
}
return
}
</script> </script>

View File

@ -1,68 +1,151 @@
<script lang="ts"> <script lang="ts">
import {Table, TableBody, TableBodyCell, TableBodyRow, TableHead, TableHeadCell} from "flowbite-svelte"; import {writable} from 'svelte/store'
import {writable} from "svelte/store"; import type {ColumnDef, TableOptions} from '@tanstack/svelte-table'
import type {TableItems} from "../helperTypes/TableTypes"; import {
createSvelteTable,
flexRender,
getCoreRowModel,
getSortedRowModel,
type OnChangeFn,
type SortingState,
} from '@tanstack/svelte-table'
import {tableItems} from "./GlobalVariablesAndHelperFunctions.svelte"
import type {TableItem, TableItems} from "../helperTypes/TableTypes";
export let items: TableItems let tableItemsView: TableItems
// tableItems.subscribe(value => items = value) tableItems.subscribe(value => tableItemsView = value)
const sortKey = writable('service'); // default sort key const defaultColumns: ColumnDef<TableItem>[] = [
const sortDirection = writable(1); // default sort direction (ascending) {
const sortItems = writable(items.slice()); // make a copy of the items array accessorKey: 'id',
header: () => "Service Id",
cell: info => info.getValue(),
},
{
accessorKey: 'service',
header: () => 'Service',
cell: info => info.getValue(),
},
{
accessorKey: 'progress',
header: () => 'Episode Progress',
cell: info => info.getValue(),
},
{
accessorKey: 'status',
header: () => 'Status',
cell: info => info.getValue(),
},
{
accessorKey: 'startedAt',
header: () => 'Started At',
cell: info => info.getValue(),
},
{
accessorKey: 'completedAt',
header: () => 'Completed At',
cell: info => info.getValue(),
},
{
accessorKey: 'score',
header: () => 'Rating',
cell: info => info.getValue(),
},
{
accessorKey: 'repeat',
header: () => 'Repeat',
cell: info => info.getValue(),
},
{
accessorKey: 'notes',
header: () => 'Notes',
cell: info => info.getValue(),
},
]
// Define a function to sort the items let sorting: SortingState = []
const sortTable = (key: any) => {
// If the same key is clicked, reverse the sort direction const setSorting: OnChangeFn<SortingState> = updater => {
if ($sortKey === key) { if (updater instanceof Function) {
sortDirection.update((val) => -val); sorting = updater(sorting)
} else { } else {
sortKey.set(key); sorting = updater
sortDirection.set(1); }
options.update(old => ({
...old,
state: {
...old.state,
sorting,
},
}))
} }
};
$: { const options = writable<TableOptions<TableItem>>({
const key = $sortKey; data: tableItemsView,
const direction = $sortDirection; columns: defaultColumns,
const sorted = [...$sortItems].sort((a, b) => { state: {
const aVal = a[key]; sorting,
const bVal = b[key]; },
if (aVal < bVal) { onSortingChange: setSorting,
return -direction; getCoreRowModel: getCoreRowModel(),
} else if (aVal > bVal) { getSortedRowModel: getSortedRowModel(),
return direction; })
}
return 0; const rerender = () => {
}); console.log(tableItemsView)
sortItems.set(sorted); options.update(options => ({
...options,
data: tableItemsView,
}))
} }
const table = createSvelteTable(options)
</script> </script>
<Table hoverable={true}> <div class="relative overflow-x-auto rounded-lg mb-5">
<TableHead> <table class="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400">
<TableHeadCell class="cursor-pointer" on:click={() => sortTable('id')}>ID</TableHeadCell> <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<TableHeadCell class="cursor-pointer" on:click={() => sortTable('service')}>Service</TableHeadCell> {#each $table.getHeaderGroups() as headerGroup}
<TableHeadCell class="cursor-pointer" on:click={() => sortTable('progress')}>Episode Progress</TableHeadCell> <tr>
<TableHeadCell class="cursor-pointer" on:click={() => sortTable('status')}>Status</TableHeadCell> {#each headerGroup.headers as header}
<TableHeadCell class="cursor-pointer" on:click={() => sortTable('startedAt')}>Date Started</TableHeadCell> <th class="px-6 py-3">
<TableHeadCell class="cursor-pointer" on:click={() => sortTable('completedAt')}>Date Completed</TableHeadCell> {#if !header.isPlaceholder}
<TableHeadCell class="cursor-pointer" on:click={() => sortTable('score')}>Rating</TableHeadCell> <button
<TableHeadCell class="cursor-pointer" on:click={() => sortTable('repeat')}>Rewatches</TableHeadCell> class:cursor-pointer={header.column.getCanSort()}
<TableHeadCell>Notes</TableHeadCell> class:select-none={header.column.getCanSort()}
</TableHead> on:click={header.column.getToggleSortingHandler()}
<TableBody tableBodyClass="divide-y"> >
{#each $sortItems as item} <svelte:component
<TableBodyRow> this={flexRender(
<TableBodyCell class="overflow-x-auto">{item.id}</TableBodyCell> header.column.columnDef.header,
<TableBodyCell class="overflow-x-auto">{item.service}</TableBodyCell> header.getContext()
<TableBodyCell class="overflow-x-auto">{item.progress}</TableBodyCell> )}
<TableBodyCell class="overflow-x-auto">{item.status}</TableBodyCell> />
<TableBodyCell class="overflow-x-auto">{item.startedAt}</TableBodyCell> {#if header.column.getIsSorted().toString() === 'asc'}
<TableBodyCell class="overflow-x-auto">{item.completedAt}</TableBodyCell> 🔼
<TableBodyCell class="overflow-x-auto">{item.score}</TableBodyCell> {:else if header.column.getIsSorted().toString() === 'desc'}
<TableBodyCell class="overflow-x-auto">{item.repeat}</TableBodyCell> 🔽
<TableBodyCell class="overflow-x-auto">{item.notes}</TableBodyCell> {/if}
</TableBodyRow> </button>
{/if}
</th>
{/each} {/each}
</TableBody> </tr>
</Table> {/each}
</thead>
<tbody>
{#each $table.getRowModel().rows as row}
<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
{#each row.getVisibleCells() as cell}
<td class="px-6 py-4">
<svelte:component
this={flexRender(cell.column.columnDef.cell, cell.getContext())}
/>
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
<button on:click={() => rerender()} class="border p-2 mb-3"> Rerender</button>
</div>

View File

@ -34,7 +34,6 @@
let currentLocation: any let currentLocation: any
location.subscribe(value => currentLocation = value) location.subscribe(value => currentLocation = value)
console.log(currentLocation)
</script> </script>
<nav class="bg-white border-gray-200 dark:bg-gray-900"> <nav class="bg-white border-gray-200 dark:bg-gray-900">

View File

@ -26,7 +26,7 @@
SimklSyncRating, SimklSyncRating,
SimklSyncStatus SimklSyncStatus
} from "../../wailsjs/go/main/App"; } from "../../wailsjs/go/main/App";
import type {TableItems} from "../helperTypes/TableTypes"; import {AddAnimeServiceToTable} from "../helperComponents/AddAnimeServiceToTable.svelte";
let isAniListLoggedIn: boolean let isAniListLoggedIn: boolean
let isMalLoggedIn: boolean let isMalLoggedIn: boolean
@ -60,9 +60,8 @@
let startingAnilistStatusOption: StatusOption = statusOptions.filter(option => currentAniListAnime.data.MediaList.status === option.aniList)[0] let startingAnilistStatusOption: StatusOption = statusOptions.filter(option => currentAniListAnime.data.MediaList.status === option.aniList)[0]
const startedAtDate = convertAniListDateToString(currentAniListAnime.data.MediaList.startedAt) const startedAtDate = convertAniListDateToString(currentAniListAnime.data.MediaList.startedAt)
const completedAtDate = convertAniListDateToString(currentAniListAnime.data.MediaList.completedAt) const completedAtDate = convertAniListDateToString(currentAniListAnime.data.MediaList.completedAt)
let tableItems: TableItems = []
if (isAniListLoggedIn) tableItems.push({ if (isAniListLoggedIn) AddAnimeServiceToTable({
id: currentAniListAnime.data.MediaList.id, id: currentAniListAnime.data.MediaList.id,
service: "AniList", service: "AniList",
progress: currentAniListAnime.data.MediaList.progress, progress: currentAniListAnime.data.MediaList.progress,
@ -75,7 +74,7 @@
}) })
if (isMalLoggedIn) tableItems.push({ if (isMalLoggedIn) AddAnimeServiceToTable({
id: currentMalAnime.id, id: currentMalAnime.id,
service: "MyAnimeList", service: "MyAnimeList",
progress: currentMalAnime.my_list_status.num_episodes_watched, progress: currentMalAnime.my_list_status.num_episodes_watched,
@ -87,7 +86,7 @@
notes: currentMalAnime.my_list_status.comments notes: currentMalAnime.my_list_status.comments
}) })
if (isSimklLoggedIn && Object.keys(currentSimklAnime).length > 0) tableItems.push({ if (isSimklLoggedIn && Object.keys(currentSimklAnime).length > 0) AddAnimeServiceToTable({
id: currentSimklAnime.show.ids.simkl, id: currentSimklAnime.show.ids.simkl,
service: "Simkl", service: "Simkl",
progress: currentSimklAnime.watched_episodes_count, progress: currentSimklAnime.watched_episodes_count,
@ -99,7 +98,6 @@
notes: "" notes: ""
}) })
const handleSubmit = async (e: any) => { const handleSubmit = async (e: any) => {
submitting.set(true) submitting.set(true)
let submitData: { let submitData: {
@ -165,19 +163,17 @@
newValue = value newValue = value
return newValue return newValue
}) })
for (const [index, tableItem] of tableItems.entries()) { AddAnimeServiceToTable({
if (tableItem.service === "AniList") { id: currentAniListAnime.data.MediaList.id,
tableItems[index].id = currentAniListAnime.data.MediaList.id service: "AniList",
tableItems[index].service = "AniList" progress: currentAniListAnime.data.MediaList.progress,
tableItems[index].progress = currentAniListAnime.data.MediaList.progress status: currentAniListAnime.data.MediaList.status,
tableItems[index].status = currentAniListAnime.data.MediaList.status startedAt: convertAniListDateToString(currentAniListAnime.data.MediaList.startedAt),
tableItems[index].startedAt = convertAniListDateToString(currentAniListAnime.data.MediaList.startedAt) completedAt: convertAniListDateToString(currentAniListAnime.data.MediaList.completedAt),
tableItems[index].completedAt = convertAniListDateToString(currentAniListAnime.data.MediaList.completedAt) score: currentAniListAnime.data.MediaList.score,
tableItems[index].score = currentAniListAnime.data.MediaList.score repeat: currentAniListAnime.data.MediaList.repeat,
tableItems[index].repeat = currentAniListAnime.data.MediaList.repeat notes: currentAniListAnime.data.MediaList.notes,
tableItems[index].notes = currentAniListAnime.data.MediaList.notes })
}
}
}) })
} }
@ -201,47 +197,54 @@
value.my_list_status.comments = malAnimeReturn.comments value.my_list_status.comments = malAnimeReturn.comments
return value return value
}) })
for (const [index, tableItem] of tableItems.entries()) { AddAnimeServiceToTable({
if (tableItem.service === "MyAnimeList") { id: currentMalAnime.id,
tableItems[index].id = currentMalAnime.id service: "MyAnimeList",
tableItems[index].service = "MyAnimeList" progress: currentMalAnime.my_list_status.num_episodes_watched,
tableItems[index].progress = currentMalAnime.my_list_status.num_episodes_watched status: currentMalAnime.my_list_status.status,
tableItems[index].status = currentMalAnime.my_list_status.status startedAt: currentMalAnime.my_list_status.start_date,
tableItems[index].startedAt = currentMalAnime.my_list_status.start_date completedAt: currentMalAnime.my_list_status.finish_date,
tableItems[index].completedAt = currentMalAnime.my_list_status.finish_date score: currentMalAnime.my_list_status.score,
tableItems[index].score = currentMalAnime.my_list_status.score repeat: currentMalAnime.my_list_status.num_times_rewatched,
tableItems[index].repeat = currentMalAnime.my_list_status.num_times_rewatched notes: currentMalAnime.my_list_status.comments,
tableItems[index].notes = currentMalAnime.my_list_status.comments })
}
}
}) })
} }
if (simklLoggedIn) { if (simklLoggedIn) {
if (currentSimklAnime.watched_episodes_count !== submitData.episodes) { if (currentSimklAnime.watched_episodes_count !== submitData.episodes) {
await SimklSyncEpisodes(currentSimklAnime, submitData.episodes).then(value => { await SimklSyncEpisodes(currentSimklAnime, submitData.episodes).then((value: SimklAnime) => {
AddAnimeServiceToTable({
id: value.show.ids.simkl,
service: "Simkl",
progress: value.watched_episodes_count,
status: value.status,
startedAt: "",
completedAt: "",
score: value.user_rating,
repeat: 0,
notes: ""
})
simklAnime.update(newValue => { simklAnime.update(newValue => {
newValue = value newValue = value
return newValue return newValue
}) })
for (const [index, tableItem] of tableItems.entries()) {
if (tableItem.service === "MyAnimeList") {
tableItems[index].id = currentSimklAnime.show.ids.simkl
tableItems[index].service = "Simkl"
tableItems[index].progress = currentSimklAnime.watched_episodes_count
tableItems[index].status = currentSimklAnime.status
tableItems[index].startedAt = ""
tableItems[index].completedAt = ""
tableItems[index].score = currentSimklAnime.user_rating
tableItems[index].repeat = 0
tableItems[index].notes = ""
}
}
}) })
} }
if (currentSimklAnime.user_rating !== submitData.rating) { if (currentSimklAnime.user_rating !== submitData.rating) {
await SimklSyncRating(currentSimklAnime, submitData.rating).then(value => { await SimklSyncRating(currentSimklAnime, submitData.rating).then(value => {
AddAnimeServiceToTable({
id: value.show.ids.simkl,
service: "Simkl",
progress: value.watched_episodes_count,
status: value.status,
startedAt: "",
completedAt: "",
score: value.user_rating,
repeat: 0,
notes: ""
})
simklAnime.update(newValue => { simklAnime.update(newValue => {
newValue = value newValue = value
return newValue return newValue
@ -251,6 +254,17 @@
if (currentSimklAnime.status !== submitData.status.simkl) { if (currentSimklAnime.status !== submitData.status.simkl) {
await SimklSyncStatus(currentSimklAnime, submitData.status.simkl).then(value => { await SimklSyncStatus(currentSimklAnime, submitData.status.simkl).then(value => {
AddAnimeServiceToTable({
id: value.show.ids.simkl,
service: "Simkl",
progress: value.watched_episodes_count,
status: value.status,
startedAt: "",
completedAt: "",
score: value.user_rating,
repeat: 0,
notes: ""
})
simklAnime.update(newValue => { simklAnime.update(newValue => {
newValue = value newValue = value
return newValue return newValue
@ -394,7 +408,7 @@
</div> </div>
</div> </div>
<AnimeTable items={tableItems}/> <AnimeTable/>
<div class="bg-white rounded-lg shadow max-w-4-4 dark:bg-gray-800"> <div class="bg-white rounded-lg shadow max-w-4-4 dark:bg-gray-800">
<div class="w-full mx-auto max-w-screen-xl p-4 md:flex md:items-center md:justify-end"> <div class="w-full mx-auto max-w-screen-xl p-4 md:flex md:items-center md:justify-end">