svelte-rtf-editor 1.8.3 → 1.10.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/dist/images.js CHANGED
@@ -38,6 +38,43 @@ export function initialDisplayWidth(naturalWidth, columnWidth, maxDisplayWidth)
38
38
  }
39
39
  /** Successive reductions tried when a picture will not fit the byte budget. */
40
40
  const SIZE_LADDER = [1, 0.8, 0.64, 0.5];
41
+ /**
42
+ * A picture is never made smaller than this on its longest edge, in px. Below it nothing can be
43
+ * made out, so a picture that still does not fit is refused instead.
44
+ */
45
+ const MIN_IMAGE_EDGE = 16;
46
+ /**
47
+ * A picture that could not be brought under the byte limit. The limit is a ceiling: a picture
48
+ * over it is not handed back for the caller to embed anyway.
49
+ */
50
+ export class ImageTooLargeError extends Error {
51
+ maxBytes;
52
+ constructor(maxBytes) {
53
+ super(`This picture could not be made small enough for the ${formatBytes(maxBytes)} size limit`);
54
+ this.maxBytes = maxBytes;
55
+ this.name = 'ImageTooLargeError';
56
+ }
57
+ }
58
+ /**
59
+ * A picture the browser could not open: a format it does not show (TIFF, HEIC in most browsers),
60
+ * or a damaged file. Its size has nothing to do with it, so it is refused in these words whatever
61
+ * the limit. It could not be shown in the editor, and what it holds could not be checked or
62
+ * converted for the RTF.
63
+ */
64
+ export class ImageUnreadableError extends Error {
65
+ constructor() {
66
+ super('This picture could not be opened: the browser cannot show its format, or the file is damaged');
67
+ this.name = 'ImageUnreadableError';
68
+ }
69
+ }
70
+ /** A byte count as a person reads it: "512 KB", "1.5 MB", "900 bytes". */
71
+ function formatBytes(bytes) {
72
+ if (bytes >= 1024 * 1024)
73
+ return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MB`;
74
+ if (bytes >= 1024)
75
+ return `${Math.round(bytes / 1024)} KB`;
76
+ return `${bytes} bytes`;
77
+ }
41
78
  /** JPEG qualities tried at each size, best first. */
42
79
  const QUALITY_LADDER = [0.85, 0.7];
43
80
  /**
@@ -169,11 +206,31 @@ function loadImage(src) {
169
206
  });
170
207
  }
171
208
  /**
172
- * Prepare a data URL for embedding: scale it down to `maxEdge` and re-encode it
173
- * to PNG when its format cannot be carried by RTF. JPEG sources stay JPEG so
174
- * photographs do not balloon; everything else becomes PNG. Animated images keep
175
- * their first frame. Falls back to the original data URL when the runtime
176
- * cannot rasterise, so nothing is lost if the conversion is unavailable.
209
+ * Prepare a data URL for embedding: scale it down to `maxEdge`, re-encode it to
210
+ * PNG when its format cannot be carried by RTF, and bring it under `maxBytes`.
211
+ * JPEG sources stay JPEG so photographs do not balloon; everything else becomes
212
+ * PNG while that fits. Animated images keep their first frame.
213
+ *
214
+ * `maxBytes` is a ceiling. The picture is shrunk until it fits:
215
+ *
216
+ * 1. At full size, then 80%, 64% and 50% of it, a PNG source is tried as PNG first, so
217
+ * screenshots and diagrams stay sharp, and as JPEG only when it has no transparency to lose.
218
+ * 2. If none of those fits, transparency is given up: the picture is laid on white and tried as
219
+ * JPEG from full size again, then smaller and smaller, each step sized from how far over the
220
+ * last one was.
221
+ *
222
+ * A picture that cannot be brought under the limit, because nothing legible would be left of it
223
+ * or because this runtime cannot redraw it, is refused with an ImageTooLargeError; it is never
224
+ * returned over the limit. Where the runtime cannot rasterise (SSR, a test DOM), a picture within
225
+ * the limit is passed through as it is.
226
+ *
227
+ * A browser has a largest canvas (268 million pixels in Chromium, about 16.7 million in Safari on
228
+ * a phone). Only a picture larger than `maxEdge` normally allows can meet it: with `maxEdge` 0, or
229
+ * a very large one. Such a picture is brought down to a size the canvas can hold, and the steps
230
+ * above start from there.
231
+ *
232
+ * A picture the browser cannot open at all is refused with an ImageUnreadableError, whatever its
233
+ * size.
177
234
  */
178
235
  export async function toRtfSafeDataUrl(dataUrl, limits = {}) {
179
236
  const { maxEdge = DEFAULT_MAX_IMAGE_EDGE, maxBytes = DEFAULT_MAX_IMAGE_BYTES } = limits;
@@ -182,67 +239,151 @@ export async function toRtfSafeDataUrl(dataUrl, limits = {}) {
182
239
  const actual = sniffImageType(dataUrl);
183
240
  const isJpeg = actual === 'image/jpeg';
184
241
  const isNative = actual !== null;
185
- if (!canRasterize())
242
+ const capped = !!maxBytes && maxBytes > 0;
243
+ const fits = (bytes) => !capped || bytes <= maxBytes;
244
+ /** The picture as it came, where it cannot be redrawn: only if it is within the limit. */
245
+ const asIs = () => {
246
+ if (!fits(dataUrlByteLength(dataUrl)))
247
+ throw new ImageTooLargeError(maxBytes);
186
248
  return dataUrl;
249
+ };
250
+ if (!canRasterize())
251
+ return asIs();
252
+ let img;
253
+ let ctx;
254
+ const canvas = document.createElement('canvas');
187
255
  try {
188
- const img = await loadImage(dataUrl);
189
- const width = img.naturalWidth || img.width;
190
- const height = img.naturalHeight || img.height;
191
- if (!width || !height)
192
- return dataUrl;
193
- const target = scaledSize(width, height, maxEdge);
194
- const fits = (bytes) => !maxBytes || maxBytes <= 0 || bytes <= maxBytes;
195
- // Already embeddable, within the pixel cap and within budget — leave the
196
- // original bytes alone rather than losing quality to a pointless re-encode.
197
- if (isNative &&
198
- target.width === width &&
199
- target.height === height &&
200
- fits(dataUrlByteLength(dataUrl))) {
201
- return dataUrl;
256
+ img = await loadImage(dataUrl);
257
+ }
258
+ catch {
259
+ // Not a matter of size: a smaller file of the same kind fails the same way.
260
+ throw new ImageUnreadableError();
261
+ }
262
+ try {
263
+ ctx = canvas.getContext('2d');
264
+ }
265
+ catch {
266
+ return asIs();
267
+ }
268
+ const width = img.naturalWidth || img.width;
269
+ const height = img.naturalHeight || img.height;
270
+ if (!width || !height || !ctx)
271
+ return asIs();
272
+ const target = scaledSize(width, height, maxEdge);
273
+ // Already embeddable, within the pixel cap and within budget — leave the
274
+ // original bytes alone rather than losing quality to a pointless re-encode.
275
+ if (isNative && target.width === width && target.height === height && fits(dataUrlByteLength(dataUrl))) {
276
+ return dataUrl;
277
+ }
278
+ /** Draw the picture at a share of its target size; `onWhite` gives up its transparency. */
279
+ const draw = (scale, onWhite) => {
280
+ const w = Math.max(1, Math.round(target.width * scale));
281
+ const h = Math.max(1, Math.round(target.height * scale));
282
+ canvas.width = w;
283
+ canvas.height = h;
284
+ ctx.clearRect(0, 0, w, h);
285
+ if (onWhite) {
286
+ // A JPEG has no transparency, and a canvas encodes what shows through as black.
287
+ ctx.fillStyle = '#ffffff';
288
+ ctx.fillRect(0, 0, w, h);
202
289
  }
203
- const canvas = document.createElement('canvas');
204
- const ctx = canvas.getContext('2d');
205
- if (!ctx)
206
- return dataUrl;
290
+ ctx.drawImage(img, 0, 0, w, h);
291
+ return { w, h };
292
+ };
293
+ const jpegs = () => QUALITY_LADDER.map((quality) => canvas.toDataURL('image/jpeg', quality));
294
+ /**
295
+ * Whether the canvas gave a picture. Asked for more pixels than the browser allows, it does
296
+ * not throw: toDataURL returns "data:,", which is no picture and no bytes. Counted as a fit,
297
+ * that was returned as the picture.
298
+ */
299
+ const isPicture = (candidate) => sniffImageType(candidate) !== null;
300
+ /**
301
+ * The first candidate that fits, or the size of the smallest one. `smallest` stays Infinity
302
+ * when the canvas gave no picture at this size.
303
+ */
304
+ const pick = (candidates) => {
305
+ let smallest = Infinity;
306
+ for (const candidate of candidates) {
307
+ if (!isPicture(candidate))
308
+ continue;
309
+ const bytes = dataUrlByteLength(candidate);
310
+ if (fits(bytes))
311
+ return { fit: candidate, smallest: bytes };
312
+ smallest = Math.min(smallest, bytes);
313
+ }
314
+ return { fit: null, smallest };
315
+ };
316
+ try {
207
317
  let opaque = null;
208
- let smallest = '';
318
+ let smallest = Infinity;
319
+ const longest = Math.max(target.width, target.height);
320
+ // The share of the target size the canvas can hold: all of it, until a size gives no picture.
321
+ let room = 1;
322
+ // Whether the canvas gave a picture at any size.
323
+ let drew = false;
209
324
  // Shrink in steps until the encoded picture fits the budget. At each size a
210
325
  // PNG source is tried as PNG first — screenshots and diagrams stay sharp and
211
326
  // usually compress well — and only falls back to JPEG when PNG is too heavy
212
327
  // and the image has no transparency to lose.
213
- for (const scale of SIZE_LADDER) {
214
- const w = Math.max(1, Math.round(target.width * scale));
215
- const h = Math.max(1, Math.round(target.height * scale));
216
- canvas.width = w;
217
- canvas.height = h;
218
- ctx.clearRect(0, 0, w, h);
219
- ctx.drawImage(img, 0, 0, w, h);
328
+ for (let step = 0; step < SIZE_LADDER.length;) {
329
+ const scale = room * SIZE_LADDER[step];
330
+ const { w, h } = draw(scale, false);
220
331
  const candidates = [];
221
- if (!isJpeg)
222
- candidates.push(canvas.toDataURL('image/png'));
223
- if (isJpeg || !fits(dataUrlByteLength(candidates[0] ?? ''))) {
224
- if (opaque === null)
225
- opaque = !hasTransparency(ctx, w, h);
226
- if (isJpeg || opaque) {
227
- for (const quality of QUALITY_LADDER) {
228
- candidates.push(canvas.toDataURL('image/jpeg', quality));
229
- }
332
+ if (isJpeg) {
333
+ candidates.push(...jpegs());
334
+ }
335
+ else {
336
+ const png = canvas.toDataURL('image/png');
337
+ candidates.push(png);
338
+ if (!fits(dataUrlByteLength(png))) {
339
+ if (opaque === null)
340
+ opaque = !hasTransparency(ctx, w, h);
341
+ if (opaque)
342
+ candidates.push(...jpegs());
230
343
  }
231
344
  }
232
- for (const candidate of candidates) {
233
- const bytes = dataUrlByteLength(candidate);
234
- if (fits(bytes))
235
- return candidate;
236
- if (!smallest || bytes < dataUrlByteLength(smallest))
237
- smallest = candidate;
345
+ const picked = pick(candidates);
346
+ if (picked.fit)
347
+ return picked.fit;
348
+ if (picked.smallest === Infinity) {
349
+ // No picture at this size: it is more than the canvas holds. Half the area becomes
350
+ // the full size, and the steps start again from it.
351
+ room = scale * Math.SQRT1_2;
352
+ if (longest * room < MIN_IMAGE_EDGE)
353
+ break;
354
+ step = 0;
355
+ continue;
238
356
  }
357
+ drew = true;
358
+ smallest = picked.smallest;
359
+ step++;
360
+ }
361
+ // The canvas gave no picture at any size, which is the canvas failing, not the picture
362
+ // being too heavy.
363
+ if (!drew)
364
+ return asIs();
365
+ // Nothing fit. The limit is a ceiling, so keep going: smaller, and for a picture with
366
+ // transparency as a JPEG on white from full size again, which keeps far more of it than
367
+ // a PNG a fraction of the size. Each step is sized from how far over the last one was
368
+ // (the bytes of a picture go with its area), and is never less than a fifth smaller.
369
+ const smaller = (bytes) => Math.min(0.8, Math.sqrt(maxBytes / bytes) * 0.95);
370
+ let scale = room * (isJpeg || opaque ? SIZE_LADDER[SIZE_LADDER.length - 1] * smaller(smallest) : 1);
371
+ while (longest * scale >= MIN_IMAGE_EDGE) {
372
+ draw(scale, !isJpeg);
373
+ const candidates = isJpeg ? jpegs() : [canvas.toDataURL('image/png'), ...jpegs()];
374
+ const picked = pick(candidates);
375
+ if (picked.fit)
376
+ return picked.fit;
377
+ scale *= smaller(picked.smallest);
239
378
  }
240
- // Nothing fit — hand back the smallest we managed rather than the original.
241
- return smallest || dataUrl;
242
379
  }
243
- catch {
244
- return dataUrl;
380
+ catch (err) {
381
+ if (err instanceof ImageTooLargeError)
382
+ throw err;
383
+ // The canvas gave up by throwing (a tainted source, no memory for it).
384
+ return asIs();
245
385
  }
386
+ throw new ImageTooLargeError(maxBytes);
246
387
  }
247
388
  /** Read an image File into a data URL the RTF writer can embed. */
248
389
  export async function fileToImageSrc(file, limits = {}) {
@@ -252,33 +393,101 @@ export async function fileToImageSrc(file, limits = {}) {
252
393
  }
253
394
  return toRtfSafeDataUrl(dataUrl, limits);
254
395
  }
396
+ /** How long a pasted or typed picture address may take to answer before it is given up on. */
397
+ export const IMAGE_FETCH_TIMEOUT_MS = 15_000;
398
+ /** The most a fetched picture may weigh before it is scaled down: 25 MB. */
399
+ export const MAX_FETCHED_IMAGE_BYTES = 25 * 1024 * 1024;
255
400
  /**
256
401
  * Resolve a URL to an embeddable data URL. Remote images are fetched so they
257
- * survive export; when the fetch is blocked (CORS, offline) the original URL is
258
- * kept and the image still displays — it just exports as a text placeholder.
402
+ * survive export; when the fetch is blocked (CORS, offline), takes longer than
403
+ * IMAGE_FETCH_TIMEOUT_MS or is larger than MAX_FETCHED_IMAGE_BYTES, the original
404
+ * URL is kept and the image still displays — it just exports as a text
405
+ * placeholder. `embedded` is true only for PNG or JPEG data, the two formats the
406
+ * RTF writer carries: a GIF, WebP or SVG that could not be converted is not.
407
+ *
408
+ * A picture that could not be brought under `maxBytes` is never returned as data. One fetched
409
+ * from an address keeps its address, and so exports as the placeholder. One given as data has
410
+ * no address to fall back to: it comes back with `tooLarge` set, and must not be inserted.
411
+ *
412
+ * Picture data the browser cannot open comes back with `unreadable` set, and must not be inserted
413
+ * either: it would show as a broken picture. `tooLarge` and `unreadable` are never both set.
259
414
  */
260
415
  export async function urlToImageSrc(url, limits = {}) {
261
416
  const value = url.trim();
417
+ const result = (src) => ({ src, embedded: src.startsWith('data:') && sniffImageType(src) !== null });
262
418
  if (value.startsWith('data:image/')) {
263
- return { src: await toRtfSafeDataUrl(value, limits), embedded: true };
419
+ try {
420
+ return result(await toRtfSafeDataUrl(value, limits));
421
+ }
422
+ catch (err) {
423
+ if (err instanceof ImageUnreadableError)
424
+ return { src: value, embedded: false, unreadable: true };
425
+ if (!(err instanceof ImageTooLargeError))
426
+ throw err;
427
+ // Picture data over the limit that could not be reduced. The data is the
428
+ // address here, so there is nothing to keep that would not also be over it:
429
+ // the caller must not put it in the document.
430
+ return { src: value, embedded: false, tooLarge: true };
431
+ }
264
432
  }
265
433
  // A picture that could not be inlined still displays, but it leaves the
266
434
  // document as a text placeholder instead of picture data. The caller is told
267
435
  // so it can say as much, rather than letting the image vanish at export.
436
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
437
+ const timer = controller ? setTimeout(() => controller.abort(), IMAGE_FETCH_TIMEOUT_MS) : null;
268
438
  try {
269
- const response = await fetch(value, { mode: 'cors' });
439
+ const response = await fetch(value, { mode: 'cors', signal: controller?.signal });
270
440
  if (!response.ok)
271
441
  return { src: value, embedded: false };
272
- const blob = await response.blob();
273
- if (!blob.type.startsWith('image/'))
442
+ const declared = Number(response.headers?.get('content-length') ?? '');
443
+ if (declared > MAX_FETCHED_IMAGE_BYTES) {
444
+ controller?.abort();
445
+ return { src: value, embedded: false };
446
+ }
447
+ const blob = await readCapped(response, MAX_FETCHED_IMAGE_BYTES);
448
+ if (!blob) {
449
+ controller?.abort();
274
450
  return { src: value, embedded: false };
451
+ }
452
+ if (blob.size > MAX_FETCHED_IMAGE_BYTES || !blob.type.startsWith('image/')) {
453
+ return { src: value, embedded: false };
454
+ }
275
455
  const dataUrl = await readFileAsDataUrl(blob);
276
- const src = await toRtfSafeDataUrl(dataUrl, limits);
277
- return { src, embedded: src.startsWith('data:') };
456
+ const converted = result(await toRtfSafeDataUrl(dataUrl, limits));
457
+ return converted.embedded ? converted : { src: value, embedded: false };
278
458
  }
279
459
  catch {
280
460
  return { src: value, embedded: false };
281
461
  }
462
+ finally {
463
+ if (timer)
464
+ clearTimeout(timer);
465
+ }
466
+ }
467
+ /**
468
+ * A response's body, or null once it has run past `limit` bytes. A server need not say how much
469
+ * it will send (no Content-Length), and read in one piece the whole of it was held in memory
470
+ * before its size was looked at. Read as it arrives, it is given up at the limit.
471
+ */
472
+ async function readCapped(response, limit) {
473
+ const reader = response.body?.getReader?.();
474
+ if (!reader)
475
+ return response.blob();
476
+ const chunks = [];
477
+ let size = 0;
478
+ for (;;) {
479
+ const { done, value } = await reader.read();
480
+ if (done)
481
+ break;
482
+ size += value.byteLength;
483
+ if (size > limit) {
484
+ void reader.cancel().catch(() => { });
485
+ return null;
486
+ }
487
+ chunks.push(value);
488
+ }
489
+ const type = (response.headers?.get('content-type') ?? '').split(';')[0].trim();
490
+ return new Blob(chunks, { type });
282
491
  }
283
492
  /** "sunset-over-lake.png" → "sunset-over-lake" — a usable default alt text. */
284
493
  export function stripExtension(filename) {
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
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';
7
7
  export { htmlToMarkdown, downloadFile } from './utils.js';
8
+ export { sanitizeHtml } from './sanitize.js';
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@
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';
8
+ export { sanitizeHtml } from './sanitize.js';
@@ -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, bullet/numbered lists, tables,
8
- * embedded pictures (\pict PNG/JPEG blips, with captions),
9
- * Unicode characters, hex escapes, and nested groups.
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>;