Files
vibemake/js/layout.js
T

212 lines
11 KiB
JavaScript

// 全站外壳:顶部导航 + ⌘K 搜索面板 + 页脚 + 通用小工具。
export const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
export const store = {
get(k, fallback) { try { return JSON.parse(localStorage.getItem(k)) ?? fallback; } catch { return fallback; } },
set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch { /* 隐私模式下忽略 */ } },
};
export function fmt(n) {
if (n >= 10000) return (n / 10000).toFixed(1).replace(/\.0$/, '') + '万';
if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
return String(n);
}
export function timeAgo(iso) {
const s = (Date.now() - new Date(iso).getTime()) / 1000;
if (s < 60) return '刚刚';
if (s < 3600) return `${Math.floor(s / 60)} 分钟前`;
if (s < 86400) return `${Math.floor(s / 3600)} 小时前`;
if (s < 86400 * 30) return `${Math.floor(s / 86400)} 天前`;
return new Date(iso).toLocaleDateString('zh-CN');
}
export function avatar(user, size = 24) {
const u = user || { name: '?', color: '#666' };
return `<span class="avatar" style="--c:${esc(u.color)};width:${size}px;height:${size}px;font-size:${Math.round(size * 0.42)}px" title="${esc(u.name)}">${esc((u.name || '?').slice(0, 1).toUpperCase())}</span>`;
}
export const ICON = {
star: '<path d="m12 3 2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/>',
fork: '<circle cx="6" cy="5" r="2"/><circle cx="18" cy="5" r="2"/><circle cx="12" cy="19" r="2"/><path d="M6 7v2a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7M12 12v5"/>',
eye: '<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>',
comment: '<path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.4A8 8 0 1 1 21 12z"/>',
search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
plus: '<path d="M12 5v14M5 12h14"/>',
folder: '<path d="M3 6.5A1.5 1.5 0 0 1 4.5 5H9l2 2h8.5A1.5 1.5 0 0 1 21 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 17.5z"/>',
file: '<path d="M14 3H6.5A1.5 1.5 0 0 0 5 4.5v15A1.5 1.5 0 0 0 6.5 21h11a1.5 1.5 0 0 0 1.5-1.5V8z"/><path d="M14 3v5h5"/>',
cube: '<path d="M12 2 3 7v10l9 5 9-5V7z"/><path d="m3 7 9 5 9-5M12 12v10"/>',
heart: '<path d="M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.6-7 10-7 10z"/>',
branch: '<circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="8" r="2"/><path d="M6 8v8M18 10c0 4-6 3-11 6"/>',
commit: '<circle cx="12" cy="12" r="3"/><path d="M3 12h6M15 12h6"/>',
play: '<path d="M7 5v14l11-7z"/>',
menu: '<path d="M4 7h16M4 12h16M4 17h16"/>',
close: '<path d="M6 6l12 12M18 6 6 18"/>',
arrow: '<path d="M5 12h14M13 6l6 6-6 6"/>',
left: '<path d="M15 6l-6 6 6 6"/>',
right: '<path d="M9 6l6 6-6 6"/>',
book: '<path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z"/><path d="M4 21V5"/>',
pulse: '<path d="M3 12h4l3-7 4 14 3-7h4"/>',
code: '<path d="m8 8-5 4 5 4M16 8l5 4-5 4M14 4l-4 16"/>',
sparkle: '<path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M6 18l2.5-2.5M15.5 8.5 18 6"/>',
upload: '<path d="M12 16V4M6 10l6-6 6 6M4 20h16"/>',
edit: '<path d="M4 20h4L19 9l-4-4L4 16z"/><path d="m13.5 6.5 4 4"/>',
trash: '<path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/>',
download: '<path d="M12 4v12M6 10l6 6 6-6M4 20h16"/>',
history: '<path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5M12 7v5l3 2"/>',
gear: '<circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M4.9 19.1 7 17M17 7l2.1-2.1"/>',
lock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',
globe: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/>',
chevron: '<path d="m6 9 6 6 6-6"/>',
check: '<path d="m5 12 5 5 9-10"/>',
};
export function icon(name, size = 16, extra = '') {
return `<svg class="ic" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" ${extra}>${ICON[name] || ''}</svg>`;
}
const NAV = [
{ id: 'home', label: '首页', href: '/' },
{ id: 'explore', label: '社区', href: '/explore/' },
{ id: 'studio', label: '工作台', href: '/studio/' },
{ id: 'cad', label: 'CAD', href: '/cad/' },
{ id: 'pcb', label: 'PCB', href: '/pcb/' },
{ id: 'workspace', label: '我的', href: '/workspace/' },
];
const navLink = (item, active) => `<a href="${item.href}"${item.newTab ? ' target="_blank" rel="noopener noreferrer"' : ''} class="${item.id === active ? 'active' : ''}">${item.label}</a>`;
function scrollbarWidth() {
const probe = document.createElement('div');
probe.style.cssText = 'position:absolute;top:-9999px;width:100px;height:100px;overflow:scroll';
document.body.appendChild(probe);
const w = probe.offsetWidth - probe.clientWidth;
probe.remove();
return w;
}
export function renderShell(active, { overlay = false, footer = true, assistant = true } = {}) {
// 导航栏由 js/shell.js 在页面一开始就画好;这里只补上交互。没有的话(旧页面)再自己生成
const existing = document.querySelector('body > header.nav');
if (existing) return bindShell(existing, overlay, footer, assistant);
const nav = document.createElement('header');
nav.className = `nav${overlay ? ' overlay' : ''}`;
// 工作台(studio)页面不滚动、没有滚动条,其他页面有。给导航补上滚动条宽度,切换页面时 logo 和按钮不会左右跳
if (overlay) nav.style.paddingRight = `${scrollbarWidth()}px`;
nav.innerHTML = `
<div class="nav-inner">
<a class="nav-logo" href="/" aria-label="vibemake 首页"><img src="assets/logo.png" alt="vibemake"></a>
<nav class="nav-links">${NAV.map((n) => navLink(n, active)).join('')}</nav>
<div class="nav-actions">
<button class="nav-search" data-palette>${icon('search', 15)}<span>搜索</span><kbd>⌘K</kbd></button>
<button class="btn btn-sm btn-ghost hide-sm" data-publish>${icon('upload', 14)}发布项目</button>
<span class="hide-sm" data-auth></span>
<button class="icon-btn nav-menu" aria-label="菜单">${icon('menu', 20)}</button>
</div>
</div>
<div class="sheet">
${NAV.map((n) => navLink(n, active)).join('')}
<div class="sheet-actions"><button class="btn" data-publish>发布项目</button><span data-auth></span></div>
</div>`;
document.body.prepend(nav);
bindShell(nav, overlay, footer, assistant);
}
function bindShell(nav, overlay, footer, assistant) {
if (overlay && !nav.style.paddingRight) nav.style.paddingRight = `${scrollbarWidth()}px`;
if (!overlay) {
const onScroll = () => nav.classList.toggle('scrolled', scrollY > 8);
addEventListener('scroll', onScroll, { passive: true });
onScroll();
}
nav.querySelector('.nav-menu').addEventListener('click', () => nav.classList.toggle('open'));
import('./auth.js').then((m) => m.mountNavAuth(nav));
if (assistant) import('./assistant.js').then((m) => m.mountAssistant());
nav.querySelector('[data-palette]').addEventListener('click', openPalette);
addEventListener('keydown', (e) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); openPalette(); }
if (e.key === 'Escape') closePalette();
});
if (footer) {
const f = renderFooter();
f.querySelector('[data-publish]').addEventListener('click', () => import('./auth.js').then((m) => m.openPublish()));
document.body.append(f);
}
}
function renderFooter() {
const f = document.createElement('footer');
f.className = 'site-footer';
f.innerHTML = `
<div class="container footer-grid">
<div class="footer-brand">
<img src="assets/logo.png" alt="vibemake">
<p>开源机器人社区。<br>把你的机器人带到浏览器里,让更多人一起造。</p>
</div>
<nav class="footer-links"><a href="/explore/">社区</a><a href="/studio/">工作台</a><a href="/cad/">CAD</a><a href="/pcb/">PCB</a><a href="/workspace/">我的</a><a data-publish>发布项目</a></nav>
</div>
<div class="container footer-bottom"><span>© 2026 vibemake</span><span>Build robots with good vibes.</span></div>`;
return f;
}
// ---------- ⌘K 搜索面板 ----------
let palette;
async function openPalette() {
if (!palette) {
palette = document.createElement('div');
palette.className = 'palette';
palette.innerHTML = `<div class="palette-box" role="dialog" aria-label="搜索">
<label class="palette-input">${icon('search', 18)}<input placeholder="搜索项目、创客、话题…" autocomplete="off"><kbd>ESC</kbd></label>
<div class="palette-list"></div></div>`;
document.body.append(palette);
palette.addEventListener('click', (e) => { if (e.target === palette) closePalette(); });
const input = palette.querySelector('input');
const { dataMode, listProjects } = await import('./source.js');
const api = (await dataMode()) === 'api';
let projects = [];
let ctrl;
if (!api) projects = (await (await import('./community.js')).fetchCommunity()).projects;
const render = async () => {
const q = input.value.trim().toLowerCase();
let hits;
if (api) {
ctrl?.abort();
ctrl = new AbortController();
try { hits = (await listProjects({ size: 7, keyword: q }, ctrl.signal)).items; } catch { return; }
} else {
hits = projects.filter((p) => !q || [p.name, p.description, p.owner.name, p.owner.handle, p.type, ...p.topics].join(' ').toLowerCase().includes(q)).slice(0, 7);
}
palette.querySelector('.palette-list').innerHTML = hits.length ? hits.map((p) => `
<a href="/project/?id=${encodeURIComponent(p.id)}">${avatar(p.owner, 28)}
<span><b>${esc(p.name)}</b><small>${esc(p.owner.handle || p.owner.name)} · ${esc(p.type)}</small></span>
<em>${icon('star', 13)}${fmt(p.starsTotal)}</em></a>`).join('')
: `<div class="palette-empty">没有找到「${esc(input.value)}」,<a href="/explore/?q=${encodeURIComponent(input.value)}">去社区搜索</a></div>`;
};
let debounce;
input.addEventListener('input', () => { clearTimeout(debounce); debounce = setTimeout(render, api ? 250 : 0); });
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { const a = palette.querySelector('.palette-list a'); if (a) location.href = a.href; }
});
render();
}
palette.classList.add('open');
palette.querySelector('input').focus();
}
function closePalette() { palette?.classList.remove('open'); }
let toastTimer;
export function toast(message) {
let el = document.getElementById('toast');
if (!el) {
el = Object.assign(document.createElement('div'), { id: 'toast', className: 'toast' });
document.body.append(el);
}
el.textContent = message;
el.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.classList.remove('show'), 2600);
}