@folijs/view 0.2.0 → 0.4.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.
@@ -18,6 +18,14 @@ export interface BlockBox {
18
18
  keepWithNext?: boolean;
19
19
  /** The lines that end with an explicit page break (indices into `lines()`), if any. */
20
20
  breaksAfter?(): readonly number[];
21
+ /** Height shown again at the top of each fragment after the first (a table's header rows). */
22
+ repeat?: number;
23
+ /**
24
+ * Content height of the pages this block goes on, when not the flow's (a section's page). A
25
+ * block with another page height than the one before it must start a page (an explicit
26
+ * break before it): a page has one height.
27
+ */
28
+ pageHeight?: number;
21
29
  }
22
30
 
23
31
  /** The lines `[fromLine, toLine)` of a block, placed on one page (`toLine` Infinity: to the end). */
@@ -32,6 +40,13 @@ export interface FlowRules {
32
40
  orphans: number;
33
41
  /** Fewest lines of a split block carried to the top of the next page. */
34
42
  widows: number;
43
+ /**
44
+ * How margins (paragraph spacing) combine. `css` (the default): as CSS in a padded page.
45
+ * `word`: as Word spaces paragraphs. The space after one and the space before the next add up.
46
+ * A page that a block flowed onto (not one an explicit break started, nor the first) drops
47
+ * the space before its first block. The space after the last block on a page need not fit.
48
+ */
49
+ spacing?: "css" | "word";
35
50
  }
36
51
 
37
52
  export const DEFAULT_RULES: FlowRules = { orphans: 2, widows: 2 };
@@ -52,6 +67,8 @@ export interface FlowState {
52
67
  onPage: number;
53
68
  /** An explicit page break ended the previous block: the next one starts a new page. */
54
69
  breakPending: boolean;
70
+ /** The page is the first or an explicit break started it (Word keeps its first space before). */
71
+ forcedPage: boolean;
55
72
  }
56
73
 
57
74
  /**
@@ -111,7 +128,7 @@ export interface Reuse {
111
128
  */
112
129
  export function flowFrom(
113
130
  boxes: readonly BlockBox[],
114
- pageHeight: number,
131
+ flowHeight: number,
115
132
  rules: FlowRules = DEFAULT_RULES,
116
133
  reuse?: Reuse,
117
134
  ): FlowResult {
@@ -122,27 +139,32 @@ export function flowFrom(
122
139
  let state: FlowState = (
123
140
  reuse && reuse.previous.states[start]
124
141
  ? { ...reuse.previous.states[start] }
125
- : { page: 0, used: 0, previousMargin: 0, onPage: 0, breakPending: false }
142
+ : { page: 0, used: 0, previousMargin: 0, onPage: 0, breakPending: false, forcedPage: true }
126
143
  ) as FlowState;
127
144
  /** Blocks that start a page because the keep-with-next rule moved them. */
128
145
  const breakBefore = new Set<number>();
129
- const newPage = () => {
146
+ const word = rules.spacing === "word";
147
+ const newPage = (forced = false) => {
130
148
  state.page++;
131
149
  state.used = 0;
132
150
  state.onPage = 0;
151
+ state.forcedPage = forced;
133
152
  };
134
153
 
135
154
  const place = (box: BlockBox, index: number): Fragment[] => {
136
- if ((state.breakPending || breakBefore.has(index)) && state.onPage) newPage();
155
+ const pageHeight = box.pageHeight ?? flowHeight;
156
+ if ((state.breakPending || breakBefore.has(index)) && state.onPage) newPage(state.breakPending);
137
157
  state.breakPending = false;
138
158
  const above = state.previousMargin;
139
159
  state.previousMargin = box.marginBottom;
140
- const gap = () => (state.onPage ? Math.max(above, box.marginTop) : box.marginTop);
160
+ const gap = () => {
161
+ if (!state.onPage) return word && !state.forcedPage ? 0 : box.marginTop;
162
+ return word ? above + box.marginTop : Math.max(above, box.marginTop);
163
+ };
164
+ // The bottom margin that must fit on the page (Word lets the space after hang).
165
+ const below = word ? 0 : box.marginBottom;
141
166
  const forced = box.breaksAfter?.() ?? [];
142
- if (
143
- !forced.length &&
144
- state.used + gap() + box.height + box.marginBottom <= pageHeight + SLACK
145
- ) {
167
+ if (!forced.length && state.used + gap() + box.height + below <= pageHeight + SLACK) {
146
168
  state.used += gap() + box.height;
147
169
  state.onPage++;
148
170
  return [{ page: state.page, fromLine: 0, toLine: Infinity }];
@@ -158,11 +180,11 @@ export function flowFrom(
158
180
  while (segmentEnd < count && !breaks.has(segmentEnd)) segmentEnd++;
159
181
  segmentEnd = Math.min(segmentEnd + 1, count);
160
182
  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;
183
+ // Only the block's first fragment has the gap above it; the others repeat its header.
184
+ const spacing = line === 0 ? gap() : (box.repeat ?? 0);
163
185
  let end = line;
164
186
  while (end < segmentEnd) {
165
- const bottom = (lines[end] as number) - top + (end + 1 === count ? box.marginBottom : 0);
187
+ const bottom = (lines[end] as number) - top + (end + 1 === count ? below : 0);
166
188
  if (state.used + spacing + bottom > pageHeight + SLACK) break;
167
189
  end++;
168
190
  }
@@ -276,6 +298,7 @@ function sameState(a: FlowState, b: FlowState): boolean {
276
298
  a.used === b.used &&
277
299
  a.previousMargin === b.previousMargin &&
278
300
  a.onPage === b.onPage &&
279
- a.breakPending === b.breakPending
301
+ a.breakPending === b.breakPending &&
302
+ a.forcedPage === b.forcedPage
280
303
  );
281
304
  }
package/src/render.ts CHANGED
@@ -1,29 +1,8 @@
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
- );
1
+ import type { Node as ModelNode } from "@folijs/core";
13
2
 
14
3
  /** Marks the <br> of an explicit page break. */
15
4
  export const PAGE_BREAK_ATTR = "data-page-break";
16
5
 
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
6
  /**
28
7
  * A rendered inline leaf (a text node or hard break) and where it sits in its block's content.
29
8
  * A text node split across fragments is two leaves, one per fragment.
@@ -46,152 +25,3 @@ export interface BlockDesc {
46
25
  readonly splits: readonly number[];
47
26
  readonly leaves: readonly LeafDesc[];
48
27
  }
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
- }