@estiva-app/interop 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.
package/src/topics.ts CHANGED
@@ -24,20 +24,20 @@
24
24
  * archive chain and a Folder move all ignore it. It carries no `p`, so it adds
25
25
  * nobody to the file (§11.8).
26
26
  */
27
- import { type SignedEvent, type UnsignedEvent } from '@estiva-app/protocol'
27
+ import { encodeNpub, type SignedEvent, type UnsignedEvent } from '@estiva-app/protocol'
28
28
  import { RELAY_PAGE_CEILING } from '@estiva-app/protocol'
29
29
  import {
30
30
  byOrder,
31
31
  candidateFilesOf,
32
32
  fileContext,
33
33
  foldMemberships,
34
+ followingOf,
34
35
  HORIZON_SECONDS,
35
- membersOf,
36
- membershipJudges,
36
+ isUnreadOnPlace,
37
+ mentions,
37
38
  REPLY_FLOOR_CONTEXT,
38
- streamHasUnread,
39
- streamTermsOf,
40
39
  THREAD_RULE_FROM,
40
+ type Following,
41
41
  type MembershipRead,
42
42
  } from '@estiva-app/conversation'
43
43
  import {
@@ -46,6 +46,7 @@ import {
46
46
  isArchived,
47
47
  KIND_FOLDER_STATE,
48
48
  resolveForeignRoots,
49
+ rootOf,
49
50
  type ForeignObject,
50
51
  type ProjectionCache,
51
52
  type QueryFn,
@@ -348,11 +349,15 @@ export interface ReadTopic {
348
349
  /** Its list, as {@link topicLists} reads it. */
349
350
  listed: ListedFile[]
350
351
  /**
351
- * The viewer is a member (§11.8): by the horizon's membership read, or,
352
- * where that read has no word on them, over all history — a topic joined
353
- * before the horizon with nothing since is still theirs, as Peek's Topics
354
- * says.
352
+ * How the viewer is in it (§11.8 *Places and following*), by the shared
353
+ * fold every app uses: a level they chose, an Add or a join, or having made
354
+ * it, over all history. Writing in it is not one. A space's team default is
355
+ * not read here (no roster, no private teams list): Ship's Topics draws no
356
+ * space.
357
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/writing-in-a-place-never-follows-it.md
355
358
  */
359
+ following: Following
360
+ /** The viewer is in it: `following.in`. */
356
361
  yours: boolean
357
362
  /**
358
363
  * A team marks it one of its spaces (§3.3): its entry on a team's
@@ -399,7 +404,22 @@ function spacesOf(states: readonly SignedEvent[], addresses: readonly string[]):
399
404
  export interface TopicsRead {
400
405
  me: string
401
406
  topics: ReadTopic[]
407
+ /** Folded from the viewer's part inside the horizon: `mentioned` says which messages name them. */
402
408
  membership: MembershipRead
409
+ /** The topics where a message inside the horizon names the viewer: a mention lights at any level, and when they are not in (§11.8). */
410
+ mentionedIn: ReadonlySet<string>
411
+ /**
412
+ * The conversations the viewer is in, by {@link conversationKey} (topic and
413
+ * root id): the second they first wrote in one or were named in it, over all
414
+ * history — so a reply of theirs from before the reply floor still makes a
415
+ * later reply light at Important.
416
+ */
417
+ inConversations: ReadonlyMap<string, number>
418
+ }
419
+
420
+ /** A conversation's key in {@link TopicsRead.inConversations}: the topic it is anchored to and its root's id. */
421
+ export function conversationKey(topic: string, root: string): string {
422
+ return `${topic} ${root}`
403
423
  }
404
424
 
405
425
  /** The filters for a person's part in some files over all history: the changes naming them, what they wrote, what names them. */
@@ -448,14 +468,6 @@ async function readAll(query: QueryFn, filters: readonly Record<string, unknown>
448
468
  return [...out.values()]
449
469
  }
450
470
 
451
- /** Whether the person is a member of the file over all history, folded as its own page folds it. */
452
- function memberOverAllHistory(person: string, file: string, events: readonly SignedEvent[]): boolean {
453
- const [kind, pubkey, ...d] = file.split(':')
454
- // The root, dated before everything: its author is a member unless a leave of theirs says otherwise.
455
- const root = { id: '0'.repeat(64), pubkey: pubkey ?? '', kind: Number(kind), created_at: 0, tags: [['d', d.join(':')]], content: '', sig: '' }
456
- return membersOf(file, [root, ...events]).has(person)
457
- }
458
-
459
471
  /**
460
472
  * Every topic the viewer can read, once (SHIPS-2): each with its list, its
461
473
  * archive (its own, or with its project), its Folder, whether it is the
@@ -475,8 +487,8 @@ function memberOverAllHistory(person: string, file: string, events: readonly Sig
475
487
  * production, QA-2's horizon read over every file was 500 KB; over the topics
476
488
  * it is a few.
477
489
  *
478
- * "Yours" is today's membership fold (§11.8); following replaces it in this
479
- * same function (Teams and following, milestone 5).
490
+ * How the viewer is in each topic is {@link followingOf} over its root and
491
+ * the changes naming them (TEA-6), the fold Peek's switch reads too.
480
492
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-topic-keeps-its-own-list-of-files.md
481
493
  */
482
494
  export async function readTopics(
@@ -495,7 +507,7 @@ export async function readTopics(
495
507
  if (!held || root.created_at > held.created_at || (root.created_at === held.created_at && root.id < held.id)) roots.set(address, root)
496
508
  }
497
509
  const addresses = [...roots.keys()]
498
- if (addresses.length === 0) return { me, topics: [], membership: foldMemberships(me, [], nowSeconds) }
510
+ if (addresses.length === 0) return { me, topics: [], membership: foldMemberships(me, [], nowSeconds), mentionedIn: new Set(), inConversations: new Map() }
499
511
  const [objects, lists, part, states] = await Promise.all([
500
512
  resolveForeignRoots(addresses, query, options.cache, { archivedWith: true }),
501
513
  listsOf(query, addresses, Promise.resolve(roots), options),
@@ -511,18 +523,36 @@ export async function readTopics(
511
523
  const membership = foldMemberships(me, part.filter((e) => e.created_at >= nowSeconds - HORIZON_SECONDS), nowSeconds)
512
524
  // Each topic's own events, so each is folded over its own and not over all of them.
513
525
  const byTopic = new Map<string, SignedEvent[]>()
514
- for (const event of part) for (const file of candidateFilesOf(event)) byTopic.set(file, [...(byTopic.get(file) ?? []), event])
515
- const none = new Set<string>()
526
+ // A change by its `a`, a level included: `candidateFilesOf` leaves levels out, since they say nothing of file membership.
527
+ const filesOf = (event: SignedEvent) => (event.kind === KIND_CHANGE ? event.tags.filter((t) => t[0] === 'a').map((t) => t[1]) : candidateFilesOf(event))
528
+ for (const event of part) {
529
+ for (const file of filesOf(event)) {
530
+ const held = byTopic.get(file)
531
+ if (held) held.push(event)
532
+ else byTopic.set(file, [event])
533
+ }
534
+ }
535
+ const mentionedIn = new Set<string>()
536
+ for (const [file, events] of byTopic) if (events.some((e) => e.kind === KIND_COMMENT && membership.mentioned.has(e.id))) mentionedIn.add(file)
537
+ const inConversations = new Map<string, number>()
538
+ for (const e of part) {
539
+ if (e.kind !== KIND_COMMENT || (e.pubkey !== me && !mentions(e, me))) continue
540
+ // Keyed by the topic the comment is anchored to as well: an `E` naming another topic's thread puts nobody in that thread.
541
+ for (const file of candidateFilesOf(e)) {
542
+ const key = conversationKey(file, rootOf(e))
543
+ inConversations.set(key, Math.min(inConversations.get(key) ?? Infinity, e.created_at))
544
+ }
545
+ }
516
546
  const topics = objects.flatMap((object): ReadTopic[] => {
517
547
  const root = object.address ? roots.get(object.address) : undefined
518
548
  const folder = root ? folderOf(root) : null
519
549
  if (!root || !folder || object.unreachable) return []
520
550
  const address = object.address!
521
- const yours =
522
- streamTermsOf(address, membership, me, none).member || (!membershipJudges(address, membership, me) && memberOverAllHistory(me, address, byTopic.get(address) ?? []))
523
- return [{ address, object, folder, listed: lists.get(address) ?? [], yours, space: spaces.has(address) }]
551
+ // The team is the topic's own Folder; a team's default reaches no topic, so its roster is not needed (§11.8).
552
+ const following = followingOf({ address, team: folder }, me, { events: [root, ...(byTopic.get(address) ?? [])], listing: states })
553
+ return [{ address, object, folder, listed: lists.get(address) ?? [], following, yours: following.in, space: spaces.has(address) }]
524
554
  })
525
- return { me, topics, membership }
555
+ return { me, topics, membership, mentionedIn, inConversations }
526
556
  }
527
557
 
528
558
  // An untitled topic sorts where the apps' "Untitled topic" would.
@@ -554,17 +584,23 @@ export interface TopicConversation {
554
584
  /**
555
585
  * Each topic's conversations and dot, as Peek's Topics shows them (SHIPS-2):
556
586
  * the count is the thread roots addressed to the topic (`conversationsOf`),
557
- * the dot is {@link streamHasUnread} on the topic's own marker, gated by
558
- * membership (§11.8), on the viewer's open topics only. `fresh` is the same
559
- * judge over each thread alone (a root and its replies), so Ship's Topics can
560
- * say how many of them are new where Peek shows the dot (SHIPS-3).
587
+ * the dot is §11.8's *What is unread on a place* ({@link isUnreadOnPlace}) at
588
+ * the viewer's level on it ({@link ReadTopic.following}): at Important a new
589
+ * conversation, or a reply in one they wrote in or were named in; at All every
590
+ * message since they chose it; a mention at any level, and when they are not
591
+ * in. An archived topic lights nothing. `fresh` is the same judge over each
592
+ * thread alone (a root and its replies), so Ship's Topics can say how many of
593
+ * them are new where Peek shows the dot (SHIPS-3).
561
594
  *
562
595
  * The read state and the muted list are encrypted, so the app hands in what
563
596
  * it holds: `merged` (the merged markers, once the first merge has landed)
564
- * and `muted`. Replies are read only for the topics a dot is judged on, and
565
- * only from the latest second before which none can be unread: the thread
566
- * rule's cut-over, the reply floor, and when the viewer joined (§11.3: a
567
- * reply is read by its thread's marker or the floor, never the topic's).
597
+ * and `muted`. Replies are read only for the topics a dot is judged on — the
598
+ * open ones the viewer is in or is named in — and only from the latest second
599
+ * before which none can be unread: the thread rule's cut-over and the reply
600
+ * floor (§11.3: a reply is read by its thread's marker or the floor, never the
601
+ * topic's). Not from when the viewer came in: a reply of theirs from before
602
+ * then still puts them in its conversation.
603
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/writing-in-a-place-never-follows-it.md
568
604
  */
569
605
  export async function topicConversations(
570
606
  read: TopicsRead,
@@ -573,15 +609,20 @@ export async function topicConversations(
573
609
  options: { cache?: ProjectionCache } = {},
574
610
  ): Promise<Map<string, TopicConversation>> {
575
611
  const nowSeconds = state.nowSeconds ?? Math.floor(Date.now() / 1000)
576
- const terms = (address: string) => streamTermsOf(address, read.membership, read.me, state.muted)
577
- const judged = new Set(read.topics.filter((topic) => topic.yours && !isArchived(topic.object)).map((topic) => topic.address))
612
+ const judged = new Set(
613
+ read.topics
614
+ .filter((topic) => (topic.following.in || read.mentionedIn.has(topic.address)) && !isArchived(topic.object))
615
+ .map((topic) => topic.address),
616
+ )
578
617
  const repliesSince = (address: string) => {
579
618
  if (!judged.has(address)) return null
580
- const floor = state.merged[REPLY_FLOOR_CONTEXT]
581
- return Math.max(THREAD_RULE_FROM, floor ?? 0, terms(address).since ?? 0)
619
+ // Not from when they came in: a reply of theirs from before then still says they are in that conversation.
620
+ return Math.max(THREAD_RULE_FROM, state.merged[REPLY_FLOOR_CONTEXT] ?? 0)
582
621
  }
583
622
  const files = read.topics.map((topic) => ({ ...topic.object, ref: topic.address }))
584
623
  const held = await conversationsOf(files, query, options.cache, { replies: true, repliesSince })
624
+ // The messages carry no body: one the membership read found naming the viewer is judged as the body it would have had.
625
+ const named = `nostr:${encodeNpub(read.me)}`
585
626
  const out = new Map<string, TopicConversation>()
586
627
  for (const topic of read.topics) {
587
628
  const messages = held[topic.address]
@@ -597,11 +638,15 @@ export async function topicConversations(
597
638
  if (thread) thread.push(m)
598
639
  else threads.set(m.root, [m])
599
640
  }
600
- const topicTerms = terms(topic.address)
601
- const frontier = { merged: state.merged, me: read.me, nowSeconds, horizonSeconds: HORIZON_SECONDS }
641
+ const judge = { stream: context, me: read.me, following: topic.following, muted: state.muted.has(topic.address), floor: nowSeconds - HORIZON_SECONDS }
602
642
  // Every thread here is one of the topic's: `conversationsOf` keeps a reply only under a root of this file.
603
643
  for (const thread of threads.values()) {
604
- if (streamHasUnread(thread, context, topicTerms, frontier, (id) => read.membership.mentioned.has(id))) fresh++
644
+ const asEvents = thread
645
+ .sort((a, b) => a.at - b.at)
646
+ .map((m) => ({ id: m.id, pubkey: m.by, kind: KIND_COMMENT, created_at: m.at, tags: [], content: read.membership.mentioned.has(m.id) ? named : '', root: m.root }))
647
+ // When the viewer came into this conversation (wrote in it or was named in it), before the reply floor too.
648
+ const inSince = read.inConversations.get(conversationKey(topic.address, thread[0]!.root))
649
+ if (asEvents.some((m) => isUnreadOnPlace(m, m.root === m.id ? undefined : m.root, state.merged, judge, inSince))) fresh++
605
650
  }
606
651
  }
607
652
  out.set(topic.address, { conversations: messages.filter((m) => m.root === m.id).length, unread: fresh > 0, fresh })