@openrails/contentkit-ui 0.86.0 → 0.87.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.
Files changed (127) hide show
  1. package/README.md +39 -14
  2. package/dist/client/beacons.js +5 -1
  3. package/dist/client/beacons.js.map +1 -1
  4. package/dist/client/content/types.d.ts +4 -2
  5. package/dist/client/content/types.js.map +1 -1
  6. package/dist/client/contents.d.ts +8 -6
  7. package/dist/client/contents.js +10 -7
  8. package/dist/client/contents.js.map +1 -1
  9. package/dist/client/discovery.js +3 -0
  10. package/dist/client/discovery.js.map +1 -1
  11. package/dist/client/errors.d.ts +21 -3
  12. package/dist/client/errors.js +44 -14
  13. package/dist/client/errors.js.map +1 -1
  14. package/dist/client/gallery.d.ts +3 -5
  15. package/dist/client/gallery.js +16 -20
  16. package/dist/client/gallery.js.map +1 -1
  17. package/dist/client/generated/error-codes.d.ts +1 -1
  18. package/dist/client/generated/error-codes.js +8 -0
  19. package/dist/client/generated/error-codes.js.map +1 -1
  20. package/dist/client/generated/routes.d.ts +16 -3
  21. package/dist/client/generated/routes.js +28 -3
  22. package/dist/client/generated/routes.js.map +1 -1
  23. package/dist/client/generated/wire.d.ts +43 -14
  24. package/dist/client/generated/wire.js.map +1 -1
  25. package/dist/client/http.js +27 -27
  26. package/dist/client/http.js.map +1 -1
  27. package/dist/client/index.d.ts +2 -2
  28. package/dist/client/media/client.d.ts +10 -4
  29. package/dist/client/media/client.js +33 -7
  30. package/dist/client/media/client.js.map +1 -1
  31. package/dist/client/media/rules.d.ts +1 -1
  32. package/dist/client/media/rules.js +6 -6
  33. package/dist/client/media/rules.js.map +1 -1
  34. package/dist/client/media/transport.d.ts +1 -1
  35. package/dist/client/media/transport.js +16 -16
  36. package/dist/client/media/transport.js.map +1 -1
  37. package/dist/client/media/windows.js +1 -1
  38. package/dist/client/media/windows.js.map +1 -1
  39. package/dist/client/public.d.ts +2 -2
  40. package/dist/client/public.js +2 -2
  41. package/dist/client/public.js.map +1 -1
  42. package/dist/client/versions.d.ts +6 -4
  43. package/dist/client/versions.js +24 -26
  44. package/dist/client/versions.js.map +1 -1
  45. package/dist/client.js +25 -25
  46. package/dist/components/admin/content-manager.js +233 -232
  47. package/dist/components/admin/content-manager.js.map +1 -1
  48. package/dist/components/content/card.d.ts +5 -3
  49. package/dist/components/content/card.js +131 -109
  50. package/dist/components/content/card.js.map +1 -1
  51. package/dist/components/content/download-button.d.ts +26 -0
  52. package/dist/components/content/download-button.js +51 -0
  53. package/dist/components/content/download-button.js.map +1 -0
  54. package/dist/components/content/editors.d.ts +8 -0
  55. package/dist/components/content/editors.js +299 -229
  56. package/dist/components/content/editors.js.map +1 -1
  57. package/dist/components/content/grid.d.ts +8 -1
  58. package/dist/components/content/grid.js +125 -76
  59. package/dist/components/content/grid.js.map +1 -1
  60. package/dist/components/content/index.d.ts +3 -2
  61. package/dist/components/content/listing.d.ts +3 -1
  62. package/dist/components/content/listing.js.map +1 -1
  63. package/dist/components/content/paywall.js +61 -61
  64. package/dist/components/content/paywall.js.map +1 -1
  65. package/dist/components/media-gallery.d.ts +1 -4
  66. package/dist/components/media-gallery.js +19 -34
  67. package/dist/components/media-gallery.js.map +1 -1
  68. package/dist/components/social/comments.js +1 -1
  69. package/dist/components/social/comments.js.map +1 -1
  70. package/dist/components/social/engagement.d.ts +2 -1
  71. package/dist/components/social/engagement.js +5 -3
  72. package/dist/components/social/engagement.js.map +1 -1
  73. package/dist/i18n/messages.js +49 -46
  74. package/dist/i18n/messages.js.map +1 -1
  75. package/dist/index.js +12 -11
  76. package/dist/locales/de.js +15 -3
  77. package/dist/locales/de.js.map +1 -1
  78. package/dist/locales/discovery/de.js +3 -0
  79. package/dist/locales/discovery/de.js.map +1 -1
  80. package/dist/locales/discovery/en.d.ts +3 -0
  81. package/dist/locales/discovery/en.js +3 -0
  82. package/dist/locales/discovery/en.js.map +1 -1
  83. package/dist/locales/discovery/es.js +3 -0
  84. package/dist/locales/discovery/es.js.map +1 -1
  85. package/dist/locales/discovery/ja.js +3 -0
  86. package/dist/locales/discovery/ja.js.map +1 -1
  87. package/dist/locales/discovery/ko.js +3 -0
  88. package/dist/locales/discovery/ko.js.map +1 -1
  89. package/dist/locales/discovery/zh.js +3 -0
  90. package/dist/locales/discovery/zh.js.map +1 -1
  91. package/dist/locales/en.d.ts +17 -2
  92. package/dist/locales/en.js +15 -3
  93. package/dist/locales/en.js.map +1 -1
  94. package/dist/locales/es.js +15 -3
  95. package/dist/locales/es.js.map +1 -1
  96. package/dist/locales/ja.js +15 -3
  97. package/dist/locales/ja.js.map +1 -1
  98. package/dist/locales/ko.js +15 -3
  99. package/dist/locales/ko.js.map +1 -1
  100. package/dist/locales/zh.js +15 -3
  101. package/dist/locales/zh.js.map +1 -1
  102. package/dist/react/comments.d.ts +1 -1
  103. package/dist/react/comments.js +3 -2
  104. package/dist/react/comments.js.map +1 -1
  105. package/dist/react/contents.d.ts +13 -5
  106. package/dist/react/contents.js +163 -149
  107. package/dist/react/contents.js.map +1 -1
  108. package/dist/react/context.d.ts +1 -1
  109. package/dist/react/context.js.map +1 -1
  110. package/dist/react/detail.d.ts +7 -1
  111. package/dist/react/detail.js +9 -6
  112. package/dist/react/detail.js.map +1 -1
  113. package/dist/react/discovery.d.ts +11 -0
  114. package/dist/react/discovery.js +49 -30
  115. package/dist/react/discovery.js.map +1 -1
  116. package/dist/react/engagement.d.ts +6 -2
  117. package/dist/react/engagement.js +2 -6
  118. package/dist/react/engagement.js.map +1 -1
  119. package/dist/react/index.d.ts +3 -3
  120. package/dist/react/public.js +17 -16
  121. package/dist/react/public.js.map +1 -1
  122. package/dist/react/versions.d.ts +25 -5
  123. package/dist/react/versions.js +58 -37
  124. package/dist/react/versions.js.map +1 -1
  125. package/dist/react.js +9 -9
  126. package/dist/styles.css +1 -1
  127. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { ContentKitClient } from '../client/client.js';
2
2
  import { ContentKitError } from '../client/errors.js';
3
- import { CatalogText, Content, ContentInput, ContentPatch } from '../client/generated/wire.js';
3
+ import { CatalogText, Content, ContentInput, ContentPatch, Version } from '../client/generated/wire.js';
4
4
  import { ManageQuery } from '../client/contents.js';
5
5
  import { UseList } from './use-resource.js';
6
6
  export interface ManageFilter extends Omit<ManageQuery, "limit" | "offset"> {
@@ -29,9 +29,15 @@ export interface UseContent {
29
29
  unpublish: () => Promise<Content>;
30
30
  remove: () => Promise<void>;
31
31
  restore: () => Promise<Content>;
32
- /** Uploads the cover (null clears it); resolves with a URL that shows it now. */
32
+ /**
33
+ * The version whose cover and body images the hook edits: the one asked
34
+ * for, else the first. Every version has its own cover and its own copy of
35
+ * the body's images.
36
+ */
37
+ version: Version | null;
38
+ /** Uploads the version's cover (null returns to its first upload); resolves with a URL that shows it now. */
33
39
  setCover: (file: Blob | null) => Promise<string | null>;
34
- /** Uploads an image for the body; resolves with a URL that shows it now, to place in the editor. */
40
+ /** Uploads an image for the body into the version, copied into the others; resolves with a URL that shows it now, to place in the editor. */
35
41
  uploadImage: (file: Blob) => Promise<string>;
36
42
  /**
37
43
  * A URL that shows one of the item's images now, by name ("i-{uuid}") or
@@ -40,7 +46,7 @@ export interface UseContent {
40
46
  * signed editor view from an editor read. Anything else is returned as is.
41
47
  */
42
48
  imageSrc: (image: string | null | undefined) => string | undefined;
43
- /** The cover through imageSrc. */
49
+ /** The version's cover through imageSrc. */
44
50
  coverSrc: string | undefined;
45
51
  /** The language's stored text, its body's images through imageSrc: what an editor shows. */
46
52
  text: CatalogText | undefined;
@@ -49,9 +55,11 @@ export interface UseContent {
49
55
  }
50
56
  /**
51
57
  * One content item of kind for its editors: read, create, text in language,
52
- * publish, delete, restore, cover and body images. null creates a new item.
58
+ * publish, delete, restore, a version's cover and the body's images. null
59
+ * creates a new item.
53
60
  */
54
61
  export declare function useContent(id: string | null | undefined, kind: string, language: string, o?: {
55
62
  initial?: Content;
56
63
  client?: ContentKitClient;
64
+ version?: string;
57
65
  }): UseContent;
@@ -1,10 +1,10 @@
1
1
  import { useGuarded as e } from "./context.js";
2
2
  import { keyOf as t, offsetPages as n, useContentScope as r, useList as i, useResource as a } from "./use-resource.js";
3
3
  import { useMediaRead as o } from "./read.js";
4
- import { BODY_SUFFIX as s, IMAGE_SCHEME as c, imageRef as l, imageRefs as u } from "../client/contents.js";
5
- import { useCallback as d, useEffect as f, useMemo as p, useRef as m, useState as h } from "react";
4
+ import { IMAGE_SCHEME as s, imageRef as c, imageRefs as l } from "../client/contents.js";
5
+ import { useCallback as u, useEffect as d, useMemo as f, useRef as p, useState as m } from "react";
6
6
  //#region src/react/contents.ts
7
- function g(e = {}, a = {}) {
7
+ function h(e = {}, a = {}) {
8
8
  let { client: o, store: s, scope: c } = r(a.client), { pageSize: l, ...u } = e, d = l ?? 20;
9
9
  return i(s, t("contents", c, u.kind, u.state, u.owner_group, u.q, u.language, d), {
10
10
  type: "contents",
@@ -14,201 +14,215 @@ function g(e = {}, a = {}) {
14
14
  ...e
15
15
  }, t)));
16
16
  }
17
- var ee = (e) => [...new Set([...(e ?? "").matchAll(u())].map((e) => e[1]))], _ = (e) => {
17
+ var ee = (e) => [...new Set([...(e ?? "").matchAll(l())].map((e) => e[1]))], g = (e) => {
18
18
  let t = e.slice(e.lastIndexOf("/") + 1), n = t.lastIndexOf(".");
19
19
  return n > 0 ? t.slice(0, n) : t;
20
20
  };
21
- function v(n, i, g, v = {}) {
22
- let { client: y, store: te, scope: ne } = r(v.client), [b, re] = h(null), x = n ?? b, S = x ? t("content", ne, x) : null, C = a(te, S, {
21
+ function _(n, i, h, _ = {}) {
22
+ let { client: v, store: y, scope: te } = r(_.client), [b, x] = m(null), S = n ?? b, C = S ? t("content", te, S) : null, w = a(y, C, {
23
23
  type: "content",
24
- id: x ?? void 0
25
- }, (e) => y.contents.get(x, g, e), { initial: v.initial }), w = C.data ?? null, [ie, T] = h(0), E = e(), D = d(async (e) => {
26
- T((e) => e + 1);
24
+ id: S ?? void 0
25
+ }, (e) => v.contents.get(S, h, e), { initial: _.initial }), T = w.data ?? null, [ne, E] = m(0), D = e(), O = u(async (e) => {
26
+ E((e) => e + 1);
27
27
  try {
28
- return await E(e);
28
+ return await D(e);
29
29
  } finally {
30
- T((e) => e - 1);
30
+ E((e) => e - 1);
31
31
  }
32
- }, [E]), O = d(() => {
33
- if (!x) throw Error("contentkit-ui: create the item first");
34
- return x;
35
- }, [x]), k = w?.text?.[g], A = k?.body, j = w?.cover, [M, ae] = h(/* @__PURE__ */ new Map()), N = m([]);
36
- f(() => {
37
- let e = N.current;
32
+ }, [D]), k = u(() => {
33
+ if (!S) throw Error("contentkit-ui: create the item first");
34
+ return S;
35
+ }, [S]), A = T?.text?.[h], j = A?.body, M = f(() => {
36
+ let e = [...T?.versions ?? []].sort((e, t) => e.position - t.position);
37
+ return e.find((e) => e.id === _.version) ?? e[0] ?? null;
38
+ }, [T?.versions, _.version]), N = M?.id, P = M?.cover, F = u(() => {
39
+ if (!N) throw Error("contentkit-ui: the item has no version yet");
40
+ return N;
41
+ }, [N]), [I, L] = m(/* @__PURE__ */ new Map()), R = p([]);
42
+ d(() => {
43
+ let e = R.current;
38
44
  return () => {
39
45
  for (let t of e) URL.revokeObjectURL(t);
40
46
  };
41
47
  }, []);
42
- let P = p(() => new Map(Object.entries(w?.images ?? {})), [w?.images]), F = !!j && !j.url && !M.has(j.image) && !P.has(j.image), I = p(() => ee(A).filter((e) => !M.has(e) && !P.has(e)), [
43
- A,
44
- M,
45
- P
46
- ]), L = p(() => F ? [...I, j.image] : I, [
47
- F,
48
+ let z = f(() => {
49
+ let e = new Map(Object.entries(T?.images ?? {}));
50
+ return P?.image && P.url && e.set(P.image, P.url), e;
51
+ }, [
52
+ T?.images,
53
+ P?.image,
54
+ P?.url
55
+ ]), B = !!P?.image && !P.url && !I.has(P.image) && !z.has(P.image), V = f(() => ee(j).filter((e) => !I.has(e) && !z.has(e)), [
56
+ j,
48
57
  I,
49
- j
50
- ]), R = p(() => ({
58
+ z
59
+ ]), H = f(() => B ? [...V, P.image] : V, [
60
+ B,
61
+ V,
62
+ P
63
+ ]), U = f(() => ({
51
64
  kind: i,
52
- id: x ?? "none"
53
- }), [i, x]), oe = p(() => ({
54
- kind: i + s,
55
- id: x ?? "none"
56
- }), [i, x]), z = o(R, {
57
- editor: !0,
58
- read: F ? void 0 : null,
59
- client: y
60
- }), B = o(oe, {
65
+ id: S ?? "none",
66
+ version: N
67
+ }), [
68
+ i,
69
+ S,
70
+ N
71
+ ]), W = o(U, {
61
72
  editor: !0,
62
- read: I.length ? void 0 : null,
63
- client: y
64
- }), V = p(() => [...z.read?.files ?? [], ...B.read?.files ?? []], [z.read, B.read]), H = p(() => {
73
+ read: H.length && N ? void 0 : null,
74
+ client: v
75
+ }), G = f(() => W.read?.files ?? [], [W.read]), K = f(() => {
65
76
  let e = /* @__PURE__ */ new Map();
66
- for (let t of V) t.upload && t.editor_url && e.set(_(t.path), t.editor_url);
77
+ for (let t of G) t.upload && t.editor_url && e.set(g(t.path), t.editor_url);
67
78
  return e;
68
- }, [V]), U = (e) => V.some((t) => t.failed && _(t.path) === e), W = (!!z.read || !!B.read) && L.some((e) => !H.has(e) && !U(e)), G = m(0), K = z.reload, q = B.reload, J = d(() => {
69
- K(), q();
70
- }, [K, q]);
71
- f(() => {
72
- if (!W) {
73
- G.current = 0;
79
+ }, [G]), re = (e) => G.some((t) => t.failed && g(t.path) === e), q = !!W.read && H.some((e) => !K.has(e) && !re(e)), J = p(0), Y = W.reload;
80
+ d(() => {
81
+ if (!q) {
82
+ J.current = 0;
74
83
  return;
75
84
  }
76
- if (G.current >= 6) return;
85
+ if (J.current >= 6) return;
77
86
  let e = setTimeout(() => {
78
- G.current++, J();
79
- }, 1e3 * 2 ** G.current);
87
+ J.current++, Y();
88
+ }, 1e3 * 2 ** J.current);
80
89
  return () => clearTimeout(e);
81
90
  }, [
82
- W,
83
- V,
84
- J
91
+ q,
92
+ G,
93
+ Y
85
94
  ]);
86
- let Y = m(/* @__PURE__ */ new Map());
87
- f(() => {
95
+ let X = p(/* @__PURE__ */ new Map());
96
+ d(() => {
88
97
  for (let e of [
89
- M,
90
- P,
91
- H
92
- ]) for (let [t, n] of e) Y.current.set(n, t);
98
+ I,
99
+ z,
100
+ K
101
+ ]) for (let [t, n] of e) X.current.set(n, t);
93
102
  }, [
94
- M,
95
- P,
96
- H
103
+ I,
104
+ z,
105
+ K
97
106
  ]);
98
- let X = d((e) => {
107
+ let Z = u((e) => {
99
108
  if (!e) return;
100
- let t = e.startsWith("contentkit:") ? e.slice(c.length) : e;
101
- return M.get(t) ?? P.get(t) ?? H.get(t) ?? e;
109
+ let t = e.startsWith("contentkit:") ? e.slice(s.length) : e;
110
+ return I.get(t) ?? z.get(t) ?? K.get(t) ?? e;
102
111
  }, [
103
- M,
104
- P,
105
- H
106
- ]), se = p(() => k ? {
107
- ...k,
108
- body: (k.body ?? "").replace(u(), (e, t) => M.get(t) ?? P.get(t) ?? H.get(t) ?? e)
112
+ I,
113
+ z,
114
+ K
115
+ ]), ie = f(() => A ? {
116
+ ...A,
117
+ body: (A.body ?? "").replace(l(), (e, t) => I.get(t) ?? z.get(t) ?? K.get(t) ?? e)
109
118
  } : void 0, [
110
- k,
111
- M,
112
- P,
113
- H
114
- ]), Z = d((e) => {
115
- let t = new Map(Y.current);
119
+ A,
120
+ I,
121
+ z,
122
+ K
123
+ ]), Q = u((e) => {
124
+ let t = new Map(X.current);
116
125
  for (let e of [
117
- M,
118
- P,
119
- H
126
+ I,
127
+ z,
128
+ K
120
129
  ]) for (let [n, r] of e) t.set(r, n);
121
130
  let n = e;
122
- for (let [e, r] of t) n = n.split(e).join(l(r)).split(e.replaceAll("&", "&amp;")).join(l(r));
131
+ for (let [e, r] of t) n = n.split(e).join(c(r)).split(e.replaceAll("&", "&amp;")).join(c(r));
123
132
  return n;
124
133
  }, [
125
- M,
126
- P,
127
- H
128
- ]), Q = d((e, t) => {
134
+ I,
135
+ z,
136
+ K
137
+ ]), $ = u((e, t) => {
129
138
  if (typeof URL.createObjectURL != "function") return;
130
139
  let n = URL.createObjectURL(t);
131
- return N.current.push(n), ae((t) => new Map(t).set(e, n)), n;
132
- }, []), ce = d((e) => D(async () => {
133
- let t = await y.contents.create(e);
134
- return re(t.id), t;
135
- }), [y, D]), le = d((e) => D(() => y.contents.update(O(), e)), [
136
- y,
137
- D,
138
- O
139
- ]), ue = d((e) => D(() => y.contents.putText(O(), g, e.body === void 0 ? e : {
140
+ return R.current.push(n), L((t) => new Map(t).set(e, n)), n;
141
+ }, []), ae = u((e) => O(async () => {
142
+ let t = await v.contents.create(e);
143
+ return x(t.id), t;
144
+ }), [v, O]), oe = u((e) => O(() => v.contents.update(k(), e)), [
145
+ v,
146
+ O,
147
+ k
148
+ ]), se = u((e) => O(() => v.contents.putText(k(), h, e.body === void 0 ? e : {
140
149
  ...e,
141
- body: Z(e.body)
150
+ body: Q(e.body)
142
151
  })), [
143
- y,
144
- D,
152
+ v,
153
+ O,
154
+ k,
155
+ h,
156
+ Q
157
+ ]), ce = u((e) => O(() => v.contents.publish(k(), e)), [
158
+ v,
159
+ O,
160
+ k
161
+ ]), le = u(() => O(() => v.contents.unpublish(k())), [
162
+ v,
163
+ O,
164
+ k
165
+ ]), ue = u(() => O(() => v.contents.remove(k())), [
166
+ v,
167
+ O,
168
+ k
169
+ ]), de = u(() => O(() => v.contents.restore(k())), [
170
+ v,
145
171
  O,
146
- g,
147
- Z
148
- ]), $ = d((e) => D(() => y.contents.publish(O(), e)), [
149
- y,
150
- D,
151
- O
152
- ]), de = d(() => D(() => y.contents.unpublish(O())), [
153
- y,
154
- D,
155
- O
156
- ]), fe = d(() => D(() => y.contents.remove(O())), [
157
- y,
158
- D,
159
- O
160
- ]), pe = d(() => D(() => y.contents.restore(O())), [
161
- y,
162
- D,
163
- O
164
- ]), me = d((e) => D(async () => {
165
- if (!e) return await y.contents.setCover(O(), null), null;
166
- let t = await y.media.uploadNamed({
172
+ k
173
+ ]), fe = u((e) => O(async () => {
174
+ if (!e) return await v.contents.setCover(k(), F(), null), null;
175
+ let t = {
167
176
  kind: i,
168
- id: O()
169
- }, e), n = await y.contents.setCover(O(), t.name), r = Q(t.name, e) ?? n.cover?.url ?? null;
170
- return r && Y.current.set(r, t.name), r;
177
+ id: k(),
178
+ version: F()
179
+ }, n = await v.media.uploadNamed(t, e, { path: await v.media.presetPath(i, "cover", e) }), r = await v.contents.setCover(t.id, t.version, n.name), a = $(n.name, e) ?? r.cover?.url ?? null;
180
+ return a && X.current.set(a, n.name), a;
171
181
  }), [
172
- y,
173
- D,
182
+ v,
174
183
  O,
184
+ k,
185
+ F,
175
186
  i,
176
- Q
177
- ]), he = d((e) => D(async () => {
178
- let t = await y.media.uploadInline({
179
- kind: i + s,
180
- id: O()
181
- }, e), n = Q(t.name, e) ?? t.url ?? t.ref;
182
- return Y.current.set(n, t.name), n;
187
+ $
188
+ ]), pe = u((e) => O(async () => {
189
+ let t = await v.media.uploadInline({
190
+ kind: i,
191
+ id: k(),
192
+ version: F()
193
+ }, e), n = $(t.name, e) ?? t.url ?? t.ref;
194
+ return X.current.set(n, t.name), n;
183
195
  }), [
184
- y,
185
- D,
196
+ v,
186
197
  O,
198
+ k,
199
+ F,
187
200
  i,
188
- Q
201
+ $
189
202
  ]);
190
203
  return {
191
- content: w,
192
- reload: C.reload,
193
- loading: !!S && (C.loading || !C.loaded && v.initial === void 0),
194
- error: C.error,
195
- saving: ie > 0,
196
- create: ce,
197
- update: le,
198
- putText: ue,
199
- publish: $,
200
- unpublish: de,
201
- remove: fe,
202
- restore: pe,
203
- setCover: me,
204
- uploadImage: he,
205
- imageSrc: X,
206
- coverSrc: X(j?.image),
207
- text: se,
208
- storedBody: Z
204
+ content: T,
205
+ reload: w.reload,
206
+ loading: !!C && (w.loading || !w.loaded && _.initial === void 0),
207
+ error: w.error,
208
+ saving: ne > 0,
209
+ create: ae,
210
+ update: oe,
211
+ putText: se,
212
+ publish: ce,
213
+ unpublish: le,
214
+ remove: ue,
215
+ restore: de,
216
+ version: M,
217
+ setCover: fe,
218
+ uploadImage: pe,
219
+ imageSrc: Z,
220
+ coverSrc: P?.image ? Z(P.image) : P?.url ?? void 0,
221
+ text: ie,
222
+ storedBody: Q
209
223
  };
210
224
  }
211
225
  //#endregion
212
- export { v as useContent, g as useManagedContents };
226
+ export { _ as useContent, h as useManagedContents };
213
227
 
214
228
  //# sourceMappingURL=contents.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"contents.js","names":[],"sources":["../../src/react/contents.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ContentKitClient } from \"../client/client.js\";\nimport type { ContentKitError } from \"../client/errors.js\";\nimport type { CatalogText, Content, ContentInput, ContentPatch } from \"../client/generated/wire.js\";\nimport { BODY_SUFFIX, IMAGE_SCHEME, imageRef, imageRefs, type ManageQuery } from \"../client/contents.js\";\nimport { useMediaRead } from \"./read.js\";\nimport { useGuarded } from \"./context.js\";\nimport { keyOf, offsetPages, useContentScope, useList, useResource, type UseList } from \"./use-resource.js\";\n\nexport interface ManageFilter extends Omit<ManageQuery, \"limit\" | \"offset\"> {\n pageSize?: number;\n}\n\n/** The content items the caller manages, newest first, a page at a time. */\nexport function useManagedContents(f: ManageFilter = {}, o: { client?: ContentKitClient } = {}): UseList<Content> {\n const { client, store, scope } = useContentScope(o.client);\n const { pageSize, ...q } = f;\n const size = pageSize ?? 20;\n return useList(\n store,\n keyOf(\"contents\", scope, q.kind, q.state, q.owner_group, q.q, q.language, size),\n { type: \"contents\", scope: q.state === \"deleted\" ? \"deleted\" : undefined },\n offsetPages(size, (page, signal) => client.contents.manage({ ...q, ...page }, signal)),\n );\n}\n\nexport interface UseContent {\n /** null before create (or while loading). */\n content: Content | null;\n loading: boolean;\n error?: ContentKitError;\n /** Writes in flight. */\n saving: boolean;\n /** Reads the item again. */\n reload: () => void;\n /** Creates the item as a draft; the hook then edits it. */\n create: (input: ContentInput) => Promise<Content>;\n update: (patch: ContentPatch) => Promise<Content>;\n /** Sets the text in the hook's language; a body from the editor is stored with image references (storedBody). */\n putText: (text: CatalogText) => Promise<Content>;\n /** Publishes now, or schedules for at. */\n publish: (at?: string) => Promise<Content>;\n unpublish: () => Promise<Content>;\n remove: () => Promise<void>;\n restore: () => Promise<Content>;\n /** Uploads the cover (null clears it); resolves with a URL that shows it now. */\n setCover: (file: Blob | null) => Promise<string | null>;\n /** Uploads an image for the body; resolves with a URL that shows it now, to place in the editor. */\n uploadImage: (file: Blob) => Promise<string>;\n /**\n * A URL that shows one of the item's images now, by name (\"i-{uuid}\") or\n * reference: a fresh upload from its file, else its public file\n * (`content.images`), else, while it has none (an unpublished item's), its\n * signed editor view from an editor read. Anything else is returned as is.\n */\n imageSrc: (image: string | null | undefined) => string | undefined;\n /** The cover through imageSrc. */\n coverSrc: string | undefined;\n /** The language's stored text, its body's images through imageSrc: what an editor shows. */\n text: CatalogText | undefined;\n /** HTML from the editor with every image URL this hook showed turned back into the image's reference. */\n storedBody: (html: string) => string;\n}\n\n/** The names of the images a body references, once each. */\nconst refNames = (body: string | undefined) => [...new Set([...(body ?? \"\").matchAll(imageRefs())].map((m) => m[1]!))];\nconst uploadName = (path: string) => {\n const base = path.slice(path.lastIndexOf(\"/\") + 1);\n const dot = base.lastIndexOf(\".\");\n return dot > 0 ? base.slice(0, dot) : base;\n};\n\n/**\n * One content item of kind for its editors: read, create, text in language,\n * publish, delete, restore, cover and body images. null creates a new item.\n */\nexport function useContent(id: string | null | undefined, kind: string, language: string, o: { initial?: Content; client?: ContentKitClient } = {}): UseContent {\n const { client, store, scope } = useContentScope(o.client);\n const [created, setCreated] = useState<string | null>(null);\n const cid = id ?? created;\n const key = cid ? keyOf(\"content\", scope, cid) : null;\n const r = useResource<Content | null>(store, key, { type: \"content\", id: cid ?? undefined }, (s) => client.contents.get(cid!, language, s), { initial: o.initial });\n const content = r.data ?? null;\n const [inflight, setInflight] = useState(0);\n const guarded = useGuarded();\n const run = useCallback(async <T>(fn: () => Promise<T>): Promise<T> => {\n setInflight((n) => n + 1);\n try {\n return await guarded(fn);\n } finally {\n setInflight((n) => n - 1);\n }\n }, [guarded]);\n const need = useCallback(() => {\n if (!cid) throw new Error(\"contentkit-ui: create the item first\");\n return cid;\n }, [cid]);\n const stored = content?.text?.[language];\n const body = stored?.body;\n const cover = content?.cover;\n\n // Images: fresh uploads show from their file, published ones from\n // content.images, the rest (an unpublished item's) from an editor read.\n const [previews, setPreviews] = useState<ReadonlyMap<string, string>>(new Map());\n const blobs = useRef<string[]>([]);\n useEffect(() => {\n const urls = blobs.current;\n return () => {\n for (const u of urls) URL.revokeObjectURL(u);\n };\n }, []);\n const published = useMemo(() => new Map(Object.entries(content?.images ?? {})), [content?.images]);\n // The cover is the item's folder's; body images are its body folder's ({kind}.body).\n const coverPending = !!cover && !cover.url && !previews.has(cover.image) && !published.has(cover.image);\n const bodyPending = useMemo(() => refNames(body).filter((n) => !previews.has(n) && !published.has(n)), [body, previews, published]);\n const pending = useMemo(() => (coverPending ? [...bodyPending, cover!.image] : bodyPending), [coverPending, bodyPending, cover]);\n const folder = useMemo(() => ({ kind, id: cid ?? \"none\" }), [kind, cid]);\n const bodyFolder = useMemo(() => ({ kind: kind + BODY_SUFFIX, id: cid ?? \"none\" }), [kind, cid]);\n const coverRead = useMediaRead(folder, { editor: true, read: coverPending ? undefined : null, client });\n const bodyRead = useMediaRead(bodyFolder, { editor: true, read: bodyPending.length ? undefined : null, client });\n const files = useMemo(() => [...(coverRead.read?.files ?? []), ...(bodyRead.read?.files ?? [])], [coverRead.read, bodyRead.read]);\n const views = useMemo(() => {\n const out = new Map<string, string>();\n for (const f of files) if (f.upload && f.editor_url) out.set(uploadName(f.path), f.editor_url);\n return out;\n }, [files]);\n // Editor views render on the first editor read that misses them: read again, backing off.\n const failed = (n: string) => files.some((f) => f.failed && uploadName(f.path) === n);\n const missing = (!!coverRead.read || !!bodyRead.read) && pending.some((n) => !views.has(n) && !failed(n));\n const tries = useRef(0);\n const reloadCover = coverRead.reload;\n const reloadBody = bodyRead.reload;\n const reload = useCallback(() => {\n reloadCover();\n reloadBody();\n }, [reloadCover, reloadBody]);\n useEffect(() => {\n if (!missing) {\n tries.current = 0;\n return;\n }\n if (tries.current >= 6) return;\n const t = setTimeout(() => {\n tries.current++;\n reload();\n }, 1000 * 2 ** tries.current);\n return () => clearTimeout(t);\n }, [missing, files, reload]);\n\n // Every URL shown for an image, of this and earlier reads, back to its name.\n const shown = useRef(new Map<string, string>());\n useEffect(() => {\n for (const m of [previews, published, views]) for (const [n, u] of m) shown.current.set(u, n);\n }, [previews, published, views]);\n\n const imageSrc = useCallback(\n (image: string | null | undefined) => {\n if (!image) return undefined;\n const n = image.startsWith(IMAGE_SCHEME) ? image.slice(IMAGE_SCHEME.length) : image;\n return previews.get(n) ?? published.get(n) ?? views.get(n) ?? image;\n },\n [previews, published, views],\n );\n const text = useMemo(\n () => (stored ? { ...stored, body: (stored.body ?? \"\").replace(imageRefs(), (ref, n: string) => previews.get(n) ?? published.get(n) ?? views.get(n) ?? ref) } : undefined),\n [stored, previews, published, views],\n );\n const storedBody = useCallback(\n (html: string) => {\n const back = new Map(shown.current);\n for (const m of [previews, published, views]) for (const [n, u] of m) back.set(u, n);\n let out = html;\n for (const [u, n] of back) out = out.split(u).join(imageRef(n)).split(u.replaceAll(\"&\", \"&amp;\")).join(imageRef(n));\n return out;\n },\n [previews, published, views],\n );\n const preview = useCallback((name: string, file: Blob): string | undefined => {\n if (typeof URL.createObjectURL !== \"function\") return undefined;\n const url = URL.createObjectURL(file);\n blobs.current.push(url);\n setPreviews((m) => new Map(m).set(name, url));\n return url;\n }, []);\n\n const create = useCallback(\n (input: ContentInput) =>\n run(async () => {\n const c = await client.contents.create(input);\n setCreated(c.id);\n return c;\n }),\n [client, run],\n );\n const update = useCallback((patch: ContentPatch) => run(() => client.contents.update(need(), patch)), [client, run, need]);\n const putText = useCallback(\n (t: CatalogText) => run(() => client.contents.putText(need(), language, t.body === undefined ? t : { ...t, body: storedBody(t.body) })),\n [client, run, need, language, storedBody],\n );\n const publish = useCallback((at?: string) => run(() => client.contents.publish(need(), at)), [client, run, need]);\n const unpublish = useCallback(() => run(() => client.contents.unpublish(need())), [client, run, need]);\n const remove = useCallback(() => run(() => client.contents.remove(need())), [client, run, need]);\n const restore = useCallback(() => run(() => client.contents.restore(need())), [client, run, need]);\n const setCover = useCallback(\n (file: Blob | null) =>\n run(async () => {\n if (!file) {\n await client.contents.setCover(need(), null);\n return null;\n }\n const up = await client.media.uploadNamed({ kind, id: need() }, file);\n const saved = await client.contents.setCover(need(), up.name);\n const url = preview(up.name, file) ?? saved.cover?.url ?? null;\n if (url) shown.current.set(url, up.name);\n return url;\n }),\n [client, run, need, kind, preview],\n );\n const uploadImage = useCallback(\n (file: Blob) =>\n run(async () => {\n const up = await client.media.uploadInline({ kind: kind + BODY_SUFFIX, id: need() }, file);\n const url = preview(up.name, file) ?? up.url ?? up.ref;\n shown.current.set(url, up.name);\n return url;\n }),\n [client, run, need, kind, preview],\n );\n return {\n content,\n reload: r.reload,\n loading: !!key && (r.loading || (!r.loaded && o.initial === undefined)),\n error: r.error,\n saving: inflight > 0,\n create,\n update,\n putText,\n publish,\n unpublish,\n remove,\n restore,\n setCover,\n uploadImage,\n imageSrc,\n coverSrc: imageSrc(cover?.image),\n text,\n storedBody,\n };\n}\n"],"mappings":";;;;;;AAcA,SAAgB,EAAmB,IAAkB,CAAC,GAAG,IAAmC,CAAC,GAAqB;CAChH,IAAM,EAAE,WAAQ,UAAO,aAAU,EAAgB,EAAE,MAAM,GACnD,EAAE,aAAU,GAAG,MAAM,GACrB,IAAO,KAAY;CACzB,OAAO,EACL,GACA,EAAM,YAAY,GAAO,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,GAAG,EAAE,UAAU,CAAI,GAC9E;EAAE,MAAM;EAAY,OAAO,EAAE,UAAU,YAAY,YAAY,KAAA;CAAU,GACzE,EAAY,IAAO,GAAM,MAAW,EAAO,SAAS,OAAO;EAAE,GAAG;EAAG,GAAG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AAQ;EAAK;EAAM;EAAM;CAAO,CACnC;CACA,OAAO;EACL;EACA,QAAQ,EAAE;EACV,SAAS,CAAC,CAAC,MAAQ,EAAE,WAAY,CAAC,EAAE,UAAU,EAAE,YAAY,KAAA;EAC5D,OAAO,EAAE;EACT,QAAQ,KAAW;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU,EAAS,GAAO,KAAK;EAC/B;EACA;CACF;AACF"}
1
+ {"version":3,"file":"contents.js","names":[],"sources":["../../src/react/contents.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ContentKitClient } from \"../client/client.js\";\nimport type { ContentKitError } from \"../client/errors.js\";\nimport type { CatalogText, Content, ContentInput, ContentPatch, Version } from \"../client/generated/wire.js\";\nimport { IMAGE_SCHEME, imageRef, imageRefs, type ManageQuery } from \"../client/contents.js\";\nimport { useMediaRead } from \"./read.js\";\nimport { useGuarded } from \"./context.js\";\nimport { keyOf, offsetPages, useContentScope, useList, useResource, type UseList } from \"./use-resource.js\";\n\nexport interface ManageFilter extends Omit<ManageQuery, \"limit\" | \"offset\"> {\n pageSize?: number;\n}\n\n/** The content items the caller manages, newest first, a page at a time. */\nexport function useManagedContents(f: ManageFilter = {}, o: { client?: ContentKitClient } = {}): UseList<Content> {\n const { client, store, scope } = useContentScope(o.client);\n const { pageSize, ...q } = f;\n const size = pageSize ?? 20;\n return useList(\n store,\n keyOf(\"contents\", scope, q.kind, q.state, q.owner_group, q.q, q.language, size),\n { type: \"contents\", scope: q.state === \"deleted\" ? \"deleted\" : undefined },\n offsetPages(size, (page, signal) => client.contents.manage({ ...q, ...page }, signal)),\n );\n}\n\nexport interface UseContent {\n /** null before create (or while loading). */\n content: Content | null;\n loading: boolean;\n error?: ContentKitError;\n /** Writes in flight. */\n saving: boolean;\n /** Reads the item again. */\n reload: () => void;\n /** Creates the item as a draft; the hook then edits it. */\n create: (input: ContentInput) => Promise<Content>;\n update: (patch: ContentPatch) => Promise<Content>;\n /** Sets the text in the hook's language; a body from the editor is stored with image references (storedBody). */\n putText: (text: CatalogText) => Promise<Content>;\n /** Publishes now, or schedules for at. */\n publish: (at?: string) => Promise<Content>;\n unpublish: () => Promise<Content>;\n remove: () => Promise<void>;\n restore: () => Promise<Content>;\n /**\n * The version whose cover and body images the hook edits: the one asked\n * for, else the first. Every version has its own cover and its own copy of\n * the body's images.\n */\n version: Version | null;\n /** Uploads the version's cover (null returns to its first upload); resolves with a URL that shows it now. */\n setCover: (file: Blob | null) => Promise<string | null>;\n /** Uploads an image for the body into the version, copied into the others; resolves with a URL that shows it now, to place in the editor. */\n uploadImage: (file: Blob) => Promise<string>;\n /**\n * A URL that shows one of the item's images now, by name (\"i-{uuid}\") or\n * reference: a fresh upload from its file, else its public file\n * (`content.images`), else, while it has none (an unpublished item's), its\n * signed editor view from an editor read. Anything else is returned as is.\n */\n imageSrc: (image: string | null | undefined) => string | undefined;\n /** The version's cover through imageSrc. */\n coverSrc: string | undefined;\n /** The language's stored text, its body's images through imageSrc: what an editor shows. */\n text: CatalogText | undefined;\n /** HTML from the editor with every image URL this hook showed turned back into the image's reference. */\n storedBody: (html: string) => string;\n}\n\n/** The names of the images a body references, once each. */\nconst refNames = (body: string | undefined) => [...new Set([...(body ?? \"\").matchAll(imageRefs())].map((m) => m[1]!))];\nconst uploadName = (path: string) => {\n const base = path.slice(path.lastIndexOf(\"/\") + 1);\n const dot = base.lastIndexOf(\".\");\n return dot > 0 ? base.slice(0, dot) : base;\n};\n\n/**\n * One content item of kind for its editors: read, create, text in language,\n * publish, delete, restore, a version's cover and the body's images. null\n * creates a new item.\n */\nexport function useContent(\n id: string | null | undefined,\n kind: string,\n language: string,\n o: { initial?: Content; client?: ContentKitClient; version?: string } = {},\n): UseContent {\n const { client, store, scope } = useContentScope(o.client);\n const [created, setCreated] = useState<string | null>(null);\n const cid = id ?? created;\n const key = cid ? keyOf(\"content\", scope, cid) : null;\n const r = useResource<Content | null>(store, key, { type: \"content\", id: cid ?? undefined }, (s) => client.contents.get(cid!, language, s), { initial: o.initial });\n const content = r.data ?? null;\n const [inflight, setInflight] = useState(0);\n const guarded = useGuarded();\n const run = useCallback(async <T>(fn: () => Promise<T>): Promise<T> => {\n setInflight((n) => n + 1);\n try {\n return await guarded(fn);\n } finally {\n setInflight((n) => n - 1);\n }\n }, [guarded]);\n const need = useCallback(() => {\n if (!cid) throw new Error(\"contentkit-ui: create the item first\");\n return cid;\n }, [cid]);\n const stored = content?.text?.[language];\n const body = stored?.body;\n const version = useMemo(() => {\n const vs = [...(content?.versions ?? [])].sort((a, b) => a.position - b.position);\n return vs.find((v) => v.id === o.version) ?? vs[0] ?? null;\n }, [content?.versions, o.version]);\n const vid = version?.id;\n const cover = version?.cover;\n const needVersion = useCallback(() => {\n if (!vid) throw new Error(\"contentkit-ui: the item has no version yet\");\n return vid;\n }, [vid]);\n\n // Images: fresh uploads show from their file, published ones from\n // content.images, the rest (an unpublished item's) from an editor read.\n const [previews, setPreviews] = useState<ReadonlyMap<string, string>>(new Map());\n const blobs = useRef<string[]>([]);\n useEffect(() => {\n const urls = blobs.current;\n return () => {\n for (const u of urls) URL.revokeObjectURL(u);\n };\n }, []);\n const published = useMemo(() => {\n const out = new Map(Object.entries(content?.images ?? {}));\n if (cover?.image && cover.url) out.set(cover.image, cover.url);\n return out;\n }, [content?.images, cover?.image, cover?.url]);\n // The cover and the body's images are the version's.\n const coverPending = !!cover?.image && !cover.url && !previews.has(cover.image) && !published.has(cover.image);\n const bodyPending = useMemo(() => refNames(body).filter((n) => !previews.has(n) && !published.has(n)), [body, previews, published]);\n const pending = useMemo(() => (coverPending ? [...bodyPending, cover!.image!] : bodyPending), [coverPending, bodyPending, cover]);\n const folder = useMemo(() => ({ kind, id: cid ?? \"none\", version: vid }), [kind, cid, vid]);\n const folderRead = useMediaRead(folder, { editor: true, read: pending.length && vid ? undefined : null, client });\n const files = useMemo(() => folderRead.read?.files ?? [], [folderRead.read]);\n const views = useMemo(() => {\n const out = new Map<string, string>();\n for (const f of files) if (f.upload && f.editor_url) out.set(uploadName(f.path), f.editor_url);\n return out;\n }, [files]);\n // Editor views render on the first editor read that misses them: read again, backing off.\n const failed = (n: string) => files.some((f) => f.failed && uploadName(f.path) === n);\n const missing = !!folderRead.read && pending.some((n) => !views.has(n) && !failed(n));\n const tries = useRef(0);\n const reload = folderRead.reload;\n useEffect(() => {\n if (!missing) {\n tries.current = 0;\n return;\n }\n if (tries.current >= 6) return;\n const t = setTimeout(() => {\n tries.current++;\n reload();\n }, 1000 * 2 ** tries.current);\n return () => clearTimeout(t);\n }, [missing, files, reload]);\n\n // Every URL shown for an image, of this and earlier reads, back to its name.\n const shown = useRef(new Map<string, string>());\n useEffect(() => {\n for (const m of [previews, published, views]) for (const [n, u] of m) shown.current.set(u, n);\n }, [previews, published, views]);\n\n const imageSrc = useCallback(\n (image: string | null | undefined) => {\n if (!image) return undefined;\n const n = image.startsWith(IMAGE_SCHEME) ? image.slice(IMAGE_SCHEME.length) : image;\n return previews.get(n) ?? published.get(n) ?? views.get(n) ?? image;\n },\n [previews, published, views],\n );\n const text = useMemo(\n () => (stored ? { ...stored, body: (stored.body ?? \"\").replace(imageRefs(), (ref, n: string) => previews.get(n) ?? published.get(n) ?? views.get(n) ?? ref) } : undefined),\n [stored, previews, published, views],\n );\n const storedBody = useCallback(\n (html: string) => {\n const back = new Map(shown.current);\n for (const m of [previews, published, views]) for (const [n, u] of m) back.set(u, n);\n let out = html;\n for (const [u, n] of back) out = out.split(u).join(imageRef(n)).split(u.replaceAll(\"&\", \"&amp;\")).join(imageRef(n));\n return out;\n },\n [previews, published, views],\n );\n const preview = useCallback((name: string, file: Blob): string | undefined => {\n if (typeof URL.createObjectURL !== \"function\") return undefined;\n const url = URL.createObjectURL(file);\n blobs.current.push(url);\n setPreviews((m) => new Map(m).set(name, url));\n return url;\n }, []);\n\n const create = useCallback(\n (input: ContentInput) =>\n run(async () => {\n const c = await client.contents.create(input);\n setCreated(c.id);\n return c;\n }),\n [client, run],\n );\n const update = useCallback((patch: ContentPatch) => run(() => client.contents.update(need(), patch)), [client, run, need]);\n const putText = useCallback(\n (t: CatalogText) => run(() => client.contents.putText(need(), language, t.body === undefined ? t : { ...t, body: storedBody(t.body) })),\n [client, run, need, language, storedBody],\n );\n const publish = useCallback((at?: string) => run(() => client.contents.publish(need(), at)), [client, run, need]);\n const unpublish = useCallback(() => run(() => client.contents.unpublish(need())), [client, run, need]);\n const remove = useCallback(() => run(() => client.contents.remove(need())), [client, run, need]);\n const restore = useCallback(() => run(() => client.contents.restore(need())), [client, run, need]);\n const setCover = useCallback(\n (file: Blob | null) =>\n run(async () => {\n if (!file) {\n await client.contents.setCover(need(), needVersion(), null);\n return null;\n }\n const ref = { kind, id: need(), version: needVersion() };\n const up = await client.media.uploadNamed(ref, file, { path: await client.media.presetPath(kind, \"cover\", file) });\n const saved = await client.contents.setCover(ref.id, ref.version, up.name);\n const url = preview(up.name, file) ?? saved.cover?.url ?? null;\n if (url) shown.current.set(url, up.name);\n return url;\n }),\n [client, run, need, needVersion, kind, preview],\n );\n const uploadImage = useCallback(\n (file: Blob) =>\n run(async () => {\n const up = await client.media.uploadInline({ kind, id: need(), version: needVersion() }, file);\n const url = preview(up.name, file) ?? up.url ?? up.ref;\n shown.current.set(url, up.name);\n return url;\n }),\n [client, run, need, needVersion, kind, preview],\n );\n return {\n content,\n reload: r.reload,\n loading: !!key && (r.loading || (!r.loaded && o.initial === undefined)),\n error: r.error,\n saving: inflight > 0,\n create,\n update,\n putText,\n publish,\n unpublish,\n remove,\n restore,\n version,\n setCover,\n uploadImage,\n imageSrc,\n coverSrc: cover?.image ? imageSrc(cover.image) : (cover?.url ?? undefined),\n text,\n storedBody,\n };\n}\n"],"mappings":";;;;;;AAcA,SAAgB,EAAmB,IAAkB,CAAC,GAAG,IAAmC,CAAC,GAAqB;CAChH,IAAM,EAAE,WAAQ,UAAO,aAAU,EAAgB,EAAE,MAAM,GACnD,EAAE,aAAU,G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,SAAS,CAAI,EAAE,CAAC,GAC3G,IAAQ,MAAM,EAAO,SAAS,SAAS,EAAI,IAAI,EAAI,SAAS,EAAG,IAAI,GACnE,IAAM,EAAQ,EAAG,MAAM,CAAI,KAAK,EAAM,OAAO,OAAO;EAE1D,OADI,KAAK,EAAM,QAAQ,IAAI,GAAK,EAAG,IAAI,GAChC;CACT,CAAC,GACH;EAAC;EAAQ;EAAK;EAAM;EAAa;EAAM;CAAO,CAChD,GACM,KAAc,GACjB,MACC,EAAI,YAAY;EACd,IAAM,IAAK,MAAM,EAAO,MAAM,aAAa;GAAE;GAAM,IAAI,EAAK;GAAG,SAAS,EAAY;EAAE,GAAG,CAAI,GACvF,IAAM,EAAQ,EAAG,MAAM,CAAI,KAAK,EAAG,OAAO,EAAG;EAEnD,OADA,EAAM,QAAQ,IAAI,GAAK,EAAG,IAAI,GACvB;CACT,CAAC,GACH;EAAC;EAAQ;EAAK;EAAM;EAAa;EAAM;CAAO,CAChD;CACA,OAAO;EACL;EACA,QAAQ,EAAE;EACV,SAAS,CAAC,CAAC,MAAQ,EAAE,WAAY,CAAC,EAAE,UAAU,EAAE,YAAY,KAAA;EAC5D,OAAO,EAAE;EACT,QAAQ,KAAW;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU,GAAO,QAAQ,EAAS,EAAM,KAAK,IAAK,GAAO,OAAO,KAAA;EAChE;EACA;CACF;AACF"}
@@ -3,7 +3,7 @@ import { ContentKitError } from '../client/errors.js';
3
3
  import { ContentURLs } from '../urls/index.js';
4
4
  import { ReadStore } from './store.js';
5
5
  /** What failed: a component's or hook's save, load or render step. */
6
- export type ContentKitOperation = "poster.load" | "poster.frame" | "poster.save" | "slot.load" | "slot.decode" | "slot.save" | "slot.remove" | "upload" | "folder.load" | "folder.commit" | "folder.update" | "folder.process" | "crop.load" | "crop.save" | SocialOperation;
6
+ export type ContentKitOperation = "poster.load" | "poster.frame" | "poster.save" | "slot.load" | "slot.decode" | "slot.save" | "slot.remove" | "upload" | "folder.load" | "folder.commit" | "folder.update" | "folder.process" | "crop.load" | "crop.save" | "version.download" | SocialOperation;
7
7
  /** What failed in a content component: a load or a write. */
8
8
  export type SocialOperation = "comment.load" | "comment.post" | "comment.edit" | "comment.delete" | "comment.react" | "comment.restore" | "ban.save" | "ban.lift" | "reaction.save" | "favorite.save" | "poll.load" | "poll.vote" | "poll.answer" | "poll.save" | "post.load" | "content.save" | "moderation.load" | "moderation.resolve" | "rules.save" | "reader.save" | "media.save" | "notifications.load" | "notifications.read" | "notifications.dismiss" | "group.load" | "group.save" | "membership.save" | "history.forget" | "filters.save" | "offer.save" | "membership.join";
9
9
  /** The failure's context: the operation and, for one file, its name. */
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../src/react/context.ts"],"sourcesContent":["import { createContext, useCallback, useContext, useLayoutEffect, useRef } from \"react\";\nimport type { ContentKitClient } from \"../client/client.js\";\nimport { toContentKitError, type ContentKitError } from \"../client/errors.js\";\nimport type { ContentURLs } from \"../urls/index.js\";\nimport type { ReadStore } from \"./store.js\";\n\n/** What failed: a component's or hook's save, load or render step. */\nexport type ContentKitOperation =\n | \"poster.load\"\n | \"poster.frame\"\n | \"poster.save\"\n | \"slot.load\"\n | \"slot.decode\"\n | \"slot.save\"\n | \"slot.remove\"\n | \"upload\"\n | \"folder.load\"\n | \"folder.commit\"\n | \"folder.update\"\n | \"folder.process\"\n | \"crop.load\"\n | \"crop.save\"\n | SocialOperation;\n\n/** What failed in a content component: a load or a write. */\nexport type SocialOperation =\n | \"comment.load\"\n | \"comment.post\"\n | \"comment.edit\"\n | \"comment.delete\"\n | \"comment.react\"\n | \"comment.restore\"\n | \"ban.save\"\n | \"ban.lift\"\n | \"reaction.save\"\n | \"favorite.save\"\n | \"poll.load\"\n | \"poll.vote\"\n | \"poll.answer\"\n | \"poll.save\"\n | \"post.load\"\n | \"content.save\"\n | \"moderation.load\"\n | \"moderation.resolve\"\n | \"rules.save\"\n | \"reader.save\"\n | \"media.save\"\n | \"notifications.load\"\n | \"notifications.read\"\n | \"notifications.dismiss\"\n | \"group.load\"\n | \"group.save\"\n | \"membership.save\"\n | \"history.forget\"\n | \"filters.save\"\n | \"offer.save\"\n | \"membership.join\";\n\n/** The failure's context: the operation and, for one file, its name. */\nexport interface ContentKitErrorInfo {\n operation: ContentKitOperation;\n file?: string;\n}\n\n/**\n * Every failure a component shows is also reported here (aborts excepted), so\n * the host can toast or log it. Components still show it in place.\n */\nexport type ContentKitErrorHandler = (error: ContentKitError, info: ContentKitErrorInfo) => void;\n\n/** The host router: in-app navigation, e.g. a canonical replace. */\nexport type Navigate = (to: string, options?: { replace?: boolean }) => void;\n\nexport interface ContentKitContextValue {\n client: ContentKitClient;\n /**\n * The signed-in user's id as ContentKit sees it, null when signed out,\n * undefined when the host does not say. Content reads are kept per viewer.\n */\n viewer?: string | null;\n /** Request language; keep it in sync with the client's language callback. */\n language?: string;\n /** Change when the current viewer's permissions or entitlements change. */\n accessRevision?: string | number;\n readScope: string;\n /** Asks the visitor to sign in; with it, signed-out visitors are prompted instead of acting anonymously. */\n onSignIn?: () => void;\n /** The host's content URL config (createContentURLs). */\n urls?: ContentURLs;\n navigate?: Navigate;\n onError?: ContentKitErrorHandler;\n /** The reads hooks share. */\n store: ReadStore;\n}\n\nexport const ContentKitContext = createContext<ContentKitContextValue | null>(null);\n\n/** Values that can change a read without changing its content reference. */\nexport function useReadScope(): string {\n return useContext(ContentKitContext)?.readScope ?? \"{}\";\n}\n\n/** The ContentKitProvider's value; throws outside one. */\nexport function useContentKit(): ContentKitContextValue {\n const ctx = useContext(ContentKitContext);\n if (!ctx) throw new Error(\"contentkit-ui: wrap the tree in <ContentKitProvider client>\");\n return ctx;\n}\n\n/** The client a hook or component uses: its own, else the provider's; throws without either. */\nexport function useContentKitClient(own?: ContentKitClient | null): ContentKitClient {\n const c = useOptionalContentKitClient(own);\n if (!c) throw new Error(\"contentkit-ui: pass `client` or render inside <ContentKitProvider client>\");\n return c;\n}\n\nexport function useOptionalContentKitClient(own?: ContentKitClient | null): ContentKitClient | null {\n const ctx = useContext(ContentKitContext);\n const client = own ?? ctx?.client ?? null;\n const scope = useReadScope();\n useLayoutEffect(() => { client?.setReadScope(scope); }, [client, scope]);\n return client;\n}\n\n/** The provider's content URL helpers; throws when none were given. */\nexport function useContentURLs(): ContentURLs {\n const urls = useContext(ContentKitContext)?.urls;\n if (!urls) throw new Error(\"contentkit-ui: pass `urls` to <ContentKitProvider>\");\n return urls;\n}\n\n/** A stable reporter: the component's own `onError`, else the provider's. */\nexport function useErrorReporter(own?: ContentKitErrorHandler): (e: unknown, operation: ContentKitOperation, file?: string) => void {\n const ctx = useContext(ContentKitContext)?.onError;\n const handler = useRef(own ?? ctx);\n handler.current = own ?? ctx;\n return useCallback((e: unknown, operation: ContentKitOperation, file?: string) => {\n const error = toContentKitError(e);\n if (error.code !== \"aborted\") handler.current?.(error, file === undefined ? { operation } : { operation, file });\n }, []);\n}\n\n/** Runs a write, e.g. auth-ui's useStepUpGuard(): re-authenticates when the write asks for a recent sign-in, then retries. */\nexport type ContentKitGuard = <T>(write: () => Promise<T>) => Promise<T>;\n\n/** The admin flow's guard; hooks run their writes through it. */\nexport const GuardContext = createContext<ContentKitGuard | undefined>(undefined);\n\n/** Runs fn through the flow's guard, when the host gave one. */\nexport function useGuarded(): <T>(fn: () => Promise<T>) => Promise<T> {\n const guard = useContext(GuardContext);\n return useCallback(<T,>(fn: () => Promise<T>) => (guard ? guard(fn) : fn()), [guard]);\n}\n"],"mappings":";;;AA+FA,IAAa,IAAoB,EAA6C,IAAI;AAGlF,SAAgB,IAAuB;CACrC,OAAO,EAAW,CAAiB,CAAC,EAAE,aAAa;AACrD;AAGA,SAAgB,IAAwC;CACtD,IAAM,IAAM,EAAW,CAAiB;CACxC,IAAI,CAAC,GAAK,MAAU,MAAM,6DAA6D;CACvF,OAAO;AACT;AAGA,SAAgB,EAAoB,GAAiD;CACnF,IAAM,IAAI,EAA4B,CAAG;CACzC,IAAI,CAAC,GAAG,MAAU,MAAM,2EAA2E;CACnG,OAAO;AACT;AAEA,SAAgB,EAA4B,GAAwD;CAClG,IAAM,IAAM,EAAW,CAAiB,GAClC,IAAS,KAAO,GAAK,UAAU,MAC/B,IAAQ,EAAa;CAE3B,OADA,QAAsB;EAAE,GAAQ,aAAa,CAAK;CAAG,GAAG,CAAC,GAAQ,CAAK,CAAC,GAChE;AACT;AAGA,SAAgB,IAA8B;CAC5C,IAAM,IAAO,EAAW,CAAiB,CAAC,EAAE;CAC5C,IAAI,CAAC,GAAM,MAAU,MAAM,oDAAoD;CAC/E,OAAO;AACT;AAGA,SAAgB,EAAiB,GAAmG;CAClI,IAAM,IAAM,EAAW,CAAiB,CAAC,EAAE,SACrC,IAAU,EAAO,KAAO,CAAG;CAEjC,OADA,EAAQ,UAAU,KAAO,GAClB,GAAa,GAAY,GAAgC,MAAkB;EAChF,IAAM,IAAQ,EAAkB,CAAC;EACjC,AAAI,EAAM,SAAS,aAAW,EAAQ,UAAU,GAAO,MAAS,KAAA,IAAY,EAAE,aAAU,IAAI;GAAE;GAAW;EAAK,CAAC;CACjH,GAAG,CAAC,CAAC;AACP;AAMA,IAAa,IAAe,EAA2C,KAAA,CAAS;AAGhF,SAAgB,IAAsD;CACpE,IAAM,IAAQ,EAAW,CAAY;CACrC,OAAO,GAAiB,MAA0B,IAAQ,EAAM,CAAE,IAAI,EAAG,GAAI,CAAC,CAAK,CAAC;AACtF"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../src/react/context.ts"],"sourcesContent":["import { createContext, useCallback, useContext, useLayoutEffect, useRef } from \"react\";\nimport type { ContentKitClient } from \"../client/client.js\";\nimport { toContentKitError, type ContentKitError } from \"../client/errors.js\";\nimport type { ContentURLs } from \"../urls/index.js\";\nimport type { ReadStore } from \"./store.js\";\n\n/** What failed: a component's or hook's save, load or render step. */\nexport type ContentKitOperation =\n | \"poster.load\"\n | \"poster.frame\"\n | \"poster.save\"\n | \"slot.load\"\n | \"slot.decode\"\n | \"slot.save\"\n | \"slot.remove\"\n | \"upload\"\n | \"folder.load\"\n | \"folder.commit\"\n | \"folder.update\"\n | \"folder.process\"\n | \"crop.load\"\n | \"crop.save\"\n | \"version.download\"\n | SocialOperation;\n\n/** What failed in a content component: a load or a write. */\nexport type SocialOperation =\n | \"comment.load\"\n | \"comment.post\"\n | \"comment.edit\"\n | \"comment.delete\"\n | \"comment.react\"\n | \"comment.restore\"\n | \"ban.save\"\n | \"ban.lift\"\n | \"reaction.save\"\n | \"favorite.save\"\n | \"poll.load\"\n | \"poll.vote\"\n | \"poll.answer\"\n | \"poll.save\"\n | \"post.load\"\n | \"content.save\"\n | \"moderation.load\"\n | \"moderation.resolve\"\n | \"rules.save\"\n | \"reader.save\"\n | \"media.save\"\n | \"notifications.load\"\n | \"notifications.read\"\n | \"notifications.dismiss\"\n | \"group.load\"\n | \"group.save\"\n | \"membership.save\"\n | \"history.forget\"\n | \"filters.save\"\n | \"offer.save\"\n | \"membership.join\";\n\n/** The failure's context: the operation and, for one file, its name. */\nexport interface ContentKitErrorInfo {\n operation: ContentKitOperation;\n file?: string;\n}\n\n/**\n * Every failure a component shows is also reported here (aborts excepted), so\n * the host can toast or log it. Components still show it in place.\n */\nexport type ContentKitErrorHandler = (error: ContentKitError, info: ContentKitErrorInfo) => void;\n\n/** The host router: in-app navigation, e.g. a canonical replace. */\nexport type Navigate = (to: string, options?: { replace?: boolean }) => void;\n\nexport interface ContentKitContextValue {\n client: ContentKitClient;\n /**\n * The signed-in user's id as ContentKit sees it, null when signed out,\n * undefined when the host does not say. Content reads are kept per viewer.\n */\n viewer?: string | null;\n /** Request language; keep it in sync with the client's language callback. */\n language?: string;\n /** Change when the current viewer's permissions or entitlements change. */\n accessRevision?: string | number;\n readScope: string;\n /** Asks the visitor to sign in; with it, signed-out visitors are prompted instead of acting anonymously. */\n onSignIn?: () => void;\n /** The host's content URL config (createContentURLs). */\n urls?: ContentURLs;\n navigate?: Navigate;\n onError?: ContentKitErrorHandler;\n /** The reads hooks share. */\n store: ReadStore;\n}\n\nexport const ContentKitContext = createContext<ContentKitContextValue | null>(null);\n\n/** Values that can change a read without changing its content reference. */\nexport function useReadScope(): string {\n return useContext(ContentKitContext)?.readScope ?? \"{}\";\n}\n\n/** The ContentKitProvider's value; throws outside one. */\nexport function useContentKit(): ContentKitContextValue {\n const ctx = useContext(ContentKitContext);\n if (!ctx) throw new Error(\"contentkit-ui: wrap the tree in <ContentKitProvider client>\");\n return ctx;\n}\n\n/** The client a hook or component uses: its own, else the provider's; throws without either. */\nexport function useContentKitClient(own?: ContentKitClient | null): ContentKitClient {\n const c = useOptionalContentKitClient(own);\n if (!c) throw new Error(\"contentkit-ui: pass `client` or render inside <ContentKitProvider client>\");\n return c;\n}\n\nexport function useOptionalContentKitClient(own?: ContentKitClient | null): ContentKitClient | null {\n const ctx = useContext(ContentKitContext);\n const client = own ?? ctx?.client ?? null;\n const scope = useReadScope();\n useLayoutEffect(() => { client?.setReadScope(scope); }, [client, scope]);\n return client;\n}\n\n/** The provider's content URL helpers; throws when none were given. */\nexport function useContentURLs(): ContentURLs {\n const urls = useContext(ContentKitContext)?.urls;\n if (!urls) throw new Error(\"contentkit-ui: pass `urls` to <ContentKitProvider>\");\n return urls;\n}\n\n/** A stable reporter: the component's own `onError`, else the provider's. */\nexport function useErrorReporter(own?: ContentKitErrorHandler): (e: unknown, operation: ContentKitOperation, file?: string) => void {\n const ctx = useContext(ContentKitContext)?.onError;\n const handler = useRef(own ?? ctx);\n handler.current = own ?? ctx;\n return useCallback((e: unknown, operation: ContentKitOperation, file?: string) => {\n const error = toContentKitError(e);\n if (error.code !== \"aborted\") handler.current?.(error, file === undefined ? { operation } : { operation, file });\n }, []);\n}\n\n/** Runs a write, e.g. auth-ui's useStepUpGuard(): re-authenticates when the write asks for a recent sign-in, then retries. */\nexport type ContentKitGuard = <T>(write: () => Promise<T>) => Promise<T>;\n\n/** The admin flow's guard; hooks run their writes through it. */\nexport const GuardContext = createContext<ContentKitGuard | undefined>(undefined);\n\n/** Runs fn through the flow's guard, when the host gave one. */\nexport function useGuarded(): <T>(fn: () => Promise<T>) => Promise<T> {\n const guard = useContext(GuardContext);\n return useCallback(<T,>(fn: () => Promise<T>) => (guard ? guard(fn) : fn()), [guard]);\n}\n"],"mappings":";;;AAgGA,IAAa,IAAoB,EAA6C,IAAI;AAGlF,SAAgB,IAAuB;CACrC,OAAO,EAAW,CAAiB,CAAC,EAAE,aAAa;AACrD;AAGA,SAAgB,IAAwC;CACtD,IAAM,IAAM,EAAW,CAAiB;CACxC,IAAI,CAAC,GAAK,MAAU,MAAM,6DAA6D;CACvF,OAAO;AACT;AAGA,SAAgB,EAAoB,GAAiD;CACnF,IAAM,IAAI,EAA4B,CAAG;CACzC,IAAI,CAAC,GAAG,MAAU,MAAM,2EAA2E;CACnG,OAAO;AACT;AAEA,SAAgB,EAA4B,GAAwD;CAClG,IAAM,IAAM,EAAW,CAAiB,GAClC,IAAS,KAAO,GAAK,UAAU,MAC/B,IAAQ,EAAa;CAE3B,OADA,QAAsB;EAAE,GAAQ,aAAa,CAAK;CAAG,GAAG,CAAC,GAAQ,CAAK,CAAC,GAChE;AACT;AAGA,SAAgB,IAA8B;CAC5C,IAAM,IAAO,EAAW,CAAiB,CAAC,EAAE;CAC5C,IAAI,CAAC,GAAM,MAAU,MAAM,oDAAoD;CAC/E,OAAO;AACT;AAGA,SAAgB,EAAiB,GAAmG;CAClI,IAAM,IAAM,EAAW,CAAiB,CAAC,EAAE,SACrC,IAAU,EAAO,KAAO,CAAG;CAEjC,OADA,EAAQ,UAAU,KAAO,GAClB,GAAa,GAAY,GAAgC,MAAkB;EAChF,IAAM,IAAQ,EAAkB,CAAC;EACjC,AAAI,EAAM,SAAS,aAAW,EAAQ,UAAU,GAAO,MAAS,KAAA,IAAY,EAAE,aAAU,IAAI;GAAE;GAAW;EAAK,CAAC;CACjH,GAAG,CAAC,CAAC;AACP;AAMA,IAAa,IAAe,EAA2C,KAAA,CAAS;AAGhF,SAAgB,IAAsD;CACpE,IAAM,IAAQ,EAAW,CAAY;CACrC,OAAO,GAAiB,MAA0B,IAAQ,EAAM,CAAE,IAAI,EAAG,GAAI,CAAC,CAAK,CAAC;AACtF"}
@@ -3,8 +3,14 @@ import { ContentKitError } from '../client/errors.js';
3
3
  import { Content, Decision, Version } from '../client/generated/wire.js';
4
4
  /** A content's live versions, first first. */
5
5
  export declare function liveVersions(c: Content | null | undefined): Version[];
6
- /** The version a reader of language opens by default: the first live one serving it, else the first live one. */
6
+ /**
7
+ * The version a reader of language opens by default: the first live one by
8
+ * position serving it, else the first live one. The server picks cards'
9
+ * versions, covers and meta by the same rule.
10
+ */
7
11
  export declare function defaultVersion(c: Content | null | undefined, language?: string): Version | null;
12
+ /** defaultVersion among versions: the first by position serving language, else the first. */
13
+ export declare function editionOf(versions: readonly Version[], language?: string): Version | null;
8
14
  /** The version selected names: its code (any spelling, the page's ?v=) or its id; undefined when none. */
9
15
  export declare function findVersion(versions: readonly Version[], selected: string | null | undefined): Version | undefined;
10
16
  export interface UseContentDetail {
@@ -7,21 +7,24 @@ function o(e) {
7
7
  return (e?.versions ?? []).filter((e) => e.live).sort((e, t) => e.position - t.position);
8
8
  }
9
9
  function s(e, t) {
10
- let n = o(e);
11
- return (t ? n.find((e) => e.languages.includes(t)) : void 0) ?? n[0] ?? null;
10
+ return c(o(e), t);
12
11
  }
13
12
  function c(e, t) {
13
+ let n = [...e].sort((e, t) => e.position - t.position);
14
+ return (t ? n.find((e) => e.languages.includes(t)) : void 0) ?? n[0] ?? null;
15
+ }
16
+ function l(e, t) {
14
17
  if (!t) return;
15
18
  let n = r(t);
16
19
  return e.find((e) => e.id === t) ?? (n ? e.find((e) => e.code === n) : void 0);
17
20
  }
18
- function l(r, l = {}) {
19
- let { client: u, store: d, scope: f, language: p } = t(l.client), m = l.language ?? p, [h] = i({ location: l.location }), g = l.version === void 0 ? h : l.version, _ = r ? e("content-detail", f, r, m) : null, v = n(d, _, {
21
+ function u(r, c = {}) {
22
+ let { client: u, store: d, scope: f, language: p } = t(c.client), m = c.language ?? p, [h] = i({ location: c.location }), g = c.version === void 0 ? h : c.version, _ = r ? e("content-detail", f, r, m) : null, v = n(d, _, {
20
23
  type: "content-detail",
21
24
  id: r ?? void 0
22
25
  }, (e) => u.contents.get(r, m, e)), y = v.data ?? null;
23
26
  return a(() => {
24
- let e = o(y), t = c(e, g) ?? s(y, m);
27
+ let e = o(y), t = l(e, g) ?? s(y, m);
25
28
  return {
26
29
  content: y,
27
30
  versions: e,
@@ -44,6 +47,6 @@ function l(r, l = {}) {
44
47
  ]);
45
48
  }
46
49
  //#endregion
47
- export { s as defaultVersion, c as findVersion, o as liveVersions, l as useContentDetail };
50
+ export { s as defaultVersion, c as editionOf, l as findVersion, o as liveVersions, u as useContentDetail };
48
51
 
49
52
  //# sourceMappingURL=detail.js.map