// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2), src/utils/lyrics/sentenceLayout.ts. // Splits one lyric line into a wanted number of display lines, at the most natural places first: punctuation, // then brackets and quotes, runs of Western words inside CJK text, spaces after CJK, special separators; a line // still too long is cut at the word boundary nearest its middle, and too many pieces are merged shortest first. // // Changed from Folia: the class with static methods became functions; only the positive `targetCount` path that // 倾诉 uses is kept. const CJK_REGEX = /[一-龥぀-ヿ가-힯]/; const hasCjkText = (text: string) => CJK_REGEX.test(text); const splitByPunctuation = (text: string): string[] => { const matches = [...text.matchAll(/[,。;!?、…·.,;!?]+/g)]; if (matches.length === 0) return [text]; const result: string[] = []; let lastIndex = 0; for (const match of matches) { const punctStart = match.index ?? 0; const punctEnd = punctStart + match[0].length; const trailingSpaces = text.slice(punctEnd).match(/^\s+/)?.[0] ?? ''; const beforePunct = text.slice(lastIndex, punctStart); const punctWithSpaces = match[0] + trailingSpaces; if (beforePunct.length > 0) result.push(beforePunct + punctWithSpaces); else if (result.length > 0) result[result.length - 1] += punctWithSpaces; else result.push(punctWithSpaces); lastIndex = punctEnd + trailingSpaces.length; } if (lastIndex < text.length) result.push(text.slice(lastIndex)); return result.filter(part => part.length > 0); }; interface PairedSymbol { open: string; close: string } const PAIRED_SYMBOLS: PairedSymbol[] = [ { open: '「', close: '」' }, { open: '『', close: '』' }, { open: '《', close: '》' }, { open: '【', close: '】' }, { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '(', close: ')' }, { open: '"', close: '"' }, { open: "'", close: "'" }, ]; const findOutermostPair = (text: string): { openStart: number; closeEnd: number } | null => { let best: { openStart: number; closeEnd: number } | null = null; for (const { open, close } of PAIRED_SYMBOLS) { const openStart = text.indexOf(open); if (openStart === -1) continue; const closeStart = text.indexOf(close, openStart + open.length); if (closeStart === -1) continue; const candidate = { openStart, closeEnd: closeStart + close.length }; if (!best || candidate.openStart < best.openStart || (candidate.openStart === best.openStart && candidate.closeEnd > best.closeEnd)) { best = candidate; } } return best; }; const extractOutermostPairs = (text: string): string[] => { const best = findOutermostPair(text); if (!best) return [text]; const before = text.slice(0, best.openStart); const remainder = text.slice(best.closeEnd); const result: string[] = []; if (before.length > 0) result.push(...extractOutermostPairs(before)); result.push(text.slice(best.openStart, best.closeEnd)); if (remainder.length > 0) result.push(...extractOutermostPairs(remainder)); return result.filter(part => part.length > 0); }; const splitByBracketsQuotes = (text: string): string[] => { const result = extractOutermostPairs(text); return result.length > 1 ? result : [text]; }; const countOf = (text: string, char: string) => text.split(char).length - 1; const shouldSkipBoundary = (fullText: string, beforeBlock: string): boolean => { if (beforeBlock.length === 0) return false; const sepChar = beforeBlock[beforeBlock.length - 1]; if (sepChar === '-') return true; if (':://||'.includes(sepChar)) return countOf(fullText, sepChar) >= 2; return false; }; const splitByWesternWords = (text: string): string[] => { if (!hasCjkText(text)) return [text]; const westernBlockRegex = /[a-zA-Z0-9]+(?:[a-zA-Z0-9'-]*[a-zA-Z0-9]+)?(?:\s+[a-zA-Z0-9]+(?:[a-zA-Z0-9'-]*[a-zA-Z0-9]+)?)+[.,;:!?。,;:!?]?\s*/g; const blocks = [...text.matchAll(westernBlockRegex)]; if (!blocks.some(block => (block[0].match(/[a-zA-Z0-9]+/g)?.length ?? 0) > 1)) return [text]; const parts: string[] = []; let lastIndex = 0; for (const block of blocks) { const blockStart = block.index ?? 0; const beforeBlock = text.slice(lastIndex, blockStart); if (shouldSkipBoundary(text, beforeBlock)) { parts.push(beforeBlock + block[0]); } else if (blockStart > lastIndex) { parts.push(beforeBlock); parts.push(block[0]); } else { parts.push(block[0]); } lastIndex = blockStart + block[0].length; } if (lastIndex < text.length) parts.push(text.slice(lastIndex)); return parts.length > 1 ? parts : [text]; }; const splitCJKBySpace = (text: string): string[] => { if (!hasCjkText(text)) return [text]; const segments: string[] = []; let currentSegment = ''; let inCjkBlock = false; for (const char of text) { if (CJK_REGEX.test(char)) { currentSegment += char; inCjkBlock = true; } else if (/[a-zA-Z0-9]/.test(char)) { // Western characters stay with the block they are in. currentSegment += char; } else if (/\s/.test(char)) { // A full-width space always splits and stays with the piece before it; a half-width one splits // only right after a CJK character. if (char === ' ' && currentSegment.length > 0) { segments.push(currentSegment + char); currentSegment = ''; inCjkBlock = false; } else if (inCjkBlock && currentSegment.length > 0) { if (CJK_REGEX.test(currentSegment[currentSegment.length - 1])) { segments.push(currentSegment + char); currentSegment = ''; inCjkBlock = false; } else { currentSegment += char; } } else if (currentSegment.length === 0 && segments.length > 0) { segments[segments.length - 1] += char; } else { currentSegment += char; } } else if (currentSegment.length === 0 && segments.length > 0) { segments[segments.length - 1] += char; } else { currentSegment += char; } } if (currentSegment) { if (segments.length > 0 && /^\s+$/.test(currentSegment)) segments[segments.length - 1] += currentSegment; else segments.push(currentSegment); } return segments.length > 1 ? segments : [text]; }; const splitBySpecialChars = (text: string): string[] => { const parts = text.split(/[:://\\||~~]+/); if (parts.filter(part => part.length > 0).length <= 1) return [text]; const result: string[] = []; let lastIndex = 0; for (const part of parts) { const index = text.indexOf(part, lastIndex); if (index > lastIndex) { const specialChar = text.slice(lastIndex, index); if (result.length > 0) result[result.length - 1] += specialChar; else result.push(specialChar); } if (part) { result.push(part); lastIndex = index + part.length; } else if (index !== -1) { lastIndex = index; } } if (lastIndex < text.length) { const tail = text.slice(lastIndex); if (tail && result.length > 0) result[result.length - 1] += tail; else if (tail) result.push(tail); } return result.filter(part => part.length > 0); }; const LEVELS = [splitByPunctuation, splitByBracketsQuotes, splitByWesternWords, splitCJKBySpace, splitBySpecialChars]; const wordSegmenter = typeof Intl !== 'undefined' && Intl.Segmenter ? new Intl.Segmenter(undefined, { granularity: 'word' }) : null; /** Cuts the best-balanced piece in two at a word boundary until there are enough pieces. */ const secondarySplit = (sentences: string[], targetCount: number, timeSeed = 0): string[] => { while (sentences.length < targetCount) { const candidates = sentences.filter(sentence => sentence.length > 2); if (candidates.length === 0) break; if (wordSegmenter) { const semanticCandidates: { index: number; splitPos: number; score: number }[] = []; for (const sentence of candidates) { const wordStarts: number[] = []; let offset = 0; for (const part of wordSegmenter.segment(sentence)) { if (part.isWordLike) wordStarts.push(offset); offset += part.segment.length; } if (wordStarts.length < 2) continue; const midChar = sentence.length / 2; let bestGap = 1; let bestDist = Infinity; for (let gap = 1; gap < wordStarts.length; gap++) { const dist = Math.abs(wordStarts[gap] - midChar); if (dist < bestDist) { bestDist = dist; bestGap = gap; } } const splitPos = wordStarts[bestGap]; const balanceScore = 1 - Math.abs(splitPos - midChar) / midChar; semanticCandidates.push({ index: sentences.indexOf(sentence), splitPos, score: balanceScore * 10 + wordStarts.length }); } if (semanticCandidates.length > 0) { semanticCandidates.sort((a, b) => b.score - a.score); const best = semanticCandidates[0]; const sentence = sentences[best.index]; sentences.splice(best.index, 1, sentence.slice(0, best.splitPos), sentence.slice(best.splitPos)); continue; } } const textHash = sentences.reduce((acc, sentence) => acc + sentence.split('').reduce((sum, char) => sum + char.charCodeAt(0), 0), 0); const x = Math.sin(textHash + sentences.length + timeSeed) * 10000; const selected = candidates[Math.floor((x - Math.floor(x)) * candidates.length)]; const selectedIndex = sentences.indexOf(selected); const midPoint = Math.floor(selected.length / 2); sentences.splice(selectedIndex, 1, selected.slice(0, midPoint), selected.slice(midPoint)); } return sentences; }; /** Joins the two neighbours that are shortest together until the count fits. */ const mergeSentences = (sentences: string[], targetCount: number): string[] => { while (sentences.length > targetCount) { let bestMergeIndex = 0; let shortestCombinedLength = Infinity; for (let i = 0; i < sentences.length - 1; i++) { const combinedLength = sentences[i].length + sentences[i + 1].length; if (combinedLength < shortestCombinedLength) { shortestCombinedLength = combinedLength; bestMergeIndex = i; } } sentences.splice(bestMergeIndex, 2, sentences[bestMergeIndex] + sentences[bestMergeIndex + 1]); } return sentences; }; /** `text` as `targetCount` pieces that join back to it exactly. */ export const splitIntoSentences = (text: string, targetCount: number, timeSeed?: number): string[] => { if (targetCount <= 1) return [text]; let sentences = [text]; for (const splitLevel of LEVELS) { if (sentences.length >= targetCount) break; sentences = sentences.flatMap(sentence => splitLevel(sentence)); } if (sentences.length < targetCount) sentences = secondarySplit(sentences, targetCount, timeSeed); if (sentences.length > 1 && sentences.length > targetCount) sentences = mergeSentences(sentences, targetCount); return sentences; };