341 lines
18 KiB
JavaScript
341 lines
18 KiB
JavaScript
import { icon } from './layout.js';
|
|
import { assemblySource, loadProjectAssembly } from './project-resources.js';
|
|
import { ASSEMBLY_PACE } from './assembly-animation.js';
|
|
import { AssemblyTimeline } from './assembly-timeline.js';
|
|
import { setupAssemblyControls } from './assembly-controls.js';
|
|
|
|
export const getAssemblyModel = (project) => assemblySource(project);
|
|
|
|
let activeDialog;
|
|
|
|
export function openAssemblyPreview(project, { initialStep = 0, focusPartId = null, autoPlay = initialStep === 0 } = {}) {
|
|
const model = getAssemblyModel(project);
|
|
if (!model || activeDialog) return;
|
|
const previousFocus = document.activeElement;
|
|
const previousOverflow = document.body.style.overflow;
|
|
const dialog = document.createElement('dialog');
|
|
activeDialog = dialog;
|
|
dialog.className = 'assembly-dialog';
|
|
dialog.setAttribute('aria-label', `${project.name} 装配模型`);
|
|
dialog.innerHTML = `
|
|
<button class="icon-btn preview-close" data-close aria-label="关闭 AI 装配" autofocus>${icon('close', 20)}</button>
|
|
<div class="assembly-viewport assembly-with-controls" aria-label="机器人三维模型">
|
|
<div class="assembly-scene"></div>
|
|
<div class="assembly-loading" role="status" aria-live="polite">
|
|
<span class="spinner"></span><strong>正在加载装配模型</strong><span data-progress>准备模型与材质…</span>
|
|
<button class="btn btn-sm" data-retry hidden>重新加载</button>
|
|
</div>
|
|
<aside class="assembly-controls" aria-label="装配控制">
|
|
<button class="assembly-controls-toggle" data-controls-toggle aria-expanded="false" aria-controls="assembly-player assembly-view-tools" aria-label="显示播放控制">${icon('menu', 14)}<span>显示控制</span></button>
|
|
<div class="assembly-progress-panel">
|
|
<div class="assembly-panel-heading">
|
|
<strong data-panel-title>模型视图</strong>
|
|
<span data-step-count></span>
|
|
</div>
|
|
<div class="assembly-panel-context">
|
|
<span data-stage-label>拖拽模型查看细节</span>
|
|
<button class="assembly-motion-status" data-focus hidden aria-label="聚焦当前螺丝">
|
|
<span data-motion-label></span><span data-focus-label>查看特写 ↗</span>
|
|
</button>
|
|
</div>
|
|
<div class="assembly-step" hidden>
|
|
<div class="assembly-timeline" id="assembly-step-list" aria-label="附近装配步骤,可上下滑动切换"><ol></ol></div>
|
|
<span class="assembly-sr-only" data-step-label aria-live="polite" aria-atomic="true"></span>
|
|
<div class="assembly-playback" id="assembly-player">
|
|
<input class="assembly-progress" data-seek type="range" min="0" step="1" value="0" aria-label="装配进度">
|
|
<div class="assembly-transport">
|
|
<button class="btn btn-sm" data-prev aria-label="上一步装配" title="上一步">${icon('left', 18)}</button>
|
|
<button class="btn btn-sm" data-play aria-pressed="false" aria-label="播放装配">
|
|
<span class="assembly-play-symbol" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16"><path class="play-shape" d="m8 5 11 7-11 7Z"/><path class="pause-shape" d="M7 5h3v14H7zM14 5h3v14h-3z"/></svg></span><span data-play-label>播放装配</span>
|
|
</button>
|
|
<button class="btn btn-sm" data-next aria-label="下一步装配" title="下一步">${icon('right', 18)}</button>
|
|
<button class="btn btn-sm assembly-tools-toggle" data-tools-toggle aria-expanded="false" aria-controls="assembly-view-tools" aria-label="更多装配操作" title="更多操作"><svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor" aria-hidden="true"><circle cx="5" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="19" cy="12" r="1.7"/></svg><span>更多</span></button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="assembly-tools" id="assembly-view-tools" aria-label="视图工具">
|
|
<button class="btn btn-sm" data-steps hidden title="逐步装配">${icon('cube', 15)}<span>逐步装配</span></button>
|
|
<button class="btn btn-sm" data-explode hidden disabled aria-pressed="false" title="爆炸图">${icon('sparkle', 15)}<span>爆炸图</span></button>
|
|
<button class="btn btn-sm" data-replay hidden title="重播本步">${icon('history', 15)}<span>重播本步</span></button>
|
|
<button class="btn btn-sm" data-closeup hidden aria-pressed="false" title="固定查看当前安装位置;拖动视角可退出特写">${icon('eye', 15)}<span>特写</span></button>
|
|
<button class="btn btn-sm" data-rotate aria-pressed="false" disabled title="自动旋转">${icon('play', 15)}<span>自动旋转</span></button>
|
|
<button class="btn btn-sm" data-reset disabled title="重置视角">${icon('history', 15)}<span>重置视角</span></button>
|
|
</div>
|
|
<label class="assembly-explosion" hidden>
|
|
<span>分散程度</span>
|
|
<input data-explosion type="range" min="0" max="100" step="1" value="65" aria-label="爆炸分散程度">
|
|
<output data-explosion-value>65%</output>
|
|
</label>
|
|
</aside>
|
|
</div>`;
|
|
document.body.append(dialog);
|
|
dialog.showModal();
|
|
document.body.style.overflow = 'hidden';
|
|
|
|
const find = (selector) => dialog.querySelector(selector);
|
|
const controller = new AbortController();
|
|
let preview;
|
|
let loading = false;
|
|
let config;
|
|
let timeline;
|
|
let stepIndex = null;
|
|
let playing = false;
|
|
let playTimer;
|
|
let activeScrew;
|
|
let exploded = false;
|
|
const labelTool = (target, label) => {
|
|
const button = typeof target === 'string' ? find(target) : target;
|
|
button.querySelector('span').textContent = label;
|
|
button.setAttribute('aria-label', label);
|
|
button.setAttribute('data-tooltip', label);
|
|
button.removeAttribute('title');
|
|
};
|
|
dialog.querySelectorAll('.assembly-tools button').forEach(button => {
|
|
labelTool(button, button.querySelector('span').textContent);
|
|
});
|
|
const hasMotion = () => !!preview?.cameraTransition || !!preview?.transitions?.length;
|
|
const syncPlaybackUI = () => {
|
|
const active = playing || (hasMotion() && !preview?.animationPaused);
|
|
const label = active ? '暂停装配' : hasMotion() ? '继续装配' : '播放装配';
|
|
find('[data-play-label]').textContent = label;
|
|
find('[data-play]').setAttribute('aria-label', label);
|
|
find('[data-play]').title = label;
|
|
find('[data-play]').setAttribute('aria-pressed', String(active));
|
|
};
|
|
const updateExplosionUI = (enabled) => {
|
|
exploded = enabled;
|
|
find('.assembly-viewport').classList.toggle('is-exploded', enabled);
|
|
find('.assembly-explosion').hidden = !enabled;
|
|
labelTool('[data-explode]', enabled ? '还原模型' : '爆炸图');
|
|
find('[data-explode]').setAttribute('aria-pressed', String(enabled));
|
|
};
|
|
const stopPlayback = () => {
|
|
playing = false;
|
|
clearTimeout(playTimer);
|
|
preview?.setAnimationPaused(true);
|
|
syncPlaybackUI();
|
|
};
|
|
const showStep = (index, animate = true) => {
|
|
stepIndex = index;
|
|
if (index === null) setToolsExpanded(false);
|
|
updateExplosionUI(false);
|
|
preview.setStep(index, animate);
|
|
syncPlaybackUI();
|
|
find('.assembly-viewport').classList.toggle('is-stepping', index !== null);
|
|
find('.assembly-step').hidden = index === null;
|
|
find('[data-play]').hidden = index === null;
|
|
find('[data-replay]').hidden = index === null;
|
|
find('[data-closeup]').hidden = index === null || config.steps[index].type === 'join';
|
|
find('[data-rotate]').hidden = index !== null;
|
|
find('[data-explode]').hidden = index !== null || config.parts.length < 2;
|
|
labelTool('[data-steps]', index === null ? '逐步装配' : '查看整体');
|
|
find('[data-panel-title]').textContent = index === null ? '模型视图' : '装配进度';
|
|
find('[data-step-count]').textContent = index === null ? '' : `${String(index + 1).padStart(2, '0')} / ${config.steps.length}`;
|
|
const step = index === null ? null : config.steps[index];
|
|
find('[data-stage-label]').textContent = step
|
|
? (config.groups?.find(group => group.id === step.groupId)?.label || (step.type === 'join' ? '总装 · 部件就位'
|
|
: step.label.includes('·') ? step.label.split('·')[0].trim() : '逐步安装'))
|
|
: '拖拽模型查看细节';
|
|
if (index !== null) {
|
|
preview.setAutoRotate(false);
|
|
find('[data-rotate]').setAttribute('aria-pressed', 'false');
|
|
labelTool('[data-rotate]', '自动旋转');
|
|
}
|
|
if (index !== null) {
|
|
find('[data-step-label]').textContent = `${index + 1} / ${config.steps.length} · ${config.steps[index].label}`;
|
|
find('[data-step-label]').title = find('[data-step-label]').textContent;
|
|
find('[data-seek]').value = String(index);
|
|
find('[data-seek]').style.setProperty('--assembly-progress-value', `${config.steps.length > 1 ? index / (config.steps.length - 1) * 100 : 100}%`);
|
|
find('[data-seek]').setAttribute('aria-valuetext', `第 ${index + 1} 步,共 ${config.steps.length} 步,${config.steps[index].label}`);
|
|
find('[data-prev]').disabled = index === 0;
|
|
find('[data-next]').disabled = index === config.steps.length - 1;
|
|
timeline.update(index, animate);
|
|
}
|
|
};
|
|
const setToolsExpanded = (expanded) => {
|
|
const wasExpanded = find('[data-tools-toggle]').getAttribute('aria-expanded') === 'true';
|
|
find('.assembly-viewport').classList.toggle('is-tools-expanded', expanded);
|
|
find('[data-tools-toggle]').setAttribute('aria-expanded', String(expanded));
|
|
if (wasExpanded && !expanded && find('.assembly-tools').contains(document.activeElement) && stepIndex !== null) find('[data-tools-toggle]').focus({ preventScroll: true });
|
|
};
|
|
find('[data-tools-toggle]').addEventListener('click', () => {
|
|
const expanded = find('[data-tools-toggle]').getAttribute('aria-expanded') !== 'true';
|
|
setToolsExpanded(expanded);
|
|
if (expanded) {
|
|
stopPlayback();
|
|
}
|
|
});
|
|
find('.assembly-tools').addEventListener('click', (event) => {
|
|
if (event.target.closest('button') && find('.assembly-viewport').classList.contains('is-tools-expanded')) setToolsExpanded(false);
|
|
});
|
|
dialog.addEventListener('pointerdown', (event) => {
|
|
if (!event.target.closest('.assembly-tools, [data-tools-toggle]')) setToolsExpanded(false);
|
|
});
|
|
dialog.addEventListener('cancel', (event) => {
|
|
if (find('.assembly-viewport').classList.contains('is-tools-expanded')) { event.preventDefault(); setToolsExpanded(false); }
|
|
});
|
|
find('[data-explode]').addEventListener('click', () => {
|
|
stopPlayback();
|
|
updateExplosionUI(!exploded);
|
|
preview.setExploded(exploded, Number(find('[data-explosion]').value) / 100);
|
|
});
|
|
find('[data-explosion]').addEventListener('input', (event) => {
|
|
const amount = Number(event.target.value);
|
|
find('[data-explosion-value]').textContent = `${amount}%`;
|
|
preview.setExploded(true, amount / 100, false);
|
|
});
|
|
find('[data-steps]').addEventListener('click', () => { stopPlayback(); showStep(stepIndex === null ? 0 : null); });
|
|
find('[data-prev]').addEventListener('click', () => { stopPlayback(); showStep(Math.max(0, stepIndex - 1)); });
|
|
find('[data-next]').addEventListener('click', () => { stopPlayback(); showStep(Math.min(config.steps.length - 1, stepIndex + 1)); });
|
|
find('[data-seek]').addEventListener('input', (event) => { stopPlayback(); showStep(Number(event.target.value), false); });
|
|
find('[data-replay]').addEventListener('click', () => { stopPlayback(); showStep(stepIndex); });
|
|
find('[data-focus]').addEventListener('click', () => { if (activeScrew) preview.focusPart(activeScrew); });
|
|
find('[data-closeup]').addEventListener('click', () => preview?.setCloseup(!preview.closeupEnabled));
|
|
const startPlayback = () => {
|
|
if (!preview || stepIndex === null || !config.steps.length || controller.signal.aborted) return;
|
|
clearTimeout(playTimer);
|
|
if (stepIndex === config.steps.length - 1 && !hasMotion()) showStep(0, false);
|
|
playing = true;
|
|
preview.setAnimationPaused(false);
|
|
syncPlaybackUI();
|
|
let settledAt = null;
|
|
const advance = () => {
|
|
if (!playing || controller.signal.aborted) return;
|
|
if (document.hidden) { stopPlayback(); return; }
|
|
// Give every completed installation a visible hold, independent of frame rate.
|
|
if (hasMotion()) settledAt = null;
|
|
else if (settledAt === null) settledAt = performance.now();
|
|
else if (performance.now() - settledAt >= ASSEMBLY_PACE.stepHold * 1000) {
|
|
if (stepIndex === config.steps.length - 1) { stopPlayback(); return; }
|
|
showStep(stepIndex + 1);
|
|
settledAt = null;
|
|
}
|
|
playTimer = setTimeout(advance, 100);
|
|
};
|
|
playTimer = setTimeout(advance, 100);
|
|
};
|
|
find('[data-play]').addEventListener('click', () => {
|
|
if (playing || (hasMotion() && !preview.animationPaused)) { stopPlayback(); return; }
|
|
startPlayback();
|
|
});
|
|
const visibility = () => { if (document.hidden) stopPlayback(); };
|
|
document.addEventListener('visibilitychange', visibility);
|
|
const setEnabled = (enabled) => {
|
|
dialog.querySelectorAll('.assembly-controls button, .assembly-controls input')
|
|
.forEach((control) => { control.disabled = !enabled; });
|
|
timeline?.setEnabled(enabled);
|
|
};
|
|
|
|
dialog.addEventListener('close', () => {
|
|
stopPlayback();
|
|
document.removeEventListener('visibilitychange', visibility);
|
|
controller.abort();
|
|
timeline?.dispose();
|
|
preview?.dispose();
|
|
document.body.style.overflow = previousOverflow;
|
|
dialog.remove();
|
|
activeDialog = null;
|
|
previousFocus?.focus({ preventScroll: true });
|
|
}, { once: true });
|
|
find('[data-close]').addEventListener('click', () => dialog.close());
|
|
// 只有整个手势都在弹窗外才关闭,避免旋转模型时拖出窗口误关。
|
|
let outside = false;
|
|
dialog.addEventListener('pointerdown', (e) => { outside = e.target === dialog; });
|
|
dialog.addEventListener('click', (e) => { if (outside && e.target === dialog) dialog.close(); });
|
|
|
|
find('[data-reset]').addEventListener('click', () => preview?.resetView());
|
|
find('[data-rotate]').addEventListener('click', (e) => {
|
|
const button = e.currentTarget;
|
|
const enabled = button.getAttribute('aria-pressed') !== 'true';
|
|
preview?.setAutoRotate(enabled);
|
|
button.setAttribute('aria-pressed', String(enabled));
|
|
labelTool('[data-rotate]', enabled ? '停止旋转' : '自动旋转');
|
|
});
|
|
|
|
setupAssemblyControls(dialog, controller.signal);
|
|
|
|
async function load() {
|
|
if (loading || controller.signal.aborted) return;
|
|
loading = true;
|
|
const overlay = find('.assembly-loading');
|
|
overlay.hidden = false;
|
|
overlay.classList.remove('is-error');
|
|
find('[data-retry]').hidden = true;
|
|
find('[data-progress]').textContent = '准备模型与材质…';
|
|
overlay.querySelector('strong').textContent = '正在加载装配模型';
|
|
labelTool('[data-closeup]', '特写');
|
|
find('[data-closeup]').setAttribute('aria-pressed', 'false');
|
|
find('[data-focus-label]').textContent = '查看特写 ↗';
|
|
setEnabled(false);
|
|
try {
|
|
find('[data-progress]').textContent = '读取装配清单…';
|
|
const [{ AssemblyViewer }, pkg] = await Promise.all([import('./assembly-viewer.js'), loadProjectAssembly(project, controller.signal)]);
|
|
config = pkg;
|
|
if (controller.signal.aborted) return;
|
|
preview = new AssemblyViewer(find('.assembly-scene'));
|
|
preview.onCloseupChange = (enabled) => {
|
|
labelTool('[data-closeup]', enabled ? '退出特写' : '特写');
|
|
find('[data-closeup]').setAttribute('aria-pressed', String(enabled));
|
|
find('[data-focus-label]').textContent = enabled ? '固定特写' : '查看特写 ↗';
|
|
};
|
|
preview.onContextLost = () => {
|
|
stopPlayback();
|
|
preview?.dispose();
|
|
preview = null;
|
|
setEnabled(false);
|
|
overlay.hidden = false;
|
|
overlay.classList.add('is-error');
|
|
overlay.querySelector('strong').textContent = '三维显示已中断';
|
|
find('[data-progress]').textContent = '可重新加载拼装模型,无需刷新页面。';
|
|
find('[data-retry]').hidden = false;
|
|
};
|
|
preview.onMotionChange = (motion) => {
|
|
activeScrew = motion?.partId;
|
|
find('[data-focus]').hidden = !motion;
|
|
if (motion) {
|
|
const phase = { approach: '螺丝就位', engage: '插入扳手', tighten: '拧紧螺丝', retract: '退出扳手' }[motion.phase];
|
|
find('[data-motion-label]').textContent = `${phase} · ${motion.index} / ${motion.count}`;
|
|
}
|
|
};
|
|
await preview.load(config, controller.signal, (percent) => {
|
|
find('[data-progress]').textContent = percent < 100 ? `读取模型 ${percent}%` : '正在还原材质…';
|
|
});
|
|
if (controller.signal.aborted) return;
|
|
preview.onAnimationEnd = () => { if (!playing) stopPlayback(); };
|
|
timeline?.dispose();
|
|
timeline = new AssemblyTimeline(find('.assembly-timeline'), config.steps, (index, animate = true) => {
|
|
stopPlayback(); showStep(index, animate);
|
|
}, stopPlayback);
|
|
overlay.hidden = true;
|
|
setEnabled(true);
|
|
find('[data-steps]').hidden = config.steps.length === 0;
|
|
find('[data-explode]').hidden = config.parts.length < 2;
|
|
find('[data-seek]').max = String(Math.max(0, config.steps.length - 1));
|
|
showStep(null, false);
|
|
find('[data-focus]').hidden = true;
|
|
if (Number.isInteger(initialStep) && initialStep >= 0 && initialStep < config.steps.length) {
|
|
showStep(initialStep, false);
|
|
if (focusPartId) preview.focusPart(focusPartId);
|
|
showStep(initialStep);
|
|
if (autoPlay && !document.hidden) startPlayback();
|
|
}
|
|
} catch (err) {
|
|
stopPlayback();
|
|
preview?.dispose();
|
|
preview = null;
|
|
if (controller.signal.aborted) return;
|
|
console.error('装配模型加载失败', err);
|
|
overlay.classList.add('is-error');
|
|
overlay.querySelector('strong').textContent = '模型暂时无法加载';
|
|
find('[data-progress]').textContent = err.message || '请重试,或关闭后重新打开。';
|
|
find('[data-retry]').hidden = false;
|
|
} finally {
|
|
loading = false;
|
|
}
|
|
}
|
|
find('[data-retry]').addEventListener('click', load);
|
|
load();
|
|
return dialog;
|
|
}
|