@folijs/view 0.1.0 → 0.2.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/CHANGELOG.md +26 -0
- package/dist/clipboard.d.ts +9 -2
- package/dist/clipboard.d.ts.map +1 -1
- package/dist/clipboard.js +370 -51
- package/dist/clipboard.js.map +1 -1
- package/dist/render.d.ts +17 -4
- package/dist/render.d.ts.map +1 -1
- package/dist/render.js +104 -8
- package/dist/render.js.map +1 -1
- package/dist/view.d.ts +42 -6
- package/dist/view.d.ts.map +1 -1
- package/dist/view.js +490 -74
- package/dist/view.js.map +1 -1
- package/package.json +2 -2
- package/src/clipboard.ts +399 -60
- package/src/render.ts +109 -10
- package/src/view.ts +491 -69
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# @folijs/view
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Rich content (schema v2): bulleted and numbered lists (nested, across pages), links, text color, highlight, alignment and horizontal rules, with toolbar controls and keyboard shortcuts; HTML paste from Word, Google Docs and web pages keeps them. Documents saved by 0.1.0 load unchanged; 0.1.0 cannot read documents saved by 0.2.0.
|
|
8
|
+
|
|
9
|
+
Known risks, besides those of 0.1.0 (manual IME, screen-reader and real-paste checks not run): Word and Google Docs lists are read from hand-written fixtures; long documents made of lists miss the editing-speed targets (Enter near the top, first layout, full re-flow). See [Known limitations](https://github.com/josep-audenis/foli/blob/main/docs/limitations.md).
|
|
10
|
+
|
|
11
|
+
Breaking (pre-1.0 minor): upgrade every app that reads your documents before saving with 0.2.0, since 0.1.0 cannot read version 2. `Transform.split(pos, after)` is now `split(pos, depth, typesAfter)` (`split(pos, 1, [after])`); `StepMap.side` is now `sides`; `MARK_TYPES` now lists every mark, `link`, `textColor` and `highlight` included (for attribute-free toggles use `SIMPLE_MARK_TYPES`); JSON no longer writes attributes equal to their default; `setBlockType` returns false when nothing changes, and `toggleMark` with invalid attributes returns false instead of throwing.
|
|
12
|
+
|
|
13
|
+
- cb92eb4: HTML paste reads schema v2: lists at any depth (`ul`/`ol`/`li`, `start`, a list nested directly in a list), Word list paragraphs (`mso-list` levels, numbered or bulleted from their marker) and Google Docs lists, rules (`hr`), links from `a[href]` when the href is safe (in-page `#…` anchors dropped), text color and highlight from inline styles and `<font color>` (black or white text and white highlight are dropped), and block alignment (`text-align`, `align`). Lists and rules that cannot be pasted as a slice go in as whole blocks at the caret (a list pasted into a list item joins it). Copy writes the same structures, so Foli's HTML reads back as the same document.
|
|
14
|
+
- 069f986: Alignment, colors and horizontal rules. Core: `setAlign`, `setTextColor`, `setHighlight` (null removes; at a caret, for the next typed text), `insertHorizontalRule`, `alignAt`, `colorAt`, `Transform.setBlockAttrs`, and `editor.commands` for each; typing over a selected rule replaces it with a paragraph, Enter adds one after it; arrow keys select a rule from the text beside it and leave it again (`arrowAcrossLeaf`). View: Up/Down onto a rule from a textblock's first or last line. React: toolbar alignment group, text color and highlight menu buttons (accessible menus, fixed palette), horizontal rule button; CSS variables `--foli-link-color`, `--foli-marker-color`, `--foli-rule-color`, `--foli-rule-thickness`; a rule is a taller box (easier to click) with its line in the middle.
|
|
15
|
+
- c0290aa: Links. Core: `setLink(href)`, `removeLink`, `insertLink(href, text?)`, `linkAt(state)`, `normalizeHref` (trim, `\` to `/`, spaces percent-encoded, `mailto:` for an email address and `https://` for a host name) and `autolinkHref`; the commands, the dialog and plain-text paste normalize the href, and every entry (including document load and paste) validates it, so unsafe protocols never apply; `editor.commands.setLink` and `removeLink`. Mod-K runs `openLinkEditor`, a request (`linkEditorRequest` transaction metadata, `requestsLinkEditor(tr)`) that a link UI answers. View: Ctrl+click (Cmd+click on Apple platforms) opens a link in a new tab with `noopener,noreferrer`; pasting plain text that is one URL makes a link (over selected text, links it), except paste as plain text; `view.paste(data, autolink?)`. React: a Link toolbar button (pressed in a link) and Mod-K open an accessible link dialog (URL field, Apply, Remove link, Cancel, Escape; an invalid URL is announced and not applied); new CSS variable `--foli-error-color`.
|
|
16
|
+
- ed66e43: List editing. Core: `toggleList`, `wrapInList`, `splitListItem`, `sinkListItem`, `liftListItem`, `liftListItemAtStart`, `listTypeAt` and `listKeymap()` (in every editor): Enter splits an item and leaves the list on an empty one, Tab and Shift+Tab nest and lift items (outside a list Tab is left to the browser), Backspace at an item's start lifts it, Ctrl/Cmd+Shift+7 and +8 toggle numbered and bulleted lists; `editor.commands.toggleList`, `wrapInList`, `indentListItem`, `outdentListItem`. Backspace after a list and Delete before one join into it; Delete at the end of a list item pulls in the next item's text (or what follows the list). Toggling a list off takes the selected items out of every list of that type they are in, leaving unselected items of outer lists; a numbered list split by lifting items goes on counting. Enter over a range across items deletes it, then splits. Each list change is its own undo step. View: Ctrl/Cmd+Shift+digit shortcuts work on every layout; `insertParagraph` and one-character delete inputs (keyboards without keydown) go through the same key bindings. React: toolbar buttons for bulleted and numbered lists (pressed inside one, disabled where no list can be made), decrease and increase indent.
|
|
17
|
+
- ef157b2: Document format v2 (`schemaVersion: 2`): bullet and ordered lists (`bulletList`, `orderedList` with `start`, `listItem`), `horizontalRule`, `align` on paragraphs and headings (`start`, `center`, `end`, `justify`; changing a block's type keeps it), and the marks `link` (`href` limited to relative URLs and http, https, mailto, tel: see `isSafeHref`), `textColor` and `highlight` (lowercase `#rrggbb`: see `isColor`). Documents saved by 0.1.0 (v1) load unchanged through a migration; 0.1.0 cannot read v2 documents. Attributes equal to their default are no longer written to JSON. `MARK_TYPES` now lists every mark (attribute-free ones are `SIMPLE_MARK_TYPES`). `setBlockType` no longer applies (or records undo) when nothing changes; `toggleMark` with invalid attributes (a link with an unsafe href) does not apply instead of throwing.
|
|
18
|
+
- a034e62: The view renders document format v2: bulleted and numbered lists (nested, rebuilt on each page they are on, numbering continued across pages, no repeated marker on an item continued from the previous page), horizontal rules (a click selects one; shown with the class `foli-selected-node`, outlined by the default theme), links (`<a href>` that does not navigate on click), text color, highlight and alignment. Copy writes real nested lists.
|
|
19
|
+
|
|
20
|
+
### Patch Changes
|
|
21
|
+
|
|
22
|
+
- Updated dependencies [069f986]
|
|
23
|
+
- Updated dependencies [c0290aa]
|
|
24
|
+
- Updated dependencies [ed66e43]
|
|
25
|
+
- Updated dependencies [ef157b2]
|
|
26
|
+
- Updated dependencies [f09aefe]
|
|
27
|
+
- @folijs/core@0.2.0
|
|
28
|
+
|
|
3
29
|
## 0.1.0
|
|
4
30
|
|
|
5
31
|
### Minor Changes
|
package/dist/clipboard.d.ts
CHANGED
|
@@ -31,8 +31,15 @@ export declare function docFromClipboard(data: Pick<DataTransfer, "getData">, ma
|
|
|
31
31
|
/** Plain text: one paragraph per line. */
|
|
32
32
|
export declare function textToDoc(text: string, marks?: readonly MarkJSON[]): DocJSON;
|
|
33
33
|
/**
|
|
34
|
-
*
|
|
35
|
-
* (
|
|
34
|
+
* A CSS color as the schema stores it (lowercase `#rrggbb`), or null: transparent, unknown
|
|
35
|
+
* (system colors such as Word's `windowtext`) or empty. Hex (3 or 6 digits), `rgb()`/`rgba()`
|
|
36
|
+
* and the basic named colors.
|
|
37
|
+
*/
|
|
38
|
+
export declare function parseColor(value: string): string | null;
|
|
39
|
+
/**
|
|
40
|
+
* Own HTML reader: maps known tags and inline styles to the schema (paragraphs, headings,
|
|
41
|
+
* lists, rules; bold, italic, underline, strike, links, colors; alignment), drops everything
|
|
42
|
+
* else. The HTML is parsed into an inert document and never inserted.
|
|
36
43
|
*/
|
|
37
44
|
export declare function htmlToDoc(html: string): DocJSON | null;
|
|
38
45
|
//# sourceMappingURL=clipboard.d.ts.map
|
package/dist/clipboard.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard.d.ts","sourceRoot":"","sources":["../src/clipboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,OAAO,
|
|
1
|
+
{"version":3,"file":"clipboard.d.ts","sourceRoot":"","sources":["../src/clipboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,OAAO,EAIZ,KAAK,QAAQ,EACb,KAAK,IAAI,IAAI,SAAS,EAIvB,MAAM,cAAc,CAAC;AAGtB;;;GAGG;AACH,eAAO,MAAM,SAAS,4BAA4B,CAAC;AAEnD,mCAAmC;AACnC,MAAM,WAAW,MAAM;IACrB,GAAG,EAAE,SAAS,CAAC;IACf;;;;OAIG;IACH,IAAI,EAAE,OAAO,CAAC;CACf;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,gGAAgG;AAChG,wBAAgB,cAAc,CAC5B,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,aAAa,EAAE,QAAQ,GACtB,gBAAgB,CA8BlB;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,EACnC,KAAK,GAAE,SAAS,QAAQ,EAAO,GAC9B,MAAM,GAAG,IAAI,CAyBf;AAED,0CAA0C;AAC1C,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,SAAS,QAAQ,EAAO,GAAG,OAAO,CAahF;AA0GD;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAiBvD;AAoJD;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAEtD"}
|
package/dist/clipboard.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Fragment, parseContent, } from "@folijs/core";
|
|
2
|
-
import { PAGE_BREAK_ATTR,
|
|
1
|
+
import { Fragment, isSafeHref, parseContent, } from "@folijs/core";
|
|
2
|
+
import { PAGE_BREAK_ATTR, renderTree } from "./render.js";
|
|
3
3
|
/**
|
|
4
4
|
* Clipboard type for Foli content, read back first on paste: `{ open, content }`, the copied
|
|
5
5
|
* blocks as `DocJSON` and whether they were cut out of one block (see `Pasted.open`).
|
|
@@ -12,17 +12,25 @@ export function serializeRange(doc, from, to, ownerDocument) {
|
|
|
12
12
|
let content = doc.slice(from, to).content;
|
|
13
13
|
for (let depth = $from.sharedDepth(to); depth > 0; depth--)
|
|
14
14
|
content = Fragment.from($from.node(depth).copy(content));
|
|
15
|
-
|
|
15
|
+
// Not validated: a cut-open list item may lack its first paragraph. The JSON is validated
|
|
16
|
+
// when pasted; the HTML is only markup.
|
|
17
|
+
const blocks = doc.type.createOpen(null, content);
|
|
16
18
|
const container = ownerDocument.createElement("div");
|
|
17
19
|
// Built with createElement/textContent (render.ts); reading innerHTML only serializes it.
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
20
|
+
// A range inside one textblock is that block's text: its lists around it stay out of the HTML
|
|
21
|
+
// (a word copied from a list item must not paste as a one-item list); the JSON keeps them.
|
|
22
|
+
const $to = doc.resolve(to);
|
|
23
|
+
const inline = $from.parent.isTextblock && $from.sameParent($to);
|
|
24
|
+
const htmlBlocks = inline
|
|
25
|
+
? [$from.parent.copy(doc.slice(from, to).content)]
|
|
26
|
+
: blocks.content.content;
|
|
27
|
+
renderTree(htmlBlocks, container, ownerDocument);
|
|
28
|
+
// Keep repeated and leading spaces in other apps.
|
|
29
|
+
for (const block of container.querySelectorAll("p, h1, h2, h3, h4, h5, h6"))
|
|
30
|
+
block.style.whiteSpace = "pre-wrap";
|
|
31
|
+
// How other apps (and print) recognize a page break; the editor itself does not need it.
|
|
32
|
+
for (const br of container.querySelectorAll(`br[${PAGE_BREAK_ATTR}]`))
|
|
33
|
+
br.style.cssText = "page-break-before: always; break-before: page";
|
|
26
34
|
return {
|
|
27
35
|
text: doc.textBetween(from, to, "\n", "\n"),
|
|
28
36
|
html: container.innerHTML,
|
|
@@ -150,33 +158,129 @@ const TAG_MARKS = new Map([
|
|
|
150
158
|
["strike", "strike"],
|
|
151
159
|
["del", "strike"],
|
|
152
160
|
]);
|
|
153
|
-
|
|
161
|
+
const NAMED_COLORS = {
|
|
162
|
+
black: "#000000",
|
|
163
|
+
white: "#ffffff",
|
|
164
|
+
red: "#ff0000",
|
|
165
|
+
green: "#008000",
|
|
166
|
+
blue: "#0000ff",
|
|
167
|
+
yellow: "#ffff00",
|
|
168
|
+
gray: "#808080",
|
|
169
|
+
grey: "#808080",
|
|
170
|
+
silver: "#c0c0c0",
|
|
171
|
+
maroon: "#800000",
|
|
172
|
+
navy: "#000080",
|
|
173
|
+
purple: "#800080",
|
|
174
|
+
teal: "#008080",
|
|
175
|
+
olive: "#808000",
|
|
176
|
+
orange: "#ffa500",
|
|
177
|
+
lime: "#00ff00",
|
|
178
|
+
aqua: "#00ffff",
|
|
179
|
+
cyan: "#00ffff",
|
|
180
|
+
fuchsia: "#ff00ff",
|
|
181
|
+
magenta: "#ff00ff",
|
|
182
|
+
};
|
|
183
|
+
const hex2 = (n) => Math.max(0, Math.min(255, Math.round(n)))
|
|
184
|
+
.toString(16)
|
|
185
|
+
.padStart(2, "0");
|
|
186
|
+
/**
|
|
187
|
+
* A CSS color as the schema stores it (lowercase `#rrggbb`), or null: transparent, unknown
|
|
188
|
+
* (system colors such as Word's `windowtext`) or empty. Hex (3 or 6 digits), `rgb()`/`rgba()`
|
|
189
|
+
* and the basic named colors.
|
|
190
|
+
*/
|
|
191
|
+
export function parseColor(value) {
|
|
192
|
+
const color = value.trim().toLowerCase();
|
|
193
|
+
const named = NAMED_COLORS[color];
|
|
194
|
+
if (named)
|
|
195
|
+
return named;
|
|
196
|
+
const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(color);
|
|
197
|
+
if (short)
|
|
198
|
+
return `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`;
|
|
199
|
+
if (/^#[0-9a-f]{6}$/.test(color))
|
|
200
|
+
return color;
|
|
201
|
+
// rgb(r, g, b), rgb(r g b), rgba(r, g, b, a), rgb(r g b / a): split, no backtracking regex.
|
|
202
|
+
const body = /^rgba?\(([^()]*)\)$/.exec(color)?.[1];
|
|
203
|
+
if (body === undefined)
|
|
204
|
+
return null;
|
|
205
|
+
const parts = body.trim().split(/\s*[,/]\s*|\s+/);
|
|
206
|
+
if (parts.length < 3 || parts.length > 4)
|
|
207
|
+
return null;
|
|
208
|
+
if (!parts.every((part) => /^\d+(?:\.\d+)?%?$/.test(part)))
|
|
209
|
+
return null;
|
|
210
|
+
const numbers = parts.map((part) => Number.parseFloat(part));
|
|
211
|
+
if (numbers[3] === 0)
|
|
212
|
+
return null; // fully transparent
|
|
213
|
+
const hex = `#${hex2(numbers[0])}${hex2(numbers[1])}${hex2(numbers[2])}`;
|
|
214
|
+
return hex;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Marks of an element on top of the inherited ones: tags first, then inline styles; a link
|
|
218
|
+
* from `a[href]` when the href is safe (`isSafeHref`; links inside the source page, `#…`, are
|
|
219
|
+
* dropped); text color and highlight from inline elements only (a page's colored containers
|
|
220
|
+
* are layout, not formatting), black text and white highlight being the defaults.
|
|
221
|
+
*/
|
|
154
222
|
function marksOf(element, inherited) {
|
|
155
|
-
const marks = new
|
|
156
|
-
const
|
|
223
|
+
const marks = new Map(inherited);
|
|
224
|
+
const tag = element.localName;
|
|
225
|
+
const tagMark = TAG_MARKS.get(tag);
|
|
157
226
|
if (tagMark)
|
|
158
|
-
marks.
|
|
227
|
+
marks.set(tagMark, { type: tagMark });
|
|
228
|
+
if (tag === "a") {
|
|
229
|
+
const href = element.getAttribute("href")?.trim().replace(/ /g, "%20");
|
|
230
|
+
if (href && !href.startsWith("#") && isSafeHref(href)) {
|
|
231
|
+
marks.set("link", { type: "link", attrs: { href } });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
159
234
|
const style = element.style;
|
|
160
235
|
if (!style)
|
|
161
236
|
return marks;
|
|
162
237
|
const weight = style.fontWeight;
|
|
163
238
|
// Google Docs wraps everything in <b style="font-weight:normal">.
|
|
164
239
|
if (/^(bold|bolder|[6-9]00)$/.test(weight))
|
|
165
|
-
marks.
|
|
240
|
+
marks.set("bold", { type: "bold" });
|
|
166
241
|
else if (/^(normal|lighter|[1-5]00)$/.test(weight))
|
|
167
242
|
marks.delete("bold");
|
|
168
243
|
if (/^(italic|oblique)/.test(style.fontStyle))
|
|
169
|
-
marks.
|
|
244
|
+
marks.set("italic", { type: "italic" });
|
|
170
245
|
else if (style.fontStyle === "normal")
|
|
171
246
|
marks.delete("italic");
|
|
172
247
|
const decoration = `${style.textDecorationLine} ${style.textDecoration}`;
|
|
173
248
|
if (decoration.includes("underline"))
|
|
174
|
-
marks.
|
|
249
|
+
marks.set("underline", { type: "underline" });
|
|
175
250
|
if (decoration.includes("line-through"))
|
|
176
|
-
marks.
|
|
251
|
+
marks.set("strike", { type: "strike" });
|
|
177
252
|
// `text-decoration: none` on a child does not remove a parent's line in CSS: keep it.
|
|
253
|
+
if (!BLOCK_TAGS.has(tag)) {
|
|
254
|
+
const color = parseColor(style.color || (tag === "font" ? (element.getAttribute("color") ?? "") : ""));
|
|
255
|
+
// Black is the default; white text comes from dark pages and would be invisible.
|
|
256
|
+
if (color === "#000000" || color === "#ffffff")
|
|
257
|
+
marks.delete("textColor");
|
|
258
|
+
else if (color)
|
|
259
|
+
marks.set("textColor", { type: "textColor", attrs: { color } });
|
|
260
|
+
const background = parseColor(style.backgroundColor);
|
|
261
|
+
if (background === "#ffffff")
|
|
262
|
+
marks.delete("highlight");
|
|
263
|
+
else if (background) {
|
|
264
|
+
marks.set("highlight", { type: "highlight", attrs: { color: background } });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
178
267
|
return marks;
|
|
179
268
|
}
|
|
269
|
+
/** A block's own alignment (`text-align`, or the old `align` attribute), or undefined. */
|
|
270
|
+
function alignOf(element) {
|
|
271
|
+
const value = (element.style?.textAlign ||
|
|
272
|
+
element.getAttribute("align") ||
|
|
273
|
+
"").toLowerCase();
|
|
274
|
+
if (value === "left" || value === "start")
|
|
275
|
+
return "start";
|
|
276
|
+
if (value === "center" || value === "-webkit-center")
|
|
277
|
+
return "center";
|
|
278
|
+
if (value === "right" || value === "end")
|
|
279
|
+
return "end";
|
|
280
|
+
if (value === "justify")
|
|
281
|
+
return "justify";
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
180
284
|
/**
|
|
181
285
|
* A page break in pasted HTML: Foli's own `<br data-page-break>`, or a `<br>` or `<hr>` styled
|
|
182
286
|
* to break the page (Word writes `<br clear=all style='page-break-before:always'>`, Google Docs
|
|
@@ -201,11 +305,57 @@ function isNoise(element) {
|
|
|
201
305
|
if (element.style?.display === "none" || element.hasAttribute("hidden")) {
|
|
202
306
|
return true;
|
|
203
307
|
}
|
|
204
|
-
return element.localName === "o:p" && !element.textContent?.replace(/[\s
|
|
308
|
+
return element.localName === "o:p" && !element.textContent?.replace(/[\s ]/g, "");
|
|
205
309
|
}
|
|
206
310
|
/**
|
|
207
|
-
*
|
|
208
|
-
* (
|
|
311
|
+
* A Word list paragraph (`style="mso-list:l0 level2 lfo1"`): its list and level, and from its
|
|
312
|
+
* marker (the `mso-list:Ignore` span Word adds for other apps) whether it is numbered and
|
|
313
|
+
* where the numbering starts. Best effort: a marker ending in "." or ")" is a number or
|
|
314
|
+
* letter (numbered); anything else ("·", "o", "§") a bullet.
|
|
315
|
+
*/
|
|
316
|
+
function wordListItem(element) {
|
|
317
|
+
const match = /mso-list:\s*(l\d+)\s+level(\d+)/i.exec(element.getAttribute("style") ?? "");
|
|
318
|
+
if (!match)
|
|
319
|
+
return null;
|
|
320
|
+
let marker = "";
|
|
321
|
+
for (const child of element.querySelectorAll("[style]")) {
|
|
322
|
+
if (/mso-list:\s*ignore/i.test(child.getAttribute("style") ?? "")) {
|
|
323
|
+
marker = (child.textContent ?? "").replace(/[\s ]+/g, "");
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
// "1.", "a)", "(iv)", and multi-level "1.2." or "1.2": numbered; its last part is its number.
|
|
328
|
+
const ordered = /^\(?[0-9a-zA-Z]{1,6}(?:\.[0-9]{1,6})*[.)]$|^\d{1,6}(?:\.\d{1,6})+$/.test(marker);
|
|
329
|
+
const number = /(\d+)[.)]?$/.exec(marker);
|
|
330
|
+
return {
|
|
331
|
+
list: match[1],
|
|
332
|
+
level: Number(match[2]),
|
|
333
|
+
ordered,
|
|
334
|
+
start: ordered && number ? Number(number[1]) : 1,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
/** A list item must start with a paragraph: a heading becomes one, else one is added. */
|
|
338
|
+
function finishItem(item) {
|
|
339
|
+
if (!item.content)
|
|
340
|
+
item.content = [];
|
|
341
|
+
const content = item.content;
|
|
342
|
+
const first = content[0];
|
|
343
|
+
if (first?.type === "heading") {
|
|
344
|
+
first.type = "paragraph";
|
|
345
|
+
const align = first.attrs?.align;
|
|
346
|
+
if (align)
|
|
347
|
+
first.attrs = { align };
|
|
348
|
+
else
|
|
349
|
+
delete first.attrs;
|
|
350
|
+
}
|
|
351
|
+
else if (first?.type !== "paragraph") {
|
|
352
|
+
content.unshift({ type: "paragraph" });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Own HTML reader: maps known tags and inline styles to the schema (paragraphs, headings,
|
|
357
|
+
* lists, rules; bold, italic, underline, strike, links, colors; alignment), drops everything
|
|
358
|
+
* else. The HTML is parsed into an inert document and never inserted.
|
|
209
359
|
*/
|
|
210
360
|
export function htmlToDoc(html) {
|
|
211
361
|
return readHTML(html)?.content ?? null;
|
|
@@ -213,17 +363,34 @@ export function htmlToDoc(html) {
|
|
|
213
363
|
/** `htmlToDoc`, plus whether the HTML had no block elements (`Pasted.open`). */
|
|
214
364
|
function readHTML(html) {
|
|
215
365
|
const parsed = new DOMParser().parseFromString(html, "text/html");
|
|
216
|
-
const
|
|
366
|
+
const doc = { type: "doc", content: [] };
|
|
367
|
+
const stack = [{ node: doc, kind: "doc" }];
|
|
217
368
|
let inline = null;
|
|
218
369
|
let blockType = "paragraph";
|
|
219
370
|
let level = 1;
|
|
371
|
+
let blockAlign;
|
|
220
372
|
let blockPre = false;
|
|
221
373
|
let sawBlock = false;
|
|
222
374
|
let afterSpace = true; // collapse leading and repeated whitespace like HTML layout does
|
|
223
|
-
const
|
|
375
|
+
const top = () => stack[stack.length - 1];
|
|
376
|
+
/** Where blocks go now: the open item or the document (text directly in a list gets an item). */
|
|
377
|
+
const container = () => {
|
|
378
|
+
if (top().kind === "list") {
|
|
379
|
+
const item = { type: "listItem", content: [] };
|
|
380
|
+
top().node.content.push(item);
|
|
381
|
+
stack.push({ node: item, kind: "item", implicit: true });
|
|
382
|
+
}
|
|
383
|
+
return top().node.content;
|
|
384
|
+
};
|
|
385
|
+
const lastBlock = () => {
|
|
386
|
+
const blocks = top().node.content;
|
|
387
|
+
return blocks[blocks.length - 1];
|
|
388
|
+
};
|
|
389
|
+
const open = (type, headingLevel = 1, pre = false, align = undefined) => {
|
|
224
390
|
inline = [];
|
|
225
391
|
blockType = type;
|
|
226
392
|
level = headingLevel;
|
|
393
|
+
blockAlign = align;
|
|
227
394
|
blockPre = pre;
|
|
228
395
|
afterSpace = true;
|
|
229
396
|
};
|
|
@@ -239,22 +406,33 @@ function readHTML(html) {
|
|
|
239
406
|
// Non-breaking spaces survive the trimming above, then become ordinary spaces.
|
|
240
407
|
for (const node of inline) {
|
|
241
408
|
if (node.type === "text")
|
|
242
|
-
node.text = node.text.replace(
|
|
409
|
+
node.text = node.text.replace(/ /g, " ");
|
|
243
410
|
}
|
|
244
411
|
const content = inline.filter((node) => node.type !== "text" || node.text);
|
|
245
|
-
if (content.length || keepEmpty) {
|
|
246
|
-
blocks.push(blockType === "heading"
|
|
247
|
-
? { type: "heading", attrs: { level }, content }
|
|
248
|
-
: { type: "paragraph", content });
|
|
249
|
-
}
|
|
250
412
|
inline = null;
|
|
413
|
+
if (!content.length && !keepEmpty)
|
|
414
|
+
return;
|
|
415
|
+
const attrs = {};
|
|
416
|
+
if (blockType === "heading")
|
|
417
|
+
attrs.level = level;
|
|
418
|
+
if (blockAlign && blockAlign !== "start")
|
|
419
|
+
attrs.align = blockAlign;
|
|
420
|
+
container().push({
|
|
421
|
+
type: blockType,
|
|
422
|
+
...(Object.keys(attrs).length ? { attrs } : {}),
|
|
423
|
+
...(content.length ? { content } : {}),
|
|
424
|
+
});
|
|
251
425
|
};
|
|
252
426
|
const addText = (raw, marks, pre) => {
|
|
253
427
|
// Source formatting between blocks ("</p>\n<br>\n<p>") is not content.
|
|
254
428
|
if (!inline && !pre && !/[^ \t\n\r\f]/.test(raw))
|
|
255
429
|
return;
|
|
256
|
-
if (!inline)
|
|
430
|
+
if (!inline) {
|
|
431
|
+
// Text of its own after Word list paragraphs ends them (it is not part of an item).
|
|
432
|
+
if (stack.some((entry) => entry.word))
|
|
433
|
+
closeWordLists();
|
|
257
434
|
open("paragraph", 1, pre);
|
|
435
|
+
}
|
|
258
436
|
const lines = pre ? raw.replace(/\r\n?/g, "\n").split("\n") : [raw];
|
|
259
437
|
lines.forEach((line, i) => {
|
|
260
438
|
if (i > 0)
|
|
@@ -265,7 +443,8 @@ function readHTML(html) {
|
|
|
265
443
|
if (!text)
|
|
266
444
|
return;
|
|
267
445
|
afterSpace = !pre && text.endsWith(" ");
|
|
268
|
-
|
|
446
|
+
// A link's own look (Google Docs' blue underline) is the link's, not formatting.
|
|
447
|
+
const markJSON = [...marks.values()].filter((mark) => !marks.has("link") || (mark.type !== "underline" && mark.type !== "textColor"));
|
|
269
448
|
inline.push({
|
|
270
449
|
type: "text",
|
|
271
450
|
text,
|
|
@@ -273,13 +452,14 @@ function readHTML(html) {
|
|
|
273
452
|
});
|
|
274
453
|
});
|
|
275
454
|
};
|
|
276
|
-
/** An explicit page break: in the open block, else at the end of the previous
|
|
455
|
+
/** An explicit page break: in the open block, else at the end of the previous textblock. */
|
|
277
456
|
const addPageBreak = () => {
|
|
278
|
-
const previous =
|
|
457
|
+
const previous = lastBlock();
|
|
279
458
|
if (inline)
|
|
280
459
|
inline.push({ type: "pageBreak" });
|
|
281
|
-
else if (previous)
|
|
460
|
+
else if (previous && (previous.type === "paragraph" || previous.type === "heading")) {
|
|
282
461
|
previous.content = [...(previous.content ?? []), { type: "pageBreak" }];
|
|
462
|
+
}
|
|
283
463
|
else {
|
|
284
464
|
open("paragraph");
|
|
285
465
|
inline?.push({ type: "pageBreak" });
|
|
@@ -289,7 +469,7 @@ function readHTML(html) {
|
|
|
289
469
|
const addBreak = () => {
|
|
290
470
|
// A <br> between blocks is an empty line (Google Docs writes empty paragraphs this way).
|
|
291
471
|
if (!inline) {
|
|
292
|
-
|
|
472
|
+
container().push({ type: "paragraph" });
|
|
293
473
|
return;
|
|
294
474
|
}
|
|
295
475
|
const list = inline;
|
|
@@ -299,10 +479,97 @@ function readHTML(html) {
|
|
|
299
479
|
list.push({ type: "hardBreak" });
|
|
300
480
|
afterSpace = true;
|
|
301
481
|
};
|
|
482
|
+
/** Closes the top container: an item gets its first paragraph, a list goes to its parent. */
|
|
483
|
+
const pop = () => {
|
|
484
|
+
const container = stack.pop();
|
|
485
|
+
if (container.kind === "item" && container.implicit && !container.node.content?.length) {
|
|
486
|
+
// An item opened for content that never came (`<ul><ul></ul></ul>`): not an empty bullet.
|
|
487
|
+
const items = top().node.content;
|
|
488
|
+
items.splice(items.indexOf(container.node), 1);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (container.kind === "item")
|
|
492
|
+
finishItem(container.node);
|
|
493
|
+
if (container.kind === "list" && container.node.content?.length) {
|
|
494
|
+
container.parent?.push(container.node);
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
/** Opens a list; one directly inside a list (sloppy HTML, Google Docs) nests in its last item. */
|
|
498
|
+
const openList = (ordered, start, word) => {
|
|
499
|
+
close(false);
|
|
500
|
+
if (top().kind === "list") {
|
|
501
|
+
const items = top().node.content;
|
|
502
|
+
let item = items[items.length - 1];
|
|
503
|
+
if (!item) {
|
|
504
|
+
item = { type: "listItem", content: [] };
|
|
505
|
+
items.push(item);
|
|
506
|
+
}
|
|
507
|
+
stack.push({ node: item, kind: "item", implicit: true });
|
|
508
|
+
}
|
|
509
|
+
const node = {
|
|
510
|
+
type: ordered ? "orderedList" : "bulletList",
|
|
511
|
+
...(ordered && start !== 1 && Number.isInteger(start) && start >= 0 && start <= 99_999
|
|
512
|
+
? { attrs: { start } }
|
|
513
|
+
: {}),
|
|
514
|
+
content: [],
|
|
515
|
+
};
|
|
516
|
+
stack.push({
|
|
517
|
+
node,
|
|
518
|
+
kind: "list",
|
|
519
|
+
parent: top().node.content,
|
|
520
|
+
...(word && { word }),
|
|
521
|
+
});
|
|
522
|
+
};
|
|
523
|
+
const openItem = (word) => {
|
|
524
|
+
close(false);
|
|
525
|
+
while (top().kind === "item" && (top().implicit || word))
|
|
526
|
+
pop();
|
|
527
|
+
const item = { type: "listItem", content: [] };
|
|
528
|
+
top().node.content.push(item);
|
|
529
|
+
stack.push({ node: item, kind: "item", ...(word && { word }) });
|
|
530
|
+
};
|
|
531
|
+
/** Word lists are flat paragraphs with levels: open and close lists to nest them. */
|
|
532
|
+
const wordItem = (item) => {
|
|
533
|
+
close(false);
|
|
534
|
+
const wordList = () => {
|
|
535
|
+
for (let i = stack.length - 1; i > 0; i--) {
|
|
536
|
+
const entry = stack[i];
|
|
537
|
+
if (entry.kind === "list" && entry.word)
|
|
538
|
+
return { entry, index: i };
|
|
539
|
+
}
|
|
540
|
+
return null;
|
|
541
|
+
};
|
|
542
|
+
for (let found = wordList(); found; found = wordList()) {
|
|
543
|
+
const { word } = found.entry;
|
|
544
|
+
if (!word)
|
|
545
|
+
break;
|
|
546
|
+
const same = word.level === item.level && word.list === item.list && word.ordered === item.ordered;
|
|
547
|
+
if (word.level < item.level || (same && word.level === item.level))
|
|
548
|
+
break;
|
|
549
|
+
while (stack.length > found.index)
|
|
550
|
+
pop();
|
|
551
|
+
}
|
|
552
|
+
const current = wordList();
|
|
553
|
+
const word = { list: item.list, level: item.level, ordered: item.ordered };
|
|
554
|
+
if (!current || current.entry.word?.level !== item.level) {
|
|
555
|
+
openList(item.ordered, item.start, word);
|
|
556
|
+
}
|
|
557
|
+
else {
|
|
558
|
+
// A sibling item: close the previous one (and anything nested in it).
|
|
559
|
+
while (stack.length > current.index + 1)
|
|
560
|
+
pop();
|
|
561
|
+
}
|
|
562
|
+
openItem(word);
|
|
563
|
+
};
|
|
564
|
+
const closeWordLists = () => {
|
|
565
|
+
close(false);
|
|
566
|
+
while (stack.some((entry) => entry.word))
|
|
567
|
+
pop();
|
|
568
|
+
};
|
|
302
569
|
/** Walks `node`; returns whether it contained a block element. */
|
|
303
|
-
const walk = (node,
|
|
570
|
+
const walk = (node, context) => {
|
|
304
571
|
if (node.nodeType === 3) {
|
|
305
|
-
addText(node.data, marks, pre);
|
|
572
|
+
addText(node.data, context.marks, context.pre);
|
|
306
573
|
return false;
|
|
307
574
|
}
|
|
308
575
|
if (node.nodeType !== 1)
|
|
@@ -322,28 +589,80 @@ function readHTML(html) {
|
|
|
322
589
|
addBreak();
|
|
323
590
|
return false;
|
|
324
591
|
}
|
|
325
|
-
const childMarks = marksOf(element, marks);
|
|
326
592
|
const whiteSpace = element.style?.whiteSpace ?? "";
|
|
327
|
-
const
|
|
328
|
-
|
|
593
|
+
const child = {
|
|
594
|
+
marks: marksOf(element, context.marks),
|
|
595
|
+
pre: context.pre || tag === "pre" || whiteSpace.startsWith("pre"),
|
|
596
|
+
align: BLOCK_TAGS.has(tag) ? (alignOf(element) ?? context.align) : context.align,
|
|
597
|
+
};
|
|
598
|
+
const children = () => {
|
|
329
599
|
let hasBlock = false;
|
|
330
|
-
for (const
|
|
331
|
-
hasBlock = walk(
|
|
600
|
+
for (const node of element.childNodes)
|
|
601
|
+
hasBlock = walk(node, child) || hasBlock;
|
|
332
602
|
return hasBlock;
|
|
333
|
-
}
|
|
603
|
+
};
|
|
604
|
+
if (!BLOCK_TAGS.has(tag))
|
|
605
|
+
return children();
|
|
334
606
|
sawBlock = true;
|
|
607
|
+
// Word list paragraphs: <p> only (a numbered Word heading stays a heading), and not inside an
|
|
608
|
+
// HTML list (Outlook writes `<li style="mso-list:…">` in real lists).
|
|
609
|
+
const word = tag === "p" && !stack.some((entry) => entry.kind === "list" && !entry.word)
|
|
610
|
+
? wordListItem(element)
|
|
611
|
+
: null;
|
|
612
|
+
if (word) {
|
|
613
|
+
wordItem(word);
|
|
614
|
+
open("paragraph", 1, child.pre, child.align);
|
|
615
|
+
children();
|
|
616
|
+
close(true);
|
|
617
|
+
return true;
|
|
618
|
+
}
|
|
619
|
+
// Word wraps its content in a <div>: only a block of its own content ends Word lists.
|
|
620
|
+
if (!/^(div|body|section|article|main)$/.test(tag))
|
|
621
|
+
closeWordLists();
|
|
622
|
+
// A list or item closes everything opened inside it, so unbalanced input cannot leak.
|
|
623
|
+
const base = stack.length;
|
|
624
|
+
const closeTo = (height) => {
|
|
625
|
+
close(false);
|
|
626
|
+
while (stack.length > height)
|
|
627
|
+
pop();
|
|
628
|
+
};
|
|
629
|
+
if (tag === "ul" || tag === "ol") {
|
|
630
|
+
const start = Number.parseInt(element.getAttribute("start") ?? "", 10);
|
|
631
|
+
openList(tag === "ol", Number.isNaN(start) ? 1 : start);
|
|
632
|
+
children();
|
|
633
|
+
closeTo(base);
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
if (tag === "li" && stack.some((entry) => entry.kind === "list")) {
|
|
637
|
+
// Inside a list item that is itself still open, an <li> is a sibling: close down to a list.
|
|
638
|
+
while (top().kind === "item")
|
|
639
|
+
closeTo(stack.length - 1);
|
|
640
|
+
const height = stack.length;
|
|
641
|
+
openItem();
|
|
642
|
+
children();
|
|
643
|
+
closeTo(height);
|
|
644
|
+
return true;
|
|
645
|
+
}
|
|
646
|
+
if (tag === "hr") {
|
|
647
|
+
close(false);
|
|
648
|
+
container().push({ type: "horizontalRule" });
|
|
649
|
+
return true;
|
|
650
|
+
}
|
|
335
651
|
close(false);
|
|
336
652
|
const heading = /^h([1-6])$/.exec(tag);
|
|
337
|
-
open(heading ? "heading" : "paragraph", heading ? Number(heading[1]) : 1,
|
|
338
|
-
|
|
339
|
-
for (const child of element.childNodes)
|
|
340
|
-
hasBlock = walk(child, childMarks, childPre) || hasBlock;
|
|
653
|
+
open(heading ? "heading" : "paragraph", heading ? Number(heading[1]) : 1, child.pre, child.align);
|
|
654
|
+
const hasBlock = children();
|
|
341
655
|
// <p></p> is an empty line; a container such as <div><p>…</p></div> adds none.
|
|
342
|
-
close(!hasBlock &&
|
|
656
|
+
close(!hasBlock && !/^(ol|ul|dl|table|tbody|thead|tfoot|tr|li)$/.test(tag));
|
|
343
657
|
return true;
|
|
344
658
|
};
|
|
345
|
-
walk(parsed.body, new
|
|
659
|
+
walk(parsed.body, { marks: new Map(), pre: false, align: undefined });
|
|
346
660
|
close(false);
|
|
347
|
-
|
|
661
|
+
while (stack.length > 1)
|
|
662
|
+
pop();
|
|
663
|
+
const content = doc.content;
|
|
664
|
+
return content.length
|
|
665
|
+
? { content: { type: "doc", content }, open: !sawBlock }
|
|
666
|
+
: null;
|
|
348
667
|
}
|
|
349
668
|
//# sourceMappingURL=clipboard.js.map
|