@adatechnology/conversations-ui 0.6.1 → 0.8.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 (119) hide show
  1. package/README.md +221 -19
  2. package/dist/{ConversationSimulatorPanel-CrfFjiWh.d.ts → ConversationSimulatorPanel-q-wVgBCN.d.ts} +1 -1
  3. package/dist/{chunk-HOKNKXIT.js → chunk-HMCOTZAX.js} +1 -1
  4. package/dist/{chunk-FAQLC3TX.js → chunk-L3OFAQPS.js} +2 -4
  5. package/dist/{chunk-CBYEHPX6.js → chunk-PJNR6UMN.js} +63 -1
  6. package/dist/flows/index.js +3 -5
  7. package/dist/index.d.ts +4 -4
  8. package/dist/index.js +834 -764
  9. package/dist/participant/index.d.ts +62 -3
  10. package/dist/participant/index.js +1444 -394
  11. package/dist/preview/index.d.ts +3 -3
  12. package/dist/preview/index.js +2 -3
  13. package/dist/{quickReply.types-B4gmZsSr.d.ts → quickReply.types-DzWH3NYV.d.ts} +1 -1
  14. package/dist/styles.css +629 -20
  15. package/package.json +3 -3
  16. package/src/participant/ConversationThread.test.tsx +165 -0
  17. package/src/participant/ConversationThread.tsx +117 -0
  18. package/src/participant/ParticipantAuthorAvatar.test.tsx +30 -0
  19. package/src/participant/ParticipantAuthorAvatar.tsx +24 -0
  20. package/src/participant/ParticipantBackButton.tsx +14 -0
  21. package/src/participant/ParticipantBubbleStatus.tsx +67 -0
  22. package/src/participant/ParticipantChannelBadges.tsx +13 -4
  23. package/src/participant/ParticipantComposer.tsx +8 -40
  24. package/src/participant/ParticipantComposerControls.tsx +83 -0
  25. package/src/participant/ParticipantConversationAvatar.tsx +13 -0
  26. package/src/participant/ParticipantConversations.tsx +7 -0
  27. package/src/participant/ParticipantConversationsOptions.test.tsx +87 -0
  28. package/src/participant/ParticipantCopyAnnouncer.tsx +48 -0
  29. package/src/participant/ParticipantCopyableToken.tsx +51 -0
  30. package/src/participant/ParticipantDayDivider.tsx +18 -0
  31. package/src/participant/ParticipantInbox.tsx +3 -1
  32. package/src/participant/ParticipantInboxRow.tsx +6 -4
  33. package/src/participant/ParticipantMessageBubble.test.tsx +52 -5
  34. package/src/participant/ParticipantMessageBubble.tsx +32 -84
  35. package/src/participant/ParticipantMessageNodes.tsx +54 -0
  36. package/src/participant/ParticipantMessageText.test.tsx +106 -0
  37. package/src/participant/ParticipantMessageText.tsx +52 -0
  38. package/src/participant/ParticipantProtocolBadge.tsx +15 -7
  39. package/src/participant/ParticipantProtocolView.test.tsx +4 -6
  40. package/src/participant/ParticipantScrollToLatest.test.tsx +153 -0
  41. package/src/participant/ParticipantScrollToLatest.tsx +40 -0
  42. package/src/participant/ParticipantThread.test.tsx +37 -0
  43. package/src/participant/ParticipantThread.tsx +54 -95
  44. package/src/participant/ParticipantThreadAvatarSequence.test.tsx +65 -0
  45. package/src/participant/ParticipantThreadHeader.test.tsx +181 -0
  46. package/src/participant/ParticipantThreadHeader.tsx +83 -0
  47. package/src/participant/ParticipantThreadScreen.tsx +30 -56
  48. package/src/participant/ParticipantTimeline.tsx +106 -0
  49. package/src/participant/conversationThreadApi.test.ts +27 -0
  50. package/src/participant/conversationThreadApi.ts +24 -0
  51. package/src/participant/conversationThreadCss.test.ts +116 -0
  52. package/src/participant/conversationThreadSummary.ts +34 -0
  53. package/src/participant/index.ts +4 -0
  54. package/src/participant/participantAutoGrow.test.ts +43 -0
  55. package/src/participant/participantAutoGrow.ts +12 -0
  56. package/src/participant/participantAvatar.test.ts +74 -0
  57. package/src/participant/participantAvatar.ts +48 -0
  58. package/src/participant/participantBubbleTail.test.tsx +107 -0
  59. package/src/participant/participantChatDesign.test.tsx +198 -0
  60. package/src/participant/participantContrast.test-helper.ts +116 -0
  61. package/src/participant/participantCopyAnnouncement.test.ts +52 -0
  62. package/src/participant/participantCopyAnnouncement.ts +37 -0
  63. package/src/participant/participantCss.test-helper.ts +34 -0
  64. package/src/participant/participantDay.test.ts +22 -0
  65. package/src/participant/participantDay.ts +8 -0
  66. package/src/participant/participantDocuments.ts +45 -0
  67. package/src/participant/participantGolden.test.tsx +46 -0
  68. package/src/participant/participantGoldenScenarios.test-helper.tsx +57 -0
  69. package/src/participant/participantHeaderA11y.test.tsx +85 -0
  70. package/src/participant/participantHeaderDesign.test.tsx +111 -0
  71. package/src/participant/participantLabels.ts +11 -0
  72. package/src/participant/participantMessageAtoms.ts +53 -0
  73. package/src/participant/participantMessageCopyables.test.ts +141 -0
  74. package/src/participant/participantMessageCopyables.ts +76 -0
  75. package/src/participant/participantMessageFormat.test-helper.ts +21 -0
  76. package/src/participant/participantMessageFormat.test.ts +177 -0
  77. package/src/participant/participantMessageFormat.ts +135 -0
  78. package/src/participant/participantMessageFormat.types.ts +22 -0
  79. package/src/participant/participantMessageInline.test.ts +82 -0
  80. package/src/participant/participantMessageInline.ts +99 -0
  81. package/src/participant/participantMessageLinks.test.ts +100 -0
  82. package/src/participant/participantMessageLinks.ts +54 -0
  83. package/src/participant/participantMessageTextStyle.test.ts +137 -0
  84. package/src/participant/participantMessages.ts +4 -3
  85. package/src/participant/participantNewMessages.test.ts +21 -0
  86. package/src/participant/participantNewMessages.ts +8 -3
  87. package/src/participant/participantPerspective.test.ts +67 -0
  88. package/src/participant/participantPerspective.ts +50 -0
  89. package/src/participant/participantPerspectiveRender.test.tsx +94 -0
  90. package/src/participant/participantScrollFocus.test.ts +22 -0
  91. package/src/participant/participantScrollFocus.ts +10 -0
  92. package/src/participant/participantScrollView.test.ts +74 -0
  93. package/src/participant/participantScrollView.ts +38 -0
  94. package/src/participant/participantScrollbars.test.ts +156 -0
  95. package/src/participant/participantSubjectIcon.test.tsx +27 -0
  96. package/src/participant/participantSubjectIcon.ts +26 -0
  97. package/src/participant/participantThemeContrast.test.ts +98 -0
  98. package/src/participant/test-fixtures/conversations-list.golden.html +1 -0
  99. package/src/participant/test-fixtures/conversations-selected.golden.html +1 -0
  100. package/src/participant/test-fixtures/thread-avatars-initials.golden.html +1 -0
  101. package/src/participant/test-fixtures/thread-closed.golden.html +1 -0
  102. package/src/participant/test-fixtures/thread-default.golden.html +1 -0
  103. package/src/participant/test-fixtures/thread-error.golden.html +1 -0
  104. package/src/participant/test-fixtures/thread-loading.golden.html +1 -0
  105. package/src/participant/test-fixtures/thread-plain.golden.html +1 -0
  106. package/src/participant/test-fixtures/thread-tail-off.golden.html +1 -0
  107. package/src/participant/useParticipantConversationView.ts +3 -0
  108. package/src/participant/useParticipantCopyFeedback.ts +33 -0
  109. package/src/participant/useParticipantThread.ts +13 -2
  110. package/src/participant/useParticipantThreadController.ts +112 -0
  111. package/src/participant/useParticipantThreadScroll.ts +13 -3
  112. package/src/participant/useParticipantUnread.test.tsx +40 -0
  113. package/src/participant/useParticipantUnread.ts +38 -0
  114. package/src/participant/useRevealActiveChip.ts +20 -0
  115. package/src/participant/useScrollAwayState.ts +24 -0
  116. package/src/participant/useStickToBottom.ts +16 -2
  117. package/src/styles.css +151 -23
  118. package/dist/chunk-MRVFFJEH.js +0 -64
  119. package/dist/chunk-OVFCLRQQ.js +0 -84
@@ -0,0 +1,82 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+
3
+ import { show } from './participantMessageFormat.test-helper'
4
+ import { parseInline } from './participantMessageInline'
5
+
6
+ function inline(line: string): string {
7
+ return show(parseInline(line))
8
+ }
9
+
10
+ describe('parseInline - basic marks', () => {
11
+ it('formats bold, italic, strike and inline code', () => {
12
+ expect(inline('*a b*')).toBe('⟦s:a b⟧')
13
+ expect(inline('x *a* y')).toBe('x ⟦s:a⟧ y')
14
+ expect(inline('_a b_')).toBe('⟦e:a b⟧')
15
+ expect(inline('~a b~')).toBe('⟦d:a b⟧')
16
+ expect(inline('`a b`')).toBe('⟦c:a b⟧')
17
+ expect(inline('oi *tudo* _bem_ ~mal~ `ok`')).toBe('oi ⟦s:tudo⟧ ⟦e:bem⟧ ⟦d:mal⟧ ⟦c:ok⟧')
18
+ })
19
+
20
+ it('formats marks that touch punctuation', () => {
21
+ expect(inline('(*a*)')).toBe('(⟦s:a⟧)')
22
+ expect(inline('*a*, _b_.')).toBe('⟦s:a⟧, ⟦e:b⟧.')
23
+ })
24
+
25
+ it('treats triple backticks in the middle of a line as inline code', () => {
26
+ expect(inline('veja ```x y``` aqui')).toBe('veja ⟦c:x y⟧ aqui')
27
+ })
28
+ })
29
+
30
+ describe('parseInline - nesting', () => {
31
+ it('nests valid combinations in both orders', () => {
32
+ expect(inline('*_negrito itálico_*')).toBe('⟦s:⟦e:negrito itálico⟧⟧')
33
+ expect(inline('_*assim*_')).toBe('⟦e:⟦s:assim⟧⟧')
34
+ expect(inline('~*_x_*~')).toBe('⟦d:⟦s:⟦e:x⟧⟧⟧')
35
+ expect(inline('*a _b_ c*')).toBe('⟦s:a ⟦e:b⟧ c⟧')
36
+ })
37
+
38
+ it('does not let crossing marks form invalid trees', () => {
39
+ expect(inline('*a _b* c_')).toBe('⟦s:a _b⟧ c_')
40
+ expect(inline('_a *b_ c*')).toBe('⟦e:a *b⟧ c*')
41
+ })
42
+
43
+ it('keeps code inside marks and never formats inside code', () => {
44
+ expect(inline('*a `b` c*')).toBe('⟦s:a ⟦c:b⟧ c⟧')
45
+ expect(inline('`*a*`')).toBe('⟦c:*a*⟧')
46
+ expect(inline('`_a_ ~b~`')).toBe('⟦c:_a_ ~b~⟧')
47
+ })
48
+ })
49
+
50
+ describe('parseInline - loose markers', () => {
51
+ it('does not format when the marker is glued to whitespace', () => {
52
+ expect(inline('* a *')).toBe('* a *')
53
+ expect(inline('2 * 3 * 4')).toBe('2 * 3 * 4')
54
+ expect(inline('_ a _')).toBe('_ a _')
55
+ expect(inline('~ a ~')).toBe('~ a ~')
56
+ })
57
+
58
+ it('does not format inside a word', () => {
59
+ expect(inline('snake_case_nome')).toBe('snake_case_nome')
60
+ expect(inline('a*b*c')).toBe('a*b*c')
61
+ expect(inline('2*3*4')).toBe('2*3*4')
62
+ })
63
+
64
+ it('leaves unmatched and empty markers alone', () => {
65
+ expect(inline('*a')).toBe('*a')
66
+ expect(inline('a*')).toBe('a*')
67
+ expect(inline('**')).toBe('**')
68
+ expect(inline('__')).toBe('__')
69
+ expect(inline('``')).toBe('``')
70
+ expect(inline('`aberto')).toBe('`aberto')
71
+ })
72
+ })
73
+
74
+ describe('parseInline - emoji', () => {
75
+ it('keeps ZWJ sequences, flags, skin tones and variation selectors intact', () => {
76
+ expect(inline('*👨‍👩‍👧*')).toBe('⟦s:👨‍👩‍👧⟧')
77
+ expect(inline('🇧🇷 _oi_')).toBe('🇧🇷 ⟦e:oi⟧')
78
+ expect(inline('👍🏽*x*')).toBe('👍🏽⟦s:x⟧')
79
+ expect(inline('‼️ ~não~')).toBe('‼️ ⟦d:não⟧')
80
+ expect(inline('👨‍👩‍👧 🇧🇷 👍🏽 ‼️')).toBe('👨‍👩‍👧 🇧🇷 👍🏽 ‼️')
81
+ })
82
+ })
@@ -0,0 +1,99 @@
1
+ import { findInlineAtoms } from './participantMessageAtoms'
2
+ import type { InlineAtom, InlineNode } from './participantMessageFormat.types'
3
+
4
+ type MarkKind = 'strong' | 'em' | 'del'
5
+
6
+ const MARKS: Readonly<Record<string, MarkKind>> = { '*': 'strong', _: 'em', '~': 'del' }
7
+
8
+ type LineContext = {
9
+ readonly text: string
10
+ readonly atomAt: ReadonlyMap<number, InlineAtom>
11
+ readonly isMasked: readonly boolean[]
12
+ readonly closers: Readonly<Record<string, readonly number[]>>
13
+ }
14
+
15
+ function isWord(character: string | undefined): boolean {
16
+ return character !== undefined && /[\p{L}\p{N}]/u.test(character)
17
+ }
18
+
19
+ function isSpace(character: string | undefined): boolean {
20
+ return character === undefined || /\s/u.test(character)
21
+ }
22
+
23
+ function characterBefore(text: string, index: number): string | undefined {
24
+ if (index <= 0) return undefined
25
+ const code = text.charCodeAt(index - 1)
26
+ const isLowSurrogate = code >= 0xdc00 && code <= 0xdfff
27
+ if (isLowSurrogate && index >= 2) return String.fromCodePoint(text.codePointAt(index - 2) ?? code)
28
+ return text.charAt(index - 1)
29
+ }
30
+
31
+ function buildContext(text: string): LineContext {
32
+ const atoms = findInlineAtoms(text)
33
+ const isMasked: boolean[] = new Array<boolean>(text.length).fill(false)
34
+ for (const atom of atoms) isMasked.fill(true, atom.start, atom.end)
35
+ const closers: Record<string, number[]> = { '*': [], _: [], '~': [] }
36
+ for (let index = 1; index < text.length; index += 1) {
37
+ const character = text.charAt(index)
38
+ const list = closers[character]
39
+ const isCloser = list !== undefined && !isMasked[index] && !isSpace(text[index - 1]) && !isWord(text[index + 1])
40
+ if (isCloser) list.push(index)
41
+ }
42
+ return { text, atomAt: new Map(atoms.map((atom) => [atom.start, atom])), isMasked, closers }
43
+ }
44
+
45
+ function isOpener(context: LineContext, index: number): boolean {
46
+ const { text } = context
47
+ const next = text[index + 1]
48
+ if (context.isMasked[index] || next === undefined || isSpace(next) || next === text[index]) return false
49
+ return !isWord(characterBefore(text, index))
50
+ }
51
+
52
+ function findCloser(context: LineContext, mark: string, from: number, limit: number): number | undefined {
53
+ const list = context.closers[mark] ?? []
54
+ let low = 0
55
+ let high = list.length
56
+ while (low < high) {
57
+ const middle = (low + high) >> 1
58
+ if ((list[middle] ?? 0) < from) low = middle + 1
59
+ else high = middle
60
+ }
61
+ const found = list[low]
62
+ return found !== undefined && found < limit ? found : undefined
63
+ }
64
+
65
+ function parseRange(context: LineContext, start: number, end: number): InlineNode[] {
66
+ const nodes: InlineNode[] = []
67
+ let textStart = start
68
+ let index = start
69
+ const flush = (until: number): void => {
70
+ if (until > textStart) nodes.push({ kind: 'text', value: context.text.slice(textStart, until) })
71
+ }
72
+ while (index < end) {
73
+ const atom = context.atomAt.get(index)
74
+ const mark = MARKS[context.text.charAt(index)]
75
+ const closer =
76
+ mark !== undefined && !atom && isOpener(context, index)
77
+ ? findCloser(context, context.text.charAt(index), index + 2, end)
78
+ : undefined
79
+ if (atom) {
80
+ flush(index)
81
+ nodes.push(atom.node)
82
+ index = atom.end
83
+ } else if (mark !== undefined && closer !== undefined) {
84
+ flush(index)
85
+ nodes.push({ kind: mark, children: parseRange(context, index + 1, closer) })
86
+ index = closer + 1
87
+ } else {
88
+ index += 1
89
+ continue
90
+ }
91
+ textStart = index
92
+ }
93
+ flush(end)
94
+ return nodes
95
+ }
96
+
97
+ export function parseInline(line: string): InlineNode[] {
98
+ return parseRange(buildContext(line), 0, line.length)
99
+ }
@@ -0,0 +1,100 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+
3
+ import { show } from './participantMessageFormat.test-helper'
4
+ import { isAllowedLinkHref } from './participantMessageLinks'
5
+ import { parseInline } from './participantMessageInline'
6
+
7
+ function inline(line: string): string {
8
+ return show(parseInline(line))
9
+ }
10
+
11
+ describe('isAllowedLinkHref', () => {
12
+ it('accepts only http, https, mailto and tel', () => {
13
+ expect(isAllowedLinkHref('http://a.com')).toBe(true)
14
+ expect(isAllowedLinkHref('https://a.com/x?y=1')).toBe(true)
15
+ expect(isAllowedLinkHref('HTTPS://A.COM')).toBe(true)
16
+ expect(isAllowedLinkHref('mailto:a@b.co')).toBe(true)
17
+ expect(isAllowedLinkHref('tel:+5511987654321')).toBe(true)
18
+ })
19
+
20
+ it('rejects every other protocol and non-URLs', () => {
21
+ expect(isAllowedLinkHref('javascript:alert(1)')).toBe(false)
22
+ expect(isAllowedLinkHref(' javascript:alert(1)')).toBe(false)
23
+ expect(isAllowedLinkHref('JaVaScRiPt:alert(1)')).toBe(false)
24
+ expect(isAllowedLinkHref('data:text/html,<b>x</b>')).toBe(false)
25
+ expect(isAllowedLinkHref('vbscript:x')).toBe(false)
26
+ expect(isAllowedLinkHref('file:///etc/passwd')).toBe(false)
27
+ expect(isAllowedLinkHref('ftp://a.com')).toBe(false)
28
+ expect(isAllowedLinkHref('//a.com')).toBe(false)
29
+ expect(isAllowedLinkHref('/relativo')).toBe(false)
30
+ expect(isAllowedLinkHref('')).toBe(false)
31
+ })
32
+ })
33
+
34
+ describe('autolink - http and https', () => {
35
+ it('links plain URLs and keeps the literal as the label', () => {
36
+ expect(inline('veja https://a.com/x agora')).toBe('veja ⟦l:https://a.com/x→https://a.com/x⟧ agora')
37
+ expect(inline('http://a.com')).toBe('⟦l:http://a.com→http://a.com⟧')
38
+ })
39
+
40
+ it('keeps trailing punctuation outside the link', () => {
41
+ expect(inline('https://a.com.')).toBe('⟦l:https://a.com→https://a.com⟧.')
42
+ expect(inline('https://a.com,')).toBe('⟦l:https://a.com→https://a.com⟧,')
43
+ expect(inline('https://a.com;')).toBe('⟦l:https://a.com→https://a.com⟧;')
44
+ expect(inline('https://a.com:')).toBe('⟦l:https://a.com→https://a.com⟧:')
45
+ expect(inline('https://a.com!')).toBe('⟦l:https://a.com→https://a.com⟧!')
46
+ expect(inline('https://a.com?')).toBe('⟦l:https://a.com→https://a.com⟧?')
47
+ expect(inline('https://a.com/x...')).toBe('⟦l:https://a.com/x→https://a.com/x⟧...')
48
+ })
49
+
50
+ it('keeps balanced parentheses inside and drops the unbalanced one', () => {
51
+ expect(inline('(veja https://a.com/p)')).toBe('(veja ⟦l:https://a.com/p→https://a.com/p⟧)')
52
+ expect(inline('https://a.com/p_(x)')).toBe('⟦l:https://a.com/p_(x)→https://a.com/p_(x)⟧')
53
+ expect(inline('(https://a.com/p_(x))')).toBe('(⟦l:https://a.com/p_(x)→https://a.com/p_(x)⟧)')
54
+ })
55
+
56
+ it('keeps query strings and ampersands', () => {
57
+ expect(inline('https://a.com/?a=1&b=2')).toBe('⟦l:https://a.com/?a=1&b=2→https://a.com/?a=1&b=2⟧')
58
+ })
59
+
60
+ it('accepts an uppercase scheme, normalising only the scheme of the href', () => {
61
+ expect(inline('HTTP://MAIUSCULO')).toBe('⟦l:HTTP://MAIUSCULO→http://MAIUSCULO⟧')
62
+ })
63
+
64
+ it('does not format marks inside a URL, but a mark may wrap it', () => {
65
+ expect(inline('https://a.com/_x_/~y~/*z*')).toBe('⟦l:https://a.com/_x_/~y~/*z→https://a.com/_x_/~y~/*z⟧*')
66
+ expect(inline('*https://a.com*')).toBe('⟦s:⟦l:https://a.com→https://a.com⟧⟧')
67
+ })
68
+
69
+ it('does not link a scheme with nothing after it, nor inside code', () => {
70
+ expect(inline('https://')).toBe('https://')
71
+ expect(inline('`https://a.com`')).toBe('⟦c:https://a.com⟧')
72
+ })
73
+ })
74
+
75
+ describe('autolink - unsafe protocols stay text', () => {
76
+ it('never links javascript, data or vbscript', () => {
77
+ expect(inline('javascript:alert(1)')).toBe('javascript:alert(1)')
78
+ expect(inline('data:text/html,<script>alert(1)</script>')).toBe('data:text/html,<script>alert(1)</script>')
79
+ expect(inline('vbscript:msgbox(1)')).toBe('vbscript:msgbox(1)')
80
+ expect(inline('clique: javascript://%0aalert(1)')).toBe('clique: javascript://%0aalert(1)')
81
+ })
82
+ })
83
+
84
+ describe('autolink - cost and userinfo', () => {
85
+ it('trims a long run of closing parentheses in linear time', () => {
86
+ const started = performance.now()
87
+ inline(`https://a${')'.repeat(7990)}`)
88
+ expect(performance.now() - started).toBeLessThan(20)
89
+ })
90
+
91
+ it('still balances parentheses', () => {
92
+ expect(inline('https://a.com/x_(y))')).toBe('⟦l:https://a.com/x_(y)→https://a.com/x_(y)⟧)')
93
+ })
94
+
95
+ it('leaves a link with credentials as text', () => {
96
+ expect(isAllowedLinkHref('https://user:pass@a.com')).toBe(false)
97
+ expect(isAllowedLinkHref('https://user@a.com')).toBe(false)
98
+ expect(inline('https://user:pass@a.com/x')).not.toContain('⟦l:')
99
+ })
100
+ })
@@ -0,0 +1,54 @@
1
+ import type { InlineAtom } from './participantMessageFormat.types'
2
+
3
+ const ALLOWED_LINK_PROTOCOLS: ReadonlySet<string> = new Set(['http:', 'https:', 'mailto:', 'tel:'])
4
+ const URL_PATTERN = /https?:\/\/[^\s<>`\u0000-\u001f]+/giu
5
+ const TRAILING_PUNCTUATION = '.,;:!?*_~\'"]}>'
6
+
7
+ export function isAllowedLinkHref(href: string): boolean {
8
+ try {
9
+ const url = new URL(href)
10
+ return ALLOWED_LINK_PROTOCOLS.has(url.protocol) && url.username === '' && url.password === ''
11
+ } catch {
12
+ return false
13
+ }
14
+ }
15
+
16
+ function isAlphanumeric(character: string | undefined): boolean {
17
+ return character !== undefined && /[\p{L}\p{N}]/u.test(character)
18
+ }
19
+
20
+ function countOf(text: string, character: string): number {
21
+ let count = 0
22
+ for (const current of text) if (current === character) count += 1
23
+ return count
24
+ }
25
+
26
+ function trimUrl(raw: string): string {
27
+ let openCount = countOf(raw, '(')
28
+ let closeCount = countOf(raw, ')')
29
+ let end = raw.length
30
+ while (end > 0) {
31
+ const last = raw.charAt(end - 1)
32
+ if (last === ')' && closeCount > openCount) closeCount -= 1
33
+ else if (!TRAILING_PUNCTUATION.includes(last)) break
34
+ end -= 1
35
+ }
36
+ return raw.slice(0, end)
37
+ }
38
+
39
+ function toLinkAtom(text: string, start: number, raw: string): InlineAtom | undefined {
40
+ const label = trimUrl(raw)
41
+ if (/^https?:\/\/$/i.test(label) || isAlphanumeric(text[start - 1])) return undefined
42
+ const href = label.replace(/^https?/i, (scheme) => scheme.toLowerCase())
43
+ if (!isAllowedLinkHref(href)) return undefined
44
+ return { start, end: start + label.length, node: { kind: 'link', href, label } }
45
+ }
46
+
47
+ export function findLinkAtoms(text: string): InlineAtom[] {
48
+ const atoms: InlineAtom[] = []
49
+ for (const match of text.matchAll(URL_PATTERN)) {
50
+ const atom = toLinkAtom(text, match.index, match[0])
51
+ if (atom) atoms.push(atom)
52
+ }
53
+ return atoms
54
+ }
@@ -0,0 +1,137 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { describe, expect, it } from 'bun:test'
4
+
5
+ import { splitBlocks } from '../cssBlocks.test-helper'
6
+ import { PARTICIPANT_CSS, declarationsIn } from './participantCss.test-helper'
7
+
8
+ const TEXT_SELECTOR = /\.cv-p-(text|copyable)/
9
+
10
+ function collectBlocks(css: string): string[] {
11
+ return splitBlocks(css).flatMap(({ prelude, body }) => {
12
+ if (body === undefined) return []
13
+ if (prelude.startsWith('@media')) return collectBlocks(body)
14
+ return TEXT_SELECTOR.test(prelude) ? [`${prelude} {${body}}`] : []
15
+ })
16
+ }
17
+
18
+ function forcedColorsBody(): string {
19
+ return splitBlocks(PARTICIPANT_CSS)
20
+ .filter(({ prelude }) => prelude === '@media (forced-colors: active)')
21
+ .map(({ body }) => body ?? '')
22
+ .join('\n')
23
+ }
24
+
25
+ const TEXT_CSS = collectBlocks(PARTICIPANT_CSS).join('\n')
26
+
27
+ describe('participant message text - stylesheet', () => {
28
+ it('has rules for the text, the code, the block, the quote and the tokens', () => {
29
+ expect(collectBlocks(PARTICIPANT_CSS).length).toBeGreaterThan(12)
30
+ })
31
+
32
+ it('uses no fixed colour and no url()', () => {
33
+ expect(TEXT_CSS).not.toMatch(/#[0-9a-f]{3,8}\b/i)
34
+ expect(TEXT_CSS).not.toMatch(/\b(rgb|rgba|hsl|hsla)\(/i)
35
+ expect(TEXT_CSS).not.toContain('url(')
36
+ })
37
+
38
+ it('keeps the text selectable and the typography of the old text', () => {
39
+ const text = declarationsIn('.cv-p-text')
40
+ expect(text.get('user-select')).toBe('text')
41
+ expect(text.get('white-space')).toBe('pre-wrap')
42
+ expect(text.get('font-size')).toBe('14.2px')
43
+ expect(text.get('line-height')).toBe('19px')
44
+ })
45
+
46
+ it('styles inline code and the block from the tokens', () => {
47
+ expect(declarationsIn('.cv-p-text__code').get('background')).toBe(
48
+ declarationsIn('.cv-p-text__pre').get('background'),
49
+ )
50
+ expect(declarationsIn('.cv-p-text__code').get('background')).toContain('color-mix(in srgb, var(--cv-p-i-border)')
51
+ expect(declarationsIn('.cv-p-text__code').get('border-radius')).toBe('var(--cv-p-i-radius)')
52
+ const pre = declarationsIn('.cv-p-text__pre')
53
+ expect(pre.get('overflow-x')).toBe('auto')
54
+ expect(pre.get('white-space')).toBe('pre')
55
+ expect(pre.get('border-inline-start')).toBe('2px solid var(--cv-p-i-accent)')
56
+ expect(pre.get('scrollbar-color')).toBe('var(--cv-p-i-scrollbar-thumb) transparent')
57
+ })
58
+
59
+ it('styles the quote, the lists and the links from the tokens', () => {
60
+ const quote = declarationsIn('.cv-p-text__quote')
61
+ expect(quote.get('border-inline-start')).toBe('3px solid var(--cv-p-i-border)')
62
+ expect(quote.get('color')).toBe('var(--cv-p-i-text-muted)')
63
+ expect(declarationsIn('.cv-p-text__list').get('padding-inline-start')).toBe('1.25rem')
64
+ const link = declarationsIn('.cv-p-text__link')
65
+ expect(link.get('color')).toBe('var(--cv-p-i-accent)')
66
+ expect(link.get('text-decoration')).toBe('underline')
67
+ expect(link.get('overflow-wrap')).toBe('anywhere')
68
+ expect(declarationsIn('.cv-p-text__link:focus-visible').get('outline')).toBe('2px solid var(--cv-p-i-accent)')
69
+ })
70
+
71
+ it('highlights tokens discreetly with the accent', () => {
72
+ const token = declarationsIn('.cv-p-copyable')
73
+ expect(token.get('background')).toBe('color-mix(in srgb, var(--cv-p-i-accent) 14%, transparent)')
74
+ expect(token.get('border-bottom')).toBe('1px dotted var(--cv-p-i-accent)')
75
+ expect(token.get('font-family')).toContain('monospace')
76
+ expect(token.get('border-radius')).toBe('var(--cv-p-i-radius)')
77
+ expect(token.get('user-select')).toBe('text')
78
+ })
79
+
80
+ it('keeps the tap target of tokens and the copy icon from invading neighbouring lines or the link text', () => {
81
+ expect(declarationsIn('.cv-p').get('--cv-p-i-touch')).toBe('2.75rem')
82
+ for (const selector of ['.cv-p-copyable::after', '.cv-p-text__link-copy::after']) {
83
+ expect(declarationsIn(selector).get('min-height')).toBe('1.5rem')
84
+ }
85
+ const icon = declarationsIn('.cv-p-text__link-copy::after')
86
+ expect(icon.get('inset-inline')).toBe('0 auto')
87
+ expect(icon.get('min-width')).toBe('var(--cv-p-i-touch)')
88
+ expect(icon.get('margin-inline-start')).toBeUndefined()
89
+ expect(declarationsIn('.cv-p-copyable').get('display')).toBe('inline')
90
+ expect(declarationsIn('.cv-p-copyable').get('position')).toBe('relative')
91
+ })
92
+
93
+ it('gets borders instead of backgrounds under forced colors', () => {
94
+ const forced = forcedColorsBody()
95
+ expect(forced).toContain('.cv-p-copyable')
96
+ expect(forced).toContain('.cv-p-text__pre')
97
+ expect(declarationsIn('.cv-p-copyable', forced).get('border')).toBe('1px solid')
98
+ expect(declarationsIn('.cv-p-copyable', forced).get('background')).toBe('none')
99
+ })
100
+ })
101
+
102
+ describe('participant message text - hygiene', () => {
103
+ const FILES = [
104
+ 'participantMessageFormat.ts',
105
+ 'participantMessageInline.ts',
106
+ 'participantMessageAtoms.ts',
107
+ 'participantMessageLinks.ts',
108
+ 'participantMessageCopyables.ts',
109
+ 'participantDocuments.ts',
110
+ 'ParticipantMessageText.tsx',
111
+ 'ParticipantMessageNodes.tsx',
112
+ 'ParticipantCopyableToken.tsx',
113
+ 'ParticipantCopyAnnouncer.tsx',
114
+ 'useParticipantCopyFeedback.ts',
115
+ ] as const
116
+ const sources = FILES.map((file) => ({ file, source: readFileSync(join(import.meta.dir, file), 'utf8') }))
117
+
118
+ it('stays within 200 lines per file', () => {
119
+ for (const { file, source } of sources) {
120
+ expect({ file, ok: source.split('\n').length <= 200 }).toEqual({ file, ok: true })
121
+ }
122
+ })
123
+
124
+ it('never sets inner HTML, never uses any, never reuses the shared MessageText', () => {
125
+ for (const { source } of sources) {
126
+ expect(source).not.toMatch(/innerHTML|dangerouslySetInnerHTML|:\s*any\b|as any|MessageText\b.*from '\.\.\//)
127
+ expect(source).not.toContain('whatsapp-formatting')
128
+ }
129
+ })
130
+
131
+ it('has no Tailwind utilities and no vocabulary from a specific product', () => {
132
+ for (const { source } of sources) {
133
+ expect(source).not.toMatch(/className="[^"]*\b(flex|grid|p-\d|m-\d|text-(sm|xs|lg)|bg-\w+)\b/)
134
+ expect(source).not.toMatch(/\b(carga|entrega|frete|cte|nf-?e|transport\w*|motorista|viagem|trip|driver)\b/i)
135
+ }
136
+ })
137
+ })
@@ -1,6 +1,7 @@
1
1
  import type { MessageDeliveryStatus, ParticipantMessage, ParticipantSubjectRef } from '@adatechnology/conversation-contracts'
2
2
 
3
3
  import type { ParticipantLocalPendingMessage, ParticipantPendingMessage } from './participantApi.types'
4
+ import { isMessageMine, type ParticipantPerspective } from './participantPerspective'
4
5
 
5
6
  export type ParticipantPendingDisplayState = 'sending' | 'queued' | 'failed' | 'sent'
6
7
  export type ParticipantOwnMessageStatus = 'sending' | 'queued' | 'sent' | 'delivered' | 'read' | 'failed'
@@ -58,9 +59,9 @@ export function mergeParticipantMessages(params: MergeParticipantMessagesParams)
58
59
  return items.sort((left, right) => createdAtOf(left) - createdAtOf(right))
59
60
  }
60
61
 
61
- /** Direction is from the company perspective: the participant is the inbound side. */
62
- export function isOwnMessage(message: ParticipantMessage): boolean {
63
- return message.direction === 'inbound'
62
+ /** Direction is from the company side: the participant is the inbound side, the operator the outbound one. */
63
+ export function isOwnMessage(message: ParticipantMessage, perspective?: ParticipantPerspective): boolean {
64
+ return isMessageMine(message, perspective)
64
65
  }
65
66
 
66
67
  export function resolveOwnMessageStatus(params: ResolveOwnMessageStatusParams): ParticipantOwnMessageStatus {
@@ -52,3 +52,24 @@ describe('collectServerMessageIds', () => {
52
52
  expect([...collectServerMessageIds([server('a', 'inbound'), server('b', 'outbound')])]).toEqual(['a', 'b'])
53
53
  })
54
54
  })
55
+
56
+ describe('countNewIncomingMessages with the operator perspective', () => {
57
+ const seen = [server('s', 'inbound', '2026-10-01T10:00:00.000Z')]
58
+ const seenIds = collectServerMessageIds(seen)
59
+
60
+ it('counts a new inbound message as news', () => {
61
+ const items = [...seen, server('n', 'inbound', '2026-10-01T10:05:00.000Z')]
62
+ expect(countNewIncomingMessages(seenIds, items, 'operator')).toBe(1)
63
+ })
64
+
65
+ it('does not count a new outbound message (written by the operator)', () => {
66
+ const items = [...seen, server('n', 'outbound', '2026-10-01T10:05:00.000Z')]
67
+ expect(countNewIncomingMessages(seenIds, items, 'operator')).toBe(0)
68
+ })
69
+
70
+ it('keeps the participant behavior when the perspective is omitted or participant', () => {
71
+ const items = [...seen, server('n', 'outbound', '2026-10-01T10:05:00.000Z'), server('m', 'inbound', '2026-10-01T10:06:00.000Z')]
72
+ expect(countNewIncomingMessages(seenIds, items)).toBe(1)
73
+ expect(countNewIncomingMessages(seenIds, items, 'participant')).toBe(1)
74
+ })
75
+ })
@@ -1,4 +1,5 @@
1
1
  import type { ParticipantTimelineItem } from './participantMessages'
2
+ import { isMessageMine, type ParticipantPerspective } from './participantPerspective'
2
3
 
3
4
  export function collectServerMessageIds(items: readonly ParticipantTimelineItem[]): ReadonlySet<string> {
4
5
  const ids = new Set<string>()
@@ -16,13 +17,17 @@ function latestSeenTime(previousIds: ReadonlySet<string>, items: readonly Partic
16
17
  return latest
17
18
  }
18
19
 
19
- /** Messages from the other side ('outbound') newer than what the participant has seen; older history loaded above is not news. */
20
- export function countNewIncomingMessages(previousIds: ReadonlySet<string>, currentItems: readonly ParticipantTimelineItem[]): number {
20
+ /** Messages from the other side of the viewer's perspective newer than what the participant has seen; older history loaded above is not news. */
21
+ export function countNewIncomingMessages(
22
+ previousIds: ReadonlySet<string>,
23
+ currentItems: readonly ParticipantTimelineItem[],
24
+ perspective?: ParticipantPerspective,
25
+ ): number {
21
26
  const latestSeen = latestSeenTime(previousIds, currentItems)
22
27
  return currentItems.filter(
23
28
  (item) =>
24
29
  item.kind === 'server' &&
25
- item.message.direction === 'outbound' &&
30
+ !isMessageMine(item.message, perspective) &&
26
31
  !previousIds.has(item.message.id) &&
27
32
  Date.parse(item.message.createdAt) > latestSeen,
28
33
  ).length
@@ -0,0 +1,67 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+
3
+ import { buildMessage } from './participantFixtures.test-helper'
4
+ import { isOwnMessage } from './participantMessages'
5
+ import {
6
+ countOtherSideMessages,
7
+ countUnreadByViewer,
8
+ isMessageMine,
9
+ resolveViewerUnread,
10
+ } from './participantPerspective'
11
+
12
+ const INBOUND = buildMessage({ id: 'i', direction: 'inbound' })
13
+ const OUTBOUND = buildMessage({ id: 'o', direction: 'outbound' })
14
+
15
+ describe('isMessageMine', () => {
16
+ it('treats inbound as mine for the participant, and by default', () => {
17
+ expect(isMessageMine(INBOUND, 'participant')).toBe(true)
18
+ expect(isMessageMine(OUTBOUND, 'participant')).toBe(false)
19
+ expect(isMessageMine(INBOUND)).toBe(true)
20
+ expect(isMessageMine(OUTBOUND)).toBe(false)
21
+ })
22
+
23
+ it('inverts for the operator: outbound is mine', () => {
24
+ expect(isMessageMine(OUTBOUND, 'operator')).toBe(true)
25
+ expect(isMessageMine(INBOUND, 'operator')).toBe(false)
26
+ })
27
+
28
+ it('keeps isOwnMessage identical without a perspective', () => {
29
+ expect(isOwnMessage(INBOUND)).toBe(true)
30
+ expect(isOwnMessage(OUTBOUND)).toBe(false)
31
+ expect(isOwnMessage(OUTBOUND, 'operator')).toBe(true)
32
+ })
33
+ })
34
+
35
+ describe('unread by the viewer', () => {
36
+ const MESSAGES = [
37
+ buildMessage({ id: 'a', direction: 'inbound' }),
38
+ buildMessage({ id: 'b', direction: 'inbound', status: 'read' }),
39
+ buildMessage({ id: 'c', direction: 'inbound', readAt: '2026-10-01T11:00:00.000Z' }),
40
+ buildMessage({ id: 'd', direction: 'outbound' }),
41
+ buildMessage({ id: 'e', direction: 'outbound' }),
42
+ ]
43
+
44
+ it('counts only the other side, never the viewer own messages', () => {
45
+ expect(countUnreadByViewer(MESSAGES, 'operator')).toBe(1)
46
+ expect(countUnreadByViewer(MESSAGES, 'participant')).toBe(2)
47
+ expect(countOtherSideMessages(MESSAGES, 'operator')).toBe(3)
48
+ expect(countOtherSideMessages(MESSAGES, 'participant')).toBe(2)
49
+ })
50
+
51
+ it('reads nothing as unread when the operator has only outbound messages', () => {
52
+ expect(countUnreadByViewer([OUTBOUND, OUTBOUND], 'operator')).toBe(0)
53
+ })
54
+
55
+ it('resolves to zero until something new arrives after the acknowledgement', () => {
56
+ const base = { messages: MESSAGES, perspective: 'operator' } as const
57
+ expect(resolveViewerUnread({ ...base, acknowledgedCount: 0 })).toBe(1)
58
+ expect(resolveViewerUnread({ ...base, acknowledgedCount: 3 })).toBe(0)
59
+ expect(
60
+ resolveViewerUnread({
61
+ ...base,
62
+ messages: [...MESSAGES, buildMessage({ id: 'f', direction: 'inbound' })],
63
+ acknowledgedCount: 3,
64
+ }),
65
+ ).toBe(2)
66
+ })
67
+ })
@@ -0,0 +1,50 @@
1
+ import type { MessageDirection, ParticipantMessage } from '@adatechnology/conversation-contracts'
2
+
3
+ /** Who is looking at the conversation. `participant` is the outside party; `operator` is the company. */
4
+ export type ParticipantPerspective = 'participant' | 'operator'
5
+
6
+ export const DEFAULT_PARTICIPANT_PERSPECTIVE: ParticipantPerspective = 'participant'
7
+
8
+ /** `direction` is from the company side: the participant writes `inbound`, the operator writes `outbound`. */
9
+ const OWN_DIRECTION: Record<ParticipantPerspective, MessageDirection> = {
10
+ participant: 'inbound',
11
+ operator: 'outbound',
12
+ }
13
+
14
+ export function isMessageMine(
15
+ message: Pick<ParticipantMessage, 'direction'>,
16
+ perspective: ParticipantPerspective = DEFAULT_PARTICIPANT_PERSPECTIVE,
17
+ ): boolean {
18
+ return message.direction === OWN_DIRECTION[perspective]
19
+ }
20
+
21
+ type ReadState = Pick<ParticipantMessage, 'direction' | 'status' | 'readAt'>
22
+
23
+ function isUnreadByViewer(message: ReadState, perspective: ParticipantPerspective): boolean {
24
+ if (isMessageMine(message, perspective)) return false
25
+ return !message.readAt && message.status !== 'read'
26
+ }
27
+
28
+ export function countOtherSideMessages(
29
+ messages: readonly Pick<ParticipantMessage, 'direction'>[],
30
+ perspective: ParticipantPerspective,
31
+ ): number {
32
+ return messages.filter((message) => !isMessageMine(message, perspective)).length
33
+ }
34
+
35
+ export function countUnreadByViewer(messages: readonly ReadState[], perspective: ParticipantPerspective): number {
36
+ return messages.filter((message) => isUnreadByViewer(message, perspective)).length
37
+ }
38
+
39
+ export type ResolveViewerUnreadParams = {
40
+ readonly messages: readonly ReadState[]
41
+ readonly perspective: ParticipantPerspective
42
+ /** How many other-side messages the viewer already acknowledged through markRead. */
43
+ readonly acknowledgedCount: number
44
+ }
45
+
46
+ /** Unread other-side messages, or zero while nothing arrived since the last acknowledgement. */
47
+ export function resolveViewerUnread({ messages, perspective, acknowledgedCount }: ResolveViewerUnreadParams): number {
48
+ if (countOtherSideMessages(messages, perspective) <= acknowledgedCount) return 0
49
+ return countUnreadByViewer(messages, perspective)
50
+ }