@estiva-app/ui 0.98.1 → 0.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/README.md +4 -2
  2. package/dist/AppProvider.d.ts +6 -3
  3. package/dist/AppProvider.d.ts.map +1 -1
  4. package/dist/ArchiveDialog.d.ts +35 -0
  5. package/dist/ArchiveDialog.d.ts.map +1 -0
  6. package/dist/AttachedCard.d.ts +13 -2
  7. package/dist/AttachedCard.d.ts.map +1 -1
  8. package/dist/Card.d.ts +6 -1
  9. package/dist/Card.d.ts.map +1 -1
  10. package/dist/ChipInput.d.ts +3 -1
  11. package/dist/ChipInput.d.ts.map +1 -1
  12. package/dist/CollapsibleSection.d.ts +27 -2
  13. package/dist/CollapsibleSection.d.ts.map +1 -1
  14. package/dist/CommentBox.d.ts +2 -2
  15. package/dist/CommentBox.d.ts.map +1 -1
  16. package/dist/ConfirmDialog.d.ts +15 -2
  17. package/dist/ConfirmDialog.d.ts.map +1 -1
  18. package/dist/ConversationCard.d.ts +12 -1
  19. package/dist/ConversationCard.d.ts.map +1 -1
  20. package/dist/ConversationLayout.d.ts +20 -5
  21. package/dist/ConversationLayout.d.ts.map +1 -1
  22. package/dist/ConversationMenu.d.ts +5 -1
  23. package/dist/ConversationMenu.d.ts.map +1 -1
  24. package/dist/ConversationPlace.d.ts +17 -0
  25. package/dist/ConversationPlace.d.ts.map +1 -0
  26. package/dist/DocumentEditor.d.ts +38 -0
  27. package/dist/DocumentEditor.d.ts.map +1 -1
  28. package/dist/DocumentField.d.ts +50 -0
  29. package/dist/DocumentField.d.ts.map +1 -0
  30. package/dist/EditableText.d.ts +38 -4
  31. package/dist/EditableText.d.ts.map +1 -1
  32. package/dist/EmptyState.d.ts +10 -5
  33. package/dist/EmptyState.d.ts.map +1 -1
  34. package/dist/FormDialog.d.ts +38 -0
  35. package/dist/FormDialog.d.ts.map +1 -0
  36. package/dist/InlineText.d.ts.map +1 -1
  37. package/dist/Menu.d.ts +11 -3
  38. package/dist/Menu.d.ts.map +1 -1
  39. package/dist/MoveDialog.d.ts +64 -0
  40. package/dist/MoveDialog.d.ts.map +1 -0
  41. package/dist/NavItem.d.ts +9 -2
  42. package/dist/NavItem.d.ts.map +1 -1
  43. package/dist/NavTree.d.ts +16 -3
  44. package/dist/NavTree.d.ts.map +1 -1
  45. package/dist/PinnedComment.d.ts +3 -1
  46. package/dist/PinnedComment.d.ts.map +1 -1
  47. package/dist/ReactionHorizon.d.ts +3 -1
  48. package/dist/ReactionHorizon.d.ts.map +1 -1
  49. package/dist/RepliesRow.d.ts +5 -3
  50. package/dist/RepliesRow.d.ts.map +1 -1
  51. package/dist/ResolveDialog.d.ts +3 -1
  52. package/dist/ResolveDialog.d.ts.map +1 -1
  53. package/dist/SelectionToolbar.d.ts +2 -2
  54. package/dist/Thread.d.ts +6 -3
  55. package/dist/Thread.d.ts.map +1 -1
  56. package/dist/commentBoxFrame.d.ts.map +1 -1
  57. package/dist/conversation.examples.d.ts +4 -1
  58. package/dist/conversation.examples.d.ts.map +1 -1
  59. package/dist/conversationScroll.d.ts +80 -0
  60. package/dist/conversationScroll.d.ts.map +1 -0
  61. package/dist/editor.d.ts +1 -0
  62. package/dist/editor.d.ts.map +1 -1
  63. package/dist/editor.js +228 -69
  64. package/dist/editor.js.map +4 -4
  65. package/dist/eslint/index.js +2 -2
  66. package/dist/eslint/index.js.map +2 -2
  67. package/dist/eslint/no-field-outside-a-form.d.ts +2 -2
  68. package/dist/eslint/no-field-outside-a-form.d.ts.map +1 -1
  69. package/dist/eslint/no-native-title.d.ts +1 -1
  70. package/dist/eslint/no-native-title.d.ts.map +1 -1
  71. package/dist/formBusy.d.ts +5 -2
  72. package/dist/formBusy.d.ts.map +1 -1
  73. package/dist/index.d.ts +14 -6
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +2242 -1471
  76. package/dist/index.js.map +4 -4
  77. package/dist/looks.d.ts +8 -0
  78. package/dist/looks.d.ts.map +1 -1
  79. package/dist/seenOnScreen.d.ts +27 -0
  80. package/dist/seenOnScreen.d.ts.map +1 -0
  81. package/dist/showInConversation.d.ts +31 -0
  82. package/dist/showInConversation.d.ts.map +1 -0
  83. package/dist/threadCard.d.ts +13 -0
  84. package/dist/threadCard.d.ts.map +1 -1
  85. package/package.json +1 -1
  86. package/registry.json +953 -126
  87. package/src/AppProvider.mdx +4 -0
  88. package/src/AppProvider.test.tsx +34 -2
  89. package/src/AppProvider.tsx +17 -6
  90. package/src/ArchiveDialog.mdx +70 -0
  91. package/src/ArchiveDialog.stories.tsx +64 -0
  92. package/src/ArchiveDialog.test.tsx +90 -0
  93. package/src/ArchiveDialog.tsx +70 -0
  94. package/src/AttachedCard.mdx +6 -0
  95. package/src/AttachedCard.stories.tsx +9 -1
  96. package/src/AttachedCard.test.tsx +111 -2
  97. package/src/AttachedCard.tsx +77 -7
  98. package/src/Card.mdx +20 -1
  99. package/src/Card.stories.tsx +20 -0
  100. package/src/Card.test.tsx +87 -1
  101. package/src/Card.tsx +51 -3
  102. package/src/ChipInput.mdx +7 -1
  103. package/src/ChipInput.stories.tsx +9 -0
  104. package/src/ChipInput.test.tsx +42 -0
  105. package/src/ChipInput.tsx +7 -3
  106. package/src/CollapsibleSection.mdx +20 -1
  107. package/src/CollapsibleSection.stories.tsx +19 -1
  108. package/src/CollapsibleSection.test.tsx +85 -2
  109. package/src/CollapsibleSection.tsx +54 -15
  110. package/src/CommentBox.mdx +2 -1
  111. package/src/CommentBox.test.tsx +81 -1
  112. package/src/CommentBox.tsx +32 -11
  113. package/src/ConfirmDialog.mdx +25 -3
  114. package/src/ConfirmDialog.stories.tsx +27 -0
  115. package/src/ConfirmDialog.test.tsx +87 -1
  116. package/src/ConfirmDialog.tsx +39 -8
  117. package/src/ConversationCard.mdx +7 -0
  118. package/src/ConversationCard.states.test.tsx +67 -0
  119. package/src/ConversationCard.stories.tsx +27 -1
  120. package/src/ConversationCard.test.tsx +76 -0
  121. package/src/ConversationCard.tsx +65 -53
  122. package/src/ConversationLayout.mdx +34 -4
  123. package/src/ConversationLayout.scroll.test.tsx +411 -0
  124. package/src/ConversationLayout.stories.tsx +107 -1
  125. package/src/ConversationLayout.test.tsx +133 -0
  126. package/src/ConversationLayout.tsx +141 -16
  127. package/src/ConversationMenu.mdx +3 -0
  128. package/src/ConversationMenu.stories.tsx +12 -0
  129. package/src/ConversationMenu.test.tsx +17 -0
  130. package/src/ConversationMenu.tsx +7 -3
  131. package/src/ConversationPlace.mdx +53 -0
  132. package/src/ConversationPlace.stories.tsx +48 -0
  133. package/src/ConversationPlace.test.tsx +51 -0
  134. package/src/ConversationPlace.tsx +30 -0
  135. package/src/DocumentEditor.mdx +2 -1
  136. package/src/DocumentEditor.tsx +118 -64
  137. package/src/DocumentField.mdx +83 -0
  138. package/src/DocumentField.stories.tsx +110 -0
  139. package/src/DocumentField.test.tsx +281 -0
  140. package/src/DocumentField.tsx +199 -0
  141. package/src/EditableText.buttons.test.tsx +318 -0
  142. package/src/EditableText.mdx +50 -2
  143. package/src/EditableText.stories.tsx +96 -2
  144. package/src/EditableText.tsx +189 -5
  145. package/src/EmptyState.mdx +33 -8
  146. package/src/EmptyState.stories.tsx +26 -1
  147. package/src/EmptyState.test.tsx +63 -2
  148. package/src/EmptyState.tsx +28 -6
  149. package/src/Form.mdx +3 -1
  150. package/src/FormDialog.mdx +78 -0
  151. package/src/FormDialog.stories.tsx +90 -0
  152. package/src/FormDialog.test.tsx +183 -0
  153. package/src/FormDialog.tsx +93 -0
  154. package/src/InlineText.mdx +1 -0
  155. package/src/InlineText.tsx +2 -1
  156. package/src/Menu.test.tsx +80 -0
  157. package/src/Menu.tsx +35 -14
  158. package/src/MenuItem.mdx +12 -0
  159. package/src/MenuItem.stories.tsx +39 -1
  160. package/src/MoveDialog.mdx +85 -0
  161. package/src/MoveDialog.stories.tsx +134 -0
  162. package/src/MoveDialog.test.tsx +239 -0
  163. package/src/MoveDialog.tsx +186 -0
  164. package/src/NavItem.mdx +15 -0
  165. package/src/NavItem.stories.tsx +15 -0
  166. package/src/NavItem.test.tsx +64 -1
  167. package/src/NavItem.tsx +10 -2
  168. package/src/NavTree.mdx +26 -4
  169. package/src/NavTree.stories.tsx +59 -0
  170. package/src/NavTree.test.tsx +232 -2
  171. package/src/NavTree.tsx +93 -43
  172. package/src/PinnedComment.mdx +6 -1
  173. package/src/PinnedComment.stories.tsx +11 -1
  174. package/src/PinnedComment.tsx +15 -2
  175. package/src/ReactionHorizon.mdx +2 -0
  176. package/src/ReactionHorizon.stories.tsx +3 -0
  177. package/src/ReactionHorizon.test.tsx +32 -0
  178. package/src/ReactionHorizon.tsx +28 -11
  179. package/src/RepliesRow.mdx +6 -3
  180. package/src/RepliesRow.stories.tsx +3 -0
  181. package/src/RepliesRow.test.tsx +24 -0
  182. package/src/RepliesRow.tsx +12 -6
  183. package/src/ReplyCard.mdx +8 -0
  184. package/src/ReplyCard.stories.tsx +45 -1
  185. package/src/ResolveDialog.mdx +2 -0
  186. package/src/ResolveDialog.test.tsx +21 -0
  187. package/src/ResolveDialog.tsx +11 -39
  188. package/src/SelectionToolbar.tsx +2 -2
  189. package/src/Textarea.mdx +1 -0
  190. package/src/Thread.mdx +20 -1
  191. package/src/Thread.stories.tsx +94 -3
  192. package/src/Thread.test.tsx +11 -0
  193. package/src/Thread.tsx +56 -12
  194. package/src/commentBoxFrame.tsx +2 -2
  195. package/src/conversation.examples.tsx +10 -2
  196. package/src/conversationScroll.ts +155 -0
  197. package/src/editor.ts +1 -0
  198. package/src/editorSelection.test.tsx +53 -0
  199. package/src/eslint/no-field-outside-a-form.test.ts +4 -0
  200. package/src/eslint/no-field-outside-a-form.ts +2 -2
  201. package/src/eslint/no-native-title.ts +1 -1
  202. package/src/formBusy.ts +5 -2
  203. package/src/index.ts +16 -6
  204. package/src/looks.ts +10 -0
  205. package/src/registry/registry.test.ts +12 -6
  206. package/src/seenOnScreen.test.tsx +241 -0
  207. package/src/seenOnScreen.ts +146 -0
  208. package/src/showInConversation.test.tsx +168 -0
  209. package/src/showInConversation.ts +93 -0
  210. package/src/threadCard.ts +16 -0
  211. package/stories/Choosing.mdx +8 -3
  212. package/tailwind-preset.js +7 -0
@@ -0,0 +1,241 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * What reads a comment or a reply (Katerina, 30 October): being on screen for a moment, not being drawn. Peek's own
4
+ * hook and its tests, moved into the kit (C2 of the audit of 2 November): an app says which conversation or thread it
5
+ * is (`useSeenOnScreen(key)`), hands what it returns to the layout or the thread (`seen`), and reads back what was seen.
6
+ * A stand-in IntersectionObserver says what shows.
7
+ */
8
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
9
+ import { act, cleanup, render, screen } from '@testing-library/react'
10
+ import { ConversationCard, ReplyCard } from './ConversationCard'
11
+ import { ConversationLayout } from './ConversationLayout'
12
+ import { useSeenOnScreen } from './seenOnScreen'
13
+ import { Thread } from './Thread'
14
+
15
+ /** The moment a comment must stay on screen: Peek's READ_DWELL_MS. */
16
+ const DWELL = 1500
17
+ const ONE = { name: 'Person one' }
18
+
19
+ let observers: { callback: IntersectionObserverCallback; targets: Element[] }[] = []
20
+ class FakeObserver {
21
+ targets: Element[] = []
22
+ callback: IntersectionObserverCallback
23
+ constructor(callback: IntersectionObserverCallback) {
24
+ this.callback = callback
25
+ observers.push(this)
26
+ }
27
+ observe(target: Element) {
28
+ this.targets.push(target)
29
+ }
30
+ disconnect() {
31
+ this.targets = []
32
+ }
33
+ unobserve() {}
34
+ takeRecords() {
35
+ return []
36
+ }
37
+ }
38
+
39
+ /** Says how much of the comment or reply `id` shows: its share of the card and its height on screen. */
40
+ function show(id: string, ratio: number, height = 60 * ratio) {
41
+ const target = document.querySelector(`[data-conversation-item="${id}"], [data-reply-id="${id}"]`)!
42
+ act(() => {
43
+ for (const o of observers) {
44
+ if (!o.targets.includes(target)) continue
45
+ const entry = { target, isIntersecting: ratio > 0, intersectionRatio: ratio, intersectionRect: { height } } as unknown as IntersectionObserverEntry
46
+ o.callback([entry], o as unknown as IntersectionObserver)
47
+ }
48
+ })
49
+ }
50
+
51
+ const wait = (ms: number) => act(() => void vi.advanceTimersByTime(ms))
52
+
53
+ function Comments({ ids, at = 'conversation' }: { ids: string[]; at?: string | null }) {
54
+ const seen = useSeenOnScreen(at)
55
+ return (
56
+ <>
57
+ <ConversationLayout
58
+ threads="beside"
59
+ seen={seen}
60
+ items={ids.map((id) => ({
61
+ id,
62
+ card: (
63
+ <ConversationCard author={ONE} time="11:08 AM">
64
+ {id}
65
+ </ConversationCard>
66
+ ),
67
+ }))}
68
+ />
69
+ <output data-testid="seen">{[...seen.ids].sort().join(',')}</output>
70
+ </>
71
+ )
72
+ }
73
+
74
+ const seenNow = () => screen.getByTestId('seen').textContent
75
+
76
+ beforeEach(() => {
77
+ observers = []
78
+ vi.useFakeTimers()
79
+ vi.stubGlobal('IntersectionObserver', FakeObserver)
80
+ })
81
+ afterEach(() => {
82
+ cleanup()
83
+ vi.useRealTimers()
84
+ vi.unstubAllGlobals()
85
+ })
86
+
87
+ describe('useSeenOnScreen, in a ConversationLayout', () => {
88
+ it('a comment on screen for the dwell is seen; one never shown is not', () => {
89
+ render(<Comments ids={['a', 'b']} />)
90
+ show('a', 1)
91
+ wait(DWELL)
92
+ expect(seenNow()).toBe('a')
93
+ })
94
+
95
+ it('scrolling past before the dwell reads nothing', () => {
96
+ render(<Comments ids={['a']} />)
97
+ show('a', 1)
98
+ wait(DWELL - 100)
99
+ show('a', 0)
100
+ wait(DWELL)
101
+ expect(seenNow()).toBe('')
102
+ })
103
+
104
+ it('a sliver is not enough; half, or enough of a tall card, is', () => {
105
+ render(<Comments ids={['a', 'b', 'c']} />)
106
+ show('a', 0.2)
107
+ show('b', 0.5)
108
+ show('c', 0.3, 300)
109
+ wait(DWELL)
110
+ expect(seenNow()).toBe('b,c')
111
+ })
112
+
113
+ it('a comment drawn later is watched too', () => {
114
+ const { rerender } = render(<Comments ids={['a']} />)
115
+ rerender(<Comments ids={['a', 'b']} />)
116
+ show('b', 1)
117
+ wait(DWELL)
118
+ expect(seenNow()).toBe('b')
119
+ })
120
+
121
+ it('a hidden tab reads nothing until it is shown again', () => {
122
+ render(<Comments ids={['a']} />)
123
+ const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)
124
+ show('a', 1)
125
+ wait(DWELL * 2)
126
+ expect(seenNow()).toBe('')
127
+ hidden.mockReturnValue(false)
128
+ act(() => void document.dispatchEvent(new Event('visibilitychange')))
129
+ wait(DWELL)
130
+ expect(seenNow()).toBe('a')
131
+ })
132
+
133
+ it('starts again empty for another conversation, and watches nothing while it has none', () => {
134
+ const { rerender } = render(<Comments ids={['a']} />)
135
+ show('a', 1)
136
+ wait(DWELL)
137
+ expect(seenNow()).toBe('a')
138
+ rerender(<Comments ids={['a']} at="another" />)
139
+ expect(seenNow()).toBe('')
140
+ rerender(<Comments ids={['a']} at={null} />)
141
+ show('a', 1)
142
+ wait(DWELL)
143
+ expect(seenNow()).toBe('')
144
+ })
145
+ })
146
+
147
+ describe('useSeenOnScreen, in a Thread', () => {
148
+ function Replies({ ids }: { ids: string[] }) {
149
+ const seen = useSeenOnScreen('thread')
150
+ return (
151
+ <>
152
+ <Thread start={{ author: ONE, time: '11:08 AM', words: 'The comment' }} seen={seen}>
153
+ {ids.map((id) => (
154
+ <ReplyCard key={id} id={id} author={ONE} time="11:30 AM">
155
+ {id}
156
+ </ReplyCard>
157
+ ))}
158
+ </Thread>
159
+ <output data-testid="seen">{[...seen.ids].sort().join(',')}</output>
160
+ </>
161
+ )
162
+ }
163
+
164
+ it('a reply on screen for the dwell is seen; one never shown is not', () => {
165
+ render(<Replies ids={['r1', 'r2']} />)
166
+ show('r2', 1)
167
+ wait(DWELL)
168
+ expect(seenNow()).toBe('r2')
169
+ })
170
+ })
171
+
172
+ describe('useSeenOnScreen, where there is no IntersectionObserver (a test’s page)', () => {
173
+ it('everything drawn counts as on screen: the dwell alone decides', () => {
174
+ vi.unstubAllGlobals()
175
+ vi.stubGlobal('IntersectionObserver', undefined)
176
+ render(<Comments ids={['a', 'b']} />)
177
+ wait(DWELL - 1)
178
+ expect(seenNow()).toBe('')
179
+ wait(1)
180
+ expect(seenNow()).toBe('a,b')
181
+ })
182
+ })
183
+
184
+ describe('useSeenOnScreen, in a Thread under its comment (one column; Ship, 2 November)', () => {
185
+ function OneColumn({ ids }: { ids: string[] }) {
186
+ const seen = useSeenOnScreen('thread')
187
+ return (
188
+ <>
189
+ <ConversationLayout
190
+ threads="under"
191
+ open="c"
192
+ onOpenChange={() => {}}
193
+ items={[
194
+ {
195
+ id: 'c',
196
+ card: (
197
+ <ConversationCard author={ONE} time="11:08 AM" replies={{ count: ids.length }}>
198
+ The comment
199
+ </ConversationCard>
200
+ ),
201
+ thread: (
202
+ <Thread place="under" seen={seen}>
203
+ {ids.map((id) => (
204
+ <ReplyCard key={id} id={id} author={ONE} time="11:30 AM">
205
+ {id}
206
+ </ReplyCard>
207
+ ))}
208
+ </Thread>
209
+ ),
210
+ },
211
+ ]}
212
+ />
213
+ <output data-testid="seen">{[...seen.ids].sort().join(',')}</output>
214
+ </>
215
+ )
216
+ }
217
+
218
+ it('a reply on screen for the dwell is seen, as in the thread beside; one never shown is not', () => {
219
+ render(<OneColumn ids={['r1', 'r2']} />)
220
+ show('r2', 1)
221
+ wait(DWELL)
222
+ expect(seenNow()).toBe('r2')
223
+ })
224
+
225
+ it('scrolling past before the dwell reads nothing', () => {
226
+ render(<OneColumn ids={['r1']} />)
227
+ show('r1', 1)
228
+ wait(DWELL - 100)
229
+ show('r1', 0)
230
+ wait(DWELL)
231
+ expect(seenNow()).toBe('')
232
+ })
233
+
234
+ it('a reply drawn later is watched too', () => {
235
+ const { rerender } = render(<OneColumn ids={['r1']} />)
236
+ rerender(<OneColumn ids={['r1', 'r2']} />)
237
+ show('r2', 1)
238
+ wait(DWELL)
239
+ expect(seenNow()).toBe('r2')
240
+ })
241
+ })
@@ -0,0 +1,146 @@
1
+ import { useEffect, useMemo, useState, type RefObject } from 'react'
2
+
3
+ const NONE: ReadonlySet<string> = new Set()
4
+ /** How long it must stay on screen, without a break: Peek's READ_DWELL_MS. */
5
+ const DWELL_MS = 1500
6
+ /** A card taller than the view can never show half of itself: this much of it is enough. */
7
+ const TALL_ENOUGH_PX = 120
8
+ /** Every tenth, so a tall card's share is reported as it scrolls, not only as it crosses half. */
9
+ const THRESHOLDS = Array.from({ length: 11 }, (_, i) => i / 10)
10
+
11
+ /** What has been seen of one conversation or thread: given to a `ConversationLayout`'s or a `Thread`'s `seen`. */
12
+ export interface SeenOnScreen {
13
+ /** The ids of the comments or replies that have been on screen a moment, for the key it was made with. */
14
+ readonly ids: ReadonlySet<string>
15
+ }
16
+
17
+ /** The boxes a part hands in, each with the attribute that names its comments, and the watch over them. */
18
+ interface Watcher {
19
+ roots: Map<HTMLElement, string>
20
+ watch: { current: ((el: Element, attribute: string) => void) | null }
21
+ }
22
+
23
+ const watchers = new WeakMap<SeenOnScreen, Watcher>()
24
+
25
+ /**
26
+ * The comments or replies that have been on screen for a moment: what reads them (Katerina, 30 October). Their "new"
27
+ * look goes once they have been seen, by scrolling to them or opening their thread, not when their conversation is
28
+ * opened. Peek's, moved with the conversation (C2 of the audit of 2 November).
29
+ *
30
+ * Hand what it returns to a `ConversationLayout`'s `seen` (its comments, by `data-conversation-item`) or a `Thread`'s
31
+ * (its replies, by `ReplyCard`'s `id`), and read back `ids`. On screen means half of the card shows, or 120px of a
32
+ * taller one, inside every scrolling pane round it, for 1.5 seconds without a break, in a tab that is not hidden.
33
+ * Scrolling past reads nothing. Where there is no IntersectionObserver (a test's page), everything drawn counts as on
34
+ * screen: the dwell alone decides.
35
+ *
36
+ * What has been seen is held for `key`, the conversation or the thread, and starts again empty when it changes;
37
+ * `null` watches nothing (before the app has judged what is new: what is seen first would be read).
38
+ */
39
+ export function useSeenOnScreen(key: string | null): SeenOnScreen {
40
+ const [seen, setSeen] = useState<{ key: string | null; ids: ReadonlySet<string> }>({ key: null, ids: NONE })
41
+ const [watcher] = useState<Watcher>(() => ({ roots: new Map(), watch: { current: null } }))
42
+
43
+ useEffect(() => {
44
+ if (!key) return
45
+ const timers = new Map<string, ReturnType<typeof setTimeout>>()
46
+ const showing = new Set<string>()
47
+ const done = new Set<string>()
48
+ const idOf = new WeakMap<Element, string>()
49
+ const boxlessOf = new WeakMap<Element, boolean>()
50
+
51
+ const arm = (id: string) => {
52
+ if (done.has(id) || timers.has(id) || document.hidden) return
53
+ timers.set(
54
+ id,
55
+ setTimeout(() => {
56
+ timers.delete(id)
57
+ done.add(id)
58
+ setSeen((prev) => ({ key, ids: new Set([...(prev.key === key ? prev.ids : []), id]) }))
59
+ }, DWELL_MS),
60
+ )
61
+ }
62
+ const disarm = (id: string) => {
63
+ clearTimeout(timers.get(id))
64
+ timers.delete(id)
65
+ }
66
+
67
+ const observer =
68
+ typeof IntersectionObserver === 'undefined'
69
+ ? null
70
+ : new IntersectionObserver(
71
+ (entries) => {
72
+ for (const entry of entries) {
73
+ const id = idOf.get(entry.target)
74
+ if (!id) continue
75
+ const onScreen = entry.isIntersecting && (entry.intersectionRatio >= 0.5 || entry.intersectionRect.height >= TALL_ENOUGH_PX)
76
+ if (onScreen) {
77
+ showing.add(id)
78
+ arm(id)
79
+ } else {
80
+ showing.delete(id)
81
+ disarm(id)
82
+ }
83
+ }
84
+ },
85
+ { threshold: THRESHOLDS },
86
+ )
87
+
88
+ const watch = (el: Element, attribute: string) => {
89
+ const id = el.getAttribute(attribute)
90
+ if (!id) return
91
+ // Asked once per element; the card inside is looked up on every draw, since it can be drawn anew. One drawn as
92
+ // `display: contents` has no box of its own and is watched through its first child, the card.
93
+ let boxless = boxlessOf.get(el)
94
+ if (boxless === undefined) boxlessOf.set(el, (boxless = getComputedStyle(el).display === 'contents'))
95
+ const target = boxless ? el.firstElementChild : el
96
+ if (!target || idOf.has(target)) return
97
+ idOf.set(target, id)
98
+ if (observer) observer.observe(target)
99
+ else {
100
+ showing.add(id)
101
+ arm(id)
102
+ }
103
+ }
104
+ watcher.watch.current = watch
105
+ // What the parts drew before this key was known.
106
+ for (const [root, attribute] of watcher.roots) root.querySelectorAll(`[${attribute}]`).forEach((el) => watch(el, attribute))
107
+
108
+ // A hidden tab is not being read: its clocks stop, and start again on what still shows.
109
+ const onVisibility = () => {
110
+ if (document.hidden) for (const id of [...timers.keys()]) disarm(id)
111
+ else for (const id of showing) arm(id)
112
+ }
113
+ document.addEventListener('visibilitychange', onVisibility)
114
+ return () => {
115
+ watcher.watch.current = null
116
+ observer?.disconnect()
117
+ for (const t of timers.values()) clearTimeout(t)
118
+ document.removeEventListener('visibilitychange', onVisibility)
119
+ }
120
+ }, [key, watcher])
121
+
122
+ const ids = seen.key === key ? seen.ids : NONE
123
+ return useMemo(() => {
124
+ const handle: SeenOnScreen = { ids }
125
+ watchers.set(handle, watcher)
126
+ return handle
127
+ }, [ids, watcher])
128
+ }
129
+
130
+ /**
131
+ * A part's half: every draw, the comments under `root` that carry `attribute` are watched for `seen`. Used by
132
+ * ConversationLayout and Thread; nothing for an app to call.
133
+ */
134
+ export function useWatchSeen(seen: SeenOnScreen | undefined, root: RefObject<HTMLElement | null>, attribute: string) {
135
+ useEffect(() => {
136
+ const watcher = seen && watchers.get(seen)
137
+ const el = root.current
138
+ if (!watcher || !el) return
139
+ watcher.roots.set(el, attribute)
140
+ const watch = watcher.watch.current
141
+ if (watch) el.querySelectorAll(`[${attribute}]`).forEach((item) => watch(item, attribute))
142
+ return () => {
143
+ watcher.roots.delete(el)
144
+ }
145
+ })
146
+ }
@@ -0,0 +1,168 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * A link to a comment or a reply lands on it (Peek's INT-3, INT-8, moved into the kit for every app, C3 of the audit
4
+ * of 2 November): it is scrolled to the middle of the view and flashed, so the click delivers the comment and not a
5
+ * place near it; one not drawn yet is waited for, a while; one never drawn says so. Peek's own tests, ported, and what
6
+ * the kit adds: an id on every reply it draws.
7
+ */
8
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
9
+ import { cleanup, render } from '@testing-library/react'
10
+ import { ReplyCard } from './ConversationCard'
11
+ import { ConversationCard } from './ConversationCard'
12
+ import { ConversationLayout } from './ConversationLayout'
13
+ import { showInConversation, showInConversationWhenDrawn } from './showInConversation'
14
+ import { Thread } from './Thread'
15
+
16
+ let scrollIntoView: ReturnType<typeof vi.fn>
17
+ const marked = (selector: string) => document.querySelector(selector)?.getAttribute('data-shown') ?? null
18
+
19
+ beforeEach(() => {
20
+ vi.useFakeTimers()
21
+ scrollIntoView = vi.fn()
22
+ Element.prototype.scrollIntoView = scrollIntoView as unknown as Element['scrollIntoView']
23
+ document.body.innerHTML = `
24
+ <div data-reply-id="r1">first</div>
25
+ <div data-reply-id="r2">second</div>
26
+ `
27
+ })
28
+
29
+ afterEach(() => {
30
+ cleanup()
31
+ vi.useRealTimers()
32
+ document.body.innerHTML = ''
33
+ })
34
+
35
+ describe('showInConversation', () => {
36
+ it('scrolls the reply into the middle of the view', () => {
37
+ // Centred rather than to the top: the replies around it are what makes it checkable.
38
+ expect(showInConversation('r2')).toBe(true)
39
+ expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth', block: 'center' })
40
+ })
41
+
42
+ it('marks the reply it arrived at', () => {
43
+ showInConversation('r1')
44
+ expect(marked('[data-reply-id="r1"]')).toBe('true')
45
+ })
46
+
47
+ it('clears the mark, because it marks an arrival and not a state', () => {
48
+ showInConversation('r1')
49
+ vi.advanceTimersByTime(2000)
50
+ expect(marked('[data-reply-id="r1"]')).toBeNull()
51
+ })
52
+
53
+ it('does not clear a mark a later show has claimed', () => {
54
+ // Two links pressed in quick succession: the first one's timer must not unmark the second one's arrival.
55
+ showInConversation('r1')
56
+ vi.advanceTimersByTime(1000)
57
+ showInConversation('r1')
58
+ vi.advanceTimersByTime(1000)
59
+ expect(marked('[data-reply-id="r1"]')).toBe('true')
60
+ })
61
+
62
+ it('reports false for one that is not drawn', () => {
63
+ // A thread reads its newest first: a reply can sit above what is drawn, and the caller must be able to tell.
64
+ expect(showInConversation('r99')).toBe(false)
65
+ expect(scrollIntoView).not.toHaveBeenCalled()
66
+ })
67
+
68
+ it('does not break on an id with quotes in it', () => {
69
+ document.body.innerHTML = `<div data-reply-id='a"b'>odd</div>`
70
+ expect(showInConversation('a"b')).toBe(true)
71
+ })
72
+
73
+ it('finds a thread’s pinned comment, and a comment in the list only when asked to, the thread’s first', () => {
74
+ document.body.innerHTML = `<div data-conversation-item="c1">in the list</div><div data-thread-start="c1">pinned</div><div data-conversation-item="c2">only in the list</div>`
75
+ expect(showInConversation('c2')).toBe(false)
76
+ expect(showInConversation('c1')).toBe(true)
77
+ expect(marked('[data-thread-start="c1"]')).toBe('true')
78
+ expect(marked('[data-conversation-item="c1"]')).toBeNull()
79
+ expect(showInConversation('c2', { comments: true })).toBe(true)
80
+ expect(marked('[data-conversation-item="c2"]')).toBe('true')
81
+ })
82
+ })
83
+
84
+ describe('showInConversationWhenDrawn (INT-8)', () => {
85
+ it('shows at once when it is already there', async () => {
86
+ await expect(showInConversationWhenDrawn('r1')).resolves.toBe(true)
87
+ expect(scrollIntoView).toHaveBeenCalled()
88
+ })
89
+
90
+ it('waits for a thread that is still being drawn', async () => {
91
+ const pending = showInConversationWhenDrawn('r-late')
92
+ document.body.insertAdjacentHTML('beforeend', '<div data-reply-id="r-late">late</div>')
93
+ await vi.advanceTimersByTimeAsync(100)
94
+ await expect(pending).resolves.toBe(true)
95
+ })
96
+
97
+ it('gives up rather than waiting forever: 3 seconds, or as long as asked', async () => {
98
+ const pending = showInConversationWhenDrawn('r-never', { wait: 500 })
99
+ await vi.advanceTimersByTimeAsync(600)
100
+ await expect(pending).resolves.toBe(false)
101
+ expect(scrollIntoView).not.toHaveBeenCalled()
102
+ const longer = showInConversationWhenDrawn('r-never')
103
+ let answer: boolean | undefined
104
+ void longer.then((a) => (answer = a))
105
+ await vi.advanceTimersByTimeAsync(2900)
106
+ expect(answer).toBeUndefined()
107
+ await vi.advanceTimersByTimeAsync(200)
108
+ expect(answer).toBe(false)
109
+ })
110
+
111
+ it('a newer show stops an older wait: the reader’s last link is the one that lands', async () => {
112
+ // A link to one not drawn yet, then a link to one that is: the first, drawn later, must not take the view back.
113
+ const first = showInConversationWhenDrawn('r-late')
114
+ expect(showInConversation('r1')).toBe(true)
115
+ document.body.insertAdjacentHTML('beforeend', '<div data-reply-id="r-late">late</div>')
116
+ await vi.advanceTimersByTimeAsync(100)
117
+ await expect(first).resolves.toBe(false)
118
+ expect(scrollIntoView).toHaveBeenCalledOnce()
119
+ expect(marked('[data-reply-id="r-late"]')).toBeNull()
120
+ // And a newer wait stops an older one the same way.
121
+ const older = showInConversationWhenDrawn('r-older')
122
+ const newer = showInConversationWhenDrawn('r-newer')
123
+ document.body.insertAdjacentHTML('beforeend', '<div data-reply-id="r-older">older</div><div data-reply-id="r-newer">newer</div>')
124
+ await vi.advanceTimersByTimeAsync(100)
125
+ await expect(older).resolves.toBe(false)
126
+ await expect(newer).resolves.toBe(true)
127
+ expect(marked('[data-reply-id="r-older"]')).toBeNull()
128
+ expect(marked('[data-reply-id="r-newer"]')).toBe('true')
129
+ })
130
+
131
+ it('marks the one it eventually lands on', async () => {
132
+ const pending = showInConversationWhenDrawn('r-late')
133
+ document.body.insertAdjacentHTML('beforeend', '<div data-reply-id="r-late">late</div>')
134
+ await vi.advanceTimersByTimeAsync(100)
135
+ await pending
136
+ expect(marked('[data-reply-id="r-late"]')).toBe('true')
137
+ })
138
+ })
139
+
140
+ describe('what the kit draws carries its id', () => {
141
+ const ONE = { name: 'Person one' }
142
+
143
+ it('a reply carries its id on its card, with nothing round it of the app’s', () => {
144
+ document.body.innerHTML = ''
145
+ render(
146
+ <Thread start={{ id: 'c1', author: ONE, time: '11:08 AM', words: 'The comment' }}>
147
+ <ReplyCard id="r1" author={ONE} time="11:30 AM">
148
+ A reply
149
+ </ReplyCard>
150
+ </Thread>,
151
+ )
152
+ const card = document.querySelector('[data-reply-id="r1"]')
153
+ expect(card?.textContent).toContain('A reply')
154
+ expect(showInConversation('r1')).toBe(true)
155
+ expect(card?.getAttribute('data-shown')).toBe('true')
156
+ expect(showInConversation('c1')).toBe(true)
157
+ })
158
+
159
+ it('a comment in the list is shown when asked to, in either layout', () => {
160
+ for (const threads of ['beside', 'under'] as const) {
161
+ document.body.innerHTML = ''
162
+ render(<ConversationLayout threads={threads} items={[{ id: 'c9', card: <ConversationCard author={ONE} time="11:08 AM">A comment</ConversationCard> }]} />)
163
+ expect(showInConversation('c9', { comments: true })).toBe(true)
164
+ expect(document.querySelector('[data-conversation-item="c9"]')?.getAttribute('data-shown')).toBe('true')
165
+ cleanup()
166
+ }
167
+ })
168
+ })
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Showing one comment or reply: what a link to it does (Peek's INT-3 and INT-8, moved with the conversation for every
3
+ * app). It is scrolled to the middle of the view, the ones round it being what makes it checkable, and marked a moment
4
+ * (`data-shown`, the kit's flash: the accent's wash, fading), so the press lands on it and not near it.
5
+ *
6
+ * What it finds is what the kit draws: a reply's `data-reply-id` (`ReplyCard`'s `id`), a thread's pinned comment's
7
+ * `data-thread-start` (`Thread`'s `start.id`), and, asked for, a comment in a `ConversationLayout`'s list
8
+ * (`data-conversation-item`), after the open thread's.
9
+ */
10
+
11
+ /** How long it stays marked: the flash's own length (`animate-shown`). */
12
+ const SHOWN_MS = 1800
13
+ /** How long a show waits for it to be drawn, and how often it looks. */
14
+ const WAIT_MS = 3000
15
+ const POLL_MS = 50
16
+
17
+ /**
18
+ * The timer that will take each mark off. Without it, two shows of one comment in quick succession leave the first
19
+ * one's timer to clear the second one's mark: "is it still marked?" cannot tell whose mark it is.
20
+ */
21
+ const owed = new WeakMap<HTMLElement, number>()
22
+
23
+ /**
24
+ * Counts the shows asked for. Each wait keeps the count it started at, and stops once a newer show is asked for: a
25
+ * link pressed while an earlier one still waits is the one that lands, and the earlier never takes the view back.
26
+ */
27
+ let asked = 0
28
+
29
+ export interface ShowOptions {
30
+ /** Look in the comments of a `ConversationLayout` too, after the open thread's pinned comment and replies. */
31
+ comments?: boolean
32
+ }
33
+
34
+ export interface ShowWhenDrawnOptions extends ShowOptions {
35
+ /** How long to wait for it to be drawn, in ms: 3 seconds by default. */
36
+ wait?: number
37
+ }
38
+
39
+ function find(id: string, { comments = false }: ShowOptions): HTMLElement | null {
40
+ const quoted = CSS.escape(id)
41
+ return (
42
+ document.querySelector<HTMLElement>(`[data-reply-id="${quoted}"], [data-thread-start="${quoted}"]`) ??
43
+ (comments ? document.querySelector<HTMLElement>(`[data-conversation-item="${quoted}"]`) : null)
44
+ )
45
+ }
46
+
47
+ /**
48
+ * Scrolls a comment or reply drawn by the kit into the middle of the view and flashes it. `false` when it is not
49
+ * drawn (a thread whose older replies are not read yet, a thread not open): never a press that seems to work and does
50
+ * nothing, so the caller says it, or opens its thread and waits with `showInConversationWhenDrawn`.
51
+ */
52
+ export function showInConversation(id: string, options: ShowOptions = {}): boolean {
53
+ asked += 1
54
+ return show(id, options)
55
+ }
56
+
57
+ /** The show itself, for a show already counted: a wait's every look is one show, not a newer one. */
58
+ function show(id: string, options: ShowOptions): boolean {
59
+ const el = find(id, options)
60
+ if (!el) return false
61
+ el.scrollIntoView({ behavior: 'smooth', block: 'center' })
62
+ const previous = owed.get(el)
63
+ if (previous !== undefined) window.clearTimeout(previous)
64
+ el.dataset.shown = 'true'
65
+ owed.set(
66
+ el,
67
+ window.setTimeout(() => {
68
+ delete el.dataset.shown
69
+ owed.delete(el)
70
+ }, SHOWN_MS),
71
+ )
72
+ return true
73
+ }
74
+
75
+ /**
76
+ * The same, for one that may not be drawn yet: its thread was just asked to open, and the page draws it a moment
77
+ * later. Looks every 50ms, for 3 seconds (`wait`), and answers whether it was shown: `false` must be said, since
78
+ * waiting forever and never working look the same to the person who pressed. A newer show, of any comment, stops the
79
+ * wait (`false` too): the reader's last link is the one that lands.
80
+ */
81
+ export function showInConversationWhenDrawn(id: string, { wait = WAIT_MS, ...options }: ShowWhenDrawnOptions = {}): Promise<boolean> {
82
+ const mine = ++asked
83
+ return new Promise((resolve) => {
84
+ const deadline = Date.now() + wait
85
+ const attempt = () => {
86
+ if (mine !== asked) return resolve(false)
87
+ if (show(id, options)) return resolve(true)
88
+ if (Date.now() >= deadline) return resolve(false)
89
+ window.setTimeout(attempt, POLL_MS)
90
+ }
91
+ attempt()
92
+ })
93
+ }
package/src/threadCard.ts CHANGED
@@ -37,6 +37,22 @@ export const caretOnOpen = createContext(0)
37
37
  */
38
38
  export const LineByLayout = createContext(false)
39
39
 
40
+ /**
41
+ * A comment's exact date and time, from its moment (ms), in the reader's own way: what its time says under the pointer
42
+ * (Peek's words for it: `dateStyle: 'long'`, `timeStyle: 'short'`).
43
+ */
44
+ export const exactTime = (at: number) => new Date(at).toLocaleString(undefined, { dateStyle: 'long', timeStyle: 'short' })
45
+
46
+ /** A comment's moment when it is one, else none: a moment that is not a number (a bad date read) draws the time as with none, rather than throwing. */
47
+ export const momentOf = (at: number | undefined) => (at !== undefined && Number.isFinite(at) ? at : undefined)
48
+
49
+ /**
50
+ * The flash on a comment or reply a link just showed (`data-shown`, set by `showInConversation`): the accent's wash,
51
+ * fading over 1.8s, in 8px corners; held still, without the fade, for a reader who asks for less motion. Peek's
52
+ * cited-flash, moved (INT-3). On every element the kit marks with an id a link can name.
53
+ */
54
+ export const SHOWN_CLASSES = 'data-[shown]:animate-shown data-[shown]:rounded-lg motion-reduce:data-[shown]:animate-none motion-reduce:data-[shown]:bg-accent-wash'
55
+
40
56
  /** The room between a face and the line under it. */
41
57
  const FACE_GAP = 4
42
58