@public-ui/components
Version:
Contains all web components that belong to KoliBri - The accessible HTML-Standard.
1,323 lines (1,185 loc) • 68.5 kB
JavaScript
/*!
* KoliBri - The accessible HTML-Standard
*/
'use strict';
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var loglevel$1 = {exports: {}};
/*
* loglevel - https://github.com/pimterry/loglevel
*
* Copyright (c) 2013 Tim Perry
* Licensed under the MIT license.
*/
var loglevel = loglevel$1.exports;
var hasRequiredLoglevel;
function requireLoglevel () {
if (hasRequiredLoglevel) return loglevel$1.exports;
hasRequiredLoglevel = 1;
(function (module) {
(function (root, definition) {
if (module.exports) {
module.exports = definition();
} else {
root.log = definition();
}
}(loglevel, function () {
// Slightly dubious tricks to cut down minimized file size
var noop = function() {};
var undefinedType = "undefined";
var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
/Trident\/|MSIE /.test(window.navigator.userAgent)
);
var logMethods = [
"trace",
"debug",
"info",
"warn",
"error"
];
var _loggersByName = {};
var defaultLogger = null;
// Cross-browser bind equivalent that works at least back to IE6
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function() {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
}
// Trace() doesn't print the message in IE, so for that case we need to wrap it
function traceForIE() {
if (console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
// In old IE, native console methods themselves don't have apply().
Function.prototype.apply.apply(console.log, [console, arguments]);
}
}
if (console.trace) console.trace();
}
// Build the best logging method possible for this env
// Wherever possible we want to bind, not wrap, to preserve stack traces
function realMethod(methodName) {
if (methodName === 'debug') {
methodName = 'log';
}
if (typeof console === undefinedType) {
return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
} else if (methodName === 'trace' && isIE) {
return traceForIE;
} else if (console[methodName] !== undefined) {
return bindMethod(console, methodName);
} else if (console.log !== undefined) {
return bindMethod(console, 'log');
} else {
return noop;
}
}
// These private functions always need `this` to be set properly
function replaceLoggingMethods() {
/*jshint validthis:true */
var level = this.getLevel();
// Replace the actual methods.
for (var i = 0; i < logMethods.length; i++) {
var methodName = logMethods[i];
this[methodName] = (i < level) ?
noop :
this.methodFactory(methodName, level, this.name);
}
// Define log.log as an alias for log.debug
this.log = this.debug;
// Return any important warnings.
if (typeof console === undefinedType && level < this.levels.SILENT) {
return "No console available for logging";
}
}
// In old IE versions, the console isn't present until you first open it.
// We build realMethod() replacements here that regenerate logging methods
function enableLoggingWhenConsoleArrives(methodName) {
return function () {
if (typeof console !== undefinedType) {
replaceLoggingMethods.call(this);
this[methodName].apply(this, arguments);
}
};
}
// By default, we use closely bound real methods wherever possible, and
// otherwise we wait for a console to appear, and then try again.
function defaultMethodFactory(methodName, _level, _loggerName) {
/*jshint validthis:true */
return realMethod(methodName) ||
enableLoggingWhenConsoleArrives.apply(this, arguments);
}
function Logger(name, factory) {
// Private instance variables.
var self = this;
/**
* The level inherited from a parent logger (or a global default). We
* cache this here rather than delegating to the parent so that it stays
* in sync with the actual logging methods that we have installed (the
* parent could change levels but we might not have rebuilt the loggers
* in this child yet).
* @type {number}
*/
var inheritedLevel;
/**
* The default level for this logger, if any. If set, this overrides
* `inheritedLevel`.
* @type {number|null}
*/
var defaultLevel;
/**
* A user-specific level for this logger. If set, this overrides
* `defaultLevel`.
* @type {number|null}
*/
var userLevel;
var storageKey = "loglevel";
if (typeof name === "string") {
storageKey += ":" + name;
} else if (typeof name === "symbol") {
storageKey = undefined;
}
function persistLevelIfPossible(levelNum) {
var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
if (typeof window === undefinedType || !storageKey) return;
// Use localStorage if available
try {
window.localStorage[storageKey] = levelName;
return;
} catch (ignore) {}
// Use session cookie as fallback
try {
window.document.cookie =
encodeURIComponent(storageKey) + "=" + levelName + ";";
} catch (ignore) {}
}
function getPersistedLevel() {
var storedLevel;
if (typeof window === undefinedType || !storageKey) return;
try {
storedLevel = window.localStorage[storageKey];
} catch (ignore) {}
// Fallback to cookies if local storage gives us nothing
if (typeof storedLevel === undefinedType) {
try {
var cookie = window.document.cookie;
var cookieName = encodeURIComponent(storageKey);
var location = cookie.indexOf(cookieName + "=");
if (location !== -1) {
storedLevel = /^([^;]+)/.exec(
cookie.slice(location + cookieName.length + 1)
)[1];
}
} catch (ignore) {}
}
// If the stored level is not valid, treat it as if nothing was stored.
if (self.levels[storedLevel] === undefined) {
storedLevel = undefined;
}
return storedLevel;
}
function clearPersistedLevel() {
if (typeof window === undefinedType || !storageKey) return;
// Use localStorage if available
try {
window.localStorage.removeItem(storageKey);
} catch (ignore) {}
// Use session cookie as fallback
try {
window.document.cookie =
encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
} catch (ignore) {}
}
function normalizeLevel(input) {
var level = input;
if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
level = self.levels[level.toUpperCase()];
}
if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
return level;
} else {
throw new TypeError("log.setLevel() called with invalid level: " + input);
}
}
/*
*
* Public logger API - see https://github.com/pimterry/loglevel for details
*
*/
self.name = name;
self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
"ERROR": 4, "SILENT": 5};
self.methodFactory = factory || defaultMethodFactory;
self.getLevel = function () {
if (userLevel != null) {
return userLevel;
} else if (defaultLevel != null) {
return defaultLevel;
} else {
return inheritedLevel;
}
};
self.setLevel = function (level, persist) {
userLevel = normalizeLevel(level);
if (persist !== false) { // defaults to true
persistLevelIfPossible(userLevel);
}
// NOTE: in v2, this should call rebuild(), which updates children.
return replaceLoggingMethods.call(self);
};
self.setDefaultLevel = function (level) {
defaultLevel = normalizeLevel(level);
if (!getPersistedLevel()) {
self.setLevel(level, false);
}
};
self.resetLevel = function () {
userLevel = null;
clearPersistedLevel();
replaceLoggingMethods.call(self);
};
self.enableAll = function(persist) {
self.setLevel(self.levels.TRACE, persist);
};
self.disableAll = function(persist) {
self.setLevel(self.levels.SILENT, persist);
};
self.rebuild = function () {
if (defaultLogger !== self) {
inheritedLevel = normalizeLevel(defaultLogger.getLevel());
}
replaceLoggingMethods.call(self);
if (defaultLogger === self) {
for (var childName in _loggersByName) {
_loggersByName[childName].rebuild();
}
}
};
// Initialize all the internal levels.
inheritedLevel = normalizeLevel(
defaultLogger ? defaultLogger.getLevel() : "WARN"
);
var initialLevel = getPersistedLevel();
if (initialLevel != null) {
userLevel = normalizeLevel(initialLevel);
}
replaceLoggingMethods.call(self);
}
/*
*
* Top-level API
*
*/
defaultLogger = new Logger();
defaultLogger.getLogger = function getLogger(name) {
if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
throw new TypeError("You must supply a name when creating a logger.");
}
var logger = _loggersByName[name];
if (!logger) {
logger = _loggersByName[name] = new Logger(
name,
defaultLogger.methodFactory
);
}
return logger;
};
// Grab the current global log variable in case of overwrite
var _log = (typeof window !== undefinedType) ? window.log : undefined;
defaultLogger.noConflict = function() {
if (typeof window !== undefinedType &&
window.log === defaultLogger) {
window.log = _log;
}
return defaultLogger;
};
defaultLogger.getLoggers = function getLoggers() {
return _loggersByName;
};
// ES6 default export, for compatibility
defaultLogger['default'] = defaultLogger;
return defaultLogger;
}));
} (loglevel$1));
return loglevel$1.exports;
}
var loglevelExports = requireLoglevel();
var h = /*@__PURE__*/getDefaultExportFromCjs(loglevelExports);
const j=(t,e)=>s=>s(t,e),F=(t,e)=>s=>s(t,e,{append:false}),Y=()=>{const t=typeof process<"u"&&process.env?process.env:{},e=t.NODE_ENV==="test",s="VITEST"in t,a="JEST_WORKER_ID"in t,o="PLAYWRIGHT_TEST_BASE_URL"in t,r=t.CI==="true",i=t.TEST==="true"||t.IS_TEST==="true",c=typeof navigator<"u"&&navigator.webdriver===true,u=typeof navigator<"u"&&/playwright|puppeteer|webdriver|selenium|testcafe/i.test(navigator.userAgent);return e||s||a||o||r||i||c||u},n$1={A11yUi:{CSS_STYLE_CACHE:new Map,IS_TEST_ENVIRONMENT:Y(),PERFORMANCE_MEASURES:new Map,STYLING_TASK_QUEUE:new Map,THEMES:new Map,showAverageTimes:()=>{const t={};for(const[s,a]of n$1.A11yUi.PERFORMANCE_MEASURES.entries())t[s]=[a.totalTime/a.count,a.count];const e=Object.entries(t).sort((s,a)=>a[1][0]-s[1][0]);return console.table(Object.fromEntries(e.map(([s,[a,o]])=>[s,{"avg (ms)":parseFloat(a.toFixed(2)),count:o}]))),t}}};let T=true,f$1=false;const k=/^[a-z][a-z0-9]{1,}(-[a-z0-9]+)?$/,G=t=>typeof t=="string"&&k.test(t),A=t=>{if(!G(t))throw new Error(`[Theming] The theme identifier "${typeof t=="string"?t:""}" (Type: ${typeof t}) is not valid. Please use only follow this pattern: /^[a-z][a-z0-9]{1,}(-[a-z0-9]+)?$/`)},b=t=>t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s*([{},;])\s*/g,"$1").replace(/:\s+/g,":").replace(/\s+/g," ").replace(/;\}/g,"}").trim(),x=(t,e,s,a)=>g(t,e,s,a),g=(t,e,s,a)=>{a=a??{},a.append=a.append??false,A(t),T&&!f$1&&(f$1=true,h.warn(`[Theming] The theme process is locked. This means that the theme "${t}" should not be patched.
import { register } from 'adopted-style-sheets';
import { defineCustomElements } from '...';
import { THEME } from '...';
register(THEME, defineCustomElements)
.then(() => {
// run your app or website
})
.catch(console.warn);`));let o=n$1.A11yUi.THEMES.get(t);if(o||(o=new Map,n$1.A11yUi.THEMES.set(t,o)),a.append&&o.has(e)){const r=o.get(e);o.set(e,b(`${r}${s}`));}else o.set(e,b(s));},K=(t,e,s,a)=>E(t,e,s,a),E=(t,e,s,a)=>(A(t),typeof e=="object"&&e!==null&&Object.getOwnPropertyNames(e).forEach(o=>{const r=e[o],i=o.toLowerCase(),c=typeof a?.transformTagName=="function"&&!["GLOBAL","PROPERTIES"].includes(o)?a.transformTagName(i):o;typeof r=="string"&&r.length>0&&g(t,c.toUpperCase(),r,s);}),t),U=t=>{if(t instanceof HTMLElement){if(typeof t.dataset.theme=="string")return t;{let e=t.parentNode;for(;e instanceof ShadowRoot;)e=e.host;return U(e)}}else return null},C=(t={})=>t.themeEncroachCss==="false"||t.themeReset==="true"?false:{mode:t.themeEncroachCssMode==="after"||t.themeEncroachCssMode==="before"?t.themeEncroachCssMode:"before"},d=()=>typeof n$1.A11yUi.Theme=="object"&&n$1.A11yUi.Theme!==null&&typeof n$1.A11yUi.Theme.cache=="boolean"&&typeof n$1.A11yUi.Theme.encroachCss=="object"&&n$1.A11yUi.Theme.encroachCss!==null&&typeof n$1.A11yUi.Theme.encroachCss.mode=="string"&&typeof n$1.A11yUi.Theme.name=="string",B=()=>!(typeof n$1.A11yUi.Theme=="object"&&n$1.A11yUi.Theme!==null)||n$1.A11yUi.Theme.name!=="default",w=t=>{if(d())return n$1.A11yUi.Theme;{const e={cache:true,encroachCss:C(),loglevel:"silent",mode:"csr",name:null},s=U(t);return s instanceof HTMLElement&&(e.cache=s.dataset.themeCache!=="false",e.encroachCss=C(s.dataset),e.loglevel=s.dataset.themeLoglevel==="debug"?s.dataset.themeLoglevel:"silent",e.mode=s.dataset.themeMode==="ssr"?s.dataset.themeMode:"csr",e.name=s.dataset.theme||null),e}},z=()=>d()?n$1.A11yUi.Theme.name:null,V=(t,e)=>({cache:e.cache!==false,detect:e.detect==="auto"?"auto":"fixed",encroachCss:e.encroachCss===false?false:typeof e.encroachCss=="object"&&e.encroachCss!=null&&(e.encroachCss.mode==="after"||e.encroachCss.mode==="before")?e.encroachCss:{mode:"before"},loglevel:e.loglevel==="debug"?e.loglevel:"silent",mode:e.mode==="ssr"?e.mode:"csr",name:typeof e.name=="string"?e.name:t}),W=(t,e)=>{d()===false&&B()&&typeof e=="object"&&e!==null&&(e=V(t,e),e.detect==="fixed"?(e.name===null&&typeof t=="string"&&(e.name=t),t===e.name&&(n$1.A11yUi.Theme=e,h.info(`[Theming] Theme "${t}" was set as default theme.`))):f$1||(f$1=true,h.warn("[Theming] The presetting of theme options is only relevant by using 'fixed' detection mode.")));};let M=false;const Z=(t,e,s={})=>{M||(M=true,T=false,typeof window<"u"&&(window.A11yUi=n$1.A11yUi)),typeof t=="function"?t=new Set([t]):Array.isArray(t)&&(t=new Set(t)),t instanceof Set&&t.forEach(o=>{typeof o=="function"&&o.length===1?W(o((r,i,c)=>E(r,i,c,s)),{cache:s.theme?.cache,detect:s.theme?.detect,encroachCss:s.theme?.encroachCss,mode:s.theme?.mode,name:s.theme?.name}):h.error("[Theming] An attempt was made to load an incompatible theme.");}),T=true,typeof e=="function"?e=new Set([e]):Array.isArray(e)&&(e=new Set(e));const a=[];return e.forEach(o=>{const r=o();r instanceof Promise&&a.push(r);}),Promise.all(a)};const v=new Set,N=new Map,ee=/--[^;]+/g,te=/:/,se=typeof MutationObserver<"u";let L=25,R=()=>{L=Math.min(25+Math.log2(n$1.A11yUi.STYLING_TASK_QUEUE.size+1)*20,250);};const ae=(t,e)=>{let s=e.match(ee);if(Array.isArray(s)){s=s.filter(o=>te.test(o));const a=document.createElement("style");a.innerHTML=`.${t} {${s.join(";")}}`,document.querySelector("head")?.appendChild(a);}v.add(t);},y=(t,e)=>{const s=n$1.A11yUi.THEMES.get(t);if(s instanceof Map){const a=s.get(e);if(a!==void 0)return a}return ""},oe=t=>{const e=t.firstChild;if(!(!(e instanceof HTMLStyleElement)||e.dataset.themingFallback!==void 0))for(const s of Array.from(t.childNodes))if(s instanceof HTMLStyleElement&&s.tagName==="STYLE"&&s.dataset.themingFallback===void 0)t.removeChild(s);else break},ne=(t,e)=>{try{if(n$1.A11yUi.Theme?.mode==="ssr")throw new Error("SSR");const s=e.filter(a=>typeof a=="string"&&a.length>0).map(a=>{let o=N.get(a);return o||(o=new CSSStyleSheet,o.replaceSync(a),N.set(a,o)),o});t.adoptedStyleSheets=s;}catch{for(let a=e.length-1;a>=0;a--){const o=e[a];if(typeof o!="string"||o.length===0)continue;const r=e.length-1-a,i=document.createElement("style");switch(i.dataset.themingFallback="",r){case 4:i.dataset.themingBaseA11y="";break;case 3:i.dataset.themingBaseGlobal="";break;case 2:i.dataset.themingBaseComponent="";break;case 1:i.dataset.themingCustomGlobal="";break;case 0:i.dataset.themingCustomComponent="";break;default:i.dataset.themingUnknown="";break}i.innerHTML=o,t.insertBefore(i,t.firstChild);}}},re=(t,e,s)=>{if(s===false||s?.mode!=="before"&&s?.mode!=="after")return;const a=Array.from(t.childNodes).filter(r=>r instanceof HTMLStyleElement&&r.tagName==="STYLE");let o;try{o=Array.from(t.adoptedStyleSheets);}catch{o=[];}if(!(a.length===0&&o.length===0))if(s.mode==="before"){const r=[...o.map(i=>Array.from(i.cssRules).map(c=>c.cssText).join("")),...a.map(i=>i.innerHTML)];e.unshift(...r);}else a.forEach(r=>e.push(r.innerHTML)),o.forEach(r=>e.push(Array.from(r.cssRules).map(i=>i.cssText).join("")));},ie=(t,e,s)=>{const a=e.name||"default";let o;try{if(t.shadowRoot===null)throw new Error("ShadowRoot is null");o=t.shadowRoot;}catch{o=t;}const r=n$1.A11yUi.CSS_STYLE_CACHE.get(a)?.get(t.tagName);if(r)_(t,o,r,s);else {const i=y(a,"PROPERTIES"),c=y(a,"GLOBAL"),u=y(a,t.tagName);v.has(a)===false&&ae(a,c);const p=[i,c,u];if(re(o,p,e.encroachCss),e.cache===true){let m=n$1.A11yUi.CSS_STYLE_CACHE.get(a);m||(m=new Map,n$1.A11yUi.CSS_STYLE_CACHE.set(a,m)),m.set(t.tagName,p);}_(t,o,p,s);}},_=(t,e,s,a)=>{const o=n$1.A11yUi.Theme?.loglevel==="debug",r=o?performance.now():0;if(oe(e),ne(e,s),fe(t),requestAnimationFrame(a),o){const i=performance.now()-r,c=n$1.A11yUi.PERFORMANCE_MEASURES.get(t.tagName);c?(c.count+=1,c.totalTime+=i):n$1.A11yUi.PERFORMANCE_MEASURES.set(t.tagName,{count:1,totalTime:i});}},O=t=>{const e=n$1.A11yUi.STYLING_TASK_QUEUE.get(t);if(e){const{resetCss:s,themeDetails:a}=e;ie(t,a,s);}},ce=100;let S=(t,e=0)=>{if(e>=ce)return;const s=setTimeout(()=>{clearTimeout(s),t.classList.contains("hydrated")?O(t):S(t,e+1);},L);};const le={attributes:true,attributeFilter:["class"],childList:false,subtree:false},me={attributes:true,attributeFilter:[],childList:false,subtree:false},I=se?new MutationObserver((t,e)=>{const s=[];for(const a of t){const o=a.target;o.classList.contains("hydrated")&&n$1.A11yUi.STYLING_TASK_QUEUE.has(o)&&(O(o),s.push(o));}for(const a of s)e.observe(a,me);}):null;I&&(S=t=>I.observe(t,le),R=()=>{});const H=new Map;let P=(t,e)=>{if(e){const o=H.get(e);if(o!==void 0)return o}const s=getComputedStyle(t).getPropertyValue("--theme-visibility-delay").trim();let a;if(s.endsWith("ms"))a=parseFloat(s);else if(s.endsWith("s"))a=parseFloat(s)*1e3;else {const o=parseFloat(s);a=isNaN(o)?0:o;}return e&&H.set(e,a),a};n$1.A11yUi.IS_TEST_ENVIRONMENT&&(P=()=>0);const $=(t,e)=>{t.style.setProperty("visibility",e),t.dataset.themed="";},he=(t,e)=>{const s=t.style.visibility||null,a=e.name||"default";n$1.A11yUi.STYLING_TASK_QUEUE.set(t,{resetCss:()=>{const o=P(t,a);o>0?setTimeout(()=>{$(t,s);},o):$(t,s);},themeDetails:e}),t.style.setProperty("visibility","hidden","important"),S(t);},fe=t=>{n$1.A11yUi.STYLING_TASK_QUEUE.delete(t),R();},de=(t,e)=>{he(t,{...n$1.A11yUi.Theme,...e});};class ye{Prefix;Key;Tag;createTheme=(e,s)=>F(e,s);createTranslation=(e,s)=>j(e,s);constructor(e,s,a){this.Prefix=e,this.Key=Object.getOwnPropertyNames(s),this.Tag=Object.getOwnPropertyNames(a);}}
exports.KeyEnum = void 0;
(function (KeyEnum) {
KeyEnum[KeyEnum["error"] = 0] = "error";
KeyEnum[KeyEnum["warning"] = 1] = "warning";
KeyEnum[KeyEnum["info"] = 2] = "info";
KeyEnum[KeyEnum["success"] = 3] = "success";
KeyEnum[KeyEnum["message"] = 4] = "message";
KeyEnum[KeyEnum["close"] = 5] = "close";
KeyEnum[KeyEnum["form-description"] = 6] = "form-description";
KeyEnum[KeyEnum["of"] = 7] = "of";
KeyEnum[KeyEnum["characters"] = 8] = "characters";
KeyEnum[KeyEnum["new"] = 9] = "new";
KeyEnum[KeyEnum["no-entries"] = 10] = "no-entries";
KeyEnum[KeyEnum["change-order"] = 11] = "change-order";
KeyEnum[KeyEnum["action-running"] = 12] = "action-running";
KeyEnum[KeyEnum["action-done"] = 13] = "action-done";
KeyEnum[KeyEnum["page-first"] = 14] = "page-first";
KeyEnum[KeyEnum["page-back"] = 15] = "page-back";
KeyEnum[KeyEnum["page-next"] = 16] = "page-next";
KeyEnum[KeyEnum["page-last"] = 17] = "page-last";
KeyEnum[KeyEnum["entries-per-site"] = 18] = "entries-per-site";
KeyEnum[KeyEnum["page-current"] = 19] = "page-current";
KeyEnum[KeyEnum["page-selected"] = 20] = "page-selected";
KeyEnum[KeyEnum["page-per-site"] = 21] = "page-per-site";
KeyEnum[KeyEnum["logo-description"] = 22] = "logo-description";
KeyEnum[KeyEnum["live-value-bounded"] = 23] = "live-value-bounded";
KeyEnum[KeyEnum["live-value"] = 24] = "live-value";
KeyEnum[KeyEnum["open-link-in-tab"] = 25] = "open-link-in-tab";
KeyEnum[KeyEnum["kolibri-logo"] = 26] = "kolibri-logo";
})(exports.KeyEnum || (exports.KeyEnum = {}));
exports.TagEnum = void 0;
(function (TagEnum) {
TagEnum[TagEnum["abbr"] = 0] = "abbr";
TagEnum[TagEnum["accordion"] = 1] = "accordion";
TagEnum[TagEnum["alert"] = 2] = "alert";
TagEnum[TagEnum["avatar"] = 3] = "avatar";
TagEnum[TagEnum["badge"] = 4] = "badge";
TagEnum[TagEnum["breadcrumb"] = 5] = "breadcrumb";
TagEnum[TagEnum["button"] = 6] = "button";
TagEnum[TagEnum["button-link"] = 7] = "button-link";
TagEnum[TagEnum["card"] = 8] = "card";
TagEnum[TagEnum["combobox"] = 9] = "combobox";
TagEnum[TagEnum["details"] = 10] = "details";
TagEnum[TagEnum["dialog"] = 11] = "dialog";
TagEnum[TagEnum["drawer"] = 12] = "drawer";
TagEnum[TagEnum["form"] = 13] = "form";
TagEnum[TagEnum["heading"] = 14] = "heading";
TagEnum[TagEnum["icon"] = 15] = "icon";
TagEnum[TagEnum["image"] = 16] = "image";
TagEnum[TagEnum["input-checkbox"] = 17] = "input-checkbox";
TagEnum[TagEnum["input-color"] = 18] = "input-color";
TagEnum[TagEnum["input-date"] = 19] = "input-date";
TagEnum[TagEnum["input-email"] = 20] = "input-email";
TagEnum[TagEnum["input-file"] = 21] = "input-file";
TagEnum[TagEnum["input-number"] = 22] = "input-number";
TagEnum[TagEnum["input-password"] = 23] = "input-password";
TagEnum[TagEnum["input-radio"] = 24] = "input-radio";
TagEnum[TagEnum["input-range"] = 25] = "input-range";
TagEnum[TagEnum["input-text"] = 26] = "input-text";
TagEnum[TagEnum["kolibri"] = 27] = "kolibri";
TagEnum[TagEnum["link"] = 28] = "link";
TagEnum[TagEnum["link-button"] = 29] = "link-button";
TagEnum[TagEnum["logo"] = 30] = "logo";
TagEnum[TagEnum["meter"] = 31] = "meter";
TagEnum[TagEnum["modal"] = 32] = "modal";
TagEnum[TagEnum["nav"] = 33] = "nav";
TagEnum[TagEnum["pagination"] = 34] = "pagination";
TagEnum[TagEnum["popover-button"] = 35] = "popover-button";
TagEnum[TagEnum["progress"] = 36] = "progress";
TagEnum[TagEnum["quote"] = 37] = "quote";
TagEnum[TagEnum["select"] = 38] = "select";
TagEnum[TagEnum["single-select"] = 39] = "single-select";
TagEnum[TagEnum["skip-nav"] = 40] = "skip-nav";
TagEnum[TagEnum["spin"] = 41] = "spin";
TagEnum[TagEnum["split-button"] = 42] = "split-button";
TagEnum[TagEnum["symbol"] = 43] = "symbol";
TagEnum[TagEnum["table"] = 44] = "table";
TagEnum[TagEnum["table-stateful"] = 45] = "table-stateful";
TagEnum[TagEnum["table-stateless"] = 46] = "table-stateless";
TagEnum[TagEnum["tabs"] = 47] = "tabs";
TagEnum[TagEnum["textarea"] = 48] = "textarea";
TagEnum[TagEnum["toast-container"] = 49] = "toast-container";
TagEnum[TagEnum["toolbar"] = 50] = "toolbar";
TagEnum[TagEnum["tooltip"] = 51] = "tooltip";
TagEnum[TagEnum["tree"] = 52] = "tree";
TagEnum[TagEnum["tree-item"] = 53] = "tree-item";
})(exports.TagEnum || (exports.TagEnum = {}));
const getWindow = () => {
if (typeof window !== 'undefined')
return window;
return {};
};
const getDocument = () => {
const win = getWindow();
if (win && typeof win.document !== 'undefined')
return win.document;
return {};
};
const MODES = ['development', 'production', 'test'];
let runtimeMode = 'production';
const setRuntimeMode = (mode) => {
try {
if (MODES.includes(mode)) {
runtimeMode = mode;
}
else {
throw new Error(`Invalid NODE_ENV value: ${mode}. Expected one of ${MODES.join(', ')}.`);
}
}
catch (_a) {
runtimeMode = 'production';
}
};
const getInitialMode = () => {
try {
const nodeEnv = typeof process !== 'undefined' && process.env ? process.env['NODE_ENV'] : undefined;
if (nodeEnv && MODES.includes(nodeEnv)) {
return nodeEnv;
}
}
catch (_a) {
}
return 'production';
};
setRuntimeMode(getInitialMode());
let EXPERIMENTAL_MODE = false;
let COLOR_CONTRAST_ANALYSIS = false;
const isDevMode = () => runtimeMode === 'development';
const isTestMode = () => runtimeMode === 'test';
const getExperimentalMode = () => EXPERIMENTAL_MODE === true;
const setExperimentalMode = (mode) => {
EXPERIMENTAL_MODE = mode === true;
};
const getColorContrastAnalysis = () => COLOR_CONTRAST_ANALYSIS === true;
const setColorContrastAnalysis = (mode) => {
COLOR_CONTRAST_ANALYSIS = mode === true;
};
const LOG_STYLE = 'color: white; background: #666; font-weight: bold; padding: .25em .5em; border-radius: 3px; border: 1px solid #000';
const mapToArray = (msg) => {
return Array.isArray(msg) ? msg : [msg];
};
const getLogLabel = (label) => {
return `%c${label}`;
};
const handleClassifier = (label, classifier) => {
if (typeof classifier === 'string' && classifier.length > 0) {
return `${getLogLabel(label)} | ${classifier}`;
}
else {
return getLogLabel(label);
}
};
const getShield = (label, options) => {
return [handleClassifier(label, options === null || options === void 0 ? void 0 : options.classifier), `${LOG_STYLE};${(options === null || options === void 0 ? void 0 : options.overwriteStyle) || ''}`];
};
const isDevModeOrForceLog = (forceLog) => isDevMode() || forceLog === true;
class Logger {
constructor(label) {
this.label = label;
}
debug(msg, options) {
if (isDevModeOrForceLog(options === null || options === void 0 ? void 0 : options.forceLog)) {
console.debug(...getShield(this.label, options), ...mapToArray(msg));
}
}
info(msg, options) {
if (isDevModeOrForceLog(options === null || options === void 0 ? void 0 : options.forceLog)) {
console.info(...getShield(this.label, options), ...mapToArray(msg));
}
}
trace(msg, options) {
if (isDevModeOrForceLog(options === null || options === void 0 ? void 0 : options.forceLog)) {
console.trace(...getShield(this.label, options), ...mapToArray(msg));
}
}
warn(msg, options) {
if (isDevModeOrForceLog(options === null || options === void 0 ? void 0 : options.forceLog)) {
console.warn(...getShield(this.label, options), ...mapToArray(msg));
}
}
error(msg, options) {
console.error(...getShield(this.label, options), ...mapToArray(msg));
}
throw(msg, options) {
if (isDevModeOrForceLog(options === null || options === void 0 ? void 0 : options.forceLog)) {
throw new Error(...getShield(this.label, options), ...mapToArray(msg));
}
}
}
const Log = new Logger('KoliBri');
const a11yCache = new Set();
const a11yHint = (msg, options) => {
if (a11yCache.has(msg) === false || false) {
a11yCache.add(msg);
Log.debug([msg].concat([]), {
classifier: `✋ a11y`,
forceLog: false,
overwriteStyle: '; background-color: #09f',
});
}
};
const deprecatedCache = new Set();
const deprecatedHint = (msg, options) => {
if (deprecatedCache.has(msg) === false || false) {
deprecatedCache.add(msg);
Log.warn([msg].concat([]), {
classifier: `🔥 deprecated`,
forceLog: false,
overwriteStyle: '; background-color: #f00',
});
}
};
const devCache = new Set();
const devHint = (msg, options) => {
if (devCache.has(msg) === false || !!(options === null || options === void 0 ? void 0 : options.force)) {
devCache.add(msg);
Log.debug([msg].concat((options === null || options === void 0 ? void 0 : options.details) || []), {
classifier: `💻 dev`,
forceLog: !!(options === null || options === void 0 ? void 0 : options.force),
overwriteStyle: '; background-color: #f09',
});
}
};
const devWarning = (msg, options) => {
if (devCache.has(msg) === false || false) {
devCache.add(msg);
Log.warn([msg].concat([]), {
classifier: `⚠️ dev`,
forceLog: false,
overwriteStyle: '; background-color: #f09',
});
}
};
const featureCache = new Set();
const featureHint = (msg, done = false, options) => {
if (featureCache.has(msg) === false || false) {
featureCache.add(msg);
msg += done === true ? ' ✅' : '';
Log.debug([msg].concat([]), {
classifier: `🌟 feature`,
forceLog: false,
overwriteStyle: '; background-color: #309',
});
}
};
devHint(`We appreciate any feedback, comments, screenshots, or demo links of an application based on KoliBri (kolibri@itzbund.de). Thank you!`);
const uiUxCache = new Set();
const uiUxHint = (msg, options) => {
if (uiUxCache.has(msg) === false || false) {
uiUxCache.add(msg);
Log.debug([msg].concat([]), {
classifier: `📑 ui/ux`,
forceLog: false,
overwriteStyle: '; background-color: #060;',
});
}
};
const a11yHintDisabled = () => {
a11yHint(`"Disabled" limits accessibility and visibility. From an accessibility perspective, we recommend using the readonly attribute instead of disabled.\n- https://uxdesign.cc/is-it-ok-to-grey-out-disabled-buttons-8afa74a0fae`);
};
const a11yHintLabelingLandmarks = (value) => {
if (typeof value !== 'string' || value === '') {
a11yHint(`Some structural elements, such as the nav tag, can be used multiple times on a webpage. To distinguish between similarly named structural elements, it is necessary to set an ARIA label.\n- https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/Navigation_Role#accessibility_concerns`);
}
};
const uiUxHintMillerscheZahl = (className, length = 8) => {
if (length > 7) {
uiUxHint(`[${className}] Within navigation structures, it is recommended to use no more than 7 menu items.
Link:
- https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two`);
}
};
var n=.2126,r=.7152,t=.0722,e=1/12.92;function u(n){return Math.pow((n+.055)/1.055,2.4)}function a(a){var i=a[0]/255,c=a[1]/255,o=a[2]/255,s=i<=.03928?i*e:u(i),f=c<=.03928?c*e:u(c),l=o<=.03928?o*e:u(o);return s*n+f*r+l*t}function i(n){var r=255;8===(n=n.replace(/^#/,"")).length&&(r=parseInt(n.slice(6,8),16),n=n.substring(0,6)),4===n.length&&(r=parseInt(n.slice(3,4).repeat(2),16),n=n.substring(0,3)),3===n.length&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]);var t=parseInt(n,16);return [t>>16,t>>8&255,255&t,r]}function c(n,r){return (Math.max(n,r)+.05)/(Math.min(n,r)+.05)}function o(n,r){return c(a(n),a(r))}function s(n,r){return o(i(n),i(r))}function f(n){return n>=7?"AAA":n>=4.5?"AA":n>=3?"AA Large":"Fail"}
var colorName;
var hasRequiredColorName;
function requireColorName () {
if (hasRequiredColorName) return colorName;
hasRequiredColorName = 1;
colorName = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
return colorName;
}
/**
* @module color-parse
*/
var colorParse;
var hasRequiredColorParse;
function requireColorParse () {
if (hasRequiredColorParse) return colorParse;
hasRequiredColorParse = 1;
var names = requireColorName();
colorParse = parse;
/**
* Base hues
* http://dev.w3.org/csswg/css-color/#typedef-named-hue
*/
//FIXME: use external hue detector
var baseHues = {
red: 0,
orange: 60,
yellow: 120,
green: 180,
blue: 240,
purple: 300
};
/**
* Parse color from the string passed
*
* @return {Object} A space indicator `space`, an array `values` and `alpha`
*/
function parse(cstr) {
var m, parts = [], alpha = 1, space;
if (typeof cstr === 'string') {
cstr = cstr.toLowerCase();
//keyword
if (names[cstr]) {
parts = names[cstr].slice();
space = 'rgb';
}
//reserved words
else if (cstr === 'transparent') {
alpha = 0;
space = 'rgb';
parts = [0, 0, 0];
}
//hex
else if (/^#[A-Fa-f0-9]+$/.test(cstr)) {
var base = cstr.slice(1);
var size = base.length;
var isShort = size <= 4;
alpha = 1;
if (isShort) {
parts = [
parseInt(base[0] + base[0], 16),
parseInt(base[1] + base[1], 16),
parseInt(base[2] + base[2], 16)
];
if (size === 4) {
alpha = parseInt(base[3] + base[3], 16) / 255;
}
}
else {
parts = [
parseInt(base[0] + base[1], 16),
parseInt(base[2] + base[3], 16),
parseInt(base[4] + base[5], 16)
];
if (size === 8) {
alpha = parseInt(base[6] + base[7], 16) / 255;
}
}
if (!parts[0]) parts[0] = 0;
if (!parts[1]) parts[1] = 0;
if (!parts[2]) parts[2] = 0;
space = 'rgb';
}
//color space
else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) {
var name = m[1];
var isRGB = name === 'rgb';
var base = name.replace(/a$/, '');
space = base;
var size = base === 'cmyk' ? 4 : base === 'gray' ? 1 : 3;
parts = m[2].trim()
.split(/\s*[,\/]\s*|\s+/)
.map(function (x, i) {
//<percentage>
if (/%$/.test(x)) {
//alpha
if (i === size) return parseFloat(x) / 100
//rgb
if (base === 'rgb') return parseFloat(x) * 255 / 100
return parseFloat(x)
}
//hue
else if (base[i] === 'h') {
//<deg>
if (/deg$/.test(x)) {
return parseFloat(x)
}
//<base-hue>
else if (baseHues[x] !== undefined) {
return baseHues[x]
}
}
return parseFloat(x)
});
if (name === base) parts.push(1);
alpha = (isRGB) ? 1 : (parts[size] === undefined) ? 1 : parts[size];
parts = parts.slice(0, size);
}
//named channels case
else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) {
parts = cstr.match(/([0-9]+)/g).map(function (value) {
return parseFloat(value)
});
space = cstr.match(/([a-z])/ig).join('').toLowerCase();
}
}
//numeric case
else if (!isNaN(cstr)) {
space = 'rgb';
parts = [cstr >>> 16, (cstr & 0x00ff00) >>> 8, cstr & 0x0000ff];
}
//array-like
else if (Array.isArray(cstr) || cstr.length) {
parts = [cstr[0], cstr[1], cstr[2]];
space = 'rgb';
alpha = cstr.length === 4 ? cstr[3] : 1;
}
//object case - detects css cases of rgb and hsl
else if (cstr instanceof Object) {
if (cstr.r != null || cstr.red != null || cstr.R != null) {
space = 'rgb';
parts = [
cstr.r || cstr.red || cstr.R || 0,
cstr.g || cstr.green || cstr.G || 0,
cstr.b || cstr.blue || cstr.B || 0
];
}
else {
space = 'hsl';
parts = [
cstr.h || cstr.hue || cstr.H || 0,
cstr.s || cstr.saturation || cstr.S || 0,
cstr.l || cstr.lightness || cstr.L || cstr.b || cstr.brightness
];
}
alpha = cstr.a || cstr.alpha || cstr.opacity || 1;
if (cstr.opacity != null) alpha /= 100;
}
return {
space: space,
values: parts,
alpha: alpha
}
}
return colorParse;
}
var colorParseExports = requireColorParse();
var parse = /*@__PURE__*/getDefaultExportFromCjs(colorParseExports);
/**
* RGB space.
*
* @module color-space/rgb
*/
const rgb = {
min: [0, 0, 0],
max: [255, 255, 255]};
/**
* @module color-space/hsl
*/
var hsl = {
name: 'hsl',
min: [0, 0, 0],
max: [360, 100, 100],
channel: ['hue', 'saturation', 'lightness'],
alias: ['HSL'],
rgb: function (hsl) {
var h = hsl[0] / 360, s = hsl[1] / 100, l = hsl[2] / 100, t1, t2, t3, rgb, val, i = 0;
if (s === 0) return val = l * 255, [val, val, val];
t2 = l < 0.5 ? l * (1 + s) : l + s - l * s;
t1 = 2 * l - t2;
rgb = [0, 0, 0];
for (; i < 3;) {
t3 = h + 1 / 3 * - (i - 1);
t3 < 0 ? t3++ : t3 > 1 && t3--;
val = 6 * t3 < 1 ? t1 + (t2 - t1) * 6 * t3 :
2 * t3 < 1 ? t2 :
3 * t3 < 2 ? t1 + (t2 - t1) * (2 / 3 - t3) * 6 :
t1;
rgb[i++] = val * 255;
}
return rgb;
}
};
//extend rgb
rgb.hsl = function (rgb) {
var r = rgb[0] / 255,
g = rgb[1] / 255,
b = rgb[2] / 255,
min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s, l;
if (max === min) {
h = 0;
}
else if (r === max) {
h = (g - b) / delta;
}
else if (g === max) {
h = 2 + (b - r) / delta;
}
else if (b === max) {
h = 4 + (r - g) / delta;
}
//FIXME h is possibly undefined
//@ts-ignore
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
l = (min + max) / 2;
if (max === min) {
s = 0;
}
else if (l <= 0.5) {
s = delta / (max + min);
}
else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
var rgbaConvert = {exports: {}};
var hasRequiredRgbaConvert;
function requireRgbaConvert () {
if (hasRequiredRgbaConvert) return rgbaConvert.exports;
hasRequiredRgbaConvert = 1;
rgbaConvert.exports = arr;
rgbaConvert.exports.arr = arr;
rgbaConvert.exports.obj = obj;
rgbaConvert.exports.css = css;
rgbaConvert.exports.hex = hex;
rgbaConvert.exports.num = num;
function arr(data) {
var a = parse(data);
if (a.length == 3) {
return a.concat(255)
} else {
a[3] = Math.round(a[3]);
return a
}
}
function obj(data) {
var a = parse(data);
return {
r: a[0],
g: a[1],
b: a[2],
a: a.length == 3
? 255
: Math.round(a[3])
}
}
function css(data) {
var a = parse(data);
if (a.length == 3) a.push(255);
return a[3] == 255
? 'rgb(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')'
: a[3] == 0
? 'rgba(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', 0)'
: 'rgba(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + String(a[3] / 255).substr(1) + ')'
}
function hex(data) {
var a = parse(data);
if (a.length == 3) a.push(255);
var opaque = a[3] == 255;
var r = num2hex(a[0]);
var g = num2hex(a[1]);
var b = num2hex(a[2]);
var a = num2hex(Math.round(a[3]));
var is = isshort(r, g, b, a);
if (opaque) {
return is
? '#' + r.charAt(0) + g.charAt(0) + b.charAt(0)
: '#' + r + g + b
}
return is
? '#' + r.charAt(0) + g.charAt(0) + b.charAt(0) + a.charAt(0)
: '#' + r + g + b + a
}
function num(data) {
var a = parse(data);
if (a.length == 3) a.push(255);
else a[3] = Math.round(a[3]);
return ((a[3] << 24) >>> 0 | a[0] << 16 | a[1] << 8 | a[2]) >>> 0
}
function parse(data) {
if (typeof data == 'string') {
data = data.toLowerCase();
return name(data)
|| hex3(data)
|| hex6(data)
|| rgb(data)
|| rgba(data)
|| [0, 0, 0, 255]
}
return object(data)
|| array(data)
|| number(data)
|| [0, 0, 0, 255]
}
function num2hex(num) {
var s = num.toString(16);
return s.length == 1
? '0' + s
: s
}
function isshort(r, g, b, a) {
var h = ['ff', '00', '11', '22', '33', '44', '55', '66',
'77', '88', '99', 'aa', 'bb', 'cc', 'dd', 'ee'];
return h.indexOf(r) != -1
&& h.indexOf(g) != -1
&& h.indexOf(b) != -1
&& h.indexOf(a) != -1
}
function name(str) {
if (str == 'red') return [255, 0, 0]
if (str == 'green') return [0, 255, 0]
if (str == 'blue') return [0, 0, 255]
if (str == 'black') return [0, 0, 0]
if (str == 'white') return [255, 255, 255]
if (str == 'cyan') return [0, 255, 255]
if (str == 'gray') return [128, 128, 128]
if (str == 'grey') return [128, 128, 128]
if (str == 'magenta') return [255, 0, 255]
// ok, not the real css `pink` but my personal `magenta` alias
// `pink` is simpler than `fuchsia`, whatever...
if (str == 'pink') return [255, 0, 255]
if (str == 'yellow') return [255, 255, 0]
}
function hex2num(str) {
return str.length == 1
? parseInt(str + str, 16)
: parseInt(str, 16)
}
function hex3(str) {
var s = str.replace(/^#/,'');
var l = s.length;
if (l == 3 || l == 4) {
var r = hex2num(s[0]);
var g = hex2num(s[1]);
var b = hex2num(s[2]);
var a = l == 3
? 255
: hex2num(s[3]);
if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return
return [r, g, b, a]
}
}
function hex6(str) {
var s = str.replace(/^#/,'');
var l = s.length;
if (l == 6 || l == 8) {
var r = hex2num(s.slice(0, 2));
var g = hex2num(s.slice(2, 4));
var b = hex2num(s.slice(4, 6));
var a = l == 6
? 255
: hex2num(s.slice(6, 8));
if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return
return [r, g, b, a]
}
}
function getnum(val, integer) {
if (typeof val != 'number') return -1
if (integer === true && Math.floor(val) !== val) return -1
return val >= 0 && val <= 255
? val
: -1
}
function object(obj) {
if (Object.prototype.toString.call(obj) === '[object Object]'
&& Object.getPrototypeOf(obj) === Object.getPrototypeOf({})) {
var r = getnum(obj.r != undefined ? obj.r : obj.red != undefined ? obj.red : 0, true);
var g = getnum(obj.g != undefined ? obj.g : obj.green != undefined ? obj.green : 0, true);
var b = getnum(obj.b != undefined ? obj.b : obj.blue != undefined ? obj.blue : 0, true);
var a = getnum(obj.a != undefined ? obj.a : obj.alpha != undefined ? obj.alpha : 255, true);
if (r != -1 && g != -1 && b != -1 && a != -1) {
return [r, g, b, a]
}
}
}
function array(arr) {
if (Array.isArray(arr) && (arr.length == 3 || arr.length == 4)) {
var r = getnum(arr[0], true);
var g = getnum(arr[1], true);
var b = getnum(arr[2], true);
var a = getnum(arr[3] != undefined ? arr[3] : 255, true);
if (r != -1 && g != -1 && b != -1 && a != -1) {
return [r, g, b, a]
}
}
}
function number(num) {
if (typeof num == 'number' && Math.floor(num) == num && num <= 4294967295 && num >= 0) {
var a = num >> 24 & 255;
var r = num >> 16 & 255;
var g = num >> 8 & 255;
var b = num & 255;
return [r, g, b, a]
}
}
function rgb(str) {
if (str.substr(0, 4) == 'rgb(') {
str = str.match(/^rgb\(([^)]+)\)/)[1];
var t = str.split(/ *, */).map(Number);
var r = getnum(t[0], true);
var g = getnum(t[1], true);
var b = getnum(t[2], true);
if (r != -1 && g != -1 && b != -1) {
return [r, g, b, 255]
}
}
}
function rgba(str) {
if (str.substr(0, 5)