Files
stack/packages/webui/src/public/brand.js
T
jason.woltje e24e7e93a2 feat(webui): one shell, a system dashboard, organization pages as drill-ins (#1873, lane sp1)
#/dashboard is the system landing route: one row per organization with its bus
state, agent count (organization files), project count and needs-you count,
each only when a read gave it, and active agents. Opening an organization from
the sidebar or a dashboard row is a route inside the same page: no reload, a
Dashboard / <organization> breadcrumb, and later /api reads scoped to it through
the existing fetch wrapper, whose organization is now a variable the router sets
(mosaic-org-switch event). #/orgs/<id>/... stays the address. An organization
whose bus is down says so on the dashboard and on its page, with the reason the
workspace read gives.
2026-11-14 22:35:00 -06:00

212 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Original brand studies. This file contains prototype design data, not an API. */
(function (root) {
const palettes = [
{id:'harbor', name:'Harbor', hue:214, sat:70, accent:34, accentSat:63, theory:'Complementary', note:'Clear blue with a restrained copper counterpoint. The warm accent balances cool navigation and gives selected details a second voice.', use:'Proposed default. Blue without the blue-purple gradient.'},
{id:'carmine', name:'Carmine', hue:350, sat:65, accent:176, accentSat:42, theory:'Near-complementary', note:'A red-led identity with a cool turquoise counterpoint. Rose-tinted neutrals keep the red from covering every surface.', use:'For a red preference. Errors still use an icon and explicit wording.'},
{id:'atlantic', name:'Atlantic', hue:199, sat:72, accent:170, accentSat:52, theory:'Analogous', note:'Ocean blue and teal sit close on the hue wheel. Their shared cool bias makes a quieter combination than an opposing accent.', use:'A cohesive blue-green alternative with low visual rivalry.'},
{id:'terracotta', name:'Terracotta', hue:18, sat:60, accent:198, accentSat:44, theory:'Complementary', note:'Fired-clay orange meets a desaturated steel blue. Warm neutral surfaces connect the palette without needing a beige wash everywhere.', use:'An earthier option for writing and personal work.'},
{id:'aubergine', name:'Aubergine', hue:287, sat:38, accent:47, accentSat:46, theory:'Triadic pair', note:'Muted plum and ochre sit 120 degrees apart on the hue wheel. The third triadic hue, teal, is left out so the interface has two brand accents rather than three.', use:'A deliberate purple option for users who want it, without the AI gradient.'},
{id:'mineral', name:'Mineral', hue:171, sat:47, accent:351, accentSat:42, theory:'Complementary', note:'Deep teal and dusty rose oppose each other while keeping saturation restrained. Blue-green tinted layers carry the identity in dark mode.', use:'Cool surfaces with a small warm punctuation.'},
{id:'cobalt', name:'Cobalt', hue:229, sat:75, accent:49, accentSat:63, theory:'Complementary', note:'A stronger royal blue meets a small amber accent. The high hue separation is controlled by using amber only in secondary details.', use:'The most assertive blue option. No large yellow surfaces.'},
{id:'rosewood', name:'Rosewood', hue:329, sat:47, accent:209, accentSat:39, theory:'Triadic pair', note:'Dusty pink and steel blue occupy two points of a triadic relationship. The third, yellow-green, is omitted to avoid an overly colorful interface.', use:'A softer warm identity that does not become pastel text.'},
{id:'graphite', name:'Graphite', hue:216, sat:9, accent:216, accentSat:12, theory:'Monochromatic', note:'One blue-gray hue uses value and saturation changes instead of a second brand hue. Semantic status colors remain independent.', use:'Minimal chroma for content-heavy work. Hierarchy comes from contrast.'},
{id:'grove', name:'Grove', hue:146, sat:37, accent:356, accentSat:39, theory:'Split-complementary pair', note:'Muted forest green meets dusty rose, 30 degrees to one side of its magenta complement. The second split accent is omitted. Low-saturation surfaces keep green from dominating.', use:'An optional green palette for other preferences, not the proposed default.'},
];
const fonts = [
{id:'dm', name:'DM Sans', family:'"DM Sans", system-ui, sans-serif', note:'Open, rounded forms without becoming playful. My first choice for a product that spans everyday work and professional tools.', detail:'Recommended balance'},
{id:'plex', name:'IBM Plex Sans', family:'"IBM Plex Sans", system-ui, sans-serif', note:'More engineered letterforms and a distinctive rhythm. Strong for dense labels and data; its technical character is more noticeable.', detail:'Precise and structured'},
{id:'manrope', name:'Manrope', family:'Manrope, system-ui, sans-serif', note:'Broad geometric forms give the wordmark more presence. Compare long control labels carefully because the wider forms use more space.', detail:'Geometric and expressive'},
];
const logos = [
{id:'mosaic', name:'Assembly', family:'An assembled M', note:'Four solid pieces form an M with an open center. The gaps suggest independent tools working together without using a puzzle-piece cliché.', tradeoff:'Most direct link to Mosaic. At 16 px, the two-unit gaps become fine seams.', paths:'<path d="M4 4h10v24H4zM18 4l12 12-7 7-5-5zM34 4v14l-5 5-7-7zM38 4h10v24H38z" transform="translate(2 10)"/>', recommended:true},
{id:'weave', name:'Relay', family:'An interlocking ribbon', note:'Two angular links cross to make a compact woven loop. The open counters suggest handoffs between people, agents, and tools.', tradeoff:'Strong standalone symbol, but less obviously an M. Check for resemblance to existing link marks before final adoption.', paths:'<path fill-rule="evenodd" d="M4 18 18 4h12l10 10-8 8-8-8h-2L14 22v2l8 8-8 8L4 30zm48 8L38 40H26L16 30l8-8 8 8h2l8-8v-2l-8-8 8-8 10 10z" transform="translate(0 6)"/>'},
{id:'fold', name:'Aperture', family:'A cut-paper tile', note:'An asymmetric square folds around an open center. A single diagonal cut gives the mark direction without an arrow, robot, or sparkle.', tradeoff:'The most abstract and artistic candidate. Its relationship to Mosaic will rely on repeated use with the wordmark.', paths:'<path fill-rule="evenodd" d="M4 4h30v10H14v28H4zm34 0 14 14v34H18V18h16v10h-6v14h14V22l-4-4z"/>'},
];
const icons = {
home:'<path d="m3 10 9-7 9 7v10H3zM9 20v-7h6v7"/>',
conversation:'<path d="M4 4h16v12H9l-5 4zM8 8h8M8 12h5"/>',
projects:'<path d="M3 6h7l2 3h9v11H3zM3 6V4h7l2 2h7v3"/>',
agents:'<rect x="5" y="7" width="14" height="13" rx="3"/><path d="M12 3v4M9 12h.01M15 12h.01M9 16h6M2 11v5M22 11v5"/>',
people:'<circle cx="9" cy="7" r="3"/><path d="M3 21v-3a6 6 0 0 1 12 0v3M16 4a3 3 0 0 1 0 6M18 14a5 5 0 0 1 3 4v3"/>',
board:'<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18M15 3v18M6 7v4M12 7v7M18 7v2"/>',
extensions:'<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><path d="M14 17.5h7M17.5 14v7"/>',
search:'<circle cx="10" cy="10" r="6"/><path d="m15 15 6 6"/>',
check:'<path d="m5 12 4 4L19 6"/>',
warning:'<path d="m12 3 10 18H2zM12 9v5M12 17h.01"/>',
error:'<circle cx="12" cy="12" r="9"/><path d="m9 9 6 6m0-6-6 6"/>',
plus:'<path d="M12 4v16M4 12h16"/>',
arrow:'<path d="M4 12h16m-6-6 6 6-6 6"/>',
sun:'<circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1 1m12 12 1 1M5 19l1-1M18 6l1-1"/>',
dim:'<circle cx="12" cy="12" r="9"/><path d="M12 3v18M12 7h6M12 12h9M12 17h6"/>',
moon:'<path d="M20 14A9 9 0 0 1 10 3a9 9 0 1 0 10 11z"/>',
};
function hsl(h,s,l) {
s/=100; l/=100;
const c=(1-Math.abs(2*l-1))*s, x=c*(1-Math.abs(h/60%2-1)), m=l-c/2;
const rgb=h<60?[c,x,0]:h<120?[x,c,0]:h<180?[0,c,x]:h<240?[0,x,c]:h<300?[x,0,c]:[c,0,x];
return '#'+rgb.map(v=>Math.round((v+m)*255).toString(16).padStart(2,'0')).join('');
}
function luminance(hex) {
const a=hex.slice(1).match(/../g).map(x=>parseInt(x,16)/255).map(v=>v<=0.04045?v/12.92:((v+0.055)/1.055)**2.4);
return a[0]*.2126+a[1]*.7152+a[2]*.0722;
}
function contrast(a,b) { const x=luminance(a), y=luminance(b);return (Math.max(x,y)+.05)/(Math.min(x,y)+.05); }
function foreground(h,s,start, backgrounds, minimum, light) {
for(let l=start; l>=0 && l<=100; l+=light?-1:1) {
const c=hsl(h,s,l);
if(backgrounds.every(bg=>contrast(c,bg)>=minimum)) return c;
}
throw new Error('No contrast-compliant color');
}
function tokens(p, mode) {
const light=mode==='light', dim=mode==='dim', s=Math.min(p.sat*.3,22);
const canvas=hsl(p.hue,s,light?96:dim?18:9);
const surface=light?'#ffffff':hsl(p.hue,s,dim?23:14);
const raised=hsl(p.hue,s,light?92:dim?28:20);
const backgrounds=[canvas,surface,raised];
const color=(h,s,min=4.5)=>foreground(h,s,light?44:68,backgrounds,min,light);
const action=color(p.hue,p.sat);
const onAction=contrast('#ffffff',action)>=4.5?'#ffffff':'#10141a';
return {canvas,surface,raised,text:color(p.hue,15,7),muted:color(p.hue,12),
line:hsl(p.hue,s,light?84:dim?35:28),border:color(p.hue,12,3),action,onAction,
accent:color(p.accent,p.accentSat),focus:action,success:color(157,49),warning:color(34,70),danger:color(3,66)};
}
function logo(id, size=56) {const l=logos.find(l=>l.id===id)||logos[0];return `<svg class="logo" width="${size}" height="${size}" viewBox="0 0 56 56" fill="currentColor" aria-hidden="true">${l.paths}</svg>`;}
function icon(id) {return `<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${icons[id]||icons.home}</svg>`;}
// Stream S4 (PLAN C5): which installed theme and mode the page shows, and what a theme may put on the page.
// Pure, so Node tests exactly what the browser runs. Harbor in the dark is today's page and is built in:
// tokens.css alone draws it, so it needs no installed module and no inline value.
const DEFAULT_THEME = 'harbor', DEFAULT_MODE = 'dark', MODES = ['system','light','dim','dark'];
const THEME_NAME = /^[a-z][a-z0-9-]*$/, COLOR = /^#[0-9a-f]{6}$/;
const TOKEN_NAMES = ['--canvas','--surface','--raised','--line','--border','--text','--muted','--action','--onAction','--accent','--focus','--success','--warning','--danger'];
const present = v => v !== undefined && v !== null;
const themeName = v => typeof v === 'string' && v.length <= 64 && THEME_NAME.test(v);
// The concrete mode a theme's tokens are read for; System follows the device.
const concreteMode = (mode, systemDark) => mode === 'system' ? (systemDark ? 'dark' : 'light') : mode;
// The theme's tokens for one concrete mode, or null unless every one of the fourteen is a #rrggbb colour.
function modeTokens(theme, mode) {
const t = theme && typeof theme === 'object' && themeName(theme.id) && theme.tokens && theme.tokens[mode];
if (!t || typeof t !== 'object') return null;
const names = Object.keys(t);
if (names.length !== TOKEN_NAMES.length || !TOKEN_NAMES.every(n => typeof t[n] === 'string' && COLOR.test(t[n]))) return null;
return t;
}
const usableTheme = theme => ['light','dim','dark'].every(m => modeTokens(theme, m));
// [name, value] pairs to set on <html>: the theme's fourteen colours, plus the two values tokens.css derives
// for every palette (--strong from --text, color-scheme from the mode). Null when the theme is not usable.
function themeProperties(theme, mode, systemDark) {
const m = concreteMode(mode, systemDark), t = modeTokens(theme, m);
if (!t) return null;
return [...TOKEN_NAMES.map(n => [n, t[n]]), ['--strong', m === 'light' ? 'color-mix(in srgb, var(--text) 72%, #000)' : 'color-mix(in srgb, var(--text) 70%, #fff)'], ['color-scheme', m === 'light' ? 'light' : 'dark']];
}
// Precedence, one field at a time: this browser's override for the organization, then the organization's
// saved value, then the built-in default. A winning theme that cannot be shown renders the default with a
// warning; the value itself is never altered here. themes: null while the list is loading (a name-shaped id
// is shown as asked, provisionally), an array once known. unavailable: the list could not be read.
function resolveAppearance({ themes = null, unavailable = false, saved = null, override = null } = {}) {
const field = (name, accept) => {
for (const [source, from] of [['browser', override], ['organization', saved]]) {
const v = from && typeof from === 'object' ? from[name] : undefined;
if (present(v) && accept(v)) return { value: v, source };
}
return { value: name === 'theme' ? DEFAULT_THEME : DEFAULT_MODE, source: 'default' };
};
// A mode outside the four is skipped (storage can hold anything); a theme value of any kind is honoured,
// so a bad one is reported instead of silently replaced.
const m = field('mode', v => MODES.includes(v));
const t = field('theme', () => true);
const asked = t.value, base = { mode: m.value, modeSource: m.source, requested: asked, themeSource: t.source, entry: null, provisional: false, warning: null };
if (asked === DEFAULT_THEME) return { ...base, theme: DEFAULT_THEME };
if (themes === null && themeName(asked)) return { ...base, theme: asked, provisional: true };
const entry = themes && themes.find(x => x && x.id === asked && usableTheme(x));
if (entry) return { ...base, theme: asked, entry };
return { ...base, theme: DEFAULT_THEME, warning: { code: unavailable ? 'unavailable' : 'missing', theme: asked, source: t.source } };
}
// Only the two fields, whatever else a stored or served object carries; null when it has neither.
function appearanceOf(v) {
if (!v || typeof v !== 'object' || Array.isArray(v)) return null;
const out = {};
if (present(v.theme)) out.theme = v.theme;
if (present(v.mode)) out.mode = v.mode;
return Object.keys(out).length ? out : null;
}
// The old browser-wide record {palette, mode} was written on every load, so Harbor in the dark is also what
// an unchosen page left behind. Only a value that differs from that is read as a choice worth keeping.
function legacySeed(legacy) {
if (!legacy || typeof legacy !== 'object') return null;
const theme = legacy.theme ?? legacy.palette, seed = {};
if (themeName(theme) && theme !== DEFAULT_THEME) seed.theme = theme;
if (MODES.includes(legacy.mode) && legacy.mode !== DEFAULT_MODE) seed.mode = legacy.mode;
return Object.keys(seed).length ? seed : null;
}
root.Brand = {palettes,fonts,logos,icons,tokens,contrast,logo,icon,resolveAppearance,themeProperties,usableTheme,appearanceOf,legacySeed,themeName,TOKEN_NAMES,MODES,DEFAULT_THEME,DEFAULT_MODE};
})(typeof window === 'undefined' ? globalThis : window);
/* Shared dashboard chrome. All values come from the Console's existing reads. */
(() => {
if (typeof document === 'undefined' || !document.getElementById('dashboard-kpis')) return;
const $ = id => document.getElementById(id);
let data = {}, halted = null, lastInboxHtml = null;
const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function paint() {
if (!$('dashboard-kpis')) return;
const metrics = [
['Active agents', data.agents, 'Held roles now'], ['Needs your input', data.inbox?.length, 'Open decisions'],
['Unread messages', data.messages, 'Messages'], ['Open tasks', data.tasks, 'Tasks'],
['Projects', data.projects, 'Active projects'], ['Queue rows open', data.queue, 'Rows'],
['Processing', halted === null ? null : halted ? 'Stopped' : 'On', 'Instance status']
];
$('dashboard-kpis').innerHTML = metrics.map(([label, value, caption]) => `<div class="kpi"><div>${label}</div><strong>${value == null ? '–' : escape(value)}</strong><span>${value == null ? 'Not available yet' : caption}</span></div>`).join('');
$('dashboard-business').textContent = data.business ? `Business · ${data.business}` : 'Business overview';
const inboxHtml = data.inbox == null ? '<p class="muted">Not available yet</p>' : data.inbox.length ? `<ul>${data.inbox.slice(0, 4).map(d => `<li><a href="#/inbox/${encodeURIComponent(d.id)}">${escape(String(d.question ?? 'Decision').split('\n')[0])}</a></li>`).join('')}</ul>` : '<p class="muted">Nothing is waiting on you.</p>';
if (lastInboxHtml !== inboxHtml) { $('dashboard-inbox-items').innerHTML = inboxHtml; lastInboxHtml = inboxHtml; }
age();
}
function age() { if (!$('dashboard-updated')) return; $('dashboard-updated').textContent = data.readAt ? `Updated ${Math.max(0, Math.floor((Date.now() - data.readAt) / 1000))} s ago` : 'Not read yet'; }
window.MosaicDashboard = { update(value) { data = value; paint(); } };
document.addEventListener('mosaic-processing-state', e => {
halted = e.detail.halted;
const cell = $('dashboard-kpis').lastElementChild;
if (cell) { const strong=cell.querySelector('strong'), span=cell.querySelector('span'), value=halted === null ? '–' : halted ? 'Stopped' : 'On', caption=halted === null ? 'Not available yet' : 'Instance status'; if(strong.textContent!==value) strong.textContent=value; if(span.textContent!==caption) span.textContent=caption; }
});
setInterval(age, 1000);
const button = $('avatar-button'), menu = $('avatar-menu');
const controls = () => [...menu.querySelectorAll('a[href],button:not(:disabled),select:not(:disabled)')].filter(el => el.getClientRects().length);
function close(focus = false) { menu.hidden = true; button.setAttribute('aria-expanded', 'false'); if (focus) button.focus(); }
function open() { menu.hidden = false; button.setAttribute('aria-expanded', 'true'); }
button.addEventListener('click', () => menu.hidden ? open() : close());
button.addEventListener('keydown', e => { if (e.key === 'Escape' && !menu.hidden) { e.preventDefault(); close(true); } else if (['ArrowDown','ArrowUp'].includes(e.key)) { e.preventDefault(); open(); const items = controls(); (e.key === 'ArrowDown' ? items[0] : items.at(-1))?.focus(); } });
menu.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); close(true); } else if (['ArrowDown','ArrowUp'].includes(e.key) && e.target.tagName !== 'SELECT') { e.preventDefault(); const items = controls(), i = items.indexOf(document.activeElement); items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus(); } });
button.closest('.avatar-wrap').addEventListener('focusout', e => { if (!e.currentTarget.contains(e.relatedTarget)) close(); });
menu.addEventListener('click', e => { if (e.target.closest('a')) close(); });
document.addEventListener('click', e => { if (!e.target.closest('.avatar-wrap')) close(); });
function breadcrumbs() {
draw();
// SP1: every page inside an organization says which one, after the dashboard: Dashboard / Acme / ...
const box = $('breadcrumbs'), org = /^#\/orgs\/[^/?]+/.test(location.hash) ? window.MosaicOrg : null;
if (!box || !org?.id || box.querySelector('[data-crumb-org]') || /^#\/orgs\/[^/?]+\/organization(?:[/?]|$)/.test(location.hash)) return;
box.insertAdjacentHTML('afterbegin', `<a href="#/dashboard">Dashboard</a><span aria-hidden="true">/</span><a href="#/orgs/${encodeURIComponent(org.id)}/organization" data-crumb-org>${escape(org.label)}</a><span aria-hidden="true">/</span>`);
}
window.MosaicBreadcrumbs = breadcrumbs;
function draw() {
// SP1: an organization's pages are routes under #/orgs/<id>; the crumb reads the route inside it.
const path = location.hash.replace(/^#\/orgs\/[^/?]+/, '#').slice(2).split('?')[0], parts = path.split('/').filter(Boolean), box = $('breadcrumbs');
if (!box || !$('bus-view')) return;
if (window.MosaicProjects?.breadcrumb?.(box, $('bus-view'))) return;
// Inside an organization the board is its control board; the system dashboard is the crumb before it.
if (parts[0] === 'board' && /^#\/orgs\//.test(location.hash)) { box.innerHTML = '<span aria-current="page">Control board</span>'; return; }
if (!parts.length || parts[0] === 'board' || parts[0] === 'dashboard') { box.innerHTML = '<span aria-current="page">Dashboard</span>'; return; }
if (parts[0] === 'organization') { const h = $('bus-view').querySelector('[data-org-dashboard] h1')?.textContent?.trim(); box.innerHTML = `<a href="#/dashboard">Dashboard</a>${h ? `<span aria-hidden="true">/</span><span aria-current="page">${escape(h)}</span>` : ''}`; return; }
const names = {projects:'Projects',chat:'Projects',inbox:'Inbox',messages:'Messages',tasks:'Tasks',agents:'Agents',queue:'Queue',business:'Business',docs:'Docs',settings:'Settings'};
if (parts[0] === 'settings' && parts[1] === 'business' && $('bus-view').querySelector('#settings-page-title')?.textContent.trim() === 'Business') { box.innerHTML = '<a href="#/settings">Settings</a><span aria-hidden="true">/</span><span aria-current="page">Business</span>'; return; }
const name = names[parts[0]] || 'Dashboard', heading = $('bus-view').querySelector('h1')?.textContent?.trim();
const project = $('bus-view').querySelector('.chat-conversation > p:first-child a, .chat-room > p:first-child a');
const middle = project && heading !== project.textContent.trim() ? `<a href="${escape(project.getAttribute('href'))}">${escape(project.textContent.trim())}</a><span aria-hidden="true">/</span>` : '';
box.innerHTML = parts.length > 1 && heading && heading !== name ? `<a href="#/${parts[0] === 'chat' ? 'projects' : escape(parts[0])}">${name}</a><span aria-hidden="true">/</span>${middle}<span aria-current="page">${escape(heading)}</span>` : `<span aria-current="page">${name}</span>`;
}
window.addEventListener('hashchange', () => { close(); breadcrumbs(); });
new MutationObserver(breadcrumbs).observe($('bus-view'), {childList:true, subtree:true});
for (const link of [$('processing-link'), $('mobile-processing-link')]) link.addEventListener('click', () => { if (!location.hash || location.hash === '#/' || location.hash === '#/board') $('dashboard-processing').scrollIntoView({block:'center'}); else setTimeout(() => $('dashboard-processing').scrollIntoView({block:'center'}), 0); });
paint(); breadcrumbs();
})();