From 90c94338e3f5c95d2818783fdfebbee57806fd5e Mon Sep 17 00:00:00 2001 From: Glenn Verschooren Date: Tue, 17 Sep 2024 15:23:25 +0200 Subject: [PATCH 1/5] chore: upgrade stencil to v4.21.0 Upgarde stencil core to v4.21.0. This is need because we need the new features inside the generated hydration script. --- libs/output-target-angular/package-lock.json | 2 +- libs/output-target-angular/package.json | 2 +- .../src/lib/generate-value-accessors.ts | 5 +- .../src/lib/output-angular.ts | 1 + libs/output-target-web/package.json | 2 +- package-lock.json | 49 ++++++++++++++++--- package.json | 2 +- 7 files changed, 51 insertions(+), 12 deletions(-) diff --git a/libs/output-target-angular/package-lock.json b/libs/output-target-angular/package-lock.json index d865283d81..1da558be08 100644 --- a/libs/output-target-angular/package-lock.json +++ b/libs/output-target-angular/package-lock.json @@ -10,7 +10,7 @@ "dependencies": { "@angular/core": "~15.0.0", "@angular/forms": "~15.0.0", - "@stencil/core": "~4.11.0", + "@stencil/core": "~4.21.0", "rxjs": "^7.8.1", "tslib": "^2.3.0" } diff --git a/libs/output-target-angular/package.json b/libs/output-target-angular/package.json index 7b1997acec..92e8393322 100644 --- a/libs/output-target-angular/package.json +++ b/libs/output-target-angular/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { - "@stencil/core": "~4.11.0", + "@stencil/core": "~4.21.0", "tslib": "~2.3.0" }, "type": "commonjs", diff --git a/libs/output-target-angular/src/lib/generate-value-accessors.ts b/libs/output-target-angular/src/lib/generate-value-accessors.ts index 968d2b02c4..022e364034 100644 --- a/libs/output-target-angular/src/lib/generate-value-accessors.ts +++ b/libs/output-target-angular/src/lib/generate-value-accessors.ts @@ -1,6 +1,6 @@ import { dirname, join } from 'path' import type { OutputTargetAngular, ValueAccessorTypes } from './types' -import type { CompilerCtx, ComponentCompilerMeta, Config } from '@stencil/core/internal' +import type { CompilerCtx, ComponentCompilerMeta, Config, CopyTask } from '@stencil/core/internal' interface ValueAccessor { elementSelectors: string[] @@ -78,12 +78,13 @@ function copyResources(config: Config, resourcesFilesToCopy: string[], directory if (!config.sys || !config.sys.copy) { throw new Error('stencil is not properly intialized at this step. Notify the developer') } - const copyTasks = resourcesFilesToCopy.map(rf => { + const copyTasks: Required[] = resourcesFilesToCopy.map(rf => { return { src: join(__dirname, '../../../resources/control-value-accessors/', rf), dest: join(directory, rf), keepDirStructure: false, warn: false, + ignore: [], } }) return config.sys.copy(copyTasks, join(directory)) diff --git a/libs/output-target-angular/src/lib/output-angular.ts b/libs/output-target-angular/src/lib/output-angular.ts index 080dd0a746..425da1e241 100644 --- a/libs/output-target-angular/src/lib/output-angular.ts +++ b/libs/output-target-angular/src/lib/output-angular.ts @@ -58,6 +58,7 @@ async function copyResources(config: Config, outputTarget: OutputTargetAngular) dest: destDirectory, keepDirStructure: false, warn: false, + ignore: [], }, ], srcDirectory, diff --git a/libs/output-target-web/package.json b/libs/output-target-web/package.json index 92c417091e..fd0b8bcfe7 100644 --- a/libs/output-target-web/package.json +++ b/libs/output-target-web/package.json @@ -4,7 +4,7 @@ "private": true, "dependencies": { "tslib": "~2.3.0", - "@stencil/core": "~4.11.0", + "@stencil/core": "~4.21.0", "fs-extra": "11.2.0", "replace-in-file": "~7.1.0" }, diff --git a/package-lock.json b/package-lock.json index 48dddbb4b7..3ecdec6e5c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -51,7 +51,7 @@ "@nx/web": "~18.0.4", "@nxkit/style-dictionary": "~5.0.0", "@schematics/angular": "~15.0.0", - "@stencil/core": "~4.11.0", + "@stencil/core": "~4.21.0", "@stencil/sass": "~3.0.8", "@swc-node/register": "~1.8.0", "@swc/cli": "~0.1.62", @@ -350,7 +350,7 @@ "name": "@baloise/output-target-angular", "version": "0.0.0", "dependencies": { - "@stencil/core": "~4.11.0", + "@stencil/core": "~4.21.0", "tslib": "~2.3.0" } }, @@ -366,6 +366,18 @@ "react-dom": "~18.2.0" } }, + "libs/output-target-react/node_modules/@stencil/core": { + "version": "4.11.0", + "resolved": "https://registry.npmjs.org/@stencil/core/-/core-4.11.0.tgz", + "integrity": "sha512-zsKhgIkTGo+s7IthitxR/MKiMS3Ck1yIypOdXr0aE6ofboKqe9NdffTcxZ0vel0wD2bZYOb6WfPMzuhRKk6+FA==", + "bin": { + "stencil": "bin/stencil" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=7.10.0" + } + }, "libs/output-target-vue": { "name": "@baloise/output-target-vue", "version": "0.0.0", @@ -374,11 +386,23 @@ "tslib": "~2.3.0" } }, + "libs/output-target-vue/node_modules/@stencil/core": { + "version": "4.11.0", + "resolved": "https://registry.npmjs.org/@stencil/core/-/core-4.11.0.tgz", + "integrity": "sha512-zsKhgIkTGo+s7IthitxR/MKiMS3Ck1yIypOdXr0aE6ofboKqe9NdffTcxZ0vel0wD2bZYOb6WfPMzuhRKk6+FA==", + "bin": { + "stencil": "bin/stencil" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=7.10.0" + } + }, "libs/output-target-web": { "name": "@baloise/output-target-web", "version": "0.0.0", "dependencies": { - "@stencil/core": "~4.11.0", + "@stencil/core": "~4.21.0", "fs-extra": "11.2.0", "replace-in-file": "~7.1.0", "tslib": "~2.3.0" @@ -12160,9 +12184,10 @@ } }, "node_modules/@stencil/core": { - "version": "4.11.0", - "resolved": "https://registry.npmjs.org/@stencil/core/-/core-4.11.0.tgz", - "integrity": "sha512-zsKhgIkTGo+s7IthitxR/MKiMS3Ck1yIypOdXr0aE6ofboKqe9NdffTcxZ0vel0wD2bZYOb6WfPMzuhRKk6+FA==", + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/@stencil/core/-/core-4.21.0.tgz", + "integrity": "sha512-v50lnVbzS8mpMSnEVxR+G75XpvxHKtkJaQrNPE8+/fF6Ppr5z4bcdcBhcP8LPfEW+4BZcic6VifMXRwTopc+kw==", + "dev": true, "bin": { "stencil": "bin/stencil" }, @@ -48734,6 +48759,18 @@ "@baloise/output-target-web": "0.0.0" } }, + "packages/core/node_modules/@stencil/core": { + "version": "4.11.0", + "resolved": "https://registry.npmjs.org/@stencil/core/-/core-4.11.0.tgz", + "integrity": "sha512-zsKhgIkTGo+s7IthitxR/MKiMS3Ck1yIypOdXr0aE6ofboKqe9NdffTcxZ0vel0wD2bZYOb6WfPMzuhRKk6+FA==", + "bin": { + "stencil": "bin/stencil" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=7.10.0" + } + }, "packages/core/node_modules/big.js": { "version": "6.2.1", "license": "MIT", diff --git a/package.json b/package.json index 3656add626..17f149ece1 100644 --- a/package.json +++ b/package.json @@ -67,7 +67,7 @@ "@nx/web": "~18.0.4", "@nxkit/style-dictionary": "~5.0.0", "@schematics/angular": "~15.0.0", - "@stencil/core": "~4.11.0", + "@stencil/core": "~4.21.0", "@stencil/sass": "~3.0.8", "@swc-node/register": "~1.8.0", "@swc/cli": "~0.1.62", From 3c15726f4591dfa31525c919d674513651101ae0 Mon Sep 17 00:00:00 2001 From: Glenn Verschooren Date: Tue, 17 Sep 2024 15:25:17 +0200 Subject: [PATCH 2/5] feat: add output target `dist-hydration-script` and test the generated hydration script --- packages/core/hydrate/index.js | 92121 ++++++++++++++++ packages/core/hydrate/index.mjs | 92113 +++++++++++++++ .../bal-checkbox-group/bal-checkbox-group.tsx | 4 +- .../bal-radio-group/bal-radio-group.tsx | 4 +- packages/core/stencil.config.ts | 4 + 5 files changed, 184242 insertions(+), 4 deletions(-) create mode 100644 packages/core/hydrate/index.js create mode 100644 packages/core/hydrate/index.mjs diff --git a/packages/core/hydrate/index.js b/packages/core/hydrate/index.js new file mode 100644 index 0000000000..3cf1a699df --- /dev/null +++ b/packages/core/hydrate/index.js @@ -0,0 +1,92121 @@ +'use strict' + +Object.defineProperty(exports, '__esModule', { value: true }) + +var stream = require('stream') + +function hydrateFactory( + $stencilWindow, + $stencilHydrateOpts, + $stencilHydrateResults, + $stencilAfterHydrate, + $stencilHydrateResolve, +) { + var globalThis = $stencilWindow + var self = $stencilWindow + var top = $stencilWindow + var parent = $stencilWindow + + var addEventListener = $stencilWindow.addEventListener.bind($stencilWindow) + var alert = $stencilWindow.alert.bind($stencilWindow) + var blur = $stencilWindow.blur.bind($stencilWindow) + var cancelAnimationFrame = $stencilWindow.cancelAnimationFrame.bind($stencilWindow) + var cancelIdleCallback = $stencilWindow.cancelIdleCallback.bind($stencilWindow) + var clearInterval = $stencilWindow.clearInterval.bind($stencilWindow) + var clearTimeout = $stencilWindow.clearTimeout.bind($stencilWindow) + var close = () => {} + var confirm = $stencilWindow.confirm.bind($stencilWindow) + var dispatchEvent = $stencilWindow.dispatchEvent.bind($stencilWindow) + var focus = $stencilWindow.focus.bind($stencilWindow) + var getComputedStyle = $stencilWindow.getComputedStyle.bind($stencilWindow) + var matchMedia = $stencilWindow.matchMedia.bind($stencilWindow) + var open = $stencilWindow.open.bind($stencilWindow) + var prompt = $stencilWindow.prompt.bind($stencilWindow) + var removeEventListener = $stencilWindow.removeEventListener.bind($stencilWindow) + var requestAnimationFrame = $stencilWindow.requestAnimationFrame.bind($stencilWindow) + var requestIdleCallback = $stencilWindow.requestIdleCallback.bind($stencilWindow) + var setInterval = $stencilWindow.setInterval.bind($stencilWindow) + var setTimeout = $stencilWindow.setTimeout.bind($stencilWindow) + + var CharacterData = $stencilWindow.CharacterData + var CSS = $stencilWindow.CSS + var CustomEvent = $stencilWindow.CustomEvent + var Document = $stencilWindow.Document + var DocumentFragment = $stencilWindow.DocumentFragment + var DocumentType = $stencilWindow.DocumentType + var DOMTokenList = $stencilWindow.DOMTokenList + var Element = $stencilWindow.Element + var Event = $stencilWindow.Event + var HTMLAnchorElement = $stencilWindow.HTMLAnchorElement + var HTMLBaseElement = $stencilWindow.HTMLBaseElement + var HTMLButtonElement = $stencilWindow.HTMLButtonElement + var HTMLCanvasElement = $stencilWindow.HTMLCanvasElement + var HTMLElement = $stencilWindow.HTMLElement + var HTMLFormElement = $stencilWindow.HTMLFormElement + var HTMLImageElement = $stencilWindow.HTMLImageElement + var HTMLInputElement = $stencilWindow.HTMLInputElement + var HTMLLinkElement = $stencilWindow.HTMLLinkElement + var HTMLMetaElement = $stencilWindow.HTMLMetaElement + var HTMLScriptElement = $stencilWindow.HTMLScriptElement + var HTMLStyleElement = $stencilWindow.HTMLStyleElement + var HTMLTemplateElement = $stencilWindow.HTMLTemplateElement + var HTMLTitleElement = $stencilWindow.HTMLTitleElement + var IntersectionObserver = $stencilWindow.IntersectionObserver + var KeyboardEvent = $stencilWindow.KeyboardEvent + var MouseEvent = $stencilWindow.MouseEvent + var Node = $stencilWindow.Node + var NodeList = $stencilWindow.NodeList + var URL = $stencilWindow.URL + + var console = $stencilWindow.console + var customElements = $stencilWindow.customElements + var history = $stencilWindow.history + var localStorage = $stencilWindow.localStorage + var location = $stencilWindow.location + var navigator = $stencilWindow.navigator + var performance = $stencilWindow.performance + var sessionStorage = $stencilWindow.sessionStorage + + var devicePixelRatio = $stencilWindow.devicePixelRatio + var innerHeight = $stencilWindow.innerHeight + var innerWidth = $stencilWindow.innerWidth + var origin = $stencilWindow.origin + var pageXOffset = $stencilWindow.pageXOffset + var pageYOffset = $stencilWindow.pageYOffset + var screen = $stencilWindow.screen + var screenLeft = $stencilWindow.screenLeft + var screenTop = $stencilWindow.screenTop + var screenX = $stencilWindow.screenX + var screenY = $stencilWindow.screenY + var scrollX = $stencilWindow.scrollX + var scrollY = $stencilWindow.scrollY + var exports = {} + + var fetch, FetchError, Headers, Request, Response + + if (typeof $stencilWindow.fetch === 'function') { + fetch = $stencilWindow.fetch + } else { + fetch = $stencilWindow.fetch = function () { + throw new Error('fetch() is not implemented') + } + } + + if (typeof $stencilWindow.FetchError === 'function') { + FetchError = $stencilWindow.FetchError + } else { + FetchError = $stencilWindow.FetchError = class FetchError { + constructor() { + throw new Error('FetchError is not implemented') + } + } + } + + if (typeof $stencilWindow.Headers === 'function') { + Headers = $stencilWindow.Headers + } else { + Headers = $stencilWindow.Headers = class Headers { + constructor() { + throw new Error('Headers is not implemented') + } + } + } + + if (typeof $stencilWindow.Request === 'function') { + Request = $stencilWindow.Request + } else { + Request = $stencilWindow.Request = class Request { + constructor() { + throw new Error('Request is not implemented') + } + } + } + + if (typeof $stencilWindow.Response === 'function') { + Response = $stencilWindow.Response + } else { + Response = $stencilWindow.Response = class Response { + constructor() { + throw new Error('Response is not implemented') + } + } + } + + function hydrateAppClosure($stencilWindow) { + const window = $stencilWindow + const document = $stencilWindow.document + /*hydrateAppClosure start*/ + + const NAMESPACE = 'baloise-design-system' + const BUILD = /* baloise-design-system */ { + allRenderFn: true, + appendChildSlotFix: false, + asyncLoading: true, + attachStyles: true, + cloneNodeFix: false, + cmpDidLoad: true, + cmpDidRender: true, + cmpDidUnload: false, + cmpDidUpdate: true, + cmpShouldUpdate: false, + cmpWillLoad: true, + cmpWillRender: true, + cmpWillUpdate: false, + connectedCallback: true, + constructableCSS: false, + cssAnnotations: true, + devTools: false, + disconnectedCallback: true, + element: false, + event: true, + experimentalScopedSlotChanges: false, + experimentalSlotFixes: false, + formAssociated: false, + hasRenderFn: true, + hostListener: true, + hostListenerTarget: true, + hostListenerTargetBody: true, + hostListenerTargetDocument: true, + hostListenerTargetParent: false, + hostListenerTargetWindow: true, + hotModuleReplacement: false, + hydrateClientSide: true, + hydrateServerSide: true, + hydratedAttribute: false, + hydratedClass: true, + hydratedSelectorName: 'hydrated', + invisiblePrehydration: true, + isDebug: false, + isDev: false, + isTesting: false, + lazyLoad: true, + lifecycle: true, + lifecycleDOMEvents: false, + member: true, + method: true, + mode: false, + observeAttribute: true, + profile: false, + prop: true, + propBoolean: true, + propMutable: true, + propNumber: true, + propString: true, + reflect: true, + scoped: true, + scopedSlotTextContentFix: false, + scriptDataOpts: false, + shadowDelegatesFocus: false, + shadowDom: true, + shadowDomShim: true, + slot: true, + slotChildNodesFix: false, + slotRelocation: true, + state: true, + style: true, + svg: true, + taskQueue: true, + updatable: true, + vdomAttribute: true, + vdomClass: true, + vdomFunctional: true, + vdomKey: true, + vdomListener: true, + vdomPropOrAttr: true, + vdomRef: true, + vdomRender: true, + vdomStyle: true, + vdomText: true, + vdomXlink: true, + watchCallback: true, + } + + /* + Stencil Hydrate Platform v4.21.0 | MIT Licensed | https://stenciljs.com + */ + var __defProp = Object.defineProperty + var __export = (target, all) => { + for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }) + } + + // src/utils/constants.ts + var EMPTY_OBJ = {} + var SVG_NS = 'http://www.w3.org/2000/svg' + var HTML_NS = 'http://www.w3.org/1999/xhtml' + + // src/utils/helpers.ts + var isDef = v => v != null + var isComplexType = o => { + o = typeof o + return o === 'object' || o === 'function' + } + + // src/utils/query-nonce-meta-tag-content.ts + function queryNonceMetaTagContent(doc2) { + var _a, _b, _c + return (_c = + (_b = (_a = doc2.head) == null ? void 0 : _a.querySelector('meta[name="csp-nonce"]')) == null + ? void 0 + : _b.getAttribute('content')) != null + ? _c + : void 0 + } + + // src/utils/result.ts + var result_exports = {} + __export(result_exports, { + err: () => err, + map: () => map, + ok: () => ok, + unwrap: () => unwrap, + unwrapErr: () => unwrapErr, + }) + var ok = value => ({ + isOk: true, + isErr: false, + value, + }) + var err = value => ({ + isOk: false, + isErr: true, + value, + }) + function map(result, fn) { + if (result.isOk) { + const val = fn(result.value) + if (val instanceof Promise) { + return val.then(newVal => ok(newVal)) + } else { + return ok(val) + } + } + if (result.isErr) { + const value = result.value + return err(value) + } + throw 'should never get here' + } + var unwrap = result => { + if (result.isOk) { + return result.value + } else { + throw result.value + } + } + var unwrapErr = result => { + if (result.isErr) { + return result.value + } else { + throw result.value + } + } + var createTime = (fnName, tagName = '') => { + { + return () => { + return + } + } + } + var uniqueTime = (key, measureText) => { + { + return () => { + return + } + } + } + + // src/runtime/runtime-constants.ts + var CONTENT_REF_ID = 'r' + var ORG_LOCATION_ID = 'o' + var SLOT_NODE_ID = 's' + var TEXT_NODE_ID = 't' + var HYDRATE_ID = 's-id' + var HYDRATED_STYLE_ID = 'sty-id' + var HYDRATE_CHILD_ID = 'c-id' + var SLOT_FB_CSS = 'slot-fb{display:contents}slot-fb[hidden]{display:none}' + var XLINK_NS = 'http://www.w3.org/1999/xlink' + var h = (nodeName, vnodeData, ...children) => { + let child = null + let key = null + let slotName = null + let simple = false + let lastSimple = false + const vNodeChildren = [] + const walk = c => { + for (let i2 = 0; i2 < c.length; i2++) { + child = c[i2] + if (Array.isArray(child)) { + walk(child) + } else if (child != null && typeof child !== 'boolean') { + if ((simple = typeof nodeName !== 'function' && !isComplexType(child))) { + child = String(child) + } + if (simple && lastSimple) { + vNodeChildren[vNodeChildren.length - 1].$text$ += child + } else { + vNodeChildren.push(simple ? newVNode(null, child) : child) + } + lastSimple = simple + } + } + } + walk(children) + if (vnodeData) { + if (vnodeData.key) { + key = vnodeData.key + } + if (vnodeData.name) { + slotName = vnodeData.name + } + { + const classData = vnodeData.className || vnodeData.class + if (classData) { + vnodeData.class = + typeof classData !== 'object' + ? classData + : Object.keys(classData) + .filter(k => classData[k]) + .join(' ') + } + } + } + if (typeof nodeName === 'function') { + return nodeName(vnodeData === null ? {} : vnodeData, vNodeChildren, vdomFnUtils) + } + const vnode = newVNode(nodeName, null) + vnode.$attrs$ = vnodeData + if (vNodeChildren.length > 0) { + vnode.$children$ = vNodeChildren + } + { + vnode.$key$ = key + } + { + vnode.$name$ = slotName + } + return vnode + } + var newVNode = (tag, text) => { + const vnode = { + $flags$: 0, + $tag$: tag, + $text$: text, + $elm$: null, + $children$: null, + } + { + vnode.$attrs$ = null + } + { + vnode.$key$ = null + } + { + vnode.$name$ = null + } + return vnode + } + var Host = {} + var isHost = node => node && node.$tag$ === Host + var vdomFnUtils = { + forEach: (children, cb) => children.map(convertToPublic).forEach(cb), + map: (children, cb) => children.map(convertToPublic).map(cb).map(convertToPrivate), + } + var convertToPublic = node => ({ + vattrs: node.$attrs$, + vchildren: node.$children$, + vkey: node.$key$, + vname: node.$name$, + vtag: node.$tag$, + vtext: node.$text$, + }) + var convertToPrivate = node => { + if (typeof node.vtag === 'function') { + const vnodeData = { ...node.vattrs } + if (node.vkey) { + vnodeData.key = node.vkey + } + if (node.vname) { + vnodeData.name = node.vname + } + return h(node.vtag, vnodeData, ...(node.vchildren || [])) + } + const vnode = newVNode(node.vtag, node.vtext) + vnode.$attrs$ = node.vattrs + vnode.$children$ = node.vchildren + vnode.$key$ = node.vkey + vnode.$name$ = node.vname + return vnode + } + + // src/runtime/client-hydrate.ts + var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => { + const endHydrate = createTime('hydrateClient', tagName) + const shadowRoot = hostElm.shadowRoot + const childRenderNodes = [] + const slotNodes = [] + const shadowRootNodes = shadowRoot ? [] : null + const vnode = (hostRef.$vnode$ = newVNode(tagName, null)) + if (!plt.$orgLocNodes$) { + initializeDocumentHydrate(doc.body, (plt.$orgLocNodes$ = /* @__PURE__ */ new Map())) + } + hostElm[HYDRATE_ID] = hostId + hostElm.removeAttribute(HYDRATE_ID) + clientHydrate(vnode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, hostElm, hostId) + childRenderNodes.map(c => { + const orgLocationId = c.$hostId$ + '.' + c.$nodeId$ + const orgLocationNode = plt.$orgLocNodes$.get(orgLocationId) + const node = c.$elm$ + if (orgLocationNode && supportsShadow && orgLocationNode['s-en'] === '') { + orgLocationNode.parentNode.insertBefore(node, orgLocationNode.nextSibling) + } + if (!shadowRoot) { + node['s-hn'] = tagName + if (orgLocationNode) { + node['s-ol'] = orgLocationNode + node['s-ol']['s-nr'] = node + } + } + plt.$orgLocNodes$.delete(orgLocationId) + }) + if (shadowRoot) { + shadowRootNodes.map(shadowRootNode => { + if (shadowRootNode) { + shadowRoot.appendChild(shadowRootNode) + } + }) + } + endHydrate() + } + var clientHydrate = (parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node, hostId) => { + let childNodeType + let childIdSplt + let childVNode + let i2 + if (node.nodeType === 1 /* ElementNode */) { + childNodeType = node.getAttribute(HYDRATE_CHILD_ID) + if (childNodeType) { + childIdSplt = childNodeType.split('.') + if (childIdSplt[0] === hostId || childIdSplt[0] === '0') { + childVNode = { + $flags$: 0, + $hostId$: childIdSplt[0], + $nodeId$: childIdSplt[1], + $depth$: childIdSplt[2], + $index$: childIdSplt[3], + $tag$: node.tagName.toLowerCase(), + $elm$: node, + $attrs$: null, + $children$: null, + $key$: null, + $name$: null, + $text$: null, + } + childRenderNodes.push(childVNode) + node.removeAttribute(HYDRATE_CHILD_ID) + if (!parentVNode.$children$) { + parentVNode.$children$ = [] + } + parentVNode.$children$[childVNode.$index$] = childVNode + parentVNode = childVNode + if (shadowRootNodes && childVNode.$depth$ === '0') { + shadowRootNodes[childVNode.$index$] = childVNode.$elm$ + } + } + } + if (node.shadowRoot) { + for (i2 = node.shadowRoot.childNodes.length - 1; i2 >= 0; i2--) { + clientHydrate( + parentVNode, + childRenderNodes, + slotNodes, + shadowRootNodes, + hostElm, + node.shadowRoot.childNodes[i2], + hostId, + ) + } + } + for (i2 = node.childNodes.length - 1; i2 >= 0; i2--) { + clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node.childNodes[i2], hostId) + } + } else if (node.nodeType === 8 /* CommentNode */) { + childIdSplt = node.nodeValue.split('.') + if (childIdSplt[1] === hostId || childIdSplt[1] === '0') { + childNodeType = childIdSplt[0] + childVNode = { + $flags$: 0, + $hostId$: childIdSplt[1], + $nodeId$: childIdSplt[2], + $depth$: childIdSplt[3], + $index$: childIdSplt[4], + $elm$: node, + $attrs$: null, + $children$: null, + $key$: null, + $name$: null, + $tag$: null, + $text$: null, + } + if (childNodeType === TEXT_NODE_ID) { + childVNode.$elm$ = node.nextSibling + if (childVNode.$elm$ && childVNode.$elm$.nodeType === 3 /* TextNode */) { + childVNode.$text$ = childVNode.$elm$.textContent + childRenderNodes.push(childVNode) + node.remove() + if (!parentVNode.$children$) { + parentVNode.$children$ = [] + } + parentVNode.$children$[childVNode.$index$] = childVNode + if (shadowRootNodes && childVNode.$depth$ === '0') { + shadowRootNodes[childVNode.$index$] = childVNode.$elm$ + } + } + } else if (childVNode.$hostId$ === hostId) { + if (childNodeType === SLOT_NODE_ID) { + childVNode.$tag$ = 'slot' + if (childIdSplt[5]) { + node['s-sn'] = childVNode.$name$ = childIdSplt[5] + } else { + node['s-sn'] = '' + } + node['s-sr'] = true + if (shadowRootNodes) { + childVNode.$elm$ = doc.createElement(childVNode.$tag$) + if (childVNode.$name$) { + childVNode.$elm$.setAttribute('name', childVNode.$name$) + } + node.parentNode.insertBefore(childVNode.$elm$, node) + node.remove() + if (childVNode.$depth$ === '0') { + shadowRootNodes[childVNode.$index$] = childVNode.$elm$ + } + } + slotNodes.push(childVNode) + if (!parentVNode.$children$) { + parentVNode.$children$ = [] + } + parentVNode.$children$[childVNode.$index$] = childVNode + } else if (childNodeType === CONTENT_REF_ID) { + if (shadowRootNodes) { + node.remove() + } else { + hostElm['s-cr'] = node + node['s-cn'] = true + } + } + } + } + } else if (parentVNode && parentVNode.$tag$ === 'style') { + const vnode = newVNode(null, node.textContent) + vnode.$elm$ = node + vnode.$index$ = '0' + parentVNode.$children$ = [vnode] + } + } + var initializeDocumentHydrate = (node, orgLocNodes) => { + if (node.nodeType === 1 /* ElementNode */) { + let i2 = 0 + if (node.shadowRoot) { + for (; i2 < node.shadowRoot.childNodes.length; i2++) { + initializeDocumentHydrate(node.shadowRoot.childNodes[i2], orgLocNodes) + } + } + for (i2 = 0; i2 < node.childNodes.length; i2++) { + initializeDocumentHydrate(node.childNodes[i2], orgLocNodes) + } + } else if (node.nodeType === 8 /* CommentNode */) { + const childIdSplt = node.nodeValue.split('.') + if (childIdSplt[0] === ORG_LOCATION_ID) { + orgLocNodes.set(childIdSplt[1] + '.' + childIdSplt[2], node) + node.nodeValue = '' + node['s-en'] = childIdSplt[3] + } + } + } + var parsePropertyValue = (propValue, propType) => { + if (propValue != null && !isComplexType(propValue)) { + if (propType & 4 /* Boolean */) { + return propValue === 'false' ? false : propValue === '' || !!propValue + } + if (propType & 2 /* Number */) { + return parseFloat(propValue) + } + if (propType & 1 /* String */) { + return String(propValue) + } + return propValue + } + return propValue + } + var getElement = ref => getHostRef(ref).$hostElement$ + + // src/runtime/event-emitter.ts + var createEvent = (ref, name, flags) => { + const elm = getElement(ref) + return { + emit: detail => { + return emitEvent(elm, name, { + bubbles: !!((flags & 4) /* Bubbles */), + composed: !!((flags & 2) /* Composed */), + cancelable: !!((flags & 1) /* Cancellable */), + detail, + }) + }, + } + } + var emitEvent = (elm, name, opts) => { + const ev = plt.ce(name, opts) + elm.dispatchEvent(ev) + return ev + } + var rootAppliedStyles = /* @__PURE__ */ new WeakMap() + var registerStyle = (scopeId2, cssText, allowCS) => { + let style = styles.get(scopeId2) + { + style = cssText + } + styles.set(scopeId2, style) + } + var addStyle = (styleContainerNode, cmpMeta, mode) => { + var _a + const scopeId2 = getScopeId(cmpMeta) + const style = styles.get(scopeId2) + styleContainerNode = styleContainerNode.nodeType === 11 /* DocumentFragment */ ? styleContainerNode : doc + if (style) { + if (typeof style === 'string') { + styleContainerNode = styleContainerNode.head || styleContainerNode + let appliedStyles = rootAppliedStyles.get(styleContainerNode) + let styleElm + if (!appliedStyles) { + rootAppliedStyles.set(styleContainerNode, (appliedStyles = /* @__PURE__ */ new Set())) + } + if (!appliedStyles.has(scopeId2)) { + if ( + styleContainerNode.host && + (styleElm = styleContainerNode.querySelector(`[${HYDRATED_STYLE_ID}="${scopeId2}"]`)) + ) { + styleElm.innerHTML = style + } else { + styleElm = doc.createElement('style') + styleElm.innerHTML = style + const nonce = (_a = plt.$nonce$) != null ? _a : queryNonceMetaTagContent(doc) + if (nonce != null) { + styleElm.setAttribute('nonce', nonce) + } + if (cmpMeta.$flags$ & 2 /* scopedCssEncapsulation */) { + styleElm.setAttribute(HYDRATED_STYLE_ID, scopeId2) + } + if (!((cmpMeta.$flags$ & 1) /* shadowDomEncapsulation */)) { + if (styleContainerNode.nodeName === 'HEAD') { + const preconnectLinks = styleContainerNode.querySelectorAll('link[rel=preconnect]') + const referenceNode2 = + preconnectLinks.length > 0 + ? preconnectLinks[preconnectLinks.length - 1].nextSibling + : document.querySelector('style') + styleContainerNode.insertBefore(styleElm, referenceNode2) + } else if ('host' in styleContainerNode) { + styleContainerNode.prepend(styleElm) + } else { + styleContainerNode.append(styleElm) + } + } + if (cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */ && styleContainerNode.nodeName !== 'HEAD') { + styleContainerNode.insertBefore(styleElm, null) + } + } + if (cmpMeta.$flags$ & 4 /* hasSlotRelocation */) { + styleElm.innerHTML += SLOT_FB_CSS + } + if (appliedStyles) { + appliedStyles.add(scopeId2) + } + } + } + } + return scopeId2 + } + var attachStyles = hostRef => { + const cmpMeta = hostRef.$cmpMeta$ + const elm = hostRef.$hostElement$ + const flags = cmpMeta.$flags$ + const endAttachStyles = createTime('attachStyles', cmpMeta.$tagName$) + const scopeId2 = addStyle(elm.shadowRoot ? elm.shadowRoot : elm.getRootNode(), cmpMeta) + if (flags & 10 /* needsScopedEncapsulation */ && flags & 2 /* scopedCssEncapsulation */) { + elm['s-sc'] = scopeId2 + elm.classList.add(scopeId2 + '-h') + if (flags & 2 /* scopedCssEncapsulation */) { + elm.classList.add(scopeId2 + '-s') + } + } + endAttachStyles() + } + var getScopeId = (cmp, mode) => 'sc-' + cmp.$tagName$ + var setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags) => { + if (oldValue !== newValue) { + let isProp = isMemberInElement(elm, memberName) + let ln = memberName.toLowerCase() + if (memberName === 'class') { + const classList = elm.classList + const oldClasses = parseClassList(oldValue) + const newClasses = parseClassList(newValue) + classList.remove(...oldClasses.filter(c => c && !newClasses.includes(c))) + classList.add(...newClasses.filter(c => c && !oldClasses.includes(c))) + } else if (memberName === 'style') { + { + for (const prop in oldValue) { + if (!newValue || newValue[prop] == null) { + { + elm.style[prop] = '' + } + } + } + } + for (const prop in newValue) { + if (!oldValue || newValue[prop] !== oldValue[prop]) { + { + elm.style[prop] = newValue[prop] + } + } + } + } else if (memberName === 'key'); + else if (memberName === 'ref') { + if (newValue) { + newValue(elm) + } + } else if (!isProp && memberName[0] === 'o' && memberName[1] === 'n') { + if (memberName[2] === '-') { + memberName = memberName.slice(3) + } else if (isMemberInElement(win, ln)) { + memberName = ln.slice(2) + } else { + memberName = ln[2] + memberName.slice(3) + } + if (oldValue || newValue) { + const capture = memberName.endsWith(CAPTURE_EVENT_SUFFIX) + memberName = memberName.replace(CAPTURE_EVENT_REGEX, '') + if (oldValue) { + plt.rel(elm, memberName, oldValue, capture) + } + if (newValue) { + plt.ael(elm, memberName, newValue, capture) + } + } + } else { + const isComplex = isComplexType(newValue) + if ((isProp || (isComplex && newValue !== null)) && !isSvg) { + try { + if (!elm.tagName.includes('-')) { + const n = newValue == null ? '' : newValue + if (memberName === 'list') { + isProp = false + } else if (oldValue == null || elm[memberName] != n) { + if (typeof elm.__lookupSetter__(memberName) === 'function') { + elm[memberName] = n + } else { + elm.setAttribute(memberName, n) + } + } + } else { + elm[memberName] = newValue + } + } catch (e) {} + } + let xlink = false + { + if (ln !== (ln = ln.replace(/^xlink\:?/, ''))) { + memberName = ln + xlink = true + } + } + if (newValue == null || newValue === false) { + if (newValue !== false || elm.getAttribute(memberName) === '') { + if (xlink) { + elm.removeAttributeNS(XLINK_NS, memberName) + } else { + elm.removeAttribute(memberName) + } + } + } else if ((!isProp || flags & 4 /* isHost */ || isSvg) && !isComplex) { + newValue = newValue === true ? '' : newValue + if (xlink) { + elm.setAttributeNS(XLINK_NS, memberName, newValue) + } else { + elm.setAttribute(memberName, newValue) + } + } + } + } + } + var parseClassListRegex = /\s/ + var parseClassList = value => (!value ? [] : value.split(parseClassListRegex)) + var CAPTURE_EVENT_SUFFIX = 'Capture' + var CAPTURE_EVENT_REGEX = new RegExp(CAPTURE_EVENT_SUFFIX + '$') + + // src/runtime/vdom/update-element.ts + var updateElement = (oldVnode, newVnode, isSvgMode2) => { + const elm = + newVnode.$elm$.nodeType === 11 /* DocumentFragment */ && newVnode.$elm$.host + ? newVnode.$elm$.host + : newVnode.$elm$ + const oldVnodeAttrs = (oldVnode && oldVnode.$attrs$) || EMPTY_OBJ + const newVnodeAttrs = newVnode.$attrs$ || EMPTY_OBJ + { + for (const memberName of sortedAttrNames(Object.keys(oldVnodeAttrs))) { + if (!(memberName in newVnodeAttrs)) { + setAccessor(elm, memberName, oldVnodeAttrs[memberName], void 0, isSvgMode2, newVnode.$flags$) + } + } + } + for (const memberName of sortedAttrNames(Object.keys(newVnodeAttrs))) { + setAccessor(elm, memberName, oldVnodeAttrs[memberName], newVnodeAttrs[memberName], isSvgMode2, newVnode.$flags$) + } + } + function sortedAttrNames(attrNames) { + return attrNames.includes('ref') + ? // we need to sort these to ensure that `'ref'` is the last attr + [...attrNames.filter(attr => attr !== 'ref'), 'ref'] + : // no need to sort, return the original array + attrNames + } + + // src/runtime/vdom/vdom-render.ts + var scopeId + var contentRef + var hostTagName + var useNativeShadowDom = false + var checkSlotFallbackVisibility = false + var checkSlotRelocate = false + var isSvgMode = false + var createElm = (oldParentVNode, newParentVNode, childIndex, parentElm) => { + var _a + const newVNode2 = newParentVNode.$children$[childIndex] + let i2 = 0 + let elm + let childNode + let oldVNode + if (!useNativeShadowDom) { + checkSlotRelocate = true + if (newVNode2.$tag$ === 'slot') { + if (scopeId) { + parentElm.classList.add(scopeId + '-s') + } + newVNode2.$flags$ |= newVNode2.$children$ + ? // slot element has fallback content + // still create an element that "mocks" the slot element + 2 /* isSlotFallback */ + : // slot element does not have fallback content + // create an html comment we'll use to always reference + // where actual slot content should sit next to + 1 /* isSlotReference */ + } + } + if (newVNode2.$text$ !== null) { + elm = newVNode2.$elm$ = doc.createTextNode(newVNode2.$text$) + } else if (newVNode2.$flags$ & 1 /* isSlotReference */) { + elm = newVNode2.$elm$ = slotReferenceDebugNode(newVNode2) + } else { + if (!isSvgMode) { + isSvgMode = newVNode2.$tag$ === 'svg' + } + elm = newVNode2.$elm$ = doc.createElementNS( + isSvgMode ? SVG_NS : HTML_NS, + !useNativeShadowDom && BUILD.slotRelocation && newVNode2.$flags$ & 2 /* isSlotFallback */ + ? 'slot-fb' + : newVNode2.$tag$, + ) + if (isSvgMode && newVNode2.$tag$ === 'foreignObject') { + isSvgMode = false + } + { + updateElement(null, newVNode2, isSvgMode) + } + const rootNode = elm.getRootNode() + const isElementWithinShadowRoot = !rootNode.querySelector('body') + if (!isElementWithinShadowRoot && BUILD.scoped && isDef(scopeId) && elm['s-si'] !== scopeId) { + elm.classList.add((elm['s-si'] = scopeId)) + } + { + updateElementScopeIds(elm, parentElm) + } + if (newVNode2.$children$) { + for (i2 = 0; i2 < newVNode2.$children$.length; ++i2) { + childNode = createElm(oldParentVNode, newVNode2, i2, elm) + if (childNode) { + elm.appendChild(childNode) + } + } + } + { + if (newVNode2.$tag$ === 'svg') { + isSvgMode = false + } else if (elm.tagName === 'foreignObject') { + isSvgMode = true + } + } + } + elm['s-hn'] = hostTagName + { + if (newVNode2.$flags$ & (2 /* isSlotFallback */ | 1) /* isSlotReference */) { + elm['s-sr'] = true + elm['s-cr'] = contentRef + elm['s-sn'] = newVNode2.$name$ || '' + elm['s-rf'] = (_a = newVNode2.$attrs$) == null ? void 0 : _a.ref + oldVNode = oldParentVNode && oldParentVNode.$children$ && oldParentVNode.$children$[childIndex] + if (oldVNode && oldVNode.$tag$ === newVNode2.$tag$ && oldParentVNode.$elm$) { + { + putBackInOriginalLocation(oldParentVNode.$elm$, false) + } + } + } + } + return elm + } + var putBackInOriginalLocation = (parentElm, recursive) => { + plt.$flags$ |= 1 /* isTmpDisconnected */ + const oldSlotChildNodes = Array.from(parentElm.childNodes) + if (parentElm['s-sr'] && BUILD.experimentalSlotFixes) { + let node = parentElm + while ((node = node.nextSibling)) { + if (node && node['s-sn'] === parentElm['s-sn'] && node['s-sh'] === hostTagName) { + oldSlotChildNodes.push(node) + } + } + } + for (let i2 = oldSlotChildNodes.length - 1; i2 >= 0; i2--) { + const childNode = oldSlotChildNodes[i2] + if (childNode['s-hn'] !== hostTagName && childNode['s-ol']) { + insertBefore(parentReferenceNode(childNode), childNode, referenceNode(childNode)) + childNode['s-ol'].remove() + childNode['s-ol'] = void 0 + childNode['s-sh'] = void 0 + checkSlotRelocate = true + } + if (recursive) { + putBackInOriginalLocation(childNode, recursive) + } + } + plt.$flags$ &= ~1 /* isTmpDisconnected */ + } + var addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => { + let containerElm = (parentElm['s-cr'] && parentElm['s-cr'].parentNode) || parentElm + let childNode + if (containerElm.shadowRoot && containerElm.tagName === hostTagName) { + containerElm = containerElm.shadowRoot + } + for (; startIdx <= endIdx; ++startIdx) { + if (vnodes[startIdx]) { + childNode = createElm(null, parentVNode, startIdx, parentElm) + if (childNode) { + vnodes[startIdx].$elm$ = childNode + insertBefore(containerElm, childNode, referenceNode(before)) + } + } + } + } + var removeVnodes = (vnodes, startIdx, endIdx) => { + for (let index = startIdx; index <= endIdx; ++index) { + const vnode = vnodes[index] + if (vnode) { + const elm = vnode.$elm$ + nullifyVNodeRefs(vnode) + if (elm) { + { + checkSlotFallbackVisibility = true + if (elm['s-ol']) { + elm['s-ol'].remove() + } else { + putBackInOriginalLocation(elm, true) + } + } + elm.remove() + } + } + } + } + var updateChildren = (parentElm, oldCh, newVNode2, newCh, isInitialRender = false) => { + let oldStartIdx = 0 + let newStartIdx = 0 + let idxInOld = 0 + let i2 = 0 + let oldEndIdx = oldCh.length - 1 + let oldStartVnode = oldCh[0] + let oldEndVnode = oldCh[oldEndIdx] + let newEndIdx = newCh.length - 1 + let newStartVnode = newCh[0] + let newEndVnode = newCh[newEndIdx] + let node + let elmToMove + while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { + if (oldStartVnode == null) { + oldStartVnode = oldCh[++oldStartIdx] + } else if (oldEndVnode == null) { + oldEndVnode = oldCh[--oldEndIdx] + } else if (newStartVnode == null) { + newStartVnode = newCh[++newStartIdx] + } else if (newEndVnode == null) { + newEndVnode = newCh[--newEndIdx] + } else if (isSameVnode(oldStartVnode, newStartVnode, isInitialRender)) { + patch(oldStartVnode, newStartVnode, isInitialRender) + oldStartVnode = oldCh[++oldStartIdx] + newStartVnode = newCh[++newStartIdx] + } else if (isSameVnode(oldEndVnode, newEndVnode, isInitialRender)) { + patch(oldEndVnode, newEndVnode, isInitialRender) + oldEndVnode = oldCh[--oldEndIdx] + newEndVnode = newCh[--newEndIdx] + } else if (isSameVnode(oldStartVnode, newEndVnode, isInitialRender)) { + if (oldStartVnode.$tag$ === 'slot' || newEndVnode.$tag$ === 'slot') { + putBackInOriginalLocation(oldStartVnode.$elm$.parentNode, false) + } + patch(oldStartVnode, newEndVnode, isInitialRender) + insertBefore(parentElm, oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling) + oldStartVnode = oldCh[++oldStartIdx] + newEndVnode = newCh[--newEndIdx] + } else if (isSameVnode(oldEndVnode, newStartVnode, isInitialRender)) { + if (oldStartVnode.$tag$ === 'slot' || newEndVnode.$tag$ === 'slot') { + putBackInOriginalLocation(oldEndVnode.$elm$.parentNode, false) + } + patch(oldEndVnode, newStartVnode, isInitialRender) + insertBefore(parentElm, oldEndVnode.$elm$, oldStartVnode.$elm$) + oldEndVnode = oldCh[--oldEndIdx] + newStartVnode = newCh[++newStartIdx] + } else { + idxInOld = -1 + { + for (i2 = oldStartIdx; i2 <= oldEndIdx; ++i2) { + if (oldCh[i2] && oldCh[i2].$key$ !== null && oldCh[i2].$key$ === newStartVnode.$key$) { + idxInOld = i2 + break + } + } + } + if (idxInOld >= 0) { + elmToMove = oldCh[idxInOld] + if (elmToMove.$tag$ !== newStartVnode.$tag$) { + node = createElm(oldCh && oldCh[newStartIdx], newVNode2, idxInOld, parentElm) + } else { + patch(elmToMove, newStartVnode, isInitialRender) + oldCh[idxInOld] = void 0 + node = elmToMove.$elm$ + } + newStartVnode = newCh[++newStartIdx] + } else { + node = createElm(oldCh && oldCh[newStartIdx], newVNode2, newStartIdx, parentElm) + newStartVnode = newCh[++newStartIdx] + } + if (node) { + { + insertBefore(parentReferenceNode(oldStartVnode.$elm$), node, referenceNode(oldStartVnode.$elm$)) + } + } + } + } + if (oldStartIdx > oldEndIdx) { + addVnodes( + parentElm, + newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].$elm$, + newVNode2, + newCh, + newStartIdx, + newEndIdx, + ) + } else if (newStartIdx > newEndIdx) { + removeVnodes(oldCh, oldStartIdx, oldEndIdx) + } + } + var isSameVnode = (leftVNode, rightVNode, isInitialRender = false) => { + if (leftVNode.$tag$ === rightVNode.$tag$) { + if (leftVNode.$tag$ === 'slot') { + if ( + // The component gets hydrated and no VDOM has been initialized. + // Here the comparison can't happen as $name$ property is not set for `leftNode`. + '$nodeId$' in leftVNode && + isInitialRender && // `leftNode` is not from type HTMLComment which would cause many + // hydration comments to be removed + leftVNode.$elm$.nodeType !== 8 + ) { + return false + } + return leftVNode.$name$ === rightVNode.$name$ + } + if (!isInitialRender) { + return leftVNode.$key$ === rightVNode.$key$ + } + return true + } + return false + } + var referenceNode = node => { + return (node && node['s-ol']) || node + } + var parentReferenceNode = node => (node['s-ol'] ? node['s-ol'] : node).parentNode + var patch = (oldVNode, newVNode2, isInitialRender = false) => { + const elm = (newVNode2.$elm$ = oldVNode.$elm$) + const oldChildren = oldVNode.$children$ + const newChildren = newVNode2.$children$ + const tag = newVNode2.$tag$ + const text = newVNode2.$text$ + let defaultHolder + if (text === null) { + { + isSvgMode = tag === 'svg' ? true : tag === 'foreignObject' ? false : isSvgMode + } + { + if (tag === 'slot' && !useNativeShadowDom); + else { + updateElement(oldVNode, newVNode2, isSvgMode) + } + } + if (oldChildren !== null && newChildren !== null) { + updateChildren(elm, oldChildren, newVNode2, newChildren, isInitialRender) + } else if (newChildren !== null) { + if (oldVNode.$text$ !== null) { + elm.textContent = '' + } + addVnodes(elm, null, newVNode2, newChildren, 0, newChildren.length - 1) + } else if ( + // don't do this on initial render as it can cause non-hydrated content to be removed + !isInitialRender && + BUILD.updatable && + oldChildren !== null + ) { + removeVnodes(oldChildren, 0, oldChildren.length - 1) + } + if (isSvgMode && tag === 'svg') { + isSvgMode = false + } + } else if ((defaultHolder = elm['s-cr'])) { + defaultHolder.parentNode.textContent = text + } else if (oldVNode.$text$ !== text) { + elm.data = text + } + } + var updateFallbackSlotVisibility = elm => { + const childNodes = elm.childNodes + for (const childNode of childNodes) { + if (childNode.nodeType === 1 /* ElementNode */) { + if (childNode['s-sr']) { + const slotName = childNode['s-sn'] + childNode.hidden = false + for (const siblingNode of childNodes) { + if (siblingNode !== childNode) { + if (siblingNode['s-hn'] !== childNode['s-hn'] || slotName !== '') { + if ( + (siblingNode.nodeType === 1 /* ElementNode */ && + (slotName === siblingNode.getAttribute('slot') || slotName === siblingNode['s-sn'])) || + (siblingNode.nodeType === 3 /* TextNode */ && slotName === siblingNode['s-sn']) + ) { + childNode.hidden = true + break + } + } else { + if ( + siblingNode.nodeType === 1 /* ElementNode */ || + (siblingNode.nodeType === 3 /* TextNode */ && siblingNode.textContent.trim() !== '') + ) { + childNode.hidden = true + break + } + } + } + } + } + updateFallbackSlotVisibility(childNode) + } + } + } + var relocateNodes = [] + var markSlotContentForRelocation = elm => { + let node + let hostContentNodes + let j + for (const childNode of elm.childNodes) { + if (childNode['s-sr'] && (node = childNode['s-cr']) && node.parentNode) { + hostContentNodes = node.parentNode.childNodes + const slotName = childNode['s-sn'] + for (j = hostContentNodes.length - 1; j >= 0; j--) { + node = hostContentNodes[j] + if (!node['s-cn'] && !node['s-nr'] && node['s-hn'] !== childNode['s-hn'] && !BUILD.experimentalSlotFixes) { + if (isNodeLocatedInSlot(node, slotName)) { + let relocateNodeData = relocateNodes.find(r => r.$nodeToRelocate$ === node) + checkSlotFallbackVisibility = true + node['s-sn'] = node['s-sn'] || slotName + if (relocateNodeData) { + relocateNodeData.$nodeToRelocate$['s-sh'] = childNode['s-hn'] + relocateNodeData.$slotRefNode$ = childNode + } else { + node['s-sh'] = childNode['s-hn'] + relocateNodes.push({ + $slotRefNode$: childNode, + $nodeToRelocate$: node, + }) + } + if (node['s-sr']) { + relocateNodes.map(relocateNode => { + if (isNodeLocatedInSlot(relocateNode.$nodeToRelocate$, node['s-sn'])) { + relocateNodeData = relocateNodes.find(r => r.$nodeToRelocate$ === node) + if (relocateNodeData && !relocateNode.$slotRefNode$) { + relocateNode.$slotRefNode$ = relocateNodeData.$slotRefNode$ + } + } + }) + } + } else if (!relocateNodes.some(r => r.$nodeToRelocate$ === node)) { + relocateNodes.push({ + $nodeToRelocate$: node, + }) + } + } + } + } + if (childNode.nodeType === 1 /* ElementNode */) { + markSlotContentForRelocation(childNode) + } + } + } + var isNodeLocatedInSlot = (nodeToRelocate, slotName) => { + if (nodeToRelocate.nodeType === 1 /* ElementNode */) { + if (nodeToRelocate.getAttribute('slot') === null && slotName === '') { + return true + } + if (nodeToRelocate.getAttribute('slot') === slotName) { + return true + } + return false + } + if (nodeToRelocate['s-sn'] === slotName) { + return true + } + return slotName === '' + } + var nullifyVNodeRefs = vNode => { + { + vNode.$attrs$ && vNode.$attrs$.ref && vNode.$attrs$.ref(null) + vNode.$children$ && vNode.$children$.map(nullifyVNodeRefs) + } + } + var insertBefore = (parent, newNode, reference) => { + const inserted = parent == null ? void 0 : parent.insertBefore(newNode, reference) + { + updateElementScopeIds(newNode, parent) + } + return inserted + } + var findScopeIds = element => { + const scopeIds = [] + if (element) { + scopeIds.push( + ...(element['s-scs'] || []), + element['s-si'], + element['s-sc'], + ...findScopeIds(element.parentElement), + ) + } + return scopeIds + } + var updateElementScopeIds = (element, parent, iterateChildNodes = false) => { + var _a + if (element && parent && element.nodeType === 1 /* ElementNode */) { + const scopeIds = new Set(findScopeIds(parent).filter(Boolean)) + if (scopeIds.size) { + ;(_a = element.classList) == null ? void 0 : _a.add(...(element['s-scs'] = [...scopeIds])) + if (element['s-ol'] || iterateChildNodes) { + for (const childNode of Array.from(element.childNodes)) { + updateElementScopeIds(childNode, element, true) + } + } + } + } + } + var renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => { + var _a, _b, _c, _d + const hostElm = hostRef.$hostElement$ + const cmpMeta = hostRef.$cmpMeta$ + const oldVNode = hostRef.$vnode$ || newVNode(null, null) + const rootVnode = isHost(renderFnResults) ? renderFnResults : h(null, null, renderFnResults) + hostTagName = hostElm.tagName + if (cmpMeta.$attrsToReflect$) { + rootVnode.$attrs$ = rootVnode.$attrs$ || {} + cmpMeta.$attrsToReflect$.map(([propName, attribute]) => (rootVnode.$attrs$[attribute] = hostElm[propName])) + } + if (isInitialLoad && rootVnode.$attrs$) { + for (const key of Object.keys(rootVnode.$attrs$)) { + if (hostElm.hasAttribute(key) && !['key', 'ref', 'style', 'class'].includes(key)) { + rootVnode.$attrs$[key] = hostElm[key] + } + } + } + rootVnode.$tag$ = null + rootVnode.$flags$ |= 4 /* isHost */ + hostRef.$vnode$ = rootVnode + rootVnode.$elm$ = oldVNode.$elm$ = hostElm.shadowRoot || hostElm + { + scopeId = hostElm['s-sc'] + } + useNativeShadowDom = (cmpMeta.$flags$ & 1) /* shadowDomEncapsulation */ !== 0 + { + contentRef = hostElm['s-cr'] + checkSlotFallbackVisibility = false + } + patch(oldVNode, rootVnode, isInitialLoad) + { + plt.$flags$ |= 1 /* isTmpDisconnected */ + if (checkSlotRelocate) { + markSlotContentForRelocation(rootVnode.$elm$) + for (const relocateData of relocateNodes) { + const nodeToRelocate = relocateData.$nodeToRelocate$ + if (!nodeToRelocate['s-ol']) { + const orgLocationNode = originalLocationDebugNode(nodeToRelocate) + orgLocationNode['s-nr'] = nodeToRelocate + insertBefore(nodeToRelocate.parentNode, (nodeToRelocate['s-ol'] = orgLocationNode), nodeToRelocate) + } + } + for (const relocateData of relocateNodes) { + const nodeToRelocate = relocateData.$nodeToRelocate$ + const slotRefNode = relocateData.$slotRefNode$ + if (slotRefNode) { + const parentNodeRef = slotRefNode.parentNode + let insertBeforeNode = slotRefNode.nextSibling + { + let orgLocationNode = (_a = nodeToRelocate['s-ol']) == null ? void 0 : _a.previousSibling + while (orgLocationNode) { + let refNode = (_b = orgLocationNode['s-nr']) != null ? _b : null + if (refNode && refNode['s-sn'] === nodeToRelocate['s-sn'] && parentNodeRef === refNode.parentNode) { + refNode = refNode.nextSibling + while (refNode === nodeToRelocate || (refNode == null ? void 0 : refNode['s-sr'])) { + refNode = refNode == null ? void 0 : refNode.nextSibling + } + if (!refNode || !refNode['s-nr']) { + insertBeforeNode = refNode + break + } + } + orgLocationNode = orgLocationNode.previousSibling + } + } + if ( + (!insertBeforeNode && parentNodeRef !== nodeToRelocate.parentNode) || + nodeToRelocate.nextSibling !== insertBeforeNode + ) { + if (nodeToRelocate !== insertBeforeNode) { + if (!nodeToRelocate['s-hn'] && nodeToRelocate['s-ol']) { + nodeToRelocate['s-hn'] = nodeToRelocate['s-ol'].parentNode.nodeName + } + insertBefore(parentNodeRef, nodeToRelocate, insertBeforeNode) + if (nodeToRelocate.nodeType === 1 /* ElementNode */) { + nodeToRelocate.hidden = (_c = nodeToRelocate['s-ih']) != null ? _c : false + } + } + } + nodeToRelocate && typeof slotRefNode['s-rf'] === 'function' && slotRefNode['s-rf'](nodeToRelocate) + } else { + if (nodeToRelocate.nodeType === 1 /* ElementNode */) { + if (isInitialLoad) { + nodeToRelocate['s-ih'] = (_d = nodeToRelocate.hidden) != null ? _d : false + } + nodeToRelocate.hidden = true + } + } + } + } + if (checkSlotFallbackVisibility) { + updateFallbackSlotVisibility(rootVnode.$elm$) + } + plt.$flags$ &= ~1 /* isTmpDisconnected */ + relocateNodes.length = 0 + } + contentRef = void 0 + } + var slotReferenceDebugNode = slotVNode => + doc.createComment( + ` (host=${hostTagName.toLowerCase()})`, + ) + var originalLocationDebugNode = nodeToRelocate => + doc.createComment( + `org-location for ` + + (nodeToRelocate.localName + ? `<${nodeToRelocate.localName}> (host=${nodeToRelocate['s-hn']})` + : `[${nodeToRelocate.textContent}]`), + ) + + // src/runtime/update-component.ts + var attachToAncestor = (hostRef, ancestorComponent) => { + if (ancestorComponent && !hostRef.$onRenderResolve$ && ancestorComponent['s-p']) { + ancestorComponent['s-p'].push(new Promise(r => (hostRef.$onRenderResolve$ = r))) + } + } + var scheduleUpdate = (hostRef, isInitialLoad) => { + { + hostRef.$flags$ |= 16 /* isQueuedForUpdate */ + } + if (hostRef.$flags$ & 4 /* isWaitingForChildren */) { + hostRef.$flags$ |= 512 /* needsRerender */ + return + } + attachToAncestor(hostRef, hostRef.$ancestorComponent$) + const dispatch = () => dispatchHooks(hostRef, isInitialLoad) + return writeTask(dispatch) + } + var dispatchHooks = (hostRef, isInitialLoad) => { + const elm = hostRef.$hostElement$ + const endSchedule = createTime('scheduleUpdate', hostRef.$cmpMeta$.$tagName$) + const instance = hostRef.$lazyInstance$ + if (!instance) { + throw new Error( + `Can't render component <${elm.tagName.toLowerCase()} /> with invalid Stencil runtime! Make sure this imported component is compiled with a \`externalRuntime: true\` flag. For more information, please refer to https://stenciljs.com/docs/custom-elements#externalruntime`, + ) + } + let maybePromise + if (isInitialLoad) { + { + hostRef.$flags$ |= 256 /* isListenReady */ + if (hostRef.$queuedListeners$) { + hostRef.$queuedListeners$.map(([methodName, event]) => safeCall(instance, methodName, event)) + hostRef.$queuedListeners$ = void 0 + } + } + { + maybePromise = safeCall(instance, 'componentWillLoad') + } + } + { + maybePromise = enqueue(maybePromise, () => safeCall(instance, 'componentWillRender')) + } + endSchedule() + return enqueue(maybePromise, () => updateComponent(hostRef, instance, isInitialLoad)) + } + var enqueue = (maybePromise, fn) => + isPromisey(maybePromise) + ? maybePromise.then(fn).catch(err2 => { + console.error(err2) + fn() + }) + : fn() + var isPromisey = maybePromise => + maybePromise instanceof Promise || (maybePromise && maybePromise.then && typeof maybePromise.then === 'function') + var updateComponent = async (hostRef, instance, isInitialLoad) => { + var _a + const elm = hostRef.$hostElement$ + const endUpdate = createTime('update', hostRef.$cmpMeta$.$tagName$) + const rc = elm['s-rc'] + if (isInitialLoad) { + attachStyles(hostRef) + } + const endRender = createTime('render', hostRef.$cmpMeta$.$tagName$) + { + await callRender(hostRef, instance, elm, isInitialLoad) + } + { + try { + serverSideConnected(elm) + if (isInitialLoad) { + if (hostRef.$cmpMeta$.$flags$ & 1 /* shadowDomEncapsulation */) { + elm['s-en'] = '' + } else if (hostRef.$cmpMeta$.$flags$ & 2 /* scopedCssEncapsulation */) { + elm['s-en'] = 'c' + } + } + } catch (e) { + consoleError(e, elm) + } + } + if (rc) { + rc.map(cb => cb()) + elm['s-rc'] = void 0 + } + endRender() + endUpdate() + { + const childrenPromises = (_a = elm['s-p']) != null ? _a : [] + const postUpdate = () => postUpdateComponent(hostRef) + if (childrenPromises.length === 0) { + postUpdate() + } else { + Promise.all(childrenPromises).then(postUpdate) + hostRef.$flags$ |= 4 /* isWaitingForChildren */ + childrenPromises.length = 0 + } + } + } + var callRender = (hostRef, instance, elm, isInitialLoad) => { + try { + instance = instance.render() + { + hostRef.$flags$ &= ~16 /* isQueuedForUpdate */ + } + { + hostRef.$flags$ |= 2 /* hasRendered */ + } + { + { + { + return Promise.resolve(instance).then(value => renderVdom(hostRef, value, isInitialLoad)) + } + } + } + } catch (e) { + consoleError(e, hostRef.$hostElement$) + } + return null + } + var postUpdateComponent = hostRef => { + const tagName = hostRef.$cmpMeta$.$tagName$ + const elm = hostRef.$hostElement$ + const endPostUpdate = createTime('postUpdate', tagName) + const instance = hostRef.$lazyInstance$ + const ancestorComponent = hostRef.$ancestorComponent$ + { + safeCall(instance, 'componentDidRender') + } + if (!((hostRef.$flags$ & 64) /* hasLoadedComponent */)) { + hostRef.$flags$ |= 64 /* hasLoadedComponent */ + { + addHydratedFlag(elm) + } + { + safeCall(instance, 'componentDidLoad') + } + endPostUpdate() + { + hostRef.$onReadyResolve$(elm) + if (!ancestorComponent) { + appDidLoad() + } + } + } else { + { + safeCall(instance, 'componentDidUpdate') + } + endPostUpdate() + } + { + hostRef.$onInstanceResolve$(elm) + } + { + if (hostRef.$onRenderResolve$) { + hostRef.$onRenderResolve$() + hostRef.$onRenderResolve$ = void 0 + } + if (hostRef.$flags$ & 512 /* needsRerender */) { + nextTick(() => scheduleUpdate(hostRef, false)) + } + hostRef.$flags$ &= ~((4 /* isWaitingForChildren */ | 512) /* needsRerender */) + } + } + var appDidLoad = who => { + { + addHydratedFlag(doc.documentElement) + } + nextTick(() => emitEvent(win, 'appload', { detail: { namespace: NAMESPACE } })) + } + var safeCall = (instance, method, arg) => { + if (instance && instance[method]) { + try { + return instance[method](arg) + } catch (e) { + consoleError(e) + } + } + return void 0 + } + var addHydratedFlag = elm => { + var _a + return elm.classList.add((_a = BUILD.hydratedSelectorName) != null ? _a : 'hydrated') + } + var serverSideConnected = elm => { + const children = elm.children + if (children != null) { + for (let i2 = 0, ii = children.length; i2 < ii; i2++) { + const childElm = children[i2] + if (typeof childElm.connectedCallback === 'function') { + childElm.connectedCallback() + } + serverSideConnected(childElm) + } + } + } + + // src/runtime/set-value.ts + var getValue = (ref, propName) => getHostRef(ref).$instanceValues$.get(propName) + var setValue = (ref, propName, newVal, cmpMeta) => { + const hostRef = getHostRef(ref) + if (!hostRef) { + throw new Error( + `Couldn't find host element for "${cmpMeta.$tagName$}" as it is unknown to this Stencil runtime. This usually happens when integrating a 3rd party Stencil component with another Stencil component or application. Please reach out to the maintainers of the 3rd party Stencil component or report this on the Stencil Discord server (https://chat.stenciljs.com) or comment on this similar [GitHub issue](https://github.com/ionic-team/stencil/issues/5457).`, + ) + } + const elm = hostRef.$hostElement$ + const oldVal = hostRef.$instanceValues$.get(propName) + const flags = hostRef.$flags$ + const instance = hostRef.$lazyInstance$ + newVal = parsePropertyValue(newVal, cmpMeta.$members$[propName][0]) + const areBothNaN = Number.isNaN(oldVal) && Number.isNaN(newVal) + const didValueChange = newVal !== oldVal && !areBothNaN + if ((!((flags & 8) /* isConstructingInstance */) || oldVal === void 0) && didValueChange) { + hostRef.$instanceValues$.set(propName, newVal) + if (instance) { + if (cmpMeta.$watchers$ && flags & 128 /* isWatchReady */) { + const watchMethods = cmpMeta.$watchers$[propName] + if (watchMethods) { + watchMethods.map(watchMethodName => { + try { + instance[watchMethodName](newVal, oldVal, propName) + } catch (e) { + consoleError(e, elm) + } + }) + } + } + if ((flags & (2 /* hasRendered */ | 16) /* isQueuedForUpdate */) === 2 /* hasRendered */) { + scheduleUpdate(hostRef, false) + } + } + } + } + + // src/runtime/proxy-component.ts + var proxyComponent = (Cstr, cmpMeta, flags) => { + var _a, _b + const prototype = Cstr.prototype + if (cmpMeta.$members$ || cmpMeta.$watchers$ || Cstr.watchers) { + if (Cstr.watchers && !cmpMeta.$watchers$) { + cmpMeta.$watchers$ = Cstr.watchers + } + const members = Object.entries((_a = cmpMeta.$members$) != null ? _a : {}) + members.map(([memberName, [memberFlags]]) => { + if (memberFlags & 31 /* Prop */ || (flags & 2 /* proxyState */ && memberFlags & 32) /* State */) { + Object.defineProperty(prototype, memberName, { + get() { + return getValue(this, memberName) + }, + set(newValue) { + setValue(this, memberName, newValue, cmpMeta) + }, + configurable: true, + enumerable: true, + }) + } else if (flags & 1 /* isElementConstructor */ && memberFlags & 64 /* Method */) { + Object.defineProperty(prototype, memberName, { + value(...args) { + var _a2 + const ref = getHostRef(this) + return (_a2 = ref == null ? void 0 : ref.$onInstancePromise$) == null + ? void 0 + : _a2.then(() => { + var _a3 + return (_a3 = ref.$lazyInstance$) == null ? void 0 : _a3[memberName](...args) + }) + }, + }) + } + }) + if (flags & 1 /* isElementConstructor */) { + const attrNameToPropName = /* @__PURE__ */ new Map() + prototype.attributeChangedCallback = function (attrName, oldValue, newValue) { + plt.jmp(() => { + var _a2 + const propName = attrNameToPropName.get(attrName) + if (this.hasOwnProperty(propName)) { + newValue = this[propName] + delete this[propName] + } else if ( + prototype.hasOwnProperty(propName) && + typeof this[propName] === 'number' && // cast type to number to avoid TS compiler issues + this[propName] == newValue + ) { + return + } else if (propName == null) { + const hostRef = getHostRef(this) + const flags2 = hostRef == null ? void 0 : hostRef.$flags$ + if ( + flags2 && + !((flags2 & 8) /* isConstructingInstance */) && + flags2 & 128 /* isWatchReady */ && + newValue !== oldValue + ) { + const instance = hostRef.$lazyInstance$ + const entry = (_a2 = cmpMeta.$watchers$) == null ? void 0 : _a2[attrName] + entry == null + ? void 0 + : entry.forEach(callbackName => { + if (instance[callbackName] != null) { + instance[callbackName].call(instance, newValue, oldValue, attrName) + } + }) + } + return + } + this[propName] = newValue === null && typeof this[propName] === 'boolean' ? false : newValue + }) + } + Cstr.observedAttributes = Array.from( + /* @__PURE__ */ new Set([ + ...Object.keys((_b = cmpMeta.$watchers$) != null ? _b : {}), + ...members + .filter(([_, m]) => m[0] & 15 /* HasAttribute */) + .map(([propName, m]) => { + var _a2 + const attrName = m[1] || propName + attrNameToPropName.set(attrName, propName) + if (m[0] & 512 /* ReflectAttr */) { + ;(_a2 = cmpMeta.$attrsToReflect$) == null ? void 0 : _a2.push([propName, attrName]) + } + return attrName + }), + ]), + ) + } + } + return Cstr + } + + // src/runtime/initialize-component.ts + var initializeComponent = async (elm, hostRef, cmpMeta, hmrVersionId) => { + let Cstr + if ((hostRef.$flags$ & 32) /* hasInitializedComponent */ === 0) { + hostRef.$flags$ |= 32 /* hasInitializedComponent */ + const bundleId = cmpMeta.$lazyBundleId$ + if (bundleId) { + const CstrImport = loadModule(cmpMeta) + if (CstrImport && 'then' in CstrImport) { + const endLoad = uniqueTime() + Cstr = await CstrImport + endLoad() + } else { + Cstr = CstrImport + } + if (!Cstr) { + throw new Error(`Constructor for "${cmpMeta.$tagName$}#${hostRef.$modeName$}" was not found`) + } + if (!Cstr.isProxied) { + { + cmpMeta.$watchers$ = Cstr.watchers + } + proxyComponent(Cstr, cmpMeta, 2 /* proxyState */) + Cstr.isProxied = true + } + const endNewInstance = createTime('createInstance', cmpMeta.$tagName$) + { + hostRef.$flags$ |= 8 /* isConstructingInstance */ + } + try { + new Cstr(hostRef) + } catch (e) { + consoleError(e) + } + { + hostRef.$flags$ &= ~8 /* isConstructingInstance */ + } + { + hostRef.$flags$ |= 128 /* isWatchReady */ + } + endNewInstance() + fireConnectedCallback(hostRef.$lazyInstance$) + } else { + Cstr = elm.constructor + const cmpTag = elm.localName + customElements.whenDefined(cmpTag).then(() => (hostRef.$flags$ |= 128) /* isWatchReady */) + } + if (Cstr && Cstr.style) { + let style + if (typeof Cstr.style === 'string') { + style = Cstr.style + } + const scopeId2 = getScopeId(cmpMeta) + if (!styles.has(scopeId2)) { + const endRegisterStyles = createTime('registerStyles', cmpMeta.$tagName$) + registerStyle(scopeId2, style) + endRegisterStyles() + } + } + } + const ancestorComponent = hostRef.$ancestorComponent$ + const schedule = () => scheduleUpdate(hostRef, true) + if (ancestorComponent && ancestorComponent['s-rc']) { + ancestorComponent['s-rc'].push(schedule) + } else { + schedule() + } + } + var fireConnectedCallback = instance => { + { + safeCall(instance, 'connectedCallback') + } + } + + // src/runtime/connected-callback.ts + var connectedCallback = elm => { + if ((plt.$flags$ & 1) /* isTmpDisconnected */ === 0) { + const hostRef = getHostRef(elm) + const cmpMeta = hostRef.$cmpMeta$ + const endConnected = createTime('connectedCallback', cmpMeta.$tagName$) + if (!((hostRef.$flags$ & 1) /* hasConnected */)) { + hostRef.$flags$ |= 1 /* hasConnected */ + let hostId + { + hostId = elm.getAttribute(HYDRATE_ID) + if (hostId) { + if (cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) { + const scopeId2 = addStyle(elm.shadowRoot, cmpMeta) + elm.classList.remove(scopeId2 + '-h', scopeId2 + '-s') + } + initializeClientHydrate(elm, cmpMeta.$tagName$, hostId, hostRef) + } + } + if (!hostId) { + { + setContentReference(elm) + } + } + { + let ancestorComponent = elm + while ((ancestorComponent = ancestorComponent.parentNode || ancestorComponent.host)) { + if ( + (ancestorComponent.nodeType === 1 /* ElementNode */ && + ancestorComponent.hasAttribute('s-id') && + ancestorComponent['s-p']) || + ancestorComponent['s-p'] + ) { + attachToAncestor(hostRef, (hostRef.$ancestorComponent$ = ancestorComponent)) + break + } + } + } + { + initializeComponent(elm, hostRef, cmpMeta) + } + } else { + addHostEventListeners(elm, hostRef, cmpMeta.$listeners$) + if (hostRef == null ? void 0 : hostRef.$lazyInstance$) { + fireConnectedCallback(hostRef.$lazyInstance$) + } else if (hostRef == null ? void 0 : hostRef.$onReadyPromise$) { + hostRef.$onReadyPromise$.then(() => fireConnectedCallback(hostRef.$lazyInstance$)) + } + } + endConnected() + } + } + var setContentReference = elm => { + const contentRefElm = (elm['s-cr'] = doc.createComment('')) + contentRefElm['s-cn'] = true + insertBefore(elm, contentRefElm, elm.firstChild) + } + var addHostEventListeners = (elm, hostRef, listeners, attachParentListeners) => { + if (listeners) { + listeners.map(([flags, name, method]) => { + const target = getHostListenerTarget(elm, flags) + const handler = hostListenerProxy(hostRef, method) + const opts = hostListenerOpts(flags) + plt.ael(target, name, handler, opts) + ;(hostRef.$rmListeners$ = hostRef.$rmListeners$ || []).push(() => plt.rel(target, name, handler, opts)) + }) + } + } + var hostListenerProxy = (hostRef, methodName) => ev => { + var _a + try { + { + if (hostRef.$flags$ & 256 /* isListenReady */) { + ;(_a = hostRef.$lazyInstance$) == null ? void 0 : _a[methodName](ev) + } else { + ;(hostRef.$queuedListeners$ = hostRef.$queuedListeners$ || []).push([methodName, ev]) + } + } + } catch (e) { + consoleError(e) + } + } + var getHostListenerTarget = (elm, flags) => { + if (flags & 4 /* TargetDocument */) return doc + if (flags & 8 /* TargetWindow */) return win + if (flags & 16 /* TargetBody */) return doc.body + return elm + } + var hostListenerOpts = flags => (flags & 2) /* Capture */ !== 0 + + // src/runtime/vdom/vdom-annotations.ts + var insertVdomAnnotations = (doc2, staticComponents) => { + if (doc2 != null) { + const docData = { + hostIds: 0, + rootLevelIds: 0, + staticComponents: new Set(staticComponents), + } + const orgLocationNodes = [] + parseVNodeAnnotations(doc2, doc2.body, docData, orgLocationNodes) + orgLocationNodes.forEach(orgLocationNode => { + var _a + if (orgLocationNode != null && orgLocationNode['s-nr']) { + const nodeRef = orgLocationNode['s-nr'] + let hostId = nodeRef['s-host-id'] + let nodeId = nodeRef['s-node-id'] + let childId = `${hostId}.${nodeId}` + if (hostId == null) { + hostId = 0 + docData.rootLevelIds++ + nodeId = docData.rootLevelIds + childId = `${hostId}.${nodeId}` + if (nodeRef.nodeType === 1 /* ElementNode */) { + nodeRef.setAttribute(HYDRATE_CHILD_ID, childId) + } else if (nodeRef.nodeType === 3 /* TextNode */) { + if (hostId === 0) { + const textContent = (_a = nodeRef.nodeValue) == null ? void 0 : _a.trim() + if (textContent === '') { + orgLocationNode.remove() + return + } + } + const commentBeforeTextNode = doc2.createComment(childId) + commentBeforeTextNode.nodeValue = `${TEXT_NODE_ID}.${childId}` + insertBefore(nodeRef.parentNode, commentBeforeTextNode, nodeRef) + } + } + let orgLocationNodeId = `${ORG_LOCATION_ID}.${childId}` + const orgLocationParentNode = orgLocationNode.parentElement + if (orgLocationParentNode) { + if (orgLocationParentNode['s-en'] === '') { + orgLocationNodeId += `.` + } else if (orgLocationParentNode['s-en'] === 'c') { + orgLocationNodeId += `.c` + } + } + orgLocationNode.nodeValue = orgLocationNodeId + } + }) + } + } + var parseVNodeAnnotations = (doc2, node, docData, orgLocationNodes) => { + var _a + if (node == null) { + return + } + if (node['s-nr'] != null) { + orgLocationNodes.push(node) + } + if (node.nodeType === 1 /* ElementNode */) { + const childNodes = [ + ...Array.from(node.childNodes), + ...Array.from(((_a = node.shadowRoot) == null ? void 0 : _a.childNodes) || []), + ] + childNodes.forEach(childNode => { + const hostRef = getHostRef(childNode) + if (hostRef != null && !docData.staticComponents.has(childNode.nodeName.toLowerCase())) { + const cmpData = { + nodeIds: 0, + } + insertVNodeAnnotations(doc2, childNode, hostRef.$vnode$, docData, cmpData) + } + parseVNodeAnnotations(doc2, childNode, docData, orgLocationNodes) + }) + } + } + var insertVNodeAnnotations = (doc2, hostElm, vnode, docData, cmpData) => { + if (vnode != null) { + const hostId = ++docData.hostIds + hostElm.setAttribute(HYDRATE_ID, hostId) + if (hostElm['s-cr'] != null) { + hostElm['s-cr'].nodeValue = `${CONTENT_REF_ID}.${hostId}` + } + if (vnode.$children$ != null) { + const depth = 0 + vnode.$children$.forEach((vnodeChild, index) => { + insertChildVNodeAnnotations(doc2, vnodeChild, cmpData, hostId, depth, index) + }) + } + if (hostElm && vnode && vnode.$elm$ && !hostElm.hasAttribute(HYDRATE_CHILD_ID)) { + const parent = hostElm.parentElement + if (parent && parent.childNodes) { + const parentChildNodes = Array.from(parent.childNodes) + const comment = parentChildNodes.find(node => node.nodeType === 8 /* CommentNode */ && node['s-sr']) + if (comment) { + const index = parentChildNodes.indexOf(hostElm) - 1 + vnode.$elm$.setAttribute(HYDRATE_CHILD_ID, `${comment['s-host-id']}.${comment['s-node-id']}.0.${index}`) + } + } + } + } + } + var insertChildVNodeAnnotations = (doc2, vnodeChild, cmpData, hostId, depth, index) => { + const childElm = vnodeChild.$elm$ + if (childElm == null) { + return + } + const nodeId = cmpData.nodeIds++ + const childId = `${hostId}.${nodeId}.${depth}.${index}` + childElm['s-host-id'] = hostId + childElm['s-node-id'] = nodeId + if (childElm.nodeType === 1 /* ElementNode */) { + childElm.setAttribute(HYDRATE_CHILD_ID, childId) + } else if (childElm.nodeType === 3 /* TextNode */) { + const parentNode = childElm.parentNode + const nodeName = parentNode == null ? void 0 : parentNode.nodeName + if (nodeName !== 'STYLE' && nodeName !== 'SCRIPT') { + const textNodeId = `${TEXT_NODE_ID}.${childId}` + const commentBeforeTextNode = doc2.createComment(textNodeId) + insertBefore(parentNode, commentBeforeTextNode, childElm) + } + } else if (childElm.nodeType === 8 /* CommentNode */) { + if (childElm['s-sr']) { + const slotName = childElm['s-sn'] || '' + const slotNodeId = `${SLOT_NODE_ID}.${childId}.${slotName}` + childElm.nodeValue = slotNodeId + } + } + if (vnodeChild.$children$ != null) { + const childDepth = depth + 1 + vnodeChild.$children$.forEach((vnode, index2) => { + insertChildVNodeAnnotations(doc2, vnode, cmpData, hostId, childDepth, index2) + }) + } + } + + // src/hydrate/platform/h-async.ts + var hAsync = (nodeName, vnodeData, ...children) => { + if (Array.isArray(children) && children.length > 0) { + const flatChildren = children.flat(Infinity) + if (flatChildren.some(child => child instanceof Promise)) { + return Promise.all(flatChildren) + .then(resolvedChildren => { + return h(nodeName, vnodeData, ...resolvedChildren) + }) + .catch(err2 => { + return h(nodeName, vnodeData) + }) + } + return h(nodeName, vnodeData, ...flatChildren) + } + return h(nodeName, vnodeData) + } + function proxyHostElement(elm, cmpMeta) { + if (typeof elm.componentOnReady !== 'function') { + elm.componentOnReady = componentOnReady$1 + } + if (typeof elm.forceUpdate !== 'function') { + elm.forceUpdate = forceUpdate2 + } + if (!elm.shadowRoot && !!((cmpMeta.$flags$ & 1) /* shadowDomEncapsulation */)) { + { + elm.attachShadow({ mode: 'open' }) + } + } + if (cmpMeta.$members$ != null) { + const hostRef = getHostRef(elm) + const members = Object.entries(cmpMeta.$members$) + members.forEach(([memberName, m]) => { + var _a, _b + const memberFlags = m[0] + if (memberFlags & 31 /* Prop */) { + const attributeName = m[1] || memberName + let attrValue = elm.getAttribute(attributeName) + if ( + ((attrValue == null ? void 0 : attrValue.startsWith('{')) && attrValue.endsWith('}')) || + ((attrValue == null ? void 0 : attrValue.startsWith('[')) && attrValue.endsWith(']')) + ) { + try { + attrValue = JSON.parse(attrValue) + } catch (e) {} + } + if (attrValue != null) { + const parsedAttrValue = parsePropertyValue(attrValue, memberFlags) + ;(_a = hostRef == null ? void 0 : hostRef.$instanceValues$) == null + ? void 0 + : _a.set(memberName, parsedAttrValue) + } + const ownValue = elm[memberName] + if (ownValue !== void 0) { + ;(_b = hostRef == null ? void 0 : hostRef.$instanceValues$) == null + ? void 0 + : _b.set(memberName, ownValue) + delete elm[memberName] + } + Object.defineProperty(elm, memberName, { + get() { + return getValue(this, memberName) + }, + set(newValue) { + setValue(this, memberName, newValue, cmpMeta) + }, + configurable: true, + enumerable: true, + }) + } else if (memberFlags & 64 /* Method */) { + Object.defineProperty(elm, memberName, { + value(...args) { + var _a2 + const ref = getHostRef(this) + return (_a2 = ref == null ? void 0 : ref.$onInstancePromise$) == null + ? void 0 + : _a2 + .then(() => { + var _a3 + return (_a3 = ref == null ? void 0 : ref.$lazyInstance$) == null + ? void 0 + : _a3[memberName](...args) + }) + .catch(consoleError) + }, + }) + } + }) + } + } + function componentOnReady$1() { + var _a + return (_a = getHostRef(this)) == null ? void 0 : _a.$onReadyPromise$ + } + function forceUpdate2() {} + + // src/hydrate/platform/hydrate-app.ts + function hydrateApp(win2, opts, results, afterHydrate, resolve) { + const connectedElements = /* @__PURE__ */ new Set() + const createdElements = /* @__PURE__ */ new Set() + const waitingElements = /* @__PURE__ */ new Set() + const orgDocumentCreateElement = win2.document.createElement + const orgDocumentCreateElementNS = win2.document.createElementNS + const resolved2 = Promise.resolve() + let tmrId + let ranCompleted = false + function hydratedComplete() { + globalThis.clearTimeout(tmrId) + createdElements.clear() + connectedElements.clear() + if (!ranCompleted) { + ranCompleted = true + try { + if (opts.clientHydrateAnnotations) { + insertVdomAnnotations(win2.document, opts.staticComponents) + } + win2.dispatchEvent(new win2.Event('DOMContentLoaded')) + win2.document.createElement = orgDocumentCreateElement + win2.document.createElementNS = orgDocumentCreateElementNS + } catch (e) { + renderCatchError(opts, results, e) + } + } + afterHydrate(win2, opts, results, resolve) + } + function hydratedError(err2) { + renderCatchError(opts, results, err2) + hydratedComplete() + } + function timeoutExceeded() { + hydratedError(`Hydrate exceeded timeout${waitingOnElementsMsg(waitingElements)}`) + } + try { + let patchedConnectedCallback2 = function () { + return connectElement2(this) + }, + patchElement2 = function (elm) { + if (isValidComponent(elm, opts)) { + const hostRef = getHostRef(elm) + if (!hostRef) { + const Cstr = loadModule({ + $tagName$: elm.nodeName.toLowerCase(), + $flags$: null, + }) + if (Cstr != null && Cstr.cmpMeta != null) { + createdElements.add(elm) + elm.connectedCallback = patchedConnectedCallback2 + registerHost(elm, Cstr.cmpMeta) + proxyHostElement(elm, Cstr.cmpMeta) + } + } + } + }, + patchChild2 = function (elm) { + if (elm != null && elm.nodeType === 1) { + patchElement2(elm) + const children = elm.children + for (let i2 = 0, ii = children.length; i2 < ii; i2++) { + patchChild2(children[i2]) + } + } + }, + connectElement2 = function (elm) { + createdElements.delete(elm) + if (isValidComponent(elm, opts) && results.hydratedCount < opts.maxHydrateCount) { + if (!connectedElements.has(elm) && shouldHydrate(elm)) { + connectedElements.add(elm) + return hydrateComponent.call(elm, win2, results, elm.nodeName, elm, waitingElements) + } + } + return resolved2 + }, + waitLoop2 = function () { + const toConnect = Array.from(createdElements).filter(elm => elm.parentElement) + if (toConnect.length > 0) { + return Promise.all(toConnect.map(connectElement2)).then(waitLoop2) + } + return resolved2 + } + win2.document.createElement = function patchedCreateElement(tagName) { + const elm = orgDocumentCreateElement.call(win2.document, tagName) + patchElement2(elm) + return elm + } + win2.document.createElementNS = function patchedCreateElement(namespaceURI, tagName) { + const elm = orgDocumentCreateElementNS.call(win2.document, namespaceURI, tagName) + patchElement2(elm) + return elm + } + tmrId = globalThis.setTimeout(timeoutExceeded, opts.timeout) + plt.$resourcesUrl$ = new URL(opts.resourcesUrl || './', doc.baseURI).href + patchChild2(win2.document.body) + waitLoop2().then(hydratedComplete).catch(hydratedError) + } catch (e) { + hydratedError(e) + } + } + async function hydrateComponent(win2, results, tagName, elm, waitingElements) { + tagName = tagName.toLowerCase() + const Cstr = loadModule({ + $tagName$: tagName, + $flags$: null, + }) + if (Cstr != null) { + const cmpMeta = Cstr.cmpMeta + if (cmpMeta != null) { + waitingElements.add(elm) + const hostRef = getHostRef(this) + addHostEventListeners(this, hostRef, cmpMeta.$listeners$) + try { + connectedCallback(elm) + await elm.componentOnReady() + results.hydratedCount++ + const ref = getHostRef(elm) + const modeName = !ref.$modeName$ ? '$' : ref.$modeName$ + if (!results.components.some(c => c.tag === tagName && c.mode === modeName)) { + results.components.push({ + tag: tagName, + mode: modeName, + count: 0, + depth: -1, + }) + } + } catch (e) { + win2.console.error(e) + } + waitingElements.delete(elm) + } + } + } + function isValidComponent(elm, opts) { + if (elm != null && elm.nodeType === 1) { + const tagName = elm.nodeName + if (typeof tagName === 'string' && tagName.includes('-')) { + if (opts.excludeComponents.includes(tagName.toLowerCase())) { + return false + } + return true + } + } + return false + } + function shouldHydrate(elm) { + if (elm.nodeType === 9) { + return true + } + if (NO_HYDRATE_TAGS.has(elm.nodeName)) { + return false + } + if (elm.hasAttribute('no-prerender')) { + return false + } + const parentNode = elm.parentNode + if (parentNode == null) { + return true + } + return shouldHydrate(parentNode) + } + var NO_HYDRATE_TAGS = /* @__PURE__ */ new Set([ + 'CODE', + 'HEAD', + 'IFRAME', + 'INPUT', + 'OBJECT', + 'OUTPUT', + 'NOSCRIPT', + 'PRE', + 'SCRIPT', + 'SELECT', + 'STYLE', + 'TEMPLATE', + 'TEXTAREA', + ]) + function renderCatchError(opts, results, err2) { + const diagnostic = { + level: 'error', + type: 'build', + header: 'Hydrate Error', + messageText: '', + relFilePath: void 0, + absFilePath: void 0, + lines: [], + } + if (opts.url) { + try { + const u = new URL(opts.url) + if (u.pathname !== '/') { + diagnostic.header += ': ' + u.pathname + } + } catch (e) {} + } + if (err2 != null) { + if (err2.stack != null) { + diagnostic.messageText = err2.stack.toString() + } else if (err2.message != null) { + diagnostic.messageText = err2.message.toString() + } else { + diagnostic.messageText = err2.toString() + } + } + results.diagnostics.push(diagnostic) + } + function printTag(elm) { + let tag = `<${elm.nodeName.toLowerCase()}` + if (Array.isArray(elm.attributes)) { + for (let i2 = 0; i2 < elm.attributes.length; i2++) { + const attr = elm.attributes[i2] + tag += ` ${attr.name}` + if (attr.value !== '') { + tag += `="${attr.value}"` + } + } + } + tag += `>` + return tag + } + function waitingOnElementMsg(waitingElement) { + let msg = '' + if (waitingElement) { + const lines = [] + msg = ' - waiting on:' + let elm = waitingElement + while (elm && elm.nodeType !== 9 && elm.nodeName !== 'BODY') { + lines.unshift(printTag(elm)) + elm = elm.parentElement + } + let indent = '' + for (const ln of lines) { + indent += ' ' + msg += ` +${indent}${ln}` + } + } + return msg + } + function waitingOnElementsMsg(waitingElements) { + return Array.from(waitingElements).map(waitingOnElementMsg) + } + var cmpModules = /* @__PURE__ */ new Map() + var getModule = tagName => { + if (typeof tagName === 'string') { + tagName = tagName.toLowerCase() + const cmpModule = cmpModules.get(tagName) + if (cmpModule != null) { + return cmpModule[tagName] + } + } + return null + } + var loadModule = (cmpMeta, _hostRef, _hmrVersionId) => { + return getModule(cmpMeta.$tagName$) + } + var isMemberInElement = (elm, memberName) => { + if (elm != null) { + if (memberName in elm) { + return true + } + const cstr = getModule(elm.nodeName) + if (cstr != null) { + const hostRef = cstr + if (hostRef != null && hostRef.cmpMeta != null && hostRef.cmpMeta.$members$ != null) { + return memberName in hostRef.cmpMeta.$members$ + } + } + } + return false + } + var registerComponents = Cstrs => { + for (const Cstr of Cstrs) { + const exportName = Cstr.cmpMeta.$tagName$ + cmpModules.set(exportName, { + [exportName]: Cstr, + }) + } + } + var win = window + var doc = win.document + var writeTask = cb => { + nextTick(() => { + try { + cb() + } catch (e) { + consoleError(e) + } + }) + } + var resolved = /* @__PURE__ */ Promise.resolve() + var nextTick = cb => resolved.then(cb) + var defaultConsoleError = e => { + if (e != null) { + console.error(e.stack || e.message || e) + } + } + var consoleError = (e, el) => defaultConsoleError(e, el) + var plt = { + $flags$: 0, + $resourcesUrl$: '', + jmp: h2 => h2(), + raf: h2 => requestAnimationFrame(h2), + ael: (el, eventName, listener, opts) => el.addEventListener(eventName, listener, opts), + rel: (el, eventName, listener, opts) => el.removeEventListener(eventName, listener, opts), + ce: (eventName, opts) => new win.CustomEvent(eventName, opts), + } + var setPlatformHelpers = helpers => { + Object.assign(plt, helpers) + } + var supportsShadow = BUILD.shadowDom + var hostRefs = /* @__PURE__ */ new WeakMap() + var getHostRef = ref => hostRefs.get(ref) + var registerInstance = (lazyInstance, hostRef) => hostRefs.set((hostRef.$lazyInstance$ = lazyInstance), hostRef) + var registerHost = (elm, cmpMeta) => { + const hostRef = { + $flags$: 0, + $cmpMeta$: cmpMeta, + $hostElement$: elm, + $instanceValues$: /* @__PURE__ */ new Map(), + $renderCount$: 0, + } + hostRef.$onInstancePromise$ = new Promise(r => (hostRef.$onInstanceResolve$ = r)) + hostRef.$onReadyPromise$ = new Promise(r => (hostRef.$onReadyResolve$ = r)) + elm['s-p'] = [] + elm['s-rc'] = [] + return hostRefs.set(elm, hostRef) + } + var styles = /* @__PURE__ */ new Map() + + /*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + + function __decorate(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? (desc = Object.getOwnPropertyDescriptor(target, key)) : desc, + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') + r = Reflect.decorate(decorators, target, key, desc) + else + for (var i = decorators.length - 1; i >= 0; i--) + if ((d = decorators[i])) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r + } + + function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === 'object' && typeof Reflect.metadata === 'function') + return Reflect.metadata(metadataKey, metadataValue) + } + + class BrowserWindow { + /** + * Returns the width of the window + */ + get width() { + if (balBrowser.hasWindow) { + return window.innerWidth + } + return 0 + } + /** + * Returns the height of the window + */ + get height() { + if (balBrowser.hasWindow) { + return window.innerHeight + } + return 0 + } + } + class Browser { + constructor() { + this.window = new BrowserWindow() + } + /** + * Is true when it is a Safari browser + */ + get isSafari() { + return /^((?!chrome|android).)*safari/i.test(this.userAgent) + } + /** + * Is true when the window object is defined + */ + get hasWindow() { + return typeof window !== 'undefined' + } + /** + * Is true when the navigator object is defined + */ + get hasNavigator() { + return typeof navigator !== 'undefined' + } + /** + * Is true when the document object is defined + */ + get hasDocument() { + return typeof document !== 'undefined' + } + /** + * Returns a string with the user agents + */ + get userAgent() { + var _a + if (this.hasWindow && this.hasNavigator) { + return (_a = navigator.userAgent) !== null && _a !== void 0 ? _a : '' + } + return '' + } + } + const balBrowser = new Browser() + + const BALOISE_SESSION_KEY = 'baloise-persist-config' + + const defaultLoggerConfig = { + components: [], + event: false, + lifecycle: false, + render: false, + custom: false, + } + const getConfig = () => { + let loggerConfig = defaultLoggerConfig + if ( + balBrowser.hasWindow && + window.BaloiseDesignSystem && + window.BaloiseDesignSystem.config && + window.BaloiseDesignSystem.config.logger + ) { + loggerConfig = window.BaloiseDesignSystem.config.logger + } + return loggerConfig + } + const buildLogger = tag => { + const l = (type, message, ...optionalParams) => { + const config = getConfig() + if (config.components.includes(tag) && config[type]) { + console.log(message, ...optionalParams) + } + } + return { + custom: (message, ...optionalParams) => l('custom', ` ➡️ [${tag}] - ${message}`, ...optionalParams), + lifecycle: (lifecycleName, ...optionalParams) => + l( + 'lifecycle', + `${ + lifecycleName === 'connectedCallback' + ? '🟢' + : lifecycleName === 'disconnectedCallback' + ? '🔴' + : lifecycleName === 'componentDidLoad' + ? '🏁' + : ' ➡️' + } [${tag}] - (${lifecycleName})`, + ...optionalParams, + ), + event: (eventName, ...optionalParams) => l('event', `🔥 [${tag}] - (${eventName})`, ...optionalParams), + render: (...optionalParams) => l('render', `🖌️ [${tag}] - (render)`, ...optionalParams), + } + } + function Logger(tag = 'unknown') { + return function (target, _propertyKey, _descriptor) { + const { connectedCallback, disconnectedCallback, render, componentDidLoad, createLogger } = target + const log = buildLogger(tag) + target.connectedCallback = function () { + log.lifecycle(`connectedCallback`, this) + const events = Object.keys(this) + .filter(n => n.startsWith('bal')) + .filter(n => typeof this[n] === 'object') + for (let index = 0; index < events.length; index++) { + const event = events[index] + const emitter = this[event] + this[event] = { + emit: (...args) => { + log.event(event, this, ...args) + return emitter.emit.call(this, ...args) + }, + } + } + createLogger.call(this, log.custom) + return connectedCallback && connectedCallback.call(this) + } + target.disconnectedCallback = function () { + log.lifecycle(`disconnectedCallback`, this) + return disconnectedCallback && disconnectedCallback.call(this) + } + target.componentDidLoad = function () { + log.lifecycle(`componentDidLoad`, this) + return componentDidLoad && componentDidLoad.call(this) + } + target.render = function () { + log.render(this) + return render.call(this) + } + } + } + + // generated file + const balIconYoutube$1 = + '' + const balIconXing$1 = + '' + const balIconX$1 = + '' + const balIconWeb$1 = + '' + const balIconUpload$1 = + '' + const balIconTwitter$1 = + '' + const balIconTrash$1 = + '' + const balIconPlus$1 = + '' + const balIconNavGoUp$1 = + '' + const balIconNavGoRight$1 = + '' + const balIconNavGoLeft$1 = + '' + const balIconNavGoDown$1 = + '' + const balIconMinus$1 = + '' + const balIconMenuBars$1 = + '' + const balIconLinkedin$1 = + '' + const balIconInstagram$1 = + '' + const balIconInfoCircle$1 = + '' + const balIconFacebook$1 = + '' + const balIconEdit$1 = + '' + const balIconDocument$1 = + '' + const balIconDate$1 = + '' + const balIconClose$1 = + '' + const balIconCheck$1 = + '' + const balIconCaretUp$1 = + '' + const balIconCaretRight$1 = + '' + const balIconCaretLeft$1 = + '' + const balIconCaretDown$1 = + '' + + const defaultIcons = { + balIconClose: balIconClose$1, + balIconInfoCircle: balIconInfoCircle$1, + balIconPlus: balIconPlus$1, + balIconMinus: balIconMinus$1, + balIconEdit: balIconEdit$1, + balIconTrash: balIconTrash$1, + balIconNavGoLeft: balIconNavGoLeft$1, + balIconNavGoRight: balIconNavGoRight$1, + balIconNavGoDown: balIconNavGoDown$1, + balIconNavGoUp: balIconNavGoUp$1, + balIconCheck: balIconCheck$1, + balIconDate: balIconDate$1, + balIconDocument: balIconDocument$1, + balIconUpload: balIconUpload$1, + balIconMenuBars: balIconMenuBars$1, + balIconFacebook: balIconFacebook$1, + balIconInstagram: balIconInstagram$1, + balIconLinkedin: balIconLinkedin$1, + balIconTwitter: balIconTwitter$1, + balIconX: balIconX$1, + balIconXing: balIconXing$1, + balIconYoutube: balIconYoutube$1, + balIconWeb: balIconWeb$1, + balIconCaretDown: balIconCaretDown$1, + balIconCaretLeft: balIconCaretLeft$1, + balIconCaretRight: balIconCaretRight$1, + balIconCaretUp: balIconCaretUp$1, + } + const defaultConfig = { + region: 'CH', + language: 'de', + allowedLanguages: ['de', 'fr', 'it', 'en'], + icons: defaultIcons, + fallbackLanguage: 'de', + logger: defaultLoggerConfig, + animated: true, + httpFormSubmit: true, + } + const defaultLocale$2 = `${defaultConfig.language}-${defaultConfig.region}` + + class Config { + constructor() { + this._componentObservers = [] + this._observers = [] + this._config = defaultConfig + } + get locale() { + return `${this._config.language}-${this._config.region}` + } + get region() { + return this._config.region + } + set region(region) { + if (region !== this._config.region) { + this._config.region = region + this._notify() + } + } + get language() { + return this._config.language + } + set language(language) { + if (language !== this._config.language) { + if (this._config.allowedLanguages.includes(language)) { + this._config.language = language + } else { + this._config.language = this._config.fallbackLanguage + } + this._notify() + } + } + get allowedLanguages() { + return this._config.allowedLanguages + } + set allowedLanguages(allowedLanguages) { + if (allowedLanguages !== this._config.allowedLanguages) { + this._config.allowedLanguages = allowedLanguages + this._notify() + } + } + get icons() { + return this._config.icons + } + set icons(icons) { + this._config.icons = Object.assign(Object.assign({}, this._config.icons), icons) + this._notify() + } + get logger() { + return this._config.logger + } + set logger(logger) { + this._config.logger = Object.assign({}, logger) + this._notify() + } + get animated() { + return this._config.animated + } + set animated(animated) { + this._config.animated = animated + this._notify() + } + get httpFormSubmit() { + return this._config.httpFormSubmit + } + set httpFormSubmit(httpFormSubmit) { + this._config.httpFormSubmit = httpFormSubmit + this._notify() + } + attach(observer) { + const isExist = this._observers.includes(observer) + if (isExist) { + return console.log('Subject: Observer has been attached already.') + } + this._observers.push(observer) + observer.configChanged(this._config) + } + detach(observer) { + const observerIndex = this._observers.indexOf(observer) + if (observerIndex === -1) { + return console.log('Subject: Nonexistent observer.') + } + this._observers.splice(observerIndex, 1) + } + attachComponent(observer) { + const isExist = this._componentObservers.includes(observer) + if (isExist) { + return console.log('Subject: Observer has been attached already.') + } + this._componentObservers.push(observer) + observer.configChanged(this._config) + } + detachComponent(observer) { + const observerIndex = this._componentObservers.indexOf(observer) + if (observerIndex === -1) { + return console.log('Subject: Nonexistent observer.') + } + this._componentObservers.splice(observerIndex, 1) + } + toString() { + return JSON.stringify(this._config) + } + reset(config) { + this._config = Object.assign(Object.assign(Object.assign({}, this._config), config), { + icons: Object.assign(Object.assign({}, this._config.icons), config.icons), + }) + this._notify(false) + } + _notify(all = true) { + for (const observer of this._componentObservers) { + observer.configChanged(this._config) + } + if (all) { + for (const observer of this._observers) { + observer.configChanged(this._config) + } + } + if (balBrowser.hasWindow) { + saveConfig(window, this._config) + } + } + } + const config = /*@__PURE__*/ new Config() + const configFromSession = win => { + try { + const configStr = win.sessionStorage.getItem(BALOISE_SESSION_KEY) + return configStr !== null ? JSON.parse(configStr) : {} + } catch (e) { + return {} + } + } + const saveConfig = (win, c) => { + try { + win.sessionStorage.setItem(BALOISE_SESSION_KEY, JSON.stringify(c)) + } catch (e) { + return + } + } + + const setupConfig = (userConfig = {}, win = {}) => { + if (Object.keys(win).length === 0 && balBrowser.hasWindow) { + win = window + } + win.BaloiseDesignSystem = win.BaloiseDesignSystem || {} + config.reset( + Object.assign(Object.assign(Object.assign({}, configFromSession(win)), userConfig), { + icons: Object.assign(Object.assign({}, configFromSession(win).icons), userConfig.icons), + }), + ) + win.BaloiseDesignSystem.config = config + } + + function ListenToConfig() { + return function (target, _propertyKey, _descriptor) { + const { connectedCallback, disconnectedCallback } = target + target.connectedCallback = function () { + attachComponentToConfig(this) + return connectedCallback && connectedCallback.call(this) + } + target.disconnectedCallback = function () { + detachComponentFromConfig(this) + return disconnectedCallback && disconnectedCallback.call(this) + } + } + } + + const useBalConfig = () => { + if (!balBrowser.hasWindow) { + return + } + const win = window + return win && win.BaloiseDesignSystem && win.BaloiseDesignSystem.config + } + const attachComponentToConfig = observer => { + const config = useBalConfig() + if (config) { + config.attachComponent(observer) + } + } + const detachComponentFromConfig = observer => { + const config = useBalConfig() + if (config) { + config.detachComponent(observer) + } + } + const updateBalLanguage = language => { + const config = useBalConfig() + if (config) { + config.language = language + } + } + const updateBalIcons = icons => { + const config = useBalConfig() + if (config) { + config.icons = Object.assign(Object.assign({}, config.icons), icons) + } + } + const updateBalAnimated = animated => { + const config = useBalConfig() + if (config) { + config.animated = animated + } + } + + const rIC = (callback, timeout = 5000) => { + if (balBrowser.hasWindow && 'requestIdleCallback' in window) { + window.requestIdleCallback(callback, { timeout }) + } else { + setTimeout(callback, 32) + } + } + const wait = (ms = 0) => { + return new Promise(resolve => { + setTimeout(() => resolve(), ms) + }) + } + const debounceEvent = (ev, wait) => { + const original = ev._original || ev + return { + _original: ev, + emit: debounce$1(original.emit.bind(original), wait), + } + } + const debounce$1 = (func, wait = 0) => { + let timer + return (...args) => { + clearTimeout(timer) + timer = setTimeout(func, wait, ...args) + } + } + const hasTagName = (element, tag) => { + return element && element.tagName && element.tagName === tag.toUpperCase() + } + const isDescendant = (parent, child) => { + let node = child.parentNode + while (node != null) { + if (node == parent) { + return true + } + node = node.parentNode + } + return false + } + const hasParent = (parentTag, child) => { + let node = child.parentNode + while (node != null) { + if (node.tagName === parentTag.toUpperCase()) { + return true + } + node = node.parentNode + } + return false + } + /** + * Waits for a component to be ready for + * both custom element and non-custom element builds. + * If non-custom element build, el.componentOnReady + * will be used. + * For custom element builds, we wait a frame + * so that the inner contents of the component + * have a chance to render. + * + * Use this utility rather than calling + * el.componentOnReady yourself. + */ + const componentOnReady = (el, callback) => { + if (el.componentOnReady !== null && el.componentOnReady !== undefined) { + el.componentOnReady().then(resolvedEl => callback(resolvedEl)) + } else { + raf(() => callback(el)) + } + } + /** + * Patched version of requestAnimationFrame that avoids ngzone + * Use only when you know ngzone should not run + */ + const raf = h => { + if (typeof __zone_symbol__requestAnimationFrame === 'function') { + return __zone_symbol__requestAnimationFrame(h) + } + if (typeof requestAnimationFrame === 'function') { + return requestAnimationFrame(h) + } + return setTimeout(h) + } + const transitionEndAsync = (el, expectedDuration = 0) => { + return new Promise(resolve => { + transitionEnd(el, expectedDuration, resolve) + }) + } + /** + * Allows developer to wait for a transition + * to finish and fallback to a timer if the + * transition is cancelled or otherwise + * never finishes. Also see transitionEndAsync + * which is an await-able version of this. + */ + const transitionEnd = (el, expectedDuration = 0, callback) => { + let unRegTrans + let animationTimeout + const opts = { passive: true } + const ANIMATION_FALLBACK_TIMEOUT = 500 + const unregister = () => { + if (unRegTrans) { + unRegTrans() + } + } + const onTransitionEnd = ev => { + if (ev === undefined || el === ev.target) { + unregister() + callback(ev) + } + } + if (el) { + el.addEventListener('webkitTransitionEnd', onTransitionEnd, opts) + el.addEventListener('transitionend', onTransitionEnd, opts) + animationTimeout = setTimeout(onTransitionEnd, expectedDuration + ANIMATION_FALLBACK_TIMEOUT) + unRegTrans = () => { + if (animationTimeout) { + clearTimeout(animationTimeout) + animationTimeout = undefined + } + el.removeEventListener('webkitTransitionEnd', onTransitionEnd, opts) + el.removeEventListener('transitionend', onTransitionEnd, opts) + } + } + return unregister + } + const addEventListener = (el, eventName, callback, opts) => { + if (balBrowser.hasWindow) { + const config = useBalConfig() + if (config) { + const ael = config._ael + if (ael) { + return ael(el, eventName, callback, opts) + } else if (config._ael) { + return config._ael(el, eventName, callback, opts) + } + } + } + return el.addEventListener(eventName, callback, opts) + } + const removeEventListener = (el, eventName, callback, opts) => { + if (balBrowser.hasWindow) { + const config = useBalConfig() + if (config) { + const rel = config._rel + if (rel) { + return rel(el, eventName, callback, opts) + } else if (config._rel) { + return config._rel(el, eventName, callback, opts) + } + } + } + return el.removeEventListener(eventName, callback, opts) + } + const deepReady = async (el, full = false) => { + const element = el + if (element) { + if (element.componentOnReady !== null && element.componentOnReady !== undefined) { + const stencilEl = await element.componentOnReady() + if (!full && stencilEl !== null && stencilEl !== undefined) { + return + } + } + await Promise.all(Array.from(element.children).map(child => deepReady(child, full))) + } + } + const waitForComponent = async el => { + await deepReady(el, true) + await waitAfterFramePaint() + await waitAfterIdleCallback() + } + const isChildOfEventTarget = async (ev, el, callback) => { + if (ev && ev.target && el && el !== ev.target && isDescendant(ev.target, el)) { + callback() + } + } + const waitAfterFramePaint = () => { + return new Promise(resolve => raf(() => runHighPrioritizedTask(resolve))) + } + const waitAfterIdleCallback = () => { + return new Promise(resolve => rIC(() => runHighPrioritizedTask(resolve))) + } + const runHighPrioritizedTask = callback => { + if (balBrowser.hasWindow && 'MessageChannel' in window) { + const messageChannel = new window.MessageChannel() + messageChannel.port1.onmessage = callback + messageChannel.port2.postMessage(undefined) + } else { + setTimeout(callback, 32) + } + } + + const bemReturn = selector => ({ + class: (condition = true) => ({ [selector]: condition }), + element: bemElement(selector), + modifier: bemModifier(selector), + }) + const bemElement = selector => name => bemReturn(`${selector}__${name}`) + const bemModifier = selector => name => bemReturn(`${selector}--${name}`) + const BEM = { block: name => bemReturn(`bal-${name}`) } + + const balAccordionCss = + '.bal-accordion{display:block;position:relative;width:100%}.bal-accordion--card-v1,.bal-accordion--card-v2{margin-top:var(--bal-space-medium)}@media screen and (min-width: 769px),print{.bal-accordion--card-v1,.bal-accordion--card-v2{margin-top:var(--bal-space-medium-tablet)}}@media screen and (min-width: 1024px){.bal-accordion--card-v1,.bal-accordion--card-v2{margin-top:var(--bal-space-medium-desktop)}}.bal-accordion--card-v2{padding-left:var(--bal-space-medium);padding-right:var(--bal-space-medium);padding-bottom:var(--bal-space-medium)}@media screen and (min-width: 769px),print{.bal-accordion--card-v2{padding-left:var(--bal-space-medium-tablet);padding-right:var(--bal-space-medium-tablet);padding-bottom:var(--bal-space-medium-tablet)}}@media screen and (min-width: 1024px){.bal-accordion--card-v2{padding-left:var(--bal-space-medium-desktop);padding-right:var(--bal-space-medium-desktop);padding-bottom:var(--bal-space-medium-desktop)}}.bal-accordion__wrapper{display:-ms-flexbox;display:flex;-ms-flex-direction:column-reverse;flex-direction:column-reverse}.bal-accordion__trigger--card{margin-left:var(--bal-space-medium);margin-right:var(--bal-space-medium);margin-bottom:var(--bal-space-medium)}@media screen and (min-width: 769px),print{.bal-accordion__trigger--card{margin-left:var(--bal-space-medium-tablet);margin-right:var(--bal-space-medium-tablet);margin-bottom:var(--bal-space-medium-tablet)}}@media screen and (min-width: 1024px){.bal-accordion__trigger--card{margin-left:var(--bal-space-medium-desktop);margin-right:var(--bal-space-medium-desktop);margin-bottom:var(--bal-space-medium-desktop)}}.bal-accordion__content--card{margin-left:var(--bal-space-medium);margin-right:var(--bal-space-medium)}@media screen and (min-width: 769px),print{.bal-accordion__content--card{margin-left:var(--bal-space-medium-tablet);margin-right:var(--bal-space-medium-tablet)}}@media screen and (min-width: 1024px){.bal-accordion__content--card{margin-left:var(--bal-space-medium-desktop);margin-right:var(--bal-space-medium-desktop)}}.bal-accordion--animated{-webkit-transition:all var(--bal-animation-transition-duration) var(--bal-animation-transition-easing);transition:all var(--bal-animation-transition-duration) var(--bal-animation-transition-easing)}.bal-accordion--animated .bal-accordion__content{-webkit-transition:max-height var(--bal-animation-transition-duration) var(--bal-animation-transition-easing);transition:max-height var(--bal-animation-transition-duration) var(--bal-animation-transition-easing)}.bal-accordion__content{overflow:hidden;will-change:max-height}.bal-accordion--collapsing .bal-accordion__content{max-height:0 !important}.bal-accordion--collapsed .bal-accordion__content{display:none}.bal-accordion--expanding .bal-accordion__content{max-height:0}@media (prefers-reduced-motion: reduce){.bal-accordion,.bal-accordion__content{-webkit-transition:none !important;transition:none !important}}' + var BalAccordionStyle0 = balAccordionCss + + class Accordion { + constructor(hostRef) { + registerInstance(this, hostRef) + this.balChange = createEvent(this, 'balChange', 7) + this.balWillAnimate = createEvent(this, 'balWillAnimate', 7) + this.balDidAnimate = createEvent(this, 'balDidAnimate', 7) + this.componentId = `bal-accordion-${accordionIds++}` + /** + * PRIVATE METHODS + * ------------------------------------------------------ + */ + this.updateState = (initialUpdate = false) => { + if (this.active) { + this.expand(initialUpdate) + } else { + this.collapse(initialUpdate) + } + } + this.setState = state => { + this.state = state + if (this.version === 2) { + this.updateTriggerElement() + this.updateDetailsElement() + this.updateSummaryElement() + } + } + this.updateDetailsElement = () => { + const detailsElement = this.detailsElement + if (detailsElement) { + detailsElement.state = this.state + detailsElement.active = this.active + detailsElement.animated = this.animated + } + } + this.updateTriggerElement = () => { + const triggerElement = this.triggerElement + if (triggerElement) { + triggerElement.state = this.state + triggerElement.active = this.active + } + } + this.updateSummaryElement = () => { + const summaryElement = this.summaryElement + if (summaryElement) { + summaryElement.state = this.state + summaryElement.active = this.active + } + } + this.expand = (initialUpdate = false) => { + this.active = true + const detailsElement = this.detailsElement + const detailsWrapperElement = this.detailsWrapperElement + if (initialUpdate || detailsElement === null || detailsWrapperElement === null) { + this.setState(4 /* AccordionState.Expanded */) + return this.active + } + if (this.state === 4 /* AccordionState.Expanded */) { + return this.active + } + if (this.currentRaf !== undefined) { + cancelAnimationFrame(this.currentRaf) + } + if (this.shouldAnimate()) { + raf(() => { + this.setState(8 /* AccordionState.Expanding */) + this.currentRaf = raf(async () => { + const contentHeight = detailsWrapperElement.offsetHeight + const waitForTransition = transitionEndAsync(detailsElement, 300) + detailsElement.style.setProperty('max-height', `${contentHeight}px`) + this.balWillAnimate.emit(this.active) + await waitForTransition + this.setState(4 /* AccordionState.Expanded */) + detailsElement.style.removeProperty('max-height') + this.balDidAnimate.emit(this.active) + }) + }) + } else { + this.balWillAnimate.emit(this.active) + this.setState(4 /* AccordionState.Expanded */) + this.balDidAnimate.emit(this.active) + } + return this.active + } + this.collapse = (initialUpdate = false) => { + this.active = false + const detailsElement = this.detailsElement + if (initialUpdate || detailsElement === null) { + this.setState(1 /* AccordionState.Collapsed */) + return this.active + } + if (this.state === 1 /* AccordionState.Collapsed */) { + return this.active + } + if (this.currentRaf !== undefined) { + cancelAnimationFrame(this.currentRaf) + } + if (this.shouldAnimate()) { + this.currentRaf = raf(async () => { + const contentHeight = detailsElement.offsetHeight + detailsElement.style.setProperty('max-height', `${contentHeight}px`) + raf(async () => { + const waitForTransition = transitionEndAsync(detailsElement, 300) + this.setState(2 /* AccordionState.Collapsing */) + this.balDidAnimate.emit(this.active) + await waitForTransition + this.setState(1 /* AccordionState.Collapsed */) + detailsElement.style.removeProperty('max-height') + this.balDidAnimate.emit(this.active) + }) + }) + } else { + this.balDidAnimate.emit(this.active) + this.setState(1 /* AccordionState.Collapsed */) + this.balDidAnimate.emit(this.active) + } + return this.active + } + this.shouldAnimate = () => { + if (typeof window === 'undefined') { + return false + } + return this.animated + } + /** + * EVENT BINDING + * ------------------------------------------------------ + */ + this.onTriggerClickV1 = () => { + this.humanToggle() + } + this.state = 1 /* AccordionState.Collapsed */ + this.animated = true + this.active = false + this.debounce = 0 + this.openLabel = '' + this.openIcon = 'plus' + this.closeLabel = '' + this.closeIcon = 'close' + this.card = false + this.version = 1 + } + createLogger(log) { + this.log = log + } + async activeChanged(newActive, oldActive) { + if (newActive !== oldActive) { + this.active = newActive + this.updateState() + } + } + debounceChanged() { + this.balChange = debounceEvent(this.balChange, this.debounce) + } + /** + * LIFECYCLE + * ------------------------------------------------------ + */ + async connectedCallback() { + this.debounceChanged() + await waitForComponent(this.el) + if (this.active) { + this.activeChanged(this.active, false) + } + this.updateState(true) + } + /** + * LISTENERS + * ------------------------------------------------------ + */ + /** + * @internal define config for the component + */ + async configChanged(state) { + this.animated = state.animated + } + /** + * PUBLIC METHODS + * ------------------------------------------------------ + */ + /** + * Opens the accordion + */ + async present() { + return this.expand() + } + /** + * Closes the accordion + */ + async dismiss() { + return this.collapse() + } + /** + * Triggers the accordion + */ + async toggle() { + if (this.active) { + return this.collapse() + } else { + return this.expand() + } + } + /** + * @internal + */ + async humanToggle() { + if (this.active) { + await this.collapse() + } else { + await this.expand() + } + this.balChange.emit(this.active) + return this.active + } + /** + * GETTERS + * ------------------------------------------------------ + */ + get summaryElement() { + var _a + return ( + ((_a = this.el) === null || _a === void 0 ? void 0 : _a.querySelector(`#${this.componentId}-summary`)) || null + ) + } + get triggerElement() { + var _a + return ( + ((_a = this.el) === null || _a === void 0 ? void 0 : _a.querySelector(`#${this.componentId}-trigger`)) || null + ) + } + get detailsElement() { + var _a + if (this.version === 1) { + return this.contentEl || null + } + return ( + ((_a = this.el) === null || _a === void 0 ? void 0 : _a.querySelector(`#${this.componentId}-details`)) || null + ) + } + get detailsWrapperElement() { + var _a + if (this.version === 1) { + return this.contentElWrapper || null + } + return ( + ((_a = this.el) === null || _a === void 0 + ? void 0 + : _a.querySelector(`#${this.componentId}-details > div`)) || null + ) + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + return this.version === 2 ? this.renderVersion2() : this.renderVersion1() + } + renderVersion2() { + const block = BEM.block('accordion') + return hAsync(Host, { + id: this.componentId, + class: Object.assign( + Object.assign( + Object.assign(Object.assign({}, block.class()), block.modifier('active').class(this.active)), + block.modifier('card-v2').class(this.card), + ), + block.modifier('animated').class(this.animated), + ), + }) + } + renderVersion1() { + const label = this.active ? this.closeLabel : this.openLabel + const icon = this.active ? this.closeIcon : this.openIcon + const block = BEM.block('accordion') + const expanded = + this.state === 4 /* AccordionState.Expanded */ || this.state === 8 /* AccordionState.Expanding */ + const buttonPart = expanded ? 'button expanded' : 'button' + const contentPart = expanded ? 'content expanded' : 'content' + return hAsync( + Host, + { + id: this.componentId, + class: Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign(Object.assign({}, block.class()), block.modifier('card-v1').class(this.card)), + block.modifier('active').class(this.active), + ), + block.modifier('expanding').class(this.state === 8 /* AccordionState.Expanding */), + ), + block.modifier('expanded').class(this.state === 4 /* AccordionState.Expanded */), + ), + block.modifier('collapsing').class(this.state === 2 /* AccordionState.Collapsing */), + ), + block.modifier('collapsed').class(this.state === 1 /* AccordionState.Collapsed */), + ), + block.modifier('animated').class(this.animated), + ), + }, + hAsync( + 'div', + { class: Object.assign({}, block.element('wrapper').class()) }, + hAsync( + 'div', + { + 'class': Object.assign( + Object.assign({}, block.element('trigger').class()), + block.element('trigger').modifier('card').class(this.card), + ), + 'data-testid': 'bal-accordion-summary', + }, + hAsync( + 'bal-button', + { + 'id': `${this.componentId}-button`, + 'aria-controls': `${this.componentId}-content`, + 'part': buttonPart, + 'data-testid': 'bal-accordion-trigger', + 'expanded': true, + 'color': 'info', + 'icon': icon, + 'onClick': this.onTriggerClickV1, + }, + label, + ), + ), + hAsync( + 'div', + { + 'id': `${this.componentId}-content`, + 'aria-labelledby': `${this.componentId}-button`, + 'role': 'region', + 'part': contentPart, + 'class': Object.assign( + Object.assign({}, block.element('content').class()), + block.element('content').modifier('card').class(this.card), + ), + 'ref': contentEl => (this.contentEl = contentEl), + }, + hAsync( + 'div', + { + 'id': `${this.componentId}-content-wrapper`, + 'data-testid': 'bal-accordion-details', + 'class': Object.assign({}, block.element('content').element('wrapper').class()), + 'ref': contentElWrapper => (this.contentElWrapper = contentElWrapper), + }, + hAsync('slot', null), + ), + ), + ), + ) + } + get el() { + return getElement(this) + } + static get watchers() { + return { + active: ['activeChanged'], + debounce: ['debounceChanged'], + } + } + static get style() { + return BalAccordionStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-accordion', + $members$: { + active: [1540], + debounce: [2], + openLabel: [1, 'open-label'], + openIcon: [1, 'open-icon'], + closeLabel: [1, 'close-label'], + closeIcon: [1, 'close-icon'], + card: [4], + version: [2], + state: [32], + animated: [32], + configChanged: [64], + present: [64], + dismiss: [64], + toggle: [64], + humanToggle: [64], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [['active', 'active']], + } + } + } + __decorate( + [ + Logger('bal-accordion'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + Accordion.prototype, + 'createLogger', + null, + ) + __decorate( + [ + ListenToConfig(), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Object]), + __metadata('design:returntype', Promise), + ], + Accordion.prototype, + 'configChanged', + null, + ) + let accordionIds = 0 + + const balAccordionDetailsCss = + '.bal-accordion__details{display:block;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;will-change:max-height;min-block-size:auto;min-height:auto;min-inline-size:auto;min-width:auto}.bal-accordion__details--animated{-webkit-transition:max-height var(--bal-animation-transition-duration) var(--bal-animation-transition-easing);transition:max-height var(--bal-animation-transition-duration) var(--bal-animation-transition-easing)}.bal-accordion__details--collapsing{max-height:0 !important}.bal-accordion__details--collapsed{display:none}.bal-accordion__details--expanding{max-height:0}@media (prefers-reduced-motion: reduce){.bal-accordion__details{-webkit-transition:none !important;transition:none !important}}' + var BalAccordionDetailsStyle0 = balAccordionDetailsCss + + class AccordionDetails { + constructor(hostRef) { + registerInstance(this, hostRef) + this.componentId = `bal-accordion-details-${accordionDetailIds++}` + /** + * PRIVATE METHODS + * ------------------------------------------------------ + */ + this.updateAccordionId = () => { + var _a + return (this.parentAccordionId = + (_a = this.parentAccordionElement) === null || _a === void 0 ? void 0 : _a.id) + } + this.parentAccordionId = undefined + this.state = 1 /* AccordionState.Collapsed */ + this.active = false + this.animated = true + } + createLogger(log) { + this.log = log + } + /** + * LIFECYCLE + * ------------------------------------------------------ + */ + connectedCallback() { + this.updateAccordionId() + } + componentWillRender() { + this.updateAccordionId() + } + /** + * GETTERS + * ------------------------------------------------------ + */ + get parentAccordionElement() { + var _a + return ((_a = this.el) === null || _a === void 0 ? void 0 : _a.closest('bal-accordion')) || null + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + const block = BEM.block('accordion').element('details') + const containerEl = block.element('container') + const wrapperEl = containerEl.element('wrapper') + const id = this.parentAccordionId ? `${this.parentAccordionId}-details` : this.componentId + const expanded = + this.state === 4 /* AccordionState.Expanded */ || this.state === 8 /* AccordionState.Expanding */ + const contentPart = expanded ? 'content expanded' : 'content' + return hAsync( + Host, + { + key: '46658e9e2842371f4faac02f3666f908f48000a2', + id: id, + class: Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign(Object.assign({}, block.class()), block.modifier('active').class(this.active)), + block.modifier('expanding').class(this.state === 8 /* AccordionState.Expanding */), + ), + block.modifier('expanded').class(this.state === 4 /* AccordionState.Expanded */), + ), + block.modifier('collapsing').class(this.state === 2 /* AccordionState.Collapsing */), + ), + block.modifier('collapsed').class(this.state === 1 /* AccordionState.Collapsed */), + ), + block.modifier('animated').class(this.animated), + ), + }, + hAsync( + 'div', + { + 'key': '4e2616b9946f33ce3a30c396f200dd2a8c16eed4', + 'id': `${id}-content`, + 'aria-labelledby': `${this.parentAccordionId}-trigger-button`, + 'role': 'region', + 'part': contentPart, + 'class': Object.assign({}, wrapperEl.class()), + 'data-testid': 'bal-accordion-details', + }, + hAsync('slot', { key: '76467aaa5660e88ab9a208fdf0577f203f000fcf' }), + ), + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalAccordionDetailsStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-accordion-details', + $members$: { + state: [2], + active: [4], + animated: [4], + parentAccordionId: [32], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + __decorate( + [ + Logger('bal-accordion-details'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + AccordionDetails.prototype, + 'createLogger', + null, + ) + let accordionDetailIds = 0 + + const stopEventBubbling = ev => { + if (ev) { + ev.preventDefault() + ev.stopPropagation() + } + } + const getInputTarget = ev => { + return ev.target + } + const getNativeInputValue = component => { + var _a + return ((_a = component.nativeInput) === null || _a === void 0 ? void 0 : _a.value) || '' + } + const getUpcomingValue = (component, ev) => { + var _a, _b + const value = ((_a = component.nativeInput) === null || _a === void 0 ? void 0 : _a.value) || '' + const idx = (_b = ev.target) === null || _b === void 0 ? void 0 : _b.selectionStart + return value.slice(0, idx) + ev.key + value.slice(idx + Math.abs(0)) + } + const inputSetBlur = component => { + if (component.nativeInput) { + component.nativeInput.blur() + } + } + const inputListenOnClick = (component, ev) => { + if ((component.disabled || component.readonly) && ev.target && ev.target === component.el) { + stopEventBubbling(ev) + } + } + const inputSetFocus = async component => { + var _a + await waitAfterIdleCallback() + ;(_a = component === null || component === void 0 ? void 0 : component.nativeInput) === null || _a === void 0 + ? void 0 + : _a.focus() + } + const inputHandleHostClick = (component, ev) => { + if (component.disabled || component.readonly) { + stopEventBubbling(ev) + } + } + const inputHandleClick = (component, ev) => { + if (!component.disabled && !component.readonly && component.balClick) { + component.balClick.emit(ev) + } + } + const inputHandleFocus = (component, ev) => { + component.focused = true + component.inputValue = component.value + if (!component.disabled && component.balFocus) { + component.balFocus.emit(ev) + } + } + const inputHandleReset = (component, defaultValue = undefined, timer) => { + component.value = defaultValue + component.inputValue = component.value + clearTimeout(timer) + timer = setTimeout(() => { + if (component.nativeInput) { + component.nativeInput.value = component.value + } + }) + } + const inputHandleBlur = (component, ev) => { + component.focused = false + if (!component.disabled && component.balBlur) { + component.balBlur.emit(ev) + } + } + const inputHandleChange = component => { + if (component.value !== component.inputValue) { + component.value = component.inputValue + component.balChange.emit(component.value) + } + } + + var commonjsGlobal = + typeof globalThis !== 'undefined' + ? globalThis + : typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : typeof self !== 'undefined' + ? self + : {} + + /** + * lodash 4.0.0 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null + } + + var lodash_isnil = isNil + + var lodash_isequal = { exports: {} } + + /** + * Lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + + ;(function (module, exports) { + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200 + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__' + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2 + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991 + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]' + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]' + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/ + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/ + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {} + typedArrayTags[float32Tag] = + typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = + typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = + typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = + typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = + true + typedArrayTags[argsTag] = + typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = + typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = + typedArrayTags[dateTag] = + typedArrayTags[errorTag] = + typedArrayTags[funcTag] = + typedArrayTags[mapTag] = + typedArrayTags[numberTag] = + typedArrayTags[objectTag] = + typedArrayTags[regexpTag] = + typedArrayTags[setTag] = + typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = + false + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = + typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')() + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function () { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util') + } catch (e) {} + })() + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = [] + + while (++index < length) { + var value = array[index] + if (predicate(value, index, array)) { + result[resIndex++] = value + } + } + return result + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length + + while (++index < length) { + array[offset + index] = values[index] + } + return array + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true + } + } + return false + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n) + + while (++index < n) { + result[index] = iteratee(index) + } + return result + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function (value) { + return func(value) + } + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key) + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key] + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size) + + map.forEach(function (value, key) { + result[++index] = [key, value] + }) + return result + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function (arg) { + return func(transform(arg)) + } + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size) + + set.forEach(function (value) { + result[++index] = value + }) + return result + } + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__'] + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function () { + var uid = /[^.]+$/.exec((coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO) || '') + return uid ? 'Symbol(src)_1.' + uid : '' + })() + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString + + /** Used to detect if a method is native. */ + var reIsNative = RegExp( + '^' + + funcToString + .call(hasOwnProperty) + .replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + + '$', + ) + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object) + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create') + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap) + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length + + this.clear() + while (++index < length) { + var entry = entries[index] + this.set(entry[0], entry[1]) + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {} + this.size = 0 + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key] + this.size -= result ? 1 : 0 + return result + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__ + if (nativeCreate) { + var result = data[key] + return result === HASH_UNDEFINED ? undefined : result + } + return hasOwnProperty.call(data, key) ? data[key] : undefined + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__ + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key) + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__ + this.size += this.has(key) ? 0 : 1 + data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value + return this + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear + Hash.prototype['delete'] = hashDelete + Hash.prototype.get = hashGet + Hash.prototype.has = hashHas + Hash.prototype.set = hashSet + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length + + this.clear() + while (++index < length) { + var entry = entries[index] + this.set(entry[0], entry[1]) + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = [] + this.size = 0 + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key) + + if (index < 0) { + return false + } + var lastIndex = data.length - 1 + if (index == lastIndex) { + data.pop() + } else { + splice.call(data, index, 1) + } + --this.size + return true + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key) + + return index < 0 ? undefined : data[index][1] + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1 + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key) + + if (index < 0) { + ++this.size + data.push([key, value]) + } else { + data[index][1] = value + } + return this + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear + ListCache.prototype['delete'] = listCacheDelete + ListCache.prototype.get = listCacheGet + ListCache.prototype.has = listCacheHas + ListCache.prototype.set = listCacheSet + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length + + this.clear() + while (++index < length) { + var entry = entries[index] + this.set(entry[0], entry[1]) + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0 + this.__data__ = { + hash: new Hash(), + map: new (Map || ListCache)(), + string: new Hash(), + } + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key) + this.size -= result ? 1 : 0 + return result + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key) + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key) + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size + + data.set(key, value) + this.size += data.size == size ? 0 : 1 + return this + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear + MapCache.prototype['delete'] = mapCacheDelete + MapCache.prototype.get = mapCacheGet + MapCache.prototype.has = mapCacheHas + MapCache.prototype.set = mapCacheSet + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length + + this.__data__ = new MapCache() + while (++index < length) { + this.add(values[index]) + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED) + return this + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value) + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd + SetCache.prototype.has = setCacheHas + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = (this.__data__ = new ListCache(entries)) + this.size = data.size + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache() + this.size = 0 + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key) + + this.size = data.size + return result + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key) + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key) + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__ + if (data instanceof ListCache) { + var pairs = data.__data__ + if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) { + pairs.push([key, value]) + this.size = ++data.size + return this + } + data = this.__data__ = new MapCache(pairs) + } + data.set(key, value) + this.size = data.size + return this + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear + Stack.prototype['delete'] = stackDelete + Stack.prototype.get = stackGet + Stack.prototype.has = stackHas + Stack.prototype.set = stackSet + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length + + for (var key in value) { + if ( + (inherited || hasOwnProperty.call(value, key)) && + !( + skipIndexes && + // Safari 9 has enumerable `arguments.length` in strict mode. + (key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length)) + ) + ) { + result.push(key) + } + } + return result + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length + while (length--) { + if (eq(array[length][0], key)) { + return length + } + } + return -1 + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object) + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)) + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag + } + return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value) + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack) + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other) + + objTag = objTag == argsTag ? objectTag : objTag + othTag = othTag == argsTag ? objectTag : othTag + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false + } + objIsArr = true + objIsObj = false + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack()) + return objIsArr || isTypedArray(object) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack) + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__') + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other + + stack || (stack = new Stack()) + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack) + } + } + if (!isSameTag) { + return false + } + stack || (stack = new Stack()) + return equalObjects(object, other, bitmask, customizer, equalFunc, stack) + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor + return pattern.test(toSource(value)) + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)] + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object) + } + var result = [] + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key) + } + } + return result + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false + } + // Assume cyclic values are equal. + var stacked = stack.get(array) + if (stacked && stack.get(other)) { + return stacked == other + } + var index = -1, + result = true, + seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined + + stack.set(array, other) + stack.set(other, array) + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index] + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack) + } + if (compared !== undefined) { + if (compared) { + continue + } + result = false + break + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if ( + !arraySome(other, function (othValue, othIndex) { + if ( + !cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack)) + ) { + return seen.push(othIndex) + } + }) + ) { + result = false + break + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + result = false + break + } + } + stack['delete'](array) + stack['delete'](other) + return result + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { + return false + } + object = object.buffer + other = other.buffer + + case arrayBufferTag: + if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false + } + return true + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other) + + case errorTag: + return object.name == other.name && object.message == other.message + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == other + '' + + case mapTag: + var convert = mapToArray + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG + convert || (convert = setToArray) + + if (object.size != other.size && !isPartial) { + return false + } + // Assume cyclic values are equal. + var stacked = stack.get(object) + if (stacked) { + return stacked == other + } + bitmask |= COMPARE_UNORDERED_FLAG + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other) + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack) + stack['delete'](object) + return result + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other) + } + } + return false + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length + + if (objLength != othLength && !isPartial) { + return false + } + var index = objLength + while (index--) { + var key = objProps[index] + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object) + if (stacked && stack.get(other)) { + return stacked == other + } + var result = true + stack.set(object, other) + stack.set(other, object) + + var skipCtor = isPartial + while (++index < objLength) { + key = objProps[index] + var objValue = object[key], + othValue = other[key] + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack) + } + // Recursively compare objects (susceptible to call stack limits). + if ( + !(compared === undefined + ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) + : compared) + ) { + result = false + break + } + skipCtor || (skipCtor = key == 'constructor') + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor + + // Non `Object` object instances with different constructors are not equal. + if ( + objCtor != othCtor && + 'constructor' in object && + 'constructor' in other && + !( + typeof objCtor == 'function' && + objCtor instanceof objCtor && + typeof othCtor == 'function' && + othCtor instanceof othCtor + ) + ) { + result = false + } + } + stack['delete'](object) + stack['delete'](other) + return result + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols) + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__ + return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key) + return baseIsNative(value) ? value : undefined + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag] + + try { + value[symToStringTag] = undefined + var unmasked = true + } catch (e) {} + + var result = nativeObjectToString.call(value) + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag + } else { + delete value[symToStringTag] + } + } + return result + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols + ? stubArray + : function (object) { + if (object == null) { + return [] + } + object = Object(object) + return arrayFilter(nativeGetSymbols(object), function (symbol) { + return propertyIsEnumerable.call(object, symbol) + }) + } + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ( + (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map()) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set()) != setTag) || + (WeakMap && getTag(new WeakMap()) != weakMapTag) + ) { + getTag = function (value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : '' + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag + case mapCtorString: + return mapTag + case promiseCtorString: + return promiseTag + case setCtorString: + return setTag + case weakMapCtorString: + return weakMapTag + } + } + return result + } + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length + return ( + !!length && + (typeof value == 'number' || reIsUint.test(value)) && + value > -1 && + value % 1 == 0 && + value < length + ) + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value + return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' + ? value !== '__proto__' + : value === null + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func + } + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto + + return value === proto + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value) + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func) + } catch (e) {} + try { + return func + '' + } catch (e) {} + } + return '' + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other) + } + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments( + (function () { + return arguments + })(), + ) + ? baseIsArguments + : function (value) { + return ( + isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee') + ) + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value) + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other) + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value) + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value + return value != null && (type == 'object' || type == 'function') + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object' + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object) + } + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return [] + } + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false + } + + module.exports = isEqual + })(lodash_isequal, lodash_isequal.exports) + + var isEqual = lodash_isequal.exports + + function _typeof(o) { + '@babel/helpers - typeof' + + return ( + (_typeof = + 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator + ? function (o) { + return typeof o + } + : function (o) { + return o && 'function' == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype + ? 'symbol' + : typeof o + }), + _typeof(o) + ) + } + + function toInteger$1(dirtyNumber) { + if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { + return NaN + } + var number = Number(dirtyNumber) + if (isNaN(number)) { + return number + } + return number < 0 ? Math.ceil(number) : Math.floor(number) + } + + function requiredArgs(required, args) { + if (args.length < required) { + throw new TypeError( + required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present', + ) + } + } + + /** + * @name toDate + * @category Common Helpers + * @summary Convert the given argument to an instance of Date. + * + * @description + * Convert the given argument to an instance of Date. + * + * If the argument is an instance of Date, the function returns its clone. + * + * If the argument is a number, it is treated as a timestamp. + * + * If the argument is none of the above, the function returns Invalid Date. + * + * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`. + * + * @param {Date|Number} argument - the value to convert + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + * + * @example + * // Clone the date: + * const result = toDate(new Date(2014, 1, 11, 11, 30, 30)) + * //=> Tue Feb 11 2014 11:30:30 + * + * @example + * // Convert the timestamp to date: + * const result = toDate(1392098430000) + * //=> Tue Feb 11 2014 11:30:30 + */ + function toDate(argument) { + requiredArgs(1, arguments) + var argStr = Object.prototype.toString.call(argument) + + // Clone the date + if (argument instanceof Date || (_typeof(argument) === 'object' && argStr === '[object Date]')) { + // Prevent the date to lose the milliseconds when passed to new Date() in IE10 + return new Date(argument.getTime()) + } else if (typeof argument === 'number' || argStr === '[object Number]') { + return new Date(argument) + } else { + if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') { + // eslint-disable-next-line no-console + console.warn( + "Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments", + ) + // eslint-disable-next-line no-console + console.warn(new Error().stack) + } + return new Date(NaN) + } + } + + /** + * @name addDays + * @category Day Helpers + * @summary Add the specified number of days to the given date. + * + * @description + * Add the specified number of days to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} - the new date with the days added + * @throws {TypeError} - 2 arguments required + * + * @example + * // Add 10 days to 1 September 2014: + * const result = addDays(new Date(2014, 8, 1), 10) + * //=> Thu Sep 11 2014 00:00:00 + */ + function addDays(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments) + var date = toDate(dirtyDate) + var amount = toInteger$1(dirtyAmount) + if (isNaN(amount)) { + return new Date(NaN) + } + if (!amount) { + // If 0 days, no-op to avoid changing times in the hour before end of DST + return date + } + date.setDate(date.getDate() + amount) + return date + } + + /** + * @name addMonths + * @category Month Helpers + * @summary Add the specified number of months to the given date. + * + * @description + * Add the specified number of months to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the months added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 5 months to 1 September 2014: + * const result = addMonths(new Date(2014, 8, 1), 5) + * //=> Sun Feb 01 2015 00:00:00 + */ + function addMonths(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments) + var date = toDate(dirtyDate) + var amount = toInteger$1(dirtyAmount) + if (isNaN(amount)) { + return new Date(NaN) + } + if (!amount) { + // If 0 months, no-op to avoid changing times in the hour before end of DST + return date + } + var dayOfMonth = date.getDate() + + // The JS Date object supports date math by accepting out-of-bounds values for + // month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and + // new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we + // want except that dates will wrap around the end of a month, meaning that + // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So + // we'll default to the end of the desired month by adding 1 to the desired + // month and using a date of 0 to back up one day to the end of the desired + // month. + var endOfDesiredMonth = new Date(date.getTime()) + endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0) + var daysInMonth = endOfDesiredMonth.getDate() + if (dayOfMonth >= daysInMonth) { + // If we're already at the end of the month, then this is the correct date + // and we're done. + return endOfDesiredMonth + } else { + // Otherwise, we now know that setting the original day-of-month value won't + // cause an overflow, so set the desired day-of-month. Note that we can't + // just set the date of `endOfDesiredMonth` because that object may have had + // its time changed in the unusual case where where a DST transition was on + // the last day of the month and its local time was in the hour skipped or + // repeated next to a DST transition. So we use `date` instead which is + // guaranteed to still have the original time. + date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth) + return date + } + } + + /** + * @name addMilliseconds + * @category Millisecond Helpers + * @summary Add the specified number of milliseconds to the given date. + * + * @description + * Add the specified number of milliseconds to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the milliseconds added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 750 milliseconds to 10 July 2014 12:45:30.000: + * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) + * //=> Thu Jul 10 2014 12:45:30.750 + */ + function addMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments) + var timestamp = toDate(dirtyDate).getTime() + var amount = toInteger$1(dirtyAmount) + return new Date(timestamp + amount) + } + + var defaultOptions = {} + function getDefaultOptions() { + return defaultOptions + } + + /** + * @name startOfWeek + * @category Week Helpers + * @summary Return the start of a week for the given date. + * + * @description + * Return the start of a week for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Date} the start of a week + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // The start of a week for 2 September 2014 11:55:00: + * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sun Aug 31 2014 00:00:00 + * + * @example + * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: + * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) + * //=> Mon Sep 01 2014 00:00:00 + */ + function startOfWeek(dirtyDate, options) { + var _ref, + _ref2, + _ref3, + _options$weekStartsOn, + _options$locale, + _options$locale$optio, + _defaultOptions$local, + _defaultOptions$local2 + requiredArgs(1, arguments) + var defaultOptions = getDefaultOptions() + var weekStartsOn = toInteger$1( + (_ref = + (_ref2 = + (_ref3 = + (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== + null && _options$weekStartsOn !== void 0 + ? _options$weekStartsOn + : options === null || options === void 0 + ? void 0 + : (_options$locale = options.locale) === null || _options$locale === void 0 + ? void 0 + : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 + ? void 0 + : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 + ? _ref3 + : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 + ? _ref2 + : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 + ? void 0 + : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 + ? void 0 + : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 + ? _ref + : 0, + ) + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively') + } + var date = toDate(dirtyDate) + var day = date.getDay() + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn + date.setDate(date.getDate() - diff) + date.setHours(0, 0, 0, 0) + return date + } + + /** + * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. + * They usually appear for dates that denote time before the timezones were introduced + * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 + * and GMT+01:00:00 after that date) + * + * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, + * which would lead to incorrect calculations. + * + * This function returns the timezone offset in milliseconds that takes seconds in account. + */ + function getTimezoneOffsetInMilliseconds(date) { + var utcDate = new Date( + Date.UTC( + date.getFullYear(), + date.getMonth(), + date.getDate(), + date.getHours(), + date.getMinutes(), + date.getSeconds(), + date.getMilliseconds(), + ), + ) + utcDate.setUTCFullYear(date.getFullYear()) + return date.getTime() - utcDate.getTime() + } + + /** + * @name startOfDay + * @category Day Helpers + * @summary Return the start of a day for the given date. + * + * @description + * Return the start of a day for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a day + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a day for 2 September 2014 11:55:00: + * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 02 2014 00:00:00 + */ + function startOfDay(dirtyDate) { + requiredArgs(1, arguments) + var date = toDate(dirtyDate) + date.setHours(0, 0, 0, 0) + return date + } + + /** + * @name addYears + * @category Year Helpers + * @summary Add the specified number of years to the given date. + * + * @description + * Add the specified number of years to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of years to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the years added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 5 years to 1 September 2014: + * const result = addYears(new Date(2014, 8, 1), 5) + * //=> Sun Sep 01 2019 00:00:00 + */ + function addYears(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments) + var amount = toInteger$1(dirtyAmount) + return addMonths(dirtyDate, amount * 12) + } + + /** + * Days in 1 week. + * + * @name daysInWeek + * @constant + * @type {number} + * @default + */ + + /** + * Milliseconds in 1 minute + * + * @name millisecondsInMinute + * @constant + * @type {number} + * @default + */ + var millisecondsInMinute = 60000 + + /** + * Milliseconds in 1 hour + * + * @name millisecondsInHour + * @constant + * @type {number} + * @default + */ + var millisecondsInHour = 3600000 + + /** + * Milliseconds in 1 second + * + * @name millisecondsInSecond + * @constant + * @type {number} + * @default + */ + var millisecondsInSecond = 1000 + + /** + * @name isSameDay + * @category Day Helpers + * @summary Are the given dates in the same day (and year and month)? + * + * @description + * Are the given dates in the same day (and year and month)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same day (and year and month) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? + * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0)) + * //=> true + * + * @example + * // Are 4 September and 4 October in the same day? + * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4)) + * //=> false + * + * @example + * // Are 4 September, 2014 and 4 September, 2015 in the same day? + * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4)) + * //=> false + */ + function isSameDay(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments) + var dateLeftStartOfDay = startOfDay(dirtyDateLeft) + var dateRightStartOfDay = startOfDay(dirtyDateRight) + return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime() + } + + /** + * @name isDate + * @category Common Helpers + * @summary Is the given value a date? + * + * @description + * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes. + * + * @param {*} value - the value to check + * @returns {boolean} true if the given value is a date + * @throws {TypeError} 1 arguments required + * + * @example + * // For a valid date: + * const result = isDate(new Date()) + * //=> true + * + * @example + * // For an invalid date: + * const result = isDate(new Date(NaN)) + * //=> true + * + * @example + * // For some value: + * const result = isDate('2014-02-31') + * //=> false + * + * @example + * // For an object: + * const result = isDate({}) + * //=> false + */ + function isDate$1(value) { + requiredArgs(1, arguments) + return ( + value instanceof Date || + (_typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]') + ) + } + + /** + * @name isValid + * @category Common Helpers + * @summary Is the given date valid? + * + * @description + * Returns false if argument is Invalid Date and true otherwise. + * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate} + * Invalid Date is a Date, whose time value is NaN. + * + * Time value of Date: http://es5.github.io/#x15.9.1.1 + * + * @param {*} date - the date to check + * @returns {Boolean} the date is valid + * @throws {TypeError} 1 argument required + * + * @example + * // For the valid date: + * const result = isValid(new Date(2014, 1, 31)) + * //=> true + * + * @example + * // For the value, convertable into a date: + * const result = isValid(1393804800000) + * //=> true + * + * @example + * // For the invalid date: + * const result = isValid(new Date('')) + * //=> false + */ + function isValid(dirtyDate) { + requiredArgs(1, arguments) + if (!isDate$1(dirtyDate) && typeof dirtyDate !== 'number') { + return false + } + var date = toDate(dirtyDate) + return !isNaN(Number(date)) + } + + /** + * @name subMilliseconds + * @category Millisecond Helpers + * @summary Subtract the specified number of milliseconds from the given date. + * + * @description + * Subtract the specified number of milliseconds from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the milliseconds subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: + * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) + * //=> Thu Jul 10 2014 12:45:29.250 + */ + function subMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments) + var amount = toInteger$1(dirtyAmount) + return addMilliseconds(dirtyDate, -amount) + } + + function startOfUTCISOWeek(dirtyDate) { + requiredArgs(1, arguments) + var weekStartsOn = 1 + var date = toDate(dirtyDate) + var day = date.getUTCDay() + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn + date.setUTCDate(date.getUTCDate() - diff) + date.setUTCHours(0, 0, 0, 0) + return date + } + + function getUTCISOWeekYear(dirtyDate) { + requiredArgs(1, arguments) + var date = toDate(dirtyDate) + var year = date.getUTCFullYear() + var fourthOfJanuaryOfNextYear = new Date(0) + fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4) + fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0) + var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear) + var fourthOfJanuaryOfThisYear = new Date(0) + fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4) + fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0) + var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear) + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1 + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year + } else { + return year - 1 + } + } + + function startOfUTCISOWeekYear(dirtyDate) { + requiredArgs(1, arguments) + var year = getUTCISOWeekYear(dirtyDate) + var fourthOfJanuary = new Date(0) + fourthOfJanuary.setUTCFullYear(year, 0, 4) + fourthOfJanuary.setUTCHours(0, 0, 0, 0) + var date = startOfUTCISOWeek(fourthOfJanuary) + return date + } + + var MILLISECONDS_IN_WEEK$1 = 604800000 + function getUTCISOWeek(dirtyDate) { + requiredArgs(1, arguments) + var date = toDate(dirtyDate) + var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime() + + // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1 + } + + function startOfUTCWeek(dirtyDate, options) { + var _ref, + _ref2, + _ref3, + _options$weekStartsOn, + _options$locale, + _options$locale$optio, + _defaultOptions$local, + _defaultOptions$local2 + requiredArgs(1, arguments) + var defaultOptions = getDefaultOptions() + var weekStartsOn = toInteger$1( + (_ref = + (_ref2 = + (_ref3 = + (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== + null && _options$weekStartsOn !== void 0 + ? _options$weekStartsOn + : options === null || options === void 0 + ? void 0 + : (_options$locale = options.locale) === null || _options$locale === void 0 + ? void 0 + : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 + ? void 0 + : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 + ? _ref3 + : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 + ? _ref2 + : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 + ? void 0 + : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 + ? void 0 + : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 + ? _ref + : 0, + ) + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively') + } + var date = toDate(dirtyDate) + var day = date.getUTCDay() + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn + date.setUTCDate(date.getUTCDate() - diff) + date.setUTCHours(0, 0, 0, 0) + return date + } + + function getUTCWeekYear(dirtyDate, options) { + var _ref, + _ref2, + _ref3, + _options$firstWeekCon, + _options$locale, + _options$locale$optio, + _defaultOptions$local, + _defaultOptions$local2 + requiredArgs(1, arguments) + var date = toDate(dirtyDate) + var year = date.getUTCFullYear() + var defaultOptions = getDefaultOptions() + var firstWeekContainsDate = toInteger$1( + (_ref = + (_ref2 = + (_ref3 = + (_options$firstWeekCon = + options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && + _options$firstWeekCon !== void 0 + ? _options$firstWeekCon + : options === null || options === void 0 + ? void 0 + : (_options$locale = options.locale) === null || _options$locale === void 0 + ? void 0 + : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 + ? void 0 + : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 + ? _ref3 + : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 + ? _ref2 + : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 + ? void 0 + : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 + ? void 0 + : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 + ? _ref + : 1, + ) + + // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively') + } + var firstWeekOfNextYear = new Date(0) + firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate) + firstWeekOfNextYear.setUTCHours(0, 0, 0, 0) + var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options) + var firstWeekOfThisYear = new Date(0) + firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate) + firstWeekOfThisYear.setUTCHours(0, 0, 0, 0) + var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options) + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1 + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year + } else { + return year - 1 + } + } + + function startOfUTCWeekYear(dirtyDate, options) { + var _ref, + _ref2, + _ref3, + _options$firstWeekCon, + _options$locale, + _options$locale$optio, + _defaultOptions$local, + _defaultOptions$local2 + requiredArgs(1, arguments) + var defaultOptions = getDefaultOptions() + var firstWeekContainsDate = toInteger$1( + (_ref = + (_ref2 = + (_ref3 = + (_options$firstWeekCon = + options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && + _options$firstWeekCon !== void 0 + ? _options$firstWeekCon + : options === null || options === void 0 + ? void 0 + : (_options$locale = options.locale) === null || _options$locale === void 0 + ? void 0 + : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 + ? void 0 + : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 + ? _ref3 + : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 + ? _ref2 + : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 + ? void 0 + : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 + ? void 0 + : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 + ? _ref + : 1, + ) + var year = getUTCWeekYear(dirtyDate, options) + var firstWeek = new Date(0) + firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate) + firstWeek.setUTCHours(0, 0, 0, 0) + var date = startOfUTCWeek(firstWeek, options) + return date + } + + var MILLISECONDS_IN_WEEK = 604800000 + function getUTCWeek(dirtyDate, options) { + requiredArgs(1, arguments) + var date = toDate(dirtyDate) + var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime() + + // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + return Math.round(diff / MILLISECONDS_IN_WEEK) + 1 + } + + function addLeadingZeros(number, targetLength) { + var sign = number < 0 ? '-' : '' + var output = Math.abs(number).toString() + while (output.length < targetLength) { + output = '0' + output + } + return sign + output + } + + var dateLongFormatter = function dateLongFormatter(pattern, formatLong) { + switch (pattern) { + case 'P': + return formatLong.date({ + width: 'short', + }) + case 'PP': + return formatLong.date({ + width: 'medium', + }) + case 'PPP': + return formatLong.date({ + width: 'long', + }) + case 'PPPP': + default: + return formatLong.date({ + width: 'full', + }) + } + } + var timeLongFormatter = function timeLongFormatter(pattern, formatLong) { + switch (pattern) { + case 'p': + return formatLong.time({ + width: 'short', + }) + case 'pp': + return formatLong.time({ + width: 'medium', + }) + case 'ppp': + return formatLong.time({ + width: 'long', + }) + case 'pppp': + default: + return formatLong.time({ + width: 'full', + }) + } + } + var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) { + var matchResult = pattern.match(/(P+)(p+)?/) || [] + var datePattern = matchResult[1] + var timePattern = matchResult[2] + if (!timePattern) { + return dateLongFormatter(pattern, formatLong) + } + var dateTimeFormat + switch (datePattern) { + case 'P': + dateTimeFormat = formatLong.dateTime({ + width: 'short', + }) + break + case 'PP': + dateTimeFormat = formatLong.dateTime({ + width: 'medium', + }) + break + case 'PPP': + dateTimeFormat = formatLong.dateTime({ + width: 'long', + }) + break + case 'PPPP': + default: + dateTimeFormat = formatLong.dateTime({ + width: 'full', + }) + break + } + return dateTimeFormat + .replace('{{date}}', dateLongFormatter(datePattern, formatLong)) + .replace('{{time}}', timeLongFormatter(timePattern, formatLong)) + } + var longFormatters = { + p: timeLongFormatter, + P: dateTimeLongFormatter, + } + var longFormatters$1 = longFormatters + + var protectedDayOfYearTokens = ['D', 'DD'] + var protectedWeekYearTokens = ['YY', 'YYYY'] + function isProtectedDayOfYearToken(token) { + return protectedDayOfYearTokens.indexOf(token) !== -1 + } + function isProtectedWeekYearToken(token) { + return protectedWeekYearTokens.indexOf(token) !== -1 + } + function throwProtectedError(token, format, input) { + if (token === 'YYYY') { + throw new RangeError( + 'Use `yyyy` instead of `YYYY` (in `' + .concat(format, '`) for formatting years to the input `') + .concat(input, '`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md'), + ) + } else if (token === 'YY') { + throw new RangeError( + 'Use `yy` instead of `YY` (in `' + .concat(format, '`) for formatting years to the input `') + .concat(input, '`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md'), + ) + } else if (token === 'D') { + throw new RangeError( + 'Use `d` instead of `D` (in `' + .concat(format, '`) for formatting days of the month to the input `') + .concat(input, '`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md'), + ) + } else if (token === 'DD') { + throw new RangeError( + 'Use `dd` instead of `DD` (in `' + .concat(format, '`) for formatting days of the month to the input `') + .concat(input, '`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md'), + ) + } + } + + var formatDistanceLocale = { + lessThanXSeconds: { + one: 'less than a second', + other: 'less than {{count}} seconds', + }, + xSeconds: { + one: '1 second', + other: '{{count}} seconds', + }, + halfAMinute: 'half a minute', + lessThanXMinutes: { + one: 'less than a minute', + other: 'less than {{count}} minutes', + }, + xMinutes: { + one: '1 minute', + other: '{{count}} minutes', + }, + aboutXHours: { + one: 'about 1 hour', + other: 'about {{count}} hours', + }, + xHours: { + one: '1 hour', + other: '{{count}} hours', + }, + xDays: { + one: '1 day', + other: '{{count}} days', + }, + aboutXWeeks: { + one: 'about 1 week', + other: 'about {{count}} weeks', + }, + xWeeks: { + one: '1 week', + other: '{{count}} weeks', + }, + aboutXMonths: { + one: 'about 1 month', + other: 'about {{count}} months', + }, + xMonths: { + one: '1 month', + other: '{{count}} months', + }, + aboutXYears: { + one: 'about 1 year', + other: 'about {{count}} years', + }, + xYears: { + one: '1 year', + other: '{{count}} years', + }, + overXYears: { + one: 'over 1 year', + other: 'over {{count}} years', + }, + almostXYears: { + one: 'almost 1 year', + other: 'almost {{count}} years', + }, + } + var formatDistance = function formatDistance(token, count, options) { + var result + var tokenValue = formatDistanceLocale[token] + if (typeof tokenValue === 'string') { + result = tokenValue + } else if (count === 1) { + result = tokenValue.one + } else { + result = tokenValue.other.replace('{{count}}', count.toString()) + } + if (options !== null && options !== void 0 && options.addSuffix) { + if (options.comparison && options.comparison > 0) { + return 'in ' + result + } else { + return result + ' ago' + } + } + return result + } + var formatDistance$1 = formatDistance + + function buildFormatLongFn(args) { + return function () { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {} + // TODO: Remove String() + var width = options.width ? String(options.width) : args.defaultWidth + var format = args.formats[width] || args.formats[args.defaultWidth] + return format + } + } + + var dateFormats = { + full: 'EEEE, MMMM do, y', + long: 'MMMM do, y', + medium: 'MMM d, y', + short: 'MM/dd/yyyy', + } + var timeFormats = { + full: 'h:mm:ss a zzzz', + long: 'h:mm:ss a z', + medium: 'h:mm:ss a', + short: 'h:mm a', + } + var dateTimeFormats = { + full: "{{date}} 'at' {{time}}", + long: "{{date}} 'at' {{time}}", + medium: '{{date}}, {{time}}', + short: '{{date}}, {{time}}', + } + var formatLong = { + date: buildFormatLongFn({ + formats: dateFormats, + defaultWidth: 'full', + }), + time: buildFormatLongFn({ + formats: timeFormats, + defaultWidth: 'full', + }), + dateTime: buildFormatLongFn({ + formats: dateTimeFormats, + defaultWidth: 'full', + }), + } + var formatLong$1 = formatLong + + var formatRelativeLocale = { + lastWeek: "'last' eeee 'at' p", + yesterday: "'yesterday at' p", + today: "'today at' p", + tomorrow: "'tomorrow at' p", + nextWeek: "eeee 'at' p", + other: 'P', + } + var formatRelative = function formatRelative(token, _date, _baseDate, _options) { + return formatRelativeLocale[token] + } + var formatRelative$1 = formatRelative + + function buildLocalizeFn(args) { + return function (dirtyIndex, options) { + var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone' + var valuesArray + if (context === 'formatting' && args.formattingValues) { + var defaultWidth = args.defaultFormattingWidth || args.defaultWidth + var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth + valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth] + } else { + var _defaultWidth = args.defaultWidth + var _width = + options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth + valuesArray = args.values[_width] || args.values[_defaultWidth] + } + var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex + // @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it! + return valuesArray[index] + } + } + + var eraValues = { + narrow: ['B', 'A'], + abbreviated: ['BC', 'AD'], + wide: ['Before Christ', 'Anno Domini'], + } + var quarterValues = { + narrow: ['1', '2', '3', '4'], + abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'], + wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'], + } + + // Note: in English, the names of days of the week and months are capitalized. + // If you are making a new locale based on this one, check if the same is true for the language you're working on. + // Generally, formatted dates should look like they are in the middle of a sentence, + // e.g. in Spanish language the weekdays and months should be in the lowercase. + var monthValues = { + narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], + abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + wide: [ + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December', + ], + } + var dayValues = { + narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], + short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + } + var dayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night', + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night', + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night', + }, + } + var formattingDayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night', + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night', + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night', + }, + } + var ordinalNumber = function ordinalNumber(dirtyNumber, _options) { + var number = Number(dirtyNumber) + + // If ordinal numbers depend on context, for example, + // if they are different for different grammatical genders, + // use `options.unit`. + // + // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear', + // 'day', 'hour', 'minute', 'second'. + + var rem100 = number % 100 + if (rem100 > 20 || rem100 < 10) { + switch (rem100 % 10) { + case 1: + return number + 'st' + case 2: + return number + 'nd' + case 3: + return number + 'rd' + } + } + return number + 'th' + } + var localize = { + ordinalNumber: ordinalNumber, + era: buildLocalizeFn({ + values: eraValues, + defaultWidth: 'wide', + }), + quarter: buildLocalizeFn({ + values: quarterValues, + defaultWidth: 'wide', + argumentCallback: function argumentCallback(quarter) { + return quarter - 1 + }, + }), + month: buildLocalizeFn({ + values: monthValues, + defaultWidth: 'wide', + }), + day: buildLocalizeFn({ + values: dayValues, + defaultWidth: 'wide', + }), + dayPeriod: buildLocalizeFn({ + values: dayPeriodValues, + defaultWidth: 'wide', + formattingValues: formattingDayPeriodValues, + defaultFormattingWidth: 'wide', + }), + } + var localize$1 = localize + + function buildMatchFn(args) { + return function (string) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {} + var width = options.width + var matchPattern = (width && args.matchPatterns[width]) || args.matchPatterns[args.defaultMatchWidth] + var matchResult = string.match(matchPattern) + if (!matchResult) { + return null + } + var matchedString = matchResult[0] + var parsePatterns = (width && args.parsePatterns[width]) || args.parsePatterns[args.defaultParseWidth] + var key = Array.isArray(parsePatterns) + ? findIndex(parsePatterns, function (pattern) { + return pattern.test(matchedString) + }) + : findKey(parsePatterns, function (pattern) { + return pattern.test(matchedString) + }) + var value + value = args.valueCallback ? args.valueCallback(key) : key + value = options.valueCallback ? options.valueCallback(value) : value + var rest = string.slice(matchedString.length) + return { + value: value, + rest: rest, + } + } + } + function findKey(object, predicate) { + for (var key in object) { + if (object.hasOwnProperty(key) && predicate(object[key])) { + return key + } + } + return undefined + } + function findIndex(array, predicate) { + for (var key = 0; key < array.length; key++) { + if (predicate(array[key])) { + return key + } + } + return undefined + } + + function buildMatchPatternFn(args) { + return function (string) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {} + var matchResult = string.match(args.matchPattern) + if (!matchResult) return null + var matchedString = matchResult[0] + var parseResult = string.match(args.parsePattern) + if (!parseResult) return null + var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0] + value = options.valueCallback ? options.valueCallback(value) : value + var rest = string.slice(matchedString.length) + return { + value: value, + rest: rest, + } + } + } + + var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i + var parseOrdinalNumberPattern = /\d+/i + var matchEraPatterns = { + narrow: /^(b|a)/i, + abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, + wide: /^(before christ|before common era|anno domini|common era)/i, + } + var parseEraPatterns = { + any: [/^b/i, /^(a|c)/i], + } + var matchQuarterPatterns = { + narrow: /^[1234]/i, + abbreviated: /^q[1234]/i, + wide: /^[1234](th|st|nd|rd)? quarter/i, + } + var parseQuarterPatterns = { + any: [/1/i, /2/i, /3/i, /4/i], + } + var matchMonthPatterns = { + narrow: /^[jfmasond]/i, + abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, + wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i, + } + var parseMonthPatterns = { + narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], + any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i], + } + var matchDayPatterns = { + narrow: /^[smtwf]/i, + short: /^(su|mo|tu|we|th|fr|sa)/i, + abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, + wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i, + } + var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i], + } + var matchDayPeriodPatterns = { + narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, + any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i, + } + var parseDayPeriodPatterns = { + any: { + am: /^a/i, + pm: /^p/i, + midnight: /^mi/i, + noon: /^no/i, + morning: /morning/i, + afternoon: /afternoon/i, + evening: /evening/i, + night: /night/i, + }, + } + var match$1 = { + ordinalNumber: buildMatchPatternFn({ + matchPattern: matchOrdinalNumberPattern, + parsePattern: parseOrdinalNumberPattern, + valueCallback: function valueCallback(value) { + return parseInt(value, 10) + }, + }), + era: buildMatchFn({ + matchPatterns: matchEraPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseEraPatterns, + defaultParseWidth: 'any', + }), + quarter: buildMatchFn({ + matchPatterns: matchQuarterPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseQuarterPatterns, + defaultParseWidth: 'any', + valueCallback: function valueCallback(index) { + return index + 1 + }, + }), + month: buildMatchFn({ + matchPatterns: matchMonthPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseMonthPatterns, + defaultParseWidth: 'any', + }), + day: buildMatchFn({ + matchPatterns: matchDayPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseDayPatterns, + defaultParseWidth: 'any', + }), + dayPeriod: buildMatchFn({ + matchPatterns: matchDayPeriodPatterns, + defaultMatchWidth: 'any', + parsePatterns: parseDayPeriodPatterns, + defaultParseWidth: 'any', + }), + } + var match$2 = match$1 + + /** + * @type {Locale} + * @category Locales + * @summary English locale (United States). + * @language English + * @iso-639-2 eng + * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp} + * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss} + */ + var locale = { + code: 'en-US', + formatDistance: formatDistance$1, + formatLong: formatLong$1, + formatRelative: formatRelative$1, + localize: localize$1, + match: match$2, + options: { + weekStartsOn: 0 /* Sunday */, + firstWeekContainsDate: 1, + }, + } + var defaultLocale$1 = locale + + function assign(target, object) { + if (target == null) { + throw new TypeError('assign requires that input parameter not be null or undefined') + } + for (var property in object) { + if (Object.prototype.hasOwnProperty.call(object, property)) { + target[property] = object[property] + } + } + return target + } + + /** + * @name formatISO + * @category Common Helpers + * @summary Format the date according to the ISO 8601 standard (https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm). + * + * @description + * Return the formatted date string in ISO 8601 format. Options may be passed to control the parts and notations of the date. + * + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {'extended'|'basic'} [options.format='extended'] - if 'basic', hide delimiters between date and time values. + * @param {'complete'|'date'|'time'} [options.representation='complete'] - format date, time with local time zone, or both. + * @returns {String} the formatted date string (in local time zone) + * @throws {TypeError} 1 argument required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `options.format` must be 'extended' or 'basic' + * @throws {RangeError} `options.representation` must be 'date', 'time' or 'complete' + * + * @example + * // Represent 18 September 2019 in ISO 8601 format (local time zone is UTC): + * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52)) + * //=> '2019-09-18T19:00:52Z' + * + * @example + * // Represent 18 September 2019 in ISO 8601, short format (local time zone is UTC): + * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' }) + * //=> '20190918T190052' + * + * @example + * // Represent 18 September 2019 in ISO 8601 format, date only: + * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' }) + * //=> '2019-09-18' + * + * @example + * // Represent 18 September 2019 in ISO 8601 format, time only (local time zone is UTC): + * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' }) + * //=> '19:00:52Z' + */ + function formatISO(date, options) { + var _options$format, _options$representati + requiredArgs(1, arguments) + var originalDate = toDate(date) + if (isNaN(originalDate.getTime())) { + throw new RangeError('Invalid time value') + } + var format = String( + (_options$format = options === null || options === void 0 ? void 0 : options.format) !== null && + _options$format !== void 0 + ? _options$format + : 'extended', + ) + var representation = String( + (_options$representati = options === null || options === void 0 ? void 0 : options.representation) !== null && + _options$representati !== void 0 + ? _options$representati + : 'complete', + ) + if (format !== 'extended' && format !== 'basic') { + throw new RangeError("format must be 'extended' or 'basic'") + } + if (representation !== 'date' && representation !== 'time' && representation !== 'complete') { + throw new RangeError("representation must be 'date', 'time', or 'complete'") + } + var result = '' + var tzOffset = '' + var dateDelimiter = format === 'extended' ? '-' : '' + var timeDelimiter = format === 'extended' ? ':' : '' + + // Representation is either 'date' or 'complete' + if (representation !== 'time') { + var day = addLeadingZeros(originalDate.getDate(), 2) + var month = addLeadingZeros(originalDate.getMonth() + 1, 2) + var year = addLeadingZeros(originalDate.getFullYear(), 4) + + // yyyyMMdd or yyyy-MM-dd. + result = ''.concat(year).concat(dateDelimiter).concat(month).concat(dateDelimiter).concat(day) + } + + // Representation is either 'time' or 'complete' + if (representation !== 'date') { + // Add the timezone. + var offset = originalDate.getTimezoneOffset() + if (offset !== 0) { + var absoluteOffset = Math.abs(offset) + var hourOffset = addLeadingZeros(Math.floor(absoluteOffset / 60), 2) + var minuteOffset = addLeadingZeros(absoluteOffset % 60, 2) + // If less than 0, the sign is +, because it is ahead of time. + var sign = offset < 0 ? '+' : '-' + tzOffset = ''.concat(sign).concat(hourOffset, ':').concat(minuteOffset) + } else { + tzOffset = 'Z' + } + var hour = addLeadingZeros(originalDate.getHours(), 2) + var minute = addLeadingZeros(originalDate.getMinutes(), 2) + var second = addLeadingZeros(originalDate.getSeconds(), 2) + + // If there's also date, separate it with time with 'T' + var separator = result === '' ? '' : 'T' + + // Creates a time string consisting of hour, minute, and second, separated by delimiters, if defined. + var time = [hour, minute, second].join(timeDelimiter) + + // HHmmss or HH:mm:ss. + result = ''.concat(result).concat(separator).concat(time).concat(tzOffset) + } + return result + } + + /** + * @name getDate + * @category Day Helpers + * @summary Get the day of the month of the given date. + * + * @description + * Get the day of the month of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the day of month + * @throws {TypeError} 1 argument required + * + * @example + * // Which day of the month is 29 February 2012? + * const result = getDate(new Date(2012, 1, 29)) + * //=> 29 + */ + function getDate(dirtyDate) { + requiredArgs(1, arguments) + var date = toDate(dirtyDate) + var dayOfMonth = date.getDate() + return dayOfMonth + } + + /** + * @name getMonth + * @category Month Helpers + * @summary Get the month of the given date. + * + * @description + * Get the month of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the month + * @throws {TypeError} 1 argument required + * + * @example + * // Which month is 29 February 2012? + * const result = getMonth(new Date(2012, 1, 29)) + * //=> 1 + */ + function getMonth(dirtyDate) { + requiredArgs(1, arguments) + var date = toDate(dirtyDate) + var month = date.getMonth() + return month + } + + /** + * @name lastDayOfMonth + * @category Month Helpers + * @summary Return the last day of a month for the given date. + * + * @description + * Return the last day of a month for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the last day of a month + * @throws {TypeError} 1 argument required + * + * @example + * // The last day of a month for 2 September 2014 11:55:00: + * const result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 30 2014 00:00:00 + */ + function lastDayOfMonth(dirtyDate) { + requiredArgs(1, arguments) + var date = toDate(dirtyDate) + var month = date.getMonth() + date.setFullYear(date.getFullYear(), month + 1, 0) + date.setHours(0, 0, 0, 0) + return date + } + + /** + * @name getYear + * @category Year Helpers + * @summary Get the year of the given date. + * + * @description + * Get the year of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the year + * @throws {TypeError} 1 argument required + * + * @example + * // Which year is 2 July 2014? + * const result = getYear(new Date(2014, 6, 2)) + * //=> 2014 + */ + function getYear(dirtyDate) { + requiredArgs(1, arguments) + return toDate(dirtyDate).getFullYear() + } + + /** + * @name isAfter + * @category Common Helpers + * @summary Is the first date after the second one? + * + * @description + * Is the first date after the second one? + * + * @param {Date|Number} date - the date that should be after the other one to return true + * @param {Date|Number} dateToCompare - the date to compare with + * @returns {Boolean} the first date is after the second date + * @throws {TypeError} 2 arguments required + * + * @example + * // Is 10 July 1989 after 11 February 1987? + * const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) + * //=> true + */ + function isAfter(dirtyDate, dirtyDateToCompare) { + requiredArgs(2, arguments) + var date = toDate(dirtyDate) + var dateToCompare = toDate(dirtyDateToCompare) + return date.getTime() > dateToCompare.getTime() + } + + /** + * @name isBefore + * @category Common Helpers + * @summary Is the first date before the second one? + * + * @description + * Is the first date before the second one? + * + * @param {Date|Number} date - the date that should be before the other one to return true + * @param {Date|Number} dateToCompare - the date to compare with + * @returns {Boolean} the first date is before the second date + * @throws {TypeError} 2 arguments required + * + * @example + * // Is 10 July 1989 before 11 February 1987? + * const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) + * //=> false + */ + function isBefore(dirtyDate, dirtyDateToCompare) { + requiredArgs(2, arguments) + var date = toDate(dirtyDate) + var dateToCompare = toDate(dirtyDateToCompare) + return date.getTime() < dateToCompare.getTime() + } + + function _arrayLikeToArray$1(arr, len) { + if (len == null || len > arr.length) len = arr.length + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i] + return arr2 + } + + function _unsupportedIterableToArray$1(o, minLen) { + if (!o) return + if (typeof o === 'string') return _arrayLikeToArray$1(o, minLen) + var n = Object.prototype.toString.call(o).slice(8, -1) + if (n === 'Object' && o.constructor) n = o.constructor.name + if (n === 'Map' || n === 'Set') return Array.from(o) + if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen) + } + + function _createForOfIteratorHelper(o, allowArrayLike) { + var it = (typeof Symbol !== 'undefined' && o[Symbol.iterator]) || o['@@iterator'] + if (!it) { + if ( + Array.isArray(o) || + (it = _unsupportedIterableToArray$1(o)) || + (allowArrayLike && o && typeof o.length === 'number') + ) { + if (it) o = it + var i = 0 + var F = function F() {} + return { + s: F, + n: function n() { + if (i >= o.length) + return { + done: true, + } + return { + done: false, + value: o[i++], + } + }, + e: function e(_e) { + throw _e + }, + f: F, + } + } + throw new TypeError( + 'Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.', + ) + } + var normalCompletion = true, + didErr = false, + err + return { + s: function s() { + it = it.call(o) + }, + n: function n() { + var step = it.next() + normalCompletion = step.done + return step + }, + e: function e(_e2) { + didErr = true + err = _e2 + }, + f: function f() { + try { + if (!normalCompletion && it['return'] != null) it['return']() + } finally { + if (didErr) throw err + } + }, + } + } + + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called") + } + return self + } + + function _setPrototypeOf$1(o, p) { + _setPrototypeOf$1 = Object.setPrototypeOf + ? Object.setPrototypeOf.bind() + : function _setPrototypeOf(o, p) { + o.__proto__ = p + return o + } + return _setPrototypeOf$1(o, p) + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function') + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true, + }, + }) + Object.defineProperty(subClass, 'prototype', { + writable: false, + }) + if (superClass) _setPrototypeOf$1(subClass, superClass) + } + + function _getPrototypeOf$1(o) { + _getPrototypeOf$1 = Object.setPrototypeOf + ? Object.getPrototypeOf.bind() + : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o) + } + return _getPrototypeOf$1(o) + } + + function _isNativeReflectConstruct$1() { + try { + var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})) + } catch (t) {} + return (_isNativeReflectConstruct$1 = function _isNativeReflectConstruct() { + return !!t + })() + } + + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call + } else if (call !== void 0) { + throw new TypeError('Derived constructors may only return object or undefined') + } + return _assertThisInitialized(self) + } + + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct$1() + return function _createSuperInternal() { + var Super = _getPrototypeOf$1(Derived), + result + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf$1(this).constructor + result = Reflect.construct(Super, arguments, NewTarget) + } else { + result = Super.apply(this, arguments) + } + return _possibleConstructorReturn(this, result) + } + } + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function') + } + } + + function toPrimitive(t, r) { + if ('object' != _typeof(t) || !t) return t + var e = t[Symbol.toPrimitive] + if (void 0 !== e) { + var i = e.call(t, r || 'default') + if ('object' != _typeof(i)) return i + throw new TypeError('@@toPrimitive must return a primitive value.') + } + return ('string' === r ? String : Number)(t) + } + + function toPropertyKey(t) { + var i = toPrimitive(t, 'string') + return 'symbol' == _typeof(i) ? i : String(i) + } + + function _defineProperties$1(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i] + descriptor.enumerable = descriptor.enumerable || false + descriptor.configurable = true + if ('value' in descriptor) descriptor.writable = true + Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor) + } + } + function _createClass$1(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties$1(Constructor.prototype, protoProps) + if (staticProps) _defineProperties$1(Constructor, staticProps) + Object.defineProperty(Constructor, 'prototype', { + writable: false, + }) + return Constructor + } + + function _defineProperty(obj, key, value) { + key = toPropertyKey(key) + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true, + }) + } else { + obj[key] = value + } + return obj + } + + var TIMEZONE_UNIT_PRIORITY = 10 + var Setter = /*#__PURE__*/ (function () { + function Setter() { + _classCallCheck(this, Setter) + _defineProperty(this, 'priority', void 0) + _defineProperty(this, 'subPriority', 0) + } + _createClass$1(Setter, [ + { + key: 'validate', + value: function validate(_utcDate, _options) { + return true + }, + }, + ]) + return Setter + })() + var ValueSetter = /*#__PURE__*/ (function (_Setter) { + _inherits(ValueSetter, _Setter) + var _super = _createSuper(ValueSetter) + function ValueSetter(value, validateValue, setValue, priority, subPriority) { + var _this + _classCallCheck(this, ValueSetter) + _this = _super.call(this) + _this.value = value + _this.validateValue = validateValue + _this.setValue = setValue + _this.priority = priority + if (subPriority) { + _this.subPriority = subPriority + } + return _this + } + _createClass$1(ValueSetter, [ + { + key: 'validate', + value: function validate(utcDate, options) { + return this.validateValue(utcDate, this.value, options) + }, + }, + { + key: 'set', + value: function set(utcDate, flags, options) { + return this.setValue(utcDate, flags, this.value, options) + }, + }, + ]) + return ValueSetter + })(Setter) + var DateToSystemTimezoneSetter = /*#__PURE__*/ (function (_Setter2) { + _inherits(DateToSystemTimezoneSetter, _Setter2) + var _super2 = _createSuper(DateToSystemTimezoneSetter) + function DateToSystemTimezoneSetter() { + var _this2 + _classCallCheck(this, DateToSystemTimezoneSetter) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this2 = _super2.call.apply(_super2, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this2), 'priority', TIMEZONE_UNIT_PRIORITY) + _defineProperty(_assertThisInitialized(_this2), 'subPriority', -1) + return _this2 + } + _createClass$1(DateToSystemTimezoneSetter, [ + { + key: 'set', + value: function set(date, flags) { + if (flags.timestampIsSet) { + return date + } + var convertedDate = new Date(0) + convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()) + convertedDate.setHours( + date.getUTCHours(), + date.getUTCMinutes(), + date.getUTCSeconds(), + date.getUTCMilliseconds(), + ) + return convertedDate + }, + }, + ]) + return DateToSystemTimezoneSetter + })(Setter) + + var Parser = /*#__PURE__*/ (function () { + function Parser() { + _classCallCheck(this, Parser) + _defineProperty(this, 'incompatibleTokens', void 0) + _defineProperty(this, 'priority', void 0) + _defineProperty(this, 'subPriority', void 0) + } + _createClass$1(Parser, [ + { + key: 'run', + value: function run(dateString, token, match, options) { + var result = this.parse(dateString, token, match, options) + if (!result) { + return null + } + return { + setter: new ValueSetter(result.value, this.validate, this.set, this.priority, this.subPriority), + rest: result.rest, + } + }, + }, + { + key: 'validate', + value: function validate(_utcDate, _value, _options) { + return true + }, + }, + ]) + return Parser + })() + + var EraParser = /*#__PURE__*/ (function (_Parser) { + _inherits(EraParser, _Parser) + var _super = _createSuper(EraParser) + function EraParser() { + var _this + _classCallCheck(this, EraParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 140) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['R', 'u', 't', 'T']) + return _this + } + _createClass$1(EraParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + // AD, BC + case 'G': + case 'GG': + case 'GGG': + return ( + match.era(dateString, { + width: 'abbreviated', + }) || + match.era(dateString, { + width: 'narrow', + }) + ) + // A, B + case 'GGGGG': + return match.era(dateString, { + width: 'narrow', + }) + // Anno Domini, Before Christ + case 'GGGG': + default: + return ( + match.era(dateString, { + width: 'wide', + }) || + match.era(dateString, { + width: 'abbreviated', + }) || + match.era(dateString, { + width: 'narrow', + }) + ) + } + }, + }, + { + key: 'set', + value: function set(date, flags, value) { + flags.era = value + date.setUTCFullYear(value, 0, 1) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return EraParser + })(Parser) + + var numericPatterns = { + month: /^(1[0-2]|0?\d)/, + // 0 to 12 + date: /^(3[0-1]|[0-2]?\d)/, + // 0 to 31 + dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, + // 0 to 366 + week: /^(5[0-3]|[0-4]?\d)/, + // 0 to 53 + hour23h: /^(2[0-3]|[0-1]?\d)/, + // 0 to 23 + hour24h: /^(2[0-4]|[0-1]?\d)/, + // 0 to 24 + hour11h: /^(1[0-1]|0?\d)/, + // 0 to 11 + hour12h: /^(1[0-2]|0?\d)/, + // 0 to 12 + minute: /^[0-5]?\d/, + // 0 to 59 + second: /^[0-5]?\d/, + // 0 to 59 + + singleDigit: /^\d/, + // 0 to 9 + twoDigits: /^\d{1,2}/, + // 0 to 99 + threeDigits: /^\d{1,3}/, + // 0 to 999 + fourDigits: /^\d{1,4}/, + // 0 to 9999 + + anyDigitsSigned: /^-?\d+/, + singleDigitSigned: /^-?\d/, + // 0 to 9, -0 to -9 + twoDigitsSigned: /^-?\d{1,2}/, + // 0 to 99, -0 to -99 + threeDigitsSigned: /^-?\d{1,3}/, + // 0 to 999, -0 to -999 + fourDigitsSigned: /^-?\d{1,4}/, // 0 to 9999, -0 to -9999 + } + + var timezonePatterns = { + basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/, + basic: /^([+-])(\d{2})(\d{2})|Z/, + basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/, + extended: /^([+-])(\d{2}):(\d{2})|Z/, + extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/, + } + + function mapValue(parseFnResult, mapFn) { + if (!parseFnResult) { + return parseFnResult + } + return { + value: mapFn(parseFnResult.value), + rest: parseFnResult.rest, + } + } + function parseNumericPattern(pattern, dateString) { + var matchResult = dateString.match(pattern) + if (!matchResult) { + return null + } + return { + value: parseInt(matchResult[0], 10), + rest: dateString.slice(matchResult[0].length), + } + } + function parseTimezonePattern(pattern, dateString) { + var matchResult = dateString.match(pattern) + if (!matchResult) { + return null + } + + // Input is 'Z' + if (matchResult[0] === 'Z') { + return { + value: 0, + rest: dateString.slice(1), + } + } + var sign = matchResult[1] === '+' ? 1 : -1 + var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0 + var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0 + var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0 + return { + value: sign * (hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * millisecondsInSecond), + rest: dateString.slice(matchResult[0].length), + } + } + function parseAnyDigitsSigned(dateString) { + return parseNumericPattern(numericPatterns.anyDigitsSigned, dateString) + } + function parseNDigits(n, dateString) { + switch (n) { + case 1: + return parseNumericPattern(numericPatterns.singleDigit, dateString) + case 2: + return parseNumericPattern(numericPatterns.twoDigits, dateString) + case 3: + return parseNumericPattern(numericPatterns.threeDigits, dateString) + case 4: + return parseNumericPattern(numericPatterns.fourDigits, dateString) + default: + return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), dateString) + } + } + function parseNDigitsSigned(n, dateString) { + switch (n) { + case 1: + return parseNumericPattern(numericPatterns.singleDigitSigned, dateString) + case 2: + return parseNumericPattern(numericPatterns.twoDigitsSigned, dateString) + case 3: + return parseNumericPattern(numericPatterns.threeDigitsSigned, dateString) + case 4: + return parseNumericPattern(numericPatterns.fourDigitsSigned, dateString) + default: + return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), dateString) + } + } + function dayPeriodEnumToHours(dayPeriod) { + switch (dayPeriod) { + case 'morning': + return 4 + case 'evening': + return 17 + case 'pm': + case 'noon': + case 'afternoon': + return 12 + case 'am': + case 'midnight': + case 'night': + default: + return 0 + } + } + function normalizeTwoDigitYear(twoDigitYear, currentYear) { + var isCommonEra = currentYear > 0 + // Absolute number of the current year: + // 1 -> 1 AC + // 0 -> 1 BC + // -1 -> 2 BC + var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear + var result + if (absCurrentYear <= 50) { + result = twoDigitYear || 100 + } else { + var rangeEnd = absCurrentYear + 50 + var rangeEndCentury = Math.floor(rangeEnd / 100) * 100 + var isPreviousCentury = twoDigitYear >= rangeEnd % 100 + result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0) + } + return isCommonEra ? result : 1 - result + } + function isLeapYearIndex$1(year) { + return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0) + } + + // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns + // | Year | y | yy | yyy | yyyy | yyyyy | + // |----------|-------|----|-------|-------|-------| + // | AD 1 | 1 | 01 | 001 | 0001 | 00001 | + // | AD 12 | 12 | 12 | 012 | 0012 | 00012 | + // | AD 123 | 123 | 23 | 123 | 0123 | 00123 | + // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | + // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | + var YearParser = /*#__PURE__*/ (function (_Parser) { + _inherits(YearParser, _Parser) + var _super = _createSuper(YearParser) + function YearParser() { + var _this + _classCallCheck(this, YearParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 130) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'Y', + 'R', + 'u', + 'w', + 'I', + 'i', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(YearParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(year) { + return { + year: year, + isTwoDigitYear: token === 'yy', + } + } + switch (token) { + case 'y': + return mapValue(parseNDigits(4, dateString), valueCallback) + case 'yo': + return mapValue( + match.ordinalNumber(dateString, { + unit: 'year', + }), + valueCallback, + ) + default: + return mapValue(parseNDigits(token.length, dateString), valueCallback) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value.isTwoDigitYear || value.year > 0 + }, + }, + { + key: 'set', + value: function set(date, flags, value) { + var currentYear = date.getUTCFullYear() + if (value.isTwoDigitYear) { + var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear) + date.setUTCFullYear(normalizedTwoDigitYear, 0, 1) + date.setUTCHours(0, 0, 0, 0) + return date + } + var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year + date.setUTCFullYear(year, 0, 1) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return YearParser + })(Parser) + + // Local week-numbering year + var LocalWeekYearParser = /*#__PURE__*/ (function (_Parser) { + _inherits(LocalWeekYearParser, _Parser) + var _super = _createSuper(LocalWeekYearParser) + function LocalWeekYearParser() { + var _this + _classCallCheck(this, LocalWeekYearParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 130) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'y', + 'R', + 'u', + 'Q', + 'q', + 'M', + 'L', + 'I', + 'd', + 'D', + 'i', + 't', + 'T', + ]) + return _this + } + _createClass$1(LocalWeekYearParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(year) { + return { + year: year, + isTwoDigitYear: token === 'YY', + } + } + switch (token) { + case 'Y': + return mapValue(parseNDigits(4, dateString), valueCallback) + case 'Yo': + return mapValue( + match.ordinalNumber(dateString, { + unit: 'year', + }), + valueCallback, + ) + default: + return mapValue(parseNDigits(token.length, dateString), valueCallback) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value.isTwoDigitYear || value.year > 0 + }, + }, + { + key: 'set', + value: function set(date, flags, value, options) { + var currentYear = getUTCWeekYear(date, options) + if (value.isTwoDigitYear) { + var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear) + date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate) + date.setUTCHours(0, 0, 0, 0) + return startOfUTCWeek(date, options) + } + var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year + date.setUTCFullYear(year, 0, options.firstWeekContainsDate) + date.setUTCHours(0, 0, 0, 0) + return startOfUTCWeek(date, options) + }, + }, + ]) + return LocalWeekYearParser + })(Parser) + + var ISOWeekYearParser = /*#__PURE__*/ (function (_Parser) { + _inherits(ISOWeekYearParser, _Parser) + var _super = _createSuper(ISOWeekYearParser) + function ISOWeekYearParser() { + var _this + _classCallCheck(this, ISOWeekYearParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 130) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'G', + 'y', + 'Y', + 'u', + 'Q', + 'q', + 'M', + 'L', + 'w', + 'd', + 'D', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(ISOWeekYearParser, [ + { + key: 'parse', + value: function parse(dateString, token) { + if (token === 'R') { + return parseNDigitsSigned(4, dateString) + } + return parseNDigitsSigned(token.length, dateString) + }, + }, + { + key: 'set', + value: function set(_date, _flags, value) { + var firstWeekOfYear = new Date(0) + firstWeekOfYear.setUTCFullYear(value, 0, 4) + firstWeekOfYear.setUTCHours(0, 0, 0, 0) + return startOfUTCISOWeek(firstWeekOfYear) + }, + }, + ]) + return ISOWeekYearParser + })(Parser) + + var ExtendedYearParser = /*#__PURE__*/ (function (_Parser) { + _inherits(ExtendedYearParser, _Parser) + var _super = _createSuper(ExtendedYearParser) + function ExtendedYearParser() { + var _this + _classCallCheck(this, ExtendedYearParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 130) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'G', + 'y', + 'Y', + 'R', + 'w', + 'I', + 'i', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(ExtendedYearParser, [ + { + key: 'parse', + value: function parse(dateString, token) { + if (token === 'u') { + return parseNDigitsSigned(4, dateString) + } + return parseNDigitsSigned(token.length, dateString) + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCFullYear(value, 0, 1) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return ExtendedYearParser + })(Parser) + + var QuarterParser = /*#__PURE__*/ (function (_Parser) { + _inherits(QuarterParser, _Parser) + var _super = _createSuper(QuarterParser) + function QuarterParser() { + var _this + _classCallCheck(this, QuarterParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 120) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'Y', + 'R', + 'q', + 'M', + 'L', + 'w', + 'I', + 'd', + 'D', + 'i', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(QuarterParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + // 1, 2, 3, 4 + case 'Q': + case 'QQ': + // 01, 02, 03, 04 + return parseNDigits(token.length, dateString) + // 1st, 2nd, 3rd, 4th + case 'Qo': + return match.ordinalNumber(dateString, { + unit: 'quarter', + }) + // Q1, Q2, Q3, Q4 + case 'QQQ': + return ( + match.quarter(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.quarter(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + case 'QQQQQ': + return match.quarter(dateString, { + width: 'narrow', + context: 'formatting', + }) + // 1st quarter, 2nd quarter, ... + case 'QQQQ': + default: + return ( + match.quarter(dateString, { + width: 'wide', + context: 'formatting', + }) || + match.quarter(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.quarter(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 1 && value <= 4 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCMonth((value - 1) * 3, 1) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return QuarterParser + })(Parser) + + var StandAloneQuarterParser = /*#__PURE__*/ (function (_Parser) { + _inherits(StandAloneQuarterParser, _Parser) + var _super = _createSuper(StandAloneQuarterParser) + function StandAloneQuarterParser() { + var _this + _classCallCheck(this, StandAloneQuarterParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 120) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'Y', + 'R', + 'Q', + 'M', + 'L', + 'w', + 'I', + 'd', + 'D', + 'i', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(StandAloneQuarterParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + // 1, 2, 3, 4 + case 'q': + case 'qq': + // 01, 02, 03, 04 + return parseNDigits(token.length, dateString) + // 1st, 2nd, 3rd, 4th + case 'qo': + return match.ordinalNumber(dateString, { + unit: 'quarter', + }) + // Q1, Q2, Q3, Q4 + case 'qqq': + return ( + match.quarter(dateString, { + width: 'abbreviated', + context: 'standalone', + }) || + match.quarter(dateString, { + width: 'narrow', + context: 'standalone', + }) + ) + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + case 'qqqqq': + return match.quarter(dateString, { + width: 'narrow', + context: 'standalone', + }) + // 1st quarter, 2nd quarter, ... + case 'qqqq': + default: + return ( + match.quarter(dateString, { + width: 'wide', + context: 'standalone', + }) || + match.quarter(dateString, { + width: 'abbreviated', + context: 'standalone', + }) || + match.quarter(dateString, { + width: 'narrow', + context: 'standalone', + }) + ) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 1 && value <= 4 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCMonth((value - 1) * 3, 1) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return StandAloneQuarterParser + })(Parser) + + var MonthParser = /*#__PURE__*/ (function (_Parser) { + _inherits(MonthParser, _Parser) + var _super = _createSuper(MonthParser) + function MonthParser() { + var _this + _classCallCheck(this, MonthParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'Y', + 'R', + 'q', + 'Q', + 'L', + 'w', + 'I', + 'D', + 'i', + 'e', + 'c', + 't', + 'T', + ]) + _defineProperty(_assertThisInitialized(_this), 'priority', 110) + return _this + } + _createClass$1(MonthParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(value) { + return value - 1 + } + switch (token) { + // 1, 2, ..., 12 + case 'M': + return mapValue(parseNumericPattern(numericPatterns.month, dateString), valueCallback) + // 01, 02, ..., 12 + case 'MM': + return mapValue(parseNDigits(2, dateString), valueCallback) + // 1st, 2nd, ..., 12th + case 'Mo': + return mapValue( + match.ordinalNumber(dateString, { + unit: 'month', + }), + valueCallback, + ) + // Jan, Feb, ..., Dec + case 'MMM': + return ( + match.month(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.month(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + // J, F, ..., D + case 'MMMMM': + return match.month(dateString, { + width: 'narrow', + context: 'formatting', + }) + // January, February, ..., December + case 'MMMM': + default: + return ( + match.month(dateString, { + width: 'wide', + context: 'formatting', + }) || + match.month(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.month(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 11 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCMonth(value, 1) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return MonthParser + })(Parser) + + var StandAloneMonthParser = /*#__PURE__*/ (function (_Parser) { + _inherits(StandAloneMonthParser, _Parser) + var _super = _createSuper(StandAloneMonthParser) + function StandAloneMonthParser() { + var _this + _classCallCheck(this, StandAloneMonthParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 110) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'Y', + 'R', + 'q', + 'Q', + 'M', + 'w', + 'I', + 'D', + 'i', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(StandAloneMonthParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(value) { + return value - 1 + } + switch (token) { + // 1, 2, ..., 12 + case 'L': + return mapValue(parseNumericPattern(numericPatterns.month, dateString), valueCallback) + // 01, 02, ..., 12 + case 'LL': + return mapValue(parseNDigits(2, dateString), valueCallback) + // 1st, 2nd, ..., 12th + case 'Lo': + return mapValue( + match.ordinalNumber(dateString, { + unit: 'month', + }), + valueCallback, + ) + // Jan, Feb, ..., Dec + case 'LLL': + return ( + match.month(dateString, { + width: 'abbreviated', + context: 'standalone', + }) || + match.month(dateString, { + width: 'narrow', + context: 'standalone', + }) + ) + // J, F, ..., D + case 'LLLLL': + return match.month(dateString, { + width: 'narrow', + context: 'standalone', + }) + // January, February, ..., December + case 'LLLL': + default: + return ( + match.month(dateString, { + width: 'wide', + context: 'standalone', + }) || + match.month(dateString, { + width: 'abbreviated', + context: 'standalone', + }) || + match.month(dateString, { + width: 'narrow', + context: 'standalone', + }) + ) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 11 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCMonth(value, 1) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return StandAloneMonthParser + })(Parser) + + function setUTCWeek(dirtyDate, dirtyWeek, options) { + requiredArgs(2, arguments) + var date = toDate(dirtyDate) + var week = toInteger$1(dirtyWeek) + var diff = getUTCWeek(date, options) - week + date.setUTCDate(date.getUTCDate() - diff * 7) + return date + } + + var LocalWeekParser = /*#__PURE__*/ (function (_Parser) { + _inherits(LocalWeekParser, _Parser) + var _super = _createSuper(LocalWeekParser) + function LocalWeekParser() { + var _this + _classCallCheck(this, LocalWeekParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 100) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'y', + 'R', + 'u', + 'q', + 'Q', + 'M', + 'L', + 'I', + 'd', + 'D', + 'i', + 't', + 'T', + ]) + return _this + } + _createClass$1(LocalWeekParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'w': + return parseNumericPattern(numericPatterns.week, dateString) + case 'wo': + return match.ordinalNumber(dateString, { + unit: 'week', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 1 && value <= 53 + }, + }, + { + key: 'set', + value: function set(date, _flags, value, options) { + return startOfUTCWeek(setUTCWeek(date, value, options), options) + }, + }, + ]) + return LocalWeekParser + })(Parser) + + function setUTCISOWeek(dirtyDate, dirtyISOWeek) { + requiredArgs(2, arguments) + var date = toDate(dirtyDate) + var isoWeek = toInteger$1(dirtyISOWeek) + var diff = getUTCISOWeek(date) - isoWeek + date.setUTCDate(date.getUTCDate() - diff * 7) + return date + } + + var ISOWeekParser = /*#__PURE__*/ (function (_Parser) { + _inherits(ISOWeekParser, _Parser) + var _super = _createSuper(ISOWeekParser) + function ISOWeekParser() { + var _this + _classCallCheck(this, ISOWeekParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 100) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'y', + 'Y', + 'u', + 'q', + 'Q', + 'M', + 'L', + 'w', + 'd', + 'D', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(ISOWeekParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'I': + return parseNumericPattern(numericPatterns.week, dateString) + case 'Io': + return match.ordinalNumber(dateString, { + unit: 'week', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 1 && value <= 53 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + return startOfUTCISOWeek(setUTCISOWeek(date, value)) + }, + }, + ]) + return ISOWeekParser + })(Parser) + + var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + // Day of the month + var DateParser = /*#__PURE__*/ (function (_Parser) { + _inherits(DateParser, _Parser) + var _super = _createSuper(DateParser) + function DateParser() { + var _this + _classCallCheck(this, DateParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 90) + _defineProperty(_assertThisInitialized(_this), 'subPriority', 1) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'Y', + 'R', + 'q', + 'Q', + 'w', + 'I', + 'D', + 'i', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(DateParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'd': + return parseNumericPattern(numericPatterns.date, dateString) + case 'do': + return match.ordinalNumber(dateString, { + unit: 'date', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(date, value) { + var year = date.getUTCFullYear() + var isLeapYear = isLeapYearIndex$1(year) + var month = date.getUTCMonth() + if (isLeapYear) { + return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month] + } else { + return value >= 1 && value <= DAYS_IN_MONTH[month] + } + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCDate(value) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return DateParser + })(Parser) + + var DayOfYearParser = /*#__PURE__*/ (function (_Parser) { + _inherits(DayOfYearParser, _Parser) + var _super = _createSuper(DayOfYearParser) + function DayOfYearParser() { + var _this + _classCallCheck(this, DayOfYearParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 90) + _defineProperty(_assertThisInitialized(_this), 'subpriority', 1) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'Y', + 'R', + 'q', + 'Q', + 'M', + 'L', + 'w', + 'I', + 'd', + 'E', + 'i', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(DayOfYearParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'D': + case 'DD': + return parseNumericPattern(numericPatterns.dayOfYear, dateString) + case 'Do': + return match.ordinalNumber(dateString, { + unit: 'date', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(date, value) { + var year = date.getUTCFullYear() + var isLeapYear = isLeapYearIndex$1(year) + if (isLeapYear) { + return value >= 1 && value <= 366 + } else { + return value >= 1 && value <= 365 + } + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCMonth(0, value) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return DayOfYearParser + })(Parser) + + function setUTCDay(dirtyDate, dirtyDay, options) { + var _ref, + _ref2, + _ref3, + _options$weekStartsOn, + _options$locale, + _options$locale$optio, + _defaultOptions$local, + _defaultOptions$local2 + requiredArgs(2, arguments) + var defaultOptions = getDefaultOptions() + var weekStartsOn = toInteger$1( + (_ref = + (_ref2 = + (_ref3 = + (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== + null && _options$weekStartsOn !== void 0 + ? _options$weekStartsOn + : options === null || options === void 0 + ? void 0 + : (_options$locale = options.locale) === null || _options$locale === void 0 + ? void 0 + : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 + ? void 0 + : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 + ? _ref3 + : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 + ? _ref2 + : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 + ? void 0 + : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 + ? void 0 + : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 + ? _ref + : 0, + ) + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively') + } + var date = toDate(dirtyDate) + var day = toInteger$1(dirtyDay) + var currentDay = date.getUTCDay() + var remainder = day % 7 + var dayIndex = (remainder + 7) % 7 + var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay + date.setUTCDate(date.getUTCDate() + diff) + return date + } + + var DayParser = /*#__PURE__*/ (function (_Parser) { + _inherits(DayParser, _Parser) + var _super = _createSuper(DayParser) + function DayParser() { + var _this + _classCallCheck(this, DayParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 90) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['D', 'i', 'e', 'c', 't', 'T']) + return _this + } + _createClass$1(DayParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + // Tue + case 'E': + case 'EE': + case 'EEE': + return ( + match.day(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + // T + case 'EEEEE': + return match.day(dateString, { + width: 'narrow', + context: 'formatting', + }) + // Tu + case 'EEEEEE': + return ( + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + // Tuesday + case 'EEEE': + default: + return ( + match.day(dateString, { + width: 'wide', + context: 'formatting', + }) || + match.day(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 6 + }, + }, + { + key: 'set', + value: function set(date, _flags, value, options) { + date = setUTCDay(date, value, options) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return DayParser + })(Parser) + + var LocalDayParser = /*#__PURE__*/ (function (_Parser) { + _inherits(LocalDayParser, _Parser) + var _super = _createSuper(LocalDayParser) + function LocalDayParser() { + var _this + _classCallCheck(this, LocalDayParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 90) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'y', + 'R', + 'u', + 'q', + 'Q', + 'M', + 'L', + 'I', + 'd', + 'D', + 'E', + 'i', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(LocalDayParser, [ + { + key: 'parse', + value: function parse(dateString, token, match, options) { + var valueCallback = function valueCallback(value) { + var wholeWeekDays = Math.floor((value - 1) / 7) * 7 + return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays + } + switch (token) { + // 3 + case 'e': + case 'ee': + // 03 + return mapValue(parseNDigits(token.length, dateString), valueCallback) + // 3rd + case 'eo': + return mapValue( + match.ordinalNumber(dateString, { + unit: 'day', + }), + valueCallback, + ) + // Tue + case 'eee': + return ( + match.day(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + // T + case 'eeeee': + return match.day(dateString, { + width: 'narrow', + context: 'formatting', + }) + // Tu + case 'eeeeee': + return ( + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + // Tuesday + case 'eeee': + default: + return ( + match.day(dateString, { + width: 'wide', + context: 'formatting', + }) || + match.day(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 6 + }, + }, + { + key: 'set', + value: function set(date, _flags, value, options) { + date = setUTCDay(date, value, options) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return LocalDayParser + })(Parser) + + var StandAloneLocalDayParser = /*#__PURE__*/ (function (_Parser) { + _inherits(StandAloneLocalDayParser, _Parser) + var _super = _createSuper(StandAloneLocalDayParser) + function StandAloneLocalDayParser() { + var _this + _classCallCheck(this, StandAloneLocalDayParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 90) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'y', + 'R', + 'u', + 'q', + 'Q', + 'M', + 'L', + 'I', + 'd', + 'D', + 'E', + 'i', + 'e', + 't', + 'T', + ]) + return _this + } + _createClass$1(StandAloneLocalDayParser, [ + { + key: 'parse', + value: function parse(dateString, token, match, options) { + var valueCallback = function valueCallback(value) { + var wholeWeekDays = Math.floor((value - 1) / 7) * 7 + return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays + } + switch (token) { + // 3 + case 'c': + case 'cc': + // 03 + return mapValue(parseNDigits(token.length, dateString), valueCallback) + // 3rd + case 'co': + return mapValue( + match.ordinalNumber(dateString, { + unit: 'day', + }), + valueCallback, + ) + // Tue + case 'ccc': + return ( + match.day(dateString, { + width: 'abbreviated', + context: 'standalone', + }) || + match.day(dateString, { + width: 'short', + context: 'standalone', + }) || + match.day(dateString, { + width: 'narrow', + context: 'standalone', + }) + ) + // T + case 'ccccc': + return match.day(dateString, { + width: 'narrow', + context: 'standalone', + }) + // Tu + case 'cccccc': + return ( + match.day(dateString, { + width: 'short', + context: 'standalone', + }) || + match.day(dateString, { + width: 'narrow', + context: 'standalone', + }) + ) + // Tuesday + case 'cccc': + default: + return ( + match.day(dateString, { + width: 'wide', + context: 'standalone', + }) || + match.day(dateString, { + width: 'abbreviated', + context: 'standalone', + }) || + match.day(dateString, { + width: 'short', + context: 'standalone', + }) || + match.day(dateString, { + width: 'narrow', + context: 'standalone', + }) + ) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 6 + }, + }, + { + key: 'set', + value: function set(date, _flags, value, options) { + date = setUTCDay(date, value, options) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return StandAloneLocalDayParser + })(Parser) + + function setUTCISODay(dirtyDate, dirtyDay) { + requiredArgs(2, arguments) + var day = toInteger$1(dirtyDay) + if (day % 7 === 0) { + day = day - 7 + } + var weekStartsOn = 1 + var date = toDate(dirtyDate) + var currentDay = date.getUTCDay() + var remainder = day % 7 + var dayIndex = (remainder + 7) % 7 + var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay + date.setUTCDate(date.getUTCDate() + diff) + return date + } + + var ISODayParser = /*#__PURE__*/ (function (_Parser) { + _inherits(ISODayParser, _Parser) + var _super = _createSuper(ISODayParser) + function ISODayParser() { + var _this + _classCallCheck(this, ISODayParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 90) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', [ + 'y', + 'Y', + 'u', + 'q', + 'Q', + 'M', + 'L', + 'w', + 'd', + 'D', + 'E', + 'e', + 'c', + 't', + 'T', + ]) + return _this + } + _createClass$1(ISODayParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(value) { + if (value === 0) { + return 7 + } + return value + } + switch (token) { + // 2 + case 'i': + case 'ii': + // 02 + return parseNDigits(token.length, dateString) + // 2nd + case 'io': + return match.ordinalNumber(dateString, { + unit: 'day', + }) + // Tue + case 'iii': + return mapValue( + match.day(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }), + valueCallback, + ) + // T + case 'iiiii': + return mapValue( + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }), + valueCallback, + ) + // Tu + case 'iiiiii': + return mapValue( + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }), + valueCallback, + ) + // Tuesday + case 'iiii': + default: + return mapValue( + match.day(dateString, { + width: 'wide', + context: 'formatting', + }) || + match.day(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.day(dateString, { + width: 'short', + context: 'formatting', + }) || + match.day(dateString, { + width: 'narrow', + context: 'formatting', + }), + valueCallback, + ) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 1 && value <= 7 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date = setUTCISODay(date, value) + date.setUTCHours(0, 0, 0, 0) + return date + }, + }, + ]) + return ISODayParser + })(Parser) + + var AMPMParser = /*#__PURE__*/ (function (_Parser) { + _inherits(AMPMParser, _Parser) + var _super = _createSuper(AMPMParser) + function AMPMParser() { + var _this + _classCallCheck(this, AMPMParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 80) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['b', 'B', 'H', 'k', 't', 'T']) + return _this + } + _createClass$1(AMPMParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'a': + case 'aa': + case 'aaa': + return ( + match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + case 'aaaaa': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + case 'aaaa': + default: + return ( + match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + } + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0) + return date + }, + }, + ]) + return AMPMParser + })(Parser) + + var AMPMMidnightParser = /*#__PURE__*/ (function (_Parser) { + _inherits(AMPMMidnightParser, _Parser) + var _super = _createSuper(AMPMMidnightParser) + function AMPMMidnightParser() { + var _this + _classCallCheck(this, AMPMMidnightParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 80) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['a', 'B', 'H', 'k', 't', 'T']) + return _this + } + _createClass$1(AMPMMidnightParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'b': + case 'bb': + case 'bbb': + return ( + match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + case 'bbbbb': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + case 'bbbb': + default: + return ( + match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + } + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0) + return date + }, + }, + ]) + return AMPMMidnightParser + })(Parser) + + var DayPeriodParser = /*#__PURE__*/ (function (_Parser) { + _inherits(DayPeriodParser, _Parser) + var _super = _createSuper(DayPeriodParser) + function DayPeriodParser() { + var _this + _classCallCheck(this, DayPeriodParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 80) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['a', 'b', 't', 'T']) + return _this + } + _createClass$1(DayPeriodParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'B': + case 'BB': + case 'BBB': + return ( + match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + case 'BBBBB': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + case 'BBBB': + default: + return ( + match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting', + }) || + match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting', + }) + ) + } + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0) + return date + }, + }, + ]) + return DayPeriodParser + })(Parser) + + var Hour1to12Parser = /*#__PURE__*/ (function (_Parser) { + _inherits(Hour1to12Parser, _Parser) + var _super = _createSuper(Hour1to12Parser) + function Hour1to12Parser() { + var _this + _classCallCheck(this, Hour1to12Parser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 70) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['H', 'K', 'k', 't', 'T']) + return _this + } + _createClass$1(Hour1to12Parser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'h': + return parseNumericPattern(numericPatterns.hour12h, dateString) + case 'ho': + return match.ordinalNumber(dateString, { + unit: 'hour', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 1 && value <= 12 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + var isPM = date.getUTCHours() >= 12 + if (isPM && value < 12) { + date.setUTCHours(value + 12, 0, 0, 0) + } else if (!isPM && value === 12) { + date.setUTCHours(0, 0, 0, 0) + } else { + date.setUTCHours(value, 0, 0, 0) + } + return date + }, + }, + ]) + return Hour1to12Parser + })(Parser) + + var Hour0to23Parser = /*#__PURE__*/ (function (_Parser) { + _inherits(Hour0to23Parser, _Parser) + var _super = _createSuper(Hour0to23Parser) + function Hour0to23Parser() { + var _this + _classCallCheck(this, Hour0to23Parser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 70) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['a', 'b', 'h', 'K', 'k', 't', 'T']) + return _this + } + _createClass$1(Hour0to23Parser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'H': + return parseNumericPattern(numericPatterns.hour23h, dateString) + case 'Ho': + return match.ordinalNumber(dateString, { + unit: 'hour', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 23 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCHours(value, 0, 0, 0) + return date + }, + }, + ]) + return Hour0to23Parser + })(Parser) + + var Hour0To11Parser = /*#__PURE__*/ (function (_Parser) { + _inherits(Hour0To11Parser, _Parser) + var _super = _createSuper(Hour0To11Parser) + function Hour0To11Parser() { + var _this + _classCallCheck(this, Hour0To11Parser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 70) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['h', 'H', 'k', 't', 'T']) + return _this + } + _createClass$1(Hour0To11Parser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'K': + return parseNumericPattern(numericPatterns.hour11h, dateString) + case 'Ko': + return match.ordinalNumber(dateString, { + unit: 'hour', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 11 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + var isPM = date.getUTCHours() >= 12 + if (isPM && value < 12) { + date.setUTCHours(value + 12, 0, 0, 0) + } else { + date.setUTCHours(value, 0, 0, 0) + } + return date + }, + }, + ]) + return Hour0To11Parser + })(Parser) + + var Hour1To24Parser = /*#__PURE__*/ (function (_Parser) { + _inherits(Hour1To24Parser, _Parser) + var _super = _createSuper(Hour1To24Parser) + function Hour1To24Parser() { + var _this + _classCallCheck(this, Hour1To24Parser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 70) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['a', 'b', 'h', 'H', 'K', 't', 'T']) + return _this + } + _createClass$1(Hour1To24Parser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'k': + return parseNumericPattern(numericPatterns.hour24h, dateString) + case 'ko': + return match.ordinalNumber(dateString, { + unit: 'hour', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 1 && value <= 24 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + var hours = value <= 24 ? value % 24 : value + date.setUTCHours(hours, 0, 0, 0) + return date + }, + }, + ]) + return Hour1To24Parser + })(Parser) + + var MinuteParser = /*#__PURE__*/ (function (_Parser) { + _inherits(MinuteParser, _Parser) + var _super = _createSuper(MinuteParser) + function MinuteParser() { + var _this + _classCallCheck(this, MinuteParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 60) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['t', 'T']) + return _this + } + _createClass$1(MinuteParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 'm': + return parseNumericPattern(numericPatterns.minute, dateString) + case 'mo': + return match.ordinalNumber(dateString, { + unit: 'minute', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 59 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCMinutes(value, 0, 0) + return date + }, + }, + ]) + return MinuteParser + })(Parser) + + var SecondParser = /*#__PURE__*/ (function (_Parser) { + _inherits(SecondParser, _Parser) + var _super = _createSuper(SecondParser) + function SecondParser() { + var _this + _classCallCheck(this, SecondParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 50) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['t', 'T']) + return _this + } + _createClass$1(SecondParser, [ + { + key: 'parse', + value: function parse(dateString, token, match) { + switch (token) { + case 's': + return parseNumericPattern(numericPatterns.second, dateString) + case 'so': + return match.ordinalNumber(dateString, { + unit: 'second', + }) + default: + return parseNDigits(token.length, dateString) + } + }, + }, + { + key: 'validate', + value: function validate(_date, value) { + return value >= 0 && value <= 59 + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCSeconds(value, 0) + return date + }, + }, + ]) + return SecondParser + })(Parser) + + var FractionOfSecondParser = /*#__PURE__*/ (function (_Parser) { + _inherits(FractionOfSecondParser, _Parser) + var _super = _createSuper(FractionOfSecondParser) + function FractionOfSecondParser() { + var _this + _classCallCheck(this, FractionOfSecondParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 30) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['t', 'T']) + return _this + } + _createClass$1(FractionOfSecondParser, [ + { + key: 'parse', + value: function parse(dateString, token) { + var valueCallback = function valueCallback(value) { + return Math.floor(value * Math.pow(10, -token.length + 3)) + } + return mapValue(parseNDigits(token.length, dateString), valueCallback) + }, + }, + { + key: 'set', + value: function set(date, _flags, value) { + date.setUTCMilliseconds(value) + return date + }, + }, + ]) + return FractionOfSecondParser + })(Parser) + + var ISOTimezoneWithZParser = /*#__PURE__*/ (function (_Parser) { + _inherits(ISOTimezoneWithZParser, _Parser) + var _super = _createSuper(ISOTimezoneWithZParser) + function ISOTimezoneWithZParser() { + var _this + _classCallCheck(this, ISOTimezoneWithZParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 10) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['t', 'T', 'x']) + return _this + } + _createClass$1(ISOTimezoneWithZParser, [ + { + key: 'parse', + value: function parse(dateString, token) { + switch (token) { + case 'X': + return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, dateString) + case 'XX': + return parseTimezonePattern(timezonePatterns.basic, dateString) + case 'XXXX': + return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, dateString) + case 'XXXXX': + return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, dateString) + case 'XXX': + default: + return parseTimezonePattern(timezonePatterns.extended, dateString) + } + }, + }, + { + key: 'set', + value: function set(date, flags, value) { + if (flags.timestampIsSet) { + return date + } + return new Date(date.getTime() - value) + }, + }, + ]) + return ISOTimezoneWithZParser + })(Parser) + + var ISOTimezoneParser = /*#__PURE__*/ (function (_Parser) { + _inherits(ISOTimezoneParser, _Parser) + var _super = _createSuper(ISOTimezoneParser) + function ISOTimezoneParser() { + var _this + _classCallCheck(this, ISOTimezoneParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 10) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', ['t', 'T', 'X']) + return _this + } + _createClass$1(ISOTimezoneParser, [ + { + key: 'parse', + value: function parse(dateString, token) { + switch (token) { + case 'x': + return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, dateString) + case 'xx': + return parseTimezonePattern(timezonePatterns.basic, dateString) + case 'xxxx': + return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, dateString) + case 'xxxxx': + return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, dateString) + case 'xxx': + default: + return parseTimezonePattern(timezonePatterns.extended, dateString) + } + }, + }, + { + key: 'set', + value: function set(date, flags, value) { + if (flags.timestampIsSet) { + return date + } + return new Date(date.getTime() - value) + }, + }, + ]) + return ISOTimezoneParser + })(Parser) + + var TimestampSecondsParser = /*#__PURE__*/ (function (_Parser) { + _inherits(TimestampSecondsParser, _Parser) + var _super = _createSuper(TimestampSecondsParser) + function TimestampSecondsParser() { + var _this + _classCallCheck(this, TimestampSecondsParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 40) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', '*') + return _this + } + _createClass$1(TimestampSecondsParser, [ + { + key: 'parse', + value: function parse(dateString) { + return parseAnyDigitsSigned(dateString) + }, + }, + { + key: 'set', + value: function set(_date, _flags, value) { + return [ + new Date(value * 1000), + { + timestampIsSet: true, + }, + ] + }, + }, + ]) + return TimestampSecondsParser + })(Parser) + + var TimestampMillisecondsParser = /*#__PURE__*/ (function (_Parser) { + _inherits(TimestampMillisecondsParser, _Parser) + var _super = _createSuper(TimestampMillisecondsParser) + function TimestampMillisecondsParser() { + var _this + _classCallCheck(this, TimestampMillisecondsParser) + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key] + } + _this = _super.call.apply(_super, [this].concat(args)) + _defineProperty(_assertThisInitialized(_this), 'priority', 20) + _defineProperty(_assertThisInitialized(_this), 'incompatibleTokens', '*') + return _this + } + _createClass$1(TimestampMillisecondsParser, [ + { + key: 'parse', + value: function parse(dateString) { + return parseAnyDigitsSigned(dateString) + }, + }, + { + key: 'set', + value: function set(_date, _flags, value) { + return [ + new Date(value), + { + timestampIsSet: true, + }, + ] + }, + }, + ]) + return TimestampMillisecondsParser + })(Parser) + + /* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | Milliseconds in day | + * | b | AM, PM, noon, midnight | B | Flexible day period | + * | c | Stand-alone local day of week | C* | Localized hour w/ day period | + * | d | Day of month | D | Day of year | + * | e | Local day of week | E | Day of week | + * | f | | F* | Day of week in month | + * | g* | Modified Julian day | G | Era | + * | h | Hour [1-12] | H | Hour [0-23] | + * | i! | ISO day of week | I! | ISO week of year | + * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | + * | k | Hour [1-24] | K | Hour [0-11] | + * | l* | (deprecated) | L | Stand-alone month | + * | m | Minute | M | Month | + * | n | | N | | + * | o! | Ordinal number modifier | O* | Timezone (GMT) | + * | p | | P | | + * | q | Stand-alone quarter | Q | Quarter | + * | r* | Related Gregorian year | R! | ISO week-numbering year | + * | s | Second | S | Fraction of second | + * | t! | Seconds timestamp | T! | Milliseconds timestamp | + * | u | Extended year | U* | Cyclic year | + * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | + * | w | Local week of year | W* | Week of month | + * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | + * | y | Year (abs) | Y | Local week-numbering year | + * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + * + * Letters marked by ! are non-standard, but implemented by date-fns: + * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs) + * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, + * i.e. 7 for Sunday, 1 for Monday, etc. + * - `I` is ISO week of year, as opposed to `w` which is local week of year. + * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. + * `R` is supposed to be used in conjunction with `I` and `i` + * for universal ISO week-numbering date, whereas + * `Y` is supposed to be used in conjunction with `w` and `e` + * for week-numbering date specific to the locale. + */ + var parsers = { + G: new EraParser(), + y: new YearParser(), + Y: new LocalWeekYearParser(), + R: new ISOWeekYearParser(), + u: new ExtendedYearParser(), + Q: new QuarterParser(), + q: new StandAloneQuarterParser(), + M: new MonthParser(), + L: new StandAloneMonthParser(), + w: new LocalWeekParser(), + I: new ISOWeekParser(), + d: new DateParser(), + D: new DayOfYearParser(), + E: new DayParser(), + e: new LocalDayParser(), + c: new StandAloneLocalDayParser(), + i: new ISODayParser(), + a: new AMPMParser(), + b: new AMPMMidnightParser(), + B: new DayPeriodParser(), + h: new Hour1to12Parser(), + H: new Hour0to23Parser(), + K: new Hour0To11Parser(), + k: new Hour1To24Parser(), + m: new MinuteParser(), + s: new SecondParser(), + S: new FractionOfSecondParser(), + X: new ISOTimezoneWithZParser(), + x: new ISOTimezoneParser(), + t: new TimestampSecondsParser(), + T: new TimestampMillisecondsParser(), + } + + // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token + // (one of the certain letters followed by `o`) + // - (\w)\1* matches any sequences of the same letter + // - '' matches two quote characters in a row + // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), + // except a single quote symbol, which ends the sequence. + // Two quote characters do not end the sequence. + // If there is no matching single quote + // then the sequence will continue until the end of the string. + // - . matches any single character unmatched by previous parts of the RegExps + var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g + + // This RegExp catches symbols escaped by quotes, and also + // sequences of symbols P, p, and the combinations like `PPPPPPPppppp` + var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g + var escapedStringRegExp = /^'([^]*?)'?$/ + var doubleQuoteRegExp = /''/g + var notWhitespaceRegExp = /\S/ + var unescapedLatinCharacterRegExp = /[a-zA-Z]/ + + /** + * @name parse + * @category Common Helpers + * @summary Parse the date. + * + * @description + * Return the date parsed from string using the given format string. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * The characters in the format string wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * + * Format of the format string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 5 below the table). + * + * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited + * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: + * + * ```javascript + * parse('23 AM', 'HH a', new Date()) + * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time + * ``` + * + * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true + * + * Accepted format string patterns: + * | Unit |Prior| Pattern | Result examples | Notes | + * |---------------------------------|-----|---------|-----------------------------------|-------| + * | Era | 140 | G..GGG | AD, BC | | + * | | | GGGG | Anno Domini, Before Christ | 2 | + * | | | GGGGG | A, B | | + * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | + * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | yy | 44, 01, 00, 17 | 4 | + * | | | yyy | 044, 001, 123, 999 | 4 | + * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | + * | | | yyyyy | ... | 2,4 | + * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | + * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | YY | 44, 01, 00, 17 | 4,6 | + * | | | YYY | 044, 001, 123, 999 | 4 | + * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | + * | | | YYYYY | ... | 2,4 | + * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | + * | | | RR | -43, 01, 00, 17 | 4,5 | + * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | + * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | + * | | | RRRRR | ... | 2,4,5 | + * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | + * | | | uu | -43, 01, 99, -99 | 4 | + * | | | uuu | -043, 001, 123, 999, -999 | 4 | + * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | + * | | | uuuuu | ... | 2,4 | + * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | + * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | QQ | 01, 02, 03, 04 | | + * | | | QQQ | Q1, Q2, Q3, Q4 | | + * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | + * | | | qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | qq | 01, 02, 03, 04 | | + * | | | qqq | Q1, Q2, Q3, Q4 | | + * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | | qqqqq | 1, 2, 3, 4 | 3 | + * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | + * | | | Mo | 1st, 2nd, ..., 12th | 5 | + * | | | MM | 01, 02, ..., 12 | | + * | | | MMM | Jan, Feb, ..., Dec | | + * | | | MMMM | January, February, ..., December | 2 | + * | | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | + * | | | Lo | 1st, 2nd, ..., 12th | 5 | + * | | | LL | 01, 02, ..., 12 | | + * | | | LLL | Jan, Feb, ..., Dec | | + * | | | LLLL | January, February, ..., December | 2 | + * | | | LLLLL | J, F, ..., D | | + * | Local week of year | 100 | w | 1, 2, ..., 53 | | + * | | | wo | 1st, 2nd, ..., 53th | 5 | + * | | | ww | 01, 02, ..., 53 | | + * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | + * | | | Io | 1st, 2nd, ..., 53th | 5 | + * | | | II | 01, 02, ..., 53 | 5 | + * | Day of month | 90 | d | 1, 2, ..., 31 | | + * | | | do | 1st, 2nd, ..., 31st | 5 | + * | | | dd | 01, 02, ..., 31 | | + * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | + * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | + * | | | DD | 01, 02, ..., 365, 366 | 7 | + * | | | DDD | 001, 002, ..., 365, 366 | | + * | | | DDDD | ... | 2 | + * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | | + * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | | EEEEE | M, T, W, T, F, S, S | | + * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | + * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | + * | | | io | 1st, 2nd, ..., 7th | 5 | + * | | | ii | 01, 02, ..., 07 | 5 | + * | | | iii | Mon, Tue, Wed, ..., Sun | 5 | + * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | + * | | | iiiii | M, T, W, T, F, S, S | 5 | + * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | + * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | + * | | | eo | 2nd, 3rd, ..., 1st | 5 | + * | | | ee | 02, 03, ..., 01 | | + * | | | eee | Mon, Tue, Wed, ..., Sun | | + * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | | eeeee | M, T, W, T, F, S, S | | + * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | + * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | + * | | | co | 2nd, 3rd, ..., 1st | 5 | + * | | | cc | 02, 03, ..., 01 | | + * | | | ccc | Mon, Tue, Wed, ..., Sun | | + * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | | ccccc | M, T, W, T, F, S, S | | + * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | + * | AM, PM | 80 | a..aaa | AM, PM | | + * | | | aaaa | a.m., p.m. | 2 | + * | | | aaaaa | a, p | | + * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | + * | | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | | bbbbb | a, p, n, mi | | + * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | + * | | | BBBB | at night, in the morning, ... | 2 | + * | | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | + * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | + * | | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | + * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | + * | | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | + * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | + * | | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | + * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | + * | | | kk | 24, 01, 02, ..., 23 | | + * | Minute | 60 | m | 0, 1, ..., 59 | | + * | | | mo | 0th, 1st, ..., 59th | 5 | + * | | | mm | 00, 01, ..., 59 | | + * | Second | 50 | s | 0, 1, ..., 59 | | + * | | | so | 0th, 1st, ..., 59th | 5 | + * | | | ss | 00, 01, ..., 59 | | + * | Seconds timestamp | 40 | t | 512969520 | | + * | | | tt | ... | 2 | + * | Fraction of second | 30 | S | 0, 1, ..., 9 | | + * | | | SS | 00, 01, ..., 99 | | + * | | | SSS | 000, 001, ..., 999 | | + * | | | SSSS | ... | 2 | + * | Milliseconds timestamp | 20 | T | 512969520900 | | + * | | | TT | ... | 2 | + * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | + * | | | XX | -0800, +0530, Z | | + * | | | XXX | -08:00, +05:30, Z | | + * | | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | + * | | | xx | -0800, +0530, +0000 | | + * | | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | | xxxx | -0800, +0530, +0000, +123456 | | + * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Long localized date | NA | P | 05/29/1453 | 5,8 | + * | | | PP | May 29, 1453 | | + * | | | PPP | May 29th, 1453 | | + * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | + * | Long localized time | NA | p | 12:00 AM | 5,8 | + * | | | pp | 12:00:00 AM | | + * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | + * | | | PPpp | May 29, 1453, 12:00:00 AM | | + * | | | PPPpp | May 29th, 1453 at ... | | + * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular. + * In `format` function, they will produce different result: + * + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * + * `parse` will try to match both formatting and stand-alone units interchangably. + * + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table: + * - for numerical units (`yyyyyyyy`) `parse` will try to match a number + * as wide as the sequence + * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit. + * These variations are marked with "2" in the last column of the table. + * + * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 4. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: + * + * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00` + * + * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00` + * + * while `uu` will just assign the year as is: + * + * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00` + * + * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00` + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} + * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). + * + * 5. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based + * on the given locale. + * + * using `en-US` locale: `P` => `MM/dd/yyyy` + * using `en-US` locale: `p` => `hh:mm a` + * using `pt-BR` locale: `P` => `dd/MM/yyyy` + * using `pt-BR` locale: `p` => `HH:mm` + * + * Values will be assigned to the date in the descending order of its unit's priority. + * Units of an equal priority overwrite each other in the order of appearance. + * + * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year), + * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing. + * + * `referenceDate` must be passed for correct work of the function. + * If you're not sure which `referenceDate` to supply, create a new instance of Date: + * `parse('02/11/2014', 'MM/dd/yyyy', new Date())` + * In this case parsing will be done in the context of the current date. + * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`, + * then `Invalid Date` will be returned. + * + * The result may vary by locale. + * + * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. + * + * If parsing failed, `Invalid Date` will be returned. + * Invalid Date is a Date, whose time value is NaN. + * Time value of Date: http://es5.github.io/#x15.9.1.1 + * + * @param {String} dateString - the string to parse + * @param {String} formatString - the string of tokens + * @param {Date|Number} referenceDate - defines values missing from the parsed dateString + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @returns {Date} the parsed date + * @throws {TypeError} 3 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} `options.locale` must contain `match` property + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Parse 11 February 2014 from middle-endian format: + * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date()) + * //=> Tue Feb 11 2014 00:00:00 + * + * @example + * // Parse 28th of February in Esperanto locale in the context of 2010 year: + * import eo from 'date-fns/locale/eo' + * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), { + * locale: eo + * }) + * //=> Sun Feb 28 2010 00:00:00 + */ + function parse$2(dirtyDateString, dirtyFormatString, dirtyReferenceDate, options) { + var _ref, + _options$locale, + _ref2, + _ref3, + _ref4, + _options$firstWeekCon, + _options$locale2, + _options$locale2$opti, + _defaultOptions$local, + _defaultOptions$local2, + _ref5, + _ref6, + _ref7, + _options$weekStartsOn, + _options$locale3, + _options$locale3$opti, + _defaultOptions$local3, + _defaultOptions$local4 + requiredArgs(3, arguments) + var dateString = String(dirtyDateString) + var formatString = String(dirtyFormatString) + var defaultOptions = getDefaultOptions() + var locale = + (_ref = + (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && + _options$locale !== void 0 + ? _options$locale + : defaultOptions.locale) !== null && _ref !== void 0 + ? _ref + : defaultLocale$1 + if (!locale.match) { + throw new RangeError('locale must contain match property') + } + var firstWeekContainsDate = toInteger$1( + (_ref2 = + (_ref3 = + (_ref4 = + (_options$firstWeekCon = + options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && + _options$firstWeekCon !== void 0 + ? _options$firstWeekCon + : options === null || options === void 0 + ? void 0 + : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 + ? void 0 + : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 + ? void 0 + : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 + ? _ref4 + : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 + ? _ref3 + : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 + ? void 0 + : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 + ? void 0 + : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 + ? _ref2 + : 1, + ) + + // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively') + } + var weekStartsOn = toInteger$1( + (_ref5 = + (_ref6 = + (_ref7 = + (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== + null && _options$weekStartsOn !== void 0 + ? _options$weekStartsOn + : options === null || options === void 0 + ? void 0 + : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 + ? void 0 + : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 + ? void 0 + : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 + ? _ref7 + : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 + ? _ref6 + : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 + ? void 0 + : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 + ? void 0 + : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 + ? _ref5 + : 0, + ) + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively') + } + if (formatString === '') { + if (dateString === '') { + return toDate(dirtyReferenceDate) + } else { + return new Date(NaN) + } + } + var subFnOptions = { + firstWeekContainsDate: firstWeekContainsDate, + weekStartsOn: weekStartsOn, + locale: locale, + } + + // If timezone isn't specified, it will be set to the system timezone + var setters = [new DateToSystemTimezoneSetter()] + var tokens = formatString + .match(longFormattingTokensRegExp) + .map(function (substring) { + var firstCharacter = substring[0] + if (firstCharacter in longFormatters$1) { + var longFormatter = longFormatters$1[firstCharacter] + return longFormatter(substring, locale.formatLong) + } + return substring + }) + .join('') + .match(formattingTokensRegExp) + var usedTokens = [] + var _iterator = _createForOfIteratorHelper(tokens), + _step + try { + var _loop = function _loop() { + var token = _step.value + if ( + !(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && + isProtectedWeekYearToken(token) + ) { + throwProtectedError(token, formatString, dirtyDateString) + } + if ( + !(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && + isProtectedDayOfYearToken(token) + ) { + throwProtectedError(token, formatString, dirtyDateString) + } + var firstCharacter = token[0] + var parser = parsers[firstCharacter] + if (parser) { + var incompatibleTokens = parser.incompatibleTokens + if (Array.isArray(incompatibleTokens)) { + var incompatibleToken = usedTokens.find(function (usedToken) { + return incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter + }) + if (incompatibleToken) { + throw new RangeError( + "The format string mustn't contain `" + .concat(incompatibleToken.fullToken, '` and `') + .concat(token, '` at the same time'), + ) + } + } else if (parser.incompatibleTokens === '*' && usedTokens.length > 0) { + throw new RangeError( + "The format string mustn't contain `".concat(token, '` and any other token at the same time'), + ) + } + usedTokens.push({ + token: firstCharacter, + fullToken: token, + }) + var parseResult = parser.run(dateString, token, locale.match, subFnOptions) + if (!parseResult) { + return { + v: new Date(NaN), + } + } + setters.push(parseResult.setter) + dateString = parseResult.rest + } else { + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError( + 'Format string contains an unescaped latin alphabet character `' + firstCharacter + '`', + ) + } + + // Replace two single quote characters with one single quote character + if (token === "''") { + token = "'" + } else if (firstCharacter === "'") { + token = cleanEscapedString(token) + } + + // Cut token from string, or, if string doesn't match the token, return Invalid Date + if (dateString.indexOf(token) === 0) { + dateString = dateString.slice(token.length) + } else { + return { + v: new Date(NaN), + } + } + } + } + for (_iterator.s(); !(_step = _iterator.n()).done; ) { + var _ret = _loop() + if (_typeof(_ret) === 'object') return _ret.v + } + + // Check if the remaining input contains something other than whitespace + } catch (err) { + _iterator.e(err) + } finally { + _iterator.f() + } + if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) { + return new Date(NaN) + } + var uniquePrioritySetters = setters + .map(function (setter) { + return setter.priority + }) + .sort(function (a, b) { + return b - a + }) + .filter(function (priority, index, array) { + return array.indexOf(priority) === index + }) + .map(function (priority) { + return setters + .filter(function (setter) { + return setter.priority === priority + }) + .sort(function (a, b) { + return b.subPriority - a.subPriority + }) + }) + .map(function (setterArray) { + return setterArray[0] + }) + var date = toDate(dirtyReferenceDate) + if (isNaN(date.getTime())) { + return new Date(NaN) + } + + // Convert the date in system timezone to the same date in UTC+00:00 timezone. + var utcDate = subMilliseconds(date, getTimezoneOffsetInMilliseconds(date)) + var flags = {} + var _iterator2 = _createForOfIteratorHelper(uniquePrioritySetters), + _step2 + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) { + var setter = _step2.value + if (!setter.validate(utcDate, subFnOptions)) { + return new Date(NaN) + } + var result = setter.set(utcDate, flags, subFnOptions) + // Result is tuple (date, flags) + if (Array.isArray(result)) { + utcDate = result[0] + assign(flags, result[1]) + // Result is date + } else { + utcDate = result + } + } + } catch (err) { + _iterator2.e(err) + } finally { + _iterator2.f() + } + return utcDate + } + function cleanEscapedString(input) { + return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'") + } + + /** + * @name isMatch + * @category Common Helpers + * @summary validates the date string against given formats + * + * @description + * Return the true if given date is string correct against the given format else + * will return false. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * The characters in the format string wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * + * Format of the format string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 5 below the table). + * + * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited + * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: + * + * ```javascript + * isMatch('23 AM', 'HH a') + * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time + * ``` + * + * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true + * + * Accepted format string patterns: + * | Unit |Prior| Pattern | Result examples | Notes | + * |---------------------------------|-----|---------|-----------------------------------|-------| + * | Era | 140 | G..GGG | AD, BC | | + * | | | GGGG | Anno Domini, Before Christ | 2 | + * | | | GGGGG | A, B | | + * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | + * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | yy | 44, 01, 00, 17 | 4 | + * | | | yyy | 044, 001, 123, 999 | 4 | + * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | + * | | | yyyyy | ... | 2,4 | + * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | + * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | YY | 44, 01, 00, 17 | 4,6 | + * | | | YYY | 044, 001, 123, 999 | 4 | + * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | + * | | | YYYYY | ... | 2,4 | + * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | + * | | | RR | -43, 01, 00, 17 | 4,5 | + * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | + * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | + * | | | RRRRR | ... | 2,4,5 | + * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | + * | | | uu | -43, 01, 99, -99 | 4 | + * | | | uuu | -043, 001, 123, 999, -999 | 4 | + * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | + * | | | uuuuu | ... | 2,4 | + * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | + * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | QQ | 01, 02, 03, 04 | | + * | | | QQQ | Q1, Q2, Q3, Q4 | | + * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | + * | | | qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | qq | 01, 02, 03, 04 | | + * | | | qqq | Q1, Q2, Q3, Q4 | | + * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | | qqqqq | 1, 2, 3, 4 | 3 | + * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | + * | | | Mo | 1st, 2nd, ..., 12th | 5 | + * | | | MM | 01, 02, ..., 12 | | + * | | | MMM | Jan, Feb, ..., Dec | | + * | | | MMMM | January, February, ..., December | 2 | + * | | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | + * | | | Lo | 1st, 2nd, ..., 12th | 5 | + * | | | LL | 01, 02, ..., 12 | | + * | | | LLL | Jan, Feb, ..., Dec | | + * | | | LLLL | January, February, ..., December | 2 | + * | | | LLLLL | J, F, ..., D | | + * | Local week of year | 100 | w | 1, 2, ..., 53 | | + * | | | wo | 1st, 2nd, ..., 53th | 5 | + * | | | ww | 01, 02, ..., 53 | | + * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | + * | | | Io | 1st, 2nd, ..., 53th | 5 | + * | | | II | 01, 02, ..., 53 | 5 | + * | Day of month | 90 | d | 1, 2, ..., 31 | | + * | | | do | 1st, 2nd, ..., 31st | 5 | + * | | | dd | 01, 02, ..., 31 | | + * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | + * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | + * | | | DD | 01, 02, ..., 365, 366 | 7 | + * | | | DDD | 001, 002, ..., 365, 366 | | + * | | | DDDD | ... | 2 | + * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Su | | + * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | | EEEEE | M, T, W, T, F, S, S | | + * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | + * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | + * | | | io | 1st, 2nd, ..., 7th | 5 | + * | | | ii | 01, 02, ..., 07 | 5 | + * | | | iii | Mon, Tue, Wed, ..., Su | 5 | + * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | + * | | | iiiii | M, T, W, T, F, S, S | 5 | + * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | + * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | + * | | | eo | 2nd, 3rd, ..., 1st | 5 | + * | | | ee | 02, 03, ..., 01 | | + * | | | eee | Mon, Tue, Wed, ..., Su | | + * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | | eeeee | M, T, W, T, F, S, S | | + * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | + * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | + * | | | co | 2nd, 3rd, ..., 1st | 5 | + * | | | cc | 02, 03, ..., 01 | | + * | | | ccc | Mon, Tue, Wed, ..., Su | | + * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | | ccccc | M, T, W, T, F, S, S | | + * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | + * | AM, PM | 80 | a..aaa | AM, PM | | + * | | | aaaa | a.m., p.m. | 2 | + * | | | aaaaa | a, p | | + * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | + * | | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | | bbbbb | a, p, n, mi | | + * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | + * | | | BBBB | at night, in the morning, ... | 2 | + * | | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | + * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | + * | | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | + * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | + * | | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | + * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | + * | | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | + * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | + * | | | kk | 24, 01, 02, ..., 23 | | + * | Minute | 60 | m | 0, 1, ..., 59 | | + * | | | mo | 0th, 1st, ..., 59th | 5 | + * | | | mm | 00, 01, ..., 59 | | + * | Second | 50 | s | 0, 1, ..., 59 | | + * | | | so | 0th, 1st, ..., 59th | 5 | + * | | | ss | 00, 01, ..., 59 | | + * | Seconds timestamp | 40 | t | 512969520 | | + * | | | tt | ... | 2 | + * | Fraction of second | 30 | S | 0, 1, ..., 9 | | + * | | | SS | 00, 01, ..., 99 | | + * | | | SSS | 000, 001, ..., 999 | | + * | | | SSSS | ... | 2 | + * | Milliseconds timestamp | 20 | T | 512969520900 | | + * | | | TT | ... | 2 | + * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | + * | | | XX | -0800, +0530, Z | | + * | | | XXX | -08:00, +05:30, Z | | + * | | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | + * | | | xx | -0800, +0530, +0000 | | + * | | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | | xxxx | -0800, +0530, +0000, +123456 | | + * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Long localized date | NA | P | 05/29/1453 | 5,8 | + * | | | PP | May 29, 1453 | | + * | | | PPP | May 29th, 1453 | | + * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | + * | Long localized time | NA | p | 12:00 AM | 5,8 | + * | | | pp | 12:00:00 AM | | + * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | + * | | | PPpp | May 29, 1453, 12:00:00 AM | | + * | | | PPPpp | May 29th, 1453 at ... | | + * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular. + * In `format` function, they will produce different result: + * + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * + * `isMatch` will try to match both formatting and stand-alone units interchangably. + * + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table: + * - for numerical units (`yyyyyyyy`) `isMatch` will try to match a number + * as wide as the sequence + * - for text units (`MMMMMMMM`) `isMatch` will try to match the widest variation of the unit. + * These variations are marked with "2" in the last column of the table. + * + * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 4. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: + * + * `isMatch('50', 'yy') //=> true` + * + * `isMatch('75', 'yy') //=> true` + * + * while `uu` will use the year as is: + * + * `isMatch('50', 'uu') //=> true` + * + * `isMatch('75', 'uu') //=> true` + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} + * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). + * + * 5. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based + * on the given locale. + * + * using `en-US` locale: `P` => `MM/dd/yyyy` + * using `en-US` locale: `p` => `hh:mm a` + * using `pt-BR` locale: `P` => `dd/MM/yyyy` + * using `pt-BR` locale: `p` => `HH:mm` + * + * Values will be checked in the descending order of its unit's priority. + * Units of an equal priority overwrite each other in the order of appearance. + * + * If no values of higher priority are matched (e.g. when matching string 'January 1st' without a year), + * the values will be taken from today's using `new Date()` date which works as a context of parsing. + * + * The result may vary by locale. + * + * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. + * + * + * + * @param {String} dateString - the date string to verify + * @param {String} formatString - the string of tokens + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @returns {Boolean} + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} `options.locale` must contain `match` property + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `yy` instead of `YY` for formatting years; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `d` instead of `D` for formatting days of the month; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Match 11 February 2014 from middle-endian format: + * const result = isMatch('02/11/2014', 'MM/dd/yyyy') + * //=> true + * + * @example + * // Match 28th of February in Esperanto locale in the context of 2010 year: + * import eo from 'date-fns/locale/eo' + * const result = isMatch('28-a de februaro', "do 'de' MMMM", { + * locale: eo + * }) + * //=> true + */ + function isMatch(dateString, formatString, options) { + requiredArgs(2, arguments) + return isValid(parse$2(dateString, formatString, new Date(), options)) + } + + /** + * @name isSameWeek + * @category Week Helpers + * @summary Are the given dates in the same week (and month and year)? + * + * @description + * Are the given dates in the same week (and month and year)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Boolean} the dates are in the same week (and month and year) + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // Are 31 August 2014 and 4 September 2014 in the same week? + * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4)) + * //=> true + * + * @example + * // If week starts with Monday, + * // are 31 August 2014 and 4 September 2014 in the same week? + * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4), { + * weekStartsOn: 1 + * }) + * //=> false + * + * @example + * // Are 1 January 2014 and 1 January 2015 in the same week? + * const result = isSameWeek(new Date(2014, 0, 1), new Date(2015, 0, 1)) + * //=> false + */ + function isSameWeek(dirtyDateLeft, dirtyDateRight, options) { + requiredArgs(2, arguments) + var dateLeftStartOfWeek = startOfWeek(dirtyDateLeft, options) + var dateRightStartOfWeek = startOfWeek(dirtyDateRight, options) + return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime() + } + + /** + * @name isSameMonth + * @category Month Helpers + * @summary Are the given dates in the same month (and year)? + * + * @description + * Are the given dates in the same month (and year)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same month (and year) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 2 September 2014 and 25 September 2014 in the same month? + * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25)) + * //=> true + * + * @example + * // Are 2 September 2014 and 25 September 2015 in the same month? + * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25)) + * //=> false + */ + function isSameMonth(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments) + var dateLeft = toDate(dirtyDateLeft) + var dateRight = toDate(dirtyDateRight) + return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth() + } + + /** + * @name isWithinInterval + * @category Interval Helpers + * @summary Is the given date within the interval? + * + * @description + * Is the given date within the interval? (Including start and end.) + * + * @param {Date|Number} date - the date to check + * @param {Interval} interval - the interval to check + * @returns {Boolean} the date is within the interval + * @throws {TypeError} 2 arguments required + * @throws {RangeError} The start of an interval cannot be after its end + * @throws {RangeError} Date in interval cannot be `Invalid Date` + * + * @example + * // For the date within the interval: + * isWithinInterval(new Date(2014, 0, 3), { + * start: new Date(2014, 0, 1), + * end: new Date(2014, 0, 7) + * }) + * //=> true + * + * @example + * // For the date outside of the interval: + * isWithinInterval(new Date(2014, 0, 10), { + * start: new Date(2014, 0, 1), + * end: new Date(2014, 0, 7) + * }) + * //=> false + * + * @example + * // For date equal to interval start: + * isWithinInterval(date, { start, end: date }) // => true + * + * @example + * // For date equal to interval end: + * isWithinInterval(date, { start: date, end }) // => true + */ + function isWithinInterval(dirtyDate, interval) { + requiredArgs(2, arguments) + var time = toDate(dirtyDate).getTime() + var startTime = toDate(interval.start).getTime() + var endTime = toDate(interval.end).getTime() + + // Throw an exception if start date is after end date or if any date is `Invalid Date` + if (!(startTime <= endTime)) { + throw new RangeError('Invalid interval') + } + return time >= startTime && time <= endTime + } + + /** + * @name subDays + * @category Day Helpers + * @summary Subtract the specified number of days from the given date. + * + * @description + * Subtract the specified number of days from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of days to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the days subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 10 days from 1 September 2014: + * const result = subDays(new Date(2014, 8, 1), 10) + * //=> Fri Aug 22 2014 00:00:00 + */ + function subDays(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments) + var amount = toInteger$1(dirtyAmount) + return addDays(dirtyDate, -amount) + } + + /** + * @name parseISO + * @category Common Helpers + * @summary Parse ISO string + * + * @description + * Parse the given string in ISO 8601 format and return an instance of Date. + * + * Function accepts complete ISO 8601 formats as well as partial implementations. + * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 + * + * If the argument isn't a string, the function cannot parse the string or + * the values are invalid, it returns Invalid Date. + * + * @param {String} argument - the value to convert + * @param {Object} [options] - an object with options. + * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 + * + * @example + * // Convert string '2014-02-11T11:30:30' to date: + * const result = parseISO('2014-02-11T11:30:30') + * //=> Tue Feb 11 2014 11:30:30 + * + * @example + * // Convert string '+02014101' to date, + * // if the additional number of digits in the extended year format is 1: + * const result = parseISO('+02014101', { additionalDigits: 1 }) + * //=> Fri Apr 11 2014 00:00:00 + */ + function parseISO(argument, options) { + var _options$additionalDi + requiredArgs(1, arguments) + var additionalDigits = toInteger$1( + (_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && + _options$additionalDi !== void 0 + ? _options$additionalDi + : 2, + ) + if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) { + throw new RangeError('additionalDigits must be 0, 1 or 2') + } + if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) { + return new Date(NaN) + } + var dateStrings = splitDateString(argument) + var date + if (dateStrings.date) { + var parseYearResult = parseYear(dateStrings.date, additionalDigits) + date = parseDate(parseYearResult.restDateString, parseYearResult.year) + } + if (!date || isNaN(date.getTime())) { + return new Date(NaN) + } + var timestamp = date.getTime() + var time = 0 + var offset + if (dateStrings.time) { + time = parseTime(dateStrings.time) + if (isNaN(time)) { + return new Date(NaN) + } + } + if (dateStrings.timezone) { + offset = parseTimezone(dateStrings.timezone) + if (isNaN(offset)) { + return new Date(NaN) + } + } else { + var dirtyDate = new Date(timestamp + time) + // js parsed string assuming it's in UTC timezone + // but we need it to be parsed in our timezone + // so we use utc values to build date in our timezone. + // Year values from 0 to 99 map to the years 1900 to 1999 + // so set year explicitly with setFullYear. + var result = new Date(0) + result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate()) + result.setHours( + dirtyDate.getUTCHours(), + dirtyDate.getUTCMinutes(), + dirtyDate.getUTCSeconds(), + dirtyDate.getUTCMilliseconds(), + ) + return result + } + return new Date(timestamp + time + offset) + } + var patterns = { + dateTimeDelimiter: /[T ]/, + timeZoneDelimiter: /[Z ]/i, + timezone: /([Z+-].*)$/, + } + var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/ + var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/ + var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/ + function splitDateString(dateString) { + var dateStrings = {} + var array = dateString.split(patterns.dateTimeDelimiter) + var timeString + + // The regex match should only return at maximum two array elements. + // [date], [time], or [date, time]. + if (array.length > 2) { + return dateStrings + } + if (/:/.test(array[0])) { + timeString = array[0] + } else { + dateStrings.date = array[0] + timeString = array[1] + if (patterns.timeZoneDelimiter.test(dateStrings.date)) { + dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0] + timeString = dateString.substr(dateStrings.date.length, dateString.length) + } + } + if (timeString) { + var token = patterns.timezone.exec(timeString) + if (token) { + dateStrings.time = timeString.replace(token[1], '') + dateStrings.timezone = token[1] + } else { + dateStrings.time = timeString + } + } + return dateStrings + } + function parseYear(dateString, additionalDigits) { + var regex = new RegExp( + '^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)', + ) + var captures = dateString.match(regex) + // Invalid ISO-formatted year + if (!captures) + return { + year: NaN, + restDateString: '', + } + var year = captures[1] ? parseInt(captures[1]) : null + var century = captures[2] ? parseInt(captures[2]) : null + + // either year or century is null, not both + return { + year: century === null ? year : century * 100, + restDateString: dateString.slice((captures[1] || captures[2]).length), + } + } + function parseDate(dateString, year) { + // Invalid ISO-formatted year + if (year === null) return new Date(NaN) + var captures = dateString.match(dateRegex) + // Invalid ISO-formatted string + if (!captures) return new Date(NaN) + var isWeekDate = !!captures[4] + var dayOfYear = parseDateUnit(captures[1]) + var month = parseDateUnit(captures[2]) - 1 + var day = parseDateUnit(captures[3]) + var week = parseDateUnit(captures[4]) + var dayOfWeek = parseDateUnit(captures[5]) - 1 + if (isWeekDate) { + if (!validateWeekDate(year, week, dayOfWeek)) { + return new Date(NaN) + } + return dayOfISOWeekYear(year, week, dayOfWeek) + } else { + var date = new Date(0) + if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) { + return new Date(NaN) + } + date.setUTCFullYear(year, month, Math.max(dayOfYear, day)) + return date + } + } + function parseDateUnit(value) { + return value ? parseInt(value) : 1 + } + function parseTime(timeString) { + var captures = timeString.match(timeRegex) + if (!captures) return NaN // Invalid ISO-formatted time + + var hours = parseTimeUnit(captures[1]) + var minutes = parseTimeUnit(captures[2]) + var seconds = parseTimeUnit(captures[3]) + if (!validateTime(hours, minutes, seconds)) { + return NaN + } + return hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1000 + } + function parseTimeUnit(value) { + return (value && parseFloat(value.replace(',', '.'))) || 0 + } + function parseTimezone(timezoneString) { + if (timezoneString === 'Z') return 0 + var captures = timezoneString.match(timezoneRegex) + if (!captures) return 0 + var sign = captures[1] === '+' ? -1 : 1 + var hours = parseInt(captures[2]) + var minutes = (captures[3] && parseInt(captures[3])) || 0 + if (!validateTimezone(hours, minutes)) { + return NaN + } + return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute) + } + function dayOfISOWeekYear(isoWeekYear, week, day) { + var date = new Date(0) + date.setUTCFullYear(isoWeekYear, 0, 4) + var fourthOfJanuaryDay = date.getUTCDay() || 7 + var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay + date.setUTCDate(date.getUTCDate() + diff) + return date + } + + // Validation functions + + // February is null to handle the leap year (using ||) + var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + function isLeapYearIndex(year) { + return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0) + } + function validateDate(year, month, date) { + return ( + month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)) + ) + } + function validateDayOfYearDate(year, dayOfYear) { + return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365) + } + function validateWeekDate(_year, week, day) { + return week >= 1 && week <= 53 && day >= 0 && day <= 6 + } + function validateTime(hours, minutes, seconds) { + if (hours === 24) { + return minutes === 0 && seconds === 0 + } + return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25 + } + function validateTimezone(_hours, minutes) { + return minutes >= 0 && minutes <= 59 + } + + /** + * @name setYear + * @category Year Helpers + * @summary Set the year to the given date. + * + * @description + * Set the year to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} year - the year of the new date + * @returns {Date} the new date with the year set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set year 2013 to 1 September 2014: + * const result = setYear(new Date(2014, 8, 1), 2013) + * //=> Sun Sep 01 2013 00:00:00 + */ + function setYear(dirtyDate, dirtyYear) { + requiredArgs(2, arguments) + var date = toDate(dirtyDate) + var year = toInteger$1(dirtyYear) + + // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date + if (isNaN(date.getTime())) { + return new Date(NaN) + } + date.setFullYear(year) + return date + } + + /** + * @name subYears + * @category Year Helpers + * @summary Subtract the specified number of years from the given date. + * + * @description + * Subtract the specified number of years from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the years subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 5 years from 1 September 2014: + * const result = subYears(new Date(2014, 8, 1), 5) + * //=> Tue Sep 01 2009 00:00:00 + */ + function subYears(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments) + var amount = toInteger$1(dirtyAmount) + return addYears(dirtyDate, -amount) + } + + /** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + + /** Used as references for various `Number` constants. */ + var INFINITY$2 = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e308, + NAN = 0 / 0 + + /** `Object#toString` result references. */ + var symbolTag$2 = '[object Symbol]' + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i + + /** Used to compose unicode character classes. */ + var rsAstralRange$2 = '\\ud800-\\udfff', + rsComboMarksRange$2 = '\\u0300-\\u036f\\ufe20-\\ufe23', + rsComboSymbolsRange$2 = '\\u20d0-\\u20f0', + rsVarRange$2 = '\\ufe0e\\ufe0f' + + /** Used to compose unicode capture groups. */ + var rsAstral$2 = '[' + rsAstralRange$2 + ']', + rsCombo$2 = '[' + rsComboMarksRange$2 + rsComboSymbolsRange$2 + ']', + rsFitz$2 = '\\ud83c[\\udffb-\\udfff]', + rsModifier$2 = '(?:' + rsCombo$2 + '|' + rsFitz$2 + ')', + rsNonAstral$2 = '[^' + rsAstralRange$2 + ']', + rsRegional$2 = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair$2 = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ$2 = '\\u200d' + + /** Used to compose unicode regexes. */ + var reOptMod$2 = rsModifier$2 + '?', + rsOptVar$2 = '[' + rsVarRange$2 + ']?', + rsOptJoin$2 = + '(?:' + + rsZWJ$2 + + '(?:' + + [rsNonAstral$2, rsRegional$2, rsSurrPair$2].join('|') + + ')' + + rsOptVar$2 + + reOptMod$2 + + ')*', + rsSeq$2 = rsOptVar$2 + reOptMod$2 + rsOptJoin$2, + rsSymbol$2 = + '(?:' + [rsNonAstral$2 + rsCombo$2 + '?', rsCombo$2, rsRegional$2, rsSurrPair$2, rsAstral$2].join('|') + ')' + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode$2 = RegExp(rsFitz$2 + '(?=' + rsFitz$2 + ')|' + rsSymbol$2 + rsSeq$2, 'g') + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode$2 = RegExp( + '[' + rsZWJ$2 + rsAstralRange$2 + rsComboMarksRange$2 + rsComboSymbolsRange$2 + rsVarRange$2 + ']', + ) + + /** Built-in method references without a dependency on `root`. */ + var freeParseInt = parseInt + + /** Detect free variable `global` from Node.js. */ + var freeGlobal$2 = + typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal + + /** Detect free variable `self`. */ + var freeSelf$2 = typeof self == 'object' && self && self.Object === Object && self + + /** Used as a reference to the global object. */ + var root$2 = freeGlobal$2 || freeSelf$2 || Function('return this')() + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length') + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray$2(string) { + return string.split('') + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function (object) { + return object == null ? undefined : object[key] + } + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode$2(string) { + return reHasUnicode$2.test(string) + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode$2(string) ? unicodeSize(string) : asciiSize(string) + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray$2(string) { + return hasUnicode$2(string) ? unicodeToArray$2(string) : asciiToArray$2(string) + } + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = (reUnicode$2.lastIndex = 0) + while (reUnicode$2.test(string)) { + result++ + } + return result + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray$2(string) { + return string.match(reUnicode$2) || [] + } + + /** Used for built-in method references. */ + var objectProto$3 = Object.prototype + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString$3 = objectProto$3.toString + + /** Built-in value references. */ + var Symbol$3 = root$2.Symbol + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor + + /** Used to convert symbols to primitives and strings. */ + var symbolProto$2 = Symbol$3 ? Symbol$3.prototype : undefined, + symbolToString$2 = symbolProto$2 ? symbolProto$2.toString : undefined + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = '' + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string + } + n = nativeFloor(n / 2) + if (n) { + string += string + } + } while (n) + + return result + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice$2(array, start, end) { + var index = -1, + length = array.length + + if (start < 0) { + start = -start > length ? 0 : length + start + } + end = end > length ? length : end + if (end < 0) { + end += length + } + length = start > end ? 0 : (end - start) >>> 0 + start >>>= 0 + + var result = Array(length) + while (++index < length) { + result[index] = array[index + start] + } + return result + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString$2(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value + } + if (isSymbol$2(value)) { + return symbolToString$2 ? symbolToString$2.call(value) : '' + } + var result = value + '' + return result == '0' && 1 / value == -INFINITY$2 ? '-0' : result + } + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice$2(array, start, end) { + var length = array.length + end = end === undefined ? length : end + return !start && end >= length ? array : baseSlice$2(array, start, end) + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString$2(chars) + + var charsLength = chars.length + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))) + return hasUnicode$2(chars) ? castSlice$2(stringToArray$2(result), 0, length).join('') : result.slice(0, length) + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value + return !!value && (type == 'object' || type == 'function') + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike$3(value) { + return !!value && typeof value == 'object' + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol$2(value) { + return typeof value == 'symbol' || (isObjectLike$3(value) && objectToString$3.call(value) == symbolTag$2) + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0 + } + value = toNumber$2(value) + if (value === INFINITY$2 || value === -INFINITY$2) { + var sign = value < 0 ? -1 : 1 + return sign * MAX_INTEGER + } + return value === value ? value : 0 + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1 + + return result === result ? (remainder ? result - remainder : result) : 0 + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber$2(value) { + if (typeof value == 'number') { + return value + } + if (isSymbol$2(value)) { + return NAN + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value + value = isObject(other) ? other + '' : other + } + if (typeof value != 'string') { + return value === 0 ? value : +value + } + value = value.replace(reTrim, '') + var isBinary = reIsBinary.test(value) + return isBinary || reIsOctal.test(value) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : reIsBadHex.test(value) + ? NAN + : +value + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString$2(value) { + return value == null ? '' : baseToString$2(value) + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart$1(string, length, chars) { + string = toString$2(string) + length = toInteger(length) + + var strLength = length ? stringSize(string) : 0 + return length && strLength < length ? createPadding(length - strLength, chars) + string : string + } + + var lodash_padstart = padStart$1 + + var lodash_isdate = { exports: {} } + + /** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + + ;(function (module, exports) { + /** `Object#toString` result references. */ + var dateTag = '[object Date]' + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = + typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function () { + try { + return freeProcess && freeProcess.binding('util') + } catch (e) {} + })() + + /* Node.js helper references. */ + var nodeIsDate = nodeUtil && nodeUtil.isDate + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function (value) { + return func(value) + } + } + + /** Used for built-in method references. */ + var objectProto = Object.prototype + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && objectToString.call(value) == dateTag + } + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return !!value && typeof value == 'object' + } + + module.exports = isDate + })(lodash_isdate, lodash_isdate.exports) + + /** + * lodash 3.0.2 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + + /** `Object#toString` result references. */ + var numberTag = '[object Number]' + + /** Used for built-in method references. */ + var objectProto$2 = Object.prototype + + /** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString$2 = objectProto$2.toString + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike$2(value) { + return !!value && typeof value == 'object' + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4) + * which returns `true` for `undefined` and other non-numeric values. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN$1(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some ActiveX objects in IE. + return isNumber$2(value) && value != +value + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber$2(value) { + return typeof value == 'number' || (isObjectLike$2(value) && objectToString$2.call(value) == numberTag) + } + + var lodash_isnan = isNaN$1 + + /** + * Returns `true` if the arrays are equal + * + * ```typescript + * areArraysEqual(['a', 'b'], ['b', 'a']) // true + * ``` + */ + function areArraysEqual(a, b) { + if (lodash_isnil(a) || lodash_isnil(b)) { + return false + } + const copyA = [...a].sort() + const copyB = [...b].sort() + return isEqual(copyA, copyB) + } + + /** + * Parses the locale to the correct display locale + * + * ```typescript + * numberLocale('de-CH') + * // 'de-CH' + * ``` + */ + function numberLocale(locale = 'de-CH') { + const [, region] = locale.split('-') + if (region === 'CH') { + return 'de-CH' + } + if (region === 'BE') { + return 'fr-BE' + } + if (region === 'LU') { + return 'fr-LU' + } + return locale + } + /** + * Parses the locale to the correct display locale + * + * ```typescript + * numberLocale('de-CH') + * // 'fr-CH' + * ``` + */ + function dateLocale(locale = 'de-CH') { + const [, region] = locale.split('-') + if (region === 'CH') { + return 'fr-CH' + } + if (region === 'BE') { + return 'fr-BE' + } + if (region === 'LU') { + return 'fr-LU' + } + return locale + } + + const ISO_PATTERN = 'yyyy-MM-dd' + const DATE_PATTERN = 'dd-MM-yyyy' + const TIMEZONE = 'T00:00:00.000Z' + /** + * Returns a JS Date instance of the exact moment + * + * ```typescript + * const date = now() + * // Wed Mar 10 2021 20:30:32 GMT+0100 (Central European Standard Time) + * ``` + */ + function now$1() { + return new Date() + } + /** + * Return the formatted date string in ISO 8601 format. Options may be passed to control the parts and notations of the date. + * + * ```typescript + * const dateString = formatDateString(new Date()) + * // '2022-02-14' + * ``` + */ + function formatDateString(date) { + return date && isValid(date) ? formatISO(date, { representation: 'date' }) : '' + } + /** + * Validates if the given date string matches the iso date format. + * + * ```typescript + * isValidIsoString('2022-02-14') + * // 'true' + * ``` + */ + function isValidIsoString(dateString) { + return !!dateString ? isMatch(dateString, ISO_PATTERN) : false + } + /** + * Formats the dates according to the given locale. + * + * ```typescript + * format('de-CH', new Date()) + * // '14.2.2022' + * ``` + */ + function format(locale = 'de-CH', date) { + return isValid(date) ? intlFormat(dateLocale(locale), date) : '' + } + /** + * Parses the iso date string into a javascript date object. + * + * ```typescript + * const dateString = parse('2021-03-10') + * // Wed Mar 10 2021 00:00:00 GMT+0100 (Central European Standard Time) + * ``` + */ + function parse$1(dateString, locale = 'de-CH') { + if (isMatch(dateString, ISO_PATTERN)) { + const d = parseISO(dateString + TIMEZONE) + if (d && isValid(d)) { + return validateYear(d) + } + const [year, month, day] = `${dateString}`.split('-').map(d => parseInt(d, 10)) + return generateIsoDate([year, month, day]) + } + if (isMatch(dateString, getDatePattern(locale))) { + const d = parse$2(dateString, getDatePattern(locale), now$1()) + return generateIsoDate([getYear(d), getMonth(d) + 1, getDate(d)]) + } + return undefined + } + /** + * Returns the char which separates day form month and year. + * + * ```typescript + * dateSeparator('de-CH') + * // . + * ``` + */ + function dateSeparator(locale = 'de-CH') { + return new Intl.DateTimeFormat(dateLocale(locale)) + .format(now$1()) + .replace(/\p{Number}/gu, '') + .charAt(0) + } + /************************************************************** + * PRIVATE + **************************************************************/ + function getDatePattern(locale = 'de-CH') { + return DATE_PATTERN.split('-').join(dateSeparator(locale)) + } + function intlFormat(locale = 'de-CH', date) { + const intl = new Intl.DateTimeFormat(dateLocale(locale)) + return intl.format(date) + } + function pad(value) { + return lodash_padstart(`${value}`, 2, '0') + } + function validateYear(date) { + if (date && isValid(date)) { + if (getYear(date) < 1000) { + return setYear(date, getYear(date) + 2000) + } + return date + } + return undefined + } + function generateIsoDate([year, month, day]) { + if (year > 0 && month > 0 && day > 0) { + return parseISO(`${year < 1000 ? year + 2000 : year}-${pad(month)}-${pad(day)}` + TIMEZONE) + } + return undefined + } + + /** + * Returns `true` if the keyboard event was triggered by the `Enter` key + */ + function isEnterKey(event) { + return event.key === 'Enter' + } + /** + * Returns `true` if the keyboard event was triggered by the `Space` key + */ + function isSpaceKey(event) { + return event.key === ' ' + } + /** + * Returns `true` if the keyboard event was triggered by the `Escape` key + */ + function isEscapeKey(event) { + return event.key === 'Escape' + } + /** + * Returns `true` if the keyboard event was triggered by the `Backspace` key + */ + function isBackspaceKey(event) { + return event.key === 'Backspace' + } + /** + * Returns `true` if the keyboard event was triggered by the `ArrowDown` key + */ + function isArrowDownKey(event) { + return event.key === 'ArrowDown' || event.key === 'Down' + } + /** + * Returns `true` if the keyboard event was triggered by the `ArrowUp` key + */ + function isArrowUpKey(event) { + return event.key === 'ArrowUp' || event.key === 'Up' + } + /** + * Returns the decimal separator of the given locale + * + * ```typescript + * getDecimalSeparator('de-ch') // . + * ``` + */ + function getDecimalSeparator$1(locale = 'de-CH') { + return Intl.NumberFormat(numberLocale(locale)) + .format(1.1) + .replace(/\p{Number}/gu, '') + } + /** + * Returns the thousand separator of the given locale + * + * ```typescript + * getThousandSeparator('de-ch') // ' + * ``` + */ + function getThousandSeparator$1(locale = 'de-CH') { + return Intl.NumberFormat(numberLocale(locale)) + .format(11111) + .replace(/\p{Number}/gu, '') + } + /** + * Formats the number into the given locale + * + * ```typescript + * formatLocaleNumber('de-ch', 1000.42) // 1'000.42 + * ``` + */ + function formatLocaleNumber$1(locale = 'de-CH', number, minimumFractionDigits) { + const options = + minimumFractionDigits !== undefined + ? { minimumFractionDigits, maximumFractionDigits: minimumFractionDigits } + : {} + const formattedNumber = Intl.NumberFormat(numberLocale(locale), Object.assign({}, options)).format(number) + if (formattedNumber === 'NaN') { + return '' + } + return formattedNumber + } + + var RequestState + ;(function (RequestState) { + RequestState[(RequestState['INIT'] = 0)] = 'INIT' + RequestState[(RequestState['RUNNING'] = 1)] = 'RUNNING' + RequestState[(RequestState['SUCCESS'] = 2)] = 'SUCCESS' + RequestState[(RequestState['ERROR'] = 3)] = 'ERROR' + })(RequestState || (RequestState = {})) + + class Language { + constructor(key) { + this.key = key + } + } + + new Language('de') + new Language('fr') + new Language('it') + new Language('en') + new Language('nl') + new Language('lb') + + const INTEGRATION_BASE_URL = 'https://www.baloise.ch' + const INTEGRATION_BASE_PATH = '/app-integration' + const getIntegrationBaseUrl = () => { + const host = getHost() + if (host && host.indexOf('www.baloise.ch') >= 0) { + return `https://${host}` + } + return INTEGRATION_BASE_URL + } + const getIntegrationUrl = (lang, region = 'CH', type = IntegrationType.FOOTER, version = 'v2') => { + let langPath = lang.key + if (type === IntegrationType.ONETRUST) { + langPath = 'all' + } else { + if (region === 'DE') { + langPath = 'de' + } + } + return `${getIntegrationBaseUrl()}${INTEGRATION_BASE_PATH}/${version}/${region.toLowerCase()}/${type}/${langPath}.json` + } + const getHost = () => { + var _a + return ( + ((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 + ? void 0 + : _a.host) || undefined + ) + } + var IntegrationType + ;(function (IntegrationType) { + IntegrationType['FOOTER'] = 'footer' + IntegrationType['SOCIAL_MEDIA'] = 'socialmediachannels' + IntegrationType['ONETRUST'] = 'onetrust' + })(IntegrationType || (IntegrationType = {})) + + const loadFooterLinks = (lang, region = 'CH') => { + const url = getIntegrationUrl(lang, region, IntegrationType.FOOTER) + return fetch(url) + .then(res => res.json()) + .then(res => res) + } + + const loadSocialMediaLinks = (lang, region = 'CH') => { + const url = getIntegrationUrl(lang, region, IntegrationType.SOCIAL_MEDIA, 'v1') + return fetch(url) + .then(res => res.json()) + .then(res => res) + } + + const balAccordionSummaryCss = + '@media (hover: hover)and (pointer: fine){.bal-accordion__summary--trigger:focus-visible{-webkit-box-shadow:var(--bal-focus-shadow) !important;box-shadow:var(--bal-focus-shadow) !important}}.bal-accordion__summary{position:static;display:block}.bal-accordion__summary--trigger{cursor:pointer}' + var BalAccordionSummaryStyle0 = balAccordionSummaryCss + + class AccordionSummary { + constructor(hostRef) { + registerInstance(this, hostRef) + this.componentId = `bal-accordion-summary-${accordionSummaryIds++}` + /** + * PRIVATE METHODS + * ------------------------------------------------------ + */ + this.updateAccordionId = () => { + var _a + return (this.parentAccordionId = + (_a = this.parentAccordionElement) === null || _a === void 0 ? void 0 : _a.id) + } + /** + * EVENT HANDLER + * ------------------------------------------------------ + */ + this.onClick = ev => { + var _a + stopEventBubbling(ev) + ;(_a = this.parentAccordionElement) === null || _a === void 0 ? void 0 : _a.humanToggle() + } + this.onKeyDown = ev => { + var _a + if (isEnterKey(ev) || isSpaceKey(ev)) { + stopEventBubbling(ev) + ;(_a = this.parentAccordionElement) === null || _a === void 0 ? void 0 : _a.humanToggle() + } + } + this.parentAccordionId = undefined + this.trigger = false + this.active = false + this.state = 1 /* AccordionState.Collapsed */ + } + createLogger(log) { + this.log = log + } + /** + * LIFECYCLE + * ------------------------------------------------------ + */ + connectedCallback() { + const accordion = this.parentAccordionElement + if (accordion) { + accordion.version = 2 + } + this.updateAccordionId() + } + disconnectedCallback() { + const accordion = this.parentAccordionElement + if (accordion) { + accordion.version = 1 + } + this.updateAccordionId() + } + /** + * GETTERS + * ------------------------------------------------------ + */ + get parentAccordionElement() { + var _a + return ((_a = this.el) === null || _a === void 0 ? void 0 : _a.closest('bal-accordion')) || null + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + const block = BEM.block('accordion').element('summary') + const id = this.parentAccordionId ? `${this.parentAccordionId}-summary` : this.componentId + const expanded = + this.state === 4 /* AccordionState.Expanded */ || this.state === 8 /* AccordionState.Expanding */ + const buttonPart = expanded ? 'button expanded' : 'button' + let attributes = {} + if (this.trigger) { + attributes = { + 'aria-controls': `${this.parentAccordionId}-details-content`, + 'role': 'button', + 'tabindex': 0, + 'part': buttonPart, + 'data-testid': 'bal-accordion-button', + 'onClick': this.onClick, + 'onKeyDown': this.onKeyDown, + } + } + return hAsync( + Host, + Object.assign( + { + key: 'fdc15536bfcd84d7892ba5a6b64cf702d26a0b7e', + id: id, + class: Object.assign( + Object.assign( + Object.assign(Object.assign({}, block.class()), block.modifier('trigger').class(this.trigger)), + block.modifier('inner-trigger').class(!this.trigger), + ), + { 'bal-focused': this.trigger }, + ), + }, + attributes, + { 'data-testid': 'bal-accordion-summary' }, + ), + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalAccordionSummaryStyle0 + } + static get cmpMeta() { + return { + $flags$: 0, + $tagName$: 'bal-accordion-summary', + $members$: { + trigger: [4], + active: [1540], + state: [2], + parentAccordionId: [32], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [['active', 'active']], + } + } + } + __decorate( + [ + Logger('bal-accordion-summary'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + AccordionSummary.prototype, + 'createLogger', + null, + ) + let accordionSummaryIds = 0 + + const balAccordionTriggerCss = + '@media (hover: hover)and (pointer: fine){.bal-accordion__trigger__button.bal-focused:focus-visible{-webkit-box-shadow:var(--bal-focus-shadow) !important;box-shadow:var(--bal-focus-shadow) !important}}.bal-accordion__trigger{position:static;display:block}.bal-accordion__trigger__button{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;background:rgba(0,0,0,0);border:none;height:3rem;width:3rem;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer}' + var BalAccordionTriggerStyle0 = balAccordionTriggerCss + + class AccordionTrigger { + constructor(hostRef) { + registerInstance(this, hostRef) + this.componentId = `bal-accordion-trigger-${accordionTriggerIds++}` + /** + * PRIVATE METHODS + * ------------------------------------------------------ + */ + this.updateAccordionId = () => { + var _a + return (this.parentAccordionId = + (_a = this.parentAccordionElement) === null || _a === void 0 ? void 0 : _a.id) + } + /** + * EVENT HANDLER + * ------------------------------------------------------ + */ + this.onClick = ev => { + var _a + stopEventBubbling(ev) + ;(_a = this.parentAccordionElement) === null || _a === void 0 ? void 0 : _a.humanToggle() + } + this.parentAccordionId = undefined + this.button = false + this.openLabel = '' + this.openIcon = 'caret-down' + this.closeLabel = '' + this.closeIcon = '' + this.color = 'info' + this.size = '' + this.active = false + this.state = 1 /* AccordionState.Collapsed */ + } + createLogger(log) { + this.log = log + } + /** + * LIFECYCLE + * ------------------------------------------------------ + */ + connectedCallback() { + this.updateAccordionId() + } + componentWillRender() { + this.updateAccordionId() + } + /** + * GETTERS + * ------------------------------------------------------ + */ + get parentAccordionElement() { + var _a + return ((_a = this.el) === null || _a === void 0 ? void 0 : _a.closest('bal-accordion')) || null + } + get parentAccordionSummaryElement() { + var _a + return ((_a = this.el) === null || _a === void 0 ? void 0 : _a.closest('bal-accordion-summary')) || null + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + const block = BEM.block('accordion').element('trigger') + const id = this.parentAccordionId ? `${this.parentAccordionId}-trigger` : this.componentId + const label = this.active ? this.closeLabel : this.openLabel + let turn = false + let icon = this.active ? this.closeIcon : this.openIcon + if (this.closeIcon === '' || this.closeIcon === undefined || this.closeIcon === null) { + turn = this.active + icon = this.openIcon || 'caret-down' + } + const expanded = + this.state === 4 /* AccordionState.Expanded */ || this.state === 8 /* AccordionState.Expanding */ + const buttonPart = expanded ? 'button expanded' : 'button' + const parentSummaryEl = this.parentAccordionSummaryElement + let triggerAttributes = { + tabindex: -1, + } + if (parentSummaryEl && !parentSummaryEl.trigger) { + triggerAttributes = { + tabindex: 0, + } + } + return hAsync( + Host, + { key: 'af0ac1bbf7cb49a28ad9e481d3cf41f377c3d434', id: id, class: Object.assign({}, block.class()) }, + this.button + ? hAsync( + 'bal-button', + { + 'id': `${id}-button`, + 'aria-controls': `${this.parentAccordionId}-details-content`, + 'part': buttonPart, + 'data-testid': 'bal-accordion-trigger', + 'expanded': true, + 'icon': icon, + 'iconTurn': turn, + 'color': this.color, + 'size': this.size, + 'onClick': this.onClick, + }, + label, + ) + : hAsync( + 'button', + Object.assign( + { + 'class': Object.assign(Object.assign({}, block.element('button').class()), { + 'bal-focused': parentSummaryEl && !parentSummaryEl.trigger, + }), + 'id': `${id}-button`, + 'aria-controls': `${this.parentAccordionId}-details-content`, + 'aria-label': 'accordion trigger', + 'part': buttonPart, + 'data-testid': 'bal-accordion-trigger', + 'onClick': this.onClick, + }, + triggerAttributes, + ), + hAsync('bal-icon', { turn: turn, name: icon }), + ), + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalAccordionTriggerStyle0 + } + static get cmpMeta() { + return { + $flags$: 0, + $tagName$: 'bal-accordion-trigger', + $members$: { + button: [4], + openLabel: [1, 'open-label'], + openIcon: [1, 'open-icon'], + closeLabel: [1, 'close-label'], + closeIcon: [1, 'close-icon'], + color: [1], + size: [1], + active: [1540], + state: [2], + parentAccordionId: [32], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [['active', 'active']], + } + } + } + __decorate( + [ + Logger('bal-accordion-trigger'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + AccordionTrigger.prototype, + 'createLogger', + null, + ) + let accordionTriggerIds = 0 + + class Orientation { + /** + * Is true when the orientation is in portrait mode + */ + get isPortrait() { + if (balBrowser.hasWindow && window.matchMedia) { + return window.matchMedia('(orientation: portrait)').matches + } + return false + } + /** + * Is true when the orientation is in landscape mode + */ + get isLandscape() { + if (balBrowser.hasWindow && window.matchMedia) { + return window.matchMedia('(orientation: landscape)').matches + } + return true + } + toObject() { + return { + landscape: this.isLandscape, + portrait: this.isPortrait, + } + } + } + class BalDevice { + constructor() { + this.orientation = new Orientation() + } + /** + * Is true if it is a native mobile device like a iPhone + */ + get isMobile() { + return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(balBrowser.userAgent) + } + /** + * Is true if the device supports touchscreen + */ + get hasTouchScreen() { + if (balBrowser.hasWindow && balBrowser.hasNavigator) { + return !!('ontouchstart' in window || navigator.msMaxTouchPoints) + } + return false + } + } + const balDevice = new BalDevice() + + const BAL_FOCUSED = 'bal-focused' + const BAL_FOCUSABLE = 'bal-focusable' + const FOCUS_KEYS = [ + 'Tab', + 'ArrowDown', + 'Space', + 'Escape', + ' ', + 'Shift', + 'Enter', + 'ArrowLeft', + 'ArrowRight', + 'ArrowUp', + 'Home', + 'End', + ] + const focusableQueryString = + '[tabindex]:not([tabindex^="-"]), input:not([type=hidden]):not([tabindex^="-"]), textarea:not([tabindex^="-"]), button:not([tabindex^="-"]), select:not([tabindex^="-"]), .bal-focusable:not([tabindex^="-"])' + const startFocusVisible = rootEl => { + let currentFocus = [] + let keyboardMode = true + const ref = rootEl ? rootEl.shadowRoot : document + const root = rootEl ? rootEl : document.body + const setFocus = elements => { + currentFocus.forEach(el => el.classList.remove(BAL_FOCUSED)) + elements.forEach(el => el.classList.add(BAL_FOCUSED)) + currentFocus = elements + } + const pointerDown = () => { + keyboardMode = false + setFocus([]) + } + const onKeydown = ev => { + keyboardMode = FOCUS_KEYS.includes(ev.key) + if (!keyboardMode) { + setFocus([]) + } + } + const onFocusin = ev => { + if (keyboardMode && ev.composedPath !== undefined) { + const toFocus = ev.composedPath().filter(el => { + if (el.classList) { + return el.classList.contains(BAL_FOCUSABLE) + } + return false + }) + setFocus(toFocus) + } + } + const onFocusout = () => { + if (ref.activeElement === root) { + setFocus([]) + } + } + ref.addEventListener('keydown', onKeydown) + ref.addEventListener('focusin', onFocusin) + ref.addEventListener('focusout', onFocusout) + ref.addEventListener('touchstart', pointerDown) + ref.addEventListener('mousedown', pointerDown) + const destroy = () => { + ref.removeEventListener('keydown', onKeydown) + ref.removeEventListener('focusin', onFocusin) + ref.removeEventListener('focusout', onFocusout) + ref.removeEventListener('touchstart', pointerDown) + ref.removeEventListener('mousedown', pointerDown) + } + return { + destroy, + setFocus, + } + } + + const balAppCss = ':root{--bal-app-height:100%}.bal-app{position:relative;display:block}' + var BalAppStyle0 = balAppCss + + class App { + constructor(hostRef) { + registerInstance(this, hostRef) + this.debouncedNotify = debounce$1(() => this.notifyResize(), 100) + this.notifyResize = async () => { + if (balBrowser.hasDocument && balBrowser.hasWindow) { + const doc = document.documentElement + doc.style.setProperty('--bal-app-height', `${window.innerHeight}px`) + } + } + this.animated = true + this.ready = false + } + createLogger(log) { + this.log = log + } + connectedCallback() { + updateBalAnimated(this.animated) + if (balBrowser.hasWindow) { + window.addEventListener('resize', this.debouncedNotify) + this.debouncedNotify() + } + } + componentDidLoad() { + rIC(async () => { + this.ready = true + startFocusVisible() + }) + } + disconnectedCallback() { + if (balBrowser.hasWindow) { + window.removeEventListener('resize', this.debouncedNotify) + } + } + async setFocus(elements) { + if (this.focusVisible) { + this.focusVisible.setFocus(elements) + } + } + render() { + return hAsync( + Host, + { + key: '0b9e41e0d5c4062670a1d3c346d25bffd2384905', + class: { + 'bal-app': true, + 'bal-app--safari': balBrowser.isSafari, + 'bal-app--touch': balDevice.hasTouchScreen, + }, + }, + hAsync('slot', { key: 'f91c9fc88930ac7c0b3114252ddf099b249e39ae' }), + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalAppStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-app', + $members$: { + animated: [516], + ready: [1540], + setFocus: [64], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [ + ['animated', 'animated'], + ['ready', 'ready'], + ], + } + } + } + __decorate( + [ + Logger('bal-app'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + App.prototype, + 'createLogger', + null, + ) + + const balBadgeCss = + ':root{--bal-badge-background:var(--bal-color-red-3);--bal-badge-background-grey:var(--bal-color-grey-3);--bal-badge-background-red:var(--bal-color-red-3);--bal-badge-background-yellow:var(--bal-color-yellow-3);--bal-badge-background-green:var(--bal-color-green-3);--bal-badge-background-purple:var(--bal-color-purple-3);--bal-badge-radius:var(--bal-radius-rounded);--bal-badge-text-color:var(--bal-color-text-primary);--bal-badge-color-grey:var(--bal-color-text-grey-dark);--bal-badge-color-red:var(--bal-color-text-primary);--bal-badge-color-yellow:var(--bal-color-text-primary);--bal-badge-color-green:var(--bal-color-text-primary);--bal-badge-color-purple:var(--bal-color-text-primary)}.bal-badge{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;min-width:1.5rem;height:1.5rem;border-radius:var(--bal-badge-radius);background:var(--bal-badge-background);padding:.25rem}.bal-badge--size-small{width:.75rem;max-width:.75rem;min-width:.75rem;height:.75rem}.bal-badge--size-large{width:2rem;height:2rem}.bal-badge--background-red,.bal-badge--background-danger{background:var(--bal-badge-background-red)}.bal-badge--background-yellow,.bal-badge--background-warning{background:var(--bal-badge-background-yellow)}.bal-badge--background-green,.bal-badge--background-success{background:var(--bal-badge-background-green)}.bal-badge--background-purple{background:var(--bal-badge-background-purple)}.bal-badge--background-grey{background:var(--bal-badge-background-grey)}.bal-badge--position-card,.bal-badge--position-button{position:absolute;right:-0.5rem;top:-0.5rem}.bal-badge--position-tabs{margin-top:-0.25rem;position:absolute;right:-1.625rem}.bal-badge--position-tabs.bal-badge--size-small{right:-1rem}span.bal-badge__label{font-weight:var(--bal-font-weight-bold) !important;font-family:var(--bal-font-family-text) !important;font-size:var(--bal-text-size-small) !important;color:var(--bal-badge-text-color);line-height:1.5rem !important;-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto}span.bal-badge__label--hidden{display:none !important}span.bal-badge__label--color-red,span.bal-badge__label--color-danger{color:var(--bal-badge-color-red)}span.bal-badge__label--color-yellow,span.bal-badge__label--color-warning{color:var(--bal-badge-color-yellow)}span.bal-badge__label--color-green,span.bal-badge__label--color-success{color:var(--bal-badge-color-green)}span.bal-badge__label--color-grey{color:var(--bal-badge-color-grey)}span.bal-badge__label--color-purple{color:var(--bal-badge-color-purple)}.bal-badge__icon--hidden{display:none !important}' + var BalBadgeStyle0 = balBadgeCss + + class Badge { + constructor(hostRef) { + registerInstance(this, hostRef) + this.icon = undefined + this.size = '' + this.color = '' + this.position = '' + } + render() { + const block = BEM.block('badge') + const labelEl = block.element('label') + const iconEl = block.element('icon') + const color = this.color !== '' + const size = this.size !== '' + const position = this.position !== '' + const labelHidden = !!this.icon || this.size === 'small' + return hAsync( + Host, + { + key: '8fefcf48fb5ba2011faf11b6d5dee452080d3344', + class: Object.assign( + Object.assign( + Object.assign( + Object.assign({}, block.class()), + block.modifier(`background-${this.color}`).class(color), + ), + block.modifier(`position-${this.position}`).class(position), + ), + block.modifier(`size-${this.size}`).class(size), + ), + }, + hAsync( + 'span', + { + 'key': '582a5f522dd5c7fff3c373b4e85055d7b203aa20', + 'class': Object.assign( + Object.assign(Object.assign({}, labelEl.class()), labelEl.modifier(`color-${this.color}`).class(color)), + labelEl.modifier(`hidden`).class(labelHidden), + ), + 'data-testid': 'bal-badge-label', + }, + hAsync('slot', { key: 'cb210bd83465da685b87be59d29195f96be0b584' }), + ), + this.size !== 'small' + ? hAsync('bal-icon', { + class: Object.assign(Object.assign({}, iconEl.class()), iconEl.modifier(`hidden`).class(!labelHidden)), + size: this.size === '' ? 'small' : '', + name: this.icon, + color: this.color === 'grey' ? 'grey' : 'primary', + }) + : '', + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalBadgeStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-badge', + $members$: { + icon: [1], + size: [1], + color: [1], + position: [1], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + const trackingAttributes = [ + 'data-tracking-style', + 'data-tracking-topic', + 'data-tracking-context', + 'data-tracking-id', + ] + /** + * Elements inside of web components sometimes need to inherit global attributes + * set on the host. For example, the inner input in `bal-input` should inherit + * the `title` attribute that developers set directly on `bal-input`. This + * helper function should be called in componentWillLoad and assigned to a variable + * that is later used in the render function. + * + * This does not need to be reactive as changing attributes on the host element + * does not trigger a re-render. + */ + const inheritAttributes = (el, attributes = []) => { + const attributeObject = {} + attributes.forEach(attr => { + if (el.hasAttribute(attr)) { + const value = el.getAttribute(attr) + if (value !== null) { + attributeObject[attr] = el.getAttribute(attr) + } + el.removeAttribute(attr) + } + }) + return attributeObject + } + /** + * Returns an array of tracking attributes that should be copied from + * the host element to a target within the component. + * @param el The element that the attributes should be copied from. + * @param ignoreList The list of aria-attributes to ignore reflecting and removing from the host. + * Use this in instances where we manually specify aria attributes on the `` element. + */ + const inheritTrackingAttributes = (el, ignoreList) => { + let attributesToInherit = trackingAttributes + if (ignoreList && ignoreList.length > 0) { + attributesToInherit = attributesToInherit.filter(attr => !ignoreList.includes(attr)) + } + return inheritAttributes(el, attributesToInherit) + } + + const balButtonCss = + 'bal-button,.bal-button{display:inline-block;position:static}bal-button.is-fullwidth,.bal-button.is-fullwidth{width:100%;-ms-flex:1 1 100%;flex:1 1 100%}bal-button[disabled] bal-icon,.bal-button[disabled] bal-icon{pointer-events:none}.bal-button .button-label.has-no-wrap{text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.bal-button-group{display:-ms-flexbox;display:flex}.bal-button-group--position-center{-ms-flex-pack:center;justify-content:center}.bal-button-group--position-left{-ms-flex-pack:start;justify-content:flex-start}.bal-button-group--position-right{-ms-flex-pack:end;justify-content:flex-end}@media screen and (max-width: 768px){.bal-button-group--direction-auto .field.is-grouped,.bal-button-group--direction-auto .bal-button,.bal-button-group--direction-auto .bal-button .button{width:100% !important}}@media screen and (max-width: 768px){.bal-button-group--direction-column .field.is-grouped,.bal-button-group--direction-column .bal-button,.bal-button-group--direction-column .bal-button .button{width:100% !important}}' + var BalButtonStyle0 = balButtonCss + + class Button { + constructor(hostRef) { + registerInstance(this, hostRef) + this.balNavigate = createEvent(this, 'balNavigate', 7) + this.balFocus = createEvent(this, 'balFocus', 7) + this.balBlur = createEvent(this, 'balBlur', 7) + this.balDidRender = createEvent(this, 'balDidRender', 7) + this.inheritAttributes = {} + this.onFocus = () => { + this.balFocus.emit() + } + this.onBlur = () => { + this.balBlur.emit() + } + this.onClick = ev => { + if (this.href !== undefined) { + this.balNavigate.emit(ev) + } + } + this.color = 'primary' + this.elementType = 'button' + this.disabled = false + this.size = '' + this.href = undefined + this.target = '_self' + this.rel = undefined + this.download = undefined + this.shadow = false + this.square = false + this.isActive = false + this.expanded = false + this.flat = false + this.outlined = false + this.inverted = false + this.loading = false + this.rounded = false + this.icon = '' + this.iconTurn = false + this.iconRight = '' + this.noWrap = false + this.name = '' + this.value = '' + this.aria = undefined + } + listenOnClick(ev) { + if (this.disabled && ev.target && ev.target === this.el) { + ev.preventDefault() + ev.stopPropagation() + } + } + componentWillLoad() { + this.inheritAttributes = inheritAttributes(this.el, [ + 'title', + 'aria-label', + 'aria-controls', + 'aria-hidden', + 'tabindex', + ]) + } + componentDidRender() { + this.balDidRender.emit() + } + get isIconInverted() { + return this.inverted + } + get buttonCssClass() { + return { + 'button': true, + [`is-${this.color}`]: true, + 'is-flat': this.flat, + 'is-square': this.square, + 'is-small': this.size === 'small', + 'is-inverted': this.inverted, + 'is-active': this.isActive, + 'is-outlined': this.outlined, + 'is-fullwidth': this.expanded, + 'is-disabled': this.disabled, + 'is-loading': this.loading, + 'is-rounded': this.rounded === true, + 'has-blur-shadow': this.shadow === true, + } + } + get leftIconAttrs() { + if (!this.icon || this.loading) { + return { + style: { display: 'none' }, + } + } + return {} + } + get leftRightAttrs() { + if (!this.iconRight || this.loading) { + return { + style: { display: 'none' }, + } + } + return {} + } + get loadingAttrs() { + if (!this.loading) { + return { + style: { display: 'none' }, + } + } + return { + style: { position: 'absolute' }, + } + } + handleClick(ev) { + if (this.disabled) { + ev.preventDefault() + ev.stopPropagation() + } + } + render() { + var _a, _b, _c, _d + const { elementType, download, href, rel, target, name, value } = this + const TagType = this.href === undefined ? 'button' : 'a' + const attrs = + TagType === 'button' + ? { type: elementType, name, value } + : { + download, + href, + rel, + target, + } + const spinnerColor = () => { + if (this.disabled) { + return 'blue' + } + switch (this.color) { + case 'primary': + case 'success': + case 'warning': + case 'danger': + return this.inverted ? 'blue' : 'white' + default: + return this.inverted ? 'white' : 'blue' + } + } + const ariaAttributes = { + 'title': ((_a = this.aria) === null || _a === void 0 ? void 0 : _a.title) || this.inheritAttributes['title'], + 'aria-label': + ((_b = this.aria) === null || _b === void 0 ? void 0 : _b.label) || + this.inheritAttributes['aria-label'] || + ((_c = this.aria) === null || _c === void 0 ? void 0 : _c.title) || + this.inheritAttributes['title'], + 'aria-controls': + ((_d = this.aria) === null || _d === void 0 ? void 0 : _d.controls) || + this.inheritAttributes['aria-controls'], + } + return hAsync( + Host, + { + onClick: this.handleClick, + class: { + 'bal-button': true, + 'control': true, + 'is-fullwidth': this.expanded, + 'is-disabled': this.disabled, + }, + }, + hAsync( + TagType, + Object.assign( + {}, + attrs, + this.inheritAttributes, + { + 'type': this.elementType, + 'class': this.buttonCssClass, + 'part': 'native', + 'disabled': this.disabled, + 'onFocus': this.onFocus, + 'onBlur': this.onBlur, + 'onClick': this.onClick, + 'aria-disabled': this.disabled ? 'true' : null, + 'data-testid': 'bal-button', + }, + ariaAttributes, + ), + hAsync( + 'bal-spinner', + Object.assign({ color: spinnerColor(), small: true }, this.loadingAttrs, { deactivated: !this.loading }), + ), + hAsync( + 'bal-icon', + Object.assign({}, this.leftIconAttrs, { + class: this.square ? '' : 'icon-left', + name: this.icon, + size: this.square ? this.size : 'small', + turn: this.iconTurn, + inverted: this.isIconInverted, + }), + ), + hAsync( + 'span', + { + 'class': { + 'button-label': true, + 'has-no-wrap': this.noWrap, + 'is-small': this.size === 'small', + }, + 'style': { opacity: this.loading ? '0' : '1' }, + 'data-testid': 'bal-button-label', + }, + hAsync('slot', null), + ), + hAsync( + 'bal-icon', + Object.assign({}, this.leftRightAttrs, { + class: 'icon-right', + name: this.iconRight, + size: 'small', + turn: this.iconTurn, + inverted: this.isIconInverted, + }), + ), + ), + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalButtonStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-button', + $members$: { + color: [1], + elementType: [1, 'element-type'], + disabled: [516], + size: [513], + href: [1], + target: [1], + rel: [1], + download: [1], + shadow: [4], + square: [4], + isActive: [4, 'is-active'], + expanded: [4], + flat: [4], + outlined: [4], + inverted: [4], + loading: [4], + rounded: [4], + icon: [1], + iconTurn: [4, 'icon-turn'], + iconRight: [1, 'icon-right'], + noWrap: [4, 'no-wrap'], + name: [1], + value: [8], + aria: [16], + }, + $listeners$: [[6, 'click', 'listenOnClick']], + $lazyBundleId$: '-', + $attrsToReflect$: [ + ['disabled', 'disabled'], + ['size', 'size'], + ], + } + } + } + + class ButtonGroup { + constructor(hostRef) { + registerInstance(this, hostRef) + this.position = '' + this.direction = 'auto' + this.reverse = false + } + render() { + const block = BEM.block('button-group') + return hAsync( + Host, + { + key: '37a0df1c1011b201337d3a3838131fd4eec4ad52', + class: Object.assign( + Object.assign(Object.assign({}, block.class()), block.modifier(`position-${this.position}`).class()), + block.modifier(`direction-${this.direction}`).class(), + ), + }, + hAsync( + 'div', + { + key: 'fc6667209c1ce56dee220bca313c1b894e49be62', + class: { + 'field': true, + 'is-grouped': true, + 'is-reverse': this.reverse, + [`has-direction-${this.direction}`]: true, + }, + }, + hAsync('slot', { key: '8187edbafa351fc0b57178bd826dd4d36fc56721' }), + ), + ) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-button-group', + $members$: { + position: [1], + direction: [1], + reverse: [4], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + var lodash_isempty = { exports: {} } + + /** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + + ;(function (module, exports) { + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991 + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + setTag = '[object Set]', + weakMapTag = '[object WeakMap]' + + var dataViewTag = '[object DataView]' + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/ + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = + typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')() + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key] + } + + /** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ + function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + '') + } catch (e) {} + } + return result + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function (arg) { + return func(transform(arg)) + } + } + + /** Used for built-in method references. */ + var funcProto = Function.prototype, + objectProto = Object.prototype + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__'] + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function () { + var uid = /[^.]+$/.exec((coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO) || '') + return uid ? 'Symbol(src)_1.' + uid : '' + })() + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString + + /** Used to detect if a method is native. */ + var reIsNative = RegExp( + '^' + + funcToString + .call(hasOwnProperty) + .replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + + '$', + ) + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined, + propertyIsEnumerable = objectProto.propertyIsEnumerable + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object) + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap') + + /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */ + var nonEnumShadows = !propertyIsEnumerable.call({ valueOf: 1 }, 'valueOf') + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap) + + /** + * The base implementation of `getTag`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + return objectToString.call(value) + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false + } + var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor + return pattern.test(toSource(value)) + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key) + return baseIsNative(value) ? value : undefined + } + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag + + // Fallback for data views, maps, sets, and weak maps in IE 11, + // for data views in Edge < 14, and promises in Node.js. + if ( + (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map()) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set()) != setTag) || + (WeakMap && getTag(new WeakMap()) != weakMapTag) + ) { + getTag = function (value) { + var result = objectToString.call(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : undefined + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag + case mapCtorString: + return mapTag + case promiseCtorString: + return promiseTag + case setCtorString: + return setTag + case weakMapCtorString: + return weakMapTag + } + } + return result + } + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func + } + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto + + return value === proto + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func) + } catch (e) {} + try { + return func + '' + } catch (e) {} + } + return '' + } + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return ( + isArrayLikeObject(value) && + hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag) + ) + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value) + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value) + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if ( + isArrayLike(value) && + (isArray(value) || + typeof value == 'string' || + typeof value.splice == 'function' || + isBuffer(value) || + isArguments(value)) + ) { + return !value.length + } + var tag = getTag(value) + if (tag == mapTag || tag == setTag) { + return !value.size + } + if (nonEnumShadows || isPrototype(value)) { + return !nativeKeys(value).length + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false + } + } + return true + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : '' + return tag == funcTag || tag == genTag + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value + return !!value && (type == 'object' || type == 'function') + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return !!value && typeof value == 'object' + } + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false + } + + module.exports = isEmpty + })(lodash_isempty, lodash_isempty.exports) + + var isEmpty = lodash_isempty.exports + + const balCardCss = + ':root{--bal-card-background:transparent;--bal-card-background-white:var(--bal-color-white);--bal-card-background-blue:var(--bal-color-primary);--bal-card-background-primary:var(--bal-color-primary);--bal-card-background-info:var(--bal-color-primary);--bal-card-background-success:var(--bal-color-success-2);--bal-card-background-warning:var(--bal-color-warning-2);--bal-card-background-danger:var(--bal-color-danger-2);--bal-card-background-grey:var(--bal-color-grey);--bal-card-background-red:var(--bal-color-red);--bal-card-background-yellow:var(--bal-color-yellow);--bal-card-background-purple:var(--bal-color-purple);--bal-card-background-green:var(--bal-color-green);--bal-card-background-red-light:var(--bal-color-red-1);--bal-card-background-yellow-light:var(--bal-color-yellow-1);--bal-card-background-purple-light:var(--bal-color-purple-1);--bal-card-background-green-light:var(--bal-color-green-1);--bal-card-background-grey-light:var(--bal-color-grey-1);--bal-card-background-purple-1:var(--bal-color-purple-1);--bal-card-background-purple-2:var(--bal-color-purple-2);--bal-card-background-purple-3:var(--bal-color-purple);--bal-card-background-green-1:var(--bal-color-green-1);--bal-card-background-green-2:var(--bal-color-green-2);--bal-card-background-green-3:var(--bal-color-green);--bal-card-background-red-1:var(--bal-color-red-1);--bal-card-background-red-2:var(--bal-color-red-2);--bal-card-background-red-3:var(--bal-color-red);--bal-card-background-yellow-1:var(--bal-color-yellow-1);--bal-card-background-yellow-2:var(--bal-color-yellow-2);--bal-card-background-yellow-3:var(--bal-color-yellow);--bal-card-selected-background:var(--bal-color-primary-2);--bal-card-radius:var(--bal-radius-large);--bal-card-square-radius:0;--bal-card-border:var(--bal-border-width-normal) dashed var(--bal-color-grey)}.bal-card{position:relative;display:block;background:var(--bal-card-background);-webkit-box-shadow:var(--bal-shadow-normal);box-shadow:var(--bal-shadow-normal);border-radius:var(--bal-card-radius)}.bal-card--is-white{background:var(--bal-card-background-white)}.bal-card--is-blue{background:var(--bal-card-background-blue)}.bal-card--is-primary{background:var(--bal-card-background-primary)}.bal-card--is-info{background:var(--bal-card-background-info)}.bal-card--is-success{background:var(--bal-card-background-success)}.bal-card--is-warning{background:var(--bal-card-background-warning)}.bal-card--is-danger{background:var(--bal-card-background-danger)}.bal-card--is-grey{background:var(--bal-card-background-grey)}.bal-card--is-red{background:var(--bal-card-background-red)}.bal-card--is-yellow{background:var(--bal-card-background-yellow)}.bal-card--is-purple{background:var(--bal-card-background-purple)}.bal-card--is-green{background:var(--bal-card-background-green)}.bal-card--is-red-light{background:var(--bal-card-background-red-light)}.bal-card--is-yellow-light{background:var(--bal-card-background-yellow-light)}.bal-card--is-purple-light{background:var(--bal-card-background-purple-light)}.bal-card--is-green-light{background:var(--bal-card-background-green-light)}.bal-card--is-grey-light{background:var(--bal-card-background-grey-light)}.bal-card--is-purple-1{background:var(--bal-card-background-purple-1)}.bal-card--is-purple-2{background:var(--bal-card-background-purple-2)}.bal-card--is-purple-3{background:var(--bal-card-background-purple-3)}.bal-card--is-green-1{background:var(--bal-card-background-green-1)}.bal-card--is-green-2{background:var(--bal-card-background-green-2)}.bal-card--is-green-3{background:var(--bal-card-background-green-3)}.bal-card--is-red-1{background:var(--bal-card-background-red-1)}.bal-card--is-red-2{background:var(--bal-card-background-red-2)}.bal-card--is-red-3{background:var(--bal-card-background-red-3)}.bal-card--is-yellow-1{background:var(--bal-card-background-yellow-1)}.bal-card--is-yellow-2{background:var(--bal-card-background-yellow-2)}.bal-card--is-yellow-3{background:var(--bal-card-background-yellow-3)}.bal-card--has-fullheight,.bal-card--has-fullheight .bal-card-content,.bal-card--has-fullheight .bal-card-content>.is-flex{height:100%}.bal-card--has-border{border:var(--bal-card-border)}.bal-card--is-flat{-webkit-box-shadow:none;box-shadow:none}.bal-card--is-square{border-radius:var(--bal-card-square-radius)}.bal-card--is-selected{background:var(--bal-card-selected-background)}.bal-card--is-clickable{cursor:pointer;-webkit-transition:-webkit-transform .15s ease-in-out;transition:-webkit-transform .15s ease-in-out;transition:transform .15s ease-in-out;transition:transform .15s ease-in-out, -webkit-transform .15s ease-in-out}.bal-card--is-clickable:active,.bal-card--is-clickable:hover{-webkit-box-shadow:var(--bal-shadow-large);box-shadow:var(--bal-shadow-large);-webkit-transform:translate3d(0, -2px, 0);transform:translate3d(0, -2px, 0)}.bal-card>:not(bal-badge):not(bal-tag):first-child{padding-top:1rem}.bal-card>:not(bal-badge):not(bal-tag):last-child{padding-bottom:1rem}.bal-card>bal-badge+bal-card-title,.bal-card>bal-badge+bal-card-content,.bal-card>bal-tag+bal-card-title,.bal-card>bal-tag+bal-card-content,.bal-card>bal-card-title+bal-card-content,.bal-card>bal-card-subtitle+bal-card-content,.bal-card>bal-card-actions,.bal-card>bal-card-button{padding-top:1rem}.bal-card>.bal-accordion--card-v1{padding-bottom:0 !important}.bal-card bal-card-title,.bal-card bal-card-subtitle,.bal-card bal-card-content,.bal-card bal-card-actions,.bal-card bal-card-button{padding-left:1rem;padding-right:1rem}@media screen and (min-width: 769px),print{.bal-card>:not(bal-badge):not(bal-tag):first-child{padding-top:1.5rem}.bal-card>:not(bal-badge):not(bal-tag):last-child{padding-bottom:1.5rem}.bal-card>bal-badge+bal-card-title,.bal-card>bal-badge+bal-card-content,.bal-card>bal-tag+bal-card-title,.bal-card>bal-tag+bal-card-content,.bal-card>bal-card-title+bal-card-content,.bal-card>bal-card-subtitle+bal-card-content,.bal-card>bal-card-actions,.bal-card>bal-card-button{padding-top:1.5rem}.bal-card>.bal-accordion--card-v1{padding-bottom:0 !important}.bal-card bal-card-title,.bal-card bal-card-subtitle,.bal-card bal-card-content,.bal-card bal-card-actions,.bal-card bal-card-button{padding-left:1.5rem;padding-right:1.5rem}}@media screen and (min-width: 769px),print{.bal-card--is-small>:not(bal-badge):not(bal-tag):first-child{padding-top:1rem}.bal-card--is-small>:not(bal-badge):not(bal-tag):last-child{padding-bottom:1rem}.bal-card--is-small>bal-badge+bal-card-title,.bal-card--is-small>bal-badge+bal-card-content,.bal-card--is-small>bal-tag+bal-card-title,.bal-card--is-small>bal-tag+bal-card-content,.bal-card--is-small>bal-card-title+bal-card-content,.bal-card--is-small>bal-card-subtitle+bal-card-content,.bal-card--is-small>bal-card-actions,.bal-card--is-small>bal-card-button{padding-top:1rem}.bal-card--is-small>.bal-accordion--card-v1{padding-bottom:0 !important}.bal-card--is-small bal-card-title,.bal-card--is-small bal-card-subtitle,.bal-card--is-small bal-card-content,.bal-card--is-small bal-card-actions,.bal-card--is-small bal-card-button{padding-left:1rem;padding-right:1rem}}@media screen and (min-width: 769px),print{.bal-card--is-medium>:not(bal-badge):not(bal-tag):first-child{padding-top:1.5rem}.bal-card--is-medium>:not(bal-badge):not(bal-tag):last-child{padding-bottom:1.5rem}.bal-card--is-medium>bal-badge+bal-card-title,.bal-card--is-medium>bal-badge+bal-card-content,.bal-card--is-medium>bal-tag+bal-card-title,.bal-card--is-medium>bal-tag+bal-card-content,.bal-card--is-medium>bal-card-title+bal-card-content,.bal-card--is-medium>bal-card-subtitle+bal-card-content,.bal-card--is-medium>bal-card-actions,.bal-card--is-medium>bal-card-button{padding-top:1.5rem}.bal-card--is-medium>.bal-accordion--card-v1{padding-bottom:0 !important}.bal-card--is-medium bal-card-title,.bal-card--is-medium bal-card-subtitle,.bal-card--is-medium bal-card-content,.bal-card--is-medium bal-card-actions,.bal-card--is-medium bal-card-button{padding-left:1.5rem;padding-right:1.5rem}}@media screen and (min-width: 1024px){.bal-card--is-medium>:not(bal-badge):not(bal-tag):first-child{padding-top:2rem}.bal-card--is-medium>:not(bal-badge):not(bal-tag):last-child{padding-bottom:2rem}.bal-card--is-medium>bal-badge+bal-card-title,.bal-card--is-medium>bal-badge+bal-card-content,.bal-card--is-medium>bal-tag+bal-card-title,.bal-card--is-medium>bal-tag+bal-card-content,.bal-card--is-medium>bal-card-title+bal-card-content,.bal-card--is-medium>bal-card-subtitle+bal-card-content,.bal-card--is-medium>bal-card-actions,.bal-card--is-medium>bal-card-button{padding-top:2rem}.bal-card--is-medium>.bal-accordion--card-v1{padding-bottom:0 !important}.bal-card--is-medium bal-card-title,.bal-card--is-medium bal-card-subtitle,.bal-card--is-medium bal-card-content,.bal-card--is-medium bal-card-actions,.bal-card--is-medium bal-card-button{padding-left:2rem;padding-right:2rem}}@media screen and (min-width: 769px),print{.bal-card--is-large>:not(bal-badge):not(bal-tag):first-child{padding-top:2rem}.bal-card--is-large>:not(bal-badge):not(bal-tag):last-child{padding-bottom:2rem}.bal-card--is-large>bal-badge+bal-card-title,.bal-card--is-large>bal-badge+bal-card-content,.bal-card--is-large>bal-tag+bal-card-title,.bal-card--is-large>bal-tag+bal-card-content,.bal-card--is-large>bal-card-title+bal-card-content,.bal-card--is-large>bal-card-subtitle+bal-card-content,.bal-card--is-large>bal-card-actions,.bal-card--is-large>bal-card-button{padding-top:2rem}.bal-card--is-large>.bal-accordion--card-v1{padding-bottom:0 !important}.bal-card--is-large bal-card-title,.bal-card--is-large bal-card-subtitle,.bal-card--is-large bal-card-content,.bal-card--is-large bal-card-actions,.bal-card--is-large bal-card-button{padding-left:2rem;padding-right:2rem}}@media screen and (min-width: 1024px){.bal-card--is-large>:not(bal-badge):not(bal-tag):first-child{padding-top:4rem}.bal-card--is-large>:not(bal-badge):not(bal-tag):last-child{padding-bottom:4rem}.bal-card--is-large>bal-badge+bal-card-title,.bal-card--is-large>bal-badge+bal-card-content,.bal-card--is-large>bal-tag+bal-card-title,.bal-card--is-large>bal-tag+bal-card-content,.bal-card--is-large>bal-card-title+bal-card-content,.bal-card--is-large>bal-card-subtitle+bal-card-content,.bal-card--is-large>bal-card-actions,.bal-card--is-large>bal-card-button{padding-top:4rem}.bal-card--is-large>.bal-accordion--card-v1{padding-bottom:0 !important}.bal-card--is-large bal-card-title,.bal-card--is-large bal-card-subtitle,.bal-card--is-large bal-card-content,.bal-card--is-large bal-card-actions,.bal-card--is-large bal-card-button{padding-left:4rem;padding-right:4rem}}.bal-card>.bal-tag{position:absolute;left:1rem;top:-1rem}@media screen and (min-width: 1024px){.bal-card>.bal-tag{left:1.5rem}}.bal-card>.bal-tag--is-left{left:1rem}@media screen and (min-width: 1024px){.bal-card>.bal-tag--is-left{left:1.5rem}}.bal-card>.bal-tag--is-center{left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}@media screen and (min-width: 1024px){.bal-card>.bal-tag--is-center{left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}}.bal-card-title{display:block;position:static}.bal-card-title .title .bal-tag-group,.bal-card-title .title .bal-button-group,.bal-card-title .bal-heading__text .bal-tag-group,.bal-card-title .bal-heading__text .bal-button-group{margin-top:.5rem}@media screen and (min-width: 769px),print{.bal-card-title .bal-heading h3{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.bal-card-title .title,.bal-card-title .bal-heading__text{display:-ms-flexbox;display:flex}.bal-card-title .title .bal-tag-group,.bal-card-title .title .bal-button-group,.bal-card-title .bal-heading__text .bal-tag-group,.bal-card-title .bal-heading__text .bal-button-group{margin-top:0;margin-left:.5rem;display:-ms-inline-flexbox;display:inline-flex}.bal-card-title .title .bal-tag-group .bal-tag,.bal-card-title .bal-heading__text .bal-tag-group .bal-tag{margin-top:.125rem}.bal-card-title .title .bal-button-group,.bal-card-title .bal-heading__text .bal-button-group{-ms-flex:1;flex:1}}.bal-card-subtitle{display:block;position:static}.bal-card-content{display:block;position:static;word-break:break-word;text-align:left;font-family:var(--bal-font-family-text);font-size:var(--bal-text-size-normal);line-height:var(--bal-line-height-normal);-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto}.bal-card-actions{display:block;position:static}.bal-card-button{display:block;position:static}.column bal-card.has-height-auto,.column bal-card.has-height-auto bal-card-content,.column bal-card.has-height-auto bal-card-content>.is-flex{height:100%}' + var BalCardStyle0 = balCardCss + + class Card { + constructor(hostRef) { + registerInstance(this, hostRef) + this.border = false + this.flat = false + this.square = false + this.inverted = false + this.clickable = false + this.selected = false + this.fullheight = false + this.space = '' + this.color = 'white' + } + get colorTypeClass() { + return isEmpty(this.color) ? '' : `is-${this.inverted ? 'blue' : this.color}` + } + render() { + return hAsync( + Host, + { + key: '7bc59c101e875eedda1f209d3eb2442ac00b4df5', + class: { + 'bal-card': true, + [`bal-card--${this.colorTypeClass}`]: !isEmpty(this.color), + [`bal-card--is-${this.space}`]: this.space !== '', + 'bal-card--has-border': this.border, + 'bal-card--is-flat': this.flat, + 'bal-card--is-clickable': this.clickable, + 'bal-card--is-selected': this.selected, + 'bal-card--is-square': this.square, + 'bal-card--has-fullheight': this.fullheight, + }, + }, + hAsync('slot', { key: '577a43d779ac88042185e9bf5d3eb61f663cebad' }), + ) + } + static get style() { + return BalCardStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-card', + $members$: { + border: [4], + flat: [4], + square: [4], + inverted: [4], + clickable: [4], + selected: [4], + fullheight: [4], + space: [1], + color: [1], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + class CardActions { + constructor(hostRef) { + registerInstance(this, hostRef) + this.position = '' + } + render() { + return hAsync( + Host, + { key: '78f85e69ecf9184127533a57f8fb53793bf7f49e', class: 'bal-card-actions' }, + hAsync( + 'bal-button-group', + { key: 'bee1def05a211bffb60f76b69a32cbd9e6d1a536', class: 'm-none', position: this.position }, + hAsync('slot', { key: 'd62d486907ed3ef8bcd888464a0ddb32f2dfdcd3' }), + ), + ) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-card-actions', + $members$: { + position: [1], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + class CardButton { + constructor(hostRef) { + registerInstance(this, hostRef) + this.icon = '' + this.elementType = 'button' + this.disabled = false + this.href = undefined + this.target = '_self' + this.iconRight = '' + this.loading = false + } + render() { + return hAsync( + Host, + { key: 'a9a6233b6262d6160868017fd254d5a6ad2612ae', class: 'bal-card-button' }, + hAsync( + 'bal-button', + { + 'key': 'b7a5317e53b75f8d8bb4bbb8dd6ef56325c6676b', + 'color': 'info', + 'expanded': true, + 'bottom-rounded': true, + 'icon': this.icon, + 'iconRight': this.iconRight, + 'elementType': this.elementType, + 'disabled': this.disabled, + 'href': this.href, + 'target': this.target, + 'loading': this.loading, + }, + hAsync('slot', { key: '9461aa5ace6d22d8c7dd6eff5495dfc4e3232506' }), + ), + ) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-card-button', + $members$: { + icon: [1], + elementType: [1, 'element-type'], + disabled: [516], + href: [1], + target: [1], + iconRight: [1, 'icon-right'], + loading: [4], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [['disabled', 'disabled']], + } + } + } + + class CardContent { + constructor(hostRef) { + registerInstance(this, hostRef) + } + render() { + return hAsync( + Host, + { key: '3d9b2511b8743f33efeb25ae05691964b938cbcc', class: 'bal-card-content' }, + hAsync('slot', { key: '2085fa6085da72981d7a5fb86eca8979b8d84076' }), + ) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-card-content', + $members$: undefined, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + class CardSubtitle { + constructor(hostRef) { + registerInstance(this, hostRef) + this.inverted = false + this.bold = false + this.color = '' + } + render() { + return hAsync( + Host, + { key: '3c1cf2160f9cca6e5d9b2ce60069a23bedcb590a', class: 'bal-card-subtitle' }, + hAsync( + 'bal-text', + { + key: '22fab503a09f822fe30a6e06340312c3c080b6a4', + bold: this.bold, + space: 'none', + color: this.inverted ? 'white' : this.color, + }, + hAsync('slot', { key: 'bb28c8fcbfec3ba10184721940a453b22b2b8865' }), + ), + ) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-card-subtitle', + $members$: { + inverted: [4], + bold: [4], + color: [1], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + class CardTitle { + constructor(hostRef) { + registerInstance(this, hostRef) + this.inverted = false + } + render() { + return hAsync( + Host, + { key: '7e5021e2cf281b237676f401ca3109a6988b8edc', class: 'bal-card-title' }, + hAsync( + 'bal-heading', + { key: 'b1a0badb897ba81b3fc25367cdd2155ee5bb7b43', level: 'h3', space: 'none', inverted: this.inverted }, + hAsync('slot', { key: '8765c2c2485f4f1a885278070328136ec1402b1a' }), + ), + ) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-card-title', + $members$: { + inverted: [4], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + const TabControl = ({ value, items, containerId, onControlChange }) => { + const block = BEM.block('carousel') + const controls = block.element('controls') + return hAsync( + 'div', + { class: Object.assign(Object.assign({}, controls.class()), controls.modifier('tabs').class()) }, + hAsync( + 'bal-card', + null, + hAsync( + 'bal-card-content', + null, + items.map(item => + hAsync( + 'bal-button', + { + 'aria-controls': containerId, + 'key': item.value, + 'expanded': true, + 'color': value === item.value ? 'primary' : 'light', + 'onClick': () => onControlChange(item), + }, + item.label, + ), + ), + ), + ), + ) + } + + const DotControl = ({ value, items, containerId, onControlChange }) => { + const block = BEM.block('carousel') + const controls = block.element('controls') + const onChange = ev => { + let selectedValue = ev.detail - 1 + if (selectedValue < 0) { + selectedValue = 0 + } + if (selectedValue >= items.length) { + selectedValue = items.length - 1 + } + onControlChange(items[selectedValue]) + } + return hAsync( + 'div', + { class: Object.assign(Object.assign({}, controls.class()), controls.modifier('tabs').class()) }, + hAsync('bal-pagination', { + 'aria-controls': containerId, + 'interface': 'small', + 'value': value + 1, + 'totalPages': items.length, + 'onBalChange': onChange, + }), + ) + } + + const LargeControl = ({ + isFirst, + isLast, + inverted, + areControlsHidden, + onNextClick, + onPreviousClick, + containerId, + leftControlTitle, + rightControlTitle, + }) => { + const block = BEM.block('carousel') + const controls = block.element('controls') + const button = controls.element('button') + return hAsync( + 'div', + { + 'data-mutation': 'false', + 'class': Object.assign(Object.assign({}, controls.class()), controls.modifier('large').class()), + }, + hAsync('bal-button', { + 'class': Object.assign( + Object.assign(Object.assign({}, button.class()), button.modifier('left').class()), + button.modifier('hidden').class(isFirst && areControlsHidden), + ), + 'aria-controls': containerId, + 'square': true, + 'icon': 'nav-go-left', + 'rounded': true, + 'inverted': inverted, + 'onClick': () => onPreviousClick(), + 'disabled': isFirst, + 'aria-hidden': isFirst && areControlsHidden ? 'true' : null, + 'data-testid': 'bal-carousel-control-left', + 'title': leftControlTitle, + }), + hAsync('bal-button', { + 'class': Object.assign( + Object.assign(Object.assign({}, button.class()), button.modifier('right').class()), + button.modifier('hidden').class(isLast && areControlsHidden), + ), + 'aria-controls': containerId, + 'square': true, + 'icon': 'nav-go-right', + 'rounded': true, + 'inverted': inverted, + 'onClick': () => onNextClick(), + 'disabled': isLast, + 'aria-hidden': isLast && areControlsHidden ? 'true' : null, + 'data-testid': 'bal-carousel-control-right', + 'title': rightControlTitle, + }), + ) + } + + const SmallControl = ({ + isFirst, + isLast, + inverted, + leftControlTitle, + rightControlTitle, + containerId, + onNextClick, + onPreviousClick, + }) => { + const block = BEM.block('carousel') + const controls = block.element('controls') + const button = controls.element('button') + return hAsync( + 'div', + { class: Object.assign(Object.assign({}, controls.class()), controls.modifier('small').class()) }, + hAsync('bal-button', { + 'class': Object.assign( + Object.assign(Object.assign({}, button.class()), button.modifier('left').class()), + button.modifier('hidden').class(isFirst), + ), + 'aria-controls': containerId, + 'square': true, + 'size': 'small', + 'icon': 'nav-go-left', + 'rounded': true, + 'inverted': inverted, + 'onClick': () => onPreviousClick(), + 'disabled': isFirst, + 'aria-hidden': isFirst ? 'true' : null, + 'tabindex': '-1', + 'data-testid': 'bal-carousel-control-left', + 'title': leftControlTitle, + }), + hAsync('bal-button', { + 'class': Object.assign( + Object.assign(Object.assign({}, button.class()), button.modifier('right').class()), + button.modifier('hidden').class(isLast), + ), + 'aria-controls': containerId, + 'square': true, + 'size': 'small', + 'icon': 'nav-go-right', + 'rounded': true, + 'inverted': inverted, + 'onClick': () => onNextClick(), + 'disabled': isLast, + 'aria-hidden': isLast ? 'true' : null, + 'tabindex': '-1', + 'data-testid': 'bal-carousel-control-right', + 'title': rightControlTitle, + }), + ) + } + + class BalWindowResizeHandler { + constructor(options = {}) { + this.previousWidth = balBrowser.window.width + this.previousHeight = balBrowser.window.height + this.previousIsLandscape = this.isLandscape + this.options = { + onlyListenToWidthChanges: false, + } + this.options = Object.assign(Object.assign({}, this.options), options) + } + async hasResized() { + if (balDevice.hasTouchScreen) { + if (!this.sameWidth || this.previousIsLandscape !== this.isLandscape) { + this.resetPreviousValues() + return true + } + } else { + if (this.options.onlyListenToWidthChanges) { + if (!this.sameWidth) { + this.resetPreviousValues() + return true + } + } else { + if (!this.sameWidth || !this.sameHeight) { + this.resetPreviousValues() + return true + } + } + } + return false + } + get isLandscape() { + return balBrowser.window.width > balBrowser.window.height + } + get sameWidth() { + return this.previousWidth === balBrowser.window.width + } + get sameHeight() { + return this.previousHeight === balBrowser.window.height + } + resetPreviousValues() { + this.previousWidth = balBrowser.window.width + this.previousHeight = balBrowser.window.height + this.previousIsLandscape = this.isLandscape + } + } + + class Subject { + constructor(notifyCallback) { + this.notifyCallback = notifyCallback + this.observers = [] + } + attach(observer) { + const isExist = this.observers.includes(observer) + if (isExist) { + return console.log('Subject: Observer has been attached already.') + } + this.observers.push(observer) + } + detach(observer) { + const observerIndex = this.observers.indexOf(observer) + if (observerIndex === -1) { + return console.log('Subject: Nonexistent observer.') + } + this.observers.splice(observerIndex, 1) + } + notify(data) { + for (const observer of this.observers) { + if (typeof observer === 'function') { + observer(data) + } else { + if (this.notifyCallback) { + this.notifyCallback(observer, data) + } + } + } + } + } + class SingleSubject { + constructor(notifyCallback) { + this.notifyCallback = notifyCallback + } + attach(observer) { + this.observer = observer + } + detach() { + this.observer = undefined + } + notify(data) { + if (this.observer) { + if (typeof this.observer === 'function') { + this.observer(data) + } else { + if (this.notifyCallback) { + this.notifyCallback(this.observer, data) + } + } + } + } + } + + class ListenerAbstract extends Subject { + constructor() { + super(...arguments) + this.el = undefined + } + connect(el) { + if (el) { + this.el = el + } else { + if (balBrowser.hasWindow) { + this.el = window + } + } + } + disconnect() { + this.el = undefined + } + add(listener) { + super.attach(listener) + } + remove(listener) { + super.detach(listener) + } + } + + class BalWindowResizeListener extends ListenerAbstract { + constructor() { + super(...arguments) + this.resizeHandler = new BalWindowResizeHandler({ onlyListenToWidthChanges: true }) + this.debouncedNotify = debounce$1(() => this.notify(), 10) + this.notify = async () => { + if (await this.resizeHandler.hasResized()) { + super.notify(undefined) + } + } + } + connect() { + super.connect() + if (this.el) { + addEventListener(this.el, 'resize', this.debouncedNotify, { passive: true }) + } + } + disconnect() { + super.disconnect() + if (this.el) { + removeEventListener(this.el, 'resize', this.debouncedNotify) + } + } + } + + /** + * Do not edit directly + * Generated on Fri, 13 Sep 2024 12:05:13 GMT + */ + const balColorGreen3 = '#94e3d4' + const balColorGreen6 = '#1b5951' + const balColorPurple3 = '#b8b2ff' + const balColorPurple6 = '#6c2273' + const balColorYellow3 = '#fae052' + const balColorYellow5 = '#fa9319' + const balColorRed3 = '#ffaca6' + const balColorRed5 = '#d9304c' + const balColorGrey4 = '#b6b6b6' + const balBreakpointTablet = '769px' // Tailored for tablet devices, this breakpoint ensures a seamless and optimized user experience on medium-sized screens. + const balBreakpointDesktop = '1024px' // Optimized for desktop screens, this breakpoint provides a spacious canvas for your design, allowing for more intricate layouts and detailed content presentation. + const balBreakpointHighDefinition = '1280px' // Designed for high-definition displays, this breakpoint elevates your interface to a level of visual richness and clarity. + const balBreakpointWidescreen = '1440px' // Tailored for widescreen monitors, this breakpoint offers a panoramic view that accommodates expansive content layouts. + const balBreakpointFullhd$1 = '1920px' // Crafted for Full HD displays, this breakpoint strikes a balance between detail and performance. + + const toNumber$1 = pixel => parseInt(pixel.slice(0, -2), 10) + const breakpointTablet = toNumber$1(balBreakpointTablet) + const breakpointDesktop = toNumber$1(balBreakpointDesktop) + const breakpointHighDefinition = toNumber$1(balBreakpointHighDefinition) + const breakpointWidescreen = toNumber$1(balBreakpointWidescreen) + const balBreakpointFullhd = toNumber$1(balBreakpointFullhd$1) + const isMobile = win => { + const width = win.innerWidth + return width < breakpointTablet + } + const isTablet = win => { + const width = win.innerWidth + return width >= breakpointTablet && width < breakpointDesktop + } + const isTouch = win => isMobile(win) || isTablet(win) + const isDesktop = win => !isTouch(win) + const isHighDefinition = win => { + const width = win.innerWidth + return width >= breakpointHighDefinition && width < breakpointWidescreen + } + const isWideScreen = win => { + const width = win.innerWidth + return width >= breakpointWidescreen && width < balBreakpointFullhd + } + const isFullHD = win => { + const width = win.innerWidth + return width >= balBreakpointFullhd + } + const BREAKPOINTS_MAP = { + mobile: isMobile, + tablet: isTablet, + touch: isTouch, + desktop: isDesktop, + highDefinition: isHighDefinition, + widescreen: isWideScreen, + fullhd: isFullHD, + } + + class BalBreakpointsUtil { + constructor() { + this.breakpoints = [] + if (balBrowser.hasWindow) { + this.win = window + this.win.BaloiseDesignSystem = this.win.BaloiseDesignSystem || {} + this.detect() + } + } + /** + * Is true when mobile breakpoint is active + */ + get isMobile() { + return this.includes('mobile') + } + /** + * Is true when tablet breakpoint is active + */ + get isTablet() { + return this.includes('tablet') + } + /** + * Is true when mobile or tablet breakpoint is active + */ + get isTouch() { + return this.includes('touch') + } + /** + * Is true when desktop, highDefinition, widescreen or fullhd breakpoint is active + */ + get isDesktop() { + return this.includes('desktop') + } + /** + * Is true when highDefinition breakpoint is active + */ + get isHighDefinition() { + return this.includes('highDefinition') + } + /** + * Is true when widescreen breakpoint is active + */ + get isWidescreen() { + return this.includes('widescreen') + } + /** + * Is true when fullhd breakpoint is active + */ + get isFullHD() { + return this.includes('fullhd') + } + /** + * Verifies if given breakpoint is active + * @param breakpoint + * @returns boolean: True if breakpoint is active + */ + includes(breakpoint) { + var _a + this.detect() + return !!((_a = this.breakpoints) === null || _a === void 0 ? void 0 : _a.includes(breakpoint)) + } + /** + * Detects breakpoints and updates state + * @returns breakpoints: list of breakpoints which are active + */ + detect() { + if (this.win) { + this.breakpoints = Object.keys(BREAKPOINTS_MAP).filter(p => BREAKPOINTS_MAP[p](this.win)) + this.win.BaloiseDesignSystem.breakpoints = this.breakpoints + this.win.BaloiseDesignSystem.platforms = this.breakpoints + } + return this.breakpoints + } + /** + * Turns the breakpoints array to a object. + * @returns Object with all the breakpoints + */ + toObject() { + return { + mobile: this.breakpoints.includes('mobile'), + tablet: this.breakpoints.includes('tablet'), + touch: this.breakpoints.includes('touch'), + desktop: this.breakpoints.includes('desktop'), + highDefinition: this.breakpoints.includes('highDefinition'), + widescreen: this.breakpoints.includes('widescreen'), + fullhd: this.breakpoints.includes('fullhd'), + } + } + } + const balBreakpoints = /*@__PURE__*/ new BalBreakpointsUtil() + + const initialBreakpoints = { + mobile: false, + tablet: false, + touch: false, + desktop: false, + highDefinition: false, + widescreen: false, + fullhd: false, + } + + class BalBreakpointSubject extends Subject { + constructor() { + super(observer => observer.breakpointListener(this.state)) + this.state = initialBreakpoints + this.listener = new BalWindowResizeListener() + this.debouncedNotify = debounce$1(() => this.notify(), 50) + this.listener.connect() + this.listener.add(() => { + balBreakpoints.detect() + const newState = balBreakpoints.toObject() + if (!this.isEqual(newState)) { + this.state = newState + this.debouncedNotify() + } + }) + } + attach(observer) { + super.attach(observer) + balBreakpoints.detect() + const newState = balBreakpoints.toObject() + if (!this.isEqual(newState)) { + this.state = newState + this.debouncedNotify() + } + } + isEqual(newState) { + return JSON.stringify(this.state) === JSON.stringify(newState) + } + } + const balBreakpointSubject = new BalBreakpointSubject() + + function ListenToBreakpoints() { + return function (target, _propertyKey, _descriptor) { + const { connectedCallback, disconnectedCallback } = target + target.connectedCallback = function () { + balBreakpointSubject.attach(this) + return connectedCallback && connectedCallback.call(this) + } + target.disconnectedCallback = function () { + balBreakpointSubject.detach(this) + return disconnectedCallback && disconnectedCallback.call(this) + } + } + } + + class BalSwipeListener extends ListenerAbstract { + async connect(el) { + super.connect(el) + await this.loadLib() + if (this.PointerListenerLib) { + this.pointerListener = new this.PointerListenerLib(el, { handleTouchEvents: false }) + this.pointerListener.on('swipeleft', () => this.notify({ left: true, right: false })) + this.pointerListener.on('swiperight', () => this.notify({ left: false, right: true })) + } + } + disconnect() { + var _a + super.disconnect() + ;(_a = this.pointerListener) === null || _a === void 0 ? void 0 : _a.destroy() + } + async loadLib() { + return new Promise((resolve, reject) => { + rIC(async () => { + Promise.resolve() + .then(function () { + return contact + }) + .then(module => { + this.PointerListenerLib = module.PointerListener + resolve() + }) + .catch(reject) + }) + }) + } + } + + class BalSwipeSubject extends SingleSubject { + constructor(options = { mobileOnly: false }) { + super((observer, data) => { + if (data) { + observer.swipeListener(data) + } + }) + this.options = options + this.listener = new BalSwipeListener() + } + attach(observer) { + if ((this.options.mobileOnly === true && balDevice.isMobile) || this.options.mobileOnly !== true) { + super.attach(observer) + this.listener.connect(observer.el) + this.listener.add(info => super.notify(info)) + } + } + detach() { + super.detach() + this.listener.disconnect() + } + } + + function ListenToSwipe(options = { mobileOnly: false }) { + return function (target, _propertyKey, _descriptor) { + const { connectedCallback, disconnectedCallback } = target + target.connectedCallback = function () { + if (!this._balSwipeSubject) { + this._balSwipeSubject = new BalSwipeSubject(options) + this._balSwipeSubject.attach(this) + } + return connectedCallback && connectedCallback.call(this) + } + target.disconnectedCallback = function () { + if (this._balSwipeSubject) { + this._balSwipeSubject.detach() + this._balSwipeSubject = undefined + } + return disconnectedCallback && disconnectedCallback.call(this) + } + } + } + + class BalMutationListener extends ListenerAbstract { + constructor(options) { + super() + this.tags = [] + this.waitAfterFramePrint = false + this.mutationObserver = undefined + this.mutationObserverInit = { + childList: true, + subtree: true, + attributes: true, + characterData: true, + } + this.mutationCallback = mutationRecord => { + const hasChanges = mutationRecord.some(record => this.tags.includes(record.target.nodeName)) + if (hasChanges) { + return this.notify(undefined) + } + const hasRemovedNodeChanges = mutationRecord.some(record => + Array.from(record.removedNodes).some(node => this.tags.includes(node.nodeName)), + ) + if (hasRemovedNodeChanges) { + return this.notify(undefined) + } + if (this.tags.length === 0 && mutationRecord.length > 0) { + const hasCharacterDataChanges = mutationRecord.some(record => record.type === 'characterData') + if (hasCharacterDataChanges) { + return this.notify(undefined) + } + } + if (this.tags.length === 0 && mutationRecord.length > 0) { + return this.notify(undefined) + } + } + this.waitAfterFramePrint = options.waitAfterFramePrint || this.waitAfterFramePrint + this.tags = (options.tags || []).map(t => t.toUpperCase()) + this.mutationObserverInit = { + childList: options.childList === false ? false : true, + subtree: options.subtree === false ? false : true, + attributes: options.attributes === false ? false : true, + characterData: options.characterData === false ? false : true, + } + } + async connect(el) { + super.connect(el) + if (typeof MutationObserver === 'undefined') { + return + } + if (this.waitAfterFramePrint) { + await deepReady(el) + await waitAfterFramePaint() + } + this.destroyMutationObserver() + this.mutationObserver = new MutationObserver(this.mutationCallback) + this.mutationObserver.observe(el, this.mutationObserverInit) + } + disconnect() { + super.disconnect() + this.destroyMutationObserver() + } + destroyMutationObserver() { + if (this.mutationObserver !== undefined) { + this.mutationObserver.disconnect() + this.mutationObserver = undefined + } + } + } + + class BalMutationSubject extends SingleSubject { + constructor(options) { + super(observer => { + if (observer.mutationObserverActive) { + observer.mutationListener() + } + }) + this.options = options + this.debouncedNotify = debounce$1(() => this.notify(), 50) + this.listener = new BalMutationListener(options) + } + attach(observer) { + var _a, _b, _c + super.attach(observer) + if (this.options.closest) { + const closestElement = observer.el.closest(this.options.closest) + if (closestElement) { + ;(_a = this.listener) === null || _a === void 0 ? void 0 : _a.connect(closestElement) + } + } else { + ;(_b = this.listener) === null || _b === void 0 ? void 0 : _b.connect(observer.el) + } + ;(_c = this.listener) === null || _c === void 0 ? void 0 : _c.add(() => this.debouncedNotify()) + } + detach() { + var _a + super.detach() + ;(_a = this.listener) === null || _a === void 0 ? void 0 : _a.disconnect() + } + } + + function ListenToMutation(options) { + return function (target, _propertyKey, _descriptor) { + const { connectedCallback, disconnectedCallback } = target + target.connectedCallback = function () { + if (!this._balMutationSubject) { + this._balMutationSubject = new BalMutationSubject(options) + this._balMutationSubject.attach(this) + } + return connectedCallback && connectedCallback.call(this) + } + target.disconnectedCallback = function () { + if (this._balMutationSubject) { + this._balMutationSubject.detach() + this._balMutationSubject = undefined + } + return disconnectedCallback && disconnectedCallback.call(this) + } + } + } + + class BalResizeListener extends ListenerAbstract { + constructor() { + super(...arguments) + this.debouncedNotify = debounce$1(() => this.notify(), 10) + } + connect(el) { + var _a + super.connect(el) + if (typeof ResizeObserver === 'undefined') { + return + } + if (this.resizeObserver !== undefined) { + ;(_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect() + this.resizeObserver = undefined + } + this.resizeObserver = new ResizeObserver(entries => { + if (balBrowser.hasWindow) { + window.requestAnimationFrame(() => { + if (!Array.isArray(entries) || !entries.length) { + return + } + this.debouncedNotify() + }) + } + }) + this.resizeObserver.observe(el) + } + disconnect() { + var _a + super.disconnect() + ;(_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect() + this.resizeObserver = undefined + } + } + + class BalResizeSubject extends SingleSubject { + constructor() { + super((observer, _data) => { + observer.resizeListener({}) + }) + this.listener = new BalResizeListener() + } + attach(observer) { + super.attach(observer) + this.listener.connect(observer.el) + this.listener.add(info => super.notify(info)) + } + detach() { + super.detach() + this.listener.disconnect() + } + } + + function ListenToResize() { + return function (target, _propertyKey, _descriptor) { + const { connectedCallback, disconnectedCallback } = target + target.connectedCallback = function () { + if (!this._balResizeSubject) { + this._balResizeSubject = new BalResizeSubject() + this._balResizeSubject.attach(this) + } + return connectedCallback && connectedCallback.call(this) + } + target.disconnectedCallback = function () { + if (this._balResizeSubject) { + this._balResizeSubject.detach() + this._balResizeSubject = undefined + } + return disconnectedCallback && disconnectedCallback.call(this) + } + } + } + + const convert = value => parseInt(value.slice(0, -2), 10) + const getComputedPadding = (element, defaultPadding = 16) => { + if (typeof window === 'undefined' || element === undefined) { + return { top: defaultPadding, right: defaultPadding, bottom: defaultPadding, left: defaultPadding } + } + const computedStyle = window.getComputedStyle(element) + const top = convert(computedStyle.getPropertyValue('padding-top')) + const right = convert(computedStyle.getPropertyValue('padding-right')) + const bottom = convert(computedStyle.getPropertyValue('padding-bottom')) + const left = convert(computedStyle.getPropertyValue('padding-left')) + return { top, right, bottom, left } + } + const getComputedWidth = element => { + if (typeof window === 'undefined') { + return element.clientWidth + } + const computedStyle = window.getComputedStyle(element) + const width = convert(computedStyle.getPropertyValue('width')) + const paddingLeft = convert(computedStyle.getPropertyValue('padding-left')) + const paddingRight = convert(computedStyle.getPropertyValue('padding-left')) + return width + paddingLeft + paddingRight + } + + const i18nControlLabel$1 = { + de: { + left: 'vorherige', + right: 'nächste', + }, + en: { + left: 'previous', + right: 'next', + }, + fr: { + left: 'précédent', + right: 'suivant', + }, + it: { + left: 'precedente', + right: 'successivo', + }, + nl: { + left: 'vorige', + right: 'volgende', + }, + es: { + left: 'anterior', + right: 'siguiente', + }, + pl: { + left: 'poprzedni', + right: 'następny', + }, + pt: { + left: 'anterior', + right: 'próximo', + }, + sv: { + left: 'föregående', + right: 'nästa', + }, + fi: { + left: 'edellinen', + right: 'seuraava', + }, + } + + const balCarouselCss = + ':root{--bal-carousel-inner-border-background:var(--bal-color-border);--bal-carousel-inner-border-background-inverted:var(--bal-color-border-primary-light);--bal-carousel-inner-shadow-left-background-before:var(--bal-color-white);--bal-carousel-inner-shadow-right-background-after:var(--bal-color-white);--bal-carousel-inner-shadow-left-background-inverted-before:var(--bal-color-primary);--bal-carousel-inner-shadow-right-background-inverted-after:var(--bal-color-primary);--bal-carousel-product-item-button-background:var(--bal-color-white);--bal-carousel-product-item-button-background-green:var(--bal-color-green-1);--bal-carousel-product-item-button-background-green-hover:var(--bal-color-green-1);--bal-carousel-product-item-button-background-green-active:var(--bal-color-green-2);--bal-carousel-product-item-button-background-red:var(--bal-color-red-1);--bal-carousel-product-item-button-background-red-hover:var(--bal-color-red-1);--bal-carousel-product-item-button-background-red-active:var(--bal-color-red-2);--bal-carousel-product-item-button-background-yellow:var(--bal-color-yellow-1);--bal-carousel-product-item-button-background-yellow-hover:var(--bal-color-yellow-1);--bal-carousel-product-item-button-background-yellow-active:var(--bal-color-yellow-2);--bal-carousel-product-item-button-background-purple:var(--bal-color-purple-1);--bal-carousel-product-item-button-background-purple-hover:var(--bal-color-purple-1);--bal-carousel-product-item-button-background-purple-active:var(--bal-color-purple-2);--bal-carousel-inner-border-radius:var(--bal-radius-rounded);--bal-carousel-image-border-radius:var(--bal-radius-normal);--bal-carousel-product-item-button-border-radius:var(--bal-radius-large);--bal-carousel-product-item-button-label-text-color:var(--bal-color-text-primary);--bal-carousel-sticky-top:0}.bal-carousel{display:block;position:relative}.bal-carousel__inner{display:block;position:relative;margin-left:auto;margin-right:auto;position:relative;overflow:hidden;list-style:none;padding:0;-ms-touch-action:pan-y;touch-action:pan-y}.bal-carousel--full-height{height:100%}.bal-carousel__inner--full-height{height:100%}.bal-carousel__inner__container{position:relative;width:100%;height:100%;display:-ms-flexbox;display:flex;-webkit-box-sizing:content-box;box-sizing:content-box;-webkit-transition-property:-webkit-transform;transition-property:-webkit-transform;transition-property:transform;transition-property:transform, -webkit-transform;-webkit-transition-duration:0ms;transition-duration:0ms;-webkit-transform:translate3d(0px, 0px, 0px);transform:translate3d(0px, 0px, 0px)}.bal-carousel__inner__container--border{padding-bottom:var(--bal-border-width-normal)}.bal-carousel__inner__container__border{position:absolute;background:var(--bal-carousel-inner-border-background);border-radius:var(--bal-carousel-inner-border-radius);height:var(--bal-border-width-normal);width:100%;bottom:0;-webkit-transform:translate3d(0px, 0px, 0px);transform:translate3d(0px, 0px, 0px)}.bal-carousel__inner__container__border--inverted{background:var(--bal-carousel-inner-border-background-inverted)}.bal-carousel__item{text-align:center;font-size:var(--bal-text-size-large);min-height:2rem;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;-ms-flex-negative:0;flex-shrink:0;width:100%;height:100%;position:relative;-webkit-transition-property:-webkit-transform;transition-property:-webkit-transform;transition-property:transform;transition-property:transform, -webkit-transform;-webkit-transform:translateZ(0);transform:translateZ(0);-webkit-backface-visibility:hidden;backface-visibility:hidden}.bal-carousel__inner--shadow-left::before,.bal-carousel__inner--shadow-right::after{position:absolute;width:3rem;height:100%;top:0}.bal-carousel__inner--shadow-left::before{content:"";left:0;background:-webkit-gradient(linear, left top, right top, color-stop(50%, var(--bal-carousel-inner-shadow-left-background-before)), to(rgba(255, 255, 255, 0)));background:linear-gradient(90deg, var(--bal-carousel-inner-shadow-left-background-before) 50%, rgba(255, 255, 255, 0) 100%)}.bal-carousel__inner--shadow-right::after{content:"";right:0;background:-webkit-gradient(linear, left top, right top, from(rgba(255, 255, 255, 0)), color-stop(50%, var(--bal-carousel-inner-shadow-right-background-after)));background:linear-gradient(90deg, rgba(255, 255, 255, 0), var(--bal-carousel-inner-shadow-right-background-after) 50%)}.bal-carousel__inner--shadow-left.bal-carousel__inner--inverted::before{background:-webkit-gradient(linear, left top, right top, color-stop(50%, var(--bal-carousel-inner-shadow-left-background-inverted-before)), to(rgba(255, 255, 255, 0)));background:linear-gradient(90deg, var(--bal-carousel-inner-shadow-left-background-inverted-before) 50%, rgba(255, 255, 255, 0) 100%)}.bal-carousel__inner--shadow-right.bal-carousel__inner--inverted::after{background:-webkit-gradient(linear, left top, right top, from(rgba(255, 255, 255, 0)), color-stop(50%, var(--bal-carousel-inner-shadow-right-background-inverted-after)));background:linear-gradient(90deg, rgba(255, 255, 255, 0), var(--bal-carousel-inner-shadow-right-background-inverted-after) 50%)}.bal-carousel__inner--items-per-view-auto .bal-carousel__item{width:auto}.bal-carousel__inner--items-per-view-1 .bal-carousel__item{width:100%}.bal-carousel__inner--items-per-view-2 .bal-carousel__item{width:50%}.bal-carousel__inner--items-per-view-3 .bal-carousel__item{width:33.3333%}.bal-carousel__inner--items-per-view-4 .bal-carousel__item{width:25%}.bal-carousel--card .bal-carousel__inner--shadow-left::before,.bal-carousel--card .bal-carousel__inner--shadow-right::after{width:1rem}@media screen and (min-width: 769px),print{.bal-carousel--card .bal-carousel__inner--shadow-left::before,.bal-carousel--card .bal-carousel__inner--shadow-right::after{width:2.5rem}}@media screen and (min-width: 1024px){.bal-carousel--card .bal-carousel__inner--shadow-left::before,.bal-carousel--card .bal-carousel__inner--shadow-right::after{width:3rem}}.bal-carousel--card{margin-left:-1rem;margin-right:-1rem}@media screen and (min-width: 769px),print{.bal-carousel--card{margin-left:-2.5rem;margin-right:-2.5rem}}.bal-carousel--card .bal-carousel__controls{padding-left:1rem;padding-right:1rem}@media screen and (min-width: 769px),print{.bal-carousel--card .bal-carousel__controls{padding-left:2.5rem;padding-right:2.5rem}}.bal-carousel--card .bal-carousel__item{width:calc(100% - 2rem);padding-top:1rem;padding-bottom:1rem;padding-left:1rem;padding-right:1rem}@media screen and (min-width: 769px),print{.bal-carousel--card .bal-carousel__item{width:calc(100% - 5rem);padding-top:2.5rem;padding-bottom:2.5rem;padding-left:2.5rem;padding-right:2.5rem}}.bal-carousel--controls-sticky .bal-carousel__controls--tabs{position:-webkit-sticky;position:sticky;top:var(--bal-carousel-sticky-top);z-index:var(--bal-z-index-sticky)}.bal-carousel__controls--tabs .bal-card{padding:0}.bal-carousel__controls--tabs .bal-card-content{padding:.5rem !important;gap:.5rem;display:-ms-flexbox;display:flex}.bal-carousel__controls--tabs .bal-card-content .bal-button{-ms-flex:1;flex:1}.bal-carousel__controls--tabs .bal-card-content .bal-button .button{padding:.5rem !important}.bal-carousel--image .bal-carousel__inner{border-radius:var(--bal-carousel-image-border-radius)}.bal-carousel--image .bal-carousel__inner--is-1by1{padding-top:100%}.bal-carousel--image .bal-carousel__inner--is-16by9{padding-top:56.25%}.bal-carousel--image .bal-carousel__inner--is-3by2{padding-top:66.66%}.bal-carousel--image .bal-carousel__inner--is-4by3{padding-top:75%}.bal-carousel--image .bal-carousel__inner__container{position:absolute;top:0;left:0;display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;height:100%}.bal-carousel--image .bal-carousel__item{position:relative;-ms-flex:0 0 100%;flex:0 0 100%}.bal-carousel--image .bal-carousel__item>img{height:100%;width:100%;-o-object-fit:cover;object-fit:cover;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;user-drag:none;user-zoom:fixed}.bal-carousel--product .bal-carousel__inner__container{gap:1rem;width:-webkit-fit-content;width:-moz-fit-content;width:fit-content}.bal-carousel--product .bal-carousel__item{display:-ms-flexbox;display:flex;width:10rem;height:11rem;text-align:center;padding-top:.5rem;padding-bottom:.5rem;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;user-zoom:fixed;user-drag:none}.bal-carousel--product .bal-carousel__item img{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;user-zoom:fixed;user-drag:none}.bal-carousel--product .bal-carousel__item__button{display:-ms-flexbox;display:flex;-ms-flex:1;flex:1;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:center;align-items:center;gap:1rem;border-radius:var(--bal-carousel-product-item-button-border-radius);padding:var(--bal-text-size-x-small);border:none;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;outline:none;background:var(--bal-carousel-product-item-button-background)}@media (hover: hover)and (pointer: fine){.bal-carousel--product .bal-carousel__item__button:focus-visible:not(:active){-webkit-box-shadow:var(--bal-focus-shadow) !important;box-shadow:var(--bal-focus-shadow) !important}}@media screen and (max-width: 1023px){.bal-carousel--product .bal-carousel__item__button--color-green{background:var(--bal-carousel-product-item-button-background-green)}}@media screen and (min-width: 1024px){.bal-carousel--product .bal-carousel__item__button--color-green:hover{background:var(--bal-carousel-product-item-button-background-green-hover)}.bal-carousel--product .bal-carousel__item__button--color-green:active{background:var(--bal-carousel-product-item-button-background-green-active)}}@media screen and (max-width: 1023px){.bal-carousel--product .bal-carousel__item__button--color-red{background:var(--bal-carousel-product-item-button-background-red)}}@media screen and (min-width: 1024px){.bal-carousel--product .bal-carousel__item__button--color-red:hover{background:var(--bal-carousel-product-item-button-background-red-hover)}.bal-carousel--product .bal-carousel__item__button--color-red:active{background:var(--bal-carousel-product-item-button-background-red-active)}}@media screen and (max-width: 1023px){.bal-carousel--product .bal-carousel__item__button--color-yellow{background:var(--bal-carousel-product-item-button-background-yellow)}}@media screen and (min-width: 1024px){.bal-carousel--product .bal-carousel__item__button--color-yellow:hover{background:var(--bal-carousel-product-item-button-background-yellow-hover)}.bal-carousel--product .bal-carousel__item__button--color-yellow:active{background:var(--bal-carousel-product-item-button-background-yellow-active)}}@media screen and (max-width: 1023px){.bal-carousel--product .bal-carousel__item__button--color-purple{background:var(--bal-carousel-product-item-button-background-purple)}}@media screen and (min-width: 1024px){.bal-carousel--product .bal-carousel__item__button--color-purple:hover{background:var(--bal-carousel-product-item-button-background-purple-hover)}.bal-carousel--product .bal-carousel__item__button--color-purple:active{background:var(--bal-carousel-product-item-button-background-purple-active)}}.bal-carousel--product .bal-carousel__item__button__image{width:5rem;height:5rem;pointer-events:none}.bal-carousel--product .bal-carousel__item__button__label{font-weight:var(--bal-font-weight-bold);color:var(--bal-carousel-product-item-button-label-text-color);font-size:var(--bal-text-size-normal);-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;height:3.5rem;overflow:hidden;line-height:1.15rem;word-break:break-word}@media screen and (max-width: 768px){.bal-carousel__controls--large{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;width:100%;gap:2rem;margin-top:1rem}}@media screen and (min-width: 769px),print{.bal-carousel__controls--large .bal-carousel__controls__button{position:absolute;top:calc(50% - 24px);z-index:7}.bal-carousel__controls--large .bal-carousel__controls__button--left{left:0}.bal-carousel__controls--large .bal-carousel__controls__button--right{right:0}}.bal-carousel__controls__button--hidden{display:none !important;visibility:none !important}.bal-carousel__controls--small .bal-carousel__controls__button{position:absolute;top:calc(50% - 1rem);z-index:7}.bal-carousel__controls--small .bal-carousel__controls__button--left{left:0}.bal-carousel__controls--small .bal-carousel__controls__button--right{right:0}.bal-carousel__controls--small .bal-carousel__controls__button--hidden{display:none !important;visibility:hidden !important}' + var BalCarouselStyle0 = balCarouselCss + + class Carousel { + constructor(hostRef) { + registerInstance(this, hostRef) + this.balChange = createEvent(this, 'balChange', 7) + this.previousTransformValue = 0 + this.carouselId = `bal-carousel-${CarouselIds++}` + this.carouselContainerId = `bal-carousel-${CarouselIds++}-container` + this.mutationObserverActive = true + /** + * EVENT BINDING + * ------------------------------------------------------ + */ + this.onPreviousButtonClick = () => this.previous() + this.onNextButtonClick = () => this.next() + this.onControlChange = selectedValue => { + if (selectedValue !== this.value) { + const isForward = selectedValue > this.value + if (isForward) { + this.next(selectedValue - this.value) + } else { + this.previous(this.value - selectedValue) + } + } + } + this.isLastSlideVisible = true + this.isMobile = balBreakpoints.isMobile + this.language = defaultConfig.language + this.value = 0 + this.steps = 1 + this.itemsPerView = 1 + this.controls = 'none' + this.htmlRole = 'list' + this.controlsOverflow = false + this.inverted = false + this.fullHeight = false + this.aspectRatio = '16by9' + this.interface = '' + this.controlsSticky = false + this.scrollY = true + this.border = false + } + /** + * LIFECYCLE + * ------------------------------------------------------ + */ + /** + * LISTENERS + * ------------------------------------------------------ + */ + async blockVerticalScrolling(ev) { + var _a + if (!this.scrollY && ((_a = this.el) === null || _a === void 0 ? void 0 : _a.contains(ev.target))) { + stopEventBubbling(ev) + } + } + mutationListener() { + this.itemsChanged() + } + swipeListener({ left, right }) { + if (left) { + this.next() + } else if (right) { + this.previous() + } + } + breakpointListener(breakpoints) { + this.isMobile = breakpoints.mobile + this.itemsChanged() + } + resizeListener() { + this.itemsChanged() + } + listenToKeyDown(ev) { + if (this.htmlRole !== 'tablist') { + if (ev.code === 'Tab') { + if (ev.shiftKey) { + this.focusPreviousItem(ev) + } else { + this.focusNextItem(ev) + } + } + } + } + /** + * @internal define config for the component + */ + async configChanged(state) { + this.language = state.language + } + /** + * PUBLIC METHODS + * ------------------------------------------------------ + */ + async previous(steps = this.steps) { + let previousValue = this.value - steps + if (previousValue < 0) { + previousValue = 0 + } + const activeSlide = await this.buildSlide(previousValue) + if (activeSlide) { + const didAnimate = await this.animate(activeSlide.transformActive, true) + if (didAnimate || this.value !== previousValue) { + this.value = previousValue + this.balChange.emit(this.value) + } + } + return activeSlide + } + async next(steps = this.steps) { + const items = this.getAllItemElements() + const length = items.length + let nextValue = this.value + steps + if (nextValue >= length) { + nextValue = length - 1 + } + const activeSlide = await this.buildSlide(nextValue) + if (activeSlide) { + const didAnimate = await this.animate(activeSlide.transformActive, true) + if (didAnimate || this.value !== nextValue) { + this.value = nextValue + this.balChange.emit(this.value) + } + } + return activeSlide + } + /** + * PRIVATE METHODS + * ------------------------------------------------------ + */ + async animate(amount = 0, animated = true) { + return new Promise(resolve => { + if (this.currentRaf !== undefined) { + cancelAnimationFrame(this.currentRaf) + } + this.currentRaf = raf(async () => { + if (this.containerEl && this.innerEl) { + const lastSlide = await this.buildSlide() + if (lastSlide) { + const containerWidth = this.innerEl.clientWidth || 0 + const itemsWith = lastSlide.transformNext || 0 + const noNeedForSlide = itemsWith <= containerWidth + let maxAmount = itemsWith - containerWidth + let isLastSlideVisible = maxAmount <= amount + // -1 one is needed for example when we use items per view 3 with 33.333% + if (this.itemsPerView === 3) { + maxAmount = itemsWith - containerWidth - 1 + isLastSlideVisible = maxAmount <= amount + } + const isFirst = amount === 0 || maxAmount <= 2 + if (isFirst) { + this.value = 0 + this.balChange.emit(this.value) + } + const hasSmallControls = this.controls === 'small' + const hasLargeControls = this.controls === 'large' + let transformValue = noNeedForSlide ? 0 : isLastSlideVisible ? maxAmount : amount + if (!isFirst && !noNeedForSlide && (hasSmallControls || (hasLargeControls && !this.isMobile))) { + transformValue = transformValue - (isLastSlideVisible ? 0 : hasLargeControls ? 56 : 48) + } + this.containerEl.style.transitionDuration = animated ? '0.6s' : '0' + this.containerEl.style.transform = `translate3d(-${transformValue}px, 0px, 0px)` + const didAnimate = transformValue !== this.previousTransformValue + this.previousTransformValue = transformValue + this.isLastSlideVisible = isLastSlideVisible + if (this.borderEl) { + this.borderEl.style.transitionDuration = animated ? '0.6s' : '0' + this.borderEl.style.transform = `translate3d(${transformValue}px, 0px, 0px)` + } + if (!didAnimate) { + return resolve(false) + } + return resolve(true) + } + } + }) + }) + } + async buildSlide(slideIndex) { + const items = this.getAllItemElements() + const index = slideIndex === undefined ? items.length - 1 : slideIndex + if (items.length > index && index >= 0) { + const data = await this.getAllItemData() + const gapSize = this.interface === 'product' ? 16 : 0 + return { + el: items[index], + data: data[index], + transformNext: items + .filter((_, n) => n < index + 1) + .reduce((acc, item) => acc + getComputedWidth(item) + gapSize, 0), + transformActive: items + .filter((_, n) => n < index) + .reduce((acc, item) => acc + getComputedWidth(item) + gapSize, 0), + isFirst: index === 0, + isLast: index === items.length - 1, + total: items.length, + index, + } + } + return undefined + } + async itemsChanged() { + const activeSlide = await this.buildSlide(this.value) + if (activeSlide) { + this.animate(activeSlide.transformActive, false) + } + } + async focusNextItem(ev) { + if (!this.isLast) { + const slide = await this.next(1) + if (slide && slide.el) { + stopEventBubbling(ev) + await slide.el.setFocus() + } + } + } + async focusPreviousItem(ev) { + if (!this.isFirst) { + const slide = await this.previous(1) + if (slide && slide.el) { + stopEventBubbling(ev) + await slide.el.setFocus() + } + } + } + /** + * GETTERS + * ------------------------------------------------------ + */ + async getAllItemData() { + const queue = this.getAllItemElements().map(el => el.getData()) + return await Promise.all(queue) + } + getAllItemElements() { + return Array.from(this.el.querySelectorAll('bal-carousel-item')) + } + getAllControlItems() { + const items = this.getAllItemElements() + return items.map((item, index) => ({ value: index, label: item.label })) + } + hasShadow() { + return this.itemsPerView === 'auto' || this.itemsPerView > 1 || this.interface === 'card' + } + hasShadowLeft() { + return this.hasShadow() && (this.value !== 0 || this.interface === 'card') + } + hasShadowRight() { + return this.hasShadow() && (!this.isLastSlideVisible || this.interface === 'card') + } + isFirst() { + return this.value === 0 + } + isLast() { + return this.isLastSlideVisible + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + const block = BEM.block('carousel') + const inner = block.element('inner') + const container = inner.element('container') + const leftControlTitle = i18nControlLabel$1[this.language].left + const rightControlTitle = i18nControlLabel$1[this.language].right + const controlItems = this.getAllControlItems() + return hAsync( + Host, + { + key: 'a78a4c05dc1656ca01a421fb52cb3cacb176bca1', + class: Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign({}, block.class()), + block.modifier(this.interface).class(this.interface !== ''), + ), + block.modifier(`full-height`).class(this.fullHeight), + ), + block.modifier('controls-sticky').class(this.controlsSticky), + ), + block.modifier(`controls-${this.controls}`).class(), + ), + }, + this.controls === 'tabs' + ? hAsync(TabControl, { + value: this.value, + items: controlItems, + containerId: this.carouselContainerId, + onControlChange: item => this.onControlChange(item.value), + }) + : '', + hAsync( + 'div', + { + key: '880f8757830aecd4be7b1ba8394e34501e6314cd', + class: Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign({}, inner.class()), + inner.modifier(`items-per-view-${this.itemsPerView}`).class(), + ), + inner.modifier(`is-${this.aspectRatio}`).class(), + ), + inner.modifier(`inverted`).class(this.inverted), + ), + inner.modifier(`full-height`).class(this.fullHeight), + ), + inner.modifier(`shadow-left`).class(this.hasShadowLeft()), + ), + inner.modifier(`shadow-right`).class(this.hasShadowRight()), + ), + ref: el => (this.innerEl = el), + }, + hAsync( + 'div', + { + 'key': 'e5047832a5feffe8c203505f1e9162734fd0252d', + 'role': this.htmlRole, + 'aria-live': this.htmlRole !== '' ? 'polite' : undefined, + 'id': this.carouselContainerId, + 'class': Object.assign( + Object.assign(Object.assign({}, container.class()), container.modifier(`border`).class(this.border)), + container.modifier(`is-${this.aspectRatio}`).class(), + ), + 'ref': el => (this.containerEl = el), + }, + hAsync('slot', { key: '5de3491bfa1d42a8326ee80d4dc2119672fdd6b3' }), + this.border + ? hAsync('div', { + 'id': `${this.carouselId}-border`, + 'aria-hidden': 'true', + 'class': Object.assign( + Object.assign({}, container.element('border').class()), + container.element('border').modifier('inverted').class(this.inverted), + ), + 'ref': el => (this.borderEl = el), + }) + : '', + ), + ), + this.controls === 'dots' + ? hAsync(DotControl, { + value: this.value, + items: controlItems, + containerId: this.carouselContainerId, + onControlChange: item => this.onControlChange(item.value), + }) + : '', + this.controls === 'large' + ? hAsync(LargeControl, { + isFirst: this.isFirst(), + isLast: this.isLast(), + inverted: this.inverted, + areControlsHidden: !this.isMobile, + leftControlTitle: leftControlTitle, + rightControlTitle: rightControlTitle, + containerId: this.carouselContainerId, + onNextClick: () => this.onNextButtonClick(), + onPreviousClick: () => this.onPreviousButtonClick(), + }) + : '', + this.controls === 'small' + ? hAsync(SmallControl, { + isFirst: this.isFirst(), + isLast: this.isLast(), + inverted: this.inverted, + leftControlTitle: leftControlTitle, + rightControlTitle: rightControlTitle, + containerId: this.carouselContainerId, + onNextClick: () => this.onNextButtonClick(), + onPreviousClick: () => this.onPreviousButtonClick(), + }) + : '', + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalCarouselStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-carousel', + $members$: { + value: [1026], + steps: [2], + itemsPerView: [8, 'items-per-view'], + controls: [1], + htmlRole: [1, 'html-role'], + controlsOverflow: [4, 'controls-overflow'], + inverted: [4], + fullHeight: [4, 'full-height'], + aspectRatio: [1, 'aspect-ratio'], + interface: [1], + controlsSticky: [4, 'controls-sticky'], + scrollY: [4, 'scroll-y'], + border: [4], + isLastSlideVisible: [32], + isMobile: [32], + language: [32], + configChanged: [64], + previous: [64], + next: [64], + }, + $listeners$: [ + [8, 'touchmove', 'blockVerticalScrolling'], + [0, 'keydown', 'listenToKeyDown'], + ], + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + __decorate( + [ + ListenToMutation({ tags: ['bal-carousel-item'], characterData: false }), + __metadata('design:type', Function), + __metadata('design:paramtypes', []), + __metadata('design:returntype', void 0), + ], + Carousel.prototype, + 'mutationListener', + null, + ) + __decorate( + [ + ListenToSwipe(), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Object]), + __metadata('design:returntype', void 0), + ], + Carousel.prototype, + 'swipeListener', + null, + ) + __decorate( + [ + ListenToBreakpoints(), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Object]), + __metadata('design:returntype', void 0), + ], + Carousel.prototype, + 'breakpointListener', + null, + ) + __decorate( + [ + ListenToResize(), + __metadata('design:type', Function), + __metadata('design:paramtypes', []), + __metadata('design:returntype', void 0), + ], + Carousel.prototype, + 'resizeListener', + null, + ) + __decorate( + [ + ListenToConfig(), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Object]), + __metadata('design:returntype', Promise), + ], + Carousel.prototype, + 'configChanged', + null, + ) + let CarouselIds = 0 + + class CarouselItem { + constructor(hostRef) { + registerInstance(this, hostRef) + this.balNavigate = createEvent(this, 'balNavigate', 7) + this.balFocus = createEvent(this, 'balFocus', 7) + this.balBlur = createEvent(this, 'balBlur', 7) + this.imageInheritAttributes = {} + this.onClick = ev => { + if (this.href !== undefined) { + this.balNavigate.emit(ev) + } + } + this.onFocus = () => { + this.balFocus.emit() + } + this.onBlur = () => { + this.balBlur.emit() + } + this.src = undefined + this.label = '' + this.htmlRole = 'listitem' + this.elementType = 'button' + this.name = '' + this.value = '' + this.href = undefined + this.target = '_self' + this.rel = undefined + this.download = undefined + this.color = undefined + } + componentWillLoad() { + this.imageInheritAttributes = inheritAttributes(this.el, ['alt']) + } + async getData() { + return { + clientWidth: this.el.clientWidth, + label: this.label, + } + } + async setFocus() { + await waitAfterFramePaint() + if (this.buttonEl) { + this.buttonEl.focus() + } + } + render() { + const block = BEM.block('carousel') + const itemEl = block.element('item') + const isProduct = !!this.color && !!this.label + if (!isProduct) { + return hAsync( + Host, + { role: this.htmlRole, class: Object.assign({}, itemEl.class()) }, + this.src !== undefined + ? hAsync( + 'img', + Object.assign( + { draggable: false, onDragStart: () => false, src: this.src }, + this.imageInheritAttributes, + ), + ) + : '', + hAsync('slot', null), + ) + } + const button = itemEl.element('button') + const image = button.element('image') + const label = button.element('label') + const { elementType, download, href, rel, target, name, value } = this + const TagType = this.href === undefined ? 'button' : 'a' + const attrs = + TagType === 'button' + ? { type: elementType, name, value } + : { + download, + href, + rel, + target, + } + return hAsync( + Host, + { role: this.htmlRole, class: Object.assign({}, itemEl.class()) }, + hAsync( + TagType, + Object.assign({}, attrs, { + class: Object.assign(Object.assign({}, button.class()), button.modifier(`color-${this.color}`).class()), + part: 'native', + onFocus: this.onFocus, + onBlur: this.onBlur, + onClick: this.onClick, + ref: el => (this.buttonEl = el), + }), + this.src !== undefined + ? hAsync( + 'img', + Object.assign( + { + 'class': Object.assign({}, image.class()), + 'loading': 'lazy', + 'draggable': false, + 'onDragStart': () => false, + 'aria-hidden': 'true', + 'src': this.src, + }, + this.imageInheritAttributes, + ), + ) + : '', + this.label !== undefined ? hAsync('span', { class: Object.assign({}, label.class()) }, this.label) : '', + hAsync('slot', null), + ), + ) + } + get el() { + return getElement(this) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-carousel-item', + $members$: { + src: [513], + label: [513], + htmlRole: [1, 'html-role'], + elementType: [1, 'element-type'], + name: [513], + value: [520], + href: [1], + target: [1], + rel: [1], + download: [1], + color: [1], + getData: [64], + setFocus: [64], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [ + ['src', 'src'], + ['label', 'label'], + ['name', 'name'], + ['value', 'value'], + ], + } + } + } + + const scrollToFirstInvalidField = options => { + const selector = options.selector || '.bal-field--invalid' + const invalidFieldNodes = options.formEl.querySelectorAll(selector) + const invalidFields = Array.from(invalidFieldNodes) + if (invalidFields.length > 0) { + const firstInvalidField = invalidFields[0] + if (firstInvalidField) { + const invalidField = firstInvalidField.closest('bal-field') + if (invalidField && invalidField.scrollIntoView) { + invalidField.scrollIntoView() + } + } + } + } + const defaultBalAriaForm = { + controlId: undefined, + labelId: undefined, + messageId: undefined, + } + + const ariaBooleanToString = bool => (!!bool ? 'true' : 'false') + + const radioCheckboxCss$1 = + '@media (hover: hover)and (pointer: fine){.bal-radio-checkbox.bal-focused .bal-radio-checkbox__input:not(.bal-radio-checkbox__input--select-button)+.bal-radio-checkbox__label::before,.bal-radio-checkbox.bal-focused.bal-radio-checkbox--select-button{-webkit-box-shadow:var(--bal-focus-shadow) !important;box-shadow:var(--bal-focus-shadow) !important}}:root{--bal-radio-checkbox-symbol-size:1.5rem;--bal-radio-checkbox-symbol-width:calc(0.5rem - 1px);--bal-radio-checkbox-symbol-height:calc(0.875rem - 1px);--bal-radio-checkbox-symbol-left:calc(0.5rem + 1px);--bal-radio-checkbox-symbol-margin-top:0.25rem;--bal-radio-checkbox-label-min-height:1.5rem;--bal-radio-checkbox-select-button-background-hover:var(--bal-color-grey-2);--bal-radio-checkbox-select-button-background-active:var(--bal-color-grey-2);--bal-radio-checkbox-select-button-background-checked:var(--bal-color-primary);--bal-radio-checkbox-select-button-background-checked-hover:var(--bal-color-light-blue-5);--bal-radio-checkbox-select-button-background-checked-active:var(--bal-color-primary-6);--bal-radio-checkbox-select-button-background-invalid:var(--bal-color-danger-1);--bal-radio-checkbox-select-button-background-invalid-hover:var(--bal-color-danger-1);--bal-radio-checkbox-select-button-background-invalid-active:var(--bal-color-danger-1);--bal-radio-checkbox-select-button-background-invalid-checked:var(--bal-color-border-danger);--bal-radio-checkbox-select-button-background-invalid-checked-hover:var(--bal-color-danger-5);--bal-radio-checkbox-select-button-background-invalid-checked-active:var(--bal-color-danger-6);--bal-radio-checkbox-select-button-background-disabled-hover-active:var(--bal-color-grey-2);--bal-radio-checkbox-select-button-background-disabled-checked-hover-active:var(--bal-color-border-grey-dark);--bal-radio-checkbox-switch-label-background-before:var(--bal-color-primary-1);--bal-radio-checkbox-switch-label-background-after:var(--bal-color-primary);--bal-radio-checkbox-switch-label-background-hover-after:var(--bal-color-light-blue-5);--bal-radio-checkbox-switch-label-background-active-after:var(--bal-color-primary-6);--bal-radio-checkbox-switch-label-background-checked-before:var(--bal-color-success-4);--bal-radio-checkbox-switch-label-background-checked-after:var(--bal-color-white);--bal-radio-checkbox-switch-label-background-checked-hover-before:var(--bal-color-success-5);--bal-radio-checkbox-switch-label-background-checked-active-before:var(--bal-color-success-6);--bal-radio-checkbox-switch-label-background-invalid-before:var(--bal-color-danger-1);--bal-radio-checkbox-switch-label-background-invalid-after:var(--bal-color-border-danger);--bal-radio-checkbox-switch-label-background-invalid-hover-after:var(--bal-color-danger-6);--bal-radio-checkbox-switch-label-background-invalid-active-after:var(--bal-color-border-danger);--bal-radio-checkbox-switch-label-background-invalid-checked-before:var(--bal-color-danger-4);--bal-radio-checkbox-switch-label-background-invalid-checked-after:var(--bal-color-white);--bal-radio-checkbox-switch-label-background-invalid-checked-hover-before:var(--bal-color-danger-5);--bal-radio-checkbox-switch-label-background-invalid-checked-active-before:var(--bal-color-danger-6);--bal-radio-checkbox-switch-label-background-disabled-hover-active-before:var(--bal-color-grey-3);--bal-radio-checkbox-switch-label-background-disabled-hover-active-after:var(--bal-color-border-grey-dark);--bal-radio-checkbox-switch-label-background-disabled-checked-hover-active-before:var(--bal-color-border-grey-dark);--bal-radio-checkbox-switch-label-background-disabled-checked-hover-active-after:var(--bal-color-white);--bal-radio-checkbox-button-background:transparent;--bal-radio-checkbox-button-background-checked-green:var(--bal-color-green-1);--bal-radio-checkbox-button-background-checked-purple:var(--bal-color-purple-1);--bal-radio-checkbox-button-background-checked-red:var(--bal-color-red-1);--bal-radio-checkbox-button-background-checked-yellow:var(--bal-color-yellow-1);--bal-radio-checkbox-button-background-disabled:var(--bal-color-grey-1);--bal-radio-checkbox-button-background-hover:var(--bal-color-grey-1);--bal-radio-checkbox-select-button-border-color:var(--bal-color-primary);--bal-radio-checkbox-select-button-border-color-hover:var(--bal-color-light-blue-5);--bal-radio-checkbox-select-button-border-color-active:var(--bal-color-primary-6);--bal-radio-checkbox-select-button-border-color-invalid:var(--bal-color-border-danger);--bal-radio-checkbox-select-button-border-color-invalid-hover:var(--bal-color-danger-5);--bal-radio-checkbox-select-button-border-color-invalid-active:var(--bal-color-danger-6);--bal-radio-checkbox-select-button-border-color-invalid-checked:var(--bal-color-border-danger);--bal-radio-checkbox-select-button-border-color-invalid-checked-hover:var(--bal-color-danger-5);--bal-radio-checkbox-select-button-border-color-invalid-checked-active:var(--bal-color-danger-6);--bal-radio-checkbox-select-button-border-color-disabled-hover-active:var(--bal-color-border-grey-dark);--bal-radio-checkbox-select-button-border-color-disabled-checked-hover-active:var(--bal-color-border-grey-dark);--bal-radio-checkbox-button-border-color-hover:var(--bal-color-border-primary-hovered);--bal-radio-checkbox-button-border-color-active:var(--bal-color-border-primary-pressed);--bal-radio-checkbox-button-border-color-invalid-hover:var(--bal-color-border-danger-hovered);--bal-radio-checkbox-button-border-color-invalid-active:var(--bal-color-border-danger-pressed);--bal-radio-checkbox-button-border-color:var(--bal-color-border);--bal-radio-checkbox-button-border-color-checked:var(--bal-color-border-primary);--bal-radio-checkbox-button-border-color-disabled:var(--bal-color-border-grey-dark);--bal-radio-checkbox-button-border-color-invalid:var(--bal-color-border-danger)}bal-radio .bal-radio-checkbox__label::before,bal-radio .bal-radio-checkbox__label::after{margin-top:0px !important}.bal-radio-checkbox-group{display:inline-block;position:relative;width:100%}.bal-radio-checkbox-group__inner{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;-ms-flex-pack:start;justify-content:flex-start;-ms-flex-align:stretch;align-items:stretch;-ms-flex-wrap:wrap;flex-wrap:wrap;gap:var(--bal-space-normal)}.bal-radio-checkbox-group__inner--select-button{-ms-flex-direction:column;flex-direction:column;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex:1;flex:1;gap:var(--bal-space-x-small)}@media screen and (min-width: 769px),print{.bal-radio-checkbox-group__inner--select-button{-ms-flex-direction:row;flex-direction:row}}.bal-radio-checkbox-group__inner--expanded{-ms-flex-align:stretch;align-items:stretch}.bal-radio-checkbox-group__inner--expanded .bal-radio-checkbox{-ms-flex:1;flex:1}@media screen and (max-width: 768px){.bal-radio-checkbox-group__inner--expanded .bal-radio-checkbox{width:100%}}.bal-radio-checkbox-group__inner--select-button.bal-radio-checkbox-group__inner--vertical{gap:var(--bal-space-x-small)}.bal-radio-checkbox-group__inner--vertical{-ms-flex-direction:column;flex-direction:column;border-radius:var(--bal-radius-normal);gap:0}@media screen and (min-width: 769px),print{.bal-radio-checkbox-group__inner--vertical{-ms-flex-align:start;align-items:flex-start}}@media screen and (max-width: 768px){.bal-radio-checkbox-group__inner--vertical-mobile{-ms-flex-direction:column;flex-direction:column;border-radius:var(--bal-radius-normal);gap:0}}.bal-radio-checkbox{position:relative;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-pack:start;justify-content:flex-start;-ms-flex-align:center;align-items:center;outline:none;min-width:1.5rem;min-height:3rem}.bal-radio-checkbox--flat:not(.bal-radio-checkbox--select-button){min-height:1.5rem}.bal-radio-checkbox__input{position:absolute !important;left:0;top:0;margin:0;padding:0;opacity:0;outline:0;border:none;width:1px;height:1px;clip:rect(1px, 1px, 1px, 1px);overflow:hidden}.bal-radio-checkbox--invisible{position:absolute !important;left:0;top:0;margin:0;padding:0;opacity:0;outline:0;border:none;width:1px;height:1px;clip:rect(1px, 1px, 1px, 1px);overflow:hidden}.bal-radio-checkbox:not(.bal-radio-checkbox--disabled),.bal-radio-checkbox:not(.bal-radio-checkbox--disabled) input,.bal-radio-checkbox:not(.bal-radio-checkbox--disabled) input+label,.bal-radio-checkbox:not(.bal-radio-checkbox--disabled) input+label>span{cursor:pointer}.bal-radio-checkbox__label{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;margin:0;line-height:1.5rem;contain:layout style;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;text-align:left;min-height:var(--bal-radio-checkbox-label-min-height);font-family:var(--bal-font-family-text)}.bal-radio-checkbox__label__text{padding-left:2rem;-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;padding-top:.25rem;padding-bottom:.25rem}.bal-radio-checkbox__label__text--hidden{padding-left:0;display:none}.bal-radio-checkbox__label__text--flat{padding-top:0;padding-bottom:0}.bal-radio-checkbox__label--flat:not(.bal-radio-checkbox--select-button)::before,.bal-radio-checkbox__label--flat:not(.bal-radio-checkbox--select-button)::after{top:0px !important}.bal-radio-checkbox__label--hidden::before,.bal-radio-checkbox__label--hidden::after{top:0px !important}.bal-radio-checkbox__label::before,.bal-radio-checkbox__label::after{display:inline-block;position:absolute;left:0;top:.25rem;height:var(--bal-radio-checkbox-symbol-size);width:var(--bal-radio-checkbox-symbol-size);background-color:rgba(0,0,0,0);background-position:center;background-repeat:no-repeat;background-size:var(--bal-radio-checkbox-symbol-size) var(--bal-radio-checkbox-symbol-size)}.bal-radio-checkbox__label::before{content:"";border-style:var(--bal-form-field-control-border-style);border-width:2px}.bal-radio-checkbox__label::after{content:none}.bal-radio-checkbox__label--checked::after{content:""}.bal-radio-checkbox__label--radio::before,.bal-radio-checkbox__label--radio::after{border-radius:50%}.bal-radio-checkbox__label--radio::after{left:0;-webkit-transform:scale(0.25);transform:scale(0.25)}.bal-radio-checkbox__label--checkbox::before{border-radius:var(--bal-form-field-control-radius)}.bal-radio-checkbox__label--checkbox::after{border-top:0;border-right-style:var(--bal-form-field-control-border-style);border-right-width:2px;border-bottom-style:var(--bal-form-field-control-border-style);border-bottom-width:2px;border-left:0;border-radius:1px;width:var(--bal-radio-checkbox-symbol-width);height:var(--bal-radio-checkbox-symbol-height);left:var(--bal-radio-checkbox-symbol-left);margin-top:var(--bal-radio-checkbox-symbol-margin-top);-webkit-transform:rotate(45deg);transform:rotate(45deg)}.bal-radio-checkbox .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-primary);background:var(--bal-color-transparent)}.bal-radio-checkbox .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-primary)}.bal-radio-checkbox .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-primary)}.bal-radio-checkbox:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before,.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-light-blue-5);background:var(--bal-color-grey-2)}.bal-radio-checkbox:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after,.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-light-blue-5)}.bal-radio-checkbox:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after,.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-light-blue-5)}.bal-radio-checkbox:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before,.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-blue-6);background:var(--bal-color-grey-2)}.bal-radio-checkbox:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after,.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-blue-6)}.bal-radio-checkbox:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after,.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-blue-6)}.bal-radio-checkbox--invalid .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-border-danger);background:var(--bal-color-danger-1)}.bal-radio-checkbox--invalid .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--invalid .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-border-danger)}.bal-radio-checkbox--invalid .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--invalid .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-border-danger)}.bal-radio-checkbox--invalid:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before,.bal-radio-checkbox--invalid.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-danger-5);background:var(--bal-color-danger-1)}.bal-radio-checkbox--invalid:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after,.bal-radio-checkbox--invalid.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--invalid:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--invalid.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-danger-5)}.bal-radio-checkbox--invalid:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after,.bal-radio-checkbox--invalid.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--invalid:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--invalid.bal-radio-checkbox--hovered .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-danger-5)}.bal-radio-checkbox--invalid:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before,.bal-radio-checkbox--invalid.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-danger-6);background:var(--bal-color-danger-1)}.bal-radio-checkbox--invalid:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after,.bal-radio-checkbox--invalid.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--invalid:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--invalid.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-danger-6)}.bal-radio-checkbox--invalid:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after,.bal-radio-checkbox--invalid.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--invalid:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--invalid.bal-radio-checkbox--pressed .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-danger-6)}.bal-radio-checkbox--disabled .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before,.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before,.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-border-grey-dark);background:var(--bal-color-grey-2)}.bal-radio-checkbox--disabled .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after,.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after,.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--disabled .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-border-grey-dark)}.bal-radio-checkbox--disabled .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after,.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after,.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--disabled .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-border-grey-dark)}.bal-radio-checkbox .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-primary)}.bal-radio-checkbox:hover .bal-radio-checkbox__label .bal-radio-checkbox__label__text,.bal-radio-checkbox--hovered .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-light-blue-5)}.bal-radio-checkbox:active .bal-radio-checkbox__label .bal-radio-checkbox__label__text,.bal-radio-checkbox--pressed .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-blue-6)}.bal-radio-checkbox--invalid .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-border-danger)}.bal-radio-checkbox--invalid:hover .bal-radio-checkbox__label .bal-radio-checkbox__label__text,.bal-radio-checkbox--invalid.bal-radio-checkbox--hovered .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-danger-5)}.bal-radio-checkbox--invalid:active .bal-radio-checkbox__label .bal-radio-checkbox__label__text,.bal-radio-checkbox--invalid.bal-radio-checkbox--pressed .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-danger-6)}.bal-radio-checkbox--disabled .bal-radio-checkbox__label .bal-radio-checkbox__label__text,.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label .bal-radio-checkbox__label__text,.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label .bal-radio-checkbox__label__text,.bal-radio-checkbox--disabled.bal-radio-checkbox--hovered .bal-radio-checkbox__label .bal-radio-checkbox__label__text,.bal-radio-checkbox--disabled.bal-radio-checkbox--pressed .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-text-grey)}.bal-radio-checkbox--inline{display:inline}.bal-radio-checkbox--select-button{padding-left:.75rem;padding-right:.75rem;min-width:3rem;border-width:2px;border-style:var(--bal-form-field-control-border-style);border-radius:var(--bal-form-field-control-radius);border-color:var(--bal-radio-checkbox-select-button-border-color)}.bal-radio-checkbox--select-button:hover{border-color:var(--bal-radio-checkbox-select-button-border-color-hover);background:var(--bal-radio-checkbox-select-button-background-hover)}.bal-radio-checkbox--select-button:active{border-color:var(--bal-radio-checkbox-select-button-border-color-active);background:var(--bal-radio-checkbox-select-button-background-active)}.bal-radio-checkbox--select-button label::before{top:unset}.bal-radio-checkbox--select-button label::after{top:unset;margin-top:-3px}.bal-radio-checkbox--select-button .bal-radio-checkbox__label--flat::before{top:unset !important}.bal-radio-checkbox--select-button .bal-radio-checkbox__label--flat::after{margin-top:-3px;top:unset !important}.bal-radio-checkbox--select-button .bal-radio-checkbox__label--flat .bal-radio-checkbox__label__text--flat{padding-top:.25rem;padding-bottom:.25rem}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked{background:var(--bal-radio-checkbox-select-button-background-checked)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked .bal-radio-checkbox__label .bal-radio-checkbox__label__text .is-link{color:var(--bal-radio-checkbox-select-button-link-text-color-checked)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:hover{background:var(--bal-radio-checkbox-select-button-background-checked-hover)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:active{background:var(--bal-radio-checkbox-select-button-background-checked-active)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-white);background:var(--bal-color-transparent)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-primary)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-primary)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-white);background:var(--bal-color-transparent)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-light-blue-5)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-light-blue-5)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-white);background:var(--bal-color-transparent)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-blue-6)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-blue-6)}.bal-radio-checkbox--select-button.bal-radio-checkbox--checked:active .bal-radio-checkbox__label .bal-radio-checkbox__label__text{color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid{border-color:var(--bal-radio-checkbox-select-button-border-color-invalid);background:var(--bal-radio-checkbox-select-button-background-invalid)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid .bal-radio-checkbox__label .bal-radio-checkbox__label__text .is-link{color:var(--bal-form-field-label-danger-color)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid:hover{border-color:var(--bal-radio-checkbox-select-button-border-color-invalid-hover);background:var(--bal-radio-checkbox-select-button-background-invalid-hover)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid:active{border-color:var(--bal-radio-checkbox-select-button-border-color-invalid-active);background:var(--bal-radio-checkbox-select-button-background-invalid-active)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked{border-color:var(--bal-radio-checkbox-select-button-border-color-invalid-checked);background:var(--bal-radio-checkbox-select-button-background-invalid-checked)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:hover{border-color:var(--bal-radio-checkbox-select-button-border-color-invalid-checked-hover);background:var(--bal-radio-checkbox-select-button-background-invalid-checked-hover)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:active{border-color:var(--bal-radio-checkbox-select-button-border-color-invalid-checked-active);background:var(--bal-radio-checkbox-select-button-background-invalid-checked-active)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-white);background:var(--bal-color-transparent)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-border-danger)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-border-danger)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-white);background:var(--bal-color-transparent)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-danger-5)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-danger-5)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-white);background:var(--bal-color-transparent)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-danger-6)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-danger-6)}.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled:hover,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled:active{border-color:var(--bal-radio-checkbox-select-button-border-color-disabled-hover-active);background:var(--bal-radio-checkbox-select-button-background-disabled-hover-active)}.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled .bal-radio-checkbox__label .bal-radio-checkbox__label__text .is-link,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label .bal-radio-checkbox__label__text .is-link,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label .bal-radio-checkbox__label__text .is-link{color:var(--bal-form-field-label-disabled-color)}.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:hover,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:active{border-color:var(--bal-radio-checkbox-select-button-border-color-disabled-checked-hover-active);background:var(--bal-radio-checkbox-select-button-background-disabled-checked-hover-active)}.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch)::before{border-color:var(--bal-color-white);background:var(--bal-color-transparent)}.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::after{background:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--radio.bal-radio-checkbox__label--checked::before{background:var(--bal-color-border-grey-dark)}.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox::after{border-right-color:var(--bal-color-white);border-bottom-color:var(--bal-color-white)}.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before,.bal-radio-checkbox--select-button.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:active .bal-radio-checkbox__label:not(.bal-radio-checkbox__label--switch).bal-radio-checkbox__label--checkbox.bal-radio-checkbox__label--checked::before{background:var(--bal-color-border-grey-dark)}.bal-radio-checkbox--switch{min-width:2.5rem}.bal-radio-checkbox--switch .bal-radio-checkbox__label{padding-left:1rem}.bal-radio-checkbox--switch .bal-radio-checkbox__label::before{border-radius:1.5rem;position:absolute;display:block;top:0;left:0;width:2.5rem;height:1.5rem;border:1.6px solid rgba(0,0,0,0);content:"";-webkit-transition:left .25s ease-out,background .25s ease-out;transition:left .25s ease-out,background .25s ease-out;margin-top:.25rem}.bal-radio-checkbox--switch .bal-radio-checkbox__label::after{border:none;margin:0;border-radius:50%;display:block;position:absolute;top:.25rem !important;left:.25rem;width:1rem;height:1rem;margin-top:.25rem;-webkit-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);-webkit-transition:left .25s ease-out,background .25s ease-out;transition:left .25s ease-out,background .25s ease-out;content:""}.bal-radio-checkbox--switch .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-before)}.bal-radio-checkbox--switch .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-after)}.bal-radio-checkbox--switch:hover .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-hover-after)}.bal-radio-checkbox--switch:active .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-active-after)}.bal-radio-checkbox--switch.bal-radio-checkbox--checked .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-checked-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--checked .bal-radio-checkbox__label::after{left:1.25rem;background:var(--bal-radio-checkbox-switch-label-background-checked-after)}.bal-radio-checkbox--switch.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-checked-hover-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--checked:active .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-checked-active-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--invalid .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-invalid-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--invalid .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-invalid-after)}.bal-radio-checkbox--switch.bal-radio-checkbox--invalid:hover .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-invalid-hover-after)}.bal-radio-checkbox--switch.bal-radio-checkbox--invalid:active .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-invalid-active-after)}.bal-radio-checkbox--switch.bal-radio-checkbox--invalid.bal-radio-checkbox--checked .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-invalid-checked-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--invalid.bal-radio-checkbox--checked .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-invalid-checked-after)}.bal-radio-checkbox--switch.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-invalid-checked-hover-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--invalid.bal-radio-checkbox--checked:active .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-invalid-checked-active-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--disabled .bal-radio-checkbox__label::before,.bal-radio-checkbox--switch.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label::before,.bal-radio-checkbox--switch.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-disabled-hover-active-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--disabled .bal-radio-checkbox__label::after,.bal-radio-checkbox--switch.bal-radio-checkbox--disabled:hover .bal-radio-checkbox__label::after,.bal-radio-checkbox--switch.bal-radio-checkbox--disabled:active .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-disabled-hover-active-after)}.bal-radio-checkbox--switch.bal-radio-checkbox--disabled.bal-radio-checkbox--checked .bal-radio-checkbox__label::before,.bal-radio-checkbox--switch.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label::before,.bal-radio-checkbox--switch.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:active .bal-radio-checkbox__label::before{background:var(--bal-radio-checkbox-switch-label-background-disabled-checked-hover-active-before)}.bal-radio-checkbox--switch.bal-radio-checkbox--disabled.bal-radio-checkbox--checked .bal-radio-checkbox__label::after,.bal-radio-checkbox--switch.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:hover .bal-radio-checkbox__label::after,.bal-radio-checkbox--switch.bal-radio-checkbox--disabled.bal-radio-checkbox--checked:active .bal-radio-checkbox__label::after{background:var(--bal-radio-checkbox-switch-label-background-disabled-checked-hover-active-after)}' + var BalCheckboxStyle0 = radioCheckboxCss$1 + + class Checkbox { + constructor(hostRef) { + registerInstance(this, hostRef) + this.balFocus = createEvent(this, 'balFocus', 7) + this.balBlur = createEvent(this, 'balBlur', 7) + this.balChange = createEvent(this, 'balChange', 7) + this.inputId = `bal-cb-${checkboxIds++}` + this.inheritedAttributes = {} + this.keyboardMode = true + this.initialValue = false + this.onKeypress = ev => { + if (isSpaceKey(ev)) { + const element = ev.target + if (element.href) { + return + } + if (element.nodeName === 'INPUT' && !this.disabled && !this.readonly) { + this.toggleChecked() + ev.preventDefault() + } else { + stopEventBubbling(ev) + } + } + } + this.onClick = ev => { + var _a + const element = ev.target + if (element.href) { + return + } + if (this.wasFocused) { + this.focused = true + } + if (element.nodeName !== 'INPUT' && !this.disabled && !this.readonly) { + this.toggleChecked() + ;(_a = this.nativeInput) === null || _a === void 0 ? void 0 : _a.focus() + ev.preventDefault() + } else { + stopEventBubbling(ev) + } + } + this.onFocus = ev => { + if (this.disabled || this.readonly) { + this.focused = false + return stopEventBubbling(ev) + } + this.balFocus.emit(ev) + if (this.keyboardMode) { + this.focused = true + this.wasFocused = true + } + } + this.onBlur = ev => { + if (this.disabled || this.readonly) { + return stopEventBubbling(ev) + } + this.balBlur.emit(ev) + this.focused = false + } + this.onPointerDown = () => (this.keyboardMode = false) + this.onKeydown = ev => { + if (!isSpaceKey(ev)) { + this.wasFocused = false + } + this.keyboardMode = FOCUS_KEYS.includes(ev.key) + } + this.hasLabel = true + this.focused = false + this.buttonTabindex = undefined + this.ariaForm = defaultBalAriaForm + this.wasFocused = false + this.name = this.inputId + this.label = '' + this.invisible = false + this.labelHidden = false + this.flat = false + this.inline = false + this.interface = 'checkbox' + this.value = 'on' + this.checked = false + this.disabled = false + this.readonly = false + this.required = false + this.autoInvalidOff = false + this.nonSubmit = false + this.invalid = false + this.hovered = false + this.pressed = false + } + createLogger(log) { + this.log = log + } + /** + * LIFECYCLE + * ------------------------------------------------------ + */ + connectedCallback() { + const groupEl = this.group + const checkboxButton = this.checkboxButton + if (checkboxButton || groupEl) { + this.updateState() + } + if (groupEl) { + groupEl.addEventListener('balChange', () => this.updateState()) + } + this.initialValue = this.checked + this.el.addEventListener('keydown', this.onKeydown) + this.el.addEventListener('touchstart', this.onPointerDown) + this.el.addEventListener('mousedown', this.onPointerDown) + } + componentWillLoad() { + this.inheritedAttributes = inheritAttributes(this.el, ['aria-label', 'tabindex', 'title']) + } + disconnectedCallback() { + if (this.group) { + this.group.removeEventListener('balChange', () => this.updateState()) + } + this.el.removeEventListener('keydown', this.onKeydown) + this.el.removeEventListener('touchstart', this.onPointerDown) + this.el.removeEventListener('mousedown', this.onPointerDown) + } + /** + * LISTENERS + * ------------------------------------------------------ + */ + listenOnClick(ev) { + if ( + (this.disabled || this.readonly) && + ev.target && + (ev.target === this.el || isDescendant(this.el, ev.target)) + ) { + stopEventBubbling(ev) + } + } + resetHandler(ev) { + const formElement = ev.target + if (formElement === null || formElement === void 0 ? void 0 : formElement.contains(this.el)) { + this.checked = this.initialValue + } + } + /** + * PUBLIC METHODS + * ------------------------------------------------------ + */ + /** + * Sets the focus on the checkbox input element. + */ + async setFocus() { + inputSetFocus(this) + } + /** + * Sets blur on the native `input`. Use this method instead of the global + * `input.blur()`. + * @internal + */ + async setBlur() { + inputSetBlur(this) + } + /** + * Returns the native `` element used under the hood. + */ + getInputElement() { + return Promise.resolve(this.nativeInput) + } + /** + * Options of the tab like label, value etc. + */ + async getOption() { + return this.option + } + /** @internal */ + async setButtonTabindex(value) { + if (this.checkboxButton) { + this.buttonTabindex = -1 + } else { + this.buttonTabindex = value + } + } + /** + * @internal + * Options of the tab like label, value etc. + */ + async updateState() { + if (this.group && this.group.control && Array.isArray(this.group.value)) { + const newChecked = this.group.value.includes(this.value) + if (newChecked !== this.checked) { + this.checked = newChecked + } + } + if (this.checkboxButton) { + this.buttonTabindex = -1 + if (this.checkboxButton.setChecked) { + this.checkboxButton.setChecked(this.checked) + } + } + } + /** + * @internal + */ + async setAriaForm(ariaForm) { + this.ariaForm = Object.assign({}, ariaForm) + } + /** + * GETTERS + * ------------------------------------------------------ + */ + get option() { + return { + name: this.name, + value: this.value, + checked: this.checked, + label: this.label, + labelHidden: this.labelHidden, + flat: this.flat, + interface: this.interface, + disabled: this.disabled, + readonly: this.readonly, + required: this.required, + nonSubmit: this.nonSubmit, + invisible: this.invisible, + invalid: this.invalid, + } + } + get group() { + return this.el.closest('bal-checkbox-group') + } + get checkboxButton() { + return this.el.closest('bal-checkbox-button') + } + /** + * EVENT HANDLERS + * ------------------------------------------------------ + */ + toggleChecked() { + this.checked = !this.checked + this.balChange.emit(this.checked) + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + const block = BEM.block('radio-checkbox') + const inputEl = block.element('input') + const labelEl = block.element('label') + const labelTextEl = labelEl.element('text') + const focused = this.focused && this.buttonTabindex !== -1 + const inputAttributes = this.inheritedAttributes + if (this.buttonTabindex !== undefined) { + inputAttributes.tabIndex = this.buttonTabindex + } + const id = this.ariaForm.controlId || this.inputId + let labelId = this.ariaForm.labelId || null + const LabelTag = this.labelHidden ? 'span' : 'label' + const labelAttributes = {} + if (!this.labelHidden) { + labelId = `${labelId || ''} ${id}-lbl`.trim() + labelAttributes.id = `${id}-lbl` + labelAttributes.htmlFor = id + } + return hAsync( + Host, + { + 'key': '9d164faecfc67eb6fa03bd41ecfe15cfbaa09ee1', + 'aria-checked': `${this.checked}`, + 'aria-disabled': ariaBooleanToString(this.disabled), + 'aria-hidden': ariaBooleanToString(this.disabled || this.nonSubmit), + 'aria-focused': focused ? 'true' : null, + 'class': Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign({ 'bal-focused': focused }, block.class()), + block.modifier('checkbox').class(), + ), + block.modifier('select-button').class(this.interface === 'select-button'), + ), + block.modifier('switch').class(this.interface === 'switch'), + ), + block.modifier('focused').class(this.focused), + ), + block.modifier('invalid').class(this.invalid), + ), + block.modifier('checked').class(this.checked), + ), + block.modifier('invisible').class(this.invisible), + ), + block.modifier('flat').class(this.flat), + ), + block.modifier('disabled').class(this.disabled || this.readonly), + ), + block.modifier('hovered').class(this.hovered), + ), + block.modifier('pressed').class(this.pressed), + ), + block.modifier('inline').class(this.inline), + ), + 'onKeypress': this.onKeypress, + 'onClick': this.onClick, + }, + hAsync( + 'input', + Object.assign( + { + 'key': 'd670f5206055b8bcaf2d1985f5d6fb7102029449', + 'class': Object.assign( + Object.assign({}, inputEl.class()), + inputEl.modifier('select-button').class(this.interface === 'select-button'), + ), + 'data-testid': 'bal-checkbox-input', + 'type': 'checkbox', + 'id': id, + 'aria-labelledby': labelId, + 'aria-describedby': this.ariaForm.messageId, + 'aria-invalid': this.invalid === true ? 'true' : 'false', + 'aria-disabled': ariaBooleanToString(this.disabled), + 'aria-checked': `${this.checked}`, + 'aria-hidden': ariaBooleanToString(this.nonSubmit), + 'name': this.name, + 'value': this.value, + 'checked': this.checked, + 'disabled': this.disabled || this.nonSubmit, + 'readonly': this.readonly, + 'required': this.required, + 'onFocus': this.onFocus, + 'onBlur': this.onBlur, + 'ref': inputEl => (this.nativeInput = inputEl), + }, + inputAttributes, + ), + ), + !this.invisible + ? hAsync( + LabelTag, + Object.assign( + { + class: Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign(Object.assign({}, labelEl.class()), labelEl.modifier('checkbox').class()), + labelEl.modifier('checked').class(this.checked), + ), + labelEl.modifier('hidden').class(this.labelHidden), + ), + labelEl.modifier('flat').class(this.flat), + ), + labelEl.modifier('switch').class(this.interface === 'switch'), + ), + }, + labelAttributes, + { 'data-testid': 'bal-checkbox-label' }, + ), + hAsync( + 'span', + { + 'class': Object.assign( + Object.assign( + Object.assign({}, labelTextEl.class()), + labelTextEl.modifier('hidden').class(this.labelHidden), + ), + labelTextEl.modifier('flat').class(this.flat), + ), + 'data-testid': 'bal-checkbox-text', + }, + this.label, + hAsync('slot', null), + ), + ) + : '', + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalCheckboxStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-checkbox', + $members$: { + name: [1], + label: [1], + invisible: [4], + labelHidden: [4, 'label-hidden'], + flat: [4], + inline: [4], + interface: [1], + value: [8], + checked: [1028], + disabled: [4], + readonly: [4], + required: [4], + autoInvalidOff: [516, 'auto-invalid-off'], + nonSubmit: [4, 'non-submit'], + invalid: [4], + hovered: [4], + pressed: [4], + hasLabel: [32], + focused: [32], + buttonTabindex: [32], + ariaForm: [32], + wasFocused: [32], + setFocus: [64], + setBlur: [64], + getInputElement: [64], + getOption: [64], + setButtonTabindex: [64], + updateState: [64], + setAriaForm: [64], + }, + $listeners$: [ + [6, 'click', 'listenOnClick'], + [6, 'reset', 'resetHandler'], + ], + $lazyBundleId$: '-', + $attrsToReflect$: [['autoInvalidOff', 'auto-invalid-off']], + } + } + } + __decorate( + [ + Logger('bal-checkbox'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + Checkbox.prototype, + 'createLogger', + null, + ) + let checkboxIds = 0 + + class BalElementStateListener extends ListenerAbstract { + constructor() { + super(...arguments) + this.state = BalElementStateListener.DefaultState + this.onMouseEnter = () => { + this.updateState({ hovered: true }) + } + this.onMouseLeave = () => { + this.updateState({ hovered: false }) + } + this.onPointerDown = () => { + this.updateState({ pressed: true }) + } + this.onPointerUp = () => { + this.updateState({ pressed: false }) + } + } + connect(el) { + super.connect(el) + addEventListener(this.el, 'mouseenter', this.onMouseEnter, BalElementStateListener.EventListenerOptions) + addEventListener(this.el, 'mouseleave', this.onMouseLeave, BalElementStateListener.EventListenerOptions) + addEventListener(this.el, 'pointerdown', this.onPointerDown, BalElementStateListener.EventListenerOptions) + if (balBrowser.hasDocument) { + addEventListener(document, 'pointerup', this.onPointerUp, BalElementStateListener.EventListenerOptions) + } + } + disconnect() { + super.disconnect() + if (this.el) { + removeEventListener(this.el, 'mouseenter', this.onMouseEnter) + removeEventListener(this.el, 'mouseleave', this.onMouseLeave) + removeEventListener(this.el, 'pointerdown', this.onPointerDown) + if (balBrowser.hasDocument) { + removeEventListener(document, 'pointerup', this.onPointerUp) + } + } + } + updateState(newState) { + this.state = Object.assign(Object.assign({}, this.state), newState) + this.notify(this.state) + } + } + BalElementStateListener.EventListenerOptions = { + passive: true, + } + BalElementStateListener.DefaultState = { + hovered: false, + pressed: false, + } + + class BalElementStateSubject extends SingleSubject { + constructor() { + super((observer, data) => { + if (data) { + observer.elementStateListener(data) + } + }) + this.listener = new BalElementStateListener() + } + attach(observer) { + super.attach(observer) + this.listener.connect(observer.el) + this.listener.add(info => super.notify(info)) + } + detach() { + super.detach() + this.listener.disconnect() + } + } + + function ListenToElementStates() { + return function (target, _propertyKey, _descriptor) { + const { connectedCallback, disconnectedCallback } = target + target.connectedCallback = function () { + if (!this._balElementStateSubject) { + this._balElementStateSubject = new BalElementStateSubject() + this._balElementStateSubject.attach(this) + } + return connectedCallback && connectedCallback.call(this) + } + target.disconnectedCallback = function () { + if (this._balElementStateSubject) { + this._balElementStateSubject.detach() + this._balElementStateSubject = undefined + } + return disconnectedCallback && disconnectedCallback.call(this) + } + } + } + + const balCheckboxButtonCss = + '@media (hover: hover)and (pointer: fine){.bal-checkbox-button__native.bal-focused{-webkit-box-shadow:var(--bal-focus-shadow) !important;box-shadow:var(--bal-focus-shadow) !important}}:root{--bal-radio-checkbox-symbol-size:1.5rem;--bal-radio-checkbox-symbol-width:calc(0.5rem - 1px);--bal-radio-checkbox-symbol-height:calc(0.875rem - 1px);--bal-radio-checkbox-symbol-left:calc(0.5rem + 1px);--bal-radio-checkbox-symbol-margin-top:0.25rem;--bal-radio-checkbox-label-min-height:1.5rem;--bal-radio-checkbox-select-button-background-hover:var(--bal-color-grey-2);--bal-radio-checkbox-select-button-background-active:var(--bal-color-grey-2);--bal-radio-checkbox-select-button-background-checked:var(--bal-color-primary);--bal-radio-checkbox-select-button-background-checked-hover:var(--bal-color-light-blue-5);--bal-radio-checkbox-select-button-background-checked-active:var(--bal-color-primary-6);--bal-radio-checkbox-select-button-background-invalid:var(--bal-color-danger-1);--bal-radio-checkbox-select-button-background-invalid-hover:var(--bal-color-danger-1);--bal-radio-checkbox-select-button-background-invalid-active:var(--bal-color-danger-1);--bal-radio-checkbox-select-button-background-invalid-checked:var(--bal-color-border-danger);--bal-radio-checkbox-select-button-background-invalid-checked-hover:var(--bal-color-danger-5);--bal-radio-checkbox-select-button-background-invalid-checked-active:var(--bal-color-danger-6);--bal-radio-checkbox-select-button-background-disabled-hover-active:var(--bal-color-grey-2);--bal-radio-checkbox-select-button-background-disabled-checked-hover-active:var(--bal-color-border-grey-dark);--bal-radio-checkbox-switch-label-background-before:var(--bal-color-primary-1);--bal-radio-checkbox-switch-label-background-after:var(--bal-color-primary);--bal-radio-checkbox-switch-label-background-hover-after:var(--bal-color-light-blue-5);--bal-radio-checkbox-switch-label-background-active-after:var(--bal-color-primary-6);--bal-radio-checkbox-switch-label-background-checked-before:var(--bal-color-success-4);--bal-radio-checkbox-switch-label-background-checked-after:var(--bal-color-white);--bal-radio-checkbox-switch-label-background-checked-hover-before:var(--bal-color-success-5);--bal-radio-checkbox-switch-label-background-checked-active-before:var(--bal-color-success-6);--bal-radio-checkbox-switch-label-background-invalid-before:var(--bal-color-danger-1);--bal-radio-checkbox-switch-label-background-invalid-after:var(--bal-color-border-danger);--bal-radio-checkbox-switch-label-background-invalid-hover-after:var(--bal-color-danger-6);--bal-radio-checkbox-switch-label-background-invalid-active-after:var(--bal-color-border-danger);--bal-radio-checkbox-switch-label-background-invalid-checked-before:var(--bal-color-danger-4);--bal-radio-checkbox-switch-label-background-invalid-checked-after:var(--bal-color-white);--bal-radio-checkbox-switch-label-background-invalid-checked-hover-before:var(--bal-color-danger-5);--bal-radio-checkbox-switch-label-background-invalid-checked-active-before:var(--bal-color-danger-6);--bal-radio-checkbox-switch-label-background-disabled-hover-active-before:var(--bal-color-grey-3);--bal-radio-checkbox-switch-label-background-disabled-hover-active-after:var(--bal-color-border-grey-dark);--bal-radio-checkbox-switch-label-background-disabled-checked-hover-active-before:var(--bal-color-border-grey-dark);--bal-radio-checkbox-switch-label-background-disabled-checked-hover-active-after:var(--bal-color-white);--bal-radio-checkbox-button-background:transparent;--bal-radio-checkbox-button-background-checked-green:var(--bal-color-green-1);--bal-radio-checkbox-button-background-checked-purple:var(--bal-color-purple-1);--bal-radio-checkbox-button-background-checked-red:var(--bal-color-red-1);--bal-radio-checkbox-button-background-checked-yellow:var(--bal-color-yellow-1);--bal-radio-checkbox-button-background-disabled:var(--bal-color-grey-1);--bal-radio-checkbox-button-background-hover:var(--bal-color-grey-1);--bal-radio-checkbox-select-button-border-color:var(--bal-color-primary);--bal-radio-checkbox-select-button-border-color-hover:var(--bal-color-light-blue-5);--bal-radio-checkbox-select-button-border-color-active:var(--bal-color-primary-6);--bal-radio-checkbox-select-button-border-color-invalid:var(--bal-color-border-danger);--bal-radio-checkbox-select-button-border-color-invalid-hover:var(--bal-color-danger-5);--bal-radio-checkbox-select-button-border-color-invalid-active:var(--bal-color-danger-6);--bal-radio-checkbox-select-button-border-color-invalid-checked:var(--bal-color-border-danger);--bal-radio-checkbox-select-button-border-color-invalid-checked-hover:var(--bal-color-danger-5);--bal-radio-checkbox-select-button-border-color-invalid-checked-active:var(--bal-color-danger-6);--bal-radio-checkbox-select-button-border-color-disabled-hover-active:var(--bal-color-border-grey-dark);--bal-radio-checkbox-select-button-border-color-disabled-checked-hover-active:var(--bal-color-border-grey-dark);--bal-radio-checkbox-button-border-color-hover:var(--bal-color-border-primary-hovered);--bal-radio-checkbox-button-border-color-active:var(--bal-color-border-primary-pressed);--bal-radio-checkbox-button-border-color-invalid-hover:var(--bal-color-border-danger-hovered);--bal-radio-checkbox-button-border-color-invalid-active:var(--bal-color-border-danger-pressed);--bal-radio-checkbox-button-border-color:var(--bal-color-border);--bal-radio-checkbox-button-border-color-checked:var(--bal-color-border-primary);--bal-radio-checkbox-button-border-color-disabled:var(--bal-color-border-grey-dark);--bal-radio-checkbox-button-border-color-invalid:var(--bal-color-border-danger)}.bal-checkbox-button{display:block;position:relative;-ms-flex:0 0 100%;flex:0 0 100%}@media screen and (min-width: 769px),print{.bal-checkbox-button--column-2{-ms-flex:0 0 calc(50% - var(--bal-space-normal)*1/2);flex:0 0 calc(50% - var(--bal-space-normal)*1/2)}.bal-checkbox-button--column-3{-ms-flex:0 0 calc(33.3333333333% - var(--bal-space-normal)*2/3);flex:0 0 calc(33.3333333333% - var(--bal-space-normal)*2/3)}.bal-checkbox-button--column-4{-ms-flex:0 0 calc(25% - var(--bal-space-normal)*3/4);flex:0 0 calc(25% - var(--bal-space-normal)*3/4)}}@media screen and (max-width: 768px){.bal-checkbox-button--column-mobile-2{-ms-flex:0 0 calc(50% - var(--bal-space-normal)*1/2);flex:0 0 calc(50% - var(--bal-space-normal)*1/2)}.bal-checkbox-button--column-mobile-3{-ms-flex:0 0 calc(33.3333333333% - var(--bal-space-normal)*2/3);flex:0 0 calc(33.3333333333% - var(--bal-space-normal)*2/3)}.bal-checkbox-button--column-mobile-4{-ms-flex:0 0 calc(25% - var(--bal-space-normal)*3/4);flex:0 0 calc(25% - var(--bal-space-normal)*3/4)}}@media screen and (min-width: 769px),print{.bal-checkbox-button--column-tablet-2{-ms-flex:0 0 calc(50% - var(--bal-space-normal)*1/2);flex:0 0 calc(50% - var(--bal-space-normal)*1/2)}.bal-checkbox-button--column-tablet-3{-ms-flex:0 0 calc(33.3333333333% - var(--bal-space-normal)*2/3);flex:0 0 calc(33.3333333333% - var(--bal-space-normal)*2/3)}.bal-checkbox-button--column-tablet-4{-ms-flex:0 0 calc(25% - var(--bal-space-normal)*3/4);flex:0 0 calc(25% - var(--bal-space-normal)*3/4)}}@media screen and (min-width: 1024px){.bal-checkbox-button--column-2{-ms-flex:0 0 calc(50% - var(--bal-space-normal)*1/2);flex:0 0 calc(50% - var(--bal-space-normal)*1/2)}.bal-checkbox-button--column-3{-ms-flex:0 0 calc(33.3333333333% - var(--bal-space-normal)*2/3);flex:0 0 calc(33.3333333333% - var(--bal-space-normal)*2/3)}.bal-checkbox-button--column-4{-ms-flex:0 0 calc(25% - var(--bal-space-normal)*3/4);flex:0 0 calc(25% - var(--bal-space-normal)*3/4)}}.bal-checkbox-button__native{display:block;width:100%;height:100%;background:var(--bal-radio-checkbox-button-background);border-style:var(--bal-form-field-control-border-style);border-radius:var(--bal-form-field-control-radius);border-width:var(--bal-form-field-control-border-width);border-color:var(--bal-radio-checkbox-button-border-color);padding:var(--bal-text-size-medium);cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.bal-checkbox-button__native--checked{border-color:var(--bal-radio-checkbox-button-border-color-checked)}.bal-checkbox-button__native--checked.bal-checkbox-button__native--color-green{background:var(--bal-radio-checkbox-button-background-checked-green)}.bal-checkbox-button__native--checked.bal-checkbox-button__native--color-purple{background:var(--bal-radio-checkbox-button-background-checked-purple)}.bal-checkbox-button__native--checked.bal-checkbox-button__native--color-red{background:var(--bal-radio-checkbox-button-background-checked-red)}.bal-checkbox-button__native--checked.bal-checkbox-button__native--color-yellow{background:var(--bal-radio-checkbox-button-background-checked-yellow)}.bal-checkbox-button__native:disabled,.bal-checkbox-button__native--disabled{background:var(--bal-radio-checkbox-button-background-disabled);border-color:var(--bal-radio-checkbox-button-border-color-disabled);cursor:default}.bal-checkbox-button__native--invalid{border-color:var(--bal-radio-checkbox-button-border-color-invalid)}@media (hover: hover)and (pointer: fine){.bal-checkbox-button__native:hover:not(:disabled):not(.bal-checkbox-button__native--colored){background:var(--bal-radio-checkbox-button-background-hover);border-color:var(--bal-radio-checkbox-button-border-color-hover)}}.bal-checkbox-button__native:active:not(:disabled){border-color:var(--bal-radio-checkbox-button-border-color-active)}@media (hover: hover)and (pointer: fine){.bal-checkbox-button__native--invalid:hover:not(:disabled){border-color:var(--bal-radio-checkbox-button-border-color-invalid-hover)}.bal-checkbox-button__native--invalid:active:not(:disabled){border-color:var(--bal-radio-checkbox-button-border-color-invalid-active)}}' + var BalCheckboxButtonStyle0 = balCheckboxButtonCss + + class CheckboxButton { + constructor(hostRef) { + registerInstance(this, hostRef) + this.balFocus = createEvent(this, 'balFocus', 7) + this.balBlur = createEvent(this, 'balBlur', 7) + this.balFormControlDidLoad = createEvent(this, 'balFormControlDidLoad', 7) + this.keyboardMode = true + /** + * EVENT BINDING + * ------------------------------------------------------ + */ + this.onClick = ev => { + if (this.disabled || this.readonly) { + return stopEventBubbling(ev) + } + const element = ev.target + if (element && element.href) { + return + } + const checkboxEl = this.el.querySelector('bal-checkbox') + const targetEl = ev.target + if (checkboxEl && targetEl) { + const isCheckbox = targetEl === checkboxEl || isDescendant(checkboxEl, targetEl) + if (!isCheckbox) { + stopEventBubbling(ev) + checkboxEl.click() + } + } + } + this.onFocus = ev => { + var _a + if (this.disabled || this.readonly) { + return stopEventBubbling(ev) + } + const checkboxEl = this.el.querySelector('bal-checkbox') + const targetEl = ev.target + if (this.keyboardMode) { + this.focused = true + } + if (checkboxEl && targetEl) { + const isCheckbox = targetEl === checkboxEl || isDescendant(checkboxEl, targetEl) + if (isCheckbox) { + stopEventBubbling(ev) + ;(_a = checkboxEl.querySelector('input')) === null || _a === void 0 ? void 0 : _a.focus() + } + } else { + this.balFocus.emit() + } + } + this.onBlur = ev => { + var _a + if (this.disabled || this.readonly) { + return stopEventBubbling(ev) + } + const checkboxEl = this.el.querySelector('bal-checkbox') + const targetEl = ev.target + this.focused = false + if (checkboxEl && targetEl) { + const isCheckbox = targetEl === checkboxEl || isDescendant(checkboxEl, targetEl) + if (isCheckbox) { + stopEventBubbling(ev) + ;(_a = checkboxEl.querySelector('input')) === null || _a === void 0 ? void 0 : _a.blur() + } + } else { + this.balBlur.emit() + } + } + this.onPointerDown = () => (this.keyboardMode = false) + this.onKeydown = ev => (this.keyboardMode = FOCUS_KEYS.includes(ev.key)) + this.interactionState = BalElementStateListener.DefaultState + this.checked = false + this.focused = false + this.invalid = undefined + this.disabled = undefined + this.readonly = undefined + this.color = undefined + this.colSize = 1 + this.colSizeTablet = 1 + this.colSizeMobile = 1 + } + createLogger(log) { + this.log = log + } + invalidHandler() { + this.updateProps('invalid', ['bal-checkbox', 'bal-icon', 'bal-label', 'bal-text']) + } + disabledHandler() { + this.updateProps('disabled', ['bal-checkbox', 'bal-icon', 'bal-label', 'bal-text']) + } + readonlyHandler() { + this.updateProps('readonly', ['bal-checkbox', 'bal-icon', 'bal-label', 'bal-text']) + } + /** + * LIFECYCLE + * ------------------------------------------------------ + */ + connectedCallback() { + this.triggerAllHandlers() + this.el.addEventListener('keydown', this.onKeydown) + this.el.addEventListener('touchstart', this.onPointerDown) + this.el.addEventListener('mousedown', this.onPointerDown) + } + componentWillLoad() { + this.triggerAllHandlers() + } + componentDidLoad() { + this.balFormControlDidLoad.emit(this.el) + } + disconnectedCallback() { + this.el.removeEventListener('keydown', this.onKeydown) + this.el.removeEventListener('touchstart', this.onPointerDown) + this.el.removeEventListener('mousedown', this.onPointerDown) + } + /** + * LISTENERS + * ------------------------------------------------------ + */ + elementStateListener(info) { + this.interactionChildElements.forEach(element => { + element.hovered = info.hovered + element.pressed = info.pressed + }) + } + /** + * PUBLIC METHODS + * ------------------------------------------------------ + */ + /** + * @internal + */ + async setChecked(checked = true) { + this.checked = checked + } + /** + * PRIVATE METHODS + * ------------------------------------------------------ + */ + get interactionChildElements() { + return Array.from(this.el.querySelectorAll('bal-label, bal-text, bal-icon, bal-checkbox')) + } + triggerAllHandlers() { + this.disabledHandler() + this.readonlyHandler() + this.invalidHandler() + } + updateProps(key, selectors) { + const value = this[key] + if (value !== undefined) { + this.notifyComponents(selectors, input => (input[key] = value)) + } + } + notifyComponents(selectors, callback) { + const components = this.el.querySelectorAll(selectors.join(', ')) + components.forEach(c => callback(c)) + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + const block = BEM.block('checkbox-button') + const disabled = !!this.disabled || !!this.readonly + const invalid = !!this.invalid + const color = !!this.color + const colored = this.checked && color + return hAsync( + Host, + { + key: '1cc87d4d87494ed93c669658d6b113ecdded148e', + class: Object.assign( + Object.assign( + Object.assign( + Object.assign({}, block.class()), + block.modifier(`column-${this.colSize}`).class(this.colSize > 1), + ), + block.modifier(`column-tablet-${this.colSizeTablet}`).class(this.colSizeTablet > 1), + ), + block.modifier(`column-mobile-${this.colSizeMobile}`).class(this.colSizeMobile > 1), + ), + onClick: this.onClick, + }, + hAsync( + 'button', + { + key: '2875aff0c5511077bbbbf697e589ca2e9cba9861', + role: 'checkbox', + class: Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign({}, block.element('native').class()), + block.element('native').modifier('disabled').class(disabled), + ), + block.element('native').modifier('invalid').class(invalid), + ), + block.element('native').modifier('checked').class(this.checked), + ), + block.element('native').modifier(`colored`).class(colored), + ), + block.element('native').modifier(`color-${this.color}`).class(color), + ), + { 'bal-focusable': !this.disabled }, + ), + disabled: disabled, + onFocus: this.onFocus, + onBlur: this.onBlur, + }, + hAsync('slot', { key: 'e83b0706ab2f9d2c8f39b15a654159448921336a' }), + ), + ) + } + get el() { + return getElement(this) + } + static get watchers() { + return { + invalid: ['invalidHandler'], + disabled: ['disabledHandler'], + readonly: ['readonlyHandler'], + } + } + static get style() { + return BalCheckboxButtonStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-checkbox-button', + $members$: { + invalid: [4], + disabled: [4], + readonly: [4], + color: [1], + colSize: [2, 'col-size'], + colSizeTablet: [2, 'col-size-tablet'], + colSizeMobile: [2, 'col-size-mobile'], + interactionState: [32], + checked: [32], + focused: [32], + setChecked: [64], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + __decorate( + [ + Logger('bal-checkbox-button'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + CheckboxButton.prototype, + 'createLogger', + null, + ) + __decorate( + [ + ListenToElementStates(), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Object]), + __metadata('design:returntype', void 0), + ], + CheckboxButton.prototype, + 'elementStateListener', + null, + ) + + class BalFocusListener extends ListenerAbstract { + constructor() { + super(...arguments) + this.onFocusin = ev => { + this.notify({ ev, isFocusIn: true, isFocusOut: false }) + } + this.onFocusout = async ev => { + await waitAfterIdleCallback() + if (balBrowser.hasDocument && this.el) { + const target = document.activeElement + if (target && !isDescendant(this.el, target)) { + this.notify({ ev, isFocusIn: false, isFocusOut: true }) + } + } + } + } + connect(el) { + super.connect(el) + if (this.el) { + addEventListener(this.el, 'focusin', this.onFocusin) + addEventListener(this.el, 'focusout', this.onFocusout) + } + } + disconnect() { + super.disconnect() + if (this.el) { + removeEventListener(this.el, 'focusin', this.onFocusin) + removeEventListener(this.el, 'focusout', this.onFocusout) + } + } + } + + class BalFocusSubject extends SingleSubject { + constructor() { + super((observer, data) => { + if (data) { + if (data.isFocusIn) { + if (observer.hasFocus === false) { + observer.focusInListener(data.ev) + } + observer.hasFocus = true + } + if (data.isFocusOut) { + observer.focusOutListener(data.ev) + observer.hasFocus = false + } + } + }) + this.listener = new BalFocusListener() + } + attach(observer) { + super.attach(observer) + this.listener.connect(observer.el) + this.listener.add(info => super.notify(info)) + } + detach() { + super.detach() + this.listener.disconnect() + } + } + + function ListenToFocus() { + return function (target, _propertyKey, _descriptor) { + const { connectedCallback, disconnectedCallback } = target + target.connectedCallback = function () { + if (!this._balFocusSubject) { + this._balFocusSubject = new BalFocusSubject() + this._balFocusSubject.attach(this) + } + return connectedCallback && connectedCallback.call(this) + } + target.disconnectedCallback = function () { + if (this._balFocusSubject) { + this._balFocusSubject.detach() + this._balFocusSubject = undefined + } + return disconnectedCallback && disconnectedCallback.call(this) + } + } + } + + class CheckboxGroup { + constructor(hostRef) { + registerInstance(this, hostRef) + this.balChange = createEvent(this, 'balChange', 7) + this.balFocus = createEvent(this, 'balFocus', 7) + this.balBlur = createEvent(this, 'balBlur', 7) + this.inputId = `bal-cg-${checkboxGroupIds++}` + this.inheritedAttributes = {} + /** + * LISTENERS + * ------------------------------------------------------ + */ + this.hasFocus = false + this.mutationObserverActive = true + /** + * EVENT BINDING + * ------------------------------------------------------ + */ + this.onClick = ev => { + if (!this.control) { + return + } + const element = ev.target + if (element.href) { + return + } + ev.preventDefault() + const selectedCheckbox = ev.target && ev.target.closest('bal-checkbox') + if (selectedCheckbox) { + if (selectedCheckbox.disabled || selectedCheckbox.readonly) { + return ev.stopPropagation() + } + } + // generate new value array out of the checked checkboxes + const newValue = [] + this.getCheckboxes().forEach(cb => { + if (cb.checked) { + newValue.push(cb.value) + } + }) + if (!areArraysEqual(this.value, newValue)) { + this.value = [...newValue] + this.balChange.emit(this.value) + } + } + this.onOptionChange = async () => { + this.sync() + } + this.ariaForm = defaultBalAriaForm + this.options = undefined + this.interface = undefined + this.control = false + this.name = this.inputId + this.vertical = false + this.verticalOnMobile = false + this.expanded = false + this.invalid = undefined + this.disabled = undefined + this.readonly = undefined + this.value = [] + this.columns = 1 + this.columnsTablet = 1 + this.columnsMobile = 1 + this.autoInvalidOff = false + } + createLogger(log) { + this.log = log + } + async optionChanged() { + if (this.control) { + this.onOptionChange() + this.mutationObserverActive = this.options === undefined + } + } + invalidChanged(value) { + if (this.control) { + if (value !== undefined) { + this.getCheckboxes().forEach(child => { + child.invalid = value + }) + this.getCheckboxButtons().forEach(child => { + child.invalid = value + }) + } + } + } + disabledChanged(value) { + if (this.control) { + if (value !== undefined) { + this.getCheckboxes().forEach(child => { + child.disabled = value + }) + this.getCheckboxButtons().forEach(child => { + child.disabled = value + }) + } + } + } + readonlyChanged(value) { + if (this.control) { + if (value !== undefined) { + this.getCheckboxes().forEach(child => { + child.readonly = value + }) + this.getCheckboxButtons().forEach(child => { + child.readonly = value + }) + } + } + } + valueChanged(_value, oldValue) { + if (this.control) { + if (!areArraysEqual(this.value, oldValue)) { + this.onOptionChange() + } + } else { + this.onOptionChange() + } + } + columnsChanged(value) { + this.getCheckboxButtons().forEach(checkboxButton => (checkboxButton.colSize = value)) + } + columnsTabletChanged(value) { + this.getCheckboxButtons().forEach(checkboxButton => (checkboxButton.colSizeTablet = value)) + } + columnsMobileChanged(value) { + this.getCheckboxButtons().forEach(checkboxButton => (checkboxButton.colSizeMobile = value)) + } + /** + * LIFECYCLE + * ------------------------------------------------------ + */ + connectedCallback() { + if (this.control) { + this.mutationObserverActive = this.options === undefined + } + } + componentWillLoad() { + if (this.control) { + this.inheritedAttributes = inheritAttributes(this.el, ['aria-label', 'tabindex', 'title']) + this.disabledChanged(this.disabled) + this.readonlyChanged(this.readonly) + } + this.columnsChanged(this.columns) + this.columnsTabletChanged(this.columnsTablet) + this.columnsMobileChanged(this.columnsMobile) + this.onOptionChange() + } + focusInListener(ev) { + this.balFocus.emit(ev) + } + focusOutListener(ev) { + this.balBlur.emit(ev) + } + mutationListener() { + if (this.control) { + this.disabledChanged(this.disabled) + this.readonlyChanged(this.readonly) + } + this.columnsChanged(this.columns) + this.columnsTabletChanged(this.columnsTablet) + this.columnsMobileChanged(this.columnsMobile) + this.onOptionChange() + } + listenOnClick(ev) { + if (this.control) { + if (isDescendant(this.el, ev.target)) { + stopEventBubbling(ev) + } + } + } + resetHandler(ev) { + const formElement = ev.target + if (formElement === null || formElement === void 0 ? void 0 : formElement.contains(this.el)) { + if (this.control) { + this.value = [] + } + this.onOptionChange() + } + } + checkboxFocusListener(ev) { + const { target } = ev + if (target && isDescendant(this.el, target) && hasTagName(target, 'bal-checkbox')) { + stopEventBubbling(ev) + } + } + checkboxBlurListener(ev) { + const { target } = ev + if (target && isDescendant(this.el, target) && hasTagName(target, 'bal-checkbox')) { + stopEventBubbling(ev) + } + } + /** + * PUBLIC METHODS + * ------------------------------------------------------ + */ + /** @internal */ + async setValue(value) { + if (this.control) { + this.value = value + } + } + /** + * Find the options properties by its value + */ + async getOptionByValue(value) { + const options = this.options + if (options) { + return options.find(option => option.value === value) + } + return undefined + } + /** + * @internal + */ + async setAriaForm(ariaForm) { + this.ariaForm = Object.assign({}, ariaForm) + } + /** + * PRIVATE METHODS + * ------------------------------------------------------ + */ + sync() { + if (this.control) { + const isChecked = checkbox => { + for (let index = 0; index < this.value.length; index++) { + const valueItem = this.value[index] + if (valueItem !== undefined && valueItem.toString() === checkbox.value.toString()) { + return true + } + } + return false + } + this.getCheckboxes().forEach(checkbox => { + checkbox.checked = isChecked(checkbox) + }) + } + this.getCheckboxes().forEach(checkbox => { + if (this.interface) { + checkbox.interface = this.interface + } + }) + } + /** + * GETTERS + * ------------------------------------------------------ + */ + getCheckboxes() { + return Array.from(this.el.querySelectorAll('bal-checkbox')) + } + getCheckboxButtons() { + return Array.from(this.el.querySelectorAll('bal-checkbox-button')) + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + const block = BEM.block('radio-checkbox-group') + const innerEl = block.element('inner') + const rawOptions = this.options || [] + const options = rawOptions.map(option => { + if (typeof option.html === 'function') { + return Object.assign(Object.assign({}, option), { html: option.html() }) + } + return option + }) + return hAsync( + Host, + Object.assign( + { + 'class': Object.assign({}, block.class()), + 'role': 'group', + 'aria-disabled': this.disabled ? 'true' : null, + 'aria-labelledby': this.ariaForm.labelId, + 'aria-describedby': this.ariaForm.messageId, + 'onClick': this.onClick, + }, + this.inheritedAttributes, + ), + hAsync( + 'div', + { + class: Object.assign( + Object.assign( + Object.assign( + Object.assign( + Object.assign({}, innerEl.class()), + innerEl.modifier('vertical-mobile').class(this.verticalOnMobile), + ), + innerEl.modifier('vertical').class(this.vertical), + ), + innerEl.modifier('expanded').class(this.expanded), + ), + innerEl.modifier('select-button').class(this.interface === 'select-button'), + ), + }, + hAsync('slot', null), + options.map(option => + hAsync('bal-checkbox', { + key: option.value, + name: option.name, + value: option.value, + labelHidden: option.labelHidden, + flat: option.flat, + interface: option.interface, + disabled: option.disabled, + readonly: option.readonly, + required: option.required, + nonSubmit: !!option.nonSubmit, + invalid: option.invalid, + innerHTML: option.html, + }), + ), + ), + ) + } + get el() { + return getElement(this) + } + static get watchers() { + return { + options: ['optionChanged'], + invalid: ['invalidChanged'], + disabled: ['disabledChanged'], + readonly: ['readonlyChanged'], + value: ['valueChanged'], + columns: ['columnsChanged'], + columnsTablet: ['columnsTabletChanged'], + columnsMobile: ['columnsMobileChanged'], + } + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-checkbox-group', + $members$: { + options: [16], + interface: [1], + control: [4], + name: [1], + vertical: [4], + verticalOnMobile: [4, 'vertical-on-mobile'], + expanded: [4], + invalid: [4], + disabled: [4], + readonly: [4], + value: [1040], + columns: [2], + columnsTablet: [2, 'columns-tablet'], + columnsMobile: [2, 'columns-mobile'], + autoInvalidOff: [516, 'auto-invalid-off'], + ariaForm: [32], + setValue: [64], + getOptionByValue: [64], + setAriaForm: [64], + }, + $listeners$: [ + [6, 'balChange', 'listenOnClick'], + [6, 'reset', 'resetHandler'], + [6, 'balFocus', 'checkboxFocusListener'], + [6, 'balBlur', 'checkboxBlurListener'], + ], + $lazyBundleId$: '-', + $attrsToReflect$: [['autoInvalidOff', 'auto-invalid-off']], + } + } + } + __decorate( + [ + Logger('bal-checkbox-group'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + CheckboxGroup.prototype, + 'createLogger', + null, + ) + __decorate( + [ + ListenToFocus(), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Object]), + __metadata('design:returntype', void 0), + ], + CheckboxGroup.prototype, + 'focusInListener', + null, + ) + __decorate( + [ + ListenToFocus(), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Object]), + __metadata('design:returntype', void 0), + ], + CheckboxGroup.prototype, + 'focusOutListener', + null, + ) + __decorate( + [ + ListenToMutation({ tags: ['bal-checkbox-group', 'bal-checkbox'], attributes: false, characterData: false }), + __metadata('design:type', Function), + __metadata('design:paramtypes', []), + __metadata('design:returntype', void 0), + ], + CheckboxGroup.prototype, + 'mutationListener', + null, + ) + let checkboxGroupIds = 0 + + const i18nBalClose = { + de: { + close: 'Schliessen', + }, + en: { + close: 'close', + }, + fr: { + close: 'Fermer', + }, + it: { + close: 'Chiudi', + }, + nl: { + close: 'Sluiten', + }, + es: { + close: 'Cerrar', + }, + pl: { + close: 'Zamknij', + }, + pt: { + close: 'Fechar', + }, + sv: { + close: 'Stäng', + }, + fi: { + close: 'Sulje', + }, + } + + const balCloseCss = + '@media (hover: hover)and (pointer: fine){.bal-close__button--inverted:focus-visible:not(:active),.bal-close__button:focus-visible:not(:active){-webkit-box-shadow:var(--bal-focus-shadow) !important;box-shadow:var(--bal-focus-shadow) !important}}:root{--bal-close-background:transparent;--bal-close-background-focus-visible:var(--bal-form-field-control-background);--bal-close-background-focus-inverted-focus-visible:var(--bal-form-field-control-background);--bal-close-border-radius:var(--bal-radius-rounded)}.bal-close{position:static;display:inline-block}.bal-close__button{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-moz-appearance:none;-webkit-appearance:none;background-color:var(--bal-close-background);border:none;border-radius:var(--bal-close-border-radius);cursor:pointer;pointer-events:auto;display:inline-block;-ms-flex-positive:0;flex-grow:0;-ms-flex-negative:0;flex-shrink:0;font-size:0;outline:none;position:relative;vertical-align:top;padding:.313rem}@media (hover: hover)and (pointer: fine){.bal-close__button:hover{background:rgba(0,7,57,.1)}}@media (hover: hover)and (pointer: fine){.bal-close__button:focus-visible:not(:active){background:var(--bal-close-background-focus-visible)}}.bal-close__button:active{background:rgba(0,7,57,.3)}@media (hover: hover)and (pointer: fine){.bal-close__button--inverted:hover{background:rgba(255,255,255,.3)}}@media (hover: hover)and (pointer: fine){.bal-close__button--inverted:focus-visible:not(:active){background:var(--bal-close-background-focus-inverted-focus-visible)}}.bal-close__button--inverted:active{background:rgba(255,255,255,.5)}.bal-close__button--size-small{padding:.25rem}.bal-close__button--size-medium{padding:.531rem}' + var BalCloseStyle0 = balCloseCss + + class Close { + constructor(hostRef) { + registerInstance(this, hostRef) + this.inheritedAttributes = {} + this.language = defaultConfig.language + this.region = defaultConfig.region + this.size = '' + this.inverted = false + } + componentWillRender() { + this.inheritedAttributes = inheritAttributes(this.el, ['tabindex']) + } + /** + * @internal define config for the component + */ + async configChanged(state) { + this.language = state.language + this.region = state.region + } + render() { + const blockEl = BEM.block('close') + const buttonEl = blockEl.element('button') + const iconEl = buttonEl.element('icon') + const label = i18nBalClose[this.language].close + return hAsync( + Host, + { key: '7c22b9ac6beeb4758c5aa9548827ccc17f4a06c0', class: Object.assign({}, blockEl.class()) }, + hAsync( + 'button', + Object.assign( + { + 'key': '270b7e767876501ea4dcb9e0c9316f33379b9633', + 'type': 'button', + 'aria-label': label, + 'title': label, + 'tabindex': '0', + 'class': Object.assign( + Object.assign( + Object.assign({}, buttonEl.class()), + buttonEl.modifier('inverted').class(this.inverted), + ), + buttonEl.modifier(`size-${this.size}`).class(this.size !== ''), + ), + 'data-testid': 'bal-close', + }, + this.inheritedAttributes, + ), + hAsync('bal-icon', { + key: '858caeaac1d2ecdff7e335b3b4eb7953a5c9ae97', + name: 'close', + size: this.size === 'small' ? 'x-small' : this.size === 'medium' ? 'medium' : 'small', + inverted: this.inverted, + class: Object.assign({}, iconEl.class()), + }), + ), + ) + } + get el() { + return getElement(this) + } + static get style() { + return BalCloseStyle0 + } + static get cmpMeta() { + return { + $flags$: 0, + $tagName$: 'bal-close', + $members$: { + size: [1], + inverted: [4], + language: [32], + region: [32], + configChanged: [64], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + __decorate( + [ + ListenToConfig(), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Object]), + __metadata('design:returntype', Promise), + ], + Close.prototype, + 'configChanged', + null, + ) + + const balContentCss = + '.bal-content{display:-ms-flexbox;display:flex;-ms-flex:1;flex:1;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:start;align-items:flex-start;text-align:left;gap:.25rem}.bal-content--align-center{-ms-flex-align:center;align-items:center;text-align:center}.bal-content--align-end{-ms-flex-align:end;align-items:flex-end;text-align:right}.bal-content--layout-horizontal{-ms-flex-direction:row;flex-direction:row}.bal-content--layout-vertical{-ms-flex-direction:column;flex-direction:column}.bal-content--space-xx-small{gap:.25rem}.bal-content--space-x-small{gap:.5rem}.bal-content--space-small{gap:.75rem}.bal-content--space-normal{gap:1rem}.bal-content>.bal-text{margin:0}' + var BalContentStyle0 = balContentCss + + class Content { + constructor(hostRef) { + registerInstance(this, hostRef) + this.layout = 'vertical' + this.align = 'start' + this.space = 'xx-small' + this.direction = '' + this.alignment = '' + } + createLogger(log) { + this.log = log + } + /** + * RENDER + * ------------------------------------------------------ + */ + render() { + const block = BEM.block('content') + const direction = !!this.direction + const layout = !!this.layout + const alignment = !!this.alignment + const align = !!this.align + const space = !!this.space + let layoutValue = this.layout + if (direction) { + layoutValue = this.direction === 'row' ? 'horizontal' : 'vertical' + } + let alignValue = this.align.split(' ').join('-') + if (alignment) { + alignValue = this.alignment.split(' ').join('-') + } + return hAsync( + Host, + { + key: 'f5838f89492ab4147c9654d4490780ac55f64437', + class: Object.assign( + Object.assign( + Object.assign( + Object.assign({}, block.class()), + block.modifier(`layout-${layoutValue}`).class(layout || direction), + ), + block.modifier(`align-${alignValue}`).class(align || alignment), + ), + block.modifier(`space-${this.space}`).class(space), + ), + }, + hAsync('slot', { key: '07907466799f1bc60d530215fd92b7e2c2636e6f' }), + ) + } + static get style() { + return BalContentStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-content', + $members$: { + layout: [1], + align: [1], + space: [1], + direction: [1], + alignment: [1], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + __decorate( + [ + Logger('bal-content'), + __metadata('design:type', Function), + __metadata('design:paramtypes', [Function]), + __metadata('design:returntype', void 0), + ], + Content.prototype, + 'createLogger', + null, + ) + + const balDataCss = + ':root{--bal-data-item-border-color:var(--bal-color-grey-2);--bal-data-item-border-style:solid;--bal-data-item-border-width:var(--bal-border-width-normal);--bal-data-horizontal-border-bottom-width:var(--bal-border-width-normal);--bal-data-horizontal-border-color:var(--bal-color-primary-2);--bal-data-item-border-bottom:none;--bal-data-item-text-color-disabled:var(--bal-color-text-grey-dark);--bal-data-label-text-color:var(--bal-color-text-primary)}.bal-data{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;max-width:100%;width:100%;outline:none;text-decoration:none;overflow-wrap:break-word;white-space:normal}.bal-data>*{display:-ms-flexbox;display:flex;-ms-flex:1 1;flex:1 1;-ms-flex-wrap:wrap;flex-wrap:wrap}.bal-data-item{display:-ms-flexbox;display:flex;-ms-flex:1 1;flex:1 1;min-height:3rem;-ms-flex-pack:start;justify-content:flex-start;-ms-flex-align:center;align-items:center;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:1rem 0}.bal-data-item.is-disabled .bal-data-label,.bal-data-item.is-disabled .bal-data-value{color:var(--bal-data-item-text-color-disabled)}.bal-data-item--has-border{border-bottom:var(--bal-data-item-border-width) var(--bal-data-item-border-style) var(--bal-data-item-border-color)}.bal-data-label{position:relative;display:block;color:var(--bal-data-label-text-color);-ms-flex:1 1;flex:1 1;-ms-flex-preferred-size:100%;flex-basis:100%;font-family:var(--bal-font-family-text);font-weight:var(--bal-font-weight-bold);font-size:var(--bal-text-size-small);line-height:var(--bal-text-size-normal);-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto}.bal-data-label .bal-hint{margin-left:.5rem;position:absolute;top:-3px;font-weight:var(--bal-font-weight-regular)}.bal-data-value{display:block;-ms-flex:1 1;flex:1 1;-ms-flex-preferred-size:100%;flex-basis:100%;margin-top:.25rem;min-height:1.5rem;overflow:visible !important;font-family:var(--bal-font-family-text);font-weight:var(--bal-font-weight-bold);font-size:var(--bal-text-size-small);line-height:var(--bal-text-size-normal)}.bal-data-value,.bal-data-value>div{font-family:var(--bal-font-family-text);font-weight:var(--bal-font-weight-regular);font-size:var(--bal-text-size-normal);line-height:1.25rem;-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;padding-bottom:2px}.bal-data-value>ul,.bal-data-value>div>ul{margin-bottom:0 !important;margin-left:1.5rem !important}.bal-data-value .bal-button{display:none}.bal-data-value--is-multiline,.bal-data-value--is-multiline>div{white-space:normal}.bal-data:not(.bal-data--is-horizontal) .bal-data-value{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.bal-data:not(.bal-data--is-horizontal) .bal-data-value>div{-ms-flex:1;flex:1}.bal-data:not(.bal-data--is-horizontal) .bal-data-value>div>bal-input input.input{-ms-flex:1;flex:1}.bal-data:not(.bal-data--is-horizontal) .bal-data-value--is-editable .bal-data-value__button{display:block}.bal-data:not(.bal-data--is-horizontal) .bal-data-value>bal-button{margin-left:.5rem}@media screen and (min-width: 769px),print{.bal-data>*{-ms-flex-wrap:no-wrap;flex-wrap:no-wrap}.bal-data .bal-data-item{-ms-flex-wrap:no-wrap;flex-wrap:no-wrap;padding:.5rem 0}.bal-data .bal-data-item .bal-data-label{-ms-flex-preferred-size:0;flex-basis:0}.bal-data .bal-data-item .bal-data-value{-ms-flex-preferred-size:0;flex-basis:0}.bal-data:not(.bal-data--is-horizontal) .bal-data-label{font-size:var(--bal-text-size-normal)}.bal-data:not(.bal-data--is-horizontal) .bal-data-value{margin-top:2px}.bal-data.bal-data--is-horizontal{-ms-flex-direction:row;flex-direction:row;gap:.5rem}.bal-data.bal-data--is-horizontal.has-border{border-bottom:var(--bal-data-horizontal-border-bottom-width) var(--bal-data-item-border-style) var(--bal-data-horizontal-border-color)}.bal-data.bal-data--is-horizontal>*{-ms-flex-wrap:wrap;flex-wrap:wrap}.bal-data.bal-data--is-horizontal .bal-data-item{-ms-flex-wrap:wrap;flex-wrap:wrap;min-width:5rem;-ms-flex-align:start;align-items:flex-start;border-bottom:var(--bal-data-item-border-bottom)}.bal-data.bal-data--is-horizontal .bal-data-item .bal-data-value{min-height:100%}.bal-data.bal-data--is-horizontal .bal-data-item .bal-data-label,.bal-data.bal-data--is-horizontal .bal-data-item .bal-data-value{-ms-flex-preferred-size:100%;flex-basis:100%;width:100%;-ms-flex-item-align:start;align-self:flex-start}}' + var BalDataStyle0 = balDataCss + + class Data { + constructor(hostRef) { + registerInstance(this, hostRef) + this.inputElements = ['bal-data-item'] + this.border = false + this.horizontal = false + } + borderHandler() { + this.updateProps([...this.inputElements], 'border') + } + updateProps(selectors, key) { + const value = this[key] + if (value !== undefined) { + this.notifyComponents(selectors, input => (input[key] = value)) + } + } + notifyComponents(selectors, callback) { + const components = this.element.querySelectorAll(selectors.join(', ')) + components.forEach(c => callback(c)) + } + componentWillLoad() { + this.borderHandler() + } + render() { + const block = BEM.block('data') + return hAsync( + Host, + { + key: '864257bdb7de053ad8905c5ed5bd0b2bb9dd5793', + class: Object.assign( + Object.assign(Object.assign({}, block.class()), block.modifier('has-border').class(this.border)), + block.modifier('is-horizontal').class(this.horizontal), + ), + }, + hAsync('slot', { key: '2480dde04221d364d9a6f16a3469d6238762bf86' }), + ) + } + get element() { + return getElement(this) + } + static get watchers() { + return { + border: ['borderHandler'], + } + } + static get style() { + return BalDataStyle0 + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-data', + $members$: { + border: [4], + horizontal: [4], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + class DataItem { + constructor(hostRef) { + registerInstance(this, hostRef) + this.disabled = false + this.border = false + } + render() { + const element = BEM.block('data-item') + return hAsync( + Host, + { + key: 'a2c7f920fdafc6672964f3a34785f9e1bf10f7e3', + class: Object.assign( + Object.assign(Object.assign({}, element.class()), element.modifier('is-disabled').class(this.disabled)), + element.modifier('has-border').class(this.border), + ), + }, + hAsync('slot', { key: 'e34d2d90b08bd824b54cd636beee7702c2e57192' }), + ) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-data-item', + $members$: { + disabled: [4], + border: [4], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + class DataLabel { + constructor(hostRef) { + registerInstance(this, hostRef) + this.required = false + } + render() { + return hAsync( + Host, + { + key: '1c156284930b724997e295912bfebfba138649a2', + class: Object.assign({}, BEM.block('data-label').class()), + }, + hAsync('slot', { key: 'b39c528fb8f45324a056c9b7305bb4ce8fea47c6' }), + this.required ? '*' : '', + ) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-data-label', + $members$: { + required: [4], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + class DataValue { + constructor(hostRef) { + registerInstance(this, hostRef) + this.balClick = createEvent(this, 'balClick', 7) + this.balFocus = createEvent(this, 'balFocus', 7) + this.balBlur = createEvent(this, 'balBlur', 7) + this.onClickHandler = ev => { + const input = this.el.querySelector('bal-input') + if (!lodash_isnil(input)) { + input.setFocus() + } + this.balClick.emit(ev) + } + this.editable = false + this.disabled = false + this.multiline = false + } + render() { + const block = BEM.block('data-value') + const buttonEl = block.element('button') + return hAsync( + Host, + { + key: 'a3694b08f08f4bfd2a6de223ae7c27453cdc7f02', + class: Object.assign( + Object.assign(Object.assign({}, block.class()), block.modifier('is-editable').class(this.editable)), + block.modifier('is-multiline').class(this.multiline), + ), + }, + hAsync( + 'div', + { key: 'f26f3535658c7a2aacd45b71d0c7feab05703bbb' }, + hAsync('slot', { key: 'd2b482f904a0312555cc24cc22db7126e1b8da6c' }), + ), + hAsync('bal-button', { + 'key': 'c3357978fa4d4fdbc65825e8dd0d87d3b22af10b', + 'class': Object.assign({}, buttonEl.class()), + 'data-testid': 'bal-data-value-button', + 'square': true, + 'outlined': true, + 'color': 'text', + 'size': 'small', + 'icon': 'edit', + 'disabled': this.disabled, + 'onBalBlur': _ => this.balBlur.emit(), + 'onBalFocus': _ => this.balFocus.emit(), + 'onClick': ev => this.onClickHandler(ev), + }), + ) + } + get el() { + return getElement(this) + } + static get cmpMeta() { + return { + $flags$: 4, + $tagName$: 'bal-data-value', + $members$: { + editable: [4], + disabled: [4], + multiline: [4], + }, + $listeners$: undefined, + $lazyBundleId$: '-', + $attrsToReflect$: [], + } + } + } + + /** + * Custom positioning reference element. + * @see https://floating-ui.com/docs/virtual-elements + */ + const min$1 = Math.min + const max$1 = Math.max + const round$2 = Math.round + const floor = Math.floor + const createCoords = v => ({ + x: v, + y: v, + }) + const oppositeSideMap = { + left: 'right', + right: 'left', + bottom: 'top', + top: 'bottom', + } + const oppositeAlignmentMap = { + start: 'end', + end: 'start', + } + function clamp(start, value, end) { + return max$1(start, min$1(value, end)) + } + function evaluate(value, param) { + return typeof value === 'function' ? value(param) : value + } + function getSide(placement) { + return placement.split('-')[0] + } + function getAlignment(placement) { + return placement.split('-')[1] + } + function getOppositeAxis(axis) { + return axis === 'x' ? 'y' : 'x' + } + function getAxisLength(axis) { + return axis === 'y' ? 'height' : 'width' + } + function getSideAxis(placement) { + return ['top', 'bottom'].includes(getSide(placement)) ? 'y' : 'x' + } + function getAlignmentAxis(placement) { + return getOppositeAxis(getSideAxis(placement)) + } + function getAlignmentSides(placement, rects, rtl) { + if (rtl === void 0) { + rtl = false + } + const alignment = getAlignment(placement) + const alignmentAxis = getAlignmentAxis(placement) + const length = getAxisLength(alignmentAxis) + let mainAlignmentSide = + alignmentAxis === 'x' + ? alignment === (rtl ? 'end' : 'start') + ? 'right' + : 'left' + : alignment === 'start' + ? 'bottom' + : 'top' + if (rects.reference[length] > rects.floating[length]) { + mainAlignmentSide = getOppositePlacement$1(mainAlignmentSide) + } + return [mainAlignmentSide, getOppositePlacement$1(mainAlignmentSide)] + } + function getExpandedPlacements(placement) { + const oppositePlacement = getOppositePlacement$1(placement) + return [ + getOppositeAlignmentPlacement(placement), + oppositePlacement, + getOppositeAlignmentPlacement(oppositePlacement), + ] + } + function getOppositeAlignmentPlacement(placement) { + return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]) + } + function getSideList(side, isStart, rtl) { + const lr = ['left', 'right'] + const rl = ['right', 'left'] + const tb = ['top', 'bottom'] + const bt = ['bottom', 'top'] + switch (side) { + case 'top': + case 'bottom': + if (rtl) return isStart ? rl : lr + return isStart ? lr : rl + case 'left': + case 'right': + return isStart ? tb : bt + default: + return [] + } + } + function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { + const alignment = getAlignment(placement) + let list = getSideList(getSide(placement), direction === 'start', rtl) + if (alignment) { + list = list.map(side => side + '-' + alignment) + if (flipAlignment) { + list = list.concat(list.map(getOppositeAlignmentPlacement)) + } + } + return list + } + function getOppositePlacement$1(placement) { + return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]) + } + function expandPaddingObject(padding) { + return { + top: 0, + right: 0, + bottom: 0, + left: 0, + ...padding, + } + } + function getPaddingObject(padding) { + return typeof padding !== 'number' + ? expandPaddingObject(padding) + : { + top: padding, + right: padding, + bottom: padding, + left: padding, + } + } + function rectToClientRect$1(rect) { + return { + ...rect, + top: rect.y, + left: rect.x, + right: rect.x + rect.width, + bottom: rect.y + rect.height, + } + } + + function computeCoordsFromPlacement(_ref, placement, rtl) { + let { reference, floating } = _ref + const sideAxis = getSideAxis(placement) + const alignmentAxis = getAlignmentAxis(placement) + const alignLength = getAxisLength(alignmentAxis) + const side = getSide(placement) + const isVertical = sideAxis === 'y' + const commonX = reference.x + reference.width / 2 - floating.width / 2 + const commonY = reference.y + reference.height / 2 - floating.height / 2 + const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2 + let coords + switch (side) { + case 'top': + coords = { + x: commonX, + y: reference.y - floating.height, + } + break + case 'bottom': + coords = { + x: commonX, + y: reference.y + reference.height, + } + break + case 'right': + coords = { + x: reference.x + reference.width, + y: commonY, + } + break + case 'left': + coords = { + x: reference.x - floating.width, + y: commonY, + } + break + default: + coords = { + x: reference.x, + y: reference.y, + } + } + switch (getAlignment(placement)) { + case 'start': + coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1) + break + case 'end': + coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1) + break + } + return coords + } + + /** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a given reference element. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ + const computePosition$1 = async (reference, floating, config) => { + const { placement = 'bottom', strategy = 'absolute', middleware = [], platform } = config + const validMiddleware = middleware.filter(Boolean) + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)) + let rects = await platform.getElementRects({ + reference, + floating, + strategy, + }) + let { x, y } = computeCoordsFromPlacement(rects, placement, rtl) + let statefulPlacement = placement + let middlewareData = {} + let resetCount = 0 + for (let i = 0; i < validMiddleware.length; i++) { + const { name, fn } = validMiddleware[i] + const { + x: nextX, + y: nextY, + data, + reset, + } = await fn({ + x, + y, + initialPlacement: placement, + placement: statefulPlacement, + strategy, + middlewareData, + rects, + platform, + elements: { + reference, + floating, + }, + }) + x = nextX != null ? nextX : x + y = nextY != null ? nextY : y + middlewareData = { + ...middlewareData, + [name]: { + ...middlewareData[name], + ...data, + }, + } + if (reset && resetCount <= 50) { + resetCount++ + if (typeof reset === 'object') { + if (reset.placement) { + statefulPlacement = reset.placement + } + if (reset.rects) { + rects = + reset.rects === true + ? await platform.getElementRects({ + reference, + floating, + strategy, + }) + : reset.rects + } + ;({ x, y } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)) + } + i = -1 + } + } + return { + x, + y, + placement: statefulPlacement, + strategy, + middlewareData, + } + } + + /** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ + async function detectOverflow$1(state, options) { + var _await$platform$isEle + if (options === void 0) { + options = {} + } + const { x, y, platform, rects, elements, strategy } = state + const { + boundary = 'clippingAncestors', + rootBoundary = 'viewport', + elementContext = 'floating', + altBoundary = false, + padding = 0, + } = evaluate(options, state) + const paddingObject = getPaddingObject(padding) + const altContext = elementContext === 'floating' ? 'reference' : 'floating' + const element = elements[altBoundary ? altContext : elementContext] + const clippingClientRect = rectToClientRect$1( + await platform.getClippingRect({ + element: ( + (_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null + ? _await$platform$isEle + : true + ) + ? element + : element.contextElement || + (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), + boundary, + rootBoundary, + strategy, + }), + ) + const rect = + elementContext === 'floating' + ? { + ...rects.floating, + x, + y, + } + : rects.reference + const offsetParent = await (platform.getOffsetParent == null + ? void 0 + : platform.getOffsetParent(elements.floating)) + const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) + ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { + x: 1, + y: 1, + } + : { + x: 1, + y: 1, + } + const elementClientRect = rectToClientRect$1( + platform.convertOffsetParentRelativeRectToViewportRelativeRect + ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ + elements, + rect, + offsetParent, + strategy, + }) + : rect, + ) + return { + top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, + bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, + left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, + right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x, + } + } + + /** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ + const arrow$3 = options => ({ + name: 'arrow', + options, + async fn(state) { + const { x, y, placement, rects, platform, elements, middlewareData } = state + // Since `element` is required, we don't Partial<> the type. + const { element, padding = 0 } = evaluate(options, state) || {} + if (element == null) { + return {} + } + const paddingObject = getPaddingObject(padding) + const coords = { + x, + y, + } + const axis = getAlignmentAxis(placement) + const length = getAxisLength(axis) + const arrowDimensions = await platform.getDimensions(element) + const isYAxis = axis === 'y' + const minProp = isYAxis ? 'top' : 'left' + const maxProp = isYAxis ? 'bottom' : 'right' + const clientProp = isYAxis ? 'clientHeight' : 'clientWidth' + const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length] + const startDiff = coords[axis] - rects.reference[axis] + const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)) + let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0 + + // DOM platform can return `window` as the `offsetParent`. + if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { + clientSize = elements.floating[clientProp] || rects.floating[length] + } + const centerToReference = endDiff / 2 - startDiff / 2 + + // If the padding is large enough that it causes the arrow to no longer be + // centered, modify the padding so that it is centered. + const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1 + const minPadding = min$1(paddingObject[minProp], largestPossiblePadding) + const maxPadding = min$1(paddingObject[maxProp], largestPossiblePadding) + + // Make sure the arrow doesn't overflow the floating element if the center + // point is outside the floating element's bounds. + const min$1$1 = minPadding + const max = clientSize - arrowDimensions[length] - maxPadding + const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference + const offset = clamp(min$1$1, center, max) + + // If the reference is small enough that the arrow's padding causes it to + // to point to nothing for an aligned placement, adjust the offset of the + // floating element itself. To ensure `shift()` continues to take action, + // a single reset is performed when this is true. + const shouldAddOffset = + !middlewareData.arrow && + getAlignment(placement) != null && + center !== offset && + rects.reference[length] / 2 - (center < min$1$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0 + const alignmentOffset = shouldAddOffset ? (center < min$1$1 ? center - min$1$1 : center - max) : 0 + return { + [axis]: coords[axis] + alignmentOffset, + data: { + [axis]: offset, + centerOffset: center - offset - alignmentOffset, + ...(shouldAddOffset && { + alignmentOffset, + }), + }, + reset: shouldAddOffset, + } + }, + }) + + /** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ + const flip$3 = function (options) { + if (options === void 0) { + options = {} + } + return { + name: 'flip', + options, + async fn(state) { + var _middlewareData$arrow, _middlewareData$flip + const { placement, middlewareData, rects, initialPlacement, platform, elements } = state + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true, + fallbackPlacements: specifiedFallbackPlacements, + fallbackStrategy = 'bestFit', + fallbackAxisSideDirection = 'none', + flipAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state) + + // If a reset by the arrow was caused due to an alignment offset being + // added, we should skip any logic now since `flip()` has already done its + // work. + // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 + if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {} + } + const side = getSide(placement) + const isBasePlacement = getSide(initialPlacement) === initialPlacement + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)) + const fallbackPlacements = + specifiedFallbackPlacements || + (isBasePlacement || !flipAlignment + ? [getOppositePlacement$1(initialPlacement)] + : getExpandedPlacements(initialPlacement)) + if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') { + fallbackPlacements.push( + ...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl), + ) + } + const placements = [initialPlacement, ...fallbackPlacements] + const overflow = await detectOverflow$1(state, detectOverflowOptions) + const overflows = [] + let overflowsData = + ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [] + if (checkMainAxis) { + overflows.push(overflow[side]) + } + if (checkCrossAxis) { + const sides = getAlignmentSides(placement, rects, rtl) + overflows.push(overflow[sides[0]], overflow[sides[1]]) + } + overflowsData = [ + ...overflowsData, + { + placement, + overflows, + }, + ] + + // One or more sides is overflowing. + if (!overflows.every(side => side <= 0)) { + var _middlewareData$flip2, _overflowsData$filter + const nextIndex = + (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1 + const nextPlacement = placements[nextIndex] + if (nextPlacement) { + // Try next placement and re-run the lifecycle. + return { + data: { + index: nextIndex, + overflows: overflowsData, + }, + reset: { + placement: nextPlacement, + }, + } + } + + // First, find the candidates that fit on the mainAxis side of overflow, + // then find the placement that fits the best on the main crossAxis side. + let resetPlacement = + (_overflowsData$filter = overflowsData + .filter(d => d.overflows[0] <= 0) + .sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null + ? void 0 + : _overflowsData$filter.placement + + // Otherwise fallback. + if (!resetPlacement) { + switch (fallbackStrategy) { + case 'bestFit': { + var _overflowsData$map$so + const placement = + (_overflowsData$map$so = overflowsData + .map(d => [ + d.placement, + d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0), + ]) + .sort((a, b) => a[1] - b[1])[0]) == null + ? void 0 + : _overflowsData$map$so[0] + if (placement) { + resetPlacement = placement + } + break + } + case 'initialPlacement': + resetPlacement = initialPlacement + break + } + } + if (placement !== resetPlacement) { + return { + reset: { + placement: resetPlacement, + }, + } + } + } + return {} + }, + } + } + + // For type backwards-compatibility, the `OffsetOptions` type was also + // Derivable. + + async function convertValueToCoords(state, options) { + const { placement, platform, elements } = state + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)) + const side = getSide(placement) + const alignment = getAlignment(placement) + const isVertical = getSideAxis(placement) === 'y' + const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1 + const crossAxisMulti = rtl && isVertical ? -1 : 1 + const rawValue = evaluate(options, state) + let { mainAxis, crossAxis, alignmentAxis } = + typeof rawValue === 'number' + ? { + mainAxis: rawValue, + crossAxis: 0, + alignmentAxis: null, + } + : { + mainAxis: 0, + crossAxis: 0, + alignmentAxis: null, + ...rawValue, + } + if (alignment && typeof alignmentAxis === 'number') { + crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis + } + return isVertical + ? { + x: crossAxis * crossAxisMulti, + y: mainAxis * mainAxisMulti, + } + : { + x: mainAxis * mainAxisMulti, + y: crossAxis * crossAxisMulti, + } + } + + /** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ + const offset$3 = function (options) { + if (options === void 0) { + options = 0 + } + return { + name: 'offset', + options, + async fn(state) { + var _middlewareData$offse, _middlewareData$arrow + const { x, y, placement, middlewareData } = state + const diffCoords = await convertValueToCoords(state, options) + + // If the placement is the same and the arrow caused an alignment offset + // then we don't need to change the positioning coordinates. + if ( + placement === + ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && + (_middlewareData$arrow = middlewareData.arrow) != null && + _middlewareData$arrow.alignmentOffset + ) { + return {} + } + return { + x: x + diffCoords.x, + y: y + diffCoords.y, + data: { + ...diffCoords, + placement, + }, + } + }, + } + } + + /** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ + const shift$1 = function (options) { + if (options === void 0) { + options = {} + } + return { + name: 'shift', + options, + async fn(state) { + const { x, y, placement } = state + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = false, + limiter = { + fn: _ref => { + let { x, y } = _ref + return { + x, + y, + } + }, + }, + ...detectOverflowOptions + } = evaluate(options, state) + const coords = { + x, + y, + } + const overflow = await detectOverflow$1(state, detectOverflowOptions) + const crossAxis = getSideAxis(getSide(placement)) + const mainAxis = getOppositeAxis(crossAxis) + let mainAxisCoord = coords[mainAxis] + let crossAxisCoord = coords[crossAxis] + if (checkMainAxis) { + const minSide = mainAxis === 'y' ? 'top' : 'left' + const maxSide = mainAxis === 'y' ? 'bottom' : 'right' + const min = mainAxisCoord + overflow[minSide] + const max = mainAxisCoord - overflow[maxSide] + mainAxisCoord = clamp(min, mainAxisCoord, max) + } + if (checkCrossAxis) { + const minSide = crossAxis === 'y' ? 'top' : 'left' + const maxSide = crossAxis === 'y' ? 'bottom' : 'right' + const min = crossAxisCoord + overflow[minSide] + const max = crossAxisCoord - overflow[maxSide] + crossAxisCoord = clamp(min, crossAxisCoord, max) + } + const limitedCoords = limiter.fn({ + ...state, + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord, + }) + return { + ...limitedCoords, + data: { + x: limitedCoords.x - x, + y: limitedCoords.y - y, + }, + } + }, + } + } + + function getNodeName$1(node) { + if (isNode(node)) { + return (node.nodeName || '').toLowerCase() + } + // Mocked nodes in testing environments may not be instances of Node. By + // returning `#document` an infinite loop won't occur. + // https://github.com/floating-ui/floating-ui/issues/2317 + return '#document' + } + function getWindow$1(node) { + var _node$ownerDocument + return ( + (node == null || (_node$ownerDocument = node.ownerDocument) == null + ? void 0 + : _node$ownerDocument.defaultView) || window + ) + } + function getDocumentElement$1(node) { + var _ref + return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null + ? void 0 + : _ref.documentElement + } + function isNode(value) { + return value instanceof Node || value instanceof getWindow$1(value).Node + } + function isElement$1(value) { + return value instanceof Element || value instanceof getWindow$1(value).Element + } + function isHTMLElement$1(value) { + return value instanceof HTMLElement || value instanceof getWindow$1(value).HTMLElement + } + function isShadowRoot$1(value) { + // Browsers without `ShadowRoot` support. + if (typeof ShadowRoot === 'undefined') { + return false + } + return value instanceof ShadowRoot || value instanceof getWindow$1(value).ShadowRoot + } + function isOverflowElement(element) { + const { overflow, overflowX, overflowY, display } = getComputedStyle$2(element) + return ( + /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && + !['inline', 'contents'].includes(display) + ) + } + function isTableElement$1(element) { + return ['table', 'td', 'th'].includes(getNodeName$1(element)) + } + function isContainingBlock(element) { + const webkit = isWebKit() + const css = getComputedStyle$2(element) + + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + return ( + css.transform !== 'none' || + css.perspective !== 'none' || + (css.containerType ? css.containerType !== 'normal' : false) || + (!webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false)) || + (!webkit && (css.filter ? css.filter !== 'none' : false)) || + ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || + ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value)) + ) + } + function getContainingBlock$1(element) { + let currentNode = getParentNode$1(element) + while (isHTMLElement$1(currentNode) && !isLastTraversableNode(currentNode)) { + if (isContainingBlock(currentNode)) { + return currentNode + } else { + currentNode = getParentNode$1(currentNode) + } + } + return null + } + function isWebKit() { + if (typeof CSS === 'undefined' || !CSS.supports) return false + return CSS.supports('-webkit-backdrop-filter', 'none') + } + function isLastTraversableNode(node) { + return ['html', 'body', '#document'].includes(getNodeName$1(node)) + } + function getComputedStyle$2(element) { + return getWindow$1(element).getComputedStyle(element) + } + function getNodeScroll$1(element) { + if (isElement$1(element)) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop, + } + } + return { + scrollLeft: element.pageXOffset, + scrollTop: element.pageYOffset, + } + } + function getParentNode$1(node) { + if (getNodeName$1(node) === 'html') { + return node + } + const result = + // Step into the shadow DOM of the parent of a slotted node. + node.assignedSlot || + // DOM Element detected. + node.parentNode || + // ShadowRoot detected. + (isShadowRoot$1(node) && node.host) || + // Fallback. + getDocumentElement$1(node) + return isShadowRoot$1(result) ? result.host : result + } + function getNearestOverflowAncestor(node) { + const parentNode = getParentNode$1(node) + if (isLastTraversableNode(parentNode)) { + return node.ownerDocument ? node.ownerDocument.body : node.body + } + if (isHTMLElement$1(parentNode) && isOverflowElement(parentNode)) { + return parentNode + } + return getNearestOverflowAncestor(parentNode) + } + function getOverflowAncestors(node, list, traverseIframes) { + var _node$ownerDocument2 + if (list === void 0) { + list = [] + } + if (traverseIframes === void 0) { + traverseIframes = true + } + const scrollableAncestor = getNearestOverflowAncestor(node) + const isBody = + scrollableAncestor === + ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body) + const win = getWindow$1(scrollableAncestor) + if (isBody) { + return list.concat( + win, + win.visualViewport || [], + isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], + win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : [], + ) + } + return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes)) + } + + function getCssDimensions(element) { + const css = getComputedStyle$2(element) + // In testing environments, the `width` and `height` properties are empty + // strings for SVG elements, returning NaN. Fallback to `0` in this case. + let width = parseFloat(css.width) || 0 + let height = parseFloat(css.height) || 0 + const hasOffset = isHTMLElement$1(element) + const offsetWidth = hasOffset ? element.offsetWidth : width + const offsetHeight = hasOffset ? element.offsetHeight : height + const shouldFallback = round$2(width) !== offsetWidth || round$2(height) !== offsetHeight + if (shouldFallback) { + width = offsetWidth + height = offsetHeight + } + return { + width, + height, + $: shouldFallback, + } + } + + function unwrapElement(element) { + return !isElement$1(element) ? element.contextElement : element + } + + function getScale(element) { + const domElement = unwrapElement(element) + if (!isHTMLElement$1(domElement)) { + return createCoords(1) + } + const rect = domElement.getBoundingClientRect() + const { width, height, $ } = getCssDimensions(domElement) + let x = ($ ? round$2(rect.width) : rect.width) / width + let y = ($ ? round$2(rect.height) : rect.height) / height + + // 0, NaN, or Infinity should always fallback to 1. + + if (!x || !Number.isFinite(x)) { + x = 1 + } + if (!y || !Number.isFinite(y)) { + y = 1 + } + return { + x, + y, + } + } + + const noOffsets = /*#__PURE__*/ createCoords(0) + function getVisualOffsets(element) { + const win = getWindow$1(element) + if (!isWebKit() || !win.visualViewport) { + return noOffsets + } + return { + x: win.visualViewport.offsetLeft, + y: win.visualViewport.offsetTop, + } + } + function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) { + if (isFixed === void 0) { + isFixed = false + } + if (!floatingOffsetParent || (isFixed && floatingOffsetParent !== getWindow$1(element))) { + return false + } + return isFixed + } + + function getBoundingClientRect$1(element, includeScale, isFixedStrategy, offsetParent) { + if (includeScale === void 0) { + includeScale = false + } + if (isFixedStrategy === void 0) { + isFixedStrategy = false + } + const clientRect = element.getBoundingClientRect() + const domElement = unwrapElement(element) + let scale = createCoords(1) + if (includeScale) { + if (offsetParent) { + if (isElement$1(offsetParent)) { + scale = getScale(offsetParent) + } + } else { + scale = getScale(element) + } + } + const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) + ? getVisualOffsets(domElement) + : createCoords(0) + let x = (clientRect.left + visualOffsets.x) / scale.x + let y = (clientRect.top + visualOffsets.y) / scale.y + let width = clientRect.width / scale.x + let height = clientRect.height / scale.y + if (domElement) { + const win = getWindow$1(domElement) + const offsetWin = offsetParent && isElement$1(offsetParent) ? getWindow$1(offsetParent) : offsetParent + let currentWin = win + let currentIFrame = currentWin.frameElement + while (currentIFrame && offsetParent && offsetWin !== currentWin) { + const iframeScale = getScale(currentIFrame) + const iframeRect = currentIFrame.getBoundingClientRect() + const css = getComputedStyle$2(currentIFrame) + const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x + const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y + x *= iframeScale.x + y *= iframeScale.y + width *= iframeScale.x + height *= iframeScale.y + x += left + y += top + currentWin = getWindow$1(currentIFrame) + currentIFrame = currentWin.frameElement + } + } + return rectToClientRect$1({ + width, + height, + x, + y, + }) + } + + const topLayerSelectors = [':popover-open', ':modal'] + function isTopLayer(floating) { + return topLayerSelectors.some(selector => { + try { + return floating.matches(selector) + } catch (e) { + return false + } + }) + } + + function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { + let { elements, rect, offsetParent, strategy } = _ref + const isFixed = strategy === 'fixed' + const documentElement = getDocumentElement$1(offsetParent) + const topLayer = elements ? isTopLayer(elements.floating) : false + if (offsetParent === documentElement || (topLayer && isFixed)) { + return rect + } + let scroll = { + scrollLeft: 0, + scrollTop: 0, + } + let scale = createCoords(1) + const offsets = createCoords(0) + const isOffsetParentAnElement = isHTMLElement$1(offsetParent) + if (isOffsetParentAnElement || (!isOffsetParentAnElement && !isFixed)) { + if (getNodeName$1(offsetParent) !== 'body' || isOverflowElement(documentElement)) { + scroll = getNodeScroll$1(offsetParent) + } + if (isHTMLElement$1(offsetParent)) { + const offsetRect = getBoundingClientRect$1(offsetParent) + scale = getScale(offsetParent) + offsets.x = offsetRect.x + offsetParent.clientLeft + offsets.y = offsetRect.y + offsetParent.clientTop + } + } + return { + width: rect.width * scale.x, + height: rect.height * scale.y, + x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x, + y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y, + } + } + + function getClientRects(element) { + return Array.from(element.getClientRects()) + } + + function getWindowScrollBarX$1(element) { + // If has a CSS width greater than the viewport, then this will be + // incorrect for RTL. + return getBoundingClientRect$1(getDocumentElement$1(element)).left + getNodeScroll$1(element).scrollLeft + } + + // Gets the entire size of the scrollable document area, even extending outside + // of the `` and `` rect bounds if horizontally scrollable. + function getDocumentRect$1(element) { + const html = getDocumentElement$1(element) + const scroll = getNodeScroll$1(element) + const body = element.ownerDocument.body + const width = max$1(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth) + const height = max$1(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight) + let x = -scroll.scrollLeft + getWindowScrollBarX$1(element) + const y = -scroll.scrollTop + if (getComputedStyle$2(body).direction === 'rtl') { + x += max$1(html.clientWidth, body.clientWidth) - width + } + return { + width, + height, + x, + y, + } + } + + function getViewportRect$1(element, strategy) { + const win = getWindow$1(element) + const html = getDocumentElement$1(element) + const visualViewport = win.visualViewport + let width = html.clientWidth + let height = html.clientHeight + let x = 0 + let y = 0 + if (visualViewport) { + width = visualViewport.width + height = visualViewport.height + const visualViewportBased = isWebKit() + if (!visualViewportBased || (visualViewportBased && strategy === 'fixed')) { + x = visualViewport.offsetLeft + y = visualViewport.offsetTop + } + } + return { + width, + height, + x, + y, + } + } + + // Returns the inner client rect, subtracting scrollbars if present. + function getInnerBoundingClientRect$1(element, strategy) { + const clientRect = getBoundingClientRect$1(element, true, strategy === 'fixed') + const top = clientRect.top + element.clientTop + const left = clientRect.left + element.clientLeft + const scale = isHTMLElement$1(element) ? getScale(element) : createCoords(1) + const width = element.clientWidth * scale.x + const height = element.clientHeight * scale.y + const x = left * scale.x + const y = top * scale.y + return { + width, + height, + x, + y, + } + } + function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { + let rect + if (clippingAncestor === 'viewport') { + rect = getViewportRect$1(element, strategy) + } else if (clippingAncestor === 'document') { + rect = getDocumentRect$1(getDocumentElement$1(element)) + } else if (isElement$1(clippingAncestor)) { + rect = getInnerBoundingClientRect$1(clippingAncestor, strategy) + } else { + const visualOffsets = getVisualOffsets(element) + rect = { + ...clippingAncestor, + x: clippingAncestor.x - visualOffsets.x, + y: clippingAncestor.y - visualOffsets.y, + } + } + return rectToClientRect$1(rect) + } + function hasFixedPositionAncestor(element, stopNode) { + const parentNode = getParentNode$1(element) + if (parentNode === stopNode || !isElement$1(parentNode) || isLastTraversableNode(parentNode)) { + return false + } + return getComputedStyle$2(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode) + } + + // A "clipping ancestor" is an `overflow` element with the characteristic of + // clipping (or hiding) child elements. This returns all clipping ancestors + // of the given element up the tree. + function getClippingElementAncestors(element, cache) { + const cachedResult = cache.get(element) + if (cachedResult) { + return cachedResult + } + let result = getOverflowAncestors(element, [], false).filter( + el => isElement$1(el) && getNodeName$1(el) !== 'body', + ) + let currentContainingBlockComputedStyle = null + const elementIsFixed = getComputedStyle$2(element).position === 'fixed' + let currentNode = elementIsFixed ? getParentNode$1(element) : element + + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + while (isElement$1(currentNode) && !isLastTraversableNode(currentNode)) { + const computedStyle = getComputedStyle$2(currentNode) + const currentNodeIsContaining = isContainingBlock(currentNode) + if (!currentNodeIsContaining && computedStyle.position === 'fixed') { + currentContainingBlockComputedStyle = null + } + const shouldDropCurrentNode = elementIsFixed + ? !currentNodeIsContaining && !currentContainingBlockComputedStyle + : (!currentNodeIsContaining && + computedStyle.position === 'static' && + !!currentContainingBlockComputedStyle && + ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position)) || + (isOverflowElement(currentNode) && + !currentNodeIsContaining && + hasFixedPositionAncestor(element, currentNode)) + if (shouldDropCurrentNode) { + // Drop non-containing blocks. + result = result.filter(ancestor => ancestor !== currentNode) + } else { + // Record last containing block for next iteration. + currentContainingBlockComputedStyle = computedStyle + } + currentNode = getParentNode$1(currentNode) + } + cache.set(element, result) + return result + } + + // Gets the maximum area that the element is visible in due to any number of + // clipping ancestors. + function getClippingRect$1(_ref) { + let { element, boundary, rootBoundary, strategy } = _ref + const elementClippingAncestors = + boundary === 'clippingAncestors' ? getClippingElementAncestors(element, this._c) : [].concat(boundary) + const clippingAncestors = [...elementClippingAncestors, rootBoundary] + const firstClippingAncestor = clippingAncestors[0] + const clippingRect = clippingAncestors.reduce( + (accRect, clippingAncestor) => { + const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy) + accRect.top = max$1(rect.top, accRect.top) + accRect.right = min$1(rect.right, accRect.right) + accRect.bottom = min$1(rect.bottom, accRect.bottom) + accRect.left = max$1(rect.left, accRect.left) + return accRect + }, + getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy), + ) + return { + width: clippingRect.right - clippingRect.left, + height: clippingRect.bottom - clippingRect.top, + x: clippingRect.left, + y: clippingRect.top, + } + } + + function getDimensions(element) { + const { width, height } = getCssDimensions(element) + return { + width, + height, + } + } + + function getRectRelativeToOffsetParent(element, offsetParent, strategy) { + const isOffsetParentAnElement = isHTMLElement$1(offsetParent) + const documentElement = getDocumentElement$1(offsetParent) + const isFixed = strategy === 'fixed' + const rect = getBoundingClientRect$1(element, true, isFixed, offsetParent) + let scroll = { + scrollLeft: 0, + scrollTop: 0, + } + const offsets = createCoords(0) + if (isOffsetParentAnElement || (!isOffsetParentAnElement && !isFixed)) { + if (getNodeName$1(offsetParent) !== 'body' || isOverflowElement(documentElement)) { + scroll = getNodeScroll$1(offsetParent) + } + if (isOffsetParentAnElement) { + const offsetRect = getBoundingClientRect$1(offsetParent, true, isFixed, offsetParent) + offsets.x = offsetRect.x + offsetParent.clientLeft + offsets.y = offsetRect.y + offsetParent.clientTop + } else if (documentElement) { + offsets.x = getWindowScrollBarX$1(documentElement) + } + } + const x = rect.left + scroll.scrollLeft - offsets.x + const y = rect.top + scroll.scrollTop - offsets.y + return { + x, + y, + width: rect.width, + height: rect.height, + } + } + + function getTrueOffsetParent$1(element, polyfill) { + if (!isHTMLElement$1(element) || getComputedStyle$2(element).position === 'fixed') { + return null + } + if (polyfill) { + return polyfill(element) + } + return element.offsetParent + } + + // Gets the closest ancestor positioned element. Handles some edge cases, + // such as table ancestors and cross browser bugs. + function getOffsetParent$1(element, polyfill) { + const window = getWindow$1(element) + if (!isHTMLElement$1(element) || isTopLayer(element)) { + return window + } + let offsetParent = getTrueOffsetParent$1(element, polyfill) + while (offsetParent && isTableElement$1(offsetParent) && getComputedStyle$2(offsetParent).position === 'static') { + offsetParent = getTrueOffsetParent$1(offsetParent, polyfill) + } + if ( + offsetParent && + (getNodeName$1(offsetParent) === 'html' || + (getNodeName$1(offsetParent) === 'body' && + getComputedStyle$2(offsetParent).position === 'static' && + !isContainingBlock(offsetParent))) + ) { + return window + } + return offsetParent || getContainingBlock$1(element) || window + } + + const getElementRects = async function (data) { + const getOffsetParentFn = this.getOffsetParent || getOffsetParent$1 + const getDimensionsFn = this.getDimensions + return { + reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy), + floating: { + x: 0, + y: 0, + ...(await getDimensionsFn(data.floating)), + }, + } + } + + function isRTL(element) { + return getComputedStyle$2(element).direction === 'rtl' + } + + const platform = { + convertOffsetParentRelativeRectToViewportRelativeRect, + getDocumentElement: getDocumentElement$1, + getClippingRect: getClippingRect$1, + getOffsetParent: getOffsetParent$1, + getElementRects, + getClientRects, + getDimensions, + getScale, + isElement: isElement$1, + isRTL, + } + + // https://samthor.au/2021/observing-dom/ + function observeMove(element, onMove) { + let io = null + let timeoutId + const root = getDocumentElement$1(element) + function cleanup() { + var _io + clearTimeout(timeoutId) + ;(_io = io) == null || _io.disconnect() + io = null + } + function refresh(skip, threshold) { + if (skip === void 0) { + skip = false + } + if (threshold === void 0) { + threshold = 1 + } + cleanup() + const { left, top, width, height } = element.getBoundingClientRect() + if (!skip) { + onMove() + } + if (!width || !height) { + return + } + const insetTop = floor(top) + const insetRight = floor(root.clientWidth - (left + width)) + const insetBottom = floor(root.clientHeight - (top + height)) + const insetLeft = floor(left) + const rootMargin = -insetTop + 'px ' + -insetRight + 'px ' + -insetBottom + 'px ' + -insetLeft + 'px' + const options = { + rootMargin, + threshold: max$1(0, min$1(1, threshold)) || 1, + } + let isFirstUpdate = true + function handleObserve(entries) { + const ratio = entries[0].intersectionRatio + if (ratio !== threshold) { + if (!isFirstUpdate) { + return refresh() + } + if (!ratio) { + timeoutId = setTimeout(() => { + refresh(false, 1e-7) + }, 100) + } else { + refresh(false, ratio) + } + } + isFirstUpdate = false + } + + // Older browsers don't support a `document` as the root and will throw an + // error. + try { + io = new IntersectionObserver(handleObserve, { + ...options, + // Handle