diff --git a/.gitignore b/.gitignore index 3c3629e..f06235c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ node_modules +dist diff --git a/.prettierignore b/.prettierignore index 89c86f6..a3414d0 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,2 @@ dist -package-lock.json CHANGELOG.md -demo/demo.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 60adc5a..0059119 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Changed +- Upgrade to `@floating-ui/dom` 1.0.0. +- Switch build tool from Rollup to Vite. ## [0.1.3] - 2022-06-05 ### Added diff --git a/README.md b/README.md index 794a1d0..444a509 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Accessible, lightweight, unstyled implementations of common UI controls.** -[**Demo**](https://tobyzerner.github.io/inclusive-elements/demo/index.html) +[**Demo**](https://tobyzerner.github.io/inclusive-elements/index.html) Basic interactive UI patterns like popup menus, tooltips, and modals are surprisingly hard to get right on the web. Component libraries tend to be weighty, opinionated, and come tightly coupled with styles you don't want. On the other hand, rolling your own components feels like you're reinventing the wheel and puts accessibility at risk. diff --git a/demo/demo.js b/demo/demo.js deleted file mode 100644 index 474995d..0000000 --- a/demo/demo.js +++ /dev/null @@ -1,10 +0,0 @@ -function t(t,e,n={}){const i=new WeakMap,o=s(n);t instanceof HTMLCollection&&(t=Array.from(t)),t.forEach((t=>{"none"!==getComputedStyle(t).display&&i.set(t,t.getBoundingClientRect())})),e(),t.forEach((t=>{const e=i.get(t);if(!e)return;const n=e.left-t.getBoundingClientRect().left,s=e.top-t.getBoundingClientRect().top;if(!n&&!s)return;const a=t.style;a.transitionDuration="0s",a.transform=`translate(${n}px, ${s}px)`,document.body.offsetWidth,a.transitionDuration=a.transform="",t.classList.add(o+"move"),r(t,(()=>{t.classList.remove(o+"move")}))}))}function e(t){t._currentTransition&&(t.classList.remove(...["active","from","to"].map((e=>t._currentTransition+e))),t._currentTransition=null)}function n(t,n,i={}){const o=s(i)+n+"-",a=t.classList;var c;e(t),t._currentTransition=o,a.add(o+"active",o+"from"),c=()=>{a.add(o+"to"),a.remove(o+"from"),r(t,(()=>{a.remove(o+"to",o+"active"),t._currentTransition===o&&(i.finish&&i.finish(),t._currentTransition=null)}))},requestAnimationFrame((()=>{requestAnimationFrame(c)}))}function i(t,e={}){n(t,"enter",e)}function o(t,e={}){n(t,"leave",e)}function r(t,e){if(getComputedStyle(t).transitionDuration.startsWith("0s"))e();else{const n=()=>{e(),t.removeEventListener("transitionend",n),t.removeEventListener("transitioncancel",n)};t.addEventListener("transitionend",n),t.addEventListener("transitioncancel",n)}}function s(t){return t.prefix?t.prefix+"-":""} -/*! -* tabbable 5.2.1 -* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE -*/var a=["input","select","textarea","a[href]","button","[tabindex]","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable="false"])',"details>summary:first-of-type","details"],c=a.join(","),l="undefined"==typeof Element?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,u=function(t,e,n){var i=Array.prototype.slice.apply(t.querySelectorAll(c));return e&&l.call(t,c)&&i.unshift(t),i=i.filter(n)},d=function(t){var e=parseInt(t.getAttribute("tabindex"),10);return isNaN(e)?function(t){return"true"===t.contentEditable}(t)?0:"AUDIO"!==t.nodeName&&"VIDEO"!==t.nodeName&&"DETAILS"!==t.nodeName||null!==t.getAttribute("tabindex")?t.tabIndex:0:e},h=function(t,e){return t.tabIndex===e.tabIndex?t.documentOrder-e.documentOrder:t.tabIndex-e.tabIndex},f=function(t){return"INPUT"===t.tagName},p=function(t){return function(t){return f(t)&&"radio"===t.type}(t)&&!function(t){if(!t.name)return!0;var e,n=t.form||t.ownerDocument,i=function(t){return n.querySelectorAll('input[type="radio"][name="'+t+'"]')};if("undefined"!=typeof window&&void 0!==window.CSS&&"function"==typeof window.CSS.escape)e=i(window.CSS.escape(t.name));else try{e=i(t.name)}catch(t){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",t.message),!1}var o=function(t,e){for(var n=0;nsummary:first-of-type")?t.parentElement:t;if(l.call(n,"details:not([open]) *"))return!0;if(e&&"full"!==e){if("non-zero-area"===e){var i=t.getBoundingClientRect(),o=i.width,r=i.height;return 0===o&&0===r}}else for(;t;){if("none"===getComputedStyle(t).display)return!0;t=t.parentElement}return!1}(e,t.displayCheck)||function(t){return"DETAILS"===t.tagName&&Array.prototype.slice.apply(t.children).some((function(t){return"SUMMARY"===t.tagName}))}(e)||function(t){if(f(t)||"SELECT"===t.tagName||"TEXTAREA"===t.tagName||"BUTTON"===t.tagName)for(var e=t.parentElement;e;){if("FIELDSET"===e.tagName&&e.disabled){for(var n=0;n0){var e=T[T.length-1];e!==t&&e.pause()}var n=T.indexOf(t);-1===n||T.splice(n,1),T.push(t)},deactivateTrap:function(t){var e=T.indexOf(t);-1!==e&&T.splice(e,1),T.length>0&&T[T.length-1].unpause()}}),k=function(t){return setTimeout(t,0)},A=function(t,e){var n=-1;return t.every((function(t,i){return!e(t)||(n=i,!1)})),n},C=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i1?n-1:0),s=1;s0)return{container:t,firstTabbableNode:o[0],lastTabbableNode:o[o.length-1]}})).filter((function(t){return!!t})),r.tabbableGroups.length<=0&&!c("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times")},p=function t(e){!1!==e&&e!==i.activeElement&&(e&&e.focus?(e.focus({preventScroll:!!o.preventScroll}),r.mostRecentlyFocusedNode=e,function(t){return t.tagName&&"input"===t.tagName.toLowerCase()&&"function"==typeof t.select}(e)&&e.select()):t(l()))},m=function(t){var e=c("setReturnFocus",t);return e||!1!==e&&t},v=function(t){var e=D(t);a(e)||(C(o.clickOutsideDeactivates,t)?n.deactivate({returnFocus:o.returnFocusOnDeactivate&&!w(e)}):C(o.allowOutsideClick,t)||t.preventDefault())},y=function(t){var e=D(t),n=a(e);n||e instanceof Document?n&&(r.mostRecentlyFocusedNode=e):(t.stopImmediatePropagation(),p(r.mostRecentlyFocusedNode||l()))},T=function(t){if(function(t){return"Escape"===t.key||"Esc"===t.key||27===t.keyCode}(t)&&!1!==C(o.escapeDeactivates,t))return t.preventDefault(),void n.deactivate();(function(t){return"Tab"===t.key||9===t.keyCode})(t)&&function(t){var e=D(t);f();var n=null;if(r.tabbableGroups.length>0){var i=A(r.tabbableGroups,(function(t){return t.container.contains(e)}));if(i<0)n=t.shiftKey?r.tabbableGroups[r.tabbableGroups.length-1].lastTabbableNode:r.tabbableGroups[0].firstTabbableNode;else if(t.shiftKey){var o=A(r.tabbableGroups,(function(t){var n=t.firstTabbableNode;return e===n}));if(o<0&&(r.tabbableGroups[i].container===e||w(e)&&!g(e))&&(o=i),o>=0){var s=0===o?r.tabbableGroups.length-1:o-1;n=r.tabbableGroups[s].lastTabbableNode}}else{var a=A(r.tabbableGroups,(function(t){var n=t.lastTabbableNode;return e===n}));if(a<0&&(r.tabbableGroups[i].container===e||w(e)&&!g(e))&&(a=i),a>=0){var l=a===r.tabbableGroups.length-1?0:a+1;n=r.tabbableGroups[l].firstTabbableNode}}}else n=c("fallbackFocus");n&&(t.preventDefault(),p(n))}(t)},O=function(t){if(!C(o.clickOutsideDeactivates,t)){var e=D(t);a(e)||C(o.allowOutsideClick,t)||(t.preventDefault(),t.stopImmediatePropagation())}},N=function(){if(r.active)return L.activateTrap(n),r.delayInitialFocusTimer=o.delayInitialFocus?k((function(){p(l())})):p(l()),i.addEventListener("focusin",y,!0),i.addEventListener("mousedown",v,{capture:!0,passive:!1}),i.addEventListener("touchstart",v,{capture:!0,passive:!1}),i.addEventListener("click",O,{capture:!0,passive:!1}),i.addEventListener("keydown",T,{capture:!0,passive:!1}),n},R=function(){if(r.active)return i.removeEventListener("focusin",y,!0),i.removeEventListener("mousedown",v,!0),i.removeEventListener("touchstart",v,!0),i.removeEventListener("click",O,!0),i.removeEventListener("keydown",T,!0),n};return(n={activate:function(t){if(r.active)return this;var e=s(t,"onActivate"),n=s(t,"onPostActivate"),o=s(t,"checkCanFocusTrap");o||f(),r.active=!0,r.paused=!1,r.nodeFocusedBeforeActivation=i.activeElement,e&&e();var a=function(){o&&f(),N(),n&&n()};return o?(o(r.containers.concat()).then(a,a),this):(a(),this)},deactivate:function(t){if(!r.active)return this;clearTimeout(r.delayInitialFocusTimer),r.delayInitialFocusTimer=void 0,R(),r.active=!1,r.paused=!1,L.deactivateTrap(n);var e=s(t,"onDeactivate"),i=s(t,"onPostDeactivate"),o=s(t,"checkCanReturnFocus");e&&e();var a=s(t,"returnFocus","returnFocusOnDeactivate"),c=function(){k((function(){a&&p(m(r.nodeFocusedBeforeActivation)),i&&i()}))};return a&&o?(o(m(r.nodeFocusedBeforeActivation)).then(c,c),this):(c(),this)},pause:function(){return r.paused||!r.active||(r.paused=!0,R()),this},unpause:function(){return r.paused&&r.active?(r.paused=!1,f(),N(),this):this},updateContainerElements:function(t){var e=[].concat(t).filter(Boolean);return r.containers=e.map((function(t){return"string"==typeof t?i.querySelector(t):t})),r.active&&f(),this}}).updateContainerElements(t),n};function N(t){return t.split("-")[0]}function R(t){return t.split("-")[1]}function S(t){return["top","bottom"].includes(N(t))?"x":"y"}function F(t){return"y"===t?"height":"width"}function I(t,e,n){let{reference:i,floating:o}=t;const r=i.x+i.width/2-o.width/2,s=i.y+i.height/2-o.height/2,a=S(e),c=F(a),l=i[c]/2-o[c]/2,u="x"===a;let d;switch(N(e)){case"top":d={x:r,y:i.y-o.height};break;case"bottom":d={x:r,y:i.y+i.height};break;case"right":d={x:i.x+i.width,y:s};break;case"left":d={x:i.x-o.width,y:s};break;default:d={x:i.x,y:i.y}}switch(R(e)){case"start":d[a]-=l*(n&&u?-1:1);break;case"end":d[a]+=l*(n&&u?-1:1)}return d}function P(t){return{...t,top:t.y,left:t.x,right:t.x+t.width,bottom:t.y+t.height}}async function H(t,e){var n;void 0===e&&(e={});const{x:i,y:o,platform:r,rects:s,elements:a,strategy:c}=t,{boundary:l="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:h=!1,padding:f=0}=e,p=function(t){return"number"!=typeof t?function(t){return{top:0,right:0,bottom:0,left:0,...t}}(t):{top:t,right:t,bottom:t,left:t}}(f),m=a[h?"floating"===d?"reference":"floating":d],b=P(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(m)))||n?m:m.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:l,rootBoundary:u,strategy:c})),v=P(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({rect:"floating"===d?{...s.floating,x:i,y:o}:s.reference,offsetParent:await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),strategy:c}):s[d]);return{top:b.top-v.top+p.top,bottom:v.bottom-b.bottom+p.bottom,left:b.left-v.left+p.left,right:v.right-b.right+p.right}}const M=Math.min,j=Math.max;function B(t,e,n){return j(t,M(e,n))}const W={left:"right",right:"left",bottom:"top",top:"bottom"};function G(t){return t.replace(/left|right|bottom|top/g,(t=>W[t]))}const K={start:"end",end:"start"};function q(t){return t.replace(/start|end/g,(t=>K[t]))}const V=function(t){return void 0===t&&(t={}),{name:"flip",options:t,async fn(e){var n;const{placement:i,middlewareData:o,rects:r,initialPlacement:s,platform:a,elements:c}=e,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:h="bestFit",flipAlignment:f=!0,...p}=t,m=N(i),b=[s,...d||(m===s||!f?[G(s)]:function(t){const e=G(t);return[q(t),e,q(e)]}(s))],v=await H(e,p),g=[];let y=(null==(n=o.flip)?void 0:n.overflows)||[];if(l&&g.push(v[m]),u){const{main:t,cross:e}=function(t,e,n){void 0===n&&(n=!1);const i=R(t),o=S(t),r=F(o);let s="x"===o?i===(n?"end":"start")?"right":"left":"start"===i?"bottom":"top";return e.reference[r]>e.floating[r]&&(s=G(s)),{main:s,cross:G(s)}}(i,r,await(null==a.isRTL?void 0:a.isRTL(c.floating)));g.push(v[t],v[e])}if(y=[...y,{placement:i,overflows:g}],!g.every((t=>t<=0))){var w,E;const t=(null!=(w=null==(E=o.flip)?void 0:E.index)?w:0)+1,e=b[t];if(e)return{data:{index:t,overflows:y},reset:{placement:e}};let n="bottom";switch(h){case"bestFit":{var x;const t=null==(x=y.map((t=>[t,t.overflows.filter((t=>t>0)).reduce(((t,e)=>t+e),0)])).sort(((t,e)=>t[1]-e[1]))[0])?void 0:x[0].placement;t&&(n=t);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}};const U=function(t){return void 0===t&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:i,placement:o}=e,{mainAxis:r=!0,crossAxis:s=!1,limiter:a={fn:t=>{let{x:e,y:n}=t;return{x:e,y:n}}},...c}=t,l={x:n,y:i},u=await H(e,c),d=S(N(o)),h="x"===d?"y":"x";let f=l[d],p=l[h];if(r){const t="y"===d?"bottom":"right";f=B(f+u["y"===d?"top":"left"],f,f-u[t])}if(s){const t="y"===h?"bottom":"right";p=B(p+u["y"===h?"top":"left"],p,p-u[t])}const m=a.fn({...e,[d]:f,[h]:p});return{...m,data:{x:m.x-n,y:m.y-i}}}}};function $(t){return t&&t.document&&t.location&&t.alert&&t.setInterval}function z(t){if(null==t)return window;if(!$(t)){const e=t.ownerDocument;return e&&e.defaultView||window}return t}function _(t){return z(t).getComputedStyle(t)}function Y(t){return $(t)?"":t?(t.nodeName||"").toLowerCase():""}function X(){const t=navigator.userAgentData;return null!=t&&t.brands?t.brands.map((t=>t.brand+"/"+t.version)).join(" "):navigator.userAgent}function J(t){return t instanceof z(t).HTMLElement}function Q(t){return t instanceof z(t).Element}function Z(t){if("undefined"==typeof ShadowRoot)return!1;return t instanceof z(t).ShadowRoot||t instanceof ShadowRoot}function tt(t){const{overflow:e,overflowX:n,overflowY:i}=_(t);return/auto|scroll|overlay|hidden/.test(e+i+n)}function et(t){return["table","td","th"].includes(Y(t))}function nt(t){const e=/firefox/i.test(X()),n=_(t);return"none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||["transform","perspective"].includes(n.willChange)||e&&"filter"===n.willChange||e&&!!n.filter&&"none"!==n.filter}function it(){return!/^((?!chrome|android).)*safari/i.test(X())}const ot=Math.min,rt=Math.max,st=Math.round;function at(t,e,n){var i,o,r,s;void 0===e&&(e=!1),void 0===n&&(n=!1);const a=t.getBoundingClientRect();let c=1,l=1;e&&J(t)&&(c=t.offsetWidth>0&&st(a.width)/t.offsetWidth||1,l=t.offsetHeight>0&&st(a.height)/t.offsetHeight||1);const u=Q(t)?z(t):window,d=!it()&&n,h=(a.left+(d&&null!=(i=null==(o=u.visualViewport)?void 0:o.offsetLeft)?i:0))/c,f=(a.top+(d&&null!=(r=null==(s=u.visualViewport)?void 0:s.offsetTop)?r:0))/l,p=a.width/c,m=a.height/l;return{width:p,height:m,top:f,right:h+p,bottom:f+m,left:h,x:h,y:f}}function ct(t){return(e=t,(e instanceof z(e).Node?t.ownerDocument:t.document)||window.document).documentElement;var e}function lt(t){return Q(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.pageXOffset,scrollTop:t.pageYOffset}}function ut(t){return at(ct(t)).left+lt(t).scrollLeft}function dt(t,e,n){const i=J(e),o=ct(e),r=at(t,i&&function(t){const e=at(t);return st(e.width)!==t.offsetWidth||st(e.height)!==t.offsetHeight}(e),"fixed"===n);let s={scrollLeft:0,scrollTop:0};const a={x:0,y:0};if(i||!i&&"fixed"!==n)if(("body"!==Y(e)||tt(o))&&(s=lt(e)),J(e)){const t=at(e,!0);a.x=t.x+e.clientLeft,a.y=t.y+e.clientTop}else o&&(a.x=ut(o));return{x:r.left+s.scrollLeft-a.x,y:r.top+s.scrollTop-a.y,width:r.width,height:r.height}}function ht(t){return"html"===Y(t)?t:t.assignedSlot||t.parentNode||(Z(t)?t.host:null)||ct(t)}function ft(t){return J(t)&&"fixed"!==getComputedStyle(t).position?t.offsetParent:null}function pt(t){const e=z(t);let n=ft(t);for(;n&&et(n)&&"static"===getComputedStyle(n).position;)n=ft(n);return n&&("html"===Y(n)||"body"===Y(n)&&"static"===getComputedStyle(n).position&&!nt(n))?e:n||function(t){let e=ht(t);for(Z(e)&&(e=e.host);J(e)&&!["html","body"].includes(Y(e));){if(nt(e))return e;e=e.parentNode}return null}(t)||e}function mt(t){if(J(t))return{width:t.offsetWidth,height:t.offsetHeight};const e=at(t);return{width:e.width,height:e.height}}function bt(t){const e=ht(t);return["html","body","#document"].includes(Y(e))?t.ownerDocument.body:J(e)&&tt(e)?e:bt(e)}function vt(t,e){var n;void 0===e&&(e=[]);const i=bt(t),o=i===(null==(n=t.ownerDocument)?void 0:n.body),r=z(i),s=o?[r].concat(r.visualViewport||[],tt(i)?i:[]):i,a=e.concat(s);return o?a:a.concat(vt(s))}function gt(t,e,n){return"viewport"===e?P(function(t,e){const n=z(t),i=ct(t),o=n.visualViewport;let r=i.clientWidth,s=i.clientHeight,a=0,c=0;if(o){r=o.width,s=o.height;const t=it();(t||!t&&"fixed"===e)&&(a=o.offsetLeft,c=o.offsetTop)}return{width:r,height:s,x:a,y:c}}(t,n)):Q(e)?function(t,e){const n=at(t,!1,"fixed"===e),i=n.top+t.clientTop,o=n.left+t.clientLeft;return{top:i,left:o,x:o,y:i,right:o+t.clientWidth,bottom:i+t.clientHeight,width:t.clientWidth,height:t.clientHeight}}(e,n):P(function(t){var e;const n=ct(t),i=lt(t),o=null==(e=t.ownerDocument)?void 0:e.body,r=rt(n.scrollWidth,n.clientWidth,o?o.scrollWidth:0,o?o.clientWidth:0),s=rt(n.scrollHeight,n.clientHeight,o?o.scrollHeight:0,o?o.clientHeight:0);let a=-i.scrollLeft+ut(t);const c=-i.scrollTop;return"rtl"===_(o||n).direction&&(a+=rt(n.clientWidth,o?o.clientWidth:0)-r),{width:r,height:s,x:a,y:c}}(ct(t)))}function yt(t){const e=vt(t),n=["absolute","fixed"].includes(_(t).position)&&J(t)?pt(t):t;return Q(n)?e.filter((t=>Q(t)&&function(t,e){const n=null==e.getRootNode?void 0:e.getRootNode();if(t.contains(e))return!0;if(n&&Z(n)){let n=e;do{if(n&&t===n)return!0;n=n.parentNode||n.host}while(n)}return!1}(t,n)&&"body"!==Y(t))):[]}const wt={getClippingRect:function(t){let{element:e,boundary:n,rootBoundary:i,strategy:o}=t;const r=[..."clippingAncestors"===n?yt(e):[].concat(n),i],s=r[0],a=r.reduce(((t,n)=>{const i=gt(e,n,o);return t.top=rt(i.top,t.top),t.right=ot(i.right,t.right),t.bottom=ot(i.bottom,t.bottom),t.left=rt(i.left,t.left),t}),gt(e,s,o));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}},convertOffsetParentRelativeRectToViewportRelativeRect:function(t){let{rect:e,offsetParent:n,strategy:i}=t;const o=J(n),r=ct(n);if(n===r)return e;let s={scrollLeft:0,scrollTop:0};const a={x:0,y:0};if((o||!o&&"fixed"!==i)&&(("body"!==Y(n)||tt(r))&&(s=lt(n)),J(n))){const t=at(n,!0);a.x=t.x+n.clientLeft,a.y=t.y+n.clientTop}return{...e,x:e.x-s.scrollLeft+a.x,y:e.y-s.scrollTop+a.y}},isElement:Q,getDimensions:mt,getOffsetParent:pt,getDocumentElement:ct,getElementRects:t=>{let{reference:e,floating:n,strategy:i}=t;return{reference:dt(e,pt(n),i),floating:{...mt(n),x:0,y:0}}},getClientRects:t=>Array.from(t.getClientRects()),isRTL:t=>"rtl"===_(t).direction};const Et=(t,e,n)=>(async(t,e,n)=>{const{placement:i="bottom",strategy:o="absolute",middleware:r=[],platform:s}=n,a=await(null==s.isRTL?void 0:s.isRTL(e));if("production"!==process.env.NODE_ENV&&(null==s&&console.error(["Floating UI: `platform` property was not passed to config. If you","want to use Floating UI on the web, install @floating-ui/dom","instead of the /core package. Otherwise, you can create your own","`platform`: https://floating-ui.com/docs/platform"].join(" ")),r.filter((t=>{let{name:e}=t;return"autoPlacement"===e||"flip"===e})).length>1))throw new Error(["Floating UI: duplicate `flip` and/or `autoPlacement`","middleware detected. This will lead to an infinite loop. Ensure only","one of either has been passed to the `middleware` array."].join(" "));let c=await s.getElementRects({reference:t,floating:e,strategy:o}),{x:l,y:u}=I(c,i,a),d=i,h={},f=0;for(let n=0;n100))throw new Error(["Floating UI: The middleware lifecycle appears to be","running in an infinite loop. This is usually caused by a `reset`","continually being returned without a break condition."].join(" "));const{name:p,fn:m}=r[n],{x:b,y:v,data:g,reset:y}=await m({x:l,y:u,initialPlacement:i,placement:d,strategy:o,middlewareData:h,rects:c,platform:s,elements:{reference:t,floating:e}});l=null!=b?b:l,u=null!=v?v:u,h={...h,[p]:{...h[p],...g}},y&&("object"==typeof y&&(y.placement&&(d=y.placement),y.rects&&(c=!0===y.rects?await s.getElementRects({reference:t,floating:e,strategy:o}):y.rects),({x:l,y:u}=I(c,d,a))),n=-1)}return{x:l,y:u,placement:d,strategy:o,middlewareData:h}})(t,e,{platform:wt,...n});class xt extends HTMLElement{static duration=1e4;timeouts=new Map;index=0;connectedCallback(){this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("aria-live")||this.setAttribute("aria-live","polite"),this.hasAttribute("aria-relevant")||this.setAttribute("aria-relevant","additions")}show(e,n={}){const o=n.key||String(this.index++);this.dismiss(o),e.dataset.key=o,t(this.children,(()=>{this.append(e),i(e)}));const r=void 0!==n.duration?Number(n.duration):xt.duration;return r>0&&(this.startTimeout(e,r),e.addEventListener("mouseenter",this.clearTimeout.bind(this,e)),e.addEventListener("focusin",this.clearTimeout.bind(this,e)),e.addEventListener("mouseleave",this.startTimeout.bind(this,e,r)),e.addEventListener("focusout",this.startTimeout.bind(this,e,r))),o}dismiss(e){"string"!=typeof e?(t(this.children,(()=>{o(e,{finish:()=>this.removeChild(e)})})),this.clearTimeout(e)):this.querySelectorAll(`[data-key="${e}"]`).forEach((t=>{this.dismiss(t)}))}clear(){for(const t of this.children)this.dismiss(t)}speak(t){const e=document.createElement("div");Object.assign(e.style,{clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:"1px",overflow:"hidden",position:"absolute",whiteSpace:"nowrap",width:"1px"}),e.textContent=t,this.show(e)}startTimeout(t,e){this.clearTimeout(t),this.timeouts.set(t,window.setTimeout((()=>{this.dismiss(t)}),e))}clearTimeout(t){this.timeouts.has(t)&&clearTimeout(this.timeouts.get(t))}}class Tt extends HTMLElement{static searchDelay=800;search="";searchTimeout;connectedCallback(){this.hasAttribute("role")||this.setAttribute("role","menu"),this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),this.items.forEach((t=>{t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1")})),this.addEventListener("keydown",this.onKeyDown)}disconnectedCallback(){this.removeEventListener("keydown",this.onKeyDown)}get items(){return Array.from(this.querySelectorAll("[role^=menuitem]")).filter((t=>w(t)))}onKeyDown=t=>{if(!this.hidden)return"ArrowUp"===t.key?(this.navigate(-1),void t.preventDefault()):"ArrowDown"===t.key?(this.navigate(1),void t.preventDefault()):void(t.key.length>1||t.ctrlKey||t.metaKey||t.altKey||(this.search+=t.key.toLowerCase(),t.preventDefault(),clearTimeout(this.searchTimeout),this.searchTimeout=window.setTimeout((()=>{this.search=""}),Tt.searchDelay),this.items.some((t=>{if(0===t.textContent?.trim().toLowerCase().indexOf(this.search))return t.focus(),!0}))))};navigate(t){const e=this.items;let n=(document.activeElement instanceof HTMLElement?e.indexOf(document.activeElement):-1)+t;n<0&&(n=e.length-1),n>=e.length&&(n=0),e[n]?.focus()}}class Lt extends HTMLElement{static attention=t=>t.animate([{transform:"scale(1)"},{transform:"scale(1.1)"},{transform:"scale(1)"}],300);static get observedAttributes(){return["open"]}focusTrap;connected=!1;constructor(){super();const t=document.createElement("template");t.innerHTML='\n
\n
\n ';const e=this.attachShadow({mode:"open"});e.appendChild(t.content.cloneNode(!0)),this.backdrop.addEventListener("click",(()=>{this.hasAttribute("static")?Lt.attention?.(e.children[1]):this.close()})),this.focusTrap=O(this,{escapeDeactivates:!1,allowOutsideClick:!0})}connectedCallback(){this.connected=!0,this.content?.hasAttribute("role")||this.content?.setAttribute("role","dialog"),this.content?.hasAttribute("aria-modal")||this.content?.setAttribute("aria-modal","true"),this.content?.hasAttribute("tabindex")||this.content?.setAttribute("tabindex","-1"),this.addEventListener("keydown",(t=>{"Escape"===t.key&&this.open&&(t.preventDefault(),t.stopPropagation(),this.close())})),this.open&&this.wasOpened()}disconnectedCallback(){this.connected=!1}get open(){return this.hasAttribute("open")}set open(t){t?this.setAttribute("open",""):this.removeAttribute("open")}close(){if(!this.open)return;const t=new Event("beforeclose",{cancelable:!0});this.dispatchEvent(t)&&(this.open=!1)}attributeChangedCallback(t,e,n){"open"===t&&this.connected&&(null!==n?this.wasOpened():this.wasClosed())}wasOpened(){this.hidden=!1,i(this),this.focusTrap.activate(),this.querySelector("[autofocus]")?.focus(),this.dispatchEvent(new Event("open"))}wasClosed(){this.focusTrap.deactivate(),o(this,{finish:()=>this.hidden=!0}),this.dispatchEvent(new Event("close"))}get backdrop(){return this.shadowRoot?.firstElementChild}get content(){return this.firstElementChild}}class kt extends HTMLElement{cleanup;static get observedAttributes(){return["open"]}constructor(){super();const t=document.createElement("template");t.innerHTML='\n \n \n ',this.attachShadow({mode:"open"}).appendChild(t.content.cloneNode(!0)),this.backdrop.onclick=()=>this.open=!1}connectedCallback(){this.backdrop.hidden=!0,this.content.hidden=!0,this.open=!1,this.button.setAttribute("aria-expanded","false"),setTimeout((()=>{"menu"===this.content.getAttribute("role")&&this.button.setAttribute("aria-haspopup","true")})),this.button.addEventListener("click",(()=>{this.open=!this.open})),this.button.addEventListener("keydown",(t=>{"ArrowDown"===t.key&&(t.preventDefault(),this.open=!0,v(this.content)[0]?.focus())})),this.addEventListener("keydown",(t=>{"Escape"===t.key&&this.open&&(t.preventDefault(),t.stopPropagation(),this.open=!1,this.button.focus())})),this.addEventListener("focusout",(t=>{t.relatedTarget instanceof Node&&this.contains(t.relatedTarget)||(this.open=!1)})),this.content.addEventListener("click",(t=>{t.target instanceof Element&&t.target.closest("[role=menuitem], [role=menuitemradio]")&&(this.open=!1,this.button.focus())}))}disconnectedCallback(){e(this.backdrop),e(this.content)}get open(){return this.hasAttribute("open")}set open(t){t?this.setAttribute("open",""):this.removeAttribute("open")}attributeChangedCallback(t,e,n){"open"===t&&(null!==n?this.wasOpened():this.wasClosed())}wasOpened(){if(!this.content.hidden)return;this.content.hidden=!1,this.backdrop.hidden=!1,i(this.content),i(this.backdrop),this.button.setAttribute("aria-expanded","true"),this.content.style.position="absolute",this.cleanup=function(t,e,n,i){void 0===i&&(i={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:s=!0,animationFrame:a=!1}=i,c=o&&!a,l=r&&!a,u=c||l?[...Q(t)?vt(t):[],...vt(e)]:[];u.forEach((t=>{c&&t.addEventListener("scroll",n,{passive:!0}),l&&t.addEventListener("resize",n)}));let d,h=null;s&&(h=new ResizeObserver(n),Q(t)&&!a&&h.observe(t),h.observe(e));let f=a?at(t):null;return a&&function e(){const i=at(t);!f||i.x===f.x&&i.y===f.y&&i.width===f.width&&i.height===f.height||n(),f=i,d=requestAnimationFrame(e)}(),s||n(),()=>{var t;u.forEach((t=>{c&&t.removeEventListener("scroll",n),l&&t.removeEventListener("resize",n)})),null==(t=h)||t.disconnect(),h=null,a&&cancelAnimationFrame(d)}}(this.button,this.content,(()=>{var t;Et(this.button,this.content,{placement:this.getAttribute("placement")||"bottom",middleware:[U(),V(),(t={apply:({availableWidth:t,availableHeight:e})=>{Object.assign(this.content.style,{maxWidth:"",maxHeight:""});const n=getComputedStyle(this.content);("none"===n.maxWidth||t{Object.assign(this.content.style,{left:`${t}px`,top:`${e}px`}),this.content.dataset.placement=n}))}),{ancestorScroll:!1});const t=this.content.querySelector("[autofocus]");t?t.focus():this.content.focus(),this.dispatchEvent(new Event("open"))}wasClosed(){this.content.hidden||(this.button.setAttribute("aria-expanded","false"),this.cleanup?.(),o(this.backdrop,{finish:()=>this.backdrop.hidden=!0}),o(this.content,{finish:()=>this.content.hidden=!0}),this.dispatchEvent(new Event("close")))}get backdrop(){return this.shadowRoot?.firstElementChild}get button(){return this.children[0]}get content(){return this.children[1]}}class At extends HTMLElement{connectedCallback(){this.hasAttribute("role")||this.setAttribute("role","toolbar"),this.setAttribute("tabindex","0"),this.addEventListener("focus",this.onInitialFocus,{once:!0}),this.addEventListener("keydown",this.onKeyDown)}disconnectedCallback(){this.removeEventListener("keydown",this.onKeyDown)}onInitialFocus=t=>{this.removeAttribute("tabindex"),this.focusControlAtIndex(0)};onKeyDown=t=>{if("ArrowRight"!==t.key&&"ArrowLeft"!==t.key&&"Home"!==t.key&&"End"!==t.key)return;const e=this.controls,n=this.controls.length,i=e.indexOf(t.target);if(-1===i)return;let o=0;"ArrowLeft"===t.key&&(o=i-1),"ArrowRight"===t.key&&(o=i+1),"End"===t.key&&(o=n-1),o<0&&(o=n-1),o>n-1&&(o=0),this.focusControlAtIndex(o),t.preventDefault()};focusControlAtIndex(t){this.controls.forEach(((e,n)=>{n===t?(e.setAttribute("tabindex","0"),e.focus()):e.setAttribute("tabindex","-1")}))}get controls(){return v(this)}}class Ct extends HTMLElement{static delay=100;static placement="top";static tooltipClass="tooltip";parent;tooltip;timeout;observer;showing=!1;onMouseEnter=this.afterDelay.bind(this,this.show);onFocus=this.show.bind(this);onMouseLeave=this.afterDelay.bind(this,this.hide);onBlur=this.hide.bind(this);connectedCallback(){this.parent=this.parentNode,this.parent&&(this.parent.addEventListener("mouseenter",this.onMouseEnter),this.parent.addEventListener("focus",this.onFocus),this.parent.addEventListener("mouseleave",this.onMouseLeave),this.parent.addEventListener("blur",this.onBlur),this.parent.addEventListener("click",this.onBlur),this.observer=new MutationObserver((t=>{t.forEach((t=>{"disabled"===t.attributeName&&this.hide()}))})),this.observer.observe(this.parent,{attributes:!0})),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("scroll",this.onBlur)}disconnectedCallback(){this.tooltip&&(this.tooltip.remove(),this.tooltip=void 0),this.parent&&(this.parent.removeEventListener("mouseenter",this.onMouseEnter),this.parent.removeEventListener("focus",this.onFocus),this.parent.removeEventListener("mouseleave",this.onMouseLeave),this.parent.removeEventListener("blur",this.onBlur),this.parent.removeEventListener("click",this.onBlur),this.parent=void 0),document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("scroll",this.onBlur),this.observer.disconnect(),clearTimeout(this.timeout)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}onKeyDown=t=>{"Escape"===t.key&&this.hide()};show(){if(this.disabled)return;const t=this.createTooltip();clearTimeout(this.timeout),this.showing||(t.hidden=!1,i(t),this.showing=!0),t.innerHTML!==this.innerHTML&&(t.innerHTML=this.innerHTML),t.style.position="absolute",Et(this.parent,t,{placement:this.getAttribute("placement")||Ct.placement,middleware:[U(),V()]}).then((({x:e,y:n,placement:i})=>{Object.assign(t.style,{left:`${e}px`,top:`${n}px`}),t.dataset.placement=i}))}hide(){clearTimeout(this.timeout),this.showing&&(this.showing=!1,o(this.tooltip,{finish:()=>{this.tooltip&&(this.tooltip.hidden=!0)}}))}afterDelay(t){clearTimeout(this.timeout);const e=parseInt(this.getAttribute("delay")||"");this.timeout=window.setTimeout(t.bind(this),isNaN(e)?Ct.delay:e)}createTooltip(){return this.tooltip||(this.tooltip=document.createElement("div"),this.tooltip.className=this.getAttribute("tooltip-class")||Ct.tooltipClass,this.tooltip.hidden=!0,this.tooltip.addEventListener("mouseenter",this.show.bind(this)),this.tooltip.addEventListener("mouseleave",this.afterDelay.bind(this,this.hide)),document.body.appendChild(this.tooltip)),this.tooltip}}window.customElements.define("ui-popup",kt),window.customElements.define("ui-tooltip",Ct),window.customElements.define("ui-menu",Tt),window.customElements.define("ui-modal",Lt),window.customElements.define("ui-alerts",xt),window.customElements.define("ui-toolbar",At); diff --git a/demo/demo.ts b/demo/demo.ts deleted file mode 100644 index fefd0e6..0000000 --- a/demo/demo.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { - PopupElement, - TooltipElement, - MenuElement, - ModalElement, - AlertsElement, - ToolbarElement, -} from '../dist/index'; - -window.customElements.define('ui-popup', PopupElement); -window.customElements.define('ui-tooltip', TooltipElement); -window.customElements.define('ui-menu', MenuElement); -window.customElements.define('ui-modal', ModalElement); -window.customElements.define('ui-alerts', AlertsElement); -window.customElements.define('ui-toolbar', ToolbarElement); diff --git a/demo/rollup.config.js b/demo/rollup.config.js deleted file mode 100644 index 78a2b59..0000000 --- a/demo/rollup.config.js +++ /dev/null @@ -1,17 +0,0 @@ -import typescript from '@rollup/plugin-typescript'; -import { terser } from 'rollup-plugin-terser'; -import { nodeResolve } from '@rollup/plugin-node-resolve'; - -export default { - input: __dirname + '/demo.ts', - output: { - file: __dirname + '/demo.js', - }, - plugins: [ - nodeResolve({ - exportConditions: ['production'], - }), - typescript(), - terser(), - ], -}; diff --git a/dist/alerts/alerts.d.ts b/dist/alerts/alerts.d.ts deleted file mode 100644 index 98b8838..0000000 --- a/dist/alerts/alerts.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -export declare type AlertOptions = { - key?: string; - duration?: number; -}; -export default class AlertsElement extends HTMLElement { - static duration: number; - private timeouts; - private index; - connectedCallback(): void; - show(el: HTMLElement, options?: AlertOptions): string; - dismiss(el: HTMLElement): void; - dismiss(key: string): void; - clear(): void; - speak(message: string): void; - private startTimeout; - private clearTimeout; -} diff --git a/dist/index.d.ts b/dist/index.d.ts deleted file mode 100644 index 183420a..0000000 --- a/dist/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export { default as AlertsElement } from './alerts/alerts'; -export { default as MenuElement } from './menu/menu'; -export { default as ModalElement } from './modal/modal'; -export { default as PopupElement } from './popup/popup'; -export { default as ToolbarElement } from './toolbar/toolbar'; -export { default as TooltipElement } from './tooltip/tooltip'; diff --git a/dist/index.js b/dist/index.js deleted file mode 100644 index 08f1c34..0000000 --- a/dist/index.js +++ /dev/null @@ -1 +0,0 @@ -import{move as t,hello as e,goodbye as i,cancel as s}from"hello-goodbye";import{isFocusable as n,focusable as o}from"tabbable";import{createFocusTrap as a}from"focus-trap";import{autoUpdate as r,computePosition as h,shift as d,flip as c,size as l}from"@floating-ui/dom";class u extends HTMLElement{static duration=1e4;timeouts=new Map;index=0;connectedCallback(){this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("aria-live")||this.setAttribute("aria-live","polite"),this.hasAttribute("aria-relevant")||this.setAttribute("aria-relevant","additions")}show(i,s={}){const n=s.key||String(this.index++);this.dismiss(n),i.dataset.key=n,t(this.children,(()=>{this.append(i),e(i)}));const o=void 0!==s.duration?Number(s.duration):u.duration;return o>0&&(this.startTimeout(i,o),i.addEventListener("mouseenter",this.clearTimeout.bind(this,i)),i.addEventListener("focusin",this.clearTimeout.bind(this,i)),i.addEventListener("mouseleave",this.startTimeout.bind(this,i,o)),i.addEventListener("focusout",this.startTimeout.bind(this,i,o))),n}dismiss(e){"string"!=typeof e?(t(this.children,(()=>{i(e,{finish:()=>this.removeChild(e)})})),this.clearTimeout(e)):this.querySelectorAll(`[data-key="${e}"]`).forEach((t=>{this.dismiss(t)}))}clear(){for(const t of this.children)this.dismiss(t)}speak(t){const e=document.createElement("div");Object.assign(e.style,{clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:"1px",overflow:"hidden",position:"absolute",whiteSpace:"nowrap",width:"1px"}),e.textContent=t,this.show(e)}startTimeout(t,e){this.clearTimeout(t),this.timeouts.set(t,window.setTimeout((()=>{this.dismiss(t)}),e))}clearTimeout(t){this.timeouts.has(t)&&clearTimeout(this.timeouts.get(t))}}class p extends HTMLElement{static searchDelay=800;search="";searchTimeout;connectedCallback(){this.hasAttribute("role")||this.setAttribute("role","menu"),this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),this.items.forEach((t=>{t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1")})),this.addEventListener("keydown",this.onKeyDown)}disconnectedCallback(){this.removeEventListener("keydown",this.onKeyDown)}get items(){return Array.from(this.querySelectorAll("[role^=menuitem]")).filter((t=>n(t)))}onKeyDown=t=>{if(!this.hidden)return"ArrowUp"===t.key?(this.navigate(-1),void t.preventDefault()):"ArrowDown"===t.key?(this.navigate(1),void t.preventDefault()):void(t.key.length>1||t.ctrlKey||t.metaKey||t.altKey||(this.search+=t.key.toLowerCase(),t.preventDefault(),clearTimeout(this.searchTimeout),this.searchTimeout=window.setTimeout((()=>{this.search=""}),p.searchDelay),this.items.some((t=>{if(0===t.textContent?.trim().toLowerCase().indexOf(this.search))return t.focus(),!0}))))};navigate(t){const e=this.items;let i=(document.activeElement instanceof HTMLElement?e.indexOf(document.activeElement):-1)+t;i<0&&(i=e.length-1),i>=e.length&&(i=0),e[i]?.focus()}}class m extends HTMLElement{static attention=t=>t.animate([{transform:"scale(1)"},{transform:"scale(1.1)"},{transform:"scale(1)"}],300);static get observedAttributes(){return["open"]}focusTrap;connected=!1;constructor(){super();const t=document.createElement("template");t.innerHTML='\n
\n
\n ';const e=this.attachShadow({mode:"open"});e.appendChild(t.content.cloneNode(!0)),this.backdrop.addEventListener("click",(()=>{this.hasAttribute("static")?m.attention?.(e.children[1]):this.close()})),this.focusTrap=a(this,{escapeDeactivates:!1,allowOutsideClick:!0})}connectedCallback(){this.connected=!0,this.content?.hasAttribute("role")||this.content?.setAttribute("role","dialog"),this.content?.hasAttribute("aria-modal")||this.content?.setAttribute("aria-modal","true"),this.content?.hasAttribute("tabindex")||this.content?.setAttribute("tabindex","-1"),this.addEventListener("keydown",(t=>{"Escape"===t.key&&this.open&&(t.preventDefault(),t.stopPropagation(),this.close())})),this.open&&this.wasOpened()}disconnectedCallback(){this.connected=!1}get open(){return this.hasAttribute("open")}set open(t){t?this.setAttribute("open",""):this.removeAttribute("open")}close(){if(!this.open)return;const t=new Event("beforeclose",{cancelable:!0});this.dispatchEvent(t)&&(this.open=!1)}attributeChangedCallback(t,e,i){"open"===t&&this.connected&&(null!==i?this.wasOpened():this.wasClosed())}wasOpened(){this.hidden=!1,e(this),this.focusTrap.activate(),this.querySelector("[autofocus]")?.focus(),this.dispatchEvent(new Event("open"))}wasClosed(){this.focusTrap.deactivate(),i(this,{finish:()=>this.hidden=!0}),this.dispatchEvent(new Event("close"))}get backdrop(){return this.shadowRoot?.firstElementChild}get content(){return this.firstElementChild}}class b extends HTMLElement{cleanup;static get observedAttributes(){return["open"]}constructor(){super();const t=document.createElement("template");t.innerHTML='\n \n \n ';this.attachShadow({mode:"open"}).appendChild(t.content.cloneNode(!0)),this.backdrop.onclick=()=>this.open=!1}connectedCallback(){this.backdrop.hidden=!0,this.content.hidden=!0,this.open=!1,this.button.setAttribute("aria-expanded","false"),setTimeout((()=>{"menu"===this.content.getAttribute("role")&&this.button.setAttribute("aria-haspopup","true")})),this.button.addEventListener("click",(()=>{this.open=!this.open})),this.button.addEventListener("keydown",(t=>{"ArrowDown"===t.key&&(t.preventDefault(),this.open=!0,o(this.content)[0]?.focus())})),this.addEventListener("keydown",(t=>{"Escape"===t.key&&this.open&&(t.preventDefault(),t.stopPropagation(),this.open=!1,this.button.focus())})),this.addEventListener("focusout",(t=>{t.relatedTarget instanceof Node&&this.contains(t.relatedTarget)||(this.open=!1)})),this.content.addEventListener("click",(t=>{t.target instanceof Element&&t.target.closest("[role=menuitem], [role=menuitemradio]")&&(this.open=!1,this.button.focus())}))}disconnectedCallback(){s(this.backdrop),s(this.content)}get open(){return this.hasAttribute("open")}set open(t){t?this.setAttribute("open",""):this.removeAttribute("open")}attributeChangedCallback(t,e,i){"open"===t&&(null!==i?this.wasOpened():this.wasClosed())}wasOpened(){if(!this.content.hidden)return;this.content.hidden=!1,this.backdrop.hidden=!1,e(this.content),e(this.backdrop),this.button.setAttribute("aria-expanded","true"),this.content.style.position="absolute",this.cleanup=r(this.button,this.content,(()=>{h(this.button,this.content,{placement:this.getAttribute("placement")||"bottom",middleware:[d(),c(),l({apply:({availableWidth:t,availableHeight:e})=>{Object.assign(this.content.style,{maxWidth:"",maxHeight:""});const i=getComputedStyle(this.content);("none"===i.maxWidth||t{Object.assign(this.content.style,{left:`${t}px`,top:`${e}px`}),this.content.dataset.placement=i}))}),{ancestorScroll:!1});const t=this.content.querySelector("[autofocus]");t?t.focus():this.content.focus(),this.dispatchEvent(new Event("open"))}wasClosed(){this.content.hidden||(this.button.setAttribute("aria-expanded","false"),this.cleanup?.(),i(this.backdrop,{finish:()=>this.backdrop.hidden=!0}),i(this.content,{finish:()=>this.content.hidden=!0}),this.dispatchEvent(new Event("close")))}get backdrop(){return this.shadowRoot?.firstElementChild}get button(){return this.children[0]}get content(){return this.children[1]}}class v extends HTMLElement{connectedCallback(){this.hasAttribute("role")||this.setAttribute("role","toolbar"),this.setAttribute("tabindex","0"),this.addEventListener("focus",this.onInitialFocus,{once:!0}),this.addEventListener("keydown",this.onKeyDown)}disconnectedCallback(){this.removeEventListener("keydown",this.onKeyDown)}onInitialFocus=t=>{this.removeAttribute("tabindex"),this.focusControlAtIndex(0)};onKeyDown=t=>{if("ArrowRight"!==t.key&&"ArrowLeft"!==t.key&&"Home"!==t.key&&"End"!==t.key)return;const e=this.controls,i=this.controls.length,s=e.indexOf(t.target);if(-1===s)return;let n=0;"ArrowLeft"===t.key&&(n=s-1),"ArrowRight"===t.key&&(n=s+1),"End"===t.key&&(n=i-1),n<0&&(n=i-1),n>i-1&&(n=0),this.focusControlAtIndex(n),t.preventDefault()};focusControlAtIndex(t){this.controls.forEach(((e,i)=>{i===t?(e.setAttribute("tabindex","0"),e.focus()):e.setAttribute("tabindex","-1")}))}get controls(){return o(this)}}class f extends HTMLElement{static delay=100;static placement="top";static tooltipClass="tooltip";parent;tooltip;timeout;observer;showing=!1;onMouseEnter=this.afterDelay.bind(this,this.show);onFocus=this.show.bind(this);onMouseLeave=this.afterDelay.bind(this,this.hide);onBlur=this.hide.bind(this);connectedCallback(){this.parent=this.parentNode,this.parent&&(this.parent.addEventListener("mouseenter",this.onMouseEnter),this.parent.addEventListener("focus",this.onFocus),this.parent.addEventListener("mouseleave",this.onMouseLeave),this.parent.addEventListener("blur",this.onBlur),this.parent.addEventListener("click",this.onBlur),this.observer=new MutationObserver((t=>{t.forEach((t=>{"disabled"===t.attributeName&&this.hide()}))})),this.observer.observe(this.parent,{attributes:!0})),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("scroll",this.onBlur)}disconnectedCallback(){this.tooltip&&(this.tooltip.remove(),this.tooltip=void 0),this.parent&&(this.parent.removeEventListener("mouseenter",this.onMouseEnter),this.parent.removeEventListener("focus",this.onFocus),this.parent.removeEventListener("mouseleave",this.onMouseLeave),this.parent.removeEventListener("blur",this.onBlur),this.parent.removeEventListener("click",this.onBlur),this.parent=void 0),document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("scroll",this.onBlur),this.observer.disconnect(),clearTimeout(this.timeout)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}onKeyDown=t=>{"Escape"===t.key&&this.hide()};show(){if(this.disabled)return;const t=this.createTooltip();clearTimeout(this.timeout),this.showing||(t.hidden=!1,e(t),this.showing=!0),t.innerHTML!==this.innerHTML&&(t.innerHTML=this.innerHTML),t.style.position="absolute",h(this.parent,t,{placement:this.getAttribute("placement")||f.placement,middleware:[d(),c()]}).then((({x:e,y:i,placement:s})=>{Object.assign(t.style,{left:`${e}px`,top:`${i}px`}),t.dataset.placement=s}))}hide(){clearTimeout(this.timeout),this.showing&&(this.showing=!1,i(this.tooltip,{finish:()=>{this.tooltip&&(this.tooltip.hidden=!0)}}))}afterDelay(t){clearTimeout(this.timeout);const e=parseInt(this.getAttribute("delay")||"");this.timeout=window.setTimeout(t.bind(this),isNaN(e)?f.delay:e)}createTooltip(){return this.tooltip||(this.tooltip=document.createElement("div"),this.tooltip.className=this.getAttribute("tooltip-class")||f.tooltipClass,this.tooltip.hidden=!0,this.tooltip.addEventListener("mouseenter",this.show.bind(this)),this.tooltip.addEventListener("mouseleave",this.afterDelay.bind(this,this.hide)),document.body.appendChild(this.tooltip)),this.tooltip}}export{u as AlertsElement,p as MenuElement,m as ModalElement,b as PopupElement,v as ToolbarElement,f as TooltipElement}; diff --git a/dist/menu/menu.d.ts b/dist/menu/menu.d.ts deleted file mode 100644 index cc1a378..0000000 --- a/dist/menu/menu.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export default class MenuElement extends HTMLElement { - static searchDelay: number; - private search; - private searchTimeout?; - connectedCallback(): void; - disconnectedCallback(): void; - private get items(); - private onKeyDown; - private navigate; -} diff --git a/dist/modal/modal.d.ts b/dist/modal/modal.d.ts deleted file mode 100644 index 96cae67..0000000 --- a/dist/modal/modal.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -export default class ModalElement extends HTMLElement { - static attention: (el: Element) => void; - static get observedAttributes(): string[]; - private focusTrap?; - private connected; - constructor(); - connectedCallback(): void; - disconnectedCallback(): void; - get open(): boolean; - set open(val: boolean); - close(): void; - attributeChangedCallback(name: string, oldValue: string, newValue: string): void; - private wasOpened; - private wasClosed; - private get backdrop(); - private get content(); -} diff --git a/dist/popup/popup.d.ts b/dist/popup/popup.d.ts deleted file mode 100644 index b443921..0000000 --- a/dist/popup/popup.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -export default class PopupElement extends HTMLElement { - cleanup?: () => void; - static get observedAttributes(): string[]; - constructor(); - connectedCallback(): void; - disconnectedCallback(): void; - get open(): boolean; - set open(val: boolean); - attributeChangedCallback(name: string, oldValue: string, newValue: string): void; - private wasOpened; - private wasClosed; - private get backdrop(); - private get button(); - private get content(); -} diff --git a/dist/toolbar/toolbar.d.ts b/dist/toolbar/toolbar.d.ts deleted file mode 100644 index e6ab0c8..0000000 --- a/dist/toolbar/toolbar.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export default class ToolbarElement extends HTMLElement { - connectedCallback(): void; - disconnectedCallback(): void; - private onInitialFocus; - private onKeyDown; - private focusControlAtIndex; - private get controls(); -} diff --git a/dist/tooltip/tooltip.d.ts b/dist/tooltip/tooltip.d.ts deleted file mode 100644 index 092525b..0000000 --- a/dist/tooltip/tooltip.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -export default class TooltipElement extends HTMLElement { - static delay: number; - static placement: string; - static tooltipClass: string; - private parent?; - private tooltip?; - private timeout?; - private observer?; - private showing; - private onMouseEnter; - private onFocus; - private onMouseLeave; - private onBlur; - connectedCallback(): void; - disconnectedCallback(): void; - get disabled(): boolean; - set disabled(val: boolean); - private onKeyDown; - private show; - private hide; - private afterDelay; - private createTooltip; -} diff --git a/demo/index.html b/index.html similarity index 92% rename from demo/index.html rename to index.html index bc17c30..cd1f45e 100644 --- a/demo/index.html +++ b/index.html @@ -291,7 +291,24 @@

Your dialog title

- +