@aurigma/design-atoms
Version:
Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.
63 lines • 2.88 kB
JavaScript
import { InStringPlaceholder } from "@aurigma/design-atoms-model/Product/Items/InStringPlaceholder";
import { VariableItemHelper } from "./VariableItemHelper";
import * as Utils from "@aurigma/design-atoms-model/Utils/Utils";
export class InStringPlaceholderConverter {
convert(textItem) {
const replacedStrings = this._replaceInterpolationStrings(textItem);
if (replacedStrings.isEmpty)
return false;
textItem.originalText = replacedStrings.inStringText;
textItem.text = replacedStrings.inStringText;
const existedPlaceholders = textItem.placeholders;
textItem.placeholders.addRange(existedPlaceholders.concat(replacedStrings.placeholders));
return true;
}
_replaceInterpolationStrings(textItem) {
const variables = VariableItemHelper.getInterpolationVariables(textItem);
const replacedStrings = new ReplacedStrings();
if (Utils.isEmpty(variables))
return replacedStrings;
let inStringText = textItem.text;
for (const variable of variables) {
const id = `[#${variable.name}]`;
const interpolationPlaceholderId = `{{${variable.name}}}`;
inStringText = Utils.isValidXml(textItem.text)
? replaceRichText(inStringText, interpolationPlaceholderId, id)
: replaceText(inStringText, interpolationPlaceholderId, id);
const placeholder = new InStringPlaceholder(id, variable.name, variable.mask, variable.name, variable.values);
replacedStrings.placeholders.push(placeholder);
}
replacedStrings.inStringText = inStringText;
return replacedStrings;
}
}
class ReplacedStrings {
constructor() {
this.placeholders = [];
}
get isEmpty() {
return Utils.isEmpty(this.placeholders);
}
}
function replaceRichText(text, searchValue, replaceValue) {
const parser = new DOMParser();
const xmlDocument = parser.parseFromString(`<body>${text}</body>`, 'text/xml');
const body = xmlDocument.getElementsByTagName('body')[0];
if (!body.textContent.includes(searchValue))
return text;
let currentNode = body;
let foundNode = null;
while (currentNode !== foundNode) {
currentNode = Array.from(currentNode.childNodes).find(childNode => childNode.textContent.includes(searchValue));
if (!currentNode)
return text;
if (Utils.isEmpty(Array.from(currentNode.childNodes)))
foundNode = currentNode;
}
foundNode.textContent = foundNode.textContent.replace(searchValue, replaceValue);
return body.innerHTML;
}
function replaceText(text, searchValue, replaceValue) {
return text.replace(searchValue, replaceValue);
}
//# sourceMappingURL=InStringPlaceholderConverter.js.map