Construct DOM via $element instead of HTML string

This commit is contained in:
tophf 2017-04-17 23:25:32 +03:00
parent 3b3ed6543e
commit 1651d52776
4 changed files with 37 additions and 22 deletions

View File

@ -48,6 +48,7 @@ globals:
animateElement: false
$: false
$$: false
$element: false
# prefs.js
prefs: false
setupLivePrefs: false

View File

@ -143,24 +143,29 @@ function importFromString(jsonString) {
stats.codeOnly.names.length +
stats.added.names.length;
Promise.resolve(numChanged && BG.refreshAllTabs()).then(() => {
const listNames = kind => {
const {ids, names} = stats[kind];
return ids
? names.map((name, i) => `<div data-id="${ids[i]}">${name}</div>`)
: names.map(name => `<div>${name}</div>`);
};
const report = Object.keys(stats)
.filter(kind => stats[kind].names.length)
.map(kind =>
`<details data-id="${kind}">
<summary><b>${stats[kind].names.length} ${t(stats[kind].legend)}</b></summary>
<small>${listNames(kind).join('')}</small>
</details>`)
.join('');
.map(kind => {
const {ids, names, legend} = stats[kind];
const listItemsWithId = (name, i) =>
$element({dataset: {id: ids[i]}, textContent: name});
const listItems = name =>
$element({textContent: name});
const block =
$element({tag: 'details', dataset: {id: kind}, appendChild: [
$element({tag: 'summary', appendChild:
$element({tag: 'b', textContent: names.length + ' ' + t(legend)})
}),
$element({tag: 'small', appendChild:
names.map(ids ? listItemsWithId : listItems)
}),
]});
return block;
});
scrollTo(0, 0);
messageBox({
title: t('importReportTitle'),
contents: report || t('importReportUnchanged'),
contents: report.length ? report : t('importReportUnchanged'),
buttons: [t('confirmOK'), numChanged && t('undo')],
onshow: bindClick,
}).then(({button, enter, esc}) => {

18
dom.js
View File

@ -79,3 +79,21 @@ function $(selector, base = document) {
function $$(selector, base = document) {
return [...base.querySelectorAll(selector)];
}
function $element(opt) {
// tag: string, default 'div'
// appendChild: element or an array of elements
// dataset: object
// any DOM property: assigned as is
const element = document.createElement(opt.tag || 'div');
(opt.appendChild instanceof Array ? opt.appendChild : [opt.appendChild])
.forEach(child => child && element.appendChild(child));
delete opt.appendChild;
delete opt.tag;
if (opt.dataset) {
Object.assign(element.dataset, opt.dataset);
delete opt.dataset;
}
return Object.assign(element, opt);
}

View File

@ -89,13 +89,4 @@ function messageBox({
messageBox.element = null;
messageBox.resolve = null;
}
function $element(opt) {
const element = document.createElement(opt.tag || 'div');
(opt.appendChild instanceof Array ? opt.appendChild : [opt.appendChild])
.forEach(child => child && element.appendChild(child));
delete opt.appendChild;
delete opt.tag;
return Object.assign(element, opt);
}
}