Files

55 lines
2.9 KiB
JavaScript

// CSS cannot extract an individual line from a var()-supplied shorthand.
// Ask the browser's CSS parser, then apply only the explicitly toggled lines.
// This file is included only for documents that need dynamic decorations.
(() => {
const reader = document.querySelector('[data-mdh-leaf-decoration]');
if (!reader) return;
const parser = document.createElement('span').style;
const applied = new WeakMap();
let pending = false;
const refresh = () => {
pending = false;
const changes = [];
// Read first, write second to avoid a layout flush for each text span.
for (const leaf of reader.querySelectorAll('[data-mdh-text]')) {
const style = getComputedStyle(leaf);
const mode = style.getPropertyValue('--mdh-decoration-mode').trim();
const masks = ['underline', 'strike'].map(field => style.getPropertyValue('--mdh-override-' + field).trim());
let line = '';
if ((mode === 'raw' || mode === 'raw-line') && masks.some(value => value === 'true' || value === 'false')) {
parser.cssText = '';
parser.setProperty(mode === 'raw' ? 'text-decoration' : 'text-decoration-line',
style.getPropertyValue(mode === 'raw' ? '--mdh-decoration-shorthand' : '--mdh-decoration-raw').trim());
const lines = new Set(parser.textDecorationLine.split(/\s+/).filter(value => value && value !== 'none'));
['underline', 'line-through'].forEach((token, index) => {
if (masks[index] === 'true') lines.add(token);
if (masks[index] === 'false') lines.delete(token);
});
line = ['underline', 'overline', 'line-through', 'blink'].filter(token => lines.has(token)).join(' ') || 'none';
}
if ((applied.get(leaf) || '') !== line) changes.push([leaf, line]);
}
for (const [leaf, line] of changes) {
if (line) leaf.style.setProperty('text-decoration-line', line, 'important');
else leaf.style.removeProperty('text-decoration-line');
applied.set(leaf, line);
}
};
const schedule = () => {
// Offscreen previews and PDF pages may not receive animation frames.
// Coalesce DOM changes in the same turn without waiting for a visible view.
if (!pending) { pending = true; queueMicrotask(refresh); }
};
// Run before the initial paint, and synchronously before HTML/PDF printing.
refresh();
window.mdhelperRefreshDecorations = refresh;
window.addEventListener('beforeprint', refresh);
window.addEventListener('resize', schedule);
for (const event of ['pointerover', 'pointerout', 'pointerdown', 'pointerup', 'focusin', 'focusout']) {
reader.addEventListener(event, schedule, {passive: true});
}
new MutationObserver(records => {
if (records.some(record => record.type !== 'attributes' || !record.target.hasAttribute('data-mdh-text'))) schedule();
}).observe(document.documentElement, {subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['style', 'class']});
})();