@blogmcp/sdk 0.8.1 → 0.9.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/dist/community/channels.d.ts +12 -0
- package/dist/community/channels.js +7 -0
- package/dist/community/client.d.ts +211 -0
- package/dist/community/client.js +188 -0
- package/dist/community/index.d.ts +34 -0
- package/dist/community/index.js +92 -0
- package/dist/community/links.d.ts +65 -0
- package/dist/community/links.js +81 -0
- package/dist/community/messages.cs.d.ts +331 -0
- package/dist/community/messages.cs.js +342 -0
- package/dist/community/messages.d.ts +40 -0
- package/dist/community/messages.en.d.ts +315 -0
- package/dist/community/messages.en.js +313 -0
- package/dist/community/messages.js +66 -0
- package/dist/community/outcome.d.ts +96 -0
- package/dist/community/outcome.js +211 -0
- package/dist/community/poll.d.ts +35 -0
- package/dist/community/poll.js +70 -0
- package/dist/community/routes.d.ts +110 -0
- package/dist/community/routes.js +66 -0
- package/dist/community/server/bff.d.ts +123 -0
- package/dist/community/server/bff.js +214 -0
- package/dist/community/server/env.d.ts +20 -0
- package/dist/community/server/env.js +16 -0
- package/dist/community/server/host-routes.d.ts +15 -0
- package/dist/community/server/host-routes.js +35 -0
- package/dist/community/server/http.d.ts +64 -0
- package/dist/community/server/http.js +90 -0
- package/dist/community/server/index.d.ts +45 -0
- package/dist/community/server/index.js +19 -0
- package/dist/community/server/route-decision.d.ts +70 -0
- package/dist/community/server/route-decision.js +89 -0
- package/dist/community/server/unknown-path.d.ts +21 -0
- package/dist/community/server/unknown-path.js +11 -0
- package/dist/community/shapes.d.ts +457 -0
- package/dist/community/shapes.js +51 -0
- package/dist/community/store.d.ts +183 -0
- package/dist/community/store.js +423 -0
- package/dist/community/transport.d.ts +42 -0
- package/dist/community/transport.js +59 -0
- package/dist/core/client.d.ts +17 -0
- package/dist/core/client.js +58 -55
- package/dist/core/comments-legacy.d.ts +19 -0
- package/dist/core/comments-legacy.js +18 -0
- package/dist/core/index.d.ts +3 -0
- package/dist/core/index.js +107 -101
- package/dist/core/queries.d.ts +46 -0
- package/dist/core/queries.js +128 -84
- package/dist/core/seo.js +40 -39
- package/dist/core/translations/cs.json.js +6 -6
- package/dist/core/translations/en.json.js +1 -1
- package/dist/core/types.d.ts +23 -1
- package/dist/core/view-model.d.ts +7 -0
- package/dist/core/view-model.js +29 -25
- package/dist/react/KbMdxContent.js +4 -3
- package/dist/vue/components/KbMdxContent.vue2.js +3 -2
- package/dist/vue/composables/useKbComments.d.ts +8 -0
- package/package.json +13 -4
- package/src/community/channels.ts +12 -0
- package/src/community/client.ts +437 -0
- package/src/community/index.ts +190 -0
- package/src/community/links.ts +166 -0
- package/src/community/messages.cs.ts +371 -0
- package/src/community/messages.en.ts +341 -0
- package/src/community/messages.ts +112 -0
- package/src/community/outcome.ts +317 -0
- package/src/community/poll.ts +154 -0
- package/src/community/routes.ts +139 -0
- package/src/community/server/bff.ts +530 -0
- package/src/community/server/env.ts +42 -0
- package/src/community/server/host-routes.ts +48 -0
- package/src/community/server/http.ts +175 -0
- package/src/community/server/index.ts +55 -0
- package/src/community/server/route-decision.ts +226 -0
- package/src/community/server/unknown-path.ts +32 -0
- package/src/community/shapes.ts +513 -0
- package/src/community/store.ts +786 -0
- package/src/community/transport.ts +111 -0
- package/src/core/client.ts +24 -1
- package/src/core/comments-legacy.ts +39 -0
- package/src/core/index.ts +8 -0
- package/src/core/queries.ts +93 -0
- package/src/core/seo.ts +5 -1
- package/src/core/translations/cs.json +3 -1
- package/src/core/translations/en.json +3 -1
- package/src/core/types.ts +19 -1
- package/src/core/view-model.ts +12 -1
- package/src/vue/composables/useKbComments.ts +8 -0
|
@@ -0,0 +1,786 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One article's discussion as an immutable two-level tree (docs/internal/m1-contracts.md §10.2), framework-free:
|
|
3
|
+
* a page renders `getState()` and re-renders on `subscribe`. Every change builds a new state and shares every
|
|
4
|
+
* message it did not touch, so a Vue or React view can compare by identity.
|
|
5
|
+
*
|
|
6
|
+
* applyPage a `discussions/list` page merged by its cursor range (refreshDiscussion, loadMoreDiscussion);
|
|
7
|
+
* applyMessage an optimistic post, edit or delete under a `clientMsgId`, then the server's row (`confirm`) or the
|
|
8
|
+
* undo (`rollback`);
|
|
9
|
+
* applyHead a `discussions/head` answer: true when it is newer than what is loaded (→ refresh);
|
|
10
|
+
* applyReaction a reaction summary (the server's, or reactionAfter's optimistic one);
|
|
11
|
+
* collapse a member blocked or unblocked: their messages collapse or open;
|
|
12
|
+
* viewerNeeds what the composer still waits for.
|
|
13
|
+
*
|
|
14
|
+
* Open enums (community.md §3.7): a message whose author kind or state this SDK does not know is dropped — with the
|
|
15
|
+
* replies under it — and so is a need or a restriction kind it does not know. Nothing a newer kb-api sends throws.
|
|
16
|
+
*
|
|
17
|
+
* One store may show one article after another (reset(), or a page of another article): an answer that outlives
|
|
18
|
+
* the switch — a write's confirm, a server row, a refresh or „load more" still on its way — changes nothing.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { CommunityCallOptions, CommunityClient } from './client'
|
|
22
|
+
import type { CommunityOutcome } from './outcome'
|
|
23
|
+
import {
|
|
24
|
+
isKnownAuthorKind,
|
|
25
|
+
isKnownNeed,
|
|
26
|
+
isKnownRestrictionKind,
|
|
27
|
+
isKnownState,
|
|
28
|
+
type Discussion,
|
|
29
|
+
type DiscussionHead,
|
|
30
|
+
type KnownAuthor,
|
|
31
|
+
type KnownMessageState,
|
|
32
|
+
type KnownNeed,
|
|
33
|
+
type KnownRestrictionKind,
|
|
34
|
+
type PublicMessage,
|
|
35
|
+
type ReactionSummary,
|
|
36
|
+
type ReactionTarget,
|
|
37
|
+
} from './shapes'
|
|
38
|
+
|
|
39
|
+
/** A message as the store keeps it: a known author and state, and the optimistic change that waits, if any. */
|
|
40
|
+
export interface DiscussionMessage extends Omit<PublicMessage, 'author' | 'state' | 'replies' | 'reactions'> {
|
|
41
|
+
readonly author: KnownAuthor
|
|
42
|
+
readonly state: KnownMessageState
|
|
43
|
+
readonly reactions: ReactionSummary
|
|
44
|
+
/** On a top-level message: its replies, oldest first (a reply has none). */
|
|
45
|
+
readonly replies: readonly DiscussionMessage[]
|
|
46
|
+
/** An optimistic change waiting for the server: render it as such (no reply, edit or reaction meanwhile). */
|
|
47
|
+
readonly pending?: 'post' | 'edit' | 'delete'
|
|
48
|
+
/** The id of that change (a post's `clientMsgId`). */
|
|
49
|
+
readonly clientMsgId?: string
|
|
50
|
+
/** The filters' warning codes the member's own write came back with (`messages/post`, `messages/edit`). */
|
|
51
|
+
readonly warnings?: readonly string[]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface DiscussionRestriction {
|
|
55
|
+
readonly kind: KnownRestrictionKind
|
|
56
|
+
readonly scope: string
|
|
57
|
+
readonly endsAt: string | null
|
|
58
|
+
readonly decisionId: string
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface DiscussionViewer {
|
|
62
|
+
readonly memberId: string | null
|
|
63
|
+
readonly canPost: boolean
|
|
64
|
+
readonly needs: readonly KnownNeed[]
|
|
65
|
+
readonly restrictions: readonly DiscussionRestriction[]
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface DiscussionState {
|
|
69
|
+
/** The article of the pages applied (lower case, as kb-api answers it), or null before the first. */
|
|
70
|
+
readonly articleId: string | null
|
|
71
|
+
readonly conversationId: string | null
|
|
72
|
+
/** The messages everyone is shown. */
|
|
73
|
+
readonly count: number
|
|
74
|
+
readonly lastSeq: number
|
|
75
|
+
readonly lastChangeAt: string | null
|
|
76
|
+
/** The loaded top-level messages, oldest first; an optimistic post comes last. */
|
|
77
|
+
readonly messages: readonly DiscussionMessage[]
|
|
78
|
+
/**
|
|
79
|
+
* Where „load more" continues — the end of the pages loaded from the first one on (a message the viewer just
|
|
80
|
+
* posted is no page of them) —, or null when the end is loaded.
|
|
81
|
+
*/
|
|
82
|
+
readonly nextCursor: number | null
|
|
83
|
+
readonly articleReactions: ReactionSummary
|
|
84
|
+
readonly reactionSet: readonly string[]
|
|
85
|
+
readonly preset: string | null
|
|
86
|
+
readonly viewer: DiscussionViewer
|
|
87
|
+
/** A page was applied. */
|
|
88
|
+
readonly loaded: boolean
|
|
89
|
+
/** A head newer than the loaded pages arrived: refresh. */
|
|
90
|
+
readonly stale: boolean
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** An optimistic change and how it settles. `clientMsgId` names the change from start to end. */
|
|
94
|
+
export type MessageChange =
|
|
95
|
+
/** A new message (a reply with `replyToSeq`): shown at once, last, as `pending: 'post'`. */
|
|
96
|
+
| {
|
|
97
|
+
readonly type: 'post'
|
|
98
|
+
readonly clientMsgId: string
|
|
99
|
+
readonly body: string
|
|
100
|
+
readonly replyToSeq?: number | null
|
|
101
|
+
/** The member as their own messages show them. */
|
|
102
|
+
readonly author: KnownAuthor
|
|
103
|
+
readonly createdAt?: string
|
|
104
|
+
readonly languageCode?: string | null
|
|
105
|
+
}
|
|
106
|
+
/** The member's own message with a new text. */
|
|
107
|
+
| { readonly type: 'edit'; readonly clientMsgId: string; readonly seq: number; readonly body: string }
|
|
108
|
+
/** The member's own message, deleted. */
|
|
109
|
+
| { readonly type: 'delete'; readonly clientMsgId: string; readonly seq: number }
|
|
110
|
+
/**
|
|
111
|
+
* The server's answer to the change: its row replaces the optimistic one (`warnings` from the write's answer).
|
|
112
|
+
* The answer to a change reset() dropped, or a row of another conversation, is not this discussion's: ignored.
|
|
113
|
+
*/
|
|
114
|
+
| { readonly type: 'confirm'; readonly clientMsgId: string; readonly message: PublicMessage; readonly warnings?: readonly string[] }
|
|
115
|
+
/** The server refused the change: it is undone. */
|
|
116
|
+
| { readonly type: 'rollback'; readonly clientMsgId: string }
|
|
117
|
+
/** A row from the server outside an optimistic change: replaces the loaded one of its conversation and seq, if any. */
|
|
118
|
+
| { readonly type: 'server'; readonly message: PublicMessage }
|
|
119
|
+
|
|
120
|
+
export interface DiscussionStore {
|
|
121
|
+
getState(): DiscussionState
|
|
122
|
+
/** Called after every change with the new state; returns the unsubscribe. */
|
|
123
|
+
subscribe(listener: (state: DiscussionState) => void): () => void
|
|
124
|
+
/** A page of `discussions/list`; `cursor` is the one it was asked with (null or absent: the first page). */
|
|
125
|
+
applyPage(page: Discussion, options?: { cursor?: number | null }): void
|
|
126
|
+
applyMessage(change: MessageChange): void
|
|
127
|
+
/** True when the head is newer than the loaded pages (the state turns `stale`): refresh. */
|
|
128
|
+
applyHead(head: DiscussionHead): boolean
|
|
129
|
+
applyReaction(target: ReactionTarget, reactions: ReactionSummary): void
|
|
130
|
+
/** The viewer blocked (true) or unblocked (false) a member. */
|
|
131
|
+
collapse(memberId: string, blocked: boolean): void
|
|
132
|
+
/** Back to the empty state (another article); the answers still on their way are dropped when they come. */
|
|
133
|
+
reset(): void
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ───────────────────────── sanitising what the server sent ─────────────────────────
|
|
137
|
+
|
|
138
|
+
type Rec = Record<string, unknown>
|
|
139
|
+
const isRecord = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
140
|
+
const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)
|
|
141
|
+
const isSeq = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v > 0
|
|
142
|
+
|
|
143
|
+
const NO_REACTIONS: ReactionSummary = Object.freeze({ counts: Object.freeze({}), mine: null })
|
|
144
|
+
|
|
145
|
+
function reactionsOf(raw: unknown): ReactionSummary {
|
|
146
|
+
if (!isRecord(raw)) return NO_REACTIONS
|
|
147
|
+
const counts: Record<string, number> = {}
|
|
148
|
+
if (isRecord(raw.counts)) {
|
|
149
|
+
for (const [emoji, n] of Object.entries(raw.counts)) {
|
|
150
|
+
if (typeof n === 'number' && Number.isSafeInteger(n) && n > 0) counts[emoji] = n
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return Object.freeze({ counts: Object.freeze(counts), mine: str(raw.mine) })
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const DELETED_AUTHOR: KnownAuthor = Object.freeze({
|
|
157
|
+
kind: 'member',
|
|
158
|
+
memberId: null,
|
|
159
|
+
handle: null,
|
|
160
|
+
displayName: null,
|
|
161
|
+
avatarPreset: null,
|
|
162
|
+
deleted: true,
|
|
163
|
+
})
|
|
164
|
+
const SYSTEM_AUTHOR: KnownAuthor = Object.freeze({ kind: 'system' })
|
|
165
|
+
|
|
166
|
+
/** A known author kind as the store renders it (a member short of its fields is the deleted placeholder); else null. */
|
|
167
|
+
function authorOf(raw: unknown): KnownAuthor | null {
|
|
168
|
+
if (!isRecord(raw) || !isKnownAuthorKind(raw.kind)) return null
|
|
169
|
+
if (raw.kind === 'system') return SYSTEM_AUTHOR
|
|
170
|
+
if (raw.kind === 'staff') {
|
|
171
|
+
return Object.freeze({ kind: 'staff', staffId: str(raw.staffId) ?? '', displayName: str(raw.displayName) ?? '', badge: str(raw.badge) ?? '' })
|
|
172
|
+
}
|
|
173
|
+
const memberId = str(raw.memberId)
|
|
174
|
+
const handle = str(raw.handle)
|
|
175
|
+
const displayName = str(raw.displayName)
|
|
176
|
+
if (memberId === null || handle === null || displayName === null || raw.deleted === true) return DELETED_AUTHOR
|
|
177
|
+
return Object.freeze({ kind: 'member', memberId, handle, displayName, avatarPreset: str(raw.avatarPreset) })
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function codesOf(raw: unknown): readonly string[] | undefined {
|
|
181
|
+
if (!Array.isArray(raw)) return undefined
|
|
182
|
+
return Object.freeze(raw.filter((c): c is string => typeof c === 'string'))
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A server message as the store keeps it, or null when its author kind or state is unknown (or it is malformed). */
|
|
186
|
+
function messageOf(raw: unknown, topLevel: boolean): DiscussionMessage | null {
|
|
187
|
+
if (!isRecord(raw)) return null
|
|
188
|
+
const author = authorOf(raw.author)
|
|
189
|
+
if (author === null || !isKnownState(raw.state)) return null
|
|
190
|
+
const conversationId = str(raw.conversationId)
|
|
191
|
+
const id = str(raw.id)
|
|
192
|
+
if (conversationId === null || id === null || !isSeq(raw.seq)) return null
|
|
193
|
+
const body = str(raw.body)
|
|
194
|
+
const replies: DiscussionMessage[] = []
|
|
195
|
+
if (topLevel && Array.isArray(raw.replies)) {
|
|
196
|
+
for (const r of raw.replies) {
|
|
197
|
+
const reply = messageOf(r, false)
|
|
198
|
+
if (reply) replies.push(reply)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const notes = codesOf(raw.notes)
|
|
202
|
+
return Object.freeze({
|
|
203
|
+
conversationId,
|
|
204
|
+
seq: raw.seq,
|
|
205
|
+
id,
|
|
206
|
+
rev: typeof raw.rev === 'number' ? raw.rev : 0,
|
|
207
|
+
replyToSeq: topLevel ? null : isSeq(raw.replyToSeq) ? raw.replyToSeq : null,
|
|
208
|
+
author,
|
|
209
|
+
state: raw.state,
|
|
210
|
+
body,
|
|
211
|
+
displayBody: str(raw.displayBody) ?? body,
|
|
212
|
+
displayLanguageCode: str(raw.displayLanguageCode),
|
|
213
|
+
sourceLanguageCode: str(raw.sourceLanguageCode),
|
|
214
|
+
isTranslated: raw.isTranslated === true,
|
|
215
|
+
isEdited: raw.isEdited === true,
|
|
216
|
+
createdAt: str(raw.createdAt) ?? '',
|
|
217
|
+
editedAt: str(raw.editedAt),
|
|
218
|
+
collapsed: raw.collapsed === true,
|
|
219
|
+
reactions: reactionsOf(raw.reactions),
|
|
220
|
+
translationVersionId: str(raw.translationVersionId),
|
|
221
|
+
...(notes && notes.length > 0 ? { notes } : {}),
|
|
222
|
+
// Only as kb-api sends it: true, on a `held` message (the author's own, held back by the art. 9 policy).
|
|
223
|
+
...(raw.hiddenUntilConsent === true && raw.state === 'held' ? { hiddenUntilConsent: true } : {}),
|
|
224
|
+
replies: ordered(replies),
|
|
225
|
+
...(topLevel && raw.repliesTruncated === true ? { repliesTruncated: true } : {}),
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function viewerOf(raw: unknown): DiscussionViewer {
|
|
230
|
+
const v = isRecord(raw) ? raw : {}
|
|
231
|
+
const needs = Array.isArray(v.needs) ? v.needs.filter(isKnownNeed) : []
|
|
232
|
+
const restrictions: DiscussionRestriction[] = []
|
|
233
|
+
if (Array.isArray(v.restrictions)) {
|
|
234
|
+
for (const r of v.restrictions) {
|
|
235
|
+
if (!isRecord(r) || !isKnownRestrictionKind(r.kind) || typeof r.decisionId !== 'string') continue
|
|
236
|
+
restrictions.push(Object.freeze({ kind: r.kind, scope: str(r.scope) ?? '', endsAt: str(r.endsAt), decisionId: r.decisionId }))
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return Object.freeze({
|
|
240
|
+
memberId: str(v.memberId),
|
|
241
|
+
canPost: v.canPost === true,
|
|
242
|
+
needs: Object.freeze([...new Set(needs)]),
|
|
243
|
+
restrictions: Object.freeze(restrictions),
|
|
244
|
+
})
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const EMPTY_VIEWER: DiscussionViewer = Object.freeze({ memberId: null, canPost: false, needs: Object.freeze([]), restrictions: Object.freeze([]) })
|
|
248
|
+
|
|
249
|
+
const EMPTY: DiscussionState = Object.freeze({
|
|
250
|
+
articleId: null,
|
|
251
|
+
conversationId: null,
|
|
252
|
+
count: 0,
|
|
253
|
+
lastSeq: 0,
|
|
254
|
+
lastChangeAt: null,
|
|
255
|
+
messages: Object.freeze([]),
|
|
256
|
+
nextCursor: null,
|
|
257
|
+
articleReactions: NO_REACTIONS,
|
|
258
|
+
reactionSet: Object.freeze([]),
|
|
259
|
+
preset: null,
|
|
260
|
+
viewer: EMPTY_VIEWER,
|
|
261
|
+
loaded: false,
|
|
262
|
+
stale: false,
|
|
263
|
+
})
|
|
264
|
+
|
|
265
|
+
// ───────────────────────── tree helpers ─────────────────────────
|
|
266
|
+
|
|
267
|
+
const later = (a: string | null, b: string | null): string | null => {
|
|
268
|
+
if (a === null) return b
|
|
269
|
+
if (b === null) return a
|
|
270
|
+
return Date.parse(b) > Date.parse(a) ? b : a
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Real messages by seq, optimistic posts (negative seq) after them in their order. */
|
|
274
|
+
function ordered(list: readonly DiscussionMessage[]): readonly DiscussionMessage[] {
|
|
275
|
+
const real = list.filter((m) => m.seq > 0).sort((a, b) => a.seq - b.seq)
|
|
276
|
+
const pending = list.filter((m) => m.seq < 0).sort((a, b) => b.seq - a.seq)
|
|
277
|
+
return Object.freeze([...real, ...pending])
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Every message, top-level and replies, through `fn` (identity kept for what `fn` returns unchanged). */
|
|
281
|
+
function mapAll(list: readonly DiscussionMessage[], fn: (m: DiscussionMessage) => DiscussionMessage | null): readonly DiscussionMessage[] {
|
|
282
|
+
let changed = false
|
|
283
|
+
const out: DiscussionMessage[] = []
|
|
284
|
+
for (const m of list) {
|
|
285
|
+
let next = fn(m)
|
|
286
|
+
if (next !== null && next.replies.length > 0) {
|
|
287
|
+
const replies = mapAll(next.replies, fn)
|
|
288
|
+
if (replies !== next.replies) next = Object.freeze({ ...next, replies })
|
|
289
|
+
}
|
|
290
|
+
if (next !== m) changed = true
|
|
291
|
+
if (next !== null) out.push(next)
|
|
292
|
+
}
|
|
293
|
+
return changed ? Object.freeze(out) : list
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function findIn(list: readonly DiscussionMessage[], pred: (m: DiscussionMessage) => boolean): DiscussionMessage | null {
|
|
297
|
+
for (const m of list) {
|
|
298
|
+
if (pred(m)) return m
|
|
299
|
+
for (const r of m.replies) if (pred(r)) return r
|
|
300
|
+
}
|
|
301
|
+
return null
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** A server row in place of the loaded message with its seq (a top-level message keeps its loaded replies). */
|
|
305
|
+
function replaceBySeq(list: readonly DiscussionMessage[], row: DiscussionMessage): readonly DiscussionMessage[] {
|
|
306
|
+
return mapAll(list, (m) => (m.seq === row.seq ? (m.replyToSeq === null && row.replyToSeq === null ? Object.freeze({ ...row, replies: m.replies }) : row) : m))
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The row inserted where it belongs (top-level by seq, a reply under its parent), replacing one with its seq. */
|
|
310
|
+
function upsert(list: readonly DiscussionMessage[], row: DiscussionMessage): readonly DiscussionMessage[] {
|
|
311
|
+
if (findIn(list, (m) => m.seq === row.seq)) return replaceBySeq(list, row)
|
|
312
|
+
if (row.replyToSeq === null) return ordered([...list, row])
|
|
313
|
+
const parent = list.find((m) => m.seq === row.replyToSeq)
|
|
314
|
+
if (!parent) return list
|
|
315
|
+
return Object.freeze(list.map((m) => (m === parent ? Object.freeze({ ...m, replies: ordered([...m.replies, row]) }) : m)))
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Whether a deleted message still shows: a top-level placeholder while it has replies. */
|
|
319
|
+
const keepsPlaceholder = (m: DiscussionMessage): boolean => m.replyToSeq === null && m.replies.length > 0
|
|
320
|
+
|
|
321
|
+
/** kb-api answers ids in lower case; a host may pass them in upper case. */
|
|
322
|
+
const sameId = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase()
|
|
323
|
+
|
|
324
|
+
// ───────────────────────── the store ─────────────────────────
|
|
325
|
+
|
|
326
|
+
interface PendingChange {
|
|
327
|
+
readonly type: 'post' | 'edit' | 'delete'
|
|
328
|
+
/** edit, delete: the row before the change (kept current while a page refreshes it). */
|
|
329
|
+
before: DiscussionMessage | null
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** The dropped changes a store remembers, to ignore their late answers (a bound, not a log). */
|
|
333
|
+
const RETIRED_MAX = 256
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Each store's generation — reset() and a page of another article start a new one — for the loaders below: a page
|
|
337
|
+
* that comes back in another generation is not applied.
|
|
338
|
+
*/
|
|
339
|
+
const generations = new WeakMap<DiscussionStore, () => number>()
|
|
340
|
+
|
|
341
|
+
export function createDiscussionStore(): DiscussionStore {
|
|
342
|
+
let state: DiscussionState = EMPTY
|
|
343
|
+
const listeners = new Set<(state: DiscussionState) => void>()
|
|
344
|
+
const pending = new Map<string, PendingChange>()
|
|
345
|
+
/** Changes reset() or another article dropped: their answers are not this discussion's. */
|
|
346
|
+
const retired = new Set<string>()
|
|
347
|
+
let generation = 0
|
|
348
|
+
let nextPendingSeq = -1
|
|
349
|
+
|
|
350
|
+
/** Another discussion from here on: the changes that wait are dropped, and their answers with them. */
|
|
351
|
+
const nextGeneration = (): void => {
|
|
352
|
+
generation += 1
|
|
353
|
+
for (const id of pending.keys()) {
|
|
354
|
+
retired.delete(id)
|
|
355
|
+
retired.add(id)
|
|
356
|
+
}
|
|
357
|
+
pending.clear()
|
|
358
|
+
for (const id of retired) {
|
|
359
|
+
if (retired.size <= RETIRED_MAX) break
|
|
360
|
+
retired.delete(id)
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const set = (next: DiscussionState): void => {
|
|
365
|
+
if (next === state) return
|
|
366
|
+
state = Object.freeze(next)
|
|
367
|
+
for (const listener of [...listeners]) {
|
|
368
|
+
try {
|
|
369
|
+
listener(state)
|
|
370
|
+
} catch {
|
|
371
|
+
// One view's bug must not stop the others from rendering.
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function applyPage(page: Discussion, options: { cursor?: number | null } = {}): void {
|
|
377
|
+
if (!isRecord(page)) return
|
|
378
|
+
const articleId = str(page.articleId)?.toLowerCase() ?? null
|
|
379
|
+
const fresh = state.articleId !== null && articleId !== null && articleId !== state.articleId
|
|
380
|
+
const base = fresh ? EMPTY : state
|
|
381
|
+
if (fresh) nextGeneration()
|
|
382
|
+
|
|
383
|
+
const cursor = typeof options.cursor === 'number' && Number.isFinite(options.cursor) ? options.cursor : null
|
|
384
|
+
const lo = cursor ?? 0
|
|
385
|
+
const pageNext = typeof page.nextCursor === 'number' && Number.isFinite(page.nextCursor) ? page.nextCursor : null
|
|
386
|
+
const hi = pageNext ?? Number.POSITIVE_INFINITY
|
|
387
|
+
|
|
388
|
+
const incoming = new Map<number, DiscussionMessage>()
|
|
389
|
+
for (const raw of Array.isArray(page.messages) ? page.messages : []) {
|
|
390
|
+
const m = messageOf(raw, true)
|
|
391
|
+
if (m && m.seq > lo && m.seq <= hi) incoming.set(m.seq, m)
|
|
392
|
+
}
|
|
393
|
+
// An optimistic edit or delete stays over the server's row until it settles; its undo becomes that row.
|
|
394
|
+
const pendingRows = new Map<number, DiscussionMessage>()
|
|
395
|
+
for (const m of base.messages) {
|
|
396
|
+
const all = [m, ...m.replies]
|
|
397
|
+
for (const x of all) if (x.pending && x.pending !== 'post' && x.clientMsgId) pendingRows.set(x.seq, x)
|
|
398
|
+
}
|
|
399
|
+
const overlay = (m: DiscussionMessage): DiscussionMessage => {
|
|
400
|
+
const mine = pendingRows.get(m.seq)
|
|
401
|
+
if (!mine) return m
|
|
402
|
+
const change = mine.clientMsgId ? pending.get(mine.clientMsgId) : undefined
|
|
403
|
+
if (change) change.before = m
|
|
404
|
+
return mine.replyToSeq === null ? Object.freeze({ ...mine, replies: m.replies }) : mine
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const kept = base.messages.filter((m) => m.seq < 0 || m.seq <= lo || m.seq > hi)
|
|
408
|
+
const optimisticReplies = new Map<number, DiscussionMessage[]>()
|
|
409
|
+
for (const m of base.messages) {
|
|
410
|
+
for (const r of m.replies) {
|
|
411
|
+
if (r.seq < 0 && r.replyToSeq !== null) optimisticReplies.set(r.replyToSeq, [...(optimisticReplies.get(r.replyToSeq) ?? []), r])
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const merged = [...kept.filter((m) => !incoming.has(m.seq)), ...[...incoming.values()]].map((m) => {
|
|
415
|
+
if (!incoming.has(m.seq)) return m
|
|
416
|
+
const withOverlay = overlay(m)
|
|
417
|
+
const replies = withOverlay.replies.map(overlay)
|
|
418
|
+
const extra = optimisticReplies.get(m.seq) ?? []
|
|
419
|
+
return replies.some((r, i) => r !== withOverlay.replies[i]) || extra.length > 0
|
|
420
|
+
? Object.freeze({ ...withOverlay, replies: ordered([...replies, ...extra]) })
|
|
421
|
+
: withOverlay
|
|
422
|
+
})
|
|
423
|
+
|
|
424
|
+
// „Load more" goes on where the pages loaded from the first one on end — not after a row past them that a write
|
|
425
|
+
// brought (confirm) —, and a page past that end leaves the gap before it to load first.
|
|
426
|
+
const loadedTo = base.loaded ? base.nextCursor : 0
|
|
427
|
+
const nextCursor = loadedTo === null ? null : lo > loadedTo ? loadedTo : pageNext === null ? null : Math.max(loadedTo, pageNext)
|
|
428
|
+
set({
|
|
429
|
+
articleId: articleId ?? base.articleId,
|
|
430
|
+
conversationId: str(page.conversationId) ?? base.conversationId,
|
|
431
|
+
count: typeof page.count === 'number' && page.count >= 0 ? page.count : base.count,
|
|
432
|
+
lastSeq: Math.max(typeof page.lastSeq === 'number' ? page.lastSeq : 0, base.lastSeq),
|
|
433
|
+
lastChangeAt: later(base.lastChangeAt, str(page.lastChangeAt)),
|
|
434
|
+
messages: ordered(merged),
|
|
435
|
+
nextCursor,
|
|
436
|
+
articleReactions: reactionsOf(page.articleReactions),
|
|
437
|
+
reactionSet: Object.freeze(Array.isArray(page.reactionSet) ? page.reactionSet.filter((e): e is string => typeof e === 'string') : []),
|
|
438
|
+
preset: str(page.preset),
|
|
439
|
+
viewer: viewerOf(page.viewer),
|
|
440
|
+
loaded: true,
|
|
441
|
+
stale: cursor === null ? false : base.stale,
|
|
442
|
+
})
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function optimisticPost(change: Extract<MessageChange, { type: 'post' }>): void {
|
|
446
|
+
if (pending.has(change.clientMsgId)) return
|
|
447
|
+
const replyToSeq = isSeq(change.replyToSeq) ? change.replyToSeq : null
|
|
448
|
+
if (replyToSeq !== null && !state.messages.some((m) => m.seq === replyToSeq)) return
|
|
449
|
+
const author = authorOf(change.author) ?? DELETED_AUTHOR
|
|
450
|
+
const row: DiscussionMessage = Object.freeze({
|
|
451
|
+
conversationId: state.conversationId ?? '',
|
|
452
|
+
seq: nextPendingSeq--,
|
|
453
|
+
id: `pending:${change.clientMsgId}`,
|
|
454
|
+
rev: 0,
|
|
455
|
+
replyToSeq,
|
|
456
|
+
author,
|
|
457
|
+
state: 'visible',
|
|
458
|
+
body: change.body,
|
|
459
|
+
displayBody: change.body,
|
|
460
|
+
displayLanguageCode: change.languageCode ?? null,
|
|
461
|
+
sourceLanguageCode: change.languageCode ?? null,
|
|
462
|
+
isTranslated: false,
|
|
463
|
+
isEdited: false,
|
|
464
|
+
createdAt: change.createdAt ?? new Date().toISOString(),
|
|
465
|
+
editedAt: null,
|
|
466
|
+
collapsed: false,
|
|
467
|
+
reactions: NO_REACTIONS,
|
|
468
|
+
translationVersionId: null,
|
|
469
|
+
replies: Object.freeze([]),
|
|
470
|
+
pending: 'post',
|
|
471
|
+
clientMsgId: change.clientMsgId,
|
|
472
|
+
})
|
|
473
|
+
pending.set(change.clientMsgId, { type: 'post', before: null })
|
|
474
|
+
const messages =
|
|
475
|
+
replyToSeq === null
|
|
476
|
+
? ordered([...state.messages, row])
|
|
477
|
+
: Object.freeze(state.messages.map((m) => (m.seq === replyToSeq ? Object.freeze({ ...m, replies: ordered([...m.replies, row]) }) : m)))
|
|
478
|
+
set({ ...state, messages })
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function optimisticChange(change: Extract<MessageChange, { type: 'edit' | 'delete' }>): void {
|
|
482
|
+
if (pending.has(change.clientMsgId)) return
|
|
483
|
+
const target = findIn(state.messages, (m) => m.seq === change.seq)
|
|
484
|
+
if (!target || target.pending) return
|
|
485
|
+
pending.set(change.clientMsgId, { type: change.type, before: target })
|
|
486
|
+
const next: DiscussionMessage =
|
|
487
|
+
change.type === 'edit'
|
|
488
|
+
? Object.freeze({
|
|
489
|
+
...target,
|
|
490
|
+
body: change.body,
|
|
491
|
+
displayBody: change.body,
|
|
492
|
+
displayLanguageCode: target.sourceLanguageCode,
|
|
493
|
+
isTranslated: false,
|
|
494
|
+
isEdited: true,
|
|
495
|
+
pending: 'edit',
|
|
496
|
+
clientMsgId: change.clientMsgId,
|
|
497
|
+
})
|
|
498
|
+
: Object.freeze({ ...target, pending: 'delete', clientMsgId: change.clientMsgId })
|
|
499
|
+
set({ ...state, messages: mapAll(state.messages, (m) => (m === target ? next : m)) })
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** A row of the shown conversation (any, before the discussion has one). */
|
|
503
|
+
const ofThisConversation = (m: DiscussionMessage): boolean => state.conversationId === null || sameId(m.conversationId, state.conversationId)
|
|
504
|
+
|
|
505
|
+
function confirm(change: Extract<MessageChange, { type: 'confirm' }>): void {
|
|
506
|
+
const settled = pending.get(change.clientMsgId)
|
|
507
|
+
// The answer to a change reset() or another article dropped (a write that outlived the switch).
|
|
508
|
+
if (!settled && retired.has(change.clientMsgId)) return
|
|
509
|
+
pending.delete(change.clientMsgId)
|
|
510
|
+
const parsed = messageOf(change.message, change.message?.replyToSeq === null || change.message?.replyToSeq === undefined)
|
|
511
|
+
const row = parsed && ofThisConversation(parsed) ? parsed : null
|
|
512
|
+
// The optimistic row goes in every case; a row this SDK cannot render, or another conversation's, is not shown in its place.
|
|
513
|
+
const withoutOptimistic = mapAll(state.messages, (m) =>
|
|
514
|
+
m.clientMsgId === change.clientMsgId && m.pending === 'post' ? null : m.clientMsgId === change.clientMsgId ? stripPending(m) : m,
|
|
515
|
+
)
|
|
516
|
+
if (!row) {
|
|
517
|
+
if (withoutOptimistic !== state.messages) set({ ...state, messages: withoutOptimistic })
|
|
518
|
+
return
|
|
519
|
+
}
|
|
520
|
+
const warnings = change.warnings ? codesOf(change.warnings) : undefined
|
|
521
|
+
const stored: DiscussionMessage = warnings && warnings.length > 0 ? Object.freeze({ ...row, warnings }) : row
|
|
522
|
+
const existed = findIn(withoutOptimistic, (m) => m.seq === stored.seq)
|
|
523
|
+
let messages: readonly DiscussionMessage[]
|
|
524
|
+
let count = state.count
|
|
525
|
+
if (stored.state === 'deleted' || settled?.type === 'delete') {
|
|
526
|
+
const current = existed ?? null
|
|
527
|
+
const wasVisible = current?.state === 'visible' && current.body !== null
|
|
528
|
+
messages = mapAll(withoutOptimistic, (m) =>
|
|
529
|
+
m.seq !== stored.seq ? m : keepsPlaceholder(m) ? Object.freeze({ ...stored, replies: m.replies }) : null,
|
|
530
|
+
)
|
|
531
|
+
if (wasVisible) count = Math.max(0, count - 1)
|
|
532
|
+
} else {
|
|
533
|
+
messages = upsert(withoutOptimistic, stored)
|
|
534
|
+
if (!existed && stored.state === 'visible') count += 1
|
|
535
|
+
}
|
|
536
|
+
set({
|
|
537
|
+
...state,
|
|
538
|
+
// The answer to this store's own change names the new conversation; a row it never saw may be another article's.
|
|
539
|
+
conversationId: state.conversationId ?? (settled ? stored.conversationId : null),
|
|
540
|
+
lastSeq: Math.max(state.lastSeq, stored.seq),
|
|
541
|
+
count,
|
|
542
|
+
messages,
|
|
543
|
+
})
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function rollback(clientMsgId: string): void {
|
|
547
|
+
const change = pending.get(clientMsgId)
|
|
548
|
+
if (!change) return
|
|
549
|
+
pending.delete(clientMsgId)
|
|
550
|
+
const messages = mapAll(state.messages, (m) => {
|
|
551
|
+
if (m.clientMsgId !== clientMsgId) return m
|
|
552
|
+
if (change.type === 'post') return null
|
|
553
|
+
const before = change.before
|
|
554
|
+
if (!before) return stripPending(m)
|
|
555
|
+
return m.replyToSeq === null ? Object.freeze({ ...before, replies: m.replies }) : before
|
|
556
|
+
})
|
|
557
|
+
if (messages !== state.messages) set({ ...state, messages })
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function server(raw: PublicMessage): void {
|
|
561
|
+
const row = messageOf(raw, raw?.replyToSeq === null || raw?.replyToSeq === undefined)
|
|
562
|
+
// Only in place of the loaded row it is: its seq in its conversation, with no change of the viewer's waiting.
|
|
563
|
+
if (!row || !findIn(state.messages, (m) => m.seq === row.seq && !m.pending && sameId(m.conversationId, row.conversationId))) return
|
|
564
|
+
set({ ...state, messages: replaceBySeq(state.messages, row) })
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function applyMessage(change: MessageChange): void {
|
|
568
|
+
if (!isRecord(change)) return
|
|
569
|
+
switch (change.type) {
|
|
570
|
+
case 'post':
|
|
571
|
+
return optimisticPost(change)
|
|
572
|
+
case 'edit':
|
|
573
|
+
case 'delete':
|
|
574
|
+
return optimisticChange(change)
|
|
575
|
+
case 'confirm':
|
|
576
|
+
return confirm(change)
|
|
577
|
+
case 'rollback':
|
|
578
|
+
return rollback(change.clientMsgId)
|
|
579
|
+
case 'server':
|
|
580
|
+
return server(change.message)
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function applyHead(head: DiscussionHead): boolean {
|
|
585
|
+
if (!isRecord(head) || !state.loaded || state.articleId === null) return false
|
|
586
|
+
if (str(head.articleId)?.toLowerCase() !== state.articleId) return false
|
|
587
|
+
if (state.stale) return true
|
|
588
|
+
const newerSeq = typeof head.lastSeq === 'number' && head.lastSeq > state.lastSeq
|
|
589
|
+
const newerCount = typeof head.count === 'number' && head.count !== state.count
|
|
590
|
+
const changeAt = str(head.lastChangeAt)
|
|
591
|
+
const newerChange = changeAt !== null && (state.lastChangeAt === null || Date.parse(changeAt) > Date.parse(state.lastChangeAt))
|
|
592
|
+
if (!newerSeq && !newerCount && !newerChange) return false
|
|
593
|
+
set({ ...state, stale: true })
|
|
594
|
+
return true
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function applyReaction(target: ReactionTarget, reactions: ReactionSummary): void {
|
|
598
|
+
if (!isRecord(target)) return
|
|
599
|
+
const summary = reactionsOf(reactions)
|
|
600
|
+
if ('articleId' in target) {
|
|
601
|
+
if (str(target.articleId)?.toLowerCase() !== state.articleId) return
|
|
602
|
+
set({ ...state, articleReactions: summary })
|
|
603
|
+
return
|
|
604
|
+
}
|
|
605
|
+
const { conversationId, seq } = target as { conversationId: unknown; seq: unknown }
|
|
606
|
+
if (!isSeq(seq) || typeof conversationId !== 'string') return
|
|
607
|
+
const id = conversationId.toLowerCase()
|
|
608
|
+
const messages = mapAll(state.messages, (m) => (m.seq === seq && m.conversationId.toLowerCase() === id ? Object.freeze({ ...m, reactions: summary }) : m))
|
|
609
|
+
if (messages !== state.messages) set({ ...state, messages })
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function collapse(memberId: string, blocked: boolean): void {
|
|
613
|
+
if (typeof memberId !== 'string' || memberId === '') return
|
|
614
|
+
const id = memberId.toLowerCase()
|
|
615
|
+
const messages = mapAll(state.messages, (m) =>
|
|
616
|
+
m.author.kind === 'member' && m.author.memberId !== null && m.author.memberId.toLowerCase() === id && m.body !== null && m.collapsed !== blocked
|
|
617
|
+
? Object.freeze({ ...m, collapsed: blocked })
|
|
618
|
+
: m,
|
|
619
|
+
)
|
|
620
|
+
if (messages !== state.messages) set({ ...state, messages })
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
const store: DiscussionStore = {
|
|
624
|
+
getState: () => state,
|
|
625
|
+
subscribe(listener) {
|
|
626
|
+
listeners.add(listener)
|
|
627
|
+
return () => {
|
|
628
|
+
listeners.delete(listener)
|
|
629
|
+
}
|
|
630
|
+
},
|
|
631
|
+
applyPage,
|
|
632
|
+
applyMessage,
|
|
633
|
+
applyHead,
|
|
634
|
+
applyReaction,
|
|
635
|
+
collapse,
|
|
636
|
+
reset() {
|
|
637
|
+
nextGeneration()
|
|
638
|
+
set(EMPTY)
|
|
639
|
+
},
|
|
640
|
+
}
|
|
641
|
+
generations.set(store, () => generation)
|
|
642
|
+
return store
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** The message without its optimistic marks (a settled change whose row could not be shown). */
|
|
646
|
+
function stripPending(m: DiscussionMessage): DiscussionMessage {
|
|
647
|
+
const { pending: _p, clientMsgId: _c, ...rest } = m
|
|
648
|
+
return Object.freeze(rest)
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ───────────────────────── selectors ─────────────────────────
|
|
652
|
+
|
|
653
|
+
/** What the composer waits for, from the viewer's known needs. */
|
|
654
|
+
export interface ViewerNeeds {
|
|
655
|
+
/** No session that can write: offer the sign-in. */
|
|
656
|
+
readonly signIn: boolean
|
|
657
|
+
/** A first join: the age band, the rules, the profile. */
|
|
658
|
+
readonly onboarding: boolean
|
|
659
|
+
/** The rules' acceptance (a first join, or a newer rules text that asks again). */
|
|
660
|
+
readonly rules: boolean
|
|
661
|
+
/** The consent the tenant asks for before writing. */
|
|
662
|
+
readonly art9: boolean
|
|
663
|
+
/** Any of these. */
|
|
664
|
+
readonly any: boolean
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
export function viewerNeeds(state: Pick<DiscussionState, 'viewer'> | { needs: readonly unknown[] }): ViewerNeeds {
|
|
668
|
+
const raw = 'viewer' in state ? state.viewer.needs : state.needs
|
|
669
|
+
const needs = new Set(raw.filter(isKnownNeed))
|
|
670
|
+
const signIn = needs.has('sign_in')
|
|
671
|
+
const onboarding = needs.has('onboarding')
|
|
672
|
+
const rules = onboarding || needs.has('reconsent_rules')
|
|
673
|
+
const art9 = needs.has('art9_consent')
|
|
674
|
+
return Object.freeze({ signIn, onboarding, rules, art9, any: signIn || onboarding || rules || art9 })
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** A loaded message (top-level or reply) by its seq, or null. */
|
|
678
|
+
export function findMessage(state: Pick<DiscussionState, 'messages'>, seq: number): DiscussionMessage | null {
|
|
679
|
+
return findIn(state.messages, (m) => m.seq === seq)
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** The viewer wrote it (a member message whose author is the viewer). */
|
|
683
|
+
export function isOwnMessage(state: Pick<DiscussionState, 'viewer'>, message: Pick<DiscussionMessage, 'author'>): boolean {
|
|
684
|
+
return message.author.kind === 'member' && message.author.memberId !== null && message.author.memberId === state.viewer.memberId
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** The reactions of the article or of one loaded message. */
|
|
688
|
+
export function reactionsFor(state: DiscussionState, target: ReactionTarget): ReactionSummary {
|
|
689
|
+
if ('articleId' in target) return state.articleReactions
|
|
690
|
+
const id = target.conversationId.toLowerCase()
|
|
691
|
+
const m = findIn(state.messages, (x) => x.seq === target.seq && x.conversationId.toLowerCase() === id)
|
|
692
|
+
return m?.reactions ?? NO_REACTIONS
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* The summary after the viewer sets `emoji` (null: removes theirs) — one reaction per member, so the previous one
|
|
697
|
+
* gives up its count. For an optimistic `applyReaction` before `reactions.set` answers; keep the old summary to undo.
|
|
698
|
+
*/
|
|
699
|
+
export function reactionAfter(summary: ReactionSummary, emoji: string | null): ReactionSummary {
|
|
700
|
+
const counts: Record<string, number> = { ...summary.counts }
|
|
701
|
+
const mine = summary.mine
|
|
702
|
+
if (mine !== null) {
|
|
703
|
+
const n = (counts[mine] ?? 0) - 1
|
|
704
|
+
if (n > 0) counts[mine] = n
|
|
705
|
+
else delete counts[mine]
|
|
706
|
+
}
|
|
707
|
+
if (emoji !== null) counts[emoji] = (counts[emoji] ?? 0) + 1
|
|
708
|
+
return Object.freeze({ counts: Object.freeze(counts), mine: emoji })
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// ───────────────────────── loading through the client ─────────────────────────
|
|
712
|
+
|
|
713
|
+
/** Pages one refresh may read before it stops (the rest stays behind „load more"). */
|
|
714
|
+
const REFRESH_MAX_PAGES = 20
|
|
715
|
+
|
|
716
|
+
type ListClient = Pick<CommunityClient, 'discussions'>
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Where a store is (its generation, the article it shows), so a loader can tell whether it moved on — reset(), a
|
|
720
|
+
* page of another article — while a page was on its way. A store of another make has no generation: the article
|
|
721
|
+
* it shows is the sign.
|
|
722
|
+
*/
|
|
723
|
+
function placeOf(store: DiscussionStore): { moved(): boolean; mark(): void } {
|
|
724
|
+
const generation = generations.get(store)
|
|
725
|
+
let at = generation?.()
|
|
726
|
+
let articleId = store.getState().articleId
|
|
727
|
+
return {
|
|
728
|
+
moved: () => (generation !== undefined && generation() !== at) || store.getState().articleId !== articleId,
|
|
729
|
+
mark() {
|
|
730
|
+
at = generation?.()
|
|
731
|
+
articleId = store.getState().articleId
|
|
732
|
+
},
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const cursorOf = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Loads the discussion, or brings the loaded pages up to date (after a newer head): the first page, then the next
|
|
740
|
+
* ones until the pages loaded before are covered — to the end when the end was loaded. The first failure is the
|
|
741
|
+
* outcome (the pages read before it stay applied). A page that comes back after the store moved on (reset(), a
|
|
742
|
+
* page of another article) is not applied, and the refresh ends there with the store as it is.
|
|
743
|
+
*/
|
|
744
|
+
export async function refreshDiscussion(
|
|
745
|
+
store: DiscussionStore,
|
|
746
|
+
client: ListClient,
|
|
747
|
+
input: { articleId: string; languageCode?: string | null },
|
|
748
|
+
options?: CommunityCallOptions,
|
|
749
|
+
): Promise<CommunityOutcome<DiscussionState>> {
|
|
750
|
+
const before = store.getState()
|
|
751
|
+
// The end of the pages loaded before (null: the end itself); a first load reads one page.
|
|
752
|
+
const until = before.loaded ? before.nextCursor : 0
|
|
753
|
+
const place = placeOf(store)
|
|
754
|
+
let cursor: number | null = null
|
|
755
|
+
for (let page = 0; page < REFRESH_MAX_PAGES; page++) {
|
|
756
|
+
const r = await client.discussions.list({ articleId: input.articleId, languageCode: input.languageCode ?? null, cursor }, options)
|
|
757
|
+
if (!r.ok) return r
|
|
758
|
+
if (place.moved()) break
|
|
759
|
+
store.applyPage(r.value, { cursor })
|
|
760
|
+
// This refresh's own page may have started the store on another article.
|
|
761
|
+
place.mark()
|
|
762
|
+
const next = cursorOf(r.value.nextCursor)
|
|
763
|
+
if (next === null || (until !== null && next >= until) || (cursor !== null && next <= cursor)) break
|
|
764
|
+
cursor = next
|
|
765
|
+
}
|
|
766
|
+
return { ok: true, value: store.getState() }
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* The next page after the loaded ones („load more"); a store with the end loaded asks nothing, and a page that
|
|
771
|
+
* comes back after the store moved on (reset(), a page of another article) is not applied.
|
|
772
|
+
*/
|
|
773
|
+
export async function loadMoreDiscussion(
|
|
774
|
+
store: DiscussionStore,
|
|
775
|
+
client: ListClient,
|
|
776
|
+
input: { articleId: string; languageCode?: string | null },
|
|
777
|
+
options?: CommunityCallOptions,
|
|
778
|
+
): Promise<CommunityOutcome<DiscussionState>> {
|
|
779
|
+
const cursor = store.getState().nextCursor
|
|
780
|
+
if (cursor === null) return { ok: true, value: store.getState() }
|
|
781
|
+
const place = placeOf(store)
|
|
782
|
+
const r = await client.discussions.list({ articleId: input.articleId, languageCode: input.languageCode ?? null, cursor }, options)
|
|
783
|
+
if (!r.ok) return r
|
|
784
|
+
if (!place.moved()) store.applyPage(r.value, { cursor })
|
|
785
|
+
return { ok: true, value: store.getState() }
|
|
786
|
+
}
|