@digdir/designsystemet-web 1.13.0 → 1.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/popover/popover.cjs +1 -1
- package/dist/cjs/popover/popover.cjs.map +1 -1
- package/dist/cjs/tooltip/tooltip.cjs +1 -1
- package/dist/cjs/tooltip/tooltip.cjs.map +1 -1
- package/dist/cjs/utils/utils.cjs +1 -1
- package/dist/cjs/utils/utils.cjs.map +1 -1
- package/dist/esm/popover/popover.js +1 -1
- package/dist/esm/popover/popover.js.map +1 -1
- package/dist/esm/tooltip/tooltip.js +1 -1
- package/dist/esm/tooltip/tooltip.js.map +1 -1
- package/dist/esm/utils/utils.js +1 -1
- package/dist/esm/utils/utils.js.map +1 -1
- package/dist/index.d.ts +9 -0
- package/dist/index.js +8 -5
- package/dist/umd/index.js +2 -2
- package/dist/umd/index.js.map +1 -1
- package/package.json +5 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/utils.cjs`);let t=require(`@floating-ui/dom`);const n=`data-placement`,r=`data-autoplacement`,i=new Map;function a(a){let{newState:o,oldState:s,target:u,source:d=a.detail}=a,f=u instanceof HTMLElement&&c(u,`--_ds-floating`);if(!f)return;if(o===`closed`)return i.get(u)?.();if(!d){let e=u.getRootNode(),t=`[popovertarget="${u.id}"],[commandfor="${u.id}"]`;d=u.id&&e?.querySelector?.(t)||void 0}if(!d||d===u||s&&s===o)return;let p=c(u,`--_ds-floating-overscroll`),m=e.attr(u,n)||e.attr(d,n)||f,h=e.attr(u,r)||e.attr(d,r),g=parseFloat(getComputedStyle(u,`::before`).height)||0,_=m.match(/left|right/gi)?`Height`:`Width`,v=d[`offset${_}`]/2+g;if(m===`none`)return;let y={strategy:`absolute`,placement:m,middleware:[(0,t.offset)(g||0),(0,t.shift)({padding:10,limiter:(0,t.limitShift)({offset:{mainAxis:v}})}),l(),...h===`false`?[]:[(0,t.flip)({padding:10,crossAxis:!1})],...p?[(0,t.size)({apply({availableHeight:e}){p===`fit`&&(u.style.width=`${d.clientWidth}px`),u.style.maxHeight=`${Math.max(50,e-20)}px`}})]:[]]},b=(0,t.autoUpdate)(d,u,async()=>{if(!d?.isConnected)return i.get(u)?.();let{x:e,y:n}=await(0,t.computePosition)(d,u,y);u.style.translate=`${e}px ${n}px`});i.set(u,()=>i.delete(u)&&b())}let o;const s=({type:e})=>{if(e===`mousedown`&&(o=!1),e===`scroll`&&o===!1&&(o=!0),e===`mouseup`&&o)for(let[e]of i)e.showPopover()};e.onHotReload(`popover`,()=>[e.on(document,`mousedown scroll mouseup`,s,!0),e.on(document,`toggle ds-toggle-source`,a,e.QUICK_EVENT)]);const c=(e,t)=>getComputedStyle(e).getPropertyValue(t).trim(),l=()=>({name:`arrowPseudo`,fn(t){let n=t.elements.floating,r=t.rects.reference,i=`${Math.round(r.width/2+r.x-t.x)}px`,a=`${Math.round(r.height/2+r.y-t.y)}px`;return n.style.setProperty(`--_ds-floating-arrow-x`,i),n.style.setProperty(`--_ds-floating-arrow-y`,a),e.attr(n,`data-floating`,t.placement),t}});
|
|
1
|
+
require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/utils.cjs`);let t=require(`@floating-ui/dom`);const n=`data-placement`,r=`data-autoplacement`,i=new Map;function a(a){let{newState:o,oldState:s,target:u,source:d=a.detail}=a,f=u instanceof HTMLElement&&e.attr(u,`popover`)!==null&&c(u,`--_ds-floating`);if(!f)return;if(o===`closed`)return i.get(u)?.();if(!d){let e=u.getRootNode(),t=`[popovertarget="${u.id}"],[commandfor="${u.id}"]`;d=u.id&&e?.querySelector?.(t)||void 0}if(!d||d===u||s&&s===o)return;let p=c(u,`--_ds-floating-overscroll`),m=e.attr(u,n)||e.attr(d,n)||f,h=e.attr(u,r)||e.attr(d,r),g=parseFloat(getComputedStyle(u,`::before`).height)||0,_=m.match(/left|right/gi)?`Height`:`Width`,v=d[`offset${_}`]/2+g;if(m===`none`)return;let y={strategy:`absolute`,placement:m,middleware:[(0,t.offset)(g||0),(0,t.shift)({padding:10,limiter:(0,t.limitShift)({offset:{mainAxis:v}})}),l(),...h===`false`?[]:[(0,t.flip)({padding:10,crossAxis:!1})],...p?[(0,t.size)({apply({availableHeight:e}){p===`fit`&&(u.style.width=`${d.clientWidth}px`),u.style.maxHeight=`${Math.max(50,e-20)}px`}})]:[]]},b=(0,t.autoUpdate)(d,u,async()=>{if(!d?.isConnected)return i.get(u)?.();let{x:e,y:n}=await(0,t.computePosition)(d,u,y);u.style.translate=`${e}px ${n}px`});i.set(u,()=>i.delete(u)&&b())}let o;const s=({type:e})=>{if(e===`mousedown`&&(o=!1),e===`scroll`&&o===!1&&(o=!0),e===`mouseup`&&o)for(let[e]of i)e.showPopover()};e.onHotReload(`popover`,()=>[e.on(document,`mousedown scroll mouseup`,s,!0),e.on(document,`toggle ds-toggle-source`,a,e.QUICK_EVENT)]);const c=(e,t)=>getComputedStyle(e).getPropertyValue(t).trim(),l=()=>({name:`arrowPseudo`,fn(t){let n=t.elements.floating,r=t.rects.reference,i=`${Math.round(r.width/2+r.x-t.x)}px`,a=`${Math.round(r.height/2+r.y-t.y)}px`;return n.style.setProperty(`--_ds-floating-arrow-x`,i),n.style.setProperty(`--_ds-floating-arrow-y`,a),e.attr(n,`data-floating`,t.placement),t}});
|
|
2
2
|
//# sourceMappingURL=popover.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"popover.cjs","names":["attr","onHotReload","on","QUICK_EVENT"],"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 { attr, on, onHotReload, QUICK_EVENT } from '../utils/utils';\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n 'ds-toggle-source': CustomEvent<Element>;\n }\n}\n\nconst ATTR_PLACE = 'data-placement';\nconst ATTR_AUTO = 'data-autoplacement';\nconst POPOVERS = new Map<HTMLElement, () => void>();\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)\nfunction handleToggle(\n event: Partial<ToggleEvent> & {\n detail?: HTMLElement;\n source?: HTMLElement;\n },\n) {\n let { newState, oldState, target: el, source = event.detail } = event;\n const
|
|
1
|
+
{"version":3,"file":"popover.cjs","names":["attr","onHotReload","on","QUICK_EVENT"],"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 { attr, on, onHotReload, QUICK_EVENT } from '../utils/utils';\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n 'ds-toggle-source': CustomEvent<Element>;\n }\n}\n\nconst ATTR_PLACE = 'data-placement';\nconst ATTR_AUTO = 'data-autoplacement';\nconst POPOVERS = new Map<HTMLElement, () => void>();\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)\nfunction handleToggle(\n event: Partial<ToggleEvent> & {\n detail?: HTMLElement;\n source?: HTMLElement;\n },\n) {\n let { newState, oldState, target: el, source = event.detail } = event;\n const isPopover = el instanceof HTMLElement && attr(el, 'popover') !== null;\n const float = isPopover && getCSSProp(el, '--_ds-floating');\n\n if (!float) return;\n if (newState === 'closed') return POPOVERS.get(el)?.(); // Cleanup on close\n if (!source) {\n const root = el.getRootNode() as Document; // Support shadow DOM\n const css = `[popovertarget=\"${el.id}\"],[commandfor=\"${el.id}\"]`;\n source = (el.id && root?.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 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(getComputedStyle(el, '::before').height) || 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 const options = {\n strategy: 'absolute',\n placement,\n middleware: [\n offset(arrowSize || 0), // Add space for arrow or default to 8px\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 (overscroll === 'fit')\n el.style.width = `${source.clientWidth}px`;\n el.style.maxHeight = `${Math.max(50, availableHeight - padding * 2)}px`;\n },\n }),\n ]\n : []),\n ],\n } as ComputePositionConfig;\n const unfloat = autoUpdate(source, el, async () => {\n if (!source?.isConnected) return POPOVERS.get(el)?.(); // 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, () => POPOVERS.delete(el) && unfloat());\n}\n\n// Prevent closing when mouse interacts with scrollbar\nlet IS_SCROLL: boolean | undefined;\nconst handleScrollbar = ({ type }: Event) => {\n if (type === 'mousedown') IS_SCROLL = false;\n if (type === 'scroll' && IS_SCROLL === false) IS_SCROLL = true;\n if (type === 'mouseup' && IS_SCROLL)\n for (const [popover] of POPOVERS) popover.showPopover(); // Immediately show again to prevent flicker\n};\n\nonHotReload('popover', () => [\n on(document, 'mousedown scroll mouseup', handleScrollbar, true),\n on(document, 'toggle ds-toggle-source', handleToggle, QUICK_EVENT), // Use capture since the toggle event does not bubble\n]);\n\nconst getCSSProp = (el: Element, prop: string) =>\n getComputedStyle(el).getPropertyValue(prop).trim();\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":"qHAkBA,MAAM,EAAa,iBACb,EAAY,qBACZ,EAAW,IAAI,IAIrB,SAAS,EACP,EAIA,CACA,GAAI,CAAE,WAAU,WAAU,OAAQ,EAAI,SAAS,EAAM,QAAW,EAE1D,EADY,aAAc,aAAeA,EAAAA,KAAK,EAAI,UAAU,GAAK,MAC5C,EAAW,EAAI,iBAAiB,CAE3D,GAAI,CAAC,EAAO,OACZ,GAAI,IAAa,SAAU,OAAO,EAAS,IAAI,EAAG,IAAI,CACtD,GAAI,CAAC,EAAQ,CACX,IAAM,EAAO,EAAG,aAAa,CACvB,EAAM,mBAAmB,EAAG,GAAG,kBAAkB,EAAG,GAAG,IAC7D,EAAU,EAAG,IAAM,GAAM,gBAA6B,EAAI,EAAK,IAAA,GAEjE,GAAI,CAAC,GAAU,IAAW,GAAO,GAAY,IAAa,EAAW,OACrE,IACM,EAAa,EAAW,EAAI,4BAA4B,CACxD,EAAYA,EAAAA,KAAK,EAAI,EAAW,EAAIA,EAAAA,KAAK,EAAQ,EAAW,EAAI,EAChE,EAAOA,EAAAA,KAAK,EAAI,EAAU,EAAIA,EAAAA,KAAK,EAAQ,EAAU,CACrD,EAAY,WAAW,iBAAiB,EAAI,WAAW,CAAC,OAAO,EAAI,EACnE,EAAY,EAAU,MAAM,eAAe,CAAG,SAAW,QACzD,EAAa,EAAO,SAAS,KAAe,EAAI,EAEtD,GAAI,IAAc,OAAQ,OAE1B,IAAM,EAAU,CACd,SAAU,WACV,YACA,WAAY,cACH,GAAa,EAAE,aAChB,CACJ,WACA,SAAA,EAAA,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AK,MAAM,EAAO,MAAQ,EAAI,EAAO,EAAI,EAAK,EAAE,CAAC,IACxD,EAAI,GAAG,KAAK,MAAM,EAAO,OAAS,EAAI,EAAO,EAAI,EAAK,EAAE,CAAC,IAK/D,OAHA,EAAO,MAAM,YAAY,yBAA0B,EAAE,CACrD,EAAO,MAAM,YAAY,yBAA0B,EAAE,CACrD,EAAA,KAAK,EAAQ,gBAAiB,EAAK,UAAU,CACtC,GAEV"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../utils/utils.cjs`);let t,n,r=0,i=0;const a=`data-tooltip`,
|
|
1
|
+
const e=require(`../utils/utils.cjs`);let t,n,r=0,i=0;const a=e.isBrowser()&&/iPad|iPhone|iPod/.test(navigator.userAgent),o=`data-tooltip`,s=`data-color`,c=`aria-label`,l=`aria-description`,u=`[${s}]`,d=`[${o}]`,f=`data-color-scheme`,p=`[${f}]`,m=n=>{n&&!(n instanceof HTMLElement)&&e.warn(`setTooltipElement expects an HTMLElement, got: `,n),t=n||void 0},h=e.debounce(()=>{for(let r of document.querySelectorAll(d)){let i=r.getAttribute(c)||r.getAttribute(l),a=r.getAttribute(o)||e.attrOrCSS(r,o);if(i!==a){let t=e.attr(r,`role`)!==`img`&&r.textContent?.trim();e.attr(r,o,a),e.attr(r,c,t?null:a),e.attr(r,l,t?a:null),r.matches(`a,button,input,label,select,textarea,[tabindex]`)||e.warn(`Missing tabindex="0" attribute on: `,r)}let s=r===n&&t?.matches(`:popover-open`),u=s&&a&&t?.textContent!==a;s&&u&&(t&&e.setTextWithoutMutation(t,a),document.activeElement===r&&e.announce(a))}},0),g=({type:c,target:l})=>{if(clearTimeout(r),l===t)return;if(c===`mouseover`&&!n&&!a){r=setTimeout(g,300,{target:l});return}let d=l?.closest?.(`[${o}]`);if(d===n)return;if(!d)return _();t||=e.tag(`div`,{class:`ds-tooltip`}),t.isConnected||document.body.appendChild(t);let m=d.closest(u),h=d.closest(p),v=m!==h&&m?.contains(h);clearTimeout(i),e.attr(t,`popover`,`manual`),e.attr(t,f,h?.getAttribute(f)||null),e.attr(t,s,v&&m?.getAttribute(s)||null),e.setTextWithoutMutation(t,e.attr(d,o)),t.showPopover(),t.dispatchEvent(new CustomEvent(`ds-toggle-source`,{detail:d})),n=d},_=()=>t?.isConnected&&t.popover&&t.hidePopover(),v=e=>{if(e?.type===`keydown`)return e?.key===`Escape`&&_();e?e.target===t&&e.newState===`closed`&&(i=setTimeout(v,300)):n=void 0};e.onHotReload(`tooltip`,()=>[e.on(document,`blur focus mouseover`,g,e.QUICK_EVENT),e.on(document,`toggle keydown`,v,e.QUICK_EVENT),e.onMutation(document,h,{attributeFilter:[o],attributes:!0,childList:!0,subtree:!0})]),exports.setTooltipElement=m;
|
|
2
2
|
//# sourceMappingURL=tooltip.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tooltip.cjs","names":["debounce","attrOrCSS","attr","tag","onHotReload","on","QUICK_EVENT","onMutation"],"sources":["../../../src/tooltip/tooltip.ts"],"sourcesContent":["import {\n announce,\n attr,\n attrOrCSS,\n debounce,\n on,\n onHotReload,\n onMutation,\n QUICK_EVENT,\n setTextWithoutMutation,\n tag,\n warn,\n} from '../utils/utils';\n\nlet TIP: HTMLElement | undefined;\nlet SOURCE: Element | undefined;\nlet HOVER_TIMER: number | ReturnType<typeof setTimeout> = 0;\nlet SKIP_TIMER: number | ReturnType<typeof setTimeout> = 0;\nconst ATTR_TOOLTIP = 'data-tooltip';\nconst ATTR_COLOR = 'data-color';\nconst ARIA_LABEL = 'aria-label';\nconst ARIA_DESC = 'aria-description';\nconst SELECTOR_COLOR = `[${ATTR_COLOR}]`;\nconst SELECTOR_TOOLTIP = `[${ATTR_TOOLTIP}]`;\nconst ATTR_SCHEME = 'data-color-scheme';\nconst SELECTOR_SCHEME = `[${ATTR_SCHEME}]`;\nconst SELECTOR_INTERACTIVE = 'a,button,input,label,select,textarea,[tabindex]';\nconst DELAY_HOVER = 300;\nconst DELAY_SKIP = 300;\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 TIP = el || undefined;\n};\n\nconst handleAriaAttributes = debounce(() => {\n for (const el of document.querySelectorAll(SELECTOR_TOOLTIP)) {\n const aria = el.getAttribute(ARIA_LABEL) || el.getAttribute(ARIA_DESC); // Using getAttribute for best performance\n const text = el.getAttribute(ATTR_TOOLTIP) || attrOrCSS(el, ATTR_TOOLTIP); // Only parse CSS if attribute is empty for better performance\n\n if (aria !== text) {\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.matches(SELECTOR_INTERACTIVE))\n warn('Missing tabindex=\"0\" attribute on: ', el);\n }\n\n // If an existing tooltip has changed programmatically, update tooltip text and announce change\n const isCurrent = el === SOURCE && TIP?.matches(':popover-open');\n const isChanged = isCurrent && text && TIP?.textContent !== text; // Only update if mutation is on source element and tooltip is open to avoid unnecessary updates\n if (isCurrent && isChanged) {\n if (TIP) setTextWithoutMutation(TIP, text);\n if (document.activeElement === el) announce(text); // Only announce if focus is on the button\n }\n }\n}, 0); // Debounce to merge multiple mutations\n\nconst handleInterest = ({ type, target }: Event) => {\n clearTimeout(HOVER_TIMER);\n\n if (target === TIP) return; // Allow tooltip to be hovered, following https://www.w3.org/TR/WCAG21/#content-on-hover-or-focus\n if (type === 'mouseover' && !SOURCE) {\n HOVER_TIMER = setTimeout(handleInterest, DELAY_HOVER, { target }); // Delay mouse showing tooltip if not already shown\n return;\n }\n\n const source = (target as Element)?.closest?.(`[${ATTR_TOOLTIP}]`);\n if (source === SOURCE) return; // No need to update\n if (!source) return hideTooltip(); // If no new anchor, cleanup previous autoUpdate\n if (!TIP) TIP = tag('div', { class: 'ds-tooltip' });\n if (!TIP.isConnected) document.body.appendChild(TIP); // Ensure connected\n\n const color = source.closest(SELECTOR_COLOR); // Match source color of source element\n const scheme = source.closest(SELECTOR_SCHEME); // Match source color-scheme 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 clearTimeout(SKIP_TIMER);\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 setTextWithoutMutation(TIP, attr(source, ATTR_TOOLTIP));\n TIP.showPopover();\n TIP.dispatchEvent(new CustomEvent('ds-toggle-source', { detail: source })); // Since showPopover({ source }) is not supported in all browsers yet\n SOURCE = source;\n};\n\nconst hideTooltip = () => TIP?.isConnected && TIP.popover && TIP.hidePopover(); // Only hide if connected and activated\n\nconst handleClose = (event?: Partial<ToggleEvent & KeyboardEvent>) => {\n if (event?.type === 'keydown')\n return event?.key === 'Escape' && hideTooltip();\n if (!event) SOURCE = undefined;\n else if (event.target === TIP && event.newState === 'closed')\n SKIP_TIMER = setTimeout(handleClose, DELAY_SKIP);\n};\n\nonHotReload('tooltip', () => [\n on(document, 'blur focus mouseover', handleInterest, QUICK_EVENT),\n on(document, 'toggle keydown', handleClose, QUICK_EVENT),\n onMutation(document, handleAriaAttributes, {\n attributeFilter: [ATTR_TOOLTIP],\n attributes: true,\n childList: true,\n subtree: true,\n }),\n]);\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"tooltip.cjs","names":["isBrowser","debounce","attrOrCSS","attr","tag","onHotReload","on","QUICK_EVENT","onMutation"],"sources":["../../../src/tooltip/tooltip.ts"],"sourcesContent":["import {\n announce,\n attr,\n attrOrCSS,\n debounce,\n isBrowser,\n on,\n onHotReload,\n onMutation,\n QUICK_EVENT,\n setTextWithoutMutation,\n tag,\n warn,\n} from '../utils/utils';\n\nlet TIP: HTMLElement | undefined;\nlet SOURCE: Element | undefined;\nlet HOVER_TIMER: number | ReturnType<typeof setTimeout> = 0;\nlet SKIP_TIMER: number | ReturnType<typeof setTimeout> = 0;\n/*needed to omit DELAY_HOVER on iOS that otherwise causes interaction delay \n(iOS triggers mouseover before click when an element is tapped)*/\nconst IS_IOS = isBrowser() && /iPad|iPhone|iPod/.test(navigator.userAgent);\nconst ATTR_TOOLTIP = 'data-tooltip';\nconst ATTR_COLOR = 'data-color';\nconst ARIA_LABEL = 'aria-label';\nconst ARIA_DESC = 'aria-description';\nconst SELECTOR_COLOR = `[${ATTR_COLOR}]`;\nconst SELECTOR_TOOLTIP = `[${ATTR_TOOLTIP}]`;\nconst ATTR_SCHEME = 'data-color-scheme';\nconst SELECTOR_SCHEME = `[${ATTR_SCHEME}]`;\nconst SELECTOR_INTERACTIVE = 'a,button,input,label,select,textarea,[tabindex]';\nconst DELAY_HOVER = 300;\nconst DELAY_SKIP = 300;\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 TIP = el || undefined;\n};\n\nconst handleAriaAttributes = debounce(() => {\n for (const el of document.querySelectorAll(SELECTOR_TOOLTIP)) {\n const aria = el.getAttribute(ARIA_LABEL) || el.getAttribute(ARIA_DESC); // Using getAttribute for best performance\n const text = el.getAttribute(ATTR_TOOLTIP) || attrOrCSS(el, ATTR_TOOLTIP); // Only parse CSS if attribute is empty for better performance\n\n if (aria !== text) {\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.matches(SELECTOR_INTERACTIVE))\n warn('Missing tabindex=\"0\" attribute on: ', el);\n }\n\n // If an existing tooltip has changed programmatically, update tooltip text and announce change\n const isCurrent = el === SOURCE && TIP?.matches(':popover-open');\n const isChanged = isCurrent && text && TIP?.textContent !== text; // Only update if mutation is on source element and tooltip is open to avoid unnecessary updates\n if (isCurrent && isChanged) {\n if (TIP) setTextWithoutMutation(TIP, text);\n if (document.activeElement === el) announce(text); // Only announce if focus is on the button\n }\n }\n}, 0); // Debounce to merge multiple mutations\n\nconst handleInterest = ({ type, target }: Event) => {\n clearTimeout(HOVER_TIMER);\n\n if (target === TIP) return; // Allow tooltip to be hovered, following https://www.w3.org/TR/WCAG21/#content-on-hover-or-focus\n if (type === 'mouseover' && !SOURCE && !IS_IOS) {\n HOVER_TIMER = setTimeout(handleInterest, DELAY_HOVER, { target }); // Delay mouse showing tooltip if not already shown\n return;\n }\n\n const source = (target as Element)?.closest?.(`[${ATTR_TOOLTIP}]`);\n if (source === SOURCE) return; // No need to update\n if (!source) return hideTooltip(); // If no new anchor, cleanup previous autoUpdate\n if (!TIP) TIP = tag('div', { class: 'ds-tooltip' });\n if (!TIP.isConnected) document.body.appendChild(TIP); // Ensure connected\n\n const color = source.closest(SELECTOR_COLOR); // Match source color of source element\n const scheme = source.closest(SELECTOR_SCHEME); // Match source color-scheme 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 clearTimeout(SKIP_TIMER);\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 setTextWithoutMutation(TIP, attr(source, ATTR_TOOLTIP));\n TIP.showPopover();\n TIP.dispatchEvent(new CustomEvent('ds-toggle-source', { detail: source })); // Since showPopover({ source }) is not supported in all browsers yet\n SOURCE = source;\n};\n\nconst hideTooltip = () => TIP?.isConnected && TIP.popover && TIP.hidePopover(); // Only hide if connected and activated\n\nconst handleClose = (event?: Partial<ToggleEvent & KeyboardEvent>) => {\n if (event?.type === 'keydown')\n return event?.key === 'Escape' && hideTooltip();\n if (!event) SOURCE = undefined;\n else if (event.target === TIP && event.newState === 'closed')\n SKIP_TIMER = setTimeout(handleClose, DELAY_SKIP);\n};\n\nonHotReload('tooltip', () => [\n on(document, 'blur focus mouseover', handleInterest, QUICK_EVENT),\n on(document, 'toggle keydown', handleClose, QUICK_EVENT),\n onMutation(document, handleAriaAttributes, {\n attributeFilter: [ATTR_TOOLTIP],\n attributes: true,\n childList: true,\n subtree: true,\n }),\n]);\n"],"mappings":"sCAeA,IAAI,EACA,EACA,EAAsD,EACtD,EAAqD,EAGzD,MAAM,EAASA,EAAAA,WAAW,EAAI,mBAAmB,KAAK,UAAU,UAAU,CACpE,EAAe,eACf,EAAa,aACb,EAAa,aACb,EAAY,mBACZ,EAAiB,IAAI,EAAW,GAChC,EAAmB,IAAI,EAAa,GACpC,EAAc,oBACd,EAAkB,IAAI,EAAY,GAU3B,EAAqB,GAA4B,CACxD,GAAM,EAAE,aAAc,cACxB,EAAA,KAAK,kDAAmD,EAAG,CAC7D,EAAM,GAAM,IAAA,IAGR,EAAuBC,EAAAA,aAAe,CAC1C,IAAK,IAAM,KAAM,SAAS,iBAAiB,EAAiB,CAAE,CAC5D,IAAM,EAAO,EAAG,aAAa,EAAW,EAAI,EAAG,aAAa,EAAU,CAChE,EAAO,EAAG,aAAa,EAAa,EAAIC,EAAAA,UAAU,EAAI,EAAa,CAEzE,GAAI,IAAS,EAAM,CACjB,IAAM,EAA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jB,EAAI,cAAc,IAAI,YAAY,mBAAoB,CAAE,OAAQ,EAAQ,CAAC,CAAC,CAC1E,EAAS,GAGL,MAAoB,GAAK,aAAe,EAAI,SAAW,EAAI,aAAa,CAExE,EAAe,GAAiD,CACpE,GAAI,GAAO,OAAS,UAClB,OAAO,GAAO,MAAQ,UAAY,GAAa,CAC5C,EACI,EAAM,SAAW,GAAO,EAAM,WAAa,WAClD,EAAa,WAAW,EAAa,IAAW,EAFtC,EAAS,IAAA,IAKvBE,EAAAA,YAAY,cAAiB,CAC3BC,EAAAA,GAAG,SAAU,uBAAwB,EAAgBC,EAAAA,YAAY,CACjED,EAAAA,GAAG,SAAU,iBAAkB,EAAaC,EAAAA,YAAY,CACxDC,EAAAA,WAAW,SAAU,EAAsB,CACzC,gBAAiB,CAAC,EAAa,CAC/B,WAAY,GACZ,UAAW,GACX,QAAS,GACV,CAAC,CACH,CAAC"}
|
package/dist/cjs/utils/utils.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={passive:!0,capture:!0},t=()=>typeof window<`u`&&typeof document<`u`,n=()=>t()&&/^Win/i.test(navigator.userAgentData?.platform||navigator.platform),r=typeof HTMLElement>`u`?class{}:HTMLElement;function i(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>e.apply(this,r),t)}}const a=(e,...t)
|
|
1
|
+
const e={passive:!0,capture:!0},t=()=>typeof window<`u`&&typeof document<`u`,n=()=>t()&&/^Win/i.test(navigator.userAgentData?.platform||navigator.platform),r=typeof HTMLElement>`u`?class{}:HTMLElement;function i(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>e.apply(this,r),t)}}const a=(e,...n)=>!t()||window.dsWarnings===!1||console.warn(`Designsystemet: ${e}`,...n),o=(e,t,n)=>n===void 0?e.getAttribute(t)??null:(n===null?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n),null),s=/^["']|["']$/g,c=(e,t)=>{let n=o(e,t);return n||=getComputedStyle(e).getPropertyValue(`--_ds-${t}`).replace(s,``).trim()||null,n||a(`Missing ${t} on:`,e),n},l=(e,...t)=>{let[n,...r]=t;for(let t of n.split(` `))e.addEventListener(t,...r);return()=>u(e,...t)},u=(e,...t)=>{let[n,...r]=t;for(let t of n.split(` `))e.removeEventListener(t,...r)},d=(e,n)=>{t()&&(window._dsHotReloadCleanup||(window._dsHotReloadCleanup=new Map),window._dsHotReloadCleanup?.get(e)?.map(e=>e()),window._dsHotReloadCleanup?.set(e,n()))};let f=!1;const p=(e,t,n)=>{let r=0,i=()=>{if(!e.isConnected)return a();t(o),o.takeRecords(),r=0},a=()=>o?.disconnect?.(),o=new MutationObserver(()=>{!f&&!r&&(r=requestAnimationFrame(i))});return o.observe(e,n),requestAnimationFrame(i),a},m=(e,t)=>{f=!0,e.textContent=t,requestAnimationFrame(h)},h=()=>{f=!1},g=(e,t)=>{let n=document.createElement(e);if(t)for(let[e,r]of Object.entries(t))o(n,e,r);return n},_={define:(e,n)=>!t()||window.customElements.get(e)||window.customElements.define(e,n)};let v=0;function y(e){return t()?(window.dsUseId||(window.dsUseId=0),e&&!e.id&&(e.id=`:ds:${++window.dsUseId}`),e?.id||``):`:ds:${++v}`}let b,x=0,S=0;const C=e=>{clearTimeout(S),b&&m(b,`${e}${x++%2?`\xA0`:``}`),e&&(S=setTimeout(C,2e3,``))},w=()=>{document.readyState===`complete`&&(b||(b=g(`div`,{"aria-live":`assertive`}),b.style.overflow=`hidden`,b.style.position=`fixed`,b.style.whiteSpace=`nowrap`,b.style.width=`1px`),b.isConnected||document.body.appendChild(b))};d(`announce`,()=>[l(document,`focus mouseover`,w,e)]),exports.DSElement=r,exports.QUICK_EVENT=e,exports.announce=C,exports.attr=o,exports.attrOrCSS=c,exports.customElements=_,exports.debounce=i,exports.isBrowser=t,exports.isWindows=n,exports.off=u,exports.on=l,exports.onHotReload=d,exports.onMutation=p,exports.setTextWithoutMutation=m,exports.tag=g,exports.useId=y,exports.warn=a;
|
|
2
2
|
//# sourceMappingURL=utils.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":[],"sources":["../../../src/utils/utils.ts"],"sourcesContent":["export const QUICK_EVENT = { passive: true, capture: true };\n\n// Using function instead of constant to support evnironments 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.warn, 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.warn>\n) =>\n typeof window === 'undefined' ||\n window.dsWarnings === false ||\n console.warn(`Designsystemet: ${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) ?? null; // Fallback to null only if el is undefined\n if (value === null) el.removeAttribute(name);\n else if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n return null;\n};\n\nconst STRIP_SURROUNDING_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 const prop = getComputedStyle(el).getPropertyValue(`--_ds-${name}`);\n value = prop.replace(STRIP_SURROUNDING_QUOTES, '').trim() || null;\n }\n if (!value) warn(`Missing ${name} on:`, el);\n return value;\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\ndeclare global {\n interface Window {\n _dsHotReloadCleanup?: 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._dsHotReloadCleanup) window._dsHotReloadCleanup = new Map(); // Hot reload cleanup support supporting all build tools\n\n window._dsHotReloadCleanup?.get(key)?.map((cleanup) => cleanup()); // Run previous cleanup\n window._dsHotReloadCleanup?.set(key, setup()); // Store new cleanup\n};\n\n/**\n * Speed up MutationObserver by debouncing and only running when page is visible\n * @return new MutaionObserver\n */\nlet SKIP_MUTATIONS = false;\nexport const onMutation = (\n el: Node,\n callback: (observer: MutationObserver) => void,\n options: MutationObserverInit,\n) => {\n let queue = 0;\n const onFrame = () => {\n if (!el.isConnected) return cleanup(); // Stop observing if element is removed from DOM\n callback(observer);\n observer.takeRecords(); // Clear records in case mutations happened during callback\n queue = 0;\n };\n const cleanup = () => observer?.disconnect?.();\n const observer = new MutationObserver(() => {\n if (!SKIP_MUTATIONS && !queue) queue = requestAnimationFrame(onFrame); // requestAnimationFrame only runs when page is visible\n });\n\n observer.observe(el, options);\n requestAnimationFrame(onFrame); // Initial run when page is visible and children has mounted\n return cleanup;\n};\n\n/**\n * Many mutation observers need to watch childNodes, thus running on all `textContent` changes\n * This utility allows skipping mutation observers while updating textContent\n */\nexport const setTextWithoutMutation = (el: Element, text: string | null) => {\n SKIP_MUTATIONS = true;\n el.textContent = text;\n requestAnimationFrame(enableMutations); // Let all mutationobservers run before enabling again\n};\nconst enableMutations = () => {\n SKIP_MUTATIONS = false;\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 */\nlet id = 0;\nconst hash = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`;\nexport function useId(el?: Element | null) {\n if (el && !el.id) el.id = `${hash}${++id}`;\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)\n setTextWithoutMutation(LIVE_EL, `${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":"AAAA,MAAa,EAAc,CAAE,QAAS,GAAM,QAAS,GAAM,CAG9C,MACX,OAAO,OAAW,KAAe,OAAO,SAAa,IAE1C,MACX,GAAW,EAEX,QAAQ,KAAK,UAAU,eAAe,UAAY,UAAU,SAAS,CAG1D,EACX,OAAO,YAAgB,IAClB,KAAM,GACP,YAEN,SAAgB,EACd,EACA,EACA,CACA,IAAI,EAEJ,OAAO,SAAyB,GAAG,EAAS,CAC1C,aAAa,EAAM,CACnB,EAAQ,eAAiB,EAAS,MAAM,KAAM,EAAK,CAAE,EAAM,EAa/D,MAAa,GACX,EACA,GAAG,IAEH,OAAO,OAAW,KAClB,OAAO,aAAe,IACtB,QAAQ,KAAK,mBAAm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"utils.cjs","names":[],"sources":["../../../src/utils/utils.ts"],"sourcesContent":["export const QUICK_EVENT = { passive: true, capture: true };\n\n// Using function instead of constant to support evnironments 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.warn, 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.warn>\n) =>\n !isBrowser() ||\n window.dsWarnings === false ||\n console.warn(`Designsystemet: ${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) ?? null; // Fallback to null only if el is undefined\n if (value === null) el.removeAttribute(name);\n else if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n return null;\n};\n\nconst STRIP_SURROUNDING_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 const prop = getComputedStyle(el).getPropertyValue(`--_ds-${name}`);\n value = prop.replace(STRIP_SURROUNDING_QUOTES, '').trim() || null;\n }\n if (!value) warn(`Missing ${name} on:`, el);\n return value;\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\ndeclare global {\n interface Window {\n _dsHotReloadCleanup?: 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._dsHotReloadCleanup) window._dsHotReloadCleanup = new Map(); // Hot reload cleanup support supporting all build tools\n\n window._dsHotReloadCleanup?.get(key)?.map((cleanup) => cleanup()); // Run previous cleanup\n window._dsHotReloadCleanup?.set(key, setup()); // Store new cleanup\n};\n\n/**\n * Speed up MutationObserver by debouncing and only running when page is visible\n * @return new MutaionObserver\n */\nlet SKIP_MUTATIONS = false;\nexport const onMutation = (\n el: Node,\n callback: (observer: MutationObserver) => void,\n options: MutationObserverInit,\n) => {\n let queue = 0;\n const onFrame = () => {\n if (!el.isConnected) return cleanup(); // Stop observing if element is removed from DOM\n callback(observer);\n observer.takeRecords(); // Clear records in case mutations happened during callback\n queue = 0;\n };\n const cleanup = () => observer?.disconnect?.();\n const observer = new MutationObserver(() => {\n if (!SKIP_MUTATIONS && !queue) queue = requestAnimationFrame(onFrame); // requestAnimationFrame only runs when page is visible\n });\n\n observer.observe(el, options);\n requestAnimationFrame(onFrame); // Initial run when page is visible and children has mounted\n return cleanup;\n};\n\n/**\n * Many mutation observers need to watch childNodes, thus running on all `textContent` changes\n * This utility allows skipping mutation observers while updating textContent\n */\nexport const setTextWithoutMutation = (el: Element, text: string | null) => {\n SKIP_MUTATIONS = true;\n el.textContent = text;\n requestAnimationFrame(enableMutations); // Let all mutationobservers run before enabling again\n};\nconst enableMutations = () => {\n SKIP_MUTATIONS = false;\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)\n setTextWithoutMutation(LIVE_EL, `${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":"AAAA,MAAa,EAAc,CAAE,QAAS,GAAM,QAAS,GAAM,CAG9C,MACX,OAAO,OAAW,KAAe,OAAO,SAAa,IAE1C,MACX,GAAW,EAEX,QAAQ,KAAK,UAAU,eAAe,UAAY,UAAU,SAAS,CAG1D,EACX,OAAO,YAAgB,IAClB,KAAM,GACP,YAEN,SAAgB,EACd,EACA,EACA,CACA,IAAI,EAEJ,OAAO,SAAyB,GAAG,EAAS,CAC1C,aAAa,EAAM,CACnB,EAAQ,eAAiB,EAAS,MAAM,KAAM,EAAK,CAAE,EAAM,EAa/D,MAAa,GACX,EACA,GAAG,I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2 @@
|
|
|
1
|
-
import{QUICK_EVENT as e,attr as t,on as n,onHotReload as r}from"../utils/utils.js";import{autoUpdate as i,computePosition as a,flip as o,limitShift as s,offset as c,shift as l,size as u}from"@floating-ui/dom";const d=`data-placement`,f=`data-autoplacement`,p=new Map;function m(e){let{newState:n,oldState:r,target:m,source:h=e.detail}=e,g=m instanceof HTMLElement&&_(m,`--_ds-floating`);if(!g)return;if(n===`closed`)return p.get(m)?.();if(!h){let e=m.getRootNode(),t=`[popovertarget="${m.id}"],[commandfor="${m.id}"]`;h=m.id&&e?.querySelector?.(t)||void 0}if(!h||h===m||r&&r===n)return;let y=_(m,`--_ds-floating-overscroll`),b=t(m,d)||t(h,d)||g,x=t(m,f)||t(h,f),S=parseFloat(getComputedStyle(m,`::before`).height)||0,C=b.match(/left|right/gi)?`Height`:`Width`,w=h[`offset${C}`]/2+S;if(b===`none`)return;let T={strategy:`absolute`,placement:b,middleware:[c(S||0),l({padding:10,limiter:s({offset:{mainAxis:w}})}),v(),...x===`false`?[]:[o({padding:10,crossAxis:!1})],...y?[u({apply({availableHeight:e}){y===`fit`&&(m.style.width=`${h.clientWidth}px`),m.style.maxHeight=`${Math.max(50,e-20)}px`}})]:[]]},E=i(h,m,async()=>{if(!h?.isConnected)return p.get(m)?.();let{x:e,y:t}=await a(h,m,T);m.style.translate=`${e}px ${t}px`});p.set(m,()=>p.delete(m)&&E())}let h;const g=({type:e})=>{if(e===`mousedown`&&(h=!1),e===`scroll`&&h===!1&&(h=!0),e===`mouseup`&&h)for(let[e]of p)e.showPopover()};r(`popover`,()=>[n(document,`mousedown scroll mouseup`,g,!0),n(document,`toggle ds-toggle-source`,m,e)]);const _=(e,t)=>getComputedStyle(e).getPropertyValue(t).trim(),v=()=>({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,on as n,onHotReload as r}from"../utils/utils.js";import{autoUpdate as i,computePosition as a,flip as o,limitShift as s,offset as c,shift as l,size as u}from"@floating-ui/dom";const d=`data-placement`,f=`data-autoplacement`,p=new Map;function m(e){let{newState:n,oldState:r,target:m,source:h=e.detail}=e,g=m instanceof HTMLElement&&t(m,`popover`)!==null&&_(m,`--_ds-floating`);if(!g)return;if(n===`closed`)return p.get(m)?.();if(!h){let e=m.getRootNode(),t=`[popovertarget="${m.id}"],[commandfor="${m.id}"]`;h=m.id&&e?.querySelector?.(t)||void 0}if(!h||h===m||r&&r===n)return;let y=_(m,`--_ds-floating-overscroll`),b=t(m,d)||t(h,d)||g,x=t(m,f)||t(h,f),S=parseFloat(getComputedStyle(m,`::before`).height)||0,C=b.match(/left|right/gi)?`Height`:`Width`,w=h[`offset${C}`]/2+S;if(b===`none`)return;let T={strategy:`absolute`,placement:b,middleware:[c(S||0),l({padding:10,limiter:s({offset:{mainAxis:w}})}),v(),...x===`false`?[]:[o({padding:10,crossAxis:!1})],...y?[u({apply({availableHeight:e}){y===`fit`&&(m.style.width=`${h.clientWidth}px`),m.style.maxHeight=`${Math.max(50,e-20)}px`}})]:[]]},E=i(h,m,async()=>{if(!h?.isConnected)return p.get(m)?.();let{x:e,y:t}=await a(h,m,T);m.style.translate=`${e}px ${t}px`});p.set(m,()=>p.delete(m)&&E())}let h;const g=({type:e})=>{if(e===`mousedown`&&(h=!1),e===`scroll`&&h===!1&&(h=!0),e===`mouseup`&&h)for(let[e]of p)e.showPopover()};r(`popover`,()=>[n(document,`mousedown scroll mouseup`,g,!0),n(document,`toggle ds-toggle-source`,m,e)]);const _=(e,t)=>getComputedStyle(e).getPropertyValue(t).trim(),v=()=>({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 { attr, on, onHotReload, QUICK_EVENT } from '../utils/utils';\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n 'ds-toggle-source': CustomEvent<Element>;\n }\n}\n\nconst ATTR_PLACE = 'data-placement';\nconst ATTR_AUTO = 'data-autoplacement';\nconst POPOVERS = new Map<HTMLElement, () => void>();\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)\nfunction handleToggle(\n event: Partial<ToggleEvent> & {\n detail?: HTMLElement;\n source?: HTMLElement;\n },\n) {\n let { newState, oldState, target: el, source = event.detail } = event;\n const
|
|
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 { attr, on, onHotReload, QUICK_EVENT } from '../utils/utils';\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n 'ds-toggle-source': CustomEvent<Element>;\n }\n}\n\nconst ATTR_PLACE = 'data-placement';\nconst ATTR_AUTO = 'data-autoplacement';\nconst POPOVERS = new Map<HTMLElement, () => void>();\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)\nfunction handleToggle(\n event: Partial<ToggleEvent> & {\n detail?: HTMLElement;\n source?: HTMLElement;\n },\n) {\n let { newState, oldState, target: el, source = event.detail } = event;\n const isPopover = el instanceof HTMLElement && attr(el, 'popover') !== null;\n const float = isPopover && getCSSProp(el, '--_ds-floating');\n\n if (!float) return;\n if (newState === 'closed') return POPOVERS.get(el)?.(); // Cleanup on close\n if (!source) {\n const root = el.getRootNode() as Document; // Support shadow DOM\n const css = `[popovertarget=\"${el.id}\"],[commandfor=\"${el.id}\"]`;\n source = (el.id && root?.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 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(getComputedStyle(el, '::before').height) || 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 const options = {\n strategy: 'absolute',\n placement,\n middleware: [\n offset(arrowSize || 0), // Add space for arrow or default to 8px\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 (overscroll === 'fit')\n el.style.width = `${source.clientWidth}px`;\n el.style.maxHeight = `${Math.max(50, availableHeight - padding * 2)}px`;\n },\n }),\n ]\n : []),\n ],\n } as ComputePositionConfig;\n const unfloat = autoUpdate(source, el, async () => {\n if (!source?.isConnected) return POPOVERS.get(el)?.(); // 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, () => POPOVERS.delete(el) && unfloat());\n}\n\n// Prevent closing when mouse interacts with scrollbar\nlet IS_SCROLL: boolean | undefined;\nconst handleScrollbar = ({ type }: Event) => {\n if (type === 'mousedown') IS_SCROLL = false;\n if (type === 'scroll' && IS_SCROLL === false) IS_SCROLL = true;\n if (type === 'mouseup' && IS_SCROLL)\n for (const [popover] of POPOVERS) popover.showPopover(); // Immediately show again to prevent flicker\n};\n\nonHotReload('popover', () => [\n on(document, 'mousedown scroll mouseup', handleScrollbar, true),\n on(document, 'toggle ds-toggle-source', handleToggle, QUICK_EVENT), // Use capture since the toggle event does not bubble\n]);\n\nconst getCSSProp = (el: Element, prop: string) =>\n getComputedStyle(el).getPropertyValue(prop).trim();\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":"iNAkBA,MAAM,EAAa,iBACb,EAAY,qBACZ,EAAW,IAAI,IAIrB,SAAS,EACP,EAIA,CACA,GAAI,CAAE,WAAU,WAAU,OAAQ,EAAI,SAAS,EAAM,QAAW,EAE1D,EADY,aAAc,aAAe,EAAK,EAAI,UAAU,GAAK,MAC5C,EAAW,EAAI,iBAAiB,CAE3D,GAAI,CAAC,EAAO,OACZ,GAAI,IAAa,SAAU,OAAO,EAAS,IAAI,EAAG,IAAI,CACtD,GAAI,CAAC,EAAQ,CACX,IAAM,EAAO,EAAG,aAAa,CACvB,EAAM,mBAAmB,EAAG,GAAG,kBAAkB,EAAG,GAAG,IAC7D,EAAU,EAAG,IAAM,GAAM,gBAA6B,EAAI,EAAK,IAAA,GAEjE,GAAI,CAAC,GAAU,IAAW,GAAO,GAAY,IAAa,EAAW,OACrE,I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Aa,EAG3D,EAAY,cAAiB,CAC3B,EAAG,SAAU,2BAA4B,EAAiB,GAAK,CAC/D,EAAG,SAAU,0BAA2B,EAAc,EAAY,CACnE,CAAC,CAEF,MAAM,GAAc,EAAa,IAC/B,iBAAiB,EAAG,CAAC,iBAAiB,EAAK,CAAC,MAAM,CAE9C,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,EAAE,CAAC,IACxD,EAAI,GAAG,KAAK,MAAM,EAAO,OAAS,EAAI,EAAO,EAAI,EAAK,EAAE,CAAC,IAK/D,OAHA,EAAO,MAAM,YAAY,yBAA0B,EAAE,CACrD,EAAO,MAAM,YAAY,yBAA0B,EAAE,CACrD,EAAK,EAAQ,gBAAiB,EAAK,UAAU,CACtC,GAEV"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{QUICK_EVENT as e,announce as t,attr as n,attrOrCSS as r,debounce as i,
|
|
1
|
+
import{QUICK_EVENT as e,announce as t,attr as n,attrOrCSS as r,debounce as i,isBrowser as a,on as o,onHotReload as s,onMutation as c,setTextWithoutMutation as l,tag as u,warn as d}from"../utils/utils.js";let f,p,m=0,h=0;const g=a()&&/iPad|iPhone|iPod/.test(navigator.userAgent),_=`data-tooltip`,v=`data-color`,y=`aria-label`,b=`aria-description`,x=`[${v}]`,S=`[${_}]`,C=`data-color-scheme`,w=`[${C}]`,T=e=>{e&&!(e instanceof HTMLElement)&&d(`setTooltipElement expects an HTMLElement, got: `,e),f=e||void 0},E=i(()=>{for(let e of document.querySelectorAll(S)){let i=e.getAttribute(y)||e.getAttribute(b),a=e.getAttribute(_)||r(e,_);if(i!==a){let t=n(e,`role`)!==`img`&&e.textContent?.trim();n(e,_,a),n(e,y,t?null:a),n(e,b,t?a:null),e.matches(`a,button,input,label,select,textarea,[tabindex]`)||d(`Missing tabindex="0" attribute on: `,e)}let o=e===p&&f?.matches(`:popover-open`),s=o&&a&&f?.textContent!==a;o&&s&&(f&&l(f,a),document.activeElement===e&&t(a))}},0),D=({type:e,target:t})=>{if(clearTimeout(m),t===f)return;if(e===`mouseover`&&!p&&!g){m=setTimeout(D,300,{target:t});return}let r=t?.closest?.(`[${_}]`);if(r===p)return;if(!r)return O();f||=u(`div`,{class:`ds-tooltip`}),f.isConnected||document.body.appendChild(f);let i=r.closest(x),a=r.closest(w),o=i!==a&&i?.contains(a);clearTimeout(h),n(f,`popover`,`manual`),n(f,C,a?.getAttribute(C)||null),n(f,v,o&&i?.getAttribute(v)||null),l(f,n(r,_)),f.showPopover(),f.dispatchEvent(new CustomEvent(`ds-toggle-source`,{detail:r})),p=r},O=()=>f?.isConnected&&f.popover&&f.hidePopover(),k=e=>{if(e?.type===`keydown`)return e?.key===`Escape`&&O();e?e.target===f&&e.newState===`closed`&&(h=setTimeout(k,300)):p=void 0};s(`tooltip`,()=>[o(document,`blur focus mouseover`,D,e),o(document,`toggle keydown`,k,e),c(document,E,{attributeFilter:[_],attributes:!0,childList:!0,subtree:!0})]);export{T as setTooltipElement};
|
|
2
2
|
//# sourceMappingURL=tooltip.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tooltip.js","names":[],"sources":["../../../src/tooltip/tooltip.ts"],"sourcesContent":["import {\n announce,\n attr,\n attrOrCSS,\n debounce,\n on,\n onHotReload,\n onMutation,\n QUICK_EVENT,\n setTextWithoutMutation,\n tag,\n warn,\n} from '../utils/utils';\n\nlet TIP: HTMLElement | undefined;\nlet SOURCE: Element | undefined;\nlet HOVER_TIMER: number | ReturnType<typeof setTimeout> = 0;\nlet SKIP_TIMER: number | ReturnType<typeof setTimeout> = 0;\nconst ATTR_TOOLTIP = 'data-tooltip';\nconst ATTR_COLOR = 'data-color';\nconst ARIA_LABEL = 'aria-label';\nconst ARIA_DESC = 'aria-description';\nconst SELECTOR_COLOR = `[${ATTR_COLOR}]`;\nconst SELECTOR_TOOLTIP = `[${ATTR_TOOLTIP}]`;\nconst ATTR_SCHEME = 'data-color-scheme';\nconst SELECTOR_SCHEME = `[${ATTR_SCHEME}]`;\nconst SELECTOR_INTERACTIVE = 'a,button,input,label,select,textarea,[tabindex]';\nconst DELAY_HOVER = 300;\nconst DELAY_SKIP = 300;\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 TIP = el || undefined;\n};\n\nconst handleAriaAttributes = debounce(() => {\n for (const el of document.querySelectorAll(SELECTOR_TOOLTIP)) {\n const aria = el.getAttribute(ARIA_LABEL) || el.getAttribute(ARIA_DESC); // Using getAttribute for best performance\n const text = el.getAttribute(ATTR_TOOLTIP) || attrOrCSS(el, ATTR_TOOLTIP); // Only parse CSS if attribute is empty for better performance\n\n if (aria !== text) {\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.matches(SELECTOR_INTERACTIVE))\n warn('Missing tabindex=\"0\" attribute on: ', el);\n }\n\n // If an existing tooltip has changed programmatically, update tooltip text and announce change\n const isCurrent = el === SOURCE && TIP?.matches(':popover-open');\n const isChanged = isCurrent && text && TIP?.textContent !== text; // Only update if mutation is on source element and tooltip is open to avoid unnecessary updates\n if (isCurrent && isChanged) {\n if (TIP) setTextWithoutMutation(TIP, text);\n if (document.activeElement === el) announce(text); // Only announce if focus is on the button\n }\n }\n}, 0); // Debounce to merge multiple mutations\n\nconst handleInterest = ({ type, target }: Event) => {\n clearTimeout(HOVER_TIMER);\n\n if (target === TIP) return; // Allow tooltip to be hovered, following https://www.w3.org/TR/WCAG21/#content-on-hover-or-focus\n if (type === 'mouseover' && !SOURCE) {\n HOVER_TIMER = setTimeout(handleInterest, DELAY_HOVER, { target }); // Delay mouse showing tooltip if not already shown\n return;\n }\n\n const source = (target as Element)?.closest?.(`[${ATTR_TOOLTIP}]`);\n if (source === SOURCE) return; // No need to update\n if (!source) return hideTooltip(); // If no new anchor, cleanup previous autoUpdate\n if (!TIP) TIP = tag('div', { class: 'ds-tooltip' });\n if (!TIP.isConnected) document.body.appendChild(TIP); // Ensure connected\n\n const color = source.closest(SELECTOR_COLOR); // Match source color of source element\n const scheme = source.closest(SELECTOR_SCHEME); // Match source color-scheme 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 clearTimeout(SKIP_TIMER);\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 setTextWithoutMutation(TIP, attr(source, ATTR_TOOLTIP));\n TIP.showPopover();\n TIP.dispatchEvent(new CustomEvent('ds-toggle-source', { detail: source })); // Since showPopover({ source }) is not supported in all browsers yet\n SOURCE = source;\n};\n\nconst hideTooltip = () => TIP?.isConnected && TIP.popover && TIP.hidePopover(); // Only hide if connected and activated\n\nconst handleClose = (event?: Partial<ToggleEvent & KeyboardEvent>) => {\n if (event?.type === 'keydown')\n return event?.key === 'Escape' && hideTooltip();\n if (!event) SOURCE = undefined;\n else if (event.target === TIP && event.newState === 'closed')\n SKIP_TIMER = setTimeout(handleClose, DELAY_SKIP);\n};\n\nonHotReload('tooltip', () => [\n on(document, 'blur focus mouseover', handleInterest, QUICK_EVENT),\n on(document, 'toggle keydown', handleClose, QUICK_EVENT),\n onMutation(document, handleAriaAttributes, {\n attributeFilter: [ATTR_TOOLTIP],\n attributes: true,\n childList: true,\n subtree: true,\n }),\n]);\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"tooltip.js","names":[],"sources":["../../../src/tooltip/tooltip.ts"],"sourcesContent":["import {\n announce,\n attr,\n attrOrCSS,\n debounce,\n isBrowser,\n on,\n onHotReload,\n onMutation,\n QUICK_EVENT,\n setTextWithoutMutation,\n tag,\n warn,\n} from '../utils/utils';\n\nlet TIP: HTMLElement | undefined;\nlet SOURCE: Element | undefined;\nlet HOVER_TIMER: number | ReturnType<typeof setTimeout> = 0;\nlet SKIP_TIMER: number | ReturnType<typeof setTimeout> = 0;\n/*needed to omit DELAY_HOVER on iOS that otherwise causes interaction delay \n(iOS triggers mouseover before click when an element is tapped)*/\nconst IS_IOS = isBrowser() && /iPad|iPhone|iPod/.test(navigator.userAgent);\nconst ATTR_TOOLTIP = 'data-tooltip';\nconst ATTR_COLOR = 'data-color';\nconst ARIA_LABEL = 'aria-label';\nconst ARIA_DESC = 'aria-description';\nconst SELECTOR_COLOR = `[${ATTR_COLOR}]`;\nconst SELECTOR_TOOLTIP = `[${ATTR_TOOLTIP}]`;\nconst ATTR_SCHEME = 'data-color-scheme';\nconst SELECTOR_SCHEME = `[${ATTR_SCHEME}]`;\nconst SELECTOR_INTERACTIVE = 'a,button,input,label,select,textarea,[tabindex]';\nconst DELAY_HOVER = 300;\nconst DELAY_SKIP = 300;\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 TIP = el || undefined;\n};\n\nconst handleAriaAttributes = debounce(() => {\n for (const el of document.querySelectorAll(SELECTOR_TOOLTIP)) {\n const aria = el.getAttribute(ARIA_LABEL) || el.getAttribute(ARIA_DESC); // Using getAttribute for best performance\n const text = el.getAttribute(ATTR_TOOLTIP) || attrOrCSS(el, ATTR_TOOLTIP); // Only parse CSS if attribute is empty for better performance\n\n if (aria !== text) {\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.matches(SELECTOR_INTERACTIVE))\n warn('Missing tabindex=\"0\" attribute on: ', el);\n }\n\n // If an existing tooltip has changed programmatically, update tooltip text and announce change\n const isCurrent = el === SOURCE && TIP?.matches(':popover-open');\n const isChanged = isCurrent && text && TIP?.textContent !== text; // Only update if mutation is on source element and tooltip is open to avoid unnecessary updates\n if (isCurrent && isChanged) {\n if (TIP) setTextWithoutMutation(TIP, text);\n if (document.activeElement === el) announce(text); // Only announce if focus is on the button\n }\n }\n}, 0); // Debounce to merge multiple mutations\n\nconst handleInterest = ({ type, target }: Event) => {\n clearTimeout(HOVER_TIMER);\n\n if (target === TIP) return; // Allow tooltip to be hovered, following https://www.w3.org/TR/WCAG21/#content-on-hover-or-focus\n if (type === 'mouseover' && !SOURCE && !IS_IOS) {\n HOVER_TIMER = setTimeout(handleInterest, DELAY_HOVER, { target }); // Delay mouse showing tooltip if not already shown\n return;\n }\n\n const source = (target as Element)?.closest?.(`[${ATTR_TOOLTIP}]`);\n if (source === SOURCE) return; // No need to update\n if (!source) return hideTooltip(); // If no new anchor, cleanup previous autoUpdate\n if (!TIP) TIP = tag('div', { class: 'ds-tooltip' });\n if (!TIP.isConnected) document.body.appendChild(TIP); // Ensure connected\n\n const color = source.closest(SELECTOR_COLOR); // Match source color of source element\n const scheme = source.closest(SELECTOR_SCHEME); // Match source color-scheme 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 clearTimeout(SKIP_TIMER);\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 setTextWithoutMutation(TIP, attr(source, ATTR_TOOLTIP));\n TIP.showPopover();\n TIP.dispatchEvent(new CustomEvent('ds-toggle-source', { detail: source })); // Since showPopover({ source }) is not supported in all browsers yet\n SOURCE = source;\n};\n\nconst hideTooltip = () => TIP?.isConnected && TIP.popover && TIP.hidePopover(); // Only hide if connected and activated\n\nconst handleClose = (event?: Partial<ToggleEvent & KeyboardEvent>) => {\n if (event?.type === 'keydown')\n return event?.key === 'Escape' && hideTooltip();\n if (!event) SOURCE = undefined;\n else if (event.target === TIP && event.newState === 'closed')\n SKIP_TIMER = setTimeout(handleClose, DELAY_SKIP);\n};\n\nonHotReload('tooltip', () => [\n on(document, 'blur focus mouseover', handleInterest, QUICK_EVENT),\n on(document, 'toggle keydown', handleClose, QUICK_EVENT),\n onMutation(document, handleAriaAttributes, {\n attributeFilter: [ATTR_TOOLTIP],\n attributes: true,\n childList: true,\n subtree: true,\n }),\n]);\n"],"mappings":"4MAeA,IAAI,EACA,EACA,EAAsD,EACtD,EAAqD,EAGzD,MAAM,EAAS,GAAW,EAAI,mBAAmB,KAAK,UAAU,UAAU,CACpE,EAAe,eACf,EAAa,aACb,EAAa,aACb,EAAY,mBACZ,EAAiB,IAAI,EAAW,GAChC,EAAmB,IAAI,EAAa,GACpC,EAAc,oBACd,EAAkB,IAAI,EAAY,GAU3B,EAAqB,GAA4B,CACxD,GAAM,EAAE,aAAc,cACxB,EAAK,kDAAmD,EAAG,CAC7D,EAAM,GAAM,IAAA,IAGR,EAAuB,MAAe,CAC1C,IAAK,IAAM,KAAM,SAAS,iBAAiB,EAAiB,CAAE,CAC5D,IAAM,EAAO,EAAG,aAAa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AAQ,EAAa,CAAC,CACvD,EAAI,aAAa,CACjB,EAAI,cAAc,IAAI,YAAY,mBAAoB,CAAE,OAAQ,EAAQ,CAAC,CAAC,CAC1E,EAAS,GAGL,MAAoB,GAAK,aAAe,EAAI,SAAW,EAAI,aAAa,CAExE,EAAe,GAAiD,CACpE,GAAI,GAAO,OAAS,UAClB,OAAO,GAAO,MAAQ,UAAY,GAAa,CAC5C,EACI,EAAM,SAAW,GAAO,EAAM,WAAa,WAClD,EAAa,WAAW,EAAa,IAAW,EAFtC,EAAS,IAAA,IAKvB,EAAY,cAAiB,CAC3B,EAAG,SAAU,uBAAwB,EAAgB,EAAY,CACjE,EAAG,SAAU,iBAAkB,EAAa,EAAY,CACxD,EAAW,SAAU,EAAsB,CACzC,gBAAiB,CAAC,EAAa,CAC/B,WAAY,GACZ,UAAW,GACX,QAAS,GACV,CAAC,CACH,CAAC"}
|
package/dist/esm/utils/utils.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={passive:!0,capture:!0},t=()=>typeof window<`u`&&typeof document<`u`,n=()=>t()&&/^Win/i.test(navigator.userAgentData?.platform||navigator.platform),r=typeof HTMLElement>`u`?class{}:HTMLElement;function i(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>e.apply(this,r),t)}}const a=(e,...t)
|
|
1
|
+
const e={passive:!0,capture:!0},t=()=>typeof window<`u`&&typeof document<`u`,n=()=>t()&&/^Win/i.test(navigator.userAgentData?.platform||navigator.platform),r=typeof HTMLElement>`u`?class{}:HTMLElement;function i(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>e.apply(this,r),t)}}const a=(e,...n)=>!t()||window.dsWarnings===!1||console.warn(`Designsystemet: ${e}`,...n),o=(e,t,n)=>n===void 0?e.getAttribute(t)??null:(n===null?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n),null),s=/^["']|["']$/g,c=(e,t)=>{let n=o(e,t);return n||=getComputedStyle(e).getPropertyValue(`--_ds-${t}`).replace(s,``).trim()||null,n||a(`Missing ${t} on:`,e),n},l=(e,...t)=>{let[n,...r]=t;for(let t of n.split(` `))e.addEventListener(t,...r);return()=>u(e,...t)},u=(e,...t)=>{let[n,...r]=t;for(let t of n.split(` `))e.removeEventListener(t,...r)},d=(e,n)=>{t()&&(window._dsHotReloadCleanup||(window._dsHotReloadCleanup=new Map),window._dsHotReloadCleanup?.get(e)?.map(e=>e()),window._dsHotReloadCleanup?.set(e,n()))};let f=!1;const p=(e,t,n)=>{let r=0,i=()=>{if(!e.isConnected)return a();t(o),o.takeRecords(),r=0},a=()=>o?.disconnect?.(),o=new MutationObserver(()=>{!f&&!r&&(r=requestAnimationFrame(i))});return o.observe(e,n),requestAnimationFrame(i),a},m=(e,t)=>{f=!0,e.textContent=t,requestAnimationFrame(h)},h=()=>{f=!1},g=(e,t)=>{let n=document.createElement(e);if(t)for(let[e,r]of Object.entries(t))o(n,e,r);return n},_={define:(e,n)=>!t()||window.customElements.get(e)||window.customElements.define(e,n)};let v=0;function y(e){return t()?(window.dsUseId||(window.dsUseId=0),e&&!e.id&&(e.id=`:ds:${++window.dsUseId}`),e?.id||``):`:ds:${++v}`}let b,x=0,S=0;const C=e=>{clearTimeout(S),b&&m(b,`${e}${x++%2?`\xA0`:``}`),e&&(S=setTimeout(C,2e3,``))},w=()=>{document.readyState===`complete`&&(b||(b=g(`div`,{"aria-live":`assertive`}),b.style.overflow=`hidden`,b.style.position=`fixed`,b.style.whiteSpace=`nowrap`,b.style.width=`1px`),b.isConnected||document.body.appendChild(b))};d(`announce`,()=>[l(document,`focus mouseover`,w,e)]);export{r as DSElement,e as QUICK_EVENT,C as announce,o as attr,c as attrOrCSS,_ as customElements,i as debounce,t as isBrowser,n as isWindows,u as off,l as on,d as onHotReload,p as onMutation,m as setTextWithoutMutation,g as tag,y as useId,a 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 QUICK_EVENT = { passive: true, capture: true };\n\n// Using function instead of constant to support evnironments 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.warn, 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.warn>\n) =>\n typeof window === 'undefined' ||\n window.dsWarnings === false ||\n console.warn(`Designsystemet: ${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) ?? null; // Fallback to null only if el is undefined\n if (value === null) el.removeAttribute(name);\n else if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n return null;\n};\n\nconst STRIP_SURROUNDING_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 const prop = getComputedStyle(el).getPropertyValue(`--_ds-${name}`);\n value = prop.replace(STRIP_SURROUNDING_QUOTES, '').trim() || null;\n }\n if (!value) warn(`Missing ${name} on:`, el);\n return value;\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\ndeclare global {\n interface Window {\n _dsHotReloadCleanup?: 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._dsHotReloadCleanup) window._dsHotReloadCleanup = new Map(); // Hot reload cleanup support supporting all build tools\n\n window._dsHotReloadCleanup?.get(key)?.map((cleanup) => cleanup()); // Run previous cleanup\n window._dsHotReloadCleanup?.set(key, setup()); // Store new cleanup\n};\n\n/**\n * Speed up MutationObserver by debouncing and only running when page is visible\n * @return new MutaionObserver\n */\nlet SKIP_MUTATIONS = false;\nexport const onMutation = (\n el: Node,\n callback: (observer: MutationObserver) => void,\n options: MutationObserverInit,\n) => {\n let queue = 0;\n const onFrame = () => {\n if (!el.isConnected) return cleanup(); // Stop observing if element is removed from DOM\n callback(observer);\n observer.takeRecords(); // Clear records in case mutations happened during callback\n queue = 0;\n };\n const cleanup = () => observer?.disconnect?.();\n const observer = new MutationObserver(() => {\n if (!SKIP_MUTATIONS && !queue) queue = requestAnimationFrame(onFrame); // requestAnimationFrame only runs when page is visible\n });\n\n observer.observe(el, options);\n requestAnimationFrame(onFrame); // Initial run when page is visible and children has mounted\n return cleanup;\n};\n\n/**\n * Many mutation observers need to watch childNodes, thus running on all `textContent` changes\n * This utility allows skipping mutation observers while updating textContent\n */\nexport const setTextWithoutMutation = (el: Element, text: string | null) => {\n SKIP_MUTATIONS = true;\n el.textContent = text;\n requestAnimationFrame(enableMutations); // Let all mutationobservers run before enabling again\n};\nconst enableMutations = () => {\n SKIP_MUTATIONS = false;\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 */\nlet id = 0;\nconst hash = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`;\nexport function useId(el?: Element | null) {\n if (el && !el.id) el.id = `${hash}${++id}`;\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)\n setTextWithoutMutation(LIVE_EL, `${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":"AAAA,MAAa,EAAc,CAAE,QAAS,GAAM,QAAS,GAAM,CAG9C,MACX,OAAO,OAAW,KAAe,OAAO,SAAa,IAE1C,MACX,GAAW,EAEX,QAAQ,KAAK,UAAU,eAAe,UAAY,UAAU,SAAS,CAG1D,EACX,OAAO,YAAgB,IAClB,KAAM,GACP,YAEN,SAAgB,EACd,EACA,EACA,CACA,IAAI,EAEJ,OAAO,SAAyB,GAAG,EAAS,CAC1C,aAAa,EAAM,CACnB,EAAQ,eAAiB,EAAS,MAAM,KAAM,EAAK,CAAE,EAAM,EAa/D,MAAa,GACX,EACA,GAAG,IAEH,OAAO,OAAW,KAClB,OAAO,aAAe,IACtB,QAAQ,KAAK,mBAAmB,IAAW,GAAG,EAAK,CASxC,GACX,EACA,EACA,IAEI,IAAU,IAAA,GAAkB,EAAG,aAAa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0B,EAAa,IAAwB,CAC1E,EAAiB,GACjB,EAAG,YAAc,EACjB,sBAAsB,EAAgB,EAElC,MAAwB,CAC5B,EAAiB,IAWN,GACX,EACA,IACmC,CACnC,IAAM,EAAK,SAAS,cAAc,EAAQ,CAC1C,GAAI,EAAO,IAAK,GAAM,CAAC,EAAK,KAAQ,OAAO,QAAQ,EAAM,CAAE,EAAK,EAAI,EAAK,EAAI,CAC7E,OAAO,GAQI,EAAiB,CAC5B,QAAS,EAAc,IACrB,CAAC,GAAW,EACZ,OAAO,eAAe,IAAI,EAAK,EAC/B,OAAO,eAAe,OAAO,EAAM,EAAS,CAC/C,CAMD,IAAI,EAAK,EACT,MAAM,EAAO,GAAG,KAAK,KAAK,CAAC,SAAS,GAAG,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAG,EAAE,GAChF,SAAgB,EAAM,EAAqB,CAEzC,OADI,GAAM,CAAC,EAAG,KAAI,EAAG,GAAK,GAAG,IAAO,EAAE,KAC/B,GAAI,IAAM,GAOnB,IAAI,EACA,EAAW,EACX,EAAqD,EACzD,MAAa,EAAY,GAAiB,CACxC,aAAa,EAAW,CACpB,GACF,EAAuB,EAAS,GAAG,IAAO,IAAa,EAAI,OAAW,KAAK,CACzE,IAAM,EAAa,WAAW,EAAU,IAAM,GAAG,GAIjD,MAAsB,CACtB,SAAS,aAAe,aACvB,IACH,EAAU,EAAI,MAAO,CAAE,YAAa,YAAa,CAAC,CAClD,EAAQ,MAAM,SAAW,SACzB,EAAQ,MAAM,SAAW,QACzB,EAAQ,MAAM,WAAa,SAC3B,EAAQ,MAAM,MAAQ,OAEnB,EAAQ,aAAa,SAAS,KAAK,YAAY,EAAQ,GAE9D,EAAY,eAAkB,CAC5B,EAAG,SAAU,kBAAmB,EAAe,EAAY,CAC5D,CAAC"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../src/utils/utils.ts"],"sourcesContent":["export const QUICK_EVENT = { passive: true, capture: true };\n\n// Using function instead of constant to support evnironments 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.warn, 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.warn>\n) =>\n !isBrowser() ||\n window.dsWarnings === false ||\n console.warn(`Designsystemet: ${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) ?? null; // Fallback to null only if el is undefined\n if (value === null) el.removeAttribute(name);\n else if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n return null;\n};\n\nconst STRIP_SURROUNDING_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 const prop = getComputedStyle(el).getPropertyValue(`--_ds-${name}`);\n value = prop.replace(STRIP_SURROUNDING_QUOTES, '').trim() || null;\n }\n if (!value) warn(`Missing ${name} on:`, el);\n return value;\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\ndeclare global {\n interface Window {\n _dsHotReloadCleanup?: 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._dsHotReloadCleanup) window._dsHotReloadCleanup = new Map(); // Hot reload cleanup support supporting all build tools\n\n window._dsHotReloadCleanup?.get(key)?.map((cleanup) => cleanup()); // Run previous cleanup\n window._dsHotReloadCleanup?.set(key, setup()); // Store new cleanup\n};\n\n/**\n * Speed up MutationObserver by debouncing and only running when page is visible\n * @return new MutaionObserver\n */\nlet SKIP_MUTATIONS = false;\nexport const onMutation = (\n el: Node,\n callback: (observer: MutationObserver) => void,\n options: MutationObserverInit,\n) => {\n let queue = 0;\n const onFrame = () => {\n if (!el.isConnected) return cleanup(); // Stop observing if element is removed from DOM\n callback(observer);\n observer.takeRecords(); // Clear records in case mutations happened during callback\n queue = 0;\n };\n const cleanup = () => observer?.disconnect?.();\n const observer = new MutationObserver(() => {\n if (!SKIP_MUTATIONS && !queue) queue = requestAnimationFrame(onFrame); // requestAnimationFrame only runs when page is visible\n });\n\n observer.observe(el, options);\n requestAnimationFrame(onFrame); // Initial run when page is visible and children has mounted\n return cleanup;\n};\n\n/**\n * Many mutation observers need to watch childNodes, thus running on all `textContent` changes\n * This utility allows skipping mutation observers while updating textContent\n */\nexport const setTextWithoutMutation = (el: Element, text: string | null) => {\n SKIP_MUTATIONS = true;\n el.textContent = text;\n requestAnimationFrame(enableMutations); // Let all mutationobservers run before enabling again\n};\nconst enableMutations = () => {\n SKIP_MUTATIONS = false;\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)\n setTextWithoutMutation(LIVE_EL, `${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":"AAAA,MAAa,EAAc,CAAE,QAAS,GAAM,QAAS,GAAM,CAG9C,MACX,OAAO,OAAW,KAAe,OAAO,SAAa,IAE1C,MACX,GAAW,EAEX,QAAQ,KAAK,UAAU,eAAe,UAAY,UAAU,SAAS,CAG1D,EACX,OAAO,YAAgB,IAClB,KAAM,GACP,YAEN,SAAgB,EACd,EACA,EACA,CACA,IAAI,EAEJ,OAAO,SAAyB,GAAG,EAAS,CAC1C,aAAa,EAAM,CACnB,EAAQ,eAAiB,EAAS,MAAM,KAAM,EAAK,CAAE,EAAM,EAa/D,MAAa,GACX,EACA,GAAG,IAEH,CAAC,GAAW,EACZ,OAAO,aAAe,IACtB,QAAQ,KAAK,mBAAmB,IAAW,GAAG,EAAK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const onMutation: (el: Node, callback: (observer: MutationObserver) => void, options: MutationObserverInit) => () => void;
|
|
37
|
+
/**
|
|
38
|
+
* useId
|
|
39
|
+
* @return A generated unique ID
|
|
40
|
+
*/
|
|
41
|
+
declare global {
|
|
42
|
+
interface Window {
|
|
43
|
+
dsUseId?: number;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
37
46
|
|
|
38
47
|
declare global {
|
|
39
48
|
interface HTMLElementTagNameMap {
|
package/dist/index.js
CHANGED
|
@@ -15,7 +15,7 @@ function debounce(callback, delay) {
|
|
|
15
15
|
timer = setTimeout(() => callback.apply(this, args), delay);
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
|
-
var warn = (message, ...args) =>
|
|
18
|
+
var warn = (message, ...args) => !isBrowser() || window.dsWarnings === false || console.warn(`Designsystemet: ${message}`, ...args);
|
|
19
19
|
var attr = (el, name, value) => {
|
|
20
20
|
if (value === void 0) return el.getAttribute(name) ?? null;
|
|
21
21
|
if (value === null) el.removeAttribute(name);
|
|
@@ -81,9 +81,10 @@ var customElements = {
|
|
|
81
81
|
define: (name, instance) => !isBrowser() || window.customElements.get(name) || window.customElements.define(name, instance)
|
|
82
82
|
};
|
|
83
83
|
var id = 0;
|
|
84
|
-
var hash = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`;
|
|
85
84
|
function useId(el) {
|
|
86
|
-
if (
|
|
85
|
+
if (!isBrowser()) return `:ds:${++id}`;
|
|
86
|
+
if (!window.dsUseId) window.dsUseId = 0;
|
|
87
|
+
if (el && !el.id) el.id = `:ds:${++window.dsUseId}`;
|
|
87
88
|
return el?.id || "";
|
|
88
89
|
}
|
|
89
90
|
var LIVE_EL;
|
|
@@ -200,7 +201,8 @@ var ATTR_AUTO = "data-autoplacement";
|
|
|
200
201
|
var POPOVERS = /* @__PURE__ */ new Map();
|
|
201
202
|
function handleToggle(event) {
|
|
202
203
|
let { newState, oldState, target: el, source = event.detail } = event;
|
|
203
|
-
const
|
|
204
|
+
const isPopover = el instanceof HTMLElement && attr(el, "popover") !== null;
|
|
205
|
+
const float = isPopover && getCSSProp(el, "--_ds-floating");
|
|
204
206
|
if (!float) return;
|
|
205
207
|
if (newState === "closed") return POPOVERS.get(el)?.();
|
|
206
208
|
if (!source) {
|
|
@@ -348,6 +350,7 @@ var TIP;
|
|
|
348
350
|
var SOURCE;
|
|
349
351
|
var HOVER_TIMER = 0;
|
|
350
352
|
var SKIP_TIMER = 0;
|
|
353
|
+
var IS_IOS = isBrowser() && /iPad|iPhone|iPod/.test(navigator.userAgent);
|
|
351
354
|
var ATTR_TOOLTIP = "data-tooltip";
|
|
352
355
|
var ATTR_COLOR = "data-color";
|
|
353
356
|
var ARIA_LABEL = "aria-label";
|
|
@@ -387,7 +390,7 @@ var handleAriaAttributes3 = debounce(() => {
|
|
|
387
390
|
var handleInterest = ({ type, target }) => {
|
|
388
391
|
clearTimeout(HOVER_TIMER);
|
|
389
392
|
if (target === TIP) return;
|
|
390
|
-
if (type === "mouseover" && !SOURCE) {
|
|
393
|
+
if (type === "mouseover" && !SOURCE && !IS_IOS) {
|
|
391
394
|
HOVER_TIMER = setTimeout(handleInterest, DELAY_HOVER, { target });
|
|
392
395
|
return;
|
|
393
396
|
}
|