class SubToolbar extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this._currentTool = 'home'; } static get observedAttributes() { return ['current-tool']; } attributeChangedCallback(name, oldValue, newValue) { if (name === 'current-tool' && oldValue !== newValue) { this._currentTool = newValue; this.updateSubMenu(); this.updateToolHeader(); } } connectedCallback() { this.render(); this.addEventListeners(); } render() { this.shadowRoot.innerHTML = `
`; } updateSubMenu() { const subMenus = this.shadowRoot.querySelectorAll('.sub-menu'); subMenus.forEach(menu => { menu.classList.toggle('active', menu.getAttribute('data-parent') === this._currentTool); }); } addEventListeners() { // 切换按钮事件 const toggleButton = this.shadowRoot.querySelector('.toolbar-toggle'); toggleButton.addEventListener('click', () => { this.classList.toggle('collapsed'); const isCollapsed = this.classList.contains('collapsed'); toggleButton.querySelector('img').src = `assets/icons/png/chevron-d${isCollapsed ? 'right' : 'left'}.png`; toggleButton.querySelector('img').alt = isCollapsed ? '展开' : '收起'; toggleButton.title = isCollapsed ? '展开' : '收起'; }); // 子菜单项点击事件 const subItems = this.shadowRoot.querySelectorAll('.sub-item'); subItems.forEach(item => { item.addEventListener('click', () => { // 移除同级菜单项的激活状态 const siblings = item.parentElement.querySelectorAll('.sub-item'); siblings.forEach(si => si.classList.remove('active')); // 激活当前菜单项 item.classList.add('active'); // 触发自定义事件 const event = new CustomEvent('sub-item-selected', { detail: { parent: item.closest('.sub-menu').getAttribute('data-parent'), text: item.textContent.trim(), icon: item.getAttribute('data-icon') }, bubbles: true, composed: true }); this.dispatchEvent(event); }); }); } // 更新管理员选项的显示状态 updateAdminItems(accessLevel) { const adminItems = this.shadowRoot.querySelectorAll('.admin-only'); adminItems.forEach(item => { item.style.display = accessLevel >= 3 ? 'flex' : 'none'; }); } updateToolHeader() { const toolIcons = { 'home': { icon: 'home', text: '主页' }, 'develop': { icon: 'develop', text: '开发' }, 'config': { icon: 'sliders', text: '配置' }, 'run': { icon: 'play', text: '运行' }, 'monitor': { icon: 'chart', text: '监控' }, 'system': { icon: 'cogs', text: '管理' } }; const currentTool = toolIcons[this._currentTool] || toolIcons['home']; const iconElement = this.shadowRoot.getElementById('currentToolIcon'); const nameElement = this.shadowRoot.getElementById('currentToolName'); iconElement.src = `assets/icons/png/${currentTool.icon}.png`; iconElement.alt = currentTool.text; nameElement.textContent = currentTool.text; } } customElements.define('sub-toolbar', SubToolbar);