attranslate
Version:
Text Translator for Websites and Apps
67 lines (66 loc) • 2.14 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestedJson = void 0;
const flatten_1 = require("../../util/flatten");
const managed_json_1 = require("../common/managed-json");
const format_cache_1 = require("../common/format-cache");
const jsonCache = new format_cache_1.FormatCache();
class NestedJson {
readTFile(args) {
const tMap = new Map();
const json = (0, managed_json_1.readManagedJson)(args.path);
traverseJson("", json, (entry) => {
tMap.set(entry[0], entry[1]);
return null;
});
jsonCache.insertFileCache({
path: args.path,
entries: new Map(),
auxData: json,
});
return Promise.resolve(tMap);
}
writeTFile(args) {
const sourceJson = jsonCache.getOldestAuxdata();
let json;
if (sourceJson) {
json = sourceJson;
replaceTranslatableProperties(args, json);
}
else {
json = constructNestedJsonFromFlatMap(args);
}
(0, managed_json_1.writeManagedJson)({ path: args.path, object: json });
jsonCache.purge();
}
}
exports.NestedJson = NestedJson;
function traverseJson(path, node, operation) {
for (const key of Object.keys(node)) {
const value = node[key];
const newPath = path ? path + "." + key : key;
if (typeof value === "string") {
const newValue = operation([newPath, value]);
if (newValue) {
node[key] = newValue;
}
}
else if (value && typeof value === "object") {
traverseJson(newPath, value, operation);
}
}
}
function replaceTranslatableProperties(args, json) {
traverseJson("", json, (entry) => {
var _a;
const path = entry[0];
return (_a = args.tSet.get(path)) !== null && _a !== void 0 ? _a : null;
});
}
function constructNestedJsonFromFlatMap(args) {
const flatJson = {};
args.tSet.forEach((value, key) => {
flatJson[key] = value;
});
return (0, flatten_1.unflatten)(flatJson);
}