UNPKG

@awesome-fe/translate

Version:
101 lines 3.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Injector = void 0; const fs_1 = require("fs"); const dom_models_1 = require("../dom/parse5/dom-models"); class Injector { styleUrls; scriptUrls; urlMap; textMap; constructor(styleUrls, scriptUrls, urlMap, textMap) { this.styleUrls = styleUrls; this.scriptUrls = scriptUrls; this.urlMap = urlMap; this.textMap = textMap; } injectFile(filename) { const content = (0, fs_1.readFileSync)(filename, 'utf8'); const result = this.inject(content); (0, fs_1.writeFileSync)(filename, result, 'utf8'); } inject(content) { const doc = dom_models_1.DomDocument.parse(content); // 对于文档片段,不需要注入 if (doc.isFragment()) { return content; } this.injectTranslationKitToDoc(doc); return replaceText(doc.toHtml(), this.textMap); } injectTranslationKitToDoc(doc) { this.injectTranslators(doc); this.replaceResourceUrls(doc); } injectTranslators(doc) { this.styleUrls.forEach(styleUrl => { if (styleSheetExists(styleSheetsOf(doc), styleUrl)) { return; } const link = new dom_models_1.DomElement('link', [{ name: 'href', value: styleUrl }, { name: 'rel', value: 'stylesheet' }]); doc.head.appendChild(link); }); this.scriptUrls.forEach(scriptUrl => { if (scriptExists(scriptsOf(doc), scriptUrl)) { return; } const script = new dom_models_1.DomElement('script', [{ name: 'src', value: scriptUrl }]); doc.body.appendChild(script); }); } replaceResourceUrls(doc) { styleSheetsOf(doc).forEach(styleSheet => { const newValue = this.urlMap[styleSheet.getAttribute('href')]; if (newValue) { styleSheet.setAttribute('href', newValue); } }); scriptsOf(doc).forEach(script => { const newValue = this.urlMap[script.getAttribute('src')]; if (newValue) { script.setAttribute('src', newValue); } }); doc.querySelectorAll(it => it.isTagOf('img') && it.hasAttribute('src')).forEach(image => { const newValue = this.urlMap[image.getAttribute('src')]; if (newValue) { image.setAttribute('src', newValue); } }); } } exports.Injector = Injector; function replaceText(text, textMap) { Object.entries(textMap).forEach(([key, value]) => { text = text.replace(new RegExp(key, 'gi'), value); }); return text; } function styleSheetExists(styleSheets, styleSheetUrl) { for (let i = 0; i < styleSheets.length; ++i) { if (styleSheets[i].getAttribute('href') === styleSheetUrl) { return true; } } return false; } function scriptExists(scripts, scriptUrl) { for (let i = 0; i < scripts.length; ++i) { if (scripts[i].getAttribute('src') === scriptUrl) { return true; } } return false; } function styleSheetsOf(doc) { return doc.querySelectorAll(it => it.isTagOf('link') && it.getAttribute('rel') === 'stylesheet'); } function scriptsOf(doc) { return doc.querySelectorAll(it => it.isTagOf('script') && it.hasAttribute('src')); } //# sourceMappingURL=injector.js.map