walter-boente_book-collection/js/snapToBaseline.js

65 lines
2.1 KiB
JavaScript
Raw Normal View History

2026-04-10 11:46:11 +02:00
import { Handler } from '/csspageweaver/lib/paged.esm.js';
export default class snapToBaseline extends Handler {
constructor(chunker, polisher, caller) {
super(chunker, polisher, caller);
2026-04-10 12:51:41 +02:00
this.baseline;
}
beforeParsed(content){
this.baseline = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--baseline').trim());
2026-04-14 18:18:10 +02:00
content.querySelectorAll('blockquote').forEach((bq) => {
const prev = bq.previousElementSibling;
if (!prev || prev.nodeName !== 'P') {
bq.style.color = 'red';
}
});
2026-04-10 11:46:11 +02:00
}
renderNode(node, sourceNode){
if (node.nodeName === 'P') {
2026-04-10 12:51:41 +02:00
this.baseline = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--baseline').trim());
2026-04-14 18:18:10 +02:00
if (!shouldSnap(node)) return node;
2026-04-10 12:51:41 +02:00
const area = node.closest('.pagedjs_area');
if (area) {
const areaRect = area.getBoundingClientRect();
const nodeRect = node.getBoundingClientRect();
const relativeTop = nodeRect.top - areaRect.top;
const modulo = relativeTop % this.baseline;
if (modulo !== 0) {
2026-04-14 18:18:10 +02:00
node.style.paddingTop = (this.baseline - modulo) + 'px';
2026-04-10 12:51:41 +02:00
}
}
2026-04-10 11:46:11 +02:00
return node;
}
}
2026-04-14 18:18:10 +02:00
afterPageLayout(pageElement, page, breakToken){
const area = pageElement.querySelector('.pagedjs_area');
if (!area) return;
const areaRect = area.getBoundingClientRect();
const paragraphs = pageElement.querySelectorAll('p');
paragraphs.forEach((node) => {
const nodeRect = node.getBoundingClientRect();
if (nodeRect.bottom < areaRect.bottom - this.baseline) return;
if (!shouldSnap(node)) return;
const relativeTop = nodeRect.top - areaRect.top;
const modulo = relativeTop % this.baseline;
if (modulo !== 0) {
node.style.paddingTop = (this.baseline - modulo) + 'px';
}
});
}
2026-04-10 11:46:11 +02:00
}
2026-04-14 18:18:10 +02:00
function shouldSnap(node) {
return !node.closest('blockquote');
}