@folijs/view 0.0.0-stage → 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/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { FOLI_MIME, htmlToDoc, textToDoc } from "./clipboard.js";
2
+ export { EditorView, type EditorViewOptions, keyName } from "./view.js";
@@ -0,0 +1,281 @@
1
+ import type { DocumentSettings } from "@folijs/core";
2
+
3
+ /** CSS pixels per millimetre (CSS fixes 1in = 96px = 25.4mm). */
4
+ export const PX_PER_MM = 96 / 25.4;
5
+
6
+ /** A rendered block's border-box height and vertical margins, in CSS px. */
7
+ export interface BlockBox {
8
+ height: number;
9
+ marginTop: number;
10
+ marginBottom: number;
11
+ /**
12
+ * The bottom of each line box, from the block's top (the last one is `height`). Only called
13
+ * for a block that does not fit where it is, or has page breaks, since measuring lines is
14
+ * expensive.
15
+ */
16
+ lines(): readonly number[];
17
+ /** Keep on the same page as the start of the next block (headings). */
18
+ keepWithNext?: boolean;
19
+ /** The lines that end with an explicit page break (indices into `lines()`), if any. */
20
+ breaksAfter?(): readonly number[];
21
+ }
22
+
23
+ /** The lines `[fromLine, toLine)` of a block, placed on one page (`toLine` Infinity: to the end). */
24
+ export interface Fragment {
25
+ page: number;
26
+ fromLine: number;
27
+ toLine: number;
28
+ }
29
+
30
+ export interface FlowRules {
31
+ /** Fewest lines of a split block left at the bottom of a page. */
32
+ orphans: number;
33
+ /** Fewest lines of a split block carried to the top of the next page. */
34
+ widows: number;
35
+ }
36
+
37
+ export const DEFAULT_RULES: FlowRules = { orphans: 2, widows: 2 };
38
+
39
+ /** Height of a page's content box (page height minus top and bottom margins), in CSS px. */
40
+ export function contentHeight({ pageSize, margins }: DocumentSettings): number {
41
+ return (pageSize.height - margins.top - margins.bottom) * PX_PER_MM;
42
+ }
43
+
44
+ // Half a pixel of slack: measured heights are fractional and rounding must not add a page.
45
+ const SLACK = 0.5;
46
+
47
+ /** Where the flow stands before a block: shared by a full and an incremental flow. */
48
+ export interface FlowState {
49
+ page: number;
50
+ used: number;
51
+ previousMargin: number;
52
+ onPage: number;
53
+ /** An explicit page break ended the previous block: the next one starts a new page. */
54
+ breakPending: boolean;
55
+ }
56
+
57
+ /**
58
+ * Page flow: the fragments of each block, in order. Blocks fill a page in order; a block that
59
+ * does not fit is split at a line boundary, the lines that fit staying on the page, the rest
60
+ * continuing at the top of the next one (as many pages as it takes). A page with room for no
61
+ * line of the next block ends; an empty page always takes at least one line.
62
+ *
63
+ * Rules:
64
+ * - Explicit page breaks: the line holding one ends its page.
65
+ * - Widows and orphans: a split leaves at least `orphans` lines at the bottom of a page and
66
+ * carries at least `widows` lines to the next; a block too short for both moves whole. Not
67
+ * applied where only an empty page could hold the lines, nor across an explicit break.
68
+ * - Keep with next: a `keepWithNext` block (and a chain of them) moves to the next page when
69
+ * the block after it would start there, unless it already starts its page or the move would
70
+ * not bring them together (then the flow stays as it was).
71
+ *
72
+ * Spacing follows CSS inside a padded page: the first block keeps its top margin, adjacent
73
+ * margins collapse to the larger, and the last block's bottom margin stays inside the page
74
+ * (it does not collapse into the padding), so it must fit too. Fragments are rendered without
75
+ * the margins at their split edges: a continued fragment has no bottom margin, a continuation
76
+ * no top margin.
77
+ *
78
+ * shortcut: positive margins only (negative margins collapse differently).
79
+ */
80
+ export function flow(
81
+ boxes: readonly BlockBox[],
82
+ pageHeight: number,
83
+ rules: FlowRules = DEFAULT_RULES,
84
+ ): Fragment[][] {
85
+ return flowFrom(boxes, pageHeight, rules).fragments;
86
+ }
87
+
88
+ /** A flow with the state before each block (and after the last), for the next incremental one. */
89
+ export interface FlowResult {
90
+ fragments: Fragment[][];
91
+ states: FlowState[];
92
+ }
93
+
94
+ /** What an incremental flow may reuse from the previous one. */
95
+ export interface Reuse {
96
+ previous: FlowResult;
97
+ /** Blocks before this index are the previous flow's first blocks, with the same boxes. */
98
+ from: number;
99
+ /**
100
+ * The previous index of block `i` when it and every block after it are unchanged from the
101
+ * previous flow (the common tail of an edit), else -1.
102
+ */
103
+ previousIndex(i: number): number;
104
+ }
105
+
106
+ /**
107
+ * `flow`, reusing a previous one: it starts at `reuse.from` (backed up over a chain of
108
+ * keep-with-next blocks, whose placement depends on what follows) with the previous state
109
+ * there, and once the state before an unchanged block equals the previous state before it, the
110
+ * rest is the previous flow's. The result is the same as a full flow.
111
+ */
112
+ export function flowFrom(
113
+ boxes: readonly BlockBox[],
114
+ pageHeight: number,
115
+ rules: FlowRules = DEFAULT_RULES,
116
+ reuse?: Reuse,
117
+ ): FlowResult {
118
+ let start = reuse ? Math.min(reuse.from, boxes.length, reuse.previous.fragments.length) : 0;
119
+ while (start > 0 && boxes[start - 1]?.keepWithNext) start--;
120
+ const result: Fragment[][] = reuse ? reuse.previous.fragments.slice(0, start) : [];
121
+ const snapshots: FlowState[] = reuse ? reuse.previous.states.slice(0, start) : [];
122
+ let state: FlowState = (
123
+ reuse && reuse.previous.states[start]
124
+ ? { ...reuse.previous.states[start] }
125
+ : { page: 0, used: 0, previousMargin: 0, onPage: 0, breakPending: false }
126
+ ) as FlowState;
127
+ /** Blocks that start a page because the keep-with-next rule moved them. */
128
+ const breakBefore = new Set<number>();
129
+ const newPage = () => {
130
+ state.page++;
131
+ state.used = 0;
132
+ state.onPage = 0;
133
+ };
134
+
135
+ const place = (box: BlockBox, index: number): Fragment[] => {
136
+ if ((state.breakPending || breakBefore.has(index)) && state.onPage) newPage();
137
+ state.breakPending = false;
138
+ const above = state.previousMargin;
139
+ state.previousMargin = box.marginBottom;
140
+ const gap = () => (state.onPage ? Math.max(above, box.marginTop) : box.marginTop);
141
+ const forced = box.breaksAfter?.() ?? [];
142
+ if (
143
+ !forced.length &&
144
+ state.used + gap() + box.height + box.marginBottom <= pageHeight + SLACK
145
+ ) {
146
+ state.used += gap() + box.height;
147
+ state.onPage++;
148
+ return [{ page: state.page, fromLine: 0, toLine: Infinity }];
149
+ }
150
+ const lines = box.lines();
151
+ const count = lines.length;
152
+ const breaks = new Set(forced.filter((line) => line >= 0 && line < count));
153
+ const fragments: Fragment[] = [];
154
+ let line = 0;
155
+ while (line < count) {
156
+ // The lines up to the next explicit break (or the end) can be split freely.
157
+ let segmentEnd = line;
158
+ while (segmentEnd < count && !breaks.has(segmentEnd)) segmentEnd++;
159
+ segmentEnd = Math.min(segmentEnd + 1, count);
160
+ const top = line ? (lines[line - 1] as number) : 0;
161
+ // Only the block's first fragment has the gap above it.
162
+ const spacing = line === 0 ? gap() : 0;
163
+ let end = line;
164
+ while (end < segmentEnd) {
165
+ const bottom = (lines[end] as number) - top + (end + 1 === count ? box.marginBottom : 0);
166
+ if (state.used + spacing + bottom > pageHeight + SLACK) break;
167
+ end++;
168
+ }
169
+ if (end < segmentEnd && end > line) {
170
+ // A natural split: keep `widows` lines for the next page and `orphans` on this one.
171
+ const kept = Math.min(end, segmentEnd - rules.widows);
172
+ if (kept - line >= rules.orphans) end = kept;
173
+ else if (state.onPage) end = line;
174
+ }
175
+ if (end === line) {
176
+ if (state.onPage) {
177
+ newPage();
178
+ continue;
179
+ }
180
+ end = line + 1; // a line taller than a page is placed anyway
181
+ }
182
+ fragments.push({ page: state.page, fromLine: line, toLine: end });
183
+ state.used += spacing + (lines[end - 1] as number) - top;
184
+ state.onPage++;
185
+ line = end;
186
+ const broken = breaks.has(end - 1);
187
+ if (line < count) newPage();
188
+ else if (broken) state.breakPending = true;
189
+ }
190
+ // Moved whole to a later page: not split.
191
+ const [only] = fragments;
192
+ if (fragments.length === 1 && only && !forced.length) only.toLine = Infinity;
193
+ return fragments;
194
+ };
195
+
196
+ /** The flow as it was before a keep-with-next move, by the block that triggered it. */
197
+ const attempts = new Map<
198
+ number,
199
+ { first: number; result: Fragment[][]; snapshots: FlowState[]; state: FlowState }
200
+ >();
201
+ let index = start;
202
+ while (index < boxes.length) {
203
+ // Realigned with the previous flow: the rest is unchanged (no keep-with-next decision
204
+ // about this block, made with the block before it, is pending). The block before it must
205
+ // be unchanged too: had it been keep-with-next before the edit, the previous flow from
206
+ // here holds a decision about a chain that no longer exists.
207
+ const was =
208
+ reuse && index > start && !attempts.size && reuse.previousIndex(index - 1) >= 0
209
+ ? reuse.previousIndex(index)
210
+ : -1;
211
+ const before = was >= 0 ? reuse?.previous.states[was] : undefined;
212
+ if (before && !boxes[index - 1]?.keepWithNext && sameState(before, state)) {
213
+ const previous = reuse as Reuse;
214
+ result.length = index;
215
+ snapshots.length = index;
216
+ result.push(...previous.previous.fragments.slice(was));
217
+ snapshots.push(...previous.previous.states.slice(was, -1));
218
+ return {
219
+ fragments: result,
220
+ states: [...snapshots, { ...(previous.previous.states.at(-1) as FlowState) }],
221
+ };
222
+ }
223
+ snapshots[index] = { ...state };
224
+ const fragments = place(boxes[index] as BlockBox, index);
225
+ result[index] = fragments;
226
+ const previous = result[index - 1];
227
+ const startsLater =
228
+ previous !== undefined &&
229
+ (fragments[0]?.page ?? 0) > (previous[previous.length - 1]?.page ?? 0);
230
+ const attempt = attempts.get(index);
231
+ if (attempt) {
232
+ attempts.delete(index);
233
+ // The move did not bring them together (the block does not fit after the heading on a
234
+ // page of its own either): keep the flow as it was.
235
+ if (startsLater) {
236
+ result.splice(attempt.first, result.length - attempt.first, ...attempt.result);
237
+ snapshots.splice(attempt.first, snapshots.length - attempt.first, ...attempt.snapshots);
238
+ state = attempt.state;
239
+ index++;
240
+ continue;
241
+ }
242
+ }
243
+ if (startsLater && boxes[index - 1]?.keepWithNext) {
244
+ // The chain of keep-with-next blocks before this one, each whole on one page.
245
+ let first = index - 1;
246
+ while (
247
+ first > 0 &&
248
+ boxes[first - 1]?.keepWithNext &&
249
+ result[first - 1]?.length === 1 &&
250
+ result[first - 1]?.[0]?.page === result[first]?.[0]?.page
251
+ )
252
+ first--;
253
+ const beforeFirst = snapshots[first] as FlowState;
254
+ if (!breakBefore.has(first) && beforeFirst.onPage > 0 && result[first]?.length === 1) {
255
+ attempts.set(index, {
256
+ first,
257
+ result: result.slice(first),
258
+ snapshots: snapshots.slice(first),
259
+ state: { ...state },
260
+ });
261
+ breakBefore.add(first);
262
+ state = { ...beforeFirst };
263
+ result.length = first;
264
+ index = first;
265
+ continue;
266
+ }
267
+ }
268
+ index++;
269
+ }
270
+ return { fragments: result, states: [...snapshots.slice(0, boxes.length), { ...state }] };
271
+ }
272
+
273
+ function sameState(a: FlowState, b: FlowState): boolean {
274
+ return (
275
+ a.page === b.page &&
276
+ a.used === b.used &&
277
+ a.previousMargin === b.previousMargin &&
278
+ a.onPage === b.onPage &&
279
+ a.breakPending === b.breakPending
280
+ );
281
+ }
package/src/render.ts ADDED
@@ -0,0 +1,197 @@
1
+ import type { Mark, Node as ModelNode, SimpleMarkName } from "@folijs/core";
2
+
3
+ // Every mark without attributes has a tag. Marks with attributes are rendered by `markElement`;
4
+ // marks of other schemas fall back to <span>.
5
+ const MARK_TAGS: ReadonlyMap<string, string> = new Map(
6
+ Object.entries({
7
+ bold: "strong",
8
+ italic: "em",
9
+ underline: "u",
10
+ strike: "s",
11
+ } satisfies Record<SimpleMarkName, string>),
12
+ );
13
+
14
+ /** Marks the <br> of an explicit page break. */
15
+ export const PAGE_BREAK_ATTR = "data-page-break";
16
+
17
+ /** Marks a container element (list, list item) the view created around blocks. */
18
+ export const WRAPPER_ATTR = "data-foli-wrapper";
19
+
20
+ /** The element for a container node: lists and list items; anything else is a <div>. */
21
+ const WRAPPER_TAGS: ReadonlyMap<string, string> = new Map([
22
+ ["bulletList", "ul"],
23
+ ["orderedList", "ol"],
24
+ ["listItem", "li"],
25
+ ]);
26
+
27
+ /**
28
+ * A rendered inline leaf (a text node or hard break) and where it sits in its block's content.
29
+ * A text node split across fragments is two leaves, one per fragment.
30
+ */
31
+ export interface LeafDesc {
32
+ readonly dom: Node;
33
+ readonly offset: number;
34
+ readonly size: number;
35
+ }
36
+
37
+ /**
38
+ * View descriptor of one block: the model node, its elements and its leaves. A block split
39
+ * across pages has one element per page (its fragments, in order); `dom` is the first.
40
+ */
41
+ export interface BlockDesc {
42
+ readonly node: ModelNode;
43
+ readonly dom: HTMLElement;
44
+ readonly fragments: readonly HTMLElement[];
45
+ /** Content offsets where each fragment after the first starts (sorted, inside the content). */
46
+ readonly splits: readonly number[];
47
+ readonly leaves: readonly LeafDesc[];
48
+ }
49
+
50
+ /** The element for a mark: a tag, a link, or a span with a color. Values come validated. */
51
+ function markElement(mark: Mark, doc: Document): HTMLElement {
52
+ const { name } = mark.type;
53
+ if (name === "link") {
54
+ const a = doc.createElement("a");
55
+ // The schema only lets safe hrefs into a document (isSafeHref); clicks do not navigate.
56
+ a.setAttribute("href", String(mark.attrs.href));
57
+ return a;
58
+ }
59
+ const element = doc.createElement(MARK_TAGS.get(name) ?? "span");
60
+ if (name === "textColor") element.style.color = String(mark.attrs.color);
61
+ if (name === "highlight") element.style.backgroundColor = String(mark.attrs.color);
62
+ return element;
63
+ }
64
+
65
+ /** The element for a block: a heading or paragraph tag, or a rule. */
66
+ function blockTag(node: ModelNode): string {
67
+ if (node.type.name === "heading") return `h${String(node.attrs.level)}`;
68
+ if (node.type.name === "horizontalRule") return "hr";
69
+ return "p";
70
+ }
71
+
72
+ /**
73
+ * Renders one leaf block (a textblock, or a block leaf such as a rule) with
74
+ * createElement/textContent only (never innerHTML), and records its leaves for position
75
+ * mapping. With `splits`, a textblock's content is rendered as several fragments of the same
76
+ * element type: each continued fragment has no bottom margin and each continuation no top
77
+ * margin, so together they take the same height as the whole block.
78
+ */
79
+ export function renderBlock(
80
+ node: ModelNode,
81
+ doc: Document,
82
+ splits: readonly number[] = [],
83
+ ): BlockDesc {
84
+ const tag = blockTag(node);
85
+ const align = node.attrs.align;
86
+ const fragments = [0, ...splits].map((_, i, all) => {
87
+ const fragment = doc.createElement(tag);
88
+ if (typeof align === "string" && align !== "start") fragment.style.textAlign = align;
89
+ if (all.length > 1) {
90
+ fragment.dataset.fragment = String(i);
91
+ if (i > 0) fragment.style.marginTop = "0";
92
+ if (i < all.length - 1) fragment.style.marginBottom = "0";
93
+ }
94
+ return fragment;
95
+ });
96
+ const leaves: LeafDesc[] = [];
97
+ const dom = fragments[0] as HTMLElement;
98
+ // A block leaf (a rule) has no content: nothing to map, nothing to split.
99
+ if (!node.isTextblock) return { node, dom, fragments, splits, leaves };
100
+ /** The fragment that holds content offset `at` (a split offset starts the next fragment). */
101
+ const fragmentAt = (at: number) => {
102
+ let i = 0;
103
+ while (i < splits.length && (splits[i] as number) <= at) i++;
104
+ return fragments[i] as HTMLElement;
105
+ };
106
+ node.forEach((child, offset) => {
107
+ if (!child.isText) {
108
+ // A hard break or a page break: both end their line (the flow ends the page at a page break).
109
+ const br = doc.createElement("br");
110
+ if (child.type.name === "pageBreak") br.setAttribute(PAGE_BREAK_ATTR, "");
111
+ leaves.push({ dom: br, offset, size: child.nodeSize });
112
+ // Text only: a mark wrapper around <br> would add nothing visible.
113
+ fragmentAt(offset).append(br);
114
+ return;
115
+ }
116
+ const text = child.text ?? "";
117
+ const cuts = splits.filter((split) => split > offset && split < offset + text.length);
118
+ let from = offset;
119
+ for (const to of [...cuts, offset + text.length]) {
120
+ const leaf = doc.createTextNode(text.slice(from - offset, to - offset));
121
+ leaves.push({ dom: leaf, offset: from, size: to - from });
122
+ let outer: Node = leaf;
123
+ // Marks are in canonical order, outermost first (a link wraps the formatting inside it).
124
+ for (const mark of [...child.marks].reverse()) {
125
+ const wrapper = markElement(mark, doc);
126
+ wrapper.append(outer);
127
+ outer = wrapper;
128
+ }
129
+ fragmentAt(from).append(outer);
130
+ from = to;
131
+ }
132
+ });
133
+ // An empty block, or one ending in a hard break, needs an extra <br> to show its last line.
134
+ if (!node.lastChild?.isText)
135
+ (fragments[fragments.length - 1] as HTMLElement).append(doc.createElement("br"));
136
+ // A fragment's last line is not the paragraph's last line: justified text stays justified up
137
+ // to the page break (CSS aligns a block's last line to the start). `text-align-last` also
138
+ // applies to every line before a forced break, which the paragraph shows start-aligned, so it
139
+ // is only set on fragments without one.
140
+ // shortcut: a fragment holding a hard break keeps its last line start-aligned at the page break; fixing that needs a per-line wrapper.
141
+ if (align === "justify")
142
+ for (const fragment of fragments.slice(0, -1))
143
+ if (!fragment.querySelector("br")) fragment.style.textAlignLast = "justify";
144
+ return { node, dom, fragments, splits, leaves };
145
+ }
146
+
147
+ /**
148
+ * Creates the element for a container (list, list item). It takes no vertical space of its own
149
+ * (block margins and paddings 0): the page flow treats the blocks inside as siblings, whose
150
+ * margins collapse through it (ADR-0004).
151
+ */
152
+ /** Every container element the view created (a set: checked for every block on every render). */
153
+ const wrappers = new WeakSet<Node>();
154
+
155
+ export function createWrapper(node: ModelNode, doc: Document): HTMLElement {
156
+ const element = doc.createElement(WRAPPER_TAGS.get(node.type.name) ?? "div");
157
+ element.setAttribute(WRAPPER_ATTR, "");
158
+ wrappers.add(element);
159
+ const { style } = element;
160
+ style.marginTop = style.marginBottom = style.paddingTop = style.paddingBottom = "0";
161
+ return element;
162
+ }
163
+
164
+ /** Whether `element` is the container element `createWrapper` makes for `node`. */
165
+ export function isWrapperFor(element: Node | null, node: ModelNode): element is HTMLElement {
166
+ return (
167
+ element !== null &&
168
+ wrappers.has(element) &&
169
+ (element as HTMLElement).localName === (WRAPPER_TAGS.get(node.type.name) ?? "div")
170
+ );
171
+ }
172
+
173
+ /** Whether `node` is a container element the view created. */
174
+ export function isWrapper(node: Node | null): node is HTMLElement {
175
+ return node !== null && wrappers.has(node);
176
+ }
177
+
178
+ /**
179
+ * Renders a fragment of blocks as one DOM tree, for the clipboard: containers become their
180
+ * elements (with the list's start number), leaf blocks as in the editor, unsplit.
181
+ */
182
+ export function renderTree(content: Iterable<ModelNode>, parent: Node, doc: Document): void {
183
+ for (const node of content) {
184
+ if (node.isTextblock || node.isLeaf) {
185
+ parent.appendChild(renderBlock(node, doc).dom);
186
+ continue;
187
+ }
188
+ const element = createWrapper(node, doc);
189
+ wrappers.delete(element);
190
+ element.removeAttribute(WRAPPER_ATTR);
191
+ element.removeAttribute("style");
192
+ const start = node.attrs.start;
193
+ if (typeof start === "number" && start !== 1) element.setAttribute("start", String(start));
194
+ renderTree(node.content.content, element, doc);
195
+ parent.appendChild(element);
196
+ }
197
+ }