@digdir/designsystemet-web 1.21.1 → 1.23.0

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.
Files changed (37) hide show
  1. package/dist/cjs/_vendors/@oddbird/popover-polyfill/dist/popover-fn.cjs +2 -2
  2. package/dist/cjs/_vendors/@oddbird/popover-polyfill/dist/popover-fn.cjs.map +1 -1
  3. package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -1
  4. package/dist/cjs/field/field.cjs.map +1 -1
  5. package/dist/cjs/index.cjs +1 -1
  6. package/dist/cjs/packages/web/package.cjs +1 -1
  7. package/dist/cjs/pagination/pagination.cjs +1 -1
  8. package/dist/cjs/pagination/pagination.cjs.map +1 -1
  9. package/dist/cjs/popover/popover.cjs +1 -1
  10. package/dist/cjs/popover/popover.cjs.map +1 -1
  11. package/dist/cjs/suggestion/suggestion.cjs +1 -1
  12. package/dist/cjs/suggestion/suggestion.cjs.map +1 -1
  13. package/dist/cjs/toggle-group/toggle-group.cjs.map +1 -1
  14. package/dist/cjs/tooltip/tooltip.cjs +1 -1
  15. package/dist/cjs/tooltip/tooltip.cjs.map +1 -1
  16. package/dist/cjs/utils/utils.cjs +1 -1
  17. package/dist/cjs/utils/utils.cjs.map +1 -1
  18. package/dist/custom-elements.json +8 -8
  19. package/dist/esm/_vendors/@oddbird/popover-polyfill/dist/popover-fn.js +2 -2
  20. package/dist/esm/_vendors/@oddbird/popover-polyfill/dist/popover-fn.js.map +1 -1
  21. package/dist/esm/field/field.js.map +1 -1
  22. package/dist/esm/packages/web/package.js +1 -1
  23. package/dist/esm/pagination/pagination.js +1 -1
  24. package/dist/esm/pagination/pagination.js.map +1 -1
  25. package/dist/esm/popover/popover.js +1 -1
  26. package/dist/esm/popover/popover.js.map +1 -1
  27. package/dist/esm/suggestion/suggestion.js +1 -1
  28. package/dist/esm/suggestion/suggestion.js.map +1 -1
  29. package/dist/esm/toggle-group/toggle-group.js.map +1 -1
  30. package/dist/esm/tooltip/tooltip.js +1 -1
  31. package/dist/esm/tooltip/tooltip.js.map +1 -1
  32. package/dist/esm/utils/utils.js +1 -1
  33. package/dist/esm/utils/utils.js.map +1 -1
  34. package/dist/index.js +62 -38
  35. package/dist/umd/index.js +8 -8
  36. package/dist/umd/index.js.map +1 -1
  37. package/package.json +7 -6
@@ -1 +1 @@
1
- {"version":3,"file":"pagination.js","names":[],"sources":["../../../src/pagination/pagination.ts"],"sourcesContent":["import {\n ARIA_LABEL,\n ARIA_LABELLEDBY,\n attr,\n attrOrCSS,\n customElements,\n DSElement,\n onMutation,\n warn,\n} from '../utils/utils';\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'ds-pagination': DSPaginationElement;\n }\n}\n\nconst ATTR_CURRENT = 'data-current';\nconst ATTR_TOTAL = 'data-total';\nconst ATTR_HREF = 'data-href';\n\n// Expose pagination logic if wanting to do custom rendering (i.e. in React/Vue/etc)\nexport const pagination = ({ current = 1, total = 10, show = 7 }) => ({\n prev: current > 1 ? current - 1 : 0,\n next: current < total ? current + 1 : 0,\n pages: getSteps(current, total, show).map((page, index) => ({\n current: page === current && ('page' as const),\n key: `key-${page}-${index}`,\n page,\n })),\n});\n\nexport class DSPaginationElement extends DSElement {\n _unmutate?: () => void; // Using underscore instead of private fields for backwards compatibility\n _render?: () => void;\n\n static get observedAttributes() {\n return [ARIA_LABEL, ARIA_LABELLEDBY, ATTR_CURRENT, ATTR_TOTAL, ATTR_HREF]; // Using ES2015 syntax for backwards compatibility\n }\n connectedCallback() {\n // Check for required attributes\n const total = attr(this, ATTR_TOTAL);\n const current = attr(this, ATTR_CURRENT);\n if (current && !total) warn(`Missing ${ATTR_TOTAL} attribute on:`, this);\n if (total && !current) warn(`Missing ${ATTR_CURRENT} attribute on:`, this);\n\n const label = attrOrCSS(this, ARIA_LABEL);\n const labelledby = attr(this, ARIA_LABELLEDBY)?.trim();\n if (label || labelledby) attr(this, ARIA_LABEL, labelledby ? null : label);\n else warn(`Missing ${ARIA_LABEL} on:`, this);\n\n attr(this, 'role', 'navigation');\n this._unmutate = onMutation(this, render, {\n childList: true,\n subtree: true,\n });\n }\n attributeChangedCallback() {\n if (this._unmutate) render(this); // Ensure we do not run any renders before connectedCallback\n }\n disconnectedCallback() {\n this._unmutate?.();\n this._unmutate = this._render = undefined;\n }\n}\n\nconst render = (self: DSPaginationElement) => {\n const current = Number(attr(self, ATTR_CURRENT));\n const total = Number(attr(self, ATTR_TOTAL));\n\n // Allowing server side generated pagination, buy only doing client side updates if total/current attributes are provided\n if (current && total) {\n const items = self.querySelectorAll('button,a');\n const show = items.length - 2;\n const href = attr(self, ATTR_HREF);\n const { next, prev, pages } = pagination({ current, total, show });\n items.forEach((item, i) => {\n const page = i ? (items[i + 1] ? pages[i - 1]?.page : next) : prev; // First is prev, last is next\n attr(item, 'aria-current', pages[i - 1]?.current ? 'true' : null);\n attr(item, ARIA_LABEL, `${page ?? 'hidden'}`); // Used for CSS content and to hide if more items than pages, using aria-label to make Axe tests and VoiceOver rotor happy\n attr(item, 'role', page ? null : 'none'); // Prevent validation errors for aria-hidden buttons\n attr(item, 'tabindex', page ? null : '-1');\n if (item instanceof HTMLButtonElement) attr(item, 'value', `${page}`);\n if (href && item instanceof HTMLAnchorElement)\n attr(item, 'href', href.replace('%d', `${page}`));\n });\n }\n};\n\nconst getSteps = (\n now: number,\n max: number,\n show = Number.POSITIVE_INFINITY,\n) => {\n const offset = (show - 1) / 2;\n const start = Math.max(Math.min(now - Math.floor(offset), max - show + 1), 1);\n const end = Math.min(Math.max(now + Math.ceil(offset), show), max);\n const pages = Array.from({ length: end + 1 - start }, (_, i) => i + start);\n\n if (show > 4 && start > 1) pages.splice(0, 2, 1, 0);\n if (show > 3 && end < max) pages.splice(-2, 2, 0, max);\n return pages;\n};\n\ncustomElements.define('ds-pagination', DSPaginationElement);\n"],"mappings":"0JAiBA,MAAM,EAAe,eACf,EAAa,aACb,EAAY,YAGL,GAAc,CAAE,UAAU,EAAG,QAAQ,GAAI,O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,CAAE,UAAS,QAAO,MAAK,CAAC,EACjE,EAAM,SAAS,EAAM,IAAM,CACzB,IAAM,EAAO,EAAK,EAAM,EAAI,GAAK,EAAM,EAAI,EAAE,EAAE,KAAO,EAAQ,EAC9D,EAAK,EAAM,eAAgB,EAAM,EAAI,EAAE,EAAE,QAAU,OAAS,IAAI,EAChE,EAAK,EAAM,EAAY,GAAG,GAAQ,UAAU,EAC5C,EAAK,EAAM,OAAQ,EAAO,KAAO,MAAM,EACvC,EAAK,EAAM,WAAY,EAAO,KAAO,IAAI,EACrC,aAAgB,mBAAmB,EAAK,EAAM,QAAS,GAAG,GAAM,EAChE,GAAQ,aAAgB,mBAC1B,EAAK,EAAM,OAAQ,EAAK,QAAQ,KAAM,GAAG,GAAM,CAAC,CACpD,CAAC,CACH,CACF,EAEM,GACJ,EACA,EACA,EAAO,MACJ,CACH,IAAM,GAAU,EAAO,GAAK,EACtB,EAAQ,KAAK,IAAI,KAAK,IAAI,EAAM,KAAK,MAAM,CAAM,EAAG,EAAM,EAAO,CAAC,EAAG,CAAC,EACtE,EAAM,KAAK,IAAI,KAAK,IAAI,EAAM,KAAK,KAAK,CAAM,EAAG,CAAI,EAAG,CAAG,EAC3D,EAAQ,MAAM,KAAK,CAAE,OAAQ,EAAM,EAAI,CAAM,GAAI,EAAG,IAAM,EAAI,CAAK,EAIzE,OAFI,EAAO,GAAK,EAAQ,GAAG,EAAM,OAAO,EAAG,EAAG,EAAG,CAAC,EAC9C,EAAO,GAAK,EAAM,GAAK,EAAM,OAAO,GAAI,EAAG,EAAG,CAAG,EAC9C,CACT,EAEA,EAAe,OAAO,gBAAiB,CAAmB"}
1
+ {"version":3,"file":"pagination.js","names":[],"sources":["../../../src/pagination/pagination.ts"],"sourcesContent":["import {\n ARIA_LABEL,\n ARIA_LABELLEDBY,\n attr,\n attrOrCSS,\n customElements,\n DSElement,\n onMutation,\n warn,\n} from '../utils/utils';\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'ds-pagination': DSPaginationElement;\n }\n}\n\nconst ATTR_CURRENT = 'data-current';\nconst ATTR_TOTAL = 'data-total';\nconst ATTR_HREF = 'data-href';\n\n// Expose pagination logic if wanting to do custom rendering (i.e. in React/Vue/etc)\nexport const pagination = ({ current = 1, total = 10, show = 7 }) => ({\n prev: current > 1 ? current - 1 : 0,\n next: current < total ? current + 1 : 0,\n pages: getSteps(current, total, show).map((page, index) => ({\n current: page === current && ('page' as const),\n key: `key-${page}-${index}`,\n page,\n })),\n});\n\nexport class DSPaginationElement extends DSElement {\n _unmutate?: () => void; // Using underscore instead of private fields for backwards compatibility\n _render?: () => void;\n\n static get observedAttributes() {\n return [ARIA_LABEL, ARIA_LABELLEDBY, ATTR_CURRENT, ATTR_TOTAL, ATTR_HREF]; // Using ES2015 syntax for backwards compatibility\n }\n connectedCallback() {\n // Check for required attributes\n const total = attr(this, ATTR_TOTAL);\n const current = attr(this, ATTR_CURRENT);\n if (current && !total) warn(`Missing ${ATTR_TOTAL} attribute on:`, this);\n if (total && !current) warn(`Missing ${ATTR_CURRENT} attribute on:`, this);\n\n const label = attrOrCSS(this, ARIA_LABEL);\n const labelledby = attr(this, ARIA_LABELLEDBY)?.trim();\n if (label || labelledby) attr(this, ARIA_LABEL, labelledby ? null : label);\n else warn(`Missing ${ARIA_LABEL} on:`, this);\n\n attr(this, 'role', 'navigation');\n this._unmutate = onMutation(this, render, {\n childList: true,\n subtree: true,\n });\n }\n attributeChangedCallback() {\n if (this._unmutate) render(this); // Ensure we do not run any renders before connectedCallback\n }\n disconnectedCallback() {\n this._unmutate?.();\n this._unmutate = this._render = undefined;\n }\n}\n\nconst isNamedByAriaLabel = (el: Element) =>\n !el.textContent?.trim() && !attr(el, ARIA_LABELLEDBY);\n\nconst render = (self: DSPaginationElement) => {\n const current = Number(attr(self, ATTR_CURRENT));\n const total = Number(attr(self, ATTR_TOTAL));\n\n // Allowing server side generated pagination, buy only doing client side updates if total/current attributes are provided\n if (current && total) {\n const items = self.querySelectorAll('button,a');\n const show = items.length - 2;\n const href = attr(self, ATTR_HREF);\n const { next, prev, pages } = pagination({ current, total, show });\n items.forEach((item, i) => {\n const isStep = i !== 0 && !!items[i + 1]; // First is prev, last is next\n const page = isStep ? pages[i - 1]?.page : i ? next : prev;\n attr(item, 'aria-current', pages[i - 1]?.current ? 'true' : null);\n\n if (isStep) {\n // Also drives CSS content, hides items without a page, and keeps Axe and the VoiceOver rotor happy\n attr(item, ARIA_LABEL, `${page ?? 'hidden'}`);\n } else if (isNamedByAriaLabel(item)) {\n // If prev/next is not named by consumer fallback to CSS-variable in Norwegian\n attr(item, ARIA_LABEL, attrOrCSS(item, ARIA_LABEL));\n }\n\n attr(item, 'role', page ? null : 'none'); // Prevent validation errors for aria-hidden buttons\n attr(item, 'tabindex', page ? null : '-1');\n if (item instanceof HTMLButtonElement) attr(item, 'value', `${page}`);\n if (href && item instanceof HTMLAnchorElement)\n attr(item, 'href', href.replace('%d', `${page}`));\n });\n }\n};\n\nconst getSteps = (\n now: number,\n max: number,\n show = Number.POSITIVE_INFINITY,\n) => {\n const offset = (show - 1) / 2;\n const start = Math.max(Math.min(now - Math.floor(offset), max - show + 1), 1);\n const end = Math.min(Math.max(now + Math.ceil(offset), show), max);\n const pages = Array.from({ length: end + 1 - start }, (_, i) => i + start);\n\n if (show > 4 && start > 1) pages.splice(0, 2, 1, 0);\n if (show > 3 && end < max) pages.splice(-2, 2, 0, max);\n return pages;\n};\n\ncustomElements.define('ds-pagination', DSPaginationElement);\n"],"mappings":"0JAiBA,MAAM,EAAe,eACf,EAAa,aACb,EAAY,YAGL,GAAc,CAAE,UAAU,EAAG,QAAQ,GAAI,OAAO,MAAS,CACpE,KAAM,EAAU,EAAI,EAAU,EAAI,EAClC,KAAM,EAAU,EAAQ,EAAU,EAAI,EACtC,MAAO,EAAS,EAAS,EAAO,CAAI,CAAC,CAAC,KAAK,EAAM,KAAW,CAC1D,QAAS,IAAS,GAAY,OAC9B,IAAK,OAAO,EAAK,GAAG,IACpB,M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AM,EAAI,EAAE,EAAE,KAAO,EAAI,EAAO,EACtD,EAAK,EAAM,eAAgB,EAAM,EAAI,EAAE,EAAE,QAAU,OAAS,IAAI,EAE5D,EAEF,EAAK,EAAM,EAAY,GAAG,GAAQ,UAAU,EACnC,EAAmB,CAAI,GAEhC,EAAK,EAAM,EAAY,EAAU,EAAM,CAAU,CAAC,EAGpD,EAAK,EAAM,OAAQ,EAAO,KAAO,MAAM,EACvC,EAAK,EAAM,WAAY,EAAO,KAAO,IAAI,EACrC,aAAgB,mBAAmB,EAAK,EAAM,QAAS,GAAG,GAAM,EAChE,GAAQ,aAAgB,mBAC1B,EAAK,EAAM,OAAQ,EAAK,QAAQ,KAAM,GAAG,GAAM,CAAC,CACpD,CAAC,CACH,CACF,EAEM,GACJ,EACA,EACA,EAAO,MACJ,CACH,IAAM,GAAU,EAAO,GAAK,EACtB,EAAQ,KAAK,IAAI,KAAK,IAAI,EAAM,KAAK,MAAM,CAAM,EAAG,EAAM,EAAO,CAAC,EAAG,CAAC,EACtE,EAAM,KAAK,IAAI,KAAK,IAAI,EAAM,KAAK,KAAK,CAAM,EAAG,CAAI,EAAG,CAAG,EAC3D,EAAQ,MAAM,KAAK,CAAE,OAAQ,EAAM,EAAI,CAAM,GAAI,EAAG,IAAM,EAAI,CAAK,EAIzE,OAFI,EAAO,GAAK,EAAQ,GAAG,EAAM,OAAO,EAAG,EAAG,EAAG,CAAC,EAC9C,EAAO,GAAK,EAAM,GAAK,EAAM,OAAO,GAAI,EAAG,EAAG,CAAG,EAC9C,CACT,EAEA,EAAe,OAAO,gBAAiB,CAAmB"}
@@ -1,2 +1,2 @@
1
- import{QUICK_EVENT as e,attr as t,getCSSProp as n,getComposedTarget as r,getRoot as i,isBrowser as a,on as o,onHotReload as s}from"../utils/utils.js";import{apply as c,isPolyfilled as l,isSupported as u}from"../_vendors/@oddbird/popover-polyfill/dist/popover-fn.js";import{autoUpdate as d,computePosition as f,flip as p,limitShift as m,offset as h,shift as g,size as _}from"@floating-ui/dom";a()&&!u()&&!l()&&c({layerName:`ds.base`});const v=new Map,y=`data-placement`,b=`data-autoplacement`,x=new Map,S=e=>C(r(e),e.newState,e.oldState,e.source||e.detail);function C(e,r,a,o){let s=e instanceof HTMLElement&&t(e,`popover`)!==null&&n(e,`--_ds-floating`),c=x.get(e);if(r===`open`&&c&&c.source===o||(c?.cleanup(),r===`closed`||!s))return;if(!o){let t=e.id&&`[popovertarget="${e.id}"],[commandfor="${e.id}"]`;o=t&&i(e).querySelector(t)||void 0}if(!o||o===e||a&&a===r)return;e.style.scrollMarginBottom=`var(--_ds-floating-arrow-size)`;let l=n(e,`--_ds-floating-overscroll`),u=t(e,y)||t(o,y)||s,v=t(e,b)||t(o,b),S=parseFloat(n(e,`scroll-margin-bottom`))||0,C=u.match(/left|right/gi)?`Height`:`Width`,w=o[`offset${C}`]/2+S;if(u===`none`)return;let T=!1,E={strategy:`absolute`,placement:u,middleware:[h(S),g({padding:10,limiter:m({offset:{mainAxis:w}})}),D(),...v===`false`?[]:[p({padding:10,crossAxis:!1})],...l?[_({apply({availableHeight:t}){if(T)return;T=!0;let n=`${o.offsetWidth}px`,r=`${Math.max(50,t-20)}px`;requestAnimationFrame(()=>{l===`fit`&&e.style.width!==n&&(e.style.width=n),e.style.maxHeight!==r&&(e.style.maxHeight=r)})}})]:[]]},O=d(o,e,async()=>{if(!o?.isConnected)return x.get(e)?.cleanup();let{x:t,y:n}=await f(o,e,E);e.style.translate=`${t}px ${n}px`});x.set(e,{source:o,cleanup:()=>x.delete(e)&&O()})}let w;const T=e=>{if(e.type===`pointerdown`&&(w=!1),e.type===`scroll`&&w===!1&&(w=!0),e.type===`pointerup`&&w)for(let[e]of x)e.showPopover()},E=t=>{for(let[e,t]of v)!e.host?.isConnected&&v.delete(e)&&t();let n=i(r(t));n instanceof ShadowRoot&&!v.has(n)&&v.set(n,o(n,`toggle`,S,e))};s(`popover`,()=>{let t=Object.getOwnPropertyDescriptors(HTMLElement.prototype),n=HTMLElement.prototype.togglePopover,r=HTMLElement.prototype.showPopover,i=HTMLElement.prototype.hidePopover;return Object.defineProperties(HTMLElement.prototype,{togglePopover:{...t.togglePopover,value(e){let t=this.matches(`:popover-open`),r=typeof e==`boolean`,i=t?`open`:`closed`,a=(r?e:e?.force??!t)?`open`:`closed`,o=r?void 0:e?.source,s=n?.call(this,e);return C(this,a,i,o),s}},showPopover:{...t.showPopover,value(e){let t=this.matches(`:popover-open`)?`open`:`closed`,n=r?.call(this,e);return C(this,`open`,t,e?.source),n}},hidePopover:{...t.hidePopover,value(){let e=this.matches(`:popover-open`)?`open`:`closed`,t=i?.call(this);return C(this,`closed`,e),t}}}),[o(document,`click`,E,e),o(document,`pointerdown pointerup scroll`,T,e),o(document,`toggle ds-toggle-source`,S,e),()=>{Object.defineProperties(HTMLElement.prototype,{togglePopover:{...t.togglePopover,value:n},showPopover:{...t.showPopover,value:r},hidePopover:{...t.hidePopover,value:i}});for(let[,e]of v)e();v.clear()}]});const D=()=>({name:`arrowPseudo`,fn(e){let n=e.elements.floating,r=e.rects.reference,i=`${Math.round(r.width/2+r.x-e.x)}px`,a=`${Math.round(r.height/2+r.y-e.y)}px`;return n.style.setProperty(`--_ds-floating-arrow-x`,i),n.style.setProperty(`--_ds-floating-arrow-y`,a),t(n,`data-floating`,e.placement),e}});
1
+ import{QUICK_EVENT as e,attr as t,getCSSProp as n,getComposedTarget as r,getRoot as i,isBrowser as a,on as o,onHotReload as s}from"../utils/utils.js";import{apply as c,isPolyfilled as l,isSupported as u}from"../_vendors/@oddbird/popover-polyfill/dist/popover-fn.js";import{autoUpdate as d,computePosition as f,flip as p,limitShift as m,offset as h,shift as g,size as _}from"@floating-ui/dom";a()&&!u()&&!l()&&c({layerName:`ds.base`});const v=new Map,y=`data-placement`,b=`data-autoplacement`,x=new Map,S=e=>C(r(e),e.newState,e.oldState,e.source||e.detail);function C(e,r,a,o){let s=e instanceof HTMLElement&&t(e,`popover`)!==null,c=x.get(e);if(r===`open`&&c&&c.source===o||(c?.cleanup(),r===`closed`||!s))return;if(!o){let t=e.id&&`[popovertarget="${e.id}"],[commandfor="${e.id}"]`;o=t&&i(e).querySelector(t)||void 0}if(!o||o===e||a&&a===r)return;let l=n(e,`--_ds-floating`),u=t(e,y)??t(o,y);if(u===null&&!l)return;e.style.scrollMarginBottom=`var(--_ds-floating-arrow-size)`;let v=u||l||`top`,S=n(e,`--_ds-floating-overscroll`),C=t(e,b)||t(o,b),w=parseFloat(n(e,`scroll-margin-bottom`))||0,T=v.match(/left|right/gi)?`Height`:`Width`,E=o[`offset${T}`]/2+w;if(v===`none`)return;let O=!1,k={strategy:`absolute`,placement:v,middleware:[h(w),g({padding:10,limiter:m({offset:{mainAxis:E}})}),D(),...C===`false`?[]:[p({padding:10,crossAxis:!1})],...S?[_({apply({availableHeight:t}){if(O)return;O=!0;let n=`${Math.max(50,t-20)}px`;requestAnimationFrame(()=>{e.style.maxHeight!==n&&(e.style.maxHeight=n)})}})]:[]]},A=d(o,e,async()=>{if(!o?.isConnected)return x.get(e)?.cleanup();if(S===`fit`){let t=`${o.offsetWidth}px`;e.style.width!==t&&(e.style.width=t)}let{x:t,y:n}=await f(o,e,k);e.style.translate=`${t}px ${n}px`});x.set(e,{source:o,cleanup:()=>x.delete(e)&&A()})}let w;const T=e=>{if(e.type===`pointerdown`&&(w=!1),e.type===`scroll`&&w===!1&&(w=!0),e.type===`pointerup`&&w)for(let[e]of x)e.showPopover()},E=t=>{for(let[e,t]of v)!e.host?.isConnected&&v.delete(e)&&t();let n=i(r(t));n instanceof ShadowRoot&&!v.has(n)&&v.set(n,o(n,`toggle`,S,e))};s(`popover`,()=>{let t=Object.getOwnPropertyDescriptors(HTMLElement.prototype),n=HTMLElement.prototype.togglePopover,r=HTMLElement.prototype.showPopover,i=HTMLElement.prototype.hidePopover;return Object.defineProperties(HTMLElement.prototype,{togglePopover:{...t.togglePopover,value(e){let t=this.matches(`:popover-open`),r=typeof e==`boolean`,i=t?`open`:`closed`,a=(r?e:e?.force??!t)?`open`:`closed`,o=r?void 0:e?.source,s=n?.call(this,e);return C(this,a,i,o),s}},showPopover:{...t.showPopover,value(e){let t=this.matches(`:popover-open`)?`open`:`closed`,n=r?.call(this,e);return C(this,`open`,t,e?.source),n}},hidePopover:{...t.hidePopover,value(){let e=this.matches(`:popover-open`)?`open`:`closed`,t=i?.call(this);return C(this,`closed`,e),t}}}),[o(document,`click`,E,e),o(document,`pointerdown pointerup scroll`,T,e),o(document,`toggle ds-toggle-source`,S,e),()=>{Object.defineProperties(HTMLElement.prototype,{togglePopover:{...t.togglePopover,value:n},showPopover:{...t.showPopover,value:r},hidePopover:{...t.hidePopover,value:i}});for(let[,e]of v)e();v.clear()}]});const D=()=>({name:`arrowPseudo`,fn(e){let n=e.elements.floating,r=e.rects.reference,i=`${Math.round(r.width/2+r.x-e.x)}px`,a=`${Math.round(r.height/2+r.y-e.y)}px`;return n.style.setProperty(`--_ds-floating-arrow-x`,i),n.style.setProperty(`--_ds-floating-arrow-y`,a),t(n,`data-floating`,e.placement),e}});
2
2
  //# sourceMappingURL=popover.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"popover.js","names":[],"sources":["../../../src/popover/popover.ts"],"sourcesContent":["import type { ComputePositionConfig, MiddlewareState } from '@floating-ui/dom';\nimport {\n autoUpdate,\n computePosition,\n flip,\n limitShift,\n offset,\n shift,\n size,\n} from '@floating-ui/dom';\nimport {\n isPolyfilled,\n isSupported,\n apply as polyfillPopover,\n} from '@oddbird/popover-polyfill/fn';\nimport {\n attr,\n getComposedTarget,\n getCSSProp,\n getRoot,\n isBrowser,\n on,\n onHotReload,\n QUICK_EVENT,\n} from '../utils/utils';\n\nif (isBrowser() && !isSupported() && !isPolyfilled()) {\n polyfillPopover({ layerName: 'ds.base' }); // Load popover polyfill in the ds.base CSS layer to keep cascade order consistent with Designsystemet layers.\n}\n\n// NOTE:\n// The native popover event \"toggle\" is not composed, meaning it does not bubble out of shadow DOM.\n// This means that if a popover is inside a shadow root, the toggle event will not be visible outside of that shadow root.\n// To handle this, we monkey-patch the showPopover and hidePopover methods to manually trigger the toggle-function.\n// We also bind toggle events to shadow roots found during click events, so that we can listen for toggle events on shadow roots as well.\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n 'ds-toggle-source': CustomEvent<Element>;\n }\n}\n\nconst ROOTS = new Map<ShadowRoot, () => void>();\nconst ATTR_PLACE = 'data-placement';\nconst ATTR_AUTO = 'data-autoplacement';\nconst POPOVERS = new Map<\n HTMLElement,\n { source: Element; cleanup: () => void }\n>();\n\n// Sometimes use \"ds-toggle\" event while waiting for better support of\n// event.source (https://developer.mozilla.org/en-US/docs/Web/API/ToggleEvent/source)\n\nconst handleToggle = (\n e: Event &\n Partial<ToggleEvent> & { detail?: HTMLElement; source?: HTMLElement },\n) => toggle(getComposedTarget(e), e.newState, e.oldState, e.source || e.detail);\n\nfunction toggle(\n el: Element | null,\n newState?: string,\n oldState?: string,\n source?: HTMLElement,\n) {\n const isPopover = el instanceof HTMLElement && attr(el, 'popover') !== null;\n const float = isPopover && getCSSProp(el, '--_ds-floating');\n const prev = POPOVERS.get(el as HTMLElement);\n\n if (newState === 'open' && prev && prev.source === source) return; // Prevent double binding\n prev?.cleanup(); // Cleanup if previously bound popover exists to avoid multiple autoUpdate memory leaks\n if (newState === 'closed' || !float) return;\n if (!source) {\n const css = el.id && `[popovertarget=\"${el.id}\"],[commandfor=\"${el.id}\"]`;\n source = (css && getRoot(el).querySelector<HTMLElement>(css)) || undefined; // Polyfill ToggleEvent .source for older browsers\n }\n if (!source || source === el || (oldState && oldState === newState)) return; // No need to update\n\n // Use scroll-margin-bottom to measure computed arrow-size property as this does\n // not affect layout or position, makes the browser calculate the pixel value instead\n // of returning the calc() (as it would if reading the --_ds-floating-arrow-size directly)\n // and makes it possible to read the value even if ::before is not used to draw the arrow.\n el.style.scrollMarginBottom = `var(--_ds-floating-arrow-size)`;\n\n const padding = 10;\n const overscroll = getCSSProp(el, '--_ds-floating-overscroll');\n const placement = attr(el, ATTR_PLACE) || attr(source, ATTR_PLACE) || float;\n const auto = attr(el, ATTR_AUTO) || attr(source, ATTR_AUTO);\n const arrowSize = parseFloat(getCSSProp(el, 'scroll-margin-bottom')) || 0;\n const shiftProp = placement.match(/left|right/gi) ? 'Height' : 'Width';\n const shiftLimit = source[`offset${shiftProp}`] / 2 + arrowSize;\n\n if (placement === 'none') return; // No need to position\n\n let sized = false; // Only size once per open, so scrolling does not resize the popover\n const options = {\n strategy: 'absolute',\n placement,\n middleware: [\n offset(arrowSize),\n shift({\n padding,\n limiter: limitShift({ offset: { mainAxis: shiftLimit } }), // Prevent from shifing away from source\n }),\n arrowPseudo(),\n ...(auto !== 'false' ? [flip({ padding, crossAxis: false })] : []),\n ...(overscroll\n ? [\n size({\n apply({ availableHeight }) {\n if (sized) return;\n sized = true;\n const width = `${source.offsetWidth}px`; // Use offsetWidth to include padding, matching the width of the source element\n const maxHeight = `${Math.max(50, availableHeight - padding * 2)}px`;\n\n requestAnimationFrame(() => {\n // Avoid changing an observed element during ResizeObserver delivery.\n if (overscroll === 'fit' && el.style.width !== width)\n el.style.width = width;\n if (el.style.maxHeight !== maxHeight)\n el.style.maxHeight = maxHeight;\n });\n },\n }),\n ]\n : []),\n ],\n } as ComputePositionConfig;\n const unfloat = autoUpdate(source, el, async () => {\n if (!source?.isConnected) return POPOVERS.get(el)?.cleanup(); // Cleanup if source element is removed\n const { x, y } = await computePosition(source, el, options);\n el.style.translate = `${x}px ${y}px`;\n });\n POPOVERS.set(el, {\n source,\n cleanup: () => POPOVERS.delete(el) && unfloat(),\n });\n}\n\n// Prevent closing when pointer interacts with scrollbar\nlet IS_SCROLL: boolean | undefined;\nconst handleScrollbar = (e: Event) => {\n if (e.type === 'pointerdown') {\n IS_SCROLL = false;\n }\n if (e.type === 'scroll' && IS_SCROLL === false) IS_SCROLL = true;\n if (e.type === 'pointerup' && IS_SCROLL)\n for (const [popover] of POPOVERS) popover.showPopover(); // Immediately show again to prevent flicker\n};\n\n// And add listeners for toggle event on shadowRoots as \"toggle\" is not a composed event\nconst handleClick = (e: Event) => {\n for (const [root, off] of ROOTS)\n if (!root.host?.isConnected && ROOTS.delete(root)) off(); // Prune roots whose host is no longer connected (e.g. removed custom elements) to avoid unbounded growth\n\n const root = getRoot(getComposedTarget(e));\n if (root instanceof ShadowRoot && !ROOTS.has(root))\n ROOTS.set(root, on(root, 'toggle', handleToggle, QUICK_EVENT));\n};\n\nonHotReload('popover', () => {\n const descriptors = Object.getOwnPropertyDescriptors(HTMLElement.prototype);\n const togglePopover = HTMLElement.prototype.togglePopover;\n const showPopover = HTMLElement.prototype.showPopover;\n const hidePopover = HTMLElement.prototype.hidePopover;\n\n // Since toggle event is not composed, we need to trigger it when programatically called inside shadow DOM\n Object.defineProperties(HTMLElement.prototype, {\n togglePopover: {\n ...descriptors.togglePopover,\n value(opt: TogglePopoverOptions) {\n const isOpen = this.matches(':popover-open');\n const isBool = typeof opt === 'boolean';\n const prev = isOpen ? 'open' : 'closed';\n const next = (isBool ? opt : (opt?.force ?? !isOpen))\n ? 'open'\n : 'closed';\n const source = isBool ? undefined : opt?.source;\n const result = togglePopover?.call(this, opt as TogglePopoverOptions);\n toggle(this, next, prev, source);\n return result;\n },\n },\n showPopover: {\n ...descriptors.showPopover,\n value(opt: ShowPopoverOptions) {\n const prev = this.matches(':popover-open') ? 'open' : 'closed';\n const result = showPopover?.call(this, opt);\n toggle(this, 'open', prev, opt?.source);\n return result;\n },\n },\n hidePopover: {\n ...descriptors.hidePopover,\n value() {\n const prev = this.matches(':popover-open') ? 'open' : 'closed';\n const result = hidePopover?.call(this);\n toggle(this, 'closed', prev);\n return result;\n },\n },\n });\n\n return [\n on(document, 'click', handleClick, QUICK_EVENT),\n on(document, 'pointerdown pointerup scroll', handleScrollbar, QUICK_EVENT),\n on(document, 'toggle ds-toggle-source', handleToggle, QUICK_EVENT), // Use capture since the toggle event does not bubble\n () => {\n // Restore original methods on hot reload\n Object.defineProperties(HTMLElement.prototype, {\n togglePopover: { ...descriptors.togglePopover, value: togglePopover },\n showPopover: { ...descriptors.showPopover, value: showPopover },\n hidePopover: { ...descriptors.hidePopover, value: hidePopover },\n });\n for (const [, off] of ROOTS) off(); // Cleanup listeners on ShadowRoots on hot reload\n ROOTS.clear();\n },\n ];\n});\n\nconst arrowPseudo = () => ({\n name: 'arrowPseudo',\n fn(data: MiddlewareState) {\n const target = data.elements.floating;\n const source = data.rects.reference;\n const x = `${Math.round(source.width / 2 + source.x - data.x)}px`;\n const y = `${Math.round(source.height / 2 + source.y - data.y)}px`;\n\n target.style.setProperty('--_ds-floating-arrow-x', x);\n target.style.setProperty('--_ds-floating-arrow-y', y);\n attr(target, 'data-floating', data.placement);\n return data;\n },\n});\n"],"mappings":"wYA0BI,EAAU,GAAK,CAAC,EAAY,GAAK,CAAC,EAAa,GACjD,EAAgB,CAAE,UAAW,SAAU,CAAC,EAe1C,MAAM,EAAQ,IAAI,IACZ,EAAa,iBACb,EAAY,qBACZ,EAAW,IAAI,IAQf,EACJ,GAEG,EAAO,EAAkB,CAAC,EAAG,EAAE,SAAU,EAAE,SAAU,EAAE,QAAU,EAAE,MAAM,EAE9E,SAAS,EACP,EACA,EACA,EACA,EACA,CAEA,IAAM,EADY,aAAc,aAAe,EAAK,EAAI,SAAS,IAAM,MAC5C,EAAW,EAAI,gBAAgB,EACpD,EAAO,EAAS,IAAI,CAAiB,EAI3C,GAFI,IAAa,QAAU,GAAQ,EAAK,SAAW,IACnD,GAAM,QAAQ,EACV,IAAa,UAAY,CAAC,GAAO,OACrC,GAAI,CAAC,EAAQ,CACX,IAAM,EAAM,EAAG,IAAM,mBAAmB,EAAG,GAAG,kBAAkB,EAAG,GAAG,IACtE,EAAU,GAAO,EAAQ,CAAE,CAAC,CAAC,cAA2B,CAAG,GAAM,IAAA,EACnE,CACA,GAAI,CAAC,GAAU,IAAW,GAAO,GAAY,IAAa,EAAW,OAMrE,EAAG,MAAM,mBAAqB,iCAE9B,IACM,EAAa,EAAW,EAA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AAe,EAAI,OAAS,SAChD,EAAS,GAAa,KAAK,IAAI,EAErC,OADA,EAAO,KAAM,SAAU,CAAI,EACpB,CACT,CACF,CACF,CAAC,EAEM,CACL,EAAG,SAAU,QAAS,EAAa,CAAW,EAC9C,EAAG,SAAU,+BAAgC,EAAiB,CAAW,EACzE,EAAG,SAAU,0BAA2B,EAAc,CAAW,MAC3D,CAEJ,OAAO,iBAAiB,YAAY,UAAW,CAC7C,cAAe,CAAE,GAAG,EAAY,cAAe,MAAO,CAAc,EACpE,YAAa,CAAE,GAAG,EAAY,YAAa,MAAO,CAAY,EAC9D,YAAa,CAAE,GAAG,EAAY,YAAa,MAAO,CAAY,CAChE,CAAC,EACD,IAAK,GAAM,EAAG,KAAQ,EAAO,EAAI,EACjC,EAAM,MAAM,CACd,CACF,CACF,CAAC,EAED,MAAM,OAAqB,CACzB,KAAM,cACN,GAAG,EAAuB,CACxB,IAAM,EAAS,EAAK,SAAS,SACvB,EAAS,EAAK,MAAM,UACpB,EAAI,GAAG,KAAK,MAAM,EAAO,MAAQ,EAAI,EAAO,EAAI,EAAK,CAAC,EAAE,IACxD,EAAI,GAAG,KAAK,MAAM,EAAO,OAAS,EAAI,EAAO,EAAI,EAAK,CAAC,EAAE,IAK/D,OAHA,EAAO,MAAM,YAAY,yBAA0B,CAAC,EACpD,EAAO,MAAM,YAAY,yBAA0B,CAAC,EACpD,EAAK,EAAQ,gBAAiB,EAAK,SAAS,EACrC,CACT,CACF"}
1
+ {"version":3,"file":"popover.js","names":[],"sources":["../../../src/popover/popover.ts"],"sourcesContent":["import type { ComputePositionConfig, MiddlewareState } from '@floating-ui/dom';\nimport {\n autoUpdate,\n computePosition,\n flip,\n limitShift,\n offset,\n shift,\n size,\n} from '@floating-ui/dom';\nimport {\n isPolyfilled,\n isSupported,\n apply as polyfillPopover,\n} from '@oddbird/popover-polyfill/fn';\nimport {\n attr,\n getComposedTarget,\n getCSSProp,\n getRoot,\n isBrowser,\n on,\n onHotReload,\n QUICK_EVENT,\n} from '../utils/utils';\n\nif (isBrowser() && !isSupported() && !isPolyfilled()) {\n polyfillPopover({ layerName: 'ds.base' }); // Load popover polyfill in the ds.base CSS layer to keep cascade order consistent with Designsystemet layers.\n}\n\n// NOTE:\n// The native popover event \"toggle\" is not composed, meaning it does not bubble out of shadow DOM.\n// This means that if a popover is inside a shadow root, the toggle event will not be visible outside of that shadow root.\n// To handle this, we monkey-patch the showPopover and hidePopover methods to manually trigger the toggle-function.\n// We also bind toggle events to shadow roots found during click events, so that we can listen for toggle events on shadow roots as well.\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n 'ds-toggle-source': CustomEvent<Element>;\n }\n}\n\nconst ROOTS = new Map<ShadowRoot, () => void>();\nconst ATTR_PLACE = 'data-placement';\nconst ATTR_AUTO = 'data-autoplacement';\nconst POPOVERS = new Map<\n HTMLElement,\n { source: Element; cleanup: () => void }\n>();\n\n// Sometimes use \"ds-toggle\" event while waiting for better support of\n// event.source (https://developer.mozilla.org/en-US/docs/Web/API/ToggleEvent/source)\n\nconst handleToggle = (\n e: Event &\n Partial<ToggleEvent> & { detail?: HTMLElement; source?: HTMLElement },\n) => toggle(getComposedTarget(e), e.newState, e.oldState, e.source || e.detail);\n\nfunction toggle(\n el: Element | null,\n newState?: string,\n oldState?: string,\n source?: HTMLElement,\n) {\n const isPopover = el instanceof HTMLElement && attr(el, 'popover') !== null;\n const prev = POPOVERS.get(el as HTMLElement);\n\n if (newState === 'open' && prev && prev.source === source) return; // Prevent double binding\n prev?.cleanup(); // Cleanup if previously bound popover exists to avoid multiple autoUpdate memory leaks\n if (newState === 'closed' || !isPopover) return;\n if (!source) {\n const css = el.id && `[popovertarget=\"${el.id}\"],[commandfor=\"${el.id}\"]`;\n source = (css && getRoot(el).querySelector<HTMLElement>(css)) || undefined; // Polyfill ToggleEvent .source for older browsers\n }\n if (!source || source === el || (oldState && oldState === newState)) return; // No need to update\n const dsFloating = getCSSProp(el, '--_ds-floating');\n const attrPlacement = attr(el, ATTR_PLACE) ?? attr(source, ATTR_PLACE);\n\n if (attrPlacement === null && !dsFloating) return; // Only take control if --_ds-floating or data-placement attributes is set\n\n // Use scroll-margin-bottom to measure computed arrow-size property as this does\n // not affect layout or position, makes the browser calculate the pixel value instead\n // of returning the calc() (as it would if reading the --_ds-floating-arrow-size directly)\n // and makes it possible to read the value even if ::before is not used to draw the arrow.\n el.style.scrollMarginBottom = `var(--_ds-floating-arrow-size)`;\n\n const padding = 10;\n const placement = attrPlacement || dsFloating || 'top';\n const overscroll = getCSSProp(el, '--_ds-floating-overscroll');\n const auto = attr(el, ATTR_AUTO) || attr(source, ATTR_AUTO);\n const arrowSize = parseFloat(getCSSProp(el, 'scroll-margin-bottom')) || 0;\n const shiftProp = placement.match(/left|right/gi) ? 'Height' : 'Width';\n const shiftLimit = source[`offset${shiftProp}`] / 2 + arrowSize;\n\n if (placement === 'none') return; // No need to position\n\n let sized = false; // Only set maxHeight once per open, so scrolling does not resize the popover\n const options = {\n strategy: 'absolute',\n placement,\n middleware: [\n offset(arrowSize),\n shift({\n padding,\n limiter: limitShift({ offset: { mainAxis: shiftLimit } }), // Prevent from shifing away from source\n }),\n arrowPseudo(),\n ...(auto !== 'false' ? [flip({ padding, crossAxis: false })] : []),\n ...(overscroll\n ? [\n size({\n apply({ availableHeight }) {\n if (sized) return;\n sized = true;\n const maxHeight = `${Math.max(50, availableHeight - padding * 2)}px`;\n\n requestAnimationFrame(() => {\n // Avoid changing an observed element during ResizeObserver delivery.\n if (el.style.maxHeight !== maxHeight)\n el.style.maxHeight = maxHeight;\n });\n },\n }),\n ]\n : []),\n ],\n } as ComputePositionConfig;\n const unfloat = autoUpdate(source, el, async () => {\n if (!source?.isConnected) return POPOVERS.get(el)?.cleanup(); // Cleanup if source element is removed\n // Match the width before measuring, so the position is computed from the\n // final size and el.style.translate reveals an already correctly sized\n // popover. Unlike maxHeight this does not depend on the available space,\n // so it is safe to keep in sync on every update rather than sizing once.\n if (overscroll === 'fit') {\n const width = `${source.offsetWidth}px`; // Use offsetWidth to include padding, matching the width of the source element\n if (el.style.width !== width) el.style.width = width;\n }\n const { x, y } = await computePosition(source, el, options);\n el.style.translate = `${x}px ${y}px`;\n });\n POPOVERS.set(el, {\n source,\n cleanup: () => POPOVERS.delete(el) && unfloat(),\n });\n}\n\n// Prevent closing when pointer interacts with scrollbar\nlet IS_SCROLL: boolean | undefined;\nconst handleScrollbar = (e: Event) => {\n if (e.type === 'pointerdown') {\n IS_SCROLL = false;\n }\n if (e.type === 'scroll' && IS_SCROLL === false) IS_SCROLL = true;\n if (e.type === 'pointerup' && IS_SCROLL)\n for (const [popover] of POPOVERS) popover.showPopover(); // Immediately show again to prevent flicker\n};\n\n// And add listeners for toggle event on shadowRoots as \"toggle\" is not a composed event\nconst handleClick = (e: Event) => {\n for (const [root, off] of ROOTS)\n if (!root.host?.isConnected && ROOTS.delete(root)) off(); // Prune roots whose host is no longer connected (e.g. removed custom elements) to avoid unbounded growth\n\n const root = getRoot(getComposedTarget(e));\n if (root instanceof ShadowRoot && !ROOTS.has(root))\n ROOTS.set(root, on(root, 'toggle', handleToggle, QUICK_EVENT));\n};\n\nonHotReload('popover', () => {\n const descriptors = Object.getOwnPropertyDescriptors(HTMLElement.prototype);\n const togglePopover = HTMLElement.prototype.togglePopover;\n const showPopover = HTMLElement.prototype.showPopover;\n const hidePopover = HTMLElement.prototype.hidePopover;\n\n // Since toggle event is not composed, we need to trigger it when programatically called inside shadow DOM\n Object.defineProperties(HTMLElement.prototype, {\n togglePopover: {\n ...descriptors.togglePopover,\n value(opt: TogglePopoverOptions) {\n const isOpen = this.matches(':popover-open');\n const isBool = typeof opt === 'boolean';\n const prev = isOpen ? 'open' : 'closed';\n const next = (isBool ? opt : (opt?.force ?? !isOpen))\n ? 'open'\n : 'closed';\n const source = isBool ? undefined : opt?.source;\n const result = togglePopover?.call(this, opt as TogglePopoverOptions);\n toggle(this, next, prev, source);\n return result;\n },\n },\n showPopover: {\n ...descriptors.showPopover,\n value(opt: ShowPopoverOptions) {\n const prev = this.matches(':popover-open') ? 'open' : 'closed';\n const result = showPopover?.call(this, opt);\n toggle(this, 'open', prev, opt?.source);\n return result;\n },\n },\n hidePopover: {\n ...descriptors.hidePopover,\n value() {\n const prev = this.matches(':popover-open') ? 'open' : 'closed';\n const result = hidePopover?.call(this);\n toggle(this, 'closed', prev);\n return result;\n },\n },\n });\n\n return [\n on(document, 'click', handleClick, QUICK_EVENT),\n on(document, 'pointerdown pointerup scroll', handleScrollbar, QUICK_EVENT),\n on(document, 'toggle ds-toggle-source', handleToggle, QUICK_EVENT), // Use capture since the toggle event does not bubble\n () => {\n // Restore original methods on hot reload\n Object.defineProperties(HTMLElement.prototype, {\n togglePopover: { ...descriptors.togglePopover, value: togglePopover },\n showPopover: { ...descriptors.showPopover, value: showPopover },\n hidePopover: { ...descriptors.hidePopover, value: hidePopover },\n });\n for (const [, off] of ROOTS) off(); // Cleanup listeners on ShadowRoots on hot reload\n ROOTS.clear();\n },\n ];\n});\n\nconst arrowPseudo = () => ({\n name: 'arrowPseudo',\n fn(data: MiddlewareState) {\n const target = data.elements.floating;\n const source = data.rects.reference;\n const x = `${Math.round(source.width / 2 + source.x - data.x)}px`;\n const y = `${Math.round(source.height / 2 + source.y - data.y)}px`;\n\n target.style.setProperty('--_ds-floating-arrow-x', x);\n target.style.setProperty('--_ds-floating-arrow-y', y);\n attr(target, 'data-floating', data.placement);\n return data;\n },\n});\n"],"mappings":"wYA0BI,EAAU,GAAK,CAAC,EAAY,GAAK,CAAC,EAAa,GACjD,EAAgB,CAAE,UAAW,SAAU,CAAC,EAe1C,MAAM,EAAQ,IAAI,IACZ,EAAa,iBACb,EAAY,qBACZ,EAAW,IAAI,IAQf,EACJ,GAEG,EAAO,EAAkB,CAAC,EAAG,EAAE,SAAU,EAAE,SAAU,EAAE,QAAU,EAAE,MAAM,EAE9E,SAAS,EACP,EACA,EACA,EACA,EACA,CACA,IAAM,EAAY,aAAc,aAAe,EAAK,EAAI,SAAS,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,GAAG,KAAK,MAAM,EAAO,OAAS,EAAI,EAAO,EAAI,EAAK,CAAC,EAAE,IAK/D,OAHA,EAAO,MAAM,YAAY,yBAA0B,CAAC,EACpD,EAAO,MAAM,YAAY,yBAA0B,CAAC,EACpD,EAAK,EAAQ,gBAAiB,EAAK,SAAS,EACrC,CACT,CACF"}
@@ -1,2 +1,2 @@
1
- import{QUICK_EVENT as e,attr as t,attrOrCSS as n,customElements as r,off as i,on as a,onMutation as o,useId as s,warn as c}from"../utils/utils.js";import{UHTMLComboboxElement as l}from"@u-elements/u-combobox";const u=`data-empty`;var d=class extends l{_unmutate;connectedCallback(){super.connectedCallback(),this._unmutate=o(this,f,{childList:!0}),a(this,`comboboxafterselect input`,p,e),a(this,`toggle`,m,e)}disconnectedCallback(){super.disconnectedCallback(),this._unmutate?.(),this._unmutate=void 0,i(this,`comboboxafterselect input`,p,e),i(this,`toggle`,m,e)}};const f=e=>{let{control:n,list:r}=e,i=r||e.querySelector(`u-datalist`);n&&t(n,`popovertarget`,r?s(r):null),i&&(t(i,`popover`,`manual`),t(i,`data-is-floating`,`true`)),p({currentTarget:e})},p=({currentTarget:e})=>{let{creatable:r,control:i,options:a}=e;if(!a)return;let o=i?.value.trim()||``,s=o.toLowerCase(),l,d=!o;for(let e of a)if(!l&&e.hasAttribute(u)?l=e:!d&&e.label?.toLowerCase()===s&&(d=!0),d&&l)break;if(!l||(l.hidden=d,l.label=o,l.value=r?o:``,!r||l.textContent))return;let f=n(l,u);f?t(l,u,f):c(`Missing ${u} value on:`,l),t(l,`data-create`,f?.replace(`{value}`,o))},m=e=>{let t=e.currentTarget,n=e.newState===`open`&&t.control;n&&t.list?.dispatchEvent(new CustomEvent(`ds-toggle-source`,{bubbles:!0,composed:!0,detail:n}))};r.define(`ds-suggestion`,d);export{d as DSSuggestionElement};
1
+ import{QUICK_EVENT as e,attr as t,attrOrCSS as n,customElements as r,off as i,on as a,onMutation as o,useId as s,warn as c}from"../utils/utils.js";import{UHTMLComboboxElement as l}from"@u-elements/u-combobox";export*from"@u-elements/u-datalist";const u=`data-empty`,d=`comboboxafterselect comboboxprogrammaticinput input`,f=/\{value\}|%s/,p=`data-sr-singular`,m=`data-sr-plural`,h=`added,clear,empty,found,invalid,items,of,plural,remove,removed,singular,toggle`.split(`,`).map(e=>`data-sr-${e}`);var g=class extends l{_unmutate;connectedCallback(){for(let e of h)t(this,e,n(this,e));super.connectedCallback(),this._unmutate=o(this,_,{childList:!0}),a(this,d,v,e),a(this,`toggle`,y,e)}disconnectedCallback(){super.disconnectedCallback(),this._unmutate?.(),this._unmutate=void 0,i(this,d,v,e),i(this,`toggle`,y,e)}};const _=e=>{let{control:n,list:r}=e;r||=e.querySelector(`u-datalist`),n&&t(n,`popovertarget`,r?s(r):null),r&&(t(r,m)||t(r,m,t(e,m)),t(r,p)||t(r,p,t(e,p)),t(r,`data-is-floating`,`true`),t(r,`popover`,`manual`)),v({currentTarget:e})},v=e=>{let r=e.currentTarget,{creatable:i,control:a,options:o}=r;if(!o)return;let s=a?.value.trim()||``,l=s.toLowerCase(),d,p=!1;for(let e of o)if(!d&&e.hasAttribute(u)?d=e:!p&&(!l||e.label?.toLowerCase()===l)&&(p=!0),p&&d)break;if(d&&(d.hidden=p||i&&!s,t(d,`label`,s),t(d,`value`,i?s:``),i)){let e=r.values.includes(s),i=n(d,u),a=!e&&i?.replace(f,()=>s)||s;i?t(d,u,i):c(`Missing ${u} value on:`,d);let o=e&&d.textContent?`true`:null;t(d,`disabled`,o),t(d,`data-create`,a)}},y=e=>{let t=e.currentTarget,n=e.newState===`open`&&t.control;n&&t.list?.dispatchEvent(new CustomEvent(`ds-toggle-source`,{bubbles:!0,composed:!0,detail:n}))};r.define(`ds-suggestion`,g);export{g as DSSuggestionElement};
2
2
  //# sourceMappingURL=suggestion.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"suggestion.js","names":[],"sources":["../../../src/suggestion/suggestion.ts"],"sourcesContent":["import { UHTMLComboboxElement } from '@u-elements/u-combobox';\nimport {\n attr,\n attrOrCSS,\n customElements,\n off,\n on,\n onMutation,\n QUICK_EVENT,\n useId,\n warn,\n} from '../utils/utils';\n\nconst ATTR_EMPTY = 'data-empty';\nconst ATTR_CREATE = 'data-create';\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'ds-suggestion': DSSuggestionElement;\n }\n}\n\nexport class DSSuggestionElement extends UHTMLComboboxElement {\n _unmutate?: ReturnType<typeof onMutation>; // Using underscore instead of private fields for backwards compatibility\n\n connectedCallback() {\n super.connectedCallback();\n this._unmutate = onMutation(this, render, { childList: true }); // .control and .list are direct children of the custom element\n on(this, 'comboboxafterselect input', handleEmpty, QUICK_EVENT);\n on(this, 'toggle', polyfillToggleSource, QUICK_EVENT);\n }\n disconnectedCallback() {\n super.disconnectedCallback();\n this._unmutate?.();\n this._unmutate = undefined;\n off(this, 'comboboxafterselect input', handleEmpty, QUICK_EVENT);\n off(this, 'toggle', polyfillToggleSource, QUICK_EVENT);\n }\n}\n\nconst render = (self: DSSuggestionElement) => {\n const { control, list } = self;\n const datalist = list || self.querySelector('u-datalist'); // Fallback to u-datalist since React can render the ds-suggestion before u-datalist is connected\n\n if (control) attr(control, 'popovertarget', list ? useId(list) : null);\n if (datalist) {\n attr(datalist, 'popover', 'manual'); // Ensure popover attribute is set on the list\n attr(datalist, 'data-is-floating', 'true'); // identifier for css to toggle opacity when it is placed by floating-ui.\n }\n handleEmpty({ currentTarget: self });\n};\n\nconst handleEmpty = ({ currentTarget: self }: Pick<Event, 'currentTarget'>) => {\n const { creatable, control, options } = self as DSSuggestionElement;\n if (!options) return;\n\n const value = control?.value.trim() || '';\n const query = value.toLowerCase();\n let empty: HTMLOptionElement | undefined;\n let exists = !value;\n\n for (const opt of options) {\n if (!empty && opt.hasAttribute(ATTR_EMPTY)) empty = opt;\n else if (!exists && opt.label?.toLowerCase() === query) exists = true; // Prevent creating an option that already exists\n if (exists && empty) break; // Speed up if both conditions are met\n }\n if (!empty) return;\n\n empty.hidden = exists;\n empty.label = value; // Ensures option is not filtered out by <u-combobox>\n empty.value = creatable ? value : ''; // Ensures clicking option does nothing\n\n if (!creatable || empty.textContent) return;\n const text = attrOrCSS(empty, ATTR_EMPTY);\n if (!text) warn(`Missing ${ATTR_EMPTY} value on:`, empty);\n else attr(empty, ATTR_EMPTY, text); // Speed up by caching attribute value\n attr(empty, ATTR_CREATE, text?.replace('{value}', value));\n};\n\n// Since showPopover({ source }) is not supported in all browsers yet:\nconst polyfillToggleSource = (event: Partial<ToggleEvent>) => {\n const self = event.currentTarget as DSSuggestionElement;\n const detail = event.newState === 'open' && self.control; // .control comes from UHTMLComboboxElement\n\n if (detail)\n self.list?.dispatchEvent(\n new CustomEvent('ds-toggle-source', {\n bubbles: true,\n composed: true, // Enable bubbling out of shadow DOM boundaries\n detail, // Since showPopover({ source }) is not supported in all browsers yet\n }),\n );\n};\n\n// Ensure u-datalist is defined before ds-suggestion\ncustomElements.define('ds-suggestion', DSSuggestionElement);\n"],"mappings":"iNAaA,MAAM,EAAa,aASnB,IAAa,EAAb,cAAyC,CAAqB,CAC5D,UAEA,mBAAoB,CAClB,MAAM,kBAAkB,EACxB,KAAK,UAAY,EAAW,KAAM,EAAQ,CAAE,UAAW,EAAK,CAAC,EAC7D,EAAG,KAAM,4BAA6B,EAAa,CAAW,EAC9D,EAAG,KAAM,SAAU,EAAsB,CAAW,CACtD,CACA,sBAAuB,CACrB,MAAM,qBAAqB,EAC3B,KAAK,YAAY,EACjB,KAAK,UAAY,IAAA,GACjB,EAAI,KAAM,4BAA6B,EAAa,CAAW,EAC/D,EAAI,KAAM,SAAU,EAAsB,CAAW,CACvD,CACF,EAEA,MAAM,EAAU,GAA8B,CAC5C,GAAM,CAAE,UAAS,QAAS,EACpB,EAAW,GAAQ,EAAK,cAAc,YAAY,EAEpD,GAAS,EAAK,EAAS,gBAAiB,EAAO,EAAM,CAAI,EAAI,IAAI,EACjE,IACF,EAAK,EAAU,UAAW,QAAQ,EAClC,EAAK,EAAU,mBAAoB,MAAM,GAE3C,EAAY,CAAE,cAAe,CAAK,CAAC,CACrC,EAEM,GAAe,CAAE,cAAe,KAAyC,CAC7E,GAAM,CAAE,YAAW,UAAS,WAAY,EACxC,GAAI,CAAC,EAAS,OAEd,IAAM,EAAQ,GAAS,MAAM,KAAK,GAAK,GACjC,EAAQ,EAAM,YAAY,EAC5B,EACA,EAAS,CAAC,EAEd,IAAK,IAAM,KAAO,EAGhB,GAFI,CAAC,GAAS,EAAI,aAAa,CAAU,EAAG,EAAQ,EAC3C,CAAC,GAAU,EAAI,OAAO,YAAY,IAAM,IAAO,EAAS,IAC7D,GAAU,EAAO,MAQvB,GANI,CAAC,IAEL,EAAM,OAAS,EACf,EAAM,MAAQ,EACd,EAAM,MAAQ,EAAY,EAAQ,GAE9B,CAAC,GAAa,EAAM,aAAa,OACrC,IAAM,EAAO,EAAU,EAAO,CAAU,EACnC,EACA,EAAK,EAAO,EAAY,CAAI,EADtB,EAAK,WAAW,EAAW,YAAa,CAAK,EAExD,EAAK,EAAO,cAAa,GAAM,QAAQ,UAAW,CAAK,CAAC,CAC1D,EAGM,EAAwB,GAAgC,CAC5D,IAAM,EAAO,EAAM,cACb,EAAS,EAAM,WAAa,QAAU,EAAK,QAE7C,GACF,EAAK,MAAM,cACT,IAAI,YAAY,mBAAoB,CAClC,QAAS,GACT,SAAU,GACV,QACF,CAAC,CACH,CACJ,EAGA,EAAe,OAAO,gBAAiB,CAAmB"}
1
+ {"version":3,"file":"suggestion.js","names":[],"sources":["../../../src/suggestion/suggestion.ts"],"sourcesContent":["import { UHTMLComboboxElement } from '@u-elements/u-combobox';\nimport {\n attr,\n attrOrCSS,\n customElements,\n off,\n on,\n onMutation,\n QUICK_EVENT,\n useId,\n warn,\n} from '../utils/utils';\n\n// Load and export u-datalist since this is a pure polyfill and not custom Designsystemet elements, should run before suggestion\nexport * from '@u-elements/u-datalist';\n\nconst ATTR_EMPTY = 'data-empty';\nconst ATTR_CREATE = 'data-create';\nconst EVENTS_EMPTY = 'comboboxafterselect comboboxprogrammaticinput input';\nconst REGEX_CREATE = /\\{value\\}|%s/; // Support both new %s and old {value} syntax\nconst SINGULAR = 'data-sr-singular';\nconst PLURAL = 'data-sr-plural';\nconst TEXTS =\n 'added,clear,empty,found,invalid,items,of,plural,remove,removed,singular,toggle'\n .split(',')\n .map((key) => `data-sr-${key}`);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'ds-suggestion': DSSuggestionElement;\n }\n}\n\nexport class DSSuggestionElement extends UHTMLComboboxElement {\n _unmutate?: ReturnType<typeof onMutation>; // Using underscore instead of private fields for backwards compatibility\n\n connectedCallback() {\n for (const key of TEXTS) attr(this, key, attrOrCSS(this, key)); // Convert CSS variables to data-sr-attributes\n super.connectedCallback(); // Run after setting data-sr-attributes\n\n this._unmutate = onMutation(this, render, { childList: true }); // .control and .list are direct children of the custom element\n on(this, EVENTS_EMPTY, handleEmpty, QUICK_EVENT);\n on(this, 'toggle', polyfillToggleSource, QUICK_EVENT);\n }\n disconnectedCallback() {\n super.disconnectedCallback();\n this._unmutate?.();\n this._unmutate = undefined;\n off(this, EVENTS_EMPTY, handleEmpty, QUICK_EVENT);\n off(this, 'toggle', polyfillToggleSource, QUICK_EVENT);\n }\n}\n\nconst render = (self: DSSuggestionElement) => {\n let { control, list } = self;\n if (!list) list = self.querySelector('u-datalist'); // Fallback to u-datalist since React can render the ds-suggestion before u-datalist is connected\n\n if (control) attr(control, 'popovertarget', list ? useId(list) : null);\n if (list) {\n if (!attr(list, PLURAL)) attr(list, PLURAL, attr(self, PLURAL)); // Inherit translations from u-combobox to u-datalist\n if (!attr(list, SINGULAR)) attr(list, SINGULAR, attr(self, SINGULAR)); // Inherit translations from u-combobox to u-datalist\n attr(list, 'data-is-floating', 'true'); // identifier for css to toggle opacity when it is placed by floating-ui.\n attr(list, 'popover', 'manual'); // Ensure popover attribute is set on the list\n }\n handleEmpty({ currentTarget: self });\n};\n\nconst handleEmpty = (event: Pick<Event, 'currentTarget'>) => {\n const self = event.currentTarget as DSSuggestionElement;\n const { creatable, control, options } = self;\n if (!options) return;\n\n const value = control?.value.trim() || '';\n const query = value.toLowerCase();\n let emptyOpt: HTMLOptionElement | undefined;\n let hasLabel = false;\n\n for (const opt of options) {\n if (!emptyOpt && opt.hasAttribute(ATTR_EMPTY)) emptyOpt = opt;\n else if (!hasLabel && (!query || opt.label?.toLowerCase() === query))\n hasLabel = true;\n if (hasLabel && emptyOpt) break; // Speed up if both conditions are met\n }\n if (!emptyOpt) return;\n\n emptyOpt.hidden = hasLabel || (creatable && !value); // Hide initial empty state when options exist, when the query already exists, or for an initially empty creatable input\n attr(emptyOpt, 'label', value); // Ensures option is not filtered out by <u-combobox>\n attr(emptyOpt, 'value', creatable ? value : ''); // Ensures clicking option does nothing\n\n if (creatable) {\n const hasValue = self.values.includes(value);\n const text = attrOrCSS(emptyOpt, ATTR_EMPTY);\n const hint =\n (!hasValue && text?.replace(REGEX_CREATE, () => value)) || value; // Only show \"Legg til\" if not already created\n\n if (!text) warn(`Missing ${ATTR_EMPTY} value on:`, emptyOpt);\n else attr(emptyOpt, ATTR_EMPTY, text); // Speed up by caching attribute value\n\n const disabled = hasValue && emptyOpt.textContent ? 'true' : null;\n attr(emptyOpt, 'disabled', disabled); // Hide hint if already created\n attr(emptyOpt, ATTR_CREATE, hint);\n }\n};\n\n// Since showPopover({ source }) is not supported in all browsers yet:\nconst polyfillToggleSource = (event: Partial<ToggleEvent>) => {\n const self = event.currentTarget as DSSuggestionElement;\n const detail = event.newState === 'open' && self.control; // .control comes from UHTMLComboboxElement\n\n if (detail)\n self.list?.dispatchEvent(\n new CustomEvent('ds-toggle-source', {\n bubbles: true,\n composed: true, // Enable bubbling out of shadow DOM boundaries\n detail, // Since showPopover({ source }) is not supported in all browsers yet\n }),\n );\n};\n\n// Ensure u-datalist is defined before ds-suggestion\ncustomElements.define('ds-suggestion', DSSuggestionElement);\n"],"mappings":"qPAgBA,MAAM,EAAa,aAEb,EAAe,sDACf,EA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CAAC,IAAa,CAAC,GAAS,EAAI,OAAO,YAAY,IAAM,KAC5D,EAAW,IACT,GAAY,EAAU,MAEvB,OAEL,EAAS,OAAS,GAAa,GAAa,CAAC,EAC7C,EAAK,EAAU,QAAS,CAAK,EAC7B,EAAK,EAAU,QAAS,EAAY,EAAQ,EAAE,EAE1C,GAAW,CACb,IAAM,EAAW,EAAK,OAAO,SAAS,CAAK,EACrC,EAAO,EAAU,EAAU,CAAU,EACrC,EACH,CAAC,GAAY,GAAM,QAAQ,MAAoB,CAAK,GAAM,EAExD,EACA,EAAK,EAAU,EAAY,CAAI,EADzB,EAAK,WAAW,EAAW,YAAa,CAAQ,EAG3D,IAAM,EAAW,GAAY,EAAS,YAAc,OAAS,KAC7D,EAAK,EAAU,WAAY,CAAQ,EACnC,EAAK,EAAU,cAAa,CAAI,CAClC,CACF,EAGM,EAAwB,GAAgC,CAC5D,IAAM,EAAO,EAAM,cACb,EAAS,EAAM,WAAa,QAAU,EAAK,QAE7C,GACF,EAAK,MAAM,cACT,IAAI,YAAY,mBAAoB,CAClC,QAAS,GACT,SAAU,GACV,QACF,CAAC,CACH,CACJ,EAGA,EAAe,OAAO,gBAAiB,CAAmB"}
@@ -1 +1 @@
1
- {"version":3,"file":"toggle-group.js","names":[],"sources":["../../../src/toggle-group/toggle-group.ts"],"sourcesContent":["import {\n ARIA_LABEL,\n ARIA_LABELLEDBY,\n attr,\n attrOrCSS,\n getComposedPath,\n getComposedTarget,\n on,\n onHotReload,\n onMutation,\n warn,\n} from '../utils/utils';\n\nconst ATTR_FOCUSGROUP = 'focusgroup';\nconst ATTR_TOGGLEGROUP = 'data-toggle-group';\nconst SELECTOR_TOGGLEGROUP = `[${ATTR_TOGGLEGROUP}]`;\nlet IS_ARROW: boolean | undefined; // Used to prevent clicks that are a result of keyboard navigation\n\nconst handleMutations = (root: Document, records?: MutationRecord[]) => {\n for (const r of records || [null]) {\n if (r?.attributeName === ATTR_TOGGLEGROUP) deprecate(r.target as Element);\n else if (!r || r.addedNodes.length) {\n const scope = (r?.target as Element) || root;\n for (const el of scope.querySelectorAll(SELECTOR_TOGGLEGROUP))\n deprecate(el);\n }\n }\n};\n\n// Prevent clicks that are a result of keyboard navigation\nconst handleRadioClick = (e: Event & Partial<PointerEvent>) => {\n if (IS_ARROW && getRadioInFocusGroup(e)) {\n e.preventDefault(); // Only handle clicks that are a result of keyboard navigation\n e.stopImmediatePropagation(); // Prevent stopped \"click\" from reaching React and other listeners\n }\n};\n\nconst resetIsArrow = () => (IS_ARROW = false);\nconst handleKeydown = (e: Event & Partial<KeyboardEvent>) => {\n IS_ARROW = e.key?.startsWith('Arrow');\n if (e.key === 'Enter') getRadioInFocusGroup(e)?.click(); // Allow Enter to activate the radio input\n if (IS_ARROW) setTimeout(resetIsArrow, 0); // Reset after event loop so we can check if next focus event is a result of arrow key navigation\n};\n\n// This function does not handle nested focusgroups, but toggle-groups should not be nested so this is not a problem\nconst getRadioInFocusGroup = (e: Event) => {\n const el = getComposedTarget(e) as HTMLInputElement | null;\n if (el?.nodeName !== 'INPUT' || el.type !== 'radio' || !el.name) return;\n for (const group of getComposedPath(el) as Set<Element>) {\n if (group.nodeType !== 1 || !group.hasAttribute(ATTR_FOCUSGROUP)) continue; // Ignore non-group nodes\n if (!attr(group, ATTR_FOCUSGROUP)?.includes('radiogroup')) return; // Ignore invalid groups\n return el;\n }\n};\n\nconst deprecate = (el: Element) => {\n if (el.hasAttribute(ATTR_FOCUSGROUP)) return; // Ignore if already migrated\n const label = attrOrCSS(el, ATTR_TOGGLEGROUP);\n const labelledby = attr(el, ARIA_LABELLEDBY)?.trim();\n const message = `Please use ${ATTR_FOCUSGROUP}=\"radiogroup\" and ${labelledby ? ARIA_LABELLEDBY : ARIA_LABEL}=\"${labelledby || label}\" instead of deprecated ${ATTR_TOGGLEGROUP} on:`;\n\n attr(el, ARIA_LABEL, labelledby ? null : label);\n attr(el, ATTR_FOCUSGROUP, 'radiogroup');\n warn(message, el);\n};\n\nonHotReload('toggle-group', () => [\n on(document, 'click', handleRadioClick, true), // Use capture to ensure we run before React and other listeners\n on(document, 'keydown', handleKeydown),\n onMutation(document, handleMutations, {\n attributeFilter: [ATTR_TOGGLEGROUP],\n attributes: true,\n childList: true,\n subtree: true,\n }),\n]);\n"],"mappings":"4LAaA,MAAM,EAAkB,aAClB,EAAmB,oBACnB,EAAuB,IAAI,EAAiB,GAClD,IAAI,EAEJ,MAAM,GAAmB,EAAgB,IAA+B,CACtE,IAAK,IAAM,KAAK,GAAW,CAAC,IAAI,EAC9B,GAAI,GAAG,gBAAkB,EAAkB,EAAU,EAAE,MAAiB,OACnE,GAAI,CAAC,GAAK,EAAE,WAAW,OAAQ,CAClC,IAAM,EAAS,GAAG,QAAsB,EACxC,IAAK,IAAM,KAAM,EAAM,iBAAiB,CAAoB,EAC1D,EAAU,CAAE,CAChB,CAEJ,EAGM,EAAoB,GAAqC,CACzD,GAAY,EAAqB,CAAC,IACpC,EAAE,eAAe,EACjB,EAAE,yBAAyB,EAE/B,EAEM,MAAsB,EAAW,GACjC,EAAiB,GAAsC,CAC3D,EAAW,EAAE,KAAK,WAAW,OAAO,EAChC,EAAE,MAAQ,SAAS,EAAqB,CAAC,CAAC,EAAE,MAAM,EAClD,GAAU,WAAW,EAAc,CAAC,CAC1C,EAGM,EAAwB,GAAa,CACzC,IAAM,EAAK,EAAkB,CAAC,EAC1B,QAAI,WAAa,SAAW,EAAG,OAAS,SAAW,CAAC,EAAG,MAC3D,KAAK,IAAM,KAAS,EAAgB,CAAE,EAChC,OAAM,WAAa,GAAK,CAAC,EAAM,aAAa,CAAe,GAE/D,OADK,EAAK,EAAO,CAAe,CAAC,EAAE,SAAS,YAAY,EACjD,EADoD,MAE7D,CACF,EAEM,EAAa,GAAgB,CACjC,GAAI,EAAG,aAAa,CAAe,EAAG,OACtC,IAAM,EAAQ,EAAU,EAAI,CAAgB,EACtC,EAAa,EAAK,EAAI,CAAe,CAAC,EAAE,KAAK,EAC7C,EAAU,cAAc,EAAgB,oBAAoB,EAAa,EAAkB,EAAW,IAAI,GAAc,EAAM,0BAA0B,EAAiB,MAE/K,EAAK,EAAI,EAAY,EAAa,KAAO,CAAK,EAC9C,EAAK,EAAI,EAAiB,YAAY,EACtC,EAAK,EAAS,CAAE,CAClB,EAEA,EAAY,mBAAsB,CAChC,EAAG,SAAU,QAAS,EAAkB,EAAI,EAC5C,EAAG,SAAU,UAAW,CAAa,EACrC,EAAW,SAAU,EAAiB,CACpC,gBAAiB,CAAC,CAAgB,EAClC,WAAY,GACZ,UAAW,GACX,QAAS,EACX,CAAC,CACH,CAAC"}
1
+ {"version":3,"file":"toggle-group.js","names":[],"sources":["../../../src/toggle-group/toggle-group.ts"],"sourcesContent":["import {\n ARIA_LABEL,\n ARIA_LABELLEDBY,\n attr,\n attrOrCSS,\n getComposedPath,\n getComposedTarget,\n on,\n onHotReload,\n onMutation,\n warn,\n} from '../utils/utils';\n\nconst ATTR_FOCUSGROUP = 'focusgroup';\nconst ATTR_TOGGLEGROUP = 'data-toggle-group';\nconst SELECTOR_TOGGLEGROUP = `[${ATTR_TOGGLEGROUP}]`;\nlet IS_ARROW: boolean | undefined; // Used to prevent clicks that are a result of keyboard navigation\n\nconst handleMutations = (root: Document, records?: MutationRecord[]) => {\n for (const r of records || [null]) {\n if (r?.attributeName === ATTR_TOGGLEGROUP) deprecate(r.target as Element);\n else if (!r || r.addedNodes.length) {\n const scope = (r?.target as Element) || root;\n for (const el of scope.querySelectorAll(SELECTOR_TOGGLEGROUP))\n deprecate(el);\n }\n }\n};\n\n// Prevent clicks that are a result of keyboard navigation\nconst handleRadioClick = (e: Event & Partial<PointerEvent>) => {\n if (IS_ARROW && getRadioInFocusGroup(e)) {\n e.preventDefault(); // Only handle clicks that are a result of keyboard navigation\n e.stopImmediatePropagation(); // Prevent stopped \"click\" from reaching React and other listeners\n }\n};\n\nconst resetIsArrow = () => (IS_ARROW = false);\nconst handleKeydown = (e: Event & Partial<KeyboardEvent>) => {\n IS_ARROW = e.key?.startsWith('Arrow');\n if (e.key === 'Enter') getRadioInFocusGroup(e)?.click(); // Allow Enter to activate the radio input\n if (IS_ARROW) setTimeout(resetIsArrow, 0); // Reset after event loop so we can check if next focus event is a result of arrow key navigation\n};\n\n// This function does not handle nested focusgroups, but toggle-groups should not be nested so this is not a problem\nconst getRadioInFocusGroup = (e: Event) => {\n const el = getComposedTarget(e) as HTMLInputElement | null;\n if (el?.nodeName !== 'INPUT' || el.type !== 'radio' || !el.name) return;\n for (const group of getComposedPath(el) as Set<Element>) {\n if (group.nodeType !== 1 || !group.hasAttribute(ATTR_FOCUSGROUP)) continue; // Ignore non-group nodes\n if (!attr(group, ATTR_FOCUSGROUP)?.includes('radiogroup')) return; // Ignore invalid groups\n return el;\n }\n};\n\n// @deprecated: Supports migration from data-toggle-group to focusgroup=\"radiogroup\".\nconst deprecate = (el: Element) => {\n if (el.hasAttribute(ATTR_FOCUSGROUP)) return; // Ignore if already migrated\n const label = attrOrCSS(el, ATTR_TOGGLEGROUP);\n const labelledby = attr(el, ARIA_LABELLEDBY)?.trim();\n const message = `Please use ${ATTR_FOCUSGROUP}=\"radiogroup\" and ${labelledby ? ARIA_LABELLEDBY : ARIA_LABEL}=\"${labelledby || label}\" instead of deprecated ${ATTR_TOGGLEGROUP} on:`;\n\n attr(el, ARIA_LABEL, labelledby ? null : label);\n attr(el, ATTR_FOCUSGROUP, 'radiogroup');\n warn(message, el);\n};\n\nonHotReload('toggle-group', () => [\n on(document, 'click', handleRadioClick, true), // Use capture to ensure we run before React and other listeners\n on(document, 'keydown', handleKeydown),\n onMutation(document, handleMutations, {\n attributeFilter: [ATTR_TOGGLEGROUP],\n attributes: true,\n childList: true,\n subtree: true,\n }),\n]);\n"],"mappings":"4LAaA,MAAM,EAAkB,aAClB,EAAmB,oBACnB,EAAuB,IAAI,EAAiB,GAClD,IAAI,EAEJ,MAAM,GAAmB,EAAgB,IAA+B,CACtE,IAAK,IAAM,KAAK,GAAW,CAAC,IAAI,EAC9B,GA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GACX,QAAS,EACX,CAAC,CACH,CAAC"}
@@ -1,2 +1,2 @@
1
- import{ARIA_DESC as e,ARIA_LABEL as t,QUICK_EVENT as n,announce as r,attr as i,attrOrCSS as a,getComposedTarget as o,getRoot as s,isBrowser as c,on as l,onHotReload as u,onMutation as d,tag as f,warn as p}from"../utils/utils.js";import"../popover/popover.js";let m,h,g,_,v=0;const y=`data-color`,b=`data-color-scheme`,x=`data-size`,S=`data-tooltip`,C=c()&&/iPad|iPhone|iPod/.test(navigator.userAgent),w=`[${y}]`,T=`[${b}]`,E=`[${x}]`,D=`[${S}]`,O=e=>{e&&!(e instanceof HTMLElement)&&p(`setTooltipElement expects an HTMLElement, got: `,e),P(),v=0,m=e||void 0},k=(e=document)=>{for(let t of e?.querySelectorAll(D)||[])j(t)},A=(e,t)=>{if(!t)return k();for(let e of t)if(e.target!==m)if(e.attributeName===S)j(e.target);else for(let t of e.addedNodes)t.nodeType===1&&(t.hasAttribute(S)?j(t):k(t))},j=(n,o=!0)=>{let c=a(n,S)||``;if(c[0]===`#`&&(c=s(n).getElementById(c.slice(1))?.textContent?.trim()||``),c!==(n.getAttribute(`aria-label`)||n.getAttribute(`aria-description`))){let r=i(n,`role`)!==`img`&&n.textContent?.trim();i(n,S,c),i(n,t,r?null:c),i(n,e,r?c:null),n.tabIndex===-1&&p(`Missing tabindex="0" attribute on: `,n)}n===_&&m?.textContent!==c&&(m&&(m.textContent=c),c&&o&&document.activeElement===n&&r(c))},M=e=>{let t=o(e);if(!t||g===t||m?.contains(t))return;g=t;let n=g?.closest?.(D)||void 0;if(_!==n&&(_&&P(),_=n,n)){if(e.type===`focus`||C||300>Date.now()-v)return N();e.type===`mousemove`&&(h=setTimeout(N,300))}},N=()=>{if(!_)return P();m||=f(`div`,{class:`ds-tooltip`}),m.isConnected||document.body.appendChild(m);let e=_.closest(w),t=_.closest(T),n=_.closest(E),r=e!==t&&e?.contains(t);i(m,`popover`,`manual`),i(m,b,t?.getAttribute(b)||null),i(m,y,r&&e?.getAttribute(y)||null),i(m,x,n?.getAttribute(x)||null),j(_,!1),m.showPopover(),m.dispatchEvent(new CustomEvent(`ds-toggle-source`,{bubbles:!0,composed:!0,detail:_}))},P=e=>{(e?.type!==`keydown`||e?.key===`Escape`)&&(_&&m?.isConnected&&m.popover&&m.hidePopover(),e||(v=Date.now()),clearTimeout(h),_=void 0)};u(`tooltip`,()=>[l(document,`focus mousemove`,M,n),l(document,`keydown`,P,n),d(document,A,{attributeFilter:[S],attributes:!0,childList:!0,subtree:!0})]);export{k as initTooltips,O as setTooltipElement};
1
+ import{ARIA_DESC as e,ARIA_LABEL as t,QUICK_EVENT as n,announce as r,attr as i,attrOrCSS as a,getComposedTarget as o,getRoot as s,isBrowser as c,on as l,onHotReload as u,onMutation as d,tag as f,warn as p}from"../utils/utils.js";import"../popover/popover.js";let m,h,g,_,v=0;const y=`data-color`,b=`data-color-scheme`,x=`data-size`,S=`data-tooltip`,C=c()&&/iPad|iPhone|iPod/.test(navigator.userAgent),w=`[${y}]`,T=`[${b}]`,E=`[${x}]`,D=`[${S}]`,O=e=>{e&&!(e instanceof HTMLElement)&&p(`setTooltipElement expects an HTMLElement, got: `,e),P(),v=0,m=e||void 0},k=(e=document)=>{for(let t of e?.querySelectorAll(D)||[])j(t)},A=(e,t)=>{if(!t)return k();for(let e of t)if(e.target!==m)if(e.attributeName===S)j(e.target);else for(let t of e.addedNodes)t.nodeType===1&&(t.hasAttribute(S)?j(t):k(t))},j=(n,o=!0)=>{let c=a(n,S)||``;if(c[0]===`#`&&(c=s(n).getElementById(c.slice(1))?.textContent?.trim()||``),c!==(n.getAttribute(`aria-label`)||n.getAttribute(`aria-description`))){let r=i(n,`role`)!==`img`&&n.textContent?.trim();i(n,S,c),i(n,t,r?null:c),i(n,e,r?c:null),n.tabIndex===-1&&!n.hasAttribute(`tabindex`)&&n.nodeName!==`LABEL`&&p(`Missing tabindex="0" attribute on: `,n)}n===_&&m?.textContent!==c&&(m&&(m.textContent=c),c&&o&&document.activeElement===n&&r(c))},M=e=>{let t=o(e);if(!t||g===t||m?.contains(t))return;g=t;let n=g?.closest?.(D)||void 0;if(_!==n&&(_&&P(),_=n,n)){if(e.type===`focus`||C||300>Date.now()-v)return N();e.type===`mousemove`&&(h=setTimeout(N,300))}},N=()=>{if(!_)return P();m||=f(`div`,{class:`ds-tooltip`}),m.isConnected||document.body.appendChild(m);let e=_.closest(w),t=_.closest(T),n=_.closest(E),r=e!==t&&e?.contains(t);i(m,`popover`,`manual`),i(m,b,t?.getAttribute(b)||null),i(m,y,r&&e?.getAttribute(y)||null),i(m,x,n?.getAttribute(x)||null),j(_,!1),m.showPopover(),m.dispatchEvent(new CustomEvent(`ds-toggle-source`,{bubbles:!0,composed:!0,detail:_}))},P=e=>{(e?.type!==`keydown`||e?.key===`Escape`)&&(_&&m?.isConnected&&m.popover&&m.hidePopover(),e||(v=Date.now()),clearTimeout(h),_=void 0)};u(`tooltip`,()=>[l(document,`focus mousemove`,M,n),l(document,`keydown`,P,n),d(document,A,{attributeFilter:[S],attributes:!0,childList:!0,subtree:!0})]);export{k as initTooltips,O as setTooltipElement};
2
2
  //# sourceMappingURL=tooltip.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tooltip.js","names":[],"sources":["../../../src/tooltip/tooltip.ts"],"sourcesContent":["import '../popover/popover'; // Ensure popover is imported when using individual imports, since tooltip relies on it\nimport {\n ARIA_DESC,\n ARIA_LABEL,\n announce,\n attr,\n attrOrCSS,\n getComposedTarget,\n getRoot,\n isBrowser,\n on,\n onHotReload,\n onMutation,\n QUICK_EVENT,\n tag,\n warn,\n} from '../utils/utils';\n\nlet TIP: HTMLElement | undefined;\nlet TIMER: ReturnType<typeof setTimeout> | undefined;\nlet TARGET: Element | undefined; // Used to speed up mousemove handling\nlet OPEN: Element | undefined;\nlet LAST_HIDE = 0;\nconst ATTR_COLOR = 'data-color';\nconst ATTR_SCHEME = 'data-color-scheme';\nconst ATTR_SIZE = 'data-size';\nconst ATTR_TOOLTIP = 'data-tooltip';\nconst DELAY_HOVER = 300;\nconst DELAY_SKIP = 300;\nconst IS_IOS = isBrowser() && /iPad|iPhone|iPod/.test(navigator.userAgent); // Needed to omit DELAY_HOVER since iOS triggers mousemove before click\nconst SELECTOR_COLOR = `[${ATTR_COLOR}]`;\nconst SELECTOR_SCHEME = `[${ATTR_SCHEME}]`;\nconst SELECTOR_SIZE = `[${ATTR_SIZE}]`;\nconst SELECTOR_TOOLTIP = `[${ATTR_TOOLTIP}]`;\n\n/**\n * setTooltipElement\n * @description Allows setting a custom tooltip element. It does not need to, and should not, be injected to document.body, as we inject on hover to ensure React hydration works as expected.\n * @param el The HTMLElement to use as tooltip\n */\nexport const setTooltipElement = (el?: HTMLElement | null) => {\n if (el && !(el instanceof HTMLElement))\n warn('setTooltipElement expects an HTMLElement, got: ', el);\n hide(); // Reset when changing source\n LAST_HIDE = 0; // Reset last hide time to re-enable delay\n TIP = el || undefined;\n};\n\nexport const initTooltips = (\n scope: Element | ShadowRoot | Document | null = document,\n) => {\n for (const el of scope?.querySelectorAll(SELECTOR_TOOLTIP) || [])\n setupText(el);\n};\n\n// Initial run has no MutationRecords, so we set records to [null] to ensure we run the querySelectorAll for any existing elements with data-tooltip\nconst handleMutations = (_: Document, records?: MutationRecord[]) => {\n if (!records) return initTooltips();\n for (const r of records) {\n if (r.target === TIP) continue; // Ignore mutations on tooltip itself\n if (r.attributeName === ATTR_TOOLTIP) setupText(r.target as Element);\n else\n for (const el of r.addedNodes as NodeListOf<Element>) {\n if (el.nodeType !== 1) continue;\n if (el.hasAttribute(ATTR_TOOLTIP)) setupText(el);\n else initTooltips(el); // Check for any child elements with data-tooltip\n }\n }\n};\n\nconst setupText = (el: Element, canAnnounce = true) => {\n let text = attrOrCSS(el, ATTR_TOOLTIP) || '';\n\n // Allow using another element as source.\n // Note: Only checks on initial mutation, as we do not want to keep checking if the source element is removed or changed,\n // since this would be a performance issue. If the source element is removed, the tooltip will be empty and not shown.\n if (text[0] === '#')\n text = getRoot(el).getElementById(text.slice(1))?.textContent?.trim() || '';\n\n if (text !== (el.getAttribute(ARIA_LABEL) || el.getAttribute(ARIA_DESC))) {\n const hasText = attr(el, 'role') !== 'img' && el.textContent?.trim(); // If role=\"img\", ignore text\n attr(el, ATTR_TOOLTIP, text); // Set data-tooltip attribute to speed up future mutations\n attr(el, ARIA_LABEL, hasText ? null : text); // Set aria-label if element does not have text\n attr(el, ARIA_DESC, hasText ? text : null); // Set aria-description if element has text\n if ((el as HTMLElement).tabIndex === -1)\n warn('Missing tabindex=\"0\" attribute on: ', el);\n }\n if (el === OPEN && TIP?.textContent !== text) {\n if (TIP) TIP.textContent = text; // Update tooltip text if it is already open\n if (text && canAnnounce && document.activeElement === el) announce(text); // Only announce if focus is on the source\n }\n};\n\nconst handleInterest = (e: Event) => {\n const target = getComposedTarget(e);\n if (!target || TARGET === target || TIP?.contains(target as Node)) return; // Same target, or allow tooltip to be hovered (following https://www.w3.org/TR/WCAG21/#content-on-hover-or-focus)\n TARGET = target;\n\n const source = TARGET?.closest?.(SELECTOR_TOOLTIP) || undefined;\n if (OPEN === source) return; // Same source, no need to update\n if (OPEN) hide(); // Reset previous tooltip, since we are moving to a new source\n OPEN = source;\n\n if (!source) return; // No source, no need to show tooltip\n if (e.type === 'focus' || IS_IOS || DELAY_SKIP > Date.now() - LAST_HIDE)\n return show(); // Instantly show if focus or if we just closed a tooltip\n if (e.type === 'mousemove') TIMER = setTimeout(show, DELAY_HOVER); // Delay mouse showing tooltip if not already shown\n};\n\nconst show = () => {\n if (!OPEN) return hide(); // If no new anchor, cleanup previous autoUpdate\n if (!TIP) TIP = tag('div', { class: 'ds-tooltip' });\n if (!TIP.isConnected) document.body.appendChild(TIP);\n\n const color = OPEN.closest(SELECTOR_COLOR); // Match source color of source element\n const scheme = OPEN.closest(SELECTOR_SCHEME); // Match source color-scheme of source element\n const size = OPEN.closest(SELECTOR_SIZE); // Match source size of source element\n const isReset = color !== scheme && color?.contains(scheme as Node); // If data-scheme is closer to target, it will reset data-color\n\n attr(TIP, 'popover', 'manual'); // Ensure popover behavior\n attr(TIP, ATTR_SCHEME, scheme?.getAttribute(ATTR_SCHEME) || null); // Fallback to null to reset if not scheme found\n attr(TIP, ATTR_COLOR, (isReset && color?.getAttribute(ATTR_COLOR)) || null); // Fallback to null to reset if not scheme found\n attr(TIP, ATTR_SIZE, size?.getAttribute(ATTR_SIZE) || null); // Fallback to null to reset if not size found\n setupText(OPEN, false); // If mutation observer is not triggered, ensure tooltip text is updated\n TIP.showPopover();\n TIP.dispatchEvent(\n new CustomEvent('ds-toggle-source', {\n bubbles: true,\n composed: true, // Enable bubbling out of shadow DOM boundaries\n detail: OPEN, // Since showPopover({ source }) is not supported in all browsers yet\n }),\n );\n};\n\nconst hide = (event?: Partial<KeyboardEvent>) => {\n if (event?.type === 'keydown' && event?.key !== 'Escape') return;\n if (OPEN && TIP?.isConnected && TIP.popover) TIP.hidePopover(); // Only hide if connected and activated\n if (!event) LAST_HIDE = Date.now(); // If closing with keyboard, do not show next tooltip instantly\n clearTimeout(TIMER);\n OPEN = undefined;\n};\n\nonHotReload('tooltip', () => [\n on(document, 'focus mousemove', handleInterest, QUICK_EVENT),\n on(document, 'keydown', hide, QUICK_EVENT),\n onMutation(document, handleMutations, {\n attributeFilter: [ATTR_TOOLTIP],\n attributes: true,\n childList: true,\n subtree: true,\n }),\n]);\n"],"mappings":"mQAkBA,IAAI,EACA,EACA,EACA,EACA,EAAY,EAChB,MAAM,EAAa,aACb,EAAc,oBACd,EAAY,YACZ,EAAe,eAGf,EAAS,EAAU,GAAK,mBAAmB,KAAK,UAAU,SAAS,EACnE,EAAiB,IAAI,EAAW,GAChC,EAAkB,IAAI,EAAY,GAClC,EAAgB,IAAI,EAAU,GAC9B,EAAmB,IAAI,EAAa,GAO7B,EAAqB,GAA4B,CACxD,GAAM,EAAE,aAAc,cACxB,EAAK,kDAAmD,CAAE,EAC5D,EAAK,EACL,EAAY,EACZ,EAAM,GAAM,IAAA,EACd,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W,GAAU,IAAa,KAAK,IAAI,EAAI,EAC5D,OAAO,EAAK,EACV,EAAE,OAAS,cAAa,EAAQ,WAAW,EAAM,GAAW,EADlD,CAEhB,EAEM,MAAa,CACjB,GAAI,CAAC,EAAM,OAAO,EAAK,EACvB,AAAU,IAAM,EAAI,MAAO,CAAE,MAAO,YAAa,CAAC,EAC7C,EAAI,aAAa,SAAS,KAAK,YAAY,CAAG,EAEnD,IAAM,EAAQ,EAAK,QAAQ,CAAc,EACnC,EAAS,EAAK,QAAQ,CAAe,EACrC,EAAO,EAAK,QAAQ,CAAa,EACjC,EAAU,IAAU,GAAU,GAAO,SAAS,CAAc,EAElE,EAAK,EAAK,UAAW,QAAQ,EAC7B,EAAK,EAAK,EAAa,GAAQ,aAAa,CAAW,GAAK,IAAI,EAChE,EAAK,EAAK,EAAa,GAAW,GAAO,aAAa,CAAU,GAAM,IAAI,EAC1E,EAAK,EAAK,EAAW,GAAM,aAAa,CAAS,GAAK,IAAI,EAC1D,EAAU,EAAM,EAAK,EACrB,EAAI,YAAY,EAChB,EAAI,cACF,IAAI,YAAY,mBAAoB,CAClC,QAAS,GACT,SAAU,GACV,OAAQ,CACV,CAAC,CACH,CACF,EAEM,EAAQ,GAAmC,EAC3C,GAAO,OAAS,WAAa,GAAO,MAAQ,YAC5C,GAAQ,GAAK,aAAe,EAAI,SAAS,EAAI,YAAY,EACxD,IAAO,EAAY,KAAK,IAAI,GACjC,aAAa,CAAK,EAClB,EAAO,IAAA,GACT,EAEA,EAAY,cAAiB,CAC3B,EAAG,SAAU,kBAAmB,EAAgB,CAAW,EAC3D,EAAG,SAAU,UAAW,EAAM,CAAW,EACzC,EAAW,SAAU,EAAiB,CACpC,gBAAiB,CAAC,CAAY,EAC9B,WAAY,GACZ,UAAW,GACX,QAAS,EACX,CAAC,CACH,CAAC"}
1
+ {"version":3,"file":"tooltip.js","names":[],"sources":["../../../src/tooltip/tooltip.ts"],"sourcesContent":["import '../popover/popover'; // Ensure popover is imported when using individual imports, since tooltip relies on it\nimport {\n ARIA_DESC,\n ARIA_LABEL,\n announce,\n attr,\n attrOrCSS,\n getComposedTarget,\n getRoot,\n isBrowser,\n on,\n onHotReload,\n onMutation,\n QUICK_EVENT,\n tag,\n warn,\n} from '../utils/utils';\n\nlet TIP: HTMLElement | undefined;\nlet TIMER: ReturnType<typeof setTimeout> | undefined;\nlet TARGET: Element | undefined; // Used to speed up mousemove handling\nlet OPEN: Element | undefined;\nlet LAST_HIDE = 0;\nconst ATTR_COLOR = 'data-color';\nconst ATTR_SCHEME = 'data-color-scheme';\nconst ATTR_SIZE = 'data-size';\nconst ATTR_TOOLTIP = 'data-tooltip';\nconst DELAY_HOVER = 300;\nconst DELAY_SKIP = 300;\nconst IS_IOS = isBrowser() && /iPad|iPhone|iPod/.test(navigator.userAgent); // Needed to omit DELAY_HOVER since iOS triggers mousemove before click\nconst SELECTOR_COLOR = `[${ATTR_COLOR}]`;\nconst SELECTOR_SCHEME = `[${ATTR_SCHEME}]`;\nconst SELECTOR_SIZE = `[${ATTR_SIZE}]`;\nconst SELECTOR_TOOLTIP = `[${ATTR_TOOLTIP}]`;\n\n/**\n * setTooltipElement\n * @description Allows setting a custom tooltip element. It does not need to, and should not, be injected to document.body, as we inject on hover to ensure React hydration works as expected.\n * @param el The HTMLElement to use as tooltip\n */\nexport const setTooltipElement = (el?: HTMLElement | null) => {\n if (el && !(el instanceof HTMLElement))\n warn('setTooltipElement expects an HTMLElement, got: ', el);\n hide(); // Reset when changing source\n LAST_HIDE = 0; // Reset last hide time to re-enable delay\n TIP = el || undefined;\n};\n\nexport const initTooltips = (\n scope: Element | ShadowRoot | Document | null = document,\n) => {\n for (const el of scope?.querySelectorAll(SELECTOR_TOOLTIP) || [])\n setupText(el);\n};\n\n// Initial run has no MutationRecords, so we set records to [null] to ensure we run the querySelectorAll for any existing elements with data-tooltip\nconst handleMutations = (_: Document, records?: MutationRecord[]) => {\n if (!records) return initTooltips();\n for (const r of records) {\n if (r.target === TIP) continue; // Ignore mutations on tooltip itself\n if (r.attributeName === ATTR_TOOLTIP) setupText(r.target as Element);\n else\n for (const el of r.addedNodes as NodeListOf<Element>) {\n if (el.nodeType !== 1) continue;\n if (el.hasAttribute(ATTR_TOOLTIP)) setupText(el);\n else initTooltips(el); // Check for any child elements with data-tooltip\n }\n }\n};\n\nconst setupText = (el: Element, canAnnounce = true) => {\n let text = attrOrCSS(el, ATTR_TOOLTIP) || '';\n\n // Allow using another element as source.\n // Note: Only checks on initial mutation, as we do not want to keep checking if the source element is removed or changed,\n // since this would be a performance issue. If the source element is removed, the tooltip will be empty and not shown.\n if (text[0] === '#')\n text = getRoot(el).getElementById(text.slice(1))?.textContent?.trim() || '';\n\n if (text !== (el.getAttribute(ARIA_LABEL) || el.getAttribute(ARIA_DESC))) {\n const hasText = attr(el, 'role') !== 'img' && el.textContent?.trim(); // If role=\"img\", ignore text\n attr(el, ATTR_TOOLTIP, text); // Set data-tooltip attribute to speed up future mutations\n attr(el, ARIA_LABEL, hasText ? null : text); // Set aria-label if element does not have text\n attr(el, ARIA_DESC, hasText ? text : null); // Set aria-description if element has text\n\n if (\n (el as HTMLElement).tabIndex === -1 && // Default tabindex property of all Elements is -1\n !el.hasAttribute('tabindex') && // But we want to allow attribute set to tabindex=\"-1\" for example in focus groups\n el.nodeName !== 'LABEL' // And labels will have focusable inputs, so their text is reactable anyway\n )\n warn('Missing tabindex=\"0\" attribute on: ', el);\n }\n if (el === OPEN && TIP?.textContent !== text) {\n if (TIP) TIP.textContent = text; // Update tooltip text if it is already open\n if (text && canAnnounce && document.activeElement === el) announce(text); // Only announce if focus is on the source\n }\n};\n\nconst handleInterest = (e: Event) => {\n const target = getComposedTarget(e);\n if (!target || TARGET === target || TIP?.contains(target as Node)) return; // Same target, or allow tooltip to be hovered (following https://www.w3.org/TR/WCAG21/#content-on-hover-or-focus)\n TARGET = target;\n\n const source = TARGET?.closest?.(SELECTOR_TOOLTIP) || undefined;\n if (OPEN === source) return; // Same source, no need to update\n if (OPEN) hide(); // Reset previous tooltip, since we are moving to a new source\n OPEN = source;\n\n if (!source) return; // No source, no need to show tooltip\n if (e.type === 'focus' || IS_IOS || DELAY_SKIP > Date.now() - LAST_HIDE)\n return show(); // Instantly show if focus or if we just closed a tooltip\n if (e.type === 'mousemove') TIMER = setTimeout(show, DELAY_HOVER); // Delay mouse showing tooltip if not already shown\n};\n\nconst show = () => {\n if (!OPEN) return hide(); // If no new anchor, cleanup previous autoUpdate\n if (!TIP) TIP = tag('div', { class: 'ds-tooltip' });\n if (!TIP.isConnected) document.body.appendChild(TIP);\n\n const color = OPEN.closest(SELECTOR_COLOR); // Match source color of source element\n const scheme = OPEN.closest(SELECTOR_SCHEME); // Match source color-scheme of source element\n const size = OPEN.closest(SELECTOR_SIZE); // Match source size of source element\n const isReset = color !== scheme && color?.contains(scheme as Node); // If data-scheme is closer to target, it will reset data-color\n\n attr(TIP, 'popover', 'manual'); // Ensure popover behavior\n attr(TIP, ATTR_SCHEME, scheme?.getAttribute(ATTR_SCHEME) || null); // Fallback to null to reset if not scheme found\n attr(TIP, ATTR_COLOR, (isReset && color?.getAttribute(ATTR_COLOR)) || null); // Fallback to null to reset if not scheme found\n attr(TIP, ATTR_SIZE, size?.getAttribute(ATTR_SIZE) || null); // Fallback to null to reset if not size found\n setupText(OPEN, false); // If mutation observer is not triggered, ensure tooltip text is updated\n TIP.showPopover();\n TIP.dispatchEvent(\n new CustomEvent('ds-toggle-source', {\n bubbles: true,\n composed: true, // Enable bubbling out of shadow DOM boundaries\n detail: OPEN, // Since showPopover({ source }) is not supported in all browsers yet\n }),\n );\n};\n\nconst hide = (event?: Partial<KeyboardEvent>) => {\n if (event?.type === 'keydown' && event?.key !== 'Escape') return;\n if (OPEN && TIP?.isConnected && TIP.popover) TIP.hidePopover(); // Only hide if connected and activated\n if (!event) LAST_HIDE = Date.now(); // If closing with keyboard, do not show next tooltip instantly\n clearTimeout(TIMER);\n OPEN = undefined;\n};\n\nonHotReload('tooltip', () => [\n on(document, 'focus mousemove', handleInterest, QUICK_EVENT),\n on(document, 'keydown', hide, QUICK_EVENT),\n onMutation(document, handleMutations, {\n attributeFilter: [ATTR_TOOLTIP],\n attributes: true,\n childList: true,\n subtree: true,\n }),\n]);\n"],"mappings":"mQAkBA,IAAI,EACA,EACA,EACA,EACA,EAAY,EAChB,MAAM,EAAa,aACb,EAAc,oBACd,EAAY,YACZ,EAAe,eAGf,EAAS,EAAU,GAAK,mBAAmB,KAAK,UAAU,SAAS,EACnE,EAAiB,IAAI,EAAW,GAChC,EAAkB,IAAI,EAAY,GAClC,EAAgB,IAAI,EAAU,GAC9B,EAAmB,IAAI,EAAa,GAO7B,EAAqB,GAA4B,CACxD,GAAM,EAAE,aAAc,cACxB,EAAK,kDAAmD,CAAE,EAC5D,EAAK,EACL,EAAY,EACZ,EAAM,GAAM,IAAA,EACd,EAEa,GACX,EAAgD,WAC7C,CACH,IAAK,IAAM,KAAM,GAAO,iBAAiB,CAAgB,GAAK,CAAC,EAC7D,EAAU,CAAE,CAChB,EAGM,GAAmB,EAAa,IAA+B,CACnE,GAAI,CAAC,EAAS,OAAO,EAAa,EAClC,IAAK,IAAM,KAAK,EACV,KAAE,SAAW,EACjB,GAAI,EAAE,gBAAkB,EAAc,EAAU,EAAE,MAAiB,OAEjE,IAAK,IAAM,KAAM,EAAE,WACb,EAAG,WAAa,IAChB,EAAG,aAAa,CAAY,EAAG,EAAU,CAAE,EAC1C,EAAa,CAAE,EAG5B,EAEM,GAAa,EAAa,EAAc,KAAS,CACrD,IAAI,EAAO,EAAU,EAAI,CAAY,GAAK,GAQ1C,GAHI,EAAK,KAAO,MACd,EAAO,EAAQ,CAAE,CAAC,CAAC,eAAe,EAAK,MAAM,CAAC,CAAC,CAAC,EAAE,aAAa,KAAK,GAAK,IAEvE,KAAU,EAAG,aAAA,YAAuB,GAAK,EAAG,aAAA,kBAAsB,GAAI,CACxE,IAAM,EAAU,EAAK,EAAI,MAAM,IAAM,OAAS,EAAG,aAAa,KAA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AChB,EAAI,cACF,IAAI,YAAY,mBAAoB,CAClC,QAAS,GACT,SAAU,GACV,OAAQ,CACV,CAAC,CACH,CACF,EAEM,EAAQ,GAAmC,EAC3C,GAAO,OAAS,WAAa,GAAO,MAAQ,YAC5C,GAAQ,GAAK,aAAe,EAAI,SAAS,EAAI,YAAY,EACxD,IAAO,EAAY,KAAK,IAAI,GACjC,aAAa,CAAK,EAClB,EAAO,IAAA,GACT,EAEA,EAAY,cAAiB,CAC3B,EAAG,SAAU,kBAAmB,EAAgB,CAAW,EAC3D,EAAG,SAAU,UAAW,EAAM,CAAW,EACzC,EAAW,SAAU,EAAiB,CACpC,gBAAiB,CAAC,CAAY,EAC9B,WAAY,GACZ,UAAW,GACX,QAAS,EACX,CAAC,CACH,CAAC"}
@@ -1,2 +1,2 @@
1
- import{version as e}from"../packages/web/package.js";const t=`aria-description`,n=`aria-label`,r=`aria-labelledby`,i={passive:!0,capture:!0},a=()=>typeof window<`u`&&typeof document<`u`,o=()=>a()&&/^Win/i.test(navigator.userAgentData?.platform||navigator.platform),s=typeof HTMLElement>`u`?class{}:HTMLElement;function c(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>e.apply(this,r),t)}}const l=(e,...t)=>!a()||window.dsWarnings===!1||console.log(`\x1B[1mDesignsystemet:\x1B[m ${e}`,...t),u=(e,t,n)=>n===void 0?e.getAttribute(t):(n===null?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n),null),d=(e,t)=>getComputedStyle(e).getPropertyValue(t).trim(),f=/^["']|["']$/g,p=(e,t)=>{let n=u(e,t);return n||=d(e,`--_ds-${t}`).replace(f,``).trim(),n||null},m=e=>{let t=e?.getRootNode?.()||e?.ownerDocument;return t instanceof Document||t instanceof ShadowRoot?t:e?.ownerDocument||document},h=e=>{let t=e.target?.shadowRoot&&e.composedPath()[0]||e.target;return t?.nodeType===1?t:null},g=e=>{let t=new Set;for(;e;)t.add(e),e=e.nodeType===11?e.host:e.assignedSlot||e.parentNode;return t},_=(e,...t)=>{let[n,...r]=t;for(let t of n.split(` `))e.addEventListener(t,...r);return()=>v(e,...t)},v=(e,...t)=>{let[n,...r]=t;for(let t of n.split(` `))e.removeEventListener(t,...r)},y=`_dsHotReloadCleanup${e}`,b=(e,t)=>{if(a()){window[y]||(window[y]=new Map);for(let t of window[y]?.get(e)||[])t();window[y]?.set(e,t())}},x=(e,t,n)=>{let r=()=>i.disconnect(),i=new MutationObserver(n=>{if(!a()||!e.isConnected)return r();t(e,n)});return t(e),i.observe(e,n),r},S=(e,t)=>{let n=document.createElement(e);if(t)for(let[e,r]of Object.entries(t))u(n,e,r);return n},C={define:(e,t)=>!a()||window.customElements.get(e)||window.customElements.define(e,t)};let w=0;function T(e){return a()?(window.dsUseId||(window.dsUseId=0),e&&!e.id&&(e.id=`:ds:${++window.dsUseId}`),e?.id||``):`:ds:${++w}`}let E,D=0,O=0;const k=e=>{clearTimeout(O),E&&(E.textContent=`${e}${D++%2?`\xA0`:``}`),e&&(O=setTimeout(k,2e3,``))},A=()=>{document.readyState===`complete`&&(E||(E=S(`div`,{"aria-live":`assertive`}),E.style.overflow=`hidden`,E.style.position=`fixed`,E.style.whiteSpace=`nowrap`,E.style.width=`1px`),E.isConnected||document.body.appendChild(E))};b(`announce`,()=>[_(document,`focus mouseover`,A,i)]);export{t as ARIA_DESC,n as ARIA_LABEL,r as ARIA_LABELLEDBY,s as DSElement,i as QUICK_EVENT,k as announce,u as attr,p as attrOrCSS,C as customElements,c as debounce,d as getCSSProp,g as getComposedPath,h as getComposedTarget,m as getRoot,a as isBrowser,o as isWindows,v as off,_ as on,b as onHotReload,x as onMutation,S as tag,T as useId,l as warn};
1
+ import{version as e}from"../packages/web/package.js";const t=`aria-description`,n=`aria-label`,r=`aria-labelledby`,i={passive:!0,capture:!0},a=()=>typeof window<`u`&&typeof document<`u`,o=()=>a()&&/^Win/i.test(navigator.userAgentData?.platform||navigator.platform),s=typeof HTMLElement>`u`?class{}:HTMLElement;function c(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>e.apply(this,r),t)}}const l=(e,...t)=>!a()||window.dsWarnings===!1||console.log(`\x1B[1mDesignsystemet:\x1B[m ${e}`,...t),u=(e,t,n)=>n===void 0?e.getAttribute(t):(n===null?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n),null),d=(e,t)=>getComputedStyle(e).getPropertyValue(t).trim(),f=/^["']|["']$/g,p=/\\(["'])/g,m=(e,t)=>{let n=u(e,t);return n||=d(e,`--_ds-${t}`).replace(f,``).replace(p,`$1`).trim(),n||null},h=e=>{let t=e?.getRootNode?.()||e?.ownerDocument;return t instanceof Document||t instanceof ShadowRoot?t:e?.ownerDocument||document},g=e=>{let t=e.target?.shadowRoot&&e.composedPath()[0]||e.target;return t?.nodeType===1?t:null},_=e=>{let t=new Set;for(;e;)t.add(e),e=e.nodeType===11?e.host:e.assignedSlot||e.parentNode;return t},v=(e,...t)=>{let[n,...r]=t;for(let t of n.split(` `))e.addEventListener(t,...r);return()=>y(e,...t)},y=(e,...t)=>{let[n,...r]=t;for(let t of n.split(` `))e.removeEventListener(t,...r)},b=`_dsHotReloadCleanup${e}`,x=(e,t)=>{if(a()){window[b]||(window[b]=new Map);for(let t of window[b]?.get(e)||[])t();window[b]?.set(e,t())}},S=(e,t,n)=>{let r=()=>i.disconnect(),i=new MutationObserver(n=>{if(!a()||!e.isConnected)return r();t(e,n)});return t(e),i.observe(e,n),r},C=(e,t)=>{let n=document.createElement(e);if(t)for(let[e,r]of Object.entries(t))u(n,e,r);return n},w={define:(e,t)=>!a()||window.customElements.get(e)||window.customElements.define(e,t)};let T=0;function E(e){return a()?(window.dsUseId||(window.dsUseId=0),e&&!e.id&&(e.id=`:ds:${++window.dsUseId}`),e?.id||``):`:ds:${++T}`}let D,O=0,k=0;const A=e=>{clearTimeout(k),D&&(D.textContent=`${e}${O++%2?`\xA0`:``}`),e&&(k=setTimeout(A,2e3,``))},j=()=>{document.readyState===`complete`&&(D||(D=C(`div`,{"aria-live":`assertive`}),D.style.overflow=`hidden`,D.style.position=`fixed`,D.style.whiteSpace=`nowrap`,D.style.width=`1px`),D.isConnected||document.body.appendChild(D))};x(`announce`,()=>[v(document,`focus mouseover`,j,i)]);export{t as ARIA_DESC,n as ARIA_LABEL,r as ARIA_LABELLEDBY,s as DSElement,i as QUICK_EVENT,A as announce,u as attr,m as attrOrCSS,w as customElements,c as debounce,d as getCSSProp,_ as getComposedPath,g as getComposedTarget,h as getRoot,a as isBrowser,o as isWindows,y as off,v as on,x as onHotReload,S as onMutation,C as tag,E as useId,l as warn};
2
2
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../../../src/utils/utils.ts"],"sourcesContent":["export const ARIA_DESC = 'aria-description';\nexport const ARIA_LABEL = 'aria-label';\nexport const ARIA_LABELLEDBY = 'aria-labelledby';\nexport const QUICK_EVENT = { passive: true, capture: true };\n\nimport { version } from '../../package.json' with { type: 'json' };\n\n// Using function instead of constant to support environments where DOM can be unloaded (like Vitest with jsdom)\nexport const isBrowser = () =>\n typeof window !== 'undefined' && typeof document !== 'undefined';\n\nexport const isWindows = () =>\n isBrowser() &&\n // @ts-expect-error Typescript has not implemented userAgentData yet https://stackoverflow.com/a/71392474\n /^Win/i.test(navigator.userAgentData?.platform || navigator.platform);\n\n// Make sure we have a HTMLElement to extend (for server side rendering)\nexport const DSElement =\n typeof HTMLElement === 'undefined'\n ? (class {} as typeof HTMLElement)\n : HTMLElement;\n\nexport function debounce<T extends unknown[]>(\n callback: (...args: T) => void,\n delay: number,\n) {\n let timer: ReturnType<typeof setTimeout>;\n\n return function (this: unknown, ...args: T) {\n clearTimeout(timer);\n timer = setTimeout(() => callback.apply(this, args), delay);\n };\n}\n\n/**\n * warn\n * @description Utility to console.log, but can be silenced in production with window.dsWarnings = false;\n */\ndeclare global {\n interface Window {\n dsWarnings?: boolean;\n }\n}\nexport const warn = (\n message: string,\n ...args: Parameters<typeof console.log> // Using console.log, not console.warn, to prevent stopping test runners such as Jest\n) =>\n !isBrowser() ||\n window.dsWarnings === false ||\n console.log(`\\x1B[1mDesignsystemet:\\x1B[m ${message}`, ...args);\n\n/**\n * attr\n * @description Utility to quickly get, set and remove attributes\n * @param el The Element to read/write attributes from\n * @param name The attribute name to get, set or remove, or a object to set multiple attributes\n * @param value A valid attribute value or null to remove attribute\n */\nexport const attr = (\n el: Element,\n name: string,\n value?: string | null,\n): string | null => {\n if (value === undefined) return el.getAttribute(name);\n if (value === null) el.removeAttribute(name);\n else if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n return null;\n};\n\n/**\n * getCSSProp\n * @description Retrieves and CSS property value and trims it\n * @param el The Element to read attributes/CSS from\n * @param name Attribute or CSS property to get\n * @return string CSS property value\n */\nexport const getCSSProp = (el: Element, prop: string) =>\n getComputedStyle(el).getPropertyValue(prop).trim();\n\nconst STRIP_QUOTES = /^[\"']|[\"']$/g; // Matches surrounding single or double quotes\n/**\n * attrOrCSS\n * @description Retrieves and updates attribute based on attribute or CSS property value\n * @param el The Element to read attributes/CSS from\n * @param name Attribute or CSS property to get\n * @return string attribute or CSS property value\n */\nexport const attrOrCSS = (el: Element, name: string) => {\n let value = attr(el, name);\n if (!value)\n value = getCSSProp(el, `--_ds-${name}`).replace(STRIP_QUOTES, '').trim();\n return value || null;\n};\n\n/**\n * getRoot\n * @description Helper for better compatibility\n * @param node The target node\n * @return The shadow root or document\n */\nexport const getRoot = (node?: Node | null): Document | ShadowRoot => {\n const root = node?.getRootNode?.() || node?.ownerDocument;\n if (root instanceof Document || root instanceof ShadowRoot) return root;\n return node?.ownerDocument || document;\n};\n\n/**\n * getComposedTarget\n * @description Helper to get the composed target of an event, supporting ShadowDOM rendering\n * @param event The event\n * @return The target Element\n */\nexport const getComposedTarget = (e: Event): Element | null => {\n const el =\n ((e.target as Element)?.shadowRoot && e.composedPath()[0]) || e.target; // Only use composedPath if the target has a shadowRoot to boost performance\n return (el as Node)?.nodeType === 1 ? (el as Element) : null;\n};\n\n/**\n * getComposedPath\n * @description Helper to get the full composed path even if listener is bound to a ShadowRoot (unlike event.composedPath())\n * @param el The element to start traversing from\n * @return Set of nodes in the path\n */\nexport const getComposedPath = (el: Node | null) => {\n const path = new Set<Node>();\n while (el) {\n path.add(el);\n if (el.nodeType === 11) el = (el as ShadowRoot).host;\n else el = (el as Element).assignedSlot || el.parentNode;\n }\n return path;\n};\n\n/**\n * on\n * @param el The Element to use as EventTarget\n * @param types A space separated string of event types\n * @param listener An event listener function or listener object\n */\nexport const on = (\n el: Node | Window | ShadowRoot,\n ...rest: Parameters<typeof Element.prototype.addEventListener>\n): (() => void) => {\n const [types, ...options] = rest;\n for (const type of types.split(' ')) el.addEventListener(type, ...options);\n return () => off(el, ...rest);\n};\n\n/**\n * off\n * @param el The Element to use as EventTarget\n * @param types A space separated string of event types\n * @param listener An event listener function or listener object\n */\nexport const off = (\n el: Node | Window | ShadowRoot,\n ...rest: Parameters<typeof Element.prototype.removeEventListener>\n): void => {\n const [types, ...options] = rest;\n for (const type of types.split(' ')) el.removeEventListener(type, ...options);\n};\n\n// Used to store cleanup functions for hot-reloading\nconst HOT_RELOAD_KEY = `_dsHotReloadCleanup${version}` as const; // Ensure multiple versions of Designsystemet can run on same page\ndeclare global {\n interface Window {\n [HOT_RELOAD_KEY]?: Map<string, Array<() => void>>;\n }\n}\n\n/**\n * onHotReload\n * @description Runs a callback when window is loaded in browser, and ensures cleanup when hot-reloading\n * @param key The key to identify setup and corresponding cleanup\n * @param callback The callback to run when the page is ready\n */\nexport const onHotReload = (key: string, setup: () => Array<() => void>) => {\n if (!isBrowser()) return; // Skip if not in modern browser environment, but on each call as Vitest might have unloaded jsdom between tests\n if (!window[HOT_RELOAD_KEY]) window[HOT_RELOAD_KEY] = new Map(); // Hot reload cleanup support supporting all build tools\n for (const cleanup of window[HOT_RELOAD_KEY]?.get(key) || []) cleanup(); // Run previous cleanup\n window[HOT_RELOAD_KEY]?.set(key, setup()); // Store new cleanup\n};\n\n/**\n * MutationObserver wrapper with automatic cleanup\n * @return new MutaionObserver\n */\nexport const onMutation = <T extends Node>(\n el: T,\n callback: (el: T, records?: MutationRecord[]) => void,\n options: MutationObserverInit,\n) => {\n const cleanup = () => observer.disconnect();\n const observer = new MutationObserver((records) => {\n if (!isBrowser() || !el.isConnected) return cleanup(); // Stop observing if element is removed from DOM or document is removed by jdsom tests\n callback(el, records);\n });\n\n callback(el); // Initial is run instantly to make test markup predictable\n observer.observe(el, options);\n return cleanup;\n};\n\n/**\n * tag\n * @description creates element and assigns properties\n * @param tagName The tagname of element to create\n * @param attrs Optional attributes to add to the element\n * @param text Optional text content to add to the element\n * @return HTMLElement with props\n */\nexport const tag = <TagName extends keyof HTMLElementTagNameMap>(\n tagName: TagName,\n attrs?: Record<string, string | null> | null,\n): HTMLElementTagNameMap[TagName] => {\n const el = document.createElement(tagName);\n if (attrs) for (const [key, val] of Object.entries(attrs)) attr(el, key, val);\n return el;\n};\n\n/**\n * customElements.define\n * @description Defines a customElement if running in browser and if not already registered\n * Scoped/named \"customElements.define\" so @custom-elements-manifest/analyzer can find tag names\n */\nexport const customElements = {\n define: (name: string, instance: CustomElementConstructor) =>\n !isBrowser() ||\n window.customElements.get(name) ||\n window.customElements.define(name, instance),\n};\n\n/**\n * useId\n * @return A generated unique ID\n */\ndeclare global {\n interface Window {\n dsUseId?: number; // Use a global counter to ensure this works even when loading designsystemet multiple times\n }\n}\nlet id = 0;\nexport function useId(el?: Element | null) {\n if (!isBrowser()) return `:ds:${++id}`; // Emulate browser environment if window not available\n if (!window.dsUseId) window.dsUseId = 0; // Make sure we have a global to support multiple instances of designsystemet in same page\n if (el && !el.id) el.id = `:ds:${++window.dsUseId}`;\n return el?.id || '';\n}\n\n/**\n * @description Based off speak function from [U-elements](https://github.com/u-elements/u-elements/blob/main/packages/utils.ts#L210)\n * @param text The text to announce\n */\nlet LIVE_EL: HTMLElement | undefined;\nlet LIVE_FIX = 0;\nlet LIVE_CLEAR: ReturnType<typeof setTimeout> | number = 0;\nexport const announce = (text: string) => {\n clearTimeout(LIVE_CLEAR);\n if (LIVE_EL) LIVE_EL.textContent = `${text}${LIVE_FIX++ % 2 ? '\\u00A0' : ''}`; // Non-breaking space to ensure screen reader announces\n if (text) LIVE_CLEAR = setTimeout(announce, 2000, ''); // Clear prevent old announcements being found by screen readers, with 2 seconds brace period to avoid cutting of Android Talkback\n};\n\n// Mount live region on first focus so its ready to be used\nconst announceMount = () => {\n if (document.readyState !== 'complete') return; // Ensure page is loaded trying to avoid issues with React hydration\n if (!LIVE_EL) {\n LIVE_EL = tag('div', { 'aria-live': 'assertive' });\n LIVE_EL.style.overflow = 'hidden'; // Settings styles individually to prevent issues with CSP\n LIVE_EL.style.position = 'fixed';\n LIVE_EL.style.whiteSpace = 'nowrap';\n LIVE_EL.style.width = '1px';\n }\n if (!LIVE_EL.isConnected) document.body.appendChild(LIVE_EL);\n};\nonHotReload('announce', () => [\n on(document, 'focus mouseover', announceMount, QUICK_EVENT),\n]);\n"],"mappings":"qDAAA,MAAa,EAAY,mBACZ,EAAa,aACb,EAAkB,kBAClB,EAAc,CAAE,QAAS,GAAM,QAAS,EAAK,EAK7C,MACX,OAAO,OAAW,KAAe,OAAO,SAAa,IAE1C,MACX,EAAU,GAEV,QAAQ,KAAK,UAAU,eAAe,UAAY,UAAU,QAAQ,EAGzD,EACX,OAAO,YAAgB,IAClB,KAAM,CAAC,EACR,YAEN,SAAgB,EACd,EACA,EACA,CACA,IAAI,EAEJ,OAAO,SAAyB,GAAG,EAAS,CAC1C,aAAa,CAAK,EAClB,EAAQ,eAAiB,EAAS,MAAM,KAAM,CAAI,EAAG,CAAK,CAC5D,CACF,CAWA,MAAa,GACX,EACA,GAAG,IAEH,CAAC,EAAU,GACX,OAAO,aAAe,IACtB,QAAQ,IAAI,gCAAgC,IAAW,GAAG,CAAI,EASnD,GACX,EACA,EACA,IAEI,IAAU,IAAA,GAAkB,EAAG,aAAa,CAAI,GAChD,IAA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AM,WAAa,SAC3B,EAAQ,MAAM,MAAQ,OAEnB,EAAQ,aAAa,SAAS,KAAK,YAAY,CAAO,EAC7D,EACA,EAAY,eAAkB,CAC5B,EAAG,SAAU,kBAAmB,EAAe,CAAW,CAC5D,CAAC"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../../../src/utils/utils.ts"],"sourcesContent":["export const ARIA_DESC = 'aria-description';\nexport const ARIA_LABEL = 'aria-label';\nexport const ARIA_LABELLEDBY = 'aria-labelledby';\nexport const QUICK_EVENT = { passive: true, capture: true };\n\nimport { version } from '../../package.json' with { type: 'json' };\n\n// Using function instead of constant to support environments where DOM can be unloaded (like Vitest with jsdom)\nexport const isBrowser = () =>\n typeof window !== 'undefined' && typeof document !== 'undefined';\n\nexport const isWindows = () =>\n isBrowser() &&\n // @ts-expect-error Typescript has not implemented userAgentData yet https://stackoverflow.com/a/71392474\n /^Win/i.test(navigator.userAgentData?.platform || navigator.platform);\n\n// Make sure we have a HTMLElement to extend (for server side rendering)\nexport const DSElement =\n typeof HTMLElement === 'undefined'\n ? (class {} as typeof HTMLElement)\n : HTMLElement;\n\nexport function debounce<T extends unknown[]>(\n callback: (...args: T) => void,\n delay: number,\n) {\n let timer: ReturnType<typeof setTimeout>;\n\n return function (this: unknown, ...args: T) {\n clearTimeout(timer);\n timer = setTimeout(() => callback.apply(this, args), delay);\n };\n}\n\n/**\n * warn\n * @description Utility to console.log, but can be silenced in production with window.dsWarnings = false;\n */\ndeclare global {\n interface Window {\n dsWarnings?: boolean;\n }\n}\nexport const warn = (\n message: string,\n ...args: Parameters<typeof console.log> // Using console.log, not console.warn, to prevent stopping test runners such as Jest\n) =>\n !isBrowser() ||\n window.dsWarnings === false ||\n console.log(`\\x1B[1mDesignsystemet:\\x1B[m ${message}`, ...args);\n\n/**\n * attr\n * @description Utility to quickly get, set and remove attributes\n * @param el The Element to read/write attributes from\n * @param name The attribute name to get, set or remove, or a object to set multiple attributes\n * @param value A valid attribute value or null to remove attribute\n */\nexport const attr = (\n el: Element,\n name: string,\n value?: string | null,\n): string | null => {\n if (value === undefined) return el.getAttribute(name);\n if (value === null) el.removeAttribute(name);\n else if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n return null;\n};\n\n/**\n * getCSSProp\n * @description Retrieves and CSS property value and trims it\n * @param el The Element to read attributes/CSS from\n * @param name Attribute or CSS property to get\n * @return string CSS property value\n */\nexport const getCSSProp = (el: Element, prop: string) =>\n getComputedStyle(el).getPropertyValue(prop).trim();\n\nconst QUOTES_STRIP_SURROUNDING = /^[\"']|[\"']$/g; // Matches surrounding single or double quotes\nconst QUOTES_MATCH = /\\\\([\"'])/g;\n\n/**\n * attrOrCSS\n * @description Retrieves and updates attribute based on attribute or CSS property value\n * @param el The Element to read attributes/CSS from\n * @param name Attribute or CSS property to get\n * @return string attribute or CSS property value\n */\nexport const attrOrCSS = (el: Element, name: string) => {\n let value = attr(el, name);\n if (!value)\n value = getCSSProp(el, `--_ds-${name}`)\n .replace(QUOTES_STRIP_SURROUNDING, '')\n .replace(QUOTES_MATCH, '$1') // Unescape quotes\n .trim();\n return value || null;\n};\n\n/**\n * getRoot\n * @description Helper for better compatibility\n * @param node The target node\n * @return The shadow root or document\n */\nexport const getRoot = (node?: Node | null): Document | ShadowRoot => {\n const root = node?.getRootNode?.() || node?.ownerDocument;\n if (root instanceof Document || root instanceof ShadowRoot) return root;\n return node?.ownerDocument || document;\n};\n\n/**\n * getComposedTarget\n * @description Helper to get the composed target of an event, supporting ShadowDOM rendering\n * @param event The event\n * @return The target Element\n */\nexport const getComposedTarget = (e: Event): Element | null => {\n const el =\n ((e.target as Element)?.shadowRoot && e.composedPath()[0]) || e.target; // Only use composedPath if the target has a shadowRoot to boost performance\n return (el as Node)?.nodeType === 1 ? (el as Element) : null;\n};\n\n/**\n * getComposedPath\n * @description Helper to get the full composed path even if listener is bound to a ShadowRoot (unlike event.composedPath())\n * @param el The element to start traversing from\n * @return Set of nodes in the path\n */\nexport const getComposedPath = (el: Node | null) => {\n const path = new Set<Node>();\n while (el) {\n path.add(el);\n if (el.nodeType === 11) el = (el as ShadowRoot).host;\n else el = (el as Element).assignedSlot || el.parentNode;\n }\n return path;\n};\n\n/**\n * on\n * @param el The Element to use as EventTarget\n * @param types A space separated string of event types\n * @param listener An event listener function or listener object\n */\nexport const on = (\n el: Node | Window | ShadowRoot,\n ...rest: Parameters<typeof Element.prototype.addEventListener>\n): (() => void) => {\n const [types, ...options] = rest;\n for (const type of types.split(' ')) el.addEventListener(type, ...options);\n return () => off(el, ...rest);\n};\n\n/**\n * off\n * @param el The Element to use as EventTarget\n * @param types A space separated string of event types\n * @param listener An event listener function or listener object\n */\nexport const off = (\n el: Node | Window | ShadowRoot,\n ...rest: Parameters<typeof Element.prototype.removeEventListener>\n): void => {\n const [types, ...options] = rest;\n for (const type of types.split(' ')) el.removeEventListener(type, ...options);\n};\n\n// Used to store cleanup functions for hot-reloading\nconst HOT_RELOAD_KEY = `_dsHotReloadCleanup${version}` as const; // Ensure multiple versions of Designsystemet can run on same page\ndeclare global {\n interface Window {\n [HOT_RELOAD_KEY]?: Map<string, Array<() => void>>;\n }\n}\n\n/**\n * onHotReload\n * @description Runs a callback when window is loaded in browser, and ensures cleanup when hot-reloading\n * @param key The key to identify setup and corresponding cleanup\n * @param callback The callback to run when the page is ready\n */\nexport const onHotReload = (key: string, setup: () => Array<() => void>) => {\n if (!isBrowser()) return; // Skip if not in modern browser environment, but on each call as Vitest might have unloaded jsdom between tests\n if (!window[HOT_RELOAD_KEY]) window[HOT_RELOAD_KEY] = new Map(); // Hot reload cleanup support supporting all build tools\n for (const cleanup of window[HOT_RELOAD_KEY]?.get(key) || []) cleanup(); // Run previous cleanup\n window[HOT_RELOAD_KEY]?.set(key, setup()); // Store new cleanup\n};\n\n/**\n * MutationObserver wrapper with automatic cleanup\n * @return new MutaionObserver\n */\nexport const onMutation = <T extends Node>(\n el: T,\n callback: (el: T, records?: MutationRecord[]) => void,\n options: MutationObserverInit,\n) => {\n const cleanup = () => observer.disconnect();\n const observer = new MutationObserver((records) => {\n if (!isBrowser() || !el.isConnected) return cleanup(); // Stop observing if element is removed from DOM or document is removed by jdsom tests\n callback(el, records);\n });\n\n callback(el); // Initial is run instantly to make test markup predictable\n observer.observe(el, options);\n return cleanup;\n};\n\n/**\n * tag\n * @description creates element and assigns properties\n * @param tagName The tagname of element to create\n * @param attrs Optional attributes to add to the element\n * @param text Optional text content to add to the element\n * @return HTMLElement with props\n */\nexport const tag = <TagName extends keyof HTMLElementTagNameMap>(\n tagName: TagName,\n attrs?: Record<string, string | null> | null,\n): HTMLElementTagNameMap[TagName] => {\n const el = document.createElement(tagName);\n if (attrs) for (const [key, val] of Object.entries(attrs)) attr(el, key, val);\n return el;\n};\n\n/**\n * customElements.define\n * @description Defines a customElement if running in browser and if not already registered\n * Scoped/named \"customElements.define\" so @custom-elements-manifest/analyzer can find tag names\n */\nexport const customElements = {\n define: (name: string, instance: CustomElementConstructor) =>\n !isBrowser() ||\n window.customElements.get(name) ||\n window.customElements.define(name, instance),\n};\n\n/**\n * useId\n * @return A generated unique ID\n */\ndeclare global {\n interface Window {\n dsUseId?: number; // Use a global counter to ensure this works even when loading designsystemet multiple times\n }\n}\nlet id = 0;\nexport function useId(el?: Element | null) {\n if (!isBrowser()) return `:ds:${++id}`; // Emulate browser environment if window not available\n if (!window.dsUseId) window.dsUseId = 0; // Make sure we have a global to support multiple instances of designsystemet in same page\n if (el && !el.id) el.id = `:ds:${++window.dsUseId}`;\n return el?.id || '';\n}\n\n/**\n * @description Based off speak function from [U-elements](https://github.com/u-elements/u-elements/blob/main/packages/utils.ts#L210)\n * @param text The text to announce\n */\nlet LIVE_EL: HTMLElement | undefined;\nlet LIVE_FIX = 0;\nlet LIVE_CLEAR: ReturnType<typeof setTimeout> | number = 0;\nexport const announce = (text: string) => {\n clearTimeout(LIVE_CLEAR);\n if (LIVE_EL) LIVE_EL.textContent = `${text}${LIVE_FIX++ % 2 ? '\\u00A0' : ''}`; // Non-breaking space to ensure screen reader announces\n if (text) LIVE_CLEAR = setTimeout(announce, 2000, ''); // Clear prevent old announcements being found by screen readers, with 2 seconds brace period to avoid cutting of Android Talkback\n};\n\n// Mount live region on first focus so its ready to be used\nconst announceMount = () => {\n if (document.readyState !== 'complete') return; // Ensure page is loaded trying to avoid issues with React hydration\n if (!LIVE_EL) {\n LIVE_EL = tag('div', { 'aria-live': 'assertive' });\n LIVE_EL.style.overflow = 'hidden'; // Settings styles individually to prevent issues with CSP\n LIVE_EL.style.position = 'fixed';\n LIVE_EL.style.whiteSpace = 'nowrap';\n LIVE_EL.style.width = '1px';\n }\n if (!LIVE_EL.isConnected) document.body.appendChild(LIVE_EL);\n};\nonHotReload('announce', () => [\n on(document, 'focus mouseover', announceMount, QUICK_EVENT),\n]);\n"],"mappings":"qDAAA,MAAa,EAAY,mBACZ,EAAa,aACb,EAAkB,kBAClB,EAAc,CAAE,QAAS,GAAM,QAAS,EAAK,EAK7C,MACX,OAAO,OAAW,KAAe,OAAO,SAAa,IAE1C,MACX,EAAU,GAEV,QAAQ,KAAK,UAAU,eAAe,UAAY,UAAU,QAAQ,EAGzD,EACX,OAAO,YAAgB,IAClB,KAAM,CAAC,EACR,YAEN,SAAgB,EACd,EACA,EACA,CACA,IAAI,EAEJ,OAAO,SAAyB,GAAG,EAAS,CAC1C,aAAa,CAAK,EAClB,EAAQ,eAAiB,EAAS,MAAM,KAAM,CAAI,EAAG,CAAK,CAC5D,CACF,CAWA,MAAa,GACX,EACA,GAAG,IAEH,CAAC,EAAU,GACX,OAAO,aAAe,IACtB,QAAQ,IAAI,gCAAgC,IAAW,GAAG,CAAI,EASnD,GACX,EACA,EACA,IAEI,IAAU,IAAA,GAAkB,EAAG,aAAa,CAAI,GAChD,IAAU,KAAM,EAAG,gBAAgB,CAAI,EAClC,EAAG,aAAa,CAAI,IAAM,GAAO,EAAG,aAAa,EAAM,CAAK,EAC9D,MAUI,GAAc,EAAa,IACtC,iBAAiB,CAAE,CAAC,CAAC,iBA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,CAC5B,EAAG,SAAU,kBAAmB,EAAe,CAAW,CAC5D,CAAC"}
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { UHTMLComboboxElement } from "@u-elements/u-combobox";
4
4
  import * as UTabs from "@u-elements/u-tabs";
5
5
  export * from "@u-elements/u-datalist";
6
6
  //#region package.json
7
- var version = "1.21.1";
7
+ var version = "1.23.0";
8
8
  //#endregion
9
9
  //#region src/utils/utils.ts
10
10
  const ARIA_DESC = "aria-description";
@@ -46,7 +46,8 @@ const attr = (el, name, value) => {
46
46
  * @return string CSS property value
47
47
  */
48
48
  const getCSSProp = (el, prop) => getComputedStyle(el).getPropertyValue(prop).trim();
49
- const STRIP_QUOTES = /^["']|["']$/g;
49
+ const QUOTES_STRIP_SURROUNDING = /^["']|["']$/g;
50
+ const QUOTES_MATCH = /\\(["'])/g;
50
51
  /**
51
52
  * attrOrCSS
52
53
  * @description Retrieves and updates attribute based on attribute or CSS property value
@@ -56,7 +57,7 @@ const STRIP_QUOTES = /^["']|["']$/g;
56
57
  */
57
58
  const attrOrCSS = (el, name) => {
58
59
  let value = attr(el, name);
59
- if (!value) value = getCSSProp(el, `--_ds-${name}`).replace(STRIP_QUOTES, "").trim();
60
+ if (!value) value = getCSSProp(el, `--_ds-${name}`).replace(QUOTES_STRIP_SURROUNDING, "").replace(QUOTES_MATCH, "$1").trim();
60
61
  return value || null;
61
62
  };
62
63
  /**
@@ -702,8 +703,9 @@ function apply$1() {
702
703
  //#region src/invokers/invokers.ts
703
704
  if (isBrowser() && !isSupported$1()) apply$1();
704
705
  //#endregion
705
- //#region ../../node_modules/.pnpm/@oddbird+popover-polyfill@0.7.2/node_modules/@oddbird/popover-polyfill/dist/popover-fn.js
706
- var ToggleEvent = class extends Event {
706
+ //#region ../../node_modules/.pnpm/@oddbird+popover-polyfill@0.7.2_patch_hash=1f3e1d4b9b98be6ea6d4707fbe7b7ac66be549654cb4bb41ad60295c10c029f8/node_modules/@oddbird/popover-polyfill/dist/popover-fn.js
707
+ var EventClass = globalThis.Event || class {};
708
+ var ToggleEvent = class extends EventClass {
707
709
  oldState;
708
710
  newState;
709
711
  constructor(type, init = {}) {
@@ -1308,20 +1310,23 @@ const ATTR_AUTO = "data-autoplacement";
1308
1310
  const POPOVERS = /* @__PURE__ */ new Map();
1309
1311
  const handleToggle = (e) => toggle(getComposedTarget(e), e.newState, e.oldState, e.source || e.detail);
1310
1312
  function toggle(el, newState, oldState, source) {
1311
- const float = el instanceof HTMLElement && attr(el, "popover") !== null && getCSSProp(el, "--_ds-floating");
1313
+ const isPopover = el instanceof HTMLElement && attr(el, "popover") !== null;
1312
1314
  const prev = POPOVERS.get(el);
1313
1315
  if (newState === "open" && prev && prev.source === source) return;
1314
1316
  prev?.cleanup();
1315
- if (newState === "closed" || !float) return;
1317
+ if (newState === "closed" || !isPopover) return;
1316
1318
  if (!source) {
1317
1319
  const css = el.id && `[popovertarget="${el.id}"],[commandfor="${el.id}"]`;
1318
1320
  source = css && getRoot(el).querySelector(css) || void 0;
1319
1321
  }
1320
1322
  if (!source || source === el || oldState && oldState === newState) return;
1323
+ const dsFloating = getCSSProp(el, "--_ds-floating");
1324
+ const attrPlacement = attr(el, ATTR_PLACE) ?? attr(source, ATTR_PLACE);
1325
+ if (attrPlacement === null && !dsFloating) return;
1321
1326
  el.style.scrollMarginBottom = `var(--_ds-floating-arrow-size)`;
1322
1327
  const padding = 10;
1328
+ const placement = attrPlacement || dsFloating || "top";
1323
1329
  const overscroll = getCSSProp(el, "--_ds-floating-overscroll");
1324
- const placement = attr(el, ATTR_PLACE) || attr(source, ATTR_PLACE) || float;
1325
1330
  const auto = attr(el, ATTR_AUTO) || attr(source, ATTR_AUTO);
1326
1331
  const arrowSize = parseFloat(getCSSProp(el, "scroll-margin-bottom")) || 0;
1327
1332
  const shiftProp = placement.match(/left|right/gi) ? "Height" : "Width";
@@ -1345,10 +1350,8 @@ function toggle(el, newState, oldState, source) {
1345
1350
  ...overscroll ? [size({ apply({ availableHeight }) {
1346
1351
  if (sized) return;
1347
1352
  sized = true;
1348
- const width = `${source.offsetWidth}px`;
1349
1353
  const maxHeight = `${Math.max(50, availableHeight - padding * 2)}px`;
1350
1354
  requestAnimationFrame(() => {
1351
- if (overscroll === "fit" && el.style.width !== width) el.style.width = width;
1352
1355
  if (el.style.maxHeight !== maxHeight) el.style.maxHeight = maxHeight;
1353
1356
  });
1354
1357
  } })] : []
@@ -1356,6 +1359,10 @@ function toggle(el, newState, oldState, source) {
1356
1359
  };
1357
1360
  const unfloat = autoUpdate(source, el, async () => {
1358
1361
  if (!source?.isConnected) return POPOVERS.get(el)?.cleanup();
1362
+ if (overscroll === "fit") {
1363
+ const width = `${source.offsetWidth}px`;
1364
+ if (el.style.width !== width) el.style.width = width;
1365
+ }
1359
1366
  const { x, y } = await computePosition(source, el, options);
1360
1367
  el.style.translate = `${x}px ${y}px`;
1361
1368
  });
@@ -1584,7 +1591,7 @@ const setupText = (el, canAnnounce = true) => {
1584
1591
  attr(el, ATTR_TOOLTIP, text);
1585
1592
  attr(el, ARIA_LABEL, hasText ? null : text);
1586
1593
  attr(el, ARIA_DESC, hasText ? text : null);
1587
- if (el.tabIndex === -1) warn("Missing tabindex=\"0\" attribute on: ", el);
1594
+ if (el.tabIndex === -1 && !el.hasAttribute("tabindex") && el.nodeName !== "LABEL") warn("Missing tabindex=\"0\" attribute on: ", el);
1588
1595
  }
1589
1596
  if (el === OPEN && TIP?.textContent !== text) {
1590
1597
  if (TIP) TIP.textContent = text;
@@ -1778,7 +1785,7 @@ const handleFieldMutation = (field) => {
1778
1785
  }
1779
1786
  field.handleEvent();
1780
1787
  };
1781
- const TEXTS = {
1788
+ const TEXTS$1 = {
1782
1789
  over: "%d tegn for mye",
1783
1790
  under: "%d tegn igjen"
1784
1791
  };
@@ -1818,7 +1825,7 @@ var DSFieldElement = class extends DSElement {
1818
1825
  if (_counter?.isConnected && _input) {
1819
1826
  const count = (Number(attr(_counter, ATTR_LIMIT)) || 0) - _input.value.length;
1820
1827
  const state = count < 0 ? "over" : "under";
1821
- const label = (attrOrCSS(_counter, `data-${state}`) || TEXTS[state])?.replace("%d", `${Math.abs(count)}`);
1828
+ const label = (attrOrCSS(_counter, `data-${state}`) || TEXTS$1[state])?.replace("%d", `${Math.abs(count)}`);
1822
1829
  if (!label) warn(`Missing data-${state} on:`, _counter);
1823
1830
  attr(_counter, "data-label", label);
1824
1831
  attr(_counter, "data-state", state);
@@ -1888,6 +1895,7 @@ var DSPaginationElement = class extends DSElement {
1888
1895
  this._unmutate = this._render = void 0;
1889
1896
  }
1890
1897
  };
1898
+ const isNamedByAriaLabel = (el) => !el.textContent?.trim() && !attr(el, "aria-labelledby");
1891
1899
  const render$1 = (self) => {
1892
1900
  const current = Number(attr(self, ATTR_CURRENT));
1893
1901
  const total = Number(attr(self, ATTR_TOTAL));
@@ -1901,9 +1909,11 @@ const render$1 = (self) => {
1901
1909
  show
1902
1910
  });
1903
1911
  items.forEach((item, i) => {
1904
- const page = i ? items[i + 1] ? pages[i - 1]?.page : next : prev;
1912
+ const isStep = i !== 0 && !!items[i + 1];
1913
+ const page = isStep ? pages[i - 1]?.page : i ? next : prev;
1905
1914
  attr(item, "aria-current", pages[i - 1]?.current ? "true" : null);
1906
- attr(item, ARIA_LABEL, `${page ?? "hidden"}`);
1915
+ if (isStep) attr(item, ARIA_LABEL, `${page ?? "hidden"}`);
1916
+ else if (isNamedByAriaLabel(item)) attr(item, ARIA_LABEL, attrOrCSS(item, ARIA_LABEL));
1907
1917
  attr(item, "role", page ? null : "none");
1908
1918
  attr(item, "tabindex", page ? null : "-1");
1909
1919
  if (item instanceof HTMLButtonElement) attr(item, "value", `${page}`);
@@ -1925,53 +1935,67 @@ customElements.define("ds-pagination", DSPaginationElement);
1925
1935
  //#region src/suggestion/suggestion.ts
1926
1936
  const ATTR_EMPTY = "data-empty";
1927
1937
  const ATTR_CREATE = "data-create";
1938
+ const EVENTS_EMPTY = "comboboxafterselect comboboxprogrammaticinput input";
1939
+ const REGEX_CREATE = /\{value\}|%s/;
1940
+ const SINGULAR = "data-sr-singular";
1941
+ const PLURAL = "data-sr-plural";
1942
+ const TEXTS = "added,clear,empty,found,invalid,items,of,plural,remove,removed,singular,toggle".split(",").map((key) => `data-sr-${key}`);
1928
1943
  var DSSuggestionElement = class extends UHTMLComboboxElement {
1929
1944
  _unmutate;
1930
1945
  connectedCallback() {
1946
+ for (const key of TEXTS) attr(this, key, attrOrCSS(this, key));
1931
1947
  super.connectedCallback();
1932
1948
  this._unmutate = onMutation(this, render, { childList: true });
1933
- on(this, "comboboxafterselect input", handleEmpty, QUICK_EVENT);
1949
+ on(this, EVENTS_EMPTY, handleEmpty, QUICK_EVENT);
1934
1950
  on(this, "toggle", polyfillToggleSource, QUICK_EVENT);
1935
1951
  }
1936
1952
  disconnectedCallback() {
1937
1953
  super.disconnectedCallback();
1938
1954
  this._unmutate?.();
1939
1955
  this._unmutate = void 0;
1940
- off(this, "comboboxafterselect input", handleEmpty, QUICK_EVENT);
1956
+ off(this, EVENTS_EMPTY, handleEmpty, QUICK_EVENT);
1941
1957
  off(this, "toggle", polyfillToggleSource, QUICK_EVENT);
1942
1958
  }
1943
1959
  };
1944
1960
  const render = (self) => {
1945
- const { control, list } = self;
1946
- const datalist = list || self.querySelector("u-datalist");
1961
+ let { control, list } = self;
1962
+ if (!list) list = self.querySelector("u-datalist");
1947
1963
  if (control) attr(control, "popovertarget", list ? useId(list) : null);
1948
- if (datalist) {
1949
- attr(datalist, "popover", "manual");
1950
- attr(datalist, "data-is-floating", "true");
1964
+ if (list) {
1965
+ if (!attr(list, PLURAL)) attr(list, PLURAL, attr(self, PLURAL));
1966
+ if (!attr(list, SINGULAR)) attr(list, SINGULAR, attr(self, SINGULAR));
1967
+ attr(list, "data-is-floating", "true");
1968
+ attr(list, "popover", "manual");
1951
1969
  }
1952
1970
  handleEmpty({ currentTarget: self });
1953
1971
  };
1954
- const handleEmpty = ({ currentTarget: self }) => {
1972
+ const handleEmpty = (event) => {
1973
+ const self = event.currentTarget;
1955
1974
  const { creatable, control, options } = self;
1956
1975
  if (!options) return;
1957
1976
  const value = control?.value.trim() || "";
1958
1977
  const query = value.toLowerCase();
1959
- let empty;
1960
- let exists = !value;
1978
+ let emptyOpt;
1979
+ let hasLabel = false;
1961
1980
  for (const opt of options) {
1962
- if (!empty && opt.hasAttribute(ATTR_EMPTY)) empty = opt;
1963
- else if (!exists && opt.label?.toLowerCase() === query) exists = true;
1964
- if (exists && empty) break;
1965
- }
1966
- if (!empty) return;
1967
- empty.hidden = exists;
1968
- empty.label = value;
1969
- empty.value = creatable ? value : "";
1970
- if (!creatable || empty.textContent) return;
1971
- const text = attrOrCSS(empty, ATTR_EMPTY);
1972
- if (!text) warn(`Missing ${ATTR_EMPTY} value on:`, empty);
1973
- else attr(empty, ATTR_EMPTY, text);
1974
- attr(empty, ATTR_CREATE, text?.replace("{value}", value));
1981
+ if (!emptyOpt && opt.hasAttribute(ATTR_EMPTY)) emptyOpt = opt;
1982
+ else if (!hasLabel && (!query || opt.label?.toLowerCase() === query)) hasLabel = true;
1983
+ if (hasLabel && emptyOpt) break;
1984
+ }
1985
+ if (!emptyOpt) return;
1986
+ emptyOpt.hidden = hasLabel || creatable && !value;
1987
+ attr(emptyOpt, "label", value);
1988
+ attr(emptyOpt, "value", creatable ? value : "");
1989
+ if (creatable) {
1990
+ const hasValue = self.values.includes(value);
1991
+ const text = attrOrCSS(emptyOpt, ATTR_EMPTY);
1992
+ const hint = !hasValue && text?.replace(REGEX_CREATE, () => value) || value;
1993
+ if (!text) warn(`Missing ${ATTR_EMPTY} value on:`, emptyOpt);
1994
+ else attr(emptyOpt, ATTR_EMPTY, text);
1995
+ const disabled = hasValue && emptyOpt.textContent ? "true" : null;
1996
+ attr(emptyOpt, "disabled", disabled);
1997
+ attr(emptyOpt, ATTR_CREATE, hint);
1998
+ }
1975
1999
  };
1976
2000
  const polyfillToggleSource = (event) => {
1977
2001
  const self = event.currentTarget;