Refactor: init

This commit is contained in:
eight 2017-09-10 23:46:54 +08:00
parent 8c374db353
commit 1c3317202f

View File

@ -1197,47 +1197,61 @@ function beautify(event) {
document.addEventListener('DOMContentLoaded', init); document.addEventListener('DOMContentLoaded', init);
function createEmptyStyle() {
const params = getParams();
const style = {
id: null,
name: '',
enabled: true,
sections: [{code: ''}]
};
for (const i in CssToProperty) {
if (params[i]) {
style.sections[0][CssToProperty[i]] = [params[i]];
}
}
return style;
}
function windowLoaded() {
if (document.readyState !== 'loading') {
return Promise.resolve();
}
return new Promise(resolve => {
window.addEventListener('load', function self() {
window.removeEventListener('load', self);
resolve();
});
});
}
function init() { function init() {
initCodeMirror(); initCodeMirror();
const params = getParams(); const params = getParams();
return Promise.resolve().then(() => {
if (!params.id) { if (!params.id) {
// match should be 2 - one for the whole thing, one for the parentheses // match should be 2 - one for the whole thing, one for the parentheses
// This is an add // This is an add
$('#heading').textContent = t('addStyleTitle'); $('#heading').textContent = t('addStyleTitle');
const section = {code: ''}; return createEmptyStyle();
for (const i in CssToProperty) {
if (params[i]) {
section[CssToProperty[i]] = [params[i]];
} }
}
window.onload = () => {
window.onload = null;
addSection(null, section);
editors[0].setOption('lint', CodeMirror.defaults.lint);
// default to enabled
$('#enabled').checked = true;
initHooks();
};
return;
}
// This is an edit
$('#heading').textContent = t('editStyleHeading'); $('#heading').textContent = t('editStyleHeading');
getStylesSafe({id: params.id}).then(styles => { // This is an edit
return getStylesSafe({id: params.id}).then(styles => {
let style = styles[0]; let style = styles[0];
if (!style) { if (!style) {
style = {id: null, sections: []}; style = createEmptyStyle();
history.replaceState({}, document.title, location.pathname); history.replaceState({}, document.title, location.pathname);
} }
return style;
});
}).then(style => {
styleId = style.id; styleId = style.id;
sessionStorage.justEditedStyleId = styleId; sessionStorage.justEditedStyleId = styleId;
setStyleMeta(style);
window.onload = () => { return windowLoaded().then(() => {
window.onload = null;
initWithStyle({style}); initWithStyle({style});
}; });
if (document.readyState !== 'loading') {
window.onload();
}
}); });
} }