@cds/core 6.4.0 → 6.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/file/file.element.js +1 -1
- package/file/file.element.js.map +1 -1
- package/icon/icon.element.scss.js +1 -1
- package/internal/motion/utils.js +1 -1
- package/internal/motion/utils.js.map +1 -1
- package/internal/utils/dom.js +1 -1
- package/internal/utils/dom.js.map +1 -1
- package/internal/utils/exists.d.ts +2 -2
- package/internal/utils/exists.js +1 -1
- package/internal/utils/exists.js.map +1 -1
- package/internal/utils/global.js +1 -1
- package/internal/utils/identity.js +1 -1
- package/internal/utils/identity.js.map +1 -1
- package/internal/utils/math.d.ts +2 -2
- package/internal/utils/math.js +1 -1
- package/internal/utils/math.js.map +1 -1
- package/internal/utils/registration.js +1 -1
- package/internal/utils/registration.js.map +1 -1
- package/package.json +2 -2
package/file/file.element.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__decorate as t}from"tslib";import{html as e}from"lit";import{I18nService as i,i18n as s,state as o}from"@cds/core/internal";import{CdsControl as n}from"@cds/core/forms";import
|
|
1
|
+
import{__decorate as t}from"tslib";import{html as e}from"lit";import{I18nService as i,i18n as s,state as o}from"@cds/core/internal";import{CdsControl as n}from"@cds/core/forms";import l from"./file.element.scss.js";class r extends n{constructor(){super(...arguments);this.i18n=i.keys.file,this.buttonLabel=this.i18n.browse,this.fixedControlWidth=!0,this.supportsPrefixSuffixActions=!1}static get styles(){return[...super.styles,l]}get inputTemplate(){return e`<div cds-layout="horizontal gap:sm align:vertical-center"><cds-button size="sm" action="outline" @click="${()=>this.label.click()}" ?disabled="${this.disabled}"><cds-icon shape="folder" aria-hidden="true"></cds-icon><span>${this.buttonLabel}</span></cds-button>${this.clearFilesControlTemplate}</div>`}get clearFilesControlTemplate(){return this.inputControl.files?.length&&!this.disabled?e`<cds-button-action shape="times" @click="${()=>this.clearFiles()}" aria-label="${this.i18n.removeFile}"></cds-button-action>`:e``}firstUpdated(t){super.firstUpdated(t),this.inputControl.addEventListener("change",(t=>{t.isTrusted&&this.updateLabelAndFocus(t.target.files)}))}clearFiles(t=!0){this.buttonLabel=this.i18n.browse,this.inputControl.value="",t&&this.inputControl.dispatchEvent&&this.inputControl.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}));const e=this.shadowRoot?.querySelector("cds-button");e&&e.focus()}updateLabelAndFocus(t){t&&t.length?this.buttonLabel=t.length>1?`${t.length} ${this.i18n.files}`:t[0].name:this.clearFiles(!1)}}t([s()],r.prototype,"i18n",void 0),t([o()],r.prototype,"buttonLabel",void 0),t([o()],r.prototype,"fixedControlWidth",void 0),t([o()],r.prototype,"supportsPrefixSuffixActions",void 0);export{r as CdsFile};
|
|
2
2
|
//# sourceMappingURL=file.element.js.map
|
package/file/file.element.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file.element.js","sources":["../../../src/file/file.element.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport { __decorate } from \"tslib\";\nimport { html } from 'lit';\nimport { state, i18n, I18nService } from '@cds/core/internal';\nimport { CdsControl } from '@cds/core/forms';\nimport styles from './file.element.scss';\n/**\n * Time Input\n *\n * ```typescript\n * import '@cds/core/file/register.js';\n * ```\n *\n * ```html\n * <cds-file>\n * <label>file</label>\n * <input type=\"file\" />\n * </cds-file>\n * ```\n *\n * @element cds-file\n * @slot - For projecting file input and label\n */\nexport class CdsFile extends CdsControl {\n constructor() {\n super(...arguments);\n this.i18n = I18nService.keys.file;\n this.buttonLabel = this.i18n.browse;\n this.fixedControlWidth = true;\n this.supportsPrefixSuffixActions = false;\n }\n static get styles() {\n return [...super.styles, styles];\n }\n get inputTemplate() {\n return html `\n <div cds-layout=\"horizontal gap:sm align:vertical-center\">\n <cds-button size=\"sm\" action=\"outline\" @click=\"${() => this.label.click()}\" ?disabled=${this.disabled}>\n <cds-icon shape=\"folder\" aria-hidden=\"true\"></cds-icon>\n <span>${this.buttonLabel}</span>\n </cds-button>\n ${this.clearFilesControlTemplate}\n </div>\n `;\n }\n get clearFilesControlTemplate() {\n return this.inputControl.files?.length && !this.disabled\n ? html `<cds-button-action\n shape=\"times\"\n @click=${() => this.clearFiles()}\n aria-label=\"${this.i18n.removeFile}\"\n ></cds-button-action>`\n : html ``;\n }\n firstUpdated(props) {\n super.firstUpdated(props);\n this.inputControl.addEventListener('change', e => {\n // NOTE: have to distinguish here being user-caused events and programmatic\n // events (e.isTrusted true/false) so that we don't fire a change event loop\n if (e.isTrusted) {\n this.updateLabelAndFocus(e.target.files);\n }\n });\n }\n /** @private */\n clearFiles(fireEvent = true) {\n this.buttonLabel = this.i18n.browse;\n this.inputControl.value = '';\n // when input is reset like this it isn't registering an onchange event\n // NOTE: tsc + karma is complaining about dispatchEvent being a method on inputControl\n if (fireEvent && this.inputControl.dispatchEvent) {\n this.inputControl.dispatchEvent(new Event('change'));\n }\n const browseButton = this.shadowRoot?.querySelector('cds-button');\n if (browseButton) {\n browseButton.focus();\n }\n }\n /** @private */\n updateLabelAndFocus(files) {\n if (files && files.length) {\n this.buttonLabel = files.length > 1 ? `${files.length} ${this.i18n.files}` : files[0].name;\n }\n else {\n this.clearFiles(false);\n }\n }\n}\n__decorate([\n i18n()\n], CdsFile.prototype, \"i18n\", void 0);\n__decorate([\n state()\n], CdsFile.prototype, \"buttonLabel\", void 0);\n__decorate([\n state()\n], CdsFile.prototype, \"fixedControlWidth\", void 0);\n__decorate([\n state()\n], CdsFile.prototype, \"supportsPrefixSuffixActions\", void 0);\n"],"names":["CdsFile","CdsControl","constructor","super","this","i18n","I18nService","keys","file","buttonLabel","browse","fixedControlWidth","supportsPrefixSuffixActions","styles","inputTemplate","html","label","click","disabled","clearFilesControlTemplate","inputControl","files","length","clearFiles","removeFile","firstUpdated","props","addEventListener","e","isTrusted","updateLabelAndFocus","target","fireEvent","value","dispatchEvent","Event","browseButton","shadowRoot","querySelector","focus","name","__decorate","prototype","state"],"mappings":"uNA2BO,MAAMA,UAAgBC,EACzBC,cACIC,oBACAC,KAAKC,KAAOC,EAAYC,KAAKC,KAC7BJ,KAAKK,YAAcL,KAAKC,KAAKK,OAC7BN,KAAKO,mBAAoB,EACzBP,KAAKQ,6BAA8B,EAE5BC,oBACP,MAAO,IAAIV,MAAMU,OAAQA,GAEzBC,oBACA,OAAOC,CAAK,4GAEqC,IAAMX,KAAKY,MAAMC,uBAAsBb,KAAKc,0EAEnFd,KAAKK,kCAEbL,KAAKe,kCAIPA,gCACA,OAAOf,KAAKgB,aAAaC,OAAOC,SAAWlB,KAAKc,SAC1CH,CAAK,4CAEA,IAAMX,KAAKmB,6BACNnB,KAAKC,KAAKmB,mCAEpBT,CAAK,GAEfU,aAAaC,GACTvB,MAAMsB,aAAaC,GACnBtB,KAAKgB,aAAaO,iBAAiB,UAAUC,IAGrCA,EAAEC,WACFzB,KAAK0B,oBAAoBF,EAAEG,OAAOV,UAK9CE,WAAWS,GAAY,GACnB5B,KAAKK,YAAcL,KAAKC,KAAKK,OAC7BN,KAAKgB,aAAaa,MAAQ,GAGtBD,GAAa5B,KAAKgB,aAAac,eAC/B9B,KAAKgB,aAAac,cAAc,IAAIC,MAAM,
|
|
1
|
+
{"version":3,"file":"file.element.js","sources":["../../../src/file/file.element.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport { __decorate } from \"tslib\";\nimport { html } from 'lit';\nimport { state, i18n, I18nService } from '@cds/core/internal';\nimport { CdsControl } from '@cds/core/forms';\nimport styles from './file.element.scss';\n/**\n * Time Input\n *\n * ```typescript\n * import '@cds/core/file/register.js';\n * ```\n *\n * ```html\n * <cds-file>\n * <label>file</label>\n * <input type=\"file\" />\n * </cds-file>\n * ```\n *\n * @element cds-file\n * @slot - For projecting file input and label\n */\nexport class CdsFile extends CdsControl {\n constructor() {\n super(...arguments);\n this.i18n = I18nService.keys.file;\n this.buttonLabel = this.i18n.browse;\n this.fixedControlWidth = true;\n this.supportsPrefixSuffixActions = false;\n }\n static get styles() {\n return [...super.styles, styles];\n }\n get inputTemplate() {\n return html `\n <div cds-layout=\"horizontal gap:sm align:vertical-center\">\n <cds-button size=\"sm\" action=\"outline\" @click=\"${() => this.label.click()}\" ?disabled=${this.disabled}>\n <cds-icon shape=\"folder\" aria-hidden=\"true\"></cds-icon>\n <span>${this.buttonLabel}</span>\n </cds-button>\n ${this.clearFilesControlTemplate}\n </div>\n `;\n }\n get clearFilesControlTemplate() {\n return this.inputControl.files?.length && !this.disabled\n ? html `<cds-button-action\n shape=\"times\"\n @click=${() => this.clearFiles()}\n aria-label=\"${this.i18n.removeFile}\"\n ></cds-button-action>`\n : html ``;\n }\n firstUpdated(props) {\n super.firstUpdated(props);\n this.inputControl.addEventListener('change', e => {\n // NOTE: have to distinguish here being user-caused events and programmatic\n // events (e.isTrusted true/false) so that we don't fire a change event loop\n if (e.isTrusted) {\n this.updateLabelAndFocus(e.target.files);\n }\n });\n }\n /** @private */\n clearFiles(fireEvent = true) {\n this.buttonLabel = this.i18n.browse;\n this.inputControl.value = '';\n // when input is reset like this it isn't registering an onchange event\n // NOTE: tsc + karma is complaining about dispatchEvent being a method on inputControl\n if (fireEvent && this.inputControl.dispatchEvent) {\n this.inputControl.dispatchEvent(new Event('change', { bubbles: true, cancelable: true }));\n }\n const browseButton = this.shadowRoot?.querySelector('cds-button');\n if (browseButton) {\n browseButton.focus();\n }\n }\n /** @private */\n updateLabelAndFocus(files) {\n if (files && files.length) {\n this.buttonLabel = files.length > 1 ? `${files.length} ${this.i18n.files}` : files[0].name;\n }\n else {\n this.clearFiles(false);\n }\n }\n}\n__decorate([\n i18n()\n], CdsFile.prototype, \"i18n\", void 0);\n__decorate([\n state()\n], CdsFile.prototype, \"buttonLabel\", void 0);\n__decorate([\n state()\n], CdsFile.prototype, \"fixedControlWidth\", void 0);\n__decorate([\n state()\n], CdsFile.prototype, \"supportsPrefixSuffixActions\", void 0);\n"],"names":["CdsFile","CdsControl","constructor","super","this","i18n","I18nService","keys","file","buttonLabel","browse","fixedControlWidth","supportsPrefixSuffixActions","styles","inputTemplate","html","label","click","disabled","clearFilesControlTemplate","inputControl","files","length","clearFiles","removeFile","firstUpdated","props","addEventListener","e","isTrusted","updateLabelAndFocus","target","fireEvent","value","dispatchEvent","Event","bubbles","cancelable","browseButton","shadowRoot","querySelector","focus","name","__decorate","prototype","state"],"mappings":"uNA2BO,MAAMA,UAAgBC,EACzBC,cACIC,oBACAC,KAAKC,KAAOC,EAAYC,KAAKC,KAC7BJ,KAAKK,YAAcL,KAAKC,KAAKK,OAC7BN,KAAKO,mBAAoB,EACzBP,KAAKQ,6BAA8B,EAE5BC,oBACP,MAAO,IAAIV,MAAMU,OAAQA,GAEzBC,oBACA,OAAOC,CAAK,4GAEqC,IAAMX,KAAKY,MAAMC,uBAAsBb,KAAKc,0EAEnFd,KAAKK,kCAEbL,KAAKe,kCAIPA,gCACA,OAAOf,KAAKgB,aAAaC,OAAOC,SAAWlB,KAAKc,SAC1CH,CAAK,4CAEA,IAAMX,KAAKmB,6BACNnB,KAAKC,KAAKmB,mCAEpBT,CAAK,GAEfU,aAAaC,GACTvB,MAAMsB,aAAaC,GACnBtB,KAAKgB,aAAaO,iBAAiB,UAAUC,IAGrCA,EAAEC,WACFzB,KAAK0B,oBAAoBF,EAAEG,OAAOV,UAK9CE,WAAWS,GAAY,GACnB5B,KAAKK,YAAcL,KAAKC,KAAKK,OAC7BN,KAAKgB,aAAaa,MAAQ,GAGtBD,GAAa5B,KAAKgB,aAAac,eAC/B9B,KAAKgB,aAAac,cAAc,IAAIC,MAAM,SAAU,CAAEC,SAAS,EAAMC,YAAY,KAErF,MAAMC,EAAelC,KAAKmC,YAAYC,cAAc,cAChDF,GACAA,EAAaG,QAIrBX,oBAAoBT,GACZA,GAASA,EAAMC,OACflB,KAAKK,YAAcY,EAAMC,OAAS,EAAI,GAAGD,EAAMC,UAAUlB,KAAKC,KAAKgB,QAAUA,EAAM,GAAGqB,KAGtFtC,KAAKmB,YAAW,IAI5BoB,EAAW,CACPtC,KACDL,EAAQ4C,UAAW,YAAQ,GAC9BD,EAAW,CACPE,KACD7C,EAAQ4C,UAAW,mBAAe,GACrCD,EAAW,CACPE,KACD7C,EAAQ4C,UAAW,yBAAqB,GAC3CD,EAAW,CACPE,KACD7C,EAAQ4C,UAAW,mCAA+B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{css as a}from"lit";var s=a`@keyframes fadeInAndOut{0%,to{opacity:0}75%{opacity:1}}:host{--color:currentColor;display:inline-block;height:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));margin:0;vertical-align:middle;fill:var(--color);color:var(--color);contain:strict;cursor:inherit}svg{display:block}:host([size*=xs]){height:var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20)))}:host([size*=sm]){height:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)))}:host([size*=md]){height:var(--cds-global-space-9,calc(24 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-9,calc(24 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-9,calc(24 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-9,calc(24 * 1rem / var(--cds-global-base,20)))}:host([size*=lg]){height:var(--cds-global-space-11,calc(36 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-11,calc(36 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-11,calc(36 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-11,calc(36 * 1rem / var(--cds-global-base,20)))}:host([size*=xl]){height:var(--cds-global-space-12,calc(48 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-12,calc(48 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-12,calc(48 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-12,calc(48 * 1rem / var(--cds-global-base,20)))}:host([size*=xxl]){height:calc(var(--cds-global-space-13,calc(64 * 1rem / var(--cds-global-base,20))) - var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20))));width:calc(var(--cds-global-space-13,calc(64 * 1rem / var(--cds-global-base,20))) - var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20))));min-height:calc(var(--cds-global-space-13,calc(64 * 1rem / var(--cds-global-base,20))) - var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20))));min-width:calc(var(--cds-global-space-13,calc(64 * 1rem / var(--cds-global-base,20))) - var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20))))}:host([size*=fit]){height:auto;width:auto;contain:layout}:host([status=success]){--color:var(--cds-alias-status-success, var(--cds-global-color-green-700, #42810e))}:host([status=danger]){--color:var(--cds-alias-status-danger, var(--cds-global-color-red-700, #e02200))}:host([status=warning]){--color:var(--cds-alias-status-warning-dark, var(--cds-global-color-ochre-800, #a36500))}:host([status=info]){--color:var(--cds-alias-status-info
|
|
1
|
+
import{css as a}from"lit";var s=a`@keyframes fadeInAndOut{0%,to{opacity:0}75%{opacity:1}}:host{--color:currentColor;display:inline-block;height:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));margin:0;vertical-align:middle;fill:var(--color);color:var(--color);contain:strict;cursor:inherit}svg{display:block}:host([size*=xs]){height:var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20)))}:host([size*=sm]){height:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-7,calc(16 * 1rem / var(--cds-global-base,20)))}:host([size*=md]){height:var(--cds-global-space-9,calc(24 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-9,calc(24 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-9,calc(24 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-9,calc(24 * 1rem / var(--cds-global-base,20)))}:host([size*=lg]){height:var(--cds-global-space-11,calc(36 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-11,calc(36 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-11,calc(36 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-11,calc(36 * 1rem / var(--cds-global-base,20)))}:host([size*=xl]){height:var(--cds-global-space-12,calc(48 * 1rem / var(--cds-global-base,20)));width:var(--cds-global-space-12,calc(48 * 1rem / var(--cds-global-base,20)));min-height:var(--cds-global-space-12,calc(48 * 1rem / var(--cds-global-base,20)));min-width:var(--cds-global-space-12,calc(48 * 1rem / var(--cds-global-base,20)))}:host([size*=xxl]){height:calc(var(--cds-global-space-13,calc(64 * 1rem / var(--cds-global-base,20))) - var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20))));width:calc(var(--cds-global-space-13,calc(64 * 1rem / var(--cds-global-base,20))) - var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20))));min-height:calc(var(--cds-global-space-13,calc(64 * 1rem / var(--cds-global-base,20))) - var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20))));min-width:calc(var(--cds-global-space-13,calc(64 * 1rem / var(--cds-global-base,20))) - var(--cds-global-space-5,calc(8 * 1rem / var(--cds-global-base,20))))}:host([size*=fit]){height:auto;width:auto;contain:layout}:host([status=success]){--color:var(--cds-alias-status-success, var(--cds-global-color-green-700, #42810e))}:host([status=danger]){--color:var(--cds-alias-status-danger, var(--cds-global-color-red-700, #e02200))}:host([status=warning]){--color:var(--cds-alias-status-warning-dark, var(--cds-global-color-ochre-800, #a36500))}:host([status=info]){--color:var(--cds-alias-status-info, var(--cds-global-color-blue-700, #0079ad))}:host([inverse]){--color:var(--cds-global-color-construction-200, #cbd4d8)}:host([direction=up]){transform:rotate(0)}:host([direction=down]){transform:rotate(180deg)}:host([direction=right]){transform:rotate(90deg)}:host([direction=left]){transform:rotate(270deg)}:host([flip=horizontal]){transform:scale(-1) rotateX(180deg)}:host([flip=vertical]){transform:scale(-1) rotateY(180deg)}.alert,.badge{fill:var(--badge-color,var(--cds-alias-status-danger,var(--cds-global-color-red-700,#e02200)))}:host([badge=success]){--badge-color:var(--cds-alias-status-success, var(--cds-global-color-green-700, #42810e))}:host([badge=danger]){--badge-color:var(--cds-alias-status-danger, var(--cds-global-color-red-700, #e02200))}:host([badge*=warning]){--badge-color:var(--cds-alias-status-warning-dark, var(--cds-global-color-ochre-800, #a36500))}:host([badge=inherit]){--badge-color:currentColor}:host([badge=info]){--badge-color:var(--cds-alias-status-info, var(--cds-global-color-blue-700, #0079ad))}:host([badge=inherit-triangle]){--badge-color:currentColor}:host([badge][inverse]){--badge-color:var(--cds-alias-status-danger, var(--cds-global-color-red-700, #e02200))}:host([badge=success][inverse]){--badge-color:var(--cds-alias-status-success, var(--cds-global-color-green-700, #42810e))}:host([badge*=warning][inverse]){--badge-color:var(--cds-alias-status-warning-dark, var(--cds-global-color-ochre-800, #a36500))}:host([badge*=inherit][inverse]){--badge-color:currentColor}:host([badge=info][inverse]){--badge-color:var(--cds-alias-status-info, var(--cds-global-color-blue-700, #0079ad))}.cds-internal-dot-1{animation:fadeInAndOut 1.8s ease-in 0s infinite}.cds-internal-dot-2{animation:fadeInAndOut 1.8s ease-out .422s infinite}.cds-internal-dot-3{animation:fadeInAndOut 1.8s ease-out .675s infinite}@media (prefers-reduced-motion){.cds-internal-dot-1,.cds-internal-dot-2,.cds-internal-dot-3{animation:none}}`;export{s as default};
|
|
2
2
|
//# sourceMappingURL=icon.element.scss.js.map
|
package/internal/motion/utils.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX as t,AnimationStatus as n,CLARITY_MOTION_REVERSE_ANIMATION_LABEL as o,CLARITY_MOTION_FALLBACK_EASING as i,CLARITY_MOTION_FALLBACK_DURATION_IN_MS as r,CLARITY_MOTION_ENTER_LEAVE_PROPERTY as e}from"./interfaces.js";import{LogService as s}from"../services/log.service.js";import{ClarityMotion as a}from"./motion.service.js";import u from"ramda/es/clone
|
|
1
|
+
import{CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX as t,AnimationStatus as n,CLARITY_MOTION_REVERSE_ANIMATION_LABEL as o,CLARITY_MOTION_FALLBACK_EASING as i,CLARITY_MOTION_FALLBACK_DURATION_IN_MS as r,CLARITY_MOTION_ENTER_LEAVE_PROPERTY as e}from"./interfaces.js";import{LogService as s}from"../services/log.service.js";import{ClarityMotion as a}from"./motion.service.js";import u from"ramda/es/clone";import{isCssPropertyName as c,getCssPropertyValue as f}from"../utils/css.js";import{isSuffixedBy as m,getNumericValueFromCssSecondsStyleValue as l,isPrefixedBy as p,removePrefix as h}from"../utils/string.js";import{queryChildFromLightOrShadowDom as g}from"../utils/dom.js";import{allPropertiesPass as d}from"../utils/identity.js";import{getMillisecondsFromSeconds as y}from"../utils/math.js";async function w(t,n){if(!n._animations)return s.warn(n.tagName.toLocaleLowerCase()+" is trying to animate but no animations are defined."),!1;const o=z(n._animations,t);return await Promise.all(o.map((o=>{const[i,r]=o;if(t.get(i)===n[i])return!1;const e=r[n[i].toString()],s=n.cdsMotion,[a,c]=M(e,x(s,i,n[i].toString()));let f=u(c);if(f.length<1)return!1;f=O(a,f,n);const m=b(e,f,n);return Promise.all(m).then((()=>(v(e,n),!0)))}))).then((t=>t.indexOf(!0)>-1)).catch((()=>!1))}function j(t,o){o.getAttribute("_cds-animation-status")!==n.active&&(o.setAttribute("_cds-animation-status",n.active),o.cdsMotionChange.emit(`${t} animation ${n.start}`))}function v(t,o){o.setAttribute("_cds-animation-status",n.ready),o.cdsMotionChange.emit(`${t} animation ${n.end}`)}function O(t,n,o){const i=o.cdsMotion,r=!i||"off"===i;return S(t)&&(n=C(n)),r?B(n):$(n=N(n,o),o)}function b(t,n,o){return n.filter((t=>!t.onlyIf||d(o,t.onlyIf))).map((n=>(j(t,o),new Promise((t=>{const i=A(o,n.target).animate(P(n.animation,o),n.options||{}),r=()=>{t("animation finished"),i.removeEventListener("finish",r)};i.addEventListener("finish",r)})))))}function A(t,n){return g(t,n)||t}function P(t,n){return Array.isArray(t)?R(t,n):t}function S(n){return m(n,t)}function C(t){return t.map((t=>(t.options?t.options.direction=o:t.options={direction:o},t)))}function _(t){return t+"-"+o}function x(t,n,o){if(!t||!n||void 0===o)return"";if("on"===t||"off"===t)return"";let i;try{i=JSON.parse(t)}catch(t){return""}return i[n]&&i[n][o]||""}function E(n){return S(n)?n.slice(0,-1*t.length):n}function L(t,n){return n&&a.has(E(n))?n:t}function M(t,n){const o=L(t,n);return[o,u(a.get(E(o)))]}function N(t,n){return I("duration",n,t,r,(t=>y(l(t))))}function $(t,n){return I("easing",n,t,i)}function B(t){return t.map((t=>(t.options?(t.options.duration=0,t.options.easing=i):t.options={duration:0,easing:i},t)))}function I(t,n,o,i,r){return o.map((o=>{if(o.options)if(o.options[t]){if(c(o.options[t])){const e=o.options[t];let s=f(e,n);s?r&&(s=r(s)):s=i,o.options[t]=s}}else o.options[t]=i;else{const n={};n[t]=i,o.options=n}return o}))}function R(t,n){return Array.isArray(t)?t.map((t=>{if(Object.prototype.hasOwnProperty.call(t,"height")&&p(t?.height?.toString()||"","from:")){const o=h(t?.height?.toString()||"","from:"),i=g(n,o)||null;t.height=i?i.getBoundingClientRect().height+"px":"auto"}if(Object.prototype.hasOwnProperty.call(t,"width")&&p(t?.width?.toString()||"","from:")){const o=h(t?.width?.toString()||"","from:"),i=g(n,o)||null;t.width=i?i.getBoundingClientRect().width+"px":"auto"}return t})):t}function J(t,n){if(null==t)return null;let o=!0;const i={};return Object.getOwnPropertyNames(t).forEach((r=>{n.has(r)&&void 0!==n.get(r)&&(i[r]=u(t[r]),o=!1)})),o?null:i}function k(t,n){if(null==t)return[];const[o,i]=t;return o.length>0?n?[].concat(i,o):[].concat(o,i):i}function q(t){const n=[],o=[];return Object.getOwnPropertyNames(t||{}).forEach((i=>{const r=[i,u(t[i])];i===e?n.push(r):o.push(r)})),[n,o]}function z(t,n){const o=J(t||{},n);return null===o?[]:k(q(o),n.get(e))}export{S as animationIsReversed,E as extractAnimationNameIfReversed,J as filterAnimationsByUpdatedProperties,k as flattenAndSortAnimations,M as getAnimationConfigForPropertyValue,L as getAnimationFromOverrideOrDecorator,P as getAnimationKeyframesOrPropertyIndexedFrames,b as getAnimationPromiseInstructions,A as getAnimationTarget,q as getHidingAndNonHidingPropertyAnimations,x as getInlineOverride,z as getPropertyAnimations,v as resolveAnimationEndStatus,_ as reverseAnimation,C as reverseAnimationConfig,w as runPropertyAnimations,O as setAnimationConfigOptions,N as setAnimationDuration,$ as setAnimationEasing,I as setAnimationProperty,j as setAnimationStartStatus,R as sizeDimensionKeyframes,B as zeroOutAnimationConfig};
|
|
2
2
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../src/internal/motion/utils.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport { AnimationStatus, CLARITY_MOTION_ENTER_LEAVE_PROPERTY, CLARITY_MOTION_FALLBACK_DURATION_IN_MS, CLARITY_MOTION_FALLBACK_EASING, CLARITY_MOTION_REVERSE_ANIMATION_LABEL, CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX, } from './interfaces.js';\nimport { LogService } from '../services/log.service.js';\nimport { ClarityMotion } from './motion.service.js';\nimport clone from 'ramda/es/clone.js';\nimport { getCssPropertyValue, isCssPropertyName } from '../utils/css.js';\nimport { isPrefixedBy, isSuffixedBy, getNumericValueFromCssSecondsStyleValue, removePrefix } from '../utils/string.js';\nimport { queryChildFromLightOrShadowDom } from '../utils/dom.js';\nimport { allPropertiesPass } from '../utils/identity.js';\nimport { getMillisecondsFromSeconds } from '../utils/math.js';\n/**\n * runPropertyAnimations() is a utility function called by the @animate(). It is a single point of entry\n * to execute the property-driven animations found in components like the accordion and overlay.\n *\n * Other utilities here are exported to break up the unit tests covering the animation/motion\n * library. While they could be called or used in isolation, it is not recommended for most use cases.\n *\n * runPropertyAnimations returns a boolean so that we know if it ran successfully or not. This is\n * mostly to make testing the function easier.\n *\n * @internal\n */\n/* c8 ignore next */\nexport async function runPropertyAnimations(props, hostEl) {\n if (!hostEl._animations) {\n LogService.warn(`${hostEl.tagName.toLocaleLowerCase()} is trying to animate but no animations are defined.`);\n return false;\n }\n // this runs through animations for each property sequentially\n // animations passed into getPropertyAnimations are the Property-Driven Animations\n // passed into the @animate decorator\n // { hidden: { true: 'cds-modal-enter-reverse', false: 'enter' }, status: { error: 'cds-component-shake' } }\n // getPropertyAnimations transforms the @animate decorator config into an array of\n // tuples so they are easier to work with.\n // ['hidden', { true: 'cds-modal-enter-reverse', false: 'enter' }], ['status', { error: 'cds-component-shake' }]\n // * inactive animations are filtered out\n const propertyAnimations = getPropertyAnimations(hostEl._animations, props);\n const animationsRan = await Promise.all(propertyAnimations.map((propNameAnimationTuple) => {\n const [propname, propertyAnimationsByValue] = propNameAnimationTuple;\n if (props.get(propname) === hostEl[propname]) {\n // a weird/unlikely state where an update is sent but the property value didn't actually change\n return false;\n }\n // gets animations to run based on the property's value\n const animatedPropertyValueAsString = propertyAnimationsByValue[hostEl[propname].toString()];\n const cdsMotionValue = hostEl.cdsMotion;\n // looping through each tuple value in order, getAnimationConfigForPropertyValue()\n // returns a tuple with the animation name from Clarity Motion and the TargetedAnimation\n // config (also returned from the Clarity Motion service)\n // ['enter-reverse', [ { target: '.private-host', animation: [ { opacity: 0 }, { opacity: 1 } ], options: { duration: 300 }}]\n const [motionName, returnedMotion] = getAnimationConfigForPropertyValue(animatedPropertyValueAsString, getInlineOverride(cdsMotionValue, propname, hostEl[propname].toString()));\n let motionForMyValue = clone(returnedMotion); // have to jump through this hoop to keep typescript happy\n // jumps out if there are no animation routines\n if (motionForMyValue.length < 1) {\n return false;\n }\n motionForMyValue = setAnimationConfigOptions(motionName, motionForMyValue, hostEl);\n // loops through animation config and runs them; assigns the promises to an array we can Promise.all() at the end\n const animations = getAnimationPromiseInstructions(animatedPropertyValueAsString, motionForMyValue, hostEl);\n return Promise.all(animations).then(() => {\n resolveAnimationEndStatus(animatedPropertyValueAsString, hostEl);\n return true;\n });\n }))\n .then(result => {\n return result.indexOf(true) > -1;\n })\n .catch(() => {\n return false;\n });\n return animationsRan;\n}\n// --- CONTROL FLOW UTILS ---\n/* c8 ignore next */\nexport function setAnimationStartStatus(animatedPropertyValueAsString, hostEl) {\n // accesses and manipulates the private animation status attr;\n if (hostEl.getAttribute('_cds-animation-status') !== AnimationStatus.active) {\n hostEl.setAttribute('_cds-animation-status', AnimationStatus.active);\n // this is here so we only emit the start event once, right when the whole animation starts...\n hostEl.cdsMotionChange.emit(`${animatedPropertyValueAsString} animation ${AnimationStatus.start}`);\n }\n}\n/* c8 ignore next */\nexport function resolveAnimationEndStatus(animatedPropertyValueAsString, hostEl) {\n // sets super secret animation attr back to 'ready'\n hostEl.setAttribute('_cds-animation-status', AnimationStatus.ready); // A\n // emits the name of the animation and that it ended\n hostEl.cdsMotionChange.emit(`${animatedPropertyValueAsString} animation ${AnimationStatus.end}`); // A\n}\n/* c8 ignore next */\nexport function setAnimationConfigOptions(motionName, motionForMyValue, hostEl) {\n const cdsMotionValue = hostEl.cdsMotion;\n const animationsAreTurnedOff = !cdsMotionValue || cdsMotionValue === 'off';\n // the following set of functions – reverseAnimationConfig(), zeroOutAnimationConfig(),\n // setAnimationDuration(), setAnimationEasing() – modify the \"options\" portion of the animation routine\n // in the tuple above that is returned from getAnimationConfigForPropertyValue\n if (animationIsReversed(motionName)) {\n motionForMyValue = reverseAnimationConfig(motionForMyValue);\n }\n if (animationsAreTurnedOff) {\n // cdsMotion is turned off, so zero out the duration\n motionForMyValue = zeroOutAnimationConfig(motionForMyValue);\n }\n else {\n // sets duration and easing based on CSS properties, passed values, or a global fallback\n motionForMyValue = setAnimationDuration(motionForMyValue, hostEl);\n motionForMyValue = setAnimationEasing(motionForMyValue, hostEl);\n }\n return motionForMyValue;\n}\n/* c8 ignore next */\nexport function getAnimationPromiseInstructions(animatedPropertyValueAsString, motionConfigs, hostEl) {\n return motionConfigs\n .filter(config => !config.onlyIf || allPropertiesPass(hostEl, config.onlyIf))\n .map(config => {\n setAnimationStartStatus(animatedPropertyValueAsString, hostEl);\n return new Promise(resolve => {\n const animationPlayer = getAnimationTarget(hostEl, config.target).animate(getAnimationKeyframesOrPropertyIndexedFrames(config.animation, hostEl), config.options || {});\n const listener = () => {\n resolve('animation finished');\n animationPlayer.removeEventListener('finish', listener);\n };\n animationPlayer.addEventListener('finish', listener);\n });\n });\n}\n/* c8 ignore next */\nexport function getAnimationTarget(hostEl, targetSelector) {\n return queryChildFromLightOrShadowDom(hostEl, targetSelector) || hostEl;\n}\n/* c8 ignore next */\nexport function getAnimationKeyframesOrPropertyIndexedFrames(animationConfig, hostEl) {\n return !Array.isArray(animationConfig) ? animationConfig : sizeDimensionKeyframes(animationConfig, hostEl);\n}\n// --- REVERSING UTILS ---\n// string -> boolean\n/* c8 ignore next */\nexport function animationIsReversed(nameOfAnimation) {\n return isSuffixedBy(nameOfAnimation, CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX);\n}\n// { target: '.my-selector', animation: [<keyframes>], options: { duration: 500 }} ->\n// { target: '.my-selector', animation: [<keyframes>], options: { duration: 500, direction: 'reverse' }}\n/* c8 ignore next */\nexport function reverseAnimationConfig(config) {\n return config.map((anim) => {\n if (anim.options) {\n anim.options.direction = CLARITY_MOTION_REVERSE_ANIMATION_LABEL;\n }\n else {\n anim.options = { direction: CLARITY_MOTION_REVERSE_ANIMATION_LABEL };\n }\n return anim;\n });\n}\n// 'my-animation' -> 'my-animation-reverse'\n/* c8 ignore next */\nexport function reverseAnimation(animationName) {\n return [animationName, '-', CLARITY_MOTION_REVERSE_ANIMATION_LABEL].join('');\n}\n// --- ANIMATION CONFIG RETRIEVAL ---\n// returns an animation name from a stringified @animate decorator config passed into the\n// cds-motion attr. looks it up by property first and value second. returns empty string\n// if no animation name matches the property and property value.\n/* c8 ignore next */\nexport function getInlineOverride(cdsMotionValue, propName, propValue) {\n if (!cdsMotionValue || !propName || typeof propValue === 'undefined') {\n return '';\n }\n if (cdsMotionValue === 'on' || cdsMotionValue === 'off') {\n return '';\n }\n let inlineOverride;\n try {\n inlineOverride = JSON.parse(cdsMotionValue);\n }\n catch (e) {\n return '';\n }\n const overrideValue = inlineOverride[propName] && inlineOverride[propName][propValue];\n return overrideValue ? overrideValue : '';\n}\n// 'i-am-reverse' -> 'i-am'\n/* c8 ignore next */\nexport function extractAnimationNameIfReversed(name) {\n return animationIsReversed(name) ? name.slice(0, -1 * CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX.length) : name;\n}\n// if the name retrieved from the cds-motion config is present in Clarity Motion, it is returned\n/* c8 ignore next */\nexport function getAnimationFromOverrideOrDecorator(decoratorValue, overrideValue) {\n if (!overrideValue) {\n return decoratorValue;\n }\n return ClarityMotion.has(extractAnimationNameIfReversed(overrideValue)) ? overrideValue : decoratorValue;\n}\n// ('animation-name') -> ['animation-name', [ { target: '.an-element', animation: [<keyframes>], options: { ... }}]];\n// ('animation-name', 'name-retrieved-from-cds-motion-config') ->\n// ['name-retrieved-from-cds-motion-config', [ { target: ..., animation: [<keyframes>], options: { ... }}]];0\n/* c8 ignore next */\nexport function getAnimationConfigForPropertyValue(nameOfAnimationFromObject, cdsMotionOverride) {\n const nameOfAnimation = getAnimationFromOverrideOrDecorator(nameOfAnimationFromObject, cdsMotionOverride);\n return [nameOfAnimation, clone(ClarityMotion.get(extractAnimationNameIfReversed(nameOfAnimation)))];\n}\n// --- SETTING ANIMATION CONFIG VALUES ---\n/* c8 ignore next */\nexport function setAnimationDuration(config, hostEl) {\n return setAnimationProperty('duration', hostEl, config, CLARITY_MOTION_FALLBACK_DURATION_IN_MS, (val) => {\n return getMillisecondsFromSeconds(getNumericValueFromCssSecondsStyleValue(val));\n });\n}\n/* c8 ignore next */\nexport function setAnimationEasing(config, hostEl) {\n /* c8 ignore next */\n return setAnimationProperty('easing', hostEl, config, CLARITY_MOTION_FALLBACK_EASING);\n}\n/* c8 ignore next */\nexport function zeroOutAnimationConfig(config) {\n /* c8 ignore next */\n return config.map(anim => {\n if (anim.options) {\n anim.options.duration = 0;\n anim.options.easing = CLARITY_MOTION_FALLBACK_EASING;\n }\n else {\n anim.options = { duration: 0, easing: CLARITY_MOTION_FALLBACK_EASING };\n }\n return anim;\n });\n}\n/* c8 ignore next */\nexport function setAnimationProperty(propertyName, hostEl, config, staticFallback, valueConverter) {\n return config.map((anim) => {\n if (anim.options) {\n if (!anim.options[propertyName]) {\n anim.options[propertyName] = staticFallback;\n }\n else if (isCssPropertyName(anim.options[propertyName])) {\n const myConfigOption = anim.options[propertyName];\n let valFromProperty = getCssPropertyValue(myConfigOption, hostEl);\n if (!valFromProperty) {\n valFromProperty = staticFallback;\n }\n else if (valueConverter) {\n valFromProperty = valueConverter(valFromProperty);\n }\n anim.options[propertyName] = valFromProperty;\n }\n // else fallthrough not required because option is already set to intended value\n }\n else {\n const newConfigOptions = {};\n newConfigOptions[propertyName] = staticFallback;\n anim.options = newConfigOptions;\n }\n return anim;\n });\n}\n// -- TRANSFORM PROPERTY-DRIVEN ANIMATION OBJECTS TO ANIMATION CONFIG OBJECTS ---\n/* c8 ignore next */\nexport function sizeDimensionKeyframes(animationKeyframes, hostEl) {\n if (!Array.isArray(animationKeyframes)) {\n return animationKeyframes;\n }\n return animationKeyframes.map((kf) => {\n if (Object.prototype.hasOwnProperty.call(kf, 'height') && isPrefixedBy(kf?.height?.toString() || '', 'from:')) {\n const selector = removePrefix(kf?.height?.toString() || '', 'from:');\n const measureTarget = queryChildFromLightOrShadowDom(hostEl, selector) || null;\n kf.height = !measureTarget ? 'auto' : measureTarget.getBoundingClientRect().height + 'px';\n }\n if (Object.prototype.hasOwnProperty.call(kf, 'width') && isPrefixedBy(kf?.width?.toString() || '', 'from:')) {\n const selector = removePrefix(kf?.width?.toString() || '', 'from:');\n const measureTarget = queryChildFromLightOrShadowDom(hostEl, selector) || null;\n kf.width = !measureTarget ? 'auto' : measureTarget.getBoundingClientRect().width + 'px';\n }\n return kf;\n });\n}\n/* c8 ignore next */\nexport function filterAnimationsByUpdatedProperties(animations, updatingProps) {\n if (animations === null || animations === undefined) {\n return null;\n }\n let objectIsEmpty = true;\n const returnObject = {};\n Object.getOwnPropertyNames(animations).forEach((prop) => {\n // test here against undefined value because Lit is running initializations\n // with properties with an \"undefined\" value. as a result of this change,\n // animations should only run on explicitly set values...\n if (updatingProps.has(prop) && updatingProps.get(prop) !== undefined) {\n returnObject[prop] = clone(animations[prop]);\n objectIsEmpty = false;\n }\n });\n return objectIsEmpty ? null : returnObject;\n}\n/* c8 ignore next */\nexport function flattenAndSortAnimations(hiddenAndNotAnimationTuple, isHiding) {\n if (hiddenAndNotAnimationTuple === null || hiddenAndNotAnimationTuple === undefined) {\n return [];\n }\n const [hiddenAnimations, otherAnimations] = hiddenAndNotAnimationTuple;\n if (hiddenAnimations.length > 0) {\n if (isHiding) {\n // hiding hostEl\n return [].concat(otherAnimations, hiddenAnimations);\n }\n else {\n // showing hostEl\n return [].concat(hiddenAnimations, otherAnimations);\n }\n }\n else {\n return otherAnimations;\n }\n}\n/* c8 ignore next */\nexport function getHidingAndNonHidingPropertyAnimations(animations) {\n const hiddenAnimations = [];\n const otherAnimations = [];\n Object.getOwnPropertyNames(animations || {}).forEach((prop) => {\n const animationTuple = [prop, clone(animations[prop])];\n if (prop === CLARITY_MOTION_ENTER_LEAVE_PROPERTY) {\n hiddenAnimations.push(animationTuple);\n }\n else {\n otherAnimations.push(animationTuple);\n }\n });\n return [hiddenAnimations, otherAnimations];\n}\n/* c8 ignore next */\nexport function getPropertyAnimations(animations, updatingProps) {\n const activeAnimations = filterAnimationsByUpdatedProperties(animations || {}, updatingProps);\n if (activeAnimations === null) {\n return [];\n }\n const hidingAndOtherAnimationsAsTuple = getHidingAndNonHidingPropertyAnimations(activeAnimations);\n const isHiding = updatingProps.get(CLARITY_MOTION_ENTER_LEAVE_PROPERTY);\n return flattenAndSortAnimations(hidingAndOtherAnimationsAsTuple, isHiding);\n}\n"],"names":["async","runPropertyAnimations","props","hostEl","_animations","LogService","warn","tagName","toLocaleLowerCase","propertyAnimations","getPropertyAnimations","Promise","all","map","propNameAnimationTuple","propname","propertyAnimationsByValue","get","animatedPropertyValueAsString","toString","cdsMotionValue","cdsMotion","motionName","returnedMotion","getAnimationConfigForPropertyValue","getInlineOverride","motionForMyValue","clone","length","setAnimationConfigOptions","animations","getAnimationPromiseInstructions","then","resolveAnimationEndStatus","result","indexOf","catch","setAnimationStartStatus","getAttribute","AnimationStatus","active","setAttribute","cdsMotionChange","emit","start","ready","end","animationsAreTurnedOff","animationIsReversed","reverseAnimationConfig","zeroOutAnimationConfig","setAnimationEasing","setAnimationDuration","motionConfigs","filter","config","onlyIf","allPropertiesPass","resolve","animationPlayer","getAnimationTarget","target","animate","getAnimationKeyframesOrPropertyIndexedFrames","animation","options","listener","removeEventListener","addEventListener","targetSelector","queryChildFromLightOrShadowDom","animationConfig","Array","isArray","sizeDimensionKeyframes","nameOfAnimation","isSuffixedBy","CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX","anim","direction","CLARITY_MOTION_REVERSE_ANIMATION_LABEL","reverseAnimation","animationName","propName","propValue","inlineOverride","JSON","parse","e","extractAnimationNameIfReversed","name","slice","getAnimationFromOverrideOrDecorator","decoratorValue","overrideValue","ClarityMotion","has","nameOfAnimationFromObject","cdsMotionOverride","setAnimationProperty","CLARITY_MOTION_FALLBACK_DURATION_IN_MS","val","getMillisecondsFromSeconds","getNumericValueFromCssSecondsStyleValue","CLARITY_MOTION_FALLBACK_EASING","duration","easing","propertyName","staticFallback","valueConverter","isCssPropertyName","myConfigOption","valFromProperty","getCssPropertyValue","newConfigOptions","animationKeyframes","kf","Object","prototype","hasOwnProperty","call","isPrefixedBy","height","selector","removePrefix","measureTarget","getBoundingClientRect","width","filterAnimationsByUpdatedProperties","updatingProps","objectIsEmpty","returnObject","getOwnPropertyNames","forEach","prop","undefined","flattenAndSortAnimations","hiddenAndNotAnimationTuple","isHiding","hiddenAnimations","otherAnimations","concat","getHidingAndNonHidingPropertyAnimations","animationTuple","CLARITY_MOTION_ENTER_LEAVE_PROPERTY","push","activeAnimations"],"mappings":"yxBA2BOA,eAAeC,EAAsBC,EAAOC,GAC/C,IAAKA,EAAOC,YAER,OADAC,EAAWC,KAAQH,EAAOI,QAAQC,oBAAlB,yDACT,EAUX,MAAMC,EAAqBC,EAAsBP,EAAOC,YAAaF,GAkCrE,aAjC4BS,QAAQC,IAAIH,EAAmBI,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(c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport { AnimationStatus, CLARITY_MOTION_ENTER_LEAVE_PROPERTY, CLARITY_MOTION_FALLBACK_DURATION_IN_MS, CLARITY_MOTION_FALLBACK_EASING, CLARITY_MOTION_REVERSE_ANIMATION_LABEL, CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX, } from './interfaces.js';\nimport { LogService } from '../services/log.service.js';\nimport { ClarityMotion } from './motion.service.js';\nimport clone from 'ramda/es/clone';\nimport { getCssPropertyValue, isCssPropertyName } from '../utils/css.js';\nimport { isPrefixedBy, isSuffixedBy, getNumericValueFromCssSecondsStyleValue, removePrefix } from '../utils/string.js';\nimport { queryChildFromLightOrShadowDom } from '../utils/dom.js';\nimport { allPropertiesPass } from '../utils/identity.js';\nimport { getMillisecondsFromSeconds } from '../utils/math.js';\n/**\n * runPropertyAnimations() is a utility function called by the @animate(). It is a single point of entry\n * to execute the property-driven animations found in components like the accordion and overlay.\n *\n * Other utilities here are exported to break up the unit tests covering the animation/motion\n * library. While they could be called or used in isolation, it is not recommended for most use cases.\n *\n * runPropertyAnimations returns a boolean so that we know if it ran successfully or not. This is\n * mostly to make testing the function easier.\n *\n * @internal\n */\n/* c8 ignore next */\nexport async function runPropertyAnimations(props, hostEl) {\n if (!hostEl._animations) {\n LogService.warn(`${hostEl.tagName.toLocaleLowerCase()} is trying to animate but no animations are defined.`);\n return false;\n }\n // this runs through animations for each property sequentially\n // animations passed into getPropertyAnimations are the Property-Driven Animations\n // passed into the @animate decorator\n // { hidden: { true: 'cds-modal-enter-reverse', false: 'enter' }, status: { error: 'cds-component-shake' } }\n // getPropertyAnimations transforms the @animate decorator config into an array of\n // tuples so they are easier to work with.\n // ['hidden', { true: 'cds-modal-enter-reverse', false: 'enter' }], ['status', { error: 'cds-component-shake' }]\n // * inactive animations are filtered out\n const propertyAnimations = getPropertyAnimations(hostEl._animations, props);\n const animationsRan = await Promise.all(propertyAnimations.map((propNameAnimationTuple) => {\n const [propname, propertyAnimationsByValue] = propNameAnimationTuple;\n if (props.get(propname) === hostEl[propname]) {\n // a weird/unlikely state where an update is sent but the property value didn't actually change\n return false;\n }\n // gets animations to run based on the property's value\n const animatedPropertyValueAsString = propertyAnimationsByValue[hostEl[propname].toString()];\n const cdsMotionValue = hostEl.cdsMotion;\n // looping through each tuple value in order, getAnimationConfigForPropertyValue()\n // returns a tuple with the animation name from Clarity Motion and the TargetedAnimation\n // config (also returned from the Clarity Motion service)\n // ['enter-reverse', [ { target: '.private-host', animation: [ { opacity: 0 }, { opacity: 1 } ], options: { duration: 300 }}]\n const [motionName, returnedMotion] = getAnimationConfigForPropertyValue(animatedPropertyValueAsString, getInlineOverride(cdsMotionValue, propname, hostEl[propname].toString()));\n let motionForMyValue = clone(returnedMotion); // have to jump through this hoop to keep typescript happy\n // jumps out if there are no animation routines\n if (motionForMyValue.length < 1) {\n return false;\n }\n motionForMyValue = setAnimationConfigOptions(motionName, motionForMyValue, hostEl);\n // loops through animation config and runs them; assigns the promises to an array we can Promise.all() at the end\n const animations = getAnimationPromiseInstructions(animatedPropertyValueAsString, motionForMyValue, hostEl);\n return Promise.all(animations).then(() => {\n resolveAnimationEndStatus(animatedPropertyValueAsString, hostEl);\n return true;\n });\n }))\n .then(result => {\n return result.indexOf(true) > -1;\n })\n .catch(() => {\n return false;\n });\n return animationsRan;\n}\n// --- CONTROL FLOW UTILS ---\n/* c8 ignore next */\nexport function setAnimationStartStatus(animatedPropertyValueAsString, hostEl) {\n // accesses and manipulates the private animation status attr;\n if (hostEl.getAttribute('_cds-animation-status') !== AnimationStatus.active) {\n hostEl.setAttribute('_cds-animation-status', AnimationStatus.active);\n // this is here so we only emit the start event once, right when the whole animation starts...\n hostEl.cdsMotionChange.emit(`${animatedPropertyValueAsString} animation ${AnimationStatus.start}`);\n }\n}\n/* c8 ignore next */\nexport function resolveAnimationEndStatus(animatedPropertyValueAsString, hostEl) {\n // sets super secret animation attr back to 'ready'\n hostEl.setAttribute('_cds-animation-status', AnimationStatus.ready); // A\n // emits the name of the animation and that it ended\n hostEl.cdsMotionChange.emit(`${animatedPropertyValueAsString} animation ${AnimationStatus.end}`); // A\n}\n/* c8 ignore next */\nexport function setAnimationConfigOptions(motionName, motionForMyValue, hostEl) {\n const cdsMotionValue = hostEl.cdsMotion;\n const animationsAreTurnedOff = !cdsMotionValue || cdsMotionValue === 'off';\n // the following set of functions – reverseAnimationConfig(), zeroOutAnimationConfig(),\n // setAnimationDuration(), setAnimationEasing() – modify the \"options\" portion of the animation routine\n // in the tuple above that is returned from getAnimationConfigForPropertyValue\n if (animationIsReversed(motionName)) {\n motionForMyValue = reverseAnimationConfig(motionForMyValue);\n }\n if (animationsAreTurnedOff) {\n // cdsMotion is turned off, so zero out the duration\n motionForMyValue = zeroOutAnimationConfig(motionForMyValue);\n }\n else {\n // sets duration and easing based on CSS properties, passed values, or a global fallback\n motionForMyValue = setAnimationDuration(motionForMyValue, hostEl);\n motionForMyValue = setAnimationEasing(motionForMyValue, hostEl);\n }\n return motionForMyValue;\n}\n/* c8 ignore next */\nexport function getAnimationPromiseInstructions(animatedPropertyValueAsString, motionConfigs, hostEl) {\n return motionConfigs\n .filter(config => !config.onlyIf || allPropertiesPass(hostEl, config.onlyIf))\n .map(config => {\n setAnimationStartStatus(animatedPropertyValueAsString, hostEl);\n return new Promise(resolve => {\n const animationPlayer = getAnimationTarget(hostEl, config.target).animate(getAnimationKeyframesOrPropertyIndexedFrames(config.animation, hostEl), config.options || {});\n const listener = () => {\n resolve('animation finished');\n animationPlayer.removeEventListener('finish', listener);\n };\n animationPlayer.addEventListener('finish', listener);\n });\n });\n}\n/* c8 ignore next */\nexport function getAnimationTarget(hostEl, targetSelector) {\n return queryChildFromLightOrShadowDom(hostEl, targetSelector) || hostEl;\n}\n/* c8 ignore next */\nexport function getAnimationKeyframesOrPropertyIndexedFrames(animationConfig, hostEl) {\n return !Array.isArray(animationConfig) ? animationConfig : sizeDimensionKeyframes(animationConfig, hostEl);\n}\n// --- REVERSING UTILS ---\n// string -> boolean\n/* c8 ignore next */\nexport function animationIsReversed(nameOfAnimation) {\n return isSuffixedBy(nameOfAnimation, CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX);\n}\n// { target: '.my-selector', animation: [<keyframes>], options: { duration: 500 }} ->\n// { target: '.my-selector', animation: [<keyframes>], options: { duration: 500, direction: 'reverse' }}\n/* c8 ignore next */\nexport function reverseAnimationConfig(config) {\n return config.map((anim) => {\n if (anim.options) {\n anim.options.direction = CLARITY_MOTION_REVERSE_ANIMATION_LABEL;\n }\n else {\n anim.options = { direction: CLARITY_MOTION_REVERSE_ANIMATION_LABEL };\n }\n return anim;\n });\n}\n// 'my-animation' -> 'my-animation-reverse'\n/* c8 ignore next */\nexport function reverseAnimation(animationName) {\n return [animationName, '-', CLARITY_MOTION_REVERSE_ANIMATION_LABEL].join('');\n}\n// --- ANIMATION CONFIG RETRIEVAL ---\n// returns an animation name from a stringified @animate decorator config passed into the\n// cds-motion attr. looks it up by property first and value second. returns empty string\n// if no animation name matches the property and property value.\n/* c8 ignore next */\nexport function getInlineOverride(cdsMotionValue, propName, propValue) {\n if (!cdsMotionValue || !propName || typeof propValue === 'undefined') {\n return '';\n }\n if (cdsMotionValue === 'on' || cdsMotionValue === 'off') {\n return '';\n }\n let inlineOverride;\n try {\n inlineOverride = JSON.parse(cdsMotionValue);\n }\n catch (e) {\n return '';\n }\n const overrideValue = inlineOverride[propName] && inlineOverride[propName][propValue];\n return overrideValue ? overrideValue : '';\n}\n// 'i-am-reverse' -> 'i-am'\n/* c8 ignore next */\nexport function extractAnimationNameIfReversed(name) {\n return animationIsReversed(name) ? name.slice(0, -1 * CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX.length) : name;\n}\n// if the name retrieved from the cds-motion config is present in Clarity Motion, it is returned\n/* c8 ignore next */\nexport function getAnimationFromOverrideOrDecorator(decoratorValue, overrideValue) {\n if (!overrideValue) {\n return decoratorValue;\n }\n return ClarityMotion.has(extractAnimationNameIfReversed(overrideValue)) ? overrideValue : decoratorValue;\n}\n// ('animation-name') -> ['animation-name', [ { target: '.an-element', animation: [<keyframes>], options: { ... }}]];\n// ('animation-name', 'name-retrieved-from-cds-motion-config') ->\n// ['name-retrieved-from-cds-motion-config', [ { target: ..., animation: [<keyframes>], options: { ... }}]];0\n/* c8 ignore next */\nexport function getAnimationConfigForPropertyValue(nameOfAnimationFromObject, cdsMotionOverride) {\n const nameOfAnimation = getAnimationFromOverrideOrDecorator(nameOfAnimationFromObject, cdsMotionOverride);\n return [nameOfAnimation, clone(ClarityMotion.get(extractAnimationNameIfReversed(nameOfAnimation)))];\n}\n// --- SETTING ANIMATION CONFIG VALUES ---\n/* c8 ignore next */\nexport function setAnimationDuration(config, hostEl) {\n return setAnimationProperty('duration', hostEl, config, CLARITY_MOTION_FALLBACK_DURATION_IN_MS, (val) => {\n return getMillisecondsFromSeconds(getNumericValueFromCssSecondsStyleValue(val));\n });\n}\n/* c8 ignore next */\nexport function setAnimationEasing(config, hostEl) {\n /* c8 ignore next */\n return setAnimationProperty('easing', hostEl, config, CLARITY_MOTION_FALLBACK_EASING);\n}\n/* c8 ignore next */\nexport function zeroOutAnimationConfig(config) {\n /* c8 ignore next */\n return config.map(anim => {\n if (anim.options) {\n anim.options.duration = 0;\n anim.options.easing = CLARITY_MOTION_FALLBACK_EASING;\n }\n else {\n anim.options = { duration: 0, easing: CLARITY_MOTION_FALLBACK_EASING };\n }\n return anim;\n });\n}\n/* c8 ignore next */\nexport function setAnimationProperty(propertyName, hostEl, config, staticFallback, valueConverter) {\n return config.map((anim) => {\n if (anim.options) {\n if (!anim.options[propertyName]) {\n anim.options[propertyName] = staticFallback;\n }\n else if (isCssPropertyName(anim.options[propertyName])) {\n const myConfigOption = anim.options[propertyName];\n let valFromProperty = getCssPropertyValue(myConfigOption, hostEl);\n if (!valFromProperty) {\n valFromProperty = staticFallback;\n }\n else if (valueConverter) {\n valFromProperty = valueConverter(valFromProperty);\n }\n anim.options[propertyName] = valFromProperty;\n }\n // else fallthrough not required because option is already set to intended value\n }\n else {\n const newConfigOptions = {};\n newConfigOptions[propertyName] = staticFallback;\n anim.options = newConfigOptions;\n }\n return anim;\n });\n}\n// -- TRANSFORM PROPERTY-DRIVEN ANIMATION OBJECTS TO ANIMATION CONFIG OBJECTS ---\n/* c8 ignore next */\nexport function sizeDimensionKeyframes(animationKeyframes, hostEl) {\n if (!Array.isArray(animationKeyframes)) {\n return animationKeyframes;\n }\n return animationKeyframes.map((kf) => {\n if (Object.prototype.hasOwnProperty.call(kf, 'height') && isPrefixedBy(kf?.height?.toString() || '', 'from:')) {\n const selector = removePrefix(kf?.height?.toString() || '', 'from:');\n const measureTarget = queryChildFromLightOrShadowDom(hostEl, selector) || null;\n kf.height = !measureTarget ? 'auto' : measureTarget.getBoundingClientRect().height + 'px';\n }\n if (Object.prototype.hasOwnProperty.call(kf, 'width') && isPrefixedBy(kf?.width?.toString() || '', 'from:')) {\n const selector = removePrefix(kf?.width?.toString() || '', 'from:');\n const measureTarget = queryChildFromLightOrShadowDom(hostEl, selector) || null;\n kf.width = !measureTarget ? 'auto' : measureTarget.getBoundingClientRect().width + 'px';\n }\n return kf;\n });\n}\n/* c8 ignore next */\nexport function filterAnimationsByUpdatedProperties(animations, updatingProps) {\n if (animations === null || animations === undefined) {\n return null;\n }\n let objectIsEmpty = true;\n const returnObject = {};\n Object.getOwnPropertyNames(animations).forEach((prop) => {\n // test here against undefined value because Lit is running initializations\n // with properties with an \"undefined\" value. as a result of this change,\n // animations should only run on explicitly set values...\n if (updatingProps.has(prop) && updatingProps.get(prop) !== undefined) {\n returnObject[prop] = clone(animations[prop]);\n objectIsEmpty = false;\n }\n });\n return objectIsEmpty ? null : returnObject;\n}\n/* c8 ignore next */\nexport function flattenAndSortAnimations(hiddenAndNotAnimationTuple, isHiding) {\n if (hiddenAndNotAnimationTuple === null || hiddenAndNotAnimationTuple === undefined) {\n return [];\n }\n const [hiddenAnimations, otherAnimations] = hiddenAndNotAnimationTuple;\n if (hiddenAnimations.length > 0) {\n if (isHiding) {\n // hiding hostEl\n return [].concat(otherAnimations, hiddenAnimations);\n }\n else {\n // showing hostEl\n return [].concat(hiddenAnimations, otherAnimations);\n }\n }\n else {\n return otherAnimations;\n }\n}\n/* c8 ignore next */\nexport function getHidingAndNonHidingPropertyAnimations(animations) {\n const hiddenAnimations = [];\n const otherAnimations = [];\n Object.getOwnPropertyNames(animations || {}).forEach((prop) => {\n const animationTuple = [prop, clone(animations[prop])];\n if (prop === CLARITY_MOTION_ENTER_LEAVE_PROPERTY) {\n hiddenAnimations.push(animationTuple);\n }\n else {\n otherAnimations.push(animationTuple);\n }\n });\n return [hiddenAnimations, otherAnimations];\n}\n/* c8 ignore next */\nexport function getPropertyAnimations(animations, updatingProps) {\n const activeAnimations = filterAnimationsByUpdatedProperties(animations || {}, updatingProps);\n if (activeAnimations === null) {\n return [];\n }\n const hidingAndOtherAnimationsAsTuple = getHidingAndNonHidingPropertyAnimations(activeAnimations);\n const isHiding = updatingProps.get(CLARITY_MOTION_ENTER_LEAVE_PROPERTY);\n return flattenAndSortAnimations(hidingAndOtherAnimationsAsTuple, isHiding);\n}\n"],"names":["async","runPropertyAnimations","props","hostEl","_animations","LogService","warn","tagName","toLocaleLowerCase","propertyAnimations","getPropertyAnimations","Promise","all","map","propNameAnimationTuple","propname","propertyAnimationsByValue","get","animatedPropertyValueAsString","toString","cdsMotionValue","cdsMotion","motionName","returnedMotion","getAnimationConfigForPropertyValue","getInlineOverride","motionForMyValue","clone","length","setAnimationConfigOptions","animations","getAnimationPromiseInstructions","then","resolveAnimationEndStatus","result","indexOf","catch","setAnimationStartStatus","getAttribute","AnimationStatus","active","setAttribute","cdsMotionChange","emit","start","ready","end","animationsAreTurnedOff","animationIsReversed","reverseAnimationConfig","zeroOutAnimationConfig","setAnimationEasing","setAnimationDuration","motionConfigs","filter","config","onlyIf","allPropertiesPass","resolve","animationPlayer","getAnimationTarget","target","animate","getAnimationKeyframesOrPropertyIndexedFrames","animation","options","listener","removeEventListener","addEventListener","targetSelector","queryChildFromLightOrShadowDom","animationConfig","Array","isArray","sizeDimensionKeyframes","nameOfAnimation","isSuffixedBy","CLARITY_MOTION_REVERSE_ANIMATION_SUFFIX","anim","direction","CLARITY_MOTION_REVERSE_ANIMATION_LABEL","reverseAnimation","animationName","propName","propValue","inlineOverride","JSON","parse","e","extractAnimationNameIfReversed","name","slice","getAnimationFromOverrideOrDecorator","decoratorValue","overrideValue","ClarityMotion","has","nameOfAnimationFromObject","cdsMotionOverride","setAnimationProperty","CLARITY_MOTION_FALLBACK_DURATION_IN_MS","val","getMillisecondsFromSeconds","getNumericValueFromCssSecondsStyleValue","CLARITY_MOTION_FALLBACK_EASING","duration","easing","propertyName","staticFallback","valueConverter","isCssPropertyName","myConfigOption","valFromProperty","getCssPropertyValue","newConfigOptions","animationKeyframes","kf","Object","prototype","hasOwnProperty","call","isPrefixedBy","height","selector","removePrefix","measureTarget","getBoundingClientRect","width","filterAnimationsByUpdatedProperties","updatingProps","objectIsEmpty","returnObject","getOwnPropertyNames","forEach","prop","undefined","flattenAndSortAnimations","hiddenAndNotAnimationTuple","isHiding","hiddenAnimations","otherAnimations","concat","getHidingAndNonHidingPropertyAnimations","animationTuple","CLARITY_MOTION_ENTER_LEAVE_PROPERTY","push","activeAnimations"],"mappings":"sxBA2BOA,eAAeC,EAAsBC,EAAOC,GAC/C,IAAKA,EAAOC,YAER,OADAC,EAAWC,KAAQH,EAAOI,QAAQC,oBAAlB,yDACT,EAUX,MAAMC,EAAqBC,EAAsBP,EAAOC,YAAaF,GAkCrE,aAjC4BS,QAAQC,IAAIH,EAAmBI,KAAKC,IAC5D,MAAOC,EAAUC,GAA6BF,EAC9C,GAAIZ,EAAMe,IAAIF,KAAcZ,EAAOY,GAE/B,OAAO,EAGX,MAAMG,EAAgCF,EAA0Bb,EAAOY,GAAUI,YAC3EC,EAAiBjB,EAAOkB,WAKvBC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wH,IAAa,KAC1EP,EAAGW,MAASF,EAAyBA,EAAcC,wBAAwBC,MAAQ,KAAvD,OAEhC,OAAOX,KAbAD,EAiBR,SAASa,EAAoClG,EAAYmG,GAC5D,GAAInG,MAAAA,EACA,OAAO,KAEX,IAAIoG,GAAgB,EACpB,MAAMC,EAAe,GAUrB,OATAd,OAAOe,oBAAoBtG,GAAYuG,SAASC,IAIxCL,EAAcjC,IAAIsC,SAAqCC,IAA5BN,EAAchH,IAAIqH,KAC7CH,EAAaG,GAAQ3G,EAAMG,EAAWwG,IACtCJ,GAAgB,MAGjBA,EAAgB,KAAOC,EAG3B,SAASK,EAAyBC,EAA4BC,GACjE,GAAID,MAAAA,EACA,MAAO,GAEX,MAAOE,EAAkBC,GAAmBH,EAC5C,OAAIE,EAAiB/G,OAAS,EACtB8G,EAEO,GAAGG,OAAOD,EAAiBD,GAI3B,GAAGE,OAAOF,EAAkBC,GAIhCA,EAIR,SAASE,EAAwChH,GACpD,MAAM6G,EAAmB,GACnBC,EAAkB,GAUxB,OATAvB,OAAOe,oBAAoBtG,GAAc,IAAIuG,SAASC,IAClD,MAAMS,EAAiB,CAACT,EAAM3G,EAAMG,EAAWwG,KAC3CA,IAASU,EACTL,EAAiBM,KAAKF,GAGtBH,EAAgBK,KAAKF,MAGtB,CAACJ,EAAkBC,GAGvB,SAASlI,EAAsBoB,EAAYmG,GAC9C,MAAMiB,EAAmBlB,EAAoClG,GAAc,GAAImG,GAC/E,OAAyB,OAArBiB,EACO,GAIJV,EAFiCM,EAAwCI,GAC/DjB,EAAchH,IAAI+H"}
|
package/internal/utils/dom.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"ramda/es/includes
|
|
1
|
+
import t from"ramda/es/includes";import e from"ramda/es/without";import{getCssPropertyValue as n}from"./css.js";import{transformSpacedStringToArray as r,pluckPixelValue as o}from"./string.js";import{isStringAndNotNilOrEmpty as i,isNumericString as u}from"./identity.js";function c(t){switch(t.tagName.toLowerCase()){case"input":return"hidden"!==t.getAttribute("type")&&!t.hasAttribute("disabled")&&!t.hasAttribute("readonly");case"button":case"select":case"textarea":return!t.hasAttribute("disabled");case"iframe":case"embed":case"object":return!0;case"a":case"area":return t.hasAttribute("href");case"audio":case"video":return t.hasAttribute("controls");default:return t.hasAttribute("tabindex")||"true"===t.getAttribute("contenteditable")||"button"===t.getAttribute("role")&&!t.hasAttribute("disabled")}}function a(t){if(!t)return!1;const e=t.getBoundingClientRect();return e.top<0||t.scrollHeight>t.offsetHeight||e.left<0||t.scrollWidth>t.clientWidth}function s(t){return t.querySelectorAll(f.join(", "))}const d=["a[href]","area[href]","audio[controls]","button:not([disabled])",'input:not([type="hidden"]):not([disabled]):not([readonly])',"iframe","object","embed","select:not([disabled])","textarea:not([disabled])","video[controls]","*[contenteditable=true]","[role=button]:not([disabled])"],l=["*[tabindex]",...d],f=['*[tabindex]:not([tabindex="-1"])',...d];function b(t,e="px"){return t&&t.getBoundingClientRect?t.getBoundingClientRect().width+e:""}function h(t,e){return e?"":b(t)}function m(t){return!!t&&t instanceof HTMLElement}function A(t,e){return!!t&&t.hasAttribute(e)&&i(t.getAttribute(e))}function g(t,e,n){const[r,o]=e;n()?p(t,[r,o]):y(t,r)}function p(t,...e){t&&e.forEach((([e,n])=>{!1===n||null===n?t.removeAttribute(e):t.setAttribute(e,n+"")}))}function y(t,...e){t&&e.forEach((e=>{t.removeAttribute(e)}))}function x(e,n,r){if(e){const o=e.getAttribute(n);o?t(r,o.split(" "))||e.setAttribute(n,o+" "+r):e.setAttribute(n,r)}}function w(t,n,o){if(t){const i=t.getAttribute(n);if(i){const u=e([o],r(i)).join(" ");u?t.setAttribute(n,u):t.removeAttribute(n)}}}function E(...t){t.forEach((t=>{const[e,n]=t;e&&p(e,["slot",n])}))}function C(t){return!!t&&t?.offsetHeight>0&&!1===t?.hasAttribute("hidden")}function R(t){Array.from(t).filter((t=>t.textContent&&t.textContent.trim().length>0&&3===t.nodeType&&t.parentElement)).forEach((t=>{const e=document.createElement("span");t.after(e),e.appendChild(t)}))}function j(t,e){return e&&(t.querySelector(e)||t?.shadowRoot?.querySelector(e))||null}function H(t){return document.createRange().createContextualFragment(t)}function q(t=window){const e=t?.document,n=t?.innerHeight||e?.documentElement?.clientHeight||0;return{width:t?.innerWidth||e?.documentElement?.clientWidth||0,height:n}}function v(t){const e=t||n("--cds-global-layout-width-xs").trim();return!!t?.endsWith("px")&&o(e)>=q().width}function S(t,e){const n=e||t;return t.shadowRoot?t.shadowRoot:n}function W(t){return u(t)?"number":t.match(/^\d{4}-\d{1,2}-\d{1,2}$/)?"date":"text"}function B(t,e){const n=t.querySelectorAll(e),r=t.shadowRoot?.querySelectorAll(e);return[...Array.from(n),...Array.from(r)]}function K(t){return 2===t.buttons&&!t.ctrlKey||1===t.buttons&&t.ctrlKey}function L(t){return null!=t&&""+t!="false"}export{x as addAttributeValue,E as assignSlotNames,L as coerceBooleanProperty,K as contextMenuClick,H as createFragment,l as focusableSelectors,b as getElementWidth,h as getElementWidthUnless,W as getInputValueType,S as getShadowRootOrElse,q as getWindowDimensions,A as hasAttributeAndIsNotEmpty,c as isFocusable,m as isHTMLElement,a as isScrollable,C as isVisible,s as queryAllFocusable,j as queryChildFromLightOrShadowDom,B as querySelectorRoots,w as removeAttributeValue,y as removeAttributes,p as setAttributes,g as setOrRemoveAttribute,R as spanWrapper,f as tabFlowSelectors,v as windowIsAboveMobileBreakpoint};
|
|
2
2
|
//# sourceMappingURL=dom.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom.js","sources":["../../../../src/internal/utils/dom.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport includes from 'ramda/es/includes.js';\nimport without from 'ramda/es/without.js';\nimport { getCssPropertyValue } from './css.js';\nimport { pluckPixelValue, transformSpacedStringToArray } from './string.js';\nimport { isNumericString, isStringAndNotNilOrEmpty } from './identity.js';\n/**\n * We are not going to be opinionated about the use of the disabled attribute here.\n * Browsers will manage that on their own. The focus of this is to determine whether\n * or not a tabindex should be set on an element to make it programmatically\n * focusable.\n *\n */\nexport function isFocusable(element) {\n /* c8 ignore next 21 */\n switch (element.tagName.toLowerCase()) {\n case 'input':\n return (element.getAttribute('type') !== 'hidden' &&\n !element.hasAttribute('disabled') &&\n !element.hasAttribute('readonly'));\n case 'button':\n case 'select':\n case 'textarea':\n return !element.hasAttribute('disabled');\n case 'iframe':\n case 'embed':\n case 'object':\n return true;\n case 'a':\n case 'area':\n return element.hasAttribute('href');\n case 'audio':\n case 'video':\n return element.hasAttribute('controls');\n default:\n // we are not going to get into invalid values sent to the\n // tabindex attr. users have control of that and should avoid\n // setting tabindex to weird/unsupported values.\n return (element.hasAttribute('tabindex') ||\n element.getAttribute('contenteditable') === 'true' ||\n (element.getAttribute('role') === 'button' && !element.hasAttribute('disabled')));\n }\n}\n/* c8 ignore next */\nexport function isScrollable(element) {\n // early return here in the event element looked up but not in the dom at present\n if (!element) {\n return false;\n }\n // there's no great way to determine if something has scrollbars or not\n // this calculation is... okay at it. it is slightly naive but covers\n // our current need/use-case. if we need something more robust, we can\n // update this function to use one of the more complicated checks.\n const boundingRect = element.getBoundingClientRect();\n return (boundingRect.top < 0 ||\n element.scrollHeight > element.offsetHeight ||\n boundingRect.left < 0 ||\n element.scrollWidth > element.clientWidth);\n}\n/**\n * Works only on light DOM because that is all we have needed it for thus far\n *\n */\n/* c8 ignore next */\nexport function queryAllFocusable(element) {\n return element.querySelectorAll(tabFlowSelectors.join(', '));\n}\nconst nonTabIndexFocusableSelectors = [\n 'a[href]',\n 'area[href]',\n 'audio[controls]',\n 'button:not([disabled])',\n 'input:not([type=\"hidden\"]):not([disabled]):not([readonly])',\n 'iframe',\n 'object',\n 'embed',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n 'video[controls]',\n '*[contenteditable=true]',\n '[role=button]:not([disabled])',\n];\nexport const focusableSelectors = ['*[tabindex]', ...nonTabIndexFocusableSelectors];\nexport const tabFlowSelectors = ['*[tabindex]:not([tabindex=\"-1\"])', ...nonTabIndexFocusableSelectors];\nexport function getElementWidth(element, unit = 'px') {\n if (element) {\n return element.getBoundingClientRect ? element.getBoundingClientRect().width + unit : '';\n }\n return '';\n}\nexport function getElementWidthUnless(element, unless) {\n if (!unless) {\n return getElementWidth(element);\n }\n return '';\n}\nexport function isHTMLElement(el) {\n return !!el && el instanceof HTMLElement;\n}\nexport function hasAttributeAndIsNotEmpty(element, attribute) {\n return !!element && element.hasAttribute(attribute) && isStringAndNotNilOrEmpty(element.getAttribute(attribute));\n}\nexport function setOrRemoveAttribute(element, attrTuple, test) {\n const [attribute, value] = attrTuple;\n if (test()) {\n setAttributes(element, [attribute, value]);\n }\n else {\n removeAttributes(element, attribute);\n }\n}\nexport function setAttributes(element, ...attributeTuples) {\n if (element) {\n attributeTuples.forEach(([attr, val]) => {\n if (val === false || val === null) {\n element.removeAttribute(attr);\n }\n else {\n element.setAttribute(attr, val + '');\n }\n });\n }\n}\nexport function removeAttributes(element, ...attrs) {\n if (element) {\n attrs.forEach(attr => {\n element.removeAttribute(attr);\n });\n }\n}\nexport function addAttributeValue(element, attr, value) {\n if (element) {\n const currentAttrVal = element.getAttribute(attr);\n if (!currentAttrVal) {\n element.setAttribute(attr, value);\n }\n else if (!includes(value, currentAttrVal.split(' '))) {\n // add it only if it is not already there\n element.setAttribute(attr, currentAttrVal + ' ' + value);\n }\n }\n}\nexport function removeAttributeValue(element, attr, value) {\n if (element) {\n const currentAttrVal = element.getAttribute(attr);\n if (currentAttrVal) {\n // remove the specified value from the list of values currently set\n const attrValues = without([value], transformSpacedStringToArray(currentAttrVal));\n const newAttrValue = attrValues.join(' ');\n if (newAttrValue) {\n element.setAttribute(attr, newAttrValue);\n }\n else {\n element.removeAttribute(attr);\n }\n }\n }\n}\nexport function assignSlotNames(...slotTuples) {\n slotTuples.forEach(slotTuple => {\n const [el, slotName] = slotTuple;\n if (el) {\n setAttributes(el, ['slot', slotName]);\n }\n });\n}\nexport function isVisible(element) {\n return !!element && element?.offsetHeight > 0 && element?.hasAttribute('hidden') === false;\n}\nexport function spanWrapper(nodeList) {\n Array.from(nodeList)\n .filter(node => node.textContent && node.textContent.trim().length > 0 && node.nodeType === 3 && node.parentElement)\n .forEach(node => {\n const spanWrapper = document.createElement('span');\n node.after(spanWrapper);\n spanWrapper.appendChild(node);\n });\n}\nexport function queryChildFromLightOrShadowDom(hostEl, selector) {\n if (!selector) {\n return null;\n }\n return hostEl.querySelector(selector) || hostEl?.shadowRoot?.querySelector(selector) || null;\n}\nexport function createFragment(tagString) {\n return document.createRange().createContextualFragment(tagString);\n}\nexport function getWindowDimensions(win = window) {\n const doc = win?.document;\n const h = win?.innerHeight || doc?.documentElement?.clientHeight || 0;\n const w = win?.innerWidth || doc?.documentElement?.clientWidth || 0;\n return { width: w, height: h };\n}\nexport function windowIsAboveMobileBreakpoint(breakpointAsPixelValue) {\n const breakpointVal = breakpointAsPixelValue || getCssPropertyValue('--cds-global-layout-width-xs').trim();\n return breakpointAsPixelValue?.endsWith('px') ? pluckPixelValue(breakpointVal) >= getWindowDimensions().width : false;\n}\nexport function getShadowRootOrElse(hostEl, fallbackEl) {\n const fallTo = fallbackEl ? fallbackEl : hostEl;\n return (hostEl.shadowRoot ? hostEl.shadowRoot : fallTo);\n}\nexport function getInputValueType(value) {\n if (isNumericString(value)) {\n return 'number';\n }\n else if (value.match(/^\\d{4}-\\d{1,2}-\\d{1,2}$/)) {\n return 'date';\n }\n else {\n return 'text';\n }\n}\n// todo cory: test\nexport function querySelectorRoots(element, selector) {\n const root = element.querySelectorAll(selector);\n const shadowRoot = element.shadowRoot?.querySelectorAll(selector);\n return [...Array.from(root), ...Array.from(shadowRoot)];\n}\n// todo cory: test\n/**\n * Checks for right click with context menus & keyboard mouse control https://apple.stackexchange.com/questions/32715/how-do-i-open-the-context-menu-from-a-mac-keyboard\n */\nexport function contextMenuClick(event) {\n return (event.buttons === 2 && !event.ctrlKey) || (event.buttons === 1 && event.ctrlKey);\n}\n/** Coerces attribute/property value to a boolean */\nexport function coerceBooleanProperty(value) {\n return value !== null && value !== undefined && `${value}` !== 'false';\n}\n"],"names":["isFocusable","element","tagName","toLowerCase","getAttribute","hasAttribute","isScrollable","boundingRect","getBoundingClientRect","top","scrollHeight","offsetHeight","left","scrollWidth","clientWidth","queryAllFocusable","querySelectorAll","tabFlowSelectors","join","nonTabIndexFocusableSelectors","focusableSelectors","getElementWidth","unit","width","getElementWidthUnless","unless","isHTMLElement","el","HTMLElement","hasAttributeAndIsNotEmpty","attribute","isStringAndNotNilOrEmpty","setOrRemoveAttribute","attrTuple","test","value","setAttributes","removeAttributes","attributeTuples","forEach","attr","val","removeAttribute","setAttribute","attrs","addAttributeValue","currentAttrVal","includes","split","removeAttributeValue","newAttrValue","without","transformSpacedStringToArray","assignSlotNames","slotTuples","slotTuple","slotName","isVisible","spanWrapper","nodeList","Array","from","filter","node","textContent","trim","length","nodeType","parentElement","document","createElement","after","appendChild","queryChildFromLightOrShadowDom","hostEl","selector","querySelector","shadowRoot","createFragment","tagString","createRange","createContextualFragment","getWindowDimensions","win","window","doc","h","innerHeight","documentElement","clientHeight","innerWidth","height","windowIsAboveMobileBreakpoint","breakpointAsPixelValue","breakpointVal","getCssPropertyValue","endsWith","pluckPixelValue","getShadowRootOrElse","fallbackEl","fallTo","getInputValueType","isNumericString","match","querySelectorRoots","root","contextMenuClick","event","buttons","ctrlKey","coerceBooleanProperty"],"mappings":"oRAiBO,SAASA,EAAYC,GAExB,OAAQA,EAAQC,QAAQC,eACpB,IAAK,QACD,MAAyC,WAAjCF,EAAQG,aAAa,UACxBH,EAAQI,aAAa,cACrBJ,EAAQI,aAAa,YAC9B,IAAK,SACL,IAAK,SACL,IAAK,WACD,OAAQJ,EAAQI,aAAa,YACjC,IAAK,SACL,IAAK,QACL,IAAK,SACD,OAAO,EACX,IAAK,IACL,IAAK,OACD,OAAOJ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pE,MAAO,CAAElE,MADC4D,GAAKO,YAAcL,GAAKG,iBAAiB1E,aAAe,EAC/C6E,OAAQL,GAExB,SAASM,EAA8BC,GAC1C,MAAMC,EAAgBD,GAA0BE,EAAoB,gCAAgC9B,OACpG,QAAO4B,GAAwBG,SAAS,OAAQC,EAAgBH,IAAkBZ,IAAsB3D,MAErG,SAAS2E,EAAoBxB,EAAQyB,GACxC,MAAMC,EAASD,GAA0BzB,EACzC,OAAQA,EAAOG,WAAaH,EAAOG,WAAauB,EAE7C,SAASC,EAAkBlE,GAC9B,OAAImE,EAAgBnE,GACT,SAEFA,EAAMoE,MAAM,2BACV,OAGA,OAIR,SAASC,EAAmBvG,EAAS0E,GACxC,MAAM8B,EAAOxG,EAAQe,iBAAiB2D,GAChCE,EAAa5E,EAAQ4E,YAAY7D,iBAAiB2D,GACxD,MAAO,IAAIf,MAAMC,KAAK4C,MAAU7C,MAAMC,KAAKgB,IAMxC,SAAS6B,EAAiBC,GAC7B,OAA0B,IAAlBA,EAAMC,UAAkBD,EAAME,SAA+B,IAAlBF,EAAMC,SAAiBD,EAAME,QAG7E,SAASC,EAAsB3E,GAClC,OAAOA,MAAAA,GAAyC,GAAGA,GAAY"}
|
|
1
|
+
{"version":3,"file":"dom.js","sources":["../../../../src/internal/utils/dom.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport includes from 'ramda/es/includes';\nimport without from 'ramda/es/without';\nimport { getCssPropertyValue } from './css.js';\nimport { pluckPixelValue, transformSpacedStringToArray } from './string.js';\nimport { isNumericString, isStringAndNotNilOrEmpty } from './identity.js';\n/**\n * We are not going to be opinionated about the use of the disabled attribute here.\n * Browsers will manage that on their own. The focus of this is to determine whether\n * or not a tabindex should be set on an element to make it programmatically\n * focusable.\n *\n */\nexport function isFocusable(element) {\n /* c8 ignore next 21 */\n switch (element.tagName.toLowerCase()) {\n case 'input':\n return (element.getAttribute('type') !== 'hidden' &&\n !element.hasAttribute('disabled') &&\n !element.hasAttribute('readonly'));\n case 'button':\n case 'select':\n case 'textarea':\n return !element.hasAttribute('disabled');\n case 'iframe':\n case 'embed':\n case 'object':\n return true;\n case 'a':\n case 'area':\n return element.hasAttribute('href');\n case 'audio':\n case 'video':\n return element.hasAttribute('controls');\n default:\n // we are not going to get into invalid values sent to the\n // tabindex attr. users have control of that and should avoid\n // setting tabindex to weird/unsupported values.\n return (element.hasAttribute('tabindex') ||\n element.getAttribute('contenteditable') === 'true' ||\n (element.getAttribute('role') === 'button' && !element.hasAttribute('disabled')));\n }\n}\n/* c8 ignore next */\nexport function isScrollable(element) {\n // early return here in the event element looked up but not in the dom at present\n if (!element) {\n return false;\n }\n // there's no great way to determine if something has scrollbars or not\n // this calculation is... okay at it. it is slightly naive but covers\n // our current need/use-case. if we need something more robust, we can\n // update this function to use one of the more complicated checks.\n const boundingRect = element.getBoundingClientRect();\n return (boundingRect.top < 0 ||\n element.scrollHeight > element.offsetHeight ||\n boundingRect.left < 0 ||\n element.scrollWidth > element.clientWidth);\n}\n/**\n * Works only on light DOM because that is all we have needed it for thus far\n *\n */\n/* c8 ignore next */\nexport function queryAllFocusable(element) {\n return element.querySelectorAll(tabFlowSelectors.join(', '));\n}\nconst nonTabIndexFocusableSelectors = [\n 'a[href]',\n 'area[href]',\n 'audio[controls]',\n 'button:not([disabled])',\n 'input:not([type=\"hidden\"]):not([disabled]):not([readonly])',\n 'iframe',\n 'object',\n 'embed',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n 'video[controls]',\n '*[contenteditable=true]',\n '[role=button]:not([disabled])',\n];\nexport const focusableSelectors = ['*[tabindex]', ...nonTabIndexFocusableSelectors];\nexport const tabFlowSelectors = ['*[tabindex]:not([tabindex=\"-1\"])', ...nonTabIndexFocusableSelectors];\nexport function getElementWidth(element, unit = 'px') {\n if (element) {\n return element.getBoundingClientRect ? element.getBoundingClientRect().width + unit : '';\n }\n return '';\n}\nexport function getElementWidthUnless(element, unless) {\n if (!unless) {\n return getElementWidth(element);\n }\n return '';\n}\nexport function isHTMLElement(el) {\n return !!el && el instanceof HTMLElement;\n}\nexport function hasAttributeAndIsNotEmpty(element, attribute) {\n return !!element && element.hasAttribute(attribute) && isStringAndNotNilOrEmpty(element.getAttribute(attribute));\n}\nexport function setOrRemoveAttribute(element, attrTuple, test) {\n const [attribute, value] = attrTuple;\n if (test()) {\n setAttributes(element, [attribute, value]);\n }\n else {\n removeAttributes(element, attribute);\n }\n}\nexport function setAttributes(element, ...attributeTuples) {\n if (element) {\n attributeTuples.forEach(([attr, val]) => {\n if (val === false || val === null) {\n element.removeAttribute(attr);\n }\n else {\n element.setAttribute(attr, val + '');\n }\n });\n }\n}\nexport function removeAttributes(element, ...attrs) {\n if (element) {\n attrs.forEach(attr => {\n element.removeAttribute(attr);\n });\n }\n}\nexport function addAttributeValue(element, attr, value) {\n if (element) {\n const currentAttrVal = element.getAttribute(attr);\n if (!currentAttrVal) {\n element.setAttribute(attr, value);\n }\n else if (!includes(value, currentAttrVal.split(' '))) {\n // add it only if it is not already there\n element.setAttribute(attr, currentAttrVal + ' ' + value);\n }\n }\n}\nexport function removeAttributeValue(element, attr, value) {\n if (element) {\n const currentAttrVal = element.getAttribute(attr);\n if (currentAttrVal) {\n // remove the specified value from the list of values currently set\n const attrValues = without([value], transformSpacedStringToArray(currentAttrVal));\n const newAttrValue = attrValues.join(' ');\n if (newAttrValue) {\n element.setAttribute(attr, newAttrValue);\n }\n else {\n element.removeAttribute(attr);\n }\n }\n }\n}\nexport function assignSlotNames(...slotTuples) {\n slotTuples.forEach(slotTuple => {\n const [el, slotName] = slotTuple;\n if (el) {\n setAttributes(el, ['slot', slotName]);\n }\n });\n}\nexport function isVisible(element) {\n return !!element && element?.offsetHeight > 0 && element?.hasAttribute('hidden') === false;\n}\nexport function spanWrapper(nodeList) {\n Array.from(nodeList)\n .filter(node => node.textContent && node.textContent.trim().length > 0 && node.nodeType === 3 && node.parentElement)\n .forEach(node => {\n const spanWrapper = document.createElement('span');\n node.after(spanWrapper);\n spanWrapper.appendChild(node);\n });\n}\nexport function queryChildFromLightOrShadowDom(hostEl, selector) {\n if (!selector) {\n return null;\n }\n return hostEl.querySelector(selector) || hostEl?.shadowRoot?.querySelector(selector) || null;\n}\nexport function createFragment(tagString) {\n return document.createRange().createContextualFragment(tagString);\n}\nexport function getWindowDimensions(win = window) {\n const doc = win?.document;\n const h = win?.innerHeight || doc?.documentElement?.clientHeight || 0;\n const w = win?.innerWidth || doc?.documentElement?.clientWidth || 0;\n return { width: w, height: h };\n}\nexport function windowIsAboveMobileBreakpoint(breakpointAsPixelValue) {\n const breakpointVal = breakpointAsPixelValue || getCssPropertyValue('--cds-global-layout-width-xs').trim();\n return breakpointAsPixelValue?.endsWith('px') ? pluckPixelValue(breakpointVal) >= getWindowDimensions().width : false;\n}\nexport function getShadowRootOrElse(hostEl, fallbackEl) {\n const fallTo = fallbackEl ? fallbackEl : hostEl;\n return (hostEl.shadowRoot ? hostEl.shadowRoot : fallTo);\n}\nexport function getInputValueType(value) {\n if (isNumericString(value)) {\n return 'number';\n }\n else if (value.match(/^\\d{4}-\\d{1,2}-\\d{1,2}$/)) {\n return 'date';\n }\n else {\n return 'text';\n }\n}\n// todo cory: test\nexport function querySelectorRoots(element, selector) {\n const root = element.querySelectorAll(selector);\n const shadowRoot = element.shadowRoot?.querySelectorAll(selector);\n return [...Array.from(root), ...Array.from(shadowRoot)];\n}\n// todo cory: test\n/**\n * Checks for right click with context menus & keyboard mouse control https://apple.stackexchange.com/questions/32715/how-do-i-open-the-context-menu-from-a-mac-keyboard\n */\nexport function contextMenuClick(event) {\n return (event.buttons === 2 && !event.ctrlKey) || (event.buttons === 1 && event.ctrlKey);\n}\n/** Coerces attribute/property value to a boolean */\nexport function coerceBooleanProperty(value) {\n return value !== null && value !== undefined && `${value}` !== 'false';\n}\n"],"names":["isFocusable","element","tagName","toLowerCase","getAttribute","hasAttribute","isScrollable","boundingRect","getBoundingClientRect","top","scrollHeight","offsetHeight","left","scrollWidth","clientWidth","queryAllFocusable","querySelectorAll","tabFlowSelectors","join","nonTabIndexFocusableSelectors","focusableSelectors","getElementWidth","unit","width","getElementWidthUnless","unless","isHTMLElement","el","HTMLElement","hasAttributeAndIsNotEmpty","attribute","isStringAndNotNilOrEmpty","setOrRemoveAttribute","attrTuple","test","value","setAttributes","removeAttributes","attributeTuples","forEach","attr","val","removeAttribute","setAttribute","attrs","addAttributeValue","currentAttrVal","includes","split","removeAttributeValue","newAttrValue","without","transformSpacedStringToArray","assignSlotNames","slotTuples","slotTuple","slotName","isVisible","spanWrapper","nodeList","Array","from","filter","node","textContent","trim","length","nodeType","parentElement","document","createElement","after","appendChild","queryChildFromLightOrShadowDom","hostEl","selector","querySelector","shadowRoot","createFragment","tagString","createRange","createContextualFragment","getWindowDimensions","win","window","doc","h","innerHeight","documentElement","clientHeight","innerWidth","height","windowIsAboveMobileBreakpoint","breakpointAsPixelValue","breakpointVal","getCssPropertyValue","endsWith","pluckPixelValue","getShadowRootOrElse","fallbackEl","fallTo","getInputValueType","isNumericString","match","querySelectorRoots","root","contextMenuClick","event","buttons","ctrlKey","coerceBooleanProperty"],"mappings":"8QAiBO,SAASA,EAAYC,GAExB,OAAQA,EAAQC,QAAQC,eACpB,IAAK,QACD,MAAyC,WAAjCF,EAAQG,aAAa,UACxBH,EAAQI,aAAa,cACrBJ,EAAQI,aAAa,YAC9B,IAAK,SACL,IAAK,SACL,IAAK,WACD,OAAQJ,EAAQI,aAAa,YACjC,IAAK,SACL,IAAK,QACL,IAAK,SACD,OAAO,EACX,IAAK,IACL,IAAK,OACD,OAAOJ,EAAQI,aAAa,QAChC,IAAK,QACL,IAAK,QACD,OAAOJ,EAAQI,aAAa,YAChC,QAII,OAAQJ,EAAQI,aAAa,aACmB,SAA5CJ,EAAQG,aAAa,oBACa,WAAjCH,EAAQG,aAAa,UAAyBH,EAAQI,aAAa,aAI7E,SAASC,EAAa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IAAkBZ,IAAsB3D,MAErG,SAAS2E,EAAoBxB,EAAQyB,GACxC,MAAMC,EAASD,GAA0BzB,EACzC,OAAQA,EAAOG,WAAaH,EAAOG,WAAauB,EAE7C,SAASC,EAAkBlE,GAC9B,OAAImE,EAAgBnE,GACT,SAEFA,EAAMoE,MAAM,2BACV,OAGA,OAIR,SAASC,EAAmBvG,EAAS0E,GACxC,MAAM8B,EAAOxG,EAAQe,iBAAiB2D,GAChCE,EAAa5E,EAAQ4E,YAAY7D,iBAAiB2D,GACxD,MAAO,IAAIf,MAAMC,KAAK4C,MAAU7C,MAAMC,KAAKgB,IAMxC,SAAS6B,EAAiBC,GAC7B,OAA0B,IAAlBA,EAAMC,UAAkBD,EAAME,SAA+B,IAAlBF,EAAMC,SAAiBD,EAAME,QAG7E,SAASC,EAAsB3E,GAClC,OAAOA,MAAAA,GAAyC,GAAGA,GAAY"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export declare const existsIn: (
|
|
1
|
+
export declare const existsIn: import("ts-toolbelt/out/Function/Curry").Curry<(a_0: string[], a_1: object) => boolean>;
|
|
2
2
|
export declare function elementExists(tagName: string, registry?: CustomElementRegistry): boolean;
|
|
3
|
-
export declare const existsInWindow:
|
|
3
|
+
export declare const existsInWindow: import("ts-toolbelt/out/Function/Curry").Curry<(p_0: string[], p_1: object) => boolean>;
|
package/internal/utils/exists.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import o from"ramda/es/curryN
|
|
1
|
+
import o from"ramda/es/curryN";import r from"ramda/es/path";import t from"./__.js";const m=o(2,((o,t)=>void 0!==r(o,t)));function n(o,r){return r||(r=window&&window.customElements),!r||!!r.get(o)}const i=m(t,window);export{n as elementExists,m as existsIn,i as existsInWindow};
|
|
2
2
|
//# sourceMappingURL=exists.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exists.js","sources":["../../../../src/internal/utils/exists.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport curryN from 'ramda/es/curryN
|
|
1
|
+
{"version":3,"file":"exists.js","sources":["../../../../src/internal/utils/exists.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport curryN from 'ramda/es/curryN';\nimport path from 'ramda/es/path';\nimport __ from './__.js';\nexport const existsIn = curryN(2, (pathToCheck, obj) => {\n const pathExists = path(pathToCheck, obj);\n return typeof pathExists !== 'undefined';\n});\nexport function elementExists(tagName, registry) {\n if (!registry) {\n registry = window && window.customElements;\n }\n if (!registry) {\n return true; // we don't want to execute further actions because window does not exist\n }\n return !!registry.get(tagName);\n}\nexport const existsInWindow = existsIn(__, window);\n"],"names":["existsIn","curryN","pathToCheck","obj","path","elementExists","tagName","registry","window","customElements","get","existsInWindow","__"],"mappings":"mFAQY,MAACA,EAAWC,EAAO,GAAG,CAACC,EAAaC,SAEf,IADVC,EAAKF,EAAaC,KAGlC,SAASE,EAAcC,EAASC,GAInC,OAHKA,IACDA,EAAWC,QAAUA,OAAOC,iBAE3BF,KAGIA,EAASG,IAAIJ,GAEd,MAACK,EAAiBX,EAASY,EAAIJ"}
|
package/internal/utils/global.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isBrowser as e}from"./environment.js";import{getAngularVersion as n,getAngularJSVersion as o,getReactVersion as t,getVueVersion as i}from"./framework.js";import{browserFeatures as s}from"./supports.js";import{LogService as r}from"../services/log.service.js";function w(){e()&&(window.CDS=window.CDS||{_version:[],_react:{version:void 0},_supports:s.supports,_isStateProxied:!1,_state:{focusTrapItems:[],layerElements:[],i18nRegistry:{},elementRegistry:{},iconRegistry:{},motionRegistry:{}},environment:{production:!1},getDetails:a,logDetails:d},function(){const e="6.4.
|
|
1
|
+
import{isBrowser as e}from"./environment.js";import{getAngularVersion as n,getAngularJSVersion as o,getReactVersion as t,getVueVersion as i}from"./framework.js";import{browserFeatures as s}from"./supports.js";import{LogService as r}from"../services/log.service.js";function w(){e()&&(window.CDS=window.CDS||{_version:[],_react:{version:void 0},_supports:s.supports,_isStateProxied:!1,_state:{focusTrapItems:[],layerElements:[],i18nRegistry:{},elementRegistry:{},iconRegistry:{},motionRegistry:{}},environment:{production:!1},getDetails:a,logDetails:d},function(){const e="6.4.1";window.CDS._version.indexOf(e)<0&&(window.CDS._version.push(e),document.querySelector("body")?.setAttribute("cds-version",window.CDS._version.join(" "))),window.CDS._version.length>1&&r.warn("Running more than one version of Clarity can cause unexpected issues. Please ensure only one version is loaded.")}(),window.CDS._isStateProxied||(window.CDS._isStateProxied=!0,window.CDS._state=new Proxy(window.CDS._state,{set:(e,n,o)=>{const t={key:n,prev:window.CDS._state[n],current:o};return e[n]=o,document.dispatchEvent(new CustomEvent("CDS_STATE_UPDATE",{detail:t})),!0}})))}function a(){return{versions:window.CDS._version,environment:window.CDS.environment,userAgent:navigator.userAgent,supports:window.CDS._supports,angularVersion:n(!1),angularJSVersion:o(!1),reactVersion:t(!1),vueVersion:i(!1),state:{...window.CDS._state,iconRegistry:Object.keys(window.CDS._state.iconRegistry),motionRegistry:Object.keys(window.CDS._state.motionRegistry),focusTrapRegistry:Object.keys(window.CDS._state.focusTrapItems.map((e=>e.focusTrapId)))}}}function d(){r.log(JSON.stringify(a(),null,2))}export{w as setupCDSGlobal};
|
|
2
2
|
//# sourceMappingURL=global.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"ramda/es/is
|
|
1
|
+
import t from"ramda/es/is";import n from"ramda/es/isEmpty";function r(t){return null==t}function e(t){return r(t)||n(t)}function u(n){return t(String,n)}function i(t){return u(t)&&!n(t.trim())&&+t==+t}function c(n){return t(String,n)||r(n)}function s(t){return u(t)&&!r(t)&&!n(t)}function f(n){return t(Object,n)}function a(n){return t(Map,n)}function o(t){return!e(t)&&f(t)}function l(t,n){return t!==n}function d(t,n){return c(t)&&l(t,n)}function h(t,n){return!e(t)&&l(t,n)}function m(t){return Object.values(t)}function p(t="_"){return`${t}${Math.random().toString(36).substr(2,9)}`}function g(t,n){return JSON.stringify(t)===JSON.stringify(n)}function y(t,n,r=`\${${t}}`){return t.split(".").reduce(((t,n)=>{try{const e=t[n];switch(!0){case null===e:case!1===e:case""===e:case 0===e:return e;default:return e||r}}catch{return r}}),n)}function A(t){const n=new Map;for(const[r,e]of t)a(e)?n.set(r,A(e)):n.set(r,e);return n}function b(t){switch(!0){case a(t):return A(t);case f(t)&&!Array.isArray(t):return x({},t);default:return JSON.parse(JSON.stringify(t))}}function O(t){switch(!0){case"true"===t:return!0;case"false"===t:return!1;case"null"===t:return null;case"undefined"===t:return;case i(t):return+t;default:return t}}function S(t){return t.split(" ").map((t=>t.split(":"))).map((t=>{const[n,r]=t;return[n,O(r)]}))}function w(t,n,r){if(!n)return!0;const e=S(n);if(!t)return!1;if(e.length<1)return!0;{const n=e.filter((n=>{const[r,e]=n;return $(t,r,e)}));return"all"===r?n.length===e.length:n.length>0}}function J(t,n){return w(t,n,"all")}function N(t,n){return w(t,n,"any")}function $(t,n,r){if(n in t)return!1===r?!t[n]:t[n]===r;if(!t.hasAttribute||!t.hasAttribute(n))return!t.hasAttribute&&(!1===r||void 0===r)||!1;{const e=t.hasAttribute(n)&&t.getAttribute(n);if(["null","false","undefined"].indexOf(e)>-1)switch(r){case null:return"null"===e;case!1:return"false"===e;default:return!r}else switch(r){case!1:return!e||"false"===e;case!0:return""===e||"true"===e;default:return e===r.toString()}}}function j(t,...n){return n.map((n=>t(n))).indexOf(!1)<0}function v(...t){return j((t=>void 0!==t),...t)}function x(...t){const n={};return t.map((t=>f(t)?{...t}:{})).forEach((t=>{Object.keys(t).forEach((r=>{const e=t[r];Array.isArray(e)?n[r]=Array.from(e):f(e)?n[r]=x(n[r]||{},e):n[r]=e}))})),n}export{j as allAre,v as allAreDefined,J as allPropertiesPass,w as anyOrAllPropertiesPass,N as anyPropertiesPass,O as convertAttributeStringValuesToValue,S as convertStringPropValuePairsToTuple,p as createId,b as deepClone,$ as doesPropertyPass,m as getEnumValues,y as getFromObjectPath,l as hasPropertyChanged,d as hasStringPropertyChanged,h as hasStringPropertyChangedAndNotNil,a as isMap,r as isNil,e as isNilOrEmpty,i as isNumericString,f as isObject,o as isObjectAndNotNilOrEmpty,u as isString,s as isStringAndNotNilOrEmpty,c as isStringOrNil,x as mergeObjects,g as objectNaiveDeepEquals};
|
|
2
2
|
//# sourceMappingURL=identity.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity.js","sources":["../../../../src/internal/utils/identity.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport is from 'ramda/es/is.js';\nimport isEmpty from 'ramda/es/isEmpty.js';\nexport function isNil(val) {\n return val === null || val === undefined;\n}\nexport function isNilOrEmpty(val) {\n return isNil(val) || isEmpty(val);\n}\nexport function isString(val) {\n return is(String, val);\n}\nexport function isNumericString(val) {\n return isString(val) && !isEmpty(val.trim()) && +val === +val;\n}\nexport function isStringOrNil(val) {\n return is(String, val) || isNil(val);\n}\nexport function isStringAndNotNilOrEmpty(val) {\n return isString(val) && !isNil(val) && !isEmpty(val);\n}\nexport function isObject(val) {\n return is(Object, val);\n}\nexport function isMap(val) {\n return is(Map, val);\n}\nexport function isObjectAndNotNilOrEmpty(val) {\n return !isNilOrEmpty(val) && isObject(val);\n}\nexport function hasPropertyChanged(val, oldVal) {\n return val !== oldVal;\n}\n// marks nil values (undefined, null, empty string) as changed\nexport function hasStringPropertyChanged(val, oldVal) {\n return isStringOrNil(val) && hasPropertyChanged(val, oldVal);\n}\n// ignores nil values when checking for changes\nexport function hasStringPropertyChangedAndNotNil(val, oldVal) {\n return !isNilOrEmpty(val) && hasPropertyChanged(val, oldVal);\n}\nexport function getEnumValues(enumeration) {\n return Object.values(enumeration);\n}\nexport function createId(prefix = '_') {\n return `${prefix}${Math.random().toString(36).substr(2, 9)}`;\n}\n// simplistic way to test objects for equality\n// note that it ignores/removes methods from objects\nexport function objectNaiveDeepEquals(obj1, obj2) {\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n}\nexport function getFromObjectPath(path, dataObj, fallback = `$\\{${path}}`) {\n return path.split('.').reduce((res, key) => {\n try {\n const val = res[key];\n switch (true) {\n case val === null:\n case val === false:\n case val === '':\n case val === 0:\n return val;\n default:\n return val || fallback;\n }\n }\n catch {\n return fallback;\n }\n }, dataObj);\n}\n// used by deepClone() tested through integration\nfunction cloneMap(mp) {\n const clonedMap = new Map();\n for (const [key, val] of mp) {\n if (isMap(val)) {\n clonedMap.set(key, cloneMap(val));\n }\n else {\n clonedMap.set(key, val);\n }\n }\n return clonedMap;\n}\nexport function deepClone(obj) {\n // this will clone almost anything (maps, arrays, objects, etc.) to the lowest of the low levels\n // be careful using this carelessly b/c it CAN have performance implications!\n switch (true) {\n case isMap(obj):\n return cloneMap(obj);\n case isObject(obj) && !Array.isArray(obj):\n return mergeObjects({}, obj);\n default:\n return JSON.parse(JSON.stringify(obj));\n }\n}\n/* c8 ignore next 2 */\nexport function convertAttributeStringValuesToValue(stringValue) {\n switch (true) {\n case stringValue === 'true':\n return true;\n case stringValue === 'false':\n return false;\n case stringValue === 'null':\n return null;\n case stringValue === 'undefined':\n return void 0; // undefined\n case isNumericString(stringValue):\n return +stringValue;\n default:\n // else it's a string and that's ok\n return stringValue;\n }\n}\n// this utility is a little restrictive on its inputs. it expects a specific format.\n// going outside of that format (like passing an object or function as the value) can yield unintended results.\n// this does NOT eval anything. that would be bad.\n// 'isValid:true status:success': string =>\n// [['isValid', true], ['status', 'success']]: [string, string | number | boolean][]\nexport function convertStringPropValuePairsToTuple(propValString) {\n // starts as a string like... \"isValid:true status:success\"\n return propValString\n .split(' ')\n .map(str => str.split(':'))\n .map(pv => {\n const [propname, propValAsString] = pv;\n return [propname, convertAttributeStringValuesToValue(propValAsString)];\n });\n // returns as [['isValid', true], ['status', 'success']]\n}\nexport function anyOrAllPropertiesPass(obj, propValuePairs, anyOrAll) {\n if (!propValuePairs) {\n return true;\n }\n const tests = convertStringPropValuePairsToTuple(propValuePairs);\n if (!obj) {\n return false;\n }\n if (tests.length < 1) {\n return true;\n }\n else {\n const testResults = tests.filter(pvArry => {\n const [propname, expectedVal] = pvArry;\n return doesPropertyPass(obj, propname, expectedVal);\n });\n return anyOrAll === 'all' ? testResults.length === tests.length : testResults.length > 0;\n }\n}\nexport function allPropertiesPass(obj, propValuePairs) {\n return anyOrAllPropertiesPass(obj, propValuePairs, 'all');\n}\nexport function anyPropertiesPass(obj, propValuePairs) {\n return anyOrAllPropertiesPass(obj, propValuePairs, 'any');\n}\n// TODO: BREAK THIS UP. TRIED ONCE. TOO CONVOLUTED.\n/**\n * This function takes an object (e.g. { ohai: 'hello', count: 2 }) or an Element\n * (e.g. <p ohai=\"hello\" count=\"2\">i am an html element</p>).\n *\n * It also takes a string that represents a potential property or attribute on the\n * object or element (e.g. \"ohai\" or \"count\").\n *\n * Lastly, it takes a potential value for the potential property or attribute\n * (e.g. \"hello\" or 2).\n *\n * If the object/element has the string as a property or attribute and the value\n * of the property/attribute equals the expected value, it returns true. If not,\n * it returns false.\n *\n * This code is the brains behind our \"key:value\" strings found in Clarity Motion.\n * (e.g. { hidden: true, onlyIf: \"responsive:false\", animation: ...})\n *\n * @export\n * @param {*} objectOrElement\n * @param {string} propertyOrAttributeName\n * @param {(string | number | boolean | null | undefined)} expectedValue\n * @returns {boolean}\n */\nexport function doesPropertyPass(objectOrElement, propertyOrAttributeName, expectedValue) {\n if (propertyOrAttributeName in objectOrElement) {\n // test expected key/value as object property first because it's less complicated\n if (expectedValue === false) {\n return !objectOrElement[propertyOrAttributeName];\n }\n else {\n return objectOrElement[propertyOrAttributeName] === expectedValue;\n }\n }\n else if (objectOrElement.hasAttribute &&\n objectOrElement.hasAttribute(propertyOrAttributeName)) {\n // test expected key/value as if an attribute on an element\n const propAsAttributeValue = objectOrElement.hasAttribute(propertyOrAttributeName) &&\n objectOrElement.getAttribute(propertyOrAttributeName);\n // sometimes attribute values can get set as string representations of\n // falsy states (see: boolean attribute with a string \"false\" value).\n // this catches that and less likely but still problematic misstep of\n // hard-setting with a string of \"undefined\" or \"null\"\n if (['null', 'false', 'undefined'].indexOf(propAsAttributeValue) > -1) {\n switch (expectedValue) {\n case null:\n return propAsAttributeValue === 'null';\n case false:\n return propAsAttributeValue === 'false';\n default:\n return !expectedValue;\n }\n }\n else {\n // after handling the weird edge case above, this is the more straightforward\n // value check.\n switch (expectedValue) {\n case false:\n return !propAsAttributeValue || propAsAttributeValue === 'false';\n case true:\n return propAsAttributeValue === '' || propAsAttributeValue === 'true';\n default:\n return propAsAttributeValue === expectedValue.toString();\n }\n }\n }\n else {\n // this is not an object property or an attribute on an element attribute so we need\n // to verify if it's expected to be undefined or false. If so, the attribute not being\n // present on the element (see: boolean attrs) meets expectations and return true.\n return ((!objectOrElement.hasAttribute && (expectedValue === false || expectedValue === undefined)) || false);\n }\n}\nexport function allAre(testFn, ...itemsToCheck) {\n return itemsToCheck.map(item => testFn(item)).indexOf(false) < 0;\n}\nexport function allAreDefined(...items) {\n const testFn = (val) => {\n return val !== undefined;\n };\n return allAre(testFn, ...items);\n}\nexport function mergeObjects(...objs) {\n const returnObj = {};\n const clones = objs.map(o => {\n // cloning here so we don't get messed up with object references\n return isObject(o) ? { ...o } : {};\n });\n clones.forEach(srcObj => {\n Object.keys(srcObj).forEach(prop => {\n const propVal = srcObj[prop];\n if (Array.isArray(propVal)) {\n returnObj[prop] = Array.from(propVal);\n }\n else if (isObject(propVal)) {\n returnObj[prop] = mergeObjects(returnObj[prop] || {}, propVal);\n }\n else {\n returnObj[prop] = propVal;\n }\n });\n });\n return returnObj;\n}\n"],"names":["isNil","val","isNilOrEmpty","isEmpty","isString","is","String","isNumericString","trim","isStringOrNil","isStringAndNotNilOrEmpty","isObject","Object","isMap","Map","isObjectAndNotNilOrEmpty","hasPropertyChanged","oldVal","hasStringPropertyChanged","hasStringPropertyChangedAndNotNil","getEnumValues","enumeration","values","createId","prefix","Math","random","toString","substr","objectNaiveDeepEquals","obj1","obj2","JSON","stringify","getFromObjectPath","path","dataObj","fallback","split","reduce","res","key","cloneMap","mp","clonedMap","set","deepClone","obj","Array","isArray","mergeObjects","parse","convertAttributeStringValuesToValue","stringValue","convertStringPropValuePairsToTuple","propValString","map","str","pv","propname","propValAsString","anyOrAllPropertiesPass","propValuePairs","anyOrAll","tests","length","testResults","filter","pvArry","expectedVal","doesPropertyPass","allPropertiesPass","anyPropertiesPass","objectOrElement","propertyOrAttributeName","expectedValue","hasAttribute","undefined","propAsAttributeValue","getAttribute","indexOf","allAre","testFn","itemsToCheck","item","allAreDefined","items","objs","returnObj","o","forEach","srcObj","keys","prop","propVal","from"],"mappings":"iEAOO,SAASA,EAAMC,GAClB,OAAOA,MAAAA,EAEJ,SAASC,EAAaD,GACzB,OAAOD,EAAMC,IAAQE,EAAQF,GAE1B,SAASG,EAASH,GACrB,OAAOI,EAAGC,OAAQL,GAEf,SAASM,EAAgBN,GAC5B,OAAOG,EAASH,KAASE,EAAQF,EAAIO,UAAYP,IAASA,EAEvD,SAASQ,EAAcR,GAC1B,OAAOI,EAAGC,OAAQL,IAAQD,EAAMC,GAE7B,SAASS,EAAyBT,GACrC,OAAOG,EAASH,KAASD,EAAMC,KAASE,EAAQF,GAE7C,SAASU,EAASV,GACrB,OAAOI,EAAGO,OAAQX,GAEf,SAASY,EAAMZ,GAClB,OAAOI,EAAGS,IAAKb,GAEZ,SAASc,EAAyBd,GACrC,OAAQC,EAAaD,IAAQU,EAASV,GAEnC,SAASe,EAAmBf,EAAKgB,GACpC,OAAOhB,IAAQgB,EAGZ,SAASC,EAAyBjB,EAAKgB,GAC1C,OAAOR,EAAcR,IAAQe,EAAmBf,EAAKgB,GAGlD,SAASE,EAAkClB,EAAKgB,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C,GAI7B,OAAOL,GAHShF,QACG4E,IAAR5E,MAEcqF,GAEtB,SAASpC,KAAgBqC,GAC5B,MAAMC,EAAY,GAmBlB,OAlBeD,EAAK/B,KAAIiC,GAEb9E,EAAS8E,GAAK,IAAKA,GAAM,KAE7BC,SAAQC,IACX/E,OAAOgF,KAAKD,GAAQD,SAAQG,IACxB,MAAMC,EAAUH,EAAOE,GACnB7C,MAAMC,QAAQ6C,GACdN,EAAUK,GAAQ7C,MAAM+C,KAAKD,GAExBnF,EAASmF,GACdN,EAAUK,GAAQ3C,EAAasC,EAAUK,IAAS,GAAIC,GAGtDN,EAAUK,GAAQC,QAIvBN"}
|
|
1
|
+
{"version":3,"file":"identity.js","sources":["../../../../src/internal/utils/identity.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport is from 'ramda/es/is';\nimport isEmpty from 'ramda/es/isEmpty';\nexport function isNil(val) {\n return val === null || val === undefined;\n}\nexport function isNilOrEmpty(val) {\n return isNil(val) || isEmpty(val);\n}\nexport function isString(val) {\n return is(String, val);\n}\nexport function isNumericString(val) {\n return isString(val) && !isEmpty(val.trim()) && +val === +val;\n}\nexport function isStringOrNil(val) {\n return is(String, val) || isNil(val);\n}\nexport function isStringAndNotNilOrEmpty(val) {\n return isString(val) && !isNil(val) && !isEmpty(val);\n}\nexport function isObject(val) {\n return is(Object, val);\n}\nexport function isMap(val) {\n return is(Map, val);\n}\nexport function isObjectAndNotNilOrEmpty(val) {\n return !isNilOrEmpty(val) && isObject(val);\n}\nexport function hasPropertyChanged(val, oldVal) {\n return val !== oldVal;\n}\n// marks nil values (undefined, null, empty string) as changed\nexport function hasStringPropertyChanged(val, oldVal) {\n return isStringOrNil(val) && hasPropertyChanged(val, oldVal);\n}\n// ignores nil values when checking for changes\nexport function hasStringPropertyChangedAndNotNil(val, oldVal) {\n return !isNilOrEmpty(val) && hasPropertyChanged(val, oldVal);\n}\nexport function getEnumValues(enumeration) {\n return Object.values(enumeration);\n}\nexport function createId(prefix = '_') {\n return `${prefix}${Math.random().toString(36).substr(2, 9)}`;\n}\n// simplistic way to test objects for equality\n// note that it ignores/removes methods from objects\nexport function objectNaiveDeepEquals(obj1, obj2) {\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n}\nexport function getFromObjectPath(path, dataObj, fallback = `$\\{${path}}`) {\n return path.split('.').reduce((res, key) => {\n try {\n const val = res[key];\n switch (true) {\n case val === null:\n case val === false:\n case val === '':\n case val === 0:\n return val;\n default:\n return val || fallback;\n }\n }\n catch {\n return fallback;\n }\n }, dataObj);\n}\n// used by deepClone() tested through integration\nfunction cloneMap(mp) {\n const clonedMap = new Map();\n for (const [key, val] of mp) {\n if (isMap(val)) {\n clonedMap.set(key, cloneMap(val));\n }\n else {\n clonedMap.set(key, val);\n }\n }\n return clonedMap;\n}\nexport function deepClone(obj) {\n // this will clone almost anything (maps, arrays, objects, etc.) to the lowest of the low levels\n // be careful using this carelessly b/c it CAN have performance implications!\n switch (true) {\n case isMap(obj):\n return cloneMap(obj);\n case isObject(obj) && !Array.isArray(obj):\n return mergeObjects({}, obj);\n default:\n return JSON.parse(JSON.stringify(obj));\n }\n}\n/* c8 ignore next 2 */\nexport function convertAttributeStringValuesToValue(stringValue) {\n switch (true) {\n case stringValue === 'true':\n return true;\n case stringValue === 'false':\n return false;\n case stringValue === 'null':\n return null;\n case stringValue === 'undefined':\n return void 0; // undefined\n case isNumericString(stringValue):\n return +stringValue;\n default:\n // else it's a string and that's ok\n return stringValue;\n }\n}\n// this utility is a little restrictive on its inputs. it expects a specific format.\n// going outside of that format (like passing an object or function as the value) can yield unintended results.\n// this does NOT eval anything. that would be bad.\n// 'isValid:true status:success': string =>\n// [['isValid', true], ['status', 'success']]: [string, string | number | boolean][]\nexport function convertStringPropValuePairsToTuple(propValString) {\n // starts as a string like... \"isValid:true status:success\"\n return propValString\n .split(' ')\n .map(str => str.split(':'))\n .map(pv => {\n const [propname, propValAsString] = pv;\n return [propname, convertAttributeStringValuesToValue(propValAsString)];\n });\n // returns as [['isValid', true], ['status', 'success']]\n}\nexport function anyOrAllPropertiesPass(obj, propValuePairs, anyOrAll) {\n if (!propValuePairs) {\n return true;\n }\n const tests = convertStringPropValuePairsToTuple(propValuePairs);\n if (!obj) {\n return false;\n }\n if (tests.length < 1) {\n return true;\n }\n else {\n const testResults = tests.filter(pvArry => {\n const [propname, expectedVal] = pvArry;\n return doesPropertyPass(obj, propname, expectedVal);\n });\n return anyOrAll === 'all' ? testResults.length === tests.length : testResults.length > 0;\n }\n}\nexport function allPropertiesPass(obj, propValuePairs) {\n return anyOrAllPropertiesPass(obj, propValuePairs, 'all');\n}\nexport function anyPropertiesPass(obj, propValuePairs) {\n return anyOrAllPropertiesPass(obj, propValuePairs, 'any');\n}\n// TODO: BREAK THIS UP. TRIED ONCE. TOO CONVOLUTED.\n/**\n * This function takes an object (e.g. { ohai: 'hello', count: 2 }) or an Element\n * (e.g. <p ohai=\"hello\" count=\"2\">i am an html element</p>).\n *\n * It also takes a string that represents a potential property or attribute on the\n * object or element (e.g. \"ohai\" or \"count\").\n *\n * Lastly, it takes a potential value for the potential property or attribute\n * (e.g. \"hello\" or 2).\n *\n * If the object/element has the string as a property or attribute and the value\n * of the property/attribute equals the expected value, it returns true. If not,\n * it returns false.\n *\n * This code is the brains behind our \"key:value\" strings found in Clarity Motion.\n * (e.g. { hidden: true, onlyIf: \"responsive:false\", animation: ...})\n *\n * @export\n * @param {*} objectOrElement\n * @param {string} propertyOrAttributeName\n * @param {(string | number | boolean | null | undefined)} expectedValue\n * @returns {boolean}\n */\nexport function doesPropertyPass(objectOrElement, propertyOrAttributeName, expectedValue) {\n if (propertyOrAttributeName in objectOrElement) {\n // test expected key/value as object property first because it's less complicated\n if (expectedValue === false) {\n return !objectOrElement[propertyOrAttributeName];\n }\n else {\n return objectOrElement[propertyOrAttributeName] === expectedValue;\n }\n }\n else if (objectOrElement.hasAttribute &&\n objectOrElement.hasAttribute(propertyOrAttributeName)) {\n // test expected key/value as if an attribute on an element\n const propAsAttributeValue = objectOrElement.hasAttribute(propertyOrAttributeName) &&\n objectOrElement.getAttribute(propertyOrAttributeName);\n // sometimes attribute values can get set as string representations of\n // falsy states (see: boolean attribute with a string \"false\" value).\n // this catches that and less likely but still problematic misstep of\n // hard-setting with a string of \"undefined\" or \"null\"\n if (['null', 'false', 'undefined'].indexOf(propAsAttributeValue) > -1) {\n switch (expectedValue) {\n case null:\n return propAsAttributeValue === 'null';\n case false:\n return propAsAttributeValue === 'false';\n default:\n return !expectedValue;\n }\n }\n else {\n // after handling the weird edge case above, this is the more straightforward\n // value check.\n switch (expectedValue) {\n case false:\n return !propAsAttributeValue || propAsAttributeValue === 'false';\n case true:\n return propAsAttributeValue === '' || propAsAttributeValue === 'true';\n default:\n return propAsAttributeValue === expectedValue.toString();\n }\n }\n }\n else {\n // this is not an object property or an attribute on an element attribute so we need\n // to verify if it's expected to be undefined or false. If so, the attribute not being\n // present on the element (see: boolean attrs) meets expectations and return true.\n return ((!objectOrElement.hasAttribute && (expectedValue === false || expectedValue === undefined)) || false);\n }\n}\nexport function allAre(testFn, ...itemsToCheck) {\n return itemsToCheck.map(item => testFn(item)).indexOf(false) < 0;\n}\nexport function allAreDefined(...items) {\n const testFn = (val) => {\n return val !== undefined;\n };\n return allAre(testFn, ...items);\n}\nexport function mergeObjects(...objs) {\n const returnObj = {};\n const clones = objs.map(o => {\n // cloning here so we don't get messed up with object references\n return isObject(o) ? { ...o } : {};\n });\n clones.forEach(srcObj => {\n Object.keys(srcObj).forEach(prop => {\n const propVal = srcObj[prop];\n if (Array.isArray(propVal)) {\n returnObj[prop] = Array.from(propVal);\n }\n else if (isObject(propVal)) {\n returnObj[prop] = mergeObjects(returnObj[prop] || {}, propVal);\n }\n else {\n returnObj[prop] = propVal;\n }\n });\n });\n return returnObj;\n}\n"],"names":["isNil","val","isNilOrEmpty","isEmpty","isString","is","String","isNumericString","trim","isStringOrNil","isStringAndNotNilOrEmpty","isObject","Object","isMap","Map","isObjectAndNotNilOrEmpty","hasPropertyChanged","oldVal","hasStringPropertyChanged","hasStringPropertyChangedAndNotNil","getEnumValues","enumeration","values","createId","prefix","Math","random","toString","substr","objectNaiveDeepEquals","obj1","obj2","JSON","stringify","getFromObjectPath","path","dataObj","fallback","split","reduce","res","key","cloneMap","mp","clonedMap","set","deepClone","obj","Array","isArray","mergeObjects","parse","convertAttributeStringValuesToValue","stringValue","convertStringPropValuePairsToTuple","propValString","map","str","pv","propname","propValAsString","anyOrAllPropertiesPass","propValuePairs","anyOrAll","tests","length","testResults","filter","pvArry","expectedVal","doesPropertyPass","allPropertiesPass","anyPropertiesPass","objectOrElement","propertyOrAttributeName","expectedValue","hasAttribute","undefined","propAsAttributeValue","getAttribute","indexOf","allAre","testFn","itemsToCheck","item","allAreDefined","items","objs","returnObj","o","forEach","srcObj","keys","prop","propVal","from"],"mappings":"2DAOO,SAASA,EAAMC,GAClB,OAAOA,MAAAA,EAEJ,SAASC,EAAaD,GACzB,OAAOD,EAAMC,IAAQE,EAAQF,GAE1B,SAASG,EAASH,GACrB,OAAOI,EAAGC,OAAQL,GAEf,SAASM,EAAgBN,GAC5B,OAAOG,EAASH,KAASE,EAAQF,EAAIO,UAAYP,IAASA,EAEvD,SAASQ,EAAcR,GAC1B,OAAOI,EAAGC,OAAQL,IAAQD,EAAMC,GAE7B,SAASS,EAAyBT,GACrC,OAAOG,EAASH,KAASD,EAAMC,KAASE,EAAQF,GAE7C,SAASU,EAASV,GACrB,OAAOI,EAAGO,OAAQX,GAEf,SAASY,EAAMZ,GAClB,OAAOI,EAAGS,IAAKb,GAEZ,SAASc,EAAyBd,GACrC,OAAQC,EAAaD,IAAQU,EAASV,GAEnC,SAASe,EAAmBf,EAAKgB,GACpC,OAAOhB,IAAQgB,EAGZ,SAASC,EAAyBjB,EAAKgB,GAC1C,OAAOR,EAAcR,IAAQe,EAAmBf,EAAKgB,GA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,GAAS,EAE5D,SAASK,KAAiBC,GAI7B,OAAOL,GAHShF,QACG4E,IAAR5E,MAEcqF,GAEtB,SAASpC,KAAgBqC,GAC5B,MAAMC,EAAY,GAmBlB,OAlBeD,EAAK/B,KAAIiC,GAEb9E,EAAS8E,GAAK,IAAKA,GAAM,KAE7BC,SAAQC,IACX/E,OAAOgF,KAAKD,GAAQD,SAAQG,IACxB,MAAMC,EAAUH,EAAOE,GACnB7C,MAAMC,QAAQ6C,GACdN,EAAUK,GAAQ7C,MAAM+C,KAAKD,GAExBnF,EAASmF,GACdN,EAAUK,GAAQ3C,EAAasC,EAAUK,IAAS,GAAIC,GAGtDN,EAAUK,GAAQC,QAIvBN"}
|
package/internal/utils/math.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export declare function getMillisecondsFromSeconds(sec: number): number;
|
|
2
|
-
export declare const sumAndSubtract: (
|
|
3
|
-
export declare const compareSumTo: (
|
|
2
|
+
export declare const sumAndSubtract: import("ts-toolbelt/out/Function/Curry").Curry<(a_0: any, a_1: number[], a_2: number[]) => number>;
|
|
3
|
+
export declare const compareSumTo: import("ts-toolbelt/out/Function/Curry").Curry<(a_0: number, a_1: number[], a_2: number[], a_3: (x: number) => boolean) => boolean>;
|
|
4
4
|
export declare function getOffesetDifference(minuend: number, subtrahend: number): number;
|
package/internal/utils/math.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import r from"ramda/es/isNil
|
|
1
|
+
import r from"ramda/es/isNil";import m from"ramda/es/sum";import t from"ramda/es/curryN";function o(m){return r(m)?0:1e3*Number(m)}const a=t(3,((r,t,o)=>(r||0)+m(t||[])-m(o||[]))),e=t(4,((r,m,t,o)=>!!o&&o(a(r,m,t))));function i(r,m){return Math.sign(m-r)*Math.abs(r-m)}export{e as compareSumTo,o as getMillisecondsFromSeconds,i as getOffesetDifference,a as sumAndSubtract};
|
|
2
2
|
//# sourceMappingURL=math.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"math.js","sources":["../../../../src/internal/utils/math.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport isNil from 'ramda/es/isNil
|
|
1
|
+
{"version":3,"file":"math.js","sources":["../../../../src/internal/utils/math.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport isNil from 'ramda/es/isNil';\nimport sum from 'ramda/es/sum';\nimport curryN from 'ramda/es/curryN';\nexport function getMillisecondsFromSeconds(sec) {\n return isNil(sec) ? 0 : Number(sec) * 1000;\n}\nexport const sumAndSubtract = curryN(3, (startValue, add, subtract) => {\n return (startValue || 0) + sum(add || []) - sum(subtract || []);\n});\nexport const compareSumTo = curryN(4, (startValue, add, subtract, compareFn) => {\n return !compareFn ? false : compareFn(sumAndSubtract(startValue, add, subtract));\n});\nexport function getOffesetDifference(minuend, subtrahend) {\n return Math.sign(subtrahend - minuend) * Math.abs(minuend - subtrahend);\n}\n"],"names":["getMillisecondsFromSeconds","sec","isNil","Number","sumAndSubtract","curryN","startValue","add","subtract","sum","compareSumTo","compareFn","getOffesetDifference","minuend","subtrahend","Math","sign","abs"],"mappings":"yFAQO,SAASA,EAA2BC,GACvC,OAAOC,EAAMD,GAAO,EAAkB,IAAdE,OAAOF,GAEvB,MAACG,EAAiBC,EAAO,GAAG,CAACC,EAAYC,EAAKC,KAC9CF,GAAc,GAAKG,EAAIF,GAAO,IAAME,EAAID,GAAY,MAEnDE,EAAeL,EAAO,GAAG,CAACC,EAAYC,EAAKC,EAAUG,MACtDA,GAAoBA,EAAUP,EAAeE,EAAYC,EAAKC,MAEnE,SAASI,EAAqBC,EAASC,GAC1C,OAAOC,KAAKC,KAAKF,EAAaD,GAAWE,KAAKE,IAAIJ,EAAUC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"ramda/es/curryN
|
|
1
|
+
import e from"ramda/es/curryN";import{isBrowser as t}from"./environment.js";import{elementExists as r,existsInWindow as o}from"./exists.js";import{setupCDSGlobal as s}from"./global.js";import{isStorybook as m}from"./framework.js";import{LogService as i}from"../services/log.service.js";const n=e(3,((e,t,o)=>{r(e)&&!m()?i.warn(e+" has already been registered"):(o.define(e,t),s(),window&&!Object.keys(window.CDS._state.elementRegistry).some((t=>t===e))&&(window.CDS._state.elementRegistry={...window.CDS._state.elementRegistry,[e]:{}}))}));function w(e,r){t()&&o(["customElements"])&&n(e,r,window.customElements)}export{w as registerElementSafely};
|
|
2
2
|
//# sourceMappingURL=registration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registration.js","sources":["../../../../src/internal/utils/registration.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport curryN from 'ramda/es/curryN
|
|
1
|
+
{"version":3,"file":"registration.js","sources":["../../../../src/internal/utils/registration.ts"],"sourcesContent":["/*\n * Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.\n * This software is released under MIT license.\n * The full license information can be found in LICENSE in the root directory of this project.\n */\nimport curryN from 'ramda/es/curryN';\nimport { isBrowser } from './environment.js';\nimport { elementExists, existsInWindow } from './exists.js';\nimport { setupCDSGlobal } from './global.js';\nimport { isStorybook } from './framework.js';\nimport { LogService } from '../services/log.service.js';\nconst addElementToRegistry = curryN(3, (tagName, elementClass, registry) => {\n if (elementExists(tagName) && !isStorybook()) {\n LogService.warn(`${tagName} has already been registered`);\n }\n else {\n registry.define(tagName, elementClass);\n setupCDSGlobal();\n if (window && !Object.keys(window.CDS._state.elementRegistry).some(i => i === tagName)) {\n window.CDS._state.elementRegistry = { ...window.CDS._state.elementRegistry, [tagName]: {} };\n }\n }\n});\nexport function registerElementSafely(tagName, elementClass) {\n if (isBrowser() && existsInWindow(['customElements'])) {\n addElementToRegistry(tagName, elementClass, window.customElements);\n }\n}\n"],"names":["addElementToRegistry","curryN","tagName","elementClass","registry","elementExists","isStorybook","LogService","warn","define","setupCDSGlobal","window","Object","keys","CDS","_state","elementRegistry","some","i","registerElementSafely","isBrowser","existsInWindow","customElements"],"mappings":"8RAWA,MAAMA,EAAuBC,EAAO,GAAG,CAACC,EAASC,EAAcC,KACvDC,EAAcH,KAAaI,IAC3BC,EAAWC,KAAQN,EAAH,iCAGhBE,EAASK,OAAOP,EAASC,GACzBO,IACIC,SAAWC,OAAOC,KAAKF,OAAOG,IAAIC,OAAOC,iBAAiBC,MAAKC,GAAKA,IAAMhB,MAC1ES,OAAOG,IAAIC,OAAOC,gBAAkB,IAAKL,OAAOG,IAAIC,OAAOC,gBAAiBd,CAACA,GAAU,SAI5F,SAASiB,EAAsBjB,EAASC,GACvCiB,KAAeC,EAAe,CAAC,oBAC/BrB,EAAqBE,EAASC,EAAcQ,OAAOW"}
|
package/package.json
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"lit": "^2.1.3",
|
|
30
|
-
"ramda": "^0.
|
|
30
|
+
"ramda": "^0.29.0",
|
|
31
31
|
"tslib": "^2.3.1"
|
|
32
32
|
},
|
|
33
33
|
"optionalDependencies": {
|
|
@@ -255,5 +255,5 @@
|
|
|
255
255
|
"./tokens/tokens.ios.swift": "./tokens/tokens.ios.swift",
|
|
256
256
|
"./tokens/tokens.android.xml": "./tokens/tokens.android.xml"
|
|
257
257
|
},
|
|
258
|
-
"version": "6.4.
|
|
258
|
+
"version": "6.4.1"
|
|
259
259
|
}
|