@wtfalch/chat 0.1.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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -0
  3. package/dist/chat/admin/admin.css +78 -0
  4. package/dist/chat/admin/index.d.ts +92 -0
  5. package/dist/chat/admin/index.js +124 -0
  6. package/dist/chat/admin/react.d.ts +40 -0
  7. package/dist/chat/admin/react.js +169 -0
  8. package/dist/chat/chat.css +1003 -0
  9. package/dist/chat/client.d.ts +30 -0
  10. package/dist/chat/client.js +1300 -0
  11. package/dist/chat/exchange.d.ts +9 -0
  12. package/dist/chat/exchange.js +31 -0
  13. package/dist/chat/fake/index.d.ts +27 -0
  14. package/dist/chat/fake/index.js +48 -0
  15. package/dist/chat/fake/intercept.d.ts +21 -0
  16. package/dist/chat/fake/intercept.js +57 -0
  17. package/dist/chat/fake/sample.d.ts +4 -0
  18. package/dist/chat/fake/sample.js +6 -0
  19. package/dist/chat/fake/server.d.ts +168 -0
  20. package/dist/chat/fake/server.js +811 -0
  21. package/dist/chat/fake/xhr.d.ts +3 -0
  22. package/dist/chat/fake/xhr.js +104 -0
  23. package/dist/chat/index.d.ts +10 -0
  24. package/dist/chat/index.js +9 -0
  25. package/dist/chat/markdown.d.ts +29 -0
  26. package/dist/chat/markdown.js +161 -0
  27. package/dist/chat/react/Attachment.d.ts +39 -0
  28. package/dist/chat/react/Attachment.js +113 -0
  29. package/dist/chat/react/Chat.d.ts +48 -0
  30. package/dist/chat/react/Chat.js +139 -0
  31. package/dist/chat/react/Composer.d.ts +25 -0
  32. package/dist/chat/react/Composer.js +157 -0
  33. package/dist/chat/react/MessageRow.d.ts +21 -0
  34. package/dist/chat/react/MessageRow.js +114 -0
  35. package/dist/chat/react/NewDirectMessage.d.ts +23 -0
  36. package/dist/chat/react/NewDirectMessage.js +47 -0
  37. package/dist/chat/react/ThreadPanel.d.ts +25 -0
  38. package/dist/chat/react/ThreadPanel.js +17 -0
  39. package/dist/chat/react/Timeline.d.ts +27 -0
  40. package/dist/chat/react/Timeline.js +120 -0
  41. package/dist/chat/react/index.d.ts +7 -0
  42. package/dist/chat/react/index.js +6 -0
  43. package/dist/chat/react/mentions.d.ts +34 -0
  44. package/dist/chat/react/mentions.js +70 -0
  45. package/dist/chat/react/scroll.d.ts +26 -0
  46. package/dist/chat/react/scroll.js +27 -0
  47. package/dist/chat/react/timelineLayout.d.ts +26 -0
  48. package/dist/chat/react/timelineLayout.js +47 -0
  49. package/dist/chat/sanitize.d.ts +49 -0
  50. package/dist/chat/sanitize.js +264 -0
  51. package/dist/chat/store.d.ts +16 -0
  52. package/dist/chat/store.js +25 -0
  53. package/dist/chat/types.d.ts +340 -0
  54. package/dist/chat/types.js +1 -0
  55. package/package.json +88 -0
@@ -0,0 +1,120 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Empty, ScrollArea } from '@wtfalch/design';
3
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
4
+ import { MessageRow } from "./MessageRow.js";
5
+ import { isNearBottom, isNearTop, nextScrollTop } from "./scroll.js";
6
+ import { layoutTimeline } from "./timelineLayout.js";
7
+ /**
8
+ * A room's messages, oldest above newest: older history loads as the
9
+ * person scrolls up with the scroll position held on the message they were
10
+ * reading, and a message arriving while they are reading history never
11
+ * pulls them away from it -- only a person already at the bottom is
12
+ * carried down with it (chat plan section 9, ticket #15).
13
+ *
14
+ * Mounted with `key={roomId}` by `Chat.tsx`, so every ref and piece of
15
+ * local state here starts fresh on a room switch rather than needing to be
16
+ * reset by hand.
17
+ */
18
+ export function Timeline({ client, roomId, threadId, onOpenThread, highlightEventId, now, }) {
19
+ const [page, setPage] = useState(() => client.timeline(roomId, threadId));
20
+ // No unread rule inside a thread: `readUpToEventId` is the *room's* read
21
+ // marker, and drawing it against a thread's own events would put "New
22
+ // messages" in a place the person has never been told about. A thread
23
+ // follow inbox is explicitly not in this ticket.
24
+ const [readUpToId] = useState(() => (threadId ? null : client.readUpToEventId(roomId)));
25
+ const scrollRef = useRef(null);
26
+ const stickToBottom = useRef(true);
27
+ const pagination = useRef(null);
28
+ useEffect(() => client.onTimelineChanged(roomId, () => setPage(client.timeline(roomId, threadId))), [client, roomId, threadId]);
29
+ useLayoutEffect(() => {
30
+ const el = scrollRef.current;
31
+ if (!el || page.events.length === 0)
32
+ return;
33
+ const snapshot = pagination.current;
34
+ if (snapshot) {
35
+ el.scrollTop = nextScrollTop(snapshot, el.scrollHeight);
36
+ pagination.current = null;
37
+ }
38
+ else if (stickToBottom.current) {
39
+ el.scrollTop = el.scrollHeight;
40
+ }
41
+ }, [page]);
42
+ useEffect(() => {
43
+ const el = scrollRef.current;
44
+ if (!el)
45
+ return;
46
+ const onScroll = () => {
47
+ stickToBottom.current = isNearBottom(el);
48
+ if (pagination.current || !page.hasMore)
49
+ return;
50
+ if (!isNearTop(el.scrollTop))
51
+ return;
52
+ pagination.current = { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight };
53
+ client.paginate(roomId, threadId).catch(() => {
54
+ pagination.current = null;
55
+ });
56
+ };
57
+ el.addEventListener('scroll', onScroll);
58
+ return () => el.removeEventListener('scroll', onScroll);
59
+ }, [client, roomId, threadId, page.hasMore]);
60
+ /** Scrolling to the message the reader was sent to find. Only ever a
61
+ * message already in the loaded timeline, which is enough: a person
62
+ * reaches this by opening a thread off a message they can see, so the
63
+ * root is still loaded when they ask to go back to it. Nothing hunts
64
+ * through history for an event that is not there. */
65
+ useEffect(() => {
66
+ if (!highlightEventId)
67
+ return;
68
+ const el = scrollRef.current;
69
+ const target = el?.querySelector(`[data-event-id="${CSS.escape(highlightEventId)}"]`);
70
+ if (!target)
71
+ return;
72
+ stickToBottom.current = false;
73
+ target.scrollIntoView({ block: 'center' });
74
+ }, [highlightEventId]);
75
+ // Reading the visible end of a room sends its receipt. Merely mounting a
76
+ // background tab or a thread must not mark unseen room messages as read.
77
+ const lastRead = useRef(null);
78
+ useEffect(() => {
79
+ if (threadId)
80
+ return;
81
+ const newest = page.events.filter((event) => event.status === 'sent').at(-1)?.id;
82
+ if (!newest)
83
+ return;
84
+ const el = scrollRef.current;
85
+ const read = () => {
86
+ if (document.visibilityState !== 'visible' ||
87
+ !el ||
88
+ el.clientHeight === 0 ||
89
+ !isNearBottom(el))
90
+ return;
91
+ if (lastRead.current === newest)
92
+ return;
93
+ lastRead.current = newest;
94
+ client.markRoomRead(roomId).catch(() => {
95
+ if (lastRead.current === newest)
96
+ lastRead.current = null;
97
+ });
98
+ };
99
+ read();
100
+ el?.addEventListener('scroll', read);
101
+ document.addEventListener('visibilitychange', read);
102
+ return () => {
103
+ el?.removeEventListener('scroll', read);
104
+ document.removeEventListener('visibilitychange', read);
105
+ };
106
+ }, [client, roomId, threadId, page]);
107
+ const rows = useMemo(() => layoutTimeline(page.events, readUpToId, now ?? new Date()), [page.events, readUpToId, now]);
108
+ if (page.events.length === 0) {
109
+ return (_jsx(Empty, { icon: "chat", children: threadId ? 'Loading this thread.' : 'No messages yet. Say hello.' }));
110
+ }
111
+ return (_jsx(ScrollArea, { className: "chat-timeline", label: threadId ? 'Thread messages' : 'Messages', ref: scrollRef, children: rows.map((row) => {
112
+ if (row.kind === 'divider') {
113
+ return (_jsx("div", { className: "chat-divider", children: _jsx("span", { children: row.label }) }, row.key));
114
+ }
115
+ if (row.kind === 'unread') {
116
+ return (_jsx("div", { className: "chat-unread", children: _jsx("span", { children: "New messages" }) }, row.key));
117
+ }
118
+ return (_jsx(MessageRow, { event: row.event, client: client, roomId: roomId, onOpenThread: onOpenThread, highlighted: row.event.id === highlightEventId }, row.key));
119
+ }) }));
120
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `@wtfalch/chat/react` -- the `Chat` component: the person's
3
+ * channels and direct rooms, and a selected room's timeline and composer.
4
+ * See the chat plan, section 9, and ticket #15.
5
+ */
6
+ export { Chat } from './Chat.tsx';
7
+ export type { ChatLocation, ChatProps } from './Chat.tsx';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@wtfalch/chat/react` -- the `Chat` component: the person's
3
+ * channels and direct rooms, and a selected room's timeline and composer.
4
+ * See the chat plan, section 9, and ticket #15.
5
+ */
6
+ export { Chat } from "./Chat.js";
@@ -0,0 +1,34 @@
1
+ import type { ChatPerson } from '../types.ts';
2
+ /**
3
+ * The `@…` a person is part-way through typing, and what to do once they
4
+ * have picked somebody. Pure, so the rules live somewhere they can be read
5
+ * and tested rather than tangled in the composer's own state (ticket #18).
6
+ */
7
+ /** The partial mention under the caret: an `@` at the start of a word, and
8
+ * everything since. `null` when the caret is not in one -- which is most
9
+ * of the time, and is why this is checked on every keystroke rather than
10
+ * a menu being opened by hand.
11
+ *
12
+ * A mention never spans a space: `@ada lovelace` is a mention of `ada`
13
+ * followed by a word, because a homeserver's own localparts cannot hold a
14
+ * space either, and a query that grew past one would match everybody. */
15
+ export declare function mentionQuery(text: string, caret: number): {
16
+ query: string;
17
+ start: number;
18
+ } | null;
19
+ /** The people worth offering for `query`, by name, best first. Matching is
20
+ * on the name and on the user id alike: somebody who knows a colleague's
21
+ * handle should not have to remember what they called themselves. */
22
+ export declare function matchPeople(people: readonly ChatPerson[], query: string): ChatPerson[];
23
+ /** The text and caret after picking `person` for the mention starting at
24
+ * `start`. A trailing space, because the next thing typed is a word and
25
+ * not more of the name. */
26
+ export declare function applyMention(text: string, start: number, caret: number, person: ChatPerson): {
27
+ text: string;
28
+ caret: number;
29
+ };
30
+ /** Which of the people picked while writing are still named in what is
31
+ * about to be sent. Somebody who was picked and then deleted is not
32
+ * mentioned, and `m.mentions.user_ids` is what decides whose notification
33
+ * this is -- so it must say what the text says. */
34
+ export declare function mentionedUserIds(text: string, picked: readonly ChatPerson[]): string[];
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The `@…` a person is part-way through typing, and what to do once they
3
+ * have picked somebody. Pure, so the rules live somewhere they can be read
4
+ * and tested rather than tangled in the composer's own state (ticket #18).
5
+ */
6
+ /** The partial mention under the caret: an `@` at the start of a word, and
7
+ * everything since. `null` when the caret is not in one -- which is most
8
+ * of the time, and is why this is checked on every keystroke rather than
9
+ * a menu being opened by hand.
10
+ *
11
+ * A mention never spans a space: `@ada lovelace` is a mention of `ada`
12
+ * followed by a word, because a homeserver's own localparts cannot hold a
13
+ * space either, and a query that grew past one would match everybody. */
14
+ export function mentionQuery(text, caret) {
15
+ const before = text.slice(0, caret);
16
+ const at = before.lastIndexOf('@');
17
+ if (at === -1)
18
+ return null;
19
+ const query = before.slice(at + 1);
20
+ if (/\s/.test(query))
21
+ return null;
22
+ // An `@` inside a word (an email address, say) starts nothing.
23
+ const preceding = at === 0 ? '' : before[at - 1];
24
+ if (preceding !== '' && !/\s/.test(preceding))
25
+ return null;
26
+ return { query, start: at };
27
+ }
28
+ /** The people worth offering for `query`, by name, best first. Matching is
29
+ * on the name and on the user id alike: somebody who knows a colleague's
30
+ * handle should not have to remember what they called themselves. */
31
+ export function matchPeople(people, query) {
32
+ const needle = query.toLowerCase();
33
+ if (needle === '')
34
+ return [...people];
35
+ const starts = [];
36
+ const contains = [];
37
+ for (const person of people) {
38
+ const name = person.name.toLowerCase();
39
+ const id = person.userId.toLowerCase();
40
+ if (name.startsWith(needle) || id.startsWith(`@${needle}`))
41
+ starts.push(person);
42
+ else if (name.includes(needle) || id.includes(needle))
43
+ contains.push(person);
44
+ }
45
+ return [...starts, ...contains];
46
+ }
47
+ /** The text and caret after picking `person` for the mention starting at
48
+ * `start`. A trailing space, because the next thing typed is a word and
49
+ * not more of the name. */
50
+ export function applyMention(text, start, caret, person) {
51
+ const mention = `@${person.name} `;
52
+ return {
53
+ text: `${text.slice(0, start)}${mention}${text.slice(caret)}`,
54
+ caret: start + mention.length,
55
+ };
56
+ }
57
+ /** Which of the people picked while writing are still named in what is
58
+ * about to be sent. Somebody who was picked and then deleted is not
59
+ * mentioned, and `m.mentions.user_ids` is what decides whose notification
60
+ * this is -- so it must say what the text says. */
61
+ export function mentionedUserIds(text, picked) {
62
+ const ids = [];
63
+ for (const person of picked) {
64
+ if (!text.includes(`@${person.name}`))
65
+ continue;
66
+ if (!ids.includes(person.userId))
67
+ ids.push(person.userId);
68
+ }
69
+ return ids;
70
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The timeline's scroll anchoring, as pure arithmetic over the three
3
+ * numbers a scroll container already has -- kept apart from the DOM effect
4
+ * that calls it (`Timeline.tsx`) so the policy itself is unit-testable.
5
+ * jsdom lays nothing out (`scrollHeight`/`clientHeight` read `0` always),
6
+ * so a real browser is the only place these numbers mean anything; a test
7
+ * supplies its own to exercise the arithmetic instead.
8
+ */
9
+ export type ScrollMetrics = {
10
+ scrollTop: number;
11
+ scrollHeight: number;
12
+ clientHeight: number;
13
+ };
14
+ /** Whether the reader is close enough to the newest message that an
15
+ * arriving one should carry them down with it. Ticket #15's rule: a
16
+ * person *at* the bottom is followed; a person reading history is not. */
17
+ export declare function isNearBottom(metrics: ScrollMetrics, thresholdPx?: number): boolean;
18
+ /** Whether the reader is close enough to the oldest loaded message that
19
+ * scrolling further should fetch the page behind it. */
20
+ export declare function isNearTop(scrollTop: number, thresholdPx?: number): boolean;
21
+ /** The `scrollTop` that keeps the reader's eye on the same message after
22
+ * older history is prepended above it: the box grew by
23
+ * `afterScrollHeight - before.scrollHeight` pixels, all of it above the
24
+ * reader's current position, so the reader's position must grow by the
25
+ * same amount to hold still on screen. */
26
+ export declare function nextScrollTop(before: Pick<ScrollMetrics, 'scrollTop' | 'scrollHeight'>, afterScrollHeight: number): number;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The timeline's scroll anchoring, as pure arithmetic over the three
3
+ * numbers a scroll container already has -- kept apart from the DOM effect
4
+ * that calls it (`Timeline.tsx`) so the policy itself is unit-testable.
5
+ * jsdom lays nothing out (`scrollHeight`/`clientHeight` read `0` always),
6
+ * so a real browser is the only place these numbers mean anything; a test
7
+ * supplies its own to exercise the arithmetic instead.
8
+ */
9
+ /** Whether the reader is close enough to the newest message that an
10
+ * arriving one should carry them down with it. Ticket #15's rule: a
11
+ * person *at* the bottom is followed; a person reading history is not. */
12
+ export function isNearBottom(metrics, thresholdPx = 80) {
13
+ return metrics.scrollHeight - metrics.scrollTop - metrics.clientHeight <= thresholdPx;
14
+ }
15
+ /** Whether the reader is close enough to the oldest loaded message that
16
+ * scrolling further should fetch the page behind it. */
17
+ export function isNearTop(scrollTop, thresholdPx = 120) {
18
+ return scrollTop <= thresholdPx;
19
+ }
20
+ /** The `scrollTop` that keeps the reader's eye on the same message after
21
+ * older history is prepended above it: the box grew by
22
+ * `afterScrollHeight - before.scrollHeight` pixels, all of it above the
23
+ * reader's current position, so the reader's position must grow by the
24
+ * same amount to hold still on screen. */
25
+ export function nextScrollTop(before, afterScrollHeight) {
26
+ return before.scrollTop + (afterScrollHeight - before.scrollHeight);
27
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Turns a room's events into the rows `Timeline.tsx` draws: a date divider
3
+ * wherever the calendar day changes, and one unread separator at the read
4
+ * marker the room was opened with. Pure and Matrix-agnostic, so the
5
+ * grouping itself is unit-testable without mounting anything.
6
+ */
7
+ import type { ChatTimelineEvent } from '../types.ts';
8
+ export type TimelineRow = {
9
+ kind: 'divider';
10
+ key: string;
11
+ label: string;
12
+ } | {
13
+ kind: 'unread';
14
+ key: string;
15
+ } | {
16
+ kind: 'message';
17
+ key: string;
18
+ event: ChatTimelineEvent;
19
+ };
20
+ /**
21
+ * `events`, oldest first, as rows: a divider whenever the day changes, and
22
+ * -- once, where `readUpToId` last stood -- an unread separator. Nothing
23
+ * placed after the newest event: "unread" past the last message there is
24
+ * says nothing a reader needs told.
25
+ */
26
+ export declare function layoutTimeline(events: readonly ChatTimelineEvent[], readUpToId: string | null, now: Date): TimelineRow[];
@@ -0,0 +1,47 @@
1
+ function dayKey(ts) {
2
+ const d = new Date(ts);
3
+ return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
4
+ }
5
+ const DAY_MS = 24 * 60 * 60 * 1000;
6
+ function dayLabel(ts, now) {
7
+ const key = dayKey(ts);
8
+ if (key === dayKey(now.getTime()))
9
+ return 'Today';
10
+ if (key === dayKey(now.getTime() - DAY_MS))
11
+ return 'Yesterday';
12
+ const d = new Date(ts);
13
+ return d.toLocaleDateString(undefined, {
14
+ weekday: 'long',
15
+ month: 'long',
16
+ day: 'numeric',
17
+ year: d.getFullYear() === now.getFullYear() ? undefined : 'numeric',
18
+ });
19
+ }
20
+ /**
21
+ * `events`, oldest first, as rows: a divider whenever the day changes, and
22
+ * -- once, where `readUpToId` last stood -- an unread separator. Nothing
23
+ * placed after the newest event: "unread" past the last message there is
24
+ * says nothing a reader needs told.
25
+ */
26
+ export function layoutTimeline(events, readUpToId, now) {
27
+ const rows = [];
28
+ let lastDay = null;
29
+ let unreadPlaced = readUpToId === null;
30
+ for (let i = 0; i < events.length; i++) {
31
+ const event = events[i];
32
+ if (!event)
33
+ continue;
34
+ const day = dayKey(event.ts);
35
+ if (day !== lastDay) {
36
+ rows.push({ kind: 'divider', key: `divider-${day}`, label: dayLabel(event.ts, now) });
37
+ lastDay = day;
38
+ }
39
+ rows.push({ kind: 'message', key: event.id, event });
40
+ if (!unreadPlaced && event.id === readUpToId) {
41
+ if (i < events.length - 1)
42
+ rows.push({ kind: 'unread', key: 'unread' });
43
+ unreadPlaced = true;
44
+ }
45
+ }
46
+ return rows;
47
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A `formatted_body` from a stranger, made fit to set as a page's HTML
3
+ * (chat plan section 9, ticket #15).
4
+ *
5
+ * **The same technique `@wtfalch/email`'s `sanitise.ts` uses**: an allow-list
6
+ * walked over a document `DOMParser` built with no browsing context, so
7
+ * nothing in the markup loads or runs while it is being cleaned. Elements
8
+ * not on the list are unwrapped, so their text survives; attributes are
9
+ * kept by name, never removed by name, so one this has not heard of is gone
10
+ * rather than let through.
11
+ *
12
+ * **Narrower than mail's, and drawn straight into the page.** A message
13
+ * body is not a stranger's whole document -- there is no `<style>`, no
14
+ * `<meta>`, nothing that repoints the page -- so this keeps to the tags
15
+ * Matrix's own client-server spec recommends a client render, and drops
16
+ * everything else, its content included where the tag itself is the
17
+ * problem (`script`, `iframe`, `form` and the like).
18
+ *
19
+ * **A link's scheme is checked, not merely present.** `href` is parsed with
20
+ * `URL`, which resolves the escapes a pattern would miss, and only
21
+ * `http:`, `https:` and `mailto:` survive -- never `javascript:`, never
22
+ * `data:`.
23
+ *
24
+ * **An image is never a request to somewhere else.** `formatted_body`'s
25
+ * `img[src]` is only ever meaningful as a Matrix `mxc://` reference in the
26
+ * first place; this refuses anything that is not one, asks `allowMedia`
27
+ * whether the reference is one this session may load -- ordinarily the
28
+ * session's own `client.canLoadMedia`, which says no to any server but its
29
+ * own -- and then writes the reference back as `data-mxc`, never as a
30
+ * `src`. There is no `src` to write: Synapse serves media only to a
31
+ * request carrying the token, so the bytes are fetched by the renderer
32
+ * (`client.loadMedia`) and shown as an object URL (ticket #13).
33
+ *
34
+ * **Depth and size are capped.** A message nested or repeated past what a
35
+ * person would ever type by hand is truncated rather than walked in full --
36
+ * the "cannot lock the browser up" half of the safety requirement, since an
37
+ * allow-list alone says nothing about *how much* of the allowed shape a
38
+ * document may contain.
39
+ */
40
+ /** Whether this session may load an `mxc://` reference at all --
41
+ * `client.canLoadMedia`, kept a callback so this module never imports
42
+ * matrix-js-sdk and a test can fake it. */
43
+ export type AllowMedia = (mxcUri: string) => boolean;
44
+ export type SanitizeOptions = {
45
+ allowMedia: AllowMedia;
46
+ };
47
+ /** A `formatted_body`, cleaned to what may be drawn as HTML. Browser only:
48
+ * it needs `DOMParser`. */
49
+ export declare function sanitizeHtml(html: string, options: SanitizeOptions): string;