@nordhealth/components 4.26.1 → 4.26.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"Textarea.js","sources":["../src/textarea/Textarea.ts"],"sourcesContent":["import { html, LitElement, nothing } from 'lit'\nimport { customElement, property } from 'lit/decorators.js'\nimport { ifDefined } from 'lit/directives/if-defined.js'\nimport { ref } from 'lit/directives/ref.js'\nimport { observe } from '../common/decorators/observe.js'\n\nimport { NordEvent } from '../common/events.js'\nimport { AutocompleteMixin } from '../common/mixins/AutocompleteMixin.js'\nimport { FocusableMixin } from '../common/mixins/FocusableMixin.js'\nimport { FormAssociatedMixin } from '../common/mixins/FormAssociatedMixin.js'\nimport { InputMixin } from '../common/mixins/InputMixin.js'\nimport { ReadonlyMixin } from '../common/mixins/ReadonlyMixin.js'\nimport { SizeMixin } from '../common/mixins/SizeMixin.js'\n\nimport { TextSelectableMixin } from '../common/mixins/TextSelectableMixin.js'\nimport componentStyle from '../common/styles/Component.css'\nimport formFieldStyle from '../common/styles/FormField.css'\nimport textFieldStyle from '../common/styles/TextField.css'\nimport { LocalizeController } from '../localization/LocalizeController.js'\nimport style from './Textarea.css'\n\nfunction createLengthMeasurer(locale: string) {\n if (Intl.Segmenter) {\n const segmenter = new Intl.Segmenter(locale)\n return (value: string) => [...segmenter.segment(value)].length\n }\n\n return (value: string) => value.length\n}\n\n/**\n * Textarea is a component that allows user to write text over\n * multiple rows. Used when the expected user input is long.\n * For shorter input, use the Input component.\n *\n * @status ready\n * @category form\n * @slot label - Use when a label requires more than plain text.\n * @slot hint - Optional slot that holds hint text for the textarea.\n * @slot error - Optional slot that holds error text for the textarea.\n *\n * @cssprop [--n-textarea-inline-size=240px] - Controls the inline size, or width, of the textarea.\n * @cssprop [--n-textarea-block-size=76px] - Controls the block size, or height, of the textarea.\n * @cssprop [--n-textarea-background=var(--n-color-active)] - Controls the background of the textarea, using our [color tokens](/tokens/#color).\n * @cssprop [--n-textarea-color=var(--n-color-text)] - Controls the text color of the textarea, using our [color tokens](/tokens/#color).\n * @cssprop [--n-textarea-border-color=var(--n-color-border-strong)] - Controls the border color of the textarea, using our [color tokens](/tokens/#color).\n * @cssprop [--n-textarea-border-radius=var(--n-border-radius-s)] - Controls how rounded the corners are, using [border radius tokens](/tokens/#border-radius).\n * @cssprop [--n-label-color=var(--n-color-text)] - Controls the text color of the label, using our [color tokens](/tokens/#color).\n *\n * @localization remainingCharacters - A function which receives the number of remaining characters and returns a string to be used as the aria-live message.\n */\n@customElement('nord-textarea')\nexport default class Textarea extends SizeMixin(\n FormAssociatedMixin(AutocompleteMixin(ReadonlyMixin(TextSelectableMixin(InputMixin(FocusableMixin(LitElement)))))),\n) {\n static styles = [componentStyle, formFieldStyle, textFieldStyle, style]\n\n protected inputId = 'textarea'\n\n private lengthMeasurer!: (value: string) => number\n private localize = new LocalizeController<'nord-textarea'>(this, {\n onLangChange: () => this.handleLangChange(),\n })\n\n /**\n * Controls whether the textarea is resizable.\n * By default is manually resizable vertically.\n * Set to \"auto\" to enable auto-resizing as content grows.\n */\n @property({ reflect: true }) resize: 'vertical' | 'auto' = 'vertical'\n\n /**\n * Controls whether the textarea expands to fill the width of its container.\n */\n @property({ reflect: true, type: Boolean }) expand = false\n\n /**\n * Controls the max allowed length for the textarea.\n */\n @property({ reflect: true, attribute: 'maxlength', type: Number }) maxLength?: number\n\n /**\n * Controls whether to show a count of the number of characters in the textarea.\n * When combined with `maxlength`, both the count and the max length are shown.\n */\n @property({ reflect: true, type: Boolean, attribute: 'character-counter' }) characterCounter = false\n\n render() {\n return html`\n ${this.renderLabel()}\n\n <div class=\"n-input-container\">\n <textarea\n ${ref(this.textSelectableRef)}\n ${ref(this.focusableRef)}\n id=${this.inputId}\n class=\"n-input\"\n ?disabled=${this.disabled}\n ?readonly=${this.readonly}\n ?required=${this.required}\n name=${ifDefined(this.name)}\n maxlength=${ifDefined(this.maxLength)}\n .value=${this.value ?? ''}\n placeholder=${ifDefined(this.placeholder)}\n @change=${this.handleChange}\n @input=${this.handleInput}\n @select=${this.handleSelect}\n aria-describedby=${ifDefined(this.getDescribedBy())}\n aria-invalid=${ifDefined(this.getInvalid())}\n autocomplete=${this.autocomplete as any}\n ></textarea>\n\n ${this.characterCounter ? this.renderCharacterCounter() : nothing}\n </div>\n\n ${this.renderError()}\n ${this.isHintBelow ? this.renderHint() : nothing}\n `\n }\n\n protected handleSelect(e: Event) {\n e.stopPropagation()\n\n /**\n * Fired when some text has been selected.\n */\n this.dispatchEvent(new NordEvent('select'))\n }\n\n private renderCharacterCounter() {\n const { value, maxLength } = this\n const length = typeof value === 'string' ? this.lengthMeasurer(value) : 0\n\n const remainder = maxLength ? maxLength - length : null\n const counter = maxLength ? `${length}/${maxLength}` : length\n\n return html`\n <nord-visually-hidden aria-live=\"polite\" aria-atomic=\"true\">\n ${remainder != null && remainder <= 10 ? this.localize.term('remainingCharacters', remainder) : ''}\n </nord-visually-hidden>\n <div class=\"n-character-counter\">${counter}</div>\n `\n }\n\n private handleLangChange() {\n const lang = this.localize.resolvedLang\n this.lengthMeasurer = createLengthMeasurer(lang)\n }\n\n @observe('resize', 'updated')\n @observe('value', 'updated')\n protected resizeToFitContent() {\n const textarea = this.focusableRef.value\n\n if (!textarea) {\n return\n }\n\n if (this.resize === 'auto') {\n textarea.style.height = 'auto'\n textarea.style.height = `${textarea.scrollHeight}px`\n }\n else {\n textarea.style.height = ''\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'nord-textarea': Textarea\n }\n}\n"],"names":["Textarea","SizeMixin","FormAssociatedMixin","AutocompleteMixin","ReadonlyMixin","TextSelectableMixin","InputMixin","FocusableMixin","LitElement","constructor","this","inputId","localize","LocalizeController","onLangChange","handleLangChange","resize","expand","characterCounter","render","html","renderLabel","ref","textSelectableRef","focusableRef","disabled","readonly","required","ifDefined","name","maxLength","_a","value","placeholder","handleChange","handleInput","handleSelect","getDescribedBy","getInvalid","autocomplete","renderCharacterCounter","nothing","renderError","isHintBelow","renderHint","e","stopPropagation","dispatchEvent","NordEvent","length","lengthMeasurer","remainder","counter","term","lang","resolvedLang","locale","Intl","Segmenter","segmenter","segment","createLengthMeasurer","resizeToFitContent","textarea","style","height","scrollHeight","styles","componentStyle","formFieldStyle","textFieldStyle","__decorate","property","reflect","prototype","type","Boolean","attribute","Number","observe","customElement"],"mappings":"8vGAoDe,IAAMA,EAAN,cAAuBC,EACpCC,EAAoBC,EAAkBC,EAAcC,EAAoBC,EAAWC,EAAeC,UADrF,WAAAC,uBAKHC,KAAOC,QAAG,WAGZD,KAAAE,SAAW,IAAIC,EAAoCH,KAAM,CAC/DI,aAAc,IAAMJ,KAAKK,qBAQEL,KAAMM,OAAwB,WAKfN,KAAMO,QAAG,EAWuBP,KAAgBQ,kBAAG,CAiFhG,CA/EC,MAAAC,SACE,OAAOC,CAAI,GACPV,KAAKW,yDAIDC,EAAIZ,KAAKa,sBACTD,EAAIZ,KAAKc,qBACNd,KAAKC,uCAEED,KAAKe,wBACLf,KAAKgB,wBACLhB,KAAKiB,mBACVC,EAAUlB,KAAKmB,qBACVD,EAAUlB,KAAKoB,uBACR,QAAVC,EAAArB,KAAKsB,aAAK,IAAAD,EAAAA,EAAI,oBACTH,EAAUlB,KAAKuB,0BACnBvB,KAAKwB,yBACNxB,KAAKyB,yBACJzB,KAAK0B,mCACIR,EAAUlB,KAAK2B,oCACnBT,EAAUlB,KAAK4B,gCACf5B,KAAK6B,6BAGpB7B,KAAKQ,iBAAmBR,KAAK8B,yBAA2BC,UAG1D/B,KAAKgC,iBACLhC,KAAKiC,YAAcjC,KAAKkC,aAAeH,GAE5C,CAES,YAAAL,CAAaS,GACrBA,EAAEC,kBAKFpC,KAAKqC,cAAc,IAAIC,EAAU,UAClC,CAEO,sBAAAR,GACN,MAAMR,MAAEA,EAAKF,UAAEA,GAAcpB,KACvBuC,EAA0B,iBAAVjB,EAAqBtB,KAAKwC,eAAelB,GAAS,E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"file":"Textarea.js","sources":["../src/textarea/Textarea.ts"],"sourcesContent":["import { html, LitElement, nothing } from 'lit'\nimport { customElement, property } from 'lit/decorators.js'\nimport { ifDefined } from 'lit/directives/if-defined.js'\nimport { ref } from 'lit/directives/ref.js'\nimport { observe } from '../common/decorators/observe.js'\n\nimport { NordEvent } from '../common/events.js'\nimport { AutocompleteMixin } from '../common/mixins/AutocompleteMixin.js'\nimport { FocusableMixin } from '../common/mixins/FocusableMixin.js'\nimport { FormAssociatedMixin } from '../common/mixins/FormAssociatedMixin.js'\nimport { InputMixin } from '../common/mixins/InputMixin.js'\nimport { ReadonlyMixin } from '../common/mixins/ReadonlyMixin.js'\nimport { SizeMixin } from '../common/mixins/SizeMixin.js'\n\nimport { TextSelectableMixin } from '../common/mixins/TextSelectableMixin.js'\nimport componentStyle from '../common/styles/Component.css'\nimport formFieldStyle from '../common/styles/FormField.css'\nimport textFieldStyle from '../common/styles/TextField.css'\nimport { LocalizeController } from '../localization/LocalizeController.js'\nimport style from './Textarea.css'\n\nfunction createLengthMeasurer(locale: string) {\n if (Intl.Segmenter) {\n const segmenter = new Intl.Segmenter(locale)\n return (value: string) => [...segmenter.segment(value)].length\n }\n\n return (value: string) => value.length\n}\n\n/**\n * Textarea is a component that allows user to write text over\n * multiple rows. Used when the expected user input is long.\n * For shorter input, use the Input component.\n *\n * @status ready\n * @category form\n * @slot label - Use when a label requires more than plain text.\n * @slot hint - Optional slot that holds hint text for the textarea.\n * @slot error - Optional slot that holds error text for the textarea.\n *\n * @cssprop [--n-textarea-inline-size=240px] - Controls the inline size, or width, of the textarea.\n * @cssprop [--n-textarea-block-size=76px] - Controls the minimum block size, or height, of the textarea. When `resize=\"auto\"`, the textarea grows from this height as content is added.\n * @cssprop [--n-textarea-max-block-size=500px] - Controls the maximum block size, or height, of the textarea. When `resize=\"auto\"`, the textarea stops growing at this height and a scrollbar appears.\n * @cssprop [--n-textarea-background=var(--n-color-active)] - Controls the background of the textarea, using our [color tokens](/tokens/#color).\n * @cssprop [--n-textarea-color=var(--n-color-text)] - Controls the text color of the textarea, using our [color tokens](/tokens/#color).\n * @cssprop [--n-textarea-border-color=var(--n-color-border-strong)] - Controls the border color of the textarea, using our [color tokens](/tokens/#color).\n * @cssprop [--n-textarea-border-radius=var(--n-border-radius-s)] - Controls how rounded the corners are, using [border radius tokens](/tokens/#border-radius).\n * @cssprop [--n-label-color=var(--n-color-text)] - Controls the text color of the label, using our [color tokens](/tokens/#color).\n *\n * @localization remainingCharacters - A function which receives the number of remaining characters and returns a string to be used as the aria-live message.\n */\n@customElement('nord-textarea')\nexport default class Textarea extends SizeMixin(\n FormAssociatedMixin(AutocompleteMixin(ReadonlyMixin(TextSelectableMixin(InputMixin(FocusableMixin(LitElement)))))),\n) {\n static styles = [componentStyle, formFieldStyle, textFieldStyle, style]\n\n protected inputId = 'textarea'\n\n private lengthMeasurer!: (value: string) => number\n private localize = new LocalizeController<'nord-textarea'>(this, {\n onLangChange: () => this.handleLangChange(),\n })\n\n /**\n * Controls whether the textarea is resizable.\n * By default is manually resizable vertically.\n * Set to \"auto\" to enable auto-resizing as content grows.\n */\n @property({ reflect: true }) resize: 'vertical' | 'auto' = 'vertical'\n\n /**\n * Controls whether the textarea expands to fill the width of its container.\n */\n @property({ reflect: true, type: Boolean }) expand = false\n\n /**\n * Controls the max allowed length for the textarea.\n */\n @property({ reflect: true, attribute: 'maxlength', type: Number }) maxLength?: number\n\n /**\n * Controls whether to show a count of the number of characters in the textarea.\n * When combined with `maxlength`, both the count and the max length are shown.\n */\n @property({ reflect: true, type: Boolean, attribute: 'character-counter' }) characterCounter = false\n\n render() {\n return html`\n ${this.renderLabel()}\n\n <div class=\"n-input-container\">\n <textarea\n ${ref(this.textSelectableRef)}\n ${ref(this.focusableRef)}\n id=${this.inputId}\n class=\"n-input\"\n ?disabled=${this.disabled}\n ?readonly=${this.readonly}\n ?required=${this.required}\n name=${ifDefined(this.name)}\n maxlength=${ifDefined(this.maxLength)}\n .value=${this.value ?? ''}\n placeholder=${ifDefined(this.placeholder)}\n @change=${this.handleChange}\n @input=${this.handleInput}\n @select=${this.handleSelect}\n aria-describedby=${ifDefined(this.getDescribedBy())}\n aria-invalid=${ifDefined(this.getInvalid())}\n autocomplete=${this.autocomplete as any}\n ></textarea>\n\n ${this.characterCounter ? this.renderCharacterCounter() : nothing}\n </div>\n\n ${this.renderError()}\n ${this.isHintBelow ? this.renderHint() : nothing}\n `\n }\n\n protected handleSelect(e: Event) {\n e.stopPropagation()\n\n /**\n * Fired when some text has been selected.\n */\n this.dispatchEvent(new NordEvent('select'))\n }\n\n private renderCharacterCounter() {\n const { value, maxLength } = this\n const length = typeof value === 'string' ? this.lengthMeasurer(value) : 0\n\n const remainder = maxLength ? maxLength - length : null\n const counter = maxLength ? `${length}/${maxLength}` : length\n\n return html`\n <nord-visually-hidden aria-live=\"polite\" aria-atomic=\"true\">\n ${remainder != null && remainder <= 10 ? this.localize.term('remainingCharacters', remainder) : ''}\n </nord-visually-hidden>\n <div class=\"n-character-counter\">${counter}</div>\n `\n }\n\n private handleLangChange() {\n const lang = this.localize.resolvedLang\n this.lengthMeasurer = createLengthMeasurer(lang)\n }\n\n @observe('resize', 'updated')\n @observe('value', 'updated')\n protected resizeToFitContent() {\n const textarea = this.focusableRef.value\n\n if (!textarea) {\n return\n }\n\n if (this.resize === 'auto') {\n textarea.style.height = 'auto'\n // scrollHeight includes padding but not border. With box-sizing: border-box,\n // setting height directly to scrollHeight would shrink the content area by the\n // border width and clip the last line. Add the border so padding-block is preserved,\n // then clamp the result to the resolved min/max so the inline height never\n // overshoots the cap.\n const computed = getComputedStyle(textarea)\n const borderSize = textarea.offsetHeight - textarea.clientHeight\n const minHeight = Number.parseFloat(computed.minBlockSize) || 0\n const maxHeight = Number.parseFloat(computed.maxBlockSize) || Number.POSITIVE_INFINITY\n const desired = textarea.scrollHeight + borderSize\n\n textarea.style.height = `${Math.min(Math.max(desired, minHeight), maxHeight)}px`\n }\n else {\n textarea.style.height = ''\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'nord-textarea': Textarea\n }\n}\n"],"names":["Textarea","SizeMixin","FormAssociatedMixin","AutocompleteMixin","ReadonlyMixin","TextSelectableMixin","InputMixin","FocusableMixin","LitElement","constructor","this","inputId","localize","LocalizeController","onLangChange","handleLangChange","resize","expand","characterCounter","render","html","renderLabel","ref","textSelectableRef","focusableRef","disabled","readonly","required","ifDefined","name","maxLength","_a","value","placeholder","handleChange","handleInput","handleSelect","getDescribedBy","getInvalid","autocomplete","renderCharacterCounter","nothing","renderError","isHintBelow","renderHint","e","stopPropagation","dispatchEvent","NordEvent","length","lengthMeasurer","remainder","counter","term","lang","resolvedLang","locale","Intl","Segmenter","segmenter","segment","createLengthMeasurer","resizeToFitContent","textarea","style","height","computed","getComputedStyle","borderSize","offsetHeight","clientHeight","minHeight","Number","parseFloat","minBlockSize","maxHeight","maxBlockSize","POSITIVE_INFINITY","desired","scrollHeight","Math","min","max","styles","componentStyle","formFieldStyle","textFieldStyle","__decorate","property","reflect","prototype","type","Boolean","attribute","observe","customElement"],"mappings":"k3GAqDe,IAAMA,EAAN,cAAuBC,EACpCC,EAAoBC,EAAkBC,EAAcC,EAAoBC,EAAWC,EAAeC,UADrF,WAAAC,uBAKHC,KAAOC,QAAG,WAGZD,KAAAE,SAAW,IAAIC,EAAoCH,KAAM,CAC/DI,aAAc,IAAMJ,KAAKK,qBAQEL,KAAMM,OAAwB,WAKfN,KAAMO,QAAG,EAWuBP,KAAgBQ,kBAAG,CA4FhG,CA1FC,MAAAC,SACE,OAAOC,CAAI,GACPV,KAAKW,yDAIDC,EAAIZ,KAAKa,sBACTD,EAAIZ,KAAKc,qBACNd,KAAKC,uCAEED,KAAKe,wBACLf,KAAKgB,wBACLhB,KAAKiB,mBACVC,EAAUlB,KAAKmB,qBACVD,EAAUlB,KAAKoB,uBACR,QAAVC,EAAArB,KAAKsB,aAAK,IAAAD,EAAAA,EAAI,oBACTH,EAAUlB,KAAKuB,0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,EAASC,MAAMC,OAAS,GAAGe,KAAKC,IAAID,KAAKE,IAAIJ,EAASP,GAAYI,MACnE,MAECZ,EAASC,MAAMC,OAAS,EAE3B,GAzHMjE,EAAMmF,OAAG,CAACC,EAAgBC,EAAgBC,EAAgBtB,GAcpCuB,EAAA,CAA5BC,EAAS,CAAEC,SAAS,KAAgDzF,EAAA0F,UAAA,cAAA,GAKzBH,EAAA,CAA3CC,EAAS,CAAEC,SAAS,EAAME,KAAMC,WAAyB5F,EAAA0F,UAAA,cAAA,GAKSH,EAAA,CAAlEC,EAAS,CAAEC,SAAS,EAAMI,UAAW,YAAaF,KAAMnB,UAA4BxE,EAAA0F,UAAA,iBAAA,GAMTH,EAAA,CAA3EC,EAAS,CAAEC,SAAS,EAAME,KAAMC,QAASC,UAAW,uBAA+C7F,EAAA0F,UAAA,wBAAA,GAkE1FH,EAAA,CAFTO,EAAQ,SAAU,WAClBA,EAAQ,QAAS,YA0BjB9F,EAAA0F,UAAA,qBAAA,MA5HkB1F,EAAQuF,EAAA,CAD5BQ,EAAc,kBACM/F,SAAAA"}
package/lib/Tooltip.js CHANGED
@@ -1,2 +1,2 @@
1
- import{_ as t}from"./tslib.es6-CmLYFWVC.js";import{c as i,l as e,o,f as s,s as n}from"./positioning-D-K8Mueq.js";import{css as r,LitElement as a,html as l}from"lit";import{state as d,property as h,customElement as p}from"lit/decorators.js";import{E as c}from"./EventController-BBOmvfLa.js";import{S as u}from"./SlotController-Z6eG7LSZ.js";import{o as v}from"./observe-D0n0zOfU.js";import{f as m}from"./fsm-Bq5jMQrK.js";import{s as y}from"./Component-DSU3Qp0O.js";function b(t,i){const e=t.getAttribute(i);return e?e.split(/\s+/):[]}function f(t,i,e){t.setAttribute(i,e.join(" "))}const g=r`:host{--_n-tooltip-max-size:var(--n-tooltip-max-size, 50ch);--_n-tooltip-background:rgb(20, 20, 20, 0.95);--_n-tooltip-color:#fff;--_n-tooltip-key-border:rgb(255, 255, 255, 0.03);--_n-tooltip-key-background:rgb(255, 255, 255, 0.1);position:fixed;pointer-events:none;visibility:hidden;opacity:0;transition:opacity var(--n-transition-slowly),visibility var(--n-transition-slowly);transition-timing-function:ease;z-index:var(--n-index-popout);inset:auto;inline-size:auto;block-size:auto;margin:0;padding:0;border:none;background:0 0;overflow:visible;color:inherit}.n-tooltip{gap:var(--n-space-s);font-family:var(--n-font-family);font-size:var(--n-font-size-xs);line-height:var(--n-line-height);color:var(--_n-tooltip-color);padding:calc(var(--n-space-s)/ 1.5) var(--n-space-s);background-color:var(--_n-tooltip-background);border-radius:var(--n-border-radius-s);word-break:break-word;max-inline-size:var(--_n-tooltip-max-size)}.n-tooltip,.n-tooltip-shortcut{display:flex;align-items:center}.n-tooltip-shortcut{gap:2px}::slotted([slot=shortcut]){box-sizing:border-box;margin:0;inline-size:var(--n-size-icon-m);block-size:var(--n-size-icon-m);border-radius:var(--n-border-radius-s);border:1px solid var(--_n-tooltip-key-border)!important;padding:1px!important;text-align:center;font-size:var(--n-font-size-xs);line-height:var(--n-line-height-tight);letter-spacing:-.5px;vertical-align:middle!important;background-color:var(--_n-tooltip-key-background)}[slot=shortcut]::slotted(nord-icon:not([size])){--_n-icon-size:var(--n-size-icon-s)}`;var x;function k(t){return t.nodeType===Node.ELEMENT_NODE}function w(t){var i;const e=null===(i=null==t?void 0:t.focusableRef)||void 0===i?void 0:i.value;return e&&"focusableRef"in e?w(e):e}const{transition:z}=m({hidden:{show:"waiting"},visible:{hide:"hidden",reposition:"positioning",show:"positioning"},waiting:{timeout:"positioning",hide:"hidden"},positioning:{positioned:"visible",hide:"hidden"}});let E=x=class extends a{constructor(){super(...arguments),this.shortcutSlot=new u(this,"shortcut"),this.events=new c(this),this.state="hidden",this.coords=[0,0],this.position="block-start",this.role="tooltip",this.id="",this.delay=500,this.open=!1,this.updatePosition=t=>i(t,this,{strategy:"fixed",placement:e(this.position),middleware:[o(8),s(),n({padding:8})]}).then((({x:t,y:i})=>{this.coords=[t,i],this.state=z(this.state,"positioned")})),this.hideTooltip=()=>{this.state=z(this.state,"hide")},this.reposition=()=>{this.state=z(this.state,"reposition")},this.handleShow=t=>{const i=function(t,i){return i.id&&k(t)?t.closest(`[aria-describedby~="${CSS.escape(i.id)}"]`):null}(t.target,this);i&&(this.currentElement=i,this.state=z(this.state,"show"))},this.handleHide=t=>{const i=t.target;this.currentElement&&k(i)&&this.currentElement.contains(i)&&this.hideTooltip()},this.hideOnEscape=t=>{"Escape"===t.key&&this.hideTooltip()},this.addDescribedBy=()=>{const t=w(this.currentElement);t&&this.proxy&&(this.proxy.hidden=!0,this.proxy.id=this.id,this.proxy.textContent=this.textContent,t.insertAdjacentElement("afterend",this.proxy),function(t,i,e){const o=b(t,i);o.includes(e)||f(t,i,o.concat(e))}(t,"aria-describedby",this.id))},this.removeDescribedBy=()=>{const t=w(this.currentElement);t&&this.proxy&&(this.proxy.remove(),function(t,i,e){const o=b(t,i);o.includes(e)&&f(t,i,o.filter((t=>t!==e)))}(t,"aria-describedby",this.id))}}connectedCallback(){super.connectedCallback(),this.proxy=document.createElement("span");const t=this.getRootNode();this.events.listen(t,"keydown",this.hideOnEscape),this.events.listen(t,"mouseover",this.handleShow),this.events.listen(t,"focusin",this.handleShow),this.events.listen(t,"mouseout",this.handleHide),this.events.listen(t,"focusout",this.handleHide),this.events.listen(t,"click",this.handleHide,{capture:!0}),this.events.listen(window,"resize",this.reposition,{passive:!0}),this.events.listen(window,"scroll",this.reposition,{passive:!0})}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this.proxy)||void 0===t||t.remove(),this.proxy=void 0}render(){return l`<div class="n-tooltip"><slot></slot><div class="n-tooltip-shortcut" ?hidden="${this.shortcutSlot.isEmpty}"><slot class="n-tooltip-key" name="shortcut"></slot></div></div>`}handleIdChange(){this.id||console.warn("NORD: The tooltip requires an id attribute and value")}handleStateChange(t){var i;switch(this.state){case"hidden":"waiting"===t&&this.timeoutId&&clearTimeout(this.timeoutId),this.removeDescribedBy(),this.currentElement=void 0,this.style.visibility="hidden",this.style.opacity="0",this.open=!1,this.leaveTopLayer();break;case"visible":{this.timeoutId=void 0,x.lastOpened=this,this.addDescribedBy();const[t,i]=this.coords;this.style.left=`${t}px`,this.style.top=`${i}px`,this.style.visibility="visible",this.style.opacity="1",this.open=!0;break}case"waiting":this.timeoutId=setTimeout((()=>{this.state=z(this.state,"timeout")}),this.delay);break;case"positioning":x.lastOpened!==this&&(null===(i=x.lastOpened)||void 0===i||i.hideTooltip()),this.enterTopLayer(),this.currentElement&&this.updatePosition(this.currentElement)}}enterTopLayer(){if("function"==typeof this.showPopover)try{this.setAttribute("popover","manual"),this.showPopover()}catch(t){this.removeAttribute("popover")}}leaveTopLayer(){this.removeAttribute("popover")}};E.styles=[y,g],t([d()],E.prototype,"state",void 0),t([h({reflect:!0})],E.prototype,"position",void 0),t([h({reflect:!0})],E.prototype,"role",void 0),t([h({reflect:!0})],E.prototype,"id",void 0),t([h({reflect:!0,type:Number})],E.prototype,"delay",void 0),t([h({type:Boolean,reflect:!0})],E.prototype,"open",void 0),t([v("id")],E.prototype,"handleIdChange",null),t([v("state")],E.prototype,"handleStateChange",null),E=x=t([p("nord-tooltip")],E);var C=E;export{C as default};
1
+ import{_ as t}from"./tslib.es6-CmLYFWVC.js";import{c as i,l as e,o,f as s,s as n}from"./positioning-D-K8Mueq.js";import{css as r,LitElement as a,html as l}from"lit";import{state as d,property as h,customElement as p}from"lit/decorators.js";import{E as c}from"./EventController-BBOmvfLa.js";import{S as u}from"./SlotController-Z6eG7LSZ.js";import{o as v}from"./observe-D0n0zOfU.js";import{f as m}from"./fsm-Bq5jMQrK.js";import{s as f}from"./Component-DSU3Qp0O.js";function y(t,i){const e=t.getAttribute(i);return e?e.split(/\s+/):[]}function b(t,i,e){t.setAttribute(i,e.join(" "))}const g=r`:host{--_n-tooltip-max-size:var(--n-tooltip-max-size, 50ch);--_n-tooltip-background:rgb(20, 20, 20, 0.95);--_n-tooltip-color:#fff;--_n-tooltip-key-border:rgb(255, 255, 255, 0.03);--_n-tooltip-key-background:rgb(255, 255, 255, 0.1);position:fixed;pointer-events:none;visibility:hidden;opacity:0;transition:opacity var(--n-transition-slowly),visibility var(--n-transition-slowly);transition-timing-function:ease;z-index:var(--n-index-popout);inset:auto;inline-size:auto;block-size:auto;margin:0;padding:0;border:none;background:0 0;overflow:visible;color:inherit}.n-tooltip{gap:var(--n-space-s);font-family:var(--n-font-family);font-size:var(--n-font-size-xs);line-height:var(--n-line-height);color:var(--_n-tooltip-color);padding:calc(var(--n-space-s)/ 1.5) var(--n-space-s);background-color:var(--_n-tooltip-background);border-radius:var(--n-border-radius-s);word-break:break-word;max-inline-size:var(--_n-tooltip-max-size)}.n-tooltip,.n-tooltip-shortcut{display:flex;align-items:center}.n-tooltip-shortcut{gap:2px}::slotted([slot=shortcut]){box-sizing:border-box;margin:0;inline-size:var(--n-size-icon-m);block-size:var(--n-size-icon-m);border-radius:var(--n-border-radius-s);border:1px solid var(--_n-tooltip-key-border)!important;padding:1px!important;text-align:center;font-size:var(--n-font-size-xs);line-height:var(--n-line-height-tight);letter-spacing:-.5px;vertical-align:middle!important;background-color:var(--_n-tooltip-key-background)}[slot=shortcut]::slotted(nord-icon:not([size])){--_n-icon-size:var(--n-size-icon-s)}`;var x;function k(t){return t.nodeType===Node.ELEMENT_NODE}function w(t){var i;const e=null===(i=null==t?void 0:t.focusableRef)||void 0===i?void 0:i.value;return e&&"focusableRef"in e?w(e):e}const{transition:z}=m({hidden:{show:"waiting"},visible:{hide:"hidden",reposition:"positioning",show:"positioning"},waiting:{timeout:"positioning",hide:"hidden"},positioning:{positioned:"visible",hide:"hidden"}});let E=x=class extends a{constructor(){super(...arguments),this.shortcutSlot=new u(this,"shortcut"),this.events=new c(this),this.state="hidden",this.coords=[0,0],this.position="block-start",this.role="tooltip",this.id="",this.delay=500,this.open=!1,this.sideOffset=8,this.alignOffset=0,this.updatePosition=t=>i(t,this,{strategy:"fixed",placement:e(this.position),middleware:[o({mainAxis:this.sideOffset,alignmentAxis:this.alignOffset}),s(),n({padding:8})]}).then((({x:t,y:i})=>{this.coords=[t,i],this.state=z(this.state,"positioned")})),this.hideTooltip=()=>{this.state=z(this.state,"hide")},this.reposition=()=>{this.state=z(this.state,"reposition")},this.handleShow=t=>{const i=function(t,i){return i.id&&k(t)?t.closest(`[aria-describedby~="${CSS.escape(i.id)}"]`):null}(t.target,this);i&&(this.currentElement=i,this.state=z(this.state,"show"))},this.handleHide=t=>{const i=t.target;this.currentElement&&k(i)&&this.currentElement.contains(i)&&this.hideTooltip()},this.hideOnEscape=t=>{"Escape"===t.key&&this.hideTooltip()},this.addDescribedBy=()=>{const t=w(this.currentElement);t&&this.proxy&&(this.proxy.hidden=!0,this.proxy.id=this.id,this.proxy.textContent=this.textContent,t.insertAdjacentElement("afterend",this.proxy),function(t,i,e){const o=y(t,i);o.includes(e)||b(t,i,o.concat(e))}(t,"aria-describedby",this.id))},this.removeDescribedBy=()=>{const t=w(this.currentElement);t&&this.proxy&&(this.proxy.remove(),function(t,i,e){const o=y(t,i);o.includes(e)&&b(t,i,o.filter((t=>t!==e)))}(t,"aria-describedby",this.id))}}connectedCallback(){super.connectedCallback(),this.proxy=document.createElement("span");const t=this.getRootNode();this.events.listen(t,"keydown",this.hideOnEscape),this.events.listen(t,"mouseover",this.handleShow),this.events.listen(t,"focusin",this.handleShow),this.events.listen(t,"mouseout",this.handleHide),this.events.listen(t,"focusout",this.handleHide),this.events.listen(t,"click",this.handleHide,{capture:!0}),this.events.listen(window,"resize",this.reposition,{passive:!0}),this.events.listen(window,"scroll",this.reposition,{passive:!0})}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this.proxy)||void 0===t||t.remove(),this.proxy=void 0}render(){return l`<div class="n-tooltip"><slot></slot><div class="n-tooltip-shortcut" ?hidden="${this.shortcutSlot.isEmpty}"><slot class="n-tooltip-key" name="shortcut"></slot></div></div>`}handleIdChange(){this.id||console.warn("NORD: The tooltip requires an id attribute and value")}handleStateChange(t){var i;switch(this.state){case"hidden":"waiting"===t&&this.timeoutId&&clearTimeout(this.timeoutId),this.removeDescribedBy(),this.currentElement=void 0,this.style.visibility="hidden",this.style.opacity="0",this.open=!1,this.leaveTopLayer();break;case"visible":{this.timeoutId=void 0,x.lastOpened=this,this.addDescribedBy();const[t,i]=this.coords;this.style.left=`${t}px`,this.style.top=`${i}px`,this.style.visibility="visible",this.style.opacity="1",this.open=!0;break}case"waiting":this.timeoutId=setTimeout((()=>{this.state=z(this.state,"timeout")}),this.delay);break;case"positioning":x.lastOpened!==this&&(null===(i=x.lastOpened)||void 0===i||i.hideTooltip()),this.enterTopLayer(),this.currentElement&&this.updatePosition(this.currentElement)}}enterTopLayer(){if("function"==typeof this.showPopover)try{this.setAttribute("popover","manual"),this.showPopover()}catch(t){this.removeAttribute("popover")}}leaveTopLayer(){this.removeAttribute("popover")}};E.styles=[f,g],t([d()],E.prototype,"state",void 0),t([h({reflect:!0})],E.prototype,"position",void 0),t([h({reflect:!0})],E.prototype,"role",void 0),t([h({reflect:!0})],E.prototype,"id",void 0),t([h({reflect:!0,type:Number})],E.prototype,"delay",void 0),t([h({type:Boolean,reflect:!0})],E.prototype,"open",void 0),t([h({reflect:!0,type:Number,attribute:"side-offset"})],E.prototype,"sideOffset",void 0),t([h({reflect:!0,type:Number,attribute:"align-offset"})],E.prototype,"alignOffset",void 0),t([v("id")],E.prototype,"handleIdChange",null),t([v("state")],E.prototype,"handleStateChange",null),E=x=t([p("nord-tooltip")],E);var C=E;export{C as default};
2
2
  //# sourceMappingURL=Tooltip.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Tooltip.js","sources":["../src/common/attribute.ts","../src/tooltip/Tooltip.ts"],"sourcesContent":["function getTokens(element: Element, attr: string) {\n const value = element.getAttribute(attr)\n return value ? value.split(/\\s+/) : []\n}\n\nfunction setTokens(element: Element, attr: string, tokens: string[]) {\n element.setAttribute(attr, tokens.join(' '))\n}\n\n/**\n * Carefully adds a token to a space-separated attribute\n * Similar to classList, but for any attribute.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/add\n */\nexport function add(element: Element, attr: string, token: string) {\n const tokens = getTokens(element, attr)\n\n if (!tokens.includes(token)) {\n setTokens(element, attr, tokens.concat(token))\n }\n}\n\n/**\n * Carefully removes a token from a space-separated attribute.\n * Similar to classList, but for any attribute.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/remove\n */\nexport function remove(element: Element, attr: string, token: string) {\n const tokens = getTokens(element, attr)\n\n if (tokens.includes(token)) {\n setTokens(\n element,\n attr,\n tokens.filter(t => t !== token),\n )\n }\n}\n","import type { States } from '../common/fsm.js'\nimport type { FocusableMixinInterface } from '../common/mixins/FocusableMixin.js'\nimport { computePosition, flip, offset, shift } from '@floating-ui/dom'\n\nimport { html, LitElement } from 'lit'\nimport { customElement, property, state } from 'lit/decorators.js'\nimport * as attr from '../common/attribute.js'\nimport { EventController } from '../common/controllers/EventController.js'\nimport { SlotController } from '../common/controllers/SlotController.js'\nimport { observe } from '../common/decorators/observe.js'\nimport { fsm } from '../common/fsm.js'\nimport { logicalToPhysical } from '../common/positioning.js'\nimport componentStyle from '../common/styles/Component.css'\nimport style from './Tooltip.css'\n\n// @ts-expect-error we're being naughty and accessing a protected field!\n// however this means we always get the correct types,\n// and it will ensure this file is not forgotten about if focusable mixin ever changes\ntype FocusableElement = HTMLElement & Pick<FocusableMixinInterface, 'focusableRef'>\n\nfunction isElement(el: Node): el is Element {\n return el.nodeType === Node.ELEMENT_NODE\n}\n\nfunction referencesTooltip(node: Node, tooltip: Tooltip): Element | null {\n if (!tooltip.id || !isElement(node))\n return null\n\n // Walk up so hovering a descendant (icon, span, etc.) still resolves to\n // the ancestor that carries aria-describedby.\n return node.closest(`[aria-describedby~=\"${CSS.escape(tooltip.id)}\"]`)\n}\n\nfunction getFocusable(el?: FocusableElement): HTMLElement | undefined {\n const focusable = el?.focusableRef?.value as HTMLElement | FocusableElement | undefined\n\n if (focusable && 'focusableRef' in focusable) {\n return getFocusable(focusable)\n }\n\n return focusable\n}\n\nconst { transition } = fsm({\n hidden: {\n show: 'waiting',\n },\n visible: {\n hide: 'hidden',\n reposition: 'positioning',\n show: 'positioning',\n },\n waiting: {\n timeout: 'positioning',\n hide: 'hidden',\n },\n positioning: {\n positioned: 'visible',\n hide: 'hidden',\n },\n})\n\ntype TooltipStates = States<typeof transition>\n\n/**\n * Tooltips are floating containers for displaying additional information\n * for the currently focused element. A tooltip can be useful when you want\n * to e.g. give a hint about an existing Command Menu shortcut.\n *\n * @status ready\n * @category overlay\n * @slot - The tooltip content\n * @slot shortcut - Optional slot that holds shortcut keys to access the subject\n * @cssprop [--n-tooltip-max-size=50ch] - Controls the maximum inline size, or width, of the tooltip.\n */\n@customElement('nord-tooltip')\nexport default class Tooltip extends LitElement {\n static styles = [componentStyle, style]\n\n // tracks the last tooltip opened, so we can enforce only one is ever open at a time\n private static lastOpened?: Tooltip\n\n private shortcutSlot = new SlotController(this, 'shortcut')\n private events = new EventController(this)\n\n // The current element which revealed the tooltip shown\n private currentElement?: FocusableElement\n private timeoutId?: ReturnType<typeof setTimeout>\n\n /**\n * the proxy element is for cases where the targetElement is a web component,\n * and the WC has a focusable child in its shadow root e.g. a button component.\n * in this case, when the tooltip is shown, we inject the proxy into targetElement's shadow root\n * and wire up aria-describedby from the focusable element to the proxy.\n * when the tooltip is hidden, we remove the proxy and remove the aria-describedby relationship.\n */\n private proxy?: HTMLSpanElement\n\n /**\n * The current state of the tooltip, dependent on the state machine\n */\n @state() private state: TooltipStates = 'hidden'\n\n // The current coordinates for the tooltip\n private coords: [number, number] = [0, 0]\n\n /**\n * Control the position of the tooltip component.\n * When set to \"none\", the tooltip will be shown above\n * but accommodate for browser boundaries.\n */\n @property({ reflect: true }) position: 'block-end' | 'block-start' | 'inline-start' | 'inline-end' = 'block-start'\n\n /**\n * The tooltip role, set on the component by default.\n */\n\n @property({ reflect: true }) role = 'tooltip'\n\n /**\n * The id for the active element to reference via aria-describedby.\n */\n\n @property({ reflect: true }) id: string = ''\n\n /**\n * The delay in milliseconds before the tooltip is opened.\n */\n @property({ reflect: true, type: Number }) delay: number = 500\n\n /**\n * Indicates whether the tooltip is currently open.\n */\n @property({ type: Boolean, reflect: true }) open: boolean = false\n\n /**\n * Apply all event listeners\n */\n connectedCallback() {\n super.connectedCallback()\n\n this.proxy = document.createElement('span')\n\n const rootNode = this.getRootNode() as Document\n\n this.events.listen(rootNode, 'keydown', this.hideOnEscape)\n\n // we treat mouseover and focusin the same, since they both show tooltip\n this.events.listen(rootNode, 'mouseover', this.handleShow)\n this.events.listen(rootNode, 'focusin', this.handleShow)\n\n // we treat focusout, mouseout, click the same, since they all hide tooltip\n this.events.listen(rootNode, 'mouseout', this.handleHide)\n this.events.listen(rootNode, 'focusout', this.handleHide)\n // we use event capture here to handle cases where e.g. a close button causes its ancestor to be removed from the DOM.\n // in this case the click event will never bubble up to the rootNode, so we never receive it, and the tooltip can remain open\n // by capturing, we get this event first, and can close the tooltip eagerly\n this.events.listen(rootNode, 'click', this.handleHide, { capture: true })\n\n this.events.listen(window, 'resize', this.reposition, { passive: true })\n this.events.listen(window, 'scroll', this.reposition, { passive: true })\n }\n\n disconnectedCallback() {\n super.disconnectedCallback()\n\n this.proxy?.remove()\n this.proxy = undefined\n }\n\n render() {\n return html`\n <div class=\"n-tooltip\">\n <slot></slot>\n <div class=\"n-tooltip-shortcut\" ?hidden=${this.shortcutSlot.isEmpty}>\n <slot class=\"n-tooltip-key\" name=\"shortcut\"></slot>\n </div>\n </div>\n `\n }\n\n @observe('id')\n protected handleIdChange() {\n if (!this.id) {\n console.warn('NORD: The tooltip requires an id attribute and value')\n }\n }\n\n @observe('state')\n private handleStateChange(prevState: TooltipStates) {\n switch (this.state) {\n case 'hidden': {\n if (prevState === 'waiting' && this.timeoutId) {\n clearTimeout(this.timeoutId)\n }\n\n this.removeDescribedBy()\n this.currentElement = undefined\n this.style.visibility = 'hidden'\n this.style.opacity = '0'\n this.open = false\n this.leaveTopLayer()\n break\n }\n\n case 'visible': {\n this.timeoutId = undefined\n Tooltip.lastOpened = this\n this.addDescribedBy()\n\n const [x, y] = this.coords\n\n // use physical properties here since floating-ui\n // works exclusively in physical dimensions\n // we do all the mapping in logicalToPhysical\n this.style.left = `${x}px`\n this.style.top = `${y}px`\n this.style.visibility = 'visible'\n this.style.opacity = '1'\n this.open = true\n break\n }\n\n case 'waiting': {\n this.timeoutId = setTimeout(() => {\n this.state = transition(this.state, 'timeout')\n }, this.delay)\n break\n }\n\n case 'positioning': {\n if (Tooltip.lastOpened !== this) {\n Tooltip.lastOpened?.hideTooltip()\n }\n\n this.enterTopLayer()\n if (this.currentElement) {\n this.updatePosition(this.currentElement)\n }\n break\n }\n }\n }\n\n /**\n * Setting and updating the position of the tooltip\n */\n private updatePosition = (currentElement: HTMLElement) =>\n computePosition(currentElement, this, {\n strategy: 'fixed',\n placement: logicalToPhysical(this.position),\n middleware: [\n offset(8),\n flip(),\n shift({\n padding: 8,\n }),\n ],\n }).then(({ x, y }) => {\n this.coords = [x, y]\n this.state = transition(this.state, 'positioned')\n })\n\n private hideTooltip = () => {\n this.state = transition(this.state, 'hide')\n }\n\n private reposition = () => {\n this.state = transition(this.state, 'reposition')\n }\n\n private handleShow = (e: Event) => {\n const node = e.target as Node\n const reference = referencesTooltip(node, this) as FocusableElement | null\n\n if (reference) {\n this.currentElement = reference\n this.state = transition(this.state, 'show')\n }\n }\n\n private handleHide = (e: Event) => {\n const node = e.target as Node\n if (this.currentElement && isElement(node) && this.currentElement.contains(node)) {\n this.hideTooltip()\n }\n }\n\n private hideOnEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.hideTooltip()\n }\n }\n\n private addDescribedBy = () => {\n const focusable = getFocusable(this.currentElement)\n\n if (focusable && this.proxy) {\n this.proxy.hidden = true\n this.proxy.id = this.id\n this.proxy.textContent = this.textContent\n\n focusable.insertAdjacentElement('afterend', this.proxy)\n attr.add(focusable, 'aria-describedby', this.id)\n }\n }\n\n /**\n * Place the element in the top layer via the Popover API so that\n * position: fixed works relative to the viewport regardless of\n * `overflow: hidden|auto` or `contain` on any ancestor.\n */\n private enterTopLayer() {\n if (typeof this.showPopover !== 'function')\n return\n\n try {\n this.setAttribute('popover', 'manual')\n this.showPopover()\n }\n catch {\n this.removeAttribute('popover')\n }\n }\n\n private leaveTopLayer() {\n this.removeAttribute('popover')\n }\n\n private removeDescribedBy = () => {\n const focusable = getFocusable(this.currentElement)\n\n if (focusable && this.proxy) {\n this.proxy.remove()\n attr.remove(focusable, 'aria-describedby', this.id)\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'nord-tooltip': Tooltip\n }\n}\n"],"names":["getTokens","element","attr","value","getAttribute","split","setTokens","tokens","setAttribute","join","isElement","el","nodeType","Node","ELEMENT_NODE","getFocusable","focusable","_a","focusableRef","transition","fsm","hidden","show","visible","hide","reposition","waiting","timeout","positioning","positioned","Tooltip","Tooltip_1","LitElement","constructor","this","shortcutSlot","SlotController","events","EventController","state","coords","position","role","id","delay","open","updatePosition","currentElement","computePosition","strategy","placement","logicalToPhysical","middleware","offset","flip","shift","padding","then","x","y","hideTooltip","handleShow","e","reference","node","tooltip","closest","CSS","escape","referencesTooltip","target","handleHide","contains","hideOnEscape","key","addDescribedBy","proxy","textContent","insertAdjacentElement","token","includes","concat","attr.add","removeDescribedBy","remove","filter","t","attr.remove","connectedCallback","super","document","createElement","rootNode","getRootNode","listen","capture","window","passive","disconnectedCallback","undefined","render","html","isEmpty","handleIdChange","console","warn","handleStateChange","prevState","timeoutId","clearTimeout","style","visibility","opacity","leaveTopLayer","lastOpened","left","top","setTimeout","enterTopLayer","showPopover","removeAttribute","styles","componentStyle","__decorate","prototype","property","reflect","type","Number","Boolean","observe","customElement"],"mappings":"+cAAA,SAASA,EAAUC,EAAkBC,GACnC,MAAMC,EAAQF,EAAQG,aAAaF,GACnC,OAAOC,EAAQA,EAAME,MAAM,OAAS,EACtC,CAEA,SAASC,EAAUL,EAAkBC,EAAcK,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Tooltip.js","sources":["../src/common/attribute.ts","../src/tooltip/Tooltip.ts"],"sourcesContent":["function getTokens(element: Element, attr: string) {\n const value = element.getAttribute(attr)\n return value ? value.split(/\\s+/) : []\n}\n\nfunction setTokens(element: Element, attr: string, tokens: string[]) {\n element.setAttribute(attr, tokens.join(' '))\n}\n\n/**\n * Carefully adds a token to a space-separated attribute\n * Similar to classList, but for any attribute.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/add\n */\nexport function add(element: Element, attr: string, token: string) {\n const tokens = getTokens(element, attr)\n\n if (!tokens.includes(token)) {\n setTokens(element, attr, tokens.concat(token))\n }\n}\n\n/**\n * Carefully removes a token from a space-separated attribute.\n * Similar to classList, but for any attribute.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/remove\n */\nexport function remove(element: Element, attr: string, token: string) {\n const tokens = getTokens(element, attr)\n\n if (tokens.includes(token)) {\n setTokens(\n element,\n attr,\n tokens.filter(t => t !== token),\n )\n }\n}\n","import type { States } from '../common/fsm.js'\nimport type { FocusableMixinInterface } from '../common/mixins/FocusableMixin.js'\nimport { computePosition, flip, offset, shift } from '@floating-ui/dom'\n\nimport { html, LitElement } from 'lit'\nimport { customElement, property, state } from 'lit/decorators.js'\nimport * as attr from '../common/attribute.js'\nimport { EventController } from '../common/controllers/EventController.js'\nimport { SlotController } from '../common/controllers/SlotController.js'\nimport { observe } from '../common/decorators/observe.js'\nimport { fsm } from '../common/fsm.js'\nimport { logicalToPhysical } from '../common/positioning.js'\nimport componentStyle from '../common/styles/Component.css'\nimport style from './Tooltip.css'\n\n// @ts-expect-error we're being naughty and accessing a protected field!\n// however this means we always get the correct types,\n// and it will ensure this file is not forgotten about if focusable mixin ever changes\ntype FocusableElement = HTMLElement & Pick<FocusableMixinInterface, 'focusableRef'>\n\nfunction isElement(el: Node): el is Element {\n return el.nodeType === Node.ELEMENT_NODE\n}\n\nfunction referencesTooltip(node: Node, tooltip: Tooltip): Element | null {\n if (!tooltip.id || !isElement(node))\n return null\n\n // Walk up so hovering a descendant (icon, span, etc.) still resolves to\n // the ancestor that carries aria-describedby.\n return node.closest(`[aria-describedby~=\"${CSS.escape(tooltip.id)}\"]`)\n}\n\nfunction getFocusable(el?: FocusableElement): HTMLElement | undefined {\n const focusable = el?.focusableRef?.value as HTMLElement | FocusableElement | undefined\n\n if (focusable && 'focusableRef' in focusable) {\n return getFocusable(focusable)\n }\n\n return focusable\n}\n\nconst { transition } = fsm({\n hidden: {\n show: 'waiting',\n },\n visible: {\n hide: 'hidden',\n reposition: 'positioning',\n show: 'positioning',\n },\n waiting: {\n timeout: 'positioning',\n hide: 'hidden',\n },\n positioning: {\n positioned: 'visible',\n hide: 'hidden',\n },\n})\n\ntype TooltipStates = States<typeof transition>\n\n/**\n * Tooltips are floating containers for displaying additional information\n * for the currently focused element. A tooltip can be useful when you want\n * to e.g. give a hint about an existing Command Menu shortcut.\n *\n * @status ready\n * @category overlay\n * @slot - The tooltip content\n * @slot shortcut - Optional slot that holds shortcut keys to access the subject\n * @cssprop [--n-tooltip-max-size=50ch] - Controls the maximum inline size, or width, of the tooltip.\n */\n@customElement('nord-tooltip')\nexport default class Tooltip extends LitElement {\n static styles = [componentStyle, style]\n\n // tracks the last tooltip opened, so we can enforce only one is ever open at a time\n private static lastOpened?: Tooltip\n\n private shortcutSlot = new SlotController(this, 'shortcut')\n private events = new EventController(this)\n\n // The current element which revealed the tooltip shown\n private currentElement?: FocusableElement\n private timeoutId?: ReturnType<typeof setTimeout>\n\n /**\n * the proxy element is for cases where the targetElement is a web component,\n * and the WC has a focusable child in its shadow root e.g. a button component.\n * in this case, when the tooltip is shown, we inject the proxy into targetElement's shadow root\n * and wire up aria-describedby from the focusable element to the proxy.\n * when the tooltip is hidden, we remove the proxy and remove the aria-describedby relationship.\n */\n private proxy?: HTMLSpanElement\n\n /**\n * The current state of the tooltip, dependent on the state machine\n */\n @state() private state: TooltipStates = 'hidden'\n\n // The current coordinates for the tooltip\n private coords: [number, number] = [0, 0]\n\n /**\n * Control the position of the tooltip component.\n * When set to \"none\", the tooltip will be shown above\n * but accommodate for browser boundaries.\n */\n @property({ reflect: true }) position: 'block-end' | 'block-start' | 'inline-start' | 'inline-end' = 'block-start'\n\n /**\n * The tooltip role, set on the component by default.\n */\n\n @property({ reflect: true }) role = 'tooltip'\n\n /**\n * The id for the active element to reference via aria-describedby.\n */\n\n @property({ reflect: true }) id: string = ''\n\n /**\n * The delay in milliseconds before the tooltip is opened.\n */\n @property({ reflect: true, type: Number }) delay: number = 500\n\n /**\n * Indicates whether the tooltip is currently open.\n */\n @property({ type: Boolean, reflect: true }) open: boolean = false\n\n /**\n * Distance in pixels from the trigger along the main axis — the gap between\n * the tooltip and the side it opens against. Fed into Floating UI's `offset`\n * middleware as `mainAxis`. Defaults to `8`.\n */\n @property({ reflect: true, type: Number, attribute: 'side-offset' }) sideOffset: number = 8\n\n /**\n * Offset in pixels along the alignment axis — skids the tooltip along the\n * trigger's edge. Fed into Floating UI's `offset` middleware as\n * `alignmentAxis`. Defaults to `0`.\n */\n @property({ reflect: true, type: Number, attribute: 'align-offset' }) alignOffset: number = 0\n\n /**\n * Apply all event listeners\n */\n connectedCallback() {\n super.connectedCallback()\n\n this.proxy = document.createElement('span')\n\n const rootNode = this.getRootNode() as Document\n\n this.events.listen(rootNode, 'keydown', this.hideOnEscape)\n\n // we treat mouseover and focusin the same, since they both show tooltip\n this.events.listen(rootNode, 'mouseover', this.handleShow)\n this.events.listen(rootNode, 'focusin', this.handleShow)\n\n // we treat focusout, mouseout, click the same, since they all hide tooltip\n this.events.listen(rootNode, 'mouseout', this.handleHide)\n this.events.listen(rootNode, 'focusout', this.handleHide)\n // we use event capture here to handle cases where e.g. a close button causes its ancestor to be removed from the DOM.\n // in this case the click event will never bubble up to the rootNode, so we never receive it, and the tooltip can remain open\n // by capturing, we get this event first, and can close the tooltip eagerly\n this.events.listen(rootNode, 'click', this.handleHide, { capture: true })\n\n this.events.listen(window, 'resize', this.reposition, { passive: true })\n this.events.listen(window, 'scroll', this.reposition, { passive: true })\n }\n\n disconnectedCallback() {\n super.disconnectedCallback()\n\n this.proxy?.remove()\n this.proxy = undefined\n }\n\n render() {\n return html`\n <div class=\"n-tooltip\">\n <slot></slot>\n <div class=\"n-tooltip-shortcut\" ?hidden=${this.shortcutSlot.isEmpty}>\n <slot class=\"n-tooltip-key\" name=\"shortcut\"></slot>\n </div>\n </div>\n `\n }\n\n @observe('id')\n protected handleIdChange() {\n if (!this.id) {\n console.warn('NORD: The tooltip requires an id attribute and value')\n }\n }\n\n @observe('state')\n private handleStateChange(prevState: TooltipStates) {\n switch (this.state) {\n case 'hidden': {\n if (prevState === 'waiting' && this.timeoutId) {\n clearTimeout(this.timeoutId)\n }\n\n this.removeDescribedBy()\n this.currentElement = undefined\n this.style.visibility = 'hidden'\n this.style.opacity = '0'\n this.open = false\n this.leaveTopLayer()\n break\n }\n\n case 'visible': {\n this.timeoutId = undefined\n Tooltip.lastOpened = this\n this.addDescribedBy()\n\n const [x, y] = this.coords\n\n // use physical properties here since floating-ui\n // works exclusively in physical dimensions\n // we do all the mapping in logicalToPhysical.\n this.style.left = `${x}px`\n this.style.top = `${y}px`\n this.style.visibility = 'visible'\n this.style.opacity = '1'\n this.open = true\n break\n }\n\n case 'waiting': {\n this.timeoutId = setTimeout(() => {\n this.state = transition(this.state, 'timeout')\n }, this.delay)\n break\n }\n\n case 'positioning': {\n if (Tooltip.lastOpened !== this) {\n Tooltip.lastOpened?.hideTooltip()\n }\n\n this.enterTopLayer()\n if (this.currentElement) {\n this.updatePosition(this.currentElement)\n }\n break\n }\n }\n }\n\n /**\n * Setting and updating the position of the tooltip\n */\n private updatePosition = (currentElement: HTMLElement) =>\n computePosition(currentElement, this, {\n strategy: 'fixed',\n placement: logicalToPhysical(this.position),\n middleware: [\n offset({ mainAxis: this.sideOffset, alignmentAxis: this.alignOffset }),\n flip(),\n shift({\n padding: 8,\n }),\n ],\n }).then(({ x, y }) => {\n this.coords = [x, y]\n this.state = transition(this.state, 'positioned')\n })\n\n private hideTooltip = () => {\n this.state = transition(this.state, 'hide')\n }\n\n private reposition = () => {\n this.state = transition(this.state, 'reposition')\n }\n\n private handleShow = (e: Event) => {\n const node = e.target as Node\n const reference = referencesTooltip(node, this) as FocusableElement | null\n\n if (reference) {\n this.currentElement = reference\n this.state = transition(this.state, 'show')\n }\n }\n\n private handleHide = (e: Event) => {\n const node = e.target as Node\n if (this.currentElement && isElement(node) && this.currentElement.contains(node)) {\n this.hideTooltip()\n }\n }\n\n private hideOnEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.hideTooltip()\n }\n }\n\n private addDescribedBy = () => {\n const focusable = getFocusable(this.currentElement)\n\n if (focusable && this.proxy) {\n this.proxy.hidden = true\n this.proxy.id = this.id\n this.proxy.textContent = this.textContent\n\n focusable.insertAdjacentElement('afterend', this.proxy)\n attr.add(focusable, 'aria-describedby', this.id)\n }\n }\n\n /**\n * Place the element in the top layer via the Popover API so that\n * position: fixed works relative to the viewport regardless of\n * `overflow: hidden|auto` or `contain` on any ancestor.\n */\n private enterTopLayer() {\n if (typeof this.showPopover !== 'function')\n return\n\n try {\n this.setAttribute('popover', 'manual')\n this.showPopover()\n }\n catch {\n this.removeAttribute('popover')\n }\n }\n\n private leaveTopLayer() {\n this.removeAttribute('popover')\n }\n\n private removeDescribedBy = () => {\n const focusable = getFocusable(this.currentElement)\n\n if (focusable && this.proxy) {\n this.proxy.remove()\n attr.remove(focusable, 'aria-describedby', this.id)\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'nord-tooltip': Tooltip\n }\n}\n"],"names":["getTokens","element","attr","value","getAttribute","split","setTokens","tokens","setAttribute","join","isElement","el","nodeType","Node","ELEMENT_NODE","getFocusable","focusable","_a","focusableRef","transition","fsm","hidden","show","visible","hide","reposition","waiting","timeout","positioning","positioned","Tooltip","Tooltip_1","LitElement","constructor","this","shortcutSlot","SlotController","events","EventController","state","coords","position","role","id","delay","open","sideOffset","alignOffset","updatePosition","currentElement","computePosition","strategy","placement","logicalToPhysical","middleware","offset","mainAxis","alignmentAxis","flip","shift","padding","then","x","y","hideTooltip","handleShow","e","reference","node","tooltip","closest","CSS","escape","referencesTooltip","target","handleHide","contains","hideOnEscape","key","addDescribedBy","proxy","textContent","insertAdjacentElement","token","includes","concat","attr.add","removeDescribedBy","remove","filter","t","attr.remove","connectedCallback","super","document","createElement","rootNode","getRootNode","listen","capture","window","passive","disconnectedCallback","undefined","render","html","isEmpty","handleIdChange","console","warn","handleStateChange","prevState","timeoutId","clearTimeout","style","visibility","opacity","leaveTopLayer","lastOpened","left","top","setTimeout","enterTopLayer","showPopover","removeAttribute","styles","componentStyle","__decorate","prototype","property","reflect","type","Number","Boolean","attribute","observe","customElement"],"mappings":"+cAAA,SAASA,EAAUC,EAAkBC,GACnC,MAAMC,EAAQF,EAAQG,aAAaF,GACnC,OAAOC,EAAQA,EAAME,MAAM,OAAS,EACtC,CAEA,SAASC,EAAUL,EAAkBC,EAAcK,GACjDN,EAAQO,aAAaN,EAAMK,EAAOE,KAAK,KACzC,8gDCaA,SAASC,EAAUC,GACjB,OAAOA,EAAGC,WAAaC,KAAKC,YAC9B,CAWA,SAASC,EAAaJ,SACpB,MAAMK,EAA8B,QAAlBC,EAAAN,aAAA,EAAAA,EAAIO,oBAAc,IAAAD,OAAA,EAAAA,EAAAd,MAEpC,OAAIa,GAAa,iBAAkBA,EAC1BD,EAAaC,GAGfA,CACT,CAEA,MAAMG,WAAEA,GAAeC,EAAI,CACzBC,OAAQ,CACNC,KAAM,WAERC,QAAS,CACPC,KAAM,SACNC,WAAY,cACZH,KAAM,eAERI,QAAS,CACPC,QAAS,cACTH,KAAM,UAERI,YAAa,CACXC,WAAY,UACZL,KAAM,YAkBK,IAAMM,EAAOC,EAAb,cAAsBC,EAAtB,WAAAC,uBAMLC,KAAYC,aAAG,IAAIC,EAAeF,KAAM,YACxCA,KAAAG,OAAS,IAAIC,EAAgBJ,MAkBpBA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EO,aAAAP,GACNnF,KAAK0F,gBAAgB,UACtB,GAxQM9F,EAAA+F,OAAS,CAACC,EAAgBZ,GAwBhBa,EAAA,CAAhBxF,KAA+CT,EAAAkG,UAAA,aAAA,GAUnBD,EAAA,CAA5BE,EAAS,CAAEC,SAAS,KAA6FpG,EAAAkG,UAAA,gBAAA,GAMrFD,EAAA,CAA5BE,EAAS,CAAEC,SAAS,KAAwBpG,EAAAkG,UAAA,YAAA,GAMhBD,EAAA,CAA5BE,EAAS,CAAEC,SAAS,KAAuBpG,EAAAkG,UAAA,UAAA,GAKDD,EAAA,CAA1CE,EAAS,CAAEC,SAAS,EAAMC,KAAMC,UAA6BtG,EAAAkG,UAAA,aAAA,GAKlBD,EAAA,CAA3CE,EAAS,CAAEE,KAAME,QAASH,SAAS,KAA6BpG,EAAAkG,UAAA,YAAA,GAOID,EAAA,CAApEE,EAAS,CAAEC,SAAS,EAAMC,KAAMC,OAAQE,UAAW,iBAAuCxG,EAAAkG,UAAA,kBAAA,GAOrBD,EAAA,CAArEE,EAAS,CAAEC,SAAS,EAAMC,KAAMC,OAAQE,UAAW,kBAAyCxG,EAAAkG,UAAA,mBAAA,GAiDnFD,EAAA,CADTQ,EAAQ,OAKRzG,EAAAkG,UAAA,iBAAA,MAGOD,EAAA,CADPQ,EAAQ,UAsDRzG,EAAAkG,UAAA,oBAAA,MApLkBlG,EAAOC,EAAAgG,EAAA,CAD3BS,EAAc,iBACM1G,SAAAA"}
package/lib/Truncate.js CHANGED
@@ -1,2 +1,2 @@
1
- import{_ as t}from"./tslib.es6-CmLYFWVC.js";import{css as e,LitElement as i,isServer as r,html as s}from"lit";import{state as o,property as n,customElement as l}from"lit/decorators.js";import{createRef as a,ref as c}from"lit/directives/ref.js";import"./Tooltip.js";import"./positioning-D-K8Mueq.js";import"./EventController-BBOmvfLa.js";import"./SlotController-Z6eG7LSZ.js";import"./observe-D0n0zOfU.js";import"./fsm-Bq5jMQrK.js";import"./Component-DSU3Qp0O.js";const d=e`:host{display:inline-block;inline-size:100%;max-inline-size:100%;min-inline-size:0;vertical-align:bottom}.n-truncate{display:block;white-space:nowrap;overflow:hidden}:host([line-clamp]) .n-truncate{white-space:normal;max-block-size:calc(var(--_n-truncate-line-clamp,2) * 1lh)}.n-truncate-source{display:none}`;let p=0;let h=class extends i{constructor(){super(...arguments),this.spanRef=a(),this.tooltipId="n-truncate-"+ ++p,this.currentTrigger=null,this.isTruncated=!1,this.text="",this.position="block-start",this.delay=500,this.lineClamp=1,this.noTooltip=!1}connectedCallback(){super.connectedCallback(),r||(this.observer=new ResizeObserver((()=>{requestAnimationFrame((()=>this.measure()))})),this.contentObserver=new MutationObserver((()=>{this.captureText(),this.measure()})),this.contentObserver.observe(this,{characterData:!0,childList:!0,subtree:!0}),this.captureText())}firstUpdated(){const t=this.spanRef.value;t&&this.observer&&this.observer.observe(t)}updated(){this.syncTooltip()}disconnectedCallback(){var t,e,i;super.disconnectedCallback(),null===(t=this.observer)||void 0===t||t.disconnect(),this.observer=void 0,null===(e=this.contentObserver)||void 0===e||e.disconnect(),this.contentObserver=void 0,null===(i=this.tooltipElement)||void 0===i||i.remove(),this.tooltipElement=void 0,this.clearTrigger()}captureText(){var t;const e=(null!==(t=this.textContent)&&void 0!==t?t:"").trim();e!==this.text&&(this.text=e)}measure(){const t=this.spanRef.value;if(!t)return;const e=this.text;if(!e)return t.textContent="",void(this.isTruncated=!1);if(t.textContent=e,this.fits(t))return void(this.isTruncated=!1);let i=0,r=e.length;for(;i<r;){const s=Math.ceil((i+r)/2);t.textContent=m(e.slice(0,s))+"…",this.fits(t)?i=s:r=s-1}t.textContent=m(e.slice(0,i))+"…",this.isTruncated=!0}fits(t){return this.lineClamp>1?t.scrollHeight<=t.clientHeight:t.scrollWidth<=t.clientWidth}findTriggerElement(){let t=this;for(;t&&t!==document.body&&t!==document.documentElement;){if("none"!==getComputedStyle(t).pointerEvents)return t;t=t.parentElement}return this}addDescribedById(t,e){const i=t.getAttribute("aria-describedby"),r=i?i.split(/\s+/).filter(Boolean):[];r.includes(e)||(r.push(e),t.setAttribute("aria-describedby",r.join(" ")))}removeDescribedById(t,e){const i=t.getAttribute("aria-describedby");if(!i)return;const r=i.split(/\s+/).filter(Boolean).filter((t=>t!==e));r.length?t.setAttribute("aria-describedby",r.join(" ")):t.removeAttribute("aria-describedby")}clearTrigger(){this.currentTrigger&&(this.removeDescribedById(this.currentTrigger,this.tooltipId),this.currentTrigger=null)}syncTooltip(){var t,e;if(!this.isTruncated||!this.text)return this.removeAttribute("truncated"),null===(t=this.tooltipElement)||void 0===t||t.remove(),this.tooltipElement=void 0,void this.clearTrigger();if(this.setAttribute("truncated",""),this.noTooltip)return null===(e=this.tooltipElement)||void 0===e||e.remove(),this.tooltipElement=void 0,void this.clearTrigger();this.tooltipElement||(this.tooltipElement=document.createElement("nord-tooltip"),this.tooltipElement.id=this.tooltipId,document.body.appendChild(this.tooltipElement)),this.tooltipElement.setAttribute("position",this.position),this.tooltipElement.setAttribute("delay",String(this.delay)),this.tooltipElement.textContent=this.text;const i=this.findTriggerElement();i!==this.currentTrigger&&(this.currentTrigger&&this.removeDescribedById(this.currentTrigger,this.tooltipId),this.currentTrigger=i),this.addDescribedById(i,this.tooltipId)}willUpdate(t){t.has("lineClamp")&&(this.lineClamp>1?(this.setAttribute("line-clamp",String(this.lineClamp)),this.style.setProperty("--_n-truncate-line-clamp",String(this.lineClamp))):(this.removeAttribute("line-clamp"),this.style.removeProperty("--_n-truncate-line-clamp")))}render(){return s`<span ${c(this.spanRef)} class="n-truncate"></span><slot class="n-truncate-source" aria-hidden="true"></slot>`}};h.styles=d,t([o()],h.prototype,"isTruncated",void 0),t([o()],h.prototype,"text",void 0),t([n({reflect:!0})],h.prototype,"position",void 0),t([n({reflect:!0,type:Number})],h.prototype,"delay",void 0),t([n({type:Number,attribute:"line-clamp"})],h.prototype,"lineClamp",void 0),t([n({type:Boolean,reflect:!0,attribute:"no-tooltip"})],h.prototype,"noTooltip",void 0),h=t([l("nord-truncate")],h);var u=h;function m(t){return t.replace(/[\s.,;:!?-]+$/u,"")}export{u as default};
1
+ import{_ as t}from"./tslib.es6-CmLYFWVC.js";import{css as e,LitElement as i,isServer as r,html as s}from"lit";import{state as o,property as n,customElement as l}from"lit/decorators.js";import{createRef as a,ref as c}from"lit/directives/ref.js";import"./Tooltip.js";import"./positioning-D-K8Mueq.js";import"./EventController-BBOmvfLa.js";import"./SlotController-Z6eG7LSZ.js";import"./observe-D0n0zOfU.js";import"./fsm-Bq5jMQrK.js";import"./Component-DSU3Qp0O.js";const d=e`:host{display:inline-block;inline-size:100%;max-inline-size:100%;min-inline-size:0;vertical-align:bottom}.n-truncate{display:block;white-space:nowrap;overflow:hidden}:host([line-clamp]) .n-truncate{white-space:normal;max-block-size:calc(var(--_n-truncate-line-clamp,2) * 1lh)}.n-truncate-source{display:none}`;let p=0;let h=class extends i{constructor(){super(...arguments),this.spanRef=a(),this.tooltipId="n-truncate-"+ ++p,this.currentTrigger=null,this.isTruncated=!1,this.text="",this.position="block-start",this.delay=500,this.sideOffset=8,this.alignOffset=0,this.lineClamp=1,this.noTooltip=!1}connectedCallback(){super.connectedCallback(),r||(this.observer=new ResizeObserver((()=>{requestAnimationFrame((()=>this.measure()))})),this.contentObserver=new MutationObserver((()=>{this.captureText(),this.measure()})),this.contentObserver.observe(this,{characterData:!0,childList:!0,subtree:!0}),this.captureText())}firstUpdated(){const t=this.spanRef.value;t&&this.observer&&this.observer.observe(t)}updated(){this.syncTooltip()}disconnectedCallback(){var t,e,i;super.disconnectedCallback(),null===(t=this.observer)||void 0===t||t.disconnect(),this.observer=void 0,null===(e=this.contentObserver)||void 0===e||e.disconnect(),this.contentObserver=void 0,null===(i=this.tooltipElement)||void 0===i||i.remove(),this.tooltipElement=void 0,this.clearTrigger()}captureText(){var t;const e=(null!==(t=this.textContent)&&void 0!==t?t:"").trim();e!==this.text&&(this.text=e)}measure(){const t=this.spanRef.value;if(!t)return;const e=this.text;if(!e)return t.textContent="",void(this.isTruncated=!1);if(t.textContent=e,this.fits(t))return void(this.isTruncated=!1);let i=0,r=e.length;for(;i<r;){const s=Math.ceil((i+r)/2);t.textContent=m(e.slice(0,s))+"…",this.fits(t)?i=s:r=s-1}t.textContent=m(e.slice(0,i))+"…",this.isTruncated=!0}fits(t){return this.lineClamp>1?t.scrollHeight<=t.clientHeight:t.scrollWidth<=t.clientWidth}findTriggerElement(){let t=this;for(;t&&t!==document.body&&t!==document.documentElement;){if("none"!==getComputedStyle(t).pointerEvents)return t;t=t.parentElement}return this}addDescribedById(t,e){const i=t.getAttribute("aria-describedby"),r=i?i.split(/\s+/).filter(Boolean):[];r.includes(e)||(r.push(e),t.setAttribute("aria-describedby",r.join(" ")))}removeDescribedById(t,e){const i=t.getAttribute("aria-describedby");if(!i)return;const r=i.split(/\s+/).filter(Boolean).filter((t=>t!==e));r.length?t.setAttribute("aria-describedby",r.join(" ")):t.removeAttribute("aria-describedby")}clearTrigger(){this.currentTrigger&&(this.removeDescribedById(this.currentTrigger,this.tooltipId),this.currentTrigger=null)}syncTooltip(){var t,e;if(!this.isTruncated||!this.text)return this.removeAttribute("truncated"),null===(t=this.tooltipElement)||void 0===t||t.remove(),this.tooltipElement=void 0,void this.clearTrigger();if(this.setAttribute("truncated",""),this.noTooltip)return null===(e=this.tooltipElement)||void 0===e||e.remove(),this.tooltipElement=void 0,void this.clearTrigger();this.tooltipElement||(this.tooltipElement=document.createElement("nord-tooltip"),this.tooltipElement.id=this.tooltipId,document.body.appendChild(this.tooltipElement)),this.tooltipElement.setAttribute("position",this.position),this.tooltipElement.setAttribute("delay",String(this.delay)),this.tooltipElement.setAttribute("side-offset",String(this.sideOffset)),this.tooltipElement.setAttribute("align-offset",String(this.alignOffset)),this.tooltipElement.textContent=this.text;const i=this.findTriggerElement();i!==this.currentTrigger&&(this.currentTrigger&&this.removeDescribedById(this.currentTrigger,this.tooltipId),this.currentTrigger=i),this.addDescribedById(i,this.tooltipId)}willUpdate(t){t.has("lineClamp")&&(this.lineClamp>1?(this.setAttribute("line-clamp",String(this.lineClamp)),this.style.setProperty("--_n-truncate-line-clamp",String(this.lineClamp))):(this.removeAttribute("line-clamp"),this.style.removeProperty("--_n-truncate-line-clamp")))}render(){return s`<span ${c(this.spanRef)} class="n-truncate"></span><slot class="n-truncate-source" aria-hidden="true"></slot>`}};h.styles=d,t([o()],h.prototype,"isTruncated",void 0),t([o()],h.prototype,"text",void 0),t([n({reflect:!0})],h.prototype,"position",void 0),t([n({reflect:!0,type:Number})],h.prototype,"delay",void 0),t([n({reflect:!0,type:Number,attribute:"side-offset"})],h.prototype,"sideOffset",void 0),t([n({reflect:!0,type:Number,attribute:"align-offset"})],h.prototype,"alignOffset",void 0),t([n({type:Number,attribute:"line-clamp"})],h.prototype,"lineClamp",void 0),t([n({type:Boolean,reflect:!0,attribute:"no-tooltip"})],h.prototype,"noTooltip",void 0),h=t([l("nord-truncate")],h);var u=h;function m(t){return t.replace(/[\s.,;:!?-]+$/u,"")}export{u as default};
2
2
  //# sourceMappingURL=Truncate.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Truncate.js","sources":["../src/truncate/Truncate.ts"],"sourcesContent":["import type { PropertyValues } from 'lit'\nimport { html, isServer, LitElement } from 'lit'\nimport { customElement, property, state } from 'lit/decorators.js'\nimport { createRef, ref } from 'lit/directives/ref.js'\nimport style from './Truncate.css'\nimport '../tooltip/Tooltip.js'\n\nlet counter = 0\n\nconst ELLIPSIS = '…'\n\n/**\n * Truncate clips text with a single- or multi-line ellipsis and reveals a tooltip with the full text when the content overflows.\n *\n * @status ready\n * @category text\n * @slot - The full text content. Plain text is recommended; rich markup is\n * not supported (only `textContent` is read for truncation).\n */\n@customElement('nord-truncate')\nexport default class Truncate extends LitElement {\n static styles = style\n\n private spanRef = createRef<HTMLSpanElement>()\n private observer?: ResizeObserver\n private contentObserver?: MutationObserver\n private tooltipId = `n-truncate-${++counter}`\n // The tooltip lives in document.body (not in shadow DOM) so its\n // root-level mouseover listener can see hovers on the trigger element,\n // and so aria-describedby can resolve across the same document tree.\n private tooltipElement?: HTMLElement\n // The element that actually receives pointer events (often this host, but\n // when slotted into nord-button — which sets `::slotted(*) { pointer-events:\n // none }` — it resolves to the nord-button itself). aria-describedby is set\n // on this element so the tooltip's `closest()` lookup succeeds.\n private currentTrigger: Element | null = null\n\n @state() private isTruncated = false\n @state() private text = ''\n\n /**\n * Position of the tooltip relative to the truncated text. Mirrors `nord-tooltip`.\n */\n @property({ reflect: true })\n position: 'block-end' | 'block-start' | 'inline-start' | 'inline-end' = 'block-start'\n\n /**\n * Delay in milliseconds before the tooltip opens.\n */\n @property({ reflect: true, type: Number })\n delay = 500\n\n /**\n * Maximum number of lines before truncating. Defaults to `1` (single line).\n * Values `>= 2` allow the text to wrap up to that many lines before the\n * ellipsis kicks in.\n */\n @property({ type: Number, attribute: 'line-clamp' })\n lineClamp = 1\n\n /**\n * When set, the component still truncates the text but does not render\n * a hover tooltip with the full content. The `truncated` attribute is\n * still reflected so consumers can style it.\n */\n @property({ type: Boolean, reflect: true, attribute: 'no-tooltip' })\n noTooltip = false\n\n connectedCallback() {\n super.connectedCallback()\n\n if (isServer)\n return\n\n this.observer = new ResizeObserver(() => {\n // Defer to next frame so the browser has finished the layout pass\n // triggered by the resize before we read geometry.\n requestAnimationFrame(() => this.measure())\n })\n // Catch content changes the ResizeObserver can't see: text-only mutations\n // via reactive bindings (Lit/Vue/React often mutate characterData), or\n // children being replaced. Without this, swapping the label to a\n // longer/shorter string after first render would never re-evaluate\n // truncation.\n this.contentObserver = new MutationObserver(() => {\n this.captureText()\n this.measure()\n })\n this.contentObserver.observe(this, {\n characterData: true,\n childList: true,\n subtree: true,\n })\n this.captureText()\n }\n\n protected firstUpdated() {\n const span = this.spanRef.value\n if (span && this.observer) {\n this.observer.observe(span)\n }\n }\n\n protected updated() {\n this.syncTooltip()\n }\n\n disconnectedCallback() {\n super.disconnectedCallback()\n this.observer?.disconnect()\n this.observer = undefined\n this.contentObserver?.disconnect()\n this.contentObserver = undefined\n this.tooltipElement?.remove()\n this.tooltipElement = undefined\n this.clearTrigger()\n }\n\n private captureText() {\n const next = (this.textContent ?? '').trim()\n if (next !== this.text) {\n this.text = next\n }\n }\n\n /**\n * Measure overflow and, if needed, binary-search the longest prefix of the\n * full text that fits in the available space, then commit `<prefix>…` as\n * the visible text. Same algorithm as Ant Design Pro's `Ellipsis`.\n */\n private measure() {\n const span = this.spanRef.value\n if (!span)\n return\n\n const fullText = this.text\n if (!fullText) {\n span.textContent = ''\n this.isTruncated = false\n return\n }\n\n // Reset to full text and check whether it already fits.\n span.textContent = fullText\n if (this.fits(span)) {\n this.isTruncated = false\n return\n }\n\n // Binary search: largest prefix length such that `prefix + …` fits.\n let lo = 0\n let hi = fullText.length\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2)\n span.textContent = trimEnd(fullText.slice(0, mid)) + ELLIPSIS\n if (this.fits(span)) {\n lo = mid\n }\n else {\n hi = mid - 1\n }\n }\n\n span.textContent = trimEnd(fullText.slice(0, lo)) + ELLIPSIS\n this.isTruncated = true\n }\n\n private fits(span: HTMLElement): boolean {\n if (this.lineClamp > 1) {\n return span.scrollHeight <= span.clientHeight\n }\n return span.scrollWidth <= span.clientWidth\n }\n\n /**\n * Walk up the DOM until we find an ancestor that actually receives pointer\n * events. Needed because `nord-button` (and similar) set\n * `::slotted(*) { pointer-events: none }`, so this host can never see hover.\n * Falls back to this host if no such ancestor is found.\n */\n private findTriggerElement(): Element {\n // pointer-events walk from the host itself so a standalone truncate\n // (default pointer-events: auto) is correctly returned as the trigger.\n // eslint-disable-next-line ts/no-this-alias -- intentional: start the\n let element: Element | null = this\n while (element && element !== document.body && element !== document.documentElement) {\n if (getComputedStyle(element).pointerEvents !== 'none') {\n return element\n }\n element = element.parentElement\n }\n return this\n }\n\n private addDescribedById(element: Element, id: string) {\n const existing = element.getAttribute('aria-describedby')\n const ids = existing ? existing.split(/\\s+/).filter(Boolean) : []\n if (!ids.includes(id)) {\n ids.push(id)\n element.setAttribute('aria-describedby', ids.join(' '))\n }\n }\n\n private removeDescribedById(element: Element, id: string) {\n const existing = element.getAttribute('aria-describedby')\n if (!existing)\n return\n const ids = existing.split(/\\s+/).filter(Boolean).filter(x => x !== id)\n if (ids.length) {\n element.setAttribute('aria-describedby', ids.join(' '))\n }\n else {\n element.removeAttribute('aria-describedby')\n }\n }\n\n private clearTrigger() {\n if (this.currentTrigger) {\n this.removeDescribedById(this.currentTrigger, this.tooltipId)\n this.currentTrigger = null\n }\n }\n\n private syncTooltip() {\n if (!this.isTruncated || !this.text) {\n this.removeAttribute('truncated')\n this.tooltipElement?.remove()\n this.tooltipElement = undefined\n this.clearTrigger()\n return\n }\n\n this.setAttribute('truncated', '')\n\n if (this.noTooltip) {\n this.tooltipElement?.remove()\n this.tooltipElement = undefined\n this.clearTrigger()\n return\n }\n\n if (!this.tooltipElement) {\n this.tooltipElement = document.createElement('nord-tooltip')\n this.tooltipElement.id = this.tooltipId\n document.body.appendChild(this.tooltipElement)\n }\n this.tooltipElement.setAttribute('position', this.position)\n this.tooltipElement.setAttribute('delay', String(this.delay))\n this.tooltipElement.textContent = this.text\n\n const trigger = this.findTriggerElement()\n if (trigger !== this.currentTrigger) {\n if (this.currentTrigger) {\n this.removeDescribedById(this.currentTrigger, this.tooltipId)\n }\n this.currentTrigger = trigger\n }\n this.addDescribedById(trigger, this.tooltipId)\n }\n\n protected willUpdate(changed: PropertyValues) {\n if (changed.has('lineClamp')) {\n if (this.lineClamp > 1) {\n this.setAttribute('line-clamp', String(this.lineClamp))\n this.style.setProperty('--_n-truncate-line-clamp', String(this.lineClamp))\n }\n else {\n this.removeAttribute('line-clamp')\n this.style.removeProperty('--_n-truncate-line-clamp')\n }\n }\n }\n\n render() {\n // The visible truncated text lives in a dedicated shadow-DOM span whose\n // `textContent` is managed imperatively in `measure()` (binary-search\n // updates would otherwise destroy Lit's ChildPart markers). The slot,\n // hidden visually, keeps the full text in light DOM so that assistive\n // tech and copy/paste of the host element still see the complete content.\n return html`\n <span ${ref(this.spanRef)} class=\"n-truncate\"></span>\n <slot class=\"n-truncate-source\" aria-hidden=\"true\"></slot>\n `\n }\n}\n\nfunction trimEnd(input: string): string {\n return input.replace(/[\\s.,;:!?-]+$/u, '')\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'nord-truncate': Truncate\n }\n}\n"],"names":["counter","Truncate","LitElement","constructor","this","spanRef","createRef","tooltipId","currentTrigger","isTruncated","text","position","delay","lineClamp","noTooltip","connectedCallback","super","isServer","observer","ResizeObserver","requestAnimationFrame","measure","contentObserver","MutationObserver","captureText","observe","characterData","childList","subtree","firstUpdated","span","value","updated","syncTooltip","disconnectedCallback","_a","disconnect","undefined","_b","_c","tooltipElement","remove","clearTrigger","next","textContent","trim","fullText","fits","lo","hi","length","mid","Math","ceil","trimEnd","slice","scrollHeight","clientHeight","scrollWidth","clientWidth","findTriggerElement","element","document","body","documentElement","getComputedStyle","pointerEvents","parentElement","addDescribedById","id","existing","getAttribute","ids","split","filter","Boolean","includes","push","setAttribute","join","removeDescribedById","x","removeAttribute","createElement","appendChild","String","trigger","willUpdate","changed","has","style","setProperty","removeProperty","render","html","ref","styles","__decorate","state","prototype","property","reflect","type","Number","attribute","customElement","input","replace"],"mappings":"8wBAOA,IAAIA,EAAU,EAaC,IAAMC,EAAN,cAAuBC,EAAvB,WAAAC,uBAGLC,KAAOC,QAAGC,IAGVF,KAAAG,UAAY,iBAAgBP,EAS5BI,KAAcI,eAAmB,KAExBJ,KAAWK,aAAG,EACdL,KAAIM,KAAG,GAMxBN,KAAQO,SAAgE,cAMxEP,KAAKQ,MAAG,IAQRR,KAASS,UAAG,EAQZT,KAASU,WAAG,CA0Nb,CAxNC,iBAAAC,GACEC,MAAMD,oBAEFE,IAGJb,KAAKc,SAAW,IAAIC,gBAAe,KAGjCC,uBAAsB,IAAMhB,KAAKiB,WAAU,IAO7CjB,KAAKkB,gBAAkB,IAAIC,kBAAiB,KAC1CnB,KAAKoB,cACLpB,KAA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S0B,SAAS,EAAMG,UAAW,gBACpCvG,EAAAkG,UAAA,iBAAA,GA9CElG,EAAQgG,EAAA,CAD5BQ,EAAc,kBACMxG,SAAAA,EA0QrB,SAASqD,EAAQoD,GACf,OAAOA,EAAMC,QAAQ,iBAAkB,GACzC"}
1
+ {"version":3,"file":"Truncate.js","sources":["../src/truncate/Truncate.ts"],"sourcesContent":["import type { PropertyValues } from 'lit'\nimport { html, isServer, LitElement } from 'lit'\nimport { customElement, property, state } from 'lit/decorators.js'\nimport { createRef, ref } from 'lit/directives/ref.js'\nimport style from './Truncate.css'\nimport '../tooltip/Tooltip.js'\n\nlet counter = 0\n\nconst ELLIPSIS = '…'\n\n/**\n * Truncate clips text with a single- or multi-line ellipsis and reveals a tooltip with the full text when the content overflows.\n *\n * @status ready\n * @category text\n * @slot - The full text content. Plain text is recommended; rich markup is\n * not supported (only `textContent` is read for truncation).\n */\n@customElement('nord-truncate')\nexport default class Truncate extends LitElement {\n static styles = style\n\n private spanRef = createRef<HTMLSpanElement>()\n private observer?: ResizeObserver\n private contentObserver?: MutationObserver\n private tooltipId = `n-truncate-${++counter}`\n // The tooltip lives in document.body (not in shadow DOM) so its\n // root-level mouseover listener can see hovers on the trigger element,\n // and so aria-describedby can resolve across the same document tree.\n private tooltipElement?: HTMLElement\n // The element that actually receives pointer events (often this host, but\n // when slotted into nord-button — which sets `::slotted(*) { pointer-events:\n // none }` — it resolves to the nord-button itself). aria-describedby is set\n // on this element so the tooltip's `closest()` lookup succeeds.\n private currentTrigger: Element | null = null\n\n @state() private isTruncated = false\n @state() private text = ''\n\n /**\n * Position of the tooltip relative to the truncated text. Mirrors `nord-tooltip`.\n */\n @property({ reflect: true })\n position: 'block-end' | 'block-start' | 'inline-start' | 'inline-end' = 'block-start'\n\n /**\n * Delay in milliseconds before the tooltip opens.\n */\n @property({ reflect: true, type: Number })\n delay = 500\n\n /**\n * Distance in pixels between the tooltip and the trigger along the main axis.\n * Mirrors `nord-tooltip`'s `side-offset` and is forwarded to the portaled\n * tooltip. Defaults to `8`.\n */\n @property({ reflect: true, type: Number, attribute: 'side-offset' })\n sideOffset = 8\n\n /**\n * Offset in pixels along the tooltip's alignment axis. Mirrors\n * `nord-tooltip`'s `align-offset` and is forwarded to the portaled tooltip.\n * Defaults to `0`.\n */\n @property({ reflect: true, type: Number, attribute: 'align-offset' })\n alignOffset = 0\n\n /**\n * Maximum number of lines before truncating. Defaults to `1` (single line).\n * Values `>= 2` allow the text to wrap up to that many lines before the\n * ellipsis kicks in.\n */\n @property({ type: Number, attribute: 'line-clamp' })\n lineClamp = 1\n\n /**\n * When set, the component still truncates the text but does not render\n * a hover tooltip with the full content. The `truncated` attribute is\n * still reflected so consumers can style it.\n */\n @property({ type: Boolean, reflect: true, attribute: 'no-tooltip' })\n noTooltip = false\n\n connectedCallback() {\n super.connectedCallback()\n\n if (isServer)\n return\n\n this.observer = new ResizeObserver(() => {\n // Defer to next frame so the browser has finished the layout pass\n // triggered by the resize before we read geometry.\n requestAnimationFrame(() => this.measure())\n })\n // Catch content changes the ResizeObserver can't see: text-only mutations\n // via reactive bindings (Lit/Vue/React often mutate characterData), or\n // children being replaced. Without this, swapping the label to a\n // longer/shorter string after first render would never re-evaluate\n // truncation.\n this.contentObserver = new MutationObserver(() => {\n this.captureText()\n this.measure()\n })\n this.contentObserver.observe(this, {\n characterData: true,\n childList: true,\n subtree: true,\n })\n this.captureText()\n }\n\n protected firstUpdated() {\n const span = this.spanRef.value\n if (span && this.observer) {\n this.observer.observe(span)\n }\n }\n\n protected updated() {\n this.syncTooltip()\n }\n\n disconnectedCallback() {\n super.disconnectedCallback()\n this.observer?.disconnect()\n this.observer = undefined\n this.contentObserver?.disconnect()\n this.contentObserver = undefined\n this.tooltipElement?.remove()\n this.tooltipElement = undefined\n this.clearTrigger()\n }\n\n private captureText() {\n const next = (this.textContent ?? '').trim()\n if (next !== this.text) {\n this.text = next\n }\n }\n\n /**\n * Measure overflow and, if needed, binary-search the longest prefix of the\n * full text that fits in the available space, then commit `<prefix>…` as\n * the visible text. Same algorithm as Ant Design Pro's `Ellipsis`.\n */\n private measure() {\n const span = this.spanRef.value\n if (!span)\n return\n\n const fullText = this.text\n if (!fullText) {\n span.textContent = ''\n this.isTruncated = false\n return\n }\n\n // Reset to full text and check whether it already fits.\n span.textContent = fullText\n if (this.fits(span)) {\n this.isTruncated = false\n return\n }\n\n // Binary search: largest prefix length such that `prefix + …` fits.\n let lo = 0\n let hi = fullText.length\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2)\n span.textContent = trimEnd(fullText.slice(0, mid)) + ELLIPSIS\n if (this.fits(span)) {\n lo = mid\n }\n else {\n hi = mid - 1\n }\n }\n\n span.textContent = trimEnd(fullText.slice(0, lo)) + ELLIPSIS\n this.isTruncated = true\n }\n\n private fits(span: HTMLElement): boolean {\n if (this.lineClamp > 1) {\n return span.scrollHeight <= span.clientHeight\n }\n return span.scrollWidth <= span.clientWidth\n }\n\n /**\n * Walk up the DOM until we find an ancestor that actually receives pointer\n * events. Needed because `nord-button` (and similar) set\n * `::slotted(*) { pointer-events: none }`, so this host can never see hover.\n * Falls back to this host if no such ancestor is found.\n */\n private findTriggerElement(): Element {\n // pointer-events walk from the host itself so a standalone truncate\n // (default pointer-events: auto) is correctly returned as the trigger.\n // eslint-disable-next-line ts/no-this-alias -- intentional: start the\n let element: Element | null = this\n while (element && element !== document.body && element !== document.documentElement) {\n if (getComputedStyle(element).pointerEvents !== 'none') {\n return element\n }\n element = element.parentElement\n }\n return this\n }\n\n private addDescribedById(element: Element, id: string) {\n const existing = element.getAttribute('aria-describedby')\n const ids = existing ? existing.split(/\\s+/).filter(Boolean) : []\n if (!ids.includes(id)) {\n ids.push(id)\n element.setAttribute('aria-describedby', ids.join(' '))\n }\n }\n\n private removeDescribedById(element: Element, id: string) {\n const existing = element.getAttribute('aria-describedby')\n if (!existing)\n return\n const ids = existing.split(/\\s+/).filter(Boolean).filter(x => x !== id)\n if (ids.length) {\n element.setAttribute('aria-describedby', ids.join(' '))\n }\n else {\n element.removeAttribute('aria-describedby')\n }\n }\n\n private clearTrigger() {\n if (this.currentTrigger) {\n this.removeDescribedById(this.currentTrigger, this.tooltipId)\n this.currentTrigger = null\n }\n }\n\n private syncTooltip() {\n if (!this.isTruncated || !this.text) {\n this.removeAttribute('truncated')\n this.tooltipElement?.remove()\n this.tooltipElement = undefined\n this.clearTrigger()\n return\n }\n\n this.setAttribute('truncated', '')\n\n if (this.noTooltip) {\n this.tooltipElement?.remove()\n this.tooltipElement = undefined\n this.clearTrigger()\n return\n }\n\n if (!this.tooltipElement) {\n this.tooltipElement = document.createElement('nord-tooltip')\n this.tooltipElement.id = this.tooltipId\n document.body.appendChild(this.tooltipElement)\n }\n this.tooltipElement.setAttribute('position', this.position)\n this.tooltipElement.setAttribute('delay', String(this.delay))\n // The tooltip is portaled to document.body, so forward the offsets onto it\n // directly rather than relying on inheritance from this host.\n this.tooltipElement.setAttribute('side-offset', String(this.sideOffset))\n this.tooltipElement.setAttribute('align-offset', String(this.alignOffset))\n this.tooltipElement.textContent = this.text\n\n const trigger = this.findTriggerElement()\n if (trigger !== this.currentTrigger) {\n if (this.currentTrigger) {\n this.removeDescribedById(this.currentTrigger, this.tooltipId)\n }\n this.currentTrigger = trigger\n }\n this.addDescribedById(trigger, this.tooltipId)\n }\n\n protected willUpdate(changed: PropertyValues) {\n if (changed.has('lineClamp')) {\n if (this.lineClamp > 1) {\n this.setAttribute('line-clamp', String(this.lineClamp))\n this.style.setProperty('--_n-truncate-line-clamp', String(this.lineClamp))\n }\n else {\n this.removeAttribute('line-clamp')\n this.style.removeProperty('--_n-truncate-line-clamp')\n }\n }\n }\n\n render() {\n // The visible truncated text lives in a dedicated shadow-DOM span whose\n // `textContent` is managed imperatively in `measure()` (binary-search\n // updates would otherwise destroy Lit's ChildPart markers). The slot,\n // hidden visually, keeps the full text in light DOM so that assistive\n // tech and copy/paste of the host element still see the complete content.\n return html`\n <span ${ref(this.spanRef)} class=\"n-truncate\"></span>\n <slot class=\"n-truncate-source\" aria-hidden=\"true\"></slot>\n `\n }\n}\n\nfunction trimEnd(input: string): string {\n return input.replace(/[\\s.,;:!?-]+$/u, '')\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'nord-truncate': Truncate\n }\n}\n"],"names":["counter","Truncate","LitElement","constructor","this","spanRef","createRef","tooltipId","currentTrigger","isTruncated","text","position","delay","sideOffset","alignOffset","lineClamp","noTooltip","connectedCallback","super","isServer","observer","ResizeObserver","requestAnimationFrame","measure","contentObserver","MutationObserver","captureText","observe","characterData","childList","subtree","firstUpdated","span","value","updated","syncTooltip","disconnectedCallback","_a","disconnect","undefined","_b","_c","tooltipElement","remove","clearTrigger","next","textContent","trim","fullText","fits","lo","hi","length","mid","Math","ceil","trimEnd","slice","scrollHeight","clientHeight","scrollWidth","clientWidth","findTriggerElement","element","document","body","documentElement","getComputedStyle","pointerEvents","parentElement","addDescribedById","id","existing","getAttribute","ids","split","filter","Boolean","includes","push","setAttribute","join","removeDescribedById","x","removeAttribute","createElement","appendChild","String","trigger","willUpdate","changed","has","style","setProperty","removeProperty","render","html","ref","styles","__decorate","state","prototype","property","reflect","type","Number","attribute","customElement","input","replace"],"mappings":"8wBAOA,IAAIA,EAAU,EAaC,IAAMC,EAAN,cAAuBC,EAAvB,WAAAC,uBAGLC,KAAOC,QAAGC,IAGVF,KAAAG,UAAY,iBAAgBP,EAS5BI,KAAcI,eAAmB,KAExBJ,KAAWK,aAAG,EACdL,KAAIM,KAAG,GAMxBN,KAAQO,SAAgE,cAMxEP,KAAKQ,MAAG,IAQRR,KAAUS,WAAG,EAQbT,KAAWU,YAAG,EAQdV,KAASW,UAAG,EAQZX,KAASY,WAAG,CA8Nb,CA5NC,iBAAAC,GACEC,MAAMD,oBAEFE,IAGJf,KAAKgB,SAAW,IAAIC,gBAAe,KAGjCC,uBAAsB,IAAMlB,KAAKmB,WAAU,IAO7CnB,KAAKoB,gBAAkB,IAAIC,kBAAiB,KAC1CrB,KAAK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