From 5a9f78e2ac92732b69f5a10a7adabf3e83266b66 Mon Sep 17 00:00:00 2001 From: eight Date: Sat, 4 Nov 2017 08:38:17 +0800 Subject: [PATCH] Add: key:label syntax in var select --- js/usercss.js | 41 ++++++++++++++++++++++++++++++----------- manage/config-dialog.js | 2 +- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/js/usercss.js b/js/usercss.js index fec3180c..cc4361a6 100644 --- a/js/usercss.js +++ b/js/usercss.js @@ -160,17 +160,13 @@ var usercss = (() => { } else if (state.type === 'select' || (state.type === 'image' && state.key === 'var')) { parseJSONValue(state); if (Array.isArray(state.value)) { - result.options = state.value.map(text => ({ - label: text, - value: text - })); + result.options = state.value.map(text => createOption(text)); } else { - result.options = Object.keys(state.value).map(k => ({ - label: k, - value: state.value[k] - })); + result.options = Object.keys(state.value).map(k => + createOption(k, state.value[k]) + ); } - result.default = result.options[0].value; + result.default = result.options[0].name; } else if (state.type === 'dropdown' || state.type === 'image') { if (state.text[state.re.lastIndex] !== '{') { throw new Error('no open {'); @@ -206,6 +202,21 @@ var usercss = (() => { state.usercssData.vars[result.name] = result; } + function createOption(label, value) { + let name; + const match = label.match(/^(\w+):(.*)/); + if (match) { + ([, name, label] = match); + } + if (!name) { + name = label; + } + if (!value) { + value = name; + } + return {name, label, value}; + } + function parseEOT(state) { const match = state.text.slice(state.re.lastIndex).match(/^<< { const va = vars[key]; output[key] = Object.assign({}, va, { value: va.value === null || va.value === undefined ? - va.default : va.value, + getVarValue(va, 'default') : getVarValue(va, 'value') }); return output; }, {}); } + function getVarValue(va, prop) { + if (va.type === 'select' || va.type === 'dropdown' || va.type === 'image') { + // TODO: handle customized image + return va.options.find(o => o.name === va[prop]).value; + } + return va[prop]; + } + function validate(style) { const {usercssData: data} = style; // mandatory fields @@ -473,7 +492,7 @@ var usercss = (() => { function validVar(va, value = 'default') { if (va.type === 'select' || va.type === 'dropdown') { - if (va.options.every(o => o.value !== va[value])) { + if (va.options.every(o => o.name !== va[value])) { throw new Error(chrome.i18n.getMessage('styleMetaErrorSelectValueMismatch')); } } else if (va.type === 'checkbox' && !/^[01]$/.test(va[value])) { diff --git a/manage/config-dialog.js b/manage/config-dialog.js index 1da16812..d5b64f3f 100644 --- a/manage/config-dialog.js +++ b/manage/config-dialog.js @@ -79,7 +79,7 @@ function configDialog(style) { va.input = $element({ tag: 'select', appendChild: va.options.map(o => $element({ - tag: 'option', value: o.value, textContent: o.label + tag: 'option', value: o.name, textContent: o.label })) }); va.input.onchange = () => {