feat: a section can have its own paper, landscape amid portrait

The page grid was one repeating cycle, so every page had to be the same
size. It is now a table of height runs the placement pass grows as each
section's first page becomes known, and the sheets are one box per page
instead of a repeating gradient — .paper reserves the widest section's
paper, a narrower one takes the difference as a right inset.

Layout ▸ Orientation offers "this section"; the size stays document-wide
in the ribbon but round-trips per section from a file.
This commit is contained in:
Steffen Becker committed 2026-08-14 10:36:52 +02:00
1 parent 12fe4e7239
commit 639fac90fd
18 files changed
+384 -157

No files matched your search

+2 -1
View File
@@ -74,6 +74,7 @@
- Table of contents: generated from headings (H1–H5) with live page numbers and dot leaders, click an entry to jump to its heading; round-trips to ODF `text:table-of-content` and a Word TOC field
- Alphabetical index (References ▸ Index entry, then the Index in the same menu): mark a word — under a key of its own where the index should file it elsewhere — and the index lists every term once, sorted case-insensitively, with all the pages it was marked on. Round-trips as ODF `text:alphabetical-index-mark` + `text:alphabetical-index` (LibreOffice reads both back unchanged) and as Word's `XE` and `INDEX` fields
- Bibliography (References ▸ Citation, then the Bibliography in the index menu): a citation carries its whole source record — short name, type and its fields — so the document needs no database beside it, and the list prints one row per source cited, in document order and without page numbers, as both word processors do. Round-trips as ODF `text:bibliography-mark` + `text:bibliography` (LibreOffice reads every field back and regenerates the list from our entry templates) and as Word's `CITATION` and `BIBLIOGRAPHY` fields over a `b:Sources` custom-XML part — which LibreOffice's own Word export drops, so the record survives our leg and not its
- Section page setup: a section carries its own paper (Layout ▸ Orientation ▸ This section), so a wide table gets its landscape page amid portrait ones. The editor lays it out — the page grid is a table of per-page boxes rather than one repeating cycle, and every page below a section moves with it — and it round-trips as an ODF page layout of its own per master page and a `w:pgSz` per `w:sectPr`
- Comments: annotate a selection (Review tab or the context menu) and work through them in the reviewing pane — edit, resolve, remove, click one to jump to the text it marks. Round-trips to ODF `office:annotation`/`office:annotation-end` (with LibreOffice's `loext:resolved`) and to Word's `w:commentRangeStart`/`-End` + `word/comments.xml`; a LibreOffice point comment, which has no range, attaches to the run before it
- Track changes (Review ▸ Record changes): while recording, typed text is marked as an insertion and deleted text stays in the document struck through instead of going away, each carrying its author and date; consecutive typing is one change, and accept / reject work on the change at the cursor or on all of them. Round-trips to ODF's `text:tracked-changes` registry — `text:change-start`/`-end` around an insertion, `text:change` where a deletion was, its text kept in the registry — and to Word's `w:ins`/`w:del` + `w:delText`
- Footnotes and endnotes (Ctrl+Alt+F / Ctrl+Alt+D): a footnote is drawn at the foot of the page its anchor sits on, with the separator line above it and the body text moved up to make room; endnotes are collected on their own page at the document end. Notes renumber themselves as anchors move, and deleting an anchor deletes its note. An options dialog covers numbering format, start value, restart, position, prefix/suffix, the two styles and the separator's length, thickness, spacing, alignment and colour. Round-trips to ODF `text:note` + `text:notes-configuration` and to Word's `word/footnotes.xml`/`endnotes.xml` + `w:footnotePr`
@@ -146,7 +147,7 @@ The gap against Word/LibreOffice, most valuable first. Reviewed 2026-08-08.
- Restarting the page numbering **per section** (only the document's own format and start value exist)
- Heading levels 7–10 (Word and LibreOffice go that far; HTML stops at `h6`)
- A bibliography's citation style: the list is set the one way ("key: author, title, year"), where both word processors offer APA, MLA, Chicago and the rest, and numbered citations (`[1]`) instead of the source's short name
- Section-level page **size and orientation**: only the margins are per section. A file whose sections disagree on the page size keeps the last one's
- A section's own **page format** is set only by the file it came from — the ribbon offers the orientation per section, the paper size document-wide. Pages of different widths are left-aligned in the scroll, where both word processors centre each
- Table extras: sort, sum/formula in a cell, number recognition
- A list level's own hanging indent: the marker sits at the 0.635 cm both exports write (`LIST_HANGING_CM`), so a wider *left*-set marker overflows where Word moves the text to the next list tab (a **right**-set one — `w:lvlJc`, which is what the built-in Roman numberings use — grows into the margin and is fine). Reading the value back naively also moves the markers of our own ODT exports — LibreOffice draws its own flat hanging at exactly the value odf-kit writes for level 2; see `tests/render-parity/README.md` before building on it
- Linked / chained text frames
+14 -2
View File
@@ -76,8 +76,20 @@ Horizontally `.tiptap`'s padding draws one pair for every page, so the differenc
everything that writes a block margin (`editor.css`, `indent.ts`, `styleSheet.ts`,
`tableView.ts`) and cleared on descendants so a nested indent can't count it twice. The page
a block lands on is read *after* its own spacer, so a forced break onto the section's second
page takes the "rest" pair. Not carried: the ruler, the header/footer layer and a frame's
`COLUMN_WIDTH_CSS` stay document-wide, and both exports write one page geometry.
page takes the "rest" pair. Not carried: the ruler and a frame's `COLUMN_WIDTH_CSS` stay document-wide.
**Per-section paper.** A section's own format/orientation (`HfSet.format`/`.orientation`,
null = the document's) makes the pages differ in size, which a repeating background
cannot express — so the page grid is a **`PageGrid`** of height runs ("every page from
here on is this tall") instead of one cycle, and the sheets are one box per page
(`PageSheetLayer`). `placeLeaves` builds its own grid as each section's first page
becomes known, so a pass never measures its own last answer; it reports the runs, and
`Editor.svelte` publishes them as `--pb-page-runs` for every other consumer (the TOC, a
cross-reference, a page-anchored frame) plus `--pb-section-page` for the next pass.
`.paper` reserves the **widest** section's paper (`--pb-paper-width`) or a landscape page
would be cut at the sheet edge, and a narrower section takes the difference as an extra
right inset on top of its own margins. The sheets are left-aligned in that box, where
both word processors centre each page.
**Tables across page breaks:** when a single continuous table box crosses a page boundary, the plugin reports `TableBreakBand`s (doc-px geometry). `Editor.svelte` renders an overlay (`.band-layer` inside `.paper`) that masks the table borders bleeding through the page margins and paints the dark page gap as one seam-free stripe.
+1
View File
@@ -984,6 +984,7 @@
bind:pageMargins
bind:pageOrientation
bind:pageFormat
bind:extraHfSections
bind:hyphenate
bind:pageNumbering
bind:pageDecor
+48 -10
View File
@@ -17,12 +17,13 @@
import ContextMenu from './ContextMenu.svelte';
import HeaderFooterLayer from './HeaderFooterLayer.svelte';
import PageDecorLayer from './PageDecorLayer.svelte';
import PageSheetLayer from './PageSheetLayer.svelte';
import LineNumberLayer from './LineNumberLayer.svelte';
import { DEFAULT_LINE_NUMBERING, type LineNumbering } from '../storage/lineNumbering';
import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
import Ruler from './Ruler.svelte';
import { saveDocument, loadDocument, markDocumentLoaded } from '../storage/autosave';
import { applyMarginVars, cmToPx, DEFAULT_MARGINS, type PageMargins } from '../storage/pageMargins';
import { applyMarginVars, cmToPx, PX_PER_CM, DEFAULT_MARGINS, type PageMargins } from '../storage/pageMargins';
import { DEFAULT_TAB_INTERVAL_CM } from '../storage/tabInterval';
import { type Orientation } from '../storage/pageOrientation';
import { type SpacingModel } from '../storage/spacingModel';
@@ -31,9 +32,9 @@ import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
import { applyNoteVars } from '../storage/noteSettings';
import { noteSettings } from '../storage/notes.svelte';
import { RESYNC_NOTES } from '../editor/extensions/notes';
import { applyPageSizeVars, type PageFormat } from '../storage/pageFormat';
import { applyPageSizeVars, pageDimsCm, type PageFormat } from '../storage/pageFormat';
import { DEFAULT_HF_DISTANCES, hfIsEmpty, hfUsesChapterField, type HfDoc, type HfZone, type HfDistances, type HfSet } from '../storage/headerFooter';
import { FORCE_PAGE_RECALC, pageOfElement, readVerticalMargins, type TableBreakBand } from '../editor/extensions/pageBreaks';
import { FORCE_PAGE_RECALC, PAGE_GAP, pageOfElement, readVerticalMargins, type TableBreakBand } from '../editor/extensions/pageBreaks';
import { findBookmark } from '../editor/extensions/bookmark';
import { recordTransaction, resetHistoryLog } from '../utils/historyLog.svelte';
import { wheelZoomFactor } from '../utils/zoom';
@@ -91,14 +92,14 @@ import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
function collectChapterStarts(): { page: number; level: number; text: string }[] {
if (!editor || editor.isDestroyed) return [];
const cycle = readVerticalMargins(editor.view.dom as HTMLElement).cycle;
const grid = readVerticalMargins(editor.view.dom as HTMLElement).grid;
const out: { page: number; level: number; text: string }[] = [];
editor.state.doc.descendants((node, pos) => {
if (node.type.name !== 'heading') return;
const text = node.textContent.trim();
const el = editor!.view.nodeDOM(pos) as HTMLElement | null;
if (!text || !el || el.nodeType !== 1) return;
out.push({ page: pageOfElement(editor!.view, el, cycle), level: (node.attrs.level as number) ?? 1, text });
out.push({ page: pageOfElement(editor!.view, el, grid), level: (node.attrs.level as number) ?? 1, text });
});
return out;
}
@@ -186,23 +187,58 @@ import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
}),
].map((g) => g.map((n) => Math.round(n)).join('|')).join(','));
// Each section's own paper (px). A section that names neither format nor orientation
// is on the document's, so its entry is the document's box.
let sectionPaper = $derived([
pageDimsCm(pageFormat, orientation),
...extraHfSections.map((s) => pageDimsCm(s.format ?? pageFormat, s.orientation ?? orientation)),
].map((d) => ({ w: Math.round(d.w * PX_PER_CM), h: Math.round(d.h * PX_PER_CM) })));
// The sheet .paper reserves is the widest of them: a landscape section is wider than
// the portrait ones around it and would otherwise be cut at the page edge.
let paperWidth = $derived(Math.max(...sectionPaper.map((p) => p.w)));
// Which section each page belongs to (sectionStartPages holds the first page of every
// section past the first), and from it the box every per-page layer paints.
let pageBoxes = $derived.by(() => {
const out: { top: number; height: number; width: number; section: number }[] = [];
let top = 0;
let section = 0;
for (let p = 1; p <= Math.max(1, numPages); p++) {
while (section < sectionStartPages.length && sectionStartPages[section] <= p) section++;
const paper = sectionPaper[Math.min(section, sectionPaper.length - 1)];
out.push({ top, height: paper.h, width: paper.w, section });
top += paper.h + PAGE_GAP;
}
return out;
});
// The same per section for the side margins, as a delta against the document's own:
// .tiptap's padding draws those for every page, so a section that wants others has
// its blocks inset by the difference ("leftFirst|rightFirst|leftRest|rightRest").
// A section narrower than the sheet (.paper reserves the widest paper) takes the whole
// difference on its right, so its text still ends at its own page's right margin.
let sectionInset = $derived([
[0, 0, 0, 0],
...extraHfSections.map((s) => {
[0, paperWidth - sectionPaper[0].w, 0, paperWidth - sectionPaper[0].w],
...extraHfSections.map((s, i) => {
const rest = s.margins ?? null;
const first = s.marginsFirst ?? rest;
const d = (m: PageMargins | null, side: 'left' | 'right') =>
m ? Math.round(cmToPx(m[side]) - cmToPx(pageMargins[side])) : 0;
return [d(first, 'left'), d(first, 'right'), d(rest, 'left'), d(rest, 'right')];
const narrow = paperWidth - (sectionPaper[i + 1]?.w ?? paperWidth);
return [d(first, 'left'), d(first, 'right') + narrow, d(rest, 'left'), d(rest, 'right') + narrow];
}),
].map((g) => g.join('|')).join(','));
$effect(() => {
const s = document.documentElement.style;
s.setProperty('--pb-section-inset', sectionInset);
s.setProperty('--pb-section-page', sectionPaper.map((p) => p.h).join(','));
s.setProperty('--pb-paper-width', `${paperWidth}px`);
// The grid the last pass laid out, as "fromPage|height" runs, so every consumer
// resolves a page number against the same one pageBreaks placed against.
s.setProperty('--pb-page-runs', sectionStartPages
.map((page, i) => `${page}|${sectionPaper[Math.min(i + 1, sectionPaper.length - 1)].h}`)
.join(','));
s.setProperty('--pb-content-top-rest', `${effTopRest}px`);
s.setProperty('--pb-content-top-first', `${effTopFirst}px`);
s.setProperty('--pb-content-bottom-rest', `${effBottomRest}px`);
@@ -1014,9 +1050,10 @@ import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
{/each}
</div>
{/if}
<PageDecorLayer decor={pageDecor} {numPages} {pageMargins} {pageFormat} {orientation} />
<PageSheetLayer {pageBoxes} />
<PageDecorLayer decor={pageDecor} {pageBoxes} {pageMargins} />
{#if lineNumbering.on}
<LineNumberLayer {editor} {tick} {lineNumbering} {numPages} {pageMargins} {pageFormat} {orientation} />
<LineNumberLayer {editor} {tick} {lineNumbering} {pageBoxes} {pageMargins} />
{/if}
<HeaderFooterLayer
bind:headerDoc
@@ -1031,6 +1068,7 @@ import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
bind:hfActive
bind:hfTick
{numPages}
{pageBoxes}
{currentPage}
{pageMargins}
{orientation}
+13 -6
View File
@@ -20,6 +20,7 @@
footerEvenDoc = $bindable(),
differentOddEven = false,
numPages,
pageBoxes,
currentPage,
pageMargins,
orientation,
@@ -42,6 +43,8 @@
footerEvenDoc: HfDoc;
differentOddEven?: boolean;
numPages: number;
/** One box per page (Editor.svelte): a section on its own paper differs in size. */
pageBoxes: { top: number; height: number; width: number }[];
currentPage: number;
/** How the page-number field counts (format + start value). */
pageNumbering?: PageNumbering;
@@ -68,12 +71,15 @@
// .paper, so the zoom transform applies to it identically to the page background.
let pageWidthPx = $derived(pageDimsCm(pageFormat, orientation).w * PX_PER_CM);
let pageHeightPx = $derived(pageDimsCm(pageFormat, orientation).h * PX_PER_CM);
let cycle = $derived(pageHeightPx + PAGE_GAP);
// A section on its own paper makes the pages differ, so every box comes from the
// grid Editor.svelte publishes; the document's own is the fallback.
const boxOf = (page: number) => pageBoxes[page - 1]
?? { top: (page - 1) * (pageHeightPx + PAGE_GAP), height: pageHeightPx, width: pageWidthPx };
let mTop = $derived(cmToPx(pageMargins.top));
let mBottom = $derived(cmToPx(pageMargins.bottom));
let mLeft = $derived(cmToPx(pageMargins.left));
let mRight = $derived(cmToPx(pageMargins.right));
let contentWidth = $derived(Math.max(0, pageWidthPx - mLeft - mRight));
const contentWidthOf = (page: number) => Math.max(0, boxOf(page).width - mLeft - mRight);
// Edge→zone distance in px. The footer may sit farther from the edge than the body
// bottom margin (Word's w:footer > w:bottom); the zone then grows up into the margin.
let headerDistPx = $derived(Math.min(cmToPx(hfDistances.header), pageHeightPx));
@@ -84,14 +90,15 @@
function zoneBox(zone: HfZone, page: number) {
// Mirrored margins: an even page is the left-hand one, so the pair is swapped.
const left = pageMargins.mirrored && page % 2 === 0 ? mRight : mLeft;
const width = contentWidth;
const width = contentWidthOf(page);
const box = boxOf(page);
if (zone === 'header') {
const top = (page - 1) * cycle + headerDistPx;
const top = box.top + headerDistPx;
return { top, left, width, height: Math.max(MIN_ZONE_PX, mTop - headerDistPx) };
}
// Footer anchors its bottom edge at footerDistPx from the page bottom and grows up.
const height = Math.max(MIN_ZONE_PX, mBottom - footerDistPx);
const top = (page - 1) * cycle + pageHeightPx - footerDistPx - height;
const top = box.top + box.height - footerDistPx - height;
return { top, left, width, height };
}
// The active (edited) zone grows to fit its content, keeping the anchored edge fixed
@@ -374,7 +381,7 @@
class="hf-page-bg"
src={bg.src}
alt=""
style="top: {(p - 1) * cycle + bg.y}px; left: {bg.x}px; width: {bg.width}px; height: {bg.height}px;"
style="top: {boxOf(p).top + bg.y}px; left: {bg.x}px; width: {bg.width}px; height: {bg.height}px;"
/>
{/each}
{/each}
+11 -12
View File
@@ -1,8 +1,6 @@
<script lang="ts">
import type { Editor } from '@tiptap/core';
import { cmToPx, PX_PER_CM, type PageMargins } from '../storage/pageMargins';
import { pageDimsCm, type PageFormat } from '../storage/pageFormat';
import type { Orientation } from '../storage/pageOrientation';
import { cmToPx, type PageMargins } from '../storage/pageMargins';
import type { LineNumbering } from '../storage/lineNumbering';
// Numbers in the left margin, one per rendered line. CSS exposes no line boxes, so
@@ -12,19 +10,20 @@
// ponytail: measures every block in the document on each settle. Fine while numbering
// is on and the document is ordinary; a 400-page one would want a windowed pass keyed
// to a running count per page.
let { editor, tick, lineNumbering, numPages, pageMargins, pageFormat, orientation }: {
let { editor, tick, lineNumbering, pageBoxes, pageMargins }: {
editor: Editor | null;
tick: number;
lineNumbering: LineNumbering;
numPages: number;
/** One box per page (Editor.svelte): a section on its own paper differs in size. */
pageBoxes: { top: number; height: number; width: number }[];
pageMargins: PageMargins;
pageFormat: PageFormat;
orientation: Orientation;
} = $props();
const PAGE_GAP = 20;
let cycle = $derived(pageDimsCm(pageFormat, orientation).h * PX_PER_CM + PAGE_GAP);
// The page a document-px top falls on, against boxes that may differ in height.
const pageAt = (top: number) => {
for (let i = pageBoxes.length - 1; i >= 0; i--) if (top >= pageBoxes[i].top) return i + 1;
return 1;
};
let left = $derived(cmToPx(pageMargins.left) - cmToPx(lineNumbering.distanceCm));
let marks = $state<{ top: number; label: string }[]>([]);
@@ -42,7 +41,7 @@
// Re-measure on every edit and on each pagination settle.
void tick;
void lineNumbering;
void numPages;
void pageBoxes;
if (!lineNumbering.on) { marks = []; return; }
schedule();
});
@@ -87,7 +86,7 @@
if (!/^(P|H1|H2|H3|H4|H5|H6|LI|BLOCKQUOTE)$/.test(block.tagName)) continue;
const empty = !block.textContent?.trim();
for (const line of lineTops(block, origin)) {
const linePage = Math.max(1, Math.floor(line.top / cycle) + 1);
const linePage = pageAt(line.top);
if (lineNumbering.restart === 'page' && linePage !== page) { page = linePage; count = 0; }
if (empty && !lineNumbering.countEmpty) continue;
count += 1;
+12 -20
View File
@@ -1,29 +1,20 @@
<script lang="ts">
import { pageDimsCm, type PageFormat } from '../storage/pageFormat';
import { cmToPx, PX_PER_CM, type PageMargins } from '../storage/pageMargins';
import type { Orientation } from '../storage/pageOrientation';
import { cmToPx, type PageMargins } from '../storage/pageMargins';
import type { PageDecor } from '../storage/pageDecor';
// The page's border and watermark, one box per page — the background itself is a
// custom property on .paper, which already paints the sheet. Geometry is unscaled
// document px: the layer sits inside .paper, so the zoom transform covers it.
let { decor, numPages, pageMargins, pageFormat, orientation }: {
let { decor, pageBoxes, pageMargins }: {
decor: PageDecor;
numPages: number;
/** One box per page (Editor.svelte): a section on its own paper differs in size. */
pageBoxes: { top: number; height: number; width: number }[];
pageMargins: PageMargins;
pageFormat: PageFormat;
orientation: Orientation;
} = $props();
const PAGE_GAP = 20;
// The watermark's aspect ratio, measured off LibreOffice's own shape.
const WATERMARK_RATIO = 4.487;
let dims = $derived(pageDimsCm(pageFormat, orientation));
let pageHeightPx = $derived(dims.h * PX_PER_CM);
let cycle = $derived(pageHeightPx + PAGE_GAP);
let pages = $derived(Array.from({ length: Math.max(1, numPages) }, (_, i) => i + 1));
// The border rings the text area, grown by its own padding — where ODF's fo:padding
// and Word's w:space put it.
let inset = $derived.by(() => {
@@ -37,23 +28,24 @@
});
});
let markWidth = $derived((dims.w - pageMargins.left - pageMargins.right) * PX_PER_CM);
let markWidth = $derived((pageBoxes[0]?.width ?? 794) - cmToPx(pageMargins.left) - cmToPx(pageMargins.right));
</script>
<div class="page-decor-layer" aria-hidden="true">
{#each pages as p}
{#each pageBoxes as box, i}
{@const p = i + 1}
{#if decor.border}
{@const box = inset(p)}
{@const ring = inset(p)}
<div
class="page-border"
style="top: {(p - 1) * cycle + box.top}px; left: {box.left}px;
width: {dims.w * PX_PER_CM - box.left - box.right}px;
height: {pageHeightPx - box.top - box.bottom}px;
style="top: {box.top + ring.top}px; left: {ring.left}px;
width: {box.width - ring.left - ring.right}px;
height: {box.height - ring.top - ring.bottom}px;
border: {decor.border.widthPt}pt solid {decor.border.color};"
></div>
{/if}
{#if decor.watermark}
<div class="watermark" style="top: {(p - 1) * cycle}px; height: {pageHeightPx}px;">
<div class="watermark" style="top: {box.top}px; height: {box.height}px;">
<!-- A fontwork shape stretches its text to the box rather than setting it at a
size, which is what textLength does here — the box is the text width, as
LibreOffice sizes its own watermark. -->
+34
View File
@@ -0,0 +1,34 @@
<script lang="ts">
// The sheets themselves, one box per page. A repeating gradient drew them while every
// page was the same size; a section on its own paper makes the pages differ in height
// and width, and only a box per page can say that.
let { pageBoxes }: {
pageBoxes: { top: number; height: number; width: number }[];
} = $props();
</script>
<div class="page-sheet-layer" aria-hidden="true">
{#each pageBoxes as box}
<div class="page-sheet" style="top: {box.top}px; height: {box.height}px; width: {box.width}px;"></div>
{/each}
</div>
<style>
/* Behind everything the page carries — the header/footer background layer sits at
-1, so the sheet has to be under that. */
.page-sheet-layer {
position: absolute;
inset: 0;
z-index: -2;
pointer-events: none;
}
.page-sheet {
position: absolute;
left: 0;
background: var(--color-page-bg);
border: 1px solid var(--color-page-border);
/* The border rings the sheet without growing it, so the page box stays the paper. */
box-sizing: border-box;
}
</style>
+4 -2
View File
@@ -24,7 +24,7 @@
import { DEFAULT_MARGINS, type PageMargins } from '../../storage/pageMargins';
import type { Orientation } from '../../storage/pageOrientation';
import type { PageFormat } from '../../storage/pageFormat';
import type { HfZone } from '../../storage/headerFooter';
import type { HfSet, HfZone } from '../../storage/headerFooter';
import type { DocumentLanguage } from '../../storage/documentLanguage';
import { DEFAULT_TAB_INTERVAL_CM } from '../../storage/tabInterval';
import { DEFAULT_PAGE_NUMBERING, type PageNumbering } from '../../storage/pageNumbering';
@@ -47,6 +47,7 @@
pageMargins = $bindable(DEFAULT_MARGINS),
pageOrientation = $bindable<Orientation>('portrait'),
pageFormat = $bindable<PageFormat>('A4'),
extraHfSections = $bindable<HfSet[]>([]),
hyphenate = $bindable(false),
pageNumbering = $bindable(DEFAULT_PAGE_NUMBERING),
pageDecor = $bindable(EMPTY_PAGE_DECOR),
@@ -81,6 +82,7 @@
pageMargins?: PageMargins;
pageOrientation?: Orientation;
pageFormat?: PageFormat;
extraHfSections?: HfSet[];
hyphenate?: boolean;
pageNumbering?: PageNumbering;
pageDecor?: PageDecor;
@@ -330,7 +332,7 @@
{:else if tab === 'insert'}
<InsertTab {editor} {tick} {hfActive} {pageMargins} {pageOrientation} {pageFormat} {onEditZone} {onManageTableStyles} />
{:else if tab === 'layout'}
<LayoutTab {editor} {tick} {hfActive} bind:pageMargins bind:pageOrientation bind:pageFormat bind:hyphenate bind:pageNumbering bind:pageDecor bind:lineNumbering onParagraphDialog={() => (paragraphDialogOpen = true)} />
<LayoutTab {editor} {tick} {hfActive} bind:pageMargins bind:pageOrientation bind:pageFormat bind:extraHfSections bind:hyphenate bind:pageNumbering bind:pageDecor bind:lineNumbering onParagraphDialog={() => (paragraphDialogOpen = true)} />
{:else if tab === 'references'}
<ReferencesTab {editor} {tick} {hfActive} {onNoteOptions} />
{:else if tab === 'review'}
@@ -8,7 +8,7 @@
import { PAGE_FORMAT_CM, type PageFormat } from '../../../storage/pageFormat';
import { DEFAULT_MARGINS, type PageMargins } from '../../../storage/pageMargins';
import type { Orientation } from '../../../storage/pageOrientation';
import type { HfZone } from '../../../storage/headerFooter';
import { EMPTY_HF_SET, type HfSet, type HfZone } from '../../../storage/headerFooter';
import { DEFAULT_PAGE_NUMBERING, PAGE_NUM_FORMATS, clampPageStart, type PageNumbering } from '../../../storage/pageNumbering';
import { EMPTY_PAGE_DECOR, type PageDecor } from '../../../storage/pageDecor';
import { DEFAULT_LINE_NUMBERING, type LineNumbering } from '../../../storage/lineNumbering';
@@ -22,6 +22,7 @@
pageMargins = $bindable(DEFAULT_MARGINS),
pageOrientation = $bindable<Orientation>('portrait'),
pageFormat = $bindable<PageFormat>('A4'),
extraHfSections = $bindable<HfSet[]>([]),
hyphenate = $bindable(false),
pageNumbering = $bindable(DEFAULT_PAGE_NUMBERING),
pageDecor = $bindable(EMPTY_PAGE_DECOR),
@@ -34,6 +35,7 @@
pageMargins?: PageMargins;
pageOrientation?: Orientation;
pageFormat?: PageFormat;
extraHfSections?: HfSet[];
hyphenate?: boolean;
pageNumbering?: PageNumbering;
pageDecor?: PageDecor;
@@ -43,6 +45,33 @@
let decorOpen = $state(false);
// The section the cursor is in: every top-level block carrying `sectionBreak` opens
// the next one, so counting them up to the cursor is the index. 0 = the document's
// own first section, which has no HfSet of its own.
let currentSection = $derived.by(() => {
if (tick < 0 || !editor) return 0;
const at = editor.state.selection.from;
let n = 0;
editor.state.doc.forEach((node, pos) => {
if (pos < at && node.attrs?.sectionBreak === true) n++;
});
return n;
});
// Its own orientation, where it has one — else the document's.
let sectionOrientation = $derived(
currentSection > 0 ? (extraHfSections[currentSection - 1]?.orientation ?? pageOrientation) : pageOrientation,
);
// Word's "apply to this section": the paper rides the section's own page setup, so
// every other section keeps the document's.
function setSectionOrientation(o: Orientation | null): void {
if (currentSection < 1) return;
const out = extraHfSections.slice();
while (out.length < currentSection) out.push({ ...EMPTY_HF_SET });
out[currentSection - 1] = { ...out[currentSection - 1], orientation: o };
extraHfSections = out;
}
const FORMATS = Object.keys(PAGE_FORMAT_CM) as PageFormat[];
const EDGES = ['top', 'bottom', 'left', 'right'] as const;
@@ -127,6 +156,13 @@
{#each (['portrait', 'landscape'] as const) as o}
<button class:selected={pageOrientation === o} onclick={() => { closeMenu(); pageOrientation = o; }}>{t().toolbarExpanded[o]}</button>
{/each}
{#if currentSection > 0}
<div class="rb-menu-label">{t().ribbon.thisSection}</div>
{#each (['portrait', 'landscape'] as const) as o}
<button class:selected={sectionOrientation === o} onclick={() => { closeMenu(); setSectionOrientation(o); }}>{t().toolbarExpanded[o]}</button>
{/each}
<button onclick={() => { closeMenu(); setSectionOrientation(null); }}>{t().ribbon.likeDocument}</button>
{/if}
</div>
{/if}
</div>
+2 -2
View File
@@ -144,8 +144,8 @@ class CrossRefView {
const at = this.editor.view.domAtPos(found.from).node;
const el = (at.nodeType === 1 ? at : at.parentElement) as HTMLElement | null;
if (!el) return String(node.attrs.text ?? '');
const { cycle } = readVerticalMargins(this.editor.view.dom as HTMLElement);
return String(pageOfElement(this.editor.view, el, cycle));
const { grid } = readVerticalMargins(this.editor.view.dom as HTMLElement);
return String(pageOfElement(this.editor.view, el, grid));
}
// Mirror what renderHTML would emit, so the DOM reads the same with or without the view.
+7 -5
View File
@@ -5,6 +5,7 @@ import { NodeSelection, Plugin, PluginKey } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import { dropCursor } from '@tiptap/pm/dropcursor';
import { cmToPx } from '../../storage/pageMargins';
import { readVerticalMargins } from './pageBreaks';
// Inline, as-character image, or a floating text-wrapped frame (wrap = flow mode);
// width/height are doc px @96dpi, rotation CW degrees. Export → cm + ODF
@@ -475,10 +476,10 @@ class ImageView {
? `${Math.round(cmToPx(x)) + (parseFloat(this.rotor.style.width) || 0) / 2}px` : '';
}
// Placed from its page's top-left corner (--page-cycle is the page plus the gap), behind
// the text like the header layer's page background — unless the file's own run-through
// says otherwise (inFront). Its paragraph collapses to nothing (editor.css), so it takes
// no flow space either way.
// Placed from its page's top-left corner, behind the text like the header layer's page
// background — unless the file's own run-through says otherwise (inFront). Its paragraph
// collapses to nothing (editor.css), so it takes no flow space either way. The page top
// comes from the grid, since a section on its own paper makes the pages differ.
private applyPageAnchor(page: number): void {
const d = this.dom;
d.dataset.anchorPage = String(page);
@@ -486,7 +487,8 @@ class ImageView {
d.style.position = 'absolute';
d.style.zIndex = this.node.attrs.inFront ? '1' : '-1';
d.style.left = `${px(this.node.attrs.wrapOffset)}px`;
d.style.top = `calc(${page - 1} * var(--page-cycle) + ${px(this.node.attrs.wrapOffsetY)}px)`;
const grid = readVerticalMargins(this.editor.view.dom as HTMLElement).grid;
d.style.top = `${grid.topOf(page) + px(this.node.attrs.wrapOffsetY)}px`;
}
// The offset counts from the anchor paragraph's top. Where text precedes the frame
+123 -35
View File
@@ -117,7 +117,7 @@ export function getPageBreakDebug(view: EditorView): PageBreakDebugSnapshot | nu
// margins (user-adjustable) are read per pass from live CSS vars; the values below
// are only portrait fallbacks.
const PAGE_HEIGHT = 1123;
const PAGE_GAP = 20;
export const PAGE_GAP = 20;
const DEFAULT_MARGIN_TOP = 96;
const DEFAULT_MARGIN_BOTTOM = 96;
// Word/LibreOffice widow-orphan control: a page break never leaves fewer than this
@@ -131,6 +131,9 @@ export type VMargins = {
contentHeight: number;
pageHeight: number;
cycle: number;
// The page grid of the last pagination pass (Editor.svelte publishes its runs), so
// every consumer resolves a page number against the same one.
grid: PageGrid;
};
// Reads vertical page margins + page height (px) from the --user-* props the Layout
@@ -155,14 +158,94 @@ export function readVerticalMargins(dom: HTMLElement): VMargins {
contentHeight: pageHeight - mt - mb,
pageHeight,
cycle: pageHeight + PAGE_GAP,
grid: gridFromRuns(cs.getPropertyValue('--pb-page-runs'), pageHeight),
};
}
// "fromPage|height,…" — the runs the last pass reported (Editor.svelte publishes them).
// A document whose sections share one paper writes none, and the grid is uniform.
export function gridFromRuns(raw: string, pageHeight: number): PageGrid {
const grid = new PageGrid(pageHeight);
for (const part of raw.split(',')) {
const [from, height] = part.split('|').map(Number);
if (Number.isFinite(from) && Number.isFinite(height) && from > 1 && height > 0) grid.setFrom(from, height);
}
return grid;
}
// The rendered page grid. A page's top is the sum of the pages above it, so a section
// on its own paper (a landscape page amid portrait ones) shifts every page below it —
// the uniform document is just the one-run case. Heights are stored as runs, "every
// page from here on is this tall", so both lookups cost one pass over the sections.
export class PageGrid {
private runs: { from: number; height: number }[];
constructor(baseHeight: number) {
this.runs = [{ from: 1, height: baseHeight }];
}
/** Every page from `page` on is `height` tall, until a later section says otherwise. */
setFrom(page: number, height: number): void {
while (this.runs.length > 1 && this.runs[this.runs.length - 1].from >= page) this.runs.pop();
if (this.runs[this.runs.length - 1].from === page) this.runs[this.runs.length - 1].height = height;
else if (this.runs[this.runs.length - 1].height !== height) this.runs.push({ from: Math.max(1, page), height });
}
heightOf(page: number): number {
let h = this.runs[0].height;
for (const r of this.runs) if (r.from <= page) h = r.height;
return h;
}
/** Top of `page` in document px — the pages above it plus a gap each. */
topOf(page: number): number {
let top = 0;
for (let i = 0; i < this.runs.length; i++) {
const from = this.runs[i].from;
if (from >= page) break;
const until = Math.min(this.runs[i + 1]?.from ?? page, page);
top += (until - from) * (this.runs[i].height + PAGE_GAP);
}
return top;
}
bottomOf(page: number): number {
return this.topOf(page) + this.heightOf(page);
}
/** The page a document-px y falls on (its gap counts to the page above it). */
pageAt(y: number): number {
let page = 1;
let top = 0;
for (let i = 0; i < this.runs.length; i++) {
const step = this.runs[i].height + PAGE_GAP;
const pages = this.runs[i + 1] ? this.runs[i + 1].from - this.runs[i].from : Infinity;
const spanned = Math.floor((y - top) / step);
if (spanned < pages) return Math.max(1, page + Math.max(0, spanned));
page += pages;
top += pages * step;
}
return page;
}
/** One box per page, for the layers that paint them. */
boxes(count: number): { top: number; height: number }[] {
const out: { top: number; height: number }[] = [];
let top = 0;
for (let p = 1; p <= count; p++) {
const height = this.heightOf(p);
out.push({ top, height });
top += height + PAGE_GAP;
}
return out;
}
}
// Rendered page of an element: its offsetTop within the editor DOM (summed up the
// offsetParent chain, spacers included) divided by the page cycle. The TOC and every
// cross-reference resolve their page numbers with it.
export function pageOfElement(view: EditorView, el: HTMLElement, cycle: number): number {
return Math.max(1, Math.floor(topInEditor(view, el) / cycle) + 1);
// offsetParent chain, spacers included) resolved against the page grid. The TOC and
// every cross-reference resolve their page numbers with it.
export function pageOfElement(view: EditorView, el: HTMLElement, grid: PageGrid): number {
return grid.pageAt(topInEditor(view, el));
}
// An element's top in document px from the editor's own top — spacers included, since
@@ -176,16 +259,8 @@ export function topInEditor(view: EditorView, el: HTMLElement): number {
return top;
}
function pageContentStart(page: number, marginTop: number, cycle: number): number {
return (page - 1) * cycle + marginTop;
}
function pageContentEnd(page: number, marginTop: number, contentHeight: number, cycle: number): number {
return (page - 1) * cycle + marginTop + contentHeight;
}
function getPageForY(y: number, cycle: number): number {
return Math.floor(y / cycle) + 1;
function pageContentStart(page: number, marginTop: number, grid: PageGrid): number {
return grid.topOf(page) + marginTop;
}
// `recalc` counts forced recomputes, `edit` the document edits. Layout-only writes
@@ -1010,7 +1085,6 @@ export const PageBreaks = Extension.create({
const vm = readVerticalMargins(dom);
const CONTENT_HEIGHT = vm.contentHeight;
const CYCLE_PX = vm.cycle;
// Side margins + page width (px) for table close/open bands. These don't
// affect pagination (only line wrapping), so readVerticalMargins ignores
@@ -1041,6 +1115,13 @@ export const PageBreaks = Extension.create({
.map((g) => g.split('|').map(Number))
.filter((g) => g.length === 4 && g.every(Number.isFinite));
const insetAt = (i: number) => inset[Math.min(i, inset.length - 1)] ?? [0, 0, 0, 0];
// Its own paper's height (px), where the section has one — a landscape page
// amid portrait ones is shorter, and every page below it moves up.
const paper = csRoot.getPropertyValue('--pb-section-page').split(',').map(Number);
const paperAt = (i: number) => {
const h = paper[Math.min(i, paper.length - 1)];
return Number.isFinite(h) && h > 0 ? h : vm.pageHeight;
};
// Mirrored margins (pageMargins.ts): the padding draws the odd page's pair,
// so an even page's blocks move right by the difference between the two.
const mirrorRaw = parseFloat(csRoot.getPropertyValue('--user-margin-mirror'));
@@ -1069,6 +1150,10 @@ export const PageBreaks = Extension.create({
const sectionStartPages: number[] = [];
let sectionIndex = 0;
let sectionFirstPage = 1;
// The grid this placement lays out against, grown as each section's first
// page becomes known. Built here, not read back, so a pass never measures
// its own last answer.
const grid = new PageGrid(paperAt(0));
const placements: {
docPos: number;
height: number;
@@ -1104,22 +1189,25 @@ export const PageBreaks = Extension.create({
}
let effectiveTop = leaf.naturalTop + cumulativeShift;
let effectiveBottom = effectiveTop + leaf.naturalHeight;
const page = getPageForY(effectiveTop, CYCLE_PX);
const page = grid.pageAt(effectiveTop);
// A section's first page uses its "first" reaches, every other page its
// "rest" ones — page 1 is section 1's first page.
if (leaf.sectionStart) {
// Where the section really begins: a forced break moves its first block to
// the next page, and that page is the one its "first" zones belong to.
const prevStart = (page - 1) * CYCLE_PX + reachAt(sectionIndex)[1];
const prevStart = grid.topOf(page) + reachAt(sectionIndex)[1];
const pushed = !!leaf.forceBreakBefore && i > 0 && effectiveTop > prevStart + 0.5;
sectionIndex++;
sectionFirstPage = pushed ? page + 1 : page;
// Its paper governs from its first page on. Setting it here can only move
// pages *below* that one, so the page just resolved stays valid.
grid.setFrom(sectionFirstPage, paperAt(sectionIndex));
}
const [topFirst, topRest, bottomFirst, bottomRest] = reachAt(sectionIndex);
const onFirst = page === sectionFirstPage;
const pageTop = (page - 1) * CYCLE_PX;
const pageTop = grid.topOf(page);
const contentStart = pageTop + (onFirst ? topFirst : topRest);
const contentEnd = pageTop + vm.pageHeight - (onFirst ? bottomFirst : bottomRest)
const contentEnd = pageTop + grid.heightOf(page) - (onFirst ? bottomFirst : bottomRest)
- (reservedByPage.get(page) ?? 0);
@@ -1183,7 +1271,7 @@ export const PageBreaks = Extension.create({
effectiveTop,
effectiveBottom,
pageOfTop: page,
pageOfBottom: getPageForY(effectiveBottom, CYCLE_PX),
pageOfBottom: grid.pageAt(effectiveBottom),
contentStart,
contentEnd,
overflowsPageEnd: effectiveBottom > contentEnd,
@@ -1210,7 +1298,7 @@ export const PageBreaks = Extension.create({
// The next page's own content start: a section beginning here brings its
// first-page header with it.
const nextTop = page + 1 === sectionFirstPage ? topFirst : topRest;
const target = pageContentStart(page + 1, nextTop, CYCLE_PX);
const target = pageContentStart(page + 1, nextTop, grid);
const { docPos, row } = leafSpacer(leaf);
breaks.push({
height: target - effectiveTop,
@@ -1234,7 +1322,7 @@ export const PageBreaks = Extension.create({
naturalY: 0,
});
} else if (effectiveTop >= contentEnd) {
const target = pageContentStart(page + 1, vm.top, CYCLE_PX);
const target = pageContentStart(page + 1, vm.top, grid);
const { docPos, row } = leafSpacer(leaf);
breaks.push({
height: target - effectiveTop,
@@ -1262,7 +1350,7 @@ export const PageBreaks = Extension.create({
} else if (leaf.naturalHeight <= CONTENT_HEIGHT || cf) {
// A columns fragment may be pushed even when taller than a page:
// the flow splits it again once it sits at the next page top.
const target = pageContentStart(page + 1, vm.top, CYCLE_PX);
const target = pageContentStart(page + 1, vm.top, grid);
const { docPos, row } = leafSpacer(leaf);
breaks.push({
height: target - effectiveTop,
@@ -1290,7 +1378,7 @@ export const PageBreaks = Extension.create({
while (boundaryNatural < leaf.naturalHeight) {
const split = findLineSplit(leaf.el, boundaryNatural, scale, minLines);
if (split === null) break;
const target = pageContentStart(targetPage, vm.top, CYCLE_PX);
const target = pageContentStart(targetPage, vm.top, grid);
const h = target - (effectiveTop + extraShift + split.naturalLineTop);
if (h <= 0) break;
breaks.push({
@@ -1307,7 +1395,7 @@ export const PageBreaks = Extension.create({
}
if (breaks.length === 0) {
if (leaf.naturalHeight <= CONTENT_HEIGHT) {
const target = pageContentStart(page + 1, vm.top, CYCLE_PX);
const target = pageContentStart(page + 1, vm.top, grid);
breaks.push({
height: target - effectiveTop,
docPos: preLeafDocPos(leaf.el),
@@ -1339,7 +1427,7 @@ export const PageBreaks = Extension.create({
? Math.min(next.naturalHeight, CONTENT_HEIGHT)
: firstLinesHeight(next.el, scale, wantLines) + (parseFloat(getComputedStyle(next.el).paddingTop) || 0);
if (effectiveBottom + (leaf.spaceAfter ?? 0) + needed > contentEnd) {
const target = pageContentStart(page + 1, vm.top, CYCLE_PX);
const target = pageContentStart(page + 1, vm.top, grid);
const { docPos, row } = leafSpacer(leaf);
breaks.push({
height: target - effectiveTop,
@@ -1387,7 +1475,7 @@ export const PageBreaks = Extension.create({
effectiveTop,
effectiveBottom,
pageOfTop: page,
pageOfBottom: getPageForY(effectiveBottom, CYCLE_PX),
pageOfBottom: grid.pageAt(effectiveBottom),
contentStart,
contentEnd,
overflowsPageEnd: effectiveBottom > contentEnd,
@@ -1435,7 +1523,7 @@ export const PageBreaks = Extension.create({
for (const anchor of leaf.refs ?? []) {
let shift = shiftAtLeafTop;
for (const br of applied) if (br.at <= anchor.dy + 0.5) shift += br.height;
anchorPages.set(anchor.id, getPageForY(leaf.naturalTop + anchor.dy + shift, CYCLE_PX));
anchorPages.set(anchor.id, grid.pageAt(leaf.naturalTop + anchor.dy + shift));
}
if (!placedAny && noPushReason !== null) {
placementsDebug.push({
@@ -1449,7 +1537,7 @@ export const PageBreaks = Extension.create({
}
// Read after this leaf's own spacer, so the page is the one it really lands on.
const landedPage = getPageForY(leaf.naturalTop + cumulativeShift, CYCLE_PX);
const landedPage = grid.pageAt(leaf.naturalTop + cumulativeShift);
if (leaf.sectionStart) sectionStartPages.push(landedPage);
const ins = insetAt(sectionIndex);
const mir = landedPage % 2 === 0 ? mirror : 0;
@@ -1482,7 +1570,7 @@ export const PageBreaks = Extension.create({
}
return {
anchorPages, maxEffectiveBottom, sectionStartPages, placements, collapsedTrailing,
pageTopBlocks, sectionInsets, tableBands, leavesDebug, placementsDebug,
pageTopBlocks, sectionInsets, tableBands, leavesDebug, placementsDebug, grid,
};
}
@@ -1535,7 +1623,7 @@ export const PageBreaks = Extension.create({
for (const note of footnotes) {
const page = placed.anchorPages.get(note.id);
if (!page) continue;
const base = page * CYCLE_PX - PAGE_GAP - vm.bottom - (reserved.get(page) ?? 0) + sepSpace;
const base = placed.grid.bottomOf(page) - vm.bottom - (reserved.get(page) ?? 0) + sepSpace;
const top = nextTop.get(page) ?? base;
noteTops.set(note.id, top);
nextTop.set(page, top + note.height);
@@ -1646,8 +1734,8 @@ export const PageBreaks = Extension.create({
// maxEffectiveBottom is the lowest rendered content across all leaves,
// including parallel cells of a too-tall row (a single last-leaf reading
// would miss a taller sibling column).
const numPages = Math.max(1, getPageForY(maxEffectiveBottom, CYCLE_PX));
const targetHeight = numPages * CYCLE_PX - PAGE_GAP;
const numPages = Math.max(1, placed.grid.pageAt(maxEffectiveBottom));
const targetHeight = placed.grid.bottomOf(numPages);
dom.style.minHeight = `${targetHeight}px`;
// In-cell table breaks (all values in unscaled document px relative to
@@ -1678,7 +1766,7 @@ export const PageBreaks = Extension.create({
PAGE_MARGIN_TOP: vm.top,
PAGE_MARGIN_BOTTOM: vm.bottom,
CONTENT_HEIGHT,
CYCLE: CYCLE_PX,
CYCLE: vm.cycle,
},
numPages,
leaves: leavesDebug,
+8 -8
View File
@@ -5,7 +5,7 @@ import { MAX_HEADING_LEVEL } from '../../export/odt';
import { seqCategoryOf, sequenceFieldText, type SeqCategory } from './caption';
import { indexEntries, indexRows } from './indexEntry';
import { bibliographyEntries, bibliographyRows } from './bibliographyEntry';
import { readVerticalMargins, pageOfElement, topInEditor, FORCE_PAGE_RECALC } from './pageBreaks';
import { readVerticalMargins, pageOfElement, topInEditor, FORCE_PAGE_RECALC, type PageGrid } from './pageBreaks';
// A generated index: a block atom listing every source with its live page number — the
// headings for a table of contents, the captions of one category for a list of figures
@@ -253,30 +253,30 @@ class TocView {
return out;
}
private cycle(): number {
return readVerticalMargins(this.editor.view.dom as HTMLElement).cycle;
private grid(): PageGrid {
return readVerticalMargins(this.editor.view.dom as HTMLElement).grid;
}
private pageOf(pos: number, cycle: number): number {
private pageOf(pos: number, grid: PageGrid): number {
const el = this.editor.view.nodeDOM(pos) as HTMLElement | null;
if (!el || el.nodeType !== 1) return 1;
return pageOfElement(this.editor.view, el, cycle);
return pageOfElement(this.editor.view, el, grid);
}
private render(): void {
if (this.editor.isDestroyed || !this.dom.isConnected) return;
const cycle = this.cycle();
const grid = this.grid();
let heads = this.sources();
let entries: TocEntry[];
if (indexKindOf(this.node()?.attrs?.index) === 'alphabetical') {
// A term marked five times is one row with five page numbers, and the row jumps
// to the first of them.
const marks = heads.map(h => ({ ...h, page: this.pageOf(h.pos, cycle) }));
const marks = heads.map(h => ({ ...h, page: this.pageOf(h.pos, grid) }));
const rows = indexRows(marks.map(m => ({ term: m.text, key1: '', page: m.page })));
entries = rows.map(r => ({ text: r.text, level: 1, page: r.pages[0], pages: r.pages }));
heads = rows.map(r => marks.find(m => m.text === r.text)!);
} else {
entries = heads.map(h => ({ text: h.text, level: h.level, page: this.pageOf(h.pos, cycle) }));
entries = heads.map(h => ({ text: h.text, level: h.level, page: this.pageOf(h.pos, grid) }));
}
const key = JSON.stringify(entries);
if (key !== this.lastKey) {
+2
View File
@@ -731,6 +731,8 @@ const de: Messages = {
indexEntry: 'Stichwort',
indexEntryPrompt: 'Stichwort — das Wort, das im Verzeichnis steht:',
indexEntryNeedsSelection: 'Markiere das Wort, das ins Stichwortverzeichnis soll',
thisSection: 'Dieser Abschnitt',
likeDocument: 'Wie das Dokument',
citation: 'Literaturangabe',
footnote: 'Fußnote',
endnote: 'Endnote',
+2
View File
@@ -733,6 +733,8 @@ const en = {
indexEntry: 'Index entry',
indexEntryPrompt: 'Index entry — the word the index lists:',
indexEntryNeedsSelection: 'Select the word to file in the index',
thisSection: 'This section',
likeDocument: 'Like the document',
citation: 'Citation',
tocOptions: 'Levels',
tocMaxLevel: 'Deepest level shown',
+6 -53
View File
@@ -25,7 +25,8 @@
--page-gap: 20px;
--page-cycle: calc(var(--page-height) + var(--page-gap));
width: var(--user-page-width, 794px);
/* The widest section's paper, so a landscape page is not cut at the sheet edge. */
width: var(--pb-paper-width, var(--user-page-width, 794px));
/* Zoom is a `transform: scale()` set inline (Editor.svelte); pin the origin so the
page scales down/right from the top-left of its reserved footprint. */
transform-origin: top left;
@@ -37,18 +38,9 @@
in LibreOffice. `clip` rather than `hidden`: it must not become a scroll box. */
overflow-x: clip;
/* The page surface (white) alternating with the gap, where .tiptap paints only the
borders on top of it. It sits here so a header's page background (.hf-bg-layer,
z-index -1) can paint between the sheet and the body text. */
background: repeating-linear-gradient(
to bottom,
var(--color-page-bg) 0px,
var(--color-page-bg) var(--page-height),
transparent var(--page-height),
transparent var(--page-cycle)
);
background-size: 100% var(--page-cycle);
background-repeat: repeat-y;
/* The sheets themselves are one box per page (PageSheetLayer), since a section on its
own paper makes them differ in size. They sit at z-index -2, under a header's page
background (.hf-bg-layer, -1) and so under the body text. */
}
/* While a freshly opened document is still finding its pagination (Editor.svelte).
@@ -82,46 +74,7 @@
line-height: 1.15;
color: var(--color-page-text);
/* Page borders, drawn over the sheet .paper paints */
background:
/* Left border per page */
repeating-linear-gradient(
to bottom,
var(--color-page-border) 0px,
var(--color-page-border) var(--page-height),
transparent var(--page-height),
transparent var(--page-cycle)
),
/* Right border per page */
repeating-linear-gradient(
to bottom,
var(--color-page-border) 0px,
var(--color-page-border) var(--page-height),
transparent var(--page-height),
transparent var(--page-cycle)
),
/* Top/bottom border lines of each page */
repeating-linear-gradient(
to bottom,
var(--color-page-border) 0px,
var(--color-page-border) 1px,
transparent 1px,
transparent calc(var(--page-height) - 1px),
var(--color-page-border) calc(var(--page-height) - 1px),
var(--color-page-border) var(--page-height),
transparent var(--page-height),
transparent var(--page-cycle)
);
background-size:
1px var(--page-cycle),
1px var(--page-cycle),
100% var(--page-cycle);
background-position:
left top,
right top,
left top;
background-repeat: repeat-y;
/* The page borders ride the sheet boxes (PageSheetLayer). */
border: none;
/* Subtle overall shadow for depth */
+58
View File
@@ -0,0 +1,58 @@
import { describe, it, expect } from 'vitest';
import { PageGrid, gridFromRuns } from '../../src/lib/editor/extensions/pageBreaks';
// A4 portrait / landscape at 96dpi, plus the 20px gap between two pages.
const P = 1123;
const L = 794;
const GAP = 20;
describe('PageGrid', () => {
it('is uniform until a section says otherwise', () => {
const g = new PageGrid(P);
expect(g.topOf(1)).toBe(0);
expect(g.topOf(3)).toBe(2 * (P + GAP));
expect(g.pageAt(0)).toBe(1);
expect(g.pageAt(P + GAP)).toBe(2);
expect(g.pageAt(2 * (P + GAP) + 10)).toBe(3);
});
it('moves every page below a section on its own paper', () => {
const g = new PageGrid(P);
g.setFrom(2, L);
g.setFrom(3, P);
expect(g.heightOf(2)).toBe(L);
expect(g.heightOf(3)).toBe(P);
expect(g.topOf(2)).toBe(P + GAP);
expect(g.topOf(3)).toBe(P + GAP + L + GAP);
expect(g.pageAt(P + GAP)).toBe(2);
expect(g.pageAt(P + GAP + L + GAP)).toBe(3);
expect(g.bottomOf(3)).toBe(P + GAP + L + GAP + P);
});
it('lets a later run replace one it starts on', () => {
const g = new PageGrid(P);
g.setFrom(4, L);
g.setFrom(4, P);
expect(g.heightOf(4)).toBe(P);
expect(g.topOf(5)).toBe(4 * (P + GAP));
});
it('boxes every page for the layers that paint them', () => {
const g = new PageGrid(P);
g.setFrom(2, L);
expect(g.boxes(3)).toEqual([
{ top: 0, height: P },
{ top: P + GAP, height: L },
{ top: P + GAP + L + GAP, height: L },
]);
});
it('reads back the runs it publishes', () => {
const g = gridFromRuns(`2|${L},3|${P}`, P);
expect(g.heightOf(1)).toBe(P);
expect(g.heightOf(2)).toBe(L);
expect(g.heightOf(3)).toBe(P);
// A document with no sections writes no runs at all.
expect(gridFromRuns('', P).heightOf(9)).toBe(P);
});
});