@remit/ui 0.0.213 → 0.0.215

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remit/ui",
3
- "version": "0.0.213",
3
+ "version": "0.0.215",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "src"
@@ -9,8 +9,13 @@ import { ConfirmDialog } from "./confirm-dialog.js";
9
9
  import { PlainTextEditor } from "./plain-text-editor.js";
10
10
  import { markdownToHtml } from "./rich-text-document.js";
11
11
  import { RichTextEditor } from "./rich-text-editor.js";
12
+ import type { InlineImages } from "./rich-text-inline-images.js";
12
13
  import type { SpellcheckOptions } from "./rich-text-spellcheck.js";
13
- import type { ComposeCaret, RichTextValue } from "./rich-text-value.js";
14
+ import type {
15
+ ComposeCaret,
16
+ ComposeInsertion,
17
+ RichTextValue,
18
+ } from "./rich-text-value.js";
14
19
  import { useComposeLanguage } from "./use-compose-language.js";
15
20
 
16
21
  export interface ConversionFailure {
@@ -69,6 +74,9 @@ export interface ComposeBodyProps {
69
74
  * the browser's.
70
75
  */
71
76
  spellcheck?: SpellcheckOptions;
77
+ insertion?: ComposeInsertion;
78
+ onInserted?: (version: number) => void;
79
+ inlineImages?: InlineImages;
72
80
  }
73
81
 
74
82
  /**
@@ -91,6 +99,9 @@ export const ComposeBody = ({
91
99
  initialLanguage,
92
100
  onLanguageChange,
93
101
  spellcheck,
102
+ insertion,
103
+ onInserted,
104
+ inlineImages,
94
105
  }: ComposeBodyProps) => {
95
106
  const [richHtml, setRichHtml] = useState(initialHtml);
96
107
  const [richGeneration, setRichGeneration] = useState(0);
@@ -195,6 +206,8 @@ export const ComposeBody = ({
195
206
  initialCaret={focusSwitchedSurface ? "end" : initialCaret}
196
207
  lang={language}
197
208
  trailing={trailing}
209
+ insertion={insertion}
210
+ onInserted={onInserted}
198
211
  />
199
212
  ) : (
200
213
  <RichTextEditor
@@ -206,6 +219,9 @@ export const ComposeBody = ({
206
219
  lang={language}
207
220
  trailing={trailing}
208
221
  spellcheck={spellcheck}
222
+ insertion={insertion}
223
+ onInserted={onInserted}
224
+ inlineImages={inlineImages}
209
225
  />
210
226
  )}
211
227
  <ConfirmDialog
@@ -1,4 +1,4 @@
1
- import type { ReactNode } from "react";
1
+ import { type DragEvent, type ReactNode, useState } from "react";
2
2
 
3
3
  /**
4
4
  * How the surface gets its height. `fill` takes the one its container hands it
@@ -23,8 +23,12 @@ export interface ComposeFormShellProps {
23
23
  /** The ComposeActionBar. */
24
24
  actionBar: ReactNode;
25
25
  layout?: ComposeShellLayout;
26
+ onDropFiles?: (files: File[]) => void;
26
27
  }
27
28
 
29
+ const carriesFiles = (event: DragEvent): boolean =>
30
+ Array.from(event.dataTransfer?.types ?? []).includes("Files");
31
+
28
32
  /**
29
33
  * Presentational compose layout: banner / header / body+quote / action bar.
30
34
  *
@@ -51,10 +55,46 @@ export function ComposeFormShell({
51
55
  attachments,
52
56
  actionBar,
53
57
  layout = "fill",
58
+ onDropFiles,
54
59
  }: ComposeFormShellProps) {
55
60
  const fills = layout === "fill";
61
+ const [dropping, setDropping] = useState(false);
62
+ const dropTarget = onDropFiles
63
+ ? {
64
+ onDragOver: (event: DragEvent<HTMLDivElement>) => {
65
+ if (!carriesFiles(event)) return;
66
+ event.preventDefault();
67
+ setDropping(true);
68
+ },
69
+ onDragLeave: (event: DragEvent<HTMLDivElement>) => {
70
+ if (
71
+ event.relatedTarget instanceof Node &&
72
+ event.currentTarget.contains(event.relatedTarget)
73
+ )
74
+ return;
75
+ setDropping(false);
76
+ },
77
+ onDrop: (event: DragEvent<HTMLDivElement>) => {
78
+ setDropping(false);
79
+ const files = Array.from(event.dataTransfer?.files ?? []);
80
+ if (files.length === 0) return;
81
+ event.preventDefault();
82
+ onDropFiles(files);
83
+ },
84
+ }
85
+ : {};
56
86
  return (
57
- <div className={fills ? "flex h-full min-h-0 flex-col" : "flex flex-col"}>
87
+ <div
88
+ className={[
89
+ fills ? "flex h-full min-h-0 flex-col" : "flex flex-col",
90
+ dropping && "outline-2 -outline-offset-2 outline-dashed outline-accent",
91
+ ]
92
+ .filter(Boolean)
93
+ .join(" ")}
94
+ data-testid="compose-drop-target"
95
+ data-dropping={dropping || undefined}
96
+ {...dropTarget}
97
+ >
58
98
  {banner}
59
99
  {header}
60
100
  <div
@@ -1,4 +1,4 @@
1
- import { CalendarDays, Copy } from "lucide-react";
1
+ import { CalendarDays, Reply } from "lucide-react";
2
2
  import { type ReactNode, useState } from "react";
3
3
  import { cn } from "../lib/cn.js";
4
4
  import { Button } from "./button.js";
@@ -82,10 +82,6 @@ export interface CalendarProseIntel {
82
82
  slots: CalendarSlotPick[];
83
83
  /** Start clocks already ticked into the reply. */
84
84
  picked: readonly string[];
85
- /** What became of the last copy of the picked times. */
86
- copy?: "idle" | "copied" | "failed";
87
- /** The picked times as text, offered to select by hand when copying failed. */
88
- copyText?: string;
89
85
  }
90
86
 
91
87
  export interface IntelligenceCalendarData {
@@ -123,7 +119,7 @@ export interface IntelligenceCalendarActions {
123
119
  onRemoveInvite?: () => void;
124
120
  onOpenNewerInvite?: () => void;
125
121
  onToggleSlot: (slot: CalendarSlotPick) => void;
126
- onCopySlots?: () => void;
122
+ onReplyWithSlots?: () => void;
127
123
  onAddSuggestion: (suggestionId: string, timeZone: string) => void;
128
124
  onReviewSuggestion?: (suggestionId: string, timeZone: string) => void;
129
125
  onDismissSuggestion: (suggestionId: string) => void;
@@ -277,41 +273,20 @@ export function IntelligenceCalendar({
277
273
  touch={touch}
278
274
  scroll
279
275
  />
280
- {actions.onCopySlots ? (
276
+ {actions.onReplyWithSlots ? (
281
277
  <div className="mt-2 flex flex-col gap-1.5">
282
278
  <Button
283
279
  variant="secondary"
284
280
  size={touch ? "md" : "sm"}
285
- icon={<Copy className="size-3.5" />}
286
- onClick={actions.onCopySlots}
281
+ icon={<Reply className="size-3.5" />}
282
+ onClick={actions.onReplyWithSlots}
287
283
  disabled={picked.size === 0}
288
284
  className={cn("self-start", touch && "min-h-11")}
289
285
  >
290
- Copy picked times
286
+ Reply with these times
291
287
  </Button>
292
- {prose.copy === "copied" && (
293
- <p role="status" className="text-2xs text-positive">
294
- Copied. Paste them into your reply.
295
- </p>
296
- )}
297
- {prose.copy === "failed" && (
298
- <div role="alert" className="flex flex-col gap-1">
299
- <p className="text-2xs text-danger">
300
- This page can't copy for you. Select the times below and
301
- copy them yourself.
302
- </p>
303
- <textarea
304
- readOnly
305
- aria-label="Picked times"
306
- value={prose.copyText ?? ""}
307
- onFocus={(event) => event.currentTarget.select()}
308
- rows={2}
309
- className="w-full resize-none rounded-md border border-line bg-surface p-1.5 text-xs text-fg"
310
- />
311
- </div>
312
- )}
313
288
  <p className="text-2xs text-fg-subtle">
314
- Picked slots are copied as plain text. Nothing is booked.
289
+ Picked slots go into the reply as plain text. Nothing is booked.
315
290
  </p>
316
291
  </div>
317
292
  ) : (
@@ -54,7 +54,6 @@ function PanelDemo({
54
54
  hideCloseButton,
55
55
  touch,
56
56
  className,
57
- copyFails = false,
58
57
  }: {
59
58
  sender: IntelligenceData;
60
59
  calendar: IntelligenceCalendarData;
@@ -62,8 +61,6 @@ function PanelDemo({
62
61
  hideCloseButton?: boolean;
63
62
  touch?: boolean;
64
63
  className?: string;
65
- /** The page cannot reach the clipboard, as on plain http. */
66
- copyFails?: boolean;
67
64
  }) {
68
65
  const [tab, setTab] = useState<IntelligenceTabId>(initialTab);
69
66
  const [rsvp, setRsvp] = useState<RsvpState>(
@@ -72,9 +69,6 @@ function PanelDemo({
72
69
  const [removed, setRemoved] = useState(false);
73
70
  const [offering, setOffering] = useState(calendar.prose !== undefined);
74
71
  const [picked, setPicked] = useState<string[]>([]);
75
- const [copy, setCopy] = useState<"idle" | "copied" | "failed">(
76
- calendar.prose?.copy ?? "idle",
77
- );
78
72
  const [dropped, setDropped] = useState<string[]>([]);
79
73
  const [selectedEventId, setSelectedEventId] = useState("");
80
74
  const [lastAction, setLastAction] = useState("");
@@ -83,8 +77,6 @@ function PanelDemo({
83
77
  ? {
84
78
  ...(calendar.prose ?? thursdayProse),
85
79
  picked,
86
- copy,
87
- copyText: `${(calendar.prose ?? thursdayProse).dayLabel}: ${picked.join(", ")}`,
88
80
  }
89
81
  : undefined;
90
82
 
@@ -123,14 +115,16 @@ function PanelDemo({
123
115
  onOfferOtherTimes: () => setOffering(true),
124
116
  onRemoveInvite: () => setRemoved(true),
125
117
  onToggleSlot: (slot) => {
126
- setCopy("idle");
127
118
  setPicked((prev) =>
128
119
  prev.includes(slot.startTime)
129
120
  ? prev.filter((start) => start !== slot.startTime)
130
121
  : [...prev, slot.startTime],
131
122
  );
132
123
  },
133
- onCopySlots: () => setCopy(copyFails ? "failed" : "copied"),
124
+ onReplyWithSlots: () =>
125
+ setLastAction(
126
+ `opened a reply holding ${(calendar.prose ?? thursdayProse).dayLabel}: ${picked.join(", ")}`,
127
+ ),
134
128
  onAddSuggestion: (id, timeZone) => {
135
129
  setDropped((prev) => [...prev, id]);
136
130
  setLastAction(
@@ -235,7 +229,6 @@ function rail(
235
229
  sender: IntelligenceData,
236
230
  calendar: IntelligenceCalendarData,
237
231
  initialTab: IntelligenceTabId = "calendar",
238
- copyFails = false,
239
232
  ): Story {
240
233
  return {
241
234
  render: () => (
@@ -244,7 +237,6 @@ function rail(
244
237
  sender={sender}
245
238
  calendar={calendar}
246
239
  initialTab={initialTab}
247
- copyFails={copyFails}
248
240
  className="h-full"
249
241
  />
250
242
  </RailHost>
@@ -367,18 +359,6 @@ export const ReadFailure = rail(PLAIN, organiserSender, {
367
359
  reportHref: REPORT,
368
360
  });
369
361
 
370
- /**
371
- * Picked times on a page that cannot reach the clipboard, as on plain http.
372
- * The failure is stated and the times are there to select by hand.
373
- */
374
- export const CopyFailed = rail(
375
- THURSDAY,
376
- organiserSender,
377
- proseTimeThread,
378
- "calendar",
379
- true,
380
- );
381
-
382
362
  /**
383
363
  * The same invitation an hour later. Nothing is booked over it, and the panel
384
364
  * says that too — silence there would read as "not checked", which is the same
@@ -10,7 +10,7 @@ import {
10
10
  import { Banner } from "./banner.js";
11
11
  import { isWritingElsewhere } from "./editor-focus.js";
12
12
  import { htmlToMarkdown } from "./rich-text-document.js";
13
- import type { ComposeCaret } from "./rich-text-value.js";
13
+ import type { ComposeCaret, ComposeInsertion } from "./rich-text-value.js";
14
14
 
15
15
  export interface PlainTextEditorProps {
16
16
  value: string;
@@ -21,6 +21,8 @@ export interface PlainTextEditorProps {
21
21
  * does not take focus.
22
22
  */
23
23
  initialCaret?: ComposeCaret;
24
+ insertion?: ComposeInsertion;
25
+ onInserted?: (version: number) => void;
24
26
  placeholder?: string;
25
27
  ariaLabel?: string;
26
28
  /** Pinned to the right of the toolbar strip. The mode toggle rides here. */
@@ -70,11 +72,27 @@ export const PlainTextEditor = ({
70
72
  ariaLabel = "Message body",
71
73
  trailing,
72
74
  lang,
75
+ insertion,
76
+ onInserted,
73
77
  }: PlainTextEditorProps) => {
74
78
  const textareaRef = useRef<HTMLTextAreaElement>(null);
75
79
  const pendingCaret = useRef<number | null>(null);
76
80
  const plainRequested = useRef(false);
77
81
  const [emptyPaste, setEmptyPaste] = useState(false);
82
+ const appliedInsertion = useRef<number | undefined>(undefined);
83
+
84
+ useEffect(() => {
85
+ if (!insertion || insertion.version === appliedInsertion.current) return;
86
+ appliedInsertion.current = insertion.version;
87
+ const textarea = textareaRef.current;
88
+ if (!textarea) return;
89
+ textarea.focus();
90
+ const spliced = insertAtCaret(textarea, insertion.text);
91
+ onInserted?.(insertion.version);
92
+ if (!spliced) return;
93
+ pendingCaret.current = spliced.caret;
94
+ onChange(spliced.value);
95
+ }, [insertion, onChange, onInserted]);
78
96
 
79
97
  // Grows to its content rather than scrolling inside itself: one scroller in
80
98
  // the compose body keeps the caret in view for free, which a nested one is
@@ -13,7 +13,10 @@ import {
13
13
  type LexicalNode,
14
14
  type TextFormatType,
15
15
  } from "lexical";
16
- import { sanitizeAdoptedHtml } from "../lib/adopted-html.js";
16
+ import {
17
+ type ContentIdOwner,
18
+ sanitizeAdoptedHtml,
19
+ } from "../lib/adopted-html.js";
17
20
  import { COMPOSE_TRANSFORMERS } from "./rich-text-markdown.js";
18
21
  import { RICH_TEXT_NODES } from "./rich-text-nodes.js";
19
22
  import type { RichTextValue } from "./rich-text-value.js";
@@ -21,9 +24,10 @@ import type { RichTextValue } from "./rich-text-value.js";
21
24
  export const $adoptHtml = (
22
25
  editor: LexicalEditor,
23
26
  html: string,
27
+ owns?: ContentIdOwner,
24
28
  ): LexicalNode[] => {
25
29
  const document = new DOMParser().parseFromString(
26
- sanitizeAdoptedHtml(html),
30
+ sanitizeAdoptedHtml(html, owns),
27
31
  "text/html",
28
32
  );
29
33
  return $generateNodesFromDOM(editor, document);
@@ -85,8 +89,11 @@ export const $documentFormatting = (): string[] => {
85
89
  * outgoing document goes back through the same profile a paste comes in
86
90
  * through.
87
91
  */
88
- export const $readRichText = (editor: LexicalEditor): RichTextValue => ({
89
- html: sanitizeAdoptedHtml($generateHtmlFromNodes(editor, null)),
92
+ export const $readRichText = (
93
+ editor: LexicalEditor,
94
+ owns?: ContentIdOwner,
95
+ ): RichTextValue => ({
96
+ html: sanitizeAdoptedHtml($generateHtmlFromNodes(editor, null), owns),
90
97
  text: $convertToMarkdownString(COMPOSE_TRANSFORMERS),
91
98
  formatting: $documentFormatting(),
92
99
  });
@@ -8,6 +8,7 @@ import {
8
8
  ComposeModeToggle,
9
9
  } from "./compose-mode-toggle.js";
10
10
  import { RichTextEditor } from "./rich-text-editor.js";
11
+ import type { InlineImages } from "./rich-text-inline-images.js";
11
12
  import type {
12
13
  CheckRequest,
13
14
  Finding,
@@ -1110,3 +1111,83 @@ export const StickyToolbar: Story = {
1110
1111
  ).toBeLessThan(60);
1111
1112
  },
1112
1113
  };
1114
+
1115
+ const pasteScreenshot = async (editable: HTMLElement): Promise<void> => {
1116
+ const canvas = document.createElement("canvas");
1117
+ canvas.width = 480;
1118
+ canvas.height = 200;
1119
+ const context = canvas.getContext("2d");
1120
+ if (!context) throw new Error("no 2d canvas to draw the screenshot on");
1121
+ context.fillStyle = "#e2e8f0";
1122
+ context.fillRect(0, 0, 480, 200);
1123
+ context.fillStyle = "#3780f6";
1124
+ for (const [index, height] of [60, 120, 90, 160].entries()) {
1125
+ context.fillRect(40 + index * 110, 180 - height, 70, height);
1126
+ }
1127
+ const blob = await new Promise<Blob | null>((resolve) =>
1128
+ canvas.toBlob(resolve, "image/png"),
1129
+ );
1130
+ if (!blob) throw new Error("the screenshot could not be encoded");
1131
+ const clipboard = new DataTransfer();
1132
+ clipboard.items.add(new File([blob], "chart.png", { type: "image/png" }));
1133
+ editable.dispatchEvent(
1134
+ new ClipboardEvent("paste", {
1135
+ clipboardData: clipboard,
1136
+ bubbles: true,
1137
+ cancelable: true,
1138
+ }),
1139
+ );
1140
+ };
1141
+
1142
+ const storyInlineImages: InlineImages = {
1143
+ attach: (files, placement) => {
1144
+ for (const file of files) placement?.stored(file, `${file.name}@remit`);
1145
+ },
1146
+ owns: (contentId) => contentId.endsWith("@remit"),
1147
+ resolve: async () => null,
1148
+ onRemoved: () => () => {},
1149
+ };
1150
+
1151
+ const InlineImageComposer = () => {
1152
+ const [outgoing, setOutgoing] = useState("");
1153
+ return (
1154
+ <>
1155
+ <RichTextEditor
1156
+ initialHtml="<p>This week's numbers:</p>"
1157
+ onChange={(value) => setOutgoing(value.html)}
1158
+ inlineImages={storyInlineImages}
1159
+ />
1160
+ <output data-testid="outgoing-html" className="sr-only">
1161
+ {outgoing}
1162
+ </output>
1163
+ </>
1164
+ );
1165
+ };
1166
+
1167
+ export const PastedInlineImage: Story = {
1168
+ name: "Pasting a screenshot inline",
1169
+ render: () => <InlineImageComposer />,
1170
+ play: async ({ canvasElement }) => {
1171
+ const editable = canvasElement.querySelector<HTMLElement>(
1172
+ "[data-testid=compose-body]",
1173
+ );
1174
+ const outgoing = canvasElement.querySelector<HTMLElement>(
1175
+ "[data-testid=outgoing-html]",
1176
+ );
1177
+ if (!editable || !outgoing) throw new Error("the editor is not mounted");
1178
+
1179
+ await userEvent.click(editable);
1180
+ await pasteScreenshot(editable);
1181
+
1182
+ const image = await waitFor(() => {
1183
+ const shown = editable.querySelector("img");
1184
+ if (!shown) throw new Error("the screenshot is not in the body");
1185
+ return shown;
1186
+ });
1187
+ await expect(image).toHaveAttribute("alt", "chart.png");
1188
+ await waitFor(() => expect(image.naturalWidth).toBe(480));
1189
+ await waitFor(() =>
1190
+ expect(outgoing.textContent).toContain('src="cid:chart.png@remit"'),
1191
+ );
1192
+ },
1193
+ };
@@ -30,9 +30,16 @@ import {
30
30
  useRef,
31
31
  useState,
32
32
  } from "react";
33
+ import type { ContentIdOwner } from "../lib/adopted-html.js";
33
34
  import { isWritingElsewhere } from "./editor-focus.js";
34
35
  import { RichTextCorrectionMenu } from "./rich-text-correction-menu.js";
35
36
  import { $adoptHtml, $readRichText } from "./rich-text-document.js";
37
+ import {
38
+ $pasteFiles,
39
+ InlineImagePlugin,
40
+ type InlineImages,
41
+ pastedFiles,
42
+ } from "./rich-text-inline-images.js";
36
43
  import { RICH_TEXT_NODES, richTextTheme } from "./rich-text-nodes.js";
37
44
  import type {
38
45
  CheckSpan,
@@ -47,7 +54,11 @@ import {
47
54
  SUGGESTION_LIMIT,
48
55
  } from "./rich-text-spellcheck-words.js";
49
56
  import { RichTextToolbar } from "./rich-text-toolbar.js";
50
- import type { ComposeCaret, RichTextValue } from "./rich-text-value.js";
57
+ import type {
58
+ ComposeCaret,
59
+ ComposeInsertion,
60
+ RichTextValue,
61
+ } from "./rich-text-value.js";
51
62
 
52
63
  export interface RichTextEditorProps {
53
64
  /**
@@ -81,6 +92,9 @@ export interface RichTextEditorProps {
81
92
  * `lang`, which is also when the browser keeps checking.
82
93
  */
83
94
  spellcheck?: SpellcheckOptions;
95
+ insertion?: ComposeInsertion;
96
+ onInserted?: (version: number) => void;
97
+ inlineImages?: InlineImages;
84
98
  }
85
99
 
86
100
  /**
@@ -92,7 +106,13 @@ export interface RichTextEditorProps {
92
106
  * Apple Mail. The clipboard event carries no modifier state, so the keystroke
93
107
  * that triggered it is what records the intent.
94
108
  */
95
- const PastePlugin = () => {
109
+ const PastePlugin = ({
110
+ inlineImages,
111
+ owns,
112
+ }: {
113
+ inlineImages: RefObject<InlineImages | undefined>;
114
+ owns: ContentIdOwner;
115
+ }) => {
96
116
  const [editor] = useLexicalComposerContext();
97
117
  const plainRequested = useRef(false);
98
118
 
@@ -124,6 +144,14 @@ const PastePlugin = () => {
124
144
  const wasPlainRequested = plainRequested.current;
125
145
  plainRequested.current = false;
126
146
 
147
+ const images = inlineImages.current;
148
+ const files = images ? pastedFiles(clipboard) : [];
149
+ if (images && files.length > 0) {
150
+ event.preventDefault();
151
+ $pasteFiles(editor, files, images);
152
+ return true;
153
+ }
154
+
127
155
  if (wasPlainRequested) {
128
156
  const selection = $getSelection();
129
157
  if (!$isRangeSelection(selection)) return false;
@@ -136,13 +164,13 @@ const PastePlugin = () => {
136
164
  if (!html) return false;
137
165
 
138
166
  event.preventDefault();
139
- $insertNodes($adoptHtml(editor, html));
167
+ $insertNodes($adoptHtml(editor, html, owns));
140
168
  return true;
141
169
  },
142
170
  COMMAND_PRIORITY_CRITICAL,
143
171
  ),
144
172
  ),
145
- [editor],
173
+ [editor, inlineImages, owns],
146
174
  );
147
175
 
148
176
  return null;
@@ -156,8 +184,10 @@ const PastePlugin = () => {
156
184
  */
157
185
  const ChangePlugin = ({
158
186
  onChange,
187
+ owns,
159
188
  }: {
160
189
  onChange: (value: RichTextValue) => void;
190
+ owns: ContentIdOwner;
161
191
  }) => {
162
192
  const [editor] = useLexicalComposerContext();
163
193
  const report = useRef(onChange);
@@ -167,13 +197,14 @@ const ChangePlugin = ({
167
197
  }, [onChange]);
168
198
 
169
199
  useEffect(() => {
170
- const emit = () => report.current(editor.read(() => $readRichText(editor)));
200
+ const emit = () =>
201
+ report.current(editor.read(() => $readRichText(editor, owns)));
171
202
  emit();
172
203
  return editor.registerUpdateListener(({ dirtyElements, dirtyLeaves }) => {
173
204
  if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return;
174
205
  emit();
175
206
  });
176
- }, [editor]);
207
+ }, [editor, owns]);
177
208
 
178
209
  return null;
179
210
  };
@@ -906,10 +937,36 @@ const AutoFocus = ({ caret }: { caret?: ComposeCaret }) => {
906
937
  return null;
907
938
  };
908
939
 
940
+ const InsertionPlugin = ({
941
+ insertion,
942
+ onInserted,
943
+ }: {
944
+ insertion: ComposeInsertion | undefined;
945
+ onInserted: ((version: number) => void) | undefined;
946
+ }) => {
947
+ const [editor] = useLexicalComposerContext();
948
+ const applied = useRef<number | undefined>(undefined);
949
+
950
+ useEffect(() => {
951
+ if (!insertion || insertion.version === applied.current) return;
952
+ applied.current = insertion.version;
953
+ editor.update(() => {
954
+ const selection = $getSelection();
955
+ const target = $isRangeSelection(selection)
956
+ ? selection
957
+ : $getRoot().selectEnd();
958
+ target.insertRawText(insertion.text);
959
+ });
960
+ onInserted?.(insertion.version);
961
+ }, [editor, insertion, onInserted]);
962
+
963
+ return null;
964
+ };
965
+
909
966
  const seedDocument =
910
- (html: string) =>
967
+ (html: string, owns: ContentIdOwner) =>
911
968
  (editor: LexicalEditor): void => {
912
- const nodes = $adoptHtml(editor, html);
969
+ const nodes = $adoptHtml(editor, html, owns);
913
970
  if (nodes.length === 0) return;
914
971
  $getRoot().select();
915
972
  $insertNodes(nodes);
@@ -925,9 +982,18 @@ export const RichTextEditor = ({
925
982
  trailing,
926
983
  lang,
927
984
  spellcheck,
985
+ insertion,
986
+ onInserted,
987
+ inlineImages,
928
988
  }: RichTextEditorProps) => {
929
989
  const [checkedHere, setCheckedHere] = useState(false);
930
990
  const bodyRef = useRef<HTMLDivElement>(null);
991
+ const inlineRef = useRef(inlineImages);
992
+ inlineRef.current = inlineImages;
993
+ const owns = useCallback(
994
+ (contentId: string) => inlineRef.current?.owns(contentId) ?? false,
995
+ [],
996
+ );
931
997
 
932
998
  return (
933
999
  <LexicalComposer
@@ -935,7 +1001,7 @@ export const RichTextEditor = ({
935
1001
  namespace: "compose",
936
1002
  nodes: RICH_TEXT_NODES,
937
1003
  theme: richTextTheme,
938
- editorState: initialHtml ? seedDocument(initialHtml) : undefined,
1004
+ editorState: initialHtml ? seedDocument(initialHtml, owns) : undefined,
939
1005
  onError: (error) => {
940
1006
  throw error;
941
1007
  },
@@ -995,9 +1061,11 @@ export const RichTextEditor = ({
995
1061
  <ListPlugin />
996
1062
  <LinkPlugin />
997
1063
  <TablePlugin />
998
- <PastePlugin />
1064
+ <PastePlugin inlineImages={inlineRef} owns={owns} />
1065
+ <InlineImagePlugin inlineImages={inlineRef} />
999
1066
  <AutoFocus caret={initialCaret} />
1000
- {onChange && <ChangePlugin onChange={onChange} />}
1067
+ <InsertionPlugin insertion={insertion} onInserted={onInserted} />
1068
+ {onChange && <ChangePlugin onChange={onChange} owns={owns} />}
1001
1069
  </LexicalComposer>
1002
1070
  );
1003
1071
  };
@@ -29,6 +29,8 @@ export class ImageNode extends DecoratorNode<null> {
29
29
  __src: string;
30
30
  /** @internal */
31
31
  __alt: string;
32
+ /** @internal */
33
+ __preview = "";
32
34
 
33
35
  $config() {
34
36
  return this.config("image", {
@@ -48,22 +50,25 @@ export class ImageNode extends DecoratorNode<null> {
48
50
  super.afterCloneFrom(prevNode);
49
51
  this.__src = prevNode.__src;
50
52
  this.__alt = prevNode.__alt;
53
+ this.__preview = prevNode.__preview;
51
54
  }
52
55
 
53
56
  createDOM(config: EditorConfig): HTMLImageElement {
54
- const element = this.buildImage();
57
+ const element = this.buildImage(this.__preview || this.__src);
55
58
  addClassNamesToElement(element, config.theme.image);
56
59
  return element;
57
60
  }
58
61
 
59
62
  updateDOM(prevNode: this, element: HTMLImageElement): boolean {
60
- if (prevNode.__src !== this.__src) element.setAttribute("src", this.__src);
63
+ const shown = this.__preview || this.__src;
64
+ if ((prevNode.__preview || prevNode.__src) !== shown)
65
+ element.setAttribute("src", shown);
61
66
  if (prevNode.__alt !== this.__alt) element.setAttribute("alt", this.__alt);
62
67
  return false;
63
68
  }
64
69
 
65
70
  exportDOM(): DOMExportOutput {
66
- return { element: this.buildImage() };
71
+ return { element: this.buildImage(this.__src) };
67
72
  }
68
73
 
69
74
  exportJSON(): SerializedImageNode {
@@ -87,6 +92,16 @@ export class ImageNode extends DecoratorNode<null> {
87
92
  return writable;
88
93
  }
89
94
 
95
+ getPreview(): string {
96
+ return this.getLatest().__preview;
97
+ }
98
+
99
+ setPreview(preview: string): this {
100
+ const writable = this.getWritable();
101
+ writable.__preview = preview;
102
+ return writable;
103
+ }
104
+
90
105
  getAlt(): string {
91
106
  return this.getLatest().__alt;
92
107
  }
@@ -106,9 +121,9 @@ export class ImageNode extends DecoratorNode<null> {
106
121
  return true;
107
122
  }
108
123
 
109
- private buildImage(): HTMLImageElement {
124
+ private buildImage(src: string): HTMLImageElement {
110
125
  const element = $getDocument().createElement("img");
111
- element.setAttribute("src", this.__src);
126
+ element.setAttribute("src", src);
112
127
  element.setAttribute("alt", this.__alt);
113
128
  return element;
114
129
  }
@@ -0,0 +1,222 @@
1
+ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
2
+ import { $dfs, mergeRegister } from "@lexical/utils";
3
+ import {
4
+ $applyNodeReplacement,
5
+ $createParagraphNode,
6
+ $getNodeByKey,
7
+ $getRoot,
8
+ $insertNodes,
9
+ $isElementNode,
10
+ HISTORY_MERGE_TAG,
11
+ HISTORY_PUSH_TAG,
12
+ type LexicalEditor,
13
+ type NodeKey,
14
+ } from "lexical";
15
+ import { type RefObject, useEffect } from "react";
16
+ import { ImageNode } from "./rich-text-image-node.js";
17
+
18
+ export interface InlineImagePlacement {
19
+ stored: (file: File, contentId: string) => void;
20
+ failed: (file: File) => void;
21
+ }
22
+
23
+ export interface InlineImages {
24
+ attach: (files: File[], placement?: InlineImagePlacement) => void;
25
+ owns: (contentId: string) => boolean;
26
+ resolve: (contentId: string) => Promise<string | null>;
27
+ onRemoved: (listener: (contentId: string) => void) => () => void;
28
+ }
29
+
30
+ const CONTENT_ID_SOURCE = /^cid:(.+)$/i;
31
+
32
+ const contentIdOf = (src: string): string | null =>
33
+ CONTENT_ID_SOURCE.exec(src)?.[1] ?? null;
34
+
35
+ export const pastedFiles = (clipboard: DataTransfer): File[] => {
36
+ if (clipboard.getData("text/plain")) return [];
37
+ return Array.from(clipboard.files ?? []);
38
+ };
39
+
40
+ const isImage = (file: File): boolean => file.type.startsWith("image/");
41
+
42
+ const merged = { tag: HISTORY_MERGE_TAG };
43
+
44
+ export const $pasteFiles = (
45
+ editor: LexicalEditor,
46
+ files: File[],
47
+ inlineImages: InlineImages,
48
+ ): void => {
49
+ const images = files.filter(isImage);
50
+ const others = files.filter((file) => !isImage(file));
51
+ const placed = new Map<File, NodeKey>();
52
+ const taken = new Map<File, { parentKey: NodeKey; index: number }>();
53
+ const $createImage = (file: File, src: string): ImageNode => {
54
+ const node = $applyNodeReplacement(
55
+ new ImageNode(src, file.name),
56
+ ).setPreview(URL.createObjectURL(file));
57
+ placed.set(file, node.getKey());
58
+ return node;
59
+ };
60
+ const nodes = images.map((file) => $createImage(file, ""));
61
+ if (nodes.length > 0) $insertNodes(nodes);
62
+ const placedImage = (file: File): ImageNode | null => {
63
+ const key = placed.get(file);
64
+ const node = key === undefined ? null : $getNodeByKey(key);
65
+ return node instanceof ImageNode ? node : null;
66
+ };
67
+ queueMicrotask(() => {
68
+ if (others.length > 0) inlineImages.attach(others);
69
+ if (images.length === 0) return;
70
+ inlineImages.attach(images, {
71
+ stored: (file, contentId) => {
72
+ const src = `cid:${contentId}`;
73
+ const node = editor.read(() => placedImage(file));
74
+ if (node) {
75
+ editor.update(() => {
76
+ placedImage(file)?.setSrc(src);
77
+ }, merged);
78
+ return;
79
+ }
80
+ const spot = taken.get(file);
81
+ if (!spot) return;
82
+ editor.update(
83
+ () => {
84
+ const image = $createImage(file, src);
85
+ const parent = $getNodeByKey(spot.parentKey);
86
+ if ($isElementNode(parent) && parent.isAttached()) {
87
+ parent.splice(Math.min(spot.index, parent.getChildrenSize()), 0, [
88
+ image,
89
+ ]);
90
+ return;
91
+ }
92
+ $getRoot().append($createParagraphNode().append(image));
93
+ },
94
+ { tag: HISTORY_PUSH_TAG },
95
+ );
96
+ },
97
+ failed: (file) => {
98
+ editor.update(() => {
99
+ const node = placedImage(file);
100
+ if (!node) return;
101
+ taken.set(file, {
102
+ parentKey: node.getParentOrThrow().getKey(),
103
+ index: node.getIndexWithinParent(),
104
+ });
105
+ node.remove();
106
+ }, merged);
107
+ },
108
+ });
109
+ });
110
+ };
111
+
112
+ const isBlobUrl = (url: string): boolean => url.startsWith("blob:");
113
+
114
+ export const InlineImagePlugin = ({
115
+ inlineImages,
116
+ }: {
117
+ inlineImages: RefObject<InlineImages | undefined>;
118
+ }) => {
119
+ const [editor] = useLexicalComposerContext();
120
+
121
+ useEffect(() => {
122
+ const owned = new Map<NodeKey, string>();
123
+ const revoked = new Set<string>();
124
+ const resolving = new Set<NodeKey>();
125
+ let live = true;
126
+
127
+ const release = (url: string): void => {
128
+ URL.revokeObjectURL(url);
129
+ revoked.add(url);
130
+ };
131
+
132
+ const adopt = (key: NodeKey, preview: string): void => {
133
+ const previous = owned.get(key);
134
+ if (previous === preview) return;
135
+ if (previous) release(previous);
136
+ owned.set(key, preview);
137
+ };
138
+
139
+ const resolve = (key: NodeKey, src: string, contentId: string): void => {
140
+ const images = inlineImages.current;
141
+ if (!images?.owns(contentId) || resolving.has(key)) return;
142
+ resolving.add(key);
143
+ void images.resolve(contentId).then((url) => {
144
+ resolving.delete(key);
145
+ if (url === null) return;
146
+ if (!live) {
147
+ URL.revokeObjectURL(url);
148
+ return;
149
+ }
150
+ editor.update(() => {
151
+ const node = $getNodeByKey(key);
152
+ if (!(node instanceof ImageNode) || node.getSrc() !== src) {
153
+ URL.revokeObjectURL(url);
154
+ return;
155
+ }
156
+ node.setPreview(url);
157
+ }, merged);
158
+ });
159
+ };
160
+
161
+ const visit = (key: NodeKey, orphans: NodeKey[]): void => {
162
+ const node = $getNodeByKey(key);
163
+ if (!(node instanceof ImageNode)) return;
164
+ const referenced = contentIdOf(node.getSrc());
165
+ if (referenced !== null && !inlineImages.current?.owns(referenced)) {
166
+ orphans.push(key);
167
+ return;
168
+ }
169
+ const preview = node.getPreview();
170
+ if (preview && !revoked.has(preview)) {
171
+ if (isBlobUrl(preview)) adopt(key, preview);
172
+ return;
173
+ }
174
+ const src = node.getSrc();
175
+ const contentId = contentIdOf(src);
176
+ if (contentId !== null) resolve(key, src, contentId);
177
+ };
178
+
179
+ const removeReferences = (contentId: string): void => {
180
+ editor.update(() => {
181
+ for (const { node } of $dfs()) {
182
+ if (node instanceof ImageNode && node.getSrc() === `cid:${contentId}`)
183
+ node.remove();
184
+ }
185
+ }, merged);
186
+ };
187
+
188
+ const unsubscribe =
189
+ inlineImages.current?.onRemoved(removeReferences) ?? (() => {});
190
+
191
+ const unregister = editor.registerMutationListener(
192
+ ImageNode,
193
+ (mutations) => {
194
+ const orphans: NodeKey[] = [];
195
+ editor.read(() => {
196
+ for (const [key, mutation] of mutations) {
197
+ if (mutation !== "destroyed") {
198
+ visit(key, orphans);
199
+ continue;
200
+ }
201
+ const url = owned.get(key);
202
+ owned.delete(key);
203
+ if (url) release(url);
204
+ }
205
+ });
206
+ if (orphans.length === 0) return;
207
+ editor.update(() => {
208
+ for (const key of orphans) $getNodeByKey(key)?.remove();
209
+ }, merged);
210
+ },
211
+ );
212
+
213
+ return () => {
214
+ live = false;
215
+ mergeRegister(unregister, unsubscribe)();
216
+ for (const url of owned.values()) URL.revokeObjectURL(url);
217
+ owned.clear();
218
+ };
219
+ }, [editor, inlineImages]);
220
+
221
+ return null;
222
+ };
@@ -23,6 +23,11 @@ export interface RichTextValue {
23
23
  */
24
24
  export type ComposeCaret = "start" | "end";
25
25
 
26
+ export interface ComposeInsertion {
27
+ version: number;
28
+ text: string;
29
+ }
30
+
26
31
  export const EMPTY_RICH_TEXT: RichTextValue = {
27
32
  html: "",
28
33
  text: "",
@@ -106,6 +106,19 @@ describe("sanitizeAdoptedHtml", () => {
106
106
  assert.equal(result.includes("cid:part1"), false);
107
107
  });
108
108
 
109
+ it("keeps a cid: image only when it names one of the draft's own files", () => {
110
+ const result = sanitizeAdoptedHtml(
111
+ [
112
+ '<img src="cid:att-1@remit" alt="Ours">',
113
+ '<img src="cid:part1" alt="Another message">',
114
+ ].join(""),
115
+ (contentId) => contentId === "att-1@remit",
116
+ );
117
+
118
+ assert.match(result, /src="cid:att-1@remit"/);
119
+ assert.equal(result.includes("cid:part1"), false);
120
+ });
121
+
109
122
  it("caps an image at the width the recipient has for it", () => {
110
123
  const result = sanitizeAdoptedHtml(
111
124
  '<img src="https://example.com/screenshot.png" width="1600">',
@@ -62,6 +62,18 @@ const ADOPTED_ATTR = [
62
62
 
63
63
  const LINK_SCHEMES = /^(?:https?:|mailto:)/i;
64
64
  const IMAGE_SCHEMES = /^(?:https:|data:image\/)/i;
65
+ const CONTENT_ID_SOURCE = /^cid:(.+)$/i;
66
+
67
+ export type ContentIdOwner = (contentId: string) => boolean;
68
+
69
+ const ownsNone: ContentIdOwner = () => false;
70
+ let ownsContentId: ContentIdOwner = ownsNone;
71
+
72
+ const keepsImage = (src: string): boolean => {
73
+ const reference = CONTENT_ID_SOURCE.exec(src);
74
+ if (reference) return ownsContentId(reference[1]);
75
+ return IMAGE_SCHEMES.test(src);
76
+ };
65
77
 
66
78
  /**
67
79
  * A pasted screenshot is as wide as the screen it came off, and the class the
@@ -107,7 +119,7 @@ const createPurifier = (profile: Profile): ReturnType<typeof DOMPurify> => {
107
119
  node.remove();
108
120
  return;
109
121
  }
110
- if (!IMAGE_SCHEMES.test(node.getAttribute("src") ?? "")) {
122
+ if (!keepsImage(node.getAttribute("src") ?? "")) {
111
123
  node.remove();
112
124
  return;
113
125
  }
@@ -142,8 +154,17 @@ const sanitize = (html: string, profile: Profile): string =>
142
154
  * It runs on the way in over a clipboard, and again on the way out over the
143
155
  * editor's own serialization, which carries the app's stylesheet with it.
144
156
  */
145
- export const sanitizeAdoptedHtml = (html: string): string =>
146
- sanitize(html, "outgoing");
157
+ export const sanitizeAdoptedHtml = (
158
+ html: string,
159
+ owns: ContentIdOwner = ownsNone,
160
+ ): string => {
161
+ ownsContentId = owns;
162
+ try {
163
+ return sanitize(html, "outgoing");
164
+ } finally {
165
+ ownsContentId = ownsNone;
166
+ }
167
+ };
147
168
 
148
169
  /** The same profile for mail quoted back at its sender, links and images defanged. */
149
170
  export const sanitizeQuotedHtml = (html: string): string =>
package/src/rich-text.ts CHANGED
@@ -37,6 +37,10 @@ export {
37
37
  RichTextEditor,
38
38
  type RichTextEditorProps,
39
39
  } from "./components/rich-text-editor.js";
40
+ export type {
41
+ InlineImagePlacement,
42
+ InlineImages,
43
+ } from "./components/rich-text-inline-images.js";
40
44
  export { COMPOSE_TRANSFORMERS } from "./components/rich-text-markdown.js";
41
45
  export type {
42
46
  CheckRequest,
@@ -59,6 +63,7 @@ export {
59
63
  normaliseWord,
60
64
  SUGGESTION_LIMIT,
61
65
  } from "./components/rich-text-spellcheck-words.js";
66
+ export type { ComposeInsertion } from "./components/rich-text-value.js";
62
67
  export {
63
68
  type ComposeCaret,
64
69
  EMPTY_RICH_TEXT,