svelte-rtf-editor 1.8.3 → 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.
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A <table> as a grid: which cell covers which row and column once rowspan and colspan are
3
+ * resolved. RTF and Markdown both describe a table column by column, so both writers start here.
4
+ */
5
+ /** One <td> or <th>, with where it starts and how far it reaches. */
6
+ export interface GridCell {
7
+ el: HTMLElement;
8
+ row: number;
9
+ col: number;
10
+ rowspan: number;
11
+ colspan: number;
12
+ }
13
+ export interface TableModel {
14
+ /** The number of columns in the widest row. */
15
+ columns: number;
16
+ /** For each row, the cell that covers each column, or null where no cell does. */
17
+ rows: (GridCell | null)[][];
18
+ cells: GridCell[];
19
+ }
20
+ /**
21
+ * A table's rows in the order a browser shows them: the head first and the foot last, wherever
22
+ * the source wrote them.
23
+ */
24
+ export declare function tableRowsInOrder(table: Element): Element[];
25
+ /** A row's own cells. */
26
+ export declare function rowCells(row: Element): HTMLElement[];
27
+ /**
28
+ * Lay a table's cells out on a grid. A cell goes in the first free column of its row and covers
29
+ * colspan columns and rowspan rows from there; rowspan="0" reaches the last row, as in HTML, and
30
+ * no span reaches past the table. Where two cells would overlap, the one placed first keeps the slot.
31
+ *
32
+ * A column in which no cell starts is not a column: a browser gives it no width. That is what
33
+ * colspan="100" on a cell meant to cross "the whole table" leaves behind, and counted as columns
34
+ * they would squeeze the real ones into a sliver of the page.
35
+ */
36
+ export declare function tableModel(table: Element): TableModel;
37
+ /**
38
+ * The share of the table's width each column takes, adding up to 1. A column is as wide as a
39
+ * cell of its own says (width: 25%); a cell across several columns gives what it has left to
40
+ * those of them with no width; the rest share what remains equally.
41
+ */
42
+ export declare function columnShares(model: TableModel): number[];
@@ -0,0 +1,139 @@
1
+ /**
2
+ * A <table> as a grid: which cell covers which row and column once rowspan and colspan are
3
+ * resolved. RTF and Markdown both describe a table column by column, so both writers start here.
4
+ */
5
+ /** The most columns one cell may span, as in HTML. */
6
+ const MAX_COLSPAN = 1000;
7
+ /**
8
+ * A table's rows in the order a browser shows them: the head first and the foot last, wherever
9
+ * the source wrote them.
10
+ */
11
+ export function tableRowsInOrder(table) {
12
+ const pick = (selector) => Array.from(table.querySelectorAll(selector));
13
+ return [
14
+ ...pick(':scope > thead > tr'),
15
+ ...pick(':scope > tbody > tr, :scope > tr'),
16
+ ...pick(':scope > tfoot > tr')
17
+ ];
18
+ }
19
+ /** A row's own cells. */
20
+ export function rowCells(row) {
21
+ return Array.from(row.querySelectorAll(':scope > td, :scope > th'));
22
+ }
23
+ function span(el, name) {
24
+ const value = parseInt(el.getAttribute(name) ?? '', 10);
25
+ return Number.isFinite(value) && value >= 0 ? value : 1;
26
+ }
27
+ /**
28
+ * Lay a table's cells out on a grid. A cell goes in the first free column of its row and covers
29
+ * colspan columns and rowspan rows from there; rowspan="0" reaches the last row, as in HTML, and
30
+ * no span reaches past the table. Where two cells would overlap, the one placed first keeps the slot.
31
+ *
32
+ * A column in which no cell starts is not a column: a browser gives it no width. That is what
33
+ * colspan="100" on a cell meant to cross "the whole table" leaves behind, and counted as columns
34
+ * they would squeeze the real ones into a sliver of the page.
35
+ */
36
+ export function tableModel(table) {
37
+ const trs = tableRowsInOrder(table);
38
+ const cells = [];
39
+ /** Put each cell on a grid, in order; returns the grid and its width. */
40
+ const place = () => {
41
+ const rows = trs.map(() => []);
42
+ let columns = 0;
43
+ for (const cell of cells) {
44
+ for (let dr = 0; dr < cell.rowspan; dr++) {
45
+ for (let dc = 0; dc < cell.colspan; dc++) {
46
+ if (!rows[cell.row + dr][cell.col + dc])
47
+ rows[cell.row + dr][cell.col + dc] = cell;
48
+ }
49
+ }
50
+ columns = Math.max(columns, cell.col + cell.colspan);
51
+ }
52
+ return { rows, columns };
53
+ };
54
+ // First pass: where each cell starts, with the spans the markup gives.
55
+ const taken = trs.map(() => []);
56
+ trs.forEach((tr, r) => {
57
+ let c = 0;
58
+ for (const el of rowCells(tr)) {
59
+ while (taken[r][c])
60
+ c++;
61
+ const colspan = Math.min(MAX_COLSPAN, Math.max(1, span(el, 'colspan')));
62
+ const rowspan = Math.min(trs.length - r, span(el, 'rowspan') || trs.length - r);
63
+ cells.push({ el, row: r, col: c, rowspan, colspan });
64
+ for (let dr = 0; dr < rowspan; dr++) {
65
+ for (let dc = 0; dc < colspan; dc++)
66
+ taken[r + dr][c + dc] = true;
67
+ }
68
+ c += colspan;
69
+ }
70
+ });
71
+ // Second pass: keep only the columns a cell starts in, and count each span in those.
72
+ const width = cells.reduce((max, cell) => Math.max(max, cell.col + cell.colspan), 0);
73
+ const starts = new Array(width).fill(false);
74
+ for (const cell of cells)
75
+ starts[cell.col] = true;
76
+ const index = [];
77
+ let kept = 0;
78
+ for (let c = 0; c <= width; c++) {
79
+ index[c] = kept;
80
+ if (starts[c])
81
+ kept++;
82
+ }
83
+ for (const cell of cells) {
84
+ const end = index[cell.col + cell.colspan];
85
+ cell.col = index[cell.col];
86
+ cell.colspan = Math.max(1, end - cell.col);
87
+ }
88
+ const { rows, columns } = place();
89
+ // Every row as wide as the table, so a short row has explicit empty slots.
90
+ for (const row of rows) {
91
+ for (let c = 0; c < columns; c++)
92
+ row[c] = row[c] ?? null;
93
+ }
94
+ return { columns, rows, cells };
95
+ }
96
+ /** The share of the table's width a cell asks for, in percent, or null when it asks for none. */
97
+ function percentWidth(el) {
98
+ const m = (el.style?.width || el.getAttribute('width') || '').trim().match(/^(\d+(?:\.\d+)?|\.\d+)%$/);
99
+ const value = m ? parseFloat(m[1]) : 0;
100
+ return value > 0 ? value : null;
101
+ }
102
+ /**
103
+ * The share of the table's width each column takes, adding up to 1. A column is as wide as a
104
+ * cell of its own says (width: 25%); a cell across several columns gives what it has left to
105
+ * those of them with no width; the rest share what remains equally.
106
+ */
107
+ export function columnShares(model) {
108
+ const width = new Array(model.columns).fill(null);
109
+ for (const cell of model.cells) {
110
+ if (cell.colspan !== 1 || width[cell.col] != null)
111
+ continue;
112
+ width[cell.col] = percentWidth(cell.el);
113
+ }
114
+ for (const cell of model.cells) {
115
+ if (cell.colspan === 1)
116
+ continue;
117
+ const pct = percentWidth(cell.el);
118
+ if (pct == null)
119
+ continue;
120
+ const cols = Array.from({ length: cell.colspan }, (_, k) => cell.col + k).filter((c) => c < model.columns);
121
+ const open = cols.filter((c) => width[c] == null);
122
+ const taken = cols.reduce((sum, c) => sum + (width[c] ?? 0), 0);
123
+ if (open.length === 0 || pct <= taken)
124
+ continue;
125
+ for (const c of open)
126
+ width[c] = (pct - taken) / open.length;
127
+ }
128
+ const known = width.filter((w) => w != null);
129
+ const sum = known.reduce((a, b) => a + b, 0);
130
+ const open = width.length - known.length;
131
+ if (open > 0) {
132
+ // What is left of 100%; where the given widths already fill it, the average of those.
133
+ const share = sum < 100 ? (100 - sum) / open : known.length > 0 ? sum / known.length : 100 / open;
134
+ for (let c = 0; c < width.length; c++)
135
+ width[c] = width[c] ?? share;
136
+ }
137
+ const total = width.reduce((a, b) => a + b, 0) || 1;
138
+ return width.map((w) => w / total);
139
+ }
package/dist/utils.js CHANGED
@@ -1,14 +1,121 @@
1
+ import { linkTarget } from './rtf-writer.js';
2
+ import { tableModel } from './table-model.js';
3
+ /**
4
+ * Text as Markdown shows it: the characters Markdown reads as markup are escaped, so "2*3*4" is
5
+ * not emphasis, "#1" not a heading, "[x]" not a link and "<b>" not HTML.
6
+ */
7
+ function escapeMarkdown(text, ctx) {
8
+ const escaped = text.replace(/[\\`*_[\]#<~]/g, '\\$&');
9
+ return ctx.inCell ? escaped.replace(/\|/g, '\\|') : escaped;
10
+ }
11
+ /** Code as a Markdown code span: fenced with more backticks than it holds, and in a table cell its pipes escaped. */
12
+ function codeSpan(code, ctx) {
13
+ const longest = Math.max(0, ...Array.from(code.matchAll(/`+/g), (m) => m[0].length));
14
+ const fence = '`'.repeat(longest + 1);
15
+ const pad = /^`|`$/.test(code) ? ' ' : '';
16
+ const body = ctx.inCell ? code.replace(/\|/g, '\\|') : code;
17
+ return `${fence}${pad}${body}${pad}${fence}`;
18
+ }
19
+ /** An address as a Markdown link or image target: what would end it, or a table cell, is encoded. */
20
+ function markdownUrl(url) {
21
+ return url.replace(/[()|\s<>]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`);
22
+ }
23
+ /**
24
+ * A picture's address, if it is one a Markdown viewer may load: a web address, a relative path,
25
+ * or PNG/JPEG/GIF/WebP data. Any other scheme (javascript:, file:) is not.
26
+ */
27
+ function imageTarget(src) {
28
+ const value = src.trim();
29
+ if (!value)
30
+ return null;
31
+ if (/^data:image\/(png|jpe?g|gif|webp);base64,[A-Za-z0-9+/=\s]+$/i.test(value))
32
+ return value.replace(/\s+/g, '');
33
+ if (/^https?:\/\//i.test(value) || !/^[a-z][a-z0-9+.-]*:/i.test(value))
34
+ return markdownUrl(value);
35
+ return null;
36
+ }
37
+ /** A picture as Markdown, or its description alone where its address is not one to load. */
38
+ function imageToMarkdown(alt, src, ctx) {
39
+ const target = imageTarget(src);
40
+ const text = escapeMarkdown(alt, ctx);
41
+ return target ? `![${text}](${target})` : text;
42
+ }
43
+ /**
44
+ * A list item's Markdown under its marker: later lines are indented to the item's text, so a
45
+ * table, a code block or a list inside the item stays in it.
46
+ */
47
+ function listItem(marker, body) {
48
+ return `${marker}${body.trim().replace(/\n(?=[^\n])/g, `\n${' '.repeat(marker.length)}`)}\n`;
49
+ }
50
+ /**
51
+ * A block's text with the marks escaped that mean something only where a line starts: "-", "+"
52
+ * and "1." open a list, ">" a quotation. A report line typed as "- Benign." stays that line.
53
+ */
54
+ function escapeLineStarts(markdown) {
55
+ return markdown.replace(/^(\s*)(?:([-+>])(?=\s|$)|(\d+)([.)])(?=\s|$))/gm, (_m, lead, mark, digits, dot) => mark ? `${lead}\\${mark}` : `${lead}${digits}\\${dot}`);
56
+ }
57
+ /** A table as a Markdown (GFM) table. */
58
+ function tableToMarkdown(table) {
59
+ const model = tableModel(table);
60
+ if (model.columns === 0)
61
+ return '';
62
+ const lines = model.rows.map((row) => {
63
+ // Markdown has no merged cells: a cell that spans is written where it starts, and the
64
+ // other columns and rows it covers are left empty so the columns still line up.
65
+ const cells = row.map((cell, c) => {
66
+ if (!cell || cell.col !== c || model.rows[cell.row] !== row)
67
+ return '';
68
+ return childrenToMarkdown(cell.el, { inCell: true })
69
+ .trim()
70
+ .replace(/\s*\n\s*/g, '<br>');
71
+ });
72
+ return `| ${cells.join(' | ')} |`;
73
+ });
74
+ // The first row is the header if it holds a header cell; a table with none gets an empty
75
+ // one, which Markdown requires.
76
+ const hasHeader = model.rows[0].some((cell) => cell?.row === 0 && cell.el.tagName.toLowerCase() === 'th');
77
+ if (!hasHeader)
78
+ lines.unshift(`| ${model.rows[0].map(() => ' ').join(' | ')} |`);
79
+ lines.splice(1, 0, `| ${model.rows[0].map(() => '---').join(' | ')} |`);
80
+ return `${lines.join('\n')}\n\n`;
81
+ }
82
+ /** A blank line before a block that follows text on the same line, as in "See<table>…". */
83
+ function blockStart(md) {
84
+ return md && !md.endsWith('\n') ? '\n\n' : '';
85
+ }
86
+ /** A table inside a table cell, as text: each row a line, its cells a slash apart. */
87
+ function nestedTableToText(table, ctx) {
88
+ const model = tableModel(table);
89
+ return model.rows
90
+ .map((row) => row
91
+ .filter((cell, c) => cell && cell.col === c && model.rows[cell.row] === row)
92
+ .map((cell) => childrenToMarkdown(cell.el, ctx).trim().replace(/\s*\n\s*/g, ' '))
93
+ .join(' / '))
94
+ .filter(Boolean)
95
+ .join('\n');
96
+ }
1
97
  export function htmlToMarkdown(el) {
98
+ return childrenToMarkdown(el, { inCell: false });
99
+ }
100
+ function childrenToMarkdown(el, ctx) {
2
101
  let md = '';
3
102
  el.childNodes.forEach((node) => {
4
103
  if (node.nodeType === Node.TEXT_NODE) {
5
- md += node.textContent;
104
+ // A line break in the HTML source shows as a space, as it does on screen; where white
105
+ // space is kept (the editor's tab, <span style="white-space:pre">), it stays.
106
+ const text = node.textContent || '';
107
+ const kept = node.parentElement?.closest('[style*="white-space"]');
108
+ const keeps = kept !== null && /^pre/.test(kept.style.whiteSpace);
109
+ md += escapeMarkdown(keeps ? text : text.replace(/[ \t\r\n]+/g, ' '), ctx);
6
110
  return;
7
111
  }
8
112
  if (node.nodeType !== Node.ELEMENT_NODE)
9
113
  return;
10
114
  const tag = node.tagName.toLowerCase();
11
- const inner = htmlToMarkdown(node);
115
+ // Code is written as it is, and a table and a picture build their own text.
116
+ const inner = tag === 'pre' || tag === 'code' || tag === 'table' || tag === 'figure'
117
+ ? ''
118
+ : childrenToMarkdown(node, ctx);
12
119
  switch (tag) {
13
120
  case 'h1':
14
121
  md += `# ${inner}\n\n`;
@@ -19,8 +126,17 @@ export function htmlToMarkdown(el) {
19
126
  case 'h3':
20
127
  md += `### ${inner}\n\n`;
21
128
  break;
129
+ case 'h4':
130
+ md += `#### ${inner}\n\n`;
131
+ break;
132
+ case 'h5':
133
+ md += `##### ${inner}\n\n`;
134
+ break;
135
+ case 'h6':
136
+ md += `###### ${inner}\n\n`;
137
+ break;
22
138
  case 'p':
23
- md += `${inner}\n\n`;
139
+ md += `${escapeLineStarts(inner)}\n\n`;
24
140
  break;
25
141
  case 'strong':
26
142
  case 'b':
@@ -37,20 +153,30 @@ export function htmlToMarkdown(el) {
37
153
  case 'strike':
38
154
  md += `~~${inner}~~`;
39
155
  break;
40
- case 'a':
41
- md += `[${inner}](${node.href || ''})`;
156
+ case 'a': {
157
+ // As in the RTF: only a web, mail or phone address is a link; a javascript:
158
+ // address, which a Markdown viewer would run, is written as its text alone.
159
+ const target = linkTarget(node.getAttribute('href') || '');
160
+ md += target ? `[${inner}](${markdownUrl(target)})` : inner;
42
161
  break;
162
+ }
43
163
  case 'img':
44
- md += `![${node.alt || ''}](${node.src || ''})`;
164
+ md += imageToMarkdown(node.getAttribute('alt') || '', node.getAttribute('src') || '', ctx);
45
165
  break;
46
166
  case 'figure': {
167
+ // The caption and the description are text like any other, so a "[x](javascript:…)"
168
+ // in either stays text. A figure with no picture keeps what it holds.
47
169
  const img = node.querySelector('img');
48
170
  const caption = (node.querySelector('figcaption')?.textContent || '').trim();
49
- if (img) {
50
- md += `![${img.getAttribute('alt') || caption}](${img.getAttribute('src') || ''})\n\n`;
51
- if (caption)
52
- md += `*${caption}*\n\n`;
171
+ if (img)
172
+ md += `${imageToMarkdown(img.getAttribute('alt') || caption, img.getAttribute('src') || '', ctx)}\n\n`;
173
+ else {
174
+ const held = childrenToMarkdown(node, ctx);
175
+ if (held.trim())
176
+ md += `${blockStart(md)}${held.endsWith('\n\n') ? held : `${held.replace(/\n*$/, '')}\n\n`}`;
53
177
  }
178
+ if (caption)
179
+ md += `*${escapeMarkdown(caption, ctx)}*\n\n`;
54
180
  break;
55
181
  }
56
182
  case 'figcaption':
@@ -59,22 +185,34 @@ export function htmlToMarkdown(el) {
59
185
  case 'blockquote':
60
186
  md += `> ${inner.trim()}\n\n`;
61
187
  break;
62
- case 'pre':
63
- md += `\`\`\`\n${node.textContent}\n\`\`\`\n\n`;
188
+ case 'pre': {
189
+ const code = node.textContent || '';
190
+ if (ctx.inCell) {
191
+ // A table cell holds one line: each line of the block is a code span of its own.
192
+ md += code.split(/\r\n|\r|\n/).map((line) => (line ? codeSpan(line, ctx) : '')).join('<br>');
193
+ break;
194
+ }
195
+ const longest = Math.max(2, ...Array.from(code.matchAll(/`+/g), (m) => m[0].length));
196
+ const fence = '`'.repeat(longest + 1);
197
+ md += `${blockStart(md)}${fence}\n${code}\n${fence}\n\n`;
64
198
  break;
199
+ }
65
200
  case 'code':
66
- md += `\`${inner}\``;
201
+ md += codeSpan(node.textContent || '', ctx);
67
202
  break;
68
203
  case 'ul':
204
+ md += blockStart(md);
69
205
  node.querySelectorAll(':scope > li').forEach((li) => {
70
- md += `- ${htmlToMarkdown(li).trim()}\n`;
206
+ md += listItem('- ', childrenToMarkdown(li, ctx));
71
207
  });
72
208
  md += '\n';
73
209
  break;
74
210
  case 'ol': {
75
- let i = 1;
211
+ md += blockStart(md);
212
+ const start = parseInt(node.getAttribute('start') ?? '', 10);
213
+ let i = Number.isFinite(start) ? start : 1;
76
214
  node.querySelectorAll(':scope > li').forEach((li) => {
77
- md += `${i++}. ${htmlToMarkdown(li).trim()}\n`;
215
+ md += listItem(`${i++}. `, childrenToMarkdown(li, ctx));
78
216
  });
79
217
  md += '\n';
80
218
  break;
@@ -88,8 +226,13 @@ export function htmlToMarkdown(el) {
88
226
  case 'hr':
89
227
  md += '\n---\n\n';
90
228
  break;
229
+ case 'table':
230
+ // Markdown cannot put a table in a table cell: the inner one is its rows as lines,
231
+ // its cells a slash apart, as the RTF writes them a tab apart.
232
+ md += ctx.inCell ? nestedTableToText(node, ctx) : `${blockStart(md)}${tableToMarkdown(node)}`;
233
+ break;
91
234
  case 'div':
92
- md += `${inner}\n`;
235
+ md += `${escapeLineStarts(inner)}\n`;
93
236
  break;
94
237
  default:
95
238
  md += inner;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-rtf-editor",
3
- "version": "1.8.3",
3
+ "version": "1.9.0",
4
4
  "description": "RTF viewer and rich-text editor components for Svelte 5",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/jcelano/svelte-rtf-editor#readme",