UNPKG

naive-ui

Version:

A Vue 3 Component Library. Fairly Complete, Theme Customizable, Uses TypeScript, Fast

1,691 lines (1,658 loc) 3.66 MB
import { ref, readonly, watch, computed, getCurrentInstance, onMounted, onBeforeUnmount, onBeforeMount, reactive, inject, onActivated, onDeactivated, createTextVNode, Fragment, Comment, defineComponent, provide, withDirectives, h, Teleport, toRef, nextTick, renderSlot, mergeProps, vShow, isVNode, shallowRef, watchEffect, Transition, TransitionGroup, cloneVNode, Text, onUnmounted, onBeforeUpdate, onUpdated, normalizeStyle, isReactive, markRaw, normalizeClass, createApp, unref, isProxy, toRaw, renderList } from 'vue'; /* eslint-disable @typescript-eslint/restrict-template-expressions */ /* eslint-disable @typescript-eslint/strict-boolean-expressions */ function plugin$1(options) { let _bPrefix = '.'; let _ePrefix = '__'; let _mPrefix = '--'; let c; if (options) { let t = options.blockPrefix; if (t) { _bPrefix = t; } t = options.elementPrefix; if (t) { _ePrefix = t; } t = options.modifierPrefix; if (t) { _mPrefix = t; } } const _plugin = { install(instance) { c = instance.c; const ctx = instance.context; ctx.bem = {}; ctx.bem.b = null; ctx.bem.els = null; } }; function b(arg) { let memorizedB; let memorizedE; return { before(ctx) { memorizedB = ctx.bem.b; memorizedE = ctx.bem.els; ctx.bem.els = null; }, after(ctx) { ctx.bem.b = memorizedB; ctx.bem.els = memorizedE; }, $({ context, props }) { arg = typeof arg === 'string' ? arg : arg({ context, props }); context.bem.b = arg; return `${(props === null || props === void 0 ? void 0 : props.bPrefix) || _bPrefix}${context.bem.b}`; } }; } function e(arg) { let memorizedE; return { before(ctx) { memorizedE = ctx.bem.els; }, after(ctx) { ctx.bem.els = memorizedE; }, $({ context, props }) { arg = typeof arg === 'string' ? arg : arg({ context, props }); context.bem.els = arg.split(',').map(v => v.trim()); return context.bem.els.map(el => `${(props === null || props === void 0 ? void 0 : props.bPrefix) || _bPrefix}${context.bem.b}${_ePrefix}${el}`).join(', '); } }; } function m(arg) { return { $({ context, props }) { arg = typeof arg === 'string' ? arg : arg({ context, props }); const modifiers = arg.split(',').map(v => v.trim()); function elementToSelector(el) { return modifiers.map(modifier => `&${(props === null || props === void 0 ? void 0 : props.bPrefix) || _bPrefix}${context.bem.b}${el !== undefined ? `${_ePrefix}${el}` : ''}${_mPrefix}${modifier}`).join(', '); } const els = context.bem.els; if (els !== null) { if (els.length >= 2) { throw Error(`[css-render/plugin-bem]: m(${arg}) is invalid, using modifier inside multiple elements is not allowed`); } return elementToSelector(els[0]); } else { return elementToSelector(); } } }; } function notM(arg) { return { $({ context, props }) { arg = typeof arg === 'string' ? arg : arg({ context, props }); const els = context.bem.els; if (els !== null && els.length >= 2) { throw Error(`[css-render/plugin-bem]: notM(${arg}) is invalid, using modifier inside multiple elements is not allowed`); } return `&:not(${(props === null || props === void 0 ? void 0 : props.bPrefix) || _bPrefix}${context.bem.b}${els !== null && els.length > 0 ? `${_ePrefix}${els[0]}` : ''}${_mPrefix}${arg})`; } }; } const cB = (...args) => c(b(args[0]), args[1], args[2]); const cE = (...args) => c(e(args[0]), args[1], args[2]); const cM = (...args) => c(m(args[0]), args[1], args[2]); const cNotM = (...args) => c(notM(args[0]), args[1], args[2]); Object.assign(_plugin, { cB, cE, cM, cNotM }); return _plugin; } function ampCount(selector) { let cnt = 0; for (let i = 0; i < selector.length; ++i) { if (selector[i] === '&') ++cnt; } return cnt; } /** * Don't just use ',' to separate css selector. For example: * x:(a, b) {} will be split into 'x:(a' and 'b)', which is not expected. * Make sure comma doesn't exist inside parentheses. */ const separatorRegex = /\s*,(?![^(]*\))\s*/g; const extraSpaceRegex = /\s+/g; /** * selector must includes '&' * selector is trimmed * every part of amp is trimmed */ function resolveSelectorWithAmp(amp, selector) { const nextAmp = []; selector.split(separatorRegex).forEach(partialSelector => { let round = ampCount(partialSelector); // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!round) { amp.forEach(partialAmp => { nextAmp.push( // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions (partialAmp && partialAmp + ' ') + partialSelector); }); return; } else if (round === 1) { amp.forEach(partialAmp => { nextAmp.push(partialSelector.replace('&', partialAmp)); }); return; } let partialNextAmp = [partialSelector]; // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions while (round--) { const nextPartialNextAmp = []; partialNextAmp.forEach(selectorItr => { amp.forEach(partialAmp => { nextPartialNextAmp.push(selectorItr.replace('&', partialAmp)); }); }); partialNextAmp = nextPartialNextAmp; } partialNextAmp.forEach(part => nextAmp.push(part)); }); return nextAmp; } /** * selector mustn't includes '&' * selector is trimmed */ function resolveSelector(amp, selector) { const nextAmp = []; selector.split(separatorRegex).forEach(partialSelector => { amp.forEach(partialAmp => { // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions nextAmp.push((partialAmp && partialAmp + ' ') + partialSelector); }); }); return nextAmp; } function parseSelectorPath(selectorPaths) { let amp = ['']; selectorPaths.forEach(selector => { // eslint-disable-next-line selector = selector && selector.trim(); if ( // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions !selector) { /** * if it's a empty selector, do nothing */ return; } // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (selector.includes('&')) { amp = resolveSelectorWithAmp(amp, selector); } else { amp = resolveSelector(amp, selector); } }); return amp.join(', ').replace(extraSpaceRegex, ' '); } function removeElement(el) { /* istanbul ignore if */ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!el) return; const parentElement = el.parentElement; /* istanbul ignore else */ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (parentElement) parentElement.removeChild(el); } function queryElement(id, parent) { return (parent !== null && parent !== void 0 ? parent : document.head).querySelector(`style[cssr-id="${id}"]`); } function createElement(id) { const el = document.createElement('style'); el.setAttribute('cssr-id', id); return el; } function isMediaOrSupports(selector) { // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!selector) return false; return /^\s*@(s|m)/.test(selector); } const kebabRegex = /[A-Z]/g; function kebabCase(pattern) { return pattern.replace(kebabRegex, match => '-' + match.toLowerCase()); } /** TODO: refine it to solve nested object */ function unwrapProperty(prop, indent = ' ') { if (typeof prop === 'object' && prop !== null) { return ' {\n' + Object.entries(prop).map(v => { return indent + ` ${kebabCase(v[0])}: ${v[1]};`; }).join('\n') + '\n' + indent + '}'; } return `: ${prop};`; } /** unwrap properties */ function unwrapProperties(props, instance, params) { if (typeof props === 'function') { return props({ context: instance.context, props: params }); } return props; } function createStyle(selector, props, instance, params) { if (!props) return ''; // eslint-disable-next-line const unwrappedProps = unwrapProperties(props, instance, params); if (!unwrappedProps) return ''; if (typeof unwrappedProps === 'string') { return `${selector} {\n${unwrappedProps}\n}`; } const propertyNames = Object.keys(unwrappedProps); if (propertyNames.length === 0) { if (instance.config.keepEmptyBlock) return selector + ' {\n}'; return ''; } const statements = selector ? [selector + ' {'] : []; propertyNames.forEach(propertyName => { const property = unwrappedProps[propertyName]; if (propertyName === 'raw') { statements.push('\n' + property + '\n'); return; } propertyName = kebabCase(propertyName); if (property !== null && property !== undefined) { statements.push(` ${propertyName}${unwrapProperty(property)}`); } }); if (selector) { statements.push('}'); } return statements.join('\n'); } function loopCNodeListWithCallback(children, options, callback) { /* istanbul ignore if */ if (!children) return; children.forEach(child => { if (Array.isArray(child)) { loopCNodeListWithCallback(child, options, callback); } else if (typeof child === 'function') { const grandChildren = child(options); if (Array.isArray(grandChildren)) { loopCNodeListWithCallback(grandChildren, options, callback); } else if (grandChildren) { callback(grandChildren); } } else if (child) { callback(child); } }); } function traverseCNode(node, selectorPaths, styles, instance, params) { const $ = node.$; let blockSelector = ''; if (!$ || typeof $ === 'string') { if (isMediaOrSupports($)) { blockSelector = $; } else { // as a string selector selectorPaths.push($); } } else if (typeof $ === 'function') { const selector = $({ context: instance.context, props: params }); if (isMediaOrSupports(selector)) { blockSelector = selector; } else { // as a lazy selector selectorPaths.push(selector); } } else { // as a option selector if ($.before) $.before(instance.context); if (!$.$ || typeof $.$ === 'string') { if (isMediaOrSupports($.$)) { blockSelector = $.$; } else { // as a string selector selectorPaths.push($.$); } } else /* istanbul ignore else */if ($.$) { const selector = $.$({ context: instance.context, props: params }); if (isMediaOrSupports(selector)) { blockSelector = selector; } else { // as a lazy selector selectorPaths.push(selector); } } } const selector = parseSelectorPath(selectorPaths); const style = createStyle(selector, node.props, instance, params); if (blockSelector) { styles.push(`${blockSelector} {`); } else if (style.length) { styles.push(style); } if (node.children) { loopCNodeListWithCallback(node.children, { context: instance.context, props: params }, childNode => { if (typeof childNode === 'string') { const style = createStyle(selector, { raw: childNode }, instance, params); styles.push(style); } else { traverseCNode(childNode, selectorPaths, styles, instance, params); } }); } selectorPaths.pop(); if (blockSelector) { styles.push('}'); } if ($ && $.after) $.after(instance.context); } function render$1(node, instance, props) { const styles = []; traverseCNode(node, [], styles, instance, props); return styles.join('\n\n'); } /* eslint-disable */ // Inspired by https://github.com/garycourt/murmurhash-js // Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86 function murmur2(str) { // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. // const m = 0x5bd1e995; // const r = 24; // Initialize the hash var h = 0; // Mix 4 bytes at a time into the hash var k, i = 0, len = str.length; for (; len >= 4; ++i, len -= 4) { k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24; k = /* Math.imul(k, m): */ (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16); k ^= /* k >>> r: */ k >>> 24; h = /* Math.imul(k, m): */ (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^ /* Math.imul(h, m): */ (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16); } // Handle the last few bytes of the input array switch (len) { case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; case 1: h ^= str.charCodeAt(i) & 0xff; h = /* Math.imul(h, m): */ (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16); } // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >>> 13; h = /* Math.imul(h, m): */ (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16); return ((h ^ h >>> 15) >>> 0).toString(36); } /* eslint-disable @typescript-eslint/prefer-ts-expect-error */ /* eslint-disable @typescript-eslint/strict-boolean-expressions */ if (typeof window !== 'undefined') { window.__cssrContext = {}; } function unmount(instance, node, id, parent) { const { els } = node; // If id is undefined, unmount all styles if (id === undefined) { els.forEach(removeElement); node.els = []; } else { const target = queryElement(id, parent); // eslint-disable-next-line if (target && els.includes(target)) { removeElement(target); node.els = els.filter(el => el !== target); } } } function addElementToList(els, target) { els.push(target); } function mount(instance, node, id, props, head, force, anchorMetaName, parent, ssrAdapter // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) { let style; if (id === undefined) { style = node.render(props); id = murmur2(style); } if (ssrAdapter) { ssrAdapter.adapter(id, style !== null && style !== void 0 ? style : node.render(props)); return; } if (parent === undefined) { parent = document.head; } const queriedTarget = queryElement(id, parent); if (queriedTarget !== null && !force) { return queriedTarget; } const target = queriedTarget !== null && queriedTarget !== void 0 ? queriedTarget : createElement(id); if (style === undefined) style = node.render(props); target.textContent = style; if (queriedTarget !== null) return queriedTarget; if (anchorMetaName) { const anchorMetaEl = parent.querySelector(`meta[name="${anchorMetaName}"]`); if (anchorMetaEl) { parent.insertBefore(target, anchorMetaEl); addElementToList(node.els, target); return target; } } if (head) { parent.insertBefore(target, parent.querySelector('style, link')); } else { parent.appendChild(target); } addElementToList(node.els, target); return target; } function wrappedRender(props) { return render$1(this, this.instance, props); } // do not guard node calling, it should throw an error. function wrappedMount(options = {} // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) { const { id, ssr, props, head = false, force = false, anchorMetaName, parent } = options; const targetElement = mount(this.instance, this, id, props, head, force, anchorMetaName, parent, ssr); return targetElement; } function wrappedUnmount(options = {}) { /* istanbul ignore next */ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions const { id, parent } = options; unmount(this.instance, this, id, parent); } const createCNode = function (instance, $, props, children) { return { instance, $, props, children, els: [], render: wrappedRender, mount: wrappedMount, unmount: wrappedUnmount }; }; const c$2 = function (instance, $, props, children) { if (Array.isArray($)) { return createCNode(instance, { $: null }, null, $); } else if (Array.isArray(props)) { return createCNode(instance, $, null, props); } else if (Array.isArray(children)) { return createCNode(instance, $, props, children); } else { return createCNode(instance, $, props, null); } }; function CssRender(config = {}) { const cssr = { c: (...args) => c$2(cssr, ...args), use: (plugin, ...args) => plugin.install(cssr, ...args), find: queryElement, context: {}, config }; return cssr; } function exists(id, ssr) { if (id === undefined) return false; if (ssr) { const { context: { ids } } = ssr; return ids.has(id); } return queryElement(id) !== null; } const namespace = "n"; const prefix$1 = `.${namespace}-`; const elementPrefix = "__"; const modifierPrefix = "--"; const cssr = CssRender(); const plugin = plugin$1({ blockPrefix: prefix$1, elementPrefix, modifierPrefix }); cssr.use(plugin); const { c: c$1, find } = cssr; const { cB, cE, cM, cNotM } = plugin; function insideModal(style) { return c$1(({ props: { bPrefix } }) => `${bPrefix || prefix$1}modal, ${bPrefix || prefix$1}drawer`, [style]); } function insidePopover(style) { return c$1(({ props: { bPrefix } }) => `${bPrefix || prefix$1}popover`, [style]); } function asModal(style) { return c$1(({ props: { bPrefix } }) => `&${bPrefix || prefix$1}modal`, style); } const cCB = (...args) => { return c$1(">", [cB(...args)]); }; function createKey(prefix2, suffix) { return prefix2 + (suffix === "default" ? "" : suffix.replace(/^[a-z]/, startChar => startChar.toUpperCase())); } let onceCbs = []; const paramsMap = new WeakMap(); function flushOnceCallbacks() { onceCbs.forEach(cb => cb(...paramsMap.get(cb))); onceCbs = []; } function beforeNextFrameOnce(cb, ...params) { paramsMap.set(cb, params); if (onceCbs.includes(cb)) return; onceCbs.push(cb) === 1 && requestAnimationFrame(flushOnceCallbacks); } function getParentNode$1(node) { // document type if (node.nodeType === 9) { return null; } return node.parentNode; } function getScrollParent$1(node) { if (node === null) return null; const parentNode = getParentNode$1(node); if (parentNode === null) { return null; } // Document if (parentNode.nodeType === 9) { return document.documentElement; } // Element if (parentNode.nodeType === 1) { // Firefox want us to check `-x` and `-y` variations as well const { overflow, overflowX, overflowY } = getComputedStyle(parentNode); if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) { return parentNode; } } return getScrollParent$1(parentNode); } function unwrapElement(target) { if (typeof target === 'string') return document.querySelector(target); if (typeof target === 'function') return target(); return target; } function happensIn(e, dataSetPropName) { let { target } = e; while (target) { if (target.dataset) { if (target.dataset[dataSetPropName] !== undefined) return true; } target = target.parentElement; } return false; } function getPreciseEventTarget(event) { return event.composedPath()[0] || null; } function parseResponsiveProp(reponsiveProp) { if (typeof reponsiveProp === "number") { return { '': reponsiveProp.toString() }; } const params = {}; reponsiveProp.split(/ +/).forEach(pairLiteral => { if (pairLiteral === '') return; const [prefix, value] = pairLiteral.split(':'); if (value === undefined) { params[''] = prefix; } else { params[prefix] = value; } }); return params; } function parseResponsivePropValue(reponsiveProp, activeKeyOrSize) { var _a; if (reponsiveProp === undefined || reponsiveProp === null) return undefined; const classObj = parseResponsiveProp(reponsiveProp); if (activeKeyOrSize === undefined) return classObj['']; if (typeof activeKeyOrSize === 'string') { return (_a = classObj[activeKeyOrSize]) !== null && _a !== void 0 ? _a : classObj['']; } else if (Array.isArray(activeKeyOrSize)) { for (let i = activeKeyOrSize.length - 1; i >= 0; --i) { const key = activeKeyOrSize[i]; if (key in classObj) return classObj[key]; } return classObj['']; } else { // Here we suppose all the keys are number formatted let activeValue = undefined; let activeKey = -1; Object.keys(classObj).forEach(key => { const keyAsNum = Number(key); if (!Number.isNaN(keyAsNum) && activeKeyOrSize >= keyAsNum && keyAsNum >= activeKey) { activeKey = keyAsNum; activeValue = classObj[key]; } }); return activeValue; } } function depx(value) { if (typeof value === 'string') { if (value.endsWith('px')) { return Number(value.slice(0, value.length - 2)); } return Number(value); } return value; } function pxfy(value) { if (value === undefined || value === null) return undefined; if (typeof value === 'number') return `${value}px`; if (value.endsWith('px')) return value; return `${value}px`; } function getMargin(value, position) { const parts = value.trim().split(/\s+/g); const margin = { top: parts[0] }; switch (parts.length) { case 1: margin.right = parts[0]; margin.bottom = parts[0]; margin.left = parts[0]; break; case 2: margin.right = parts[1]; margin.left = parts[1]; margin.bottom = parts[0]; break; case 3: margin.right = parts[1]; margin.bottom = parts[2]; margin.left = parts[1]; break; case 4: margin.right = parts[1]; margin.bottom = parts[2]; margin.left = parts[3]; break; default: throw new Error('[seemly/getMargin]:' + value + ' is not a valid value.'); } if (position === undefined) return margin; return margin[position]; } function getGap(value, orient) { const [rowGap, colGap] = value.split(' '); return { row: rowGap, col: colGap || rowGap }; } // src: https://www.w3schools.com/colors/colors_names.asp var colors = { aliceblue: "#F0F8FF", antiquewhite: "#FAEBD7", aqua: "#0FF", aquamarine: "#7FFFD4", azure: "#F0FFFF", beige: "#F5F5DC", bisque: "#FFE4C4", black: "#000", blanchedalmond: "#FFEBCD", blue: "#00F", blueviolet: "#8A2BE2", brown: "#A52A2A", burlywood: "#DEB887", cadetblue: "#5F9EA0", chartreuse: "#7FFF00", chocolate: "#D2691E", coral: "#FF7F50", cornflowerblue: "#6495ED", cornsilk: "#FFF8DC", crimson: "#DC143C", cyan: "#0FF", darkblue: "#00008B", darkcyan: "#008B8B", darkgoldenrod: "#B8860B", darkgray: "#A9A9A9", darkgrey: "#A9A9A9", darkgreen: "#006400", darkkhaki: "#BDB76B", darkmagenta: "#8B008B", darkolivegreen: "#556B2F", darkorange: "#FF8C00", darkorchid: "#9932CC", darkred: "#8B0000", darksalmon: "#E9967A", darkseagreen: "#8FBC8F", darkslateblue: "#483D8B", darkslategray: "#2F4F4F", darkslategrey: "#2F4F4F", darkturquoise: "#00CED1", darkviolet: "#9400D3", deeppink: "#FF1493", deepskyblue: "#00BFFF", dimgray: "#696969", dimgrey: "#696969", dodgerblue: "#1E90FF", firebrick: "#B22222", floralwhite: "#FFFAF0", forestgreen: "#228B22", fuchsia: "#F0F", gainsboro: "#DCDCDC", ghostwhite: "#F8F8FF", gold: "#FFD700", goldenrod: "#DAA520", gray: "#808080", grey: "#808080", green: "#008000", greenyellow: "#ADFF2F", honeydew: "#F0FFF0", hotpink: "#FF69B4", indianred: "#CD5C5C", indigo: "#4B0082", ivory: "#FFFFF0", khaki: "#F0E68C", lavender: "#E6E6FA", lavenderblush: "#FFF0F5", lawngreen: "#7CFC00", lemonchiffon: "#FFFACD", lightblue: "#ADD8E6", lightcoral: "#F08080", lightcyan: "#E0FFFF", lightgoldenrodyellow: "#FAFAD2", lightgray: "#D3D3D3", lightgrey: "#D3D3D3", lightgreen: "#90EE90", lightpink: "#FFB6C1", lightsalmon: "#FFA07A", lightseagreen: "#20B2AA", lightskyblue: "#87CEFA", lightslategray: "#778899", lightslategrey: "#778899", lightsteelblue: "#B0C4DE", lightyellow: "#FFFFE0", lime: "#0F0", limegreen: "#32CD32", linen: "#FAF0E6", magenta: "#F0F", maroon: "#800000", mediumaquamarine: "#66CDAA", mediumblue: "#0000CD", mediumorchid: "#BA55D3", mediumpurple: "#9370DB", mediumseagreen: "#3CB371", mediumslateblue: "#7B68EE", mediumspringgreen: "#00FA9A", mediumturquoise: "#48D1CC", mediumvioletred: "#C71585", midnightblue: "#191970", mintcream: "#F5FFFA", mistyrose: "#FFE4E1", moccasin: "#FFE4B5", navajowhite: "#FFDEAD", navy: "#000080", oldlace: "#FDF5E6", olive: "#808000", olivedrab: "#6B8E23", orange: "#FFA500", orangered: "#FF4500", orchid: "#DA70D6", palegoldenrod: "#EEE8AA", palegreen: "#98FB98", paleturquoise: "#AFEEEE", palevioletred: "#DB7093", papayawhip: "#FFEFD5", peachpuff: "#FFDAB9", peru: "#CD853F", pink: "#FFC0CB", plum: "#DDA0DD", powderblue: "#B0E0E6", purple: "#800080", rebeccapurple: "#663399", red: "#F00", rosybrown: "#BC8F8F", royalblue: "#4169E1", saddlebrown: "#8B4513", salmon: "#FA8072", sandybrown: "#F4A460", seagreen: "#2E8B57", seashell: "#FFF5EE", sienna: "#A0522D", silver: "#C0C0C0", skyblue: "#87CEEB", slateblue: "#6A5ACD", slategray: "#708090", slategrey: "#708090", snow: "#FFFAFA", springgreen: "#00FF7F", steelblue: "#4682B4", tan: "#D2B48C", teal: "#008080", thistle: "#D8BFD8", tomato: "#FF6347", turquoise: "#40E0D0", violet: "#EE82EE", wheat: "#F5DEB3", white: "#FFF", whitesmoke: "#F5F5F5", yellow: "#FF0", yellowgreen: "#9ACD32", transparent: "#0000" }; // All the algorithms credit to https://stackoverflow.com/questions/36721830/convert-hsl-to-rgb-and-hex/54014428#54014428 // original author: Kamil Kiełczewski /** * @param h 360 * @param s 100 * @param l 100 * @returns [h, s, v] 360, 100, 100 */ function hsl2hsv(h, s, l) { s /= 100; l /= 100; const v = s * Math.min(l, 1 - l) + l; return [h, v ? (2 - 2 * l / v) * 100 : 0, v * 100]; } /** * @param h 360 * @param s 100 * @param v 100 * @returns [h, s, l] 360, 100, 100 */ function hsv2hsl(h, s, v) { s /= 100; v /= 100; const l = v - v * s / 2; const m = Math.min(l, 1 - l); return [h, m ? (v - l) / m * 100 : 0, l * 100]; } /** * @param h 360 * @param s 100 * @param v 100 * @returns [r, g, b] 255, 255, 255 */ function hsv2rgb(h, s, v) { s /= 100; v /= 100; let f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0); return [f(5) * 255, f(3) * 255, f(1) * 255]; } /** * @param r 255 * @param g 255 * @param b 255 * @returns [360, 100, 100] */ function rgb2hsv(r, g, b) { r /= 255; g /= 255; b /= 255; let v = Math.max(r, g, b), c = v - Math.min(r, g, b); let h = c && (v == r ? (g - b) / c : v == g ? 2 + (b - r) / c : 4 + (r - g) / c); return [60 * (h < 0 ? h + 6 : h), v && c / v * 100, v * 100]; } /** * @param r 255 * @param g 255 * @param b 255 * @returns [360, 100, 100] */ function rgb2hsl(r, g, b) { r /= 255; g /= 255; b /= 255; let v = Math.max(r, g, b), c = v - Math.min(r, g, b), f = 1 - Math.abs(v + v - c - 1); let h = c && (v == r ? (g - b) / c : v == g ? 2 + (b - r) / c : 4 + (r - g) / c); return [60 * (h < 0 ? h + 6 : h), f ? c / f * 100 : 0, (v + v - c) * 50]; } /** * @param h 360 * @param s 100 * @param l 100 * @returns [255, 255, 255] */ function hsl2rgb(h, s, l) { s /= 100; l /= 100; let a = s * Math.min(l, 1 - l); let f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); return [f(0) * 255, f(8) * 255, f(4) * 255]; } const prefix = '^\\s*'; const suffix = '\\s*$'; const percent = '\\s*((\\.\\d+)|(\\d+(\\.\\d*)?))%\\s*'; // 4 offset const float = '\\s*((\\.\\d+)|(\\d+(\\.\\d*)?))\\s*'; // 4 offset const hex = '([0-9A-Fa-f])'; const dhex = '([0-9A-Fa-f]{2})'; const hslRegex = new RegExp(`${prefix}hsl\\s*\\(${float},${percent},${percent}\\)${suffix}`); const hsvRegex = new RegExp(`${prefix}hsv\\s*\\(${float},${percent},${percent}\\)${suffix}`); const hslaRegex = new RegExp(`${prefix}hsla\\s*\\(${float},${percent},${percent},${float}\\)${suffix}`); const hsvaRegex = new RegExp(`${prefix}hsva\\s*\\(${float},${percent},${percent},${float}\\)${suffix}`); const rgbRegex = new RegExp(`${prefix}rgb\\s*\\(${float},${float},${float}\\)${suffix}`); const rgbaRegex = new RegExp(`${prefix}rgba\\s*\\(${float},${float},${float},${float}\\)${suffix}`); const sHexRegex = new RegExp(`${prefix}#${hex}${hex}${hex}${suffix}`); const hexRegex = new RegExp(`${prefix}#${dhex}${dhex}${dhex}${suffix}`); const sHexaRegex = new RegExp(`${prefix}#${hex}${hex}${hex}${hex}${suffix}`); const hexaRegex = new RegExp(`${prefix}#${dhex}${dhex}${dhex}${dhex}${suffix}`); function parseHex(value) { return parseInt(value, 16); } /** * Convert color string to hsla array * @param color format like hsl(180, 100%, 100%), hsla(180, 100%, 100%, 1) * @returns */ function hsla(color) { try { let i; if (i = hslaRegex.exec(color)) { return [roundDeg(i[1]), roundPercent(i[5]), roundPercent(i[9]), roundAlpha(i[13])]; } else if (i = hslRegex.exec(color)) { return [roundDeg(i[1]), roundPercent(i[5]), roundPercent(i[9]), 1]; } throw new Error(`[seemly/hsla]: Invalid color value ${color}.`); } catch (e) { throw e; } } /** * Convert color string to hsva array * @param color format like hsv(180, 100%, 100%), hsva(180, 100%, 100%, 1) * @returns */ function hsva(color) { try { let i; if (i = hsvaRegex.exec(color)) { return [roundDeg(i[1]), roundPercent(i[5]), roundPercent(i[9]), roundAlpha(i[13])]; } else if (i = hsvRegex.exec(color)) { return [roundDeg(i[1]), roundPercent(i[5]), roundPercent(i[9]), 1]; } throw new Error(`[seemly/hsva]: Invalid color value ${color}.`); } catch (e) { throw e; } } /** * Convert color string to rgba array. * @param color format like #000[0], #000000[00], rgb(0, 0, 0), * rgba(0, 0, 0, 0), hsl(a) color, hsv(a) color and color keywords and * transparent * @returns */ function rgba(color) { try { let i; if (i = hexRegex.exec(color)) { return [parseHex(i[1]), parseHex(i[2]), parseHex(i[3]), 1]; } else if (i = rgbRegex.exec(color)) { return [roundChannel(i[1]), roundChannel(i[5]), roundChannel(i[9]), 1]; } else if (i = rgbaRegex.exec(color)) { return [roundChannel(i[1]), roundChannel(i[5]), roundChannel(i[9]), roundAlpha(i[13])]; } else if (i = sHexRegex.exec(color)) { return [parseHex(i[1] + i[1]), parseHex(i[2] + i[2]), parseHex(i[3] + i[3]), 1]; } else if (i = hexaRegex.exec(color)) { return [parseHex(i[1]), parseHex(i[2]), parseHex(i[3]), roundAlpha(parseHex(i[4]) / 255)]; } else if (i = sHexaRegex.exec(color)) { return [parseHex(i[1] + i[1]), parseHex(i[2] + i[2]), parseHex(i[3] + i[3]), roundAlpha(parseHex(i[4] + i[4]) / 255)]; } else if (color in colors) { return rgba(colors[color]); } else if (hslRegex.test(color) || hslaRegex.test(color)) { const [h, s, l, a] = hsla(color); return [...hsl2rgb(h, s, l), a]; } else if (hsvRegex.test(color) || hsvaRegex.test(color)) { const [h, s, v, a] = hsva(color); return [...hsv2rgb(h, s, v), a]; } throw new Error(`[seemly/rgba]: Invalid color value ${color}.`); } catch (e) { throw e; } } function normalizeAlpha$1(alphaValue) { return alphaValue > 1 ? 1 : alphaValue < 0 ? 0 : alphaValue; } function stringifyRgb(r, g, b) { return `rgb(${roundChannel(r)}, ${roundChannel(g)}, ${roundChannel(b)})`; } function stringifyRgba(r, g, b, a) { return `rgba(${roundChannel(r)}, ${roundChannel(g)}, ${roundChannel(b)}, ${normalizeAlpha$1(a)})`; } function compositeChannel(v1, a1, v2, a2, a) { return roundChannel((v1 * a1 * (1 - a2) + v2 * a2) / a); } function composite(background, overlay) { if (!Array.isArray(background)) background = rgba(background); if (!Array.isArray(overlay)) overlay = rgba(overlay); const a1 = background[3]; const a2 = overlay[3]; const alpha = roundAlpha(a1 + a2 - a1 * a2); return stringifyRgba(compositeChannel(background[0], a1, overlay[0], a2, alpha), compositeChannel(background[1], a1, overlay[1], a2, alpha), compositeChannel(background[2], a1, overlay[2], a2, alpha), alpha); } function changeColor(base, options) { const [r, g, b, a = 1] = Array.isArray(base) ? base : rgba(base); if (typeof options.alpha === 'number') { return stringifyRgba(r, g, b, options.alpha); } return stringifyRgba(r, g, b, a); } function scaleColor(base, options) { const [r, g, b, a = 1] = Array.isArray(base) ? base : rgba(base); const { lightness = 1, alpha = 1 } = options; return toRgbaString([r * lightness, g * lightness, b * lightness, a * alpha]); } function roundAlpha(value) { const v = Math.round(Number(value) * 100) / 100; if (v > 1) return 1; if (v < 0) return 0; return v; } function roundDeg(value) { const v = Math.round(Number(value)); if (v >= 360) return 0; if (v < 0) return 0; return v; } function roundChannel(value) { const v = Math.round(Number(value)); if (v > 255) return 255; if (v < 0) return 0; return v; } function roundPercent(value) { const v = Math.round(Number(value)); if (v > 100) return 100; if (v < 0) return 0; return v; } function toRgbString(base) { const [r, g, b] = Array.isArray(base) ? base : rgba(base); return stringifyRgb(r, g, b); } function toRgbaString(base) { const [r, g, b] = base; if (3 in base) { return `rgba(${roundChannel(r)}, ${roundChannel(g)}, ${roundChannel(b)}, ${roundAlpha(base[3])})`; } return `rgba(${roundChannel(r)}, ${roundChannel(g)}, ${roundChannel(b)}, 1)`; } function toHsvString(base) { return `hsv(${roundDeg(base[0])}, ${roundPercent(base[1])}%, ${roundPercent(base[2])}%)`; } function toHsvaString(base) { const [h, s, v] = base; if (3 in base) { return `hsva(${roundDeg(h)}, ${roundPercent(s)}%, ${roundPercent(v)}%, ${roundAlpha(base[3])})`; } return `hsva(${roundDeg(h)}, ${roundPercent(s)}%, ${roundPercent(v)}%, 1)`; } function toHslString(base) { return `hsl(${roundDeg(base[0])}, ${roundPercent(base[1])}%, ${roundPercent(base[2])}%)`; } function toHslaString(base) { const [h, s, l] = base; if (3 in base) { return `hsla(${roundDeg(h)}, ${roundPercent(s)}%, ${roundPercent(l)}%, ${roundAlpha(base[3])})`; } return `hsla(${roundDeg(h)}, ${roundPercent(s)}%, ${roundPercent(l)}%, 1)`; } /** * * @param base [255, 255, 255, 255], [255, 255, 255], any hex string * @returns */ function toHexaString(base) { if (typeof base === 'string') { let i; if (i = hexRegex.exec(base)) { return `${i[0]}FF`; } else if (i = hexaRegex.exec(base)) { return i[0]; } else if (i = sHexRegex.exec(base)) { return `#${i[1]}${i[1]}${i[2]}${i[2]}${i[3]}${i[3]}FF`; } else if (i = sHexaRegex.exec(base)) { return `#${i[1]}${i[1]}${i[2]}${i[2]}${i[3]}${i[3]}${i[4]}${i[4]}`; } throw new Error(`[seemly/toHexString]: Invalid hex value ${base}.`); } const hex = `#${base.slice(0, 3).map(unit => roundChannel(unit).toString(16).toUpperCase().padStart(2, '0')).join('')}`; const a = base.length === 3 ? 'FF' : roundChannel(base[3] * 255).toString(16).padStart(2, '0').toUpperCase(); return hex + a; } /** * * @param base [255, 255, 255, 255], [255, 255, 255], any hex string * @returns */ function toHexString(base) { if (typeof base === 'string') { let i; if (i = hexRegex.exec(base)) { return i[0]; } else if (i = hexaRegex.exec(base)) { return i[0].slice(0, 7); } else if (i = sHexRegex.exec(base) || sHexaRegex.exec(base)) { return `#${i[1]}${i[1]}${i[2]}${i[2]}${i[3]}${i[3]}`; } throw new Error(`[seemly/toHexString]: Invalid hex value ${base}.`); } return `#${base.slice(0, 3).map(unit => roundChannel(unit).toString(16).toUpperCase().padStart(2, '0')).join('')}`; } function createId(length = 8) { return Math.random().toString(16).slice(2, 2 + length); } function repeat(count, v) { const ret = []; for (let i = 0; i < count; ++i) { ret.push(v); } return ret; } function indexMap(count, createValue) { const ret = []; if (!createValue) { for (let i = 0; i < count; ++i) { ret.push(i); } return ret; } for (let i = 0; i < count; ++i) { ret.push(createValue(i)); } return ret; } function getEventTarget(e) { const path = e.composedPath(); return path[0]; } const traps = { mousemoveoutside: new WeakMap(), clickoutside: new WeakMap() }; function createTrapHandler(name, el, originalHandler) { if (name === 'mousemoveoutside') { const moveHandler = e => { if (el.contains(getEventTarget(e))) return; originalHandler(e); }; return { mousemove: moveHandler, touchstart: moveHandler }; } else if (name === 'clickoutside') { let mouseDownOutside = false; const downHandler = e => { mouseDownOutside = !el.contains(getEventTarget(e)); }; const upHanlder = e => { if (!mouseDownOutside) return; if (el.contains(getEventTarget(e))) return; originalHandler(e); }; return { mousedown: downHandler, mouseup: upHanlder, touchstart: downHandler, touchend: upHanlder }; } console.error( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `[evtd/create-trap-handler]: name \`${name}\` is invalid. This could be a bug of evtd.`); return {}; } function ensureTrapHandlers(name, el, handler) { const handlers = traps[name]; let elHandlers = handlers.get(el); if (elHandlers === undefined) { handlers.set(el, elHandlers = new WeakMap()); } let trapHandler = elHandlers.get(handler); if (trapHandler === undefined) { elHandlers.set(handler, trapHandler = createTrapHandler(name, el, handler)); } return trapHandler; } function trapOn(name, el, handler, options) { if (name === 'mousemoveoutside' || name === 'clickoutside') { const trapHandlers = ensureTrapHandlers(name, el, handler); Object.keys(trapHandlers).forEach(key => { on(key, document, trapHandlers[key], options); }); return true; } return false; } function trapOff(name, el, handler, options) { if (name === 'mousemoveoutside' || name === 'clickoutside') { const trapHandlers = ensureTrapHandlers(name, el, handler); Object.keys(trapHandlers).forEach(key => { off(key, document, trapHandlers[key], options); }); return true; } return false; } // currently `once` and `passive` is not supported function createDelegate() { if (typeof window === 'undefined') { return { on: () => {}, off: () => {} }; } const propagationStopped = new WeakMap(); const immediatePropagationStopped = new WeakMap(); function trackPropagation() { propagationStopped.set(this, true); } function trackImmediate() { propagationStopped.set(this, true); immediatePropagationStopped.set(this, true); } function spy(event, propName, fn) { const source = event[propName]; event[propName] = function () { fn.apply(event, arguments); return source.apply(event, arguments); }; return event; } function unspy(event, propName) { event[propName] = Event.prototype[propName]; } const currentTargets = new WeakMap(); const currentTargetDescriptor = Object.getOwnPropertyDescriptor(Event.prototype, 'currentTarget'); function getCurrentTarget() { var _a; return (_a = currentTargets.get(this)) !== null && _a !== void 0 ? _a : null; } function defineCurrentTarget(event, getter) { if (currentTargetDescriptor === undefined) return; Object.defineProperty(event, 'currentTarget', { configurable: true, enumerable: true, get: getter !== null && getter !== void 0 ? getter : currentTargetDescriptor.get }); } const phaseToTypeToElToHandlers = { bubble: {}, capture: {} }; const typeToWindowEventHandlers = {}; function createUnifiedHandler() { const delegeteHandler = function (e) { const { type, eventPhase, bubbles } = e; const target = getEventTarget(e); if (eventPhase === 2) return; const phase = eventPhase === 1 ? 'capture' : 'bubble'; let cursor = target; const path = []; // collecting bubble path while (true) { if (cursor === null) cursor = window; path.push(cursor); if (cursor === window) { break; } // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions cursor = cursor.parentNode || null; } const captureElToHandlers = phaseToTypeToElToHandlers.capture[type]; const bubbleElToHandlers = phaseToTypeToElToHandlers.bubble[type]; spy(e, 'stopPropagation', trackPropagation); spy(e, 'stopImmediatePropagation', trackImmediate); defineCurrentTarget(e, getCurrentTarget); if (phase === 'capture') { if (captureElToHandlers === undefined) return; // capture for (let i = path.length - 1; i >= 0; --i) { if (propagationStopped.has(e)) break; const target = path[i]; const handlers = captureElToHandlers.get(target); if (handlers !== undefined) { currentTargets.set(e, target); for (const handler of handlers) { if (immediatePropagationStopped.has(e)) break; handler(e); } } if (i === 0 && !bubbles && bubbleElToHandlers !== undefined) { const bubbleHandlers = bubbleElToHandlers.get(target); if (bubbleHandlers !== undefined) { for (const handler of bubbleHandlers) { if (immediatePropagationStopped.has(e)) break; handler(e); } } } } } else if (phase === 'bubble') { if (bubbleElToHandlers === undefined) return; // bubble for (let i = 0; i < path.length; ++i) { if (propagationStopped.has(e)) break; const target = path[i]; const handlers = bubbleElToHandlers.get(target); if (handlers !== undefined) { currentTargets.set(e, target); for (const handler of handlers) { if (immediatePropagationStopped.has(e)) break; handler(e); } } } } unspy(e, 'stopPropagation'); unspy(e, 'stopImmediatePropagation'); defineCurrentTarget(e); }; delegeteHandler.displayName = 'evtdUnifiedHandler'; return delegeteHandler; } function createUnifiedWindowEventHandler() { const delegateHandler = function (e) { const { type, eventPhase } = e; if (eventPhase !== 2) return; const handlers = typeToWindowEventHandlers[type]; if (handlers === undefined) return; handlers.forEach(handler => handler(e)); }; delegateHandler.displayName = 'evtdUnifiedWindowEventHandler'; return delegateHandler; } const unifiedHandler = createUnifiedHandler(); const unfiendWindowEventHandler = createUnifiedWindowEventHandler(); function ensureElToHandlers(phase, type) { const phaseHandlers = phaseToTypeToElToHandlers[phase]; if (phaseHandlers[type] === undefined) { phaseHandlers[type] = new Map(); window.addEventListener(type, unifiedHandler, phase === 'capture'); } return phaseHandlers[type]; } function ensureWindowEventHandlers(type) { const windowEventHandlers = typeToWindowEventHandlers[type]; if (windowEventHandlers === undefined) { typeToWindowEventHandlers[type] = new Set(); window.addEventListener(type, unfiendWindowEventHandler); } return typeToWindowEventHandlers[type]; } function ensureHandlers(elToHandlers, el) { let elHandlers = elToHandlers.get(el); if (elHandlers === undefined) { elToHandlers.set(el, elHandlers = new Set()); } return elHandlers; } function handlerExist(el, phase, type, handler) { const elToHandlers = phaseToTypeToElToHandlers[phase][type]; // phase ${type} event has handlers if (elToHandlers !== undefined) { const handlers = elToHandlers.get(el); // phase using el with ${type} event has handlers if (handlers !== undefined) { if (handlers.has(handler)) return true; } } return false; } function windowEventHandlerExist(type, handler) { const handlers = typeToWindowEventHandlers[type]; if (handlers !== undefined) { if (handlers.has(handler)) { return true; } } return false; } function on(type, el, handler, options) { let mergedHandler; if (typeof options === 'object' && options.once === true) { mergedHandler = e => { off(type, el, mergedHandler, options); handler(e); }; } else { mergedHandler = handler; } const trapped = trapOn(type, el, mergedHandler, options); if (trapped) return; const phase = options === true || typeof options === 'object' && options.capture === true ? 'capture' : 'bubble'; const elToHandlers = ensureElToHandlers(phase, type); const handlers = ensureHandlers(elToHandlers, el); if (!handlers.has(mergedHandler)) handlers.add(mergedHandler); if (el === window) { const windowEventHandlers = ensureWindowEventHandlers(type); if (!windowEventHandlers.has(mergedHandler)) { windowEventHandlers.add(mergedHandler); } } } function off(type, el, handler, options) { const trapped = trapOff(type, el, handler, options); if (trapped) return; const capture = options === true || typeof options === 'object' && options.capture === true; const phase = capture ? 'capture' : 'bubble'; const elToHandlers = ensureElToHandlers(phase, type); const handlers = ensureHandlers(elToHandlers, el); if (el === window) { const mirrorPhase = capture ? 'bubble' : 'capture'; if (!handlerExist(el, mirrorPhase, type, handler) && windowEventHandlerExist(type, handler)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const windowEventHandlers = typeToWindowEventHandlers[type]; windowEventHandlers.delete(handler); if (windowEventHandlers.size === 0) { window.removeEventListener(type, unfiendWindowEventHandler); typeToWindowEventHandlers[type] = undefined; } } } if (handlers.has(handler)) handlers.delete(handler); if (handlers.size === 0) { elToHandlers.delete(el); } if (elToHandlers.size === 0) { window.removeEventListener(type, unifiedHandler, phase === 'capture'); phaseToTypeToElToHandlers[phase][type] = undefined; } } return { on: on, off: off }; } const { on, off } = createDelegate(); function useFalseUntilTruthy(originalRef) { const currentRef = ref(!!originalRef.value); if (currentRef.value) return readonly(currentRef); const stop = watch(originalRef, value => { if (value) { currentRef.value = true; stop(); } }); return readonly(currentRef); } function useMemo(getterOrOptions) { const computedValueRef = computed(getterOrOptions); // Maybe it's not possible to lazy evaluate the value, since we can't make // render phase capture the deps behind useMemo const valueRef = ref(computedValueRef.value); watch(computedValueRef, value => { valueRef.value = value; }); if (typeof getterOrOptions === 'function') { return valueRef; } else { return { __v_isRef: true, get value() { return valueRef.value; }, set value(v) { getterOrOptions.set(v); } }; } } function hasInstance() { return getCurrentInstance() !== null; } const isBrowser$2 = typeof window !== 'undefined'; let fontsReady; let isFontReady; const init$1 = () => { var _a, _b; fontsReady = isBrowser$2 ? (_b = (_a = document) === null || _a === void 0 ? void 0 : _a.fonts) === null || _b === void 0 ? void 0 : _b.ready : undefined; isFontReady = false; /* istanbul ignore if */ if (fontsReady !== undefined) { void fontsReady.then(() => { isFontReady = true; }); } else { isFontReady = true; } }; init$1(); /** * Call callback on fontsReady is resolved. If fontsReady is already resolved, * callback won't be called. */ function onFontsReady(cb) { /* istanbul ignore next */ if (isFontReady) return; let deactivated = false; onMounted(() => { /* istanbul ignore next */ if (!isFontReady) { fontsReady === null || fontsReady === void 0 ? void 0 : fontsReady.then(() => { if (deactivated) return; cb(); }); } }); onBeforeUnmount(() => { deactivated = true; }); } const mousePositionRef = ref(null); function clickHandler(e) { if (e.clientX > 0 || e.clientY > 0) { mousePositionRef.value = { x: e.clientX, y: e.clientY }; } else { // x = 0 & y = 0 const {