@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,139 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Button, Empty, Icon, ScrollArea, Skeleton } from '@wtfalch/design';
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ import { Composer } from "./Composer.js";
5
+ import { NewDirectMessage } from "./NewDirectMessage.js";
6
+ import { ThreadPanel } from "./ThreadPanel.js";
7
+ import { Timeline } from "./Timeline.js";
8
+ const HOME_LOCATION = { roomId: null, threadId: null, eventId: null };
9
+ /**
10
+ * The client's own lifecycle, started when this hook is first used and
11
+ * stopped when it lets go -- `start()` on mount, `stop()` on unmount or on a
12
+ * new `client`. `onRoomsChanged` is the client's own push, straight off
13
+ * matrix-js-sdk's sync, so nothing here polls.
14
+ */
15
+ function useChatRooms(client, onError) {
16
+ const [rooms, setRooms] = useState(() => client.rooms());
17
+ const [loading, setLoading] = useState(true);
18
+ const [error, setError] = useState(undefined);
19
+ const onErrorRef = useRef(onError);
20
+ onErrorRef.current = onError;
21
+ useEffect(() => {
22
+ let live = true;
23
+ setLoading(true);
24
+ setError(undefined);
25
+ setRooms(client.rooms());
26
+ const unsubscribe = client.onRoomsChanged((next) => {
27
+ if (live)
28
+ setRooms(next);
29
+ });
30
+ client.start().then(() => {
31
+ if (!live)
32
+ return;
33
+ setRooms(client.rooms());
34
+ setLoading(false);
35
+ }, (reason) => {
36
+ if (!live)
37
+ return;
38
+ const err = reason instanceof Error ? reason : new Error('The chat session did not start.');
39
+ setLoading(false);
40
+ setError(err);
41
+ onErrorRef.current?.(err);
42
+ });
43
+ return () => {
44
+ live = false;
45
+ unsubscribe();
46
+ client.stop();
47
+ };
48
+ }, [client]);
49
+ return { rooms, loading, error };
50
+ }
51
+ /**
52
+ * The agora's Chat section: the person's channels and direct rooms, one of
53
+ * them selected, its timeline and composer in the room pane (ticket #15).
54
+ *
55
+ * Plain on purpose -- see the campaign brief, MSG-010: no design pass runs
56
+ * against this ticket, and this is not `Mail`'s layout reused. Structure
57
+ * and honest states, on `@wtfalch/design`'s tokens; the design pass is a
58
+ * separate step once there is a shipped surface to design around.
59
+ */
60
+ export function Chat({ client, location, onNavigate, account, onError, now, sendOnEnter, className, }) {
61
+ const [own, setOwn] = useState(HOME_LOCATION);
62
+ // Local, not part of `ChatLocation`: picking who to message is a step on
63
+ // the way to a room, not a place the agora's URL needs to name, and adding
64
+ // a field to `ChatLocation` would make every host handle it.
65
+ const [composing, setComposing] = useState(false);
66
+ const controlled = location !== undefined;
67
+ const here = controlled ? location : own;
68
+ const roomId = here.roomId;
69
+ const navigate = useCallback((to) => {
70
+ if (controlled)
71
+ onNavigate?.(to);
72
+ else
73
+ setOwn(to);
74
+ }, [controlled, onNavigate]);
75
+ const selectRoom = useCallback((next) => {
76
+ setComposing(false);
77
+ navigate({ ...HOME_LOCATION, roomId: next });
78
+ }, [navigate]);
79
+ const openThread = useCallback((rootId) => navigate({ roomId, threadId: rootId, eventId: null }), [navigate, roomId]);
80
+ const hideRoom = useCallback((next) => {
81
+ // The open room is the one being hidden: leave the pane rather than
82
+ // keep drawing a room that is no longer in the list.
83
+ if (next === roomId)
84
+ navigate(HOME_LOCATION);
85
+ client.hideDirectMessage(next).catch((reason) => {
86
+ onError?.(reason instanceof Error ? reason : new Error('The room could not be hidden.'));
87
+ });
88
+ }, [client, navigate, onError, roomId]);
89
+ const { rooms, loading, error } = useChatRooms(client, onError);
90
+ const invitations = rooms.filter((room) => room.membership === 'invite');
91
+ const channels = rooms.filter((room) => room.membership !== 'invite' && !room.isDirect);
92
+ const directs = rooms.filter((room) => room.membership !== 'invite' && room.isDirect);
93
+ const selected = rooms.find((room) => room.id === roomId);
94
+ return (_jsxs("div", { className: `chat${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "chat-bar", children: [_jsx("span", { className: "chat-wordmark", children: "Chat" }), _jsx("div", { className: "chat-bar-end", children: account })] }), _jsxs("div", { className: "chat-panes", children: [_jsx(RoomList, { loading: loading, invitations: invitations, channels: channels, directs: directs, selectedId: roomId, onSelect: selectRoom, onHide: hideRoom, onCompose: () => setComposing(true) }), _jsx("div", { className: "chat-room", children: error ? (_jsxs(Empty, { icon: "error", children: ["Chat could not load. ", error.message] })) : composing ? (_jsx(NewDirectMessage, { client: client, onStarted: selectRoom, onCancel: () => setComposing(false) })) : loading ? (_jsx(Empty, { icon: "chat", children: "Loading your rooms." })) : selected?.membership === 'invite' ? (_jsx(Invitation, { room: selected, client: client }, selected.id)) : selected ? (
95
+ // `key`: a fresh `Timeline`/`Composer` per room, rather than one
96
+ // that has to notice `roomId` changed and reset its own scroll
97
+ // position, pagination state and draft text by hand.
98
+ _jsxs("div", { className: `chat-room-pane${here.threadId ? ' has-thread' : ''}`, children: [_jsxs("div", { className: "chat-room-main", children: [_jsx(Timeline, { client: client, roomId: selected.id, onOpenThread: openThread, highlightEventId: here.eventId, now: now }), _jsx(Composer, { client: client, roomId: selected.id, sendOnEnter: sendOnEnter })] }), here.threadId && (_jsx(ThreadPanel, { client: client, roomId: selected.id, threadId: here.threadId, onClose: () => navigate({ roomId: selected.id, threadId: null, eventId: null }), onGoToRoot: () => navigate({ roomId: selected.id, threadId: null, eventId: here.threadId }), now: now, sendOnEnter: sendOnEnter }))] }, selected.id)) : rooms.length === 0 ? (_jsx(Empty, { icon: "chat", children: "You are not in any rooms yet." })) : (_jsx(Empty, { icon: "chat", children: "Pick a room to read it." })) })] })] }));
99
+ }
100
+ function RoomList({ loading, invitations, channels, directs, selectedId, onSelect, onHide, onCompose, }) {
101
+ if (loading && channels.length === 0 && directs.length === 0) {
102
+ return (_jsx("nav", { className: "chat-rooms", "aria-label": "Rooms", "aria-busy": "true", children: _jsx("ul", { className: "chat-room-list", children: [0, 1, 2].map((n) => (_jsxs("li", { className: "chat-room-row is-skeleton", children: [_jsx(Skeleton, { variant: "rounded", width: "1.1rem", height: 4 }), _jsx(Skeleton, { width: `${50 + n * 10}%`, height: 2.5 })] }, n))) }) }));
103
+ }
104
+ // The direct-messages group is always drawn, even with nothing in it:
105
+ // starting one is an action, and an action that only appears once you
106
+ // already have what it makes is not reachable from an empty account.
107
+ return (_jsx(ScrollArea, { className: "chat-rooms", label: "Rooms", children: _jsxs("nav", { "aria-label": "Rooms", children: [invitations.length > 0 && (_jsx(RoomGroup, { title: "Invitations", rooms: invitations, selectedId: selectedId, onSelect: onSelect })), channels.length > 0 && (_jsx(RoomGroup, { title: "Channels", rooms: channels, selectedId: selectedId, onSelect: onSelect })), _jsx(RoomGroup, { title: "Direct messages", rooms: directs, selectedId: selectedId, onSelect: onSelect, onHide: onHide, action: _jsx(Button, { kind: "ghost", size: "sm", onPress: onCompose, children: "New" }), empty: "No direct messages yet." })] }) }));
108
+ }
109
+ function RoomGroup({ title, rooms, selectedId, onSelect, onHide, action, empty, }) {
110
+ return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "chat-rooms-heading", children: [_jsx("h3", { className: "chat-rooms-heading-title", children: title }), action] }), rooms.length === 0 ? (empty && _jsx("p", { className: "chat-rooms-empty", children: empty })) : (_jsx("ul", { className: "chat-room-list", children: rooms.map((room) => (_jsxs("li", { className: `chat-room-item${room.id === selectedId ? ' on' : ''}`, children: [_jsxs("button", { type: "button", className: "chat-room-row", onClick: () => onSelect(room.id), "aria-current": room.id === selectedId ? 'page' : undefined, children: [_jsx("span", { className: "chat-room-icon", "aria-hidden": "true", children: _jsx(Icon, { name: "chat", size: 16 }) }), _jsx("span", { className: "chat-room-name", children: room.name })] }), onHide && (
111
+ // A word, always drawn rather than revealed on hover: a
112
+ // control that only exists under a pointer does not exist on
113
+ // a touch screen, and the Named Station Rule wants the word
114
+ // anyway.
115
+ _jsx("button", { type: "button", className: "chat-room-hide", onClick: () => onHide(room.id), "aria-label": `Hide ${room.name}`, children: "Hide" }))] }, room.id))) }))] }));
116
+ }
117
+ function Invitation({ room, client }) {
118
+ const [busy, setBusy] = useState(false);
119
+ const [error, setError] = useState(null);
120
+ async function answer(accept) {
121
+ setBusy(true);
122
+ setError(null);
123
+ try {
124
+ if (accept)
125
+ await client.acceptInvitation(room.id);
126
+ else
127
+ await client.declineInvitation(room.id);
128
+ }
129
+ catch {
130
+ setError('Could not answer this invitation. Try again.');
131
+ }
132
+ finally {
133
+ setBusy(false);
134
+ }
135
+ }
136
+ return (_jsxs("section", { className: "chat-board", "aria-label": "Room invitation", children: [_jsx("h2", { className: "chat-board-title", children: room.name }), _jsxs("div", { className: "chat-board-body", children: [_jsx("p", { children: room.isDirect
137
+ ? 'You have been invited to a direct message.'
138
+ : 'You have been invited to this channel.' }), error && (_jsx("p", { role: "alert", className: "chat-board-error", children: error })), _jsxs("div", { className: "chat-board-actions", children: [_jsx(Button, { kind: "primary", disabled: busy, onPress: () => void answer(true), children: "Accept invitation" }), _jsx(Button, { kind: "ghost", disabled: busy, onPress: () => void answer(false), children: "Decline invitation" })] })] })] }));
139
+ }
@@ -0,0 +1,25 @@
1
+ import type { ChatClient } from '../types.ts';
2
+ export type ComposerProps = {
3
+ client: ChatClient;
4
+ roomId: string;
5
+ /** Given, what is written goes into that thread rather than into the
6
+ * room. */
7
+ threadId?: string | null;
8
+ /** Enter sends and Shift-Enter makes a line by default -- see the chat
9
+ * plan section 9's build note. While the mention list is open, Enter
10
+ * picks from it instead: it is the nearer of the two things Enter could
11
+ * mean, and Escape puts it away. */
12
+ sendOnEnter?: boolean;
13
+ };
14
+ /** Sends `m.room.message`, optimistically -- `client.sendMessage` already
15
+ * puts the pending event in the timeline before this even clears the box.
16
+ * Kept deliberately unaware of pending/failed state: that is
17
+ * `MessageRow`'s job, read back off `client.timeline`, not this
18
+ * component's to track twice.
19
+ *
20
+ * Mentions (ticket #18) are the one thing it does track, because they are
21
+ * not recoverable from the text: `m.mentions.user_ids` is what decides
22
+ * whose notification a message is, and two people can share a display
23
+ * name. So who was picked is remembered as they are picked, and only the
24
+ * ones still named in the text go out. */
25
+ export declare function Composer({ client, roomId, threadId, sendOnEnter }: ComposerProps): import("react").JSX.Element;
@@ -0,0 +1,157 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Button, Icon, Textarea } from '@wtfalch/design';
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ import { MAX_UPLOAD_BYTES } from "../client.js";
5
+ import { formatSize } from "./Attachment.js";
6
+ import { applyMention, matchPeople, mentionQuery, mentionedUserIds } from "./mentions.js";
7
+ /** Sends `m.room.message`, optimistically -- `client.sendMessage` already
8
+ * puts the pending event in the timeline before this even clears the box.
9
+ * Kept deliberately unaware of pending/failed state: that is
10
+ * `MessageRow`'s job, read back off `client.timeline`, not this
11
+ * component's to track twice.
12
+ *
13
+ * Mentions (ticket #18) are the one thing it does track, because they are
14
+ * not recoverable from the text: `m.mentions.user_ids` is what decides
15
+ * whose notification a message is, and two people can share a display
16
+ * name. So who was picked is remembered as they are picked, and only the
17
+ * ones still named in the text go out. */
18
+ export function Composer({ client, roomId, threadId, sendOnEnter = true }) {
19
+ const [value, setValue] = useState('');
20
+ const [refused, setRefused] = useState(null);
21
+ const fileRef = useRef(null);
22
+ const [picked, setPicked] = useState([]);
23
+ const [query, setQuery] = useState(null);
24
+ const [active, setActive] = useState(0);
25
+ const inputRef = useRef(null);
26
+ // Only ever people in *this* room: mentioning somebody who is not here
27
+ // would notify nobody, so offering them is a promise the message cannot
28
+ // keep. Refreshed on the same push the room list uses, so somebody who
29
+ // joins mid-conversation can be mentioned without a reload.
30
+ const [members, setMembers] = useState(() => client.roomMembers(roomId));
31
+ useEffect(() => client.onTimelineChanged(roomId, () => setMembers(client.roomMembers(roomId))), [client, roomId]);
32
+ const me = client.userId();
33
+ const candidates = query
34
+ ? matchPeople(members.filter((person) => person.userId !== me), query.query).slice(0, 6)
35
+ : [];
36
+ const open = candidates.length > 0;
37
+ const readQuery = useCallback((el) => {
38
+ const caret = el.selectionStart ?? el.value.length;
39
+ const found = mentionQuery(el.value, caret);
40
+ setQuery(found ? { ...found, caret } : null);
41
+ setActive(0);
42
+ }, []);
43
+ function choose(person) {
44
+ if (!query)
45
+ return;
46
+ const next = applyMention(value, query.start, query.caret, person);
47
+ setValue(next.text);
48
+ setPicked((current) => current.some((entry) => entry.userId === person.userId) ? current : [...current, person]);
49
+ setQuery(null);
50
+ const el = inputRef.current;
51
+ if (el) {
52
+ // The value React is about to write has not landed yet, so the caret
53
+ // is put back after it has -- otherwise the browser leaves it at the
54
+ // end of the new text rather than after the name.
55
+ queueMicrotask(() => {
56
+ el.focus();
57
+ el.setSelectionRange(next.caret, next.caret);
58
+ });
59
+ }
60
+ }
61
+ /** Everything that can arrive as a file -- picked, pasted or dropped --
62
+ * comes through here, so the size limit and the refusal message are
63
+ * written once. A file over the limit never starts: Synapse would
64
+ * refuse it, but only after the whole thing had gone up. */
65
+ function attach(files) {
66
+ const tooBig = files.find((file) => file.size > MAX_UPLOAD_BYTES);
67
+ if (tooBig) {
68
+ setRefused(`${tooBig.name} is too large. The limit is ${formatSize(MAX_UPLOAD_BYTES)}.`);
69
+ return;
70
+ }
71
+ setRefused(null);
72
+ for (const file of files)
73
+ client.sendFile(roomId, file, { threadId });
74
+ }
75
+ function send() {
76
+ const text = value.trim();
77
+ if (!text)
78
+ return;
79
+ client.sendMessage(roomId, text, { threadId, mentions: mentionedUserIds(text, picked) });
80
+ setValue('');
81
+ setPicked([]);
82
+ setQuery(null);
83
+ // Sending never takes focus away -- the person is still mid-conversation.
84
+ inputRef.current?.focus();
85
+ }
86
+ function onKeyDown(event) {
87
+ if (event.nativeEvent.isComposing)
88
+ return;
89
+ if (open) {
90
+ if (event.key === 'ArrowDown') {
91
+ event.preventDefault();
92
+ setActive((current) => (current + 1) % candidates.length);
93
+ return;
94
+ }
95
+ if (event.key === 'ArrowUp') {
96
+ event.preventDefault();
97
+ setActive((current) => (current - 1 + candidates.length) % candidates.length);
98
+ return;
99
+ }
100
+ if (event.key === 'Enter' || event.key === 'Tab') {
101
+ event.preventDefault();
102
+ const person = candidates[active];
103
+ if (person)
104
+ choose(person);
105
+ return;
106
+ }
107
+ if (event.key === 'Escape') {
108
+ event.preventDefault();
109
+ setQuery(null);
110
+ return;
111
+ }
112
+ }
113
+ if (event.key !== 'Enter')
114
+ return;
115
+ if (sendOnEnter && !event.shiftKey) {
116
+ event.preventDefault();
117
+ send();
118
+ }
119
+ }
120
+ return (_jsxs("form", { className: "chat-composer", onSubmit: (event) => {
121
+ event.preventDefault();
122
+ send();
123
+ }, onPaste: (event) => {
124
+ const files = Array.from(event.clipboardData.files);
125
+ if (files.length === 0)
126
+ return;
127
+ // Only when there are actually files on the clipboard: pasting
128
+ // text is the far commoner thing and must still just paste.
129
+ event.preventDefault();
130
+ attach(files);
131
+ }, onDragOver: (event) => event.preventDefault(), onDrop: (event) => {
132
+ const files = Array.from(event.dataTransfer.files);
133
+ if (files.length === 0)
134
+ return;
135
+ event.preventDefault();
136
+ attach(files);
137
+ }, children: [refused && (
138
+ // Named and bounded, the way a failed send is: the signal colour
139
+ // says which rule was broken, it never fills the row.
140
+ _jsx("p", { role: "alert", className: "chat-composer-refused", children: refused })), open && (
141
+ // A plain list of buttons, not a `listbox`: focus stays in the box
142
+ // so the person can keep typing, and a `listbox` nothing can focus
143
+ // is a promise to a screen reader that this cannot keep. The
144
+ // buttons are reachable on their own, and Up/Down/Enter work from
145
+ // the box.
146
+ _jsx("ul", { className: "chat-mentions", "aria-label": "People in this room", children: candidates.map((person, index) => (_jsx("li", { children: _jsxs("button", { type: "button", className: `chat-mention${index === active ? ' on' : ''}`,
147
+ // The list is driven from the box, which keeps focus, so a
148
+ // press must not take it away and close the list first.
149
+ onMouseDown: (event) => event.preventDefault(), onClick: () => choose(person), "aria-current": index === active ? 'true' : undefined, children: [_jsx("span", { className: "chat-mention-name", children: person.name }), _jsx("span", { className: "chat-mention-id", children: person.userId })] }) }, person.userId))) })), _jsx(Textarea, { ref: inputRef, className: "chat-composer-input", value: value, onChange: (event) => {
150
+ setValue(event.target.value);
151
+ readQuery(event.target);
152
+ }, onKeyUp: (event) => readQuery(event.currentTarget), onClick: (event) => readQuery(event.currentTarget), onBlur: () => setQuery(null), onKeyDown: onKeyDown, placeholder: threadId ? 'Reply in this thread' : 'Write a message', "aria-label": threadId ? 'Thread reply' : 'Message', rows: 1 }), _jsx("input", { ref: fileRef, className: "chat-composer-file", type: "file", hidden: true, multiple: true, "aria-label": "Attach a file", onChange: (event) => {
153
+ attach(Array.from(event.target.files ?? []));
154
+ // Cleared so picking the same file twice in a row still fires.
155
+ event.target.value = '';
156
+ } }), _jsxs(Button, { type: "button", kind: "ghost", onPress: () => fileRef.current?.click(), children: [_jsx(Icon, { name: "paperclip", size: 16 }), " Attach"] }), _jsx(Button, { type: "submit", kind: "primary", iconOnly: true, "aria-label": "Send", children: _jsx(Icon, { name: "send", size: 16 }) })] }));
157
+ }
@@ -0,0 +1,21 @@
1
+ import type { ChatClient, ChatTimelineEvent } from '../types.ts';
2
+ export type MessageRowProps = {
3
+ event: ChatTimelineEvent;
4
+ client: ChatClient;
5
+ roomId: string;
6
+ /** Given, the row offers a thread: the reply count and who is in it when
7
+ * there is one, an invitation to start one when there is not. Left out
8
+ * inside a thread's own panel, because Matrix threads are one level --
9
+ * there is nothing to offer (ticket #17). */
10
+ onOpenThread?: (rootId: string) => void;
11
+ /** The message the reader was sent here to find, marked so they can see
12
+ * which one it is. */
13
+ highlighted?: boolean;
14
+ };
15
+ /** One `m.room.message` event: sender, time, body, and -- pending or failed
16
+ * -- its own optimistic-send state. `formatted_body` is a stranger's HTML,
17
+ * so it is never drawn without `sanitizeHtml` first (chat plan section 9,
18
+ * ticket #15's safety requirement); plain `body` needs no such pass and is
19
+ * drawn as text, with `chat.css`'s `white-space: pre-wrap` carrying its
20
+ * own line breaks. */
21
+ export declare function MessageRow({ event, client, roomId, onOpenThread, highlighted }: MessageRowProps): import("react").JSX.Element;
@@ -0,0 +1,114 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Button, Textarea } from '@wtfalch/design';
3
+ import { useRef, useState } from 'react';
4
+ import { sanitizeHtml } from "../sanitize.js";
5
+ import { AttachmentView, useInlineMedia } from "./Attachment.js";
6
+ /** What the "React" button offers. A short, fixed row rather than a whole
7
+ * emoji picker: Matrix takes any string as a reaction key, so a picker is
8
+ * a thing this package could grow later without anything already sent
9
+ * having to change. */
10
+ const QUICK_REACTIONS = ['👍', '🎉', '👀', '❤️', '😄', '🤔'];
11
+ /** One `m.room.message` event: sender, time, body, and -- pending or failed
12
+ * -- its own optimistic-send state. `formatted_body` is a stranger's HTML,
13
+ * so it is never drawn without `sanitizeHtml` first (chat plan section 9,
14
+ * ticket #15's safety requirement); plain `body` needs no such pass and is
15
+ * drawn as text, with `chat.css`'s `white-space: pre-wrap` carrying its
16
+ * own line breaks. */
17
+ export function MessageRow({ event, client, roomId, onOpenThread, highlighted }) {
18
+ const time = new Date(event.ts).toLocaleTimeString(undefined, {
19
+ hour: 'numeric',
20
+ minute: '2-digit',
21
+ });
22
+ const html = event.formattedBody
23
+ ? sanitizeHtml(event.formattedBody, { allowMedia: client.canLoadMedia })
24
+ : null;
25
+ // The sanitiser leaves an allowed image with a reference and no `src`;
26
+ // this is what puts one there, with the bytes fetched under the token.
27
+ const body = useRef(null);
28
+ useInlineMedia(client, body, html);
29
+ const [picking, setPicking] = useState(false);
30
+ const [editing, setEditing] = useState(false);
31
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
32
+ /** Only your own, and only once it is really sent: Matrix ignores an
33
+ * `m.replace` from anybody else, and an event still in flight has no id
34
+ * on the server to replace or redact yet. */
35
+ const own = event.mine && event.status === 'sent' && !event.deleted;
36
+ function react(key) {
37
+ setPicking(false);
38
+ client.toggleReaction(roomId, event.id, key).catch(() => {
39
+ // The reaction simply does not appear. Matrix is the record, and the
40
+ // next sync says what is actually there -- a local "it failed" state
41
+ // would be this component's own guess about a count it does not own.
42
+ });
43
+ }
44
+ return (_jsxs("div", { className: `chat-message${event.status !== 'sent' ? ` is-${event.status}` : ''}${highlighted ? ' is-here' : ''}${event.mentionsMe ? ' is-mentioned' : ''}`, "data-event-id": event.id, "data-status": event.status, children: [_jsxs("div", { className: "chat-message-meta", children: [_jsx("span", { className: "chat-message-sender", children: event.senderName }), _jsx("time", { className: "chat-message-time", dateTime: new Date(event.ts).toISOString(), children: time }), event.edited && !event.deleted && _jsx("span", { className: "chat-message-edited", children: "edited" })] }), event.deleted ? (
45
+ // The row stays where it was. Dropping it would move every message
46
+ // under it while somebody is reading, and a thread hanging off this
47
+ // one still has to have something to hang from.
48
+ _jsx("div", { className: "chat-message-body is-deleted", children: "Message deleted" })) : editing ? (_jsx(EditBox, { initial: event.body, onCancel: () => setEditing(false), onSave: (text) => {
49
+ setEditing(false);
50
+ client.editMessage(roomId, event.id, text).catch(() => {
51
+ // Matrix is the record: the message simply stays as it was,
52
+ // and the next sync says what is actually there.
53
+ });
54
+ } })) : html !== null ? (_jsx("div", { ref: body, className: "chat-message-body",
55
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: `html` is `sanitizeHtml`'s own output.
56
+ dangerouslySetInnerHTML: { __html: html } })) : event.attachment ? (
57
+ // A file names itself in its own row, so the body would say the
58
+ // same thing twice.
59
+ _jsx(AttachmentView, { attachment: event.attachment, client: client, upload: event.upload })) : (_jsx("div", { className: "chat-message-body", children: event.body })), (event.reactions.length > 0 || (event.status === 'sent' && !event.deleted)) && (_jsxs("div", { className: "chat-reactions", children: [event.reactions.map((reaction) => (_jsx(ReactionPill, { reaction: reaction, onPress: react }, reaction.key))), event.status === 'sent' && !event.deleted && (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "chat-react", onClick: () => setPicking((open) => !open), "aria-expanded": picking, children: "React" }), picking && (_jsx("span", { className: "chat-react-choices", children: QUICK_REACTIONS.map((key) => (_jsx("button", { type: "button", className: "chat-react-choice", onClick: () => react(key), "aria-label": `React with ${key}`, children: key }, key))) }))] })), own && !editing && !confirmingDelete && (_jsxs(_Fragment, { children: [!event.attachment && (_jsx("button", { type: "button", className: "chat-react", onClick: () => setEditing(true), children: "Edit" })), _jsx("button", { type: "button", className: "chat-react", onClick: () => setConfirmingDelete(true), children: "Delete" })] })), own && confirmingDelete && (
60
+ // Asked in the row rather than in a dialog: a redaction cannot
61
+ // be taken back, and a browser dialog would take the whole
62
+ // conversation away to ask one question.
63
+ _jsxs("span", { className: "chat-confirm", children: [_jsx("span", { className: "chat-confirm-question", children: "Delete this message?" }), _jsx("button", { type: "button", className: "chat-confirm-yes", onClick: () => {
64
+ setConfirmingDelete(false);
65
+ client.deleteMessage(roomId, event.id).catch(() => {
66
+ // As above: the message stays, and sync says what is there.
67
+ });
68
+ }, children: "Delete" }), _jsx("button", { type: "button", className: "chat-react", onClick: () => setConfirmingDelete(false), children: "Keep" })] }))] })), onOpenThread &&
69
+ (event.thread ? (
70
+ // Always drawn: a thread hanging off a message is something the
71
+ // reader needs to know is there, not an action they have to go
72
+ // looking for. Named in words, with who is in it.
73
+ _jsxs("button", { type: "button", className: "chat-thread-link", onClick: () => onOpenThread(event.id), children: [_jsxs("span", { className: "chat-thread-count", children: [event.thread.replyCount, " ", event.thread.replyCount === 1 ? 'reply' : 'replies'] }), _jsx("span", { className: "chat-thread-people", children: event.thread.participants.join(', ') })] })) : (_jsx("button", { type: "button", className: "chat-message-reply", onClick: () => onOpenThread(event.id), children: "Reply in thread" }))), event.status === 'pending' && (_jsxs("p", { className: "chat-message-status", children: [event.upload ? 'Uploading…' : 'Sending…', event.upload && (_jsx(Button, { kind: "ghost", size: "sm", onPress: () => client.cancelMessage(roomId, event.id), children: "Cancel upload" }))] })), event.status === 'failed' && (_jsxs("p", { className: "chat-message-status is-failed", children: ["Not sent.", _jsx(Button, { kind: "ghost", size: "sm", onPress: () => client.retryMessage(roomId, event.id), children: "Retry" }), _jsx(Button, { kind: "ghost", size: "sm", onPress: () => client.cancelMessage(roomId, event.id), children: "Cancel" })] }))] }));
74
+ }
75
+ /** One key, its count, and who used it. The count is drawn beside the key
76
+ * rather than only in a tooltip: a bare mark with a hidden number is the
77
+ * sort of thing the Named Station Rule exists to stop. Who reacted is the
78
+ * button's own accessible name, so it is not lost to a pointer. */
79
+ function ReactionPill({ reaction, onPress, }) {
80
+ return (_jsxs("button", { type: "button", className: `chat-reaction${reaction.mine ? ' on' : ''}`, onClick: () => onPress(reaction.key), "aria-pressed": reaction.mine, "aria-label": `${reaction.key}, ${reaction.people.join(', ')}`, children: [_jsx("span", { className: "chat-reaction-key", "aria-hidden": "true", children: reaction.key }), _jsx("span", { className: "chat-reaction-count", children: reaction.count })] }));
81
+ }
82
+ /** Editing happens where the message is, not in a dialog: the sentence
83
+ * being changed stays in its own conversation, with what was said before
84
+ * and after it still on screen. Enter saves and Shift-Enter makes a line,
85
+ * matching the composer, and Escape leaves the message as it was. */
86
+ function EditBox({ initial, onSave, onCancel, }) {
87
+ const [value, setValue] = useState(initial);
88
+ function save() {
89
+ const text = value.trim();
90
+ // An edit to nothing is a delete, and a person who means that has
91
+ // Delete right there. An edit to the same words is no edit at all.
92
+ if (!text || text === initial) {
93
+ onCancel();
94
+ return;
95
+ }
96
+ onSave(text);
97
+ }
98
+ return (_jsxs("form", { className: "chat-edit", onSubmit: (event) => {
99
+ event.preventDefault();
100
+ save();
101
+ }, children: [_jsx(Textarea, { className: "chat-edit-input", value: value, onChange: (event) => setValue(event.target.value), onKeyDown: (event) => {
102
+ if (event.nativeEvent.isComposing)
103
+ return;
104
+ if (event.key === 'Escape') {
105
+ event.preventDefault();
106
+ onCancel();
107
+ return;
108
+ }
109
+ if (event.key === 'Enter' && !event.shiftKey) {
110
+ event.preventDefault();
111
+ save();
112
+ }
113
+ }, "aria-label": "Edit message", rows: 1, autoFocus: true }), _jsx(Button, { type: "submit", kind: "primary", size: "sm", children: "Save" }), _jsx(Button, { kind: "ghost", size: "sm", onPress: onCancel, children: "Cancel" })] }));
114
+ }
@@ -0,0 +1,23 @@
1
+ import type { ChatClient } from '../types.ts';
2
+ export type NewDirectMessageProps = {
3
+ client: ChatClient;
4
+ /** The room the person ended up in -- a new one, or the one they already
5
+ * had with these people, reopened. */
6
+ onStarted: (roomId: string) => void;
7
+ onCancel: () => void;
8
+ };
9
+ /**
10
+ * Starting a direct message: who it is with, and nothing else (ticket #16).
11
+ *
12
+ * A board in the room pane rather than a dialog over it, because that is
13
+ * what the agora does with every state that is not a place you read
14
+ * (`apps/agora/DESIGN.md`'s `Board`): an enamel card under an ink name-plate.
15
+ * Nothing floats, so the Flat Map Rule holds.
16
+ *
17
+ * Who is offered comes from `client.people()`, which is the company space's
18
+ * own membership. A guest is never in that space, so a guest can never be
19
+ * on this list -- the Synapse gate would refuse the invitation anyway
20
+ * (chat plan section 5), and an offer that ends in a refusal is not an
21
+ * offer.
22
+ */
23
+ export declare function NewDirectMessage({ client, onStarted, onCancel }: NewDirectMessageProps): import("react").JSX.Element;
@@ -0,0 +1,47 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Button, Checkbox, Empty } from '@wtfalch/design';
3
+ import { useCallback, useEffect, useState } from 'react';
4
+ /**
5
+ * Starting a direct message: who it is with, and nothing else (ticket #16).
6
+ *
7
+ * A board in the room pane rather than a dialog over it, because that is
8
+ * what the agora does with every state that is not a place you read
9
+ * (`apps/agora/DESIGN.md`'s `Board`): an enamel card under an ink name-plate.
10
+ * Nothing floats, so the Flat Map Rule holds.
11
+ *
12
+ * Who is offered comes from `client.people()`, which is the company space's
13
+ * own membership. A guest is never in that space, so a guest can never be
14
+ * on this list -- the Synapse gate would refuse the invitation anyway
15
+ * (chat plan section 5), and an offer that ends in a refusal is not an
16
+ * offer.
17
+ */
18
+ export function NewDirectMessage({ client, onStarted, onCancel }) {
19
+ const [people, setPeople] = useState(() => client.people());
20
+ const [picked, setPicked] = useState([]);
21
+ const [busy, setBusy] = useState(false);
22
+ const [error, setError] = useState(null);
23
+ // The space's membership arrives and changes on sync, the same push the
24
+ // room list already listens to -- so the list of people is live without
25
+ // this component polling or the client growing a second subscription.
26
+ useEffect(() => client.onRoomsChanged(() => setPeople(client.people())), [client]);
27
+ const toggle = useCallback((userId, on) => {
28
+ setPicked((current) => on ? [...current, userId] : current.filter((entry) => entry !== userId));
29
+ }, []);
30
+ async function start() {
31
+ if (picked.length === 0 || busy)
32
+ return;
33
+ setBusy(true);
34
+ setError(null);
35
+ try {
36
+ onStarted(await client.startDirectMessage(picked));
37
+ }
38
+ catch (reason) {
39
+ setBusy(false);
40
+ setError(reason instanceof Error ? reason.message : 'The direct message could not be started.');
41
+ }
42
+ }
43
+ return (_jsxs("form", { className: "chat-board", onSubmit: (event) => {
44
+ event.preventDefault();
45
+ void start();
46
+ }, children: [_jsx("h2", { className: "chat-board-title", children: "New message" }), _jsxs("div", { className: "chat-board-body", children: [people.length === 0 ? (_jsx(Empty, { icon: "chat", children: "There is nobody else in this company's chat yet." })) : (_jsx("ul", { className: "chat-people", children: people.map((person) => (_jsx("li", { children: _jsx(Checkbox, { label: person.name, meta: person.userId, checked: picked.includes(person.userId), onChange: (on) => toggle(person.userId, on), disabled: busy }) }, person.userId))) })), error && (_jsx("p", { className: "chat-board-error", role: "alert", children: error })), _jsxs("div", { className: "chat-board-actions", children: [_jsx(Button, { type: "submit", kind: "primary", disabled: picked.length === 0, busy: busy, children: picked.length > 1 ? 'Start group message' : 'Start message' }), _jsx(Button, { kind: "ghost", onPress: onCancel, children: "Cancel" })] })] })] }));
47
+ }
@@ -0,0 +1,25 @@
1
+ import type { ChatClient } from '../types.ts';
2
+ export type ThreadPanelProps = {
3
+ client: ChatClient;
4
+ roomId: string;
5
+ /** The message that started the thread. Matrix threads are one level, so
6
+ * this is the only id a thread ever has. */
7
+ threadId: string;
8
+ onClose: () => void;
9
+ /** Leaves the thread and points the room's timeline at the message that
10
+ * started it. */
11
+ onGoToRoot: () => void;
12
+ now?: Date;
13
+ sendOnEnter?: boolean;
14
+ };
15
+ /**
16
+ * A thread: the message that started it, its replies, and a box to add one
17
+ * (ticket #17).
18
+ *
19
+ * Beside the room when there is room for it, and the whole pane when there
20
+ * is not -- `chat.css` decides, so both are the same component and the same
21
+ * mounted state. "Back" is the same control in either: at a narrow width it
22
+ * is the way off a screen, and at a wide one it is the way to close the
23
+ * panel. One word, one action, no second control that does the same thing.
24
+ */
25
+ export declare function ThreadPanel({ client, roomId, threadId, onClose, onGoToRoot, now, sendOnEnter, }: ThreadPanelProps): import("react").JSX.Element;
@@ -0,0 +1,17 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Button, Icon } from '@wtfalch/design';
3
+ import { Composer } from "./Composer.js";
4
+ import { Timeline } from "./Timeline.js";
5
+ /**
6
+ * A thread: the message that started it, its replies, and a box to add one
7
+ * (ticket #17).
8
+ *
9
+ * Beside the room when there is room for it, and the whole pane when there
10
+ * is not -- `chat.css` decides, so both are the same component and the same
11
+ * mounted state. "Back" is the same control in either: at a narrow width it
12
+ * is the way off a screen, and at a wide one it is the way to close the
13
+ * panel. One word, one action, no second control that does the same thing.
14
+ */
15
+ export function ThreadPanel({ client, roomId, threadId, onClose, onGoToRoot, now, sendOnEnter, }) {
16
+ return (_jsxs("aside", { className: "chat-thread", "aria-label": "Thread", children: [_jsxs("header", { className: "chat-thread-bar", children: [_jsxs(Button, { kind: "ghost", size: "sm", onPress: onClose, children: [_jsx(Icon, { name: "back", size: 16 }), "Back"] }), _jsx("span", { className: "chat-thread-heading", children: "Thread" }), _jsx(Button, { kind: "ghost", size: "sm", onPress: onGoToRoot, children: "Go to message" })] }), _jsx(Timeline, { client: client, roomId: roomId, threadId: threadId, now: now }, threadId), _jsx(Composer, { client: client, roomId: roomId, threadId: threadId, sendOnEnter: sendOnEnter }, `composer-${threadId}`)] }));
17
+ }
@@ -0,0 +1,27 @@
1
+ import type { ChatClient } from '../types.ts';
2
+ export type TimelineProps = {
3
+ client: ChatClient;
4
+ roomId: string;
5
+ /** Given, this draws that thread instead of the room: its root message
6
+ * first, then the replies (ticket #17). */
7
+ threadId?: string | null;
8
+ /** Given, the row offers a thread on each message. Left out inside a
9
+ * thread, where there is nothing to offer. */
10
+ onOpenThread?: (rootId: string) => void;
11
+ /** A message the reader was sent here to find. It is scrolled to and
12
+ * marked, in place of the usual stick-to-the-bottom. */
13
+ highlightEventId?: string | null;
14
+ now?: Date;
15
+ };
16
+ /**
17
+ * A room's messages, oldest above newest: older history loads as the
18
+ * person scrolls up with the scroll position held on the message they were
19
+ * reading, and a message arriving while they are reading history never
20
+ * pulls them away from it -- only a person already at the bottom is
21
+ * carried down with it (chat plan section 9, ticket #15).
22
+ *
23
+ * Mounted with `key={roomId}` by `Chat.tsx`, so every ref and piece of
24
+ * local state here starts fresh on a room switch rather than needing to be
25
+ * reset by hand.
26
+ */
27
+ export declare function Timeline({ client, roomId, threadId, onOpenThread, highlightEventId, now, }: TimelineProps): import("react").JSX.Element;