@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,3 @@
1
+ /** Route browser uploads through the same fake transport as sync. Other
2
+ * origins keep the native XHR, including its real upload progress. */
3
+ export declare function installFakeUploads(): void;
@@ -0,0 +1,104 @@
1
+ /** Route browser uploads through the same fake transport as sync. Other
2
+ * origins keep the native XHR, including its real upload progress. */
3
+ export function installFakeUploads() {
4
+ const Native = globalThis.XMLHttpRequest;
5
+ if (!Native || installed.has(Native))
6
+ return;
7
+ class FakeUpload extends Native {
8
+ fakeUrl = null;
9
+ headers = new Headers();
10
+ controller = new AbortController();
11
+ code = 0;
12
+ state = 0;
13
+ text = '';
14
+ responseHeaders = new Headers();
15
+ open(method, url, async = true) {
16
+ const parsed = new URL(url, globalThis.location?.href);
17
+ if (parsed.hostname.endsWith('.example.test') &&
18
+ parsed.pathname === '/_matrix/media/v3/upload') {
19
+ this.fakeUrl = parsed.href;
20
+ this.state = 1;
21
+ }
22
+ else {
23
+ super.open(method, url, async);
24
+ }
25
+ }
26
+ get readyState() {
27
+ return this.fakeUrl ? this.state : super.readyState;
28
+ }
29
+ get status() {
30
+ return this.fakeUrl ? this.code : super.status;
31
+ }
32
+ get statusText() {
33
+ return this.fakeUrl ? '' : super.statusText;
34
+ }
35
+ get responseText() {
36
+ return this.fakeUrl ? this.text : super.responseText;
37
+ }
38
+ getResponseHeader(name) {
39
+ return this.fakeUrl ? this.responseHeaders.get(name) : super.getResponseHeader(name);
40
+ }
41
+ setRequestHeader(name, value) {
42
+ if (this.fakeUrl)
43
+ this.headers.set(name, value);
44
+ else
45
+ super.setRequestHeader(name, value);
46
+ }
47
+ abort() {
48
+ if (!this.fakeUrl) {
49
+ super.abort();
50
+ return;
51
+ }
52
+ this.controller.abort();
53
+ this.code = 0;
54
+ this.state = 4;
55
+ this.dispatchEvent(new Event('readystatechange'));
56
+ }
57
+ send(body) {
58
+ if (!this.fakeUrl) {
59
+ super.send(body);
60
+ return;
61
+ }
62
+ const url = this.fakeUrl;
63
+ const signal = this.controller.signal;
64
+ void (async () => {
65
+ // FileReader also handles jsdom's Blob, which has no arrayBuffer().
66
+ const bytes = body instanceof Blob ? await readBlob(body) : body;
67
+ if (signal.aborted)
68
+ return;
69
+ const size = body instanceof Blob ? body.size : 0;
70
+ this.upload.dispatchEvent(new ProgressEvent('progress', { loaded: size, total: size, lengthComputable: true }));
71
+ const response = await fetch(url, {
72
+ method: 'POST',
73
+ headers: this.headers,
74
+ body: bytes,
75
+ signal,
76
+ });
77
+ const text = await response.text();
78
+ if (signal.aborted)
79
+ return;
80
+ this.text = text;
81
+ this.code = response.status;
82
+ this.responseHeaders = response.headers;
83
+ this.state = 4;
84
+ this.dispatchEvent(new Event('readystatechange'));
85
+ })().catch(() => {
86
+ if (!signal.aborted)
87
+ this.abort();
88
+ });
89
+ }
90
+ }
91
+ installed.add(FakeUpload);
92
+ globalThis.XMLHttpRequest = FakeUpload;
93
+ }
94
+ const installed = new WeakSet();
95
+ function readBlob(blob) {
96
+ if (blob.arrayBuffer)
97
+ return blob.arrayBuffer();
98
+ return new Promise((resolve, reject) => {
99
+ const reader = new FileReader();
100
+ reader.onload = () => resolve(reader.result);
101
+ reader.onerror = () => reject(reader.error);
102
+ reader.readAsArrayBuffer(blob);
103
+ });
104
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `@wtfalch/chat` -- a Matrix chat client behind the agora's token
3
+ * exchange.
4
+ *
5
+ * `createChatClient` is the only thing here that touches matrix-js-sdk;
6
+ * everything it returns is this package's own small, typed surface. See
7
+ * `README.md` and the chat plan, section 9.
8
+ */
9
+ export { createChatClient, MAX_UPLOAD_BYTES } from './client.ts';
10
+ export type { ChatAttachment, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomSummary, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@wtfalch/chat` -- a Matrix chat client behind the agora's token
3
+ * exchange.
4
+ *
5
+ * `createChatClient` is the only thing here that touches matrix-js-sdk;
6
+ * everything it returns is this package's own small, typed surface. See
7
+ * `README.md` and the chat plan, section 9.
8
+ */
9
+ export { createChatClient, MAX_UPLOAD_BYTES } from "./client.js";
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The composer's Markdown shortcuts, turned into HTML for `formatted_body`
3
+ * (chat plan section 9, ticket #15). Bold, italic, inline code, inline
4
+ * links, lists, block quotes and fenced code blocks -- the set the ticket
5
+ * asks for, nothing wider.
6
+ *
7
+ * **Matrix-agnostic on purpose.** `msgtype`, `format` and `body` are a
8
+ * Matrix event's concern, not this module's -- `client.ts` is the only file
9
+ * in this package that touches matrix-js-sdk (see `index.ts`'s module
10
+ * comment), and it shapes this output into a `RoomMessageEventContent` with
11
+ * `ContentHelpers.makeHtmlMessage`/`makeTextMessage`.
12
+ *
13
+ * **Safe by construction, not by a second pass.** Every character of the
14
+ * typed text is HTML-escaped before any shortcut is applied, so a message
15
+ * that reads `<script>` or `onerror=` as plain text can never become a tag
16
+ * or an attribute here -- there is no HTML in the input for a shortcut to
17
+ * misread. A link's `href` is parsed and scheme-checked (`http:`, `https:`,
18
+ * `mailto:` only) before it is ever written into an attribute; anything
19
+ * else -- `javascript:`, `data:`, a bare word -- leaves the `[text](url)`
20
+ * as escaped literal text instead. Nothing here reaches `sanitize.ts`,
21
+ * which cleans a *stranger's* `formatted_body`; this one has no stranger in
22
+ * it to clean up after.
23
+ */
24
+ /** `text`, as a plain body and -- only when a shortcut was actually used --
25
+ * the HTML `formatted_body` to send alongside it. */
26
+ export declare function toFormattedBody(text: string): {
27
+ body: string;
28
+ html: string | null;
29
+ };
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The composer's Markdown shortcuts, turned into HTML for `formatted_body`
3
+ * (chat plan section 9, ticket #15). Bold, italic, inline code, inline
4
+ * links, lists, block quotes and fenced code blocks -- the set the ticket
5
+ * asks for, nothing wider.
6
+ *
7
+ * **Matrix-agnostic on purpose.** `msgtype`, `format` and `body` are a
8
+ * Matrix event's concern, not this module's -- `client.ts` is the only file
9
+ * in this package that touches matrix-js-sdk (see `index.ts`'s module
10
+ * comment), and it shapes this output into a `RoomMessageEventContent` with
11
+ * `ContentHelpers.makeHtmlMessage`/`makeTextMessage`.
12
+ *
13
+ * **Safe by construction, not by a second pass.** Every character of the
14
+ * typed text is HTML-escaped before any shortcut is applied, so a message
15
+ * that reads `<script>` or `onerror=` as plain text can never become a tag
16
+ * or an attribute here -- there is no HTML in the input for a shortcut to
17
+ * misread. A link's `href` is parsed and scheme-checked (`http:`, `https:`,
18
+ * `mailto:` only) before it is ever written into an attribute; anything
19
+ * else -- `javascript:`, `data:`, a bare word -- leaves the `[text](url)`
20
+ * as escaped literal text instead. Nothing here reaches `sanitize.ts`,
21
+ * which cleans a *stranger's* `formatted_body`; this one has no stranger in
22
+ * it to clean up after.
23
+ */
24
+ /** Characters that must never reach the DOM unescaped. Order matters: `&`
25
+ * first, or every entity this inserts would itself be re-escaped. */
26
+ function escapeHtml(text) {
27
+ return text
28
+ .replace(/&/g, '&amp;')
29
+ .replace(/</g, '&lt;')
30
+ .replace(/>/g, '&gt;')
31
+ .replace(/"/g, '&quot;')
32
+ .replace(/'/g, '&#39;');
33
+ }
34
+ /** `http:`/`https:`/`mailto:` only -- never `javascript:`, never `data:`,
35
+ * never a scheme this has not heard of. `URL` is the parser, not a
36
+ * pattern: it is what decides a scheme, not a regular expression a typo
37
+ * could slip past. */
38
+ function safeLinkHref(raw) {
39
+ let url;
40
+ try {
41
+ url = new URL(raw);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ return url.protocol === 'https:' || url.protocol === 'http:' || url.protocol === 'mailto:'
47
+ ? url.href
48
+ : null;
49
+ }
50
+ /** Two Private Use Area code points bracket a placeholder's index: never
51
+ * typed by hand, never produced by `escapeHtml`, and -- unlike a plain
52
+ * space or digits alone -- never collide with ordinary text a person
53
+ * wrote. A code span or a link already turned into HTML is held behind
54
+ * one of these so a later bold/italic pass cannot re-read it as more
55
+ * Markdown. */
56
+ const MARK_START = String.fromCodePoint(0xe000);
57
+ const MARK_END = String.fromCodePoint(0xe001);
58
+ const PLACEHOLDER_RE = new RegExp(`${MARK_START}(\\d+)${MARK_END}`, 'g');
59
+ /** One line's worth of inline Markdown: code spans and links first (each
60
+ * protected behind a placeholder the moment it is found, before anything
61
+ * is escaped), then the rest of the line escaped, then bold and italic
62
+ * applied to what is left. */
63
+ function inline(raw) {
64
+ const restore = [];
65
+ const hold = (html) => {
66
+ restore.push(html);
67
+ return `${MARK_START}${restore.length - 1}${MARK_END}`;
68
+ };
69
+ let working = raw.replace(/`([^`]+)`/g, (_, code) => hold(`<code>${escapeHtml(code)}</code>`));
70
+ working = working.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (whole, label, href) => {
71
+ const safeHref = safeLinkHref(href);
72
+ return safeHref
73
+ ? hold(`<a href="${escapeHtml(safeHref)}">${escapeHtml(label)}</a>`)
74
+ : escapeHtml(whole);
75
+ });
76
+ let html = escapeHtml(working);
77
+ html = html.replace(/\*\*([^*]+)\*\*|__([^_]+)__/g, (_, a, b) => `<strong>${a ?? b}</strong>`);
78
+ html = html.replace(/\*([^*]+)\*|_([^_]+)_/g, (_, a, b) => `<em>${a ?? b}</em>`);
79
+ return html.replace(PLACEHOLDER_RE, (_, index) => restore[Number(index)] ?? '');
80
+ }
81
+ const FENCE = /^```/;
82
+ const QUOTE = /^>\s?/;
83
+ const BULLET = /^[-*]\s+/;
84
+ const ORDERED = /^\d+\.\s+/;
85
+ /** The block grammar: a line at a time, each kind consuming every line of
86
+ * its own kind that follows it before the next block starts. */
87
+ function toHtml(text) {
88
+ const lines = text.split(/\r\n|\r|\n/);
89
+ const out = [];
90
+ let i = 0;
91
+ while (i < lines.length) {
92
+ const line = lines[i] ?? '';
93
+ if (line.trim() === '') {
94
+ i += 1;
95
+ continue;
96
+ }
97
+ if (FENCE.test(line)) {
98
+ const lang = line.replace(FENCE, '').trim();
99
+ const body = [];
100
+ i += 1;
101
+ while (i < lines.length && !FENCE.test(lines[i] ?? '')) {
102
+ body.push(lines[i] ?? '');
103
+ i += 1;
104
+ }
105
+ i += 1; // the closing fence, if there was one
106
+ const cls = lang && /^[\w.+-]+$/.test(lang) ? ` class="language-${escapeHtml(lang)}"` : '';
107
+ out.push(`<pre><code${cls}>${escapeHtml(body.join('\n'))}</code></pre>`);
108
+ continue;
109
+ }
110
+ if (QUOTE.test(line)) {
111
+ const body = [];
112
+ while (i < lines.length && QUOTE.test(lines[i] ?? '')) {
113
+ body.push((lines[i] ?? '').replace(QUOTE, ''));
114
+ i += 1;
115
+ }
116
+ out.push(`<blockquote><p>${body.map(inline).join('<br />')}</p></blockquote>`);
117
+ continue;
118
+ }
119
+ if (BULLET.test(line)) {
120
+ const items = [];
121
+ while (i < lines.length && BULLET.test(lines[i] ?? '')) {
122
+ items.push((lines[i] ?? '').replace(BULLET, ''));
123
+ i += 1;
124
+ }
125
+ out.push(`<ul>${items.map((item) => `<li>${inline(item)}</li>`).join('')}</ul>`);
126
+ continue;
127
+ }
128
+ if (ORDERED.test(line)) {
129
+ const items = [];
130
+ while (i < lines.length && ORDERED.test(lines[i] ?? '')) {
131
+ items.push((lines[i] ?? '').replace(ORDERED, ''));
132
+ i += 1;
133
+ }
134
+ out.push(`<ol>${items.map((item) => `<li>${inline(item)}</li>`).join('')}</ol>`);
135
+ continue;
136
+ }
137
+ const body = [];
138
+ while (i < lines.length &&
139
+ (lines[i] ?? '').trim() !== '' &&
140
+ !FENCE.test(lines[i] ?? '') &&
141
+ !QUOTE.test(lines[i] ?? '') &&
142
+ !BULLET.test(lines[i] ?? '') &&
143
+ !ORDERED.test(lines[i] ?? '')) {
144
+ body.push(lines[i] ?? '');
145
+ i += 1;
146
+ }
147
+ out.push(`<p>${body.map(inline).join('<br />')}</p>`);
148
+ }
149
+ return out.join('');
150
+ }
151
+ /** Whether `text` uses any shortcut this converts -- cheap enough to run
152
+ * before committing to a render, so a plain "hello" never grows a
153
+ * `formatted_body` that says nothing `body` did not already. */
154
+ const HAS_SHORTCUT = /`|\*\*|__|\*[^*\s]|_[^_\s]|\[[^\]]+\]\([^)\s]+\)|^```|^>\s|^[-*]\s|^\d+\.\s/m;
155
+ /** `text`, as a plain body and -- only when a shortcut was actually used --
156
+ * the HTML `formatted_body` to send alongside it. */
157
+ export function toFormattedBody(text) {
158
+ if (!HAS_SHORTCUT.test(text))
159
+ return { body: text, html: null };
160
+ return { body: text, html: toHtml(text) };
161
+ }
@@ -0,0 +1,39 @@
1
+ import type { ChatAttachment, ChatClient, ChatUploadProgress } from '../types.ts';
2
+ /** Bytes as a person reads them. Whole units above a kilobyte: a file's
3
+ * exact byte count is never what somebody wants to know. */
4
+ export declare function formatSize(bytes: number): string;
5
+ /** Fetches `mxcUri` with the session's token and hands back an object URL
6
+ * for as long as the component is mounted, revoking it on the way out.
7
+ *
8
+ * Synapse serves media only to a request carrying the token, so there is
9
+ * no URL to put in an `<img src>` -- the bytes have to come through the
10
+ * client. `null` while it is still coming, and `null` for good if it
11
+ * cannot be had. */
12
+ export declare function useMediaUrl(client: ChatClient, mxcUri: string | null): {
13
+ url: string | null;
14
+ failed: boolean;
15
+ retry: () => void;
16
+ };
17
+ export type AttachmentViewProps = {
18
+ attachment: ChatAttachment;
19
+ client: ChatClient;
20
+ /** Set while the file is still going up, in which case there is nothing
21
+ * on the server to fetch and this draws the count instead. */
22
+ upload: ChatUploadProgress | null;
23
+ };
24
+ /** A file on a message: a picture where this package can show one, and a
25
+ * named, sized row to download where it cannot.
26
+ *
27
+ * The name is always drawn, picture or not. A photograph that fails to
28
+ * load, or that a reader cannot see, still has to say what it is -- the
29
+ * agora's Named Station Rule, which is why there is no bare thumbnail
30
+ * anywhere in here. */
31
+ export declare function AttachmentView({ attachment, client, upload }: AttachmentViewProps): import("react").JSX.Element;
32
+ /** Fills in the `src` of every `img[data-mxc]` the sanitiser left in a
33
+ * message's HTML, and revokes what it made when the message goes.
34
+ *
35
+ * The sanitiser deliberately leaves those images with no `src`, so
36
+ * nothing is requested until this runs and nothing is ever requested
37
+ * without the token. An image whose bytes cannot be had simply stays
38
+ * blank beside its own `alt`. */
39
+ export declare function useInlineMedia(client: ChatClient, host: React.RefObject<HTMLElement | null>, html: string | null): void;
@@ -0,0 +1,113 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Button } from '@wtfalch/design';
3
+ import { useEffect, useState } from 'react';
4
+ /** Bytes as a person reads them. Whole units above a kilobyte: a file's
5
+ * exact byte count is never what somebody wants to know. */
6
+ export function formatSize(bytes) {
7
+ if (bytes < 1024)
8
+ return `${bytes} B`;
9
+ const units = ['kB', 'MB', 'GB'];
10
+ let value = bytes / 1024;
11
+ let unit = 0;
12
+ while (value >= 1024 && unit < units.length - 1) {
13
+ value /= 1024;
14
+ unit += 1;
15
+ }
16
+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
17
+ }
18
+ /** Fetches `mxcUri` with the session's token and hands back an object URL
19
+ * for as long as the component is mounted, revoking it on the way out.
20
+ *
21
+ * Synapse serves media only to a request carrying the token, so there is
22
+ * no URL to put in an `<img src>` -- the bytes have to come through the
23
+ * client. `null` while it is still coming, and `null` for good if it
24
+ * cannot be had. */
25
+ export function useMediaUrl(client, mxcUri) {
26
+ const [attempt, setAttempt] = useState(0);
27
+ const [result, setResult] = useState(null);
28
+ useEffect(() => {
29
+ setResult(null);
30
+ if (!mxcUri)
31
+ return;
32
+ let current = null;
33
+ let cancelled = false;
34
+ void client
35
+ .loadMedia(mxcUri)
36
+ .catch(() => null)
37
+ .then((url) => {
38
+ if (cancelled) {
39
+ if (url)
40
+ URL.revokeObjectURL(url);
41
+ return;
42
+ }
43
+ current = url;
44
+ setResult({ client, mxcUri, url, attempt });
45
+ });
46
+ return () => {
47
+ cancelled = true;
48
+ if (current)
49
+ URL.revokeObjectURL(current);
50
+ };
51
+ }, [client, mxcUri, attempt]);
52
+ const current = result?.client === client && result.mxcUri === mxcUri && result.attempt === attempt
53
+ ? result
54
+ : null;
55
+ return {
56
+ url: current?.url ?? null,
57
+ failed: current !== null && current.url === null,
58
+ retry: () => setAttempt((value) => value + 1),
59
+ };
60
+ }
61
+ /** A file on a message: a picture where this package can show one, and a
62
+ * named, sized row to download where it cannot.
63
+ *
64
+ * The name is always drawn, picture or not. A photograph that fails to
65
+ * load, or that a reader cannot see, still has to say what it is -- the
66
+ * agora's Named Station Rule, which is why there is no bare thumbnail
67
+ * anywhere in here. */
68
+ export function AttachmentView({ attachment, client, upload }) {
69
+ const { url, failed, retry } = useMediaUrl(client, upload ? null : attachment.mxcUri);
70
+ return (_jsxs("div", { className: "chat-file", children: [attachment.isImage && url && (_jsx("img", { className: "chat-file-image", src: url, alt: attachment.name })), _jsxs("div", { className: "chat-file-row", children: [_jsx("span", { className: "chat-file-name", children: attachment.name }), _jsx("span", { className: "chat-file-size", children: formatSize(attachment.size) }), url && (_jsx("a", { className: "chat-file-get", href: url, download: attachment.name, children: "Download" }))] }), failed && (_jsxs("p", { className: "chat-message-status", children: ["Could not load this file.", ' ', _jsx(Button, { kind: "ghost", size: "sm", onPress: retry, children: "Retry download" })] })), upload && (_jsxs("p", { className: "chat-file-progress", children: [_jsx("progress", { "aria-label": `Uploading ${attachment.name}`, value: upload.loaded, max: upload.total || 1 }), _jsxs("span", { children: [Math.round((upload.loaded / (upload.total || 1)) * 100), "% sent"] })] }))] }));
71
+ }
72
+ /** Fills in the `src` of every `img[data-mxc]` the sanitiser left in a
73
+ * message's HTML, and revokes what it made when the message goes.
74
+ *
75
+ * The sanitiser deliberately leaves those images with no `src`, so
76
+ * nothing is requested until this runs and nothing is ever requested
77
+ * without the token. An image whose bytes cannot be had simply stays
78
+ * blank beside its own `alt`. */
79
+ export function useInlineMedia(client, host, html) {
80
+ useEffect(() => {
81
+ const element = host.current;
82
+ if (!element || !html)
83
+ return;
84
+ const images = Array.from(element.querySelectorAll('img[data-mxc]'));
85
+ if (images.length === 0)
86
+ return;
87
+ const made = [];
88
+ let cancelled = false;
89
+ for (const image of images) {
90
+ const mxcUri = image.getAttribute('data-mxc');
91
+ if (!mxcUri)
92
+ continue;
93
+ client
94
+ .loadMedia(mxcUri)
95
+ .then((url) => {
96
+ if (!url)
97
+ return;
98
+ if (cancelled) {
99
+ URL.revokeObjectURL(url);
100
+ return;
101
+ }
102
+ made.push(url);
103
+ image.src = url;
104
+ })
105
+ .catch(() => { });
106
+ }
107
+ return () => {
108
+ cancelled = true;
109
+ for (const url of made)
110
+ URL.revokeObjectURL(url);
111
+ };
112
+ }, [client, host, html]);
113
+ }
@@ -0,0 +1,48 @@
1
+ import type { ChatClient } from '../types.ts';
2
+ /**
3
+ * Where the reader is: which room, which thread inside it, and which
4
+ * message they were sent to find.
5
+ *
6
+ * `threadId` is the id of the message that *started* the thread -- Matrix
7
+ * threads are one level, so a thread has no id of its own. `eventId` is a
8
+ * message to scroll to and mark, not a place: it is what "go to message"
9
+ * sets, and a host is free to leave it out of the address.
10
+ */
11
+ export type ChatLocation = {
12
+ roomId: string | null;
13
+ threadId: string | null;
14
+ eventId: string | null;
15
+ };
16
+ export type ChatProps = {
17
+ client: ChatClient;
18
+ /** Drive the selected room from outside -- the URL, in the agora. Omit it
19
+ * and the component keeps its own selection, right for a gallery or an
20
+ * embed. Supply it with `onNavigate` and the two are all or nothing, the
21
+ * same rule `Mail`'s `MailLocation` follows. */
22
+ location?: ChatLocation;
23
+ onNavigate?: (to: ChatLocation) => void;
24
+ /** The right-hand end of the header: who is signed in, and the way out.
25
+ * A slot, not something this component builds -- see `Mail`'s `account`
26
+ * for why. */
27
+ account?: React.ReactNode;
28
+ onError?: (error: Error) => void;
29
+ /** What "now" is, for the timeline's date dividers ("Today" versus a
30
+ * weekday). Defaults to `new Date()`; a caller with its own clock (a
31
+ * test, a replay) wires it here rather than this reading the system
32
+ * clock on every render. */
33
+ now?: Date;
34
+ /** Enter sends and Shift-Enter makes a line, unless the caller wires a
35
+ * different preference here -- see `Composer`'s own doc. */
36
+ sendOnEnter?: boolean;
37
+ className?: string;
38
+ };
39
+ /**
40
+ * The agora's Chat section: the person's channels and direct rooms, one of
41
+ * them selected, its timeline and composer in the room pane (ticket #15).
42
+ *
43
+ * Plain on purpose -- see the campaign brief, MSG-010: no design pass runs
44
+ * against this ticket, and this is not `Mail`'s layout reused. Structure
45
+ * and honest states, on `@wtfalch/design`'s tokens; the design pass is a
46
+ * separate step once there is a shipped surface to design around.
47
+ */
48
+ export declare function Chat({ client, location, onNavigate, account, onError, now, sendOnEnter, className, }: ChatProps): import("react").JSX.Element;