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

changes.tsx

271 lines9.0 KB

1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { createServerFn } from '@tanstack/react-start'
4​
5import {
6 CHANGE_STYLES,
7 ChangeSummary,
8 JsonPane,
9 MetaStrip,
10 ReqLine,
11 SiteFooter,
12 SiteNav,
13 ViewToggle,
14} from '#/components/site.tsx'
15import type { ResourceView } from '#/components/site.tsx'
16import { changeDiffs } from '#/lib/change-diff.ts'
17import type { ChangeDiff } from '#/lib/change-diff.ts'
18import { timeAgo } from '#/lib/time.ts'
19import type { ChangeType } from '#/db/schema.ts'
20​
21interface ChangesSearch {
22 cursor?: string
23 provider?: string
24 type?: ChangeType
26​
27/** Filter links above the table; `undefined` is every type. */
28const TYPE_FILTERS: Array<[string, ChangeType | undefined]> = [
29 ['all', undefined],
30 ['new models', 'model.added'],
31 ['removed models', 'model.removed'],
32 ['updated models', 'model.updated'],
33 ['row shape', 'catalog.shape_changed'],
35​
36interface ChangeRow {
37 id: string
38 type: string
39 providerId: string
40 subjectId: string
41 summary: string
42 createdAt: number
43 /** What a `model.updated` changed; the raw payload stays on the API. */
44 diffs: Array<ChangeDiff>
46​
47/** Diffs shown per row before the rest collapse into a count. */
48const SHOWN_DIFFS = 4
49​
50interface ChangesData {
51 count: number
52 changes: Array<ChangeRow>
53 nextCursor: string | null
55​
56const getChanges = createServerFn({ method: 'GET' })
57 .inputValidator((query: ChangesSearch) => query)
58 .handler(async ({ data }): Promise<ChangesData> => {
59 const { env } = await import('cloudflare:workers')
60 const { getDb } = await import('#/db/index.ts')
61 const { listChanges } = await import('#/server/changes-api.ts')
62 const outcome = await listChanges(getDb(env), { ...data, limit: 50 })
63 if (!outcome.ok) return { count: 0, changes: [], nextCursor: null }
64 return {
65 count: outcome.result.count,
66 nextCursor: outcome.result.nextCursor,
67 changes: outcome.result.changes.map((c) => ({
68 id: c.id,
69 type: c.type,
70 providerId: c.providerId,
71 subjectId: c.subjectId,
72 summary: c.summary,
73 createdAt: c.createdAt,
74 diffs: changeDiffs(c.payload),
75 })),
76 }
77 })
78​
79export const Route = createFileRoute('/changes')({
80 validateSearch: (search: Record<string, unknown>): ChangesSearch => ({
81 cursor:
82 typeof search.cursor === 'string' && search.cursor !== ''
83 ? search.cursor
84 : undefined,
85 provider:
86 typeof search.provider === 'string' && search.provider !== ''
87 ? search.provider
88 : undefined,
89 type: TYPE_FILTERS.find(([, type]) => type === search.type)?.[1],
90 }),
91 loaderDeps: ({ search }) => search,
92 loader: ({ deps }) => getChanges({ data: deps }),
93 component: Changes,
94})
95​
96function Changes() {
97 const data = Route.useLoaderData()
98 const search = Route.useSearch()
99 const [view, setView] = useState<ResourceView>('readable')
100​
101 const params = new URLSearchParams()
102 if (search.provider) params.set('provider', search.provider)
103 if (search.type) params.set('type', search.type)
104 if (search.cursor) params.set('cursor', search.cursor)
105 const qs = params.toString() === '' ? '' : `?${params.toString()}`
106 const apiPath = `/v1/changes${qs}`
107 const jsonBody = JSON.stringify(
108 {
109 count: data.count,
110 changes: data.changes.map(({ diffs: _diffs, ...change }) => change),
111 nextCursor: data.nextCursor,
112 },
113 null,
114 2,
115 )
116​
117 const olderParams = new URLSearchParams()
118 if (search.provider) olderParams.set('provider', search.provider)
119 if (search.type) olderParams.set('type', search.type)
120 if (data.nextCursor) olderParams.set('cursor', data.nextCursor)
121​
122 /** A filter link keeps the provider and starts again at the newest page. */
123 const typeHref = (type: ChangeType | undefined) => {
124 const filter = new URLSearchParams()
125 if (search.provider) filter.set('provider', search.provider)
126 if (type) filter.set('type', type)
127 const query = filter.toString()
128 return query === '' ? '/changes' : `/changes?${query}`
129 }
130​
131 return (
132 <div className="min-h-screen text-ink">
133 <SiteNav active="changes" />
134 <main className="mx-auto max-w-[1080px] px-6 pb-16">
135 <ReqLine
136 path={
137 <>
138 /v1/changes
139 {qs === '' ? null : <span className="text-ink-faint">{qs}</span>}
140 </>
141 }
142 copyUrl={`https://modelschemas.com${apiPath}`}
143 right={<ViewToggle view={view} onChange={setView} />}
144 />
145 <MetaStrip
146 items={[
147 ['count', String(data.count)],
148 ['order', 'newest first'],
149 ['page size', '50'],
150 ]}
151 />
152​
153 <div className="mb-2.5 flex flex-wrap gap-4 font-mono text-xs">
154 {TYPE_FILTERS.map(([label, type]) =>
155 type === search.type ? (
156 <span key={label} className="text-ink">
157 {label}
158 </span>
159 ) : (
160 <a key={label} className="press-link" href={typeHref(type)}>
161 {label}
162 </a>
163 ),
164 )}
165 </div>
166​
167 {view === 'json' ? (
168 <JsonPane
169 title="application/json · 200 OK"
170 json={jsonBody}
171 note={
172 <>
173 identical body to{' '}
174 <code>curl https://modelschemas.com{apiPath}</code>
175 </>
176 }
177 />
178 ) : (
179 <>
180 <div className="figure overflow-x-auto">
181 <table className="dtable">
182 <thead>
183 <tr>
184 <th>when</th>
185 <th>type</th>
186 <th>summary</th>
187 <th className="max-sm:hidden">provider</th>
188 </tr>
189 </thead>
190 <tbody>
191 {data.changes.length === 0 ? (
192 <tr>
193 <td colSpan={4} className="text-ink-faint">
194 {search.type || search.provider
195 ? 'no changes match this filter.'
196 : 'no changes yet — the next cron poll will populate this feed.'}
197 </td>
198 </tr>
199 ) : (
200 data.changes.map((change) => (
201 <tr key={change.id}>
202 <td className="font-mono text-xs whitespace-nowrap text-ink-faint">
203 {timeAgo(change.createdAt)}
204 </td>
205 <td
206 className={`font-mono text-xs whitespace-nowrap ${CHANGE_STYLES[change.type] ?? 'text-ink-soft'}`}
207 >
208 {change.type}
209 </td>
210 <td className="max-w-[38em]">
211 <div className="truncate">
212 <ChangeSummary change={change} />
213 </div>
214 {change.diffs.slice(0, SHOWN_DIFFS).map((diff) => (
215 <div
216 key={diff.path}
217 className="truncate font-mono text-xs text-ink-faint"
218 >
219 {diff.path}{' '}
220 <span className="text-tok-red">
221 {diff.before}
222 </span>
223 {' → '}
224 <span className="text-tok-green">
225 {diff.after}
226 </span>
227 </div>
228 ))}
229 {change.diffs.length > SHOWN_DIFFS ? (
230 <div className="font-mono text-xs text-ink-faint">
231 +{change.diffs.length - SHOWN_DIFFS} more
232 </div>
233 ) : null}
234 </td>
235 <td className="font-mono text-xs text-ink-faint max-sm:hidden">
236 <a
237 className="press-link"
238 href={`/changes?provider=${change.providerId}`}
239 >
240 {change.providerId}
241 </a>
242 </td>
243 </tr>
244 ))
245 )}
246 </tbody>
247 </table>
248 </div>
249 <div className="mt-2.5 flex flex-wrap gap-4 font-mono text-xs">
250 {data.nextCursor === null ? null : (
251 <a
252 className="press-link"
253 href={`/changes?${olderParams.toString()}`}
254 >
255 older →
256 </a>
257 )}
258 <span className="ml-auto text-ink-faint">
259 webhook push:{' '}
260 <a className="press-link" href="/docs">
261 POST /v1/subscriptions
262 </a>
263 </span>
264 </div>
265 </>
266 )}
267 </main>
268 <SiteFooter />
269 </div>
270 )