@openrails/contentkit-ui 0.98.6 → 0.99.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/dist/client/content/comments.d.ts +4 -2
- package/dist/client/content/comments.js +10 -6
- package/dist/client/content/comments.js.map +1 -1
- package/dist/client/generated/routes.d.ts +28 -2
- package/dist/client/generated/routes.js +39 -2
- package/dist/client/generated/routes.js.map +1 -1
- package/dist/client/generated/wire.d.ts +85 -0
- package/dist/client/generated/wire.js.map +1 -1
- package/dist/client/media/client.d.ts +4 -0
- package/dist/client/media/client.js +8 -4
- package/dist/client/media/client.js.map +1 -1
- package/dist/client/media/queue.js +42 -26
- package/dist/client/media/queue.js.map +1 -1
- package/dist/client/media/rules.d.ts +6 -0
- package/dist/client/media/rules.js +64 -10
- package/dist/client/media/rules.js.map +1 -1
- package/dist/client/versions.d.ts +6 -2
- package/dist/client/versions.js +26 -0
- package/dist/client/versions.js.map +1 -1
- package/dist/components/admin/page-review.d.ts +13 -0
- package/dist/components/admin/page-review.js +216 -0
- package/dist/components/admin/page-review.js.map +1 -0
- package/dist/components/content/card.js +98 -103
- package/dist/components/content/card.js.map +1 -1
- package/dist/components/content/daily-releases.d.ts +8 -1
- package/dist/components/content/daily-releases.js +291 -133
- package/dist/components/content/daily-releases.js.map +1 -1
- package/dist/components/content/editors.js +216 -210
- package/dist/components/content/editors.js.map +1 -1
- package/dist/components/content/filter-dialog.d.ts +11 -0
- package/dist/components/content/filter-dialog.js +29 -0
- package/dist/components/content/filter-dialog.js.map +1 -0
- package/dist/components/content/filters.d.ts +10 -0
- package/dist/components/content/filters.js +5 -2
- package/dist/components/content/filters.js.map +1 -1
- package/dist/components/content/grid.js +19 -14
- package/dist/components/content/grid.js.map +1 -1
- package/dist/components/content/index.d.ts +2 -1
- package/dist/components/content/release-reveal.d.ts +5 -0
- package/dist/components/content/release-reveal.js +62 -0
- package/dist/components/content/release-reveal.js.map +1 -0
- package/dist/components/social/comments.d.ts +1 -1
- package/dist/components/social/comments.js +15 -15
- package/dist/components/social/comments.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +24 -22
- package/dist/locales/admin/de.js +23 -0
- package/dist/locales/admin/de.js.map +1 -1
- package/dist/locales/admin/en.d.ts +23 -0
- package/dist/locales/admin/en.js +23 -0
- package/dist/locales/admin/en.js.map +1 -1
- package/dist/locales/admin/es.js +23 -0
- package/dist/locales/admin/es.js.map +1 -1
- package/dist/locales/admin/ja.js +23 -0
- package/dist/locales/admin/ja.js.map +1 -1
- package/dist/locales/admin/ko.js +23 -0
- package/dist/locales/admin/ko.js.map +1 -1
- package/dist/locales/admin/zh.js +23 -0
- package/dist/locales/admin/zh.js.map +1 -1
- package/dist/locales/discovery/de.js +11 -0
- package/dist/locales/discovery/de.js.map +1 -1
- package/dist/locales/discovery/en.d.ts +11 -0
- package/dist/locales/discovery/en.js +11 -0
- package/dist/locales/discovery/en.js.map +1 -1
- package/dist/locales/discovery/es.js +11 -0
- package/dist/locales/discovery/es.js.map +1 -1
- package/dist/locales/discovery/ja.js +11 -0
- package/dist/locales/discovery/ja.js.map +1 -1
- package/dist/locales/discovery/ko.js +11 -0
- package/dist/locales/discovery/ko.js.map +1 -1
- package/dist/locales/discovery/zh.js +11 -0
- package/dist/locales/discovery/zh.js.map +1 -1
- package/dist/locales/en.d.ts +34 -0
- package/dist/locales/social/en.js +2 -2
- package/dist/locales/social/en.js.map +1 -1
- package/dist/react/comments.d.ts +2 -1
- package/dist/react/comments.js +10 -8
- package/dist/react/comments.js.map +1 -1
- package/dist/react/folder.js +39 -39
- package/dist/react/folder.js.map +1 -1
- package/dist/react/index.d.ts +1 -0
- package/dist/react/page-review.d.ts +14 -0
- package/dist/react/page-review.js +36 -0
- package/dist/react/page-review.js.map +1 -0
- package/dist/react/public.d.ts +3 -1
- package/dist/react/public.js +76 -72
- package/dist/react/public.js.map +1 -1
- package/dist/react/resources.d.ts +5 -13
- package/dist/react/resources.js +58 -49
- package/dist/react/resources.js.map +1 -1
- package/dist/react/use-resource.d.ts +1 -1
- package/dist/react/use-resource.js +23 -13
- package/dist/react/use-resource.js.map +1 -1
- package/dist/react/versions.js +70 -42
- package/dist/react/versions.js.map +1 -1
- package/dist/react.js +8 -7
- package/dist/styles.css +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.js","names":[],"sources":["../../src/react/resources.ts"],"sourcesContent":["import type { ContentKitClient } from \"../client/client.js\";\nimport { toContentKitError, type ContentKitError } from \"../client/errors.js\";\nimport { sameTarget, type Target } from \"../client/content/types.js\";\nimport type { Card, Comment, Content, Item, Poll } from \"../client/generated/wire.js\";\nimport type { ContentKitChange } from \"../client/http.js\";\n\n/** One shared read: its data, whether a fetch is in flight, and its last failure. */\nexport interface Resource<T> {\n data: T | undefined;\n loading: boolean;\n /** A fetch or set has completed. */\n loaded: boolean;\n /** A list's next page is in flight. */\n loadingMore?: boolean;\n error?: ContentKitError;\n}\n\n/** A page of a list and how to get the next one (null: no more). */\nexport interface Page<T> {\n items: T[];\n next: string | number | null;\n}\n\nexport type Fetcher<T> = (signal: AbortSignal) => Promise<T>;\n\n/** What a slot holds, for matching changes: its resource type and the ids it depends on. */\nexport interface Tag {\n type: string;\n readScope?: string;\n target?: Target;\n id?: string;\n scope?: string;\n}\n\ninterface Slot {\n tag: Tag;\n listeners: Set<() => void>;\n entry: Resource<unknown>;\n fetcher?: Fetcher<unknown>;\n more?: (cursor: string | number, signal: AbortSignal) => Promise<Page<unknown>>;\n ctl?: AbortController;\n moreCtl?: AbortController;\n /** Bumped by mark(): an optimistic write rolls back only if no newer one started. */\n version: number;\n /** Identifies the full read; item patches and appended pages retain it. */\n readVersion: number;\n}\n\nconst IDLE: Resource<never> = { data: undefined, loading: false, loaded: false };\n\n/**\n * The content reads hooks share, per client: one request per key while any\n * hook shows it, optimistic writes with rollback, and every change the client\n * makes applied in place (or refetched) for every hook showing it.\n */\nexport class ResourceStore {\n private readonly slots = new Map<string, Slot>();\n // Tokens must remain unique when a scope leaves and its slots are recreated.\n private version = 0;\n\n constructor(client: ContentKitClient) {\n client.subscribe((c, scope) => this.apply(c, scope));\n }\n\n subscribe(key: string, tag: Tag, listener: () => void): () => void {\n let s = this.slots.get(key);\n if (!s) this.slots.set(key, (s = { tag, listeners: new Set(), entry: IDLE, version: 0, readVersion: ++this.version }));\n const slot = s;\n slot.listeners.add(listener);\n return () => {\n slot.listeners.delete(listener);\n // Kept across a StrictMode remount; dropped once no hook shows it.\n queueMicrotask(() => {\n if (slot.listeners.size || this.slots.get(key) !== slot) return;\n slot.ctl?.abort();\n slot.moreCtl?.abort();\n this.slots.delete(key);\n });\n };\n }\n\n snapshot<T>(key: string): Resource<T> {\n return (this.slots.get(key)?.entry ?? IDLE) as Resource<T>;\n }\n\n /** The latest fetchers of a key: its first read, and a list's next page. */\n bind(key: string, fetcher: Fetcher<unknown>, more?: Slot[\"more\"]): void {\n const s = this.slots.get(key);\n if (s) Object.assign(s, { fetcher, more });\n }\n\n /** Fetches unless loaded or in flight; force refetches (a list from its first page). */\n load(key: string, force = false): void {\n const s = this.slots.get(key);\n if (!s?.fetcher || (!force && (s.entry.loaded || s.ctl))) return;\n s.ctl?.abort();\n s.moreCtl?.abort();\n s.moreCtl = undefined;\n const ctl = (s.ctl = new AbortController());\n this.update(s, { loading: true, loadingMore: false, error: undefined });\n s.fetcher(ctl.signal).then(\n (data) => {\n if (s.ctl !== ctl) return;\n s.ctl = undefined;\n s.readVersion = ++this.version;\n this.update(s, { data, loading: false, loaded: true, error: undefined });\n },\n (e) => {\n if (s.ctl !== ctl) return;\n s.ctl = undefined;\n const error = toContentKitError(e);\n if (error.code !== \"aborted\") this.update(s, { loading: false, loaded: true, error });\n },\n );\n }\n\n /** Appends a list's next page; resolves once it landed. */\n async loadMore(key: string): Promise<void> {\n const s = this.slots.get(key);\n const page = s?.entry.data as Page<{ id: string }> | undefined;\n if (!s?.more || !page || page.next === null || s.moreCtl || s.ctl) return;\n const ctl = (s.moreCtl = new AbortController());\n this.update(s, { loadingMore: true });\n try {\n const next = (await s.more(page.next, ctl.signal)) as Page<{ id: string }>;\n if (s.moreCtl !== ctl) return;\n const cur = s.entry.data as Page<{ id: string }>;\n const seen = new Set(cur.items.map((x) => x.id));\n this.update(s, { data: { items: [...cur.items, ...next.items.filter((x) => !seen.has(x.id))], next: next.next }, error: undefined });\n } catch (e) {\n const error = toContentKitError(e);\n if (s.moreCtl === ctl && error.code !== \"aborted\") this.update(s, { error });\n } finally {\n if (s.moreCtl === ctl) {\n s.moreCtl = undefined;\n this.update(s, { loadingMore: false });\n }\n }\n }\n\n /** Replaces a key's data for every hook showing it. */\n set<T>(key: string, data: T | ((prev: T | undefined) => T)): void {\n const s = this.slots.get(key);\n if (!s) return;\n const next = typeof data === \"function\" ? (data as (p: T | undefined) => T)(s.entry.data as T | undefined) : data;\n s.readVersion = ++this.version;\n this.update(s, { data: next, loaded: true, error: undefined });\n }\n\n /** Starts an optimistic write on key: the token rollback() checks. */\n mark(key: string): number {\n const s = this.slots.get(key);\n return s ? (s.version = ++this.version) : 0;\n }\n\n /** Restores data unless a newer optimistic write started since mark(). */\n rollback<T>(key: string, token: number, data: T): void {\n const s = this.slots.get(key);\n if (s && s.version === token) this.update(s, { data, loaded: true });\n }\n\n /** Applies fn to matching slots, with the read identity for scoped rollback. */\n patch<T>(match: (tag: Tag) => boolean, fn: (data: T, readVersion: number) => T): void {\n for (const s of this.slots.values()) {\n if (s.entry.data !== undefined && match(s.tag)) this.update(s, { data: fn(s.entry.data as T, s.readVersion) });\n }\n }\n\n /** Refetches every shown slot whose tag matches. */\n invalidate(match: (tag: Tag) => boolean): void {\n for (const [key, s] of this.slots) if (match(s.tag) && s.listeners.size) this.load(key, true);\n }\n\n private apply(c: ContentKitChange, scope: string | null): void {\n const patch = <T>(match: (tag: Tag) => boolean, fn: (data: T) => T) => {\n this.patch<T>((t) => match(t) && (t.readScope ?? \"{}\") === scope, fn);\n this.invalidate((t) => match(t) && (t.readScope ?? \"{}\") !== scope);\n };\n const items = <T extends { id: string }>(types: string[], fn: (item: T) => T | null) =>\n patch<Page<T>>(\n (t) => types.includes(t.type),\n (page) => {\n let changed = false;\n const out: T[] = [];\n for (const it of page.items) {\n const next = fn(it);\n if (next !== it) changed = true;\n if (next) out.push(next);\n }\n return changed ? { ...page, items: out } : page;\n },\n );\n const comments = [\"comments\", \"replies\", \"latest\", \"admin-comments\"];\n // Cards in lists (pages) and rails (arrays) show a content's counts and the viewer's state.\n const cards = (id: string, fn: (card: Card) => Card) =>\n patch<Page<Card> | Card[]>(\n (t) => t.type === \"cards\" || t.type === \"history\",\n (data) => {\n const each = (list: Card[]) => (list.some((x) => x.id === id) ? list.map((x) => (x.id === id ? fn(x) : x)) : list);\n if (Array.isArray(data)) return each(data);\n const items = each(data.items);\n return items === data.items ? data : { ...data, items };\n },\n );\n switch (c.type) {\n case \"notifications.updated\":\n this.updateNotification(c.item, scope);\n break;\n case \"notifications.changed\":\n this.invalidate((t) => t.type === \"notifications\");\n break;\n case \"comment.created\": {\n const parent = c.comment.reply_to_id;\n const published = !c.comment.moderation;\n const add = (t: Tag) => (parent ? t.type === \"replies\" && t.id === parent : t.type === \"comments\" && sameTarget(t.target, c.target));\n patch<Page<Comment>>(add, (p) => (p.items.some((x) => x.id === c.comment.id) ? p : { ...p, items: parent ? [...p.items, c.comment] : [c.comment, ...p.items] }));\n if (parent && published) items<Comment>([\"comments\"], (x) => (x.id === parent ? { ...x, reply_count: x.reply_count + 1 } : x));\n this.invalidate((t) => t.type === \"latest\" || t.type === \"admin-comments\");\n break;\n }\n case \"comment.updated\":\n items<Comment>(comments, (x) => (x.id === c.comment.id ? { ...x, ...c.comment, author: c.comment.author ?? x.author } : x));\n break;\n case \"comment.reacted\":\n items<Comment>(comments, (x) => (x.id === c.id ? { ...x, ...c.counts } : x));\n break;\n case \"comment.deleted\": {\n let parent: string | undefined;\n items<Comment>([\"comments\", \"replies\"], (x) => {\n if (x.id !== c.id || x.deleted) return x;\n if (!x.moderation) parent = x.reply_to_id;\n return { ...x, deleted: true, body: \"[deleted]\", author: undefined, user_id: undefined, anon_name: undefined };\n });\n if (parent) items<Comment>([\"comments\"], (x) => (x.id === parent ? { ...x, reply_count: Math.max(0, x.reply_count - 1) } : x));\n items<Comment>([\"latest\"], (x) => (x.id === c.id ? null : x));\n items<Comment & { deleted_at?: string }>([\"admin-comments\"], (x) => (x.id === c.id ? { ...x, deleted: true, deleted_at: new Date().toISOString() } : x));\n break;\n }\n case \"comment.restored\":\n this.invalidate((t) => comments.includes(t.type));\n break;\n case \"reaction.changed\":\n patch((t) => t.type === \"reaction\" && sameTarget(t.target, c.target), () => c.counts);\n if (c.target.type === \"contents\") {\n cards(c.target.id, (x) => ({ ...x, counts: { ...x.counts, likes: c.counts.likes, dislikes: c.counts.dislikes } }));\n this.invalidate((t) => t.type === \"daily-releases\");\n }\n this.invalidate((t) => t.type === \"reactions\");\n break;\n case \"favorite.changed\":\n patch((t) => t.type === \"favorite\" && sameTarget(t.target, c.target), () => ({ favorited: c.favorited, count: c.count }));\n if (c.target.type === \"contents\") {\n cards(c.target.id, (x) => ({ ...x, counts: { ...x.counts, favorites: c.count }, viewer: x.viewer && { ...x.viewer, favorited: c.favorited } }));\n this.invalidate((t) => t.type === \"daily-releases\");\n }\n this.invalidate((t) => t.type === \"favorites\");\n break;\n case \"content.saved\":\n patch<Content | null>((t) => t.type === \"content\" && t.id === c.content.id, () => c.content);\n // A state, kind or text change can move it between lists: refetch them.\n this.invalidate((t) => t.type === \"contents\" || t.type === \"cards\" || t.type === \"daily-releases\" || (t.type === \"content-detail\" && t.id === c.content.id));\n break;\n case \"content.changed\":\n this.invalidate((t) => ((t.type === \"content\" || t.type === \"content-detail\") && t.id === c.id) || t.type === \"contents\" || t.type === \"cards\" || t.type === \"daily-releases\");\n break;\n case \"content.deleted\":\n items<{ id: string }>([\"contents\", \"cards\", \"history\"], (x) => (x.id === c.id ? null : x));\n this.invalidate((t) => ((t.type === \"content\" || t.type === \"content-detail\") && t.id === c.id) || (t.type === \"contents\" && t.scope === \"deleted\") || t.type === \"daily-releases\");\n break;\n case \"poll.created\":\n this.invalidate((t) => t.type === \"polls\" || (t.type === \"poll\" && !t.id));\n break;\n case \"poll.updated\":\n // A latest-poll slot has no id in its tag: match by the poll it holds.\n patch<Poll | null>((t) => t.type === \"poll\", (p) => (p?.id === c.poll.id ? c.poll : p));\n items<Poll>([\"polls\"], (x) => (x.id === c.poll.id ? c.poll : x));\n break;\n case \"poll.changed\":\n this.invalidate((t) => (t.type === \"poll\" && (t.id === c.id || !t.id)) || t.type === \"polls\");\n break;\n case \"poll.deleted\":\n items<Poll>([\"polls\"], (x) => (x.id === c.id ? null : x));\n this.invalidate((t) => t.type === \"poll\" && !t.id);\n break;\n case \"ban.saved\":\n case \"ban.lifted\":\n this.invalidate((t) => (t.type === \"bans\" && t.scope === c.scope) || t.type === \"standing\");\n break;\n case \"entities.changed\":\n this.invalidate((t) => t.type.startsWith(\"group\") || t.type === \"daily-releases\");\n break;\n case \"contentFilters.changed\":\n this.invalidate((t) => t.type === \"cards\" || t.type === \"history\" || t.type === \"release-dates\" || t.type === \"daily-releases\");\n break;\n case \"access.changed\":\n this.invalidate((t) => t.type === \"cards\" || t.type === \"history\" || t.type === \"content-detail\" || t.type === \"reader-plan\" || t.type.startsWith(\"group\") || t.type === \"daily-releases\");\n break;\n case \"history.changed\":\n this.invalidate((t) => t.type === \"history\" || t.type === \"cards\" || t.type === \"daily-releases\");\n break;\n case \"searches.changed\":\n this.invalidate((t) => t.type === \"searches\");\n break;\n case \"rules.changed\":\n this.invalidate((t) => t.type === \"moderation-rules\" && t.scope === c.rules);\n break;\n case \"reader.changed\":\n this.invalidate((t) => t.type === \"reader-plan\" && t.id === c.version);\n break;\n case \"moderation.resolved\":\n items<{ id: string }>([\"held\"], (x) => (x.id === c.id ? null : x));\n if (c.kind === \"comment\") this.invalidate((t) => comments.includes(t.type));\n else this.invalidate((t) => (t.type === \"content\" && t.id === c.id) || t.type === \"contents\");\n break;\n }\n }\n\n // Preserve loaded pages and canonical receipt revisions. Reads that started\n // before a successful mutation cannot overwrite it when they finish later.\n private updateNotification(item: Item, scope: string | null): void {\n for (const [key, slot] of this.slots) {\n if (slot.tag.type !== \"notifications\" || !slot.listeners.size) continue;\n const page = slot.entry.data as Page<Item> | undefined;\n const cached = page?.items.find((n) => n.id === item.id);\n // Mutations from separate mounted views can complete out of order.\n // In particular, an old active receipt must not evict a newer archive.\n if ((slot.tag.readScope ?? \"{}\") === scope && cached && cached.revision > item.revision) continue;\n const archived = slot.tag.scope?.startsWith(\"archived:\") ?? false;\n const matches = archived === !!item.dismissed_at;\n if ((slot.tag.readScope ?? \"{}\") !== scope || !page || slot.tag.scope?.endsWith(\":unread\") || (matches && !page.items.some((n) => n.id === item.id))) {\n this.load(key, true);\n continue;\n }\n if (!matches && !page.items.some((n) => n.id === item.id)) continue;\n slot.ctl?.abort();\n slot.moreCtl?.abort();\n slot.ctl = slot.moreCtl = undefined;\n this.update(slot, { loading: false, loadingMore: false, data: { ...page, items: page.items.flatMap((n) => n.id === item.id ? matches ? [item] : [] : [n]) } });\n }\n }\n\n // A new entry per change: useSyncExternalStore compares snapshots by identity.\n private update(s: Slot, patch: Partial<Resource<unknown>>): void {\n s.entry = { ...s.entry, ...patch };\n for (const l of s.listeners) l();\n }\n}\n\nconst stores = new WeakMap<ContentKitClient, ResourceStore>();\n\n/** The client's shared content store. */\nexport function resourcesFor(client: ContentKitClient): ResourceStore {\n let s = stores.get(client);\n if (!s) stores.set(client, (s = new ResourceStore(client)));\n return s;\n}\n"],"mappings":";;;AAgDA,IAAM,IAAwB;CAAE,MAAM,KAAA;CAAW,SAAS;CAAO,QAAQ;AAAM,GAOlE,IAAb,MAA2B;CACzB,wBAAyB,IAAI,IAAkB;CAE/C,UAAkB;CAElB,YAAY,GAA0B;EACpC,EAAO,WAAW,GAAG,MAAU,KAAK,MAAM,G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M;IAAE,SAAS;IAAO,aAAa;IAAO,MAAM;KAAE,GAAG;KAAM,OAAO,EAAK,MAAM,SAAS,MAAM,EAAE,OAAO,EAAK,KAAK,IAAU,CAAC,CAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAAE;GAAE,CAAC;EAC/J;CACF;CAGA,OAAe,GAAS,GAAyC;EAC/D,EAAE,QAAQ;GAAE,GAAG,EAAE;GAAO,GAAG;EAAM;EACjC,KAAK,IAAM,KAAK,EAAE,WAAW,EAAE;CACjC;AACF,GAEM,oBAAS,IAAI,QAAyC;AAG5D,SAAgB,EAAa,GAAyC;CACpE,IAAI,IAAI,EAAO,IAAI,CAAM;CAEzB,OADK,KAAG,EAAO,IAAI,GAAS,IAAI,IAAI,EAAc,CAAM,CAAE,GACnD;AACT"}
|
|
1
|
+
{"version":3,"file":"resources.js","names":[],"sources":["../../src/react/resources.ts"],"sourcesContent":["import type { ContentKitClient } from \"../client/client.js\";\nimport { toContentKitError, type ContentKitError } from \"../client/errors.js\";\nimport { sameTarget, type Target } from \"../client/content/types.js\";\nimport type { Card, Comment, Content, Item, Poll } from \"../client/generated/wire.js\";\nimport type { ContentKitChange } from \"../client/http.js\";\n\n/** One shared read: its data, whether a fetch is in flight, and its last failure. */\nexport interface Resource<T> {\n data: T | undefined;\n loading: boolean;\n /** A fetch or set has completed. */\n loaded: boolean;\n /** A list's next page is in flight. */\n loadingMore?: boolean;\n error?: ContentKitError;\n}\n\n/** A page of a list and how to get the next one (null: no more). */\nexport interface Page<T> {\n items: T[];\n next: string | number | null;\n}\n\nexport type Fetcher<T> = (signal: AbortSignal) => Promise<T>;\n\n/** What a slot holds, for matching changes: its resource type and the ids it depends on. */\nexport interface Tag {\n type: string;\n readScope?: string;\n target?: Target;\n language?: string;\n id?: string;\n scope?: string;\n}\n\ninterface Slot {\n tag: Tag;\n listeners: Set<() => void>;\n entry: Resource<unknown>;\n bindings: Map<symbol, Binding>;\n ctl?: AbortController;\n moreCtl?: AbortController;\n /** Bumped by mark(): an optimistic write rolls back only if no newer one started. */\n version: number;\n /** Identifies the full read; item patches and appended pages retain it. */\n readVersion: number;\n}\n\ninterface Binding {\n fetcher: Fetcher<unknown>;\n more?: (cursor: string | number, signal: AbortSignal) => Promise<Page<unknown>>;\n}\n\nconst activeBinding = (s: Slot) => [...s.bindings.values()].at(-1);\n\nconst IDLE: Resource<never> = { data: undefined, loading: false, loaded: false };\n\n/**\n * The content reads hooks share, per client: one request per key while any\n * hook shows it, optimistic writes with rollback, and every change the client\n * makes applied in place (or refetched) for every hook showing it.\n */\nexport class ResourceStore {\n private readonly slots = new Map<string, Slot>();\n // Tokens must remain unique when a scope leaves and its slots are recreated.\n private version = 0;\n\n constructor(client: ContentKitClient) {\n client.subscribe((c, scope) => this.apply(c, scope));\n }\n\n subscribe(key: string, tag: Tag, listener: () => void): () => void {\n let s = this.slots.get(key);\n if (!s) this.slots.set(key, (s = { tag, listeners: new Set(), bindings: new Map(), entry: IDLE, version: 0, readVersion: ++this.version }));\n const slot = s;\n slot.listeners.add(listener);\n return () => {\n slot.listeners.delete(listener);\n // Kept across a StrictMode remount; dropped once no hook shows it.\n queueMicrotask(() => {\n if (slot.listeners.size || this.slots.get(key) !== slot) return;\n slot.ctl?.abort();\n slot.moreCtl?.abort();\n this.slots.delete(key);\n });\n };\n }\n\n snapshot<T>(key: string): Resource<T> {\n return (this.slots.get(key)?.entry ?? IDLE) as Resource<T>;\n }\n\n /** Registers one subscriber's key-bound fetchers; cleanup releases only it. */\n bind(key: string, fetcher: Fetcher<unknown>, more?: Binding[\"more\"]): () => void {\n const s = this.slots.get(key);\n if (!s) return () => {};\n const owner = Symbol();\n s.bindings.set(owner, { fetcher, more });\n return () => { s.bindings.delete(owner); };\n }\n\n /** Fetches unless loaded or in flight; force refetches (a list from its first page). */\n load(key: string, force = false): void {\n const s = this.slots.get(key);\n const binding = s && activeBinding(s);\n if (!s || !binding || (!force && (s.entry.loaded || s.ctl))) return;\n s.ctl?.abort();\n s.moreCtl?.abort();\n s.moreCtl = undefined;\n const ctl = (s.ctl = new AbortController());\n this.update(s, { loading: true, loadingMore: false, error: undefined });\n binding.fetcher(ctl.signal).then(\n (data) => {\n if (s.ctl !== ctl) return;\n s.ctl = undefined;\n s.readVersion = ++this.version;\n this.update(s, { data, loading: false, loaded: true, error: undefined });\n },\n (e) => {\n if (s.ctl !== ctl) return;\n s.ctl = undefined;\n const error = toContentKitError(e);\n if (error.code !== \"aborted\") this.update(s, { loading: false, loaded: true, error });\n },\n );\n }\n\n /** Appends a list's next page; resolves once it landed. */\n async loadMore(key: string): Promise<void> {\n const s = this.slots.get(key);\n const binding = s && activeBinding(s);\n const page = s?.entry.data as Page<{ id: string }> | undefined;\n if (!s || !binding?.more || !page || page.next === null || s.moreCtl || s.ctl) return;\n const ctl = (s.moreCtl = new AbortController());\n this.update(s, { loadingMore: true });\n try {\n const next = (await binding.more(page.next, ctl.signal)) as Page<{ id: string }>;\n if (s.moreCtl !== ctl) return;\n const cur = s.entry.data as Page<{ id: string }>;\n const seen = new Set(cur.items.map((x) => x.id));\n this.update(s, { data: { items: [...cur.items, ...next.items.filter((x) => !seen.has(x.id))], next: next.next }, error: undefined });\n } catch (e) {\n const error = toContentKitError(e);\n if (s.moreCtl === ctl && error.code !== \"aborted\") this.update(s, { error });\n } finally {\n if (s.moreCtl === ctl) {\n s.moreCtl = undefined;\n this.update(s, { loadingMore: false });\n }\n }\n }\n\n /** Replaces a key's data for every hook showing it. */\n set<T>(key: string, data: T | ((prev: T | undefined) => T)): void {\n const s = this.slots.get(key);\n if (!s) return;\n const next = typeof data === \"function\" ? (data as (p: T | undefined) => T)(s.entry.data as T | undefined) : data;\n s.readVersion = ++this.version;\n this.update(s, { data: next, loaded: true, error: undefined });\n }\n\n /** Starts an optimistic write on key: the token rollback() checks. */\n mark(key: string): number {\n const s = this.slots.get(key);\n return s ? (s.version = ++this.version) : 0;\n }\n\n /** Restores data unless a newer optimistic write started since mark(). */\n rollback<T>(key: string, token: number, data: T): void {\n const s = this.slots.get(key);\n if (s && s.version === token) this.update(s, { data, loaded: true });\n }\n\n /** Applies fn to matching slots, with the read identity for scoped rollback. */\n patch<T>(match: (tag: Tag) => boolean, fn: (data: T, readVersion: number) => T): void {\n for (const s of this.slots.values()) {\n if (s.entry.data !== undefined && match(s.tag)) this.update(s, { data: fn(s.entry.data as T, s.readVersion) });\n }\n }\n\n /** Refetches every shown slot whose tag matches. */\n invalidate(match: (tag: Tag) => boolean): void {\n for (const [key, s] of this.slots) if (match(s.tag) && s.listeners.size) this.load(key, true);\n }\n\n private apply(c: ContentKitChange, scope: string | null): void {\n const patch = <T>(match: (tag: Tag) => boolean, fn: (data: T) => T) => {\n this.patch<T>((t) => match(t) && (t.readScope ?? \"{}\") === scope, fn);\n this.invalidate((t) => match(t) && (t.readScope ?? \"{}\") !== scope);\n };\n const items = <T extends { id: string }>(types: string[], fn: (item: T) => T | null) =>\n patch<Page<T>>(\n (t) => types.includes(t.type),\n (page) => {\n let changed = false;\n const out: T[] = [];\n for (const it of page.items) {\n const next = fn(it);\n if (next !== it) changed = true;\n if (next) out.push(next);\n }\n return changed ? { ...page, items: out } : page;\n },\n );\n const comments = [\"comments\", \"replies\", \"latest\", \"admin-comments\"];\n // Cards in lists (pages) and rails (arrays) show a content's counts and the viewer's state.\n const cards = (id: string, fn: (card: Card) => Card) =>\n patch<Page<Card> | Card[]>(\n (t) => t.type === \"cards\" || t.type === \"history\",\n (data) => {\n const each = (list: Card[]) => (list.some((x) => x.id === id) ? list.map((x) => (x.id === id ? fn(x) : x)) : list);\n if (Array.isArray(data)) return each(data);\n const items = each(data.items);\n return items === data.items ? data : { ...data, items };\n },\n );\n switch (c.type) {\n case \"media.committed\":\n case \"media.processed\":\n this.invalidate((t) => t.type === \"page-review\" && t.id === c.ref.version);\n break;\n case \"notifications.updated\":\n this.updateNotification(c.item, scope);\n break;\n case \"notifications.changed\":\n this.invalidate((t) => t.type === \"notifications\");\n break;\n case \"comment.created\": {\n const parent = c.comment.reply_to_id;\n const published = !c.comment.moderation;\n const thread = (t: Tag) => sameTarget(t.target, c.target) && (!t.language || t.language === c.comment.language);\n const add = (t: Tag) => (parent ? t.type === \"replies\" && t.id === parent : t.type === \"comments\" && thread(t));\n patch<Page<Comment>>(add, (p) => (p.items.some((x) => x.id === c.comment.id) ? p : { ...p, items: parent ? [...p.items, c.comment] : [c.comment, ...p.items] }));\n if (parent && published) items<Comment>([\"comments\"], (x) => (x.id === parent ? { ...x, reply_count: x.reply_count + 1 } : x));\n this.invalidate((t) => t.type === \"latest\" || t.type === \"admin-comments\");\n if (!parent) this.invalidate((t) => t.type === \"standing\" && thread(t));\n break;\n }\n case \"comment.updated\":\n items<Comment>(comments, (x) => (x.id === c.comment.id ? { ...x, ...c.comment, author: c.comment.author ?? x.author } : x));\n this.invalidate((t) => t.type === \"standing\");\n break;\n case \"comment.reacted\":\n items<Comment>(comments, (x) => (x.id === c.id ? { ...x, ...c.counts } : x));\n break;\n case \"comment.deleted\": {\n let parent: string | undefined;\n items<Comment>([\"comments\", \"replies\"], (x) => {\n if (x.id !== c.id || x.deleted) return x;\n if (!x.moderation) parent = x.reply_to_id;\n return { ...x, deleted: true, body: \"[deleted]\", author: undefined, user_id: undefined, anon_name: undefined };\n });\n if (parent) items<Comment>([\"comments\"], (x) => (x.id === parent ? { ...x, reply_count: Math.max(0, x.reply_count - 1) } : x));\n items<Comment>([\"latest\"], (x) => (x.id === c.id ? null : x));\n items<Comment & { deleted_at?: string }>([\"admin-comments\"], (x) => (x.id === c.id ? { ...x, deleted: true, deleted_at: new Date().toISOString() } : x));\n this.invalidate((t) => t.type === \"standing\");\n break;\n }\n case \"comment.restored\":\n this.invalidate((t) => comments.includes(t.type) || t.type === \"standing\");\n break;\n case \"reaction.changed\":\n patch((t) => t.type === \"reaction\" && sameTarget(t.target, c.target), () => c.counts);\n if (c.target.type === \"contents\") {\n cards(c.target.id, (x) => ({ ...x, counts: { ...x.counts, likes: c.counts.likes, dislikes: c.counts.dislikes } }));\n this.invalidate((t) => t.type === \"daily-releases\");\n }\n this.invalidate((t) => t.type === \"reactions\");\n break;\n case \"favorite.changed\":\n patch((t) => t.type === \"favorite\" && sameTarget(t.target, c.target), () => ({ favorited: c.favorited, count: c.count }));\n if (c.target.type === \"contents\") {\n cards(c.target.id, (x) => ({ ...x, counts: { ...x.counts, favorites: c.count }, viewer: x.viewer && { ...x.viewer, favorited: c.favorited } }));\n this.invalidate((t) => t.type === \"daily-releases\");\n }\n this.invalidate((t) => t.type === \"favorites\");\n break;\n case \"content.saved\":\n patch<Content | null>((t) => t.type === \"content\" && t.id === c.content.id, () => c.content);\n // A state, kind or text change can move it between lists: refetch them.\n this.invalidate((t) => t.type === \"contents\" || t.type === \"cards\" || t.type === \"daily-releases\" || (t.type === \"content-detail\" && t.id === c.content.id));\n this.invalidate((t) => t.type === \"standing\" && t.target?.type === \"contents\" && t.target.id === c.content.id);\n break;\n case \"content.changed\":\n this.invalidate((t) => ((t.type === \"content\" || t.type === \"content-detail\") && t.id === c.id) || t.type === \"contents\" || t.type === \"cards\" || t.type === \"daily-releases\");\n this.invalidate((t) => t.type === \"standing\" && t.target?.type === \"contents\" && t.target.id === c.id);\n break;\n case \"content.deleted\":\n items<{ id: string }>([\"contents\", \"cards\", \"history\"], (x) => (x.id === c.id ? null : x));\n this.invalidate((t) => ((t.type === \"content\" || t.type === \"content-detail\") && t.id === c.id) || (t.type === \"contents\" && t.scope === \"deleted\") || t.type === \"daily-releases\");\n this.invalidate((t) => t.type === \"standing\" && t.target?.type === \"contents\" && t.target.id === c.id);\n break;\n case \"poll.created\":\n this.invalidate((t) => t.type === \"polls\" || (t.type === \"poll\" && !t.id));\n break;\n case \"poll.updated\":\n // A latest-poll slot has no id in its tag: match by the poll it holds.\n patch<Poll | null>((t) => t.type === \"poll\", (p) => (p?.id === c.poll.id ? c.poll : p));\n items<Poll>([\"polls\"], (x) => (x.id === c.poll.id ? c.poll : x));\n break;\n case \"poll.changed\":\n this.invalidate((t) => (t.type === \"poll\" && (t.id === c.id || !t.id)) || t.type === \"polls\");\n break;\n case \"poll.deleted\":\n items<Poll>([\"polls\"], (x) => (x.id === c.id ? null : x));\n this.invalidate((t) => t.type === \"poll\" && !t.id);\n break;\n case \"ban.saved\":\n case \"ban.lifted\":\n this.invalidate((t) => (t.type === \"bans\" && t.scope === c.scope) || t.type === \"standing\");\n break;\n case \"entities.changed\":\n this.invalidate((t) => t.type.startsWith(\"group\") || t.type === \"daily-releases\");\n break;\n case \"contentFilters.changed\":\n this.invalidate((t) => t.type === \"cards\" || t.type === \"history\" || t.type === \"release-dates\" || t.type === \"daily-releases\");\n break;\n case \"access.changed\":\n this.invalidate((t) => t.type === \"cards\" || t.type === \"history\" || t.type === \"content-detail\" || t.type === \"reader-plan\" || t.type.startsWith(\"group\") || t.type === \"daily-releases\" || t.type === \"standing\");\n break;\n case \"history.changed\":\n this.invalidate((t) => t.type === \"history\" || t.type === \"cards\" || t.type === \"daily-releases\");\n break;\n case \"searches.changed\":\n this.invalidate((t) => t.type === \"searches\");\n break;\n case \"rules.changed\":\n this.invalidate((t) => t.type === \"moderation-rules\" && t.scope === c.rules);\n break;\n case \"reader.changed\":\n this.invalidate((t) => (t.type === \"reader-plan\" || t.type === \"page-review\") && t.id === c.version);\n break;\n case \"moderation.resolved\":\n items<{ id: string }>([\"held\"], (x) => (x.id === c.id ? null : x));\n if (c.kind === \"comment\") this.invalidate((t) => comments.includes(t.type) || t.type === \"standing\");\n else this.invalidate((t) => (t.type === \"content\" && t.id === c.id) || t.type === \"contents\");\n break;\n }\n }\n\n // Preserve loaded pages and canonical receipt revisions. Reads that started\n // before a successful mutation cannot overwrite it when they finish later.\n private updateNotification(item: Item, scope: string | null): void {\n for (const [key, slot] of this.slots) {\n if (slot.tag.type !== \"notifications\" || !slot.listeners.size) continue;\n const page = slot.entry.data as Page<Item> | undefined;\n const cached = page?.items.find((n) => n.id === item.id);\n // Mutations from separate mounted views can complete out of order.\n // In particular, an old active receipt must not evict a newer archive.\n if ((slot.tag.readScope ?? \"{}\") === scope && cached && cached.revision > item.revision) continue;\n const archived = slot.tag.scope?.startsWith(\"archived:\") ?? false;\n const matches = archived === !!item.dismissed_at;\n if ((slot.tag.readScope ?? \"{}\") !== scope || !page || slot.tag.scope?.endsWith(\":unread\") || (matches && !page.items.some((n) => n.id === item.id))) {\n this.load(key, true);\n continue;\n }\n if (!matches && !page.items.some((n) => n.id === item.id)) continue;\n slot.ctl?.abort();\n slot.moreCtl?.abort();\n slot.ctl = slot.moreCtl = undefined;\n this.update(slot, { loading: false, loadingMore: false, data: { ...page, items: page.items.flatMap((n) => n.id === item.id ? matches ? [item] : [] : [n]) } });\n }\n }\n\n // A new entry per change: useSyncExternalStore compares snapshots by identity.\n private update(s: Slot, patch: Partial<Resource<unknown>>): void {\n s.entry = { ...s.entry, ...patch };\n for (const l of s.listeners) l();\n }\n}\n\nconst stores = new WeakMap<ContentKitClient, ResourceStore>();\n\n/** The client's shared content store. */\nexport function resourcesFor(client: ContentKitClient): ResourceStore {\n let s = stores.get(client);\n if (!s) stores.set(client, (s = new ResourceStore(client)));\n return s;\n}\n"],"mappings":";;;AAqDA,IAAM,KAAiB,MAAY,CAAC,GAAG,EAAE,SAAS,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,GAE3D,IAAwB;CAAE,MAAM,KAAA;CAAW,SAAS;CAAO,QAAQ;AAAM,GAOlE,IAAb,MAA2B;CACzB,wBAAyB,IAAI,IAAkB;CAE/C,UAAkB;CAElB,YAAY,GAA0B;EACpC,EAAO,WAAW,GAAG,MAAU,KAAK,MAAM,GAAG,CAAK,CAAC;CACrD;CAEA,UAAU,GAAa,GAAU,GAAkC;EACjE,IAAI,IAAI,KAAK,MAAM,IAAI,CAAG;EAC1B,AAAK,KAAG,KAAK,MAAM,IAAI,GAAM,IAAI;GAAE;GAAK,2BAAW,IAAI,IAAI;GAAG,0BAAU,IAAI,IAAI;GAAG,OAAO;GAAM,SAAS;GAAG,aAAa,EAAE,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entKitClient | null): {
|
|
|
11
11
|
onSignIn: (() => void) | undefined;
|
|
12
12
|
};
|
|
13
13
|
/** A shared read: fetched once per key while shown; initial is shown (and seeds the store) until it loads. */
|
|
14
|
-
export declare function useResource<T>(store: ResourceStore, key: string | null, tag: Tag, fetcher: Fetcher<T>, o?: {
|
|
14
|
+
export declare function useResource<T>(store: ResourceStore | null, key: string | null, tag: Tag, fetcher: Fetcher<T>, o?: {
|
|
15
15
|
initial?: T;
|
|
16
16
|
more?: (cursor: string | number, signal: AbortSignal) => Promise<Page<unknown>>;
|
|
17
17
|
}): Resource<T> & {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ContentKitContext as e, useContentKitClient as t, useReadScope as n } from "./context.js";
|
|
2
2
|
import { resourcesFor as r } from "./resources.js";
|
|
3
|
-
import { useCallback as i, useContext as a, useEffect as o,
|
|
3
|
+
import { useCallback as i, useContext as a, useEffect as o, useMemo as s, useSyncExternalStore as c } from "react";
|
|
4
4
|
//#region src/react/use-resource.ts
|
|
5
5
|
function l(i) {
|
|
6
6
|
let o = a(e), s = t(i);
|
|
@@ -19,29 +19,39 @@ var u = {
|
|
|
19
19
|
loaded: !1
|
|
20
20
|
}, d = () => () => {};
|
|
21
21
|
function f(e, t, r, a, l = {}) {
|
|
22
|
-
let f = n(), p = s(
|
|
22
|
+
let f = n(), p = s(() => ({
|
|
23
|
+
fetcher: a,
|
|
24
|
+
more: l.more,
|
|
25
|
+
initial: l.initial
|
|
26
|
+
}), [e, t]);
|
|
23
27
|
o(() => {
|
|
24
|
-
p.
|
|
28
|
+
p.fetcher = a, p.more = l.more, p.initial = l.initial;
|
|
25
29
|
});
|
|
26
|
-
let
|
|
30
|
+
let m = i((n) => t && e ? e.subscribe(t, {
|
|
27
31
|
...r,
|
|
28
32
|
readScope: f
|
|
29
33
|
}, n) : d(), [
|
|
30
34
|
e,
|
|
31
35
|
t,
|
|
32
36
|
f
|
|
33
|
-
]),
|
|
37
|
+
]), h = i(() => t && e ? e.snapshot(t) : u, [e, t]), g = c(m, h, h);
|
|
34
38
|
o(() => {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
39
|
+
if (!t || !e) return;
|
|
40
|
+
let n = e.bind(t, (e) => p.fetcher(e), p.more && ((e, t) => p.more(e, t)));
|
|
41
|
+
return p.initial !== void 0 && !e.snapshot(t).loaded && !e.snapshot(t).loading ? e.set(t, p.initial) : e.load(t), n;
|
|
42
|
+
}, [
|
|
43
|
+
e,
|
|
44
|
+
t,
|
|
45
|
+
p
|
|
46
|
+
]);
|
|
47
|
+
let _ = i(() => t && e?.load(t, !0), [e, t]);
|
|
48
|
+
return !g.loaded && l.initial !== void 0 ? {
|
|
49
|
+
...g,
|
|
40
50
|
data: l.initial,
|
|
41
|
-
reload:
|
|
51
|
+
reload: _
|
|
42
52
|
} : {
|
|
43
|
-
...
|
|
44
|
-
reload:
|
|
53
|
+
...g,
|
|
54
|
+
reload: _
|
|
45
55
|
};
|
|
46
56
|
}
|
|
47
57
|
var p = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-resource.js","names":[],"sources":["../../src/react/use-resource.ts"],"sourcesContent":["import { useCallback, useContext, useEffect,
|
|
1
|
+
{"version":3,"file":"use-resource.js","names":[],"sources":["../../src/react/use-resource.ts"],"sourcesContent":["import { useCallback, useContext, useEffect, useMemo, useSyncExternalStore } from \"react\";\nimport type { ContentKitClient } from \"../client/client.js\";\nimport type { ContentKitError } from \"../client/errors.js\";\nimport { ContentKitContext, useContentKitClient, useReadScope } from \"./context.js\";\nimport { resourcesFor, type Fetcher, type Page, type Resource, type ResourceStore, type Tag } from \"./resources.js\";\n\n/** The client, its shared store, and the provider's viewer, language and sign-in. */\nexport function useContentScope(own?: ContentKitClient | null) {\n const ctx = useContext(ContentKitContext);\n const client = useContentKitClient(own);\n return { client, store: resourcesFor(client), scope: useReadScope(), viewer: ctx?.viewer, language: ctx?.language, onSignIn: ctx?.onSignIn };\n}\n\nconst IDLE: Resource<never> = { data: undefined, loading: false, loaded: false };\nconst none = () => () => {};\n\n/** A shared read: fetched once per key while shown; initial is shown (and seeds the store) until it loads. */\nexport function useResource<T>(\n store: ResourceStore | null,\n key: string | null,\n tag: Tag,\n fetcher: Fetcher<T>,\n o: { initial?: T; more?: (cursor: string | number, signal: AbortSignal) => Promise<Page<unknown>> } = {},\n): Resource<T> & { reload: () => void } {\n const scope = useReadScope();\n // Each key owns its closure cell: switching this subscriber to another key\n // cannot redirect a binding still used by a different subscriber.\n const source = useMemo(() => ({ fetcher, more: o.more, initial: o.initial }),\n // Fetcher identity changes on ordinary renders; only a key change creates a cell.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [store, key]);\n useEffect(() => {\n source.fetcher = fetcher;\n source.more = o.more;\n source.initial = o.initial;\n });\n const subscribe = useCallback(\n (l: () => void) => (key && store ? store.subscribe(key, { ...tag, readScope: scope }, l) : none()),\n // The tag is part of the key.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [store, key, scope],\n );\n const snapshot = useCallback(() => (key && store ? store.snapshot<T>(key) : IDLE), [store, key]);\n const entry = useSyncExternalStore(subscribe, snapshot, snapshot);\n useEffect(() => {\n if (!key || !store) return;\n const unbind = store.bind(key, (s) => source.fetcher(s), source.more && ((c, s) => source.more!(c, s)));\n if (source.initial !== undefined && !store.snapshot(key).loaded && !store.snapshot(key).loading) store.set(key, source.initial);\n else store.load(key);\n return unbind;\n }, [store, key, source]);\n const reload = useCallback(() => key && store?.load(key, true), [store, key]);\n if (!entry.loaded && o.initial !== undefined) return { ...entry, data: o.initial, reload };\n return { ...entry, reload };\n}\n\n/** A shared list, a page at a time. */\nexport interface UseList<T> {\n items: T[];\n /** The first page is loading (also on reload). */\n loading: boolean;\n loadingMore: boolean;\n error?: ContentKitError;\n hasMore: boolean;\n loadMore: () => Promise<void>;\n reload: () => void;\n}\n\nexport type PageFetcher<T> = (cursor: string | number | undefined, signal: AbortSignal) => Promise<Page<T>>;\n\n// The items of a list not loaded: one array, so effects keyed on items don't run every render.\nconst NO_ITEMS: never[] = [];\n\nexport function useList<T extends { id: string }>(store: ResourceStore, key: string | null, tag: Tag, page: PageFetcher<T>): UseList<T> {\n const r = useResource<Page<T>>(store, key, tag, (s) => page(undefined, s), { more: (c, s) => page(c, s) });\n const loadMore = useCallback(() => (key ? store.loadMore(key) : Promise.resolve()), [store, key]);\n return {\n items: r.data?.items ?? NO_ITEMS,\n loading: r.loading || (!!key && !r.loaded),\n loadingMore: !!r.loadingMore,\n error: r.error,\n hasMore: r.data ? r.data.next !== null : false,\n loadMore,\n reload: r.reload,\n };\n}\n\n/**\n * A limit/offset list as pages. A full page means more may follow; with\n * underfill (the latest feed drops items the caller may not see) only an\n * empty page ends it.\n */\nexport function offsetPages<T>(limit: number, list: (q: { limit: number; offset: number }, signal: AbortSignal) => Promise<T[]>, underfill = false): PageFetcher<T> {\n return async (cursor, signal) => {\n const offset = typeof cursor === \"number\" ? cursor : 0;\n const items = await list({ limit, offset }, signal);\n const end = underfill ? items.length === 0 : items.length < limit;\n return { items, next: end ? null : offset + limit };\n };\n}\n\n/** A stable store key. */\nexport const keyOf = (...parts: unknown[]) => JSON.stringify(parts);\n\n/** One numbered page of a list. */\nexport interface UsePaged<T> {\n items: T[];\n loading: boolean;\n error?: ContentKitError;\n /** Another page follows. */\n hasNext: boolean;\n reload: () => void;\n}\n\n/** Page `page` (from 1) of a limit/offset list: one read of limit + 1 tells whether another follows. */\nexport function usePaged<T extends { id: string }>(\n store: ResourceStore,\n key: string | null,\n tag: Tag,\n page: number,\n limit: number,\n list: (q: { limit: number; offset: number }, signal: AbortSignal) => Promise<T[]>,\n): UsePaged<T> {\n const offset = (Math.max(1, page) - 1) * limit;\n const r = useResource<Page<T>>(store, key === null ? null : `${key}#${offset}`, tag, async (signal) => {\n const items = await list({ limit: limit + 1, offset }, signal);\n return { items: items.slice(0, limit), next: items.length > limit ? offset + limit : null };\n });\n return { items: r.data?.items ?? N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A,GACa;CACb,IAAM,KAAU,KAAK,IAAI,GAAG,CAAI,IAAI,KAAK,GACnC,IAAI,EAAqB,GAAO,MAAQ,OAAO,OAAO,GAAG,EAAI,GAAG,KAAU,GAAK,OAAO,MAAW;EACrG,IAAM,IAAQ,MAAM,EAAK;GAAE,OAAO,IAAQ;GAAG;EAAO,GAAG,CAAM;EAC7D,OAAO;GAAE,OAAO,EAAM,MAAM,GAAG,CAAK;GAAG,MAAM,EAAM,SAAS,IAAQ,IAAS,IAAQ;EAAK;CAC5F,CAAC;CACD,OAAO;EAAE,OAAO,EAAE,MAAM,SAAS;EAAU,SAAS,EAAE,WAAY,CAAC,CAAC,KAAO,CAAC,EAAE;EAAS,OAAO,EAAE;EAAO,SAAS,EAAE,OAAO,EAAE,KAAK,SAAS,OAAO;EAAO,QAAQ,EAAE;CAAO;AAC1K"}
|
package/dist/react/versions.js
CHANGED
|
@@ -1,39 +1,40 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
1
|
+
import { throwIfAborted as e, toContentKitError as t } from "../client/errors.js";
|
|
2
|
+
import { sleep as n } from "../client/media/client.js";
|
|
3
|
+
import { useMessages as r } from "../i18n/context.js";
|
|
4
|
+
import { keyOf as i, useContentScope as a, useResource as o } from "./use-resource.js";
|
|
5
|
+
import { useMediaRead as s } from "./read.js";
|
|
6
|
+
import { isPending as c } from "../client/versions.js";
|
|
7
|
+
import { useCallback as l, useEffect as u, useMemo as d, useState as f } from "react";
|
|
7
8
|
//#region src/react/versions.ts
|
|
8
|
-
var
|
|
9
|
-
function
|
|
9
|
+
var p = 2 ** 31 - 1;
|
|
10
|
+
function m(e, t = Date.now()) {
|
|
10
11
|
let n = (e?.segments ?? []).flatMap((e) => !e.released && e.release_at ? [Date.parse(e.release_at)] : []).filter((e) => e > t);
|
|
11
12
|
return n.length ? Math.min(...n) : null;
|
|
12
13
|
}
|
|
13
|
-
function
|
|
14
|
-
let { client:
|
|
14
|
+
function h(e, t, n = {}) {
|
|
15
|
+
let { client: r, store: s, scope: l } = a(n.client), d = e && t ? i("reader-plan", l, e, t) : null, f = o(s, d, {
|
|
15
16
|
type: "reader-plan",
|
|
16
17
|
id: t ?? void 0
|
|
17
|
-
}, (n) =>
|
|
18
|
-
return
|
|
19
|
-
let e =
|
|
18
|
+
}, (n) => r.versions.reader(e, t, n)), h = c(f.data), g = f.data && !h ? f.data : null, { data: _, reload: v } = f;
|
|
19
|
+
return u(() => {
|
|
20
|
+
let e = c(_) ? Date.now() + (n.poll ?? 5e3) : m(_ || null);
|
|
20
21
|
if (e === null) return;
|
|
21
|
-
let t = setTimeout(v, Math.min(
|
|
22
|
+
let t = setTimeout(v, Math.min(p, Math.max(0, e - Date.now()) + 500));
|
|
22
23
|
return () => clearTimeout(t);
|
|
23
24
|
}, [
|
|
24
25
|
_,
|
|
25
26
|
v,
|
|
26
|
-
|
|
27
|
+
n.poll
|
|
27
28
|
]), {
|
|
28
29
|
plan: g,
|
|
29
30
|
pending: h,
|
|
30
|
-
loading: !!
|
|
31
|
-
error:
|
|
31
|
+
loading: !!d && (f.loading || !f.loaded),
|
|
32
|
+
error: f.error,
|
|
32
33
|
reload: v
|
|
33
34
|
};
|
|
34
35
|
}
|
|
35
|
-
function
|
|
36
|
-
let r = e?.item ?? null, i =
|
|
36
|
+
function g(e, t, n = {}) {
|
|
37
|
+
let r = e?.item ?? null, i = s(r ?? {
|
|
37
38
|
kind: "",
|
|
38
39
|
id: ""
|
|
39
40
|
}, {
|
|
@@ -42,7 +43,7 @@ function m(e, t, n = {}) {
|
|
|
42
43
|
client: n.client
|
|
43
44
|
});
|
|
44
45
|
return {
|
|
45
|
-
pages:
|
|
46
|
+
pages: d(() => {
|
|
46
47
|
let n = new Map((i.read?.files ?? []).flatMap((e) => e.url ? [[e.path, e.url]] : []));
|
|
47
48
|
return (e?.pages ?? []).map((e) => {
|
|
48
49
|
let r = e.files[t];
|
|
@@ -62,11 +63,11 @@ function m(e, t, n = {}) {
|
|
|
62
63
|
error: i.error
|
|
63
64
|
};
|
|
64
65
|
}
|
|
65
|
-
function
|
|
66
|
+
function _(e) {
|
|
66
67
|
let t = document.createElement("a");
|
|
67
68
|
t.href = e.url, t.download = e.name, t.rel = "noopener", t.style.display = "none", document.body.appendChild(t), t.click(), t.remove();
|
|
68
69
|
}
|
|
69
|
-
function
|
|
70
|
+
function v(e, t, n = Date.now()) {
|
|
70
71
|
switch (t?.code) {
|
|
71
72
|
case void 0: return;
|
|
72
73
|
case "rate_limited": return e.t("versionDownload.limited", { minutes: Math.max(1, Math.ceil((t.retryAfter ?? 60) / 60)) });
|
|
@@ -79,37 +80,64 @@ function g(e, t, n = Date.now()) {
|
|
|
79
80
|
default: return e.t("versionDownload.failed");
|
|
80
81
|
}
|
|
81
82
|
}
|
|
82
|
-
function
|
|
83
|
-
let { client:
|
|
83
|
+
function y(i, o, s = {}) {
|
|
84
|
+
let { client: p, scope: m } = a(s.client), h = r(), g = d(() => ({
|
|
85
|
+
client: p,
|
|
86
|
+
scope: m,
|
|
87
|
+
content: i,
|
|
88
|
+
version: o,
|
|
89
|
+
active: void 0
|
|
90
|
+
}), [
|
|
91
|
+
p,
|
|
92
|
+
m,
|
|
93
|
+
i,
|
|
94
|
+
o
|
|
95
|
+
]), [y, b] = f();
|
|
96
|
+
u(() => () => g.active?.abort(), [g]);
|
|
97
|
+
let x = y?.owner === g ? y : void 0, S = s.start ?? _;
|
|
84
98
|
return {
|
|
85
|
-
download:
|
|
86
|
-
|
|
99
|
+
download: l(async () => {
|
|
100
|
+
g.active?.abort();
|
|
101
|
+
let r = g.active = new AbortController(), { signal: a } = r;
|
|
102
|
+
b({
|
|
103
|
+
owner: g,
|
|
104
|
+
preparing: !0
|
|
105
|
+
});
|
|
87
106
|
try {
|
|
88
107
|
for (;;) {
|
|
89
|
-
let
|
|
90
|
-
if (!
|
|
91
|
-
await
|
|
108
|
+
let t = await p.versions.download(i, o, a);
|
|
109
|
+
if (e(a), !c(t)) return S(t), t;
|
|
110
|
+
await n(s.poll ?? 3e3, a);
|
|
92
111
|
}
|
|
93
|
-
} catch (
|
|
94
|
-
let n = e
|
|
95
|
-
throw
|
|
112
|
+
} catch (e) {
|
|
113
|
+
let n = t(e);
|
|
114
|
+
throw !a.aborted && g.active === r && b({
|
|
115
|
+
owner: g,
|
|
116
|
+
preparing: !1,
|
|
117
|
+
error: n,
|
|
118
|
+
retryAt: n.code === "rate_limited" ? Date.now() + (n.retryAfter ?? 60) * 1e3 : void 0
|
|
119
|
+
}), n;
|
|
96
120
|
} finally {
|
|
97
|
-
|
|
121
|
+
!a.aborted && g.active === r && b((e) => e?.owner === g ? {
|
|
122
|
+
...e,
|
|
123
|
+
preparing: !1
|
|
124
|
+
} : e);
|
|
98
125
|
}
|
|
99
126
|
}, [
|
|
100
|
-
|
|
101
|
-
n,
|
|
127
|
+
p,
|
|
102
128
|
i,
|
|
103
|
-
|
|
104
|
-
|
|
129
|
+
o,
|
|
130
|
+
s.poll,
|
|
131
|
+
S,
|
|
132
|
+
g
|
|
105
133
|
]),
|
|
106
|
-
preparing:
|
|
107
|
-
error:
|
|
108
|
-
retryAt:
|
|
109
|
-
message:
|
|
134
|
+
preparing: x?.preparing ?? !1,
|
|
135
|
+
error: x?.error,
|
|
136
|
+
retryAt: x?.retryAt,
|
|
137
|
+
message: v(h, x?.error)
|
|
110
138
|
};
|
|
111
139
|
}
|
|
112
140
|
//#endregion
|
|
113
|
-
export {
|
|
141
|
+
export { v as downloadMessage, m as nextRelease, _ as startDownload, h as useReaderPlan, g as useSegmentPages, y as useVersionDownload };
|
|
114
142
|
|
|
115
143
|
//# sourceMappingURL=versions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"versions.js","names":[],"sources":["../../src/react/versions.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { ContentKitClient } from \"../client/client.js\";\nimport { toContentKitError, type ContentKitError } from \"../client/errors.js\";\nimport type { FileDownload, Pending, PlanSegment, ReaderPlan } from \"../client/generated/wire.js\";\nimport { isPending } from \"../client/versions.js\";\nimport { useMessages } from \"../i18n/context.js\";\nimport type { Translator } from \"../i18n/messages.js\";\nimport { useMediaRead, type ReadWindow } from \"./read.js\";\nimport { keyOf, useContentScope, useResource } from \"./use-resource.js\";\n\nexport interface UseReaderPlan {\n /** null while loading, pending or failed. */\n plan: ReaderPlan | null;\n /** The version has no current publication yet; the hook asks again. */\n pending: boolean;\n loading: boolean;\n error?: ContentKitError;\n reload: () => void;\n}\n\n// setTimeout's longest delay.\nconst MAX_DELAY = 2 ** 31 - 1;\n\n/** When the plan changes by itself: its next scheduled segment's release. */\nexport function nextRelease(plan: ReaderPlan | null, now = Date.now()): number | null {\n const at = (plan?.segments ?? []).flatMap((s) => (!s.released && s.release_at ? [Date.parse(s.release_at)] : [])).filter((t) => t > now);\n return at.length ? Math.min(...at) : null;\n}\n\n/**\n * A version's reader plan for this viewer: its segments (released or not,\n * open or locked), previews, playback item and reader metadata. It asks again\n * while the version is being published and when its next segment is released.\n */\nexport function useReaderPlan(content: string | null | undefined, version: string | null | undefined, o: { poll?: number; client?: ContentKitClient } = {}): UseReaderPlan {\n const { client, store, scope } = useContentScope(o.client);\n const key = content && version ? keyOf(\"reader-plan\", scope, content, version) : null;\n const r = useResource<ReaderPlan | Pending>(store, key, { type: \"reader-plan\", id: version ?? undefined }, (s) => client.versions.reader(content!, version!, s));\n const pending = isPending(r.data);\n const plan = r.data && !pending ? (r.data as ReaderPlan) : null;\n const { data, reload } = r;\n // Every answer schedules the next look: a pending one polls, a plan waits for its next release.\n useEffect(() => {\n const at = isPending(data) ? Date.now() + (o.poll ?? 5000) : nextRelease(data ? (data as ReaderPlan) : null);\n if (at === null) return;\n const t = setTimeout(reload, Math.min(MAX_DELAY, Math.max(0, at - Date.now()) + 500));\n return () => clearTimeout(t);\n }, [data, reload, o.poll]);\n return { plan, pending, loading: !!key && (r.loading || !r.loaded), error: r.error, reload };\n}\n\n/** A segment's page with the URL of one rendition, once its item's read signed it. */\nexport interface ReaderPage {\n name: string;\n w: number;\n h: number;\n /** undefined until read, or when the page lacks the rendition. */\n url?: string;\n}\n\nexport interface UseSegmentPages {\n pages: ReaderPage[];\n loading: boolean;\n error?: ContentKitError;\n}\n\n/**\n * An open segment's pages with URLs of one rendition, read through its\n * published item (windowed for long segments, refreshed before the URLs expire).\n */\nexport function useSegmentPages(segment: PlanSegment | null | undefined, rendition: string, o: { window?: ReadWindow; client?: ContentKitClient } = {}): UseSegmentPages {\n const item = segment?.item ?? null;\n const read = useMediaRead(item ?? { kind: \"\", id: \"\" }, { window: o.window, read: item ? undefined : null, client: o.client });\n const pages = useMemo(() => {\n const urls = new Map((read.read?.files ?? []).flatMap((f) => (f.url ? [[f.path, f.url] as const] : [])));\n return (segment?.pages ?? []).map((p) => {\n const path = p.files[rendition];\n return { name: p.name, w: p.w, h: p.h, url: path ? urls.get(path) : undefined };\n });\n }, [segment, rendition, read.read]);\n return { pages, loading: !!item && read.loading, error: read.error };\n}\n\nexport interface UseVersionDownload {\n /**\n * Grants the download (asking again while it is prepared), starts it in the\n * browser and resolves with the grant.\n */\n download: () => Promise<FileDownload>;\n /** Being prepared by the server, or granted and starting. */\n preparing: boolean;\n error?: ContentKitError;\n /** While a quota refused: when the viewer may download again (ms). */\n retryAt?: number;\n /**\n * What to tell the viewer about the last refusal: when a quota frees, when\n * a download the site holds back opens (\"available to download in N\n * days\"), a locked version, nothing to download, or a failure.\n */\n message?: string;\n}\n\n/** Starts a granted download: the browser fetches its URL, an attachment. */\nexport function startDownload(d: FileDownload): void {\n const a = document.createElement(\"a\");\n a.href = d.url;\n a.download = d.name;\n a.rel = \"noopener\";\n a.style.display = \"none\";\n document.body.appendChild(a);\n a.click();\n a.remove();\n}\n\n/** The viewer's line for a download refusal at now. */\nexport function downloadMessage(m: Translator, err: ContentKitError | undefined, now = Date.now()): string | undefined {\n switch (err?.code) {\n case undefined:\n return undefined;\n case \"rate_limited\":\n return m.t(\"versionDownload.limited\", { minutes: Math.max(1, Math.ceil((err.retryAfter ?? 60) / 60)) });\n case \"download_unavailable\": {\n const ms = err.availableAt ? Date.parse(err.availableAt) - now : NaN;\n return ms > 0 ? m.plural(\"versionDownload.availableIn\", Math.max(1, Math.ceil(ms / 86_400_000))) : m.t(\"versionDownload.unavailable\");\n }\n case \"forbidden\":\n return m.t(\"versionDownload.locked\");\n case \"no_download\":\n return m.error(err);\n default:\n return m.t(\"versionDownload.failed\");\n }\n}\n\n/**\n * A version's download, charged to the viewer's download quota: the\n * original or rendition its kind serves, or its pages as a zip.\n */\nexport function useVersionDownload(\n content: string,\n version: string,\n o: { poll?: number; client?: ContentKitClient; start?: (d: FileDownload) => void } = {},\n): UseVersionDownload {\n const { client } = useContentScope(o.client);\n const m = useMessages();\n const [preparing, setPreparing] = useState(false);\n const [error, setError] = useState<ContentKitError>();\n const [retryAt, setRetryAt] = useState<number>();\n const start = o.start ?? startDownload;\n const download = useCallback(async () => {\n setError(undefined);\n setRetryAt(undefined);\n setPreparing(true);\n try {\n for (;;) {\n const out = await client.versions.download(content, version);\n if (!isPending(out)) {\n start(out);\n return out;\n }\n await new Promise((r) => setTimeout(r, o.poll ?? 3000));\n }\n } catch (e) {\n const err = toContentKitError(e);\n setError(err);\n if (err.code === \"rate_limited\") setRetryAt(Date.now() + (err.retryAfter ?? 60) * 1000);\n throw err;\n } finally {\n setPreparing(false);\n }\n }, [client, content, version, o.poll, start]);\n return { download, preparing, error, retryAt, message: downloadMessage(m, error) };\n}\n"],"mappings":";;;;;;;AAqBA,IAAM,IAAY,KAAK,KAAK;AAG5B,SAAgB,EAAY,GAAyB,IAAM,KAAK,IAAI,GAAkB;CACpF,IAAM,KAAM,GAAM,YAAY,CAAC,EAAA,CAAG,SAAS,MAAO,CAAC,EAAE,YAAY,EAAE,aAAa,CAAC,KAAK,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,CAAE,CAAC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EAAE,EAAE,wBAAwB;CACvC;AACF;AAMA,SAAgB,EACd,GACA,GACA,IAAqF,CAAC,GAClE;CACpB,IAAM,EAAE,cAAW,EAAgB,EAAE,MAAM,GACrC,IAAI,EAAY,GAChB,CAAC,GAAW,KAAgB,EAAS,EAAK,GAC1C,CAAC,GAAO,KAAY,EAA0B,GAC9C,CAAC,GAAS,KAAc,EAAiB,GACzC,IAAQ,EAAE,SAAS;CAuBzB,OAAO;EAAE,UAtBQ,EAAY,YAAY;GAGvC,AAFA,EAAS,KAAA,CAAS,GAClB,EAAW,KAAA,CAAS,GACpB,EAAa,EAAI;GACjB,IAAI;IACF,SAAS;KACP,IAAM,IAAM,MAAM,EAAO,SAAS,SAAS,GAAS,CAAO;KAC3D,IAAI,CAAC,EAAU,CAAG,GAEhB,OADA,EAAM,CAAG,GACF;KAET,MAAM,IAAI,SAAS,MAAM,WAAW,GAAG,EAAE,QAAQ,GAAI,CAAC;IACxD;GACF,SAAS,GAAG;IACV,IAAM,IAAM,EAAkB,CAAC;IAG/B,MAFA,EAAS,CAAG,GACR,EAAI,SAAS,kBAAgB,EAAW,KAAK,IAAI,KAAK,EAAI,cAAc,MAAM,GAAI,GAChF;GACR,UAAU;IACR,EAAa,EAAK;GACpB;EACF,GAAG;GAAC;GAAQ;GAAS;GAAS,EAAE;GAAM;EAAK,CAClC;EAAU;EAAW;EAAO;EAAS,SAAS,EAAgB,GAAG,CAAK;CAAE;AACnF"}
|
|
1
|
+
{"version":3,"file":"versions.js","names":[],"sources":["../../src/react/versions.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { ContentKitClient } from \"../client/client.js\";\nimport { throwIfAborted, toContentKitError, type ContentKitError } from \"../client/errors.js\";\nimport type { FileDownload, Pending, PlanSegment, ReaderPlan } from \"../client/generated/wire.js\";\nimport { isPending } from \"../client/versions.js\";\nimport { sleep } from \"../client/media/client.js\";\nimport { useMessages } from \"../i18n/context.js\";\nimport type { Translator } from \"../i18n/messages.js\";\nimport { useMediaRead, type ReadWindow } from \"./read.js\";\nimport { keyOf, useContentScope, useResource } from \"./use-resource.js\";\n\nexport interface UseReaderPlan {\n /** null while loading, pending or failed. */\n plan: ReaderPlan | null;\n /** The version has no current publication yet; the hook asks again. */\n pending: boolean;\n loading: boolean;\n error?: ContentKitError;\n reload: () => void;\n}\n\n// setTimeout's longest delay.\nconst MAX_DELAY = 2 ** 31 - 1;\n\n/** When the plan changes by itself: its next scheduled segment's release. */\nexport function nextRelease(plan: ReaderPlan | null, now = Date.now()): number | null {\n const at = (plan?.segments ?? []).flatMap((s) => (!s.released && s.release_at ? [Date.parse(s.release_at)] : [])).filter((t) => t > now);\n return at.length ? Math.min(...at) : null;\n}\n\n/**\n * A version's reader plan for this viewer: its segments (released or not,\n * open or locked), previews, playback item and reader metadata. It asks again\n * while the version is being published and when its next segment is released.\n */\nexport function useReaderPlan(content: string | null | undefined, version: string | null | undefined, o: { poll?: number; client?: ContentKitClient } = {}): UseReaderPlan {\n const { client, store, scope } = useContentScope(o.client);\n const key = content && version ? keyOf(\"reader-plan\", scope, content, version) : null;\n const r = useResource<ReaderPlan | Pending>(store, key, { type: \"reader-plan\", id: version ?? undefined }, (s) => client.versions.reader(content!, version!, s));\n const pending = isPending(r.data);\n const plan = r.data && !pending ? (r.data as ReaderPlan) : null;\n const { data, reload } = r;\n // Every answer schedules the next look: a pending one polls, a plan waits for its next release.\n useEffect(() => {\n const at = isPending(data) ? Date.now() + (o.poll ?? 5000) : nextRelease(data ? (data as ReaderPlan) : null);\n if (at === null) return;\n const t = setTimeout(reload, Math.min(MAX_DELAY, Math.max(0, at - Date.now()) + 500));\n return () => clearTimeout(t);\n }, [data, reload, o.poll]);\n return { plan, pending, loading: !!key && (r.loading || !r.loaded), error: r.error, reload };\n}\n\n/** A segment's page with the URL of one rendition, once its item's read signed it. */\nexport interface ReaderPage {\n name: string;\n w: number;\n h: number;\n /** undefined until read, or when the page lacks the rendition. */\n url?: string;\n}\n\nexport interface UseSegmentPages {\n pages: ReaderPage[];\n loading: boolean;\n error?: ContentKitError;\n}\n\n/**\n * An open segment's pages with URLs of one rendition, read through its\n * published item (windowed for long segments, refreshed before the URLs expire).\n */\nexport function useSegmentPages(segment: PlanSegment | null | undefined, rendition: string, o: { window?: ReadWindow; client?: ContentKitClient } = {}): UseSegmentPages {\n const item = segment?.item ?? null;\n const read = useMediaRead(item ?? { kind: \"\", id: \"\" }, { window: o.window, read: item ? undefined : null, client: o.client });\n const pages = useMemo(() => {\n const urls = new Map((read.read?.files ?? []).flatMap((f) => (f.url ? [[f.path, f.url] as const] : [])));\n return (segment?.pages ?? []).map((p) => {\n const path = p.files[rendition];\n return { name: p.name, w: p.w, h: p.h, url: path ? urls.get(path) : undefined };\n });\n }, [segment, rendition, read.read]);\n return { pages, loading: !!item && read.loading, error: read.error };\n}\n\nexport interface UseVersionDownload {\n /**\n * Grants the download (asking again while it is prepared), starts it in the\n * browser and resolves with the grant.\n */\n download: () => Promise<FileDownload>;\n /** Being prepared by the server, or granted and starting. */\n preparing: boolean;\n error?: ContentKitError;\n /** While a quota refused: when the viewer may download again (ms). */\n retryAt?: number;\n /**\n * What to tell the viewer about the last refusal: when a quota frees, when\n * a download the site holds back opens (\"available to download in N\n * days\"), a locked version, nothing to download, or a failure.\n */\n message?: string;\n}\n\n/** Starts a granted download: the browser fetches its URL, an attachment. */\nexport function startDownload(d: FileDownload): void {\n const a = document.createElement(\"a\");\n a.href = d.url;\n a.download = d.name;\n a.rel = \"noopener\";\n a.style.display = \"none\";\n document.body.appendChild(a);\n a.click();\n a.remove();\n}\n\n/** The viewer's line for a download refusal at now. */\nexport function downloadMessage(m: Translator, err: ContentKitError | undefined, now = Date.now()): string | undefined {\n switch (err?.code) {\n case undefined:\n return undefined;\n case \"rate_limited\":\n return m.t(\"versionDownload.limited\", { minutes: Math.max(1, Math.ceil((err.retryAfter ?? 60) / 60)) });\n case \"download_unavailable\": {\n const ms = err.availableAt ? Date.parse(err.availableAt) - now : NaN;\n return ms > 0 ? m.plural(\"versionDownload.availableIn\", Math.max(1, Math.ceil(ms / 86_400_000))) : m.t(\"versionDownload.unavailable\");\n }\n case \"forbidden\":\n return m.t(\"versionDownload.locked\");\n case \"no_download\":\n return m.error(err);\n default:\n return m.t(\"versionDownload.failed\");\n }\n}\n\n/**\n * A version's download, charged to the viewer's download quota: the\n * original or rendition its kind serves, or its pages as a zip.\n */\nexport function useVersionDownload(\n content: string,\n version: string,\n o: { poll?: number; client?: ContentKitClient; start?: (d: FileDownload) => void } = {},\n): UseVersionDownload {\n const { client, scope } = useContentScope(o.client);\n const m = useMessages();\n const owner = useMemo(() => ({ client, scope, content, version, active: undefined as AbortController | undefined }), [client, scope, content, version]);\n const [state, setState] = useState<{ owner: typeof owner; preparing: boolean; error?: ContentKitError; retryAt?: number }>();\n useEffect(() => () => owner.active?.abort(), [owner]);\n const current = state?.owner === owner ? state : undefined;\n const start = o.start ?? startDownload;\n const download = useCallback(async () => {\n owner.active?.abort();\n const controller = owner.active = new AbortController();\n const { signal } = controller;\n setState({ owner, preparing: true });\n try {\n for (;;) {\n const out = await client.versions.download(content, version, signal);\n // Also reject a late result from a transport that ignored cancellation.\n throwIfAborted(signal);\n if (!isPending(out)) {\n start(out);\n return out;\n }\n await sleep(o.poll ?? 3000, signal);\n }\n } catch (e) {\n const error = toContentKitError(e);\n if (!signal.aborted && owner.active === controller) {\n setState({ owner, preparing: false, error, retryAt: error.code === \"rate_limited\" ? Date.now() + (error.retryAfter ?? 60) * 1000 : undefined });\n }\n throw error;\n } finally {\n if (!signal.aborted && owner.active === controller) setState((state) => state?.owner === owner ? { ...state, preparing: false } : state);\n }\n }, [client, content, version, o.poll, start, owner]);\n return { download, preparing: current?.preparing ?? false, error: current?.error, retryAt: current?.retryAt, message: downloadMessage(m, current?.error) };\n}\n"],"mappings":";;;;;;;;AAsBA,IAAM,IAAY,KAAK,KAAK;AAG5B,SAAgB,EAAY,GAAyB,IAAM,KAAK,IAAI,GAAkB;CACp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KAAY,GAAU,MAAU,GAAO,UAAU,IAAQ;KAAE,GAAG;KAAO,WAAW;IAAM,IAAI,CAAK;GACzI;EACF,GAAG;GAAC;GAAQ;GAAS;GAAS,EAAE;GAAM;GAAO;EAAK,CACzC;EAAU,WAAW,GAAS,aAAa;EAAO,OAAO,GAAS;EAAO,SAAS,GAAS;EAAS,SAAS,EAAgB,GAAG,GAAS,KAAK;CAAE;AAC3J"}
|
package/dist/react.js
CHANGED
|
@@ -21,10 +21,11 @@ import { useAdminLocation as me, useFlowClient as he, useStaffAccess as ge } fro
|
|
|
21
21
|
import { beaconsFor as _e, useBeacons as ve, useContentFilters as ye, useContents as be, useDailyReleases as xe, useExposure as Se, useHistory as Ce, useLockedCount as we, useMyFavorites as Te, useMyReactions as Ee, useRecentSearches as De, useRecommendations as Oe, useReleaseDates as ke, useSearch as Ae, useSimilar as je, useTypeahead as Me, useViewSignal as Ne } from "./react/discovery.js";
|
|
22
22
|
import { defaultVersion as Pe, editionOf as Fe, findVersion as Ie, liveVersions as Le, useContentDetail as Re } from "./react/detail.js";
|
|
23
23
|
import { downloadMessage as ze, nextRelease as Be, startDownload as Ve, useReaderPlan as He, useSegmentPages as Ue, useVersionDownload as We } from "./react/versions.js";
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
|
|
24
|
+
import { usePageReview as Ge } from "./react/page-review.js";
|
|
25
|
+
import { useActivity as Ke, useMyStats as qe, useTopContents as Je } from "./react/stats.js";
|
|
26
|
+
import { useContent as Ye, useManagedContents as Xe } from "./react/contents.js";
|
|
27
|
+
import { useNotificationUnread as Ze, useNotifications as Qe } from "./react/notifications.js";
|
|
28
|
+
import { ContentKitProvider as $e } from "./react/provider.js";
|
|
29
|
+
import { useReaderPreferences as et } from "./react/reader-preferences.js";
|
|
30
|
+
import { useCanonicalContent as tt } from "./react/canonical.js";
|
|
31
|
+
export { $e as ContentKitProvider, R as GALLERY_VIEW_KEY, i as GuardContext, e as HOVER_DELAY, t as InlinePreviewContext, z as PLAYER_QUALITY_KEY, h as ResourceStore, _e as beaconsFor, Pe as defaultVersion, ze as downloadMessage, A as editOutput, Fe as editionOf, Ie as findVersion, Le as liveVersions, y as memberId, G as nameIn, Be as nextRelease, g as resourcesFor, N as round3, Ve as startDownload, K as thumbnailOf, Ke as useActivity, Y as useAdminComments, me as useAdminLocation, D as useAvatar, X as useBannedWords, ve as useBeacons, Z as useCanComment, tt as useCanonicalContent, B as useCarousel, Q as useCommentBans, $ as useCommentReplies, ee as useComments, Ye as useContent, oe as useContentConfig, Re as useContentDetail, ye as useContentFilters, b as useContentGroups, a as useContentKit, o as useContentKitClient, _ as useContentScope, s as useContentURLs, be as useContents, d as useCrop, xe as useDailyReleases, W as useEditorCrop, f as useEncodeProgress, c as useErrorReporter, Se as useExposure, se as useFavorite, he as useFlowClient, P as useFrameStrip, V as useGalleryView, te as useGlobalCommentBan, x as useGroup, S as useGroupMembers, C as useGroups, l as useGuarded, Ce as useHistory, H as useHlsPlayer, ne as useIPBans, n as useInlinePreview, w as useKinds, re as useLatestComments, we as useLockedCount, Xe as useManagedContents, q as useMediaFolder, E as useMediaRead, ie as useModerationQueue, Te as useMyFavorites, T as useMyGroups, Ee as useMyReactions, qe as useMyStats, J as useNearViewport, Ze as useNotificationUnread, Qe as useNotifications, u as useOptionalContentKitClient, Ge as usePageReview, v as usePaged, le as usePoll, ue as usePollEditor, de as usePolls, O as usePresets, k as usePublicImage, ce as useReaction, He as useReaderPlan, et as useReaderPreferences, De as useRecentSearches, Oe as useRecommendations, r as useReducedMotion, U as useRefreshBeforeExpiry, ke as useReleaseDates, Ae as useSearch, Ue as useSegmentPages, je as useSimilar, j as useSlotCrop, M as useSlotImage, ge as useStaffAccess, Je as useTopContents, Me as useTypeahead, p as useUpload, m as useUploadQueue, We as useVersionDownload, pe as useVersionParam, F as useVideoFrame, I as useVideoImages, L as useVideoPoster, Ne as useViewSignal, ae as withReaction, fe as withVote };
|