@sandlada/mdc
Version:
@sandlada/mdc is an open source component library that follows the Material Design 3 design specifications.
7 lines (6 loc) • 1.98 kB
JavaScript
import"../../lit-element-Ho-VPzO1.js";
/**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/class t{get controls(){const t=this.host.getAttribute("name");return t&&this.root&&this.host.isConnected?Array.from(this.root.querySelectorAll(`[name="${t}"]`)):[this.host]}constructor(t){this.focused=!1,this.root=null,this.handleFocusIn=()=>{this.focused=!0,this.updateTabIndices()},this.handleFocusOut=()=>{this.focused=!1,this.updateTabIndices()},this.handleKeyDown=t=>{const e="ArrowDown"===t.key,s="ArrowUp"===t.key,o="ArrowLeft"===t.key,n="ArrowRight"===t.key;if(!(o||n||e||s))return;const h=this.controls;if(!h.length)return;t.preventDefault();const i="rtl"===getComputedStyle(this.host).direction?o||e:n||e,c=h.indexOf(this.host);let d=i?c+1:c-1;for(;d!==c;){d>=h.length?d=0:d<0&&(d=h.length-1);const t=h[d];if(!t.hasAttribute("disabled")){for(const e of h)e!==t&&(e.checked=!1,e.tabIndex=-1,e.blur());t.checked=!0,t.tabIndex=0,t.focus(),t.dispatchEvent(new Event("change",{bubbles:!0}));break}i?d++:d--}},this.host=t}hostConnected(){this.root=this.host.getRootNode(),this.host.addEventListener("keydown",this.handleKeyDown),this.host.addEventListener("focusin",this.handleFocusIn),this.host.addEventListener("focusout",this.handleFocusOut),this.host.checked&&this.uncheckSiblings(),this.updateTabIndices()}hostDisconnected(){this.host.removeEventListener("keydown",this.handleKeyDown),this.host.removeEventListener("focusin",this.handleFocusIn),this.host.removeEventListener("focusout",this.handleFocusOut),this.updateTabIndices(),this.root=null}handleCheckedChange(){this.host.checked&&(this.uncheckSiblings(),this.updateTabIndices())}uncheckSiblings(){for(const t of this.controls)t!==this.host&&(t.checked=!1)}updateTabIndices(){const t=this.controls,e=t.find(t=>t.checked);if(e||this.focused){const s=e||this.host;s.tabIndex=0;for(const e of t)e!==s&&(e.tabIndex=-1);return}for(const e of t)e.tabIndex=0}}export{t as SingleSelectionController};