From 7d75dd87541925b738b1eb2bc5a6e1c5b38002ac Mon Sep 17 00:00:00 2001 From: eight Date: Tue, 25 Sep 2018 21:18:39 +0800 Subject: [PATCH] Add: meta-parser --- js/meta-parser.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 js/meta-parser.js diff --git a/js/meta-parser.js b/js/meta-parser.js new file mode 100644 index 00000000..8eaf9c61 --- /dev/null +++ b/js/meta-parser.js @@ -0,0 +1,46 @@ +/* global usercssMeta colorConverter */ +'use strict'; + +// eslint-disable-next-line no-var +var metaParser = (() => { + const parser = usercssMeta.createParser({ + validateVar: { + select: state => { + if (state.value !== null && state.varResult.options.every(o => o.name !== state.value)) { + throw new Error('select value mismatch'); + } + }, + color: state => { + if (state.value !== null) { + colorConverter.format(colorConverter.parse(state.value), 'rgb'); + } + } + } + }); + return {parse, nullifyInvalidVars}; + + function parse(text, indexOffset) { + try { + return parser.parse(text); + } catch (err) { + if (typeof err.index === 'number') { + err.index += indexOffset; + } + throw err; + } + } + + function nullifyInvalidVars(vars) { + for (const va of Object.values(vars)) { + if (va.value === null) { + continue; + } + try { + parser.validateVar(va); + } catch (err) { + va.value = null; + } + } + return vars; + } +})();