-
Notifications
You must be signed in to change notification settings - Fork 0
[Romanizer] 羅馬字顯示變調 ruby #226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Aiuanyu
wants to merge
1
commit into
main
Choose a base branch
from
romanizer-sandhi-ruby-5811855358397986759
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -95,17 +95,33 @@ document.addEventListener('DOMContentLoaded', () => { | |
| const wrapper = uppercaseBtn.parentNode; | ||
| // 【新】為這粒音節加上手動設定个標籤 | ||
| wrapper.dataset.manualCase = 'true'; | ||
|
|
||
| // --- Refactored to handle ruby elements --- | ||
| const handleTextNode = (node) => { | ||
| const currentText = node.textContent; | ||
| if (currentText && currentText.length > 0) { | ||
| if (currentText[0] === currentText[0].toUpperCase()) { | ||
| node.textContent = currentText.toLowerCase(); | ||
| } else { | ||
| node.textContent = currentText.charAt(0).toUpperCase() + currentText.slice(1); | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| const textNode = Array.from(wrapper.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| const rubyElement = wrapper.querySelector('ruby'); | ||
|
|
||
| if (textNode) { | ||
| const currentText = textNode.textContent; | ||
| if (currentText[0] === currentText[0].toUpperCase()) { | ||
| textNode.textContent = currentText.toLowerCase(); | ||
| } else { | ||
| textNode.textContent = currentText.charAt(0).toUpperCase() + currentText.slice(1); | ||
| handleTextNode(textNode); | ||
| } else if (rubyElement) { | ||
| // If it's a ruby, the first child node should be the text node of the base text | ||
| const rubyTextNode = Array.from(rubyElement.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| if (rubyTextNode) { | ||
| handleTextNode(rubyTextNode); | ||
| } | ||
| // 手動調整後,毋使呼叫 applyCapitalizationRules,直接儲存狀態 | ||
| saveState(); | ||
| } | ||
| // 手動調整後,毋使呼叫 applyCapitalizationRules,直接儲存狀態 | ||
| saveState(); | ||
| } | ||
| else if (deleteBtn) { | ||
| const wrapper = deleteBtn.parentNode; | ||
|
|
@@ -498,8 +514,18 @@ document.addEventListener('DOMContentLoaded', () => { | |
| function populateSegmentGroup(container, romanizedText, sourceSpan) { | ||
| container.innerHTML = ''; | ||
| const tokens = tokenizeRomanization(romanizedText); | ||
|
|
||
| // --- Apply Sandhi if engine is available --- | ||
| let sandhiResults = []; | ||
| if (typeof HakkaSandhi !== 'undefined') { | ||
| sandhiResults = HakkaSandhi.applyToTokens(tokens, romanizerSelectedDialect); | ||
| } else { | ||
| sandhiResults = tokens.map(t => ({ text: t, sandhi: null })); | ||
| } | ||
|
|
||
| tokens.forEach(token => { | ||
| sandhiResults.forEach(res => { | ||
| const token = res.text || (res.variants && res.variants.map(v => v.text).join('/')); | ||
|
|
||
| if (!/[【】()()\/]/.test(token)) { | ||
| // 【新邏輯】淨產生音節个 wrapper,毋產生連接符號 | ||
| const wrapper = document.createElement('span'); | ||
|
|
@@ -510,7 +536,36 @@ document.addEventListener('DOMContentLoaded', () => { | |
| if (sourceSpan.dataset.noCapitalize) { | ||
| wrapper.dataset.noCapitalize = 'true'; | ||
| } | ||
| wrapper.appendChild(document.createTextNode(token)); | ||
|
|
||
| // --- Render Sandhi with Ruby --- | ||
| if (res.variants) { | ||
| res.variants.forEach((v, idx) => { | ||
| if (v.newTone) { | ||
| const ruby = document.createElement('ruby'); | ||
| ruby.className = v.rubyClass; | ||
| ruby.textContent = v.text; | ||
| const rt = document.createElement('rt'); | ||
| rt.textContent = v.newTone; | ||
| ruby.appendChild(rt); | ||
| wrapper.appendChild(ruby); | ||
| } else { | ||
| wrapper.appendChild(document.createTextNode(v.text)); | ||
| } | ||
| if (idx < res.variants.length - 1) { | ||
| wrapper.appendChild(document.createTextNode('/')); | ||
| } | ||
| }); | ||
| } else if (res.newTone) { | ||
| const ruby = document.createElement('ruby'); | ||
| ruby.className = res.rubyClass; | ||
| ruby.textContent = res.text; | ||
| const rt = document.createElement('rt'); | ||
| rt.textContent = res.newTone; | ||
| ruby.appendChild(rt); | ||
| wrapper.appendChild(ruby); | ||
| } else { | ||
| wrapper.appendChild(document.createTextNode(token)); | ||
| } | ||
|
Comment on lines
+541
to
+568
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 在 為了讓程式碼更簡潔並易於維護,建議將這段邏輯提取到一個輔助函式中,以有效減少重複的程式碼。 const createRubyElement = (text, newTone, className) => {
const ruby = document.createElement('ruby');
ruby.className = className;
ruby.textContent = text;
const rt = document.createElement('rt');
rt.textContent = newTone;
ruby.appendChild(rt);
return ruby;
};
if (res.variants) {
res.variants.forEach((v, idx) => {
if (v.newTone) {
wrapper.appendChild(createRubyElement(v.text, v.newTone, v.rubyClass));
} else {
wrapper.appendChild(document.createTextNode(v.text));
}
if (idx < res.variants.length - 1) {
wrapper.appendChild(document.createTextNode('/'));
}
});
} else if (res.newTone) {
wrapper.appendChild(createRubyElement(res.text, res.newTone, res.rubyClass));
} else {
wrapper.appendChild(document.createTextNode(token));
} |
||
|
|
||
| const uppercaseBtn = document.createElement('button'); | ||
| uppercaseBtn.className = 'uppercase-btn'; | ||
|
|
@@ -545,11 +600,23 @@ document.addEventListener('DOMContentLoaded', () => { | |
| if (wrapper.dataset.manualCase) { | ||
| return; | ||
| } | ||
|
|
||
| const handleLowering = (node) => { | ||
| const currentText = node.textContent; | ||
| if (currentText && currentText.length > 0) { | ||
| node.textContent = currentText.charAt(0).toLowerCase() + currentText.slice(1); | ||
| } | ||
| }; | ||
|
|
||
| const textNode = Array.from(wrapper.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| const rubyElement = wrapper.querySelector('ruby'); | ||
|
|
||
| if (textNode) { | ||
| const currentText = textNode.textContent; | ||
| if (currentText && currentText.length > 0) { | ||
| textNode.textContent = currentText.charAt(0).toLowerCase() + currentText.slice(1); | ||
| handleLowering(textNode); | ||
| } else if (rubyElement) { | ||
| const rubyTextNode = Array.from(rubyElement.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| if (rubyTextNode) { | ||
| handleLowering(rubyTextNode); | ||
| } | ||
| } | ||
| }); | ||
|
|
@@ -575,10 +642,21 @@ document.addEventListener('DOMContentLoaded', () => { | |
| if (firstSyllableInGroup) { | ||
| // 【新】愛確定無手動標籤,正做自動大寫 | ||
| if (capitalizeNext && !firstSyllableInGroup.dataset.manualCase && !firstSyllableInGroup.dataset.noCapitalize) { | ||
| const textNode = Array.from(firstSyllableInGroup.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| if (textNode) { | ||
| const handleUpper = (textNode) => { | ||
| const text = textNode.textContent; | ||
| textNode.textContent = text.charAt(0).toUpperCase() + text.slice(1); | ||
| }; | ||
|
|
||
| const textNode = Array.from(firstSyllableInGroup.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| const rubyElement = firstSyllableInGroup.querySelector('ruby'); | ||
|
|
||
| if (textNode) { | ||
| handleUpper(textNode); | ||
| } else if (rubyElement) { | ||
| const rubyTextNode = Array.from(rubyElement.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| if (rubyTextNode) { | ||
| handleUpper(rubyTextNode); | ||
| } | ||
| } | ||
| } | ||
| capitalizeNext = false; | ||
|
|
@@ -660,12 +738,21 @@ function updateJoiningSeparators() { | |
|
|
||
| // 若係無障礙物,正插入連接符號 | ||
| if (!hasObstacle) { | ||
| const s1TextNode = Array.from(s1.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| const s2TextNode = Array.from(s2.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| const getSyllableText = (syllableEl) => { | ||
| const textNode = Array.from(syllableEl.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| if (textNode) return textNode.textContent.toLowerCase(); | ||
| const ruby = syllableEl.querySelector('ruby'); | ||
| if (ruby) { | ||
| const rubyTextNode = Array.from(ruby.childNodes).find(n => n.nodeType === Node.TEXT_NODE); | ||
| if (rubyTextNode) return rubyTextNode.textContent.toLowerCase(); | ||
| } | ||
| return ''; | ||
| }; | ||
|
|
||
| const s1Text = getSyllableText(s1); | ||
| const s2Text = getSyllableText(s2); | ||
|
|
||
| if (s1TextNode && s2TextNode) { | ||
| const s1Text = s1TextNode.textContent.toLowerCase(); | ||
| const s2Text = s2TextNode.textContent.toLowerCase(); | ||
| if (s1Text && s2Text) { | ||
| let separator = ''; | ||
|
|
||
| switch (romanizerJoiningMode) { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| /** | ||
| * HakSpring Sandhi Engine | ||
| * Generalized framework for Hakka tone sandhi rules. | ||
| */ | ||
|
|
||
| const HakkaSandhi = (() => { | ||
| const BLOCKING_PUNCTUATION = '()()【】'; | ||
| const SKIPPABLE_PUNCTUATION = '\\s、'; | ||
| const ALL_PUNCTUATION_CHARS = SKIPPABLE_PUNCTUATION + BLOCKING_PUNCTUATION; | ||
|
|
||
| const TOKENIZER_REGEX = new RegExp( | ||
| `[^<>` + | ||
| ALL_PUNCTUATION_CHARS + | ||
| `]+|[${SKIPPABLE_PUNCTUATION}]+|[${BLOCKING_PUNCTUATION}]+`, | ||
| 'g' | ||
| ); | ||
| const SKIPPABLE_REGEX = new RegExp(`^[${SKIPPABLE_PUNCTUATION}]+$`); | ||
| const BLOCKING_REGEX = new RegExp(`^[${BLOCKING_PUNCTUATION}]+$`); | ||
|
|
||
| /** | ||
| * Defines sandhi rules for different dialects. | ||
| * Each dialect has an array of rules. | ||
| * A rule is a function: (currentSyllable, nextSyllable) => { newTone, rubyClass } | null | ||
| */ | ||
| const rules = { | ||
| '大埔': [ | ||
| // Rule 1: 31/53 + (31, 11, 33, 53, 2) -> 55 (高降變) | ||
| // Note: Dapu 31 is circumflex [âêîôû], while some other dialects/notations might use grave [àèìòù]. | ||
| (current, next) => { | ||
| if (current.match(/[àèìòùâêîôû](?![bdg])/) && next.match(/[àèìòùâêîôûǎěǐǒǔāēīōū]/)) { | ||
| return { newTone: '55', rubyClass: 'sandhi-高降變' }; | ||
| } | ||
| return null; | ||
| }, | ||
| // Rule 2: 33 + (113, 21, 53, 31, 35) -> 35 (中平變) | ||
| (current, next) => { | ||
| if (current.match(/[āēīōū]/) && next.match(/[ǎěǐǒǔâêîôûàèìòùáéíóú]/)) { | ||
| return { newTone: '35', rubyClass: 'sandhi-中平變' }; | ||
| } | ||
| return null; | ||
| }, | ||
| // Rule 3: 113 + 113 -> 33 (低升變) | ||
| (current, next) => { | ||
| if (current.match(/[ǎěǐǒǔ]/) && next.match(/[ǎěǐǒǔ]/)) { | ||
| return { newTone: '33', rubyClass: 'sandhi-低升變' }; | ||
| } | ||
| return null; | ||
| } | ||
| ] | ||
| // Other dialects can be added here | ||
| }; | ||
|
|
||
| /** | ||
| * Applies sandhi rules to a single syllable given the next one. | ||
| */ | ||
| function applyRule(syllable, nextSyllable, dialect) { | ||
| const dialectRules = rules[dialect] || []; | ||
| for (const rule of dialectRules) { | ||
| const result = rule(syllable, nextSyllable); | ||
| if (result) return result; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * Processes a list of tokens and applies sandhi. | ||
| * Tokens can be syllables, punctuation, or spaces. | ||
| */ | ||
| function applyToTokens(tokens, dialectName) { | ||
| const dialect = dialectName ? dialectName.replace('教典', '') : ''; | ||
| const results = []; | ||
| for (let i = 0; i < tokens.length; i++) { | ||
| let currentToken = tokens[i]; | ||
|
|
||
| // Skip non-syllables or already processed ruby tags | ||
| if ( | ||
| currentToken.startsWith('<ruby') || | ||
| SKIPPABLE_REGEX.test(currentToken) || | ||
| BLOCKING_REGEX.test(currentToken) | ||
| ) { | ||
| results.push({ text: currentToken, sandhi: null }); | ||
| continue; | ||
| } | ||
|
|
||
| // Find the next "real" word token | ||
| let nextWordToken = ''; | ||
| for (let j = i + 1; j < tokens.length; j++) { | ||
| if ( | ||
| tokens[j].startsWith('<ruby') || | ||
| SKIPPABLE_REGEX.test(tokens[j]) | ||
| ) { | ||
| continue; | ||
| } | ||
| if (BLOCKING_REGEX.test(tokens[j])) { | ||
| break; | ||
| } | ||
| nextWordToken = tokens[j]; | ||
| break; | ||
| } | ||
|
|
||
| if (!nextWordToken) { | ||
| results.push({ text: currentToken, sandhi: null }); | ||
| continue; | ||
| } | ||
|
|
||
| // Handle multiple variants separated by '/' | ||
| if (currentToken.includes('/')) { | ||
| const variants = currentToken.split('/'); | ||
| const processedVariants = variants.map(v => { | ||
| const ruleResult = applyRule(v, nextWordToken, dialect); | ||
| return ruleResult ? { text: v, ...ruleResult } : { text: v, sandhi: null }; | ||
| }); | ||
| results.push({ variants: processedVariants }); | ||
| } else { | ||
| const ruleResult = applyRule(currentToken, nextWordToken, dialect); | ||
| results.push(ruleResult ? { text: currentToken, ...ruleResult } : { text: currentToken, sandhi: null }); | ||
| } | ||
| } | ||
| return results; | ||
| } | ||
|
|
||
| /** | ||
| * Processes an HTML string (like from the dictionary) and injects <ruby> tags for sandhi. | ||
| */ | ||
| function applyToHtml(htmlContent, dialectName) { | ||
| const dialect = dialectName ? dialectName.replace('教典', '') : ''; | ||
| if (!dialect || !rules[dialect]) return htmlContent; | ||
|
|
||
| const sandhiRubyRegex = /<ruby class="sandhi-(?:高降變|中平變|低升變)"[^>]*>.*?<\/ruby>/g; | ||
| let preliminaryTokens = []; | ||
| let lastIndex = 0; | ||
|
|
||
| // Preserve existing sandhi ruby tags | ||
| htmlContent.replace(sandhiRubyRegex, (match, offset) => { | ||
| if (offset > lastIndex) { | ||
| preliminaryTokens.push(htmlContent.substring(lastIndex, offset)); | ||
| } | ||
| preliminaryTokens.push(match); | ||
| lastIndex = offset + match.length; | ||
| return match; | ||
| }); | ||
| if (lastIndex < htmlContent.length) { | ||
| preliminaryTokens.push(htmlContent.substring(lastIndex)); | ||
| } | ||
|
|
||
| const tokens = preliminaryTokens | ||
| .flatMap((token) => { | ||
| if (token.startsWith('<ruby')) return [token]; | ||
| return token.match(TOKENIZER_REGEX) || []; | ||
| }) | ||
| .filter((t) => t && t.length > 0); | ||
|
|
||
| const sandhiResults = applyToTokens(tokens, dialect); | ||
| let hasActualModification = false; | ||
|
|
||
| const finalTokens = sandhiResults.map(res => { | ||
| if (res.variants) { | ||
| const variantHtml = res.variants.map(v => { | ||
| if (v.newTone) { | ||
| hasActualModification = true; | ||
| return `<ruby class="${v.rubyClass}">${v.text}<rt>${v.newTone}</rt></ruby>`; | ||
| } | ||
| return v.text; | ||
| }).join('/'); | ||
| return variantHtml; | ||
| } else if (res.newTone) { | ||
| hasActualModification = true; | ||
| return `<ruby class="${res.rubyClass}">${res.text}<rt>${res.newTone}</rt></ruby>`; | ||
| } | ||
| return res.text; | ||
| }); | ||
|
|
||
| return hasActualModification ? finalTokens.join('') : htmlContent; | ||
| } | ||
|
|
||
| return { | ||
| applyToTokens, | ||
| applyToHtml, | ||
| hasRulesFor: (dialect) => !!(dialect && rules[dialect.replace('教典', '')]) | ||
| }; | ||
| })(); | ||
|
|
||
| // Export for browser environment | ||
| if (typeof window !== 'undefined') { | ||
| window.HakkaSandhi = HakkaSandhi; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
這段用來尋找 syllable wrapper (
<span>或<ruby>) 內文字節點的邏輯,在applyCapitalizationRules函式中 (分別是handleLowering和handleUpper的部分) 也有重複。為了提高程式碼的可維護性並減少重複,建議將這段邏輯提取到一個獨立的輔助函式中。例如,可以在
romanizer.js的頂層範圍定義一個函式:然後,這裡的程式碼就可以簡化成:
同樣的簡化也可以應用在
applyCapitalizationRules函式中,讓程式碼更簡潔且易於維護。