1c837766cd
Add backend-driven assembly and simulation experiences, MAKE branding, mobile rendering budgets and desktop-only CAD/PCB routes. Improve logo loading progress, document image recovery and URDF request handling; include dev packaging and regression coverage.
247 lines
12 KiB
JavaScript
247 lines
12 KiB
JavaScript
// 社区数据层:把 robots.json(机器人配置)和 community.json(项目 / 用户 / 讨论)合并成「项目」。
|
|
// 接后端时替换 COMMUNITY_ENDPOINT,或直接让接口返回合并后的结构。
|
|
import { fetchRobots, archetypeLabel } from './registry.js';
|
|
import { store, esc, fmt, avatar, icon, timeAgo } from './layout.js';
|
|
import { ensureRobot } from './source.js';
|
|
import { imageUrl } from './api.js';
|
|
|
|
export const COMMUNITY_ENDPOINT = 'data/community.json';
|
|
|
|
let cache;
|
|
export function fetchCommunity() {
|
|
cache ??= (async () => {
|
|
const [robots, res] = await Promise.all([fetchRobots(), fetch(COMMUNITY_ENDPOINT, { cache: 'no-cache' })]);
|
|
if (!res.ok) throw new Error(`读取社区数据失败:${res.status}`);
|
|
const data = await res.json();
|
|
const users = data.users || {};
|
|
const user = (handle) => ({ handle, name: handle, color: '#5b616b', ...users[handle] });
|
|
|
|
const projects = robots.map((robot) => {
|
|
const c = data.projects?.[robot.id] || {};
|
|
const p = {
|
|
robot,
|
|
id: robot.id,
|
|
slug: c.slug || robot.id,
|
|
name: robot.name,
|
|
description: robot.description,
|
|
type: archetypeLabel(robot),
|
|
archetype: robot.archetype,
|
|
owner: user(c.owner || robot.maker),
|
|
stars: c.stars ?? 0,
|
|
forks: c.forks ?? 0,
|
|
watchers: c.watchers ?? 0,
|
|
license: c.license || '未声明',
|
|
updated: c.updated || new Date().toISOString(),
|
|
topics: c.topics || robot.tags || [],
|
|
languages: c.languages || { URDF: 100 },
|
|
contributors: (c.contributors || [c.owner || robot.maker]).map(user),
|
|
featured: !!c.featured,
|
|
// featured 可以写数字,决定首页轮播顺序(越小越靠前)
|
|
featuredOrder: typeof c.featured === 'number' ? c.featured : 99,
|
|
readme: c.readme || `# ${robot.name}\n\n${robot.description || ''}`,
|
|
commits: (c.commits || []).map(([msg, author, time]) => ({ msg, author: user(author), time, hash: hash(msg + time) })),
|
|
discussions: (c.discussions || []).map((d, i) => normalizeComment(d, user, `${robot.id}-${i}`)),
|
|
forkList: (c.forkList || []).map(([owner, name, stars, note, time]) => ({ owner: user(owner), name, stars, note, time })),
|
|
};
|
|
if (!p.commits.length) p.commits.push({ msg: '初始化项目', author: p.owner, time: p.updated, hash: hash(p.id) });
|
|
p.files = buildTree(p);
|
|
return p;
|
|
});
|
|
projects.forEach(applyLocalState);
|
|
|
|
const activity = (data.activity || []).map((a) => ({ ...a, user: user(a.user), project: projects.find((p) => p.id === a.project) })).filter((a) => a.project);
|
|
return { projects, users: Object.keys(users).map(user), activity, user };
|
|
})();
|
|
return cache;
|
|
}
|
|
|
|
function normalizeComment(d, user, id) {
|
|
return { id, author: user(d.author), time: d.time, body: d.body, likes: d.likes || 0, replies: (d.replies || []).map((r, i) => normalizeComment(r, user, `${id}-${i}`)) };
|
|
}
|
|
|
|
function hash(s) {
|
|
let h = 2166136261;
|
|
for (const ch of s) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);
|
|
return (h >>> 0).toString(16).padStart(8, '0').slice(0, 7);
|
|
}
|
|
|
|
// ---------- 本地交互状态(演示用:Star / Fork / 点赞 / 评论存在浏览器里) ----------
|
|
export function localState(id) { return store.get(`vm.project.${id}`, { starred: false, forked: false, watching: false, likes: {}, comments: [] }); }
|
|
export function saveLocalState(id, s) { store.set(`vm.project.${id}`, s); }
|
|
|
|
function applyLocalState(p) {
|
|
const s = localState(p.id);
|
|
p.local = s;
|
|
p.starsTotal = p.stars + (s.starred ? 1 : 0);
|
|
p.forksTotal = p.forks + (s.forked ? 1 : 0);
|
|
p.watchersTotal = p.watchers + (s.watching ? 1 : 0);
|
|
p.commentCount = p.discussions.reduce((n, d) => n + 1 + d.replies.length, 0) + s.comments.length + Object.values(s.replies || {}).flat().length;
|
|
}
|
|
export function refreshLocal(p) { applyLocalState(p); }
|
|
|
|
// ---------- 文件树(项目里没提供完整仓库时,按约定生成一份) ----------
|
|
function buildTree(p) {
|
|
const urdfName = p.robot.urdf.split('/').pop();
|
|
const commit = (i) => p.commits[i % p.commits.length];
|
|
const files = [
|
|
{ path: 'README.md', content: p.readme, commit: commit(0) },
|
|
{ path: 'LICENSE', content: `${p.license} License\n\nCopyright (c) 2026 ${p.owner.name}\n\n本项目为 make 演示数据。`, commit: commit(p.commits.length - 1) },
|
|
{ path: 'robot.json', content: JSON.stringify(p.robot, null, 2), commit: commit(0), lang: 'json' },
|
|
{ path: `urdf/${urdfName}`, src: p.robot.urdf, commit: commit(1), lang: 'xml' },
|
|
{ path: 'urdf/meshes/README.md', content: '演示机器人使用 URDF 基础几何体(box / cylinder / sphere),没有外部网格文件。\n真实项目把 STL / GLB 放在这里,URDF 中用相对路径 `meshes/xxx.stl` 引用。', commit: commit(1) },
|
|
{ path: 'firmware/main.py', content: firmwareSample(p), commit: commit(0), lang: 'python' },
|
|
{ path: 'firmware/requirements.txt', content: 'pyserial>=3.5\nwebsockets>=12.0\nnumpy>=1.26\n', commit: commit(2) },
|
|
{ path: 'docs/assembly.md', content: `# 组装说明\n\n1. 舵机全部回中(90° / 2048)。\n2. 按 URDF 关节顺序安装:${Object.values(p.robot.jointMap || {}).slice(0, 6).join('、') || '—'}。\n3. 上电前检查线序。`, commit: commit(2) },
|
|
{ path: 'docs/bom.csv', content: 'part,qty,note\nservo,—,见 README\nmcu,1,\nbattery,1,\n', commit: commit(2), lang: 'csv' },
|
|
{ path: 'cad/frame.step', binary: '2.4 MB', commit: commit(3) },
|
|
{ path: 'cad/cover.stl', binary: '812 KB', commit: commit(3) },
|
|
{ path: 'motions/demo.json', content: JSON.stringify({ robot: p.id, fps: 30, frames: [] }, null, 2), commit: commit(1), lang: 'json' },
|
|
];
|
|
return files;
|
|
}
|
|
|
|
function firmwareSample(p) {
|
|
return `"""${p.name} 固件入口:接收 make 工作台下发的关节角并驱动舵机。"""
|
|
import json
|
|
import serial
|
|
|
|
PORT = "/dev/ttyUSB0"
|
|
BAUD = 1_000_000
|
|
|
|
|
|
def apply(q: dict[str, float]) -> None:
|
|
for joint, rad in q.items():
|
|
# TODO: 关节名 -> 舵机 ID,弧度 -> 舵机刻度
|
|
pass
|
|
|
|
|
|
def main() -> None:
|
|
with serial.Serial(PORT, BAUD, timeout=0.1) as port:
|
|
for line in port:
|
|
msg = json.loads(line)
|
|
if msg.get("type") == "joints":
|
|
apply(msg["q"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
`;
|
|
}
|
|
|
|
// 列出某个目录下的直接子项(目录在前)
|
|
export function listDir(files, dir) {
|
|
const prefix = dir ? dir + '/' : '';
|
|
const entries = new Map();
|
|
for (const f of files) {
|
|
if (!f.path.startsWith(prefix)) continue;
|
|
const rest = f.path.slice(prefix.length);
|
|
const [head, ...tail] = rest.split('/');
|
|
const isDir = tail.length > 0;
|
|
const key = (isDir ? 'd:' : 'f:') + head;
|
|
const prev = entries.get(key);
|
|
if (!prev || new Date(f.commit.time) > new Date(prev.commit.time)) {
|
|
entries.set(key, { name: head, path: prefix + head, dir: isDir, commit: f.commit, file: isDir ? null : f });
|
|
}
|
|
}
|
|
return [...entries.values()].sort((a, b) => (a.dir === b.dir ? a.name.localeCompare(b.name) : a.dir ? -1 : 1));
|
|
}
|
|
|
|
// ---------- 缩略图:离屏渲染,排队执行,session 内缓存 ----------
|
|
let queue = Promise.resolve();
|
|
const inflight = new Map();
|
|
export function thumbnail(p) {
|
|
if (p.coverUrl) return Promise.resolve(imageUrl(p.coverUrl));
|
|
const memo = `${p.id}@${p.publishedCommitSha || ''}`;
|
|
if (inflight.has(memo)) return inflight.get(memo);
|
|
// 后端项目按发布版本缓存:重新发布后缩略图跟着更新
|
|
const key = `vm.thumb.v7.${p.id}${p.api ? `@${p.publishedCommitSha}` : ''}`;
|
|
try { const hit = sessionStorage.getItem(key); if (hit) return Promise.resolve(hit); } catch { /* 忽略 */ }
|
|
if (p.robot?.thumbnail) return Promise.resolve(p.robot.thumbnail);
|
|
const job = queue.then(async () => {
|
|
const robot = p.api ? await ensureRobot(p) : p.robot;
|
|
if (!robot) throw new Error('没有 robot.json');
|
|
const { renderThumbnail } = await import('./viewer.js'); // 只有真要渲染 3D 缩略图时才加载 3D 引擎
|
|
return renderThumbnail(robot);
|
|
}).then((url) => {
|
|
try { sessionStorage.setItem(key, url); } catch { /* 超出配额时忽略 */ }
|
|
return url;
|
|
});
|
|
queue = job.catch(() => {});
|
|
inflight.set(memo, job);
|
|
return job;
|
|
}
|
|
|
|
// 卡片滚到屏幕附近再开始下载封面(列表很长时不会一次把所有图片都下载)
|
|
const nearQueue = new WeakMap();
|
|
const nearObserver = typeof IntersectionObserver === 'function' ? new IntersectionObserver((entries) => {
|
|
for (const e of entries) {
|
|
if (!e.isIntersecting) continue;
|
|
nearObserver.unobserve(e.target);
|
|
(nearQueue.get(e.target) || []).forEach((fn) => fn());
|
|
nearQueue.delete(e.target);
|
|
}
|
|
}, { rootMargin: '300px 0px' }) : null;
|
|
function whenNear(el, fn) {
|
|
if (!nearObserver) { fn(); return; }
|
|
nearQueue.set(el, [...(nearQueue.get(el) || []), fn]);
|
|
nearObserver.observe(el);
|
|
}
|
|
|
|
export function hydrateThumbnails(root, projects) {
|
|
root.querySelectorAll('[data-thumb]').forEach((el) => {
|
|
const p = projects.find((x) => x.id === el.dataset.thumb);
|
|
if (!p) return;
|
|
// 没有封面或缩略图加载失败时清空占位,不用默认图标冒充项目封面。
|
|
const clearPlaceholder = () => {
|
|
el.replaceChildren();
|
|
el.classList.remove('ready');
|
|
el.classList.add('failed');
|
|
};
|
|
thumbnail(p).then((url) => {
|
|
// 等图片下载、解码完成后再显示;慢速加载时继续显示封面 loading。
|
|
const img = Object.assign(new Image(), { alt: p.name, decoding: 'async' });
|
|
const showImage = () => {
|
|
const backdrop = Object.assign(new Image(), { alt: '', className: 'pcard-backdrop', decoding: 'async' });
|
|
backdrop.setAttribute('aria-hidden', 'true');
|
|
backdrop.src = img.src;
|
|
img.className = 'pcard-foreground';
|
|
el.replaceChildren(backdrop, img);
|
|
el.classList.remove('failed');
|
|
requestAnimationFrame(() => el.classList.add('ready'));
|
|
};
|
|
img.onload = () => {
|
|
if (typeof img.decode !== 'function') { showImage(); return; }
|
|
img.decode().then(showImage, () => img.naturalWidth ? showImage() : clearPlaceholder());
|
|
};
|
|
img.onerror = clearPlaceholder;
|
|
whenNear(el, () => { img.src = url; });
|
|
}).catch(clearPlaceholder);
|
|
});
|
|
}
|
|
|
|
// ---------- 骨架卡片:数据回来之前先占好位置,尺寸和真卡片一致,内容到了不会跳 ----------
|
|
export function skeletonCards(n = 6, layout = 'grid') {
|
|
return Array.from({ length: n }, () => `<div class="pcard ${layout} skel" aria-hidden="true">
|
|
<div class="pcard-media"><span class="pcard-loader" aria-hidden="true"></span></div>
|
|
<div class="pcard-body">
|
|
<i class="sk" style="width:28%"></i>
|
|
<i class="sk sk-title" style="width:62%"></i>
|
|
<i class="sk" style="width:92%"></i><i class="sk" style="width:70%"></i>
|
|
</div>
|
|
</div>`).join('');
|
|
}
|
|
|
|
// ---------- 项目卡片(首页与探索页共用) ----------
|
|
export function projectCard(p, { rank, layout = 'grid' } = {}) {
|
|
const href = `/project/?id=${encodeURIComponent(p.id)}`;
|
|
return `<a class="pcard ${layout}" href="${href}" style="--hue:${esc(p.owner.color)}">
|
|
<div class="pcard-media" data-thumb="${esc(p.id)}"><span class="pcard-loader" aria-hidden="true"></span></div>
|
|
${rank ? `<span class="pcard-rank">${String(rank).padStart(2, '0')}</span>` : ''}
|
|
<div class="pcard-body">
|
|
<div class="pcard-row"><span class="pcard-type">${esc(p.type)}</span></div>
|
|
<h3>${esc(p.name)}</h3>
|
|
<div class="pcard-end"><p>${esc(p.description)}</p><span class="pcard-star">${icon('star', 13)}${fmt(p.starsTotal)}</span></div>
|
|
</div>
|
|
</a>`;
|
|
}
|