@atmo-dev/kit 0.18.1 → 0.19.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 (114) hide show
  1. package/dist/articles/ArticleCard.svelte +97 -0
  2. package/dist/articles/ArticleCard.svelte.d.ts +20 -0
  3. package/dist/articles/ArticleCodeBlock.svelte +121 -0
  4. package/dist/articles/ArticleCodeBlock.svelte.d.ts +11 -0
  5. package/dist/articles/ArticleEditor.svelte +340 -0
  6. package/dist/articles/ArticleEditor.svelte.d.ts +48 -0
  7. package/dist/articles/ArticleLinkEmbed.svelte +50 -0
  8. package/dist/articles/ArticleLinkEmbed.svelte.d.ts +5 -0
  9. package/dist/articles/ArticleView.svelte +128 -0
  10. package/dist/articles/ArticleView.svelte.d.ts +46 -0
  11. package/dist/articles/PublicationIcon.svelte +37 -0
  12. package/dist/articles/PublicationIcon.svelte.d.ts +10 -0
  13. package/dist/articles/article-link-embed.d.ts +36 -0
  14. package/dist/articles/article-link-embed.js +29 -0
  15. package/dist/articles/dates.d.ts +2 -0
  16. package/dist/articles/dates.js +12 -0
  17. package/dist/articles/images.d.ts +5 -0
  18. package/dist/articles/images.js +44 -0
  19. package/dist/articles/markdown.d.ts +15 -0
  20. package/dist/articles/markdown.js +52 -0
  21. package/dist/articles/paste.d.ts +11 -0
  22. package/dist/articles/paste.js +27 -0
  23. package/dist/articles/records.d.ts +166 -0
  24. package/dist/articles/records.js +423 -0
  25. package/dist/articles/styles.d.ts +4 -0
  26. package/dist/articles/styles.js +14 -0
  27. package/dist/articles-data.d.ts +8 -0
  28. package/dist/articles-data.js +8 -0
  29. package/dist/articles.d.ts +10 -0
  30. package/dist/articles.js +8 -0
  31. package/dist/components/ExternalEmbed.svelte +16 -2
  32. package/dist/components/ExternalEmbed.svelte.d.ts +6 -0
  33. package/dist/components/IconMaker.svelte +119 -0
  34. package/dist/components/IconMaker.svelte.d.ts +9 -0
  35. package/dist/components/IconRail.svelte +9 -6
  36. package/dist/components/IconRail.svelte.d.ts +2 -0
  37. package/dist/components/LinkEmbed.svelte +24 -21
  38. package/dist/components/LinkEmbed.svelte.d.ts +3 -2
  39. package/dist/components/PaletteApply.svelte +62 -0
  40. package/dist/components/PaletteApply.svelte.d.ts +9 -0
  41. package/dist/components/PalettePicker.svelte +92 -0
  42. package/dist/components/PalettePicker.svelte.d.ts +13 -0
  43. package/dist/components/PostComments.svelte +129 -0
  44. package/dist/components/PostComments.svelte.d.ts +15 -0
  45. package/dist/components/RichText.svelte +199 -9
  46. package/dist/components/RichText.svelte.d.ts +17 -0
  47. package/dist/components/RichTextEditor.svelte +155 -13
  48. package/dist/components/RichTextEditor.svelte.d.ts +26 -3
  49. package/dist/components/composer/ComposerPost.svelte +10 -0
  50. package/dist/components/composer/ComposerPost.svelte.d.ts +3 -1
  51. package/dist/components/composer/PostComposer.svelte +28 -2
  52. package/dist/components/composer/PostComposer.svelte.d.ts +12 -1
  53. package/dist/editor/EditorMenus.svelte +438 -0
  54. package/dist/editor/EditorMenus.svelte.d.ts +9 -0
  55. package/dist/editor/SlashOptions.svelte +45 -0
  56. package/dist/editor/SlashOptions.svelte.d.ts +12 -0
  57. package/dist/editor/article-commands.d.ts +44 -0
  58. package/dist/editor/article-commands.js +289 -0
  59. package/dist/editor/article-extensions.d.ts +8 -0
  60. package/dist/editor/article-extensions.js +315 -0
  61. package/dist/editor/article-menus.d.ts +2 -0
  62. package/dist/editor/article-menus.js +3 -0
  63. package/dist/editor/document.d.ts +5 -0
  64. package/dist/editor/document.js +163 -12
  65. package/dist/editor/image-node.d.ts +8 -0
  66. package/dist/editor/image-node.js +75 -0
  67. package/dist/editor/markdown-extensions.d.ts +1 -5
  68. package/dist/editor/markdown-extensions.js +37 -2
  69. package/dist/editor/slash-menu.svelte.d.ts +9 -0
  70. package/dist/editor/slash-menu.svelte.js +134 -0
  71. package/dist/embeds/PlayerLinkEmbed.svelte +9 -1
  72. package/dist/embeds/PostLinkEmbed.svelte +12 -29
  73. package/dist/embeds/PostLinkEmbed.svelte.d.ts +3 -0
  74. package/dist/embeds/ProfileLinkEmbed.svelte +12 -17
  75. package/dist/embeds/ProfileLinkEmbed.svelte.d.ts +3 -0
  76. package/dist/embeds/defaults.d.ts +4 -2
  77. package/dist/embeds/defaults.js +7 -3
  78. package/dist/embeds/load.d.ts +44 -0
  79. package/dist/embeds/load.js +139 -0
  80. package/dist/embeds/types.d.ts +18 -3
  81. package/dist/events/EventComments.svelte +4 -101
  82. package/dist/events/EventComments.svelte.d.ts +1 -1
  83. package/dist/events/EventView.svelte +5 -0
  84. package/dist/events/EventView.svelte.d.ts +3 -0
  85. package/dist/events/event-link-embed.d.ts +4 -1
  86. package/dist/events/event-link-embed.js +9 -1
  87. package/dist/events/event-view/EventLinkEmbed.svelte +8 -8
  88. package/dist/events/event-view/EventLinkEmbed.svelte.d.ts +3 -2
  89. package/dist/icon-maker/artwork.d.ts +11 -0
  90. package/dist/icon-maker/artwork.js +25 -0
  91. package/dist/icon-maker/index.d.ts +12 -0
  92. package/dist/icon-maker/index.js +73 -0
  93. package/dist/index.d.ts +10 -3
  94. package/dist/index.js +7 -1
  95. package/dist/palettes.d.ts +20 -0
  96. package/dist/palettes.js +37 -0
  97. package/dist/richtext/article-styles.d.ts +10 -0
  98. package/dist/richtext/article-styles.js +28 -0
  99. package/dist/richtext/document.d.ts +63 -1
  100. package/dist/richtext/document.js +54 -0
  101. package/dist/richtext/markdown.d.ts +19 -4
  102. package/dist/richtext/markdown.js +223 -18
  103. package/dist/richtext/serialize.d.ts +5 -1
  104. package/dist/richtext/serialize.js +163 -31
  105. package/dist/richtext/vendor/markdown-tree.d.ts +4 -3
  106. package/dist/richtext/vendor/markdown-tree.js +2584 -26
  107. package/dist/richtext.d.ts +7 -5
  108. package/dist/richtext.js +1 -1
  109. package/dist/social/external-embeds.d.ts +5 -0
  110. package/dist/social/external-embeds.js +6 -1
  111. package/dist/social/posts.d.ts +2 -0
  112. package/dist/social/posts.js +43 -2
  113. package/dist/social/profile.js +2 -1
  114. package/package.json +28 -2
@@ -1,21 +1,34 @@
1
1
  <script lang="ts">
2
2
  import type { Snippet } from 'svelte';
3
3
  import {
4
+ collectFootnotes,
4
5
  inlineHref,
6
+ isCallout,
5
7
  inlineText,
6
- lineBreaks,
7
8
  paragraphParts,
9
+ plainTextParts,
8
10
  trimBreaks,
9
11
  MAX_RENDER_DEPTH,
12
+ type Footnotes,
10
13
  type RichTextDocument,
11
14
  type RichTextLinkOptions
12
15
  } from '../richtext/document.js';
16
+ import {
17
+ CALLOUT_ICONS,
18
+ CALLOUT_LABELS,
19
+ calloutClass,
20
+ calloutLabelClass,
21
+ highlightClass
22
+ } from '../richtext/article-styles.js';
13
23
  import { parsePlainText } from '../richtext/plain.js';
14
24
  import { linkEmbedOptions, selectLinkEmbeds } from '../embeds/context.js';
15
25
  import { resolveLinkEmbed } from '../embeds/resolve.js';
16
26
  import type { LinkEmbed as LinkEmbedDefinition } from '../embeds/types.js';
27
+ import { CornerDownLeft } from '@sketchyicons/svelte';
28
+ import Icon from './Icon.svelte';
17
29
  import LinkEmbed from './LinkEmbed.svelte';
18
30
  import { cn } from '../utils.js';
31
+ import { safeHttpUrl } from '../urls.js';
19
32
 
20
33
  export type RichTextProps = RichTextLinkOptions & {
21
34
  /** From `parseRichText`, usually on the server. Takes precedence over `text`. */
@@ -35,8 +48,25 @@
35
48
  embeds?: boolean | readonly LinkEmbedDefinition[];
36
49
  /** Custom matching instead of `embeds`; requires `linkEmbed`. */
37
50
  embedLink?: (url: string) => boolean;
51
+ /**
52
+ * What `loadLinkEmbedData` loaded for the embeds, usually on the server, so that they are
53
+ * shown with the text instead of appearing after it.
54
+ */
55
+ embedData?: Record<string, unknown>;
38
56
  /** Renders such a link. The second argument renders the ordinary link, e.g. while loading. */
39
57
  linkEmbed?: Snippet<[url: string, fallback: Snippet]>;
58
+ /**
59
+ * The address to load an article's image from, for destinations that are not HTTP(S),
60
+ * e.g. an app's own scheme for uploaded files. Other images are shown as their description.
61
+ */
62
+ imageSrc?: (url: string) => string | undefined;
63
+ /** Renders a code block in place of the plain `<pre>`, e.g. with highlighting. */
64
+ codeBlock?: Snippet<[value: string, lang: string | undefined]>;
65
+ /**
66
+ * Renders the TeX source of a formula, `display` for one on its own lines. Without it the
67
+ * source is shown as code.
68
+ */
69
+ math?: Snippet<[value: string, display: boolean]>;
40
70
  class?: string;
41
71
  };
42
72
 
@@ -50,11 +80,22 @@
50
80
  headingOffset = 0,
51
81
  embeds,
52
82
  embedLink,
83
+ embedData,
53
84
  linkEmbed,
85
+ imageSrc,
86
+ codeBlock,
87
+ math,
54
88
  class: className
55
89
  }: RichTextProps = $props();
56
90
 
91
+ const uid = $props.id();
57
92
  let doc = $derived(content ?? parsePlainText(text, { facets, detectLinks }));
93
+ let footnotes = $derived<Footnotes>(
94
+ doc.markdown
95
+ ? collectFootnotes(doc)
96
+ : { order: [], definitions: new Map(), references: new Map() }
97
+ );
98
+ const noteNumber = (id: unknown) => footnotes.order.indexOf(string(id)) + 1;
58
99
 
59
100
  const embedOptions = linkEmbedOptions();
60
101
  let embedList = $derived(selectLinkEmbeds(embeds, embedOptions()));
@@ -66,11 +107,7 @@
66
107
  : undefined
67
108
  );
68
109
  /** Plain text is one paragraph; with embeds it is split around the embedded lines. */
69
- let plainParts = $derived(
70
- isEmbed && !doc.markdown
71
- ? nodes(doc.children).flatMap((block) => paragraphParts(lineBreaks(block.children), isEmbed))
72
- : []
73
- );
110
+ let plainParts = $derived(isEmbed && !doc.markdown ? plainTextParts(doc, isEmbed) : []);
74
111
 
75
112
  type Node = Record<string, unknown>;
76
113
 
@@ -87,6 +124,25 @@
87
124
  return typeof value === 'string' ? value : '';
88
125
  }
89
126
 
127
+ function cells(row: unknown): unknown[] {
128
+ return Array.isArray(row) ? row : [];
129
+ }
130
+ function align(table: Node, index: number): string | undefined {
131
+ const value = Array.isArray(table.align) ? table.align[index] : undefined;
132
+ return value === 'left' || value === 'center' || value === 'right'
133
+ ? `text-align: ${value}`
134
+ : undefined;
135
+ }
136
+ function src(node: Node): string | undefined {
137
+ const url = string(node.url);
138
+ const resolved = safeHttpUrl(url) ?? (url ? imageSrc?.(url) : undefined);
139
+ // An app's own address is a path on its origin or HTTP(S), never a script.
140
+ if (!resolved) return undefined;
141
+ return (resolved.startsWith('/') && !resolved.startsWith('//')) || resolved.startsWith('blob:')
142
+ ? resolved
143
+ : safeHttpUrl(resolved);
144
+ }
145
+
90
146
  function href(node: Node): string | undefined {
91
147
  return inlineHref(node, { socialClient, mentionUrl });
92
148
  }
@@ -112,7 +168,24 @@
112
168
  >
113
169
  {:else if node.type === 'emphasis'}<em>{@render inlines(node.children, inLink, depth + 1)}</em>
114
170
  {:else if node.type === 'delete'}<del>{@render inlines(node.children, inLink, depth + 1)}</del>
171
+ {:else if node.type === 'highlight'}<mark class={highlightClass}
172
+ >{@render inlines(node.children, inLink, depth + 1)}</mark
173
+ >
115
174
  {:else if node.type === 'code'}<code class={codeClass}>{string(node.value)}</code>
175
+ {:else if node.type === 'math'}{#if math}{@render math(string(node.value), false)}{:else}<code
176
+ class={codeClass}>{string(node.value)}</code
177
+ >{/if}
178
+ {:else if node.type === 'footnoteReference'}
179
+ {@const number = noteNumber(node.id)}
180
+ {#if number}<sup
181
+ id={footnotes.references.get(string(node.id)) === node
182
+ ? `${uid}-ref-${number}`
183
+ : undefined}
184
+ class="scroll-mt-24"
185
+ ><a href="#{uid}-note-{number}" aria-label="Footnote {number}" class={linkClass}
186
+ >{number}</a
187
+ ></sup
188
+ >{:else}[^{string(node.id)}]{/if}
116
189
  {:else if node.type === 'link' || node.type === 'mention' || node.type === 'tag'}
117
190
  {@const url = inLink ? undefined : href(node)}
118
191
  {#if url}<a
@@ -134,8 +207,19 @@
134
207
 
135
208
  {#snippet embedOr(url: string | undefined, paragraph: Snippet)}
136
209
  {#if !url}{@render paragraph()}
137
- {:else if linkEmbed && embedLink}{@render linkEmbed(url, paragraph)}
138
- {:else}<LinkEmbed {url} embeds={embedList} fallback={paragraph} {socialClient} />{/if}
210
+ {:else}
211
+ <!-- Marked like the editor's embeds, so that text styles can leave embeds alone. -->
212
+ <div data-link-embed>
213
+ {#if linkEmbed && embedLink}{@render linkEmbed(url, paragraph)}
214
+ {:else}<LinkEmbed
215
+ {url}
216
+ data={embedData && Object.hasOwn(embedData, url) ? embedData[url] : undefined}
217
+ embeds={embedList}
218
+ fallback={paragraph}
219
+ {socialClient}
220
+ />{/if}
221
+ </div>
222
+ {/if}
139
223
  {/snippet}
140
224
 
141
225
  {#snippet blocks(children: unknown, depth: number)}
@@ -155,6 +239,13 @@
155
239
  : 'text-base'} leading-snug font-semibold"
156
240
  >{@render inlines(node.children, false, depth + 1)}</svelte:element
157
241
  >
242
+ {:else if node.type === 'blockquote' && isCallout(node.callout)}
243
+ <div role="note" data-callout={node.callout} class={calloutClass(node.callout)}>
244
+ <p class={calloutLabelClass(node.callout)}>
245
+ <Icon img={CALLOUT_ICONS[node.callout]} size={16} />{CALLOUT_LABELS[node.callout]}
246
+ </p>
247
+ {@render blocks(node.children, depth + 1)}
248
+ </div>
158
249
  {:else if node.type === 'blockquote'}<blockquote
159
250
  class="space-y-3 border-l-2 border-base-300 pl-4 dark:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))]"
160
251
  >
@@ -168,9 +259,32 @@
168
259
  class={cn('space-y-1 pl-6', node.ordered === true ? 'list-decimal' : 'list-disc')}
169
260
  >
170
261
  {#each items(node.items) as item, itemIndex (itemIndex)}
171
- <li class="space-y-3">{@render blocks(item, depth + 1)}</li>
262
+ {@const task = Array.isArray(node.checked) ? node.checked[itemIndex] : null}
263
+ {#if typeof task === 'boolean'}
264
+ <li class="relative list-none space-y-3">
265
+ <input
266
+ type="checkbox"
267
+ checked={task}
268
+ disabled
269
+ aria-label={task ? 'Done' : 'Not done'}
270
+ class="absolute top-[0.45em] -left-5 accent-accent-600"
271
+ />
272
+ {@render blocks(item, depth + 1)}
273
+ </li>
274
+ {:else}
275
+ <li class="space-y-3">{@render blocks(item, depth + 1)}</li>
276
+ {/if}
172
277
  {/each}
173
278
  </svelte:element>
279
+ {:else if node.type === 'footnoteDefinition'}<!-- Shown with the others, below. -->
280
+ {:else if node.type === 'math'}{#if math}{@render math(string(node.value), true)}{:else}<pre
281
+ class="overflow-x-auto rounded-md bg-[color-mix(in_srgb,var(--base-100)_75%,var(--base-200))] p-3 font-mono text-[0.875em] dark:bg-base-950"><code
282
+ >{string(node.value)}</code
283
+ ></pre>{/if}
284
+ {:else if node.type === 'codeBlock' && codeBlock}{@render codeBlock(
285
+ string(node.value),
286
+ string(node.lang) || undefined
287
+ )}
174
288
  {:else if node.type === 'codeBlock'}<pre
175
289
  class="overflow-x-auto rounded-md bg-[color-mix(in_srgb,var(--base-100)_75%,var(--base-200))] p-3 font-mono text-[0.875em] dark:bg-base-950"><code
176
290
  >{string(node.value)}</code
@@ -178,6 +292,50 @@
178
292
  {:else if node.type === 'thematicBreak'}<hr
179
293
  class="border-base-300 dark:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))]"
180
294
  />
295
+ {:else if node.type === 'image'}
296
+ {@const source = src(node)}
297
+ {#if source}<img
298
+ src={source}
299
+ alt={string(node.alt)}
300
+ title={string(node.title) || undefined}
301
+ loading="lazy"
302
+ decoding="async"
303
+ referrerpolicy="no-referrer"
304
+ class="max-w-full rounded-md"
305
+ />
306
+ {:else if string(node.alt)}<p>{string(node.alt)}</p>{/if}
307
+ {:else if node.type === 'table'}
308
+ {@const rows = cells(node.rows)}
309
+ <div class="overflow-x-auto">
310
+ <table class="border-collapse text-left">
311
+ {#if rows.length}
312
+ <thead>
313
+ <tr>
314
+ {#each cells(rows[0]) as cell, column (column)}
315
+ <th
316
+ style={align(node, column)}
317
+ class="border border-base-300 px-3 py-1.5 align-top font-semibold dark:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))]"
318
+ >{@render inlines(cell, false, depth + 1)}</th
319
+ >
320
+ {/each}
321
+ </tr>
322
+ </thead>
323
+ {/if}
324
+ <tbody>
325
+ {#each rows.slice(1) as row, rowIndex (rowIndex)}
326
+ <tr>
327
+ {#each cells(row) as cell, column (column)}
328
+ <td
329
+ style={align(node, column)}
330
+ class="border border-base-300 px-3 py-1.5 align-top dark:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))]"
331
+ >{@render inlines(cell, false, depth + 1)}</td
332
+ >
333
+ {/each}
334
+ </tr>
335
+ {/each}
336
+ </tbody>
337
+ </table>
338
+ </div>
181
339
  {:else}<p>{inlineText(node, depth)}</p>{/if}
182
340
  {/each}
183
341
  {/snippet}
@@ -187,6 +345,38 @@
187
345
  class={cn('space-y-3 leading-relaxed wrap-anywhere text-base-950 dark:text-base-50', className)}
188
346
  >
189
347
  {@render blocks(doc.children, 0)}
348
+ {#if footnotes.order.length}
349
+ <ol
350
+ aria-label="Footnotes"
351
+ class="list-decimal space-y-2 border-t border-base-300 pt-4 pl-6 text-[0.9em] text-base-700 dark:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))] dark:text-base-300"
352
+ >
353
+ {#each footnotes.order as id, index (id)}
354
+ {@const note = nodes(footnotes.definitions.get(id)?.children)}
355
+ {@const last = note.at(-1)}
356
+ <!-- The way back sits at the end of the note's last line of text. -->
357
+ {@const inline =
358
+ last?.type === 'paragraph' &&
359
+ paragraphParts(last.children, isEmbed).every((part) => !part.embed)}
360
+ <li id="{uid}-note-{index + 1}" class="scroll-mt-6 space-y-3">
361
+ {@render blocks(inline ? note.slice(0, -1) : note, 1)}
362
+ {#if footnotes.references.has(id)}
363
+ <p>
364
+ {#if inline}{@render inlines(last?.children, false, 2)}{/if}
365
+ <a
366
+ href="#{uid}-ref-{index + 1}"
367
+ aria-label="Back to the text"
368
+ title="Back to the text"
369
+ class="ml-0.5 inline-flex size-6 items-center justify-center rounded-md align-middle text-base-500 hover:bg-[color-mix(in_srgb,var(--base-100)_75%,var(--base-200))] hover:text-accent-700 dark:hover:bg-base-950 dark:hover:text-accent-300"
370
+ ><Icon img={CornerDownLeft} size={14} /></a
371
+ >
372
+ </p>
373
+ {:else if inline}
374
+ <p>{@render inlines(last?.children, false, 2)}</p>
375
+ {/if}
376
+ </li>
377
+ {/each}
378
+ </ol>
379
+ {/if}
190
380
  </div>
191
381
  {:else if plainParts.some((part) => part.embed)}
192
382
  <div
@@ -19,8 +19,25 @@ export type RichTextProps = RichTextLinkOptions & {
19
19
  embeds?: boolean | readonly LinkEmbedDefinition[];
20
20
  /** Custom matching instead of `embeds`; requires `linkEmbed`. */
21
21
  embedLink?: (url: string) => boolean;
22
+ /**
23
+ * What `loadLinkEmbedData` loaded for the embeds, usually on the server, so that they are
24
+ * shown with the text instead of appearing after it.
25
+ */
26
+ embedData?: Record<string, unknown>;
22
27
  /** Renders such a link. The second argument renders the ordinary link, e.g. while loading. */
23
28
  linkEmbed?: Snippet<[url: string, fallback: Snippet]>;
29
+ /**
30
+ * The address to load an article's image from, for destinations that are not HTTP(S),
31
+ * e.g. an app's own scheme for uploaded files. Other images are shown as their description.
32
+ */
33
+ imageSrc?: (url: string) => string | undefined;
34
+ /** Renders a code block in place of the plain `<pre>`, e.g. with highlighting. */
35
+ codeBlock?: Snippet<[value: string, lang: string | undefined]>;
36
+ /**
37
+ * Renders the TeX source of a formula, `display` for one on its own lines. Without it the
38
+ * source is shown as code.
39
+ */
40
+ math?: Snippet<[value: string, display: boolean]>;
24
41
  class?: string;
25
42
  };
26
43
  declare const RichText: import("svelte").Component<RichTextProps, {}, "">;
@@ -14,10 +14,13 @@
14
14
  bareUrl,
15
15
  documentToEditor,
16
16
  editorToDocument,
17
+ IMAGE,
17
18
  LINK_EMBED,
18
19
  markdownFacets
19
20
  } from '../editor/document.js';
20
21
  import { embedCurrentParagraph, LinkEmbedNode } from '../editor/link-embed-node.js';
22
+ import { ImageNode } from '../editor/image-node.js';
23
+ import { safeHttpUrl } from '../urls.js';
21
24
  import { linkEmbedOptions, selectLinkEmbeds } from '../embeds/context.js';
22
25
  import { resolveLinkEmbed } from '../embeds/resolve.js';
23
26
  import type { LinkEmbed } from '../embeds/types.js';
@@ -38,6 +41,19 @@
38
41
  json: JSONContent;
39
42
  };
40
43
 
44
+ /** Image support for article Markdown. */
45
+ export type RichTextEditorImages = {
46
+ /**
47
+ * Store a pasted, dropped or picked file and return the destination to write in the
48
+ * Markdown: a URL, or the app's own reference such as `local:1`.
49
+ */
50
+ upload?: (file: File) => Promise<string>;
51
+ /** The address to load a destination from, for those that are not HTTP(S). */
52
+ src?: (url: string) => string | undefined;
53
+ /** Label of the description field below an image. */
54
+ altLabel?: string;
55
+ };
56
+
41
57
  export type RichTextEditorProps = {
42
58
  /** Markdown source with `markdown`, otherwise plain text. */
43
59
  value?: string;
@@ -48,9 +64,18 @@
48
64
  placeholder?: string;
49
65
  /**
50
66
  * Notion-like editing of the kit's Markdown: type `# `, `- `, `> `, `**bold**` and so on
51
- * and see the result. Without it the text is plain, as in a post.
67
+ * and see the result. Without it the text is plain, as in a post. `'article'` is standard
68
+ * Markdown for long-form writing: newlines inside a paragraph wrap, and images and tables
69
+ * are kept. Parse and write such text with `article` too.
52
70
  */
53
- markdown?: boolean;
71
+ markdown?: boolean | 'article';
72
+ /** With `markdown="article"`: how images are stored and loaded. */
73
+ images?: RichTextEditorImages;
74
+ /**
75
+ * With `markdown="article"`: a menu of blocks on typing `/`, formatting and links for
76
+ * selected text (Cmd/Ctrl+K edits a link), and on touch screens a toolbar above the keyboard.
77
+ */
78
+ menus?: boolean;
54
79
  /**
55
80
  * Show an embeddable link alone on its line as its embed, as `RichText` does: `true` for
56
81
  * the app's embeds (see `setLinkEmbeds`) or an explicit list.
@@ -72,6 +97,8 @@
72
97
  label,
73
98
  placeholder = '',
74
99
  markdown = false,
100
+ images,
101
+ menus = false,
75
102
  embeds = false,
76
103
  singleLine = false,
77
104
  disabled = false,
@@ -86,7 +113,7 @@
86
113
  let embedList = $derived(singleLine ? [] : selectLinkEmbeds(embeds, embedContext()));
87
114
  const isEmbed = (url: string) => !!resolveLinkEmbed(url, embedList);
88
115
 
89
- let host: HTMLDivElement;
116
+ let host = $state<HTMLDivElement>();
90
117
  let element: HTMLDivElement;
91
118
  /** The text the editor's content stands for; `value` differing from it is an outside change. */
92
119
  let current = untrack(() => value);
@@ -94,23 +121,66 @@
94
121
  let currentFacets = untrack(() => JSON.stringify(facets ?? null));
95
122
  /** Loaded with the Markdown blocks, so plain-text editors never download them. */
96
123
  let markdownTools: typeof import('../editor/markdown.js') | undefined;
124
+ /** Loaded with the menus, for the editors that have them. */
125
+ let menuTools = $state.raw<typeof import('../editor/article-menus.js')>();
126
+ let picker = $state<HTMLInputElement>();
127
+
128
+ const article = untrack(() => markdown === 'article');
129
+ const withMenus = untrack(() => article && menus);
130
+ /** What the menus' commands can use; read when a command runs. */
131
+ const commandContext = {
132
+ get pickImages() {
133
+ return images?.upload && !disabled ? () => picker?.click() : undefined;
134
+ }
135
+ };
136
+ const imageSrc = (url: string) => safeHttpUrl(url) ?? images?.src?.(url);
97
137
 
98
138
  function load(text: string, textFacets?: unknown): JSONContent {
99
139
  const document = markdownTools
100
- ? markdownTools.parseMarkdown(text, { facets: textFacets, detectLinks: true })
140
+ ? markdownTools.parseMarkdown(text, {
141
+ facets: textFacets,
142
+ detectLinks: true,
143
+ article,
144
+ allowImage: (url) => !!images?.src?.(url)
145
+ })
101
146
  : parsePlainText(text, { facets: textFacets });
102
147
  const content = documentToEditor(document, embedList.length ? isEmbed : undefined);
103
- // Leave somewhere to type after a trailing embed.
104
- if (content.content?.at(-1)?.type === LINK_EMBED) content.content.push({ type: 'paragraph' });
148
+ // Leave somewhere to type after a trailing embed, image or table.
149
+ const last = content.content?.at(-1)?.type;
150
+ if (last === LINK_EMBED || last === IMAGE || last === 'table')
151
+ content.content!.push({ type: 'paragraph' });
105
152
  return content;
106
153
  }
107
154
 
108
155
  function read(json: JSONContent): RichTextEditorContent {
109
156
  if (!markdownTools) return { ...editorJsonToBlueskyPost(json), json };
110
- const text = markdownTools.richTextToMarkdown(editorToDocument(json));
157
+ const text = markdownTools.richTextToMarkdown(editorToDocument(json), { article });
111
158
  return { text, facets: markdownFacets(text, json), json };
112
159
  }
113
160
 
161
+ function imageFiles(data: DataTransfer | null | undefined): File[] {
162
+ return article && images?.upload
163
+ ? Array.from(data?.files ?? []).filter((file) => file.type.startsWith('image/'))
164
+ : [];
165
+ }
166
+
167
+ /** Store files with `images.upload` and insert them at `position`, or at the cursor. */
168
+ export async function insertImages(files: readonly File[], position?: number): Promise<void> {
169
+ const upload = images?.upload;
170
+ if (!editor || !article || !upload || disabled) return;
171
+ const instance = editor;
172
+ // A file the app could not store is left out; telling the user is up to `upload`.
173
+ const stored = (await Promise.allSettled(files.map((file) => upload(file)))).flatMap(
174
+ (result) =>
175
+ result.status === 'fulfilled' && result.value
176
+ ? [{ type: IMAGE, attrs: { url: result.value, alt: '', title: '' } }]
177
+ : []
178
+ );
179
+ if (instance.isDestroyed || !stored.length) return;
180
+ const at = Math.min(position ?? instance.state.selection.to, instance.state.doc.content.size);
181
+ instance.chain().focus().insertContentAt(at, stored).run();
182
+ }
183
+
114
184
  function paste(instance: Editor, text: string): void {
115
185
  if (singleLine) {
116
186
  const cleaned = text.replace(/[\r\n]+/g, ' ');
@@ -152,7 +222,14 @@
152
222
  // The same look as `RichText`, so that what is typed is what will be shown.
153
223
  // Nothing here reaches into an embed, which brings its own lists, links and code.
154
224
  const markdownClass =
155
- 'space-y-3 leading-relaxed whitespace-pre-wrap [&_strong:not([data-link-embed]_*)]:font-semibold [&_h1:not([data-link-embed]_*)]:text-xl [&_h2:not([data-link-embed]_*)]:text-lg [&_:is(h1,h2,h3,h4,h5,h6):not([data-link-embed]_*)]:leading-snug [&_:is(h1,h2,h3,h4,h5,h6):not([data-link-embed]_*)]:font-semibold [&_blockquote:not([data-link-embed]_*)]:space-y-3 [&_blockquote:not([data-link-embed]_*)]:border-l-2 [&_blockquote:not([data-link-embed]_*)]:border-base-300 [&_blockquote:not([data-link-embed]_*)]:pl-4 dark:[&_blockquote:not([data-link-embed]_*)]:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))] [&_:is(ul,ol):not([data-link-embed]_*)]:space-y-1 [&_:is(ul,ol):not([data-link-embed]_*)]:pl-6 [&_ul:not([data-link-embed]_*)]:list-disc [&_ol:not([data-link-embed]_*)]:list-decimal [&_li:not([data-link-embed]_*)]:space-y-3 [&_:not(pre)>code:not([data-link-embed]_*)]:rounded [&_:not(pre)>code:not([data-link-embed]_*)]:bg-[color-mix(in_srgb,var(--base-100)_75%,var(--base-200))] [&_:not(pre)>code:not([data-link-embed]_*)]:px-1 [&_:not(pre)>code:not([data-link-embed]_*)]:py-0.5 [&_:not(pre)>code:not([data-link-embed]_*)]:font-mono [&_:not(pre)>code:not([data-link-embed]_*)]:text-[0.875em] dark:[&_:not(pre)>code:not([data-link-embed]_*)]:bg-base-950 [&_pre:not([data-link-embed]_*)]:overflow-x-auto [&_pre:not([data-link-embed]_*)]:rounded-md [&_pre:not([data-link-embed]_*)]:bg-[color-mix(in_srgb,var(--base-100)_75%,var(--base-200))] [&_pre:not([data-link-embed]_*)]:p-3 [&_pre:not([data-link-embed]_*)]:font-mono [&_pre:not([data-link-embed]_*)]:text-[0.875em] dark:[&_pre:not([data-link-embed]_*)]:bg-base-950 [&_hr:not([data-link-embed]_*)]:border-base-300 dark:[&_hr:not([data-link-embed]_*)]:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))] [&_a:not([data-link-embed]_*)]:text-accent-700 [&_a:not([data-link-embed]_*)]:underline [&_a:not([data-link-embed]_*)]:decoration-accent-700/40 [&_a:not([data-link-embed]_*)]:underline-offset-2 dark:[&_a:not([data-link-embed]_*)]:text-accent-300 dark:[&_a:not([data-link-embed]_*)]:decoration-accent-300/40';
225
+ 'space-y-3 leading-relaxed whitespace-pre-wrap [&_strong:not([data-link-embed]_*)]:font-semibold [&_h1:not([data-link-embed]_*)]:text-xl [&_h2:not([data-link-embed]_*)]:text-lg [&_:is(h1,h2,h3,h4,h5,h6):not([data-link-embed]_*)]:leading-snug [&_:is(h1,h2,h3,h4,h5,h6):not([data-link-embed]_*)]:font-semibold [&_blockquote:not([data-link-embed]_*)]:space-y-3 [&_blockquote:not([data-link-embed]_*)]:border-l-2 [&_blockquote:not([data-link-embed]_*)]:border-base-300 [&_blockquote:not([data-link-embed]_*)]:pl-4 dark:[&_blockquote:not([data-link-embed]_*)]:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))] [&_:is(ul,ol):not([data-link-embed]_*)]:space-y-1 [&_:is(ul,ol):not([data-link-embed]_*)]:pl-6 [&_ul:not([data-link-embed]_*)]:list-disc [&_ol:not([data-link-embed]_*)]:list-decimal [&_li:not([data-link-embed]_*)]:space-y-3 [&_:not(pre)>code:not([data-link-embed]_*)]:rounded [&_:not(pre)>code:not([data-link-embed]_*)]:bg-[color-mix(in_srgb,var(--base-100)_75%,var(--base-200))] [&_:not(pre)>code:not([data-link-embed]_*)]:px-1 [&_:not(pre)>code:not([data-link-embed]_*)]:py-0.5 [&_:not(pre)>code:not([data-link-embed]_*)]:font-mono [&_:not(pre)>code:not([data-link-embed]_*)]:text-[0.875em] dark:[&_:not(pre)>code:not([data-link-embed]_*)]:bg-base-950 [&_pre:not([data-link-embed]_*)]:overflow-x-auto [&_pre:not([data-link-embed]_*)]:rounded-md [&_pre:not([data-link-embed]_*)]:bg-[color-mix(in_srgb,var(--base-100)_75%,var(--base-200))] [&_pre:not([data-link-embed]_*)]:p-3 [&_pre:not([data-link-embed]_*)]:font-mono [&_pre:not([data-link-embed]_*)]:text-[0.875em] dark:[&_pre:not([data-link-embed]_*)]:bg-base-950 [&_hr:not([data-link-embed]_*)]:border-base-300 dark:[&_hr:not([data-link-embed]_*)]:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))] [&_a:not([data-link-embed]_*)]:text-accent-700 [&_a:not([data-link-embed]_*)]:underline [&_a:not([data-link-embed]_*)]:decoration-accent-700/40 [&_a:not([data-link-embed]_*)]:underline-offset-2 dark:[&_a:not([data-link-embed]_*)]:text-accent-300 dark:[&_a:not([data-link-embed]_*)]:decoration-accent-300/40 [&_[data-image]]:whitespace-normal [&_[data-image]>img]:max-w-full [&_[data-image]>img]:rounded-md [&_[data-image]>input]:mt-1 [&_[data-image]>input]:block [&_[data-image]>input]:w-full [&_[data-image]>input]:border-0 [&_[data-image]>input]:bg-transparent [&_[data-image]>input]:p-0 [&_[data-image]>input]:text-sm [&_[data-image]>input]:text-base-600 [&_[data-image]>input]:outline-none [&_[data-image]>input]:placeholder:text-base-500 [&_[data-image]>input]:focus:ring-0 dark:[&_[data-image]>input]:text-base-400 [&_.tableWrapper]:overflow-x-auto [&_table]:border-collapse [&_table]:text-left [&_table]:whitespace-normal [&_:is(th,td)]:border [&_:is(th,td)]:border-base-300 [&_:is(th,td)]:px-3 [&_:is(th,td)]:py-1.5 [&_:is(th,td)]:align-top [&_:is(th,td)]:min-w-16 dark:[&_:is(th,td)]:border-[color-mix(in_srgb,var(--base-800)_80%,var(--base-950))] [&_th]:font-semibold [&_.selectedCell]:bg-accent-500/10';
226
+ // Task lists, math and footnotes of article Markdown.
227
+ const articleClass =
228
+ "[&_li[data-task]]:relative [&_li[data-task]]:list-none [&_li[data-task]]:before:absolute [&_li[data-task]]:before:-left-5 [&_li[data-task=false]]:before:content-['☐'] [&_li[data-task=true]]:before:content-['☑'] [&_ul[data-type=taskList]]:list-none! [&_ul[data-type=taskList]]:pl-0! [&_ul[data-type=taskList]>li]:flex [&_ul[data-type=taskList]>li]:gap-2 [&_ul[data-type=taskList]>li>label]:mt-0.5 [&_ul[data-type=taskList]>li>div]:min-w-0 [&_ul[data-type=taskList]>li>div]:flex-1 [&_ul[data-type=taskList]>li>div]:space-y-3 [&_ul[data-type=taskList]_input]:accent-accent-600 [&_[data-math]]:font-mono [&_[data-math]]:text-[0.875em] [&_[data-math]]:text-accent-700 [&_[data-math]]:before:content-['$'] [&_[data-math]]:after:content-['$'] [&_[data-math]]:before:opacity-50 [&_[data-math]]:after:opacity-50 dark:[&_[data-math]]:text-accent-300 [&_[data-footnote-ref]]:text-accent-700 dark:[&_[data-footnote-ref]]:text-accent-300 [&_[data-footnote]]:relative [&_[data-footnote]]:space-y-3 [&_[data-footnote]]:pl-10 [&_[data-footnote]]:text-[0.9em] [&_[data-footnote]]:before:absolute [&_[data-footnote]]:before:left-0 [&_[data-footnote]]:before:text-base-500 [&_[data-footnote]]:before:content-['['_attr(data-footnote)_']']";
229
+
230
+ // An empty line says how to get the menu, while it is the one being written.
231
+ const hintClass =
232
+ '[&.ProseMirror-focused>p.is-empty:not(.is-editor-empty)]:before:pointer-events-none [&.ProseMirror-focused>p.is-empty:not(.is-editor-empty)]:before:float-left [&.ProseMirror-focused>p.is-empty:not(.is-editor-empty)]:before:h-0 [&.ProseMirror-focused>p.is-empty:not(.is-editor-empty)]:before:text-base-400 [&.ProseMirror-focused>p.is-empty:not(.is-editor-empty)]:before:content-[attr(data-placeholder)] dark:[&.ProseMirror-focused>p.is-empty:not(.is-editor-empty)]:before:text-base-600';
156
233
 
157
234
  onMount(() => {
158
235
  let instance: Editor | undefined;
@@ -163,9 +240,29 @@
163
240
  element,
164
241
  extensions: [
165
242
  ...(markdownTools
166
- ? markdownTools.markdownExtensions()
243
+ ? [
244
+ ...markdownTools.markdownExtensions(article),
245
+ ...(article
246
+ ? [
247
+ ImageNode.configure({
248
+ src: imageSrc,
249
+ altLabel: images?.altLabel ?? 'Alt text'
250
+ })
251
+ ]
252
+ : [])
253
+ ]
167
254
  : ([Document, Paragraph, Text, HardBreak, History] as AnyExtension[])),
168
- Placeholder.configure({ placeholder }),
255
+ Placeholder.configure({
256
+ placeholder: menuTools
257
+ ? ({ editor: current, node }) =>
258
+ current.isEmpty
259
+ ? placeholder
260
+ : node.type.name === 'paragraph'
261
+ ? 'Type / for commands'
262
+ : ''
263
+ : placeholder
264
+ }),
265
+ ...(menuTools ? [menuTools.slashMenu({ layer: host!, context: commandContext })] : []),
169
266
  DetectedTokens.configure({ class: linkClass }),
170
267
  ...(embeds && !singleLine
171
268
  ? [
@@ -183,7 +280,7 @@
183
280
  Mention.configure({
184
281
  HTMLAttributes: { class: linkClass },
185
282
  suggestion: searchActors
186
- ? mentionSuggestions(searchActors, () => host)
283
+ ? mentionSuggestions(searchActors, () => host!)
187
284
  : { allow: () => false }
188
285
  })
189
286
  ],
@@ -193,6 +290,13 @@
193
290
  ),
194
291
  editable: !disabled,
195
292
  editorProps: {
293
+ // The line being written stays clear of the toolbar along the bottom of a touch screen.
294
+ ...(menuTools
295
+ ? {
296
+ scrollMargin: { top: 8, right: 8, bottom: 72, left: 8 },
297
+ scrollThreshold: { top: 0, right: 0, bottom: 64, left: 0 }
298
+ }
299
+ : {}),
196
300
  attributes: {
197
301
  id,
198
302
  role: searchActors ? 'combobox' : 'textbox',
@@ -206,7 +310,9 @@
206
310
  : { 'aria-multiline': String(!singleLine) }),
207
311
  class: cn(
208
312
  editorClass,
209
- markdownTools ? markdownClass : 'whitespace-pre-wrap [&_[data-link-embed]]:my-3'
313
+ markdownTools ? markdownClass : 'whitespace-pre-wrap [&_[data-link-embed]]:my-3',
314
+ article && articleClass,
315
+ menuTools && hintClass
210
316
  )
211
317
  },
212
318
  handleKeyDown: (view, event) =>
@@ -217,11 +323,27 @@
217
323
  transformPastedText: (text) => (singleLine ? text.replace(/[\r\n]+/g, ' ') : text),
218
324
  // Accept text only, read as Markdown where the editor supports it.
219
325
  handlePaste: (_view, event) => {
326
+ const files = imageFiles(event.clipboardData);
327
+ if (files.length) {
328
+ event.preventDefault();
329
+ void insertImages(files);
330
+ return true;
331
+ }
220
332
  const text = event.clipboardData?.getData('text/plain');
221
333
  if (text === undefined) return false;
222
334
  event.preventDefault();
223
335
  paste(created, text);
224
336
  return true;
337
+ },
338
+ handleDOMEvents: {
339
+ drop: (view, event) => {
340
+ const files = imageFiles(event.dataTransfer);
341
+ if (!files.length) return false;
342
+ event.preventDefault();
343
+ const at = view.posAtCoords({ left: event.clientX, top: event.clientY });
344
+ void insertImages(files, at?.pos);
345
+ return true;
346
+ }
225
347
  }
226
348
  },
227
349
  onUpdate: ({ editor: updated }) => {
@@ -235,8 +357,12 @@
235
357
  editor = created;
236
358
  };
237
359
  if (markdown)
238
- void import('../editor/markdown.js').then((module) => {
360
+ void Promise.all([
361
+ import('../editor/markdown.js'),
362
+ withMenus ? import('../editor/article-menus.js') : undefined
363
+ ]).then(([module, menuModule]) => {
239
364
  markdownTools = module;
365
+ menuTools = menuModule;
240
366
  create();
241
367
  });
242
368
  else create();
@@ -269,4 +395,20 @@
269
395
  data-slot="rich-text-editor"
270
396
  >
271
397
  <div bind:this={element}></div>
398
+ {#if menuTools && editor && host}
399
+ <menuTools.EditorMenus {editor} context={commandContext} />
400
+ {#if images?.upload}
401
+ <input
402
+ bind:this={picker}
403
+ type="file"
404
+ accept="image/*"
405
+ multiple
406
+ hidden
407
+ onchange={() => {
408
+ if (picker?.files?.length) void insertImages(Array.from(picker.files));
409
+ if (picker) picker.value = '';
410
+ }}
411
+ />
412
+ {/if}
413
+ {/if}
272
414
  </div>
@@ -13,6 +13,18 @@ export type RichTextEditorContent = {
13
13
  facets: Facet[];
14
14
  json: JSONContent;
15
15
  };
16
+ /** Image support for article Markdown. */
17
+ export type RichTextEditorImages = {
18
+ /**
19
+ * Store a pasted, dropped or picked file and return the destination to write in the
20
+ * Markdown: a URL, or the app's own reference such as `local:1`.
21
+ */
22
+ upload?: (file: File) => Promise<string>;
23
+ /** The address to load a destination from, for those that are not HTTP(S). */
24
+ src?: (url: string) => string | undefined;
25
+ /** Label of the description field below an image. */
26
+ altLabel?: string;
27
+ };
16
28
  export type RichTextEditorProps = {
17
29
  /** Markdown source with `markdown`, otherwise plain text. */
18
30
  value?: string;
@@ -23,9 +35,18 @@ export type RichTextEditorProps = {
23
35
  placeholder?: string;
24
36
  /**
25
37
  * Notion-like editing of the kit's Markdown: type `# `, `- `, `> `, `**bold**` and so on
26
- * and see the result. Without it the text is plain, as in a post.
38
+ * and see the result. Without it the text is plain, as in a post. `'article'` is standard
39
+ * Markdown for long-form writing: newlines inside a paragraph wrap, and images and tables
40
+ * are kept. Parse and write such text with `article` too.
41
+ */
42
+ markdown?: boolean | 'article';
43
+ /** With `markdown="article"`: how images are stored and loaded. */
44
+ images?: RichTextEditorImages;
45
+ /**
46
+ * With `markdown="article"`: a menu of blocks on typing `/`, formatting and links for
47
+ * selected text (Cmd/Ctrl+K edits a link), and on touch screens a toolbar above the keyboard.
27
48
  */
28
- markdown?: boolean;
49
+ menus?: boolean;
29
50
  /**
30
51
  * Show an embeddable link alone on its line as its embed, as `RichText` does: `true` for
31
52
  * the app's embeds (see `setLinkEmbeds`) or an explicit list.
@@ -39,6 +60,8 @@ export type RichTextEditorProps = {
39
60
  onupdate?: (content: RichTextEditorContent) => void;
40
61
  class?: string;
41
62
  };
42
- declare const RichTextEditor: import("svelte").Component<RichTextEditorProps, {}, "value" | "editor">;
63
+ declare const RichTextEditor: import("svelte").Component<RichTextEditorProps, {
64
+ insertImages: (files: readonly File[], position?: number) => Promise<void>;
65
+ }, "value" | "editor">;
43
66
  type RichTextEditor = ReturnType<typeof RichTextEditor>;
44
67
  export default RichTextEditor;