@estiva-app/conversation 0.30.0 → 0.32.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/CHANGELOG.md +45 -0
- package/README.md +3 -0
- package/dist/decorations.d.ts +9 -14
- package/dist/decorations.d.ts.map +1 -1
- package/dist/decorations.js +7 -25
- package/dist/decorations.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/lines.d.ts +76 -0
- package/dist/lines.d.ts.map +1 -0
- package/dist/lines.js +126 -0
- package/dist/lines.js.map +1 -0
- package/dist/references.d.ts +8 -1
- package/dist/references.d.ts.map +1 -1
- package/dist/references.js +23 -3
- package/dist/references.js.map +1 -1
- package/dist/resolution.d.ts +59 -0
- package/dist/resolution.d.ts.map +1 -0
- package/dist/resolution.js +82 -0
- package/dist/resolution.js.map +1 -0
- package/dist/shape.d.ts +98 -0
- package/dist/shape.d.ts.map +1 -0
- package/dist/shape.js +148 -0
- package/dist/shape.js.map +1 -0
- package/package.json +2 -2
- package/src/decorations.ts +13 -34
- package/src/index.ts +15 -2
- package/src/lines.ts +166 -0
- package/src/references.ts +32 -4
- package/src/resolution.ts +112 -0
- package/src/shape.ts +228 -0
package/src/lines.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a message's lines draw — the one line rule (SPEC §13.2, §13.6.2, C21),
|
|
3
|
+
* shared since ONE-2. It replaces Peek's and Ship's `messageLines.ts`, Leaf's
|
|
4
|
+
* `commentLines.ts` and Peek's `urlNames`, three copies that had drifted.
|
|
5
|
+
*
|
|
6
|
+
* A sentence keeps its chips; a line that is only a link to a file or a
|
|
7
|
+
* message is that file's row; and one whose file has a card or a part under
|
|
8
|
+
* the message draws nothing, since the card stands for it (C26). A person or a
|
|
9
|
+
* Folder alone on its line stays a chip, and a quote's or a heading's line is a
|
|
10
|
+
* sentence (protocol `lineDrawOf`).
|
|
11
|
+
*
|
|
12
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-on-words-counts-toward-the-card.md
|
|
13
|
+
*/
|
|
14
|
+
import {
|
|
15
|
+
lineDrawOf,
|
|
16
|
+
linesOf,
|
|
17
|
+
referenceOfLink,
|
|
18
|
+
type Embed,
|
|
19
|
+
type LinkResolver,
|
|
20
|
+
type PartPointer,
|
|
21
|
+
type RenderBlock,
|
|
22
|
+
type RenderInline,
|
|
23
|
+
} from '@estiva-app/protocol'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A line of a message that is only a link to a file or a message, drawn as
|
|
27
|
+
* that file's row in place. `reference` is the `nostr:` reference the line
|
|
28
|
+
* names; `unreadable` is one that names no address or event id, drawn as the
|
|
29
|
+
* not-available row.
|
|
30
|
+
*/
|
|
31
|
+
export interface RowLine {
|
|
32
|
+
reference: string
|
|
33
|
+
/** The file's value (an address or an id), when the line names one. */
|
|
34
|
+
value?: string
|
|
35
|
+
unreadable?: true
|
|
36
|
+
/** The URL the line was written as, when it names that same file: the row opens it as written (LTX-6). */
|
|
37
|
+
url?: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A paragraph's line that is a row, lifted out as a block of its own, so the row is not drawn inside a `<p>`. */
|
|
41
|
+
export const ROW_BLOCK = 'linkRow'
|
|
42
|
+
|
|
43
|
+
/** The answer of {@link placeLines}. */
|
|
44
|
+
export interface PlacedLines {
|
|
45
|
+
blocks: RenderBlock[]
|
|
46
|
+
/** The row a block of type {@link ROW_BLOCK} draws. */
|
|
47
|
+
rowOf: (block: { type: string; attrs?: Record<string, unknown> }) => RowLine | undefined
|
|
48
|
+
/** The row a list item's only run draws, by that run: a bullet that is only a link keeps its bullet. */
|
|
49
|
+
rowRuns: ReadonlyMap<object, RowLine>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What a line's drawing reads beyond the line. */
|
|
53
|
+
export interface LineContext {
|
|
54
|
+
/** The message's cards (`foldEmbeds`, `cardsIn`): a line whose file has one draws nothing. */
|
|
55
|
+
cards?: readonly Embed[]
|
|
56
|
+
/** The `part`s drawn under the message: a line whose file has one draws nothing. */
|
|
57
|
+
parts?: readonly PartPointer[]
|
|
58
|
+
/** What an app link names (§7.7), as answered so far. */
|
|
59
|
+
resolveLink?: LinkResolver
|
|
60
|
+
/**
|
|
61
|
+
* Values whose lines stay sentences, their chip only: the file the message
|
|
62
|
+
* is shown on draws no row of itself there (Miky, WID-3).
|
|
63
|
+
*/
|
|
64
|
+
stayChip?: (value: string) => boolean
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The URL a run wrote for its reference, when the URL names that same file:
|
|
69
|
+
* what its chip or row opens (LTX-6). A marker or a block comment can set any
|
|
70
|
+
* URL's text on a reference to another file, so the text must itself read as
|
|
71
|
+
* it; without `resolveLink` nothing can be checked and there is none.
|
|
72
|
+
*/
|
|
73
|
+
export function writtenUrlOf(run: Pick<RenderInline, 'text' | 'reference'>, resolveLink: LinkResolver | undefined): string | undefined {
|
|
74
|
+
if (!run.reference || !resolveLink || !/^https?:\/\//i.test(run.text)) return undefined
|
|
75
|
+
return referenceOfLink(run.text, resolveLink) === run.reference ? run.text : undefined
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Whether a pasted app link names this address: its path ends in the
|
|
80
|
+
* address's `d` (§7.2 puts the identity last, `…/<slug>-<d>`), and that `d` is
|
|
81
|
+
* long enough to be one. A `d` comes from somebody's tag, so a short one would
|
|
82
|
+
* otherwise match half the links in a body.
|
|
83
|
+
*/
|
|
84
|
+
export function urlNames(url: string, address: string): boolean {
|
|
85
|
+
const d = address.split(':')[2] ?? ''
|
|
86
|
+
if (d.length < 8) return false
|
|
87
|
+
const path = url.split(/[?#]/)[0].replace(/\/+$/, '')
|
|
88
|
+
return path.endsWith(`-${d}`) || path.endsWith(`/${d}`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const BREAK: RenderInline = { text: '\n', marks: [] }
|
|
92
|
+
|
|
93
|
+
function rowLineOf(line: readonly RenderInline[], block: Pick<RenderBlock, 'type'>, context: LineContext): RowLine | 'nothing' | undefined {
|
|
94
|
+
const drawn = lineDrawOf(line, block, context)
|
|
95
|
+
if ((drawn.draw === 'row' || drawn.draw === 'nothing') && context.stayChip?.(drawn.value)) return undefined
|
|
96
|
+
if (drawn.draw === 'nothing') return 'nothing'
|
|
97
|
+
if (drawn.draw === 'unreadable') return { reference: drawn.reference, unreadable: true }
|
|
98
|
+
// A URL whose file is not read yet stays the link it was; once read, `linksAsReferences` made it a reference.
|
|
99
|
+
if (drawn.draw !== 'row' || drawn.url) return undefined
|
|
100
|
+
const run = line.find((r) => r.reference)
|
|
101
|
+
if (!run?.reference) return undefined
|
|
102
|
+
const url = writtenUrlOf(run, context.resolveLink)
|
|
103
|
+
return { reference: run.reference, value: drawn.value, ...(url ? { url } : {}) }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Where each of a message's lines draws. `blocks` is its tree after
|
|
108
|
+
* `linksAsReferences`, so a lone app URL this reader can read is already its
|
|
109
|
+
* reference, and one it cannot stays the URL as written.
|
|
110
|
+
*/
|
|
111
|
+
export function placeLines(blocks: readonly RenderBlock[], context: LineContext = {}): PlacedLines {
|
|
112
|
+
const rows = new Map<object, RowLine>()
|
|
113
|
+
const rowRuns = new Map<RenderInline, RowLine>()
|
|
114
|
+
const out: RenderBlock[] = []
|
|
115
|
+
for (const block of blocks) {
|
|
116
|
+
if (block.type === 'paragraph') {
|
|
117
|
+
const lines = linesOf(block)
|
|
118
|
+
const drawn = lines.map((line) => rowLineOf(line, block, context))
|
|
119
|
+
if (drawn.every((d) => d === undefined)) {
|
|
120
|
+
out.push(block)
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
let sentence: RenderInline[][] = []
|
|
124
|
+
let first = true
|
|
125
|
+
const flush = () => {
|
|
126
|
+
if (!sentence.length) return
|
|
127
|
+
const inline = sentence.flatMap((line, i) => (i > 0 ? [BREAK, ...line] : line))
|
|
128
|
+
out.push({ ...block, inline, ...(first ? {} : { id: undefined }) })
|
|
129
|
+
first = false
|
|
130
|
+
sentence = []
|
|
131
|
+
}
|
|
132
|
+
lines.forEach((line, i) => {
|
|
133
|
+
const d = drawn[i]
|
|
134
|
+
if (d === undefined) {
|
|
135
|
+
sentence.push(line)
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
flush()
|
|
139
|
+
if (d === 'nothing') return
|
|
140
|
+
// Not a protocol block: a drawer hands a type it has no design for to its own renderer.
|
|
141
|
+
const row = { type: ROW_BLOCK, attrs: {} } as unknown as RenderBlock
|
|
142
|
+
rows.set(row, d)
|
|
143
|
+
out.push(row)
|
|
144
|
+
})
|
|
145
|
+
flush()
|
|
146
|
+
continue
|
|
147
|
+
}
|
|
148
|
+
if (block.type === 'bulletList' || block.type === 'orderedList') {
|
|
149
|
+
const items = (block.children ?? []).flatMap((item) => {
|
|
150
|
+
const lines = linesOf(item)
|
|
151
|
+
if (lines.length !== 1) return [item]
|
|
152
|
+
const d = rowLineOf(lines[0], item, context)
|
|
153
|
+
if (d === undefined) return [item]
|
|
154
|
+
if (d === 'nothing') return []
|
|
155
|
+
// A fresh run, so the map names this line and no other drawing of the same body.
|
|
156
|
+
const run = { ...lines[0].find((r) => r.reference || r.text.trim())! }
|
|
157
|
+
rowRuns.set(run, d)
|
|
158
|
+
return [{ ...item, inline: [run] }]
|
|
159
|
+
})
|
|
160
|
+
if (items.length) out.push({ ...block, children: items })
|
|
161
|
+
continue
|
|
162
|
+
}
|
|
163
|
+
out.push(block)
|
|
164
|
+
}
|
|
165
|
+
return { blocks: out, rowOf: (block) => rows.get(block), rowRuns }
|
|
166
|
+
}
|
package/src/references.ts
CHANGED
|
@@ -45,9 +45,16 @@ export interface ReferenceCandidate {
|
|
|
45
45
|
/**
|
|
46
46
|
* A file's summary (SPEC §6.12), plain text on one line: the row's second
|
|
47
47
|
* line, with `caption` moving up beside the title. Absent when the file has
|
|
48
|
-
* none, and on a message.
|
|
48
|
+
* none, and on a message. For a file the relay found only by its text, the
|
|
49
|
+
* words around the match instead.
|
|
49
50
|
*/
|
|
50
51
|
summary?: string
|
|
52
|
+
/**
|
|
53
|
+
* The fields a relay's search found the typed words in, best first (SPEC
|
|
54
|
+
* §6.13 `matches`): a file found by its summary, key or text is offered
|
|
55
|
+
* though its title does not hold them, after every title match.
|
|
56
|
+
*/
|
|
57
|
+
matched?: readonly string[]
|
|
51
58
|
/**
|
|
52
59
|
* Matched beside `title`: a message's own words ({@link messageWords}), an
|
|
53
60
|
* issue's ref (`CON-33`). A message without it is matched on `caption`.
|
|
@@ -279,12 +286,33 @@ export function refMatch(ref: string | undefined, query: string): number {
|
|
|
279
286
|
return score === 8 || score % 4 === 3 ? score : 0
|
|
280
287
|
}
|
|
281
288
|
|
|
282
|
-
/**
|
|
289
|
+
/**
|
|
290
|
+
* How well a relay's search says a file matched, below any title match (1 and
|
|
291
|
+
* up): its summary or key, then only its text. Title first, then summary and
|
|
292
|
+
* key, then text, as the relay ranks them.
|
|
293
|
+
*
|
|
294
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/search-finds-a-file-by-the-words-of-its-current-fields.md
|
|
295
|
+
*/
|
|
296
|
+
function relayMatch(matched: readonly string[] | undefined): number {
|
|
297
|
+
const best = matched?.[0]
|
|
298
|
+
if (!best) return 0
|
|
299
|
+
return best === 'title' ? 1 : best === 'text' ? 0.25 : 0.5
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Keeps each id once, at its closest tier, with what a search found it by: a
|
|
304
|
+
* file in your Folder found only by its text still shows the words around them.
|
|
305
|
+
*/
|
|
283
306
|
function closest(candidates: readonly ReferenceCandidate[]): ReferenceCandidate[] {
|
|
284
307
|
const best = new Map<string, ReferenceCandidate>()
|
|
285
308
|
for (const c of candidates) {
|
|
286
309
|
const known = best.get(c.id)
|
|
287
|
-
if (!known
|
|
310
|
+
if (!known) {
|
|
311
|
+
best.set(c.id, c)
|
|
312
|
+
continue
|
|
313
|
+
}
|
|
314
|
+
const [near, far] = c.tier < known.tier ? [c, known] : [known, c]
|
|
315
|
+
best.set(c.id, far.matched && !near.matched ? { ...near, matched: far.matched, ...(far.summary !== undefined ? { summary: far.summary } : {}) } : near)
|
|
288
316
|
}
|
|
289
317
|
return [...best.values()]
|
|
290
318
|
}
|
|
@@ -315,7 +343,7 @@ export function rankReferences({ messages, files, query, ownKinds = [], caps = R
|
|
|
315
343
|
|
|
316
344
|
const shownFiles = closest(files)
|
|
317
345
|
.filter((f) => !excluded.has(f.id) && (typed || f.tier !== FILE_TIER.search))
|
|
318
|
-
.map((f) => ({ f, score: typed ? Math.max(referenceMatch(f.title, query), refMatch(f.search, query)) : 0 }))
|
|
346
|
+
.map((f) => ({ f, score: typed ? Math.max(referenceMatch(f.title, query), refMatch(f.search, query), relayMatch(f.matched)) : 0 }))
|
|
319
347
|
.filter(({ score }) => !typed || score > 0)
|
|
320
348
|
.sort(
|
|
321
349
|
(a, b) =>
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolving a thread — SPEC §6.4, "Resolving a thread" (ONE-2), and C51.
|
|
3
|
+
*
|
|
4
|
+
* A `kind:9101` with `t=resolution` resolves or reopens the thread of the
|
|
5
|
+
* top-level message its first unmarked `e` names. Anyone who may write in that
|
|
6
|
+
* message's Folder may write one, and **the newest counts, in §6.3's order**
|
|
7
|
+
* (`byOrder`): `ts` when trusted, then `created_at`, then the higher id.
|
|
8
|
+
* A reader ignores one whose `h` is not its target's Folder, one about a reply
|
|
9
|
+
* (never walked to its root), and drops a `support` outside the thread.
|
|
10
|
+
*
|
|
11
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/anyone-who-may-comment-resolves-or-reopens-a-thread-and-the-newest-counts.md
|
|
12
|
+
*/
|
|
13
|
+
import type { SignedEvent } from '@estiva-app/protocol'
|
|
14
|
+
import { isEventId, KIND_ASSERTION } from './kinds.js'
|
|
15
|
+
import { orderingMs } from './order.js'
|
|
16
|
+
|
|
17
|
+
/** A `kind:9101` resolution assertion on a message (PEEK-128, SPEC §6.4). */
|
|
18
|
+
export interface Resolution {
|
|
19
|
+
id: string
|
|
20
|
+
action: 'resolved' | 'reopened'
|
|
21
|
+
by: string
|
|
22
|
+
/** `created_at`, seconds. */
|
|
23
|
+
at: number
|
|
24
|
+
/** Where it sorts, epoch milliseconds: the trusted `ts`, else `at` × 1000 (§6.3). */
|
|
25
|
+
orderMs: number
|
|
26
|
+
/** Its `h`: the Folder it was filed in, which must be its target's. */
|
|
27
|
+
folder?: string
|
|
28
|
+
/** The assertion's free text, when it carried one. */
|
|
29
|
+
message?: string
|
|
30
|
+
/** The reply that carried the resolution, when the writer named one. */
|
|
31
|
+
supportingEventId?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const tagValue = (event: Pick<SignedEvent, 'tags'>, name: string) => event.tags.find((t) => t[0] === name)?.[1]
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The message a `kind:9101` is about: its **first unmarked `e`**, lowercased.
|
|
38
|
+
* Not the first one a reader happens to hold — a resolve listing a stranger
|
|
39
|
+
* first and a thread second is about the stranger.
|
|
40
|
+
*/
|
|
41
|
+
export function resolutionTargetOf(event: Pick<SignedEvent, 'tags'>): string | undefined {
|
|
42
|
+
const tag = event.tags.find((t) => t[0] === 'e' && !t[3])
|
|
43
|
+
return tag && isEventId(tag[1]) ? tag[1].toLowerCase() : undefined
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The event read as a {@link Resolution} with its target, or undefined when it is not one. */
|
|
47
|
+
export function resolutionOfEvent(event: SignedEvent): { target: string; resolution: Resolution } | undefined {
|
|
48
|
+
if (event.kind !== KIND_ASSERTION || tagValue(event, 't') !== 'resolution') return undefined
|
|
49
|
+
const action = tagValue(event, 'action')
|
|
50
|
+
if (action !== 'resolved' && action !== 'reopened') return undefined
|
|
51
|
+
const target = resolutionTargetOf(event)
|
|
52
|
+
if (!target) return undefined
|
|
53
|
+
const support = event.tags.find((t) => t[0] === 'e' && t[3] === 'support')?.[1]
|
|
54
|
+
const folder = tagValue(event, 'h')
|
|
55
|
+
return {
|
|
56
|
+
target,
|
|
57
|
+
resolution: {
|
|
58
|
+
id: event.id,
|
|
59
|
+
action,
|
|
60
|
+
by: event.pubkey,
|
|
61
|
+
at: event.created_at,
|
|
62
|
+
orderMs: orderingMs(event),
|
|
63
|
+
...(folder ? { folder } : {}),
|
|
64
|
+
...(event.content ? { message: event.content } : {}),
|
|
65
|
+
...(isEventId(support) ? { supportingEventId: support.toLowerCase() } : {}),
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Oldest first by §6.3: `ts` when trusted, then `created_at`, then the lower id. */
|
|
71
|
+
export const byResolutionOrder = (a: Resolution, b: Resolution): number =>
|
|
72
|
+
a.orderMs - b.orderMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A thread's state: the newest of `resolutions` that counts, or undefined when
|
|
76
|
+
* none does (never resolved, or only ones a reader ignores).
|
|
77
|
+
*
|
|
78
|
+
* `resolutions` are those whose target is the thread's **top-level** message;
|
|
79
|
+
* one about a reply is never passed here. `folder` is that message's Folder
|
|
80
|
+
* (for a top-level message the read did not return, its replies'), and
|
|
81
|
+
* `replies` the thread's reply ids: a `support` naming anything else is
|
|
82
|
+
* dropped and the resolve stands.
|
|
83
|
+
*/
|
|
84
|
+
export function resolutionOf(
|
|
85
|
+
resolutions: readonly Resolution[],
|
|
86
|
+
thread: { folder: string | undefined; replies: readonly string[] },
|
|
87
|
+
): Resolution | undefined {
|
|
88
|
+
if (!thread.folder) return undefined
|
|
89
|
+
const newest = resolutions
|
|
90
|
+
.filter((r) => r.folder === thread.folder)
|
|
91
|
+
.sort(byResolutionOrder)
|
|
92
|
+
.at(-1)
|
|
93
|
+
if (!newest?.supportingEventId) return newest
|
|
94
|
+
const replies = new Set(thread.replies.map((id) => id.toLowerCase()))
|
|
95
|
+
if (replies.has(newest.supportingEventId)) return newest
|
|
96
|
+
const { supportingEventId: _dropped, ...kept } = newest
|
|
97
|
+
return kept
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Every resolution in `events`, by target id, oldest first (§6.3). */
|
|
101
|
+
export function resolutionsByTarget(events: readonly SignedEvent[]): Record<string, Resolution[]> {
|
|
102
|
+
const out: Record<string, Resolution[]> = {}
|
|
103
|
+
const seen = new Set<string>()
|
|
104
|
+
for (const event of events) {
|
|
105
|
+
if (seen.has(event.id)) continue
|
|
106
|
+
seen.add(event.id)
|
|
107
|
+
const read = resolutionOfEvent(event)
|
|
108
|
+
if (read) (out[read.target] ??= []).push(read.resolution)
|
|
109
|
+
}
|
|
110
|
+
for (const list of Object.values(out)) list.sort(byResolutionOrder)
|
|
111
|
+
return out
|
|
112
|
+
}
|
package/src/shape.ts
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One shape for a message, a reply and a thread — SPEC §6.3–§6.8 and §6.4's
|
|
3
|
+
* "Resolving a thread", folded once for every app (ONE-2).
|
|
4
|
+
*
|
|
5
|
+
* Peek, Ship and Leaf each read a conversation into their own shape until
|
|
6
|
+
* now, and they disagreed: on which resolve counts, on what a deleted
|
|
7
|
+
* comment's thread shows, and on whether a reaction is known by its person's
|
|
8
|
+
* key or name. {@link foldThreads} is the one answer. It draws nothing — the
|
|
9
|
+
* kit in `@estiva-app/ui` takes words and nodes, and this sits below it.
|
|
10
|
+
*
|
|
11
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-conversation-is-one-shared-thing-and-only-its-colours-are-the-apps.md
|
|
12
|
+
*/
|
|
13
|
+
import {
|
|
14
|
+
BLOCK_ANCHOR_TAG,
|
|
15
|
+
imetaOf,
|
|
16
|
+
partsOf,
|
|
17
|
+
quoteOf,
|
|
18
|
+
readRunIds,
|
|
19
|
+
type Embed,
|
|
20
|
+
type Imeta,
|
|
21
|
+
type PartPointer,
|
|
22
|
+
type Quote,
|
|
23
|
+
type SignedEvent,
|
|
24
|
+
} from '@estiva-app/protocol'
|
|
25
|
+
import { editsByTarget, foldEdits, foldEmbeds } from './edits.js'
|
|
26
|
+
import { isConversationKind, isEventId, KIND_COMMENT, KIND_DELETION, KIND_REACTION } from './kinds.js'
|
|
27
|
+
import { orderingMs } from './order.js'
|
|
28
|
+
import { groupReactions, reactionEventsOf, type Reaction } from './reactions.js'
|
|
29
|
+
import { resolutionOf, resolutionsByTarget, type Resolution } from './resolution.js'
|
|
30
|
+
import { groupThreads } from './threads.js'
|
|
31
|
+
|
|
32
|
+
/** One message — a top-level comment, a channel message or a reply — as it stands after its edits. */
|
|
33
|
+
export interface Message {
|
|
34
|
+
id: string
|
|
35
|
+
kind: number
|
|
36
|
+
/** Who wrote it, by key. */
|
|
37
|
+
author: string
|
|
38
|
+
/** Its `h`: the Folder it was filed in. */
|
|
39
|
+
folder?: string
|
|
40
|
+
/** When it was written, epoch milliseconds (§6.3: the trusted `ts`, else `created_at` × 1000). */
|
|
41
|
+
at: number
|
|
42
|
+
/** The text to show: the latest edit's, else its own (§6.8). */
|
|
43
|
+
body: string
|
|
44
|
+
/** Whether an edit changed the body — what a reader MUST mark (§6.8). */
|
|
45
|
+
edited: boolean
|
|
46
|
+
/** When the body last changed, epoch milliseconds. Absent unless `edited`. */
|
|
47
|
+
editedAt?: number
|
|
48
|
+
/** Its files: the latest edit's `imeta` set, else its own (§6.8, C15). */
|
|
49
|
+
files: Imeta[]
|
|
50
|
+
/** The cards its writer carried (`embed`, §13.6.2), after edits (C20). Which of them the body still names is the drawer's (`cardsIn`). */
|
|
51
|
+
cards: Embed[]
|
|
52
|
+
/** The blocks drawn live under it (`part`, §13.6.1). An edit carries none, so these are the message's own. */
|
|
53
|
+
parts: PartPointer[]
|
|
54
|
+
/** What its words link: its `a` and `q` values, or the latest edit's when it was edited, since an edit is the whole new message (§6.4, §6.8). */
|
|
55
|
+
links: string[]
|
|
56
|
+
/**
|
|
57
|
+
* What a comment on part of a document is about (§13.6): the run of blocks
|
|
58
|
+
* in its `block` tag, and the words in its `quote` when it quotes some. An
|
|
59
|
+
* edit never moves it.
|
|
60
|
+
*/
|
|
61
|
+
anchor?: { blocks: string[]; quote?: Quote }
|
|
62
|
+
/** Its reactions by emoji, each reactor by key (§6.6). */
|
|
63
|
+
reactions: Reaction[]
|
|
64
|
+
/** The event itself, for what this shape does not carry. */
|
|
65
|
+
event: SignedEvent
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The thread's top-level message, in one of §6.5's three states:
|
|
70
|
+
* - `present` — returned, and not deleted;
|
|
71
|
+
* - `deleted` — its author's `kind:5` came back: drawn as "This comment was
|
|
72
|
+
* deleted", its replies under it;
|
|
73
|
+
* - `missing` — only its replies were read. Drawn as their thread, never as
|
|
74
|
+
* deleted: it may only be outside the read.
|
|
75
|
+
*/
|
|
76
|
+
export type RootState = 'present' | 'deleted' | 'missing'
|
|
77
|
+
|
|
78
|
+
/** A thread: a top-level message, its replies, and its state. */
|
|
79
|
+
export interface Thread {
|
|
80
|
+
/** The top-level message's id, whether or not it was returned. */
|
|
81
|
+
id: string
|
|
82
|
+
state: RootState
|
|
83
|
+
/** The top-level message, when `present`. */
|
|
84
|
+
root?: Message
|
|
85
|
+
/** Its replies, oldest first by §6.3; a deleted reply is left out. */
|
|
86
|
+
replies: Message[]
|
|
87
|
+
/** The thread's Folder: its top-level message's `h`, else its replies'. */
|
|
88
|
+
folder?: string
|
|
89
|
+
/** The resolve or reopen that counts (§6.4, C51); absent when none does. `resolution.action` is the state. */
|
|
90
|
+
resolution?: Resolution
|
|
91
|
+
/**
|
|
92
|
+
* Whether Resolve or Reopen may be offered, as far as the thread can say:
|
|
93
|
+
* only on a top-level message that is `present`. Whether the reader may
|
|
94
|
+
* write in its Folder, and whether its file is archived, is the app's to add.
|
|
95
|
+
*/
|
|
96
|
+
resolvable: boolean
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const values = (event: Pick<SignedEvent, 'tags'>, name: string) =>
|
|
100
|
+
event.tags.filter((t) => t[0] === name && typeof t[1] === 'string' && t[1] !== '').map((t) => t[1])
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What its author took back: the ids a `kind:5` names by `e`, kept only for
|
|
104
|
+
* the event it names when its signer wrote that event (§6.5). A `kind:5` for
|
|
105
|
+
* an event the read does not hold is kept by its signer, for a top-level
|
|
106
|
+
* message known only from its replies.
|
|
107
|
+
*/
|
|
108
|
+
function deletionsOf(events: readonly SignedEvent[]): Map<string, Set<string>> {
|
|
109
|
+
const by = new Map<string, Set<string>>()
|
|
110
|
+
for (const event of events) {
|
|
111
|
+
if (event.kind !== KIND_DELETION) continue
|
|
112
|
+
for (const id of values(event, 'e')) {
|
|
113
|
+
if (!isEventId(id)) continue
|
|
114
|
+
const key = id.toLowerCase()
|
|
115
|
+
if (!by.has(key)) by.set(key, new Set())
|
|
116
|
+
by.get(key)!.add(event.pubkey)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return by
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Fold a conversation into its threads (§6.3–§6.8).
|
|
124
|
+
*
|
|
125
|
+
* `events` is everything read for it: its `kind:9` or `kind:1111` messages,
|
|
126
|
+
* and the `kind:40003` edits, `kind:7` reactions, `kind:5` deletions and
|
|
127
|
+
* `kind:9101` resolutions read by `#e` on them. Duplicates are read once.
|
|
128
|
+
* `viewer` marks the viewer's own reactions (`Reaction.mine`).
|
|
129
|
+
*
|
|
130
|
+
* Threads come oldest first by their top-level message, or by their first
|
|
131
|
+
* reply when it was not returned. A reply to a reply is filed under the
|
|
132
|
+
* thread's top-level message (§6.4).
|
|
133
|
+
*/
|
|
134
|
+
export function foldThreads(events: readonly SignedEvent[], options: { viewer?: string } = {}): Thread[] {
|
|
135
|
+
const unique = [...new Map(events.map((e) => [e.id, e])).values()]
|
|
136
|
+
const deletions = deletionsOf(unique)
|
|
137
|
+
const deletedBy = (id: string, author: string | undefined) => author !== undefined && deletions.get(id.toLowerCase())?.has(author) === true
|
|
138
|
+
/*
|
|
139
|
+
A top-level message the read did not return is known deleted only by its
|
|
140
|
+
author's `kind:5`, and its author only from its replies: a reply's
|
|
141
|
+
lowercase `p` names the comment's author (§6.4). Every `kind:1111` reply
|
|
142
|
+
must name the deletion's signer, so one reply's tags cannot speak for a
|
|
143
|
+
thread others answered; a channel `kind:9` names no author, and stays
|
|
144
|
+
`missing`.
|
|
145
|
+
*/
|
|
146
|
+
/** A comment the read did not return is in the Folder most of its replies were filed in, or none on a tie (§6.5). */
|
|
147
|
+
const replyFolderOf = (answers: readonly SignedEvent[]): string | undefined => {
|
|
148
|
+
const count = new Map<string, number>()
|
|
149
|
+
for (const r of answers) {
|
|
150
|
+
const h = values(r, 'h')[0]
|
|
151
|
+
if (h) count.set(h, (count.get(h) ?? 0) + 1)
|
|
152
|
+
}
|
|
153
|
+
const ranked = [...count].sort((a, b) => b[1] - a[1])
|
|
154
|
+
return ranked.length > 0 && (ranked.length === 1 || ranked[0][1] > ranked[1][1]) ? ranked[0][0] : undefined
|
|
155
|
+
}
|
|
156
|
+
const deletedUnseen = (id: string, answers: readonly SignedEvent[]) => {
|
|
157
|
+
const comments = answers.filter((r) => r.kind === KIND_COMMENT)
|
|
158
|
+
const signers = deletions.get(id.toLowerCase())
|
|
159
|
+
if (!signers || comments.length === 0) return false
|
|
160
|
+
return [...signers].some((signer) => comments.every((r) => r.tags.some((t) => t[0] === 'p' && t[1] === signer)))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const messages = unique.filter((e) => isConversationKind(e.kind))
|
|
164
|
+
const edits = foldEdits(unique)
|
|
165
|
+
const edited = editsByTarget(unique)
|
|
166
|
+
const cardsOf = foldEmbeds(unique)
|
|
167
|
+
// A taken-back reaction leaves before the one-per-person fold, so the same person's later one counts.
|
|
168
|
+
const reactions = groupReactions(
|
|
169
|
+
reactionEventsOf(unique.filter((e) => e.kind !== KIND_REACTION || !deletedBy(e.id, e.pubkey))),
|
|
170
|
+
options.viewer,
|
|
171
|
+
)
|
|
172
|
+
const resolutions = resolutionsByTarget(unique)
|
|
173
|
+
|
|
174
|
+
const messageOf = (event: SignedEvent): Message => {
|
|
175
|
+
const id = event.id.toLowerCase()
|
|
176
|
+
const fold = edits[id]
|
|
177
|
+
// An edit is the whole new message (§6.8): what its words link is the latest edit's `a` and `q`.
|
|
178
|
+
const linkSource = edited.get(id)?.at(-1) ?? event
|
|
179
|
+
const blockTag = event.tags.find((t) => t[0] === BLOCK_ANCHOR_TAG)
|
|
180
|
+
const blocks = blockTag ? readRunIds(blockTag.slice(1)) : undefined
|
|
181
|
+
const quote = blocks ? quoteOf(event) : undefined
|
|
182
|
+
const folder = values(event, 'h')[0]
|
|
183
|
+
return {
|
|
184
|
+
id,
|
|
185
|
+
kind: event.kind,
|
|
186
|
+
author: event.pubkey,
|
|
187
|
+
...(folder ? { folder } : {}),
|
|
188
|
+
at: orderingMs(event),
|
|
189
|
+
body: fold?.body ?? event.content,
|
|
190
|
+
edited: fold?.edited ?? false,
|
|
191
|
+
...(fold?.editedAt !== undefined ? { editedAt: fold.editedAt } : {}),
|
|
192
|
+
files: fold ? fold.attachments : imetaOf(event),
|
|
193
|
+
cards: cardsOf[id] ?? [],
|
|
194
|
+
parts: partsOf(event),
|
|
195
|
+
links: [...new Set([...values(linkSource, 'a'), ...values(linkSource, 'q')])],
|
|
196
|
+
...(blocks && event.kind === KIND_COMMENT ? { anchor: { blocks, ...(quote ? { quote } : {}) } } : {}),
|
|
197
|
+
reactions: reactions[id] ?? [],
|
|
198
|
+
event,
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const { roots, replies, missingRoots } = groupThreads(messages)
|
|
203
|
+
const threads: Thread[] = []
|
|
204
|
+
const thread = (id: string, root: SignedEvent | undefined): Thread => {
|
|
205
|
+
const all = replies[id] ?? []
|
|
206
|
+
const kept = all.filter((r) => !deletedBy(r.id, r.pubkey)).map(messageOf)
|
|
207
|
+
const folder = root ? values(root, 'h')[0] : replyFolderOf(all)
|
|
208
|
+
// Not returned, only the replies filed in the thread's Folder speak for its comment: one filed elsewhere neither deletes nor clears.
|
|
209
|
+
const speaking = root ? all : all.filter((r) => values(r, 'h')[0] === folder)
|
|
210
|
+
const state: RootState = (root ? deletedBy(id, root.pubkey) : folder !== undefined && deletedUnseen(id, speaking)) ? 'deleted' : root ? 'present' : 'missing'
|
|
211
|
+
const resolution = resolutionOf(resolutions[id.toLowerCase()] ?? [], { folder, replies: kept.map((r) => r.id) })
|
|
212
|
+
return {
|
|
213
|
+
id: id.toLowerCase(),
|
|
214
|
+
state,
|
|
215
|
+
...(state === 'present' && root ? { root: messageOf(root) } : {}),
|
|
216
|
+
replies: kept,
|
|
217
|
+
...(folder ? { folder } : {}),
|
|
218
|
+
...(resolution ? { resolution } : {}),
|
|
219
|
+
resolvable: state === 'present',
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
for (const root of roots) threads.push(thread(root.id, root))
|
|
223
|
+
for (const id of missingRoots) threads.push(thread(id, undefined))
|
|
224
|
+
// A thread whose top-level message is gone and has no reply left has nothing to draw.
|
|
225
|
+
const drawn = threads.filter((t) => t.root || t.replies.length > 0)
|
|
226
|
+
const firstAt = (t: Thread) => t.root?.at ?? t.replies[0].at
|
|
227
|
+
return drawn.sort((a, b) => firstAt(a) - firstAt(b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
228
|
+
}
|