Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

+layout.svelte

72 lines2.2 KB

1<script lang="ts">
2 import { resolve } from '$app/paths'
3 import { navigating, page } from '$app/state'
4 import { contactsQueries } from '$lib/services/contacts/queries'
5 import { createQuery, useIsFetching } from '@tanstack/svelte-query'
6 import { createDebouncer } from '@tanstack/svelte-pacer/debouncer'
7 import type { LayoutProps } from './$types'
8​
9 let { data, children }: LayoutProps = $props()
10​
11 const contactsQuery = createQuery(() => contactsQueries.list(data.q))
12 const fetchingContacts = useIsFetching({ queryKey: contactsQueries.lists() })
13​
14 const searchDebouncer = createDebouncer(
15 (form: HTMLFormElement | null) => form?.requestSubmit(),
16 { wait: 500 },
17 )
18</script>
19​
20<div id="root">
21 <div id="sidebar">
22 <h1>SvelteKit Contacts</h1>
23 <div>
24 <form id="search-form" role="search" data-sveltekit-keepfocus>
25 <input
26 id="q"
27 aria-label="Search contacts"
28 placeholder="Search"
29 type="search"
30 name="q"
31 value={data.q}
32 class={fetchingContacts.current > 0 ? 'loading' : ''}
33 oninput={(event) =>
34 searchDebouncer.maybeExecute(event.currentTarget.form)}
35 />
36 <div
37 id="search-spinner"
38 aria-hidden="true"
39 hidden={fetchingContacts.current === 0}
40 ></div>
41 <div class="sr-only" aria-live="polite"></div>
42 </form>
43 <a href={resolve('/contacts/new')} class="button">New</a>
44 </div>
45 <nav>
46 {#if contactsQuery.data?.length}
47 <ul>
48 {#each contactsQuery.data as contact (contact.id)}
49 {@const href = resolve('/(app)/contacts/[contactId]', {
50 contactId: contact.id,
51 })}
52 <li>
53 <a {href} class={page.url.pathname === href ? 'active' : ''}>
54 {#if contact.first || contact.last}
55 {contact.first} {contact.last}
56 {:else}
57 <i>No Name</i>
58 {/if}
59 {#if contact.favorite}<span>β˜…</span>{/if}
60 </a>
61 </li>
62 {/each}
63 </ul>
64 {:else}
65 <p><i>No contacts</i></p>
66 {/if}
67 </nav>
68 </div>
69 <div id="detail" class={navigating.to ? 'loading' : ''}>
70 {@render children()}
71 </div>
72</div>