Files
ai.interactive.fiction/public/js/text-processor.js
T

72 lines
2.6 KiB
JavaScript

/**
* TextProcessor Module
* Encapsulates text pre-processing steps required before layout calculation.
*/
export class TextProcessor {
/**
* Create a new TextProcessor
* @param {Object} smartyPants - The SmartyPants library
* @param {Function} [hyphenator] - Optional: The hyphenation function (can be set later)
*/
constructor(smartyPants, hyphenator = null) { // Make hyphenator optional
this.smartyPants = smartyPants;
this.hyphenator = hyphenator;
this.hyphenationClass = '.hyphenatePipe'; // Default hyphenation class for Knuth-Plass with pipe character
}
/**
* Process text with typographic enhancements and hyphenation
* @param {string} text - The text to process
* @returns {string} The processed text
*/
process(text) {
// First apply SmartyPants for typographic enhancement
const smartyPantsText = this.smartyPants.smartypantsu(text, 1)
// Remove these replacements that were causing the spacing issues
// .replace(/\.\s*$/g, '.')
// .replace(/\?\s*$/g, '?')
// .replace(/!\s*$/g, '!')
// Instead, ensure proper spacing between sentences
.replace(/\.\s+/g, '. ') // Normalize spaces after periods
.replace(/\?\s+/g, '? ') // Normalize spaces after question marks
.replace(/!\s+/g, '! '); // Normalize spaces after exclamation marks
// Then apply hyphenation if available
if (typeof this.hyphenator === 'function') {
return this.hyphenator(smartyPantsText, this.hyphenationClass);
} else {
console.warn('TextProcessor: Hyphenator not set, skipping hyphenation.');
return smartyPantsText; // Return text without hyphenation if not set
}
}
/**
* Set the hyphenator function after initialization.
* @param {Function} hyphenatorFunction - The hyphenation function provided by Hyphenopoly.
*/
setHyphenator(hyphenatorFunction) {
if (typeof hyphenatorFunction === 'function') {
this.hyphenator = hyphenatorFunction;
} else {
console.error('TextProcessor: Invalid hyphenator function provided.');
}
}
/**
* Set the hyphenation class
* @param {string} className - The CSS class for hyphenation
*/
setHyphenationClass(className) {
this.hyphenationClass = className;
}
/**
* Get the current hyphenation class
* @returns {string} The current hyphenation class
*/
getHyphenationClass() {
return this.hyphenationClass;
}
}