856 lines
40 KiB
JavaScript
856 lines
40 KiB
JavaScript
import { marked } from 'marked';
|
||
import DOMPurify from 'dompurify';
|
||
|
||
// README 来自用户仓库,渲染前去掉脚本、事件属性等,防止 XSS
|
||
const md = (text) => DOMPurify.sanitize(marked.parse(text));
|
||
import { splashProgress, splashDone } from './splash.js';
|
||
import { fetchCommunity, listDir, saveLocalState, refreshLocal, thumbnail } from './community.js';
|
||
import { renderShell, esc, fmt, avatar, icon, timeAgo, toast } from './layout.js';
|
||
import { dataMode, getProject, ensureRobot, getReadme, listProjects, userFrom, prefetchRoot } from './source.js';
|
||
import * as api from './api.js';
|
||
import { requireLogin, openModal } from './auth.js';
|
||
import { getAssemblyModel, openAssemblyPreview } from './assembly.js';
|
||
import { hasWalkingDemo, openWalkingDemo } from './walking.js';
|
||
import { projectExperiences } from './project-experiences.js';
|
||
import { prepareDocumentImages, hydrateDocumentImages } from './document-images.js';
|
||
import { constrainedAssemblyDevice } from './assembly-memory.js';
|
||
|
||
renderShell('explore');
|
||
|
||
const $ = (id) => document.getElementById(id);
|
||
const params = new URLSearchParams(location.search);
|
||
// 地址 /project/?id=<编号>(静态网站也能用);/project/<编号> 形式也兼容
|
||
const routeId = decodeURIComponent(location.pathname.match(/^\/project\/([^/]+)/)?.[1] || '') || params.get('id');
|
||
const GUEST = { handle: 'guest', name: '游客', color: '#9aa0aa' };
|
||
const LANG_COLORS = { Python: '#5ea8ff', 'C++': '#ff7a9a', URDF: '#c8ff3e', TypeScript: '#7cc4ff', Other: '#5c636c' };
|
||
const TABS = ['overview', 'files', 'discussions', 'forks', 'activity'];
|
||
|
||
let project, all, viewer;
|
||
let stageGeneration = 0, stageSuspended = false, stageCleanup = () => {};
|
||
function releaseStage() {
|
||
stageGeneration++;
|
||
stageCleanup();
|
||
stageCleanup = () => {};
|
||
viewer?.dispose();
|
||
viewer = null;
|
||
}
|
||
window.addEventListener('pagehide', releaseStage);
|
||
window.addEventListener('pageshow', event => {
|
||
if (event.persisted && project && !stageSuspended) setupViewer();
|
||
});
|
||
let tab = TABS.includes(params.get('tab')) ? params.get('tab') : params.get('path') ? 'files' : 'overview';
|
||
let path = params.get('path') || '';
|
||
let pathKind = null; // 后端模式:'dir' | 'file',未知时先按目录读
|
||
const sourceCache = new Map();
|
||
let descriptionObserver;
|
||
let cleanupReadmeImages, cleanupFileImages;
|
||
const documentOptions = (filePath = 'README.md') => ({ filePath, ...(project.api ? { rawUrl: (path) => api.communityRawUrl(project.code, path) } : {}) });
|
||
window.addEventListener('pagehide', (event) => {
|
||
// Mobile browsers restore this DOM from their back/forward cache.
|
||
if (!event.persisted) { cleanupReadmeImages?.(); cleanupFileImages?.(); }
|
||
});
|
||
|
||
// ---------- 标题区 ----------
|
||
function renderHead() {
|
||
const p = project;
|
||
document.title = `${p.name} · make`;
|
||
for (const el of [$('p-hero'), $('stage')]) el.style.setProperty('--hue', p.owner.color);
|
||
$('crumbs').innerHTML = `<a href="/explore/">社区</a><span>/</span><span>${esc(p.slug)}</span>`;
|
||
$('p-title').innerHTML = `<h1>${esc(p.name)}</h1><span class="badge">${esc(p.type)}</span>${p.license ? `<span class="badge">${esc(p.license)}</span>` : ''}`;
|
||
renderDescription(p.description);
|
||
$('p-meta').innerHTML = `
|
||
<span class="topics">${p.topics.map((t) => `<a class="chip" href="/explore/?q=${encodeURIComponent(t)}"># ${esc(t)}</a>`).join('')}</span>`;
|
||
$('p-meta').hidden = !p.topics.length;
|
||
renderCounters();
|
||
const experiences = projectExperiences(p);
|
||
$('ai-assembly').hidden = !getAssemblyModel(experiences);
|
||
$('ai-assembly').innerHTML = `${icon('sparkle', 15)}AI 装配`;
|
||
$('walking-demo').hidden = !hasWalkingDemo(experiences);
|
||
$('walking-demo').innerHTML = `${icon('play', 15)}仿真`;
|
||
}
|
||
|
||
function renderDescription(description) {
|
||
const wrapper = $('p-description');
|
||
const text = $('p-desc');
|
||
const toggle = $('p-desc-toggle');
|
||
descriptionObserver?.disconnect();
|
||
text.textContent = description || '';
|
||
wrapper.hidden = !text.textContent.trim();
|
||
toggle.innerHTML = `<span>展开</span>${icon('chevron', 16, 'aria-hidden="true"')}`;
|
||
const setExpanded = (expanded) => {
|
||
wrapper.classList.toggle('is-expanded', expanded);
|
||
toggle.setAttribute('aria-expanded', String(expanded));
|
||
toggle.querySelector('span').textContent = expanded ? '收起' : '展开';
|
||
};
|
||
setExpanded(false);
|
||
const updateOverflow = () => {
|
||
if (!text.isConnected) return;
|
||
const lines = Number(getComputedStyle(wrapper).getPropertyValue('--description-lines'));
|
||
const limit = parseFloat(getComputedStyle(text).lineHeight) * lines;
|
||
// 展开时仍按收起行数判断;短简介不显示多余的展开按钮。
|
||
const overflowing = text.scrollHeight > Math.ceil(limit) + 1;
|
||
toggle.hidden = !overflowing;
|
||
if (!overflowing) setExpanded(false);
|
||
};
|
||
toggle.onclick = () => {
|
||
const expanded = toggle.getAttribute('aria-expanded') !== 'true';
|
||
setExpanded(expanded);
|
||
if (!expanded && wrapper.getBoundingClientRect().top < 0) {
|
||
wrapper.scrollIntoView({ block: 'start', behavior: 'instant' });
|
||
}
|
||
};
|
||
descriptionObserver = new ResizeObserver(updateOverflow);
|
||
descriptionObserver.observe(text);
|
||
updateOverflow();
|
||
document.fonts.ready.then(updateOverflow);
|
||
}
|
||
|
||
let previewOpen = false;
|
||
function openPreview(open, releaseBackground = false) {
|
||
if (previewOpen) return;
|
||
previewOpen = true;
|
||
const release = releaseBackground && constrainedAssemblyDevice();
|
||
if (release) { stageSuspended = true; releaseStage(); }
|
||
const dialog = open();
|
||
if (!dialog) {
|
||
previewOpen = false;
|
||
if (release) { stageSuspended = false; setupViewer(); }
|
||
return;
|
||
}
|
||
viewer?.setPaused(true);
|
||
dialog.addEventListener('close', async () => {
|
||
// Wait for the iframe's physics/inference teardown before rebuilding URDF.
|
||
await dialog.previewDisposed;
|
||
previewOpen = false;
|
||
if (release) { stageSuspended = false; setupViewer(); }
|
||
else viewer?.setPaused(false);
|
||
}, { once: true });
|
||
}
|
||
$('ai-assembly').addEventListener('click', () => openPreview(() => openAssemblyPreview(projectExperiences(project)), true));
|
||
$('walking-demo').addEventListener('click', () => openPreview(() => openWalkingDemo(projectExperiences(project)), true));
|
||
|
||
function renderCounters() {
|
||
const p = project;
|
||
if (p.api) {
|
||
// 后端:收藏 = 点赞;Fork 暂无计数;没有订阅
|
||
$('counters').innerHTML = `
|
||
<div class="counter"><button data-act="fork" title="复制一份到你的工作区,在此基础上改装">${icon('fork', 15)}Fork</button>${p.forksTotal != null ? `<span>${fmt(p.forksTotal)}</span>` : ''}</div>
|
||
<div class="counter${p.liked ? ' on' : ''}"><button data-act="star">${icon('star', 15)}${p.liked ? '已收藏' : '收藏'}</button><span>${fmt(p.starsTotal)}</span></div>`;
|
||
return;
|
||
}
|
||
const s = p.local;
|
||
$('counters').innerHTML = `
|
||
<div class="counter${s.watching ? ' on' : ''}"><button data-act="watch" title="项目有新讨论或更新时通知你">${icon('eye', 15)}${s.watching ? '已订阅' : '订阅'}</button><span>${fmt(p.watchersTotal)}</span></div>
|
||
<div class="counter${s.forked ? ' on' : ''}"><button data-act="fork" title="复制一份到你的账号,在此基础上改装">${icon('fork', 15)}Fork</button><span>${fmt(p.forksTotal)}</span></div>
|
||
<div class="counter${s.starred ? ' on' : ''}"><button data-act="star">${icon('star', 15)}${s.starred ? '已收藏' : '收藏'}</button><span>${fmt(p.starsTotal)}</span></div>`;
|
||
}
|
||
|
||
$('counters').addEventListener('click', (e) => {
|
||
const b = e.target.closest('button[data-act]');
|
||
if (!b) return;
|
||
if (project.api) { remoteCounter(b.dataset.act, b); return; }
|
||
const s = project.local;
|
||
if (b.dataset.act === 'star') { s.starred = !s.starred; toast(s.starred ? '已加入收藏' : '已取消收藏'); }
|
||
if (b.dataset.act === 'watch') { s.watching = !s.watching; toast(s.watching ? '有新讨论和更新时会通知你' : '已取消订阅'); }
|
||
if (b.dataset.act === 'fork') {
|
||
if (s.forked) { toast(`你已经 Fork 过:guest/${project.slug}`); return; }
|
||
s.forked = true;
|
||
toast(`已 Fork 到 guest/${project.slug}(演示)`);
|
||
}
|
||
persist();
|
||
renderCounters();
|
||
renderTabs();
|
||
if (tab === 'forks') renderForks();
|
||
});
|
||
|
||
function persist() {
|
||
saveLocalState(project.id, project.local);
|
||
refreshLocal(project);
|
||
}
|
||
|
||
// ---------- 标签栏 ----------
|
||
function renderTabs() {
|
||
const p = project;
|
||
const items = p.api ? [
|
||
['overview', 'book', '概览', null],
|
||
['files', 'code', '文件', null],
|
||
['discussions', 'comment', '讨论', p.commentCount],
|
||
] : [
|
||
['overview', 'book', '概览', null],
|
||
['files', 'code', '文件', p.files.length],
|
||
['discussions', 'comment', '讨论', p.commentCount],
|
||
['forks', 'fork', 'Fork', p.forkList.length + (p.local.forked ? 1 : 0)],
|
||
['activity', 'pulse', '动态', p.commits.length],
|
||
];
|
||
$('tabs').innerHTML = items.map(([id, ic, label, n]) =>
|
||
`<button data-tab="${id}" class="${tab === id ? 'active' : ''}">${icon(ic, 15)}${label}${n != null ? `<span class="count">${n}</span>` : ''}</button>`).join('');
|
||
}
|
||
|
||
$('tabs').addEventListener('click', (e) => {
|
||
const b = e.target.closest('button[data-tab]');
|
||
if (!b) return;
|
||
setTab(b.dataset.tab);
|
||
const top = document.querySelector('.p-tabs').offsetTop;
|
||
if (scrollY > top) scrollTo({ top, behavior: 'smooth' });
|
||
});
|
||
|
||
function setTab(next) {
|
||
tab = next;
|
||
document.querySelectorAll('[data-panel]').forEach((el) => { el.hidden = el.dataset.panel !== tab; });
|
||
renderTabs();
|
||
if (tab === 'files') (project.api ? renderRemoteFiles : renderFiles)();
|
||
if (tab === 'discussions') (project.api ? renderRemoteDiscussions : renderDiscussions)();
|
||
if (tab === 'forks') renderForks();
|
||
if (tab === 'activity') renderActivity();
|
||
syncUrl();
|
||
}
|
||
|
||
function syncUrl() {
|
||
const url = new URL(`/project/${location.search}`, location.origin);
|
||
url.searchParams.set('id', project.id);
|
||
if (tab !== 'overview') url.searchParams.set('tab', tab); else url.searchParams.delete('tab');
|
||
if (tab === 'files' && path) url.searchParams.set('path', path); else url.searchParams.delete('path');
|
||
history.replaceState(null, '', url);
|
||
}
|
||
|
||
// ---------- 3D 展示 ----------
|
||
async function setupViewer() {
|
||
if (stageSuspended) return;
|
||
releaseStage();
|
||
const generation = stageGeneration;
|
||
const controller = new AbortController();
|
||
stageCleanup = () => controller.abort();
|
||
const stale = () => controller.signal.aborted || generation !== stageGeneration;
|
||
$('loader').classList.remove('hidden', 'error');
|
||
$('loader-text').textContent = '正在加载模型…';
|
||
if (!project.robot) {
|
||
$('stage').closest('section').hidden = true;
|
||
splashDone();
|
||
return;
|
||
}
|
||
// 详情区只展示后台绑定的 URDF;装配的 GLB 留在 AI 装配弹窗内。
|
||
$('stage').closest('section').hidden = false;
|
||
try {
|
||
// 3D 引擎按需加载:标题、README 先显示
|
||
const { RobotViewer } = await import('./viewer.js');
|
||
if (stale()) return;
|
||
const current = viewer = new RobotViewer($('stage'), { framing: 2.3, autoRotate: false, onDemand: true, renderPreset: 'studio' });
|
||
current.setPaused(!!document.querySelector('.assembly-dialog[open]'));
|
||
const loader = $('loader');
|
||
loader.classList.add('with-progress');
|
||
viewer.addEventListener('loading', () => { loader.classList.remove('hidden', 'error'); $('loader-text').textContent = '正在加载 URDF…'; });
|
||
viewer.addEventListener('progress', (e) => {
|
||
splashProgress(e.detail.loaded / e.detail.total);
|
||
$('loader-text').textContent = `正在加载零件 ${e.detail.loaded} / ${e.detail.total}`;
|
||
});
|
||
viewer.addEventListener('load', (e) => {
|
||
loader.classList.add('hidden');
|
||
splashDone();
|
||
$('stage-info').innerHTML = `<span class="chip">${icon('cube', 13)}URDF · <b>${e.detail.dof}</b> 个可动关节</span><span class="chip">拖动部件转动关节 · 拖拽空白处旋转</span>`;
|
||
const dof = $('fact-dof');
|
||
if (dof) dof.textContent = e.detail.dof;
|
||
});
|
||
viewer.addEventListener('hover', (e) => {
|
||
const tag = $('joint-tag');
|
||
if (e.detail.joint) tag.textContent = e.detail.joint;
|
||
tag.classList.toggle('show', !!e.detail.joint);
|
||
});
|
||
const retry = document.createElement('button');
|
||
retry.type = 'button'; retry.className = 'btn btn-sm'; retry.textContent = '重新加载模型'; retry.hidden = true;
|
||
loader.querySelector('.loader-box').append(retry);
|
||
let loading = false;
|
||
const loadRobot = async () => {
|
||
if (loading || stale()) return;
|
||
loading = true; retry.hidden = true;
|
||
try { await current.load(project.robot); }
|
||
catch (err) {
|
||
if (stale() || err.name === 'AbortError') return;
|
||
console.error(err);
|
||
loader.classList.remove('hidden'); loader.classList.add('error');
|
||
$('loader-text').textContent = `URDF 未能加载:${err.message || '请检查网络连接'}`;
|
||
retry.hidden = false;
|
||
splashDone({ failed: true });
|
||
} finally { loading = false; }
|
||
};
|
||
retry.addEventListener('click', loadRobot);
|
||
const reconnect = () => { if (!retry.hidden) loadRobot(); };
|
||
window.addEventListener('online', reconnect);
|
||
stageCleanup = () => {
|
||
controller.abort();
|
||
window.removeEventListener('online', reconnect);
|
||
retry.remove();
|
||
};
|
||
loadRobot();
|
||
|
||
// 只展示模型:不播放演示动作、不自动旋转(不是所有模型都有关节映射,演示动作不一定对)
|
||
viewer.setMode('manual');
|
||
viewer.controls.autoRotate = false;
|
||
$('reset-view').onclick = () => viewer?.resetPose();
|
||
} catch (error) {
|
||
if (stale()) return;
|
||
console.error(error);
|
||
releaseStage();
|
||
$('loader').classList.remove('hidden');
|
||
$('loader').classList.add('error');
|
||
$('loader-text').textContent = '3D 展示组件加载失败,请刷新页面重试';
|
||
splashDone({ failed: true });
|
||
}
|
||
}
|
||
|
||
// ---------- 概览:README ----------
|
||
function renderReadme() {
|
||
if (project.api && project.readme === undefined) return; // 还在读取:保留骨架
|
||
cleanupReadmeImages?.();
|
||
$('readme').innerHTML = `<div class="card-head"><span style="display:flex;gap:10px;align-items:center">${icon('book', 15)}<b style="font-weight:500">README.md</b></span>
|
||
<button class="btn btn-sm btn-ghost" data-open="README.md">查看源文件</button></div>
|
||
<div class="md">${project.readme ? prepareDocumentImages(md(project.readme), documentOptions()) : `<p class="muted">${esc(project.description || '作者还没有写 README')}</p>`}</div>`;
|
||
cleanupReadmeImages = hydrateDocumentImages($('readme'));
|
||
}
|
||
$('readme').addEventListener('click', (e) => {
|
||
const b = e.target.closest('[data-open]');
|
||
if (!b) return;
|
||
path = b.dataset.open;
|
||
pathKind = 'file';
|
||
setTab('files');
|
||
});
|
||
|
||
// ---------- 文件 ----------
|
||
function lastCommitRow(c) {
|
||
return `<div class="last-commit">${avatar(c.author, 24)}<b>${esc(c.author.name)}</b>
|
||
<span class="msg">${esc(c.msg)}</span><span class="h">${c.hash}</span><span>${timeAgo(c.time)}</span></div>`;
|
||
}
|
||
|
||
function crumbsFor(p) {
|
||
const parts = p ? p.split('/') : [];
|
||
const links = [`<a data-path="">${esc(project.slug)}</a>`];
|
||
parts.forEach((seg, i) => {
|
||
const sub = parts.slice(0, i + 1).join('/');
|
||
links.push('<span class="sep">/</span>', i === parts.length - 1 ? `<b>${esc(seg)}</b>` : `<a data-path="${esc(sub)}">${esc(seg)}</a>`);
|
||
});
|
||
return `<div class="path">${links.join('')}</div>`;
|
||
}
|
||
|
||
async function renderFiles() {
|
||
const files = project.files;
|
||
const file = files.find((f) => f.path === path);
|
||
const isDir = !file && (path === '' || files.some((f) => f.path.startsWith(path + '/')));
|
||
if (!file && !isDir) path = '';
|
||
const head = `<div class="card-head">
|
||
<span style="display:flex;align-items:center;gap:12px;flex-wrap:wrap"><span class="branch">${icon('branch', 14)}main</span>${crumbsFor(path)}</span>
|
||
<span style="display:flex;gap:8px;align-items:center"><span class="muted" style="font-size:13px">${project.commits.length} 次提交</span><button class="btn btn-sm" id="download">下载 ZIP</button></span>
|
||
</div>`;
|
||
const el = $('files');
|
||
if (!file) {
|
||
const entries = listDir(files, path);
|
||
const newest = entries.map((e) => e.commit).sort((a, b) => new Date(b.time) - new Date(a.time))[0] || project.commits[0];
|
||
const up = path ? `<tr><td colspan="3"><a class="fname dir" data-path="${esc(path.split('/').slice(0, -1).join('/'))}">${icon('folder', 16)}<span>..</span></a></td></tr>` : '';
|
||
el.innerHTML = head + lastCommitRow(newest) + `<table class="ftable"><tbody>${up}${entries.map((e) => `
|
||
<tr>
|
||
<td><a class="fname${e.dir ? ' dir' : ''}" data-path="${esc(e.path)}">${icon(e.dir ? 'folder' : 'file', 16)}<span>${esc(e.name)}</span></a></td>
|
||
<td class="cmsg">${esc(e.commit.msg)}</td>
|
||
<td class="ctime">${timeAgo(e.commit.time)}</td>
|
||
</tr>`).join('')}</tbody></table>`;
|
||
} else {
|
||
el.innerHTML = head + lastCommitRow(file.commit) + `<div id="file-body"><div class="empty">读取中…</div></div>`;
|
||
$('file-body').innerHTML = await fileView(file);
|
||
}
|
||
syncUrl();
|
||
}
|
||
|
||
async function fileView(file) {
|
||
if (file.binary) {
|
||
return `<div class="binary">${icon('cube', 28)}<b>二进制文件 · ${esc(file.binary)}</b><span class="muted">CAD / 网格文件无法以文本预览,可以在上方 3D 视图中查看模型。</span></div>`;
|
||
}
|
||
let text = file.content;
|
||
if (file.src) {
|
||
if (!sourceCache.has(file.src)) {
|
||
sourceCache.set(file.src, fetch(file.src).then((r) => (r.ok ? r.text() : Promise.reject(new Error(r.status)))).catch(() => '无法读取文件'));
|
||
}
|
||
text = await sourceCache.get(file.src);
|
||
}
|
||
const lines = text.replace(/\n$/, '').split('\n');
|
||
const size = new Blob([text]).size;
|
||
const meta = `<div class="last-commit" style="background:none"><span class="mono">${lines.length} 行 · ${size > 1024 ? (size / 1024).toFixed(1) + ' KB' : size + ' B'}</span><span class="msg"></span><button class="btn btn-sm" data-copy>复制</button></div>`;
|
||
if (file.path.endsWith('.md')) return meta + `<div class="md">${md(text)}</div>`;
|
||
return meta + `<pre class="code">${lines.map((l) => `<span class="ln">${esc(l) || ' '}</span>`).join('')}</pre>`;
|
||
}
|
||
|
||
$('files').addEventListener('click', async (e) => {
|
||
const link = e.target.closest('[data-path]');
|
||
if (link) {
|
||
path = link.dataset.path;
|
||
pathKind = link.dataset.kind || 'dir';
|
||
await (project.api ? renderRemoteFiles : renderFiles)();
|
||
return;
|
||
}
|
||
if (e.target.closest('#download')) toast('演示环境:发布后这里会打包下载整个仓库');
|
||
if (e.target.closest('[data-copy]')) {
|
||
navigator.clipboard?.writeText($('file-body').querySelector('.code, .md')?.innerText || '').then(() => toast('已复制到剪贴板'), () => toast('复制失败'));
|
||
}
|
||
});
|
||
|
||
// ---------- 侧栏 ----------
|
||
function renderAside() {
|
||
const p = project;
|
||
if (p.api) { renderRemoteAside(); return; }
|
||
const langs = Object.entries(p.languages);
|
||
const total = langs.reduce((n, [, v]) => n + v, 0) || 1;
|
||
const shares = (x) => [].concat(x.archetype).some((t) => [].concat(p.archetype).includes(t));
|
||
const related = all.filter((x) => x.id !== p.id).sort((a, b) => (shares(b) - shares(a)) || b.starsTotal - a.starsTotal).slice(0, 3);
|
||
$('aside').innerHTML = `
|
||
<section>
|
||
<h5>关于</h5>
|
||
<p>${esc(p.description)}</p>
|
||
<div class="facts">
|
||
<div><small>收藏</small><b>${fmt(p.starsTotal)}</b></div>
|
||
<div><small>Fork</small><b>${fmt(p.forksTotal)}</b></div>
|
||
<div><small>自由度</small><b id="fact-dof">—</b></div>
|
||
<div><small>订阅</small><b>${fmt(p.watchersTotal)}</b></div>
|
||
</div>
|
||
</section>
|
||
<section>
|
||
<h5>贡献者 · ${p.contributors.length}</h5>
|
||
<div class="people">${p.contributors.map((c) => avatar(c, 36)).join('')}</div>
|
||
</section>
|
||
<section>
|
||
<h5>语言</h5>
|
||
<div class="langbar">${langs.map(([k, v]) => `<i style="flex:${v};background:${LANG_COLORS[k] || '#888'}"></i>`).join('')}</div>
|
||
<div class="langs">${langs.map(([k, v]) => `<span><i style="background:${LANG_COLORS[k] || '#888'}"></i>${esc(k)} ${Math.round((v / total) * 100)}%</span>`).join('')}</div>
|
||
</section>
|
||
<section>
|
||
<h5>相关项目</h5>
|
||
<div class="related">${related.map((r) => `
|
||
<a href="/project/?id=${encodeURIComponent(r.id)}">
|
||
<span class="thumb" data-rel="${esc(r.id)}"></span>
|
||
<span><b style="font-weight:500">${esc(r.name)}</b><small>${esc(r.owner.handle)} · ★ ${fmt(r.starsTotal)}</small></span>
|
||
</a>`).join('')}</div>
|
||
</section>`;
|
||
// 主模型先加载,再排队生成相关项目缩略图
|
||
setTimeout(() => related.forEach((r) => thumbnail(r).then((url) => {
|
||
const el = document.querySelector(`[data-rel="${r.id}"]`);
|
||
if (el) el.innerHTML = `<img src="${url}" alt="">`;
|
||
}).catch(() => {})), 1500);
|
||
}
|
||
|
||
// ---------- 讨论 ----------
|
||
const commentBody = (text) => esc(text).replace(/`([^`]+)`/g, '<code>$1</code>');
|
||
|
||
function comment(c, { reply = false } = {}) {
|
||
const liked = !!project.local.likes[c.id];
|
||
const isOwner = c.author.handle === project.owner.handle;
|
||
return `<div class="thread">
|
||
${avatar(c.author, reply ? 32 : 40)}
|
||
<div>
|
||
<div class="c-head"><b>${esc(c.author.name)}</b><span class="mono">@${esc(c.author.handle)}</span>${isOwner ? '<span class="role">作者</span>' : ''}<span>· ${timeAgo(c.time)}</span></div>
|
||
<div class="c-body">${commentBody(c.body)}</div>
|
||
<div class="c-actions">
|
||
<button class="react${liked ? ' on' : ''}" data-like="${esc(c.id)}">${icon('heart', 14)}${c.likes + (liked ? 1 : 0)}</button>
|
||
${reply ? '' : `<button class="react" data-reply="${esc(c.id)}">${icon('comment', 14)}回复</button>`}
|
||
</div>
|
||
${reply ? '' : `<div class="reply-box" data-box="${esc(c.id)}" hidden><input placeholder="回复 @${esc(c.author.handle)}…" maxlength="500"><button class="btn btn-sm btn-primary" data-send="${esc(c.id)}">发送</button></div>`}
|
||
${!reply && c.replies.length ? `<div class="replies">${c.replies.map((r) => comment(r, { reply: true })).join('')}</div>` : ''}
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
function hydrateLocal(c) { return { likes: 0, replies: [], ...c, author: GUEST }; }
|
||
|
||
function allThreads() {
|
||
const s = project.local;
|
||
const extra = s.replies || {};
|
||
const withReplies = (c) => ({ ...c, replies: [...c.replies, ...(extra[c.id] || []).map(hydrateLocal)] });
|
||
return [...(s.comments || []).map(hydrateLocal).map(withReplies).reverse(), ...project.discussions.map(withReplies)];
|
||
}
|
||
|
||
function renderDiscussions() {
|
||
const threads = allThreads();
|
||
document.querySelector('[data-panel="discussions"]').innerHTML = `<div>
|
||
<div class="composer">
|
||
${avatar(GUEST, 40)}
|
||
<div>
|
||
<textarea id="new-comment" placeholder="分享你的改装、提问或反馈… 支持 \`代码\`,⌘ + Enter 发布" maxlength="2000"></textarea>
|
||
<div class="row"><span>演示环境:评论保存在你的浏览器本地</span><button class="btn btn-sm btn-primary" id="post-comment">发布评论</button></div>
|
||
</div>
|
||
</div>
|
||
${threads.length ? threads.map((c) => comment(c)).join('') : '<div class="empty">还没有讨论,来抢沙发吧</div>'}
|
||
</div>`;
|
||
}
|
||
|
||
const discussions = document.querySelector('[data-panel="discussions"]');
|
||
discussions.addEventListener('click', (e) => {
|
||
const s = project.local;
|
||
const like = e.target.closest('[data-like]');
|
||
if (like) {
|
||
const id = like.dataset.like;
|
||
if (s.likes[id]) delete s.likes[id]; else s.likes[id] = true;
|
||
persist();
|
||
renderDiscussions();
|
||
return;
|
||
}
|
||
const reply = e.target.closest('[data-reply]');
|
||
if (reply) {
|
||
const box = discussions.querySelector(`[data-box="${CSS.escape(reply.dataset.reply)}"]`);
|
||
box.hidden = !box.hidden;
|
||
if (!box.hidden) box.querySelector('input').focus();
|
||
return;
|
||
}
|
||
const send = e.target.closest('[data-send]');
|
||
if (send) {
|
||
const body = send.parentElement.querySelector('input').value.trim();
|
||
if (!body) return;
|
||
s.replies ??= {};
|
||
(s.replies[send.dataset.send] ??= []).push({ id: `local-r-${Date.now()}`, time: new Date().toISOString(), body });
|
||
persist();
|
||
renderDiscussions();
|
||
renderTabs();
|
||
return;
|
||
}
|
||
if (e.target.closest('#post-comment')) {
|
||
const ta = $('new-comment');
|
||
const body = ta.value.trim();
|
||
if (!body) { ta.focus(); return; }
|
||
s.comments.push({ id: `local-${Date.now()}`, time: new Date().toISOString(), body });
|
||
persist();
|
||
renderDiscussions();
|
||
renderTabs();
|
||
toast('评论已发布');
|
||
}
|
||
});
|
||
discussions.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Enter' && e.target.matches('.reply-box input')) e.target.parentElement.querySelector('[data-send]').click();
|
||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && e.target.id === 'new-comment') $('post-comment').click();
|
||
});
|
||
|
||
// ---------- Fork ----------
|
||
function renderForks() {
|
||
const p = project;
|
||
const forks = [...p.forkList];
|
||
if (p.local.forked) forks.unshift({ owner: GUEST, name: p.slug, stars: 0, note: '你的 Fork(演示)', time: new Date().toISOString() });
|
||
document.querySelector('[data-panel="forks"]').innerHTML = `<div class="card">
|
||
<div class="card-head"><span>${icon('fork', 15)} <b style="font-weight:500">${forks.length}</b> 个 Fork</span><span class="muted" style="font-size:13px">源自 ${esc(p.owner.handle)}/${esc(p.slug)}</span></div>
|
||
<div class="rows">${forks.length ? forks.map((f) => `
|
||
<div>${avatar(f.owner, 36)}
|
||
<span><b>${esc(f.owner.handle)}/${esc(f.name)}</b><span class="sub">${esc(f.note)}</span></span>
|
||
<span class="meta"><span>${icon('star', 13)}${fmt(f.stars)}</span><span>${timeAgo(f.time)}</span></span>
|
||
</div>`).join('') : '<div class="empty" style="display:block">还没有人 Fork,点右上角 Fork 成为第一个</div>'}</div>
|
||
</div>`;
|
||
}
|
||
|
||
// ---------- 动态 ----------
|
||
function renderActivity() {
|
||
const byDay = new Map();
|
||
for (const c of [...project.commits].sort((a, b) => new Date(b.time) - new Date(a.time))) {
|
||
const day = new Date(c.time).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
|
||
if (!byDay.has(day)) byDay.set(day, []);
|
||
byDay.get(day).push(c);
|
||
}
|
||
document.querySelector('[data-panel="activity"]').innerHTML = `<div class="timeline">${[...byDay].map(([day, commits]) => `
|
||
<div class="day">${esc(day)}</div>
|
||
<div class="card rows">${commits.map((c) => `
|
||
<div>${avatar(c.author, 32)}<span><b>${esc(c.msg)}</b><span class="sub">${esc(c.author.name)} 提交于 ${timeAgo(c.time)}</span></span>
|
||
<span class="meta"><span class="mono">${c.hash}</span></span></div>`).join('')}</div>`).join('')}</div>`;
|
||
}
|
||
|
||
// ---------- 启动 ----------
|
||
async function init() {
|
||
if ((await dataMode()) === 'api') { initRemote(); return; }
|
||
let data;
|
||
try {
|
||
data = await fetchCommunity();
|
||
} catch (err) {
|
||
document.querySelector('.p-body').innerHTML = `<div class="empty">${location.protocol === 'file:' ? '请通过本地服务器打开(python3 -m http.server)' : esc(err.message)}</div>`;
|
||
return;
|
||
}
|
||
all = data.projects;
|
||
const id = routeId;
|
||
project = all.find((p) => p.id === id || p.slug === id) || all[0];
|
||
if (id && project.id !== id && project.slug !== id) toast('没有找到这个项目,已为你打开推荐项目');
|
||
project.local.likes ??= {};
|
||
project.local.comments ??= [];
|
||
|
||
renderHead();
|
||
renderAside();
|
||
renderReadme();
|
||
$('stage').closest('section').hidden = false;
|
||
setupViewer();
|
||
setTab(tab);
|
||
}
|
||
|
||
// =================== 后端模式 ===================
|
||
const IMG = /\.(png|jpe?g|gif|webp)$/i;
|
||
const sizeText = (n) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MB` : n >= 1024 ? `${(n / 1024).toFixed(1)} KB` : `${n} B`);
|
||
|
||
async function initRemote() {
|
||
const code = routeId;
|
||
// 3D 区域先收起,确认项目里有模型再展开(不会出现了又收起,页面不跳)
|
||
const stageSection = $('stage').closest('section');
|
||
stageSection.hidden = true;
|
||
if (code) prefetchRoot(code).catch(() => {}); // 根目录列表和项目信息同时请求
|
||
try {
|
||
if (!code) throw new api.ApiError(404, 'NOT_FOUND', '缺少项目编号');
|
||
project = await getProject(code);
|
||
} catch (err) {
|
||
splashDone();
|
||
$('loader').classList.add('error');
|
||
$('loader-text').textContent = '';
|
||
$('p-hero').innerHTML = '';
|
||
$('stage').closest('section').hidden = true;
|
||
document.querySelector('.p-tabs').hidden = true;
|
||
document.querySelector('.p-body').innerHTML = `<div class="empty">${err.status === 404 ? '项目不存在或已撤回' : esc(api.errorText(err))}<br><br><a class="btn btn-sm" href="/explore/">回到社区</a></div>`;
|
||
return;
|
||
}
|
||
if (!['overview', 'files', 'discussions'].includes(tab)) tab = 'overview';
|
||
// 标题、统计、侧栏马上显示;README 和 3D 模型各自到了再补上
|
||
renderHead();
|
||
renderAside();
|
||
setTab(tab);
|
||
getReadme(project).catch(() => null).then((readme) => { project.readme = readme; renderReadme(); });
|
||
const robot = await ensureRobot(project).catch((err) => { console.error(err); return null; });
|
||
project.robot = robot;
|
||
if (robot) { stageSection.hidden = false; setupViewer(); } else splashDone();
|
||
}
|
||
|
||
// 收藏(点赞)与 Fork
|
||
async function remoteCounter(act, btn) {
|
||
if (!(await requireLogin())) return;
|
||
const p = project;
|
||
if (act === 'star') {
|
||
const on = !p.liked;
|
||
p.liked = on; // 先乐观更新,失败再恢复
|
||
p.starsTotal += on ? 1 : -1;
|
||
renderCounters();
|
||
try {
|
||
await (on ? api.likeProject : api.unlikeProject)(p.code);
|
||
toast(on ? '已加入收藏' : '已取消收藏');
|
||
} catch (err) {
|
||
toast(api.errorText(err));
|
||
}
|
||
refreshRemote();
|
||
return;
|
||
}
|
||
if (act === 'fork') openFork(btn);
|
||
}
|
||
|
||
async function refreshRemote() {
|
||
try {
|
||
const fresh = await getProject(project.code);
|
||
Object.assign(project, { liked: fresh.liked, starsTotal: fresh.starsTotal, commentCount: fresh.commentCount, forksTotal: fresh.forksTotal, publishedCommitSha: fresh.publishedCommitSha });
|
||
renderCounters();
|
||
renderTabs();
|
||
// 右侧栏的统计数字也跟着更新(不整块重绘,避免重新请求同类项目)
|
||
if ($('fact-stars')) $('fact-stars').textContent = fmt(project.starsTotal);
|
||
if ($('fact-comments')) $('fact-comments').textContent = fmt(project.commentCount);
|
||
} catch { /* 忽略 */ }
|
||
}
|
||
|
||
function openFork() {
|
||
const m = openModal({
|
||
title: 'Fork 到我的工作区',
|
||
body: `<form class="form">
|
||
<label class="fld"><span>新项目名称</span><input name="name" required maxlength="100" value="${esc(project.name.slice(0, 100))}"></label>
|
||
<p class="form-note">复制当前发布版本的全部文件,不包含提交历史,之后也不会自动同步原项目。</p>
|
||
<p class="form-msg" data-msg></p>
|
||
<div class="form-foot"><span></span><button class="btn btn-primary" type="submit">${icon('fork', 14)}确认 Fork</button></div>
|
||
</form>`,
|
||
});
|
||
const form = m.el.querySelector('form');
|
||
const msg = m.el.querySelector('[data-msg]');
|
||
form.addEventListener('submit', async (e) => {
|
||
e.preventDefault();
|
||
const btn = form.querySelector('[type=submit]');
|
||
btn.disabled = true;
|
||
btn.textContent = '正在复制…';
|
||
m.el.dataset.busy = '1';
|
||
msg.textContent = '';
|
||
try {
|
||
const forked = await api.forkProject(project.code, form.name.value.trim(), project.publishedCommitSha);
|
||
delete m.el.dataset.busy;
|
||
m.close();
|
||
toast(`已 Fork 到你的工作区:${forked.name}`);
|
||
location.href = `/workspace/?code=${encodeURIComponent(forked.projectCode)}`; // 跟 GitHub 一样,Fork 完进入自己的副本
|
||
} catch (err) {
|
||
delete m.el.dataset.busy;
|
||
btn.disabled = false;
|
||
btn.textContent = '确认 Fork';
|
||
// 409:作者刚发布了新版本;超时或网络中断不保证没成功,不自动重试
|
||
msg.textContent = err.status === 409 ? '作者刚刚更新了发布版本,已刷新,请确认后再 Fork' : api.errorText(err) + (err instanceof api.ApiError ? '' : '。请先查看工作区确认是否已经 Fork 成功');
|
||
if (err.status === 409) refreshRemote();
|
||
}
|
||
});
|
||
setTimeout(() => form.name.select(), 50);
|
||
}
|
||
|
||
// ---------- 文件:按目录读取 ----------
|
||
function remoteCrumbs() {
|
||
const parts = path ? path.split('/') : [];
|
||
const links = [`<a data-path="" data-kind="dir">${esc(project.slug)}</a>`];
|
||
parts.forEach((seg, i) => {
|
||
const sub = parts.slice(0, i + 1).join('/');
|
||
links.push('<span class="sep">/</span>', i === parts.length - 1 ? `<b>${esc(seg)}</b>` : `<a data-path="${esc(sub)}" data-kind="dir">${esc(seg)}</a>`);
|
||
});
|
||
return `<div class="path">${links.join('')}</div>`;
|
||
}
|
||
|
||
let filesToken = 0;
|
||
async function renderRemoteFiles() {
|
||
const token = ++filesToken;
|
||
const el = $('files');
|
||
const head = (extra = '') => `<div class="card-head">
|
||
<span style="display:flex;align-items:center;gap:12px;flex-wrap:wrap"><span class="branch">${icon('branch', 14)}发布版本 <span class="mono">${esc((project.publishedCommitSha || '').slice(0, 7))}</span></span>${remoteCrumbs()}</span>
|
||
<span style="display:flex;gap:8px;align-items:center">${extra}</span></div>`;
|
||
el.innerHTML = head() + '<div class="empty">读取中…</div>';
|
||
try {
|
||
if (pathKind !== 'file') {
|
||
try {
|
||
const tree = await api.getCommunityTree(project.code, path);
|
||
if (token !== filesToken) return;
|
||
pathKind = 'dir';
|
||
const up = path ? `<tr><td colspan="2"><a class="fname dir" data-path="${esc(path.split('/').slice(0, -1).join('/'))}" data-kind="dir">${icon('folder', 16)}<span>..</span></a></td></tr>` : '';
|
||
el.innerHTML = head() + `<table class="ftable"><tbody>${up}${tree.entries.map((e) => {
|
||
const dir = e.type === 'dir';
|
||
return `<tr>
|
||
<td><a class="fname${dir ? ' dir' : ''}" data-path="${esc(e.path)}" data-kind="${dir ? 'dir' : 'file'}">${icon(dir ? 'folder' : 'file', 16)}<span>${esc(e.name)}</span></a></td>
|
||
<td class="ctime">${dir ? '' : sizeText(e.size)}</td>
|
||
</tr>`;
|
||
}).join('') || '<tr><td class="muted">空目录</td></tr>'}</tbody></table>`;
|
||
syncUrl();
|
||
return;
|
||
} catch (err) {
|
||
if (!(err instanceof api.ApiError) || !path || err.status >= 500) throw err;
|
||
pathKind = 'file'; // 地址栏带的 path 是文件
|
||
}
|
||
}
|
||
const file = await api.getCommunityFile(project.code, path);
|
||
if (token !== filesToken) return;
|
||
const raw = api.communityRawUrl(project.code, path);
|
||
cleanupFileImages?.();
|
||
el.innerHTML = head(`<a class="btn btn-sm" href="${esc(raw)}" download>下载</a>`) + `<div id="file-body">${prepareDocumentImages(remoteFileView(file, raw), documentOptions(file.path))}</div>`;
|
||
cleanupFileImages = hydrateDocumentImages(el);
|
||
} catch (err) {
|
||
if (token !== filesToken) return;
|
||
el.innerHTML = head() + `<div class="empty">${err.status === 404 ? '文件不存在' : esc(api.errorText(err))}</div>`;
|
||
}
|
||
syncUrl();
|
||
}
|
||
|
||
function remoteFileView(file, raw) {
|
||
const meta = (extra) => `<div class="last-commit" style="background:none"><span class="mono">${extra}${sizeText(file.size)}</span><span class="msg"></span>${file.encoding === 'utf-8' ? '<button class="btn btn-sm" data-copy>复制</button>' : ''}</div>`;
|
||
if (file.encoding !== 'utf-8') {
|
||
if (IMG.test(file.path)) return meta('') + `<div class="binary"><img src="${esc(raw)}" alt="${esc(file.path)}" style="max-width:100%;max-height:520px;border-radius:12px"></div>`;
|
||
return meta('') + `<div class="binary">${icon('cube', 28)}<b>二进制或较大的文件</b><span class="muted">无法以文本预览,可以下载查看;网格文件可以在上方 3D 视图中查看。</span></div>`;
|
||
}
|
||
const text = file.content;
|
||
const lines = text.replace(/\n$/, '').split('\n');
|
||
if (/\.(md|markdown)$/i.test(file.path)) return meta(`${lines.length} 行 · `) + `<div class="md">${md(text)}</div>`;
|
||
return meta(`${lines.length} 行 · `) + `<pre class="code">${lines.map((l) => `<span class="ln">${esc(l) || ' '}</span>`).join('')}</pre>`;
|
||
}
|
||
|
||
// ---------- 侧栏 ----------
|
||
async function renderRemoteAside() {
|
||
const p = project;
|
||
$('aside').innerHTML = `
|
||
<section>
|
||
<h5>关于</h5>
|
||
<p>${esc(p.description || '暂无简介')}</p>
|
||
<div class="facts">
|
||
<div><small>收藏</small><b id="fact-stars">${fmt(p.starsTotal)}</b></div>
|
||
<div><small>讨论</small><b id="fact-comments">${fmt(p.commentCount)}</b></div>
|
||
<div><small>自由度</small><b id="fact-dof">—</b></div>
|
||
<div><small>类型</small><b style="font-size:15px">${esc(p.type)}</b></div>
|
||
</div>
|
||
${p.sourceProjectCode ? `<p class="muted" style="margin-top:14px;font-size:13px">${icon('fork', 13)} Fork 自 <a href="/project/?id=${encodeURIComponent(p.sourceProjectCode)}">原项目</a></p>` : ''}
|
||
</section>
|
||
`;
|
||
}
|
||
|
||
// ---------- 讨论:平铺评论,按时间倒序 ----------
|
||
const remoteComments = { items: [], total: 0, page: 0, loaded: false };
|
||
|
||
async function loadRemoteComments(reset) {
|
||
const page = reset ? 1 : remoteComments.page + 1;
|
||
const res = await api.listComments(project.code, { page, size: 20 });
|
||
remoteComments.items = reset ? res.items : [...remoteComments.items, ...res.items];
|
||
remoteComments.total = res.total;
|
||
remoteComments.page = page;
|
||
remoteComments.loaded = true;
|
||
}
|
||
|
||
async function renderRemoteDiscussions() {
|
||
const panel = document.querySelector('[data-panel="discussions"]');
|
||
if (!remoteComments.loaded) {
|
||
panel.innerHTML = '<div class="empty">读取中…</div>';
|
||
try { await loadRemoteComments(true); } catch (err) { panel.innerHTML = `<div class="empty">${esc(api.errorText(err))}</div>`; return; }
|
||
}
|
||
const me = api.auth.user;
|
||
const meUser = me ? userFrom(me) : GUEST;
|
||
const items = remoteComments.items;
|
||
panel.innerHTML = `<div>
|
||
<div class="composer">
|
||
${avatar(meUser, 40)}
|
||
<div>
|
||
<textarea id="new-comment" placeholder="${me ? '分享你的改装、提问或反馈… 支持 `代码`,⌘ + Enter 发布' : '登录后参与讨论'}" maxlength="2000"></textarea>
|
||
<div class="row"><span data-cmsg>${me ? '纯文本,最多 2000 字' : ''}</span><button class="btn btn-sm btn-primary" id="post-comment">${me ? '发布评论' : '登录后评论'}</button></div>
|
||
</div>
|
||
</div>
|
||
${items.length ? items.map(remoteComment).join('') : '<div class="empty">还没有讨论,来抢沙发吧</div>'}
|
||
${items.length < remoteComments.total ? '<div class="load-more"><button class="btn" id="more-comments">加载更多</button></div>' : ''}
|
||
</div>`;
|
||
}
|
||
|
||
function remoteComment(c) {
|
||
const author = userFrom(c.author);
|
||
const mine = api.auth.user && c.author?.userCode && c.author.userCode === api.auth.user.userCode;
|
||
const isOwner = c.author?.userCode && c.author.userCode === project.owner.code;
|
||
return `<div class="thread">
|
||
${avatar(author, 40)}
|
||
<div>
|
||
<div class="c-head"><b>${esc(author.name)}</b>${isOwner ? '<span class="role">作者</span>' : ''}<span>· ${timeAgo(api.utcIso(c.createdAt))}</span></div>
|
||
<div class="c-body">${commentBody(c.content)}</div>
|
||
${mine ? `<div class="c-actions"><button class="react" data-del="${esc(c.commentCode)}">${icon('close', 14)}删除</button></div>` : ''}
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
document.querySelector('[data-panel="discussions"]').addEventListener('click', async (e) => {
|
||
if (!project?.api) return;
|
||
e.stopImmediatePropagation();
|
||
if (e.target.closest('#more-comments')) {
|
||
e.target.disabled = true;
|
||
try { await loadRemoteComments(false); } catch (err) { toast(api.errorText(err)); }
|
||
renderRemoteDiscussions();
|
||
return;
|
||
}
|
||
const del = e.target.closest('[data-del]');
|
||
if (del) {
|
||
if (!confirm('删除这条评论?')) return;
|
||
try {
|
||
await api.deleteComment(del.dataset.del);
|
||
toast('评论已删除');
|
||
await loadRemoteComments(true);
|
||
refreshRemote();
|
||
} catch (err) { toast(api.errorText(err)); }
|
||
renderRemoteDiscussions();
|
||
return;
|
||
}
|
||
if (e.target.closest('#post-comment')) {
|
||
if (!(await requireLogin())) return;
|
||
const ta = $('new-comment');
|
||
const body = ta.value.trim();
|
||
if (!api.auth.user || !body) { renderRemoteDiscussions(); return; }
|
||
const btn = $('post-comment');
|
||
btn.disabled = true;
|
||
try {
|
||
await api.postComment(project.code, body); // 不自动重试,避免重复评论
|
||
toast('评论已发布');
|
||
await loadRemoteComments(true);
|
||
refreshRemote();
|
||
renderRemoteDiscussions();
|
||
} catch (err) {
|
||
btn.disabled = false;
|
||
document.querySelector('[data-cmsg]').textContent = api.errorText(err);
|
||
}
|
||
}
|
||
}, true);
|
||
|
||
init();
|