import*as LitHtml from"../third_party/lit-html/lit-html.js";export class AccessibilityTree extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open",delegatesFocus:!1}),this.nodeMap=new Map,this.rootNode=null,this.selectedNode=null,this.setAttribute("role","tree"),this.addEventListener("keydown",this.onKeyDown.bind(this))}set data(e){if(this.rootNode=e.rootNode,!this.rootNode)throw new Error("Root node is missing");this.render(),this.selectRootNode(),this.expandTree()}set selectedAXNode(e){this.selectedNode&&this.selectedNode!==e&&this.selectedNode.deselect(),this.selectedNode=e,this.selectedNode.select()}async expandTree(){if(!this.rootNode)return;let e=[this.rootNode];for(let t=0;t<3;t++){const t=[];for(const s of e)await(this.nodeMap.get(s.id)?.expand()),t.push(...await s.children());e=t}}getNodeByAXID(e){return this.nodeMap.get(e)||null}appendToNodeMap(e,t){this.nodeMap.set(e,t)}onKeyDown(e){if(this.selectedNode)switch(e.key){case"ArrowUp":this.selectedNode.selectPreviousNode(),e.preventDefault();break;case"ArrowDown":this.selectedNode.selectNextNode(),e.preventDefault();break;case"ArrowLeft":this.selectedNode.isExpanded?this.selectedNode.defaultAction():this.selectedNode.selectParent(),e.preventDefault();break;case"ArrowRight":this.selectedNode.isExpanded?this.selectedNode.selectFirstChild():this.selectedNode.defaultAction(),e.preventDefault();break;case"Home":this.selectRootNode(),e.preventDefault();break;case"End":this.selectLastNode(),e.preventDefault();break;case"Enter":this.selectedNode.defaultAction(),e.preventDefault();break;default:return}}getRoot(){if(!this.rootNode)return null;return this.getNodeByAXID(this.rootNode.id)||null}selectRootNode(){const e=this.getRoot();e&&(this.selectedAXNode=e)}selectLastNode(){const e=this.getRoot();if(!e)return;let t=e.getLastChild();for(;t&&t.isExpanded;)t=t.getLastChild();t&&(this.selectedAXNode=t)}render(){const e=LitHtml.html`
      <style>
        :host {
          overflow: auto;
        }

        :focus {
          outline: none;
        }
      </style>
      <devtools-accessibility-node .data=${{axNode:this.rootNode}}>
      </devtools-accessibility-node>
      `;LitHtml.render(e,this.shadow)}}customElements.get("devtools-accessibility-tree")||customElements.define("devtools-accessibility-tree",AccessibilityTree);