refactor: 重命名SDK为iflow-engine,使用npm包引入第三方引擎

- 将包名从 @fishdingding/bim-engine-sdk 改为 iflow-engine
- 将构建输出文件从 bim-engine-sdk.*.js 改为 iflow-engine.*.js
- 将全局变量从 LyzBimEngineSDK 改为 IflowEngine
- 将第三方引擎SDK从本地引入改为npm包引入 (iflow-engine-base)
- 移除本地 src/engine_base 目录,移至回收站
- 更新所有文档和demo中的引用
This commit is contained in:
yuding
2026-01-22 11:29:51 +08:00
parent 70523e54e5
commit f2460fb981
103 changed files with 32120 additions and 31434 deletions

View File

@@ -0,0 +1,309 @@
/* 根容器 */
.bim-btn-group-root {
display: flex;
gap: 8px;
z-index: 1000;
position: absolute;
pointer-events: auto;
}
.bim-btn-group-root.static {
position: relative;
top: auto;
left: auto;
bottom: auto;
right: auto;
transform: none;
}
.bim-btn-group-root.dir-row {
flex-direction: row;
align-items: center;
}
.bim-btn-group-root.dir-column {
flex-direction: column;
align-items: stretch;
}
/* 分组区域 */
.bim-btn-group-section {
display: flex;
gap: 4px;
background-color: var(--bim-btn-group-section-bg, rgba(17, 17, 17, 0.88));
border-radius: 6px;
padding: 4px;
/* 添加阴影效果,增强视觉层次感 */
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3), 0 1px 3px rgba(0, 0, 0, 0.2);
}
.bim-btn-group-root.dir-row .bim-btn-group-section {
flex-direction: row;
align-items: center;
}
.bim-btn-group-root.dir-column .bim-btn-group-section {
flex-direction: column;
}
/* 按钮外层 */
.opt-btn-wrapper {
position: relative;
}
/* 按钮本体 */
.opt-btn {
display: flex;
cursor: pointer;
border-radius: 4px;
transition: background-color 0.2s, color 0.2s, border-color 0.2s;
color: var(--bim-btn-text-color, #ccc);
background-color: var(--bim-btn-bg, transparent);
padding: 6px;
align-items: center;
position: relative;
/* 为绝对定位提供锚点 */
justify-content: center;
border: 1px solid transparent;
outline: none;
}
.opt-btn:hover {
background-color: var(--bim-btn-hover-bg, #444);
}
.opt-btn.active {
background-color: var(--bim-btn-active-bg, rgba(255, 255, 255, 0.15));
color: var(--bim-btn-text-active-color, #fff);
/* 开关按钮激活时不显示边框,只改变背景 */
}
/* 开关按钮激活时图标颜色保持不变,继承默认颜色 */
.opt-btn.disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* --- 图标 --- */
.opt-btn-icon {
width: var(--bim-icon-size, 24px);
height: var(--bim-icon-size, 24px);
display: flex;
align-items: center;
justify-content: center;
color: var(--bim-icon-color, #ccc);
flex-shrink: 0;
}
.opt-btn-icon svg {
width: 100%;
height: 100%;
fill: currentColor;
}
/* --- 箭头 --- */
.opt-btn-arrow {
font-size: 10px;
opacity: 0.6;
transition: transform 0.2s;
display: inline-block;
/* 默认情况 (有Label) */
margin-left: 4px;
}
.opt-btn-arrow.rotated {
transform: rotate(180deg);
}
/* --- 文字容器 --- */
.opt-btn-text-wrapper {
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
}
/* --- Label 显示控制 --- */
.opt-btn-label {
display: inline;
}
.opt-btn.no-label .opt-btn-label {
display: none;
}
/* --- 场景 A: 有 Label (常规布局) --- */
.opt-btn.align-vertical:not(.no-label) {
flex-direction: column;
text-align: center;
}
.opt-btn.align-vertical:not(.no-label) .opt-btn-text-wrapper {
margin-top: 4px;
}
.opt-btn.align-vertical:not(.no-label) .opt-btn-label {
font-size: 12px;
line-height: 1.2;
}
.opt-btn.align-horizontal:not(.no-label) {
flex-direction: row;
}
.opt-btn.align-horizontal:not(.no-label) .opt-btn-text-wrapper {
margin-left: 8px;
}
.opt-btn.align-horizontal:not(.no-label) .opt-btn-label {
font-size: 14px;
}
/* --- 场景 B: 无 Label (强制绝对定位) --- */
/* 当没有 label 时text-wrapper 其实只包裹了 arrow */
/* 我们需要让 wrapper 失去布局影响,直接定位内部的 arrow */
.opt-btn.no-label .opt-btn-text-wrapper {
/* 让 wrapper 变为 0 尺寸,不影响 flex 布局 */
width: 0;
height: 0;
margin: 0;
padding: 0;
overflow: visible;
/* 关键:允许子元素溢出 */
position: absolute;
/* 脱离文档流,相对于 .opt-btn */
top: 0;
right: 0;
}
.opt-btn.no-label .opt-btn-arrow {
position: absolute;
top: 2px;
right: 2px;
margin: 0;
/* 清除之前的 margin */
font-size: 8px;
/*
如果父级 wrapper 已经是 top:0, right:0
那么 arrow 相对 wrapper 定位即可
*/
}
/* --- 下拉菜单 & 动画 --- */
.opt-btn-dropdown {
position: absolute;
background-color: var(--bim-toolbar-bg, rgba(17, 17, 17, 0.95));
border-radius: 4px;
padding: 4px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
z-index: 1001;
display: flex;
flex-direction: column;
border: 1px solid rgba(255, 255, 255, 0.1);
/* 动画起始状态 */
opacity: 0;
visibility: hidden;
transform: translateY(-10px);
/* 默认向上偏移一点 */
transition: opacity 0.2s ease, transform 0.2s cubic-bezier(0.2, 0, 0.2, 1), visibility 0.2s;
}
/* 动画激活状态 (需要 JS 添加 .show 类,或者直接在 display:flex 时生效?) */
/* 这里的实现有点 tricky因为 JS 里直接 appendChild */
/* 我们可以利用 CSS 动画关键帧,或者简单的 transition */
/* 由于 DOM 是动态插入的,插入瞬间是 opacity: 0 -> requestAnimationFrame -> opacity: 1 */
/* 简单的办法:添加动画 keyframes */
@keyframes dropdown-fade-in {
from {
opacity: 0;
transform: translateY(-8px) scale(0.98);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
.opt-btn-dropdown {
/* 覆盖上面的 transition直接用 animation */
animation: dropdown-fade-in 0.2s cubic-bezier(0.2, 0, 0.2, 1) forwards;
/* 初始可见性由 JS 控制append 即显示) */
opacity: 1;
visibility: visible;
transform: none;
}
.opt-btn-dropdown-item {
display: flex;
align-items: center;
padding: 8px 12px;
cursor: pointer;
border-radius: 4px;
color: var(--bim-btn-text-color, #ccc);
transition: background 0.2s, border-color 0.2s, color 0.2s;
box-sizing: border-box;
border: 1px solid transparent;
outline: none;
}
/* 二级菜单项的图标默认颜色 */
.opt-btn-dropdown-item .opt-btn-icon {
color: var(--bim-icon-color, #ccc);
}
.opt-btn-dropdown-item:hover {
background-color: var(--bim-btn-hover-bg, #444);
}
/* 二级菜单项激活态(支持 keepActive 的可视化) */
.opt-btn-dropdown-item.active {
background-color: var(--bim-btn-active-bg, rgba(255, 255, 255, 0.15));
color: var(--bim-btn-text-active-color, #fff);
/* 开关按钮激活时不显示边框,只改变背景 */
}
/* 开关按钮激活时图标颜色保持不变,继承默认颜色 */
/* 下拉菜单项 - 横向布局(图标在左,默认) */
.opt-btn-dropdown-item.align-horizontal {
flex-direction: row;
}
.opt-btn-dropdown-item.align-horizontal .opt-btn-icon {
width: 18px;
height: 18px;
margin-right: 8px;
}
/* 下拉菜单项 - 纵向布局(图标在上) */
.opt-btn-dropdown-item.align-vertical {
flex-direction: column;
text-align: center;
}
.opt-btn-dropdown-item.align-vertical .opt-btn-icon {
width: 24px;
height: 24px;
margin-bottom: 4px;
}
.opt-btn-dropdown-item.align-vertical .opt-btn-dropdown-label {
font-size: 12px;
}
/* --- 特定样式覆盖:底部工具栏 --- */
.bim-btn-group-root.is-bottom-toolbar .opt-btn-icon {
width: 32px;
height: 32px;
}
.bim-btn-group-root.is-bottom-toolbar .opt-btn {
padding: 8px;
}

View File

@@ -0,0 +1,717 @@
import './index.css';
import type {
OptButton,
ButtonGroup,
ButtonGroupOptions,
ButtonConfig,
ButtonGroupColors
} from './index.type';
import { t, localeManager } from '../../services/locale';
import { themeManager } from '../../services/theme';
import type { ThemeConfig } from '../../themes/types';
import { IBimComponent } from '../../types/component';
import type { BimEngine } from '../../bim-engine';
import { EngineEvents } from '../../types/events';
/**
* 通用按钮组组件 (BimButtonGroup)
*/
export class BimButtonGroup implements IBimComponent {
private container: HTMLElement;
private options: ButtonGroupOptions;
private groups: ButtonGroup[] = [];
private activeBtnIds: Set<string> = new Set();
private btnRefs: Map<string, HTMLElement> = new Map();
private dropdownElement: HTMLElement | null = null;
private hoverTimeout: number | null = null;
private customColors: Set<keyof ButtonGroupColors> = new Set(); // 记录用户自定义的颜色属性
private unsubscribeLocale: (() => void) | null = null;
private unsubscribeTheme: (() => void) | null = null;
protected engine: BimEngine | null = null;
private readonly DEFAULT_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>';
constructor(options: ButtonGroupOptions) {
const el = typeof options.container === 'string'
? document.getElementById(options.container)
: options.container;
if (!el) throw new Error('Container not found');
this.container = el;
// 合并默认配置
this.options = {
showLabel: true,
visibility: {},
direction: 'row', // 默认横向
position: 'static', // 默认静态定位
align: 'vertical', // 默认图标在上
expand: 'down', // 默认向下展开
...options
};
// 记录初始传入的自定义颜色
const colorKeys: (keyof ButtonGroupColors)[] = [
'backgroundColor', 'btnBackgroundColor', 'btnHoverColor',
'btnActiveColor', 'iconColor', 'iconActiveColor',
'textColor', 'textActiveColor'
];
colorKeys.forEach(key => {
if (options[key]) {
this.customColors.add(key);
}
});
this.initContainer();
this.applyStyles();
}
public setEngine(engine: BimEngine) {
this.engine = engine;
}
protected emit<K extends keyof EngineEvents>(event: K, payload: EngineEvents[K]) {
if (this.engine) {
this.engine.emit(event, payload);
} else {
console.warn('[BimButtonGroup] Engine not set, cannot emit event:', event);
}
}
private initContainer(): void {
this.container.innerHTML = '';
this.container.classList.add('bim-btn-group-root');
if (this.options.direction === 'column') {
this.container.classList.add('dir-column');
} else {
this.container.classList.add('dir-row');
}
if (this.options.className) {
this.container.classList.add(this.options.className);
}
this.updatePosition();
// 添加事件拦截,防止点击穿透到 3D 引擎
this.setupEventInterception(this.container);
}
/**
* 设置事件拦截,防止事件冒泡到下层元素(如 3D 引擎)
*/
private setupEventInterception(el: HTMLElement): void {
const stopPropagation = (e: Event) => {
e.stopPropagation();
};
const events = [
'click', 'dblclick', 'contextmenu', 'wheel',
'mousedown', 'mouseup', 'mousemove',
'touchstart', 'touchend', 'touchmove',
'pointerdown', 'pointerup', 'pointermove', 'pointerenter', 'pointerleave', 'pointerover', 'pointerout'
];
events.forEach(eventType => {
el.addEventListener(eventType, stopPropagation, { passive: false });
});
}
private updatePosition() {
const pos = this.options.position;
const style = this.container.style;
style.top = ''; style.bottom = ''; style.left = ''; style.right = ''; style.transform = '';
if (pos === 'static') {
this.container.classList.add('static');
return;
}
this.container.classList.remove('static');
this.container.style.position = 'absolute';
if (typeof pos === 'object' && 'x' in pos) {
style.left = `${pos.x}px`;
style.top = `${pos.y}px`;
} else {
const margin = '20px';
switch (pos) {
case 'top-left':
style.top = margin; style.left = margin;
break;
case 'top-center':
style.top = margin; style.left = '50%'; style.transform = 'translateX(-50%)';
break;
case 'top-right':
style.top = margin; style.right = margin;
break;
case 'bottom-left':
style.bottom = margin; style.left = margin;
break;
case 'bottom-center':
style.bottom = margin; style.left = '50%'; style.transform = 'translateX(-50%)';
break;
case 'bottom-right':
style.bottom = margin; style.right = margin;
break;
case 'left-center':
style.left = margin; style.top = '50%'; style.transform = 'translateY(-50%)';
break;
case 'right-center':
style.right = margin; style.top = '50%'; style.transform = 'translateY(-50%)';
break;
case 'center':
style.top = '50%'; style.left = '50%'; style.transform = 'translate(-50%, -50%)';
break;
}
}
}
/**
* 应用样式到容器
*/
private applyStyles(): void {
const style = this.container.style;
if (this.options.backgroundColor) style.setProperty('--bim-btn-group-section-bg', this.options.backgroundColor);
if (this.options.btnBackgroundColor) style.setProperty('--bim-btn-bg', this.options.btnBackgroundColor);
if (this.options.btnHoverColor) style.setProperty('--bim-btn-hover-bg', this.options.btnHoverColor);
if (this.options.btnActiveColor) style.setProperty('--bim-btn-active-bg', this.options.btnActiveColor);
if (this.options.iconColor) style.setProperty('--bim-icon-color', this.options.iconColor);
if (this.options.iconActiveColor) style.setProperty('--bim-icon-active-color', this.options.iconActiveColor);
if (this.options.textColor) style.setProperty('--bim-btn-text-color', this.options.textColor);
if (this.options.textActiveColor) style.setProperty('--bim-btn-text-active-color', this.options.textActiveColor);
// 同步更新所有已存在的dropdown元素的CSS变量dropdown被添加到body无法继承容器的CSS变量
const dropdowns = document.querySelectorAll('.opt-btn-dropdown');
dropdowns.forEach(dropdown => {
const dropdownStyle = (dropdown as HTMLElement).style;
if (this.options.iconColor) dropdownStyle.setProperty('--bim-icon-color', this.options.iconColor);
if (this.options.iconActiveColor) dropdownStyle.setProperty('--bim-icon-active-color', this.options.iconActiveColor);
if (this.options.textColor) dropdownStyle.setProperty('--bim-btn-text-color', this.options.textColor);
if (this.options.textActiveColor) dropdownStyle.setProperty('--bim-btn-text-active-color', this.options.textActiveColor);
if (this.options.btnBackgroundColor) dropdownStyle.setProperty('--bim-btn-bg', this.options.btnBackgroundColor);
if (this.options.btnHoverColor) dropdownStyle.setProperty('--bim-btn-hover-bg', this.options.btnHoverColor);
if (this.options.btnActiveColor) dropdownStyle.setProperty('--bim-btn-active-bg', this.options.btnActiveColor);
});
}
/**
* 设置主题的primary颜色用于边框等
*/
private setPrimaryColor(color: string): void {
this.container.style.setProperty('--bim-primary-color', color);
// 同步更新所有dropdowndropdown被添加到body无法继承容器的CSS变量
const dropdowns = document.querySelectorAll('.opt-btn-dropdown');
dropdowns.forEach(dropdown => {
(dropdown as HTMLElement).style.setProperty('--bim-primary-color', color);
});
}
/**
* 设置主题颜色
* 只会应用到没有被用户自定义的颜色属性上
*/
public setTheme(theme: ThemeConfig): void {
const themeColors: ButtonGroupColors = {
backgroundColor: theme.panelBackground,
btnBackgroundColor: theme.componentBackground,
btnHoverColor: theme.componentHover,
btnActiveColor: theme.componentActive,
iconColor: theme.icon,
iconActiveColor: theme.iconActive,
textColor: theme.textSecondary,
textActiveColor: theme.textPrimary
};
// 只应用没有被自定义的颜色
Object.entries(themeColors).forEach(([key, value]) => {
const colorKey = key as keyof ButtonGroupColors;
if (!this.customColors.has(colorKey)) {
this.options[colorKey] = value;
}
});
this.applyStyles();
this.setPrimaryColor(theme.primary);
}
/**
* 直接设置颜色(强制覆盖)
* 设置的颜色会被标记为自定义,后续的 setTheme 不会覆盖它们
*/
public setColors(colors: ButtonGroupColors): void {
// 更新 options
this.options = { ...this.options, ...colors };
// 标记这些颜色为自定义
Object.keys(colors).forEach(key => {
this.customColors.add(key as keyof ButtonGroupColors);
});
this.applyStyles();
}
public async init(): Promise<void> {
this.render();
// 自动订阅语言变更
this.unsubscribeLocale = localeManager.subscribe(() => {
this.setLocales();
});
// 自动订阅主题变更
this.unsubscribeTheme = themeManager.subscribe((theme) => {
this.setTheme(theme);
});
}
public setLocales(): void {
this.render();
}
public addGroup(groupId: string, beforeGroupId?: string): void {
if (this.groups.some(g => g.id === groupId)) return;
const newGroup: ButtonGroup = { id: groupId, buttons: [] };
if (beforeGroupId) {
const index = this.groups.findIndex(g => g.id === beforeGroupId);
index !== -1 ? this.groups.splice(index, 0, newGroup) : this.groups.push(newGroup);
} else {
this.groups.push(newGroup);
}
}
public addButton(config: ButtonConfig): void {
const { groupId, parentId } = config;
const group = this.groups.find(g => g.id === groupId);
if (!group) return;
const button: OptButton = { ...config, children: config.children || [] };
if (parentId) {
const parentBtn = this.findButton(group.buttons, parentId);
if (parentBtn) {
if (!parentBtn.children) parentBtn.children = [];
parentBtn.children.push(button);
}
} else {
group.buttons.push(button);
}
}
private findButton(buttons: OptButton[], id: string): OptButton | undefined {
for (const btn of buttons) {
if (btn.id === id) return btn;
if (btn.children) {
const found = this.findButton(btn.children, id);
if (found) return found;
}
}
return undefined;
}
public render(): void {
this.container.innerHTML = '';
this.btnRefs.clear();
this.groups.forEach((group, index) => {
const groupElement = this.renderGroup(group, index, this.groups.length);
this.container.appendChild(groupElement);
});
}
private renderGroup(group: ButtonGroup, index: number, total: number): HTMLElement {
const groupEl = document.createElement('div');
groupEl.className = 'bim-btn-group-section';
if (index < total - 1) {
groupEl.classList.add('has-divider');
}
group.buttons.forEach(button => {
if (this.isVisible(button.id)) {
const btnWrapper = this.renderButton(button);
groupEl.appendChild(btnWrapper);
}
});
return groupEl;
}
private renderButton(button: OptButton): HTMLElement {
const wrapper = document.createElement('div');
wrapper.className = 'opt-btn-wrapper';
const btnEl = document.createElement('div');
btnEl.className = 'opt-btn';
// 初始化时根据 button 自身的属性同步 active 状态
if (button.isActive) {
this.activeBtnIds.add(button.id);
}
// 按钮优先使用自己的 align否则使用全局配置默认为 vertical
const align = button.align || this.options.align || 'vertical';
if (align === 'horizontal') {
btnEl.classList.add('align-horizontal');
} else {
btnEl.classList.add('align-vertical');
}
if (this.activeBtnIds.has(button.id)) btnEl.classList.add('active');
if (button.disabled) btnEl.classList.add('disabled');
// 判断是否显示 label
const hasLabel = this.options.showLabel && button.label;
if (!hasLabel) {
btnEl.classList.add('no-label');
// 当不显示 label 时,添加 title 属性作为 tooltip
if (button.label) {
btnEl.title = t(button.label);
}
}
// 应用按钮的自定义样式
const iconSize = button.iconSize || 32;
const minWidth = button.minWidth || 50;
btnEl.style.minWidth = `${minWidth}px`;
const icon = document.createElement('div');
icon.className = 'opt-btn-icon';
icon.style.width = `${iconSize}px`;
icon.style.height = `${iconSize}px`;
icon.innerHTML = this.getIcon(button.icon);
btnEl.appendChild(icon);
// 创建文字和箭头的容器,确保它们始终在一起(无论主轴是横是竖)
const textWrapper = document.createElement('div');
textWrapper.className = 'opt-btn-text-wrapper';
if (this.options.showLabel && button.label) {
const label = document.createElement('span');
label.className = 'opt-btn-label';
label.textContent = t(button.label);
textWrapper.appendChild(label);
}
if (button.children && button.children.length > 0) {
const arrow = document.createElement('span');
arrow.className = 'opt-btn-arrow';
arrow.textContent = '▼';
textWrapper.appendChild(arrow);
}
// 只有当有内容时才添加 wrapper
if (textWrapper.hasChildNodes()) {
btnEl.appendChild(textWrapper);
}
btnEl.addEventListener('click', () => this.handleClick(button));
btnEl.addEventListener('mouseenter', () => this.handleMouseEnter(button, btnEl));
btnEl.addEventListener('mouseleave', () => this.handleMouseLeave());
this.btnRefs.set(button.id, btnEl);
wrapper.appendChild(btnEl);
return wrapper;
}
/**
* 设置按钮的激活状态
* @param id 按钮 ID
* @param active 可选,如果不传则切换(toggle)当前状态
*/
public setBtnActive(id: string, active?: boolean): void {
const button = this.findButtonById(id);
if (!button) return;
// 确定最终状态
const newState = active !== undefined ? active : !this.activeBtnIds.has(id);
if (newState) {
this.activeBtnIds.add(id);
} else {
this.activeBtnIds.delete(id);
}
// 同步对象状态并更新 DOM
button.isActive = newState;
this.updateButtonState(id);
}
private handleClick(button: OptButton): void {
if (button.disabled) return;
if (!button.children || button.children.length === 0) {
if (button.keepActive) {
// 1) 先切换自身激活状态onClick 里通常会根据 isActive 决定“打开/关闭”逻辑)
const wasActive = this.activeBtnIds.has(button.id);
const newState = !wasActive;
this.setBtnActive(button.id, newState);
// 2) 互斥逻辑:仅在“本次切换为激活”时触发
// - 一级按钮:同 groupId 下其它一级按钮互斥
// - 二级按钮:同 groupId + 同 parentId 下其它二级按钮互斥
// - 被关闭的按钮需要触发 onClick用于执行关闭逻辑
if (newState && button.exclusive && button.groupId) {
this.deactivateExclusiveSiblings(button);
}
}
this.closeDropdown();
if (button.onClick) button.onClick(button);
}
}
/**
* 互斥关闭同范围内的其它已激活按钮,并触发它们的 onClick
* @param button 当前被激活的按钮
*/
private deactivateExclusiveSiblings(button: OptButton): void {
const group = this.groups.find(g => g.id === button.groupId);
if (!group) return;
// 二级按钮:同 groupId + 同 parentId
if (button.parentId) {
const parent = this.findButton(group.buttons, button.parentId);
const siblings = parent?.children || [];
for (const sib of siblings) {
if (!sib) continue;
if (sib.id === button.id) continue;
if (sib.parentId !== button.parentId) continue;
if (sib.groupId !== button.groupId) continue;
if (this.activeBtnIds.has(sib.id)) {
this.setBtnActive(sib.id, false);
// 触发被关闭按钮的 onClick此时 sib.isActive 已经同步为 false
if (sib.onClick) sib.onClick(sib);
}
}
return;
}
// 一级按钮:同 groupId 下其它一级按钮(不包含二级)
for (const sib of group.buttons) {
if (sib.id === button.id) continue;
if (sib.groupId !== button.groupId) continue;
if (sib.parentId) continue; // 只处理一级按钮
if (this.activeBtnIds.has(sib.id)) {
this.setBtnActive(sib.id, false);
if (sib.onClick) sib.onClick(sib);
}
}
}
private handleMouseEnter(button: OptButton, btnEl: HTMLElement): void {
if (this.hoverTimeout) clearTimeout(this.hoverTimeout);
if (button.children && button.children.length > 0) {
this.showDropdown(button, btnEl);
} else {
this.closeDropdown();
}
}
private handleMouseLeave(): void {
this.hoverTimeout = window.setTimeout(() => this.closeDropdown(), 200);
}
private showDropdown(button: OptButton, btnEl: HTMLElement): void {
this.closeDropdown();
if (!button.children) return;
const dropdown = document.createElement('div');
dropdown.className = 'opt-btn-dropdown';
if (this.options.backgroundColor) dropdown.style.setProperty('--bim-toolbar-bg', this.options.backgroundColor);
// 将主题CSS变量复制到dropdown元素上因为dropdown被添加到body无法继承容器的CSS变量
const dropdownStyle = dropdown.style;
if (this.options.iconColor) dropdownStyle.setProperty('--bim-icon-color', this.options.iconColor);
if (this.options.iconActiveColor) dropdownStyle.setProperty('--bim-icon-active-color', this.options.iconActiveColor);
if (this.options.textColor) dropdownStyle.setProperty('--bim-btn-text-color', this.options.textColor);
if (this.options.textActiveColor) dropdownStyle.setProperty('--bim-btn-text-active-color', this.options.textActiveColor);
if (this.options.btnBackgroundColor) dropdownStyle.setProperty('--bim-btn-bg', this.options.btnBackgroundColor);
if (this.options.btnHoverColor) dropdownStyle.setProperty('--bim-btn-hover-bg', this.options.btnHoverColor);
if (this.options.btnActiveColor) dropdownStyle.setProperty('--bim-btn-active-bg', this.options.btnActiveColor);
// 获取按钮的位置信息
const btnRect = btnEl.getBoundingClientRect();
const expand = this.options.expand || 'down';
// 根据主按钮组的方向设置下拉菜单的布局方向
if (this.options.direction === 'row') {
dropdown.style.flexDirection = 'column'; // 横向按钮组,菜单纵向排列
} else {
dropdown.style.flexDirection = 'row'; // 纵向按钮组,菜单横向排列
}
// 先添加到 DOM 以便计算尺寸
document.body.appendChild(dropdown);
// 添加事件拦截
this.setupEventInterception(dropdown);
// 添加菜单项
button.children.forEach(subBtn => {
if (this.isVisible(subBtn.id)) {
const item = this.renderDropdownItem(subBtn);
dropdown.appendChild(item);
}
});
// 获取下拉菜单的实际尺寸
const dropdownRect = dropdown.getBoundingClientRect();
if (expand === 'up') {
// 向上展开,与按钮水平居中对齐
dropdown.style.bottom = (window.innerHeight - btnRect.top + 8) + 'px';
dropdown.style.left = (btnRect.left + (btnRect.width - dropdownRect.width) / 2) + 'px';
} else if (expand === 'down') {
// 向下展开,与按钮水平居中对齐
dropdown.style.top = (btnRect.bottom + 8) + 'px';
dropdown.style.left = (btnRect.left + (btnRect.width - dropdownRect.width) / 2) + 'px';
} else if (expand === 'right') {
// 向右展开,与按钮垂直居中对齐
dropdown.style.top = (btnRect.top + (btnRect.height - dropdownRect.height) / 2) + 'px';
dropdown.style.left = (btnRect.right + 8) + 'px';
} else if (expand === 'left') {
// 向左展开,与按钮垂直居中对齐
dropdown.style.top = (btnRect.top + (btnRect.height - dropdownRect.height) / 2) + 'px';
dropdown.style.right = (window.innerWidth - btnRect.left + 8) + 'px';
}
dropdown.addEventListener('mouseenter', () => { if (this.hoverTimeout) clearTimeout(this.hoverTimeout); });
dropdown.addEventListener('mouseleave', () => this.handleMouseLeave());
this.dropdownElement = dropdown;
}
private renderDropdownItem(button: OptButton): HTMLElement {
const item = document.createElement('div');
item.className = 'opt-btn-dropdown-item';
// 应用按钮的 align 设置,默认为 horizontal图标在左
const align = button.align || 'horizontal';
if (align === 'horizontal') {
item.classList.add('align-horizontal');
} else {
item.classList.add('align-vertical');
}
// 二级菜单项的 active 状态渲染(修复 keepActive 在二级按钮“看起来不生效”的问题)
// 说明:
// - keepActive 的状态会记录在 activeBtnIds / button.isActive 上
// - 下拉菜单每次打开都会重新渲染,因此必须在这里同步一次 active 样式
if (this.activeBtnIds.has(button.id) || button.isActive) {
item.classList.add('active');
}
// 应用按钮的自定义样式
const iconSize = button.iconSize || 32; // 二级菜单默认图标更小
const minWidth = button.minWidth; // 不设置默认值,让下拉菜单项保持紧凑
if (minWidth) {
item.style.minWidth = `${minWidth}px`;
}
const icon = document.createElement('div');
icon.className = 'opt-btn-icon';
icon.style.width = `${iconSize}px`;
icon.style.height = `${iconSize}px`;
icon.innerHTML = this.getIcon(button.icon);
item.appendChild(icon);
// 只有在 showLabel 为 true 时才显示 label
if (this.options.showLabel && button.label) {
const label = document.createElement('span');
label.className = 'opt-btn-dropdown-label';
label.textContent = t(button.label);
item.appendChild(label);
} else if (button.label) {
// 当不显示 label 时,添加 title 属性作为 tooltip
item.title = t(button.label);
}
item.addEventListener('click', (e) => { e.stopPropagation(); this.handleClick(button); });
return item;
}
private closeDropdown(): void {
if (this.dropdownElement) {
this.dropdownElement.remove();
this.dropdownElement = null;
}
this.btnRefs.forEach(btnEl => {
const arrow = btnEl.querySelector('.opt-btn-arrow');
if (arrow) arrow.classList.remove('rotated');
});
}
private updateButtonState(buttonId: string): void {
const btnEl = this.btnRefs.get(buttonId);
if (btnEl) {
if (this.activeBtnIds.has(buttonId)) {
btnEl.classList.add('active');
} else {
btnEl.classList.remove('active');
}
}
}
private getIcon(icon?: string): string { return icon || this.DEFAULT_ICON; }
public updateButtonVisibility(id: string, visible: boolean): void {
if (!this.options.visibility) this.options.visibility = {};
this.options.visibility[id] = visible;
this.render();
}
public setShowLabel(show: boolean): void {
this.options.showLabel = show;
this.updateLabelsVisibility();
}
private updateLabelsVisibility(): void {
this.btnRefs.forEach((btnEl, buttonId) => {
// 查找按钮配置
const button = this.findButtonById(buttonId);
if (!button) return;
const hasLabel = this.options.showLabel && button.label;
// 更新 no-label 类和 title 属性
if (hasLabel) {
btnEl.classList.remove('no-label');
// 显示标签时,移除 title避免重复显示
btnEl.removeAttribute('title');
} else {
btnEl.classList.add('no-label');
// 隐藏标签时,添加 title 作为 tooltip
if (button.label) {
btnEl.title = t(button.label);
}
}
});
}
private findButtonById(id: string): OptButton | undefined {
for (const group of this.groups) {
const found = this.findButton(group.buttons, id);
if (found) return found;
}
return undefined;
}
public setBackgroundColor(color: string): void { this.setColors({ backgroundColor: color }); }
private isVisible(id: string): boolean { return this.options.visibility?.[id] !== false; }
public destroy(): void {
if (this.unsubscribeLocale) {
this.unsubscribeLocale();
this.unsubscribeLocale = null;
}
if (this.unsubscribeTheme) {
this.unsubscribeTheme();
this.unsubscribeTheme = null;
}
this.closeDropdown();
this.container.innerHTML = '';
this.btnRefs.clear();
}
}

View File

@@ -0,0 +1,100 @@
export type ButtonType = 'button' | 'menu';
/** 按钮配置 */
export interface ButtonConfig {
id: string;
type: ButtonType;
label: string;
icon?: string;
keepActive?: boolean;
/**
* 是否互斥(开关互斥)
*
* 行为说明:
* - 当按钮从“未激活”切换到“激活”时,如果该按钮开启了 exclusive
* 会自动关闭同互斥范围内的其它已激活按钮,并触发它们的 onClick用于执行关闭逻辑
* - 一级按钮:互斥范围 = 同 groupId 下的一级按钮
* - 二级按钮:互斥范围 = 同 groupId 且同 parentId 下的二级按钮
*
* 注意:该能力通常与 keepActive 搭配使用。
*/
exclusive?: boolean;
isActive?:boolean;
disabled?: boolean;
onClick?: (button: OptButton) => void;
children?: ButtonConfig[];
groupId?: string;
parentId?: string;
/** 按钮内部图标文字排列 (默认 vertical即图标在上) */
align?: ButtonAlign;
/** 图标大小 (正方形,单位 px默认 32) */
iconSize?: number;
/** 按钮最小宽度 (单位 px默认 50) */
minWidth?: number;
}
export interface OptButton extends ButtonConfig {
children?: OptButton[];
}
export interface ButtonGroup {
id: string;
buttons: OptButton[];
}
export interface ButtonGroupColors {
backgroundColor?: string;
btnBackgroundColor?: string;
btnHoverColor?: string;
btnActiveColor?: string;
iconColor?: string;
iconActiveColor?: string;
textColor?: string;
textActiveColor?: string;
}
// --- 新增布局类型 ---
/** 弹窗/按钮组位置 */
export type GroupPosition =
| 'center'
| 'top-left' | 'top-center' | 'top-right'
| 'left-center' | 'right-center'
| 'bottom-left' | 'bottom-center' | 'bottom-right'
| { x: number; y: number }
| 'static'; // static 表示不绝对定位,随文档流
/** 按钮组排列方向 (Flex-direction) */
export type GroupDirection = 'row' | 'column';
/** 按钮内部文字图标排列 */
export type ButtonAlign = 'vertical' /* 图标在上 */ | 'horizontal' /* 图标在左 */;
/** 二级菜单展开方向 */
export type ExpandDirection = 'up' | 'down' | 'left' | 'right';
export interface ButtonGroupOptions extends ButtonGroupColors {
container: HTMLElement | string;
/** 屏幕位置 (如 top-left) */
position?: GroupPosition;
/** 按钮组排列方向 (默认 row) */
direction?: GroupDirection;
/** 按钮内部图标文字排列 (默认 vertical) */
align?: ButtonAlign;
/** 菜单展开方向 */
expand?: ExpandDirection;
showLabel?: boolean;
visibility?: Record<string, boolean>;
className?: string;
}
export interface ClickPayload {
button: OptButton;
action: 'activate' | 'deactivate' | 'trigger';
isActive?: boolean;
}

View File

@@ -0,0 +1,96 @@
import type { ButtonGroupColors, ButtonConfig } from '../components/button-group/index.type';
import { Toolbar } from '../components/button-group/toolbar';
import type { ThemeConfig } from '../themes/types';
import { BimComponent } from '../core/component';
import type { BimEngine } from '../bim-engine';
/**
* 底部工具栏管理器 (ToolbarManager)
* 仅负责管理底部工具栏实例。
*/
export class ToolbarManager extends BimComponent {
private toolbar: Toolbar | null = null;
private toolbarContainer: HTMLElement | null = null;
private container: HTMLElement;
constructor(engine: BimEngine, container: HTMLElement) {
super(engine);
this.container = container;
this.init();
}
private init() {
// 创建底部工具栏专用容器
this.toolbarContainer = document.createElement('div');
this.toolbarContainer.id = 'opt-btn-groups';
this.toolbarContainer.className = 'bim-engine-opt-btn-container is-bottom-toolbar';
this.container.appendChild(this.toolbarContainer);
this.toolbar = new Toolbar({
container: this.toolbarContainer,
showLabel: true,
direction: 'row',
position: 'bottom-center', // 底部居中
align: 'vertical', // 图标在上
expand: 'up' // 向上展开
});
// 注入 engine 到 Toolbar
// @ts-ignore - Toolbar 还没更新类型,暂时忽略
this.toolbar.setEngine(this.engine);
this.toolbar.init();
}
public updateTheme(theme: ThemeConfig) {
this.toolbar?.setTheme(theme);
}
public refresh() {
this.toolbar?.render();
}
public destroy() {
this.toolbar?.destroy();
this.toolbar = null;
}
// --- 转发 API ---
public addGroup(groupId: string, beforeGroupId?: string) { this.toolbar?.addGroup(groupId, beforeGroupId); this.toolbar?.render(); }
public addButton(config: ButtonConfig) { this.toolbar?.addButton(config); this.toolbar?.render(); }
public setButtonVisibility(id: string, v: boolean) { this.toolbar?.updateButtonVisibility(id, v); }
public setShowLabel(show: boolean) { this.toolbar?.setShowLabel(show); }
public setBtnActive(id: string, active?: boolean) { this.toolbar?.setBtnActive(id, active); }
public setVisible(visible: boolean) {
if (this.toolbarContainer) {
this.toolbarContainer.style.visibility = visible ? 'visible' : 'hidden';
}
}
public setBackgroundColor(color: string) { this.toolbar?.setBackgroundColor(color); }
public setColors(colors: ButtonGroupColors) { this.toolbar?.setColors(colors); }
/**
* 隐藏工具栏
*/
public hide(): void {
if (this.toolbarContainer) {
this.toolbarContainer.style.display = 'none';
}
}
/**
* 显示工具栏
*/
public show(): void {
if (this.toolbarContainer) {
this.toolbarContainer.style.display = '';
}
}
/**
* 获取工具栏容器
*/
public getContainer(): HTMLElement | null {
return this.toolbarContainer;
}
}