Files
ai.interactive.fiction/public/js/paragraph-layout.js
T

50 lines
1.9 KiB
JavaScript

/**
* ParagraphLayout Module
* Interfaces with the Knuth-Plass line breaking algorithm to calculate optimal line breaks.
*/
export class ParagraphLayout {
/**
* Create a new ParagraphLayout
* @param {Function} kapAlgorithm - The Knuth and Plass algorithm function
* @param {Function} measureTextFunc - Function to measure text width
*/
constructor(kapAlgorithm, measureTextFunc) {
this.kapAlgorithm = kapAlgorithm;
this.measureText = measureTextFunc;
}
/**
* Calculate layout for a paragraph
* @param {string} processedText - The pre-processed text (with SmartyPants and hyphenation)
* @param {Array<number>} measures - Array of line width measurements
* @param {boolean} debug - Whether to enable debug output
* @param {Function} [measureFunc] - Optional specific measurement function for this call
* @returns {Object} Layout data with nodes and breaks
*/
calculateLayout(processedText, measures, hyphenate = false, measureFunc = null) {
const measure = measureFunc || this.measureText; // Use provided func or fallback to instance default
if (typeof measure !== 'function') {
console.error("ParagraphLayout: Invalid measure function provided or stored.");
// Return a dummy layout or throw an error?
return { nodes: [], breaks: [] }; // Return empty layout
}
return this.kapAlgorithm(processedText, measure, measures, hyphenate);
}
/**
* Set a new text measurement function
* @param {Function} measureFunc - The new measurement function
*/
setMeasureFunction(measureFunc) {
this.measureText = measureFunc;
}
/**
* Set a new Knuth and Plass algorithm implementation
* @param {Function} kapFunc - The new KAP algorithm function
*/
setKapAlgorithm(kapFunc) {
this.kapAlgorithm = kapFunc;
}
}