diff --git a/build/addons.all.js b/build/addons.all.js index 6e32649..97cc08e 100755 --- a/build/addons.all.js +++ b/build/addons.all.js @@ -1,3 +1,250 @@ + +//;(()=>{ + +var installReceiver = function() { + + let keys = new Set([ + /* Hex is a freebie, under the special term `#` hash: #000000 */ + // 'hex', + /* Color property is slightly more complicated, with the first param + as a forced string. */ + // 'color', + + /* Available types, each act the same way: rgb-[3 values][/A] + If the key is a mismatch, its ignored. */ + 'rgb', + 'hsl', + 'hwb', + 'lab', + 'lch', + 'oklab', + 'oklch', + ]) + + ClassGraph.addons.extendedColorValues = function(cg){ + let func = function(prop, values) { + return forwardHotWordReduce(prop, values, keys) + } + cg.reducers.push(func) + } +} + + +/* Return a boolean if the detected type is a valid css value of type: + + Number: 0 | 0.0 + Percent: 0% + Opacity: 0/0 + Angle: 0turn | 0rad +*/ +const isNumOrPerc = function(value) { + return isNumber(value) || isPercent(value) || isOpacityNum(value) || isAngle(value) +} + +/* Return boolean for the match of a css value with an alpha: 0/0 */ +const isOpacityNum = function(value) { + // '60%/0.8' + let spl = value.split('/') + if(spl.length == 2) { + return isNumOrPerc(spl[0]) && isNumber(spl[1]) + } + return false +} + +const isAngle = function(value) { + let types = new Set(["deg","grad","rad","turn"]); + let extra = value.slice(parseFloat(value).toString().length, value.length) + return types.has(extra) +} + + +const isPercent = function(value) { + return value.endsWith('%') && isNumber(value.slice(0, value.length-1)) +} + + +const isNumber = function(value) { + if(value == undefined || value.length == 0){ return false }; + let isNum = !isNaN(Number(value)) + return isNum +} + + +const asThreeBitColor = function(values) { + let ex = values.slice(4, 5) + let alp = '' + if(ex.length>0) { + alp = `/${ex}` + } + return `${values[0]}(${values.slice(1, 4).join(' ')}${alp})` +} + + +/* Perform a _hot word_ detection on the values recursively. A _hot word_ may be any key. + + forwardHotWordReduce( + ['color'] + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + ) + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail. + +This method then performs this after every release, concatenating changed and +unchanged into a response list. + + rgb-200-200-200-foo + + rgb(200 200 200) foo + + */ +const forwardHotWordReduce = function(props, values, keys, keyTestFunc=undefined) { + /* + Key pops early, and can accept a variable amount of vars. + */ + + let len = values.length + , position = 0 + , max = values.length + 1 + , count = 0 + , response = [] + ; + + while(position < len && count < max) { + let sliced = values.slice(position) + let [key, usedCount] = hotWordReduce(sliced, keys, true, keyTestFunc) + + position += usedCount + count += 1 + if(Array.isArray(key)) { + response = response.concat(key) + } else { + response.push(key) + } + } + + return response +} + +/* Perform a _hot word_ detection on the values. A _hot word_ may be any key. + + forwardHotWordReduce( + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + , true + ) + + rgb(200 200 200) // break early + rgb(200 200 200) egg + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail if `breakEarly` is true. + + rgb-200-200-200-foo-hsl-20-0%-10-foo + + rgb(200 200 200) foo hsl(20 0% 10) foo + + */ + +const hotWordReduce = function(values, keys + , breakEarly=false + , callback=asThreeBitColor + , keyTestFunc=undefined) { + + var i = 0; + let inSet = (x) => keys.has(x) + , keyStartMatch = keyTestFunc != undefined? keyTestFunc: inSet + , l = values.length + , bits = [] + , kept = [] + , lost = [] + , max = 4 // can be 3 or 4 + ; + + for (;i < l; i++) { + // console.log('---') + let k = values[i]; + let inI = i; + if(keyStartMatch(k)) { + // console.log(i, 'MATCH', k) + let j = i+1 + kept = [k] + lost = [] + let ok = true + while(ok && j < l) { + let subI = j; + let subK = values[subI]; + let isNum = isNumOrPerc(subK) + ok = isNum && j < l && kept.length <= (max-1) // +1 for the original key + if(isNum) { + // console.log('Push', subK) + j += 1 + kept.push(subK) + ok = ok && kept.length <= max // +1 for the original key + } else { + // Lost stack + // console.log('Lost stack on', subK) + // j = 1 + lost.push(subK) + } + // console.log('S', subI, subK, isNum, ok) + } + + let [a,b] = [inI, j] + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept) + if(plucked.length < 3) { + // console.log('Failed.', bits) + bits = bits.concat(kept) + if(breakEarly) { + return [bits, j] + } + } else { + // console.log('kept', kept, newEntry) + // console.log('plucked', plucked) + bits.push(newEntry) + // Push back 2, as we landed on the bad node, + // and we need step into this node, to stack it. + // + i = j-1 + } + } else { + // console.log(i, k) + bits.push(k) + + if(breakEarly) { + let [a,b] = [inI, kept.length] + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept) + // console.log('plucked', plucked) + // console.log('kept', kept) + if(kept.length < 3) { + // console.log('Failed.', 'kept', kept, 'plucked', plucked) + return [values[b], kept.length+1] + } else { + // console.log('success.') + return [newEntry, kept.length] + } + + return [values[0], 1] + } + } + } + + // console.log('Done pop', i) + // console.log('in', values, 'out', bits) + + let newEntry = callback(kept) + return [newEntry, i+1] +} + + +;installReceiver(); + +// })() /** * # Events event-[eventName]-[action]-[params]* * @@ -150,6 +397,8 @@ cg = _cg; cg.insertReceiver(['font', 'pack'], fontPackReceiver) } + ClassGraph.prototype.generateGoogleLinks = generateGoogleLinks + ClassGraph.prototype.installGoogleLinks = installGoogleLinks } /** @@ -172,15 +421,18 @@ let familyStrings = createFamilyString(values, fonts, origin) // let families = tokenize(values) - - // install as header items - // console.info('Installing Google fonts: familyStrings:', familyStrings) - generateGoogleLinks(familyStrings).forEach((x)=>document.head.appendChild(x)) + installGoogleLinks(familyStrings) // Install additional css additions installFontObjects(fonts, obj) } + const installGoogleLinks = function(familyStrings, display) { + // install as header items + // console.info('Installing Google fonts: familyStrings:', familyStrings) + return generateGoogleLinks(familyStrings, display).forEach((x)=>document.head.appendChild(x)) + } + const installFontObjects = function(fonts, splitObj) { // // For value create a font-family; @@ -544,7 +796,7 @@ }) } - const generateGoogleLinks = function(familyStrings){ + const generateGoogleLinks = function(familyStrings, display='swap'){ let a = getOrCreateLink('link', 'preconnect', { href: "https://fonts.googleapis.com" @@ -555,8 +807,10 @@ , crossorigin: '' }) + let ds = display == null? '': `&display=${display}` + let c = getOrCreateLink('link', "stylesheet", { - href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + href:`https://fonts.googleapis.com/css2?${familyStrings}${ds}` }) return [a,b,c] @@ -564,6 +818,18 @@ let linkCache = {} + /* + Create a link node + + let b = getOrCreateLink('link', 'preconnect', { + href: "https://fonts.gstatic.com" + , crossorigin: '' + }) + + let c = getOrCreateLink('link', "stylesheet", { + href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + }) + */ const getOrCreateLink = function(href, rel, opts) { let v = { rel, href @@ -600,6 +866,365 @@ })() +;(function(){ + + let cg; + let rootDeclaration = {}; + let definition = undefined + let rootRule; + + const insertReceiver = function(){ + + ClassGraph.addons.functionsReceiver = function(_cg){ + cg = _cg; + cg.keyValueFunctions.set('forceGreen', forceHook) + cg.keyValueFunctions.set('force', forceHook) + cg.keyValueFunctions.set('raise', raiseHook) + } + } + + const forceHook = function(value, token, index, splitObj) { + // console.log('Force green hook', token, splitObj) + let res = token.value.slice(0, token.match.start) + // console.log(res) + // return res + + return token.args.length > 0? token.args[0]: 'green' + } + + const raiseHook = function(value, token, index, splitObj) { + console.log('raise hook', token, splitObj) + let res = token.value.slice(0, token.match.start) + console.log(res) + // return res + } + + const functionsHook = function(d) { + + // target = document.querySelector(target) + console.log('functions', d) + } + + + ;insertReceiver(); +})() + +class PolyclassIcons { + +} + +;(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver) + // cg.insertReceiver(['icon'], iconReceiver) + } + } + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + + let key = titleCase(obj.values).join('+') + let family = `Material+Symbols+${key}` + let defaultFontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + } + let familyString = toGoogleFontParamsStr(opts) + let fontStr = `family=${family}:${familyString}` + + let receiverBits = [...obj.values, 'icon'] + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver) + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null) + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings) + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + } + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0] + let rules = {} + + let fontSettingsStr = toObjectParamStr(fontSettings) + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + } + + rules[`.material-symbols-${key}`] = conf + let items = cg.dcss.addStylesheetRules(rules) + + items.renderAll() + } + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj) + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i] + let v = obj[k] + let last = i == fKeys.length-1 + let end = last? '': ',\n' + fontSettingsStr += `'${k}' ${v}${end}` + } + return fontSettingsStr + + } + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(',') + let v = Object.values(obj).join(',') + return `${k}@${v}` + } + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + const values = obj.values, origin = obj.origin; + console.log('render icon', obj) + + return contentInjection(obj) + } + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)) + origin.innerText += `${values.join('_')}` + } + + const getInjectClass = function(obj) { + let k = obj.props[0] + return `material-symbols-${k}` + } + + ;insertReceiver(); +})() + +;(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver) + // cg.insertReceiver(['icon'], iconReceiver) + } + } + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + console.log('Install the font', obj) + let key = titleCase(obj.values).join('+') + let family = `Material+Symbols+${key}` + let fontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + } + let familyString = toGoogleFontParamsStr(opts) + let fontStr = `family=${family}:${familyString}` + + let receiverBits = [...obj.values, 'icon'] + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver) + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null) + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings) + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + } + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0] + let rules = {} + + let fontSettingsStr = toObjectParamStr(fontSettings) + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + } + + rules[`.material-symbols-${key}`] = conf + let items = cg.dcss.addStylesheetRules(rules) + + items.renderAll() + } + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj) + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i] + let v = obj[k] + let last = i == fKeys.length-1 + let end = last? '': ',\n' + fontSettingsStr += `'${k}' ${v}${end}` + } + return fontSettingsStr + + } + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(',') + let v = Object.values(obj).join(',') + return `${k}@${v}` + } + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + const values = obj.values, origin = obj.origin; + console.log('render icon', obj) + + return contentInjection(obj) + } + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)) + origin.innerText += `${values.join('_')}` + } + + const getInjectClass = function(obj) { + let k = obj.props[0] + return `material-symbols-${k}` + } + + ;insertReceiver(); +})() + /** * # Monitor * @@ -705,274 +1330,34 @@ const difference = function(setA, setB) { })() /* +Convert discovered nodes and bind them to a selector. The assigned classes +are the declarations assigned to the css class. -vars box. To assign key variables as accessible CSS varialbes through a js -definition. The definition is bound to DCSS, so edits to the vars manipulates -the view automatically. +The discovery may descend children, allowing for depth setup. - vars({ - primary: "#880000" # company red - , secondary: "#111" # dark - , accent: "red" - }) + -In the node, we access the vars reciever + + -
-

An elk called Elk lives here.

-
- -Manipulating the var propagates to the view: - - vars.primary = "#EEE" # off white - ---- - -## Secondary App - - `swatch()` - and colors.js - - Assign "colors" to a swatch of colors, each color is a function from the - colors.js module and can assign math relations to swatches. - Chaning a swatch (such as its base color), can manipulate the other - colours according to the chosen swatch type, e.g. "Diachromic". - - */ - -;(function(){ - - let cg; - let rootDeclaration = {}; - let definition = undefined - let rootRule; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varsReceiver = function(_cg){ - cg = _cg; - cg.vars = varsHook.bind(cg) - // cg.varsRootDelaration = rootDeclaration - cg.varsRoot = rootRule - // cg.insertTranslator('var', variableDigest) - } - } - - - const varsHook = function(d, target=':root') { - /** vars() function bound to the classgraph. _this_ is the classgraph - instance `cg.vars = varsHook.bind(cg)` - - each key is a var, value is the param - - { - apples: green - , foo: 10 - , bar: 1em - , baz: #444 - } - - Each var is installed on the target node: - - :root { - --apples: green - ... - --baz: #444 - } - - if an existing "vars" object exists, it's updated. - - */ - // target = document.querySelector(target) - console.log('Hook', d) - - if(rootRule == undefined) { - let rootDeclaration = {}; - - for(let key in d) { - let prop = `--${key}` - let value = d[key] - rootDeclaration[prop] = value; - } - - let rules = cg.dcss.addStylesheetRules({ - [target]: rootDeclaration - }); - - rules.renderAll() - rootRule = rules[0] - cg.varsRoot = rootRule - } else { - - // rootRule - // let pr = rootRule.getPropStr([target,Object.entries(definition)]) - // rootRule.sheetRule.cssText = `${target} { ${pr} }` - // rootRule.replace(`${target} { ${pr} }`) - - for(let key in d) { - let prop = `--${key}` - let value = d[key] - rootRule.sheetRule.style.setProperty(prop, value) - } - // rootRule.render() - // console.log(rootRule) - // window.varsRule = rootRule - } - } - - ;insertReceiver(); -})() - -/** - * # var-* Translate - * - * https://developer.mozilla.org/en-US/docs/Web/CSS/var - * - * Discover and rewrite class names values with `var-*` to the CSS function - * `var(*)`. e.g. - * - * "border-top-var-primary-edges" - * - * { - * "border-top": var(--primary-edges) - * } - */ -;(function(){ - - let cg; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // console.log('var-translate insertReceiver') - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varTranslateReceiver = function(_cg){ - cg = _cg; - cg.insertTranslator('var', variableDigest2) - // cg.insertTranslator('var', variableDigest) - } - } - - /** - * The handler function given to the dynamic css stylesheet, called - * when the dcss is prepared. - * - * @param {object} obj A definition generated by the class graph discovery - * @return {undefined} - */ - const variableDigest = function(splitObj, index) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ - - /* - This is pretty dumb, and should improve to a forward stepping - solution, detecting possible names - - Issue is a var can be anything `var(--1em)`. - Therefore forward feed on _possibles_ is sticky. This is valid: - - { - margin: var(--1em) var(--orange) - } - - Therefore break on `var` - - "margin-var-1em-var-orange" - - However `var(--var)` is valid: - { - --var: 1em - --var-orange: orange; - } - - - Meaning: - "margin-var-1em-var-var-orange" - - Therefore break on var, unless [var]+1 == var, - as then its break on var, dont break on next var, - yielding `var-orange`.` - - However also allowed: "margin-var-1em-var-var-var" - - { - --var-var: - } - - So then possibly, two dashes between `var var`` - - margin-var-key--var-var-var-var--var-var-key - - { - margin: var(key) var(var-var-var) var(var-key) - } - - Allowing the strange but valid: - { - --var-key: 1em; - --var-var-var-var: 2em; - --var-var-key: 1em solid; - } - - */ - // console.log('running on', splitObj) - // Tokenize as a family string. - values = splitObj.values - let keys = splitObj.values.slice(index) - let k1 = keys.slice(1) - let word = `var(--${k1.join("-")})` - // console.log(keys, word) - return word - // [inStack, outStack, currentIndex] = - // digestFunc(splitObj, inStack, outStack, currentIndex) - } - - - const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ - - let keys = inStack.slice(currentIndex) - let k1 = keys.slice(1) - let word = `var(--${k1.join("-")})` - - outStack.push(word) - // return [inStack, outStack, currentIndex] - return [[], outStack, currentIndex + k1.length] - } +
- - ;insertReceiver(); -})() - +Notably this may be easier as real CSS. + */ /* The words map lists all the unique string CSS values. Each word maps to an @@ -1053,10 +1438,10 @@ class Words extends Map { wordsToArrayString(indent=0, small=false){ if(!small) { - return JSON.stringify(wordsToOrderedArray(), null, indent) + return JSON.stringify(this.wordsToOrderedArray(), null, indent) } - return wordsToOrderedArray().join(' ') + return this.wordsToOrderedArray().join(' ') } wordsToObjectString(indent=0, small=false) { @@ -1096,10 +1481,79 @@ class Words extends Map { } } +/* +1. all the items have string in position +2. the we create the flat array list +each position is a word from the string list + + "all-petite-caps", + "all-scroll", + "all-small-caps", + +as a string: + + " all petite caps scroll small ..." + +Becomes: + [1, [ + [2, [ + [3, null] + ] + ], + [4, null], + [5, [ + [3,null] + ] + ] + ] + ] -const words = new Words() - , microGraph = {} - , dashprops = [ +--- + +When loaded, we can re-ask for the prop: + + w.stringToBits("all-petite-caps") + [1,2,3] + +The last key + + w.stringToBits("zoom") + [211] + w.stringToBits("zoom-out") + [211, 66] +--- + + + "all-petite-caps", + "all-scroll", + "all-small-caps", + "allow-end", + "alternate-reverse", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2", + "0-3", + "0-4-5", + "6-7", + "8-9", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2 0-3 0-4-5 6-7 8-9" + + "all petite caps scroll small allow end alternate reverse", + "0 1 2,0 3,0 4 5,6 7,8 9" + + // radix each key through 32 bits, allowing ~1000 positions as 2bits + // not really helpful under 100 keys, but then saves 1 char per position (up to 1k) + // .. With 255~ keys thats 150~ chars saved. + // In a 32bit radix, the first 31 positions are single chars. +--- + +*/ + +const words = new Words() + , microGraph = {} + , dashprops = [ "all-petite-caps", "all-scroll", "all-small-caps", @@ -1302,61 +1756,17 @@ const words = new Words() var installReceiver = function() { - ClassGraph.addons.forwardReduceValues = (cg) => words.installPropArray(dashprops) - ClassGraph.prototype.forwardReduceValues = forwardReduceValues - ClassGraph.prototype.valuesGraph = { microGraph, words } -} - - -const arrayStringMunger = function(str) { - /* given the string, crush it futher.*/ - let dmap = { - // '[': { active: false, current: 0, max: -1} - // , ']': { active: false, current: 0, max: -1} - } - - let actives = []; - - for(let c of str) { - if(dmap[c] == undefined) { - // new position - dmap[c] = { active: false, current: -1, max: -1, total: 0} + ClassGraph.addons.forwardReduceValues = function(cg){ + let func = function(prop, values) { + return forwardReduceValues(prop, values, microGraph, words) } - - if(dmap[c].active) { - // was active. just append and continue. - dmap[c].current += 1; - } else { - // Close any alive, finalise the max. - // for(let k in dmap) { - // if(k == c) { - // // The same object doesn't turn off. - // continue - // } - // dmap[k].active = false - // dmap[k].max = Math.max(dmap[k].max, dmap[k].current) - // // We set current to 0 here (not -1), - // dmap[k].current = 0 - // } - let cStash = dmap[c].current - for(let o of actives) { - o.active = false - o.max = Math.max(o.max, o.current) - o.current = 0 - } - - actives = [dmap[c]] - dmap[c].active = true - dmap[c].total += 1 - dmap[c].current = cStash + 1; - } - } - for(let o of actives) { - o.active = false - o.max = Math.max(o.max, o.current) - o.current = 0 + cg.reducers.push(func) + let res = words.installPropArray(dashprops) + return res; } - return dmap + // install one of many + // ClassGraph.prototype.forwardReduceValues = forwardReduceValues + ClassGraph.prototype.valuesGraph = { microGraph, words } } @@ -1385,9 +1795,6 @@ const forwardReduceValues = function(props, values, microGraph, translations) { 'row': { 'reverse': merge } - , 'other': { - 'horse': merge - } } let len = values.length @@ -1447,3 +1854,272 @@ const popOneValueForward = function(values, microGraph, translations) { ;installReceiver(); })() +/** + * # var-* Translate + * + * https://developer.mozilla.org/en-US/docs/Web/CSS/var + * + * Discover and rewrite class names values with `var-*` to the CSS function + * `var(*)`. e.g. + * + * "border-top-var-primary-edges" + * + * { + * "border-top": var(--primary-edges) + * } + */ +;(function(){ + + let cg; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // console.log('var-translate insertReceiver') + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varTranslateReceiver = function(_cg){ + cg = _cg; + cg.insertTranslator('var', variableDigest2) + // cg.insertTranslator('var', variableDigest) + } + } + + /** + * The handler function given to the dynamic css stylesheet, called + * when the dcss is prepared. + * + * @param {object} obj A definition generated by the class graph discovery + * @return {undefined} + */ + const variableDigest = function(splitObj, index) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + /* + This is pretty dumb, and should improve to a forward stepping + solution, detecting possible names + + Issue is a var can be anything `var(--1em)`. + Therefore forward feed on _possibles_ is sticky. This is valid: + + { + margin: var(--1em) var(--orange) + } + + Therefore break on `var` + + "margin-var-1em-var-orange" + + However `var(--var)` is valid: + { + --var: 1em + --var-orange: orange; + } + + + Meaning: + "margin-var-1em-var-var-orange" + + Therefore break on var, unless [var]+1 == var, + as then its break on var, dont break on next var, + yielding `var-orange`.` + + However also allowed: "margin-var-1em-var-var-var" + + { + --var-var: + } + + So then possibly, two dashes between `var var`` + + margin-var-key--var-var-var-var--var-var-key + + { + margin: var(key) var(var-var-var) var(var-key) + } + + Allowing the strange but valid: + { + --var-key: 1em; + --var-var-var-var: 2em; + --var-var-key: 1em solid; + } + + */ + // console.log('running on', splitObj) + // Tokenize as a family string. + values = splitObj.values + let keys = splitObj.values.slice(index) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + // console.log(keys, word) + return word + // [inStack, outStack, currentIndex] = + // digestFunc(splitObj, inStack, outStack, currentIndex) + } + + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + + + ;insertReceiver(); +})() + +/* + +vars box. To assign key variables as accessible CSS varialbes through a js +definition. The definition is bound to DCSS, so edits to the vars manipulates +the view automatically. + + vars({ + primary: "#880000" # company red + , secondary: "#111" # dark + , accent: "red" + }) + +In the node, we access the vars reciever + +
+

An elk called Elk lives here.

+
+ +Manipulating the var propagates to the view: + + vars.primary = "#EEE" # off white + +--- + +## Secondary App + + `swatch()` + and colors.js + + Assign "colors" to a swatch of colors, each color is a function from the + colors.js module and can assign math relations to swatches. + Chaning a swatch (such as its base color), can manipulate the other + colours according to the chosen swatch type, e.g. "Diachromic". + + */ + +;(function(){ + + let cg; + let rootDeclaration = {}; + let definition = undefined + let rootRule; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varsReceiver = function(_cg){ + cg = _cg; + cg.vars = varsHook.bind(cg) + // cg.varsRootDelaration = rootDeclaration + cg.varsRoot = rootRule + // cg.insertTranslator('var', variableDigest) + } + } + + + const varsHook = function(d, target=':root') { + /** vars() function bound to the classgraph. _this_ is the classgraph + instance `cg.vars = varsHook.bind(cg)` + + each key is a var, value is the param + + { + apples: green + , foo: 10 + , bar: 1em + , baz: #444 + } + + Each var is installed on the target node: + + :root { + --apples: green + ... + --baz: #444 + } + + if an existing "vars" object exists, it's updated. + + */ + // target = document.querySelector(target) + console.log('Hook', d) + + if(rootRule == undefined) { + let rootDeclaration = {}; + + for(let key in d) { + let prop = `--${key}` + let value = d[key] + rootDeclaration[prop] = value; + } + + let rules = cg.dcss.addStylesheetRules({ + [target]: rootDeclaration + }); + + rules.renderAll() + rootRule = rules[0] + cg.varsRoot = rootRule + } else { + + // rootRule + // let pr = rootRule.getPropStr([target,Object.entries(definition)]) + // rootRule.sheetRule.cssText = `${target} { ${pr} }` + // rootRule.replace(`${target} { ${pr} }`) + + for(let key in d) { + let prop = `--${key}` + let value = d[key] + rootRule.sheetRule.style.setProperty(prop, value) + } + // rootRule.render() + // console.log(rootRule) + // window.varsRule = rootRule + } + } + + ;insertReceiver(); +})() + diff --git a/build/polyclass.browser-core.js b/build/polyclass.browser-core.js index fcfae0a..b1bffe6 100755 --- a/build/polyclass.browser-core.js +++ b/build/polyclass.browser-core.js @@ -233,17 +233,17 @@ console.log(blendedcolor, blendedcolor2) })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -449,10 +449,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0 + let c = 0 for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -633,6 +633,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {} + this.announce('wake') /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -641,7 +642,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, } - + this.reducers = [] if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()) } @@ -651,8 +652,38 @@ class ClassGraph { this.aliasMap = {} this.parentSelector = conf?.parentSelector this.processAliases(this.conf?.aliases) + this.announce('ready') + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }) + dispatchEvent(e) } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func } @@ -925,8 +956,8 @@ class ClassGraph { values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ) let r = { @@ -941,7 +972,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues)//, graph, words) + loopValues = r + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -1724,12 +1761,13 @@ class ClassGraph { // } +/* DOM Loader -/* - Upon document load, process and *[polyclass] entity. Similar to process() +Upon document load, process and *[polyclass] entity. Similar to process() + + */ const autoActivator = function(watch=document){ - watch.addEventListener('DOMContentLoaded', function(){ onDomLoaded() }.bind(this)) diff --git a/build/polyclass.browser-full.js b/build/polyclass.browser-full.js index 58276a6..f77976c 100755 --- a/build/polyclass.browser-full.js +++ b/build/polyclass.browser-full.js @@ -233,17 +233,17 @@ console.log(blendedcolor, blendedcolor2) })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -449,10 +449,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0 + let c = 0 for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -633,6 +633,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {} + this.announce('wake') /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -641,7 +642,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, } - + this.reducers = [] if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()) } @@ -651,8 +652,38 @@ class ClassGraph { this.aliasMap = {} this.parentSelector = conf?.parentSelector this.processAliases(this.conf?.aliases) + this.announce('ready') + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }) + dispatchEvent(e) } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func } @@ -925,8 +956,8 @@ class ClassGraph { values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ) let r = { @@ -941,7 +972,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues)//, graph, words) + loopValues = r + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -1724,12 +1761,13 @@ class ClassGraph { // } +/* DOM Loader -/* - Upon document load, process and *[polyclass] entity. Similar to process() +Upon document load, process and *[polyclass] entity. Similar to process() + + */ const autoActivator = function(watch=document){ - watch.addEventListener('DOMContentLoaded', function(){ onDomLoaded() }.bind(this)) @@ -2050,6 +2088,253 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy) // })(); + +//;(()=>{ + +var installReceiver = function() { + + let keys = new Set([ + /* Hex is a freebie, under the special term `#` hash: #000000 */ + // 'hex', + /* Color property is slightly more complicated, with the first param + as a forced string. */ + // 'color', + + /* Available types, each act the same way: rgb-[3 values][/A] + If the key is a mismatch, its ignored. */ + 'rgb', + 'hsl', + 'hwb', + 'lab', + 'lch', + 'oklab', + 'oklch', + ]) + + ClassGraph.addons.extendedColorValues = function(cg){ + let func = function(prop, values) { + return forwardHotWordReduce(prop, values, keys) + } + cg.reducers.push(func) + } +} + + +/* Return a boolean if the detected type is a valid css value of type: + + Number: 0 | 0.0 + Percent: 0% + Opacity: 0/0 + Angle: 0turn | 0rad +*/ +const isNumOrPerc = function(value) { + return isNumber(value) || isPercent(value) || isOpacityNum(value) || isAngle(value) +} + +/* Return boolean for the match of a css value with an alpha: 0/0 */ +const isOpacityNum = function(value) { + // '60%/0.8' + let spl = value.split('/') + if(spl.length == 2) { + return isNumOrPerc(spl[0]) && isNumber(spl[1]) + } + return false +} + +const isAngle = function(value) { + let types = new Set(["deg","grad","rad","turn"]); + let extra = value.slice(parseFloat(value).toString().length, value.length) + return types.has(extra) +} + + +const isPercent = function(value) { + return value.endsWith('%') && isNumber(value.slice(0, value.length-1)) +} + + +const isNumber = function(value) { + if(value == undefined || value.length == 0){ return false }; + let isNum = !isNaN(Number(value)) + return isNum +} + + +const asThreeBitColor = function(values) { + let ex = values.slice(4, 5) + let alp = '' + if(ex.length>0) { + alp = `/${ex}` + } + return `${values[0]}(${values.slice(1, 4).join(' ')}${alp})` +} + + +/* Perform a _hot word_ detection on the values recursively. A _hot word_ may be any key. + + forwardHotWordReduce( + ['color'] + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + ) + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail. + +This method then performs this after every release, concatenating changed and +unchanged into a response list. + + rgb-200-200-200-foo + + rgb(200 200 200) foo + + */ +const forwardHotWordReduce = function(props, values, keys, keyTestFunc=undefined) { + /* + Key pops early, and can accept a variable amount of vars. + */ + + let len = values.length + , position = 0 + , max = values.length + 1 + , count = 0 + , response = [] + ; + + while(position < len && count < max) { + let sliced = values.slice(position) + let [key, usedCount] = hotWordReduce(sliced, keys, true, keyTestFunc) + + position += usedCount + count += 1 + if(Array.isArray(key)) { + response = response.concat(key) + } else { + response.push(key) + } + } + + return response +} + +/* Perform a _hot word_ detection on the values. A _hot word_ may be any key. + + forwardHotWordReduce( + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + , true + ) + + rgb(200 200 200) // break early + rgb(200 200 200) egg + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail if `breakEarly` is true. + + rgb-200-200-200-foo-hsl-20-0%-10-foo + + rgb(200 200 200) foo hsl(20 0% 10) foo + + */ + +const hotWordReduce = function(values, keys + , breakEarly=false + , callback=asThreeBitColor + , keyTestFunc=undefined) { + + var i = 0; + let inSet = (x) => keys.has(x) + , keyStartMatch = keyTestFunc != undefined? keyTestFunc: inSet + , l = values.length + , bits = [] + , kept = [] + , lost = [] + , max = 4 // can be 3 or 4 + ; + + for (;i < l; i++) { + // console.log('---') + let k = values[i]; + let inI = i; + if(keyStartMatch(k)) { + // console.log(i, 'MATCH', k) + let j = i+1 + kept = [k] + lost = [] + let ok = true + while(ok && j < l) { + let subI = j; + let subK = values[subI]; + let isNum = isNumOrPerc(subK) + ok = isNum && j < l && kept.length <= (max-1) // +1 for the original key + if(isNum) { + // console.log('Push', subK) + j += 1 + kept.push(subK) + ok = ok && kept.length <= max // +1 for the original key + } else { + // Lost stack + // console.log('Lost stack on', subK) + // j = 1 + lost.push(subK) + } + // console.log('S', subI, subK, isNum, ok) + } + + let [a,b] = [inI, j] + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept) + if(plucked.length < 3) { + // console.log('Failed.', bits) + bits = bits.concat(kept) + if(breakEarly) { + return [bits, j] + } + } else { + // console.log('kept', kept, newEntry) + // console.log('plucked', plucked) + bits.push(newEntry) + // Push back 2, as we landed on the bad node, + // and we need step into this node, to stack it. + // + i = j-1 + } + } else { + // console.log(i, k) + bits.push(k) + + if(breakEarly) { + let [a,b] = [inI, kept.length] + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept) + // console.log('plucked', plucked) + // console.log('kept', kept) + if(kept.length < 3) { + // console.log('Failed.', 'kept', kept, 'plucked', plucked) + return [values[b], kept.length+1] + } else { + // console.log('success.') + return [newEntry, kept.length] + } + + return [values[0], 1] + } + } + } + + // console.log('Done pop', i) + // console.log('in', values, 'out', bits) + + let newEntry = callback(kept) + return [newEntry, i+1] +} + + +;installReceiver(); + +// })() /** * # Events event-[eventName]-[action]-[params]* * @@ -2202,6 +2487,8 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy) cg = _cg; cg.insertReceiver(['font', 'pack'], fontPackReceiver) } + ClassGraph.prototype.generateGoogleLinks = generateGoogleLinks + ClassGraph.prototype.installGoogleLinks = installGoogleLinks } /** @@ -2224,15 +2511,18 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy) let familyStrings = createFamilyString(values, fonts, origin) // let families = tokenize(values) - - // install as header items - // console.info('Installing Google fonts: familyStrings:', familyStrings) - generateGoogleLinks(familyStrings).forEach((x)=>document.head.appendChild(x)) + installGoogleLinks(familyStrings) // Install additional css additions installFontObjects(fonts, obj) } + const installGoogleLinks = function(familyStrings, display) { + // install as header items + // console.info('Installing Google fonts: familyStrings:', familyStrings) + return generateGoogleLinks(familyStrings, display).forEach((x)=>document.head.appendChild(x)) + } + const installFontObjects = function(fonts, splitObj) { // // For value create a font-family; @@ -2596,7 +2886,7 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy) }) } - const generateGoogleLinks = function(familyStrings){ + const generateGoogleLinks = function(familyStrings, display='swap'){ let a = getOrCreateLink('link', 'preconnect', { href: "https://fonts.googleapis.com" @@ -2607,8 +2897,10 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy) , crossorigin: '' }) + let ds = display == null? '': `&display=${display}` + let c = getOrCreateLink('link', "stylesheet", { - href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + href:`https://fonts.googleapis.com/css2?${familyStrings}${ds}` }) return [a,b,c] @@ -2616,6 +2908,18 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy) let linkCache = {} + /* + Create a link node + + let b = getOrCreateLink('link', 'preconnect', { + href: "https://fonts.gstatic.com" + , crossorigin: '' + }) + + let c = getOrCreateLink('link', "stylesheet", { + href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + }) + */ const getOrCreateLink = function(href, rel, opts) { let v = { rel, href @@ -2652,417 +2956,536 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy) })() -/** - * # Monitor - * - * Monitor the HTML tree for dynamically inserted classes. - * This ensures any class applied to a node _after_ first render - * is discovered. It works through a mutation observer for the - * attribute "class". This is useful for dynamic processing of HTML pages - * - * If the view is a SPA or all the possible classes are _used_ on - * the view, this isn't required. - */ -;(()=>{ - -let cg; - -/* - Called at the root of this IIFE to install the functions on the classgraph. - */ -const insertReceiver = function(){ +;(function(){ - ClassGraph.addons.monitorClasses = function(_cg){ - cg = _cg; - } + let cg; + let rootDeclaration = {}; + let definition = undefined + let rootRule; - ClassGraph.prototype.monitor = function(parent=document.body) { - return monitorClasses(parent) - } + const insertReceiver = function(){ - return { - init(polyObj) { - console.log('init polyObj') + ClassGraph.addons.functionsReceiver = function(_cg){ + cg = _cg; + cg.keyValueFunctions.set('forceGreen', forceHook) + cg.keyValueFunctions.set('force', forceHook) + cg.keyValueFunctions.set('raise', raiseHook) } } -} + const forceHook = function(value, token, index, splitObj) { + // console.log('Force green hook', token, splitObj) + let res = token.value.slice(0, token.match.start) + // console.log(res) + // return res -const monitorClasses = function(node) { - /* + return token.args.length > 0? token.args[0]: 'green' + } - Note: If Chrome mutation observer fails to detect a change - (But this function is called.), restart the tab, window or browser. - */ + const raiseHook = function(value, token, index, splitObj) { + console.log('raise hook', token, splitObj) + let res = token.value.slice(0, token.match.start) + console.log(res) + // return res + } - // console.log('monitorClasses', node) - // configuration of the observer: - let config = { - attributes: true - , subtree: true - // , childList:true - , attributeFilter: ['class'] - // , characterData: true - , attributeOldValue: true - // , characterDataOldValue: true - }; + const functionsHook = function(d) { - let eachMutation = function(mutation) { - // console.log('eachMutation', mutation) - if(mutation.attributeName == 'class') { - classMutationDetection(mutation) - } + // target = document.querySelector(target) + console.log('functions', d) } - let mutationHandler = function(mutations) { - // console.log('mutationHandler', mutations) - mutations.forEach(eachMutation); - } - let observer = new MutationObserver(mutationHandler); - // pass in the target node, as well as the observer options - observer.observe(node, config); + ;insertReceiver(); +})() + +class PolyclassIcons { - return observer } +;(function(){ -const classMutationDetection = function(mutation) { - let classes = mutation.target.classList.value; - let old = mutation.oldValue - // console.log(`old: "${mutation.oldValue}", target:` - // , mutation.target - // , `classes: "${classes}"` - // ) - let new_spl = classes.split(/(?!\(.*)\s(?![^(]*?\))/g); //split(' ') - let old_spl = old == null ? []: old.split(' ').map((v)=>v.trim()) - let newItems = old_spl? difference(new_spl, old_spl): new_spl - console.log('new', newItems) - // let removedItems = difference(old_spl, new_spl) - // console.log('removedItems', removedItems) - cg.captureChanges(newItems, old_spl, mutation.target) -} + let cg; + const insertReceiver = function(){ + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; -const difference = function(setA, setB) { - const _difference = new Set(setA); - for (const elem of setB) { - _difference.delete(elem); + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver) + // cg.insertReceiver(['icon'], iconReceiver) + } } - return _difference; -} -;insertReceiver(); + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); -})() - -/* + const iconPackReceiver = function(obj) { -vars box. To assign key variables as accessible CSS varialbes through a js -definition. The definition is bound to DCSS, so edits to the vars manipulates -the view automatically. + let key = titleCase(obj.values).join('+') + let family = `Material+Symbols+${key}` + let defaultFontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + } + let familyString = toGoogleFontParamsStr(opts) + let fontStr = `family=${family}:${familyString}` - vars({ - primary: "#880000" # company red - , secondary: "#111" # dark - , accent: "red" - }) + let receiverBits = [...obj.values, 'icon'] -In the node, we access the vars reciever + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver) -
-

An elk called Elk lives here.

-
-Manipulating the var propagates to the view: + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null) - vars.primary = "#EEE" # off white + /* Install the css class rule object */ + installSheetRules(obj, fontSettings) ---- + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + } -## Secondary App + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0] + let rules = {} + + let fontSettingsStr = toObjectParamStr(fontSettings) + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + } - `swatch()` - and colors.js + rules[`.material-symbols-${key}`] = conf + let items = cg.dcss.addStylesheetRules(rules) - Assign "colors" to a swatch of colors, each color is a function from the - colors.js module and can assign math relations to swatches. - Chaning a swatch (such as its base color), can manipulate the other - colours according to the chosen swatch type, e.g. "Diachromic". + items.renderAll() + } - */ + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: -;(function(){ + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } - let cg; - let rootDeclaration = {}; - let definition = undefined - let rootRule; + Return a multiline string, with the properties string wrapped: - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varsReceiver = function(_cg){ - cg = _cg; - cg.vars = varsHook.bind(cg) - // cg.varsRootDelaration = rootDeclaration - cg.varsRoot = rootRule - // cg.insertTranslator('var', variableDigest) + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj) + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i] + let v = obj[k] + let last = i == fKeys.length-1 + let end = last? '': ',\n' + fontSettingsStr += `'${k}' ${v}${end}` } - } - - - const varsHook = function(d, target=':root') { - /** vars() function bound to the classgraph. _this_ is the classgraph - instance `cg.vars = varsHook.bind(cg)` - - each key is a var, value is the param + return fontSettingsStr - { - apples: green - , foo: 10 - , bar: 1em - , baz: #444 - } - - Each var is installed on the target node: + } - :root { - --apples: green - ... - --baz: #444 + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", } - if an existing "vars" object exists, it's updated. - + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` */ - // target = document.querySelector(target) - console.log('Hook', d) - - if(rootRule == undefined) { - let rootDeclaration = {}; + let k = Object.keys(obj).join(',') + let v = Object.values(obj).join(',') + return `${k}@${v}` + } - for(let key in d) { - let prop = `--${key}` - let value = d[key] - rootDeclaration[prop] = value; - } + const iconReceiver = function(obj) { - let rules = cg.dcss.addStylesheetRules({ - [target]: rootDeclaration - }); + // Tokenize as a family string. + // + const values = obj.values, origin = obj.origin; + console.log('render icon', obj) - rules.renderAll() - rootRule = rules[0] - cg.varsRoot = rootRule - } else { + return contentInjection(obj) + } - // rootRule - // let pr = rootRule.getPropStr([target,Object.entries(definition)]) - // rootRule.sheetRule.cssText = `${target} { ${pr} }` - // rootRule.replace(`${target} { ${pr} }`) + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)) + origin.innerText += `${values.join('_')}` + } - for(let key in d) { - let prop = `--${key}` - let value = d[key] - rootRule.sheetRule.style.setProperty(prop, value) - } - // rootRule.render() - // console.log(rootRule) - // window.varsRule = rootRule - } + const getInjectClass = function(obj) { + let k = obj.props[0] + return `material-symbols-${k}` } ;insertReceiver(); })() -/** - * # var-* Translate - * - * https://developer.mozilla.org/en-US/docs/Web/CSS/var - * - * Discover and rewrite class names values with `var-*` to the CSS function - * `var(*)`. e.g. - * - * "border-top-var-primary-edges" - * - * { - * "border-top": var(--primary-edges) - * } - */ ;(function(){ let cg; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ const insertReceiver = function(){ - // console.log('var-translate insertReceiver') - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - ClassGraph.addons.varTranslateReceiver = function(_cg){ + ClassGraph.addons.iconReceiver = function(_cg){ cg = _cg; - cg.insertTranslator('var', variableDigest2) - // cg.insertTranslator('var', variableDigest) + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver) + // cg.insertReceiver(['icon'], iconReceiver) } } - /** - * The handler function given to the dynamic css stylesheet, called - * when the dcss is prepared. - * - * @param {object} obj A definition generated by the class graph discovery - * @return {undefined} - */ - const variableDigest = function(splitObj, index) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + console.log('Install the font', obj) + let key = titleCase(obj.values).join('+') + let family = `Material+Symbols+${key}` + let fontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + } + let familyString = toGoogleFontParamsStr(opts) + let fontStr = `family=${family}:${familyString}` - /* - This is pretty dumb, and should improve to a forward stepping - solution, detecting possible names + let receiverBits = [...obj.values, 'icon'] - Issue is a var can be anything `var(--1em)`. - Therefore forward feed on _possibles_ is sticky. This is valid: + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver) - { - margin: var(--1em) var(--orange) - } - Therefore break on `var` + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null) - "margin-var-1em-var-orange" + /* Install the css class rule object */ + installSheetRules(obj, fontSettings) - However `var(--var)` is valid: - { - --var: 1em - --var-orange: orange; - } + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + } + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0] + let rules = {} + + let fontSettingsStr = toObjectParamStr(fontSettings) + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + } - Meaning: - "margin-var-1em-var-var-orange" + rules[`.material-symbols-${key}`] = conf + let items = cg.dcss.addStylesheetRules(rules) - Therefore break on var, unless [var]+1 == var, - as then its break on var, dont break on next var, - yielding `var-orange`.` + items.renderAll() + } - However also allowed: "margin-var-1em-var-var-var" + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: - { - --var-var: - } + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } - So then possibly, two dashes between `var var`` + Return a multiline string, with the properties string wrapped: - margin-var-key--var-var-var-var--var-var-key + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj) + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i] + let v = obj[k] + let last = i == fKeys.length-1 + let end = last? '': ',\n' + fontSettingsStr += `'${k}' ${v}${end}` + } + return fontSettingsStr - { - margin: var(key) var(var-var-var) var(var-key) - } + } - Allowing the strange but valid: - { - --var-key: 1em; - --var-var-var-var: 2em; - --var-var-key: 1em solid; - } + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } - */ - // console.log('running on', splitObj) - // Tokenize as a family string. - values = splitObj.values - let keys = splitObj.values.slice(index) - let k1 = keys.slice(1) - let word = `var(--${k1.join("-")})` - // console.log(keys, word) - return word - // [inStack, outStack, currentIndex] = - // digestFunc(splitObj, inStack, outStack, currentIndex) + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(',') + let v = Object.values(obj).join(',') + return `${k}@${v}` } + const iconReceiver = function(obj) { - const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ - - let keys = inStack.slice(currentIndex) - let k1 = keys.slice(1) - let word = `var(--${k1.join("-")})` + // Tokenize as a family string. + // + const values = obj.values, origin = obj.origin; + console.log('render icon', obj) - outStack.push(word) - // return [inStack, outStack, currentIndex] - return [[], outStack, currentIndex + k1.length] + return contentInjection(obj) } + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)) + origin.innerText += `${values.join('_')}` + } + const getInjectClass = function(obj) { + let k = obj.props[0] + return `material-symbols-${k}` + } ;insertReceiver(); })() +/** + * # Monitor + * + * Monitor the HTML tree for dynamically inserted classes. + * This ensures any class applied to a node _after_ first render + * is discovered. It works through a mutation observer for the + * attribute "class". This is useful for dynamic processing of HTML pages + * + * If the view is a SPA or all the possible classes are _used_ on + * the view, this isn't required. + */ +;(()=>{ +let cg; -/* The words map lists all the unique string CSS values. Each word maps to an - integer, used for the microGraph key. +/* + Called at the root of this IIFE to install the functions on the classgraph. + */ +const insertReceiver = function(){ - words = { - 'all' => 0, - 'petit' => 1, - ... + ClassGraph.addons.monitorClasses = function(_cg){ + cg = _cg; } -*/ -;(()=>{ - -class Words extends Map { - wordCounter = 1 + ClassGraph.prototype.monitor = function(parent=document.body) { + return monitorClasses(parent) + } - getKey(f) { - let pos = words.get(f) - if(pos == undefined) { - words.set(f, this.wordCounter) - pos = this.wordCounter; - this.wordCounter++; + return { + init(polyObj) { + console.log('init polyObj') } - return pos; } +} + +const monitorClasses = function(node) { /* - Given a dash-split-string, return a return of resolved positions. - stringToBits('all-petite') - [0, 1] - */ - stringToBits(s, sep='-') { - let items = s.split(sep) - , res = []; - items.forEach((f, j, b)=> res.push(this.getKey(f))) - return res - } + + Note: If Chrome mutation observer fails to detect a change + (But this function is called.), restart the tab, window or browser. + */ + + // console.log('monitorClasses', node) + // configuration of the observer: + let config = { + attributes: true + , subtree: true + // , childList:true + , attributeFilter: ['class'] + // , characterData: true + , attributeOldValue: true + // , characterDataOldValue: true + }; + + let eachMutation = function(mutation) { + // console.log('eachMutation', mutation) + if(mutation.attributeName == 'class') { + classMutationDetection(mutation) + } + } + + let mutationHandler = function(mutations) { + // console.log('mutationHandler', mutations) + mutations.forEach(eachMutation); + } + + let observer = new MutationObserver(mutationHandler); + // pass in the target node, as well as the observer options + observer.observe(node, config); + + return observer +} + + +const classMutationDetection = function(mutation) { + let classes = mutation.target.classList.value; + let old = mutation.oldValue + // console.log(`old: "${mutation.oldValue}", target:` + // , mutation.target + // , `classes: "${classes}"` + // ) + let new_spl = classes.split(/(?!\(.*)\s(?![^(]*?\))/g); //split(' ') + let old_spl = old == null ? []: old.split(' ').map((v)=>v.trim()) + let newItems = old_spl? difference(new_spl, old_spl): new_spl + console.log('new', newItems) + // let removedItems = difference(old_spl, new_spl) + // console.log('removedItems', removedItems) + cg.captureChanges(newItems, old_spl, mutation.target) +} + + +const difference = function(setA, setB) { + const _difference = new Set(setA); + for (const elem of setB) { + _difference.delete(elem); + } + return _difference; +} + +;insertReceiver(); + +})() + +/* +Convert discovered nodes and bind them to a selector. The assigned classes +are the declarations assigned to the css class. + +The discovery may descend children, allowing for depth setup. + + + + + + + + + +Notably this may be easier as real CSS. + */ + + +/* The words map lists all the unique string CSS values. Each word maps to an + integer, used for the microGraph key. + + words = { + 'all' => 0, + 'petit' => 1, + ... + } +*/ +;(()=>{ + + +class Words extends Map { + wordCounter = 1 + + getKey(f) { + let pos = words.get(f) + if(pos == undefined) { + words.set(f, this.wordCounter) + pos = this.wordCounter; + this.wordCounter++; + } + return pos; + } + + /* + Given a dash-split-string, return a return of resolved positions. + stringToBits('all-petite') + [0, 1] + */ + stringToBits(s, sep='-') { + let items = s.split(sep) + , res = []; + items.forEach((f, j, b)=> res.push(this.getKey(f))) + return res + } stringToNest(s, root={}) { // split @@ -3105,10 +3528,10 @@ class Words extends Map { wordsToArrayString(indent=0, small=false){ if(!small) { - return JSON.stringify(wordsToOrderedArray(), null, indent) + return JSON.stringify(this.wordsToOrderedArray(), null, indent) } - return wordsToOrderedArray().join(' ') + return this.wordsToOrderedArray().join(' ') } wordsToObjectString(indent=0, small=false) { @@ -3148,6 +3571,75 @@ class Words extends Map { } } +/* +1. all the items have string in position +2. the we create the flat array list +each position is a word from the string list + + "all-petite-caps", + "all-scroll", + "all-small-caps", + +as a string: + + " all petite caps scroll small ..." + +Becomes: + [1, [ + [2, [ + [3, null] + ] + ], + [4, null], + [5, [ + [3,null] + ] + ] + ] + ] + +--- + +When loaded, we can re-ask for the prop: + + w.stringToBits("all-petite-caps") + [1,2,3] + +The last key + + w.stringToBits("zoom") + [211] + w.stringToBits("zoom-out") + [211, 66] +--- + + + "all-petite-caps", + "all-scroll", + "all-small-caps", + "allow-end", + "alternate-reverse", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2", + "0-3", + "0-4-5", + "6-7", + "8-9", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2 0-3 0-4-5 6-7 8-9" + + "all petite caps scroll small allow end alternate reverse", + "0 1 2,0 3,0 4 5,6 7,8 9" + + // radix each key through 32 bits, allowing ~1000 positions as 2bits + // not really helpful under 100 keys, but then saves 1 char per position (up to 1k) + // .. With 255~ keys thats 150~ chars saved. + // In a 32bit radix, the first 31 positions are single chars. +--- + +*/ const words = new Words() , microGraph = {} @@ -3354,61 +3846,17 @@ const words = new Words() var installReceiver = function() { - ClassGraph.addons.forwardReduceValues = (cg) => words.installPropArray(dashprops) - ClassGraph.prototype.forwardReduceValues = forwardReduceValues - ClassGraph.prototype.valuesGraph = { microGraph, words } -} - - -const arrayStringMunger = function(str) { - /* given the string, crush it futher.*/ - let dmap = { - // '[': { active: false, current: 0, max: -1} - // , ']': { active: false, current: 0, max: -1} - } - - let actives = []; - - for(let c of str) { - if(dmap[c] == undefined) { - // new position - dmap[c] = { active: false, current: -1, max: -1, total: 0} + ClassGraph.addons.forwardReduceValues = function(cg){ + let func = function(prop, values) { + return forwardReduceValues(prop, values, microGraph, words) } - - if(dmap[c].active) { - // was active. just append and continue. - dmap[c].current += 1; - } else { - // Close any alive, finalise the max. - // for(let k in dmap) { - // if(k == c) { - // // The same object doesn't turn off. - // continue - // } - // dmap[k].active = false - // dmap[k].max = Math.max(dmap[k].max, dmap[k].current) - // // We set current to 0 here (not -1), - // dmap[k].current = 0 - // } - let cStash = dmap[c].current - for(let o of actives) { - o.active = false - o.max = Math.max(o.max, o.current) - o.current = 0 - } - - actives = [dmap[c]] - dmap[c].active = true - dmap[c].total += 1 - dmap[c].current = cStash + 1; - } - } - for(let o of actives) { - o.active = false - o.max = Math.max(o.max, o.current) - o.current = 0 + cg.reducers.push(func) + let res = words.installPropArray(dashprops) + return res; } - return dmap + // install one of many + // ClassGraph.prototype.forwardReduceValues = forwardReduceValues + ClassGraph.prototype.valuesGraph = { microGraph, words } } @@ -3437,9 +3885,6 @@ const forwardReduceValues = function(props, values, microGraph, translations) { 'row': { 'reverse': merge } - , 'other': { - 'horse': merge - } } let len = values.length @@ -3499,3 +3944,272 @@ const popOneValueForward = function(values, microGraph, translations) { ;installReceiver(); })() +/** + * # var-* Translate + * + * https://developer.mozilla.org/en-US/docs/Web/CSS/var + * + * Discover and rewrite class names values with `var-*` to the CSS function + * `var(*)`. e.g. + * + * "border-top-var-primary-edges" + * + * { + * "border-top": var(--primary-edges) + * } + */ +;(function(){ + + let cg; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // console.log('var-translate insertReceiver') + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varTranslateReceiver = function(_cg){ + cg = _cg; + cg.insertTranslator('var', variableDigest2) + // cg.insertTranslator('var', variableDigest) + } + } + + /** + * The handler function given to the dynamic css stylesheet, called + * when the dcss is prepared. + * + * @param {object} obj A definition generated by the class graph discovery + * @return {undefined} + */ + const variableDigest = function(splitObj, index) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + /* + This is pretty dumb, and should improve to a forward stepping + solution, detecting possible names + + Issue is a var can be anything `var(--1em)`. + Therefore forward feed on _possibles_ is sticky. This is valid: + + { + margin: var(--1em) var(--orange) + } + + Therefore break on `var` + + "margin-var-1em-var-orange" + + However `var(--var)` is valid: + { + --var: 1em + --var-orange: orange; + } + + + Meaning: + "margin-var-1em-var-var-orange" + + Therefore break on var, unless [var]+1 == var, + as then its break on var, dont break on next var, + yielding `var-orange`.` + + However also allowed: "margin-var-1em-var-var-var" + + { + --var-var: + } + + So then possibly, two dashes between `var var`` + + margin-var-key--var-var-var-var--var-var-key + + { + margin: var(key) var(var-var-var) var(var-key) + } + + Allowing the strange but valid: + { + --var-key: 1em; + --var-var-var-var: 2em; + --var-var-key: 1em solid; + } + + */ + // console.log('running on', splitObj) + // Tokenize as a family string. + values = splitObj.values + let keys = splitObj.values.slice(index) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + // console.log(keys, word) + return word + // [inStack, outStack, currentIndex] = + // digestFunc(splitObj, inStack, outStack, currentIndex) + } + + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + + + ;insertReceiver(); +})() + +/* + +vars box. To assign key variables as accessible CSS varialbes through a js +definition. The definition is bound to DCSS, so edits to the vars manipulates +the view automatically. + + vars({ + primary: "#880000" # company red + , secondary: "#111" # dark + , accent: "red" + }) + +In the node, we access the vars reciever + +
+

An elk called Elk lives here.

+
+ +Manipulating the var propagates to the view: + + vars.primary = "#EEE" # off white + +--- + +## Secondary App + + `swatch()` + and colors.js + + Assign "colors" to a swatch of colors, each color is a function from the + colors.js module and can assign math relations to swatches. + Chaning a swatch (such as its base color), can manipulate the other + colours according to the chosen swatch type, e.g. "Diachromic". + + */ + +;(function(){ + + let cg; + let rootDeclaration = {}; + let definition = undefined + let rootRule; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varsReceiver = function(_cg){ + cg = _cg; + cg.vars = varsHook.bind(cg) + // cg.varsRootDelaration = rootDeclaration + cg.varsRoot = rootRule + // cg.insertTranslator('var', variableDigest) + } + } + + + const varsHook = function(d, target=':root') { + /** vars() function bound to the classgraph. _this_ is the classgraph + instance `cg.vars = varsHook.bind(cg)` + + each key is a var, value is the param + + { + apples: green + , foo: 10 + , bar: 1em + , baz: #444 + } + + Each var is installed on the target node: + + :root { + --apples: green + ... + --baz: #444 + } + + if an existing "vars" object exists, it's updated. + + */ + // target = document.querySelector(target) + console.log('Hook', d) + + if(rootRule == undefined) { + let rootDeclaration = {}; + + for(let key in d) { + let prop = `--${key}` + let value = d[key] + rootDeclaration[prop] = value; + } + + let rules = cg.dcss.addStylesheetRules({ + [target]: rootDeclaration + }); + + rules.renderAll() + rootRule = rules[0] + cg.varsRoot = rootRule + } else { + + // rootRule + // let pr = rootRule.getPropStr([target,Object.entries(definition)]) + // rootRule.sheetRule.cssText = `${target} { ${pr} }` + // rootRule.replace(`${target} { ${pr} }`) + + for(let key in d) { + let prop = `--${key}` + let value = d[key] + rootRule.sheetRule.style.setProperty(prop, value) + } + // rootRule.render() + // console.log(rootRule) + // window.varsRule = rootRule + } + } + + ;insertReceiver(); +})() + diff --git a/build/polyclass.core.js b/build/polyclass.core.js index 62a8505..7c2f8c3 100755 --- a/build/polyclass.core.js +++ b/build/polyclass.core.js @@ -233,17 +233,17 @@ console.log(blendedcolor, blendedcolor2) })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -449,10 +449,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0 + let c = 0 for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -633,6 +633,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {} + this.announce('wake') /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -641,7 +642,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, } - + this.reducers = [] if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()) } @@ -651,8 +652,38 @@ class ClassGraph { this.aliasMap = {} this.parentSelector = conf?.parentSelector this.processAliases(this.conf?.aliases) + this.announce('ready') + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }) + dispatchEvent(e) } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func } @@ -925,8 +956,8 @@ class ClassGraph { values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ) let r = { @@ -941,7 +972,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues)//, graph, words) + loopValues = r + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { diff --git a/build/polyclass.full.js b/build/polyclass.full.js index c137233..dd4838e 100755 --- a/build/polyclass.full.js +++ b/build/polyclass.full.js @@ -233,17 +233,17 @@ console.log(blendedcolor, blendedcolor2) })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -449,10 +449,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0 + let c = 0 for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -633,6 +633,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {} + this.announce('wake') /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -641,7 +642,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, } - + this.reducers = [] if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()) } @@ -651,8 +652,38 @@ class ClassGraph { this.aliasMap = {} this.parentSelector = conf?.parentSelector this.processAliases(this.conf?.aliases) + this.announce('ready') + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }) + dispatchEvent(e) } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func } @@ -925,8 +956,8 @@ class ClassGraph { values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ) let r = { @@ -941,7 +972,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues)//, graph, words) + loopValues = r + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -2019,6 +2056,253 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy) export { DynamicCSSStyleSheet, RenderArray, ClassGraph, Polyclass }; + +//;(()=>{ + +var installReceiver = function() { + + let keys = new Set([ + /* Hex is a freebie, under the special term `#` hash: #000000 */ + // 'hex', + /* Color property is slightly more complicated, with the first param + as a forced string. */ + // 'color', + + /* Available types, each act the same way: rgb-[3 values][/A] + If the key is a mismatch, its ignored. */ + 'rgb', + 'hsl', + 'hwb', + 'lab', + 'lch', + 'oklab', + 'oklch', + ]) + + ClassGraph.addons.extendedColorValues = function(cg){ + let func = function(prop, values) { + return forwardHotWordReduce(prop, values, keys) + } + cg.reducers.push(func) + } +} + + +/* Return a boolean if the detected type is a valid css value of type: + + Number: 0 | 0.0 + Percent: 0% + Opacity: 0/0 + Angle: 0turn | 0rad +*/ +const isNumOrPerc = function(value) { + return isNumber(value) || isPercent(value) || isOpacityNum(value) || isAngle(value) +} + +/* Return boolean for the match of a css value with an alpha: 0/0 */ +const isOpacityNum = function(value) { + // '60%/0.8' + let spl = value.split('/') + if(spl.length == 2) { + return isNumOrPerc(spl[0]) && isNumber(spl[1]) + } + return false +} + +const isAngle = function(value) { + let types = new Set(["deg","grad","rad","turn"]); + let extra = value.slice(parseFloat(value).toString().length, value.length) + return types.has(extra) +} + + +const isPercent = function(value) { + return value.endsWith('%') && isNumber(value.slice(0, value.length-1)) +} + + +const isNumber = function(value) { + if(value == undefined || value.length == 0){ return false }; + let isNum = !isNaN(Number(value)) + return isNum +} + + +const asThreeBitColor = function(values) { + let ex = values.slice(4, 5) + let alp = '' + if(ex.length>0) { + alp = `/${ex}` + } + return `${values[0]}(${values.slice(1, 4).join(' ')}${alp})` +} + + +/* Perform a _hot word_ detection on the values recursively. A _hot word_ may be any key. + + forwardHotWordReduce( + ['color'] + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + ) + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail. + +This method then performs this after every release, concatenating changed and +unchanged into a response list. + + rgb-200-200-200-foo + + rgb(200 200 200) foo + + */ +const forwardHotWordReduce = function(props, values, keys, keyTestFunc=undefined) { + /* + Key pops early, and can accept a variable amount of vars. + */ + + let len = values.length + , position = 0 + , max = values.length + 1 + , count = 0 + , response = [] + ; + + while(position < len && count < max) { + let sliced = values.slice(position) + let [key, usedCount] = hotWordReduce(sliced, keys, true, keyTestFunc) + + position += usedCount + count += 1 + if(Array.isArray(key)) { + response = response.concat(key) + } else { + response.push(key) + } + } + + return response +} + +/* Perform a _hot word_ detection on the values. A _hot word_ may be any key. + + forwardHotWordReduce( + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + , true + ) + + rgb(200 200 200) // break early + rgb(200 200 200) egg + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail if `breakEarly` is true. + + rgb-200-200-200-foo-hsl-20-0%-10-foo + + rgb(200 200 200) foo hsl(20 0% 10) foo + + */ + +const hotWordReduce = function(values, keys + , breakEarly=false + , callback=asThreeBitColor + , keyTestFunc=undefined) { + + var i = 0; + let inSet = (x) => keys.has(x) + , keyStartMatch = keyTestFunc != undefined? keyTestFunc: inSet + , l = values.length + , bits = [] + , kept = [] + , lost = [] + , max = 4 // can be 3 or 4 + ; + + for (;i < l; i++) { + // console.log('---') + let k = values[i]; + let inI = i; + if(keyStartMatch(k)) { + // console.log(i, 'MATCH', k) + let j = i+1 + kept = [k] + lost = [] + let ok = true + while(ok && j < l) { + let subI = j; + let subK = values[subI]; + let isNum = isNumOrPerc(subK) + ok = isNum && j < l && kept.length <= (max-1) // +1 for the original key + if(isNum) { + // console.log('Push', subK) + j += 1 + kept.push(subK) + ok = ok && kept.length <= max // +1 for the original key + } else { + // Lost stack + // console.log('Lost stack on', subK) + // j = 1 + lost.push(subK) + } + // console.log('S', subI, subK, isNum, ok) + } + + let [a,b] = [inI, j] + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept) + if(plucked.length < 3) { + // console.log('Failed.', bits) + bits = bits.concat(kept) + if(breakEarly) { + return [bits, j] + } + } else { + // console.log('kept', kept, newEntry) + // console.log('plucked', plucked) + bits.push(newEntry) + // Push back 2, as we landed on the bad node, + // and we need step into this node, to stack it. + // + i = j-1 + } + } else { + // console.log(i, k) + bits.push(k) + + if(breakEarly) { + let [a,b] = [inI, kept.length] + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept) + // console.log('plucked', plucked) + // console.log('kept', kept) + if(kept.length < 3) { + // console.log('Failed.', 'kept', kept, 'plucked', plucked) + return [values[b], kept.length+1] + } else { + // console.log('success.') + return [newEntry, kept.length] + } + + return [values[0], 1] + } + } + } + + // console.log('Done pop', i) + // console.log('in', values, 'out', bits) + + let newEntry = callback(kept) + return [newEntry, i+1] +} + + +;installReceiver(); + +// })() /** * # Events event-[eventName]-[action]-[params]* * @@ -2171,6 +2455,8 @@ export { cg = _cg; cg.insertReceiver(['font', 'pack'], fontPackReceiver) } + ClassGraph.prototype.generateGoogleLinks = generateGoogleLinks + ClassGraph.prototype.installGoogleLinks = installGoogleLinks } /** @@ -2193,15 +2479,18 @@ export { let familyStrings = createFamilyString(values, fonts, origin) // let families = tokenize(values) - - // install as header items - // console.info('Installing Google fonts: familyStrings:', familyStrings) - generateGoogleLinks(familyStrings).forEach((x)=>document.head.appendChild(x)) + installGoogleLinks(familyStrings) // Install additional css additions installFontObjects(fonts, obj) } + const installGoogleLinks = function(familyStrings, display) { + // install as header items + // console.info('Installing Google fonts: familyStrings:', familyStrings) + return generateGoogleLinks(familyStrings, display).forEach((x)=>document.head.appendChild(x)) + } + const installFontObjects = function(fonts, splitObj) { // // For value create a font-family; @@ -2565,7 +2854,7 @@ export { }) } - const generateGoogleLinks = function(familyStrings){ + const generateGoogleLinks = function(familyStrings, display='swap'){ let a = getOrCreateLink('link', 'preconnect', { href: "https://fonts.googleapis.com" @@ -2576,8 +2865,10 @@ export { , crossorigin: '' }) + let ds = display == null? '': `&display=${display}` + let c = getOrCreateLink('link', "stylesheet", { - href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + href:`https://fonts.googleapis.com/css2?${familyStrings}${ds}` }) return [a,b,c] @@ -2585,6 +2876,18 @@ export { let linkCache = {} + /* + Create a link node + + let b = getOrCreateLink('link', 'preconnect', { + href: "https://fonts.gstatic.com" + , crossorigin: '' + }) + + let c = getOrCreateLink('link', "stylesheet", { + href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + }) + */ const getOrCreateLink = function(href, rel, opts) { let v = { rel, href @@ -2621,6 +2924,365 @@ export { })() +;(function(){ + + let cg; + let rootDeclaration = {}; + let definition = undefined + let rootRule; + + const insertReceiver = function(){ + + ClassGraph.addons.functionsReceiver = function(_cg){ + cg = _cg; + cg.keyValueFunctions.set('forceGreen', forceHook) + cg.keyValueFunctions.set('force', forceHook) + cg.keyValueFunctions.set('raise', raiseHook) + } + } + + const forceHook = function(value, token, index, splitObj) { + // console.log('Force green hook', token, splitObj) + let res = token.value.slice(0, token.match.start) + // console.log(res) + // return res + + return token.args.length > 0? token.args[0]: 'green' + } + + const raiseHook = function(value, token, index, splitObj) { + console.log('raise hook', token, splitObj) + let res = token.value.slice(0, token.match.start) + console.log(res) + // return res + } + + const functionsHook = function(d) { + + // target = document.querySelector(target) + console.log('functions', d) + } + + + ;insertReceiver(); +})() + +class PolyclassIcons { + +} + +;(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver) + // cg.insertReceiver(['icon'], iconReceiver) + } + } + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + + let key = titleCase(obj.values).join('+') + let family = `Material+Symbols+${key}` + let defaultFontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + } + let familyString = toGoogleFontParamsStr(opts) + let fontStr = `family=${family}:${familyString}` + + let receiverBits = [...obj.values, 'icon'] + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver) + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null) + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings) + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + } + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0] + let rules = {} + + let fontSettingsStr = toObjectParamStr(fontSettings) + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + } + + rules[`.material-symbols-${key}`] = conf + let items = cg.dcss.addStylesheetRules(rules) + + items.renderAll() + } + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj) + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i] + let v = obj[k] + let last = i == fKeys.length-1 + let end = last? '': ',\n' + fontSettingsStr += `'${k}' ${v}${end}` + } + return fontSettingsStr + + } + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(',') + let v = Object.values(obj).join(',') + return `${k}@${v}` + } + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + const values = obj.values, origin = obj.origin; + console.log('render icon', obj) + + return contentInjection(obj) + } + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)) + origin.innerText += `${values.join('_')}` + } + + const getInjectClass = function(obj) { + let k = obj.props[0] + return `material-symbols-${k}` + } + + ;insertReceiver(); +})() + +;(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver) + // cg.insertReceiver(['icon'], iconReceiver) + } + } + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + console.log('Install the font', obj) + let key = titleCase(obj.values).join('+') + let family = `Material+Symbols+${key}` + let fontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + } + let familyString = toGoogleFontParamsStr(opts) + let fontStr = `family=${family}:${familyString}` + + let receiverBits = [...obj.values, 'icon'] + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver) + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null) + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings) + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + } + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0] + let rules = {} + + let fontSettingsStr = toObjectParamStr(fontSettings) + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + } + + rules[`.material-symbols-${key}`] = conf + let items = cg.dcss.addStylesheetRules(rules) + + items.renderAll() + } + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj) + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i] + let v = obj[k] + let last = i == fKeys.length-1 + let end = last? '': ',\n' + fontSettingsStr += `'${k}' ${v}${end}` + } + return fontSettingsStr + + } + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(',') + let v = Object.values(obj).join(',') + return `${k}@${v}` + } + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + const values = obj.values, origin = obj.origin; + console.log('render icon', obj) + + return contentInjection(obj) + } + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)) + origin.innerText += `${values.join('_')}` + } + + const getInjectClass = function(obj) { + let k = obj.props[0] + return `material-symbols-${k}` + } + + ;insertReceiver(); +})() + /** * # Monitor * @@ -2726,397 +3388,226 @@ const difference = function(setA, setB) { })() /* +Convert discovered nodes and bind them to a selector. The assigned classes +are the declarations assigned to the css class. -vars box. To assign key variables as accessible CSS varialbes through a js -definition. The definition is bound to DCSS, so edits to the vars manipulates -the view automatically. - - vars({ - primary: "#880000" # company red - , secondary: "#111" # dark - , accent: "red" - }) +The discovery may descend children, allowing for depth setup. -In the node, we access the vars reciever + -
-

An elk called Elk lives here.

-
+ + -Manipulating the var propagates to the view: +
- vars.primary = "#EEE" # off white ---- +Notably this may be easier as real CSS. + */ -## Secondary App - `swatch()` - and colors.js +/* The words map lists all the unique string CSS values. Each word maps to an + integer, used for the microGraph key. - Assign "colors" to a swatch of colors, each color is a function from the - colors.js module and can assign math relations to swatches. - Chaning a swatch (such as its base color), can manipulate the other - colours according to the chosen swatch type, e.g. "Diachromic". + words = { + 'all' => 0, + 'petit' => 1, + ... + } +*/ +;(()=>{ - */ -;(function(){ +class Words extends Map { + wordCounter = 1 - let cg; - let rootDeclaration = {}; - let definition = undefined - let rootRule; + getKey(f) { + let pos = words.get(f) + if(pos == undefined) { + words.set(f, this.wordCounter) + pos = this.wordCounter; + this.wordCounter++; + } + return pos; + } - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} + /* + Given a dash-split-string, return a return of resolved positions. + stringToBits('all-petite') + [0, 1] */ - const insertReceiver = function(){ - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } + stringToBits(s, sep='-') { + let items = s.split(sep) + , res = []; + items.forEach((f, j, b)=> res.push(this.getKey(f))) + return res + } - ClassGraph.addons.varsReceiver = function(_cg){ - cg = _cg; - cg.vars = varsHook.bind(cg) - // cg.varsRootDelaration = rootDeclaration - cg.varsRoot = rootRule - // cg.insertTranslator('var', variableDigest) - } + stringToNest(s, root={}) { + // split + let items = s.split('-') + // flatgraph + var place = root; + let res = place; + let il = items.length; + items.forEach((f, j, b)=>{ + let pos = this.getKey(f); + let endleaf = j == il-1 + if(place[pos] == undefined) { + place[pos] = place = endleaf? null: {} //p: pos } + } else { + // if(place[pos] == null) { + // place[pos] = {} + // } + place = place[pos]; + } + }) + return res; } + installPropArray(words){ + words.forEach((e,i,a)=>{ + // let bits = stringToNest(e, microGraph) + this.stringToNest(e, microGraph) + }) + } - const varsHook = function(d, target=':root') { - /** vars() function bound to the classgraph. _this_ is the classgraph - instance `cg.vars = varsHook.bind(cg)` + insertBitKey(s, g=microGraph) { + return this.stringToNest(s, g) + } - each key is a var, value is the param + wordsToOrderedArray() { + let res = new Array(this.size) + this.forEach((index,key,a)=>res[index] = key) + return res; + } - { - apples: green - , foo: 10 - , bar: 1em - , baz: #444 - } + wordsToArrayString(indent=0, small=false){ + if(!small) { + return JSON.stringify(this.wordsToOrderedArray(), null, indent) + } - Each var is installed on the target node: + return this.wordsToOrderedArray().join(' ') + } - :root { - --apples: green - ... - --baz: #444 - } + wordsToObjectString(indent=0, small=false) { + if(!small) { + return JSON.stringify(Object.fromEntries(this), null, indent) + } - if an existing "vars" object exists, it's updated. + let res = '' + this.forEach((e,i,a)=>res+=[i,e].join('')) + return res; + } - */ - // target = document.querySelector(target) - console.log('Hook', d) + graphToArrayListString(o=microGraph, indent=0, blank=0){ + return JSON.stringify(this.graphToArrayListRecurse(o, indent, blank)) + } - if(rootRule == undefined) { - let rootDeclaration = {}; + graphToArrayListRecurse(o=microGraph, indent=0, blank=null){ + let res = []; + let entries = Object.entries(o) + for(let pair of entries){ + let d = pair[1]; + res.push([ + parseInt(pair[0]) + , d == null? blank: this.graphToArrayListRecurse(d, indent, blank) + ]) + } + // return JSON.stringify(res, null, indent) + return res + } - for(let key in d) { - let prop = `--${key}` - let value = d[key] - rootDeclaration[prop] = value; - } + graphToObjectString(indent=0){ + let res = {} + for(let k in microGraph){ + res[parseInt(k)] = microGraph[k] + } + return JSON.stringify(res, null, indent) + } +} - let rules = cg.dcss.addStylesheetRules({ - [target]: rootDeclaration - }); +/* +1. all the items have string in position +2. the we create the flat array list +each position is a word from the string list + + "all-petite-caps", + "all-scroll", + "all-small-caps", + +as a string: + + " all petite caps scroll small ..." + +Becomes: + [1, [ + [2, [ + [3, null] + ] + ], + [4, null], + [5, [ + [3,null] + ] + ] + ] + ] - rules.renderAll() - rootRule = rules[0] - cg.varsRoot = rootRule - } else { +--- - // rootRule - // let pr = rootRule.getPropStr([target,Object.entries(definition)]) - // rootRule.sheetRule.cssText = `${target} { ${pr} }` - // rootRule.replace(`${target} { ${pr} }`) +When loaded, we can re-ask for the prop: - for(let key in d) { - let prop = `--${key}` - let value = d[key] - rootRule.sheetRule.style.setProperty(prop, value) - } - // rootRule.render() - // console.log(rootRule) - // window.varsRule = rootRule - } - } + w.stringToBits("all-petite-caps") + [1,2,3] - ;insertReceiver(); -})() - -/** - * # var-* Translate - * - * https://developer.mozilla.org/en-US/docs/Web/CSS/var - * - * Discover and rewrite class names values with `var-*` to the CSS function - * `var(*)`. e.g. - * - * "border-top-var-primary-edges" - * - * { - * "border-top": var(--primary-edges) - * } - */ -;(function(){ +The last key - let cg; + w.stringToBits("zoom") + [211] + w.stringToBits("zoom-out") + [211, 66] +--- - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // console.log('var-translate insertReceiver') - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - ClassGraph.addons.varTranslateReceiver = function(_cg){ - cg = _cg; - cg.insertTranslator('var', variableDigest2) - // cg.insertTranslator('var', variableDigest) - } - } + "all-petite-caps", + "all-scroll", + "all-small-caps", + "allow-end", + "alternate-reverse", - /** - * The handler function given to the dynamic css stylesheet, called - * when the dcss is prepared. - * - * @param {object} obj A definition generated by the class graph discovery - * @return {undefined} - */ - const variableDigest = function(splitObj, index) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ + "all petite caps scroll small allow end alternate reverse", + "0-1-2", + "0-3", + "0-4-5", + "6-7", + "8-9", - /* - This is pretty dumb, and should improve to a forward stepping - solution, detecting possible names + "all petite caps scroll small allow end alternate reverse", + "0-1-2 0-3 0-4-5 6-7 8-9" - Issue is a var can be anything `var(--1em)`. - Therefore forward feed on _possibles_ is sticky. This is valid: + "all petite caps scroll small allow end alternate reverse", + "0 1 2,0 3,0 4 5,6 7,8 9" - { - margin: var(--1em) var(--orange) - } - - Therefore break on `var` - - "margin-var-1em-var-orange" - - However `var(--var)` is valid: - { - --var: 1em - --var-orange: orange; - } - - - Meaning: - "margin-var-1em-var-var-orange" - - Therefore break on var, unless [var]+1 == var, - as then its break on var, dont break on next var, - yielding `var-orange`.` - - However also allowed: "margin-var-1em-var-var-var" - - { - --var-var: - } - - So then possibly, two dashes between `var var`` - - margin-var-key--var-var-var-var--var-var-key - - { - margin: var(key) var(var-var-var) var(var-key) - } - - Allowing the strange but valid: - { - --var-key: 1em; - --var-var-var-var: 2em; - --var-var-key: 1em solid; - } - - */ - // console.log('running on', splitObj) - // Tokenize as a family string. - values = splitObj.values - let keys = splitObj.values.slice(index) - let k1 = keys.slice(1) - let word = `var(--${k1.join("-")})` - // console.log(keys, word) - return word - // [inStack, outStack, currentIndex] = - // digestFunc(splitObj, inStack, outStack, currentIndex) - } - - - const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ - - let keys = inStack.slice(currentIndex) - let k1 = keys.slice(1) - let word = `var(--${k1.join("-")})` - - outStack.push(word) - // return [inStack, outStack, currentIndex] - return [[], outStack, currentIndex + k1.length] - } - - - - ;insertReceiver(); -})() - - - -/* The words map lists all the unique string CSS values. Each word maps to an - integer, used for the microGraph key. + // radix each key through 32 bits, allowing ~1000 positions as 2bits + // not really helpful under 100 keys, but then saves 1 char per position (up to 1k) + // .. With 255~ keys thats 150~ chars saved. + // In a 32bit radix, the first 31 positions are single chars. +--- - words = { - 'all' => 0, - 'petit' => 1, - ... - } */ -;(()=>{ - - -class Words extends Map { - wordCounter = 1 - - getKey(f) { - let pos = words.get(f) - if(pos == undefined) { - words.set(f, this.wordCounter) - pos = this.wordCounter; - this.wordCounter++; - } - return pos; - } - - /* - Given a dash-split-string, return a return of resolved positions. - stringToBits('all-petite') - [0, 1] - */ - stringToBits(s, sep='-') { - let items = s.split(sep) - , res = []; - items.forEach((f, j, b)=> res.push(this.getKey(f))) - return res - } - - stringToNest(s, root={}) { - // split - let items = s.split('-') - // flatgraph - var place = root; - let res = place; - let il = items.length; - items.forEach((f, j, b)=>{ - let pos = this.getKey(f); - let endleaf = j == il-1 - if(place[pos] == undefined) { - place[pos] = place = endleaf? null: {} //p: pos } - } else { - // if(place[pos] == null) { - // place[pos] = {} - // } - place = place[pos]; - } - }) - return res; - } - - installPropArray(words){ - words.forEach((e,i,a)=>{ - // let bits = stringToNest(e, microGraph) - this.stringToNest(e, microGraph) - }) - } - - insertBitKey(s, g=microGraph) { - return this.stringToNest(s, g) - } - - wordsToOrderedArray() { - let res = new Array(this.size) - this.forEach((index,key,a)=>res[index] = key) - return res; - } - - wordsToArrayString(indent=0, small=false){ - if(!small) { - return JSON.stringify(wordsToOrderedArray(), null, indent) - } - - return wordsToOrderedArray().join(' ') - } - - wordsToObjectString(indent=0, small=false) { - if(!small) { - return JSON.stringify(Object.fromEntries(this), null, indent) - } - - let res = '' - this.forEach((e,i,a)=>res+=[i,e].join('')) - return res; - } - - graphToArrayListString(o=microGraph, indent=0, blank=0){ - return JSON.stringify(this.graphToArrayListRecurse(o, indent, blank)) - } - - graphToArrayListRecurse(o=microGraph, indent=0, blank=null){ - let res = []; - let entries = Object.entries(o) - for(let pair of entries){ - let d = pair[1]; - res.push([ - parseInt(pair[0]) - , d == null? blank: this.graphToArrayListRecurse(d, indent, blank) - ]) - } - // return JSON.stringify(res, null, indent) - return res - } - - graphToObjectString(indent=0){ - let res = {} - for(let k in microGraph){ - res[parseInt(k)] = microGraph[k] - } - return JSON.stringify(res, null, indent) - } -} - const words = new Words() , microGraph = {} @@ -3323,61 +3814,17 @@ const words = new Words() var installReceiver = function() { - ClassGraph.addons.forwardReduceValues = (cg) => words.installPropArray(dashprops) - ClassGraph.prototype.forwardReduceValues = forwardReduceValues - ClassGraph.prototype.valuesGraph = { microGraph, words } -} - - -const arrayStringMunger = function(str) { - /* given the string, crush it futher.*/ - let dmap = { - // '[': { active: false, current: 0, max: -1} - // , ']': { active: false, current: 0, max: -1} - } - - let actives = []; - - for(let c of str) { - if(dmap[c] == undefined) { - // new position - dmap[c] = { active: false, current: -1, max: -1, total: 0} + ClassGraph.addons.forwardReduceValues = function(cg){ + let func = function(prop, values) { + return forwardReduceValues(prop, values, microGraph, words) } - - if(dmap[c].active) { - // was active. just append and continue. - dmap[c].current += 1; - } else { - // Close any alive, finalise the max. - // for(let k in dmap) { - // if(k == c) { - // // The same object doesn't turn off. - // continue - // } - // dmap[k].active = false - // dmap[k].max = Math.max(dmap[k].max, dmap[k].current) - // // We set current to 0 here (not -1), - // dmap[k].current = 0 - // } - let cStash = dmap[c].current - for(let o of actives) { - o.active = false - o.max = Math.max(o.max, o.current) - o.current = 0 - } - - actives = [dmap[c]] - dmap[c].active = true - dmap[c].total += 1 - dmap[c].current = cStash + 1; - } - } - for(let o of actives) { - o.active = false - o.max = Math.max(o.max, o.current) - o.current = 0 + cg.reducers.push(func) + let res = words.installPropArray(dashprops) + return res; } - return dmap + // install one of many + // ClassGraph.prototype.forwardReduceValues = forwardReduceValues + ClassGraph.prototype.valuesGraph = { microGraph, words } } @@ -3406,9 +3853,6 @@ const forwardReduceValues = function(props, values, microGraph, translations) { 'row': { 'reverse': merge } - , 'other': { - 'horse': merge - } } let len = values.length @@ -3468,3 +3912,272 @@ const popOneValueForward = function(values, microGraph, translations) { ;installReceiver(); })() +/** + * # var-* Translate + * + * https://developer.mozilla.org/en-US/docs/Web/CSS/var + * + * Discover and rewrite class names values with `var-*` to the CSS function + * `var(*)`. e.g. + * + * "border-top-var-primary-edges" + * + * { + * "border-top": var(--primary-edges) + * } + */ +;(function(){ + + let cg; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // console.log('var-translate insertReceiver') + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varTranslateReceiver = function(_cg){ + cg = _cg; + cg.insertTranslator('var', variableDigest2) + // cg.insertTranslator('var', variableDigest) + } + } + + /** + * The handler function given to the dynamic css stylesheet, called + * when the dcss is prepared. + * + * @param {object} obj A definition generated by the class graph discovery + * @return {undefined} + */ + const variableDigest = function(splitObj, index) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + /* + This is pretty dumb, and should improve to a forward stepping + solution, detecting possible names + + Issue is a var can be anything `var(--1em)`. + Therefore forward feed on _possibles_ is sticky. This is valid: + + { + margin: var(--1em) var(--orange) + } + + Therefore break on `var` + + "margin-var-1em-var-orange" + + However `var(--var)` is valid: + { + --var: 1em + --var-orange: orange; + } + + + Meaning: + "margin-var-1em-var-var-orange" + + Therefore break on var, unless [var]+1 == var, + as then its break on var, dont break on next var, + yielding `var-orange`.` + + However also allowed: "margin-var-1em-var-var-var" + + { + --var-var: + } + + So then possibly, two dashes between `var var`` + + margin-var-key--var-var-var-var--var-var-key + + { + margin: var(key) var(var-var-var) var(var-key) + } + + Allowing the strange but valid: + { + --var-key: 1em; + --var-var-var-var: 2em; + --var-var-key: 1em solid; + } + + */ + // console.log('running on', splitObj) + // Tokenize as a family string. + values = splitObj.values + let keys = splitObj.values.slice(index) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + // console.log(keys, word) + return word + // [inStack, outStack, currentIndex] = + // digestFunc(splitObj, inStack, outStack, currentIndex) + } + + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + + + ;insertReceiver(); +})() + +/* + +vars box. To assign key variables as accessible CSS varialbes through a js +definition. The definition is bound to DCSS, so edits to the vars manipulates +the view automatically. + + vars({ + primary: "#880000" # company red + , secondary: "#111" # dark + , accent: "red" + }) + +In the node, we access the vars reciever + +
+

An elk called Elk lives here.

+
+ +Manipulating the var propagates to the view: + + vars.primary = "#EEE" # off white + +--- + +## Secondary App + + `swatch()` + and colors.js + + Assign "colors" to a swatch of colors, each color is a function from the + colors.js module and can assign math relations to swatches. + Chaning a swatch (such as its base color), can manipulate the other + colours according to the chosen swatch type, e.g. "Diachromic". + + */ + +;(function(){ + + let cg; + let rootDeclaration = {}; + let definition = undefined + let rootRule; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varsReceiver = function(_cg){ + cg = _cg; + cg.vars = varsHook.bind(cg) + // cg.varsRootDelaration = rootDeclaration + cg.varsRoot = rootRule + // cg.insertTranslator('var', variableDigest) + } + } + + + const varsHook = function(d, target=':root') { + /** vars() function bound to the classgraph. _this_ is the classgraph + instance `cg.vars = varsHook.bind(cg)` + + each key is a var, value is the param + + { + apples: green + , foo: 10 + , bar: 1em + , baz: #444 + } + + Each var is installed on the target node: + + :root { + --apples: green + ... + --baz: #444 + } + + if an existing "vars" object exists, it's updated. + + */ + // target = document.querySelector(target) + console.log('Hook', d) + + if(rootRule == undefined) { + let rootDeclaration = {}; + + for(let key in d) { + let prop = `--${key}` + let value = d[key] + rootDeclaration[prop] = value; + } + + let rules = cg.dcss.addStylesheetRules({ + [target]: rootDeclaration + }); + + rules.renderAll() + rootRule = rules[0] + cg.varsRoot = rootRule + } else { + + // rootRule + // let pr = rootRule.getPropStr([target,Object.entries(definition)]) + // rootRule.sheetRule.cssText = `${target} { ${pr} }` + // rootRule.replace(`${target} { ${pr} }`) + + for(let key in d) { + let prop = `--${key}` + let value = d[key] + rootRule.sheetRule.style.setProperty(prop, value) + } + // rootRule.render() + // console.log(rootRule) + // window.varsRule = rootRule + } + } + + ;insertReceiver(); +})() + diff --git a/dist/addons.all.js b/dist/addons.all.js index c055873..63da1c2 100755 --- a/dist/addons.all.js +++ b/dist/addons.all.js @@ -1 +1 @@ -!function(){let e;const t=function(e,t){values=e.values;let[r,...o]=e.values;if(void 0!==document[`on${r}`]){const t=e.origin;n(e,t,r,o)}else console.warn("Unknown action",r)},n=function(e,t,n,o){let l=e=>r(e,n,o),s=`polyaction_${n}`;void 0===t.dataset[s]?(t.addEventListener(n,l),t.dataset[s]=!0):console.log("Event already exists:",n)},r=function(e,t,n){let[r,...o]=n;console.log(e,t,n),console.log(r,o);let l={call(){},toggle(){console.log(o,n,t),e.currentTarget.classList.toggle(o.join("-"))},setvar(){}}[r];l&&l()};console.log("event receiver"),ClassGraph.addons.eventsReceiver=function(n){e=n,e.insertReceiver(["event"],t)}}(),function(){let e;const t=function(e){const t=e.values,r=e.origin;let l=s(t,r,e),i=o(t,l,r);c(i).forEach((e=>document.head.appendChild(e))),n(l)},n=function(t,n){for(let n of Object.values(t)){let t=n.first,o=(e,t)=>t?" ":"",s=r(t.replace(/[+]/g,o));n.cleanName=s,n.definition=l(n),e.dcss.addStylesheetRules(n.definition).renderAll()}},r=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},o=function(e,t,n){t=t||s(e,n);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},l=function(t){let n={};const r=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let o={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},o);t.isItal&&(e["font-style"]="italic");let s=l.concat([t.token]);n[`${r(s)}, ${r(s).toLowerCase()}`]=e}}let o=r(["font",t.first]),l=r(["font"].concat(t.first.split("+"))),s=new Set([o,l,o.toLowerCase(),l.toLowerCase()]);return n[Array.from(s).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},n},s=function(t,n,r){let o,l=0,s={},a=/([a-zA-Z-]{0,}?)(\d+)/,c=function(t,n){return e.filterSplit(n,t,!0)}(["default"],r?.origin||n),u="sans-serif",f=c.default;if(f)if(f.index<=r.index){let e="font default-* modifier should be indexed after font";console["warn"](e),u=f.values.join(" ")}else u=f.values.join(" ");for(let e in t){let n=t[e];if(0==l){s[l]={first:n,tokens:{},defaultFonts:u},o=l,l++;continue}let[r,i]=[null,null];try{let e;[e,r,i]=n.match(a),0==r.length&&(r="r")}catch{s[l]={first:n,tokens:{}},o=l,l++;continue}let c={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},f={int:Number(i)};if(0==f.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in r){let t=c[r[e]];Object.assign(f,t())}let d=s[o]?.tokens[i]||{};Object.assign(d,f),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:f.ital,token:n}),s[o].tokens[i]=d,l++}return i(s)},i=function(e){for(let t in e){let n=e[t];0!=n.first.length&&a(n)}return e},a=function(e){let t=r(e.first),n=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),o=Object.assign({},...n),l=null!=o.ital,s=[],i=new Set;l&&s.push("ital"),(l||o.regu)&&s.push("wght");for(let t in e.tokens){let n=e.tokens[t],r=n.ital?1:0,o=n.int,s=l?[r]:[];s.push(o);let a=s.join(",");if(i.add(a),null!=n.regu){let e=l?[0]:[];e.push(o);let t=e.join(",");i.add(t)}}let a=Array.from(i).sort(),c=a.join(";"),u=`${t}:${s.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:s,titleToken:t,str:u})},c=function(e){return[f("link","preconnect",{href:"https://fonts.googleapis.com"}),f("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),f("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}&display=swap`})]};let u={};const f=function(e,t,n){let r={rel:t,href:e};Object.assign(r,n||{});let o=JSON.stringify,l=u[o(r)];return l||(u[o(r)]=d("link",r))},d=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(e);for(let e in t)n.setAttribute(e,t[e]);return n};DynamicCSSStyleSheet.addons.fontPackReceiver=function(n){e=n,e.insertReceiver(["font","pack"],t)}}(),(()=>{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&n(e)},r=new MutationObserver((function(e){e.forEach(t)}));return r.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),r},n=function(t){let n=t.target.classList.value,o=t.oldValue,l=n.split(/(?!\(.*)\s(?![^(]*?\))/g),s=null==o?[]:o.split(" ").map((e=>e.trim())),i=s?r(l,s):l;console.log("new",i),e.captureChanges(i,s,t.target)},r=function(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n};ClassGraph.addons.monitorClasses=function(t){e=t},ClassGraph.prototype.monitor=function(e=document.body){return t(e)}})(),function(){let e,t;const n=function(n,r=":root"){if(console.log("Hook",n),null==t){let o={};for(let e in n){let t=`--${e}`,r=n[e];o[t]=r}let l=e.dcss.addStylesheetRules({[r]:o});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in n){let r=`--${e}`,o=n[e];t.sheetRule.style.setProperty(r,o)}};ClassGraph.addons.varsReceiver=function(r){e=r,e.vars=n.bind(e),e.varsRoot=t}}(),function(){let e;const t=function(e,t,n,r){let o=t.slice(r).slice(1),l=`var(--${o.join("-")})`;return n.push(l),[[],n,r+o.length]};ClassGraph.addons.varTranslateReceiver=function(n){e=n,e.insertTranslator("var",t)}}(),(()=>{class e extends Map{wordCounter=1;getKey(e){let n=t.get(e);return null==n&&(t.set(e,this.wordCounter),n=this.wordCounter,this.wordCounter++),n}stringToBits(e,t="-"){let n=e.split(t),r=[];return n.forEach(((e,t,n)=>r.push(this.getKey(e)))),r}stringToNest(e,t={}){let n=e.split("-");var r=t;let o=r,l=n.length;return n.forEach(((e,t,n)=>{let o=this.getKey(e),s=t==l-1;null==r[o]?r[o]=r=s?null:{}:r=r[o]})),o}installPropArray(e){e.forEach(((e,t,r)=>{this.stringToNest(e,n)}))}insertBitKey(e,t=n){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,n,r)=>e[t]=n)),e}wordsToArrayString(e=0,t=!1){return t?wordsToOrderedArray().join(" "):JSON.stringify(wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let n="";return this.forEach(((e,t,r)=>n+=[t,e].join(""))),n}graphToArrayListString(e=n,t=0,r=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,r))}graphToArrayListRecurse(e=n,t=0,r=null){let o=[],l=Object.entries(e);for(let e of l){let n=e[1];o.push([parseInt(e[0]),null==n?r:this.graphToArrayListRecurse(n,t,r)])}return o}graphToObjectString(e=0){let t={};for(let e in n)t[parseInt(e)]=n[e];return JSON.stringify(t,null,e)}}const t=new e,n={},r=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const o=function(e,t,n,r){const o=e=>e.join("-"),s=n||{row:{reverse:o},other:{horse:o}};let i=t.length,a=0,c=t.length+1,u=0,f=[];for(;ae.join("-");let n=o[r];return null==n&&(n=t),[n(e.slice(0,i+1)),i+1]}return[e[0],1]};ClassGraph.addons.forwardReduceValues=e=>t.installPropArray(r),ClassGraph.prototype.forwardReduceValues=o,ClassGraph.prototype.valuesGraph={microGraph:n,words:t}})(); +const e=function(e){return o(e)||r(e)||t(e)||n(e)},t=function(t){let n=t.split("/");return 2==n.length&&(e(n[0])&&o(n[1]))},n=function(e){let t=new Set(["deg","grad","rad","turn"]),n=e.slice(parseFloat(e).toString().length,e.length);return t.has(n)},r=function(e){return e.endsWith("%")&&o(e.slice(0,e.length-1))},o=function(e){if(null==e||0==e.length)return!1;return!isNaN(Number(e))},l=function(e){let t=e.slice(4,5),n="";return t.length>0&&(n=`/${t}`),`${e[0]}(${e.slice(1,4).join(" ")}${n})`},s=function(e,t,n,r=void 0){let o=t.length,l=0,s=t.length+1,a=0,c=[];for(;ln.has(e),c=t.length,u=[],f=[],d=[];for(;ir(e,n,o),s=`polyaction_${n}`;void 0===t.dataset[s]?(t.addEventListener(n,l),t.dataset[s]=!0):console.log("Event already exists:",n)},r=function(e,t,n){let[r,...o]=n;console.log(e,t,n),console.log(r,o);let l={call(){},toggle(){console.log(o,n,t),e.currentTarget.classList.toggle(o.join("-"))},setvar(){}}[r];l&&l()};console.log("event receiver"),ClassGraph.addons.eventsReceiver=function(n){e=n,e.insertReceiver(["event"],t)}}(),function(){let e;const t=function(e){const t=e.values,o=e.origin;let s=i(t,o,e),a=l(t,s,o);n(a),r(s)},n=function(e,t){return u(e,t).forEach((e=>document.head.appendChild(e)))},r=function(t,n){for(let n of Object.values(t)){let t=n.first,r=(e,t)=>t?" ":"",l=o(t.replace(/[+]/g,r));n.cleanName=l,n.definition=s(n),e.dcss.addStylesheetRules(n.definition).renderAll()}},o=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},l=function(e,t,n){t=t||i(e,n);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},s=function(t){let n={};const r=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let o={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},o);t.isItal&&(e["font-style"]="italic");let s=l.concat([t.token]);n[`${r(s)}, ${r(s).toLowerCase()}`]=e}}let o=r(["font",t.first]),l=r(["font"].concat(t.first.split("+"))),s=new Set([o,l,o.toLowerCase(),l.toLowerCase()]);return n[Array.from(s).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},n},i=function(t,n,r){let o,l=0,s={},i=/([a-zA-Z-]{0,}?)(\d+)/,c=function(t,n){return e.filterSplit(n,t,!0)}(["default"],r?.origin||n),u="sans-serif",f=c.default;if(f)if(f.index<=r.index){let e="font default-* modifier should be indexed after font";console["warn"](e),u=f.values.join(" ")}else u=f.values.join(" ");for(let e in t){let n=t[e];if(0==l){s[l]={first:n,tokens:{},defaultFonts:u},o=l,l++;continue}let[r,a]=[null,null];try{let e;[e,r,a]=n.match(i),0==r.length&&(r="r")}catch{s[l]={first:n,tokens:{}},o=l,l++;continue}let c={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},f={int:Number(a)};if(0==f.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in r){let t=c[r[e]];Object.assign(f,t())}let d=s[o]?.tokens[a]||{};Object.assign(d,f),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:f.ital,token:n}),s[o].tokens[a]=d,l++}return a(s)},a=function(e){for(let t in e){let n=e[t];0!=n.first.length&&c(n)}return e},c=function(e){let t=o(e.first),n=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),r=Object.assign({},...n),l=null!=r.ital,s=[],i=new Set;l&&s.push("ital"),(l||r.regu)&&s.push("wght");for(let t in e.tokens){let n=e.tokens[t],r=n.ital?1:0,o=n.int,s=l?[r]:[];s.push(o);let a=s.join(",");if(i.add(a),null!=n.regu){let e=l?[0]:[];e.push(o);let t=e.join(",");i.add(t)}}let a=Array.from(i).sort(),c=a.join(";"),u=`${t}:${s.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:s,titleToken:t,str:u})},u=function(e,t="swap"){return[d("link","preconnect",{href:"https://fonts.googleapis.com"}),d("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),d("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}${null==t?"":`&display=${t}`}`})]};let f={};const d=function(e,t,n){let r={rel:t,href:e};Object.assign(r,n||{});let o=JSON.stringify,l=f[o(r)];return l||(f[o(r)]=h("link",r))},h=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(e);for(let e in t)n.setAttribute(e,t[e]);return n};DynamicCSSStyleSheet.addons.fontPackReceiver=function(n){e=n,e.insertReceiver(["font","pack"],t)},ClassGraph.prototype.generateGoogleLinks=u,ClassGraph.prototype.installGoogleLinks=n}(),function(){let e;const t=function(e,t,n,r){return t.value.slice(0,t.match.start),t.args.length>0?t.args[0]:"green"},n=function(e,t,n,r){console.log("raise hook",t,r);let o=t.value.slice(0,t.match.start);console.log(o)};ClassGraph.addons.functionsReceiver=function(r){e=r,e.keyValueFunctions.set("forceGreen",t),e.keyValueFunctions.set("force",t),e.keyValueFunctions.set("raise",n)}}(),function(){let e;const t=function(t){var r;let s=`family=${`Material+Symbols+${(r=t.values,r.map((function(e){return e.charAt(0).toUpperCase()+e.substring(1,e.length)}))).join("+")}`}:${o({opsz:"20..48",wght:"100..700",FILL:"0..1",GRAD:"-50..200"})}`,i=[...t.values,"icon"];e.insertReceiver(i,l),Polyclass.graph.installGoogleLinks(s,null),n(t,fontSettings)},n=function(t,n){let o=t.values[0],l={},s={"font-variation-settings":`${r(n)}`,"font-size":"inherit"};l[`.material-symbols-${o}`]=s,e.dcss.addStylesheetRules(l).renderAll()},r=function(e){let t="",n=Object.keys(e);for(var r=0;r{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&n(e)},r=new MutationObserver((function(e){e.forEach(t)}));return r.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),r},n=function(t){let n=t.target.classList.value,o=t.oldValue,l=n.split(/(?!\(.*)\s(?![^(]*?\))/g),s=null==o?[]:o.split(" ").map((e=>e.trim())),i=s?r(l,s):l;console.log("new",i),e.captureChanges(i,s,t.target)},r=function(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n};ClassGraph.addons.monitorClasses=function(t){e=t},ClassGraph.prototype.monitor=function(e=document.body){return t(e)}})(),(()=>{class e extends Map{wordCounter=1;getKey(e){let n=t.get(e);return null==n&&(t.set(e,this.wordCounter),n=this.wordCounter,this.wordCounter++),n}stringToBits(e,t="-"){let n=e.split(t),r=[];return n.forEach(((e,t,n)=>r.push(this.getKey(e)))),r}stringToNest(e,t={}){let n=e.split("-");var r=t;let o=r,l=n.length;return n.forEach(((e,t,n)=>{let o=this.getKey(e),s=t==l-1;null==r[o]?r[o]=r=s?null:{}:r=r[o]})),o}installPropArray(e){e.forEach(((e,t,r)=>{this.stringToNest(e,n)}))}insertBitKey(e,t=n){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,n,r)=>e[t]=n)),e}wordsToArrayString(e=0,t=!1){return t?this.wordsToOrderedArray().join(" "):JSON.stringify(this.wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let n="";return this.forEach(((e,t,r)=>n+=[t,e].join(""))),n}graphToArrayListString(e=n,t=0,r=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,r))}graphToArrayListRecurse(e=n,t=0,r=null){let o=[],l=Object.entries(e);for(let e of l){let n=e[1];o.push([parseInt(e[0]),null==n?r:this.graphToArrayListRecurse(n,t,r)])}return o}graphToObjectString(e=0){let t={};for(let e in n)t[parseInt(e)]=n[e];return JSON.stringify(t,null,e)}}const t=new e,n={},r=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const o=function(e,t,n,r){const o=n||{row:{reverse:e=>e.join("-")}};let s=t.length,i=0,a=t.length+1,c=0,u=[];for(;ie.join("-");let n=o[r];return null==n&&(n=t),[n(e.slice(0,i+1)),i+1]}return[e[0],1]};ClassGraph.addons.forwardReduceValues=function(e){return e.reducers.push((function(e,r){return o(e,r,n,t)})),t.installPropArray(r)},ClassGraph.prototype.valuesGraph={microGraph:n,words:t}})(),function(){let e;const t=function(e,t,n,r){let o=t.slice(r).slice(1),l=`var(--${o.join("-")})`;return n.push(l),[[],n,r+o.length]};ClassGraph.addons.varTranslateReceiver=function(n){e=n,e.insertTranslator("var",t)}}(),function(){let e,t;const n=function(n,r=":root"){if(console.log("Hook",n),null==t){let o={};for(let e in n){let t=`--${e}`,r=n[e];o[t]=r}let l=e.dcss.addStylesheetRules({[r]:o});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in n){let r=`--${e}`,o=n[e];t.sheetRule.style.setProperty(r,o)}};ClassGraph.addons.varsReceiver=function(r){e=r,e.vars=n.bind(e),e.varsRoot=t}}(); diff --git a/dist/addons/color-values.js b/dist/addons/color-values.js new file mode 100755 index 0000000..aa8f52b --- /dev/null +++ b/dist/addons/color-values.js @@ -0,0 +1 @@ +const e=function(e){return r(e)||l(e)||t(e)||n(e)},t=function(t){let n=t.split("/");return 2==n.length&&(e(n[0])&&r(n[1]))},n=function(e){let t=new Set(["deg","grad","rad","turn"]),n=e.slice(parseFloat(e).toString().length,e.length);return t.has(n)},l=function(e){return e.endsWith("%")&&r(e.slice(0,e.length-1))},r=function(e){if(null==e||0==e.length)return!1;return!isNaN(Number(e))},u=function(e){let t=e.slice(4,5),n="";return t.length>0&&(n=`/${t}`),`${e[0]}(${e.slice(1,4).join(" ")}${n})`},i=function(e,t,n,l=void 0){let r=t.length,u=0,i=t.length+1,s=0,o=[];for(;un.has(e),o=t.length,c=[],g=[],f=[];for(;hdocument.head.appendChild(t))),n(l)},n=function(e,n){for(let n of Object.values(e)){let e=n.first,o=(t,e)=>e?" ":"",r=i(e.replace(/[+]/g,o));n.cleanName=r,n.definition=l(n),t.dcss.addStylesheetRules(n.definition).renderAll()}},i=function(t){return t.replace(/(^|[\s+])\S/g,(function(t){return t.toUpperCase()}))},o=function(t,e,n){e=e||r(t,n);return Object.values(e).flatMap((t=>function(t){return`family=${t.str}`}(t))).join("&")},l=function(e){let n={};const i=t.asSelectorString.bind(t);for(let t of Object.values(e.tokens)){let o={"font-weight":t.int,"font-family":`'${e.cleanName}', ${e.defaultFonts}`},l=["font",e.first];for(let e of t.keys){let t=Object.assign({},o);e.isItal&&(t["font-style"]="italic");let r=l.concat([e.token]);n[`${i(r)}, ${i(r).toLowerCase()}`]=t}}let o=i(["font",e.first]),l=i(["font"].concat(e.first.split("+"))),r=new Set([o,l,o.toLowerCase(),l.toLowerCase()]);return n[Array.from(r).join(", ")]={"font-family":`'${e.cleanName}', ${e.defaultFonts}`},n},r=function(e,n,i){let o,l=0,r={},f=/([a-zA-Z-]{0,}?)(\d+)/,a=function(e,n){return t.filterSplit(n,e,!0)}(["default"],i?.origin||n),c="sans-serif",u=a.default;if(u)if(u.index<=i.index){let t="font default-* modifier should be indexed after font";console["warn"](t),c=u.values.join(" ")}else c=u.values.join(" ");for(let t in e){let n=e[t];if(0==l){r[l]={first:n,tokens:{},defaultFonts:c},o=l,l++;continue}let[i,s]=[null,null];try{let t;[t,i,s]=n.match(f),0==i.length&&(i="r")}catch{r[l]={first:n,tokens:{}},o=l,l++;continue}let a={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},u={int:Number(s)};if(0==u.int){console.warn("Skipping zero weighted item"),l++;continue}for(let t in i){let e=a[i[t]];Object.assign(u,e())}let d=r[o]?.tokens[s]||{};Object.assign(d,u),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:u.ital,token:n}),r[o].tokens[s]=d,l++}return s(r)},s=function(t){for(let e in t){let n=t[e];0!=n.first.length&&f(n)}return t},f=function(t){let e=i(t.first),n=function(t){return 0==Object.values(t.tokens).length&&(t.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(t.tokens)}(t),o=Object.assign({},...n),l=null!=o.ital,r=[],s=new Set;l&&r.push("ital"),(l||o.regu)&&r.push("wght");for(let e in t.tokens){let n=t.tokens[e],i=n.ital?1:0,o=n.int,r=l?[i]:[];r.push(o);let f=r.join(",");if(s.add(f),null!=n.regu){let t=l?[0]:[];t.push(o);let e=t.join(",");s.add(e)}}let f=Array.from(s).sort(),a=f.join(";"),c=`${e}:${r.join(",")}@${a}`;Object.assign(t,{weights:f,formatStringParts:r,titleToken:e,str:c})},a=function(t){return[u("link","preconnect",{href:"https://fonts.googleapis.com"}),u("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),u("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${t}&display=swap`})]};let c={};const u=function(t,e,n){let i={rel:e,href:t};Object.assign(i,n||{});let o=JSON.stringify,l=c[o(i)];return l||(c[o(i)]=d("link",i))},d=function(t,e){if(null==e&&"string"!=typeof t&&null==(t=(e=t).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(t);for(let t in e)n.setAttribute(t,e[t]);return n};DynamicCSSStyleSheet.addons.fontPackReceiver=function(n){t=n,t.insertReceiver(["font","pack"],e)}}(); +!function(){let t;const e=function(t){const e=t.values,i=t.origin;let r=s(e,i,t),a=l(e,r,i);n(a),o(r)},n=function(t,e){return u(t,e).forEach((t=>document.head.appendChild(t)))},o=function(e,n){for(let n of Object.values(e)){let e=n.first,o=(t,e)=>e?" ":"",l=i(e.replace(/[+]/g,o));n.cleanName=l,n.definition=r(n),t.dcss.addStylesheetRules(n.definition).renderAll()}},i=function(t){return t.replace(/(^|[\s+])\S/g,(function(t){return t.toUpperCase()}))},l=function(t,e,n){e=e||s(t,n);return Object.values(e).flatMap((t=>function(t){return`family=${t.str}`}(t))).join("&")},r=function(e){let n={};const o=t.asSelectorString.bind(t);for(let t of Object.values(e.tokens)){let i={"font-weight":t.int,"font-family":`'${e.cleanName}', ${e.defaultFonts}`},l=["font",e.first];for(let e of t.keys){let t=Object.assign({},i);e.isItal&&(t["font-style"]="italic");let r=l.concat([e.token]);n[`${o(r)}, ${o(r).toLowerCase()}`]=t}}let i=o(["font",e.first]),l=o(["font"].concat(e.first.split("+"))),r=new Set([i,l,i.toLowerCase(),l.toLowerCase()]);return n[Array.from(r).join(", ")]={"font-family":`'${e.cleanName}', ${e.defaultFonts}`},n},s=function(e,n,o){let i,l=0,r={},s=/([a-zA-Z-]{0,}?)(\d+)/,f=function(e,n){return t.filterSplit(n,e,!0)}(["default"],o?.origin||n),u="sans-serif",c=f.default;if(c)if(c.index<=o.index){let t="font default-* modifier should be indexed after font";console["warn"](t),u=c.values.join(" ")}else u=c.values.join(" ");for(let t in e){let n=e[t];if(0==l){r[l]={first:n,tokens:{},defaultFonts:u},i=l,l++;continue}let[o,a]=[null,null];try{let t;[t,o,a]=n.match(s),0==o.length&&(o="r")}catch{r[l]={first:n,tokens:{}},i=l,l++;continue}let f={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},c={int:Number(a)};if(0==c.int){console.warn("Skipping zero weighted item"),l++;continue}for(let t in o){let e=f[o[t]];Object.assign(c,e())}let d=r[i]?.tokens[a]||{};Object.assign(d,c),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:c.ital,token:n}),r[i].tokens[a]=d,l++}return a(r)},a=function(t){for(let e in t){let n=t[e];0!=n.first.length&&f(n)}return t},f=function(t){let e=i(t.first),n=function(t){return 0==Object.values(t.tokens).length&&(t.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(t.tokens)}(t),o=Object.assign({},...n),l=null!=o.ital,r=[],s=new Set;l&&r.push("ital"),(l||o.regu)&&r.push("wght");for(let e in t.tokens){let n=t.tokens[e],o=n.ital?1:0,i=n.int,r=l?[o]:[];r.push(i);let a=r.join(",");if(s.add(a),null!=n.regu){let t=l?[0]:[];t.push(i);let e=t.join(",");s.add(e)}}let a=Array.from(s).sort(),f=a.join(";"),u=`${e}:${r.join(",")}@${f}`;Object.assign(t,{weights:a,formatStringParts:r,titleToken:e,str:u})},u=function(t,e="swap"){return[d("link","preconnect",{href:"https://fonts.googleapis.com"}),d("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),d("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${t}${null==e?"":`&display=${e}`}`})]};let c={};const d=function(t,e,n){let o={rel:e,href:t};Object.assign(o,n||{});let i=JSON.stringify,l=c[i(o)];return l||(c[i(o)]=g("link",o))},g=function(t,e){if(null==e&&"string"!=typeof t&&null==(t=(e=t).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(t);for(let t in e)n.setAttribute(t,e[t]);return n};DynamicCSSStyleSheet.addons.fontPackReceiver=function(n){t=n,t.insertReceiver(["font","pack"],e)},ClassGraph.prototype.generateGoogleLinks=u,ClassGraph.prototype.installGoogleLinks=n}(); diff --git a/dist/addons/functions.js b/dist/addons/functions.js new file mode 100755 index 0000000..ef95133 --- /dev/null +++ b/dist/addons/functions.js @@ -0,0 +1 @@ +!function(){let e;const n=function(e,n,t,s){return n.value.slice(0,n.match.start),n.args.length>0?n.args[0]:"green"},t=function(e,n,t,s){console.log("raise hook",n,s);let o=n.value.slice(0,n.match.start);console.log(o)};ClassGraph.addons.functionsReceiver=function(s){e=s,e.keyValueFunctions.set("forceGreen",n),e.keyValueFunctions.set("force",n),e.keyValueFunctions.set("raise",t)}}(); diff --git a/dist/addons/google-icon-injector-classy.js b/dist/addons/google-icon-injector-classy.js new file mode 100755 index 0000000..7bf14e9 --- /dev/null +++ b/dist/addons/google-icon-injector-classy.js @@ -0,0 +1 @@ +!function(){let n;const e=function(e){var i;let l=`family=${`Material+Symbols+${(i=e.values,i.map((function(n){return n.charAt(0).toUpperCase()+n.substring(1,n.length)}))).join("+")}`}:${s({opsz:"20..48",wght:"100..700",FILL:"0..1",GRAD:"-50..200"})}`,r=[...e.values,"icon"];n.insertReceiver(r,o),Polyclass.graph.installGoogleLinks(l,null),t(e,fontSettings)},t=function(e,t){let s=e.values[0],o={},l={"font-variation-settings":`${i(t)}`,"font-size":"inherit"};o[`.material-symbols-${s}`]=l,n.dcss.addStylesheetRules(o).renderAll()},i=function(n){let e="",t=Object.keys(n);for(var i=0;i{class e extends Map{wordCounter=1;getKey(e){let t=r.get(e);return null==t&&(r.set(e,this.wordCounter),t=this.wordCounter,this.wordCounter++),t}stringToBits(e,r="-"){let t=e.split(r),o=[];return t.forEach(((e,r,t)=>o.push(this.getKey(e)))),o}stringToNest(e,r={}){let t=e.split("-");var o=r;let a=o,n=t.length;return t.forEach(((e,r,t)=>{let a=this.getKey(e),s=r==n-1;null==o[a]?o[a]=o=s?null:{}:o=o[a]})),a}installPropArray(e){e.forEach(((e,r,o)=>{this.stringToNest(e,t)}))}insertBitKey(e,r=t){return this.stringToNest(e,r)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((r,t,o)=>e[r]=t)),e}wordsToArrayString(e=0,r=!1){return r?wordsToOrderedArray().join(" "):JSON.stringify(wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,r=!1){if(!r)return JSON.stringify(Object.fromEntries(this),null,e);let t="";return this.forEach(((e,r,o)=>t+=[r,e].join(""))),t}graphToArrayListString(e=t,r=0,o=0){return JSON.stringify(this.graphToArrayListRecurse(e,r,o))}graphToArrayListRecurse(e=t,r=0,o=null){let a=[],n=Object.entries(e);for(let e of n){let t=e[1];a.push([parseInt(e[0]),null==t?o:this.graphToArrayListRecurse(t,r,o)])}return a}graphToObjectString(e=0){let r={};for(let e in t)r[parseInt(e)]=t[e];return JSON.stringify(r,null,e)}}const r=new e,t={},o=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const a=function(e,r,t,o){const a=e=>e.join("-"),s=t||{row:{reverse:a},other:{horse:a}};let i=r.length,l=0,u=r.length+1,c=0,p=[];for(;le.join("-");let t=a[o];return null==t&&(t=r),[t(e.slice(0,i+1)),i+1]}return[e[0],1]};ClassGraph.addons.forwardReduceValues=e=>r.installPropArray(o),ClassGraph.prototype.forwardReduceValues=a,ClassGraph.prototype.valuesGraph={microGraph:t,words:r}})(); +(()=>{class e extends Map{wordCounter=1;getKey(e){let t=r.get(e);return null==t&&(r.set(e,this.wordCounter),t=this.wordCounter,this.wordCounter++),t}stringToBits(e,r="-"){let t=e.split(r),o=[];return t.forEach(((e,r,t)=>o.push(this.getKey(e)))),o}stringToNest(e,r={}){let t=e.split("-");var o=r;let n=o,a=t.length;return t.forEach(((e,r,t)=>{let n=this.getKey(e),s=r==a-1;null==o[n]?o[n]=o=s?null:{}:o=o[n]})),n}installPropArray(e){e.forEach(((e,r,o)=>{this.stringToNest(e,t)}))}insertBitKey(e,r=t){return this.stringToNest(e,r)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((r,t,o)=>e[r]=t)),e}wordsToArrayString(e=0,r=!1){return r?this.wordsToOrderedArray().join(" "):JSON.stringify(this.wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,r=!1){if(!r)return JSON.stringify(Object.fromEntries(this),null,e);let t="";return this.forEach(((e,r,o)=>t+=[r,e].join(""))),t}graphToArrayListString(e=t,r=0,o=0){return JSON.stringify(this.graphToArrayListRecurse(e,r,o))}graphToArrayListRecurse(e=t,r=0,o=null){let n=[],a=Object.entries(e);for(let e of a){let t=e[1];n.push([parseInt(e[0]),null==t?o:this.graphToArrayListRecurse(t,r,o)])}return n}graphToObjectString(e=0){let r={};for(let e in t)r[parseInt(e)]=t[e];return JSON.stringify(r,null,e)}}const r=new e,t={},o=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const n=function(e,r,t,o){const n=t||{row:{reverse:e=>e.join("-")}};let s=r.length,i=0,l=r.length+1,u=0,c=[];for(;ie.join("-");let t=n[o];return null==t&&(t=r),[t(e.slice(0,i+1)),i+1]}return[e[0],1]};ClassGraph.addons.forwardReduceValues=function(e){return e.reducers.push((function(e,o){return n(e,o,t,r)})),r.installPropArray(o)},ClassGraph.prototype.valuesGraph={microGraph:t,words:r}})(); diff --git a/dist/browser/cjs/polyclass-core.cjs b/dist/browser/cjs/polyclass-core.cjs index 42abd99..9223b34 100755 --- a/dist/browser/cjs/polyclass-core.cjs +++ b/dist/browser/cjs/polyclass-core.cjs @@ -168,17 +168,17 @@ console.log(blendedcolor, blendedcolor2); })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -384,10 +384,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -532,6 +532,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -540,7 +541,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -550,8 +551,38 @@ class ClassGraph { this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); } + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); + } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -815,13 +846,13 @@ class ClassGraph { let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -836,7 +867,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -1609,13 +1646,21 @@ ClassGraph.addons = {}; // } +/* DOM Loader -/* - Upon document load, process and *[polyclass] entity. Similar to process() +Upon document load, process and *[polyclass] entity. Similar to process() + + */ const autoActivator = function(watch=document){ + // console.log('dom-property-activator ready') + if(["complete", "interactive"].indexOf(document.readyState) > -1) { + // console.log('dom-property-activator call early') + onDomLoaded(); + } watch.addEventListener('DOMContentLoaded', function(){ + // console.log('dom-property-activator called') onDomLoaded(); }.bind(this)); }; @@ -1643,6 +1688,7 @@ const onDomLoaded = function() { } }; +// console.log('Installing dom-property-activator') autoActivator(); /** diff --git a/dist/browser/cjs/polyclass-core.min.cjs b/dist/browser/cjs/polyclass-core.min.cjs index 529f2cf..1d11ce5 100755 --- a/dist/browser/cjs/polyclass-core.min.cjs +++ b/dist/browser/cjs/polyclass-core.min.cjs @@ -1 +1 @@ -"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,S,b),blendedcolor2=f(-.8,S,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){return t}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},n=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),s=new a({target:t,isInline:!0});i.set(e,s)}};!function(e=document){e.addEventListener("DOMContentLoaded",function(){n()}.bind(this))}();class l{constructor([e]=[]){this.units=i;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return i.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const i=new Map,o={safeSpace:{units:i,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new l(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o); +"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},i=function(e,t,s){let r=e>>t;return s?r&s:r},l=function(e,t,s,r){let n=i(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,i,l){return c=(d=e<0)?-1*e:e,i.length>7?function(e,r,i){let l=r.split(","),a=n(i),h=a.split(","),c=t(l[0].slice(4)),d=t(l[1]),u=t(l[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,i,l):function(e,s,n){var i=t(s.slice(1),16),l=r(n).slice(1),o=t(l,16),a=p(i,o,16,0),h=p(i,o,8,255),c=p(i,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,i,l)}function p(e,t,s,r){let n=i(e,s,r);return l(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,i=parseInt;if(t.length>7){var l=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=i(l[0].slice(4)),h=i(l[1]),c=i(l[2]);return"rgb("+(n((i(o[0].slice(4))-a)*r)+a)+","+(n((i(o[1])-h)*r)+h)+","+(n((i(o[2])-c)*r)+c)+")"}var d=(l=i(t.slice(1),16))>>16,u=l>>8&255,p=255&l;return"#"+(16777216+65536*(n((((o=i((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=u(-.8,S,v),blendedcolor2=f(-.8,S,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,i=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){let n=e,i=t;for(let e of this.reducers){i=e(n,i)}return i}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let i,l=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:i,valid:!1};for(let e of n)if(i=o[l][e],a+=1,null!=i){if(!0===i.leaf){let e=n[a],t=i[l];if(null==(t&&t[e]))break}o=i}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:i,valid:i&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,i=[];for(;s;){let t=r[n],l=this.translateMap[t];l?[r,i,n]=l(e,r,i,n):i.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return i}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],i=null==s?n.remainder:s,l=n.handler;s=l&&l(i,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,i=e.slice(r+1,n).split(s),l=i[0],o=i.slice(1),a=this.keyValueFunctions.get(l),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:l}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],i=(e,t,s)=>n.push([s,t]);return s&&(i=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&i(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let i={[r]:this.translateValue(e)};t&&Object.assign(i,t);let l={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(l=t)}if(!1!==l.insert){let e=this.dcss.addStylesheetRules({[n]:i});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,i=n?.bind(e);i&&i(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},n=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),s=new a({target:t,isInline:!0});l.set(e,s)}};!function(e=document){["complete","interactive"].indexOf(document.readyState)>-1&&n(),e.addEventListener("DOMContentLoaded",function(){n()}.bind(this))}();class i{constructor([e]=[]){this.units=l;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return l.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const l=new Map,o={safeSpace:{units:l,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new i(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o); diff --git a/dist/browser/esm/polyclass-core.js b/dist/browser/esm/polyclass-core.js index ef2f112..2da61a8 100755 --- a/dist/browser/esm/polyclass-core.js +++ b/dist/browser/esm/polyclass-core.js @@ -166,17 +166,17 @@ console.log(blendedcolor, blendedcolor2); })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -382,10 +382,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -530,6 +530,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -538,7 +539,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -548,8 +549,38 @@ class ClassGraph { this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); } + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); + } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -813,13 +844,13 @@ class ClassGraph { let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -834,7 +865,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -1607,13 +1644,21 @@ ClassGraph.addons = {}; // } +/* DOM Loader -/* - Upon document load, process and *[polyclass] entity. Similar to process() +Upon document load, process and *[polyclass] entity. Similar to process() + + */ const autoActivator = function(watch=document){ + // console.log('dom-property-activator ready') + if(["complete", "interactive"].indexOf(document.readyState) > -1) { + // console.log('dom-property-activator call early') + onDomLoaded(); + } watch.addEventListener('DOMContentLoaded', function(){ + // console.log('dom-property-activator called') onDomLoaded(); }.bind(this)); }; @@ -1641,6 +1686,7 @@ const onDomLoaded = function() { } }; +// console.log('Installing dom-property-activator') autoActivator(); /** diff --git a/dist/browser/esm/polyclass-core.min.js b/dist/browser/esm/polyclass-core.min.js index dbef42d..af8d34b 100755 --- a/dist/browser/esm/polyclass-core.min.js +++ b/dist/browser/esm/polyclass-core.min.js @@ -1 +1 @@ -document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,S,b),blendedcolor2=f(-.8,S,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){return t}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},n=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),s=new a({target:t,isInline:!0});i.set(e,s)}};!function(e=document){e.addEventListener("DOMContentLoaded",function(){n()}.bind(this))}();class l{constructor([e]=[]){this.units=i;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return i.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const i=new Map,o={safeSpace:{units:i,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new l(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o); +document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=u(-.8,S,v),blendedcolor2=f(-.8,S,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){let n=e,l=t;for(let e of this.reducers){l=e(n,l)}return l}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},n=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),s=new a({target:t,isInline:!0});i.set(e,s)}};!function(e=document){["complete","interactive"].indexOf(document.readyState)>-1&&n(),e.addEventListener("DOMContentLoaded",function(){n()}.bind(this))}();class l{constructor([e]=[]){this.units=i;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return i.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const i=new Map,o={safeSpace:{units:i,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new l(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o); diff --git a/dist/browser/umd/polyclass-core.js b/dist/browser/umd/polyclass-core.js index d2d3625..680c543 100755 --- a/dist/browser/umd/polyclass-core.js +++ b/dist/browser/umd/polyclass-core.js @@ -171,17 +171,17 @@ })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -387,10 +387,10 @@ } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -535,6 +535,7 @@ constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -543,7 +544,7 @@ this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -553,8 +554,38 @@ this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); } + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); + } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -818,13 +849,13 @@ let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -839,7 +870,13 @@ } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -1612,13 +1649,21 @@ // } + /* DOM Loader - /* - Upon document load, process and *[polyclass] entity. Similar to process() + Upon document load, process and *[polyclass] entity. Similar to process() + + */ const autoActivator = function(watch=document){ + // console.log('dom-property-activator ready') + if(["complete", "interactive"].indexOf(document.readyState) > -1) { + // console.log('dom-property-activator call early') + onDomLoaded(); + } watch.addEventListener('DOMContentLoaded', function(){ + // console.log('dom-property-activator called') onDomLoaded(); }.bind(this)); }; @@ -1646,6 +1691,7 @@ } }; + // console.log('Installing dom-property-activator') autoActivator(); /** diff --git a/dist/browser/umd/polyclass-core.min.js b/dist/browser/umd/polyclass-core.min.js index b8a6cb4..979e4c9 100755 --- a/dist/browser/umd/polyclass-core.min.js +++ b/dist/browser/umd/polyclass-core.min.js @@ -1 +1 @@ -!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},i=function(e,t,s){let r=e>>t;return s?r&s:r},l=function(e,t,s,r){let n=i(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,i,l){return c=(d=e<0)?-1*e:e,i.length>7?function(e,r,i){let l=r.split(","),a=n(i),h=a.split(","),c=t(l[0].slice(4)),d=t(l[1]),u=t(l[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,i,l):function(e,s,n){var i=t(s.slice(1),16),l=r(n).slice(1),o=t(l,16),a=p(i,o,16,0),h=p(i,o,8,255),c=p(i,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,i,l)}function p(e,t,s,r){let n=i(e,s,r);return l(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,i=parseInt;if(t.length>7){var l=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=i(l[0].slice(4)),h=i(l[1]),c=i(l[2]);return"rgb("+(n((i(o[0].slice(4))-a)*r)+a)+","+(n((i(o[1])-h)*r)+h)+","+(n((i(o[2])-c)*r)+c)+")"}var d=(l=i(t.slice(1),16))>>16,u=l>>8&255,p=255&l;return"#"+(16777216+65536*(n((((o=i((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,S,b),blendedcolor2=f(-.8,S,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,i=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){return t}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let i,l=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:i,valid:!1};for(let e of n)if(i=o[l][e],a+=1,null!=i){if(!0===i.leaf){let e=n[a],t=i[l];if(null==(t&&t[e]))break}o=i}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:i,valid:i&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,i=[];for(;s;){let t=r[n],l=this.translateMap[t];l?[r,i,n]=l(e,r,i,n):i.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return i}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],i=null==s?n.remainder:s,l=n.handler;s=l&&l(i,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,i=e.slice(r+1,n).split(s),l=i[0],o=i.slice(1),a=this.keyValueFunctions.get(l),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:l}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],i=(e,t,s)=>n.push([s,t]);return s&&(i=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&i(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let i={[r]:this.translateValue(e)};t&&Object.assign(i,t);let l={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(l=t)}if(!1!==l.insert){let e=this.dcss.addStylesheetRules({[n]:i});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,i=n?.bind(e);i&&i(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},n=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),s=new a({target:t,isInline:!0});l.set(e,s)}};!function(e=document){e.addEventListener("DOMContentLoaded",function(){n()}.bind(this))}();class i{constructor([e]=[]){this.units=l;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return l.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const l=new Map,o={safeSpace:{units:l,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new i(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o)})); +!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},i=function(e,t,s){let r=e>>t;return s?r&s:r},l=function(e,t,s,r){let n=i(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,i,l){return c=(d=e<0)?-1*e:e,i.length>7?function(e,r,i){let l=r.split(","),a=n(i),h=a.split(","),c=t(l[0].slice(4)),d=t(l[1]),u=t(l[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,i,l):function(e,s,n){var i=t(s.slice(1),16),l=r(n).slice(1),o=t(l,16),a=p(i,o,16,0),h=p(i,o,8,255),c=p(i,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,i,l)}function p(e,t,s,r){let n=i(e,s,r);return l(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,i=parseInt;if(t.length>7){var l=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=i(l[0].slice(4)),h=i(l[1]),c=i(l[2]);return"rgb("+(n((i(o[0].slice(4))-a)*r)+a)+","+(n((i(o[1])-h)*r)+h)+","+(n((i(o[2])-c)*r)+c)+")"}var d=(l=i(t.slice(1),16))>>16,u=l>>8&255,p=255&l;return"#"+(16777216+65536*(n((((o=i((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=u(-.8,S,v),blendedcolor2=f(-.8,S,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,i=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){let n=e,i=t;for(let e of this.reducers){i=e(n,i)}return i}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let i,l=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:i,valid:!1};for(let e of n)if(i=o[l][e],a+=1,null!=i){if(!0===i.leaf){let e=n[a],t=i[l];if(null==(t&&t[e]))break}o=i}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:i,valid:i&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,i=[];for(;s;){let t=r[n],l=this.translateMap[t];l?[r,i,n]=l(e,r,i,n):i.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return i}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],i=null==s?n.remainder:s,l=n.handler;s=l&&l(i,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,i=e.slice(r+1,n).split(s),l=i[0],o=i.slice(1),a=this.keyValueFunctions.get(l),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:l}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],i=(e,t,s)=>n.push([s,t]);return s&&(i=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&i(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let i={[r]:this.translateValue(e)};t&&Object.assign(i,t);let l={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(l=t)}if(!1!==l.insert){let e=this.dcss.addStylesheetRules({[n]:i});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,i=n?.bind(e);i&&i(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},n=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),s=new a({target:t,isInline:!0});l.set(e,s)}};!function(e=document){["complete","interactive"].indexOf(document.readyState)>-1&&n(),e.addEventListener("DOMContentLoaded",function(){n()}.bind(this))}();class i{constructor([e]=[]){this.units=l;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return l.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const l=new Map,o={safeSpace:{units:l,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new i(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o)})); diff --git a/dist/core/cjs/polyclass-core.cjs b/dist/core/cjs/polyclass-core.cjs index 56f340a..2de0605 100755 --- a/dist/core/cjs/polyclass-core.cjs +++ b/dist/core/cjs/polyclass-core.cjs @@ -168,17 +168,17 @@ console.log(blendedcolor, blendedcolor2); })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -384,10 +384,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -532,6 +532,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -540,7 +541,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -550,8 +551,38 @@ class ClassGraph { this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -815,13 +846,13 @@ class ClassGraph { let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -836,7 +867,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { diff --git a/dist/core/cjs/polyclass-core.min.cjs b/dist/core/cjs/polyclass-core.min.cjs index e7f8ee2..b346875 100755 --- a/dist/core/cjs/polyclass-core.min.cjs +++ b/dist/core/cjs/polyclass-core.min.cjs @@ -1 +1 @@ -"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",S="#343BFF",y="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,y,b),blendedcolor2=f(-.8,y,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,S),blendedcolor2=f(-.8,g,S),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){return t}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};class r{constructor([e]=[]){this.units=n;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);exports.ClassGraph=s,exports.DynamicCSSStyleSheet=t,exports.Polyclass=i,exports.RenderArray=e; +"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=u(-.8,S,v),blendedcolor2=f(-.8,S,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){let n=e,l=t;for(let e of this.reducers){l=e(n,l)}return l}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};class r{constructor([e]=[]){this.units=n;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);exports.ClassGraph=s,exports.DynamicCSSStyleSheet=t,exports.Polyclass=i,exports.RenderArray=e; diff --git a/dist/core/esm/polyclass-core.js b/dist/core/esm/polyclass-core.js index 0f8e362..7c45b12 100755 --- a/dist/core/esm/polyclass-core.js +++ b/dist/core/esm/polyclass-core.js @@ -166,17 +166,17 @@ console.log(blendedcolor, blendedcolor2); })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -382,10 +382,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -530,6 +530,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -538,7 +539,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -548,8 +549,38 @@ class ClassGraph { this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -813,13 +844,13 @@ class ClassGraph { let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -834,7 +865,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { diff --git a/dist/core/esm/polyclass-core.min.js b/dist/core/esm/polyclass-core.min.js index cc6d4cc..c34184a 100755 --- a/dist/core/esm/polyclass-core.min.js +++ b/dist/core/esm/polyclass-core.min.js @@ -1 +1 @@ -document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",S="#343BFF",y="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,y,b),blendedcolor2=f(-.8,y,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,S),blendedcolor2=f(-.8,g,S),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){return t}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};class r{constructor([e]=[]){this.units=n;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);export{s as ClassGraph,t as DynamicCSSStyleSheet,i as Polyclass,e as RenderArray}; +document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=u(-.8,S,v),blendedcolor2=f(-.8,S,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){let n=e,l=t;for(let e of this.reducers){l=e(n,l)}return l}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};class r{constructor([e]=[]){this.units=n;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);export{s as ClassGraph,t as DynamicCSSStyleSheet,i as Polyclass,e as RenderArray}; diff --git a/dist/core/umd/polyclass-core.js b/dist/core/umd/polyclass-core.js index b214c6a..20a9169 100755 --- a/dist/core/umd/polyclass-core.js +++ b/dist/core/umd/polyclass-core.js @@ -172,17 +172,17 @@ })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -388,10 +388,10 @@ } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -536,6 +536,7 @@ constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -544,7 +545,7 @@ this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -554,8 +555,38 @@ this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -819,13 +850,13 @@ let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -840,7 +871,13 @@ } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { diff --git a/dist/core/umd/polyclass-core.min.js b/dist/core/umd/polyclass-core.min.js index f98bf81..870ffae 100755 --- a/dist/core/umd/polyclass-core.min.js +++ b/dist/core/umd/polyclass-core.min.js @@ -1 +1 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).polybundle={})}(this,(function(e){"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(c?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*d};var d,c;function u(e,l,i){return d=(c=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),d=t(i[0].slice(4)),c=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),d),f=o(h[1],c),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),d=p(l,o,0,255);return`#${(16777216+65536*a+256*h+d).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),d=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-d)*r)+d)+")"}var c=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-c)*r)+c)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,S,b),blendedcolor2=f(-.8,S,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class t extends Array{renderAll(){for(let e of this)e.render()}}class s{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(e,s){let r=this.getEnsureStyleSheet(s),n=new t,l=r;for(let t=0;t*% #():=.@+?\/]/g;dcss=new s(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){return t}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),d=n.slice(a);return{props:h,values:d,str:e,node:l,valid:l&&d.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}r.addons={};class n{constructor([e]=[]){this.units=l;let t=new r(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return l.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const l=new Map,i={safeSpace:{units:l,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new n(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},o=new Proxy((function(){return i.newInstance.apply(i,arguments)}),i);e.ClassGraph=r,e.DynamicCSSStyleSheet=s,e.Polyclass=o,e.RenderArray=t})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).polybundle={})}(this,(function(e){"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,S,b),blendedcolor2=f(-.8,S,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class t extends Array{renderAll(){for(let e of this)e.render()}}class s{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(e,s){let r=this.getEnsureStyleSheet(s),n=new t,l=r;for(let t=0;t*% #():=.@+?\/]/g;dcss=new s(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){let n=e,l=t;for(let e of this.reducers){l=e(n,l)}return l}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}r.addons={};class n{constructor([e]=[]){this.units=l;let t=new r(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return l.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const l=new Map,i={safeSpace:{units:l,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new n(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},o=new Proxy((function(){return i.newInstance.apply(i,arguments)}),i);e.ClassGraph=r,e.DynamicCSSStyleSheet=s,e.Polyclass=o,e.RenderArray=t})); diff --git a/dist/full/cjs/polyclass-full.cjs b/dist/full/cjs/polyclass-full.cjs index e2e45f4..85bbcfd 100755 --- a/dist/full/cjs/polyclass-full.cjs +++ b/dist/full/cjs/polyclass-full.cjs @@ -168,17 +168,17 @@ console.log(blendedcolor, blendedcolor2); })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -384,10 +384,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -532,6 +532,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -540,7 +541,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -550,8 +551,38 @@ class ClassGraph { this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -815,13 +846,13 @@ class ClassGraph { let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -836,7 +867,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -1892,6 +1929,248 @@ const polyclassProxy = { const Polyclass = new Proxy(polyclassHead, polyclassProxy); + +//;(()=>{ + +var installReceiver = function() { + + let keys = new Set([ + /* Hex is a freebie, under the special term `#` hash: #000000 */ + // 'hex', + /* Color property is slightly more complicated, with the first param + as a forced string. */ + // 'color', + + /* Available types, each act the same way: rgb-[3 values][/A] + If the key is a mismatch, its ignored. */ + 'rgb', + 'hsl', + 'hwb', + 'lab', + 'lch', + 'oklab', + 'oklch', + ]); + + ClassGraph.addons.extendedColorValues = function(cg){ + let func = function(prop, values) { + return forwardHotWordReduce(prop, values, keys) + }; + cg.reducers.push(func); + }; +}; + + +/* Return a boolean if the detected type is a valid css value of type: + + Number: 0 | 0.0 + Percent: 0% + Opacity: 0/0 + Angle: 0turn | 0rad +*/ +const isNumOrPerc = function(value) { + return isNumber(value) || isPercent(value) || isOpacityNum(value) || isAngle(value) +}; + +/* Return boolean for the match of a css value with an alpha: 0/0 */ +const isOpacityNum = function(value) { + // '60%/0.8' + let spl = value.split('/'); + if(spl.length == 2) { + return isNumOrPerc(spl[0]) && isNumber(spl[1]) + } + return false +}; + +const isAngle = function(value) { + let types = new Set(["deg","grad","rad","turn"]); + let extra = value.slice(parseFloat(value).toString().length, value.length); + return types.has(extra) +}; + + +const isPercent = function(value) { + return value.endsWith('%') && isNumber(value.slice(0, value.length-1)) +}; + + +const isNumber = function(value) { + if(value == undefined || value.length == 0){ return false } let isNum = !isNaN(Number(value)); + return isNum +}; + + +const asThreeBitColor = function(values) { + let ex = values.slice(4, 5); + let alp = ''; + if(ex.length>0) { + alp = `/${ex}`; + } + return `${values[0]}(${values.slice(1, 4).join(' ')}${alp})` +}; + + +/* Perform a _hot word_ detection on the values recursively. A _hot word_ may be any key. + + forwardHotWordReduce( + ['color'] + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + ) + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail. + +This method then performs this after every release, concatenating changed and +unchanged into a response list. + + rgb-200-200-200-foo + + rgb(200 200 200) foo + + */ +const forwardHotWordReduce = function(props, values, keys, keyTestFunc=undefined) { + /* + Key pops early, and can accept a variable amount of vars. + */ + + let len = values.length + , position = 0 + , max = values.length + 1 + , count = 0 + , response = [] + ; + + while(position < len && count < max) { + let sliced = values.slice(position); + let [key, usedCount] = hotWordReduce(sliced, keys, true, keyTestFunc); + + position += usedCount; + count += 1; + if(Array.isArray(key)) { + response = response.concat(key); + } else { + response.push(key); + } + } + + return response +}; + +/* Perform a _hot word_ detection on the values. A _hot word_ may be any key. + + forwardHotWordReduce( + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + , true + ) + + rgb(200 200 200) // break early + rgb(200 200 200) egg + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail if `breakEarly` is true. + + rgb-200-200-200-foo-hsl-20-0%-10-foo + + rgb(200 200 200) foo hsl(20 0% 10) foo + + */ + +const hotWordReduce = function(values, keys + , breakEarly=false + , callback=asThreeBitColor + , keyTestFunc=undefined) { + + var i = 0; + let inSet = (x) => keys.has(x) + , keyStartMatch = keyTestFunc != undefined? keyTestFunc: inSet + , l = values.length + , bits = [] + , kept = [] + , lost = [] + , max = 4 // can be 3 or 4 + ; + + for (;i < l; i++) { + // console.log('---') + let k = values[i]; + let inI = i; + if(keyStartMatch(k)) { + // console.log(i, 'MATCH', k) + let j = i+1; + kept = [k]; + lost = []; + let ok = true; + while(ok && j < l) { + let subI = j; + let subK = values[subI]; + let isNum = isNumOrPerc(subK); + ok = isNum && j < l && kept.length <= (max-1); // +1 for the original key + if(isNum) { + // console.log('Push', subK) + j += 1; + kept.push(subK); + ok = ok && kept.length <= max; // +1 for the original key + } else { + // Lost stack + // console.log('Lost stack on', subK) + // j = 1 + lost.push(subK); + } + // console.log('S', subI, subK, isNum, ok) + } + + let [a,b] = [inI, j]; + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept); + if(plucked.length < 3) { + // console.log('Failed.', bits) + bits = bits.concat(kept); + if(breakEarly) { + return [bits, j] + } + } else { + // console.log('kept', kept, newEntry) + // console.log('plucked', plucked) + bits.push(newEntry); + // Push back 2, as we landed on the bad node, + // and we need step into this node, to stack it. + // + i = j-1; + } + } else { + // console.log(i, k) + bits.push(k); + + if(breakEarly) { + let [a,b] = [inI, kept.length]; + // console.log('a,b ',a, b, values.slice(a,b), kept) + kept.slice(a, b); + let newEntry = callback(kept); + // console.log('plucked', plucked) + // console.log('kept', kept) + if(kept.length < 3) { + // console.log('Failed.', 'kept', kept, 'plucked', plucked) + return [values[b], kept.length+1] + } else { + // console.log('success.') + return [newEntry, kept.length] + } + } + } + } + + // console.log('Done pop', i) + // console.log('in', values, 'out', bits) + + let newEntry = callback(kept); + return [newEntry, i+1] +} + + +;installReceiver(); (function(){ let cg; @@ -2034,6 +2313,8 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); cg = _cg; cg.insertReceiver(['font', 'pack'], fontPackReceiver); }; + ClassGraph.prototype.generateGoogleLinks = generateGoogleLinks; + ClassGraph.prototype.installGoogleLinks = installGoogleLinks; }; /** @@ -2056,15 +2337,18 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); let familyStrings = createFamilyString(values, fonts, origin); // let families = tokenize(values) - - // install as header items - // console.info('Installing Google fonts: familyStrings:', familyStrings) - generateGoogleLinks(familyStrings).forEach((x)=>document.head.appendChild(x)); + installGoogleLinks(familyStrings); // Install additional css additions installFontObjects(fonts); }; + const installGoogleLinks = function(familyStrings, display) { + // install as header items + // console.info('Installing Google fonts: familyStrings:', familyStrings) + return generateGoogleLinks(familyStrings, display).forEach((x)=>document.head.appendChild(x)) + }; + const installFontObjects = function(fonts, splitObj) { // // For value create a font-family; @@ -2389,7 +2673,7 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); }); }; - const generateGoogleLinks = function(familyStrings){ + const generateGoogleLinks = function(familyStrings, display='swap'){ let a = getOrCreateLink('link', 'preconnect', { href: "https://fonts.googleapis.com" @@ -2400,8 +2684,10 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); , crossorigin: '' }); + let ds = display == null? '': `&display=${display}`; + let c = getOrCreateLink('link', "stylesheet", { - href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + href:`https://fonts.googleapis.com/css2?${familyStrings}${ds}` }); return [a,b,c] @@ -2409,6 +2695,18 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); let linkCache = {}; + /* + Create a link node + + let b = getOrCreateLink('link', 'preconnect', { + href: "https://fonts.gstatic.com" + , crossorigin: '' + }) + + let c = getOrCreateLink('link', "stylesheet", { + href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + }) + */ const getOrCreateLink = function(href, rel, opts) { let v = { rel, href @@ -2445,6 +2743,343 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); })() +;(function(){ + + let cg; + + const insertReceiver = function(){ + + ClassGraph.addons.functionsReceiver = function(_cg){ + cg = _cg; + cg.keyValueFunctions.set('forceGreen', forceHook); + cg.keyValueFunctions.set('force', forceHook); + cg.keyValueFunctions.set('raise', raiseHook); + }; + }; + + const forceHook = function(value, token, index, splitObj) { + // console.log('Force green hook', token, splitObj) + token.value.slice(0, token.match.start); + // console.log(res) + // return res + + return token.args.length > 0? token.args[0]: 'green' + }; + + const raiseHook = function(value, token, index, splitObj) { + console.log('raise hook', token, splitObj); + let res = token.value.slice(0, token.match.start); + console.log(res); + // return res + }; +insertReceiver(); +})(); +(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver); + // cg.insertReceiver(['icon'], iconReceiver) + }; + }; + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + + let key = titleCase(obj.values).join('+'); + let family = `Material+Symbols+${key}`; + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + }; + let familyString = toGoogleFontParamsStr(opts); + let fontStr = `family=${family}:${familyString}`; + + let receiverBits = [...obj.values, 'icon']; + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver); + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null); + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings); + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + }; + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0]; + let rules = {}; + + let fontSettingsStr = toObjectParamStr(fontSettings); + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + }; + + rules[`.material-symbols-${key}`] = conf; + let items = cg.dcss.addStylesheetRules(rules); + + items.renderAll(); + }; + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj); + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i]; + let v = obj[k]; + let last = i == fKeys.length-1; + let end = last? '': ',\n'; + fontSettingsStr += `'${k}' ${v}${end}`; + } + return fontSettingsStr + + }; + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(','); + let v = Object.values(obj).join(','); + return `${k}@${v}` + }; + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + obj.values; obj.origin; + console.log('render icon', obj); + + return contentInjection(obj) + }; + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)); + origin.innerText += `${values.join('_')}`; + }; + + const getInjectClass = function(obj) { + let k = obj.props[0]; + return `material-symbols-${k}` + } + + ;insertReceiver(); +})() + +;(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver); + // cg.insertReceiver(['icon'], iconReceiver) + }; + }; + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + console.log('Install the font', obj); + let key = titleCase(obj.values).join('+'); + let family = `Material+Symbols+${key}`; + let fontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + }; + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + }; + let familyString = toGoogleFontParamsStr(opts); + let fontStr = `family=${family}:${familyString}`; + + let receiverBits = [...obj.values, 'icon']; + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver); + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null); + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings); + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + }; + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0]; + let rules = {}; + + let fontSettingsStr = toObjectParamStr(fontSettings); + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + }; + + rules[`.material-symbols-${key}`] = conf; + let items = cg.dcss.addStylesheetRules(rules); + + items.renderAll(); + }; + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj); + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i]; + let v = obj[k]; + let last = i == fKeys.length-1; + let end = last? '': ',\n'; + fontSettingsStr += `'${k}' ${v}${end}`; + } + return fontSettingsStr + + }; + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(','); + let v = Object.values(obj).join(','); + return `${k}@${v}` + }; + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + obj.values; obj.origin; + console.log('render icon', obj); + + return contentInjection(obj) + }; + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)); + origin.innerText += `${values.join('_')}`; + }; + + const getInjectClass = function(obj) { + let k = obj.props[0]; + return `material-symbols-${k}` + } + + ;insertReceiver(); +})() + /** * # Monitor * @@ -2550,194 +3185,34 @@ const difference = function(setA, setB) { })() /* +Convert discovered nodes and bind them to a selector. The assigned classes +are the declarations assigned to the css class. -vars box. To assign key variables as accessible CSS varialbes through a js -definition. The definition is bound to DCSS, so edits to the vars manipulates -the view automatically. +The discovery may descend children, allowing for depth setup. - vars({ - primary: "#880000" # company red - , secondary: "#111" # dark - , accent: "red" - }) + -In the node, we access the vars reciever + + -
-

An elk called Elk lives here.

-
+
-Manipulating the var propagates to the view: - vars.primary = "#EEE" # off white - ---- - -## Secondary App - - `swatch()` - and colors.js - - Assign "colors" to a swatch of colors, each color is a function from the - colors.js module and can assign math relations to swatches. - Chaning a swatch (such as its base color), can manipulate the other - colours according to the chosen swatch type, e.g. "Diachromic". - - */ - -;(function(){ - - let cg; - let rootRule; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varsReceiver = function(_cg){ - cg = _cg; - cg.vars = varsHook.bind(cg); - // cg.varsRootDelaration = rootDeclaration - cg.varsRoot = rootRule; - // cg.insertTranslator('var', variableDigest) - }; - }; - - - const varsHook = function(d, target=':root') { - /** vars() function bound to the classgraph. _this_ is the classgraph - instance `cg.vars = varsHook.bind(cg)` - - each key is a var, value is the param - - { - apples: green - , foo: 10 - , bar: 1em - , baz: #444 - } - - Each var is installed on the target node: - - :root { - --apples: green - ... - --baz: #444 - } - - if an existing "vars" object exists, it's updated. - - */ - // target = document.querySelector(target) - console.log('Hook', d); - - if(rootRule == undefined) { - let rootDeclaration = {}; - - for(let key in d) { - let prop = `--${key}`; - let value = d[key]; - rootDeclaration[prop] = value; - } - - let rules = cg.dcss.addStylesheetRules({ - [target]: rootDeclaration - }); - - rules.renderAll(); - rootRule = rules[0]; - cg.varsRoot = rootRule; - } else { - - // rootRule - // let pr = rootRule.getPropStr([target,Object.entries(definition)]) - // rootRule.sheetRule.cssText = `${target} { ${pr} }` - // rootRule.replace(`${target} { ${pr} }`) - - for(let key in d) { - let prop = `--${key}`; - let value = d[key]; - rootRule.sheetRule.style.setProperty(prop, value); - } - // rootRule.render() - // console.log(rootRule) - // window.varsRule = rootRule - } - } - - ;insertReceiver(); -})() - -/** - * # var-* Translate - * - * https://developer.mozilla.org/en-US/docs/Web/CSS/var - * - * Discover and rewrite class names values with `var-*` to the CSS function - * `var(*)`. e.g. - * - * "border-top-var-primary-edges" - * - * { - * "border-top": var(--primary-edges) - * } - */ -;(function(){ - - let cg; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // console.log('var-translate insertReceiver') - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varTranslateReceiver = function(_cg){ - cg = _cg; - cg.insertTranslator('var', variableDigest2); - // cg.insertTranslator('var', variableDigest) - }; - }; - - - const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ - - let keys = inStack.slice(currentIndex); - let k1 = keys.slice(1); - let word = `var(--${k1.join("-")})`; - - outStack.push(word); - // return [inStack, outStack, currentIndex] - return [[], outStack, currentIndex + k1.length] - } - - - - ;insertReceiver(); -})() - +Notably this may be easier as real CSS. + */ /* The words map lists all the unique string CSS values. Each word maps to an @@ -2818,10 +3293,10 @@ class Words extends Map { wordsToArrayString(indent=0, small=false){ if(!small) { - return JSON.stringify(wordsToOrderedArray(), null, indent) + return JSON.stringify(this.wordsToOrderedArray(), null, indent) } - return wordsToOrderedArray().join(' ') + return this.wordsToOrderedArray().join(' ') } wordsToObjectString(indent=0, small=false) { @@ -2861,6 +3336,75 @@ class Words extends Map { } } +/* +1. all the items have string in position +2. the we create the flat array list +each position is a word from the string list + + "all-petite-caps", + "all-scroll", + "all-small-caps", + +as a string: + + " all petite caps scroll small ..." + +Becomes: + [1, [ + [2, [ + [3, null] + ] + ], + [4, null], + [5, [ + [3,null] + ] + ] + ] + ] + +--- + +When loaded, we can re-ask for the prop: + + w.stringToBits("all-petite-caps") + [1,2,3] + +The last key + + w.stringToBits("zoom") + [211] + w.stringToBits("zoom-out") + [211, 66] +--- + + + "all-petite-caps", + "all-scroll", + "all-small-caps", + "allow-end", + "alternate-reverse", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2", + "0-3", + "0-4-5", + "6-7", + "8-9", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2 0-3 0-4-5 6-7 8-9" + + "all petite caps scroll small allow end alternate reverse", + "0 1 2,0 3,0 4 5,6 7,8 9" + + // radix each key through 32 bits, allowing ~1000 positions as 2bits + // not really helpful under 100 keys, but then saves 1 char per position (up to 1k) + // .. With 255~ keys thats 150~ chars saved. + // In a 32bit radix, the first 31 positions are single chars. +--- + +*/ const words = new Words() , microGraph = {} @@ -3067,8 +3611,16 @@ const words = new Words() var installReceiver = function() { - ClassGraph.addons.forwardReduceValues = (cg) => words.installPropArray(dashprops); - ClassGraph.prototype.forwardReduceValues = forwardReduceValues; + ClassGraph.addons.forwardReduceValues = function(cg){ + let func = function(prop, values) { + return forwardReduceValues(prop, values, microGraph, words) + }; + cg.reducers.push(func); + let res = words.installPropArray(dashprops); + return res; + }; + // install one of many + // ClassGraph.prototype.forwardReduceValues = forwardReduceValues ClassGraph.prototype.valuesGraph = { microGraph, words }; }; @@ -3098,9 +3650,6 @@ const forwardReduceValues = function(props, values, microGraph, translations) { 'row': { 'reverse': merge } - , 'other': { - 'horse': merge - } }; let len = values.length @@ -3156,6 +3705,194 @@ const popOneValueForward = function(values, microGraph, translations) { ;installReceiver(); +})() +/** + * # var-* Translate + * + * https://developer.mozilla.org/en-US/docs/Web/CSS/var + * + * Discover and rewrite class names values with `var-*` to the CSS function + * `var(*)`. e.g. + * + * "border-top-var-primary-edges" + * + * { + * "border-top": var(--primary-edges) + * } + */ +;(function(){ + + let cg; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // console.log('var-translate insertReceiver') + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varTranslateReceiver = function(_cg){ + cg = _cg; + cg.insertTranslator('var', variableDigest2); + // cg.insertTranslator('var', variableDigest) + }; + }; + + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + let keys = inStack.slice(currentIndex); + let k1 = keys.slice(1); + let word = `var(--${k1.join("-")})`; + + outStack.push(word); + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + + + ;insertReceiver(); +})() + +/* + +vars box. To assign key variables as accessible CSS varialbes through a js +definition. The definition is bound to DCSS, so edits to the vars manipulates +the view automatically. + + vars({ + primary: "#880000" # company red + , secondary: "#111" # dark + , accent: "red" + }) + +In the node, we access the vars reciever + +
+

An elk called Elk lives here.

+
+ +Manipulating the var propagates to the view: + + vars.primary = "#EEE" # off white + +--- + +## Secondary App + + `swatch()` + and colors.js + + Assign "colors" to a swatch of colors, each color is a function from the + colors.js module and can assign math relations to swatches. + Chaning a swatch (such as its base color), can manipulate the other + colours according to the chosen swatch type, e.g. "Diachromic". + + */ + +;(function(){ + + let cg; + let rootRule; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varsReceiver = function(_cg){ + cg = _cg; + cg.vars = varsHook.bind(cg); + // cg.varsRootDelaration = rootDeclaration + cg.varsRoot = rootRule; + // cg.insertTranslator('var', variableDigest) + }; + }; + + + const varsHook = function(d, target=':root') { + /** vars() function bound to the classgraph. _this_ is the classgraph + instance `cg.vars = varsHook.bind(cg)` + + each key is a var, value is the param + + { + apples: green + , foo: 10 + , bar: 1em + , baz: #444 + } + + Each var is installed on the target node: + + :root { + --apples: green + ... + --baz: #444 + } + + if an existing "vars" object exists, it's updated. + + */ + // target = document.querySelector(target) + console.log('Hook', d); + + if(rootRule == undefined) { + let rootDeclaration = {}; + + for(let key in d) { + let prop = `--${key}`; + let value = d[key]; + rootDeclaration[prop] = value; + } + + let rules = cg.dcss.addStylesheetRules({ + [target]: rootDeclaration + }); + + rules.renderAll(); + rootRule = rules[0]; + cg.varsRoot = rootRule; + } else { + + // rootRule + // let pr = rootRule.getPropStr([target,Object.entries(definition)]) + // rootRule.sheetRule.cssText = `${target} { ${pr} }` + // rootRule.replace(`${target} { ${pr} }`) + + for(let key in d) { + let prop = `--${key}`; + let value = d[key]; + rootRule.sheetRule.style.setProperty(prop, value); + } + // rootRule.render() + // console.log(rootRule) + // window.varsRule = rootRule + } + } + + ;insertReceiver(); })(); exports.ClassGraph = ClassGraph; diff --git a/dist/full/cjs/polyclass-full.min.cjs b/dist/full/cjs/polyclass-full.min.cjs index c030799..287f226 100755 --- a/dist/full/cjs/polyclass-full.min.cjs +++ b/dist/full/cjs/polyclass-full.min.cjs @@ -1 +1 @@ -"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,r=(e,t,r)=>`rgb(${e},${t},${r})`;let s=function(e,t="#000000",r="#FFFFFF"){return e||(h?t:r)},n=function(e){return s(e,r(0,0,0),r(255,255,255))},l=function(e,t,r){let s=e>>t;return r?s&r:s},i=function(e,t,r,s){let n=l(e,t,r);return a(n,s)},o=(e,r)=>a(t(e),r),a=function(t,r){return e(c(t-r))+r},c=function(e){return e*u};var u,h;function d(e,l,i){return u=(h=e<0)?-1*e:e,l.length>7?function(e,s,l){let i=s.split(","),a=n(l),c=a.split(","),u=t(i[0].slice(4)),h=t(i[1]),d=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],h),g=o(c[2],d);return r(f,p,g)}(0,l,i):function(e,r,n){var l=t(r.slice(1),16),i=s(n).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,r,s){let n=l(e,r,s);return i(t,r,s,n)}function p(e,t,r){var s=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(r||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*s)+a)+","+(n((l(o[1])-c)*s)+c)+","+(n((l(o[2])-u)*s)+u)+")"}var h=(i=l(t.slice(1),16))>>16,d=i>>8&255,f=255&i;return"#"+(16777216+65536*(n((((o=l((r||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-h)*s)+h)+256*(n(((o>>8&255)-d)*s)+d)+(n(((255&o)-f)*s)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",m="rgb(120,99,248)";blendedcolor=d(-.8,b,m),blendedcolor2=p(-.8,b,m),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=d(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let r in t){(0,t[r])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,r=e||this.styleEl;if(null!=r)return r;if("sheet"==this.insertMethod&&(r=document.createElement("style"),document.head.appendChild(r),t=r.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,r){let s=this.getEnsureStyleSheet(r),n=new e,l=s;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,r]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,r)=>(r?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let r=this.getRoot(),s=this.nodeWord(),n=[];for(let t of e){n.push(t),r[s]||(r[s]={});let e=r[s][t];null==e&&(e=r[s][t]={key:t,position:n}),r=e}return r.leaf=!0,null!=t&&(r.handler=t),r}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var r=0;r0||!1}}forwardReduceValues(e,t,r,s){return t}minorCapture(e,t=this.sep,r=!0){let s="string"==typeof e?e.split(t):e,n=this.aliasConvert(s);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(r)break;let c=n.slice(0,a),u=n.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,r=!0){let s=this.objectSplit(e,t,r);return this.translateValue(s)}insertLine(e,t){let r=this.objectSplit(e);return this.insertRule(r,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let r=!0,s=t||[],n=0,l=[];for(;r;){let t=s[n],i=this.translateMap[t];i?[s,l,n]=i(e,s,l,n):l.push(this.beforeOutStack(s[n],n,e)),n+=1,(n>=s.length||n>100)&&(r=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,r){let s=this.getKeyFunctionMatch(e),n=this.collapseFunctions(s,r);return null==n?e:n}collapseFunctions(e,t){let r;for(var s=e.length-1;s>=0;s--){let n=e[s],l=null==r?n.remainder:r,i=n.handler;r=i&&i(l,n,s,t)||r}return r}getKeyFunctionMatch(e){let t=null!=e,r=e,s=[];for(;t;){let e=this.getKeyFunctionMatchOnce(r);e.success,t=e.match.start>-1,t&&(r=e.remainder,s.push(e))}return s}getKeyFunctionMatchOnce(e,t=".",r=":"){let s=e.lastIndexOf(t),n=e.length,l=e.slice(s+1,n).split(r),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,s),handler:a,args:o,match:{start:s,end:n,name:i}};return c.success=null!=a,c}filterClasses(e,t,r=!1){let s=e.classList,n=r?{}:[],l=(e,t,r)=>n.push([r,t]);return r&&(l=(e,t,r)=>n[e]=[r,t]),s.forEach((function(e,r,s){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,r)})),n}filterSplit(e,t,r=!1){let s=this.filterClasses(e,t,r);if(r){let e={};for(let t in s){let r=s[t];e[t]=this.objectSplit(r[1],void 0,void 0,r[0])}return e}let n=[];return s.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,r=!0){e?.props?.join("-");let s=this.asSelectorString(e,r);this.dcss.selectorExists(s)&&this.dcss.removeRuleBySelector(s)}insertRule(e,t=void 0,r=!0){let s=e?.props?.join("-"),n=this.asSelectorString(e,r);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[s]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let r=this.addTree(e);return r.handler=t,r}asSelectorString(e,t=!0){let r;if(Array.isArray(e)){let t=e.join("-");r=this.escapeStr(t)}if("string"==typeof e&&(r=this.escapeStr(e)),e.props){let t=e.props.join("-");r=this.escapeStr(t)}e.str&&(r=this.escapeStr(e.str));let s=`.${r}`;return t?this.prependParent(s,e):s}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let r=this.objectSplit(e);return r.values.length>0&&r.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let r of t.rules)e+=`${r.cssText};\n`;return e}captureChanges(e,t,r){this.discoverInsert(e,r),this.discoverRemove(t,r)}discoverInsert(e,t){let r=this;for(let s of e){if(0==s.length)continue;let e=r.objectSplit(s);e.origin=t;let n=e.node?.handler;(n?n.bind(e):r.insertRule.bind(r))(e)}}discoverRemove(e,t){let r=this;for(let s of e){if(0==s.length)continue;let e=r.objectSplit(s);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let r=0;for(let s of t)this.safeInsertLine(s,e,r++)}safeInsertLine(e,t,r=-1){let s=this.objectSplit(e,void 0,void 0,r);return s.valid&&(s.origin=t,this.insertRule(s)),s}getAllClasses(e=document.body,t=!1,r=!0){let s=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,s=function(e){n.set(e,new Set(e.classList))}),r&&s(e),e.querySelectorAll("*").forEach(s),n}addClass(e,...t){let r=this.asNodes(e);for(let e of r)for(let r of t)for(let t of r.split(" "))e.classList.add(t)}removeClass(e,...t){let r=this.asNodes(e);for(let e of r)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}r.addons={};class s{constructor([e]=[]){this.units=n;let t=new r(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,r){let s=this.reference;if(t in s)return s[t].bind?s[t].bind(s):s[t]},apply(e,t,r){console.log("innerProxyHandler apply...",r)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,r=void 0){const s=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===s)return r;let n=s.value;if(0==n.length)return r;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,r){let s=this.getInstance();if(t in s){let e=s[t];return e&&e.bind?e.bind(s):e}return this.safeSpace[t]},newInstance(){return new s(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,r){return console.log("Polyclass apply...",e,t,r),r[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,r)):this.getInstance.apply(this,r)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);!function(){let e;const t=function(e,t){values=e.values;let[r,...n]=e.values;if(void 0!==document[`on${r}`]){const t=e.origin;s(e,t,r,n)}else console.warn("Unknown action",r)},s=function(e,t,r,s){let l=e=>n(e,r,s),i=`polyaction_${r}`;void 0===t.dataset[i]?(t.addEventListener(r,l),t.dataset[i]=!0):console.log("Event already exists:",r)},n=function(e,t,r){let[s,...n]=r;console.log(e,t,r),console.log(s,n);let l={call(){},toggle(){console.log(n,r,t),e.currentTarget.classList.toggle(n.join("-"))},setvar(){}}[s];l&&l()};console.log("event receiver"),r.addons.eventsReceiver=function(r){e=r,e.insertReceiver(["event"],t)}}(),function(){let e;const r=function(e){const t=e.values,r=e.origin;let n=o(t,r,e),i=l(t,n,r);u(i).forEach((e=>document.head.appendChild(e))),s(n)},s=function(t,r){for(let r of Object.values(t)){let t=r.first,s=(e,t)=>t?" ":"",l=n(t.replace(/[+]/g,s));r.cleanName=l,r.definition=i(r),e.dcss.addStylesheetRules(r.definition).renderAll()}},n=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},l=function(e,t,r){t=t||o(e,r);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},i=function(t){let r={};const s=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let n={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},n);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);r[`${s(i)}, ${s(i).toLowerCase()}`]=e}}let n=s(["font",t.first]),l=s(["font"].concat(t.first.split("+"))),i=new Set([n,l,n.toLowerCase(),l.toLowerCase()]);return r[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},r},o=function(t,r,s){let n,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,c=function(t,r){return e.filterSplit(r,t,!0)}(["default"],s?.origin||r),u="sans-serif",h=c.default;if(h)if(h.index<=s.index){let e="font default-* modifier should be indexed after font";console["warn"](e),u=h.values.join(" ")}else u=h.values.join(" ");for(let e in t){let r=t[e];if(0==l){i[l]={first:r,tokens:{},defaultFonts:u},n=l,l++;continue}let[s,a]=[null,null];try{let e;[e,s,a]=r.match(o),0==s.length&&(s="r")}catch{i[l]={first:r,tokens:{}},n=l,l++;continue}let c={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},h={int:Number(a)};if(0==h.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in s){let t=c[s[e]];Object.assign(h,t())}let d=i[n]?.tokens[a]||{};Object.assign(d,h),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:h.ital,token:r}),i[n].tokens[a]=d,l++}return a(i)},a=function(e){for(let t in e){let r=e[t];0!=r.first.length&&c(r)}return e},c=function(e){let t=n(e.first),r=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),s=Object.assign({},...r),l=null!=s.ital,i=[],o=new Set;l&&i.push("ital"),(l||s.regu)&&i.push("wght");for(let t in e.tokens){let r=e.tokens[t],s=r.ital?1:0,n=r.int,i=l?[s]:[];i.push(n);let a=i.join(",");if(o.add(a),null!=r.regu){let e=l?[0]:[];e.push(n);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${i.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:i,titleToken:t,str:u})},u=function(e){return[d("link","preconnect",{href:"https://fonts.googleapis.com"}),d("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),d("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}&display=swap`})]};let h={};const d=function(e,t,r){let s={rel:t,href:e};Object.assign(s,r||{});let n=JSON.stringify,l=h[n(s)];return l||(h[n(s)]=f("link",s))},f=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let r=document.createElement(e);for(let e in t)r.setAttribute(e,t[e]);return r};t.addons.fontPackReceiver=function(t){e=t,e.insertReceiver(["font","pack"],r)}}(),(()=>{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&s(e)},r=new MutationObserver((function(e){e.forEach(t)}));return r.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),r},s=function(t){let r=t.target.classList.value,s=t.oldValue,l=r.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==s?[]:s.split(" ").map((e=>e.trim())),o=i?n(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},n=function(e,t){const r=new Set(e);for(const e of t)r.delete(e);return r};r.addons.monitorClasses=function(t){e=t},r.prototype.monitor=function(e=document.body){return t(e)}})(),function(){let e,t;const s=function(r,s=":root"){if(console.log("Hook",r),null==t){let n={};for(let e in r){let t=`--${e}`,s=r[e];n[t]=s}let l=e.dcss.addStylesheetRules({[s]:n});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in r){let s=`--${e}`,n=r[e];t.sheetRule.style.setProperty(s,n)}};r.addons.varsReceiver=function(r){e=r,e.vars=s.bind(e),e.varsRoot=t}}(),function(){let e;const t=function(e,t,r,s){let n=t.slice(s).slice(1),l=`var(--${n.join("-")})`;return r.push(l),[[],r,s+n.length]};r.addons.varTranslateReceiver=function(r){e=r,e.insertTranslator("var",t)}}(),(()=>{class e extends Map{wordCounter=1;getKey(e){let r=t.get(e);return null==r&&(t.set(e,this.wordCounter),r=this.wordCounter,this.wordCounter++),r}stringToBits(e,t="-"){let r=e.split(t),s=[];return r.forEach(((e,t,r)=>s.push(this.getKey(e)))),s}stringToNest(e,t={}){let r=e.split("-");var s=t;let n=s,l=r.length;return r.forEach(((e,t,r)=>{let n=this.getKey(e),i=t==l-1;null==s[n]?s[n]=s=i?null:{}:s=s[n]})),n}installPropArray(e){e.forEach(((e,t,r)=>{this.stringToNest(e,s)}))}insertBitKey(e,t=s){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,r,s)=>e[t]=r)),e}wordsToArrayString(e=0,t=!1){return t?wordsToOrderedArray().join(" "):JSON.stringify(wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let r="";return this.forEach(((e,t,s)=>r+=[t,e].join(""))),r}graphToArrayListString(e=s,t=0,r=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,r))}graphToArrayListRecurse(e=s,t=0,r=null){let n=[],l=Object.entries(e);for(let e of l){let s=e[1];n.push([parseInt(e[0]),null==s?r:this.graphToArrayListRecurse(s,t,r)])}return n}graphToObjectString(e=0){let t={};for(let e in s)t[parseInt(e)]=s[e];return JSON.stringify(t,null,e)}}const t=new e,s={},n=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,r,s){const n=e=>e.join("-"),l=r||{row:{reverse:n},other:{horse:n}};let o=t.length,a=0,c=t.length+1,u=0,h=[];for(;ae.join("-");let r=n[s];return null==r&&(r=t),[r(e.slice(0,o+1)),o+1]}return[e[0],1]};r.addons.forwardReduceValues=e=>t.installPropArray(n),r.prototype.forwardReduceValues=l,r.prototype.valuesGraph={microGraph:s,words:t}})(),exports.ClassGraph=r,exports.DynamicCSSStyleSheet=t,exports.Polyclass=i,exports.RenderArray=e; +"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,n=(e,t,n)=>`rgb(${e},${t},${n})`;let r=function(e,t="#000000",n="#FFFFFF"){return e||(h?t:n)},s=function(e){return r(e,n(0,0,0),n(255,255,255))},l=function(e,t,n){let r=e>>t;return n?r&n:r},i=function(e,t,n,r){let s=l(e,t,n);return a(s,r)},o=(e,n)=>a(t(e),n),a=function(t,n){return e(c(t-n))+n},c=function(e){return e*u};var u,h;function d(e,l,i){return u=(h=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=s(l),c=a.split(","),u=t(i[0].slice(4)),h=t(i[1]),d=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],h),g=o(c[2],d);return n(f,p,g)}(0,l,i):function(e,n,s){var l=t(n.slice(1),16),i=r(s).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,n,r){let s=l(e,n,r);return i(t,n,r,s)}function p(e,t,n){var r=e<0?-1*e:e,s=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(n||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(s((l(o[0].slice(4))-a)*r)+a)+","+(s((l(o[1])-c)*r)+c)+","+(s((l(o[2])-u)*r)+u)+")"}var h=(i=l(t.slice(1),16))>>16,d=i>>8&255,f=255&i;return"#"+(16777216+65536*(s((((o=l((n||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-h)*r)+h)+256*(s(((o>>8&255)-d)*r)+d)+(s(((255&o)-f)*r)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=d(-.8,b,v),blendedcolor2=p(-.8,b,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=d(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let n in t){(0,t[n])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,n=e||this.styleEl;if(null!=n)return n;if("sheet"==this.insertMethod&&(n=document.createElement("style"),document.head.appendChild(n),t=n.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,n){let r=this.getEnsureStyleSheet(n),s=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,n]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,n)=>(n?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let n=this.getRoot(),r=this.nodeWord(),s=[];for(let t of e){s.push(t),n[r]||(n[r]={});let e=n[r][t];null==e&&(e=n[r][t]={key:t,position:s}),n=e}return n.leaf=!0,null!=t&&(n.handler=t),n}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var n=0;n0||!1}}forwardReduceValues(e,t,n,r){let s=e,l=t;for(let e of this.reducers){l=e(s,l)}return l}minorCapture(e,t=this.sep,n=!0){let r="string"==typeof e?e.split(t):e,s=this.aliasConvert(r);s.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(s))s=s.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of s)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=s[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(n)break;let c=s.slice(0,a),u=s.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,n=!0){let r=this.objectSplit(e,t,n);return this.translateValue(r)}insertLine(e,t){let n=this.objectSplit(e);return this.insertRule(n,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let n=!0,r=t||[],s=0,l=[];for(;n;){let t=r[s],i=this.translateMap[t];i?[r,l,s]=i(e,r,l,s):l.push(this.beforeOutStack(r[s],s,e)),s+=1,(s>=r.length||s>100)&&(n=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,n){let r=this.getKeyFunctionMatch(e),s=this.collapseFunctions(r,n);return null==s?e:s}collapseFunctions(e,t){let n;for(var r=e.length-1;r>=0;r--){let s=e[r],l=null==n?s.remainder:n,i=s.handler;n=i&&i(l,s,r,t)||n}return n}getKeyFunctionMatch(e){let t=null!=e,n=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(n);e.success,t=e.match.start>-1,t&&(n=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",n=":"){let r=e.lastIndexOf(t),s=e.length,l=e.slice(r+1,s).split(n),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:s,name:i}};return c.success=null!=a,c}filterClasses(e,t,n=!1){let r=e.classList,s=n?{}:[],l=(e,t,n)=>s.push([n,t]);return n&&(l=(e,t,n)=>s[e]=[n,t]),r.forEach((function(e,n,r){let s=e.split("-")[0];t.indexOf(s)>-1&&l(s,e,n)})),s}filterSplit(e,t,n=!1){let r=this.filterClasses(e,t,n);if(n){let e={};for(let t in r){let n=r[t];e[t]=this.objectSplit(n[1],void 0,void 0,n[0])}return e}let s=[];return r.forEach((e=>{s.push(this.objectSplit(e))})),s}removeRule(e,t=void 0,n=!0){e?.props?.join("-");let r=this.asSelectorString(e,n);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,n=!0){let r=e?.props?.join("-"),s=this.asSelectorString(e,n);if(this.dcss.selectorExists(s))return this.dcss.getRuleBySelector(s);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[s]:l});return e.renderAll(),e}}insertReceiver(e,t){let n=this.addTree(e);return n.handler=t,n}asSelectorString(e,t=!0){let n;if(Array.isArray(e)){let t=e.join("-");n=this.escapeStr(t)}if("string"==typeof e&&(n=this.escapeStr(e)),e.props){let t=e.props.join("-");n=this.escapeStr(t)}e.str&&(n=this.escapeStr(e.str));let r=`.${n}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let n=this.objectSplit(e);return n.values.length>0&&n.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let n of t.rules)e+=`${n.cssText};\n`;return e}captureChanges(e,t,n){this.discoverInsert(e,n),this.discoverRemove(t,n)}discoverInsert(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.handler;(s?s.bind(e):n.insertRule.bind(n))(e)}}discoverRemove(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.unhandler,l=s?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let n=0;for(let r of t)this.safeInsertLine(r,e,n++)}safeInsertLine(e,t,n=-1){let r=this.objectSplit(e,void 0,void 0,n);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,n=!0){let r=function(e){e.classList.forEach((e=>s.add(e)))},s=new Set;return t&&(s=new Map,r=function(e){s.set(e,new Set(e.classList))}),n&&r(e),e.querySelectorAll("*").forEach(r),s}addClass(e,...t){let n=this.asNodes(e);for(let e of n)for(let n of t)for(let t of n.split(" "))e.classList.add(t)}removeClass(e,...t){let n=this.asNodes(e);for(let e of n)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}n.addons={};class r{constructor([e]=[]){this.units=s;let t=new n(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,n){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,n){console.log("innerProxyHandler apply...",n)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,n=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return n;let s=r.value;if(0==s.length)return n;return JSON.parse(s)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return s.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const s=new Map,l={safeSpace:{units:s,addons:[]},get(e,t,n){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,n){return console.log("Polyclass apply...",e,t,n),n[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,n)):this.getInstance.apply(this,n)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);const o=function(e){return h(e)||u(e)||a(e)||c(e)},a=function(e){let t=e.split("/");return 2==t.length&&(o(t[0])&&h(t[1]))},c=function(e){let t=new Set(["deg","grad","rad","turn"]),n=e.slice(parseFloat(e).toString().length,e.length);return t.has(n)},u=function(e){return e.endsWith("%")&&h(e.slice(0,e.length-1))},h=function(e){if(null==e||0==e.length)return!1;return!isNaN(Number(e))},d=function(e){let t=e.slice(4,5),n="";return t.length>0&&(n=`/${t}`),`${e[0]}(${e.slice(1,4).join(" ")}${n})`},f=function(e,t,n,r=void 0){let s=t.length,l=0,i=t.length+1,o=0,a=[];for(;lt.has(e),a=e.length,c=[],u=[],h=[];for(;ls(e,n,r),i=`polyaction_${n}`;void 0===t.dataset[i]?(t.addEventListener(n,l),t.dataset[i]=!0):console.log("Event already exists:",n)},s=function(e,t,n){let[r,...s]=n;console.log(e,t,n),console.log(r,s);let l={call(){},toggle(){console.log(s,n,t),e.currentTarget.classList.toggle(s.join("-"))},setvar(){}}[r];l&&l()};console.log("event receiver"),n.addons.eventsReceiver=function(n){e=n,e.insertReceiver(["event"],t)}}(),function(){let e;const r=function(e){const t=e.values,n=e.origin;let r=c(t,n,e),i=o(t,r,n);s(i),l(r)},s=function(e,t){return d(e,t).forEach((e=>document.head.appendChild(e)))},l=function(t,n){for(let n of Object.values(t)){let t=n.first,r=(e,t)=>t?" ":"",s=i(t.replace(/[+]/g,r));n.cleanName=s,n.definition=a(n),e.dcss.addStylesheetRules(n.definition).renderAll()}},i=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},o=function(e,t,n){t=t||c(e,n);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},a=function(t){let n={};const r=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let s={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},s);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);n[`${r(i)}, ${r(i).toLowerCase()}`]=e}}let s=r(["font",t.first]),l=r(["font"].concat(t.first.split("+"))),i=new Set([s,l,s.toLowerCase(),l.toLowerCase()]);return n[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},n},c=function(t,n,r){let s,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,a=function(t,n){return e.filterSplit(n,t,!0)}(["default"],r?.origin||n),c="sans-serif",h=a.default;if(h)if(h.index<=r.index){let e="font default-* modifier should be indexed after font";console["warn"](e),c=h.values.join(" ")}else c=h.values.join(" ");for(let e in t){let n=t[e];if(0==l){i[l]={first:n,tokens:{},defaultFonts:c},s=l,l++;continue}let[r,a]=[null,null];try{let e;[e,r,a]=n.match(o),0==r.length&&(r="r")}catch{i[l]={first:n,tokens:{}},s=l,l++;continue}let u={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},h={int:Number(a)};if(0==h.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in r){let t=u[r[e]];Object.assign(h,t())}let d=i[s]?.tokens[a]||{};Object.assign(d,h),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:h.ital,token:n}),i[s].tokens[a]=d,l++}return u(i)},u=function(e){for(let t in e){let n=e[t];0!=n.first.length&&h(n)}return e},h=function(e){let t=i(e.first),n=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),r=Object.assign({},...n),s=null!=r.ital,l=[],o=new Set;s&&l.push("ital"),(s||r.regu)&&l.push("wght");for(let t in e.tokens){let n=e.tokens[t],r=n.ital?1:0,l=n.int,i=s?[r]:[];i.push(l);let a=i.join(",");if(o.add(a),null!=n.regu){let e=s?[0]:[];e.push(l);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${l.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:l,titleToken:t,str:u})},d=function(e,t="swap"){return[p("link","preconnect",{href:"https://fonts.googleapis.com"}),p("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),p("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}${null==t?"":`&display=${t}`}`})]};let f={};const p=function(e,t,n){let r={rel:t,href:e};Object.assign(r,n||{});let s=JSON.stringify,l=f[s(r)];return l||(f[s(r)]=g("link",r))},g=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(e);for(let e in t)n.setAttribute(e,t[e]);return n};t.addons.fontPackReceiver=function(t){e=t,e.insertReceiver(["font","pack"],r)},n.prototype.generateGoogleLinks=d,n.prototype.installGoogleLinks=s}(),function(){let e;const t=function(e,t,n,r){return t.value.slice(0,t.match.start),t.args.length>0?t.args[0]:"green"},r=function(e,t,n,r){console.log("raise hook",t,r);let s=t.value.slice(0,t.match.start);console.log(s)};n.addons.functionsReceiver=function(n){e=n,e.keyValueFunctions.set("forceGreen",t),e.keyValueFunctions.set("force",t),e.keyValueFunctions.set("raise",r)}}(),function(){let e;const t=function(t){var n;let s=`family=${`Material+Symbols+${(n=t.values,n.map((function(e){return e.charAt(0).toUpperCase()+e.substring(1,e.length)}))).join("+")}`}:${l({opsz:"20..48",wght:"100..700",FILL:"0..1",GRAD:"-50..200"})}`,a=[...t.values,"icon"];e.insertReceiver(a,o),i.graph.installGoogleLinks(s,null),r(t,fontSettings)},r=function(t,n){let r=t.values[0],l={},i={"font-variation-settings":`${s(n)}`,"font-size":"inherit"};l[`.material-symbols-${r}`]=i,e.dcss.addStylesheetRules(l).renderAll()},s=function(e){let t="",n=Object.keys(e);for(var r=0;r{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&r(e)},n=new MutationObserver((function(e){e.forEach(t)}));return n.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),n},r=function(t){let n=t.target.classList.value,r=t.oldValue,l=n.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==r?[]:r.split(" ").map((e=>e.trim())),o=i?s(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},s=function(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n};n.addons.monitorClasses=function(t){e=t},n.prototype.monitor=function(e=document.body){return t(e)}})(),(()=>{class e extends Map{wordCounter=1;getKey(e){let n=t.get(e);return null==n&&(t.set(e,this.wordCounter),n=this.wordCounter,this.wordCounter++),n}stringToBits(e,t="-"){let n=e.split(t),r=[];return n.forEach(((e,t,n)=>r.push(this.getKey(e)))),r}stringToNest(e,t={}){let n=e.split("-");var r=t;let s=r,l=n.length;return n.forEach(((e,t,n)=>{let s=this.getKey(e),i=t==l-1;null==r[s]?r[s]=r=i?null:{}:r=r[s]})),s}installPropArray(e){e.forEach(((e,t,n)=>{this.stringToNest(e,r)}))}insertBitKey(e,t=r){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,n,r)=>e[t]=n)),e}wordsToArrayString(e=0,t=!1){return t?this.wordsToOrderedArray().join(" "):JSON.stringify(this.wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let n="";return this.forEach(((e,t,r)=>n+=[t,e].join(""))),n}graphToArrayListString(e=r,t=0,n=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,n))}graphToArrayListRecurse(e=r,t=0,n=null){let s=[],l=Object.entries(e);for(let e of l){let r=e[1];s.push([parseInt(e[0]),null==r?n:this.graphToArrayListRecurse(r,t,n)])}return s}graphToObjectString(e=0){let t={};for(let e in r)t[parseInt(e)]=r[e];return JSON.stringify(t,null,e)}}const t=new e,r={},s=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,n,r){const s=n||{row:{reverse:e=>e.join("-")}};let l=t.length,o=0,a=t.length+1,c=0,u=[];for(;oe.join("-");let n=s[r];return null==n&&(n=t),[n(e.slice(0,o+1)),o+1]}return[e[0],1]};n.addons.forwardReduceValues=function(e){return e.reducers.push((function(e,n){return l(e,n,r,t)})),t.installPropArray(s)},n.prototype.valuesGraph={microGraph:r,words:t}})(),function(){let e;const t=function(e,t,n,r){let s=t.slice(r).slice(1),l=`var(--${s.join("-")})`;return n.push(l),[[],n,r+s.length]};n.addons.varTranslateReceiver=function(n){e=n,e.insertTranslator("var",t)}}(),function(){let e,t;const r=function(n,r=":root"){if(console.log("Hook",n),null==t){let s={};for(let e in n){let t=`--${e}`,r=n[e];s[t]=r}let l=e.dcss.addStylesheetRules({[r]:s});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in n){let r=`--${e}`,s=n[e];t.sheetRule.style.setProperty(r,s)}};n.addons.varsReceiver=function(n){e=n,e.vars=r.bind(e),e.varsRoot=t}}(),exports.ClassGraph=n,exports.DynamicCSSStyleSheet=t,exports.Polyclass=i,exports.RenderArray=e; diff --git a/dist/full/esm/polyclass-full.js b/dist/full/esm/polyclass-full.js index 874e2d2..4555368 100755 --- a/dist/full/esm/polyclass-full.js +++ b/dist/full/esm/polyclass-full.js @@ -166,17 +166,17 @@ console.log(blendedcolor, blendedcolor2); })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -382,10 +382,10 @@ class DynamicCSSStyleSheet { } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -530,6 +530,7 @@ class ClassGraph { constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -538,7 +539,7 @@ class ClassGraph { this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -548,8 +549,38 @@ class ClassGraph { this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -813,13 +844,13 @@ class ClassGraph { let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -834,7 +865,13 @@ class ClassGraph { } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -1890,6 +1927,248 @@ const polyclassProxy = { const Polyclass = new Proxy(polyclassHead, polyclassProxy); + +//;(()=>{ + +var installReceiver = function() { + + let keys = new Set([ + /* Hex is a freebie, under the special term `#` hash: #000000 */ + // 'hex', + /* Color property is slightly more complicated, with the first param + as a forced string. */ + // 'color', + + /* Available types, each act the same way: rgb-[3 values][/A] + If the key is a mismatch, its ignored. */ + 'rgb', + 'hsl', + 'hwb', + 'lab', + 'lch', + 'oklab', + 'oklch', + ]); + + ClassGraph.addons.extendedColorValues = function(cg){ + let func = function(prop, values) { + return forwardHotWordReduce(prop, values, keys) + }; + cg.reducers.push(func); + }; +}; + + +/* Return a boolean if the detected type is a valid css value of type: + + Number: 0 | 0.0 + Percent: 0% + Opacity: 0/0 + Angle: 0turn | 0rad +*/ +const isNumOrPerc = function(value) { + return isNumber(value) || isPercent(value) || isOpacityNum(value) || isAngle(value) +}; + +/* Return boolean for the match of a css value with an alpha: 0/0 */ +const isOpacityNum = function(value) { + // '60%/0.8' + let spl = value.split('/'); + if(spl.length == 2) { + return isNumOrPerc(spl[0]) && isNumber(spl[1]) + } + return false +}; + +const isAngle = function(value) { + let types = new Set(["deg","grad","rad","turn"]); + let extra = value.slice(parseFloat(value).toString().length, value.length); + return types.has(extra) +}; + + +const isPercent = function(value) { + return value.endsWith('%') && isNumber(value.slice(0, value.length-1)) +}; + + +const isNumber = function(value) { + if(value == undefined || value.length == 0){ return false } let isNum = !isNaN(Number(value)); + return isNum +}; + + +const asThreeBitColor = function(values) { + let ex = values.slice(4, 5); + let alp = ''; + if(ex.length>0) { + alp = `/${ex}`; + } + return `${values[0]}(${values.slice(1, 4).join(' ')}${alp})` +}; + + +/* Perform a _hot word_ detection on the values recursively. A _hot word_ may be any key. + + forwardHotWordReduce( + ['color'] + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + ) + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail. + +This method then performs this after every release, concatenating changed and +unchanged into a response list. + + rgb-200-200-200-foo + + rgb(200 200 200) foo + + */ +const forwardHotWordReduce = function(props, values, keys, keyTestFunc=undefined) { + /* + Key pops early, and can accept a variable amount of vars. + */ + + let len = values.length + , position = 0 + , max = values.length + 1 + , count = 0 + , response = [] + ; + + while(position < len && count < max) { + let sliced = values.slice(position); + let [key, usedCount] = hotWordReduce(sliced, keys, true, keyTestFunc); + + position += usedCount; + count += 1; + if(Array.isArray(key)) { + response = response.concat(key); + } else { + response.push(key); + } + } + + return response +}; + +/* Perform a _hot word_ detection on the values. A _hot word_ may be any key. + + forwardHotWordReduce( + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + , true + ) + + rgb(200 200 200) // break early + rgb(200 200 200) egg + +For each forward step detect a key, if found the reducer collects as many +forward properties as required, then releases after the first fail if `breakEarly` is true. + + rgb-200-200-200-foo-hsl-20-0%-10-foo + + rgb(200 200 200) foo hsl(20 0% 10) foo + + */ + +const hotWordReduce = function(values, keys + , breakEarly=false + , callback=asThreeBitColor + , keyTestFunc=undefined) { + + var i = 0; + let inSet = (x) => keys.has(x) + , keyStartMatch = keyTestFunc != undefined? keyTestFunc: inSet + , l = values.length + , bits = [] + , kept = [] + , lost = [] + , max = 4 // can be 3 or 4 + ; + + for (;i < l; i++) { + // console.log('---') + let k = values[i]; + let inI = i; + if(keyStartMatch(k)) { + // console.log(i, 'MATCH', k) + let j = i+1; + kept = [k]; + lost = []; + let ok = true; + while(ok && j < l) { + let subI = j; + let subK = values[subI]; + let isNum = isNumOrPerc(subK); + ok = isNum && j < l && kept.length <= (max-1); // +1 for the original key + if(isNum) { + // console.log('Push', subK) + j += 1; + kept.push(subK); + ok = ok && kept.length <= max; // +1 for the original key + } else { + // Lost stack + // console.log('Lost stack on', subK) + // j = 1 + lost.push(subK); + } + // console.log('S', subI, subK, isNum, ok) + } + + let [a,b] = [inI, j]; + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept); + if(plucked.length < 3) { + // console.log('Failed.', bits) + bits = bits.concat(kept); + if(breakEarly) { + return [bits, j] + } + } else { + // console.log('kept', kept, newEntry) + // console.log('plucked', plucked) + bits.push(newEntry); + // Push back 2, as we landed on the bad node, + // and we need step into this node, to stack it. + // + i = j-1; + } + } else { + // console.log(i, k) + bits.push(k); + + if(breakEarly) { + let [a,b] = [inI, kept.length]; + // console.log('a,b ',a, b, values.slice(a,b), kept) + kept.slice(a, b); + let newEntry = callback(kept); + // console.log('plucked', plucked) + // console.log('kept', kept) + if(kept.length < 3) { + // console.log('Failed.', 'kept', kept, 'plucked', plucked) + return [values[b], kept.length+1] + } else { + // console.log('success.') + return [newEntry, kept.length] + } + } + } + } + + // console.log('Done pop', i) + // console.log('in', values, 'out', bits) + + let newEntry = callback(kept); + return [newEntry, i+1] +} + + +;installReceiver(); (function(){ let cg; @@ -2032,6 +2311,8 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); cg = _cg; cg.insertReceiver(['font', 'pack'], fontPackReceiver); }; + ClassGraph.prototype.generateGoogleLinks = generateGoogleLinks; + ClassGraph.prototype.installGoogleLinks = installGoogleLinks; }; /** @@ -2054,15 +2335,18 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); let familyStrings = createFamilyString(values, fonts, origin); // let families = tokenize(values) - - // install as header items - // console.info('Installing Google fonts: familyStrings:', familyStrings) - generateGoogleLinks(familyStrings).forEach((x)=>document.head.appendChild(x)); + installGoogleLinks(familyStrings); // Install additional css additions installFontObjects(fonts); }; + const installGoogleLinks = function(familyStrings, display) { + // install as header items + // console.info('Installing Google fonts: familyStrings:', familyStrings) + return generateGoogleLinks(familyStrings, display).forEach((x)=>document.head.appendChild(x)) + }; + const installFontObjects = function(fonts, splitObj) { // // For value create a font-family; @@ -2387,7 +2671,7 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); }); }; - const generateGoogleLinks = function(familyStrings){ + const generateGoogleLinks = function(familyStrings, display='swap'){ let a = getOrCreateLink('link', 'preconnect', { href: "https://fonts.googleapis.com" @@ -2398,8 +2682,10 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); , crossorigin: '' }); + let ds = display == null? '': `&display=${display}`; + let c = getOrCreateLink('link', "stylesheet", { - href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + href:`https://fonts.googleapis.com/css2?${familyStrings}${ds}` }); return [a,b,c] @@ -2407,6 +2693,18 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); let linkCache = {}; + /* + Create a link node + + let b = getOrCreateLink('link', 'preconnect', { + href: "https://fonts.gstatic.com" + , crossorigin: '' + }) + + let c = getOrCreateLink('link', "stylesheet", { + href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + }) + */ const getOrCreateLink = function(href, rel, opts) { let v = { rel, href @@ -2443,6 +2741,343 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); })() +;(function(){ + + let cg; + + const insertReceiver = function(){ + + ClassGraph.addons.functionsReceiver = function(_cg){ + cg = _cg; + cg.keyValueFunctions.set('forceGreen', forceHook); + cg.keyValueFunctions.set('force', forceHook); + cg.keyValueFunctions.set('raise', raiseHook); + }; + }; + + const forceHook = function(value, token, index, splitObj) { + // console.log('Force green hook', token, splitObj) + token.value.slice(0, token.match.start); + // console.log(res) + // return res + + return token.args.length > 0? token.args[0]: 'green' + }; + + const raiseHook = function(value, token, index, splitObj) { + console.log('raise hook', token, splitObj); + let res = token.value.slice(0, token.match.start); + console.log(res); + // return res + }; +insertReceiver(); +})(); +(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver); + // cg.insertReceiver(['icon'], iconReceiver) + }; + }; + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + + let key = titleCase(obj.values).join('+'); + let family = `Material+Symbols+${key}`; + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + }; + let familyString = toGoogleFontParamsStr(opts); + let fontStr = `family=${family}:${familyString}`; + + let receiverBits = [...obj.values, 'icon']; + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver); + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null); + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings); + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + }; + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0]; + let rules = {}; + + let fontSettingsStr = toObjectParamStr(fontSettings); + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + }; + + rules[`.material-symbols-${key}`] = conf; + let items = cg.dcss.addStylesheetRules(rules); + + items.renderAll(); + }; + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj); + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i]; + let v = obj[k]; + let last = i == fKeys.length-1; + let end = last? '': ',\n'; + fontSettingsStr += `'${k}' ${v}${end}`; + } + return fontSettingsStr + + }; + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(','); + let v = Object.values(obj).join(','); + return `${k}@${v}` + }; + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + obj.values; obj.origin; + console.log('render icon', obj); + + return contentInjection(obj) + }; + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)); + origin.innerText += `${values.join('_')}`; + }; + + const getInjectClass = function(obj) { + let k = obj.props[0]; + return `material-symbols-${k}` + } + + ;insertReceiver(); +})() + +;(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver); + // cg.insertReceiver(['icon'], iconReceiver) + }; + }; + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + console.log('Install the font', obj); + let key = titleCase(obj.values).join('+'); + let family = `Material+Symbols+${key}`; + let fontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + }; + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + }; + let familyString = toGoogleFontParamsStr(opts); + let fontStr = `family=${family}:${familyString}`; + + let receiverBits = [...obj.values, 'icon']; + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver); + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null); + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings); + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + }; + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0]; + let rules = {}; + + let fontSettingsStr = toObjectParamStr(fontSettings); + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + }; + + rules[`.material-symbols-${key}`] = conf; + let items = cg.dcss.addStylesheetRules(rules); + + items.renderAll(); + }; + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj); + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i]; + let v = obj[k]; + let last = i == fKeys.length-1; + let end = last? '': ',\n'; + fontSettingsStr += `'${k}' ${v}${end}`; + } + return fontSettingsStr + + }; + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(','); + let v = Object.values(obj).join(','); + return `${k}@${v}` + }; + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + obj.values; obj.origin; + console.log('render icon', obj); + + return contentInjection(obj) + }; + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)); + origin.innerText += `${values.join('_')}`; + }; + + const getInjectClass = function(obj) { + let k = obj.props[0]; + return `material-symbols-${k}` + } + + ;insertReceiver(); +})() + /** * # Monitor * @@ -2548,194 +3183,34 @@ const difference = function(setA, setB) { })() /* +Convert discovered nodes and bind them to a selector. The assigned classes +are the declarations assigned to the css class. -vars box. To assign key variables as accessible CSS varialbes through a js -definition. The definition is bound to DCSS, so edits to the vars manipulates -the view automatically. +The discovery may descend children, allowing for depth setup. - vars({ - primary: "#880000" # company red - , secondary: "#111" # dark - , accent: "red" - }) + -In the node, we access the vars reciever + + -
-

An elk called Elk lives here.

-
+
-Manipulating the var propagates to the view: - vars.primary = "#EEE" # off white - ---- - -## Secondary App - - `swatch()` - and colors.js - - Assign "colors" to a swatch of colors, each color is a function from the - colors.js module and can assign math relations to swatches. - Chaning a swatch (such as its base color), can manipulate the other - colours according to the chosen swatch type, e.g. "Diachromic". - - */ - -;(function(){ - - let cg; - let rootRule; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varsReceiver = function(_cg){ - cg = _cg; - cg.vars = varsHook.bind(cg); - // cg.varsRootDelaration = rootDeclaration - cg.varsRoot = rootRule; - // cg.insertTranslator('var', variableDigest) - }; - }; - - - const varsHook = function(d, target=':root') { - /** vars() function bound to the classgraph. _this_ is the classgraph - instance `cg.vars = varsHook.bind(cg)` - - each key is a var, value is the param - - { - apples: green - , foo: 10 - , bar: 1em - , baz: #444 - } - - Each var is installed on the target node: - - :root { - --apples: green - ... - --baz: #444 - } - - if an existing "vars" object exists, it's updated. - - */ - // target = document.querySelector(target) - console.log('Hook', d); - - if(rootRule == undefined) { - let rootDeclaration = {}; - - for(let key in d) { - let prop = `--${key}`; - let value = d[key]; - rootDeclaration[prop] = value; - } - - let rules = cg.dcss.addStylesheetRules({ - [target]: rootDeclaration - }); - - rules.renderAll(); - rootRule = rules[0]; - cg.varsRoot = rootRule; - } else { - - // rootRule - // let pr = rootRule.getPropStr([target,Object.entries(definition)]) - // rootRule.sheetRule.cssText = `${target} { ${pr} }` - // rootRule.replace(`${target} { ${pr} }`) - - for(let key in d) { - let prop = `--${key}`; - let value = d[key]; - rootRule.sheetRule.style.setProperty(prop, value); - } - // rootRule.render() - // console.log(rootRule) - // window.varsRule = rootRule - } - } - - ;insertReceiver(); -})() - -/** - * # var-* Translate - * - * https://developer.mozilla.org/en-US/docs/Web/CSS/var - * - * Discover and rewrite class names values with `var-*` to the CSS function - * `var(*)`. e.g. - * - * "border-top-var-primary-edges" - * - * { - * "border-top": var(--primary-edges) - * } - */ -;(function(){ - - let cg; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // console.log('var-translate insertReceiver') - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varTranslateReceiver = function(_cg){ - cg = _cg; - cg.insertTranslator('var', variableDigest2); - // cg.insertTranslator('var', variableDigest) - }; - }; - - - const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ - - let keys = inStack.slice(currentIndex); - let k1 = keys.slice(1); - let word = `var(--${k1.join("-")})`; - - outStack.push(word); - // return [inStack, outStack, currentIndex] - return [[], outStack, currentIndex + k1.length] - } - - - - ;insertReceiver(); -})() - +Notably this may be easier as real CSS. + */ /* The words map lists all the unique string CSS values. Each word maps to an @@ -2816,10 +3291,10 @@ class Words extends Map { wordsToArrayString(indent=0, small=false){ if(!small) { - return JSON.stringify(wordsToOrderedArray(), null, indent) + return JSON.stringify(this.wordsToOrderedArray(), null, indent) } - return wordsToOrderedArray().join(' ') + return this.wordsToOrderedArray().join(' ') } wordsToObjectString(indent=0, small=false) { @@ -2859,6 +3334,75 @@ class Words extends Map { } } +/* +1. all the items have string in position +2. the we create the flat array list +each position is a word from the string list + + "all-petite-caps", + "all-scroll", + "all-small-caps", + +as a string: + + " all petite caps scroll small ..." + +Becomes: + [1, [ + [2, [ + [3, null] + ] + ], + [4, null], + [5, [ + [3,null] + ] + ] + ] + ] + +--- + +When loaded, we can re-ask for the prop: + + w.stringToBits("all-petite-caps") + [1,2,3] + +The last key + + w.stringToBits("zoom") + [211] + w.stringToBits("zoom-out") + [211, 66] +--- + + + "all-petite-caps", + "all-scroll", + "all-small-caps", + "allow-end", + "alternate-reverse", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2", + "0-3", + "0-4-5", + "6-7", + "8-9", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2 0-3 0-4-5 6-7 8-9" + + "all petite caps scroll small allow end alternate reverse", + "0 1 2,0 3,0 4 5,6 7,8 9" + + // radix each key through 32 bits, allowing ~1000 positions as 2bits + // not really helpful under 100 keys, but then saves 1 char per position (up to 1k) + // .. With 255~ keys thats 150~ chars saved. + // In a 32bit radix, the first 31 positions are single chars. +--- + +*/ const words = new Words() , microGraph = {} @@ -3065,8 +3609,16 @@ const words = new Words() var installReceiver = function() { - ClassGraph.addons.forwardReduceValues = (cg) => words.installPropArray(dashprops); - ClassGraph.prototype.forwardReduceValues = forwardReduceValues; + ClassGraph.addons.forwardReduceValues = function(cg){ + let func = function(prop, values) { + return forwardReduceValues(prop, values, microGraph, words) + }; + cg.reducers.push(func); + let res = words.installPropArray(dashprops); + return res; + }; + // install one of many + // ClassGraph.prototype.forwardReduceValues = forwardReduceValues ClassGraph.prototype.valuesGraph = { microGraph, words }; }; @@ -3096,9 +3648,6 @@ const forwardReduceValues = function(props, values, microGraph, translations) { 'row': { 'reverse': merge } - , 'other': { - 'horse': merge - } }; let len = values.length @@ -3154,6 +3703,194 @@ const popOneValueForward = function(values, microGraph, translations) { ;installReceiver(); +})() +/** + * # var-* Translate + * + * https://developer.mozilla.org/en-US/docs/Web/CSS/var + * + * Discover and rewrite class names values with `var-*` to the CSS function + * `var(*)`. e.g. + * + * "border-top-var-primary-edges" + * + * { + * "border-top": var(--primary-edges) + * } + */ +;(function(){ + + let cg; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // console.log('var-translate insertReceiver') + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varTranslateReceiver = function(_cg){ + cg = _cg; + cg.insertTranslator('var', variableDigest2); + // cg.insertTranslator('var', variableDigest) + }; + }; + + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + let keys = inStack.slice(currentIndex); + let k1 = keys.slice(1); + let word = `var(--${k1.join("-")})`; + + outStack.push(word); + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + + + ;insertReceiver(); +})() + +/* + +vars box. To assign key variables as accessible CSS varialbes through a js +definition. The definition is bound to DCSS, so edits to the vars manipulates +the view automatically. + + vars({ + primary: "#880000" # company red + , secondary: "#111" # dark + , accent: "red" + }) + +In the node, we access the vars reciever + +
+

An elk called Elk lives here.

+
+ +Manipulating the var propagates to the view: + + vars.primary = "#EEE" # off white + +--- + +## Secondary App + + `swatch()` + and colors.js + + Assign "colors" to a swatch of colors, each color is a function from the + colors.js module and can assign math relations to swatches. + Chaning a swatch (such as its base color), can manipulate the other + colours according to the chosen swatch type, e.g. "Diachromic". + + */ + +;(function(){ + + let cg; + let rootRule; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varsReceiver = function(_cg){ + cg = _cg; + cg.vars = varsHook.bind(cg); + // cg.varsRootDelaration = rootDeclaration + cg.varsRoot = rootRule; + // cg.insertTranslator('var', variableDigest) + }; + }; + + + const varsHook = function(d, target=':root') { + /** vars() function bound to the classgraph. _this_ is the classgraph + instance `cg.vars = varsHook.bind(cg)` + + each key is a var, value is the param + + { + apples: green + , foo: 10 + , bar: 1em + , baz: #444 + } + + Each var is installed on the target node: + + :root { + --apples: green + ... + --baz: #444 + } + + if an existing "vars" object exists, it's updated. + + */ + // target = document.querySelector(target) + console.log('Hook', d); + + if(rootRule == undefined) { + let rootDeclaration = {}; + + for(let key in d) { + let prop = `--${key}`; + let value = d[key]; + rootDeclaration[prop] = value; + } + + let rules = cg.dcss.addStylesheetRules({ + [target]: rootDeclaration + }); + + rules.renderAll(); + rootRule = rules[0]; + cg.varsRoot = rootRule; + } else { + + // rootRule + // let pr = rootRule.getPropStr([target,Object.entries(definition)]) + // rootRule.sheetRule.cssText = `${target} { ${pr} }` + // rootRule.replace(`${target} { ${pr} }`) + + for(let key in d) { + let prop = `--${key}`; + let value = d[key]; + rootRule.sheetRule.style.setProperty(prop, value); + } + // rootRule.render() + // console.log(rootRule) + // window.varsRule = rootRule + } + } + + ;insertReceiver(); })(); export { ClassGraph, DynamicCSSStyleSheet, Polyclass, RenderArray }; diff --git a/dist/full/esm/polyclass-full.min.js b/dist/full/esm/polyclass-full.min.js index f5a5e67..7dcf530 100755 --- a/dist/full/esm/polyclass-full.min.js +++ b/dist/full/esm/polyclass-full.min.js @@ -1 +1 @@ -document.createElement("span"),(()=>{var e=Math.round,t=parseInt,r=(e,t,r)=>`rgb(${e},${t},${r})`;let s=function(e,t="#000000",r="#FFFFFF"){return e||(h?t:r)},n=function(e){return s(e,r(0,0,0),r(255,255,255))},l=function(e,t,r){let s=e>>t;return r?s&r:s},i=function(e,t,r,s){let n=l(e,t,r);return a(n,s)},o=(e,r)=>a(t(e),r),a=function(t,r){return e(c(t-r))+r},c=function(e){return e*u};var u,h;function d(e,l,i){return u=(h=e<0)?-1*e:e,l.length>7?function(e,s,l){let i=s.split(","),a=n(l),c=a.split(","),u=t(i[0].slice(4)),h=t(i[1]),d=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],h),g=o(c[2],d);return r(f,p,g)}(0,l,i):function(e,r,n){var l=t(r.slice(1),16),i=s(n).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,r,s){let n=l(e,r,s);return i(t,r,s,n)}function p(e,t,r){var s=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(r||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*s)+a)+","+(n((l(o[1])-c)*s)+c)+","+(n((l(o[2])-u)*s)+u)+")"}var h=(i=l(t.slice(1),16))>>16,d=i>>8&255,f=255&i;return"#"+(16777216+65536*(n((((o=l((r||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-h)*s)+h)+256*(n(((o>>8&255)-d)*s)+d)+(n(((255&o)-f)*s)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",m="rgb(120,99,248)";blendedcolor=d(-.8,b,m),blendedcolor2=p(-.8,b,m),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=d(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let r in t){(0,t[r])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,r=e||this.styleEl;if(null!=r)return r;if("sheet"==this.insertMethod&&(r=document.createElement("style"),document.head.appendChild(r),t=r.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,r){let s=this.getEnsureStyleSheet(r),n=new e,l=s;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,r]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,r)=>(r?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let r=this.getRoot(),s=this.nodeWord(),n=[];for(let t of e){n.push(t),r[s]||(r[s]={});let e=r[s][t];null==e&&(e=r[s][t]={key:t,position:n}),r=e}return r.leaf=!0,null!=t&&(r.handler=t),r}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var r=0;r0||!1}}forwardReduceValues(e,t,r,s){return t}minorCapture(e,t=this.sep,r=!0){let s="string"==typeof e?e.split(t):e,n=this.aliasConvert(s);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(r)break;let c=n.slice(0,a),u=n.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,r=!0){let s=this.objectSplit(e,t,r);return this.translateValue(s)}insertLine(e,t){let r=this.objectSplit(e);return this.insertRule(r,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let r=!0,s=t||[],n=0,l=[];for(;r;){let t=s[n],i=this.translateMap[t];i?[s,l,n]=i(e,s,l,n):l.push(this.beforeOutStack(s[n],n,e)),n+=1,(n>=s.length||n>100)&&(r=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,r){let s=this.getKeyFunctionMatch(e),n=this.collapseFunctions(s,r);return null==n?e:n}collapseFunctions(e,t){let r;for(var s=e.length-1;s>=0;s--){let n=e[s],l=null==r?n.remainder:r,i=n.handler;r=i&&i(l,n,s,t)||r}return r}getKeyFunctionMatch(e){let t=null!=e,r=e,s=[];for(;t;){let e=this.getKeyFunctionMatchOnce(r);e.success,t=e.match.start>-1,t&&(r=e.remainder,s.push(e))}return s}getKeyFunctionMatchOnce(e,t=".",r=":"){let s=e.lastIndexOf(t),n=e.length,l=e.slice(s+1,n).split(r),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,s),handler:a,args:o,match:{start:s,end:n,name:i}};return c.success=null!=a,c}filterClasses(e,t,r=!1){let s=e.classList,n=r?{}:[],l=(e,t,r)=>n.push([r,t]);return r&&(l=(e,t,r)=>n[e]=[r,t]),s.forEach((function(e,r,s){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,r)})),n}filterSplit(e,t,r=!1){let s=this.filterClasses(e,t,r);if(r){let e={};for(let t in s){let r=s[t];e[t]=this.objectSplit(r[1],void 0,void 0,r[0])}return e}let n=[];return s.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,r=!0){e?.props?.join("-");let s=this.asSelectorString(e,r);this.dcss.selectorExists(s)&&this.dcss.removeRuleBySelector(s)}insertRule(e,t=void 0,r=!0){let s=e?.props?.join("-"),n=this.asSelectorString(e,r);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[s]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let r=this.addTree(e);return r.handler=t,r}asSelectorString(e,t=!0){let r;if(Array.isArray(e)){let t=e.join("-");r=this.escapeStr(t)}if("string"==typeof e&&(r=this.escapeStr(e)),e.props){let t=e.props.join("-");r=this.escapeStr(t)}e.str&&(r=this.escapeStr(e.str));let s=`.${r}`;return t?this.prependParent(s,e):s}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let r=this.objectSplit(e);return r.values.length>0&&r.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let r of t.rules)e+=`${r.cssText};\n`;return e}captureChanges(e,t,r){this.discoverInsert(e,r),this.discoverRemove(t,r)}discoverInsert(e,t){let r=this;for(let s of e){if(0==s.length)continue;let e=r.objectSplit(s);e.origin=t;let n=e.node?.handler;(n?n.bind(e):r.insertRule.bind(r))(e)}}discoverRemove(e,t){let r=this;for(let s of e){if(0==s.length)continue;let e=r.objectSplit(s);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let r=0;for(let s of t)this.safeInsertLine(s,e,r++)}safeInsertLine(e,t,r=-1){let s=this.objectSplit(e,void 0,void 0,r);return s.valid&&(s.origin=t,this.insertRule(s)),s}getAllClasses(e=document.body,t=!1,r=!0){let s=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,s=function(e){n.set(e,new Set(e.classList))}),r&&s(e),e.querySelectorAll("*").forEach(s),n}addClass(e,...t){let r=this.asNodes(e);for(let e of r)for(let r of t)for(let t of r.split(" "))e.classList.add(t)}removeClass(e,...t){let r=this.asNodes(e);for(let e of r)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}r.addons={};class s{constructor([e]=[]){this.units=n;let t=new r(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,r){let s=this.reference;if(t in s)return s[t].bind?s[t].bind(s):s[t]},apply(e,t,r){console.log("innerProxyHandler apply...",r)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,r=void 0){const s=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===s)return r;let n=s.value;if(0==n.length)return r;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,r){let s=this.getInstance();if(t in s){let e=s[t];return e&&e.bind?e.bind(s):e}return this.safeSpace[t]},newInstance(){return new s(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,r){return console.log("Polyclass apply...",e,t,r),r[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,r)):this.getInstance.apply(this,r)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);!function(){let e;const t=function(e,t){values=e.values;let[r,...n]=e.values;if(void 0!==document[`on${r}`]){const t=e.origin;s(e,t,r,n)}else console.warn("Unknown action",r)},s=function(e,t,r,s){let l=e=>n(e,r,s),i=`polyaction_${r}`;void 0===t.dataset[i]?(t.addEventListener(r,l),t.dataset[i]=!0):console.log("Event already exists:",r)},n=function(e,t,r){let[s,...n]=r;console.log(e,t,r),console.log(s,n);let l={call(){},toggle(){console.log(n,r,t),e.currentTarget.classList.toggle(n.join("-"))},setvar(){}}[s];l&&l()};console.log("event receiver"),r.addons.eventsReceiver=function(r){e=r,e.insertReceiver(["event"],t)}}(),function(){let e;const r=function(e){const t=e.values,r=e.origin;let n=o(t,r,e),i=l(t,n,r);u(i).forEach((e=>document.head.appendChild(e))),s(n)},s=function(t,r){for(let r of Object.values(t)){let t=r.first,s=(e,t)=>t?" ":"",l=n(t.replace(/[+]/g,s));r.cleanName=l,r.definition=i(r),e.dcss.addStylesheetRules(r.definition).renderAll()}},n=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},l=function(e,t,r){t=t||o(e,r);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},i=function(t){let r={};const s=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let n={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},n);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);r[`${s(i)}, ${s(i).toLowerCase()}`]=e}}let n=s(["font",t.first]),l=s(["font"].concat(t.first.split("+"))),i=new Set([n,l,n.toLowerCase(),l.toLowerCase()]);return r[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},r},o=function(t,r,s){let n,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,c=function(t,r){return e.filterSplit(r,t,!0)}(["default"],s?.origin||r),u="sans-serif",h=c.default;if(h)if(h.index<=s.index){let e="font default-* modifier should be indexed after font";console["warn"](e),u=h.values.join(" ")}else u=h.values.join(" ");for(let e in t){let r=t[e];if(0==l){i[l]={first:r,tokens:{},defaultFonts:u},n=l,l++;continue}let[s,a]=[null,null];try{let e;[e,s,a]=r.match(o),0==s.length&&(s="r")}catch{i[l]={first:r,tokens:{}},n=l,l++;continue}let c={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},h={int:Number(a)};if(0==h.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in s){let t=c[s[e]];Object.assign(h,t())}let d=i[n]?.tokens[a]||{};Object.assign(d,h),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:h.ital,token:r}),i[n].tokens[a]=d,l++}return a(i)},a=function(e){for(let t in e){let r=e[t];0!=r.first.length&&c(r)}return e},c=function(e){let t=n(e.first),r=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),s=Object.assign({},...r),l=null!=s.ital,i=[],o=new Set;l&&i.push("ital"),(l||s.regu)&&i.push("wght");for(let t in e.tokens){let r=e.tokens[t],s=r.ital?1:0,n=r.int,i=l?[s]:[];i.push(n);let a=i.join(",");if(o.add(a),null!=r.regu){let e=l?[0]:[];e.push(n);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${i.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:i,titleToken:t,str:u})},u=function(e){return[d("link","preconnect",{href:"https://fonts.googleapis.com"}),d("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),d("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}&display=swap`})]};let h={};const d=function(e,t,r){let s={rel:t,href:e};Object.assign(s,r||{});let n=JSON.stringify,l=h[n(s)];return l||(h[n(s)]=f("link",s))},f=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let r=document.createElement(e);for(let e in t)r.setAttribute(e,t[e]);return r};t.addons.fontPackReceiver=function(t){e=t,e.insertReceiver(["font","pack"],r)}}(),(()=>{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&s(e)},r=new MutationObserver((function(e){e.forEach(t)}));return r.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),r},s=function(t){let r=t.target.classList.value,s=t.oldValue,l=r.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==s?[]:s.split(" ").map((e=>e.trim())),o=i?n(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},n=function(e,t){const r=new Set(e);for(const e of t)r.delete(e);return r};r.addons.monitorClasses=function(t){e=t},r.prototype.monitor=function(e=document.body){return t(e)}})(),function(){let e,t;const s=function(r,s=":root"){if(console.log("Hook",r),null==t){let n={};for(let e in r){let t=`--${e}`,s=r[e];n[t]=s}let l=e.dcss.addStylesheetRules({[s]:n});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in r){let s=`--${e}`,n=r[e];t.sheetRule.style.setProperty(s,n)}};r.addons.varsReceiver=function(r){e=r,e.vars=s.bind(e),e.varsRoot=t}}(),function(){let e;const t=function(e,t,r,s){let n=t.slice(s).slice(1),l=`var(--${n.join("-")})`;return r.push(l),[[],r,s+n.length]};r.addons.varTranslateReceiver=function(r){e=r,e.insertTranslator("var",t)}}(),(()=>{class e extends Map{wordCounter=1;getKey(e){let r=t.get(e);return null==r&&(t.set(e,this.wordCounter),r=this.wordCounter,this.wordCounter++),r}stringToBits(e,t="-"){let r=e.split(t),s=[];return r.forEach(((e,t,r)=>s.push(this.getKey(e)))),s}stringToNest(e,t={}){let r=e.split("-");var s=t;let n=s,l=r.length;return r.forEach(((e,t,r)=>{let n=this.getKey(e),i=t==l-1;null==s[n]?s[n]=s=i?null:{}:s=s[n]})),n}installPropArray(e){e.forEach(((e,t,r)=>{this.stringToNest(e,s)}))}insertBitKey(e,t=s){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,r,s)=>e[t]=r)),e}wordsToArrayString(e=0,t=!1){return t?wordsToOrderedArray().join(" "):JSON.stringify(wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let r="";return this.forEach(((e,t,s)=>r+=[t,e].join(""))),r}graphToArrayListString(e=s,t=0,r=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,r))}graphToArrayListRecurse(e=s,t=0,r=null){let n=[],l=Object.entries(e);for(let e of l){let s=e[1];n.push([parseInt(e[0]),null==s?r:this.graphToArrayListRecurse(s,t,r)])}return n}graphToObjectString(e=0){let t={};for(let e in s)t[parseInt(e)]=s[e];return JSON.stringify(t,null,e)}}const t=new e,s={},n=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,r,s){const n=e=>e.join("-"),l=r||{row:{reverse:n},other:{horse:n}};let o=t.length,a=0,c=t.length+1,u=0,h=[];for(;ae.join("-");let r=n[s];return null==r&&(r=t),[r(e.slice(0,o+1)),o+1]}return[e[0],1]};r.addons.forwardReduceValues=e=>t.installPropArray(n),r.prototype.forwardReduceValues=l,r.prototype.valuesGraph={microGraph:s,words:t}})();export{r as ClassGraph,t as DynamicCSSStyleSheet,i as Polyclass,e as RenderArray}; +document.createElement("span"),(()=>{var e=Math.round,t=parseInt,n=(e,t,n)=>`rgb(${e},${t},${n})`;let r=function(e,t="#000000",n="#FFFFFF"){return e||(h?t:n)},s=function(e){return r(e,n(0,0,0),n(255,255,255))},l=function(e,t,n){let r=e>>t;return n?r&n:r},i=function(e,t,n,r){let s=l(e,t,n);return a(s,r)},o=(e,n)=>a(t(e),n),a=function(t,n){return e(c(t-n))+n},c=function(e){return e*u};var u,h;function d(e,l,i){return u=(h=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=s(l),c=a.split(","),u=t(i[0].slice(4)),h=t(i[1]),d=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],h),g=o(c[2],d);return n(f,p,g)}(0,l,i):function(e,n,s){var l=t(n.slice(1),16),i=r(s).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,n,r){let s=l(e,n,r);return i(t,n,r,s)}function p(e,t,n){var r=e<0?-1*e:e,s=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(n||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(s((l(o[0].slice(4))-a)*r)+a)+","+(s((l(o[1])-c)*r)+c)+","+(s((l(o[2])-u)*r)+u)+")"}var h=(i=l(t.slice(1),16))>>16,d=i>>8&255,f=255&i;return"#"+(16777216+65536*(s((((o=l((n||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-h)*r)+h)+256*(s(((o>>8&255)-d)*r)+d)+(s(((255&o)-f)*r)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=d(-.8,b,v),blendedcolor2=p(-.8,b,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=d(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let n in t){(0,t[n])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,n=e||this.styleEl;if(null!=n)return n;if("sheet"==this.insertMethod&&(n=document.createElement("style"),document.head.appendChild(n),t=n.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,n){let r=this.getEnsureStyleSheet(n),s=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,n]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,n)=>(n?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let n=this.getRoot(),r=this.nodeWord(),s=[];for(let t of e){s.push(t),n[r]||(n[r]={});let e=n[r][t];null==e&&(e=n[r][t]={key:t,position:s}),n=e}return n.leaf=!0,null!=t&&(n.handler=t),n}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var n=0;n0||!1}}forwardReduceValues(e,t,n,r){let s=e,l=t;for(let e of this.reducers){l=e(s,l)}return l}minorCapture(e,t=this.sep,n=!0){let r="string"==typeof e?e.split(t):e,s=this.aliasConvert(r);s.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(s))s=s.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of s)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=s[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(n)break;let c=s.slice(0,a),u=s.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,n=!0){let r=this.objectSplit(e,t,n);return this.translateValue(r)}insertLine(e,t){let n=this.objectSplit(e);return this.insertRule(n,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let n=!0,r=t||[],s=0,l=[];for(;n;){let t=r[s],i=this.translateMap[t];i?[r,l,s]=i(e,r,l,s):l.push(this.beforeOutStack(r[s],s,e)),s+=1,(s>=r.length||s>100)&&(n=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,n){let r=this.getKeyFunctionMatch(e),s=this.collapseFunctions(r,n);return null==s?e:s}collapseFunctions(e,t){let n;for(var r=e.length-1;r>=0;r--){let s=e[r],l=null==n?s.remainder:n,i=s.handler;n=i&&i(l,s,r,t)||n}return n}getKeyFunctionMatch(e){let t=null!=e,n=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(n);e.success,t=e.match.start>-1,t&&(n=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",n=":"){let r=e.lastIndexOf(t),s=e.length,l=e.slice(r+1,s).split(n),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:s,name:i}};return c.success=null!=a,c}filterClasses(e,t,n=!1){let r=e.classList,s=n?{}:[],l=(e,t,n)=>s.push([n,t]);return n&&(l=(e,t,n)=>s[e]=[n,t]),r.forEach((function(e,n,r){let s=e.split("-")[0];t.indexOf(s)>-1&&l(s,e,n)})),s}filterSplit(e,t,n=!1){let r=this.filterClasses(e,t,n);if(n){let e={};for(let t in r){let n=r[t];e[t]=this.objectSplit(n[1],void 0,void 0,n[0])}return e}let s=[];return r.forEach((e=>{s.push(this.objectSplit(e))})),s}removeRule(e,t=void 0,n=!0){e?.props?.join("-");let r=this.asSelectorString(e,n);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,n=!0){let r=e?.props?.join("-"),s=this.asSelectorString(e,n);if(this.dcss.selectorExists(s))return this.dcss.getRuleBySelector(s);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[s]:l});return e.renderAll(),e}}insertReceiver(e,t){let n=this.addTree(e);return n.handler=t,n}asSelectorString(e,t=!0){let n;if(Array.isArray(e)){let t=e.join("-");n=this.escapeStr(t)}if("string"==typeof e&&(n=this.escapeStr(e)),e.props){let t=e.props.join("-");n=this.escapeStr(t)}e.str&&(n=this.escapeStr(e.str));let r=`.${n}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let n=this.objectSplit(e);return n.values.length>0&&n.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let n of t.rules)e+=`${n.cssText};\n`;return e}captureChanges(e,t,n){this.discoverInsert(e,n),this.discoverRemove(t,n)}discoverInsert(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.handler;(s?s.bind(e):n.insertRule.bind(n))(e)}}discoverRemove(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.unhandler,l=s?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let n=0;for(let r of t)this.safeInsertLine(r,e,n++)}safeInsertLine(e,t,n=-1){let r=this.objectSplit(e,void 0,void 0,n);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,n=!0){let r=function(e){e.classList.forEach((e=>s.add(e)))},s=new Set;return t&&(s=new Map,r=function(e){s.set(e,new Set(e.classList))}),n&&r(e),e.querySelectorAll("*").forEach(r),s}addClass(e,...t){let n=this.asNodes(e);for(let e of n)for(let n of t)for(let t of n.split(" "))e.classList.add(t)}removeClass(e,...t){let n=this.asNodes(e);for(let e of n)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}n.addons={};class r{constructor([e]=[]){this.units=s;let t=new n(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,n){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,n){console.log("innerProxyHandler apply...",n)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,n=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return n;let s=r.value;if(0==s.length)return n;return JSON.parse(s)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return s.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const s=new Map,l={safeSpace:{units:s,addons:[]},get(e,t,n){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,n){return console.log("Polyclass apply...",e,t,n),n[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,n)):this.getInstance.apply(this,n)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);const o=function(e){return h(e)||u(e)||a(e)||c(e)},a=function(e){let t=e.split("/");return 2==t.length&&(o(t[0])&&h(t[1]))},c=function(e){let t=new Set(["deg","grad","rad","turn"]),n=e.slice(parseFloat(e).toString().length,e.length);return t.has(n)},u=function(e){return e.endsWith("%")&&h(e.slice(0,e.length-1))},h=function(e){if(null==e||0==e.length)return!1;return!isNaN(Number(e))},d=function(e){let t=e.slice(4,5),n="";return t.length>0&&(n=`/${t}`),`${e[0]}(${e.slice(1,4).join(" ")}${n})`},f=function(e,t,n,r=void 0){let s=t.length,l=0,i=t.length+1,o=0,a=[];for(;lt.has(e),a=e.length,c=[],u=[],h=[];for(;ls(e,n,r),i=`polyaction_${n}`;void 0===t.dataset[i]?(t.addEventListener(n,l),t.dataset[i]=!0):console.log("Event already exists:",n)},s=function(e,t,n){let[r,...s]=n;console.log(e,t,n),console.log(r,s);let l={call(){},toggle(){console.log(s,n,t),e.currentTarget.classList.toggle(s.join("-"))},setvar(){}}[r];l&&l()};console.log("event receiver"),n.addons.eventsReceiver=function(n){e=n,e.insertReceiver(["event"],t)}}(),function(){let e;const r=function(e){const t=e.values,n=e.origin;let r=c(t,n,e),i=o(t,r,n);s(i),l(r)},s=function(e,t){return d(e,t).forEach((e=>document.head.appendChild(e)))},l=function(t,n){for(let n of Object.values(t)){let t=n.first,r=(e,t)=>t?" ":"",s=i(t.replace(/[+]/g,r));n.cleanName=s,n.definition=a(n),e.dcss.addStylesheetRules(n.definition).renderAll()}},i=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},o=function(e,t,n){t=t||c(e,n);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},a=function(t){let n={};const r=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let s={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},s);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);n[`${r(i)}, ${r(i).toLowerCase()}`]=e}}let s=r(["font",t.first]),l=r(["font"].concat(t.first.split("+"))),i=new Set([s,l,s.toLowerCase(),l.toLowerCase()]);return n[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},n},c=function(t,n,r){let s,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,a=function(t,n){return e.filterSplit(n,t,!0)}(["default"],r?.origin||n),c="sans-serif",h=a.default;if(h)if(h.index<=r.index){let e="font default-* modifier should be indexed after font";console["warn"](e),c=h.values.join(" ")}else c=h.values.join(" ");for(let e in t){let n=t[e];if(0==l){i[l]={first:n,tokens:{},defaultFonts:c},s=l,l++;continue}let[r,a]=[null,null];try{let e;[e,r,a]=n.match(o),0==r.length&&(r="r")}catch{i[l]={first:n,tokens:{}},s=l,l++;continue}let u={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},h={int:Number(a)};if(0==h.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in r){let t=u[r[e]];Object.assign(h,t())}let d=i[s]?.tokens[a]||{};Object.assign(d,h),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:h.ital,token:n}),i[s].tokens[a]=d,l++}return u(i)},u=function(e){for(let t in e){let n=e[t];0!=n.first.length&&h(n)}return e},h=function(e){let t=i(e.first),n=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),r=Object.assign({},...n),s=null!=r.ital,l=[],o=new Set;s&&l.push("ital"),(s||r.regu)&&l.push("wght");for(let t in e.tokens){let n=e.tokens[t],r=n.ital?1:0,l=n.int,i=s?[r]:[];i.push(l);let a=i.join(",");if(o.add(a),null!=n.regu){let e=s?[0]:[];e.push(l);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${l.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:l,titleToken:t,str:u})},d=function(e,t="swap"){return[p("link","preconnect",{href:"https://fonts.googleapis.com"}),p("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),p("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}${null==t?"":`&display=${t}`}`})]};let f={};const p=function(e,t,n){let r={rel:t,href:e};Object.assign(r,n||{});let s=JSON.stringify,l=f[s(r)];return l||(f[s(r)]=g("link",r))},g=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(e);for(let e in t)n.setAttribute(e,t[e]);return n};t.addons.fontPackReceiver=function(t){e=t,e.insertReceiver(["font","pack"],r)},n.prototype.generateGoogleLinks=d,n.prototype.installGoogleLinks=s}(),function(){let e;const t=function(e,t,n,r){return t.value.slice(0,t.match.start),t.args.length>0?t.args[0]:"green"},r=function(e,t,n,r){console.log("raise hook",t,r);let s=t.value.slice(0,t.match.start);console.log(s)};n.addons.functionsReceiver=function(n){e=n,e.keyValueFunctions.set("forceGreen",t),e.keyValueFunctions.set("force",t),e.keyValueFunctions.set("raise",r)}}(),function(){let e;const t=function(t){var n;let s=`family=${`Material+Symbols+${(n=t.values,n.map((function(e){return e.charAt(0).toUpperCase()+e.substring(1,e.length)}))).join("+")}`}:${l({opsz:"20..48",wght:"100..700",FILL:"0..1",GRAD:"-50..200"})}`,a=[...t.values,"icon"];e.insertReceiver(a,o),i.graph.installGoogleLinks(s,null),r(t,fontSettings)},r=function(t,n){let r=t.values[0],l={},i={"font-variation-settings":`${s(n)}`,"font-size":"inherit"};l[`.material-symbols-${r}`]=i,e.dcss.addStylesheetRules(l).renderAll()},s=function(e){let t="",n=Object.keys(e);for(var r=0;r{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&r(e)},n=new MutationObserver((function(e){e.forEach(t)}));return n.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),n},r=function(t){let n=t.target.classList.value,r=t.oldValue,l=n.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==r?[]:r.split(" ").map((e=>e.trim())),o=i?s(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},s=function(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n};n.addons.monitorClasses=function(t){e=t},n.prototype.monitor=function(e=document.body){return t(e)}})(),(()=>{class e extends Map{wordCounter=1;getKey(e){let n=t.get(e);return null==n&&(t.set(e,this.wordCounter),n=this.wordCounter,this.wordCounter++),n}stringToBits(e,t="-"){let n=e.split(t),r=[];return n.forEach(((e,t,n)=>r.push(this.getKey(e)))),r}stringToNest(e,t={}){let n=e.split("-");var r=t;let s=r,l=n.length;return n.forEach(((e,t,n)=>{let s=this.getKey(e),i=t==l-1;null==r[s]?r[s]=r=i?null:{}:r=r[s]})),s}installPropArray(e){e.forEach(((e,t,n)=>{this.stringToNest(e,r)}))}insertBitKey(e,t=r){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,n,r)=>e[t]=n)),e}wordsToArrayString(e=0,t=!1){return t?this.wordsToOrderedArray().join(" "):JSON.stringify(this.wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let n="";return this.forEach(((e,t,r)=>n+=[t,e].join(""))),n}graphToArrayListString(e=r,t=0,n=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,n))}graphToArrayListRecurse(e=r,t=0,n=null){let s=[],l=Object.entries(e);for(let e of l){let r=e[1];s.push([parseInt(e[0]),null==r?n:this.graphToArrayListRecurse(r,t,n)])}return s}graphToObjectString(e=0){let t={};for(let e in r)t[parseInt(e)]=r[e];return JSON.stringify(t,null,e)}}const t=new e,r={},s=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,n,r){const s=n||{row:{reverse:e=>e.join("-")}};let l=t.length,o=0,a=t.length+1,c=0,u=[];for(;oe.join("-");let n=s[r];return null==n&&(n=t),[n(e.slice(0,o+1)),o+1]}return[e[0],1]};n.addons.forwardReduceValues=function(e){return e.reducers.push((function(e,n){return l(e,n,r,t)})),t.installPropArray(s)},n.prototype.valuesGraph={microGraph:r,words:t}})(),function(){let e;const t=function(e,t,n,r){let s=t.slice(r).slice(1),l=`var(--${s.join("-")})`;return n.push(l),[[],n,r+s.length]};n.addons.varTranslateReceiver=function(n){e=n,e.insertTranslator("var",t)}}(),function(){let e,t;const r=function(n,r=":root"){if(console.log("Hook",n),null==t){let s={};for(let e in n){let t=`--${e}`,r=n[e];s[t]=r}let l=e.dcss.addStylesheetRules({[r]:s});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in n){let r=`--${e}`,s=n[e];t.sheetRule.style.setProperty(r,s)}};n.addons.varsReceiver=function(n){e=n,e.vars=r.bind(e),e.varsRoot=t}}();export{n as ClassGraph,t as DynamicCSSStyleSheet,i as Polyclass,e as RenderArray}; diff --git a/dist/full/umd/polyclass-full.js b/dist/full/umd/polyclass-full.js index 7c25228..f334221 100755 --- a/dist/full/umd/polyclass-full.js +++ b/dist/full/umd/polyclass-full.js @@ -172,17 +172,17 @@ })(); /** - * A DynamicCSSStyleSheet allows the developer to manipulate the - * CSS Style objects within the sheet, rather than switching classes - * or using JS. - * - * When installed the stylesheet acts behaves like a standard stylesheet - * We can add, update, and remove active style definitions, immediately - * affecting the view. - * - * This is very useful for complex or dynamic CSS definitions, such as - * a `path()` or font packages. We can couple view changes with style attributes - * without a middle-man + A DynamicCSSStyleSheet allows the developer to manipulate the + CSS Style objects within the sheet, rather than switching classes + or using JS. + + When installed the stylesheet acts behaves like a standard stylesheet + We can add, update, and remove active style definitions, immediately + affecting the view. + + This is very useful for complex or dynamic CSS definitions, such as + a `path()` or font packages. We can couple view changes with style attributes + without a middle-man */ class RenderArray extends Array { renderAll() { @@ -388,10 +388,10 @@ } _getIndexBySelector(selector, sheet) { - let c = 0; + let c = 0; for(let rule of sheet.cssRules) { if(selector == rule.selectorText) { - return c + return c } c++; } @@ -536,6 +536,7 @@ constructor(conf) { this.conf = conf || {}; + this.announce('wake'); /* A simple key -> function dictionary to capture special (simple) keys during the translate value phase. @@ -544,7 +545,7 @@ this.translateMap = { // 'var': this.variableDigest, }; - + this.reducers = []; if(this.conf.addons !== false) { this.installAddons(this.getPreAddons()); } @@ -554,8 +555,38 @@ this.aliasMap = {}; this.parentSelector = conf?.parentSelector; this.processAliases(this.conf?.aliases); + this.announce('ready'); + } + + announce(name) { + let e = new CustomEvent(`classgraph-${name}`, { + detail: { + entity: this + } + }); + dispatchEvent(e); } + /* Insert a literal translation to the translateMap for detection single + words within a class string. for example detect `var` in "color-var-foo" + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + *\/ + let keys = inStack.slice(currentIndex) + let k1 = keys.slice(1) + let word = `var(--${k1.join("-")})` + + outStack.push(word) + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + cg.insertTranslator('var', variableDigest2) + */ insertTranslator(key, func) { this.translateMap[key] = func; } @@ -819,13 +850,13 @@ let props = keys.slice(0, c1); let values = keys.slice(c1); - let vg = this.valuesGraph || {}; + this.valuesGraph || {}; // Reshape any values, correcting for over-splitting values = this.forwardReduceValues( props , values - , vg.microGraph - , vg.words + // , vg.microGraph + // , vg.words ); let r = { @@ -840,7 +871,13 @@ } forwardReduceValues(props, values, graph, words) { - return values + let loopProps = props; + let loopValues = values; + for(let reducer of this.reducers) { + let r = reducer(loopProps, loopValues);//, graph, words) + loopValues = r; + } + return loopValues } minorCapture(str, sep=this.sep, safe=true) { @@ -1896,6 +1933,248 @@ const Polyclass = new Proxy(polyclassHead, polyclassProxy); + + //;(()=>{ + + var installReceiver = function() { + + let keys = new Set([ + /* Hex is a freebie, under the special term `#` hash: #000000 */ + // 'hex', + /* Color property is slightly more complicated, with the first param + as a forced string. */ + // 'color', + + /* Available types, each act the same way: rgb-[3 values][/A] + If the key is a mismatch, its ignored. */ + 'rgb', + 'hsl', + 'hwb', + 'lab', + 'lch', + 'oklab', + 'oklch', + ]); + + ClassGraph.addons.extendedColorValues = function(cg){ + let func = function(prop, values) { + return forwardHotWordReduce(prop, values, keys) + }; + cg.reducers.push(func); + }; + }; + + + /* Return a boolean if the detected type is a valid css value of type: + + Number: 0 | 0.0 + Percent: 0% + Opacity: 0/0 + Angle: 0turn | 0rad + */ + const isNumOrPerc = function(value) { + return isNumber(value) || isPercent(value) || isOpacityNum(value) || isAngle(value) + }; + + /* Return boolean for the match of a css value with an alpha: 0/0 */ + const isOpacityNum = function(value) { + // '60%/0.8' + let spl = value.split('/'); + if(spl.length == 2) { + return isNumOrPerc(spl[0]) && isNumber(spl[1]) + } + return false + }; + + const isAngle = function(value) { + let types = new Set(["deg","grad","rad","turn"]); + let extra = value.slice(parseFloat(value).toString().length, value.length); + return types.has(extra) + }; + + + const isPercent = function(value) { + return value.endsWith('%') && isNumber(value.slice(0, value.length-1)) + }; + + + const isNumber = function(value) { + if(value == undefined || value.length == 0){ return false } let isNum = !isNaN(Number(value)); + return isNum + }; + + + const asThreeBitColor = function(values) { + let ex = values.slice(4, 5); + let alp = ''; + if(ex.length>0) { + alp = `/${ex}`; + } + return `${values[0]}(${values.slice(1, 4).join(' ')}${alp})` + }; + + + /* Perform a _hot word_ detection on the values recursively. A _hot word_ may be any key. + + forwardHotWordReduce( + ['color'] + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + ) + + For each forward step detect a key, if found the reducer collects as many + forward properties as required, then releases after the first fail. + + This method then performs this after every release, concatenating changed and + unchanged into a response list. + + rgb-200-200-200-foo + + rgb(200 200 200) foo + + */ + const forwardHotWordReduce = function(props, values, keys, keyTestFunc=undefined) { + /* + Key pops early, and can accept a variable amount of vars. + */ + + let len = values.length + , position = 0 + , max = values.length + 1 + , count = 0 + , response = [] + ; + + while(position < len && count < max) { + let sliced = values.slice(position); + let [key, usedCount] = hotWordReduce(sliced, keys, true, keyTestFunc); + + position += usedCount; + count += 1; + if(Array.isArray(key)) { + response = response.concat(key); + } else { + response.push(key); + } + } + + return response + }; + + /* Perform a _hot word_ detection on the values. A _hot word_ may be any key. + + forwardHotWordReduce( + , ['rgb', '10', '10', '10', 'eggs'] + , new Set(['rgb']) + , true + ) + + rgb(200 200 200) // break early + rgb(200 200 200) egg + + For each forward step detect a key, if found the reducer collects as many + forward properties as required, then releases after the first fail if `breakEarly` is true. + + rgb-200-200-200-foo-hsl-20-0%-10-foo + + rgb(200 200 200) foo hsl(20 0% 10) foo + + */ + + const hotWordReduce = function(values, keys + , breakEarly=false + , callback=asThreeBitColor + , keyTestFunc=undefined) { + + var i = 0; + let inSet = (x) => keys.has(x) + , keyStartMatch = keyTestFunc != undefined? keyTestFunc: inSet + , l = values.length + , bits = [] + , kept = [] + , lost = [] + , max = 4 // can be 3 or 4 + ; + + for (;i < l; i++) { + // console.log('---') + let k = values[i]; + let inI = i; + if(keyStartMatch(k)) { + // console.log(i, 'MATCH', k) + let j = i+1; + kept = [k]; + lost = []; + let ok = true; + while(ok && j < l) { + let subI = j; + let subK = values[subI]; + let isNum = isNumOrPerc(subK); + ok = isNum && j < l && kept.length <= (max-1); // +1 for the original key + if(isNum) { + // console.log('Push', subK) + j += 1; + kept.push(subK); + ok = ok && kept.length <= max; // +1 for the original key + } else { + // Lost stack + // console.log('Lost stack on', subK) + // j = 1 + lost.push(subK); + } + // console.log('S', subI, subK, isNum, ok) + } + + let [a,b] = [inI, j]; + // console.log('a,b ',a, b, values.slice(a,b), kept) + let plucked = kept.slice(a, b); + let newEntry = callback(kept); + if(plucked.length < 3) { + // console.log('Failed.', bits) + bits = bits.concat(kept); + if(breakEarly) { + return [bits, j] + } + } else { + // console.log('kept', kept, newEntry) + // console.log('plucked', plucked) + bits.push(newEntry); + // Push back 2, as we landed on the bad node, + // and we need step into this node, to stack it. + // + i = j-1; + } + } else { + // console.log(i, k) + bits.push(k); + + if(breakEarly) { + let [a,b] = [inI, kept.length]; + // console.log('a,b ',a, b, values.slice(a,b), kept) + kept.slice(a, b); + let newEntry = callback(kept); + // console.log('plucked', plucked) + // console.log('kept', kept) + if(kept.length < 3) { + // console.log('Failed.', 'kept', kept, 'plucked', plucked) + return [values[b], kept.length+1] + } else { + // console.log('success.') + return [newEntry, kept.length] + } + } + } + } + + // console.log('Done pop', i) + // console.log('in', values, 'out', bits) + + let newEntry = callback(kept); + return [newEntry, i+1] + } + + + ;installReceiver(); (function(){ let cg; @@ -2038,6 +2317,8 @@ cg = _cg; cg.insertReceiver(['font', 'pack'], fontPackReceiver); }; + ClassGraph.prototype.generateGoogleLinks = generateGoogleLinks; + ClassGraph.prototype.installGoogleLinks = installGoogleLinks; }; /** @@ -2060,15 +2341,18 @@ let familyStrings = createFamilyString(values, fonts, origin); // let families = tokenize(values) - - // install as header items - // console.info('Installing Google fonts: familyStrings:', familyStrings) - generateGoogleLinks(familyStrings).forEach((x)=>document.head.appendChild(x)); + installGoogleLinks(familyStrings); // Install additional css additions installFontObjects(fonts); }; + const installGoogleLinks = function(familyStrings, display) { + // install as header items + // console.info('Installing Google fonts: familyStrings:', familyStrings) + return generateGoogleLinks(familyStrings, display).forEach((x)=>document.head.appendChild(x)) + }; + const installFontObjects = function(fonts, splitObj) { // // For value create a font-family; @@ -2393,7 +2677,7 @@ }); }; - const generateGoogleLinks = function(familyStrings){ + const generateGoogleLinks = function(familyStrings, display='swap'){ let a = getOrCreateLink('link', 'preconnect', { href: "https://fonts.googleapis.com" @@ -2404,8 +2688,10 @@ , crossorigin: '' }); + let ds = display == null? '': `&display=${display}`; + let c = getOrCreateLink('link', "stylesheet", { - href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + href:`https://fonts.googleapis.com/css2?${familyStrings}${ds}` }); return [a,b,c] @@ -2413,6 +2699,18 @@ let linkCache = {}; + /* + Create a link node + + let b = getOrCreateLink('link', 'preconnect', { + href: "https://fonts.gstatic.com" + , crossorigin: '' + }) + + let c = getOrCreateLink('link', "stylesheet", { + href:`https://fonts.googleapis.com/css2?${familyStrings}&display=swap` + }) + */ const getOrCreateLink = function(href, rel, opts) { let v = { rel, href @@ -2449,6 +2747,343 @@ })() + ;(function(){ + + let cg; + + const insertReceiver = function(){ + + ClassGraph.addons.functionsReceiver = function(_cg){ + cg = _cg; + cg.keyValueFunctions.set('forceGreen', forceHook); + cg.keyValueFunctions.set('force', forceHook); + cg.keyValueFunctions.set('raise', raiseHook); + }; + }; + + const forceHook = function(value, token, index, splitObj) { + // console.log('Force green hook', token, splitObj) + token.value.slice(0, token.match.start); + // console.log(res) + // return res + + return token.args.length > 0? token.args[0]: 'green' + }; + + const raiseHook = function(value, token, index, splitObj) { + console.log('raise hook', token, splitObj); + let res = token.value.slice(0, token.match.start); + console.log(res); + // return res + }; + insertReceiver(); + })(); + (function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver); + // cg.insertReceiver(['icon'], iconReceiver) + }; + }; + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + + let key = titleCase(obj.values).join('+'); + let family = `Material+Symbols+${key}`; + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + }; + let familyString = toGoogleFontParamsStr(opts); + let fontStr = `family=${family}:${familyString}`; + + let receiverBits = [...obj.values, 'icon']; + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver); + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null); + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings); + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + }; + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0]; + let rules = {}; + + let fontSettingsStr = toObjectParamStr(fontSettings); + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + }; + + rules[`.material-symbols-${key}`] = conf; + let items = cg.dcss.addStylesheetRules(rules); + + items.renderAll(); + }; + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj); + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i]; + let v = obj[k]; + let last = i == fKeys.length-1; + let end = last? '': ',\n'; + fontSettingsStr += `'${k}' ${v}${end}`; + } + return fontSettingsStr + + }; + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(','); + let v = Object.values(obj).join(','); + return `${k}@${v}` + }; + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + obj.values; obj.origin; + console.log('render icon', obj); + + return contentInjection(obj) + }; + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)); + origin.innerText += `${values.join('_')}`; + }; + + const getInjectClass = function(obj) { + let k = obj.props[0]; + return `material-symbols-${k}` + } + + ;insertReceiver(); + })() + + ;(function(){ + + let cg; + const insertReceiver = function(){ + + ClassGraph.addons.iconReceiver = function(_cg){ + cg = _cg; + + // Capture a single key + // cg.insertTranslator('var', variableDigest2) + cg.insertReceiver(['icon', 'pack'], iconPackReceiver); + // cg.insertReceiver(['icon'], iconReceiver) + }; + }; + + const titleCase = (words) => words.map(function(word) { + return word.charAt(0).toUpperCase() + word.substring(1, word.length); + }); + + const iconPackReceiver = function(obj) { + console.log('Install the font', obj); + let key = titleCase(obj.values).join('+'); + let family = `Material+Symbols+${key}`; + let fontSettings = { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + }; + /* Options for the _variable font_ These don't change.*/ + let opts= { + opsz: "20..48", + wght: "100..700", + FILL: "0..1", + GRAD: "-50..200", + }; + let familyString = toGoogleFontParamsStr(opts); + let fontStr = `family=${family}:${familyString}`; + + let receiverBits = [...obj.values, 'icon']; + + /* Install a new class, capturing: `[variant]-icon-*` + The variant is the _style_ of icon, such as "outlined" or "sharp". */ + cg.insertReceiver(receiverBits, iconReceiver); + + + /*Leverage the font installer, using the fonter and the name given.*/ + Polyclass.graph.installGoogleLinks(fontStr, null); + + /* Install the css class rule object */ + installSheetRules(obj, fontSettings); + + // let opts = `opsz,wght,FILL,GRAD + // @20..48,100..700,0..1,-50..200` + // + // let example = `https://fonts.googleapis.com/css2? + // family=Material+Symbols+Outlined: + // opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + // + }; + + const installSheetRules = function(obj, fontSettings){ + /*.material-symbols-sharp { + font-variation-settings: + 'FILL' 0, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48; + font-size: inherit; + }*/ + let key = obj.values[0]; + let rules = {}; + + let fontSettingsStr = toObjectParamStr(fontSettings); + let conf = { + 'font-variation-settings': `${fontSettingsStr}`, + 'font-size': 'inherit', + }; + + rules[`.material-symbols-${key}`] = conf; + let items = cg.dcss.addStylesheetRules(rules); + + items.renderAll(); + }; + + const toObjectParamStr = function(obj) { + /*Given an object, convert it to a string, compatible with an object-like + CSS String: + + { + FILL: 1, + wght: 500, + GRAD: 200, + opsz: 48 + } + + Return a multiline string, with the properties string wrapped: + + 'FILL' 1, + 'wght' 500, + 'GRAD' 200, + 'opsz' 48 + */ + let fontSettingsStr = ''; + let fKeys = Object.keys(obj); + for (var i = 0; i < fKeys.length; i++) { + let k = fKeys[i]; + let v = obj[k]; + let last = i == fKeys.length-1; + let end = last? '': ',\n'; + fontSettingsStr += `'${k}' ${v}${end}`; + } + return fontSettingsStr + + }; + + const toGoogleFontParamsStr = function(obj) { + /* Given an object, convert to a string compatible with the google font + in = { + opsz: "20..48", + wght: "100..,700", + FILL: "0..1", + GRAD: "-50..200", + } + + out = `opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200` + */ + let k = Object.keys(obj).join(','); + let v = Object.values(obj).join(','); + return `${k}@${v}` + }; + + const iconReceiver = function(obj) { + + // Tokenize as a family string. + // + obj.values; obj.origin; + console.log('render icon', obj); + + return contentInjection(obj) + }; + + const contentInjection = function(obj) { + const values = obj.values, origin = obj.origin; + origin.classList.add(getInjectClass(obj)); + origin.innerText += `${values.join('_')}`; + }; + + const getInjectClass = function(obj) { + let k = obj.props[0]; + return `material-symbols-${k}` + } + + ;insertReceiver(); + })() + /** * # Monitor * @@ -2554,194 +3189,34 @@ })() /* + Convert discovered nodes and bind them to a selector. The assigned classes + are the declarations assigned to the css class. - vars box. To assign key variables as accessible CSS varialbes through a js - definition. The definition is bound to DCSS, so edits to the vars manipulates - the view automatically. + The discovery may descend children, allowing for depth setup. - vars({ - primary: "#880000" # company red - , secondary: "#111" # dark - , accent: "red" - }) + - In the node, we access the vars reciever + + -
-

An elk called Elk lives here.

-
+
- Manipulating the var propagates to the view: - vars.primary = "#EEE" # off white - - --- - - ## Secondary App - - `swatch()` - and colors.js - - Assign "colors" to a swatch of colors, each color is a function from the - colors.js module and can assign math relations to swatches. - Chaning a swatch (such as its base color), can manipulate the other - colours according to the chosen swatch type, e.g. "Diachromic". - - */ - - ;(function(){ - - let cg; - let rootRule; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varsReceiver = function(_cg){ - cg = _cg; - cg.vars = varsHook.bind(cg); - // cg.varsRootDelaration = rootDeclaration - cg.varsRoot = rootRule; - // cg.insertTranslator('var', variableDigest) - }; - }; - - - const varsHook = function(d, target=':root') { - /** vars() function bound to the classgraph. _this_ is the classgraph - instance `cg.vars = varsHook.bind(cg)` - - each key is a var, value is the param - - { - apples: green - , foo: 10 - , bar: 1em - , baz: #444 - } - - Each var is installed on the target node: - - :root { - --apples: green - ... - --baz: #444 - } - - if an existing "vars" object exists, it's updated. - - */ - // target = document.querySelector(target) - console.log('Hook', d); - - if(rootRule == undefined) { - let rootDeclaration = {}; - - for(let key in d) { - let prop = `--${key}`; - let value = d[key]; - rootDeclaration[prop] = value; - } - - let rules = cg.dcss.addStylesheetRules({ - [target]: rootDeclaration - }); - - rules.renderAll(); - rootRule = rules[0]; - cg.varsRoot = rootRule; - } else { - - // rootRule - // let pr = rootRule.getPropStr([target,Object.entries(definition)]) - // rootRule.sheetRule.cssText = `${target} { ${pr} }` - // rootRule.replace(`${target} { ${pr} }`) - - for(let key in d) { - let prop = `--${key}`; - let value = d[key]; - rootRule.sheetRule.style.setProperty(prop, value); - } - // rootRule.render() - // console.log(rootRule) - // window.varsRule = rootRule - } - } - - ;insertReceiver(); - })() - - /** - * # var-* Translate - * - * https://developer.mozilla.org/en-US/docs/Web/CSS/var - * - * Discover and rewrite class names values with `var-*` to the CSS function - * `var(*)`. e.g. - * - * "border-top-var-primary-edges" - * - * { - * "border-top": var(--primary-edges) - * } - */ - ;(function(){ - - let cg; - - /** - * The _automatic_ function called at the base of this iffe to - * install the `font-pack-*` tokens into the class graph. - * - * @return {undefined} - */ - const insertReceiver = function(){ - // console.log('var-translate insertReceiver') - // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ - // cg = _cg; - // cg.insertReceiver(['var'], varReceiver) - // } - - ClassGraph.addons.varTranslateReceiver = function(_cg){ - cg = _cg; - cg.insertTranslator('var', variableDigest2); - // cg.insertTranslator('var', variableDigest) - }; - }; - - - const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { - /* - Convert the value keys to a var representation. - `var-name-switch` -> [var, name, switch] - to - `var(--name-switch)` - */ - - let keys = inStack.slice(currentIndex); - let k1 = keys.slice(1); - let word = `var(--${k1.join("-")})`; - - outStack.push(word); - // return [inStack, outStack, currentIndex] - return [[], outStack, currentIndex + k1.length] - } - - - - ;insertReceiver(); - })() - + Notably this may be easier as real CSS. + */ /* The words map lists all the unique string CSS values. Each word maps to an @@ -2822,10 +3297,10 @@ wordsToArrayString(indent=0, small=false){ if(!small) { - return JSON.stringify(wordsToOrderedArray(), null, indent) + return JSON.stringify(this.wordsToOrderedArray(), null, indent) } - return wordsToOrderedArray().join(' ') + return this.wordsToOrderedArray().join(' ') } wordsToObjectString(indent=0, small=false) { @@ -2865,6 +3340,75 @@ } } + /* + 1. all the items have string in position + 2. the we create the flat array list + each position is a word from the string list + + "all-petite-caps", + "all-scroll", + "all-small-caps", + + as a string: + + " all petite caps scroll small ..." + + Becomes: + [1, [ + [2, [ + [3, null] + ] + ], + [4, null], + [5, [ + [3,null] + ] + ] + ] + ] + + --- + + When loaded, we can re-ask for the prop: + + w.stringToBits("all-petite-caps") + [1,2,3] + + The last key + + w.stringToBits("zoom") + [211] + w.stringToBits("zoom-out") + [211, 66] + --- + + + "all-petite-caps", + "all-scroll", + "all-small-caps", + "allow-end", + "alternate-reverse", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2", + "0-3", + "0-4-5", + "6-7", + "8-9", + + "all petite caps scroll small allow end alternate reverse", + "0-1-2 0-3 0-4-5 6-7 8-9" + + "all petite caps scroll small allow end alternate reverse", + "0 1 2,0 3,0 4 5,6 7,8 9" + + // radix each key through 32 bits, allowing ~1000 positions as 2bits + // not really helpful under 100 keys, but then saves 1 char per position (up to 1k) + // .. With 255~ keys thats 150~ chars saved. + // In a 32bit radix, the first 31 positions are single chars. + --- + + */ const words = new Words() , microGraph = {} @@ -3071,8 +3615,16 @@ var installReceiver = function() { - ClassGraph.addons.forwardReduceValues = (cg) => words.installPropArray(dashprops); - ClassGraph.prototype.forwardReduceValues = forwardReduceValues; + ClassGraph.addons.forwardReduceValues = function(cg){ + let func = function(prop, values) { + return forwardReduceValues(prop, values, microGraph, words) + }; + cg.reducers.push(func); + let res = words.installPropArray(dashprops); + return res; + }; + // install one of many + // ClassGraph.prototype.forwardReduceValues = forwardReduceValues ClassGraph.prototype.valuesGraph = { microGraph, words }; }; @@ -3102,9 +3654,6 @@ 'row': { 'reverse': merge } - , 'other': { - 'horse': merge - } }; let len = values.length @@ -3160,6 +3709,194 @@ ;installReceiver(); + })() + /** + * # var-* Translate + * + * https://developer.mozilla.org/en-US/docs/Web/CSS/var + * + * Discover and rewrite class names values with `var-*` to the CSS function + * `var(*)`. e.g. + * + * "border-top-var-primary-edges" + * + * { + * "border-top": var(--primary-edges) + * } + */ + ;(function(){ + + let cg; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // console.log('var-translate insertReceiver') + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varTranslateReceiver = function(_cg){ + cg = _cg; + cg.insertTranslator('var', variableDigest2); + // cg.insertTranslator('var', variableDigest) + }; + }; + + + const variableDigest2 = function(splitObj, inStack, outStack, currentIndex) { + /* + Convert the value keys to a var representation. + `var-name-switch` -> [var, name, switch] + to + `var(--name-switch)` + */ + + let keys = inStack.slice(currentIndex); + let k1 = keys.slice(1); + let word = `var(--${k1.join("-")})`; + + outStack.push(word); + // return [inStack, outStack, currentIndex] + return [[], outStack, currentIndex + k1.length] + } + + + + ;insertReceiver(); + })() + + /* + + vars box. To assign key variables as accessible CSS varialbes through a js + definition. The definition is bound to DCSS, so edits to the vars manipulates + the view automatically. + + vars({ + primary: "#880000" # company red + , secondary: "#111" # dark + , accent: "red" + }) + + In the node, we access the vars reciever + +
+

An elk called Elk lives here.

+
+ + Manipulating the var propagates to the view: + + vars.primary = "#EEE" # off white + + --- + + ## Secondary App + + `swatch()` + and colors.js + + Assign "colors" to a swatch of colors, each color is a function from the + colors.js module and can assign math relations to swatches. + Chaning a swatch (such as its base color), can manipulate the other + colours according to the chosen swatch type, e.g. "Diachromic". + + */ + + ;(function(){ + + let cg; + let rootRule; + + /** + * The _automatic_ function called at the base of this iffe to + * install the `font-pack-*` tokens into the class graph. + * + * @return {undefined} + */ + const insertReceiver = function(){ + // DynamicCSSStyleSheet.addons.varTranslateReceiver = function(_cg){ + // cg = _cg; + // cg.insertReceiver(['var'], varReceiver) + // } + + ClassGraph.addons.varsReceiver = function(_cg){ + cg = _cg; + cg.vars = varsHook.bind(cg); + // cg.varsRootDelaration = rootDeclaration + cg.varsRoot = rootRule; + // cg.insertTranslator('var', variableDigest) + }; + }; + + + const varsHook = function(d, target=':root') { + /** vars() function bound to the classgraph. _this_ is the classgraph + instance `cg.vars = varsHook.bind(cg)` + + each key is a var, value is the param + + { + apples: green + , foo: 10 + , bar: 1em + , baz: #444 + } + + Each var is installed on the target node: + + :root { + --apples: green + ... + --baz: #444 + } + + if an existing "vars" object exists, it's updated. + + */ + // target = document.querySelector(target) + console.log('Hook', d); + + if(rootRule == undefined) { + let rootDeclaration = {}; + + for(let key in d) { + let prop = `--${key}`; + let value = d[key]; + rootDeclaration[prop] = value; + } + + let rules = cg.dcss.addStylesheetRules({ + [target]: rootDeclaration + }); + + rules.renderAll(); + rootRule = rules[0]; + cg.varsRoot = rootRule; + } else { + + // rootRule + // let pr = rootRule.getPropStr([target,Object.entries(definition)]) + // rootRule.sheetRule.cssText = `${target} { ${pr} }` + // rootRule.replace(`${target} { ${pr} }`) + + for(let key in d) { + let prop = `--${key}`; + let value = d[key]; + rootRule.sheetRule.style.setProperty(prop, value); + } + // rootRule.render() + // console.log(rootRule) + // window.varsRule = rootRule + } + } + + ;insertReceiver(); })(); exports.ClassGraph = ClassGraph; diff --git a/dist/full/umd/polyclass-full.min.js b/dist/full/umd/polyclass-full.min.js index aa07c75..74da6ac 100755 --- a/dist/full/umd/polyclass-full.min.js +++ b/dist/full/umd/polyclass-full.min.js @@ -1 +1 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).polybundle={})}(this,(function(e){"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,r=(e,t,r)=>`rgb(${e},${t},${r})`;let n=function(e,t="#000000",r="#FFFFFF"){return e||(d?t:r)},s=function(e){return n(e,r(0,0,0),r(255,255,255))},l=function(e,t,r){let n=e>>t;return r?n&r:n},i=function(e,t,r,n){let s=l(e,t,r);return a(s,n)},o=(e,r)=>a(t(e),r),a=function(t,r){return e(c(t-r))+r},c=function(e){return e*u};var u,d;function h(e,l,i){return u=(d=e<0)?-1*e:e,l.length>7?function(e,n,l){let i=n.split(","),a=s(l),c=a.split(","),u=t(i[0].slice(4)),d=t(i[1]),h=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],d),g=o(c[2],h);return r(f,p,g)}(0,l,i):function(e,r,s){var l=t(r.slice(1),16),i=n(s).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,r,n){let s=l(e,r,n);return i(t,r,n,s)}function p(e,t,r){var n=e<0?-1*e:e,s=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(r||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(s((l(o[0].slice(4))-a)*n)+a)+","+(s((l(o[1])-c)*n)+c)+","+(s((l(o[2])-u)*n)+u)+")"}var d=(i=l(t.slice(1),16))>>16,h=i>>8&255,f=255&i;return"#"+(16777216+65536*(s((((o=l((r||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*n)+d)+256*(s(((o>>8&255)-h)*n)+h)+(s(((255&o)-f)*n)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",m="rgb(120,99,248)";blendedcolor=h(-.8,b,m),blendedcolor2=p(-.8,b,m),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=h(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class t extends Array{renderAll(){for(let e of this)e.render()}}class r{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let r in t){(0,t[r])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,r=e||this.styleEl;if(null!=r)return r;if("sheet"==this.insertMethod&&(r=document.createElement("style"),document.head.appendChild(r),t=r.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(e,r){let n=this.getEnsureStyleSheet(r),s=new t,l=n;for(let t=0;t*% #():=.@+?\/]/g;dcss=new r(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,r]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,r)=>(r?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let r=this.getRoot(),n=this.nodeWord(),s=[];for(let t of e){s.push(t),r[n]||(r[n]={});let e=r[n][t];null==e&&(e=r[n][t]={key:t,position:s}),r=e}return r.leaf=!0,null!=t&&(r.handler=t),r}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var r=0;r0||!1}}forwardReduceValues(e,t,r,n){return t}minorCapture(e,t=this.sep,r=!0){let n="string"==typeof e?e.split(t):e,s=this.aliasConvert(n);s.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(s))s=s.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of s)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=s[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(r)break;let c=s.slice(0,a),u=s.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,r=!0){let n=this.objectSplit(e,t,r);return this.translateValue(n)}insertLine(e,t){let r=this.objectSplit(e);return this.insertRule(r,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let r=!0,n=t||[],s=0,l=[];for(;r;){let t=n[s],i=this.translateMap[t];i?[n,l,s]=i(e,n,l,s):l.push(this.beforeOutStack(n[s],s,e)),s+=1,(s>=n.length||s>100)&&(r=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,r){let n=this.getKeyFunctionMatch(e),s=this.collapseFunctions(n,r);return null==s?e:s}collapseFunctions(e,t){let r;for(var n=e.length-1;n>=0;n--){let s=e[n],l=null==r?s.remainder:r,i=s.handler;r=i&&i(l,s,n,t)||r}return r}getKeyFunctionMatch(e){let t=null!=e,r=e,n=[];for(;t;){let e=this.getKeyFunctionMatchOnce(r);e.success,t=e.match.start>-1,t&&(r=e.remainder,n.push(e))}return n}getKeyFunctionMatchOnce(e,t=".",r=":"){let n=e.lastIndexOf(t),s=e.length,l=e.slice(n+1,s).split(r),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,n),handler:a,args:o,match:{start:n,end:s,name:i}};return c.success=null!=a,c}filterClasses(e,t,r=!1){let n=e.classList,s=r?{}:[],l=(e,t,r)=>s.push([r,t]);return r&&(l=(e,t,r)=>s[e]=[r,t]),n.forEach((function(e,r,n){let s=e.split("-")[0];t.indexOf(s)>-1&&l(s,e,r)})),s}filterSplit(e,t,r=!1){let n=this.filterClasses(e,t,r);if(r){let e={};for(let t in n){let r=n[t];e[t]=this.objectSplit(r[1],void 0,void 0,r[0])}return e}let s=[];return n.forEach((e=>{s.push(this.objectSplit(e))})),s}removeRule(e,t=void 0,r=!0){e?.props?.join("-");let n=this.asSelectorString(e,r);this.dcss.selectorExists(n)&&this.dcss.removeRuleBySelector(n)}insertRule(e,t=void 0,r=!0){let n=e?.props?.join("-"),s=this.asSelectorString(e,r);if(this.dcss.selectorExists(s))return this.dcss.getRuleBySelector(s);let l={[n]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[s]:l});return e.renderAll(),e}}insertReceiver(e,t){let r=this.addTree(e);return r.handler=t,r}asSelectorString(e,t=!0){let r;if(Array.isArray(e)){let t=e.join("-");r=this.escapeStr(t)}if("string"==typeof e&&(r=this.escapeStr(e)),e.props){let t=e.props.join("-");r=this.escapeStr(t)}e.str&&(r=this.escapeStr(e.str));let n=`.${r}`;return t?this.prependParent(n,e):n}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let r=this.objectSplit(e);return r.values.length>0&&r.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let r of t.rules)e+=`${r.cssText};\n`;return e}captureChanges(e,t,r){this.discoverInsert(e,r),this.discoverRemove(t,r)}discoverInsert(e,t){let r=this;for(let n of e){if(0==n.length)continue;let e=r.objectSplit(n);e.origin=t;let s=e.node?.handler;(s?s.bind(e):r.insertRule.bind(r))(e)}}discoverRemove(e,t){let r=this;for(let n of e){if(0==n.length)continue;let e=r.objectSplit(n);e.origin=t;let s=e.node?.unhandler,l=s?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let r=0;for(let n of t)this.safeInsertLine(n,e,r++)}safeInsertLine(e,t,r=-1){let n=this.objectSplit(e,void 0,void 0,r);return n.valid&&(n.origin=t,this.insertRule(n)),n}getAllClasses(e=document.body,t=!1,r=!0){let n=function(e){e.classList.forEach((e=>s.add(e)))},s=new Set;return t&&(s=new Map,n=function(e){s.set(e,new Set(e.classList))}),r&&n(e),e.querySelectorAll("*").forEach(n),s}addClass(e,...t){let r=this.asNodes(e);for(let e of r)for(let r of t)for(let t of r.split(" "))e.classList.add(t)}removeClass(e,...t){let r=this.asNodes(e);for(let e of r)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}n.addons={};class s{constructor([e]=[]){this.units=l;let t=new n(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,r){let n=this.reference;if(t in n)return n[t].bind?n[t].bind(n):n[t]},apply(e,t,r){console.log("innerProxyHandler apply...",r)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,r=void 0){const n=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===n)return r;let s=n.value;if(0==s.length)return r;return JSON.parse(s)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return l.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const l=new Map,i={safeSpace:{units:l,addons:[]},get(e,t,r){let n=this.getInstance();if(t in n){let e=n[t];return e&&e.bind?e.bind(n):e}return this.safeSpace[t]},newInstance(){return new s(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,r){return console.log("Polyclass apply...",e,t,r),r[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,r)):this.getInstance.apply(this,r)}},o=new Proxy((function(){return i.newInstance.apply(i,arguments)}),i);!function(){let e;const t=function(e,t){values=e.values;let[n,...s]=e.values;if(void 0!==document[`on${n}`]){const t=e.origin;r(e,t,n,s)}else console.warn("Unknown action",n)},r=function(e,t,r,n){let l=e=>s(e,r,n),i=`polyaction_${r}`;void 0===t.dataset[i]?(t.addEventListener(r,l),t.dataset[i]=!0):console.log("Event already exists:",r)},s=function(e,t,r){let[n,...s]=r;console.log(e,t,r),console.log(n,s);let l={call(){},toggle(){console.log(s,r,t),e.currentTarget.classList.toggle(s.join("-"))},setvar(){}}[n];l&&l()};console.log("event receiver"),n.addons.eventsReceiver=function(r){e=r,e.insertReceiver(["event"],t)}}(),function(){let e;const t=function(e){const t=e.values,r=e.origin;let s=o(t,r,e),i=l(t,s,r);u(i).forEach((e=>document.head.appendChild(e))),n(s)},n=function(t,r){for(let r of Object.values(t)){let t=r.first,n=(e,t)=>t?" ":"",l=s(t.replace(/[+]/g,n));r.cleanName=l,r.definition=i(r),e.dcss.addStylesheetRules(r.definition).renderAll()}},s=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},l=function(e,t,r){t=t||o(e,r);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},i=function(t){let r={};const n=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let s={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},s);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);r[`${n(i)}, ${n(i).toLowerCase()}`]=e}}let s=n(["font",t.first]),l=n(["font"].concat(t.first.split("+"))),i=new Set([s,l,s.toLowerCase(),l.toLowerCase()]);return r[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},r},o=function(t,r,n){let s,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,c=function(t,r){return e.filterSplit(r,t,!0)}(["default"],n?.origin||r),u="sans-serif",d=c.default;if(d)if(d.index<=n.index){let e="font default-* modifier should be indexed after font";console["warn"](e),u=d.values.join(" ")}else u=d.values.join(" ");for(let e in t){let r=t[e];if(0==l){i[l]={first:r,tokens:{},defaultFonts:u},s=l,l++;continue}let[n,a]=[null,null];try{let e;[e,n,a]=r.match(o),0==n.length&&(n="r")}catch{i[l]={first:r,tokens:{}},s=l,l++;continue}let c={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},d={int:Number(a)};if(0==d.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in n){let t=c[n[e]];Object.assign(d,t())}let h=i[s]?.tokens[a]||{};Object.assign(h,d),null==h.keys&&(h.keys=new Set),h.keys.add({isItal:d.ital,token:r}),i[s].tokens[a]=h,l++}return a(i)},a=function(e){for(let t in e){let r=e[t];0!=r.first.length&&c(r)}return e},c=function(e){let t=s(e.first),r=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),n=Object.assign({},...r),l=null!=n.ital,i=[],o=new Set;l&&i.push("ital"),(l||n.regu)&&i.push("wght");for(let t in e.tokens){let r=e.tokens[t],n=r.ital?1:0,s=r.int,i=l?[n]:[];i.push(s);let a=i.join(",");if(o.add(a),null!=r.regu){let e=l?[0]:[];e.push(s);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${i.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:i,titleToken:t,str:u})},u=function(e){return[h("link","preconnect",{href:"https://fonts.googleapis.com"}),h("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),h("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}&display=swap`})]};let d={};const h=function(e,t,r){let n={rel:t,href:e};Object.assign(n,r||{});let s=JSON.stringify,l=d[s(n)];return l||(d[s(n)]=f("link",n))},f=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let r=document.createElement(e);for(let e in t)r.setAttribute(e,t[e]);return r};r.addons.fontPackReceiver=function(r){e=r,e.insertReceiver(["font","pack"],t)}}(),(()=>{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&r(e)},n=new MutationObserver((function(e){e.forEach(t)}));return n.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),n},r=function(t){let r=t.target.classList.value,n=t.oldValue,l=r.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==n?[]:n.split(" ").map((e=>e.trim())),o=i?s(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},s=function(e,t){const r=new Set(e);for(const e of t)r.delete(e);return r};n.addons.monitorClasses=function(t){e=t},n.prototype.monitor=function(e=document.body){return t(e)}})(),function(){let e,t;const r=function(r,n=":root"){if(console.log("Hook",r),null==t){let s={};for(let e in r){let t=`--${e}`,n=r[e];s[t]=n}let l=e.dcss.addStylesheetRules({[n]:s});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in r){let n=`--${e}`,s=r[e];t.sheetRule.style.setProperty(n,s)}};n.addons.varsReceiver=function(n){e=n,e.vars=r.bind(e),e.varsRoot=t}}(),function(){let e;const t=function(e,t,r,n){let s=t.slice(n).slice(1),l=`var(--${s.join("-")})`;return r.push(l),[[],r,n+s.length]};n.addons.varTranslateReceiver=function(r){e=r,e.insertTranslator("var",t)}}(),(()=>{class e extends Map{wordCounter=1;getKey(e){let r=t.get(e);return null==r&&(t.set(e,this.wordCounter),r=this.wordCounter,this.wordCounter++),r}stringToBits(e,t="-"){let r=e.split(t),n=[];return r.forEach(((e,t,r)=>n.push(this.getKey(e)))),n}stringToNest(e,t={}){let r=e.split("-");var n=t;let s=n,l=r.length;return r.forEach(((e,t,r)=>{let s=this.getKey(e),i=t==l-1;null==n[s]?n[s]=n=i?null:{}:n=n[s]})),s}installPropArray(e){e.forEach(((e,t,n)=>{this.stringToNest(e,r)}))}insertBitKey(e,t=r){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,r,n)=>e[t]=r)),e}wordsToArrayString(e=0,t=!1){return t?wordsToOrderedArray().join(" "):JSON.stringify(wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let r="";return this.forEach(((e,t,n)=>r+=[t,e].join(""))),r}graphToArrayListString(e=r,t=0,n=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,n))}graphToArrayListRecurse(e=r,t=0,n=null){let s=[],l=Object.entries(e);for(let e of l){let r=e[1];s.push([parseInt(e[0]),null==r?n:this.graphToArrayListRecurse(r,t,n)])}return s}graphToObjectString(e=0){let t={};for(let e in r)t[parseInt(e)]=r[e];return JSON.stringify(t,null,e)}}const t=new e,r={},s=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,r,n){const s=e=>e.join("-"),l=r||{row:{reverse:s},other:{horse:s}};let o=t.length,a=0,c=t.length+1,u=0,d=[];for(;ae.join("-");let r=s[n];return null==r&&(r=t),[r(e.slice(0,o+1)),o+1]}return[e[0],1]};n.addons.forwardReduceValues=e=>t.installPropArray(s),n.prototype.forwardReduceValues=l,n.prototype.valuesGraph={microGraph:r,words:t}})(),e.ClassGraph=n,e.DynamicCSSStyleSheet=r,e.Polyclass=o,e.RenderArray=t})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).polybundle={})}(this,(function(e){"use strict";document.createElement("span"),(()=>{var e=Math.round,t=parseInt,n=(e,t,n)=>`rgb(${e},${t},${n})`;let r=function(e,t="#000000",n="#FFFFFF"){return e||(h?t:n)},s=function(e){return r(e,n(0,0,0),n(255,255,255))},l=function(e,t,n){let r=e>>t;return n?r&n:r},i=function(e,t,n,r){let s=l(e,t,n);return a(s,r)},o=(e,n)=>a(t(e),n),a=function(t,n){return e(c(t-n))+n},c=function(e){return e*u};var u,h;function d(e,l,i){return u=(h=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=s(l),c=a.split(","),u=t(i[0].slice(4)),h=t(i[1]),d=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],h),g=o(c[2],d);return n(f,p,g)}(0,l,i):function(e,n,s){var l=t(n.slice(1),16),i=r(s).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,n,r){let s=l(e,n,r);return i(t,n,r,s)}function p(e,t,n){var r=e<0?-1*e:e,s=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(n||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(s((l(o[0].slice(4))-a)*r)+a)+","+(s((l(o[1])-c)*r)+c)+","+(s((l(o[2])-u)*r)+u)+")"}var h=(i=l(t.slice(1),16))>>16,d=i>>8&255,f=255&i;return"#"+(16777216+65536*(s((((o=l((n||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-h)*r)+h)+256*(s(((o>>8&255)-d)*r)+d)+(s(((255&o)-f)*r)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=d(-.8,b,v),blendedcolor2=p(-.8,b,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=d(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class t extends Array{renderAll(){for(let e of this)e.render()}}class n{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let n in t){(0,t[n])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,n=e||this.styleEl;if(null!=n)return n;if("sheet"==this.insertMethod&&(n=document.createElement("style"),document.head.appendChild(n),t=n.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(e,n){let r=this.getEnsureStyleSheet(n),s=new t,l=r;for(let t=0;t*% #():=.@+?\/]/g;dcss=new n(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,n]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,n)=>(n?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let n=this.getRoot(),r=this.nodeWord(),s=[];for(let t of e){s.push(t),n[r]||(n[r]={});let e=n[r][t];null==e&&(e=n[r][t]={key:t,position:s}),n=e}return n.leaf=!0,null!=t&&(n.handler=t),n}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var n=0;n0||!1}}forwardReduceValues(e,t,n,r){let s=e,l=t;for(let e of this.reducers){l=e(s,l)}return l}minorCapture(e,t=this.sep,n=!0){let r="string"==typeof e?e.split(t):e,s=this.aliasConvert(r);s.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(s))s=s.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of s)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=s[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(n)break;let c=s.slice(0,a),u=s.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,n=!0){let r=this.objectSplit(e,t,n);return this.translateValue(r)}insertLine(e,t){let n=this.objectSplit(e);return this.insertRule(n,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let n=!0,r=t||[],s=0,l=[];for(;n;){let t=r[s],i=this.translateMap[t];i?[r,l,s]=i(e,r,l,s):l.push(this.beforeOutStack(r[s],s,e)),s+=1,(s>=r.length||s>100)&&(n=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,n){let r=this.getKeyFunctionMatch(e),s=this.collapseFunctions(r,n);return null==s?e:s}collapseFunctions(e,t){let n;for(var r=e.length-1;r>=0;r--){let s=e[r],l=null==n?s.remainder:n,i=s.handler;n=i&&i(l,s,r,t)||n}return n}getKeyFunctionMatch(e){let t=null!=e,n=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(n);e.success,t=e.match.start>-1,t&&(n=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",n=":"){let r=e.lastIndexOf(t),s=e.length,l=e.slice(r+1,s).split(n),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:s,name:i}};return c.success=null!=a,c}filterClasses(e,t,n=!1){let r=e.classList,s=n?{}:[],l=(e,t,n)=>s.push([n,t]);return n&&(l=(e,t,n)=>s[e]=[n,t]),r.forEach((function(e,n,r){let s=e.split("-")[0];t.indexOf(s)>-1&&l(s,e,n)})),s}filterSplit(e,t,n=!1){let r=this.filterClasses(e,t,n);if(n){let e={};for(let t in r){let n=r[t];e[t]=this.objectSplit(n[1],void 0,void 0,n[0])}return e}let s=[];return r.forEach((e=>{s.push(this.objectSplit(e))})),s}removeRule(e,t=void 0,n=!0){e?.props?.join("-");let r=this.asSelectorString(e,n);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,n=!0){let r=e?.props?.join("-"),s=this.asSelectorString(e,n);if(this.dcss.selectorExists(s))return this.dcss.getRuleBySelector(s);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[s]:l});return e.renderAll(),e}}insertReceiver(e,t){let n=this.addTree(e);return n.handler=t,n}asSelectorString(e,t=!0){let n;if(Array.isArray(e)){let t=e.join("-");n=this.escapeStr(t)}if("string"==typeof e&&(n=this.escapeStr(e)),e.props){let t=e.props.join("-");n=this.escapeStr(t)}e.str&&(n=this.escapeStr(e.str));let r=`.${n}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let n=this.objectSplit(e);return n.values.length>0&&n.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let n of t.rules)e+=`${n.cssText};\n`;return e}captureChanges(e,t,n){this.discoverInsert(e,n),this.discoverRemove(t,n)}discoverInsert(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.handler;(s?s.bind(e):n.insertRule.bind(n))(e)}}discoverRemove(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.unhandler,l=s?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let n=0;for(let r of t)this.safeInsertLine(r,e,n++)}safeInsertLine(e,t,n=-1){let r=this.objectSplit(e,void 0,void 0,n);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,n=!0){let r=function(e){e.classList.forEach((e=>s.add(e)))},s=new Set;return t&&(s=new Map,r=function(e){s.set(e,new Set(e.classList))}),n&&r(e),e.querySelectorAll("*").forEach(r),s}addClass(e,...t){let n=this.asNodes(e);for(let e of n)for(let n of t)for(let t of n.split(" "))e.classList.add(t)}removeClass(e,...t){let n=this.asNodes(e);for(let e of n)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}r.addons={};class s{constructor([e]=[]){this.units=l;let t=new r(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,n){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,n){console.log("innerProxyHandler apply...",n)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,n=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return n;let s=r.value;if(0==s.length)return n;return JSON.parse(s)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return l.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const l=new Map,i={safeSpace:{units:l,addons:[]},get(e,t,n){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new s(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,n){return console.log("Polyclass apply...",e,t,n),n[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,n)):this.getInstance.apply(this,n)}},o=new Proxy((function(){return i.newInstance.apply(i,arguments)}),i);const a=function(e){return d(e)||h(e)||c(e)||u(e)},c=function(e){let t=e.split("/");return 2==t.length&&(a(t[0])&&d(t[1]))},u=function(e){let t=new Set(["deg","grad","rad","turn"]),n=e.slice(parseFloat(e).toString().length,e.length);return t.has(n)},h=function(e){return e.endsWith("%")&&d(e.slice(0,e.length-1))},d=function(e){if(null==e||0==e.length)return!1;return!isNaN(Number(e))},f=function(e){let t=e.slice(4,5),n="";return t.length>0&&(n=`/${t}`),`${e[0]}(${e.slice(1,4).join(" ")}${n})`},p=function(e,t,n,r=void 0){let s=t.length,l=0,i=t.length+1,o=0,a=[];for(;lt.has(e),o=e.length,c=[],u=[],h=[];for(;ls(e,n,r),i=`polyaction_${n}`;void 0===t.dataset[i]?(t.addEventListener(n,l),t.dataset[i]=!0):console.log("Event already exists:",n)},s=function(e,t,n){let[r,...s]=n;console.log(e,t,n),console.log(r,s);let l={call(){},toggle(){console.log(s,n,t),e.currentTarget.classList.toggle(s.join("-"))},setvar(){}}[r];l&&l()};console.log("event receiver"),r.addons.eventsReceiver=function(n){e=n,e.insertReceiver(["event"],t)}}(),function(){let e;const t=function(e){const t=e.values,n=e.origin;let r=c(t,n,e),i=o(t,r,n);s(i),l(r)},s=function(e,t){return d(e,t).forEach((e=>document.head.appendChild(e)))},l=function(t,n){for(let n of Object.values(t)){let t=n.first,r=(e,t)=>t?" ":"",s=i(t.replace(/[+]/g,r));n.cleanName=s,n.definition=a(n),e.dcss.addStylesheetRules(n.definition).renderAll()}},i=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},o=function(e,t,n){t=t||c(e,n);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},a=function(t){let n={};const r=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let s={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},s);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);n[`${r(i)}, ${r(i).toLowerCase()}`]=e}}let s=r(["font",t.first]),l=r(["font"].concat(t.first.split("+"))),i=new Set([s,l,s.toLowerCase(),l.toLowerCase()]);return n[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},n},c=function(t,n,r){let s,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,a=function(t,n){return e.filterSplit(n,t,!0)}(["default"],r?.origin||n),c="sans-serif",h=a.default;if(h)if(h.index<=r.index){let e="font default-* modifier should be indexed after font";console["warn"](e),c=h.values.join(" ")}else c=h.values.join(" ");for(let e in t){let n=t[e];if(0==l){i[l]={first:n,tokens:{},defaultFonts:c},s=l,l++;continue}let[r,a]=[null,null];try{let e;[e,r,a]=n.match(o),0==r.length&&(r="r")}catch{i[l]={first:n,tokens:{}},s=l,l++;continue}let u={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},h={int:Number(a)};if(0==h.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in r){let t=u[r[e]];Object.assign(h,t())}let d=i[s]?.tokens[a]||{};Object.assign(d,h),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:h.ital,token:n}),i[s].tokens[a]=d,l++}return u(i)},u=function(e){for(let t in e){let n=e[t];0!=n.first.length&&h(n)}return e},h=function(e){let t=i(e.first),n=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),r=Object.assign({},...n),s=null!=r.ital,l=[],o=new Set;s&&l.push("ital"),(s||r.regu)&&l.push("wght");for(let t in e.tokens){let n=e.tokens[t],r=n.ital?1:0,l=n.int,i=s?[r]:[];i.push(l);let a=i.join(",");if(o.add(a),null!=n.regu){let e=s?[0]:[];e.push(l);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${l.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:l,titleToken:t,str:u})},d=function(e,t="swap"){return[p("link","preconnect",{href:"https://fonts.googleapis.com"}),p("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),p("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}${null==t?"":`&display=${t}`}`})]};let f={};const p=function(e,t,n){let r={rel:t,href:e};Object.assign(r,n||{});let s=JSON.stringify,l=f[s(r)];return l||(f[s(r)]=g("link",r))},g=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(e);for(let e in t)n.setAttribute(e,t[e]);return n};n.addons.fontPackReceiver=function(n){e=n,e.insertReceiver(["font","pack"],t)},r.prototype.generateGoogleLinks=d,r.prototype.installGoogleLinks=s}(),function(){let e;const t=function(e,t,n,r){return t.value.slice(0,t.match.start),t.args.length>0?t.args[0]:"green"},n=function(e,t,n,r){console.log("raise hook",t,r);let s=t.value.slice(0,t.match.start);console.log(s)};r.addons.functionsReceiver=function(r){e=r,e.keyValueFunctions.set("forceGreen",t),e.keyValueFunctions.set("force",t),e.keyValueFunctions.set("raise",n)}}(),function(){let e;const t=function(t){var r;let s=`family=${`Material+Symbols+${(r=t.values,r.map((function(e){return e.charAt(0).toUpperCase()+e.substring(1,e.length)}))).join("+")}`}:${l({opsz:"20..48",wght:"100..700",FILL:"0..1",GRAD:"-50..200"})}`,a=[...t.values,"icon"];e.insertReceiver(a,i),o.graph.installGoogleLinks(s,null),n(t,fontSettings)},n=function(t,n){let r=t.values[0],l={},i={"font-variation-settings":`${s(n)}`,"font-size":"inherit"};l[`.material-symbols-${r}`]=i,e.dcss.addStylesheetRules(l).renderAll()},s=function(e){let t="",n=Object.keys(e);for(var r=0;r{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&n(e)},r=new MutationObserver((function(e){e.forEach(t)}));return r.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),r},n=function(t){let n=t.target.classList.value,r=t.oldValue,l=n.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==r?[]:r.split(" ").map((e=>e.trim())),o=i?s(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},s=function(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n};r.addons.monitorClasses=function(t){e=t},r.prototype.monitor=function(e=document.body){return t(e)}})(),(()=>{class e extends Map{wordCounter=1;getKey(e){let n=t.get(e);return null==n&&(t.set(e,this.wordCounter),n=this.wordCounter,this.wordCounter++),n}stringToBits(e,t="-"){let n=e.split(t),r=[];return n.forEach(((e,t,n)=>r.push(this.getKey(e)))),r}stringToNest(e,t={}){let n=e.split("-");var r=t;let s=r,l=n.length;return n.forEach(((e,t,n)=>{let s=this.getKey(e),i=t==l-1;null==r[s]?r[s]=r=i?null:{}:r=r[s]})),s}installPropArray(e){e.forEach(((e,t,r)=>{this.stringToNest(e,n)}))}insertBitKey(e,t=n){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,n,r)=>e[t]=n)),e}wordsToArrayString(e=0,t=!1){return t?this.wordsToOrderedArray().join(" "):JSON.stringify(this.wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let n="";return this.forEach(((e,t,r)=>n+=[t,e].join(""))),n}graphToArrayListString(e=n,t=0,r=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,r))}graphToArrayListRecurse(e=n,t=0,r=null){let s=[],l=Object.entries(e);for(let e of l){let n=e[1];s.push([parseInt(e[0]),null==n?r:this.graphToArrayListRecurse(n,t,r)])}return s}graphToObjectString(e=0){let t={};for(let e in n)t[parseInt(e)]=n[e];return JSON.stringify(t,null,e)}}const t=new e,n={},s=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,n,r){const s=n||{row:{reverse:e=>e.join("-")}};let l=t.length,o=0,a=t.length+1,c=0,u=[];for(;oe.join("-");let n=s[r];return null==n&&(n=t),[n(e.slice(0,o+1)),o+1]}return[e[0],1]};r.addons.forwardReduceValues=function(e){return e.reducers.push((function(e,r){return l(e,r,n,t)})),t.installPropArray(s)},r.prototype.valuesGraph={microGraph:n,words:t}})(),function(){let e;const t=function(e,t,n,r){let s=t.slice(r).slice(1),l=`var(--${s.join("-")})`;return n.push(l),[[],n,r+s.length]};r.addons.varTranslateReceiver=function(n){e=n,e.insertTranslator("var",t)}}(),function(){let e,t;const n=function(n,r=":root"){if(console.log("Hook",n),null==t){let s={};for(let e in n){let t=`--${e}`,r=n[e];s[t]=r}let l=e.dcss.addStylesheetRules({[r]:s});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in n){let r=`--${e}`,s=n[e];t.sheetRule.style.setProperty(r,s)}};r.addons.varsReceiver=function(r){e=r,e.vars=n.bind(e),e.varsRoot=t}}(),e.ClassGraph=r,e.DynamicCSSStyleSheet=n,e.Polyclass=o,e.RenderArray=t})); diff --git a/dist/polyclass.browser-core.js b/dist/polyclass.browser-core.js index dbef42d..af8d34b 100755 --- a/dist/polyclass.browser-core.js +++ b/dist/polyclass.browser-core.js @@ -1 +1 @@ -document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,S,b),blendedcolor2=f(-.8,S,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){return t}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},n=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),s=new a({target:t,isInline:!0});i.set(e,s)}};!function(e=document){e.addEventListener("DOMContentLoaded",function(){n()}.bind(this))}();class l{constructor([e]=[]){this.units=i;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return i.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const i=new Map,o={safeSpace:{units:i,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new l(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o); +document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=u(-.8,S,v),blendedcolor2=f(-.8,S,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){let n=e,l=t;for(let e of this.reducers){l=e(n,l)}return l}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},n=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),s=new a({target:t,isInline:!0});i.set(e,s)}};!function(e=document){["complete","interactive"].indexOf(document.readyState)>-1&&n(),e.addEventListener("DOMContentLoaded",function(){n()}.bind(this))}();class l{constructor([e]=[]){this.units=i;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return i.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const i=new Map,o={safeSpace:{units:i,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new l(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o); diff --git a/dist/polyclass.browser-full.js b/dist/polyclass.browser-full.js index 11d159f..4cf0e8b 100755 --- a/dist/polyclass.browser-full.js +++ b/dist/polyclass.browser-full.js @@ -1 +1 @@ -document.createElement("span"),(()=>{var e=Math.round,t=parseInt,r=(e,t,r)=>`rgb(${e},${t},${r})`;let n=function(e,t="#000000",r="#FFFFFF"){return e||(d?t:r)},s=function(e){return n(e,r(0,0,0),r(255,255,255))},l=function(e,t,r){let n=e>>t;return r?n&r:n},o=function(e,t,r,n){let s=l(e,t,r);return a(s,n)},i=(e,r)=>a(t(e),r),a=function(t,r){return e(c(t-r))+r},c=function(e){return e*u};var u,d;function h(e,l,o){return u=(d=e<0)?-1*e:e,l.length>7?function(e,n,l){let o=n.split(","),a=s(l),c=a.split(","),u=t(o[0].slice(4)),d=t(o[1]),h=t(o[2]),f=i(c[0].slice(4),u),p=i(c[1],d),g=i(c[2],h);return r(f,p,g)}(0,l,o):function(e,r,s){var l=t(r.slice(1),16),o=n(s).slice(1),i=t(o,16),a=f(l,i,16,0),c=f(l,i,8,255),u=f(l,i,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,o)}function f(e,t,r,n){let s=l(e,r,n);return o(t,r,n,s)}function p(e,t,r){var n=e<0?-1*e:e,s=Math.round,l=parseInt;if(t.length>7){var o=t.split(","),i=(r||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(o[0].slice(4)),c=l(o[1]),u=l(o[2]);return"rgb("+(s((l(i[0].slice(4))-a)*n)+a)+","+(s((l(i[1])-c)*n)+c)+","+(s((l(i[2])-u)*n)+u)+")"}var d=(o=l(t.slice(1),16))>>16,h=o>>8&255,f=255&o;return"#"+(16777216+65536*(s((((i=l((r||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*n)+d)+256*(s(((i>>8&255)-h)*n)+h)+(s(((255&i)-f)*n)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",m="rgb(120,99,248)";blendedcolor=h(-.8,b,m),blendedcolor2=p(-.8,b,m),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=h(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let r in t){(0,t[r])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,r=e||this.styleEl;if(null!=r)return r;if("sheet"==this.insertMethod&&(r=document.createElement("style"),document.head.appendChild(r),t=r.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,r){let n=this.getEnsureStyleSheet(r),s=new e,l=n;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,r]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,r)=>(r?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let r=this.getRoot(),n=this.nodeWord(),s=[];for(let t of e){s.push(t),r[n]||(r[n]={});let e=r[n][t];null==e&&(e=r[n][t]={key:t,position:s}),r=e}return r.leaf=!0,null!=t&&(r.handler=t),r}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var r=0;r0||!1}}forwardReduceValues(e,t,r,n){return t}minorCapture(e,t=this.sep,r=!0){let n="string"==typeof e?e.split(t):e,s=this.aliasConvert(n);s.length;let l,o=this.nodeWord(),i=this.getRoot(),a=0;if(this.isVendorPrefixMatch(s))s=s.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of s)if(l=i[o][e],a+=1,null!=l){if(!0===l.leaf){let e=s[a],t=l[o];if(null==(t&&t[e]))break}i=l}else if(r)break;let c=s.slice(0,a),u=s.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,r=!0){let n=this.objectSplit(e,t,r);return this.translateValue(n)}insertLine(e,t){let r=this.objectSplit(e);return this.insertRule(r,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let r=!0,n=t||[],s=0,l=[];for(;r;){let t=n[s],o=this.translateMap[t];o?[n,l,s]=o(e,n,l,s):l.push(this.beforeOutStack(n[s],s,e)),s+=1,(s>=n.length||s>100)&&(r=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,r){let n=this.getKeyFunctionMatch(e),s=this.collapseFunctions(n,r);return null==s?e:s}collapseFunctions(e,t){let r;for(var n=e.length-1;n>=0;n--){let s=e[n],l=null==r?s.remainder:r,o=s.handler;r=o&&o(l,s,n,t)||r}return r}getKeyFunctionMatch(e){let t=null!=e,r=e,n=[];for(;t;){let e=this.getKeyFunctionMatchOnce(r);e.success,t=e.match.start>-1,t&&(r=e.remainder,n.push(e))}return n}getKeyFunctionMatchOnce(e,t=".",r=":"){let n=e.lastIndexOf(t),s=e.length,l=e.slice(n+1,s).split(r),o=l[0],i=l.slice(1),a=this.keyValueFunctions.get(o),c={value:e,remainder:e.slice(0,n),handler:a,args:i,match:{start:n,end:s,name:o}};return c.success=null!=a,c}filterClasses(e,t,r=!1){let n=e.classList,s=r?{}:[],l=(e,t,r)=>s.push([r,t]);return r&&(l=(e,t,r)=>s[e]=[r,t]),n.forEach((function(e,r,n){let s=e.split("-")[0];t.indexOf(s)>-1&&l(s,e,r)})),s}filterSplit(e,t,r=!1){let n=this.filterClasses(e,t,r);if(r){let e={};for(let t in n){let r=n[t];e[t]=this.objectSplit(r[1],void 0,void 0,r[0])}return e}let s=[];return n.forEach((e=>{s.push(this.objectSplit(e))})),s}removeRule(e,t=void 0,r=!0){e?.props?.join("-");let n=this.asSelectorString(e,r);this.dcss.selectorExists(n)&&this.dcss.removeRuleBySelector(n)}insertRule(e,t=void 0,r=!0){let n=e?.props?.join("-"),s=this.asSelectorString(e,r);if(this.dcss.selectorExists(s))return this.dcss.getRuleBySelector(s);let l={[n]:this.translateValue(e)};t&&Object.assign(l,t);let o={insert:!0},i=e.node?.handler?.bind(e);if(i&&"function"==typeof i){let t=i(e);void 0!==t&&(o=t)}if(!1!==o.insert){let e=this.dcss.addStylesheetRules({[s]:l});return e.renderAll(),e}}insertReceiver(e,t){let r=this.addTree(e);return r.handler=t,r}asSelectorString(e,t=!0){let r;if(Array.isArray(e)){let t=e.join("-");r=this.escapeStr(t)}if("string"==typeof e&&(r=this.escapeStr(e)),e.props){let t=e.props.join("-");r=this.escapeStr(t)}e.str&&(r=this.escapeStr(e.str));let n=`.${r}`;return t?this.prependParent(n,e):n}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let r=this.objectSplit(e);return r.values.length>0&&r.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let r of t.rules)e+=`${r.cssText};\n`;return e}captureChanges(e,t,r){this.discoverInsert(e,r),this.discoverRemove(t,r)}discoverInsert(e,t){let r=this;for(let n of e){if(0==n.length)continue;let e=r.objectSplit(n);e.origin=t;let s=e.node?.handler;(s?s.bind(e):r.insertRule.bind(r))(e)}}discoverRemove(e,t){let r=this;for(let n of e){if(0==n.length)continue;let e=r.objectSplit(n);e.origin=t;let s=e.node?.unhandler,l=s?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let r=0;for(let n of t)this.safeInsertLine(n,e,r++)}safeInsertLine(e,t,r=-1){let n=this.objectSplit(e,void 0,void 0,r);return n.valid&&(n.origin=t,this.insertRule(n)),n}getAllClasses(e=document.body,t=!1,r=!0){let n=function(e){e.classList.forEach((e=>s.add(e)))},s=new Set;return t&&(s=new Map,n=function(e){s.set(e,new Set(e.classList))}),r&&n(e),e.querySelectorAll("*").forEach(n),s}addClass(e,...t){let r=this.asNodes(e);for(let e of r)for(let r of t)for(let t of r.split(" "))e.classList.add(t)}removeClass(e,...t){let r=this.asNodes(e);for(let e of r)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}r.addons={};const n=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},s=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=n(t),r=new a({target:t,isInline:!0});o.set(e,r)}};!function(e=document){e.addEventListener("DOMContentLoaded",function(){s()}.bind(this))}();class l{constructor([e]=[]){this.units=o;let t=new r(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,r){let n=this.reference;if(t in n)return n[t].bind?n[t].bind(n):n[t]},apply(e,t,r){console.log("innerProxyHandler apply...",r)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,r=void 0){const n=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===n)return r;let s=n.value;if(0==s.length)return r;return JSON.parse(s)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return o.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const o=new Map,i={safeSpace:{units:o,addons:[]},get(e,t,r){let n=this.getInstance();if(t in n){let e=n[t];return e&&e.bind?e.bind(n):e}return this.safeSpace[t]},newInstance(){return new l(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,r){return console.log("Polyclass apply...",e,t,r),r[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,r)):this.getInstance.apply(this,r)}},a=new Proxy((function(){return i.newInstance.apply(i,arguments)}),i);!function(){let e;const t=function(e,t){values=e.values;let[r,...s]=e.values;if(void 0!==document[`on${r}`]){const t=e.origin;n(e,t,r,s)}else console.warn("Unknown action",r)},n=function(e,t,r,n){let l=e=>s(e,r,n),o=`polyaction_${r}`;void 0===t.dataset[o]?(t.addEventListener(r,l),t.dataset[o]=!0):console.log("Event already exists:",r)},s=function(e,t,r){let[n,...s]=r;console.log(e,t,r),console.log(n,s);let l={call(){},toggle(){console.log(s,r,t),e.currentTarget.classList.toggle(s.join("-"))},setvar(){}}[n];l&&l()};console.log("event receiver"),r.addons.eventsReceiver=function(r){e=r,e.insertReceiver(["event"],t)}}(),function(){let e;const r=function(e){const t=e.values,r=e.origin;let s=i(t,r,e),o=l(t,s,r);u(o).forEach((e=>document.head.appendChild(e))),n(s)},n=function(t,r){for(let r of Object.values(t)){let t=r.first,n=(e,t)=>t?" ":"",l=s(t.replace(/[+]/g,n));r.cleanName=l,r.definition=o(r),e.dcss.addStylesheetRules(r.definition).renderAll()}},s=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},l=function(e,t,r){t=t||i(e,r);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},o=function(t){let r={};const n=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let s={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},s);t.isItal&&(e["font-style"]="italic");let o=l.concat([t.token]);r[`${n(o)}, ${n(o).toLowerCase()}`]=e}}let s=n(["font",t.first]),l=n(["font"].concat(t.first.split("+"))),o=new Set([s,l,s.toLowerCase(),l.toLowerCase()]);return r[Array.from(o).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},r},i=function(t,r,n){let s,l=0,o={},i=/([a-zA-Z-]{0,}?)(\d+)/,c=function(t,r){return e.filterSplit(r,t,!0)}(["default"],n?.origin||r),u="sans-serif",d=c.default;if(d)if(d.index<=n.index){let e="font default-* modifier should be indexed after font";console["warn"](e),u=d.values.join(" ")}else u=d.values.join(" ");for(let e in t){let r=t[e];if(0==l){o[l]={first:r,tokens:{},defaultFonts:u},s=l,l++;continue}let[n,a]=[null,null];try{let e;[e,n,a]=r.match(i),0==n.length&&(n="r")}catch{o[l]={first:r,tokens:{}},s=l,l++;continue}let c={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},d={int:Number(a)};if(0==d.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in n){let t=c[n[e]];Object.assign(d,t())}let h=o[s]?.tokens[a]||{};Object.assign(h,d),null==h.keys&&(h.keys=new Set),h.keys.add({isItal:d.ital,token:r}),o[s].tokens[a]=h,l++}return a(o)},a=function(e){for(let t in e){let r=e[t];0!=r.first.length&&c(r)}return e},c=function(e){let t=s(e.first),r=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),n=Object.assign({},...r),l=null!=n.ital,o=[],i=new Set;l&&o.push("ital"),(l||n.regu)&&o.push("wght");for(let t in e.tokens){let r=e.tokens[t],n=r.ital?1:0,s=r.int,o=l?[n]:[];o.push(s);let a=o.join(",");if(i.add(a),null!=r.regu){let e=l?[0]:[];e.push(s);let t=e.join(",");i.add(t)}}let a=Array.from(i).sort(),c=a.join(";"),u=`${t}:${o.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:o,titleToken:t,str:u})},u=function(e){return[h("link","preconnect",{href:"https://fonts.googleapis.com"}),h("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),h("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}&display=swap`})]};let d={};const h=function(e,t,r){let n={rel:t,href:e};Object.assign(n,r||{});let s=JSON.stringify,l=d[s(n)];return l||(d[s(n)]=f("link",n))},f=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let r=document.createElement(e);for(let e in t)r.setAttribute(e,t[e]);return r};t.addons.fontPackReceiver=function(t){e=t,e.insertReceiver(["font","pack"],r)}}(),(()=>{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&n(e)},r=new MutationObserver((function(e){e.forEach(t)}));return r.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),r},n=function(t){let r=t.target.classList.value,n=t.oldValue,l=r.split(/(?!\(.*)\s(?![^(]*?\))/g),o=null==n?[]:n.split(" ").map((e=>e.trim())),i=o?s(l,o):l;console.log("new",i),e.captureChanges(i,o,t.target)},s=function(e,t){const r=new Set(e);for(const e of t)r.delete(e);return r};r.addons.monitorClasses=function(t){e=t},r.prototype.monitor=function(e=document.body){return t(e)}})(),function(){let e,t;const n=function(r,n=":root"){if(console.log("Hook",r),null==t){let s={};for(let e in r){let t=`--${e}`,n=r[e];s[t]=n}let l=e.dcss.addStylesheetRules({[n]:s});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in r){let n=`--${e}`,s=r[e];t.sheetRule.style.setProperty(n,s)}};r.addons.varsReceiver=function(r){e=r,e.vars=n.bind(e),e.varsRoot=t}}(),function(){let e;const t=function(e,t,r,n){let s=t.slice(n).slice(1),l=`var(--${s.join("-")})`;return r.push(l),[[],r,n+s.length]};r.addons.varTranslateReceiver=function(r){e=r,e.insertTranslator("var",t)}}(),(()=>{class e extends Map{wordCounter=1;getKey(e){let r=t.get(e);return null==r&&(t.set(e,this.wordCounter),r=this.wordCounter,this.wordCounter++),r}stringToBits(e,t="-"){let r=e.split(t),n=[];return r.forEach(((e,t,r)=>n.push(this.getKey(e)))),n}stringToNest(e,t={}){let r=e.split("-");var n=t;let s=n,l=r.length;return r.forEach(((e,t,r)=>{let s=this.getKey(e),o=t==l-1;null==n[s]?n[s]=n=o?null:{}:n=n[s]})),s}installPropArray(e){e.forEach(((e,t,r)=>{this.stringToNest(e,n)}))}insertBitKey(e,t=n){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,r,n)=>e[t]=r)),e}wordsToArrayString(e=0,t=!1){return t?wordsToOrderedArray().join(" "):JSON.stringify(wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let r="";return this.forEach(((e,t,n)=>r+=[t,e].join(""))),r}graphToArrayListString(e=n,t=0,r=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,r))}graphToArrayListRecurse(e=n,t=0,r=null){let s=[],l=Object.entries(e);for(let e of l){let n=e[1];s.push([parseInt(e[0]),null==n?r:this.graphToArrayListRecurse(n,t,r)])}return s}graphToObjectString(e=0){let t={};for(let e in n)t[parseInt(e)]=n[e];return JSON.stringify(t,null,e)}}const t=new e,n={},s=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,r,n){const s=e=>e.join("-"),l=r||{row:{reverse:s},other:{horse:s}};let i=t.length,a=0,c=t.length+1,u=0,d=[];for(;ae.join("-");let r=s[n];return null==r&&(r=t),[r(e.slice(0,i+1)),i+1]}return[e[0],1]};r.addons.forwardReduceValues=e=>t.installPropArray(s),r.prototype.forwardReduceValues=l,r.prototype.valuesGraph={microGraph:n,words:t}})(); +document.createElement("span"),(()=>{var e=Math.round,t=parseInt,n=(e,t,n)=>`rgb(${e},${t},${n})`;let r=function(e,t="#000000",n="#FFFFFF"){return e||(h?t:n)},s=function(e){return r(e,n(0,0,0),n(255,255,255))},l=function(e,t,n){let r=e>>t;return n?r&n:r},i=function(e,t,n,r){let s=l(e,t,n);return a(s,r)},o=(e,n)=>a(t(e),n),a=function(t,n){return e(c(t-n))+n},c=function(e){return e*u};var u,h;function d(e,l,i){return u=(h=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=s(l),c=a.split(","),u=t(i[0].slice(4)),h=t(i[1]),d=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],h),g=o(c[2],d);return n(f,p,g)}(0,l,i):function(e,n,s){var l=t(n.slice(1),16),i=r(s).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,n,r){let s=l(e,n,r);return i(t,n,r,s)}function p(e,t,n){var r=e<0?-1*e:e,s=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(n||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(s((l(o[0].slice(4))-a)*r)+a)+","+(s((l(o[1])-c)*r)+c)+","+(s((l(o[2])-u)*r)+u)+")"}var h=(i=l(t.slice(1),16))>>16,d=i>>8&255,f=255&i;return"#"+(16777216+65536*(s((((o=l((n||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-h)*r)+h)+256*(s(((o>>8&255)-d)*r)+d)+(s(((255&o)-f)*r)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=d(-.8,b,v),blendedcolor2=p(-.8,b,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=d(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let n in t){(0,t[n])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,n=e||this.styleEl;if(null!=n)return n;if("sheet"==this.insertMethod&&(n=document.createElement("style"),document.head.appendChild(n),t=n.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,n){let r=this.getEnsureStyleSheet(n),s=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,n]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,n)=>(n?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let n=this.getRoot(),r=this.nodeWord(),s=[];for(let t of e){s.push(t),n[r]||(n[r]={});let e=n[r][t];null==e&&(e=n[r][t]={key:t,position:s}),n=e}return n.leaf=!0,null!=t&&(n.handler=t),n}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var n=0;n0||!1}}forwardReduceValues(e,t,n,r){let s=e,l=t;for(let e of this.reducers){l=e(s,l)}return l}minorCapture(e,t=this.sep,n=!0){let r="string"==typeof e?e.split(t):e,s=this.aliasConvert(r);s.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(s))s=s.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of s)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=s[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(n)break;let c=s.slice(0,a),u=s.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,n=!0){let r=this.objectSplit(e,t,n);return this.translateValue(r)}insertLine(e,t){let n=this.objectSplit(e);return this.insertRule(n,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let n=!0,r=t||[],s=0,l=[];for(;n;){let t=r[s],i=this.translateMap[t];i?[r,l,s]=i(e,r,l,s):l.push(this.beforeOutStack(r[s],s,e)),s+=1,(s>=r.length||s>100)&&(n=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,n){let r=this.getKeyFunctionMatch(e),s=this.collapseFunctions(r,n);return null==s?e:s}collapseFunctions(e,t){let n;for(var r=e.length-1;r>=0;r--){let s=e[r],l=null==n?s.remainder:n,i=s.handler;n=i&&i(l,s,r,t)||n}return n}getKeyFunctionMatch(e){let t=null!=e,n=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(n);e.success,t=e.match.start>-1,t&&(n=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",n=":"){let r=e.lastIndexOf(t),s=e.length,l=e.slice(r+1,s).split(n),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:s,name:i}};return c.success=null!=a,c}filterClasses(e,t,n=!1){let r=e.classList,s=n?{}:[],l=(e,t,n)=>s.push([n,t]);return n&&(l=(e,t,n)=>s[e]=[n,t]),r.forEach((function(e,n,r){let s=e.split("-")[0];t.indexOf(s)>-1&&l(s,e,n)})),s}filterSplit(e,t,n=!1){let r=this.filterClasses(e,t,n);if(n){let e={};for(let t in r){let n=r[t];e[t]=this.objectSplit(n[1],void 0,void 0,n[0])}return e}let s=[];return r.forEach((e=>{s.push(this.objectSplit(e))})),s}removeRule(e,t=void 0,n=!0){e?.props?.join("-");let r=this.asSelectorString(e,n);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,n=!0){let r=e?.props?.join("-"),s=this.asSelectorString(e,n);if(this.dcss.selectorExists(s))return this.dcss.getRuleBySelector(s);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[s]:l});return e.renderAll(),e}}insertReceiver(e,t){let n=this.addTree(e);return n.handler=t,n}asSelectorString(e,t=!0){let n;if(Array.isArray(e)){let t=e.join("-");n=this.escapeStr(t)}if("string"==typeof e&&(n=this.escapeStr(e)),e.props){let t=e.props.join("-");n=this.escapeStr(t)}e.str&&(n=this.escapeStr(e.str));let r=`.${n}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let n=this.objectSplit(e);return n.values.length>0&&n.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let n of t.rules)e+=`${n.cssText};\n`;return e}captureChanges(e,t,n){this.discoverInsert(e,n),this.discoverRemove(t,n)}discoverInsert(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.handler;(s?s.bind(e):n.insertRule.bind(n))(e)}}discoverRemove(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.unhandler,l=s?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let n=0;for(let r of t)this.safeInsertLine(r,e,n++)}safeInsertLine(e,t,n=-1){let r=this.objectSplit(e,void 0,void 0,n);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,n=!0){let r=function(e){e.classList.forEach((e=>s.add(e)))},s=new Set;return t&&(s=new Map,r=function(e){s.set(e,new Set(e.classList))}),n&&r(e),e.querySelectorAll("*").forEach(r),s}addClass(e,...t){let n=this.asNodes(e);for(let e of n)for(let n of t)for(let t of n.split(" "))e.classList.add(t)}removeClass(e,...t){let n=this.asNodes(e);for(let e of n)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}n.addons={};const r=function(e){return e.dataset.polyclassId=function(e){return e.dataset.polyclassId||Math.random().toString(32).slice(2)}(e)},s=function(){const e=document.querySelectorAll("*[polyclass]");for(let t of e){let e=r(t),n=new a({target:t,isInline:!0});i.set(e,n)}};!function(e=document){["complete","interactive"].indexOf(document.readyState)>-1&&s(),e.addEventListener("DOMContentLoaded",function(){s()}.bind(this))}();class l{constructor([e]=[]){this.units=i;let t=new n(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,n){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,n){console.log("innerProxyHandler apply...",n)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,n=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return n;let s=r.value;if(0==s.length)return n;return JSON.parse(s)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return i.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const i=new Map,o={safeSpace:{units:i,addons:[]},get(e,t,n){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new l(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,n){return console.log("Polyclass apply...",e,t,n),n[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,n)):this.getInstance.apply(this,n)}},a=new Proxy((function(){return o.newInstance.apply(o,arguments)}),o);const c=function(e){return f(e)||d(e)||u(e)||h(e)},u=function(e){let t=e.split("/");return 2==t.length&&(c(t[0])&&f(t[1]))},h=function(e){let t=new Set(["deg","grad","rad","turn"]),n=e.slice(parseFloat(e).toString().length,e.length);return t.has(n)},d=function(e){return e.endsWith("%")&&f(e.slice(0,e.length-1))},f=function(e){if(null==e||0==e.length)return!1;return!isNaN(Number(e))},p=function(e){let t=e.slice(4,5),n="";return t.length>0&&(n=`/${t}`),`${e[0]}(${e.slice(1,4).join(" ")}${n})`},g=function(e,t,n,r=void 0){let s=t.length,l=0,i=t.length+1,o=0,a=[];for(;lt.has(e),o=e.length,a=[],u=[],h=[];for(;ls(e,n,r),i=`polyaction_${n}`;void 0===t.dataset[i]?(t.addEventListener(n,l),t.dataset[i]=!0):console.log("Event already exists:",n)},s=function(e,t,n){let[r,...s]=n;console.log(e,t,n),console.log(r,s);let l={call(){},toggle(){console.log(s,n,t),e.currentTarget.classList.toggle(s.join("-"))},setvar(){}}[r];l&&l()};console.log("event receiver"),n.addons.eventsReceiver=function(n){e=n,e.insertReceiver(["event"],t)}}(),function(){let e;const r=function(e){const t=e.values,n=e.origin;let r=c(t,n,e),i=o(t,r,n);s(i),l(r)},s=function(e,t){return d(e,t).forEach((e=>document.head.appendChild(e)))},l=function(t,n){for(let n of Object.values(t)){let t=n.first,r=(e,t)=>t?" ":"",s=i(t.replace(/[+]/g,r));n.cleanName=s,n.definition=a(n),e.dcss.addStylesheetRules(n.definition).renderAll()}},i=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},o=function(e,t,n){t=t||c(e,n);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},a=function(t){let n={};const r=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let s={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},s);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);n[`${r(i)}, ${r(i).toLowerCase()}`]=e}}let s=r(["font",t.first]),l=r(["font"].concat(t.first.split("+"))),i=new Set([s,l,s.toLowerCase(),l.toLowerCase()]);return n[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},n},c=function(t,n,r){let s,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,a=function(t,n){return e.filterSplit(n,t,!0)}(["default"],r?.origin||n),c="sans-serif",h=a.default;if(h)if(h.index<=r.index){let e="font default-* modifier should be indexed after font";console["warn"](e),c=h.values.join(" ")}else c=h.values.join(" ");for(let e in t){let n=t[e];if(0==l){i[l]={first:n,tokens:{},defaultFonts:c},s=l,l++;continue}let[r,a]=[null,null];try{let e;[e,r,a]=n.match(o),0==r.length&&(r="r")}catch{i[l]={first:n,tokens:{}},s=l,l++;continue}let u={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},h={int:Number(a)};if(0==h.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in r){let t=u[r[e]];Object.assign(h,t())}let d=i[s]?.tokens[a]||{};Object.assign(d,h),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:h.ital,token:n}),i[s].tokens[a]=d,l++}return u(i)},u=function(e){for(let t in e){let n=e[t];0!=n.first.length&&h(n)}return e},h=function(e){let t=i(e.first),n=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),r=Object.assign({},...n),s=null!=r.ital,l=[],o=new Set;s&&l.push("ital"),(s||r.regu)&&l.push("wght");for(let t in e.tokens){let n=e.tokens[t],r=n.ital?1:0,l=n.int,i=s?[r]:[];i.push(l);let a=i.join(",");if(o.add(a),null!=n.regu){let e=s?[0]:[];e.push(l);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${l.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:l,titleToken:t,str:u})},d=function(e,t="swap"){return[p("link","preconnect",{href:"https://fonts.googleapis.com"}),p("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),p("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}${null==t?"":`&display=${t}`}`})]};let f={};const p=function(e,t,n){let r={rel:t,href:e};Object.assign(r,n||{});let s=JSON.stringify,l=f[s(r)];return l||(f[s(r)]=g("link",r))},g=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(e);for(let e in t)n.setAttribute(e,t[e]);return n};t.addons.fontPackReceiver=function(t){e=t,e.insertReceiver(["font","pack"],r)},n.prototype.generateGoogleLinks=d,n.prototype.installGoogleLinks=s}(),function(){let e;const t=function(e,t,n,r){return t.value.slice(0,t.match.start),t.args.length>0?t.args[0]:"green"},r=function(e,t,n,r){console.log("raise hook",t,r);let s=t.value.slice(0,t.match.start);console.log(s)};n.addons.functionsReceiver=function(n){e=n,e.keyValueFunctions.set("forceGreen",t),e.keyValueFunctions.set("force",t),e.keyValueFunctions.set("raise",r)}}(),function(){let e;const t=function(t){var n;let s=`family=${`Material+Symbols+${(n=t.values,n.map((function(e){return e.charAt(0).toUpperCase()+e.substring(1,e.length)}))).join("+")}`}:${l({opsz:"20..48",wght:"100..700",FILL:"0..1",GRAD:"-50..200"})}`,o=[...t.values,"icon"];e.insertReceiver(o,i),a.graph.installGoogleLinks(s,null),r(t,fontSettings)},r=function(t,n){let r=t.values[0],l={},i={"font-variation-settings":`${s(n)}`,"font-size":"inherit"};l[`.material-symbols-${r}`]=i,e.dcss.addStylesheetRules(l).renderAll()},s=function(e){let t="",n=Object.keys(e);for(var r=0;r{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&r(e)},n=new MutationObserver((function(e){e.forEach(t)}));return n.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),n},r=function(t){let n=t.target.classList.value,r=t.oldValue,l=n.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==r?[]:r.split(" ").map((e=>e.trim())),o=i?s(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},s=function(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n};n.addons.monitorClasses=function(t){e=t},n.prototype.monitor=function(e=document.body){return t(e)}})(),(()=>{class e extends Map{wordCounter=1;getKey(e){let n=t.get(e);return null==n&&(t.set(e,this.wordCounter),n=this.wordCounter,this.wordCounter++),n}stringToBits(e,t="-"){let n=e.split(t),r=[];return n.forEach(((e,t,n)=>r.push(this.getKey(e)))),r}stringToNest(e,t={}){let n=e.split("-");var r=t;let s=r,l=n.length;return n.forEach(((e,t,n)=>{let s=this.getKey(e),i=t==l-1;null==r[s]?r[s]=r=i?null:{}:r=r[s]})),s}installPropArray(e){e.forEach(((e,t,n)=>{this.stringToNest(e,r)}))}insertBitKey(e,t=r){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,n,r)=>e[t]=n)),e}wordsToArrayString(e=0,t=!1){return t?this.wordsToOrderedArray().join(" "):JSON.stringify(this.wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let n="";return this.forEach(((e,t,r)=>n+=[t,e].join(""))),n}graphToArrayListString(e=r,t=0,n=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,n))}graphToArrayListRecurse(e=r,t=0,n=null){let s=[],l=Object.entries(e);for(let e of l){let r=e[1];s.push([parseInt(e[0]),null==r?n:this.graphToArrayListRecurse(r,t,n)])}return s}graphToObjectString(e=0){let t={};for(let e in r)t[parseInt(e)]=r[e];return JSON.stringify(t,null,e)}}const t=new e,r={},s=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,n,r){const s=n||{row:{reverse:e=>e.join("-")}};let l=t.length,o=0,a=t.length+1,c=0,u=[];for(;oe.join("-");let n=s[r];return null==n&&(n=t),[n(e.slice(0,o+1)),o+1]}return[e[0],1]};n.addons.forwardReduceValues=function(e){return e.reducers.push((function(e,n){return l(e,n,r,t)})),t.installPropArray(s)},n.prototype.valuesGraph={microGraph:r,words:t}})(),function(){let e;const t=function(e,t,n,r){let s=t.slice(r).slice(1),l=`var(--${s.join("-")})`;return n.push(l),[[],n,r+s.length]};n.addons.varTranslateReceiver=function(n){e=n,e.insertTranslator("var",t)}}(),function(){let e,t;const r=function(n,r=":root"){if(console.log("Hook",n),null==t){let s={};for(let e in n){let t=`--${e}`,r=n[e];s[t]=r}let l=e.dcss.addStylesheetRules({[r]:s});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in n){let r=`--${e}`,s=n[e];t.sheetRule.style.setProperty(r,s)}};n.addons.varsReceiver=function(n){e=n,e.vars=r.bind(e),e.varsRoot=t}}(); diff --git a/dist/polyclass.core.js b/dist/polyclass.core.js index cc6d4cc..c34184a 100755 --- a/dist/polyclass.core.js +++ b/dist/polyclass.core.js @@ -1 +1 @@ -document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",S="#343BFF",y="rgb(234,47,120)",b="rgb(120,99,248)";blendedcolor=u(-.8,y,b),blendedcolor2=f(-.8,y,b),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,S),blendedcolor2=f(-.8,g,S),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){return t}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};class r{constructor([e]=[]){this.units=n;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);export{s as ClassGraph,t as DynamicCSSStyleSheet,i as Polyclass,e as RenderArray}; +document.createElement("span"),(()=>{var e=Math.round,t=parseInt,s=(e,t,s)=>`rgb(${e},${t},${s})`;let r=function(e,t="#000000",s="#FFFFFF"){return e||(d?t:s)},n=function(e){return r(e,s(0,0,0),s(255,255,255))},l=function(e,t,s){let r=e>>t;return s?r&s:r},i=function(e,t,s,r){let n=l(e,t,s);return a(n,r)},o=(e,s)=>a(t(e),s),a=function(t,s){return e(h(t-s))+s},h=function(e){return e*c};var c,d;function u(e,l,i){return c=(d=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=n(l),h=a.split(","),c=t(i[0].slice(4)),d=t(i[1]),u=t(i[2]),p=o(h[0].slice(4),c),f=o(h[1],d),g=o(h[2],u);return s(p,f,g)}(0,l,i):function(e,s,n){var l=t(s.slice(1),16),i=r(n).slice(1),o=t(i,16),a=p(l,o,16,0),h=p(l,o,8,255),c=p(l,o,0,255);return`#${(16777216+65536*a+256*h+c).toString(16).slice(1)}`}(0,l,i)}function p(e,t,s,r){let n=l(e,s,r);return i(t,s,r,n)}function f(e,t,s){var r=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(s||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),h=l(i[1]),c=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*r)+a)+","+(n((l(o[1])-h)*r)+h)+","+(n((l(o[2])-c)*r)+c)+")"}var d=(i=l(t.slice(1),16))>>16,u=i>>8&255,p=255&i;return"#"+(16777216+65536*(n((((o=l((s||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(n(((o>>8&255)-u)*r)+u)+(n(((255&o)-p)*r)+p)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",S="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=u(-.8,S,v),blendedcolor2=f(-.8,S,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=u(-.8,g,y),blendedcolor2=f(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let s in t){(0,t[s])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,s=e||this.styleEl;if(null!=s)return s;if("sheet"==this.insertMethod&&(s=document.createElement("style"),document.head.appendChild(s),t=s.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,s){let r=this.getEnsureStyleSheet(s),n=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,s]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,s)=>(s?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let s=this.getRoot(),r=this.nodeWord(),n=[];for(let t of e){n.push(t),s[r]||(s[r]={});let e=s[r][t];null==e&&(e=s[r][t]={key:t,position:n}),s=e}return s.leaf=!0,null!=t&&(s.handler=t),s}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var s=0;s0||!1}}forwardReduceValues(e,t,s,r){let n=e,l=t;for(let e of this.reducers){l=e(n,l)}return l}minorCapture(e,t=this.sep,s=!0){let r="string"==typeof e?e.split(t):e,n=this.aliasConvert(r);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(s)break;let h=n.slice(0,a),c=n.slice(a);return{props:h,values:c,str:e,node:l,valid:l&&c.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,s=!0){let r=this.objectSplit(e,t,s);return this.translateValue(r)}insertLine(e,t){let s=this.objectSplit(e);return this.insertRule(s,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let s=!0,r=t||[],n=0,l=[];for(;s;){let t=r[n],i=this.translateMap[t];i?[r,l,n]=i(e,r,l,n):l.push(this.beforeOutStack(r[n],n,e)),n+=1,(n>=r.length||n>100)&&(s=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,s){let r=this.getKeyFunctionMatch(e),n=this.collapseFunctions(r,s);return null==n?e:n}collapseFunctions(e,t){let s;for(var r=e.length-1;r>=0;r--){let n=e[r],l=null==s?n.remainder:s,i=n.handler;s=i&&i(l,n,r,t)||s}return s}getKeyFunctionMatch(e){let t=null!=e,s=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(s);e.success,t=e.match.start>-1,t&&(s=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",s=":"){let r=e.lastIndexOf(t),n=e.length,l=e.slice(r+1,n).split(s),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),h={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:n,name:i}};return h.success=null!=a,h}filterClasses(e,t,s=!1){let r=e.classList,n=s?{}:[],l=(e,t,s)=>n.push([s,t]);return s&&(l=(e,t,s)=>n[e]=[s,t]),r.forEach((function(e,s,r){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,s)})),n}filterSplit(e,t,s=!1){let r=this.filterClasses(e,t,s);if(s){let e={};for(let t in r){let s=r[t];e[t]=this.objectSplit(s[1],void 0,void 0,s[0])}return e}let n=[];return r.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,s=!0){e?.props?.join("-");let r=this.asSelectorString(e,s);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,s=!0){let r=e?.props?.join("-"),n=this.asSelectorString(e,s);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let s=this.addTree(e);return s.handler=t,s}asSelectorString(e,t=!0){let s;if(Array.isArray(e)){let t=e.join("-");s=this.escapeStr(t)}if("string"==typeof e&&(s=this.escapeStr(e)),e.props){let t=e.props.join("-");s=this.escapeStr(t)}e.str&&(s=this.escapeStr(e.str));let r=`.${s}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let s=this.objectSplit(e);return s.values.length>0&&s.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let s of t.rules)e+=`${s.cssText};\n`;return e}captureChanges(e,t,s){this.discoverInsert(e,s),this.discoverRemove(t,s)}discoverInsert(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.handler;(n?n.bind(e):s.insertRule.bind(s))(e)}}discoverRemove(e,t){let s=this;for(let r of e){if(0==r.length)continue;let e=s.objectSplit(r);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let s=0;for(let r of t)this.safeInsertLine(r,e,s++)}safeInsertLine(e,t,s=-1){let r=this.objectSplit(e,void 0,void 0,s);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,s=!0){let r=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,r=function(e){n.set(e,new Set(e.classList))}),s&&r(e),e.querySelectorAll("*").forEach(r),n}addClass(e,...t){let s=this.asNodes(e);for(let e of s)for(let s of t)for(let t of s.split(" "))e.classList.add(t)}removeClass(e,...t){let s=this.asNodes(e);for(let e of s)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}s.addons={};class r{constructor([e]=[]){this.units=n;let t=new s(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,s){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,s){console.log("innerProxyHandler apply...",s)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,s=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return s;let n=r.value;if(0==n.length)return s;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,s){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,s){return console.log("Polyclass apply...",e,t,s),s[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,s)):this.getInstance.apply(this,s)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);export{s as ClassGraph,t as DynamicCSSStyleSheet,i as Polyclass,e as RenderArray}; diff --git a/dist/polyclass.full.js b/dist/polyclass.full.js index f5a5e67..7dcf530 100755 --- a/dist/polyclass.full.js +++ b/dist/polyclass.full.js @@ -1 +1 @@ -document.createElement("span"),(()=>{var e=Math.round,t=parseInt,r=(e,t,r)=>`rgb(${e},${t},${r})`;let s=function(e,t="#000000",r="#FFFFFF"){return e||(h?t:r)},n=function(e){return s(e,r(0,0,0),r(255,255,255))},l=function(e,t,r){let s=e>>t;return r?s&r:s},i=function(e,t,r,s){let n=l(e,t,r);return a(n,s)},o=(e,r)=>a(t(e),r),a=function(t,r){return e(c(t-r))+r},c=function(e){return e*u};var u,h;function d(e,l,i){return u=(h=e<0)?-1*e:e,l.length>7?function(e,s,l){let i=s.split(","),a=n(l),c=a.split(","),u=t(i[0].slice(4)),h=t(i[1]),d=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],h),g=o(c[2],d);return r(f,p,g)}(0,l,i):function(e,r,n){var l=t(r.slice(1),16),i=s(n).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,r,s){let n=l(e,r,s);return i(t,r,s,n)}function p(e,t,r){var s=e<0?-1*e:e,n=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(r||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(n((l(o[0].slice(4))-a)*s)+a)+","+(n((l(o[1])-c)*s)+c)+","+(n((l(o[2])-u)*s)+u)+")"}var h=(i=l(t.slice(1),16))>>16,d=i>>8&255,f=255&i;return"#"+(16777216+65536*(n((((o=l((r||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-h)*s)+h)+256*(n(((o>>8&255)-d)*s)+d)+(n(((255&o)-f)*s)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",m="rgb(120,99,248)";blendedcolor=d(-.8,b,m),blendedcolor2=p(-.8,b,m),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=d(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let r in t){(0,t[r])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,r=e||this.styleEl;if(null!=r)return r;if("sheet"==this.insertMethod&&(r=document.createElement("style"),document.head.appendChild(r),t=r.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,r){let s=this.getEnsureStyleSheet(r),n=new e,l=s;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.translateMap={},!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,r]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,r)=>(r?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let r=this.getRoot(),s=this.nodeWord(),n=[];for(let t of e){n.push(t),r[s]||(r[s]={});let e=r[s][t];null==e&&(e=r[s][t]={key:t,position:n}),r=e}return r.leaf=!0,null!=t&&(r.handler=t),r}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var r=0;r0||!1}}forwardReduceValues(e,t,r,s){return t}minorCapture(e,t=this.sep,r=!0){let s="string"==typeof e?e.split(t):e,n=this.aliasConvert(s);n.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(n))n=n.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of n)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=n[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(r)break;let c=n.slice(0,a),u=n.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,r=!0){let s=this.objectSplit(e,t,r);return this.translateValue(s)}insertLine(e,t){let r=this.objectSplit(e);return this.insertRule(r,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let r=!0,s=t||[],n=0,l=[];for(;r;){let t=s[n],i=this.translateMap[t];i?[s,l,n]=i(e,s,l,n):l.push(this.beforeOutStack(s[n],n,e)),n+=1,(n>=s.length||n>100)&&(r=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,r){let s=this.getKeyFunctionMatch(e),n=this.collapseFunctions(s,r);return null==n?e:n}collapseFunctions(e,t){let r;for(var s=e.length-1;s>=0;s--){let n=e[s],l=null==r?n.remainder:r,i=n.handler;r=i&&i(l,n,s,t)||r}return r}getKeyFunctionMatch(e){let t=null!=e,r=e,s=[];for(;t;){let e=this.getKeyFunctionMatchOnce(r);e.success,t=e.match.start>-1,t&&(r=e.remainder,s.push(e))}return s}getKeyFunctionMatchOnce(e,t=".",r=":"){let s=e.lastIndexOf(t),n=e.length,l=e.slice(s+1,n).split(r),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,s),handler:a,args:o,match:{start:s,end:n,name:i}};return c.success=null!=a,c}filterClasses(e,t,r=!1){let s=e.classList,n=r?{}:[],l=(e,t,r)=>n.push([r,t]);return r&&(l=(e,t,r)=>n[e]=[r,t]),s.forEach((function(e,r,s){let n=e.split("-")[0];t.indexOf(n)>-1&&l(n,e,r)})),n}filterSplit(e,t,r=!1){let s=this.filterClasses(e,t,r);if(r){let e={};for(let t in s){let r=s[t];e[t]=this.objectSplit(r[1],void 0,void 0,r[0])}return e}let n=[];return s.forEach((e=>{n.push(this.objectSplit(e))})),n}removeRule(e,t=void 0,r=!0){e?.props?.join("-");let s=this.asSelectorString(e,r);this.dcss.selectorExists(s)&&this.dcss.removeRuleBySelector(s)}insertRule(e,t=void 0,r=!0){let s=e?.props?.join("-"),n=this.asSelectorString(e,r);if(this.dcss.selectorExists(n))return this.dcss.getRuleBySelector(n);let l={[s]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[n]:l});return e.renderAll(),e}}insertReceiver(e,t){let r=this.addTree(e);return r.handler=t,r}asSelectorString(e,t=!0){let r;if(Array.isArray(e)){let t=e.join("-");r=this.escapeStr(t)}if("string"==typeof e&&(r=this.escapeStr(e)),e.props){let t=e.props.join("-");r=this.escapeStr(t)}e.str&&(r=this.escapeStr(e.str));let s=`.${r}`;return t?this.prependParent(s,e):s}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let r=this.objectSplit(e);return r.values.length>0&&r.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let r of t.rules)e+=`${r.cssText};\n`;return e}captureChanges(e,t,r){this.discoverInsert(e,r),this.discoverRemove(t,r)}discoverInsert(e,t){let r=this;for(let s of e){if(0==s.length)continue;let e=r.objectSplit(s);e.origin=t;let n=e.node?.handler;(n?n.bind(e):r.insertRule.bind(r))(e)}}discoverRemove(e,t){let r=this;for(let s of e){if(0==s.length)continue;let e=r.objectSplit(s);e.origin=t;let n=e.node?.unhandler,l=n?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let r=0;for(let s of t)this.safeInsertLine(s,e,r++)}safeInsertLine(e,t,r=-1){let s=this.objectSplit(e,void 0,void 0,r);return s.valid&&(s.origin=t,this.insertRule(s)),s}getAllClasses(e=document.body,t=!1,r=!0){let s=function(e){e.classList.forEach((e=>n.add(e)))},n=new Set;return t&&(n=new Map,s=function(e){n.set(e,new Set(e.classList))}),r&&s(e),e.querySelectorAll("*").forEach(s),n}addClass(e,...t){let r=this.asNodes(e);for(let e of r)for(let r of t)for(let t of r.split(" "))e.classList.add(t)}removeClass(e,...t){let r=this.asNodes(e);for(let e of r)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}r.addons={};class s{constructor([e]=[]){this.units=n;let t=new r(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,r){let s=this.reference;if(t in s)return s[t].bind?s[t].bind(s):s[t]},apply(e,t,r){console.log("innerProxyHandler apply...",r)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,r=void 0){const s=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===s)return r;let n=s.value;if(0==n.length)return r;return JSON.parse(n)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return n.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const n=new Map,l={safeSpace:{units:n,addons:[]},get(e,t,r){let s=this.getInstance();if(t in s){let e=s[t];return e&&e.bind?e.bind(s):e}return this.safeSpace[t]},newInstance(){return new s(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,r){return console.log("Polyclass apply...",e,t,r),r[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,r)):this.getInstance.apply(this,r)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);!function(){let e;const t=function(e,t){values=e.values;let[r,...n]=e.values;if(void 0!==document[`on${r}`]){const t=e.origin;s(e,t,r,n)}else console.warn("Unknown action",r)},s=function(e,t,r,s){let l=e=>n(e,r,s),i=`polyaction_${r}`;void 0===t.dataset[i]?(t.addEventListener(r,l),t.dataset[i]=!0):console.log("Event already exists:",r)},n=function(e,t,r){let[s,...n]=r;console.log(e,t,r),console.log(s,n);let l={call(){},toggle(){console.log(n,r,t),e.currentTarget.classList.toggle(n.join("-"))},setvar(){}}[s];l&&l()};console.log("event receiver"),r.addons.eventsReceiver=function(r){e=r,e.insertReceiver(["event"],t)}}(),function(){let e;const r=function(e){const t=e.values,r=e.origin;let n=o(t,r,e),i=l(t,n,r);u(i).forEach((e=>document.head.appendChild(e))),s(n)},s=function(t,r){for(let r of Object.values(t)){let t=r.first,s=(e,t)=>t?" ":"",l=n(t.replace(/[+]/g,s));r.cleanName=l,r.definition=i(r),e.dcss.addStylesheetRules(r.definition).renderAll()}},n=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},l=function(e,t,r){t=t||o(e,r);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},i=function(t){let r={};const s=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let n={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},n);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);r[`${s(i)}, ${s(i).toLowerCase()}`]=e}}let n=s(["font",t.first]),l=s(["font"].concat(t.first.split("+"))),i=new Set([n,l,n.toLowerCase(),l.toLowerCase()]);return r[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},r},o=function(t,r,s){let n,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,c=function(t,r){return e.filterSplit(r,t,!0)}(["default"],s?.origin||r),u="sans-serif",h=c.default;if(h)if(h.index<=s.index){let e="font default-* modifier should be indexed after font";console["warn"](e),u=h.values.join(" ")}else u=h.values.join(" ");for(let e in t){let r=t[e];if(0==l){i[l]={first:r,tokens:{},defaultFonts:u},n=l,l++;continue}let[s,a]=[null,null];try{let e;[e,s,a]=r.match(o),0==s.length&&(s="r")}catch{i[l]={first:r,tokens:{}},n=l,l++;continue}let c={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},h={int:Number(a)};if(0==h.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in s){let t=c[s[e]];Object.assign(h,t())}let d=i[n]?.tokens[a]||{};Object.assign(d,h),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:h.ital,token:r}),i[n].tokens[a]=d,l++}return a(i)},a=function(e){for(let t in e){let r=e[t];0!=r.first.length&&c(r)}return e},c=function(e){let t=n(e.first),r=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),s=Object.assign({},...r),l=null!=s.ital,i=[],o=new Set;l&&i.push("ital"),(l||s.regu)&&i.push("wght");for(let t in e.tokens){let r=e.tokens[t],s=r.ital?1:0,n=r.int,i=l?[s]:[];i.push(n);let a=i.join(",");if(o.add(a),null!=r.regu){let e=l?[0]:[];e.push(n);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${i.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:i,titleToken:t,str:u})},u=function(e){return[d("link","preconnect",{href:"https://fonts.googleapis.com"}),d("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),d("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}&display=swap`})]};let h={};const d=function(e,t,r){let s={rel:t,href:e};Object.assign(s,r||{});let n=JSON.stringify,l=h[n(s)];return l||(h[n(s)]=f("link",s))},f=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let r=document.createElement(e);for(let e in t)r.setAttribute(e,t[e]);return r};t.addons.fontPackReceiver=function(t){e=t,e.insertReceiver(["font","pack"],r)}}(),(()=>{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&s(e)},r=new MutationObserver((function(e){e.forEach(t)}));return r.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),r},s=function(t){let r=t.target.classList.value,s=t.oldValue,l=r.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==s?[]:s.split(" ").map((e=>e.trim())),o=i?n(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},n=function(e,t){const r=new Set(e);for(const e of t)r.delete(e);return r};r.addons.monitorClasses=function(t){e=t},r.prototype.monitor=function(e=document.body){return t(e)}})(),function(){let e,t;const s=function(r,s=":root"){if(console.log("Hook",r),null==t){let n={};for(let e in r){let t=`--${e}`,s=r[e];n[t]=s}let l=e.dcss.addStylesheetRules({[s]:n});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in r){let s=`--${e}`,n=r[e];t.sheetRule.style.setProperty(s,n)}};r.addons.varsReceiver=function(r){e=r,e.vars=s.bind(e),e.varsRoot=t}}(),function(){let e;const t=function(e,t,r,s){let n=t.slice(s).slice(1),l=`var(--${n.join("-")})`;return r.push(l),[[],r,s+n.length]};r.addons.varTranslateReceiver=function(r){e=r,e.insertTranslator("var",t)}}(),(()=>{class e extends Map{wordCounter=1;getKey(e){let r=t.get(e);return null==r&&(t.set(e,this.wordCounter),r=this.wordCounter,this.wordCounter++),r}stringToBits(e,t="-"){let r=e.split(t),s=[];return r.forEach(((e,t,r)=>s.push(this.getKey(e)))),s}stringToNest(e,t={}){let r=e.split("-");var s=t;let n=s,l=r.length;return r.forEach(((e,t,r)=>{let n=this.getKey(e),i=t==l-1;null==s[n]?s[n]=s=i?null:{}:s=s[n]})),n}installPropArray(e){e.forEach(((e,t,r)=>{this.stringToNest(e,s)}))}insertBitKey(e,t=s){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,r,s)=>e[t]=r)),e}wordsToArrayString(e=0,t=!1){return t?wordsToOrderedArray().join(" "):JSON.stringify(wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let r="";return this.forEach(((e,t,s)=>r+=[t,e].join(""))),r}graphToArrayListString(e=s,t=0,r=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,r))}graphToArrayListRecurse(e=s,t=0,r=null){let n=[],l=Object.entries(e);for(let e of l){let s=e[1];n.push([parseInt(e[0]),null==s?r:this.graphToArrayListRecurse(s,t,r)])}return n}graphToObjectString(e=0){let t={};for(let e in s)t[parseInt(e)]=s[e];return JSON.stringify(t,null,e)}}const t=new e,s={},n=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,r,s){const n=e=>e.join("-"),l=r||{row:{reverse:n},other:{horse:n}};let o=t.length,a=0,c=t.length+1,u=0,h=[];for(;ae.join("-");let r=n[s];return null==r&&(r=t),[r(e.slice(0,o+1)),o+1]}return[e[0],1]};r.addons.forwardReduceValues=e=>t.installPropArray(n),r.prototype.forwardReduceValues=l,r.prototype.valuesGraph={microGraph:s,words:t}})();export{r as ClassGraph,t as DynamicCSSStyleSheet,i as Polyclass,e as RenderArray}; +document.createElement("span"),(()=>{var e=Math.round,t=parseInt,n=(e,t,n)=>`rgb(${e},${t},${n})`;let r=function(e,t="#000000",n="#FFFFFF"){return e||(h?t:n)},s=function(e){return r(e,n(0,0,0),n(255,255,255))},l=function(e,t,n){let r=e>>t;return n?r&n:r},i=function(e,t,n,r){let s=l(e,t,n);return a(s,r)},o=(e,n)=>a(t(e),n),a=function(t,n){return e(c(t-n))+n},c=function(e){return e*u};var u,h;function d(e,l,i){return u=(h=e<0)?-1*e:e,l.length>7?function(e,r,l){let i=r.split(","),a=s(l),c=a.split(","),u=t(i[0].slice(4)),h=t(i[1]),d=t(i[2]),f=o(c[0].slice(4),u),p=o(c[1],h),g=o(c[2],d);return n(f,p,g)}(0,l,i):function(e,n,s){var l=t(n.slice(1),16),i=r(s).slice(1),o=t(i,16),a=f(l,o,16,0),c=f(l,o,8,255),u=f(l,o,0,255);return`#${(16777216+65536*a+256*c+u).toString(16).slice(1)}`}(0,l,i)}function f(e,t,n,r){let s=l(e,n,r);return i(t,n,r,s)}function p(e,t,n){var r=e<0?-1*e:e,s=Math.round,l=parseInt;if(t.length>7){var i=t.split(","),o=(n||(e<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(","),a=l(i[0].slice(4)),c=l(i[1]),u=l(i[2]);return"rgb("+(s((l(o[0].slice(4))-a)*r)+a)+","+(s((l(o[1])-c)*r)+c)+","+(s((l(o[2])-u)*r)+u)+")"}var h=(i=l(t.slice(1),16))>>16,d=i>>8&255,f=255&i;return"#"+(16777216+65536*(s((((o=l((n||(e<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-h)*r)+h)+256*(s(((o>>8&255)-d)*r)+d)+(s(((255&o)-f)*r)+f)).toString(16).slice(1)}var g="#FF343B",y="#343BFF",b="rgb(234,47,120)",v="rgb(120,99,248)";blendedcolor=d(-.8,b,v),blendedcolor2=p(-.8,b,v),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2),blendedcolor=d(-.8,g,y),blendedcolor2=p(-.8,g,y),blendedcolor!=blendedcolor2&&console.error("Fault",blendedcolor,blendedcolor2),console.log(blendedcolor,blendedcolor2)})();class e extends Array{renderAll(){for(let e of this)e.render()}}class t{styleEl=void 0;insertMethod="adopt";constructor(e){this.installAddons(e,this.constructor.addons)}installAddons(e,t){for(let n in t){(0,t[n])(e)}}addStylesheetRules(e,t){return Array.isArray(e)?this.addStylesheetRulesArray(e,t):this.addStylesheetRulesObject(e,t)}getEnsureStyleSheet(e){let t,n=e||this.styleEl;if(null!=n)return n;if("sheet"==this.insertMethod&&(n=document.createElement("style"),document.head.appendChild(n),t=n.sheet),"adopt"==this.insertMethod){const e=new CSSStyleSheet;document.adoptedStyleSheets.push(e),t=e}return null==this.styleEl&&(this.styleEl=t),t}addStylesheetRulesArray(t,n){let r=this.getEnsureStyleSheet(n),s=new e,l=r;for(let e=0;e*% #():=.@+?\/]/g;dcss=new t(this);constructor(e){this.conf=e||{},this.announce("wake"),this.translateMap={},this.reducers=[],!1!==this.conf.addons&&this.installAddons(this.getPreAddons()),this.vendorLocked=null!=e?.vendorLocked&&e.vendorLocked,this.sep=e?.sep||this.sep,this.aliasMap={},this.parentSelector=e?.parentSelector,this.processAliases(this.conf?.aliases),this.announce("ready")}announce(e){let t=new CustomEvent(`classgraph-${e}`,{detail:{entity:this}});dispatchEvent(t)}insertTranslator(e,t){this.translateMap[e]=t}getPreAddons(){return this.constructor.addons}installAddons(e){for(let t in e){(0,e[t])(this)}}generate(e){let t=Object.entries(e?.style||{});for(let[e,n]of t)this.addCamelString(e)}addCamelString(e){let t=function(e,t="-"){return e.replace(/[A-Z]+(?![a-z])|[A-Z]/g,((e,n)=>(n?t:"")+e.toLowerCase()))}(e).split("-");this.addTree(t)}addTree(e,t){let n=this.getRoot(),r=this.nodeWord(),s=[];for(let t of e){s.push(t),n[r]||(n[r]={});let e=n[r][t];null==e&&(e=n[r][t]={key:t,position:s}),n=e}return n.leaf=!0,null!=t&&(n.handler=t),n}nodeWord(){return"n"}getRoot(){return this.graph||(this.graph=this.generateRootGraph()),this.graph}generateRootGraph(){return{[this.nodeWord()]:{},meta:{key:"root",isRoot:!0},key:"root"}}processAliases(e){for(let t in e)this.addAliases(t,e[t])}getPrefixes(){let e=this.conf;return e.prefixes?e.prefixes:e.prefix?[e.prefix]:[]}isVendorPrefixMatch(e,t){t=null==t?this.getPrefixes():t;for(var n=0;n0||!1}}forwardReduceValues(e,t,n,r){let s=e,l=t;for(let e of this.reducers){l=e(s,l)}return l}minorCapture(e,t=this.sep,n=!0){let r="string"==typeof e?e.split(t):e,s=this.aliasConvert(r);s.length;let l,i=this.nodeWord(),o=this.getRoot(),a=0;if(this.isVendorPrefixMatch(s))s=s.slice(this.getPrefixes().length);else if(this.vendorLocked)return{props:void 0,values:void 0,str:e,node:l,valid:!1};for(let e of s)if(l=o[i][e],a+=1,null!=l){if(!0===l.leaf){let e=s[a],t=l[i];if(null==(t&&t[e]))break}o=l}else if(n)break;let c=s.slice(0,a),u=s.slice(a);return{props:c,values:u,str:e,node:l,valid:l&&u.length>0||!1}}objectSplitTranslateValue(e,t=this.sep,n=!0){let r=this.objectSplit(e,t,n);return this.translateValue(r)}insertLine(e,t){let n=this.objectSplit(e);return this.insertRule(n,t)}translateValue(e){let t=e.values;return t?.join(" "),this.forwardDigestKeys(e,t).join(" ")}forwardDigestKeys(e,t){let n=!0,r=t||[],s=0,l=[];for(;n;){let t=r[s],i=this.translateMap[t];i?[r,l,s]=i(e,r,l,s):l.push(this.beforeOutStack(r[s],s,e)),s+=1,(s>=r.length||s>100)&&(n=!1)}return l}keyValueFunctions=new Map;beforeOutStack(e,t,n){let r=this.getKeyFunctionMatch(e),s=this.collapseFunctions(r,n);return null==s?e:s}collapseFunctions(e,t){let n;for(var r=e.length-1;r>=0;r--){let s=e[r],l=null==n?s.remainder:n,i=s.handler;n=i&&i(l,s,r,t)||n}return n}getKeyFunctionMatch(e){let t=null!=e,n=e,r=[];for(;t;){let e=this.getKeyFunctionMatchOnce(n);e.success,t=e.match.start>-1,t&&(n=e.remainder,r.push(e))}return r}getKeyFunctionMatchOnce(e,t=".",n=":"){let r=e.lastIndexOf(t),s=e.length,l=e.slice(r+1,s).split(n),i=l[0],o=l.slice(1),a=this.keyValueFunctions.get(i),c={value:e,remainder:e.slice(0,r),handler:a,args:o,match:{start:r,end:s,name:i}};return c.success=null!=a,c}filterClasses(e,t,n=!1){let r=e.classList,s=n?{}:[],l=(e,t,n)=>s.push([n,t]);return n&&(l=(e,t,n)=>s[e]=[n,t]),r.forEach((function(e,n,r){let s=e.split("-")[0];t.indexOf(s)>-1&&l(s,e,n)})),s}filterSplit(e,t,n=!1){let r=this.filterClasses(e,t,n);if(n){let e={};for(let t in r){let n=r[t];e[t]=this.objectSplit(n[1],void 0,void 0,n[0])}return e}let s=[];return r.forEach((e=>{s.push(this.objectSplit(e))})),s}removeRule(e,t=void 0,n=!0){e?.props?.join("-");let r=this.asSelectorString(e,n);this.dcss.selectorExists(r)&&this.dcss.removeRuleBySelector(r)}insertRule(e,t=void 0,n=!0){let r=e?.props?.join("-"),s=this.asSelectorString(e,n);if(this.dcss.selectorExists(s))return this.dcss.getRuleBySelector(s);let l={[r]:this.translateValue(e)};t&&Object.assign(l,t);let i={insert:!0},o=e.node?.handler?.bind(e);if(o&&"function"==typeof o){let t=o(e);void 0!==t&&(i=t)}if(!1!==i.insert){let e=this.dcss.addStylesheetRules({[s]:l});return e.renderAll(),e}}insertReceiver(e,t){let n=this.addTree(e);return n.handler=t,n}asSelectorString(e,t=!0){let n;if(Array.isArray(e)){let t=e.join("-");n=this.escapeStr(t)}if("string"==typeof e&&(n=this.escapeStr(e)),e.props){let t=e.props.join("-");n=this.escapeStr(t)}e.str&&(n=this.escapeStr(e.str));let r=`.${n}`;return t?this.prependParent(r,e):r}prependParent(e,t){if(null!=this.parentSelector){return`${this.parentSelector}${e}`}return e}escapeStr(e){return e.replace(this.escapeRegex,"\\$&")}isProperty(e,t=this.sep){return 0==this.objectSplit(e).values.length}isDeclaration(e,t=this.sep){let n=this.objectSplit(e);return n.values.length>0&&n.props.length>0}getCSSText(){let e="",t=this.dcss.getSheet();for(let n of t.rules)e+=`${n.cssText};\n`;return e}captureChanges(e,t,n){this.discoverInsert(e,n),this.discoverRemove(t,n)}discoverInsert(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.handler;(s?s.bind(e):n.insertRule.bind(n))(e)}}discoverRemove(e,t){let n=this;for(let r of e){if(0==r.length)continue;let e=n.objectSplit(r);e.origin=t;let s=e.node?.unhandler,l=s?.bind(e);l&&l(e)}}processOnLoad(e,t=document){if(1==this.domContentLoaded)return this.process(e);(t||e).addEventListener("DOMContentLoaded",function(){this.process(e),this.domContentLoaded=!0}.bind(this))}process(e=document.body){this.getAllClasses(e,!0).forEach(((e,t)=>this.safeInsertMany(t,e)))}safeInsertMany(e,t){let n=0;for(let r of t)this.safeInsertLine(r,e,n++)}safeInsertLine(e,t,n=-1){let r=this.objectSplit(e,void 0,void 0,n);return r.valid&&(r.origin=t,this.insertRule(r)),r}getAllClasses(e=document.body,t=!1,n=!0){let r=function(e){e.classList.forEach((e=>s.add(e)))},s=new Set;return t&&(s=new Map,r=function(e){s.set(e,new Set(e.classList))}),n&&r(e),e.querySelectorAll("*").forEach(r),s}addClass(e,...t){let n=this.asNodes(e);for(let e of n)for(let n of t)for(let t of n.split(" "))e.classList.add(t)}removeClass(e,...t){let n=this.asNodes(e);for(let e of n)e.classList.remove(...t)}asNodes(e){let t=[e];return"string"==typeof e&&(t=document.querySelectorAll(e)),t}}n.addons={};class r{constructor([e]=[]){this.units=s;let t=new n(e);t.generate(e?.target),this._graph=t;(e instanceof(this?.HTMLElement||function(){})?this.hotLoad:this.loadConfig).bind(this)(e)}hotLoad(e){return console.log("Hotload"),this.loadConfig({target:e,process:!1})}loadConfig(e){if(e?.processOnLoad&&this.processOnLoad(e.processOnLoad),e?.target&&0!=e?.process&&this.process(e.target),e?.isInline){!1!==this.getParsedAttrValue("monitor",e.target)&&this._graph?.monitor&&this._graph.monitor(e.target)}this.innerProxyHandler={reference:this,get(e,t,n){let r=this.reference;if(t in r)return r[t].bind?r[t].bind(r):r[t]},apply(e,t,n){console.log("innerProxyHandler apply...",n)}},this.innerHead=function(e){},this.proxy=new Proxy(this.innerHead,this.innerProxyHandler)}get graph(){return this._graph}get sheet(){return this._graph.dcss}get config(){return this._graph.conf}getParsedAttrValue(e,t,n=void 0){const r=(t=t||this._graph.conf.target).attributes.getNamedItem(e);if(null===r)return n;let s=r.value;if(0==s.length)return n;return JSON.parse(s)}getInstance(e){void 0===e&&(e=this.target);let t=e?.dataset?.polyclassId||e;return s.get(t)}processOnLoad(){return this._graph.processOnLoad.apply(this._graph,arguments)}process(){return this._graph.process.apply(this._graph,arguments)}add(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertReceiver(e,t){return this._graph.addTree.apply(this._graph,arguments)}insertClassProps(e,t){return this._graph.insertLine.apply(this._graph,arguments)}insertRules(e){return this._graph.dcss.addStylesheetRules.apply(this._graph.dcss,arguments)}asString(){return this._graph.getCSSText()}}const s=new Map,l={safeSpace:{units:s,addons:[]},get(e,t,n){let r=this.getInstance();if(t in r){let e=r[t];return e&&e.bind?e.bind(r):e}return this.safeSpace[t]},newInstance(){return new r(Array.from(arguments))},getInstance(){return this._instance||(this._instance=this.newInstance.apply(this,arguments),this.safeSpace.instance=this._instance),this._instance},apply(e,t,n){return console.log("Polyclass apply...",e,t,n),n[0]instanceof HTMLElement?(console.log("Wrapped"),this.newInstance.apply(this,n)):this.getInstance.apply(this,n)}},i=new Proxy((function(){return l.newInstance.apply(l,arguments)}),l);const o=function(e){return h(e)||u(e)||a(e)||c(e)},a=function(e){let t=e.split("/");return 2==t.length&&(o(t[0])&&h(t[1]))},c=function(e){let t=new Set(["deg","grad","rad","turn"]),n=e.slice(parseFloat(e).toString().length,e.length);return t.has(n)},u=function(e){return e.endsWith("%")&&h(e.slice(0,e.length-1))},h=function(e){if(null==e||0==e.length)return!1;return!isNaN(Number(e))},d=function(e){let t=e.slice(4,5),n="";return t.length>0&&(n=`/${t}`),`${e[0]}(${e.slice(1,4).join(" ")}${n})`},f=function(e,t,n,r=void 0){let s=t.length,l=0,i=t.length+1,o=0,a=[];for(;lt.has(e),a=e.length,c=[],u=[],h=[];for(;ls(e,n,r),i=`polyaction_${n}`;void 0===t.dataset[i]?(t.addEventListener(n,l),t.dataset[i]=!0):console.log("Event already exists:",n)},s=function(e,t,n){let[r,...s]=n;console.log(e,t,n),console.log(r,s);let l={call(){},toggle(){console.log(s,n,t),e.currentTarget.classList.toggle(s.join("-"))},setvar(){}}[r];l&&l()};console.log("event receiver"),n.addons.eventsReceiver=function(n){e=n,e.insertReceiver(["event"],t)}}(),function(){let e;const r=function(e){const t=e.values,n=e.origin;let r=c(t,n,e),i=o(t,r,n);s(i),l(r)},s=function(e,t){return d(e,t).forEach((e=>document.head.appendChild(e)))},l=function(t,n){for(let n of Object.values(t)){let t=n.first,r=(e,t)=>t?" ":"",s=i(t.replace(/[+]/g,r));n.cleanName=s,n.definition=a(n),e.dcss.addStylesheetRules(n.definition).renderAll()}},i=function(e){return e.replace(/(^|[\s+])\S/g,(function(e){return e.toUpperCase()}))},o=function(e,t,n){t=t||c(e,n);return Object.values(t).flatMap((e=>function(e){return`family=${e.str}`}(e))).join("&")},a=function(t){let n={};const r=e.asSelectorString.bind(e);for(let e of Object.values(t.tokens)){let s={"font-weight":e.int,"font-family":`'${t.cleanName}', ${t.defaultFonts}`},l=["font",t.first];for(let t of e.keys){let e=Object.assign({},s);t.isItal&&(e["font-style"]="italic");let i=l.concat([t.token]);n[`${r(i)}, ${r(i).toLowerCase()}`]=e}}let s=r(["font",t.first]),l=r(["font"].concat(t.first.split("+"))),i=new Set([s,l,s.toLowerCase(),l.toLowerCase()]);return n[Array.from(i).join(", ")]={"font-family":`'${t.cleanName}', ${t.defaultFonts}`},n},c=function(t,n,r){let s,l=0,i={},o=/([a-zA-Z-]{0,}?)(\d+)/,a=function(t,n){return e.filterSplit(n,t,!0)}(["default"],r?.origin||n),c="sans-serif",h=a.default;if(h)if(h.index<=r.index){let e="font default-* modifier should be indexed after font";console["warn"](e),c=h.values.join(" ")}else c=h.values.join(" ");for(let e in t){let n=t[e];if(0==l){i[l]={first:n,tokens:{},defaultFonts:c},s=l,l++;continue}let[r,a]=[null,null];try{let e;[e,r,a]=n.match(o),0==r.length&&(r="r")}catch{i[l]={first:n,tokens:{}},s=l,l++;continue}let u={null:function(){return{regu:1,wasNull:1}},i:function(){return{ital:1}},r:function(){return{regu:1}}},h={int:Number(a)};if(0==h.int){console.warn("Skipping zero weighted item"),l++;continue}for(let e in r){let t=u[r[e]];Object.assign(h,t())}let d=i[s]?.tokens[a]||{};Object.assign(d,h),null==d.keys&&(d.keys=new Set),d.keys.add({isItal:h.ital,token:n}),i[s].tokens[a]=d,l++}return u(i)},u=function(e){for(let t in e){let n=e[t];0!=n.first.length&&h(n)}return e},h=function(e){let t=i(e.first),n=function(e){return 0==Object.values(e.tokens).length&&(e.tokens[400]={int:400,regu:1,keys:new Set([{isItal:void 0,token:"400"}])}),Object.values(e.tokens)}(e),r=Object.assign({},...n),s=null!=r.ital,l=[],o=new Set;s&&l.push("ital"),(s||r.regu)&&l.push("wght");for(let t in e.tokens){let n=e.tokens[t],r=n.ital?1:0,l=n.int,i=s?[r]:[];i.push(l);let a=i.join(",");if(o.add(a),null!=n.regu){let e=s?[0]:[];e.push(l);let t=e.join(",");o.add(t)}}let a=Array.from(o).sort(),c=a.join(";"),u=`${t}:${l.join(",")}@${c}`;Object.assign(e,{weights:a,formatStringParts:l,titleToken:t,str:u})},d=function(e,t="swap"){return[p("link","preconnect",{href:"https://fonts.googleapis.com"}),p("link","preconnect",{href:"https://fonts.gstatic.com",crossorigin:""}),p("link","stylesheet",{href:`https://fonts.googleapis.com/css2?${e}${null==t?"":`&display=${t}`}`})]};let f={};const p=function(e,t,n){let r={rel:t,href:e};Object.assign(r,n||{});let s=JSON.stringify,l=f[s(r)];return l||(f[s(r)]=g("link",r))},g=function(e,t){if(null==t&&"string"!=typeof e&&null==(e=(t=e).localName))throw Error("createNode requires a localName within a object definition");let n=document.createElement(e);for(let e in t)n.setAttribute(e,t[e]);return n};t.addons.fontPackReceiver=function(t){e=t,e.insertReceiver(["font","pack"],r)},n.prototype.generateGoogleLinks=d,n.prototype.installGoogleLinks=s}(),function(){let e;const t=function(e,t,n,r){return t.value.slice(0,t.match.start),t.args.length>0?t.args[0]:"green"},r=function(e,t,n,r){console.log("raise hook",t,r);let s=t.value.slice(0,t.match.start);console.log(s)};n.addons.functionsReceiver=function(n){e=n,e.keyValueFunctions.set("forceGreen",t),e.keyValueFunctions.set("force",t),e.keyValueFunctions.set("raise",r)}}(),function(){let e;const t=function(t){var n;let s=`family=${`Material+Symbols+${(n=t.values,n.map((function(e){return e.charAt(0).toUpperCase()+e.substring(1,e.length)}))).join("+")}`}:${l({opsz:"20..48",wght:"100..700",FILL:"0..1",GRAD:"-50..200"})}`,a=[...t.values,"icon"];e.insertReceiver(a,o),i.graph.installGoogleLinks(s,null),r(t,fontSettings)},r=function(t,n){let r=t.values[0],l={},i={"font-variation-settings":`${s(n)}`,"font-size":"inherit"};l[`.material-symbols-${r}`]=i,e.dcss.addStylesheetRules(l).renderAll()},s=function(e){let t="",n=Object.keys(e);for(var r=0;r{let e;const t=function(e){let t=function(e){"class"==e.attributeName&&r(e)},n=new MutationObserver((function(e){e.forEach(t)}));return n.observe(e,{attributes:!0,subtree:!0,attributeFilter:["class"],attributeOldValue:!0}),n},r=function(t){let n=t.target.classList.value,r=t.oldValue,l=n.split(/(?!\(.*)\s(?![^(]*?\))/g),i=null==r?[]:r.split(" ").map((e=>e.trim())),o=i?s(l,i):l;console.log("new",o),e.captureChanges(o,i,t.target)},s=function(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n};n.addons.monitorClasses=function(t){e=t},n.prototype.monitor=function(e=document.body){return t(e)}})(),(()=>{class e extends Map{wordCounter=1;getKey(e){let n=t.get(e);return null==n&&(t.set(e,this.wordCounter),n=this.wordCounter,this.wordCounter++),n}stringToBits(e,t="-"){let n=e.split(t),r=[];return n.forEach(((e,t,n)=>r.push(this.getKey(e)))),r}stringToNest(e,t={}){let n=e.split("-");var r=t;let s=r,l=n.length;return n.forEach(((e,t,n)=>{let s=this.getKey(e),i=t==l-1;null==r[s]?r[s]=r=i?null:{}:r=r[s]})),s}installPropArray(e){e.forEach(((e,t,n)=>{this.stringToNest(e,r)}))}insertBitKey(e,t=r){return this.stringToNest(e,t)}wordsToOrderedArray(){let e=new Array(this.size);return this.forEach(((t,n,r)=>e[t]=n)),e}wordsToArrayString(e=0,t=!1){return t?this.wordsToOrderedArray().join(" "):JSON.stringify(this.wordsToOrderedArray(),null,e)}wordsToObjectString(e=0,t=!1){if(!t)return JSON.stringify(Object.fromEntries(this),null,e);let n="";return this.forEach(((e,t,r)=>n+=[t,e].join(""))),n}graphToArrayListString(e=r,t=0,n=0){return JSON.stringify(this.graphToArrayListRecurse(e,t,n))}graphToArrayListRecurse(e=r,t=0,n=null){let s=[],l=Object.entries(e);for(let e of l){let r=e[1];s.push([parseInt(e[0]),null==r?n:this.graphToArrayListRecurse(r,t,n)])}return s}graphToObjectString(e=0){let t={};for(let e in r)t[parseInt(e)]=r[e];return JSON.stringify(t,null,e)}}const t=new e,r={},s=["all-petite-caps","all-scroll","all-small-caps","allow-end","alternate-reverse","arabic-indic","auto-fill","auto-fit","avoid-column","avoid-page","avoid-region","balance-all","bidi-override","border-box","break-all","break-spaces","break-word","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","close-quote","closest-corner","closest-side","col-resize","color-burn","color-dodge","column-reverse","common-ligatures","content-box","context-menu","crisp-edges","decimal-leading-zero","diagonal-fractions","disclosure-closed","disclosure-open","discretionary-ligatures","double-circle","e-resize","each-line","ease-in","ease-in-out","ease-out","ethiopic-numeric","ew-resize","extra-condensed","extra-expanded","farthest-corner","farthest-side","fill-box","flex-end","flex-start","flow-root","force-end","from-image","full-size-kana","full-width","hard-light","high-quality","hiragana-iroha","historical-forms","historical-ligatures","horizontal-tb","inline-block","inline-flex","inline-grid","inline-table","inter-character","inter-word","isolate-override","japanese-formal","japanese-informal","jump-both","jump-end","jump-none","jump-start","justify-all","katakana-iroha","keep-all","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","line-through","lining-nums","list-item","literal-punctuation","lower-alpha","lower-armenian","lower-greek","lower-latin","lower-roman","margin-box","match-parent","match-source","max-content","message-box","min-content","n-resize","ne-resize","nesw-resize","no-clip","no-close-quote","no-common-ligatures","no-contextual","no-discretionary-ligatures","no-drop","no-historical-ligatures","no-open-quote","no-punctuation","no-repeat","not-allowed","ns-resize","nw-resize","nwse-resize","oldstyle-nums","open-quote","padding-box","petite-caps","pre-line","pre-wrap","proportional-nums","proportional-width","repeat-x","repeat-y","row-resize","row-reverse","ruby-base","ruby-base-container","ruby-text","ruby-text-container","run-in","s-resize","sans-serif","scale-down","scroll-position","se-resize","self-end","self-start","semi-condensed","semi-expanded","sideways-lr","sideways-right","sideways-rl","simp-chinese-formal","simp-chinese-informal","slashed-zero","small-caps","small-caption","soft-light","space-around","space-between","space-evenly","spell-out","stacked-fractions","status-bar","step-end","step-start","stroke-box","sw-resize","system-ui","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tabular-nums","titling-caps","trad-chinese-formal","trad-chinese-informal","ui-monospace","ui-rounded","ui-sans-serif","ui-serif","ultra-condensed","ultra-expanded","upper-alpha","upper-armenian","upper-latin","upper-roman","vertical-lr","vertical-rl","vertical-text","view-box","w-resize","wrap-reverse","x-fast","x-high","x-loud","x-low","x-slow","x-soft","x-strong","x-weak","zoom-in","zoom-out"];const l=function(e,t,n,r){const s=n||{row:{reverse:e=>e.join("-")}};let l=t.length,o=0,a=t.length+1,c=0,u=[];for(;oe.join("-");let n=s[r];return null==n&&(n=t),[n(e.slice(0,o+1)),o+1]}return[e[0],1]};n.addons.forwardReduceValues=function(e){return e.reducers.push((function(e,n){return l(e,n,r,t)})),t.installPropArray(s)},n.prototype.valuesGraph={microGraph:r,words:t}})(),function(){let e;const t=function(e,t,n,r){let s=t.slice(r).slice(1),l=`var(--${s.join("-")})`;return n.push(l),[[],n,r+s.length]};n.addons.varTranslateReceiver=function(n){e=n,e.insertTranslator("var",t)}}(),function(){let e,t;const r=function(n,r=":root"){if(console.log("Hook",n),null==t){let s={};for(let e in n){let t=`--${e}`,r=n[e];s[t]=r}let l=e.dcss.addStylesheetRules({[r]:s});l.renderAll(),t=l[0],e.varsRoot=t}else for(let e in n){let r=`--${e}`,s=n[e];t.sheetRule.style.setProperty(r,s)}};n.addons.varsReceiver=function(n){e=n,e.vars=r.bind(e),e.varsRoot=t}}();export{n as ClassGraph,t as DynamicCSSStyleSheet,i as Polyclass,e as RenderArray}; diff --git a/docs/Polyclass.wav b/docs/Polyclass.wav new file mode 100755 index 0000000..6ee25a7 Binary files /dev/null and b/docs/Polyclass.wav differ diff --git a/docs/contents.md b/docs/contents.md index 0fce384..1babfe2 100755 --- a/docs/contents.md +++ b/docs/contents.md @@ -10,8 +10,9 @@ This is the intro content, overridden during compilation + [Css Var](css-var.md) + [Declaration Modifiers](declaration-modifiers.md) + [Events](events.md) ++ [Extended Colors](extended-colors.md) + [Font Pack](font-pack.md) -+ [How Does It Work](how-does-it-work.md) ++ [Icons](icons.md) + [Inserting Rules](inserting-rules.md) + [Options](options.md) + [Running Polyclass](running-polyclass.md) @@ -19,51 +20,63 @@ This is the intro content, overridden during compilation + [Vars Object](vars-object.md) + [Vendor Prefix](vendor-prefix.md) + [Working With](working-with.md) -+ [Class Count](dev\class-count.md) -+ [Extracting Css Values](dev\extracting-css-values.md) -+ [Understanding Tokens](dev\understanding-tokens.md) -+ [Value Reducton](dev\value-reducton.md) -+ [Contents](templates\markdown\contents.md) -+ [Actions And Events](wishlist\actions-and-events.md) -+ [Active Switch](wishlist\active-switch.md) -+ [Addon Receiver](wishlist\addon-receiver.md) -+ [Auto Docs](wishlist\auto-docs.md) -+ [Baking](wishlist\baking.md) -+ [Better Fonting](wishlist\better-fonting.md) -+ [Better String Detection](wishlist\better-string-detection.md) -+ [Clean Function](wishlist\clean-function.md) -+ [Contents](wishlist\contents.md) -+ [Decouple Graph](wishlist\decouple-graph.md) -+ [Definition Merge](wishlist\definition-merge.md) -+ [Definition Yield](wishlist\definition-yield.md) -+ [Dont Split](wishlist\dont-split.md) -+ [Dynamic Css Imports](wishlist\dynamic-css-imports.md) -+ [Feed Forward Keys](wishlist\feed-forward-keys.md) -+ [Font Here](wishlist\font-here.md) -+ [Grid](wishlist\grid.md) -+ [Image](wishlist\image.md) -+ [Magic At Rules](wishlist\magic-at-rules.md) -+ [Multi Graph](wishlist\multi-graph.md) -+ [Node Type Assignment](wishlist\node-type-assignment.md) -+ [Parent Selector](wishlist\parent-selector.md) -+ [Pragmatic Colors](wishlist\pragmatic-colors.md) -+ [Readme](wishlist\readme.md) -+ [Replacement Editing](wishlist\replacement-editing.md) -+ [Reshade Function](wishlist\reshade-function.md) -+ [Ruleproxy](wishlist\ruleproxy.md) -+ [Sibling Mutators](wishlist\sibling-mutators.md) -+ [Sub Var](wishlist\sub-var.md) -+ [Template Objects](wishlist\template-objects.md) -+ [Through Function](wishlist\through-function.md) -+ [Two Way Bnding](wishlist\two-way-bnding.md) -+ [Type Tests](wishlist\type-tests.md) -+ [Value Remap](wishlist\value-remap.md) -+ [Var Accessor](wishlist\var-accessor.md) -+ [Vendor Prefix](wishlist\vendor-prefix.md) ++ [Class Count](dev/class-count.md) ++ [Extracting Css Values](dev/extracting-css-values.md) ++ [How Does It Work](dev/how-does-it-work.md) ++ [Understanding Tokens](dev/understanding-tokens.md) ++ [Value Reducton](dev/value-reducton.md) ++ [Contents](templates/markdown/contents.md) ++ [Actions And Events](wishlist/actions-and-events.md) ++ [Active Switch](wishlist/active-switch.md) ++ [Addon Receiver](wishlist/addon-receiver.md) ++ [Auto Docs](wishlist/auto-docs.md) ++ [Baking](wishlist/baking.md) ++ [Better Colors](wishlist/better-colors.md) ++ [Better Fonting](wishlist/better-fonting.md) ++ [Better String Detection](wishlist/better-string-detection.md) ++ [Clean Function](wishlist/clean-function.md) ++ [Contents](wishlist/contents.md) ++ [Decouple Graph](wishlist/decouple-graph.md) ++ [Definition Merge](wishlist/definition-merge.md) ++ [Definition Yield](wishlist/definition-yield.md) ++ [Descendancy Operator](wishlist/descendancy-operator.md) ++ [Dont Split](wishlist/dont-split.md) ++ [Dynamic Css Imports](wishlist/dynamic-css-imports.md) ++ [Feed Forward Keys](wishlist/feed-forward-keys.md) ++ [Font Here](wishlist/font-here.md) ++ [Grid](wishlist/grid.md) ++ [Image](wishlist/image.md) ++ [Library Flavouring](wishlist/library-flavouring.md) ++ [Magic At Rules](wishlist/magic-at-rules.md) ++ [Multi Graph](wishlist/multi-graph.md) ++ [Node Type Assignment](wishlist/node-type-assignment.md) ++ [Parent Selector](wishlist/parent-selector.md) ++ [Pragmatic Colors](wishlist/pragmatic-colors.md) ++ [Readme](wishlist/readme.md) ++ [Replacement Editing](wishlist/replacement-editing.md) ++ [Reshade Function](wishlist/reshade-function.md) ++ [Ruleproxy](wishlist/ruleproxy.md) ++ [Sibling Mutators](wishlist/sibling-mutators.md) ++ [Sibling Operator](wishlist/sibling-operator.md) ++ [Style Block](wishlist/style-block.md) ++ [Sub Var](wishlist/sub-var.md) ++ [Template Objects](wishlist/template-objects.md) ++ [Through Function](wishlist/through-function.md) ++ [Two Way Bnding](wishlist/two-way-bnding.md) ++ [Type Tests](wishlist/type-tests.md) ++ [Value Remap](wishlist/value-remap.md) ++ [Var Accessor](wishlist/var-accessor.md) ++ [Vendor Prefix](wishlist/vendor-prefix.md) ++ [Badges](_bits/badges.md) ++ [Install In A Hurry](_bits/install-in-a-hurry.md) ++ [Primary Example](_bits/primary-example.md) ++ [Readme](_bits/readme.md) ++ [Readme_Original](_bits/readme_original.md) ++ [Secondary Example](_bits/secondary-example.md) --- -End 2024-06-15 04:42:50.066296 +End 2024-06-28 22:58:02.815657 \ No newline at end of file diff --git a/docs/todo+wishlist.md b/docs/todo+wishlist.md index 2d8ee9a..056baea 100755 --- a/docs/todo+wishlist.md +++ b/docs/todo+wishlist.md @@ -1,671 +1,15 @@ -# Wishlist +# Notes -Items I want in the lib - some in progress ++ https://developer.mozilla.org/en-US/docs/Web/CSS/rem + Can be implemented like a color function, but with 2 bits. ++ https://developer.mozilla.org/en-US/docs/Web/CSS/basic-shape/polygon + + similar to a forward key digest forever (like `--var`) + + comma pairs for properties ++ https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/device-cmyk + + Nearly already possible, -+ vars() box. -+ better -var-var-var detector -+ better fonting - + alt vendors - + Better string detection - + ensure two-way binding on `font-pack` and and `font-*` definition classes -+ color js swatching - + With 'theme' packs using color math -+ dpath writeup -+ dcss writeup - -+ Auto Documentation -+ vendor prefix -+ Multi-graph -+ decoupled 'auto' graph -+ Easier cooking - + convert the 'finished' stylesheet to a file. -+ Template objects -+ actions and events -+ pragmmatic color assignment - + Invert property -+ node type assignment -+ parent selector -+ Baking -+ Forward Feed Keys -+ a `clean()` function -+ Dynamic Css Import -+ _though_ key function -+ don't split - ---- - -## sibling mutators - -if a class is assigned with a sibling class,mutate the outbound declaration: - -primary: - - font-pack-robot-100-300-400 - -sibling: - - font-family-default-sans-serif - font-default-sans-serif - default-sans-serif - -Result: - - font-family-default-sans-serif font-pack-robot-100-300-400 - font-pack-robot-100-300-400 default-sans-serif - - font-here-roboto default-sans-serif - - -## value remap - -as a value is tested, asset a simple map replacement. - -The _unpack_ can be other objects. - - - color-red // classical - color-var-primary // vars() - color-rebecca // mapped - #336699 - color-other // re-mapped - rebecca ... - color-follow // another re-mapped - ... - we can return additional property values. - -To allow _remapping_ of props - - ---- - -Better addon receiver. - -+ Plug in before or after instansiation -+ target Polyclass, classgraph, or the other one - - ----- - -# .reshade- - -A first implementation of "functions" on a value. - - color-red.reshade+1 - color-red.reshade-10 - -Allowing - -## display: inline flow-root;display: inline flow-root;the reshade relative to a color stepping function (quantized step) - -# .revalue - -Convert a value to another value through a pre-map - -globals - - { - red: orange - } - -property - - { - color: { - red: #880000 - } - - background: { - red: linear-gradient(red, #880000) - } - } - -entity - - { - p: { - color: { - red: 'color.red.reshade+2' - } - } - - strong: { - color: { - red: 'p.color.red.reshade-2' - } - } - } - -## Image - -With functional values, we can implement more advanced capture and replace methods. The `*-img*` property can be configured to redirect a _short name_ to a static path location: - - polyclass.staticPath = 'https://imghost/foo/bar?name=' - -Usage rebinds the inbound path: - -
- -result - - { - background-image: url('https://imghost/foo/bar?name=apples'); - } - - -## sub-var: - - color-var-apples - - // no - color-var-top-next - - // yes - color-var-top.next - - -## var accessor $ - -Currently to assign a var: - - [prop]-var-[name] - color-var-apples - -with a short: - - color-v-apples - -the accessor uses a special syntax: - - $color-apples - -or maybe: - - color-$apples - color-$top.next - -## Magic @rules - -Define any @property : value, where the property can be a "magic" rule to unpack the inner rules and apply them to the outer declaration. This allows multi-decarlation repacking. - -## font-here-* - -Combine `font-pack-*` and `font-*` into a single statement, binding both classes into a merged object - or as one token - - font-here-roboto-400 - - - -## polyclass active switch - -Enable polyclass in the view without JS, using an auto-switch in the -body or HTML. Additional config may be applied through data-attributes. - -```html - - - - - - - - -``` - -Alterntive configs: - -```html - - -``` - - -## RuleProxy - -A proxy object to edit a single rule in the view. This can change aspects -of a key, value as a class. This change will bubble to dcss - - rule = pc.addRule('.foo.bar', {color: 'red', margin: '4em 1em 2em 3em'}) - - rule[margin][0].setValue('5em') - - -## Replacement editing - -Attempt to _replace_ a similar class with a new one, this can be bubbled to the dcss, allowing clearner editing. This is useful if the view cycles -through many styles, leaving a tail of unused styles. - - pc(node).change('margin-1.4em-1em', 'margin-1.5em-1em') - -## better fonting - - -### Alt Vendors - -Currently only google fonts work, but other vendors can be applied with work. - -### Better string detection - -The string parser is naive and will likely falter on minor edge-cases. -Rewrite this to a 'mini-graph' of sorts; allowing better forward key detection when parsing a string. - -This rewrite should allow better parsing of translatable values when parsing values within a reciever. - -### Two way binding - -In the current form, the `font-pack` does not pick-up the usage of a `font-[name]` if the named font is a node _within_ the pack node. - -This is probably due to the write of the font-pack occuring _after_ the `font-[name]` was defined. As such, the `font-[name]` is unprepared somehow. - - -```html - -
- works -
- -``` - - -```html - -
- Does not work -
- -``` - -## decoupled auto graph - -Currently the first graph applied is the 'auto graph', read from a primary node (the `body`). All available attributes are scanned as the _potential keys_ to activate a write. - -Instead, apply the graph as an 'addon' - opting for more config choices. - -## Auto Documentation - -With all the content within one sheet, The developer may choose to _export_ the -source and documentation. This allows CSS class based research - - vendor-background-color-var-primary - Aliases: vn-bg-c-v-pr - - Apply the primary background color `#111111` to an entity - -Currently the sheet can be generated with: - -```js -cg.getCSSText() -``` - -## Vendor prefix - -Install the entire class graph beneath a vendor prefix. Therefore all -applies class names must start with `vendor`: - - `vendor-margin-1em` - -This is more useful with a better unique graphing method - -## Mutli Graph - -Multiple instances of the class graph should be able to run on the same view, each with unique rules and optional prefix. - -## template objects - -Potentially or somehow leverage additional classes, styles and definitions from 'templates'. One option is html5 `