// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2), src/utils/lyrics/cjkSemanticLayout.ts. // Display planning after parsing: timed words grouped into units a style lays out (a CJK word of several // characters, a word with the punctuation that follows it), every original word kept inside for its timing. // // Changed from Folia: no user-saved or icu-folia segmentation, only Intl.Segmenter. import type { Line, Word } from '../types'; import { isCJK, segmentTextWords } from './graphemes'; export interface LyricLayoutUnit { /** Text used for layout planning. */ text: string; /** Original words in this unit; their timing stays the source of truth. */ words: Word[]; startTime: number; endTime: number; /** True when Intl.Segmenter grouped CJK words into one semantic unit. */ isSemantic: boolean; /** True when punctuation or a contraction has been attached for a stable layout. */ isSticky?: boolean; } type SegmentableLine = Pick; interface WordSegment { segment: string; isWordLike?: boolean; } const APOSTROPHE_ONLY_REGEX = /^['’]\s*$/; const CONTRACTION_SUFFIX_REGEX = /^(s|t|m|d|ll|re|ve|em)\s*$/i; const DIRECT_CONTRACTION_REGEX = /^['’](s|t|m|d|ll|re|ve|em)\s*$/i; const TRAILING_APOSTROPHE_REGEX = /['’]\s*$/; const TRAILING_WORD_CHAR_REGEX = /[\p{L}\p{N}]$/u; const INLINE_CONTRACTION_REGEX = /[\p{L}\p{N}]+['’](s|t|m|d|ll|re|ve|em)/iu; const STICKY_TRAILING_PUNCTUATION_REGEX = /^[,.;:!?,。!?、:;)】》」』〉〕])}\]"'’”’]+$/u; export const createSingleWordLayoutUnits = (words: Word[]): LyricLayoutUnit[] => words.map(word => ({ text: word.text, words: [word], startTime: word.startTime, endTime: word.endTime, isSemantic: false, })); const appendWordsToUnit = (unit: LyricLayoutUnit, text: string, words: Word[]) => { unit.text += text; unit.words.push(...words); unit.endTime = words[words.length - 1]?.endTime ?? unit.endTime; }; const cloneUnit = (unit: LyricLayoutUnit): LyricLayoutUnit => ({ ...unit, words: [...unit.words] }); const appendUnitToStickyUnit = (target: LyricLayoutUnit, unit: LyricLayoutUnit) => { target.text += unit.text; target.words.push(...unit.words); target.endTime = unit.endTime; target.isSticky = true; }; const canAttachToPrevious = (text: string) => TRAILING_WORD_CHAR_REGEX.test(text.trimEnd()); const endsWithApostrophe = (text: string) => TRAILING_APOSTROPHE_REGEX.test(text.trimEnd()); const isApostropheOnlyUnit = (unit: LyricLayoutUnit) => APOSTROPHE_ONLY_REGEX.test(unit.text.trim()); const isContractionSuffixUnit = (unit: LyricLayoutUnit) => CONTRACTION_SUFFIX_REGEX.test(unit.text.trim()); const isDirectContractionUnit = (unit: LyricLayoutUnit) => DIRECT_CONTRACTION_REGEX.test(unit.text.trim()); const isStickyTrailingPunctuationText = (text: string) => STICKY_TRAILING_PUNCTUATION_REGEX.test(text.trim()); const hasAttachedTrailingPunctuation = (unit: LyricLayoutUnit) => { if (unit.words.length <= 1) return false; const lastWord = unit.words[unit.words.length - 1]; return Boolean(lastWord && isStickyTrailingPunctuationText(lastWord.text)); }; const hasInlineContraction = (unit: LyricLayoutUnit) => ( unit.words.length > 1 && !unit.isSemantic && INLINE_CONTRACTION_REGEX.test(unit.text) ); const stripWhitespace = (text: string) => text.replace(/\s+/g, ''); // Maps Intl.Segmenter output back onto the timed words, comparing text with whitespace removed. If any segment // cannot be aligned exactly, the caller falls back to one-word units instead of guessing. const mapSegmentsToWords = (segments: WordSegment[], words: Word[]): LyricLayoutUnit[] | null => { const units: LyricLayoutUnit[] = []; let wordIndex = 0; const absorbWhitespaceWords = () => { const previous = units[units.length - 1]; while (previous && wordIndex < words.length && !stripWhitespace(words[wordIndex].text)) { appendWordsToUnit(previous, words[wordIndex].text, [words[wordIndex]]); wordIndex += 1; } }; for (const segment of segments) { const segmentKey = stripWhitespace(segment.segment); if (!segmentKey) continue; absorbWhitespaceWords(); const startWordIndex = wordIndex; let collectedKey = ''; while (wordIndex < words.length && collectedKey.length < segmentKey.length) { collectedKey += stripWhitespace(words[wordIndex].text); wordIndex += 1; if (!segmentKey.startsWith(collectedKey)) return null; } if (collectedKey !== segmentKey) return null; const segmentWords = words.slice(startWordIndex, wordIndex); const firstWord = segmentWords[0]; const lastWord = segmentWords[segmentWords.length - 1]; if (!firstWord || !lastWord) return null; // The unit's text is its words' text, so it always joins back to them. const segmentText = segmentWords.map(word => word.text).join(''); if (!segment.isWordLike && units.length > 0) { appendWordsToUnit(units[units.length - 1], segmentText, segmentWords); continue; } const glyphWordCount = segmentWords.filter(word => stripWhitespace(word.text)).length; units.push({ text: segmentText, words: segmentWords, startTime: firstWord.startTime, endTime: lastWord.endTime, isSemantic: Boolean(segment.isWordLike && isCJK(segmentText) && glyphWordCount > 1), }); } absorbWhitespaceWords(); if (wordIndex !== words.length || units.length === 0) return null; return units; }; /** CJK semantic grouping only; Intl.Segmenter adds nothing over spaced words for other scripts. */ export const buildCjkSemanticLayoutUnits = (line: SegmentableLine): LyricLayoutUnit[] => { if (line.words.length === 0) return []; const fallbackUnits = createSingleWordLayoutUnits(line.words); if (!isCJK(line.fullText)) return fallbackUnits; const segments = segmentTextWords(line.fullText); if (segments.length === 0) return fallbackUnits; return mapSegmentsToWords(segments, line.words) ?? fallbackUnits; }; /** Attaches punctuation-like units to the unit before them, so `It`, `’`, `s` are not laid out apart. */ export const applyStickyPunctuationLayoutUnits = (units: LyricLayoutUnit[]): LyricLayoutUnit[] => { const merged: LyricLayoutUnit[] = []; for (let index = 0; index < units.length; index += 1) { const current = units[index]; const previous = merged[merged.length - 1]; if (!previous) { merged.push(cloneUnit(current)); continue; } const next = units[index + 1]; if (isApostropheOnlyUnit(current) && next && canAttachToPrevious(previous.text) && isContractionSuffixUnit(next)) { appendUnitToStickyUnit(previous, current); appendUnitToStickyUnit(previous, next); index += 1; continue; } if (isDirectContractionUnit(current) && canAttachToPrevious(previous.text)) { appendUnitToStickyUnit(previous, current); continue; } if (isContractionSuffixUnit(current) && endsWithApostrophe(previous.text)) { appendUnitToStickyUnit(previous, current); continue; } if (isStickyTrailingPunctuationText(current.text) && canAttachToPrevious(previous.text)) { appendUnitToStickyUnit(previous, current); continue; } merged.push(cloneUnit(current)); } return merged.map(unit => ( hasAttachedTrailingPunctuation(unit) || hasInlineContraction(unit) ? { ...unit, isSticky: true } : unit )); }; /** Semantic grouping first, sticky punctuation second. */ export const buildPostLyricLayoutUnits = ( line: SegmentableLine, options: { semantic?: boolean; sticky?: boolean } = {}, ): LyricLayoutUnit[] => { const rawUnits = options.semantic ? buildCjkSemanticLayoutUnits(line) : createSingleWordLayoutUnits(line.words); return options.sticky ? applyStickyPunctuationLayoutUnits(rawUnits) : rawUnits; }; /** * The words a style draws. A sticky non-semantic unit becomes one word (It + ’ + s → It’s); a semantic CJK unit * gives its original words back, so each character keeps its own time. */ export const buildDisplayWordsFromLayoutUnits = (units: LyricLayoutUnit[]): Word[] => units.flatMap(unit => { if (!unit.isSticky || unit.isSemantic) return unit.words; return [{ text: unit.text, startTime: unit.startTime, endTime: unit.endTime }]; });