Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

<!-- 再載入自訂 JS(保留 defer 確保 DOM 載入完成) -->
<script type="text/javascript" src="js/sandhi.js" defer></script>
<script type="text/javascript" src="main.js" defer></script>
<script type="text/javascript" src="js/romanizer.js" defer></script>
<script type="text/javascript" src="js/supabase-config.js" defer></script>
Expand Down
125 changes: 106 additions & 19 deletions js/romanizer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Comment on lines 111 to 122

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

這段用來尋找 syllable wrapper (<span><ruby>) 內文字節點的邏輯,在 applyCapitalizationRules 函式中 (分別是 handleLoweringhandleUpper 的部分) 也有重複。

為了提高程式碼的可維護性並減少重複,建議將這段邏輯提取到一個獨立的輔助函式中。例如,可以在 romanizer.js 的頂層範圍定義一個函式:

function findSyllableTextNode(wrapper) {
    const textNode = Array.from(wrapper.childNodes).find(n => n.nodeType === Node.TEXT_NODE);
    if (textNode) return textNode;

    const rubyElement = wrapper.querySelector('ruby');
    if (rubyElement) {
        // The base text of a <ruby> tag is its first child text node.
        return Array.from(rubyElement.childNodes).find(n => n.nodeType === Node.TEXT_NODE) || null;
    }
    return null;
}

然後,這裡的程式碼就可以簡化成:

        const nodeToModify = findSyllableTextNode(wrapper);
        if (nodeToModify) {
            handleTextNode(nodeToModify);
        }

同樣的簡化也可以應用在 applyCapitalizationRules 函式中,讓程式碼更簡潔且易於維護。

// 手動調整後,毋使呼叫 applyCapitalizationRules,直接儲存狀態
saveState();
}
else if (deleteBtn) {
const wrapper = deleteBtn.parentNode;
Expand Down Expand Up @@ -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');
Expand All @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

if (res.variants) 區塊和 else if (res.newTone) 區塊中,創建 <ruby> 元素的程式碼是重複的。

為了讓程式碼更簡潔並易於維護,建議將這段邏輯提取到一個輔助函式中,以有效減少重複的程式碼。

                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';
Expand Down Expand Up @@ -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);
}
}
});
Expand All @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
186 changes: 186 additions & 0 deletions js/sandhi.js
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;
}
Loading
Loading