ad_pubfiles/translations/pagesInFoldersWithTranslati...

84 lines
2.8 KiB
JavaScript

import {JSDOM} from 'jsdom';
/*
* The idea: need to create another subdir `title/nl/index.html`
*/
/*
* addTranslationInterface adds the <trl-selector> with radio buttons and labels to each <trl-group>.
* It sets the checked property on the indicated language.
*/
/*
* first, index.html is the original page, with the page language (from markdown frontmatter) active.
* This allows switching between languages for each translated fragment in the page.
* then, for each language in the frontmatter `trls`, another folder-with-index.html is generated,
* with <trl-selector> added,
* where the language corresponding to the given language is active.
*
* So note that page `trls: []` is independent of the languages of the `<trl-alt>`s in each `<trl-group>`.
*/
export default async (page) => {
const html = await page.html;
return {
"index.html": addTranslationInterface(html, page?.lang),
...handleTranslations(html, page.trls)
}
}
//this is going to create a folder for each 'translation' specified in frontmatter.
function handleTranslations(html, trls) {
if (trls) {
console.log(trls);
const outputs = {};
trls.forEach(trl => {
outputs[trl] = {
"index.html": addTranslationInterface(html, trl)
}
})
return outputs;
} else {
return;
}
}
//"reorders" all `trl-group`s so the element with given lang is displayed.
//EN is default language ...
//also adds a (hidden by css) trl-selector at the top of `body`.
//TODO: add a link to translated pages ...
//that's complicated, because what about all the links in the page?
function addTranslationInterface(body, activelang="en"){
const dom = new JSDOM(body);
const doc = dom.window.document;
let seq = 1; //serial number for identifying translation group inputs and labels
const trlGroups = Array.from(doc.querySelectorAll('trl-group'));
trlGroups.forEach((trlGroup) => {
//for each trlGroup.
const trlAltElems = Array.from(trlGroup.querySelectorAll('trl-alt'));
const langsInGroup = trlAltElems.map(t => t.getAttribute('lang'));
const trlSel = doc.createElement('trl-selector');
langsInGroup.forEach(lang => {
console.log(lang);
let grname = `trlg-${seq}`;
let inputId = `${grname}-${lang}`;
const input = doc.createElement('input');
input.type = 'radio';
input.setAttribute('id', inputId);
input.setAttribute('name', grname);
input.setAttribute('lang', lang);
input.setAttribute('value', lang);
if (lang === activelang) {
input.setAttribute('checked', '');
}
const label = doc.createElement('label');
label.setAttribute('for', inputId);
label.textContent = lang;
trlSel.append(input);
trlSel.append(label);
})
trlGroup.prepend(trlSel);
seq ++; //increment id serial number
})
return dom.serialize();
}