svelte-rtf-editor 1.8.2 → 1.9.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.
- package/README.md +96 -7
- package/dist/RtfViewer.svelte +63 -7
- package/dist/RtfViewer.svelte.d.ts +2 -1
- package/dist/components/InkEditor.svelte +61 -2
- package/dist/components/InkEditor.svelte.d.ts +2 -0
- package/dist/images.d.ts +9 -2
- package/dist/images.js +27 -7
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/rtf-parser.d.ts +16 -3
- package/dist/rtf-parser.js +1100 -457
- package/dist/rtf-writer.d.ts +27 -4
- package/dist/rtf-writer.js +659 -298
- package/dist/table-model.d.ts +42 -0
- package/dist/table-model.js +139 -0
- package/dist/utils.js +160 -17
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -110,6 +110,7 @@ Pass an HTML string as `content`. If the content is already RTF, convert it firs
|
|
|
110
110
|
| `content` | `string` | — | Raw RTF string to parse and display |
|
|
111
111
|
| `fontFamily` | `string` | `'Arial'` | Font the document is shown in |
|
|
112
112
|
| `fontSize` | `number` | `12` | Body text size in points |
|
|
113
|
+
| `maxRtfBytes` | `number` | `52428800` | The largest document it reads (50 MB); `0` reads any size. See [Size limit on import](#size-limit-on-import) |
|
|
113
114
|
|
|
114
115
|
---
|
|
115
116
|
|
|
@@ -129,6 +130,7 @@ Pass an HTML string as `content`. If the content is already RTF, convert it firs
|
|
|
129
130
|
| `readonly` | `boolean` | `false` | Disable editing |
|
|
130
131
|
| `maxImageEdge` | `number` | `1600` | Longest edge (px) an inserted image is scaled down to; `0` keeps full size |
|
|
131
132
|
| `maxImageBytes` | `number` | `524288` | Encoded byte ceiling per image; oversized pictures are re-encoded until they fit. `0` disables |
|
|
133
|
+
| `maxRtfBytes` | `number` | `52428800` | The largest RTF file Import reads (50 MB); `0` reads any size |
|
|
132
134
|
| `maxImageDisplayWidth` | `number` | `624` | Width (px) a newly inserted image is displayed at, unless the column is narrower — 6.5in of page. `0` fills the column |
|
|
133
135
|
| `fontFamily` | `string` | `'Arial'` | Document font, on screen and in the RTF. See [Fonts](#fonts) |
|
|
134
136
|
| `fontSize` | `number` | `12` | Body text size in points, on screen and in the RTF |
|
|
@@ -163,18 +165,18 @@ editor.importRtf() // → void — open the file picker to import .rtf
|
|
|
163
165
|
```ts
|
|
164
166
|
import {
|
|
165
167
|
rtfToHtml, htmlToRtf, estimateRtfBytes, readRtfFile, htmlToMarkdown, downloadFile,
|
|
166
|
-
DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, isSafeLinkUrl
|
|
168
|
+
DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_MAX_RTF_BYTES, isSafeLinkUrl
|
|
167
169
|
} from 'svelte-rtf-editor';
|
|
168
170
|
```
|
|
169
171
|
|
|
170
172
|
| Function | Description |
|
|
171
173
|
|---------------------------------------|----------------------------------------------------|
|
|
172
|
-
| `rtfToHtml(rtf: string, options?: { fontSize? }): string` | Parse an RTF string and return an HTML string. `fontSize` is the size of the screen it will be shown on (default 12) |
|
|
174
|
+
| `rtfToHtml(rtf: string, options?: { fontSize?, maxBytes? }): string` | Parse an RTF string and return an HTML string. `fontSize` is the size of the screen it will be shown on (default 12). Throws a `RangeError` for a string longer than `maxBytes` (default 50 MB; see [Size limit on import](#size-limit-on-import)) |
|
|
173
175
|
| `htmlToRtf(el: HTMLElement, options?: { fontFamily?, fontSize? }): string` | Convert a DOM element's content to RTF, in Arial 12 pt unless told otherwise |
|
|
174
176
|
| `estimateRtfBytes(el: HTMLElement): number` | Approximate RTF size of a DOM element without converting it |
|
|
175
|
-
| `isSafeLinkUrl(url: string): boolean` | Whether a link address is a web, mail or phone address; `htmlToRtf`
|
|
176
|
-
| `readRtfFile(file: File): Promise<string>` | Read a `.rtf` File object and return HTML
|
|
177
|
-
| `htmlToMarkdown(el: HTMLElement): string` | Convert a DOM element's content to Markdown
|
|
177
|
+
| `isSafeLinkUrl(url: string): boolean` | Whether a link address is a web, mail or phone address; `htmlToRtf` and `htmlToMarkdown` write any other link as its text alone, and `rtfToHtml` reads any other as text |
|
|
178
|
+
| `readRtfFile(file: File, options?: { fontSize?, maxBytes? }): Promise<string>` | Read a `.rtf` File object and return HTML. Rejects, without reading it, for a file larger than `maxBytes` |
|
|
179
|
+
| `htmlToMarkdown(el: HTMLElement): string` | Convert a DOM element's content to Markdown. See [Markdown export](#markdown-export) |
|
|
178
180
|
| `downloadFile(name, content, mime): void` | Trigger a file download in the browser |
|
|
179
181
|
|
|
180
182
|
---
|
|
@@ -223,6 +225,72 @@ A `<p>` or `<div>` keeps its own indents, spacing and tab stops in the RTF, so a
|
|
|
223
225
|
- A heading outside a table cell also writes its right and first-line indents, so a heading read from RTF with a hanging number goes back as it came. A picture is read with a left margin only, where its line starts.
|
|
224
226
|
- `rtfToHtml` does not yet read spacing, keep-with-next or tab stops back.
|
|
225
227
|
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## What is written, and what is read back
|
|
231
|
+
|
|
232
|
+
`htmlToRtf` writes each construct below as the RTF beside it, and `rtfToHtml` reads that RTF back as the same HTML, so a document saved, reloaded and saved again is the same RTF. Where a reload changes how something is written, it changes once and then stays: nothing drifts from save to save.
|
|
233
|
+
|
|
234
|
+
| HTML | RTF | Read back as |
|
|
235
|
+
|---|---|---|
|
|
236
|
+
| `<h1>`, `<h2>`, `<h3>` | a bold paragraph at 2, 1.5 and 7/6 of the body size | the same heading, with nothing inside it but its text |
|
|
237
|
+
| `<h4>`, `<h5>`, `<h6>` (pasted text) | a bold paragraph at 1, 5/6 and 2/3 of the body size | a bold paragraph |
|
|
238
|
+
| `<ul>`, `<ol>` | one paragraph per item: `\li720\fi-360`, then `\bullet\tab` or `1.\tab` | `<ul>`, `<ol>` |
|
|
239
|
+
| a list inside a list item | the same, `\li720` further in for each level | a list inside the item |
|
|
240
|
+
| `<ol start="5">` | `5.\tab`, `6.\tab`, … | `<ol start="5">` |
|
|
241
|
+
| `<a href="https://…">` | `{\field{\*\fldinst HYPERLINK "…"}{\fldrslt …}}`, underlined, in the link color | `<a href="https://…" target="_blank" rel="noopener noreferrer">` |
|
|
242
|
+
| `<code>` | `\f1` (Courier New) | `<code>` |
|
|
243
|
+
| `<pre>` | a paragraph in `\f1` at 5/6 of the body size, lines separated by `\line` | `<pre>` |
|
|
244
|
+
| `<hr>` | a centered line of twenty em dashes | `<hr>` |
|
|
245
|
+
| `<hr style="break-after:page">` | `\page` | the same |
|
|
246
|
+
| `<blockquote>` | paragraphs indented half an inch, in italics | indented italic paragraphs |
|
|
247
|
+
| `<table>` | one `\trowd … \row` per row; see [Tables](#tables) | `<table>` |
|
|
248
|
+
| `<br>` | `\line` | `<br>` |
|
|
249
|
+
|
|
250
|
+
- **Lists.** Only the shape above is read back as a list: a bullet or `N.`, a tab, and a paragraph that hangs by 360 twips and has no right indent or alignment of its own. Word's lists have that shape and are read as lists, including the bullet it writes in a `{\listtext}` group. Anything else stays the paragraph it is, marker and all, because it could not be written back the same: a line typed as `- Invasive adenocarcinoma.`, a list hung by another distance, one marked `a.` or `1)`, a centered one. A list in a table cell is read as lines of text.
|
|
251
|
+
- **List items.** A paragraph inside an item (`<li><p>…</p></li>`, as Word and Google Docs paste a list) is the item's text; a second paragraph in the item is a line under it. A list written straight inside a list (`<ul><ul>`) is one level deeper. An item with no list around it is written as a bulleted line. The list a browser's own list command makes, which the toolbar's list buttons run, is left inside the paragraph it was made from (`<p><ul>…</ul></p>`); it is written as the list alone.
|
|
252
|
+
- **Headings.** A paragraph is read as a heading when all of its text is at a heading's size, and at a body size other than 12 pt when all of it is bold too. A large word in an ordinary paragraph is a large word. A heading set larger than its level keeps that size.
|
|
253
|
+
- **Links.** A link is read back only for an address `isSafeLinkUrl` accepts, the same test the writer applies: an absolute web, mail or phone address. A field with a `javascript:`, `data:` or `file:` address, a relative or network path, or a link to a bookmark is read as its text alone. A web link opens in a tab of its own, so a click in `RtfViewer` does not replace your application. A document with a link carries the link color as the first entry of its color table (`\red0\green0\blue255`); a document without one is written as before.
|
|
254
|
+
- **Code.** Text in a monospace font other than the document's own font is read as code, and a paragraph set wholly in it at the code block size as a code block. In a document whose own font is monospace, nothing is.
|
|
255
|
+
- **Line breaks.** The `<br>` a browser leaves at the end of a paragraph, a list item or a table cell shows as nothing and is not written. A line break that does end a paragraph in the RTF (`\line\par`) is read as `<br><br>`, which a browser shows as that empty last line.
|
|
256
|
+
- **Page breaks.** `\page` is read as a rule that is shown dashed and written back as `\page`, so a page break in a document that passes through the editor is still one.
|
|
257
|
+
|
|
258
|
+
### Tables
|
|
259
|
+
|
|
260
|
+
RTF has no table element: each row says where its cells end (`\cellx`), so columns only line up if every row is written against the same edges. `htmlToRtf` works the columns out once for the table and writes every row against them.
|
|
261
|
+
|
|
262
|
+
- **`colspan`**: one cell that ends at the right edge of the last column it covers.
|
|
263
|
+
- **`rowspan`**: `\clvmgf` on the cell where it starts and an empty `\clvmrg` cell in the same columns of each row below. `rowspan="0"` reaches the last row, and no span reaches past the table.
|
|
264
|
+
- **Column widths** come from the cells' own `width` in percent. A cell across several columns gives what it has left to those of them with no width; columns with none share what remains. The table is written 6 in wide.
|
|
265
|
+
- **A column no cell starts in is not a column.** `colspan="100"` on a cell meant to cross the whole table adds none.
|
|
266
|
+
- **A row short of cells** is filled with empty ones, so its edges are the table's.
|
|
267
|
+
- **`<th>`** gets a bottom border, on that cell only, which is how `rtfToHtml` knows a header cell.
|
|
268
|
+
- **`<thead>` and `<tfoot>`** are written first and last, wherever the source has them.
|
|
269
|
+
- **A cell's `text-align`** is written on its paragraphs (`\qc`, `\qr`, `\qj`), and read back onto the cell.
|
|
270
|
+
- **A table inside a table cell** is written as lines of text in that cell: each of its rows a paragraph, its cells a tab apart. RTF can nest tables, but many readers show a nested table wrongly or not at all; every word is kept, the inner grid is not. `rtfToHtml` reads a nested table Word wrote the same way.
|
|
271
|
+
- **Reading.** `\clvmgf` and `\clvmrg` become `rowspan`; a cell that crosses the column edges of other rows gets `colspan` (as do `\clmgf` and `\clmrg`). Each paragraph in a cell is a line in it. Widths are read to a hundredth of a percent, so a column edge is written back where it was.
|
|
272
|
+
|
|
273
|
+
### Reading RTF from other programs
|
|
274
|
+
|
|
275
|
+
- `\'xx` is read as Windows-1252, the code page RTF is written in: `\'92`, the apostrophe TextEdit writes, is `’`, not an invisible control character. Other code pages (`\ansicpg1251`, `\mac`) are still read as Windows-1252.
|
|
276
|
+
- Word writes each table row's definition twice, before its cells and again before `\row`. Both are read as one row. A row with no definition repeats the one before it.
|
|
277
|
+
- `\pard` resets the paragraph, not the characters: bold, italic, underline and strikethrough carry on until `\plain` or their own `\b0`.
|
|
278
|
+
- `\sect` ends a paragraph, as `\par` does.
|
|
279
|
+
- A font table is read in both shapes: one group per font, and TextEdit's run of fonts with no groups.
|
|
280
|
+
- Damaged input does not stop a document being read: a `\'` with no hex digits after it, a `\u` out of range, half of a surrogate pair, a color component outside 0 to 255, groups nested tens of thousands deep, `\intbl` with no `\row`, a table row the file ends in the middle of.
|
|
281
|
+
|
|
282
|
+
### What `rtfToHtml` may return
|
|
283
|
+
|
|
284
|
+
`RtfViewer` puts the HTML `rtfToHtml` returns into the page as it is, so that HTML is limited to a fixed set, whatever the file holds: the elements `p`, `br`, `strong`, `em`, `u`, `s`, `sup`, `sub`, `span`, `code`, `pre`, `h1` to `h3`, `hr`, `ul`, `ol`, `li`, `a`, `table`, `tr`, `td`, `th`, `figure`, `figcaption` and `img`, and the attributes `style` (built from numbers and fixed words only), `href` (a web, mail or phone address, escaped), `target` and `rel` (fixed), `start`, `colspan` and `rowspan` (digits), and on a picture `src` (a PNG or JPEG data URL) and `alt`. Text from the file is always escaped. The test suite checks this against hostile files.
|
|
285
|
+
|
|
286
|
+
### Size limit on import
|
|
287
|
+
|
|
288
|
+
`rtfToHtml` parses a document in one go on the main thread, and a picture costs two characters per byte, so the only bound on how long a page stops responding is the size of what it is handed. A string longer than `maxBytes` (`DEFAULT_MAX_RTF_BYTES`, 50 MB) is refused with a `RangeError` before any of it is parsed; `readRtfFile` rejects a larger file without reading it, and the editor's import shows that message; `RtfViewer` shows it in place of the document. Pass `maxBytes: 0` to read a document of any size, or a smaller number to refuse sooner; the components take the same number as `maxRtfBytes`. Where reports can carry large pictures, raise it: a 30 MB picture is a document of over 60 MB.
|
|
289
|
+
|
|
290
|
+
### Markdown export
|
|
291
|
+
|
|
292
|
+
`htmlToMarkdown` writes a table as a Markdown table (a merged cell where it starts, with the cells it covers left empty, since Markdown has none), a numbered list from its `start`, and `<h4>` to `<h6>` as headings. Characters that Markdown would read as markup are escaped in text (`*`, `_`, `` ` ``, `#`, `[`, `]`, `<`, `~`, `\`, and `|` in a table cell), and so are `-`, `+`, `>` and `1.` at the start of a line: a report line typed as `- Benign.` stays that line. A link with an address `isSafeLinkUrl` refuses is written as its text alone.
|
|
293
|
+
|
|
226
294
|
## Theming
|
|
227
295
|
|
|
228
296
|
The components use CSS custom properties with sensible fallbacks, so they work out of the box but are easy to customise. Override these in your own CSS:
|
|
@@ -291,7 +359,10 @@ It stays on until **Done** in the bar, `Esc`, or the button again. Each click is
|
|
|
291
359
|
### Pasted text
|
|
292
360
|
|
|
293
361
|
A browser copies a paragraph with its looks written out as inline styles, and repeats its `id`. After a paste, each element that came in loses its `id` and any margin or first-line indent that changes nothing on screen, so a copy pasted inside the editor is the same markup as its source. A line the browser makes as a `<div>` is spaced like a `<p>`; both are written to RTF as a paragraph.
|
|
294
|
-
|
|
362
|
+
|
|
363
|
+
A picture copied with its text comes in by address (`<img src="https://…">`). The editor fetches it and holds its data in the document, as it does for an address typed in the image dialog, so it reaches the RTF as a picture. When it cannot be fetched (the site forbids it, there is no network, it takes longer than 15 seconds or is larger than 25 MB) the picture still shows and the editor says that it will export as a placeholder. The pictures in one paste are fetched at the same time, so one slow site does not hold up the others. A picture pasted as data in a format RTF cannot carry (GIF, WebP, SVG), or larger than `maxImageBytes`, is converted and scaled the same way.
|
|
364
|
+
|
|
365
|
+
Paragraph alignment (left, center, right, justify) is written to RTF as `\qc`, `\qr` or `\qj`.
|
|
295
366
|
|
|
296
367
|
Tab stays in the editor so a line can be indented. To leave the editor from the keyboard, press
|
|
297
368
|
`Esc` first. A readonly editor leaves Tab to the browser.
|
|
@@ -317,7 +388,7 @@ Images are held inline as base64 data URLs, so a document is self-contained —
|
|
|
317
388
|
- **RTF export** writes each picture as a real `\pict` group (`\pngblip` / `\jpegblip`) sized with `\picwgoal` / `\pichgoal`, so it opens with the images in Word, TextEdit and other RTF readers. The description follows as an italic line, tagged with an ignorable `{\*\inkcap}` destination that this library uses to re-attach it to the figure on import; other readers simply skip the tag.
|
|
318
389
|
- **RTF import** decodes `\pict` PNG and JPEG data (including pictures wrapped in `{\*\shppict}`) back into images at their stored size. Picture formats a browser cannot display — metafiles and device-dependent bitmaps — are skipped.
|
|
319
390
|
- **Formats**: PNG and JPEG are embedded as-is. Anything else (GIF, WebP, SVG, …) is re-encoded to PNG when inserted, since RTF carries no other bitmap types. Animated images keep their first frame.
|
|
320
|
-
- **Images added by address
|
|
391
|
+
- **Images added by address**, typed in the dialog or pasted with text copied from a web page, are fetched and inlined so they survive export. When the fetch is blocked (CORS or offline) the address is kept and the picture still displays, but it exports as an `[Image: …]` placeholder instead of picture data — the editor says so at insert time rather than letting it go unnoticed until the document is read downstream.
|
|
321
392
|
- **Size**: RTF stores picture data as hexadecimal — two characters per byte — so an embedded image costs twice its file size in the document. Resizing an image in the editor changes its display size only; two caps applied at insert time are what bound the payload:
|
|
322
393
|
- `maxImageEdge` (1600 px) scales the picture down so neither edge exceeds it.
|
|
323
394
|
- `maxImageBytes` (512 KB, so roughly 1 MB of document per image) is the ceiling that actually matters. A picture over it is re-encoded until it fits: a PNG is tried as PNG first so screenshots and diagrams stay sharp, falls back to JPEG only when it is too heavy *and* has no transparency to lose, then steps down through 80%, 64% and 50% of the target size. Whichever candidate fits first is kept.
|
|
@@ -376,6 +447,24 @@ npm run changeset
|
|
|
376
447
|
|
|
377
448
|
Commit both your code and the generated `.changeset/*.md` file together.
|
|
378
449
|
|
|
450
|
+
### Checks
|
|
451
|
+
|
|
452
|
+
Three commands must pass before a change is merged, and CI (`.github/workflows/ci.yml`) runs them on every push and pull request:
|
|
453
|
+
|
|
454
|
+
```bash
|
|
455
|
+
npm run check # svelte-check: types
|
|
456
|
+
npm test # vitest
|
|
457
|
+
npm run prepack # build the package and lint it with publint
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
The publish workflow runs the same three before it publishes, so a release cannot go out with a failing test.
|
|
461
|
+
|
|
462
|
+
`src/lib/__tests__/random-documents.test.ts` builds 400 documents at random on each run and checks what must hold for all of them: no text lost, the RTF settles after one reload, the size estimate is never low, the HTML read back is made of known elements. For a longer run, in batches:
|
|
463
|
+
|
|
464
|
+
```bash
|
|
465
|
+
RTF_RANDOM_DOCUMENTS=4000 RTF_RANDOM_FIRST=4001 npx vitest run random-documents
|
|
466
|
+
```
|
|
467
|
+
|
|
379
468
|
### Publishing a new version
|
|
380
469
|
|
|
381
470
|
When ready to cut a release:
|
package/dist/RtfViewer.svelte
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import { rtfToHtml } from "./rtf-parser.js";
|
|
2
|
+
import { rtfToHtml, DEFAULT_MAX_RTF_BYTES } from "./rtf-parser.js";
|
|
3
3
|
import {
|
|
4
4
|
cssFontFamily,
|
|
5
5
|
normalizeFontSize,
|
|
@@ -9,22 +9,37 @@
|
|
|
9
9
|
|
|
10
10
|
// fontFamily and fontSize (points) set how the document is shown, and
|
|
11
11
|
// default to the font the editor writes, so a document reads the same in
|
|
12
|
-
// the viewer as in the editor.
|
|
12
|
+
// the viewer as in the editor. maxRtfBytes is the largest document it will
|
|
13
|
+
// read (rtfToHtml's maxBytes): a picture costs two characters per byte, so
|
|
14
|
+
// raise it where reports can carry large pictures, or pass 0 for no limit.
|
|
13
15
|
let {
|
|
14
16
|
content,
|
|
15
17
|
fontFamily = DEFAULT_FONT_FAMILY,
|
|
16
|
-
fontSize = DEFAULT_FONT_SIZE
|
|
17
|
-
|
|
18
|
+
fontSize = DEFAULT_FONT_SIZE,
|
|
19
|
+
maxRtfBytes = DEFAULT_MAX_RTF_BYTES
|
|
20
|
+
}: { content: string | null | undefined; fontFamily?: string; fontSize?: number; maxRtfBytes?: number } = $props();
|
|
18
21
|
|
|
19
22
|
const screenFontFamily = $derived(cssFontFamily(fontFamily));
|
|
20
23
|
const screenFontSize = $derived(normalizeFontSize(fontSize));
|
|
21
24
|
|
|
22
|
-
|
|
25
|
+
// rtfToHtml refuses a document over its size limit by throwing. The viewer then says so in
|
|
26
|
+
// place of the document, rather than taking the page down with it.
|
|
27
|
+
const parsed = $derived.by(() => {
|
|
28
|
+
try {
|
|
29
|
+
// A report that has not loaded yet shows as an empty document.
|
|
30
|
+
return { html: rtfToHtml(content ?? '', { fontSize, maxBytes: maxRtfBytes }), error: '' };
|
|
31
|
+
} catch (err) {
|
|
32
|
+
// Only the size limit's message is meant for the reader; anything else is a fault in
|
|
33
|
+
// the reader, not something the person looking at the report can act on.
|
|
34
|
+
const message = err instanceof RangeError && /too large/.test(err.message) ? err.message : '';
|
|
35
|
+
return { html: '', error: message || 'This document could not be read' };
|
|
36
|
+
}
|
|
37
|
+
});
|
|
23
38
|
|
|
24
39
|
let copied = $state(false);
|
|
25
40
|
|
|
26
41
|
async function copyRtf() {
|
|
27
|
-
await navigator.clipboard.writeText(content);
|
|
42
|
+
await navigator.clipboard.writeText(content ?? "");
|
|
28
43
|
copied = true;
|
|
29
44
|
setTimeout(() => (copied = false), 2000);
|
|
30
45
|
}
|
|
@@ -45,7 +60,11 @@
|
|
|
45
60
|
style:font-family={screenFontFamily}
|
|
46
61
|
style:font-size="{screenFontSize}pt"
|
|
47
62
|
>
|
|
48
|
-
{
|
|
63
|
+
{#if parsed.error}
|
|
64
|
+
<p class="rtf-viewer-error" role="alert">{parsed.error}</p>
|
|
65
|
+
{:else}
|
|
66
|
+
{@html parsed.html}
|
|
67
|
+
{/if}
|
|
49
68
|
</div>
|
|
50
69
|
</div>
|
|
51
70
|
|
|
@@ -113,6 +132,43 @@
|
|
|
113
132
|
margin-bottom: 0;
|
|
114
133
|
}
|
|
115
134
|
|
|
135
|
+
.rtf-viewer-error {
|
|
136
|
+
color: var(--text-muted, #8a7e72);
|
|
137
|
+
font-style: italic;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/* A list item's text starts half an inch in, where the RTF puts it (\li720), and each
|
|
141
|
+
level is half an inch further. */
|
|
142
|
+
.rtf-viewer :global(ul),
|
|
143
|
+
.rtf-viewer :global(ol) {
|
|
144
|
+
margin: 0 0 0.2em;
|
|
145
|
+
padding-left: 36pt;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
.rtf-viewer :global(li ul),
|
|
149
|
+
.rtf-viewer :global(li ol) {
|
|
150
|
+
margin-bottom: 0;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/* Code keeps the font the RTF names for it. A code block wraps, so a long line stays in
|
|
154
|
+
the viewer. */
|
|
155
|
+
.rtf-viewer :global(code),
|
|
156
|
+
.rtf-viewer :global(pre) {
|
|
157
|
+
font-family: 'Courier New', monospace;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
.rtf-viewer :global(pre) {
|
|
161
|
+
margin: 0 0 0.2em;
|
|
162
|
+
font-size: calc(5em / 6);
|
|
163
|
+
white-space: pre-wrap;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/* A page break in the RTF (\page). */
|
|
167
|
+
.rtf-viewer :global(hr[style*='break-after']) {
|
|
168
|
+
border: 0;
|
|
169
|
+
border-top: 1px dashed currentColor;
|
|
170
|
+
}
|
|
171
|
+
|
|
116
172
|
/* Pictures decoded from \pict groups keep their stored width but never
|
|
117
173
|
overflow the viewer. */
|
|
118
174
|
.rtf-viewer :global(img) {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
type $$ComponentProps = {
|
|
2
|
-
content: string;
|
|
2
|
+
content: string | null | undefined;
|
|
3
3
|
fontFamily?: string;
|
|
4
4
|
fontSize?: number;
|
|
5
|
+
maxRtfBytes?: number;
|
|
5
6
|
};
|
|
6
7
|
declare const RtfViewer: import("svelte").Component<$$ComponentProps, {}, "">;
|
|
7
8
|
type RtfViewer = ReturnType<typeof RtfViewer>;
|
|
@@ -23,6 +23,8 @@
|
|
|
23
23
|
* which is what bounds the RTF payload — it costs two hex
|
|
24
24
|
* characters per byte. 0 disables. Default: 524288 (512 KB,
|
|
25
25
|
* about 1 MB of document per image).
|
|
26
|
+
* maxRtfBytes — The largest RTF file Import reads. Default: 52428800 (50 MB);
|
|
27
|
+
* 0 reads any size.
|
|
26
28
|
* fontFamily — Font for the document, both on screen and in the RTF.
|
|
27
29
|
* Default: 'Arial'.
|
|
28
30
|
* fontSize — Body text size in points, both on screen and in the RTF.
|
|
@@ -52,7 +54,7 @@
|
|
|
52
54
|
import Modal from './Modal.svelte';
|
|
53
55
|
import ImageOverlay from './ImageOverlay.svelte';
|
|
54
56
|
import { htmlToMarkdown, downloadFile } from '../utils.js';
|
|
55
|
-
import { readRtfFile } from '../rtf-parser.js';
|
|
57
|
+
import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
|
|
56
58
|
import {
|
|
57
59
|
htmlToRtf,
|
|
58
60
|
estimateRtfBytes,
|
|
@@ -97,6 +99,8 @@
|
|
|
97
99
|
maxImageEdge?: number;
|
|
98
100
|
maxImageBytes?: number;
|
|
99
101
|
maxImageDisplayWidth?: number;
|
|
102
|
+
/** The largest RTF file Import reads (readRtfFile's maxBytes); 0 for no limit. */
|
|
103
|
+
maxRtfBytes?: number;
|
|
100
104
|
fontFamily?: string;
|
|
101
105
|
fontSize?: number;
|
|
102
106
|
onchange?: (payload: ChangePayload) => void;
|
|
@@ -117,6 +121,7 @@
|
|
|
117
121
|
maxImageEdge = DEFAULT_MAX_IMAGE_EDGE,
|
|
118
122
|
maxImageBytes = DEFAULT_MAX_IMAGE_BYTES,
|
|
119
123
|
maxImageDisplayWidth = DEFAULT_MAX_IMAGE_DISPLAY_WIDTH,
|
|
124
|
+
maxRtfBytes = DEFAULT_MAX_RTF_BYTES,
|
|
120
125
|
fontFamily = DEFAULT_FONT_FAMILY,
|
|
121
126
|
fontSize = DEFAULT_FONT_SIZE,
|
|
122
127
|
onchange,
|
|
@@ -1316,7 +1321,7 @@
|
|
|
1316
1321
|
importing = true;
|
|
1317
1322
|
|
|
1318
1323
|
try {
|
|
1319
|
-
const html = await readRtfFile(file, { fontSize });
|
|
1324
|
+
const html = await readRtfFile(file, { fontSize, maxBytes: maxRtfBytes });
|
|
1320
1325
|
if (editorEl) {
|
|
1321
1326
|
selectedImage = null;
|
|
1322
1327
|
documentReplaced();
|
|
@@ -1564,6 +1569,53 @@
|
|
|
1564
1569
|
}
|
|
1565
1570
|
if (!el.getAttribute('style')) el.removeAttribute('style');
|
|
1566
1571
|
}
|
|
1572
|
+
// A picture copied with its text comes in by address (<img src="https://…">), or as data in
|
|
1573
|
+
// a format the RTF cannot carry (GIF, WebP, SVG) or larger than maxImageBytes. Only PNG or
|
|
1574
|
+
// JPEG data held in the document reaches the RTF, so each one goes through the same step as
|
|
1575
|
+
// the image dialog: fetched, converted and scaled as needed.
|
|
1576
|
+
const pasted = Array.from(editorEl.querySelectorAll('img')).filter((img) => !before.has(img));
|
|
1577
|
+
if (pasted.length > 0) void embedPastedImages(pasted);
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
/**
|
|
1581
|
+
* Fetch each pasted picture and hold its data in the document. One that cannot be fetched
|
|
1582
|
+
* (the site forbids it, or there is no network) still shows, but leaves in the RTF as an
|
|
1583
|
+
* "[Image: …]" placeholder: the editor says so now, rather than letting it be found downstream.
|
|
1584
|
+
*/
|
|
1585
|
+
async function embedPastedImages(images: HTMLImageElement[]): Promise<void> {
|
|
1586
|
+
let failed = 0;
|
|
1587
|
+
let changed = false;
|
|
1588
|
+
// All at once, each with its own timeout, so one slow site does not hold up the rest.
|
|
1589
|
+
await Promise.all(
|
|
1590
|
+
images.map(async (img) => {
|
|
1591
|
+
const url = img.getAttribute('src') || '';
|
|
1592
|
+
if (!isSafeImageUrl(url)) {
|
|
1593
|
+
failed++;
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
const { src, embedded } = await urlToImageSrc(url, imageLimits());
|
|
1597
|
+
// It may have been deleted or replaced while it was fetched.
|
|
1598
|
+
if (!img.isConnected || img.getAttribute('src') !== url) return;
|
|
1599
|
+
if (!embedded) {
|
|
1600
|
+
failed++;
|
|
1601
|
+
} else if (src !== url) {
|
|
1602
|
+
img.setAttribute('src', src);
|
|
1603
|
+
changed = true;
|
|
1604
|
+
}
|
|
1605
|
+
})
|
|
1606
|
+
);
|
|
1607
|
+
if (failed > 0) {
|
|
1608
|
+
showError(
|
|
1609
|
+
failed === 1
|
|
1610
|
+
? 'A pasted image could not be embedded — it will export as a placeholder'
|
|
1611
|
+
: `${failed} pasted images could not be embedded — they will export as placeholders`
|
|
1612
|
+
);
|
|
1613
|
+
}
|
|
1614
|
+
if (changed) {
|
|
1615
|
+
updateCounts();
|
|
1616
|
+
fireChange();
|
|
1617
|
+
if (autosave) scheduleAutoSave();
|
|
1618
|
+
}
|
|
1567
1619
|
}
|
|
1568
1620
|
|
|
1569
1621
|
// ── Lifecycle ──
|
|
@@ -2032,6 +2084,13 @@
|
|
|
2032
2084
|
margin: 32px 0;
|
|
2033
2085
|
}
|
|
2034
2086
|
|
|
2087
|
+
/* A page break read from RTF (\page): a dashed rule, written back as \page. */
|
|
2088
|
+
.ink-content :global(hr[style*='break-after']) {
|
|
2089
|
+
height: 0;
|
|
2090
|
+
background: none;
|
|
2091
|
+
border-top: 1px dashed var(--text-muted, #8a7e72);
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2035
2094
|
/* ── Status Bar ── */
|
|
2036
2095
|
.ink-status-bar {
|
|
2037
2096
|
display: flex;
|
|
@@ -21,6 +21,8 @@ interface Props {
|
|
|
21
21
|
maxImageEdge?: number;
|
|
22
22
|
maxImageBytes?: number;
|
|
23
23
|
maxImageDisplayWidth?: number;
|
|
24
|
+
/** The largest RTF file Import reads (readRtfFile's maxBytes); 0 for no limit. */
|
|
25
|
+
maxRtfBytes?: number;
|
|
24
26
|
fontFamily?: string;
|
|
25
27
|
fontSize?: number;
|
|
26
28
|
onchange?: (payload: ChangePayload) => void;
|
package/dist/images.d.ts
CHANGED
|
@@ -72,10 +72,17 @@ export declare function readFileAsDataUrl(file: Blob): Promise<string>;
|
|
|
72
72
|
export declare function toRtfSafeDataUrl(dataUrl: string, limits?: ImageLimits): Promise<string>;
|
|
73
73
|
/** Read an image File into a data URL the RTF writer can embed. */
|
|
74
74
|
export declare function fileToImageSrc(file: File, limits?: ImageLimits): Promise<string>;
|
|
75
|
+
/** How long a pasted or typed picture address may take to answer before it is given up on. */
|
|
76
|
+
export declare const IMAGE_FETCH_TIMEOUT_MS = 15000;
|
|
77
|
+
/** The most a fetched picture may weigh before it is scaled down: 25 MB. */
|
|
78
|
+
export declare const MAX_FETCHED_IMAGE_BYTES: number;
|
|
75
79
|
/**
|
|
76
80
|
* Resolve a URL to an embeddable data URL. Remote images are fetched so they
|
|
77
|
-
* survive export; when the fetch is blocked (CORS, offline)
|
|
78
|
-
*
|
|
81
|
+
* survive export; when the fetch is blocked (CORS, offline), takes longer than
|
|
82
|
+
* IMAGE_FETCH_TIMEOUT_MS or is larger than MAX_FETCHED_IMAGE_BYTES, the original
|
|
83
|
+
* URL is kept and the image still displays — it just exports as a text
|
|
84
|
+
* placeholder. `embedded` is true only for PNG or JPEG data, the two formats the
|
|
85
|
+
* RTF writer carries: a GIF, WebP or SVG that could not be converted is not.
|
|
79
86
|
*/
|
|
80
87
|
export declare function urlToImageSrc(url: string, limits?: ImageLimits): Promise<{
|
|
81
88
|
src: string;
|
package/dist/images.js
CHANGED
|
@@ -252,33 +252,53 @@ export async function fileToImageSrc(file, limits = {}) {
|
|
|
252
252
|
}
|
|
253
253
|
return toRtfSafeDataUrl(dataUrl, limits);
|
|
254
254
|
}
|
|
255
|
+
/** How long a pasted or typed picture address may take to answer before it is given up on. */
|
|
256
|
+
export const IMAGE_FETCH_TIMEOUT_MS = 15_000;
|
|
257
|
+
/** The most a fetched picture may weigh before it is scaled down: 25 MB. */
|
|
258
|
+
export const MAX_FETCHED_IMAGE_BYTES = 25 * 1024 * 1024;
|
|
255
259
|
/**
|
|
256
260
|
* Resolve a URL to an embeddable data URL. Remote images are fetched so they
|
|
257
|
-
* survive export; when the fetch is blocked (CORS, offline)
|
|
258
|
-
*
|
|
261
|
+
* survive export; when the fetch is blocked (CORS, offline), takes longer than
|
|
262
|
+
* IMAGE_FETCH_TIMEOUT_MS or is larger than MAX_FETCHED_IMAGE_BYTES, the original
|
|
263
|
+
* URL is kept and the image still displays — it just exports as a text
|
|
264
|
+
* placeholder. `embedded` is true only for PNG or JPEG data, the two formats the
|
|
265
|
+
* RTF writer carries: a GIF, WebP or SVG that could not be converted is not.
|
|
259
266
|
*/
|
|
260
267
|
export async function urlToImageSrc(url, limits = {}) {
|
|
261
268
|
const value = url.trim();
|
|
269
|
+
const result = (src) => ({ src, embedded: src.startsWith('data:') && sniffImageType(src) !== null });
|
|
262
270
|
if (value.startsWith('data:image/')) {
|
|
263
|
-
return
|
|
271
|
+
return result(await toRtfSafeDataUrl(value, limits));
|
|
264
272
|
}
|
|
265
273
|
// A picture that could not be inlined still displays, but it leaves the
|
|
266
274
|
// document as a text placeholder instead of picture data. The caller is told
|
|
267
275
|
// so it can say as much, rather than letting the image vanish at export.
|
|
276
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
|
|
277
|
+
const timer = controller ? setTimeout(() => controller.abort(), IMAGE_FETCH_TIMEOUT_MS) : null;
|
|
268
278
|
try {
|
|
269
|
-
const response = await fetch(value, { mode: 'cors' });
|
|
279
|
+
const response = await fetch(value, { mode: 'cors', signal: controller?.signal });
|
|
270
280
|
if (!response.ok)
|
|
271
281
|
return { src: value, embedded: false };
|
|
282
|
+
const declared = Number(response.headers?.get('content-length') ?? '');
|
|
283
|
+
if (declared > MAX_FETCHED_IMAGE_BYTES) {
|
|
284
|
+
controller?.abort();
|
|
285
|
+
return { src: value, embedded: false };
|
|
286
|
+
}
|
|
272
287
|
const blob = await response.blob();
|
|
273
|
-
if (!blob.type.startsWith('image/'))
|
|
288
|
+
if (blob.size > MAX_FETCHED_IMAGE_BYTES || !blob.type.startsWith('image/')) {
|
|
274
289
|
return { src: value, embedded: false };
|
|
290
|
+
}
|
|
275
291
|
const dataUrl = await readFileAsDataUrl(blob);
|
|
276
|
-
const
|
|
277
|
-
return { src, embedded:
|
|
292
|
+
const converted = result(await toRtfSafeDataUrl(dataUrl, limits));
|
|
293
|
+
return converted.embedded ? converted : { src: value, embedded: false };
|
|
278
294
|
}
|
|
279
295
|
catch {
|
|
280
296
|
return { src: value, embedded: false };
|
|
281
297
|
}
|
|
298
|
+
finally {
|
|
299
|
+
if (timer)
|
|
300
|
+
clearTimeout(timer);
|
|
301
|
+
}
|
|
282
302
|
}
|
|
283
303
|
/** "sunset-over-lake.png" → "sunset-over-lake" — a usable default alt text. */
|
|
284
304
|
export function stripExtension(filename) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { default as RtfViewer } from './RtfViewer.svelte';
|
|
2
2
|
export { default as InkEditor } from './components/InkEditor.svelte';
|
|
3
|
-
export { rtfToHtml, readRtfFile } from './rtf-parser.js';
|
|
3
|
+
export { rtfToHtml, readRtfFile, DEFAULT_MAX_RTF_BYTES } from './rtf-parser.js';
|
|
4
4
|
export { htmlToRtf, estimateRtfBytes, isSafeLinkUrl, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from './rtf-writer.js';
|
|
5
5
|
export type { RtfWriteOptions } from './rtf-writer.js';
|
|
6
6
|
export type { RtfReadOptions } from './rtf-parser.js';
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
export { default as RtfViewer } from './RtfViewer.svelte';
|
|
3
3
|
export { default as InkEditor } from './components/InkEditor.svelte';
|
|
4
4
|
// RTF utilities
|
|
5
|
-
export { rtfToHtml, readRtfFile } from './rtf-parser.js';
|
|
5
|
+
export { rtfToHtml, readRtfFile, DEFAULT_MAX_RTF_BYTES } from './rtf-parser.js';
|
|
6
6
|
export { htmlToRtf, estimateRtfBytes, isSafeLinkUrl, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from './rtf-writer.js';
|
|
7
7
|
export { htmlToMarkdown, downloadFile } from './utils.js';
|
package/dist/rtf-parser.d.ts
CHANGED
|
@@ -4,12 +4,19 @@
|
|
|
4
4
|
* Parses RTF control words and groups into an HTML string.
|
|
5
5
|
* Supports: bold, italic, underline, strikethrough, super/subscript,
|
|
6
6
|
* font size, foreground color (\cf), highlight background color (\highlight),
|
|
7
|
-
* color table, font table, paragraphs
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* color table, font table (monospace text reads as code), paragraphs with their
|
|
8
|
+
* alignment and indents, headings, bullet/numbered lists, hyperlinks, tables with
|
|
9
|
+
* merged cells, embedded pictures (\pict PNG/JPEG blips, with captions),
|
|
10
|
+
* Unicode characters, Windows-1252 hex escapes, and nested groups.
|
|
10
11
|
*
|
|
11
12
|
* \cb (character background) is silently ignored on import.
|
|
12
13
|
*/
|
|
14
|
+
/**
|
|
15
|
+
* The largest RTF string rtfToHtml reads unless told otherwise: 50 MB. A document is parsed in
|
|
16
|
+
* one go on the main thread, and a picture is decoded from two characters per byte, so the size
|
|
17
|
+
* of what is handed in is the only bound on how long the page stops responding.
|
|
18
|
+
*/
|
|
19
|
+
export declare const DEFAULT_MAX_RTF_BYTES: number;
|
|
13
20
|
/** Options for rtfToHtml. */
|
|
14
21
|
export interface RtfReadOptions {
|
|
15
22
|
/**
|
|
@@ -20,6 +27,12 @@ export interface RtfReadOptions {
|
|
|
20
27
|
* a document exactly as 1.4.0 did.
|
|
21
28
|
*/
|
|
22
29
|
fontSize?: number;
|
|
30
|
+
/**
|
|
31
|
+
* The largest RTF string to read, in characters (RTF is ASCII, so also bytes). A longer one
|
|
32
|
+
* is refused with a RangeError before any of it is parsed. Default: DEFAULT_MAX_RTF_BYTES
|
|
33
|
+
* (50 MB). 0 reads a document of any size.
|
|
34
|
+
*/
|
|
35
|
+
maxBytes?: number;
|
|
23
36
|
}
|
|
24
37
|
export declare function rtfToHtml(rtfString: string, options?: RtfReadOptions): string;
|
|
25
38
|
export declare function readRtfFile(file: File, options?: RtfReadOptions): Promise<string>;
|