rspace-online/server/shell.ts

629 lines
22 KiB
TypeScript

/**
* Shell HTML renderer.
*
* Wraps module content in the shared rSpace layout: header with app/space
* switchers + identity, <main> with module content, shell script + styles.
*
* In standalone mode, modules call renderStandaloneShell() which omits the
* app/space switchers and only includes identity.
*/
import type { ModuleInfo } from "../shared/module";
export interface ShellOptions {
/** Page <title> */
title: string;
/** Current module ID (highlighted in app switcher) */
moduleId: string;
/** Current space slug */
spaceSlug: string;
/** Space display name */
spaceName?: string;
/** Module HTML content to inject into <main> */
body: string;
/** Additional <script type="module"> tags for module-specific JS */
scripts?: string;
/** Additional <link>/<style> tags for module-specific CSS */
styles?: string;
/** List of available modules (for app switcher) */
modules: ModuleInfo[];
/** Theme for the header: 'dark' or 'light' */
theme?: "dark" | "light";
/** Extra <head> content (meta tags, preloads, etc.) */
head?: string;
}
export function renderShell(opts: ShellOptions): string {
const {
title,
moduleId,
spaceSlug,
spaceName,
body,
scripts = "",
styles = "",
modules,
theme = "dark",
head = "",
} = opts;
const moduleListJSON = JSON.stringify(modules);
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🌌</text></svg>">
<title>${escapeHtml(title)}</title>
<link rel="stylesheet" href="/shell.css">
${styles}
${head}
<style>${WELCOME_CSS}</style>
</head>
<body data-theme="${theme}">
<header class="rstack-header" data-theme="${theme}">
<div class="rstack-header__left">
<rstack-app-switcher current="${escapeAttr(moduleId)}"></rstack-app-switcher>
<rstack-space-switcher current="${escapeAttr(spaceSlug)}" name="${escapeAttr(spaceName || spaceSlug)}"></rstack-space-switcher>
</div>
<div class="rstack-header__center">
<rstack-mi></rstack-mi>
</div>
<div class="rstack-header__right">
<rstack-identity></rstack-identity>
</div>
</header>
<div class="rstack-tab-row" data-theme="${theme}">
<rstack-tab-bar space="${escapeAttr(spaceSlug)}" active="" view-mode="flat"></rstack-tab-bar>
</div>
<main id="app">
${body}
</main>
${renderWelcomeOverlay()}
<script type="module">
import '/shell.js';
// Provide module list to app switcher
document.querySelector('rstack-app-switcher')?.setModules(${moduleListJSON});
// ── Auto-space resolution ──
// Logged-in users on demo space → redirect to personal space
(function() {
try {
var raw = localStorage.getItem('encryptid_session');
if (!raw) return;
var session = JSON.parse(raw);
if (!session || !session.claims || !session.claims.username) return;
var currentSpace = '${escapeAttr(spaceSlug)}';
if (currentSpace !== 'demo') return;
fetch('/api/spaces/auto-provision', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + session.accessToken,
'Content-Type': 'application/json'
}
}).then(function(r) { return r.json(); })
.then(function(data) {
if (data.slug) {
window.location.replace(window.__rspaceNavUrl(data.slug, '${escapeAttr(moduleId)}'));
}
}).catch(function() {});
} catch(e) {}
})();
// ── Welcome overlay (first visit to demo) ──
(function() {
var currentSpace = '${escapeAttr(spaceSlug)}';
if (currentSpace !== 'demo') return;
if (localStorage.getItem('rspace_welcomed')) return;
var el = document.getElementById('rspace-welcome');
if (el) el.style.display = 'flex';
})();
window.__rspaceDismissWelcome = function() {
localStorage.setItem('rspace_welcomed', '1');
var el = document.getElementById('rspace-welcome');
if (el) el.style.display = 'none';
};
// ── Tab bar / Layer system initialization ──
// Tabs persist in localStorage so they survive full-page navigations.
// When a user opens a new rApp (via the app switcher or tab-add),
// the next page load reads the existing tabs and adds the new module.
const tabBar = document.querySelector('rstack-tab-bar');
const spaceSlug = '${escapeAttr(spaceSlug)}';
const currentModuleId = '${escapeAttr(moduleId)}';
const TABS_KEY = 'rspace_tabs_' + spaceSlug;
const moduleList = ${moduleListJSON};
if (tabBar) {
// Helper: look up a module's display name
function getModuleLabel(id) {
const m = moduleList.find(mod => mod.id === id);
return m ? m.name : id;
}
// Helper: create a layer object
function makeLayer(id, order) {
return {
id: 'layer-' + id,
moduleId: id,
label: getModuleLabel(id),
order: order,
color: '',
visible: true,
createdAt: Date.now(),
};
}
// ── Restore tabs from localStorage ──
let layers;
try {
const saved = localStorage.getItem(TABS_KEY);
layers = saved ? JSON.parse(saved) : [];
if (!Array.isArray(layers)) layers = [];
} catch(e) { layers = []; }
// Ensure the current module is in the tab list
if (!layers.find(l => l.moduleId === currentModuleId)) {
layers.push(makeLayer(currentModuleId, layers.length));
}
// Persist immediately (includes the newly-added tab)
localStorage.setItem(TABS_KEY, JSON.stringify(layers));
// Render all tabs with the current one active
tabBar.setLayers(layers);
tabBar.setAttribute('active', 'layer-' + currentModuleId);
// Helper: save current tab list to localStorage
function saveTabs() {
localStorage.setItem(TABS_KEY, JSON.stringify(layers));
}
// ── Tab events ──
tabBar.addEventListener('layer-switch', (e) => {
const { moduleId } = e.detail;
saveTabs();
window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
});
tabBar.addEventListener('layer-add', (e) => {
const { moduleId } = e.detail;
// Add the new module before navigating so the next page sees it
if (!layers.find(l => l.moduleId === moduleId)) {
layers.push(makeLayer(moduleId, layers.length));
}
saveTabs();
window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
});
tabBar.addEventListener('layer-close', (e) => {
const { layerId } = e.detail;
tabBar.removeLayer(layerId);
layers = layers.filter(l => l.id !== layerId);
saveTabs();
// If we closed the active tab, switch to the first remaining
if (layerId === 'layer-' + currentModuleId && layers.length > 0) {
window.location.href = window.__rspaceNavUrl(spaceSlug, layers[0].moduleId);
}
});
tabBar.addEventListener('view-toggle', (e) => {
const { mode } = e.detail;
document.dispatchEvent(new CustomEvent('layer-view-mode', { detail: { mode } }));
});
// Expose tabBar for CommunitySync integration
window.__rspaceTabBar = tabBar;
// ── CommunitySync: merge with Automerge once connected ──
document.addEventListener('community-sync-ready', (e) => {
const sync = e.detail?.sync;
if (!sync) return;
// Merge: Automerge layers win if they exist, otherwise seed from localStorage
const remoteLayers = sync.getLayers();
if (remoteLayers.length > 0) {
// Ensure current module is also in the Automerge set
if (!remoteLayers.find(l => l.moduleId === currentModuleId)) {
const newLayer = makeLayer(currentModuleId, remoteLayers.length);
sync.addLayer(newLayer);
}
layers = sync.getLayers();
tabBar.setLayers(layers);
const activeId = sync.doc.activeLayerId;
if (activeId) tabBar.setAttribute('active', activeId);
tabBar.setFlows(sync.getFlows());
} else {
// First connection: push all localStorage tabs into Automerge
for (const l of layers) {
sync.addLayer(l);
}
sync.setActiveLayer('layer-' + currentModuleId);
}
// Keep localStorage in sync
saveTabs();
// Sync layer changes back to Automerge
tabBar.addEventListener('layer-switch', (e) => {
sync.setActiveLayer(e.detail.layerId);
});
tabBar.addEventListener('layer-add', (e) => {
const { moduleId } = e.detail;
const newLayer = makeLayer(moduleId, sync.getLayers().length);
sync.addLayer(newLayer);
});
tabBar.addEventListener('layer-close', (e) => {
sync.removeLayer(e.detail.layerId);
});
tabBar.addEventListener('layer-reorder', (e) => {
const { layerId, newIndex } = e.detail;
sync.updateLayer(layerId, { order: newIndex });
const all = sync.getLayers();
all.forEach((l, i) => { if (l.order !== i) sync.updateLayer(l.id, { order: i }); });
});
tabBar.addEventListener('flow-create', (e) => { sync.addFlow(e.detail.flow); });
tabBar.addEventListener('flow-remove', (e) => { sync.removeFlow(e.detail.flowId); });
tabBar.addEventListener('view-toggle', (e) => { sync.setLayerViewMode(e.detail.mode); });
// Listen for remote changes
sync.addEventListener('change', () => {
layers = sync.getLayers();
tabBar.setLayers(layers);
tabBar.setFlows(sync.getFlows());
const activeId = sync.doc.activeLayerId;
if (activeId) tabBar.setAttribute('active', activeId);
const viewMode = sync.doc.layerViewMode;
if (viewMode) tabBar.setAttribute('view-mode', viewMode);
saveTabs(); // keep localStorage in sync
});
});
}
</script>
${scripts}
</body>
</html>`;
}
/** Minimal shell for standalone module deployments (no app/space switcher) */
export function renderStandaloneShell(opts: {
title: string;
body: string;
scripts?: string;
styles?: string;
theme?: "dark" | "light";
head?: string;
}): string {
const { title, body, scripts = "", styles = "", theme = "dark", head = "" } = opts;
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${escapeHtml(title)}</title>
<link rel="stylesheet" href="/shell.css">
${styles}
${head}
</head>
<body data-theme="${theme}">
<header class="rstack-header rstack-header--standalone" data-theme="${theme}">
<div class="rstack-header__left">
<a href="/" class="rstack-header__brand">
<span class="rstack-header__brand-gradient">rSpace</span>
</a>
</div>
<div class="rstack-header__center">
<rstack-mi></rstack-mi>
</div>
<div class="rstack-header__right">
<rstack-identity></rstack-identity>
</div>
</header>
<main id="app">
${body}
</main>
<script type="module">
import '/shell.js';
</script>
${scripts}
</body>
</html>`;
}
// ── Welcome overlay (quarter-screen popup for first-time visitors on demo) ──
function renderWelcomeOverlay(): string {
return `
<div id="rspace-welcome" class="rspace-welcome" style="display:none">
<div class="rspace-welcome__popup">
<button class="rspace-welcome__close" onclick="window.__rspaceDismissWelcome()">&times;</button>
<h2 class="rspace-welcome__title">Welcome to rSpace</h2>
<p class="rspace-welcome__text">
A collaborative, local-first community platform with 22+ interoperable tools.
You're viewing the <strong>demo space</strong> &mdash; sign in to access your own.
</p>
<div class="rspace-welcome__grid">
<span>🎨 Canvas</span><span>📝 Notes</span>
<span>🗳 Voting</span><span>💸 Funds</span>
<span>🗺 Maps</span><span>📁 Files</span>
<span>🔐 Passkeys</span><span>📡 Offline-First</span>
</div>
<div class="rspace-welcome__actions">
<a href="/create-space" class="rspace-welcome__btn rspace-welcome__btn--primary">Create a Space</a>
<button onclick="window.__rspaceDismissWelcome()" class="rspace-welcome__btn rspace-welcome__btn--secondary">Explore Demo</button>
</div>
<div class="rspace-welcome__footer">
<a href="/about" class="rspace-welcome__link">Learn more about rSpace</a>
<span class="rspace-welcome__dot">&middot;</span>
<a href="https://ridentity.online" class="rspace-welcome__link">EncryptID</a>
</div>
</div>
</div>`;
}
const WELCOME_CSS = `
.rspace-welcome {
position: fixed; bottom: 20px; right: 20px; z-index: 10000;
display: none; align-items: flex-end; justify-content: flex-end;
}
.rspace-welcome__popup {
position: relative;
width: min(380px, 44vw); max-height: 50vh;
background: #1e293b; border: 1px solid rgba(255,255,255,0.12);
border-radius: 16px; padding: 24px 24px 18px;
box-shadow: 0 20px 60px rgba(0,0,0,0.5); color: #e2e8f0;
overflow-y: auto; animation: rspace-welcome-in 0.3s ease-out;
}
@keyframes rspace-welcome-in {
from { opacity: 0; transform: translateY(20px) scale(0.95); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.rspace-welcome__close {
position: absolute; top: 10px; right: 12px;
background: none; border: none; color: #64748b;
font-size: 1.4rem; cursor: pointer; line-height: 1;
padding: 4px; border-radius: 4px;
}
.rspace-welcome__close:hover { color: #e2e8f0; background: rgba(255,255,255,0.08); }
.rspace-welcome__title {
font-size: 1.35rem; margin: 0 0 8px;
background: linear-gradient(135deg, #14b8a6, #22d3ee);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
background-clip: text;
}
.rspace-welcome__text {
font-size: 0.85rem; color: #94a3b8; margin: 0 0 14px; line-height: 1.55;
}
.rspace-welcome__text strong { color: #e2e8f0; }
.rspace-welcome__grid {
display: grid; grid-template-columns: 1fr 1fr;
gap: 5px; margin-bottom: 14px; font-size: 0.8rem; color: #cbd5e1;
}
.rspace-welcome__grid span { padding: 3px 0; }
.rspace-welcome__actions {
display: flex; gap: 8px; margin-bottom: 12px;
}
.rspace-welcome__btn {
padding: 8px 16px; border-radius: 8px; font-size: 0.82rem;
font-weight: 600; text-decoration: none; cursor: pointer; border: none;
transition: transform 0.15s, box-shadow 0.15s;
}
.rspace-welcome__btn:hover { transform: translateY(-1px); }
.rspace-welcome__btn--primary {
background: linear-gradient(135deg, #14b8a6, #0d9488); color: white;
box-shadow: 0 2px 8px rgba(20,184,166,0.3);
}
.rspace-welcome__btn--secondary {
background: rgba(255,255,255,0.08); color: #94a3b8;
}
.rspace-welcome__btn--secondary:hover { color: #e2e8f0; }
.rspace-welcome__footer {
display: flex; align-items: center; gap: 6px;
}
.rspace-welcome__link {
font-size: 0.72rem; color: #64748b; text-decoration: none;
transition: color 0.15s;
}
.rspace-welcome__link:hover { color: #c4b5fd; }
.rspace-welcome__dot { color: #475569; font-size: 0.6rem; }
@media (max-width: 600px) {
.rspace-welcome { bottom: 12px; right: 12px; left: 12px; }
.rspace-welcome__popup { width: 100%; max-width: none; }
}
`;
/**
* Shell that embeds a standalone app via iframe.
*
* Wraps the independent app's domain in the shared rSpace header/nav
* so users get the latest code from the standalone repo while preserving
* the unified space/identity experience.
*/
export interface IframeShellOptions extends Omit<ShellOptions, "body" | "scripts" | "styles"> {
/** The standalone app domain, e.g. "rvote.online" */
standaloneDomain: string;
/** Extra path to append after the domain root (default: "") */
path?: string;
}
export function renderIframeShell(opts: IframeShellOptions): string {
const { standaloneDomain, path = "", ...shellOpts } = opts;
const iframeSrc = `https://${standaloneDomain}${path}`;
const moduleName = shellOpts.modules.find(m => m.id === shellOpts.moduleId)?.name || shellOpts.moduleId;
return renderShell({
...shellOpts,
body: `<div id="rspace-iframe-loading" class="rspace-iframe-loading">
<div class="rspace-iframe-loading__spinner"></div>
<p class="rspace-iframe-loading__text">Loading ${escapeHtml(moduleName)}...</p>
</div>
<div id="rspace-iframe-error" class="rspace-iframe-error" style="display:none">
<div class="rspace-iframe-error__icon">&#x26A0;</div>
<h3 class="rspace-iframe-error__title">${escapeHtml(moduleName)} is not available</h3>
<p class="rspace-iframe-error__text">The standalone app at <code>${escapeHtml(standaloneDomain)}</code> didn't respond.</p>
<div class="rspace-iframe-error__actions">
<button onclick="location.reload()" class="rspace-iframe-error__btn">Retry</button>
<a href="https://${escapeAttr(standaloneDomain)}" target="_blank" rel="noopener" class="rspace-iframe-error__btn rspace-iframe-error__btn--secondary">Open directly &rarr;</a>
</div>
</div>
<iframe id="rspace-module-frame"
src="${escapeAttr(iframeSrc)}"
class="rspace-iframe"
allow="camera;microphone;fullscreen;autoplay;clipboard-write;web-share"
loading="lazy"></iframe>`,
styles: `<style>
#app.iframe-layout {
padding-top: 92px;
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
position: relative;
}
.rspace-iframe {
flex: 1;
width: 100%;
border: none;
background: #0a0a0a;
opacity: 0;
transition: opacity 0.3s ease;
}
.rspace-iframe.loaded { opacity: 1; }
.rspace-iframe-loading {
position: absolute;
inset: 92px 0 0 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
background: #0a0a0a;
z-index: 1;
}
.rspace-iframe-loading__spinner {
width: 36px; height: 36px;
border: 3px solid rgba(255,255,255,0.1);
border-top-color: #14b8a6;
border-radius: 50%;
animation: rspace-spin 0.8s linear infinite;
}
@keyframes rspace-spin { to { transform: rotate(360deg); } }
.rspace-iframe-loading__text {
color: #64748b; font-size: 0.9rem; margin: 0;
}
.rspace-iframe-error {
position: absolute;
inset: 92px 0 0 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
background: #0a0a0a;
z-index: 2;
text-align: center;
padding: 24px;
}
.rspace-iframe-error__icon {
font-size: 2.5rem; opacity: 0.5;
}
.rspace-iframe-error__title {
color: #e2e8f0; font-size: 1.1rem; margin: 0;
}
.rspace-iframe-error__text {
color: #64748b; font-size: 0.85rem; margin: 0; max-width: 400px;
}
.rspace-iframe-error__text code {
color: #94a3b8; background: rgba(255,255,255,0.06);
padding: 2px 6px; border-radius: 4px; font-size: 0.82rem;
}
.rspace-iframe-error__actions {
display: flex; gap: 10px; margin-top: 8px;
}
.rspace-iframe-error__btn {
padding: 8px 18px; border-radius: 8px; font-size: 0.82rem;
font-weight: 600; cursor: pointer; border: none;
background: #14b8a6; color: white; text-decoration: none;
transition: opacity 0.15s;
}
.rspace-iframe-error__btn:hover { opacity: 0.85; }
.rspace-iframe-error__btn--secondary {
background: rgba(255,255,255,0.08); color: #94a3b8;
}
</style>`,
scripts: `<script type="module">
document.getElementById('app')?.classList.add('iframe-layout');
const frame = document.getElementById('rspace-module-frame');
const loadingEl = document.getElementById('rspace-iframe-loading');
const errorEl = document.getElementById('rspace-iframe-error');
let loaded = false;
// Timeout: if the iframe hasn't signalled a load after 12s, show error
const timeout = setTimeout(() => {
if (!loaded) {
loadingEl?.remove();
if (errorEl) errorEl.style.display = 'flex';
}
}, 12000);
if (frame) {
frame.addEventListener('load', () => {
loaded = true;
clearTimeout(timeout);
loadingEl?.remove();
errorEl?.remove();
frame.classList.add('loaded');
// Identity bridge: forward EncryptID session to the embedded app
try {
const raw = localStorage.getItem('encryptid_session');
if (raw) {
frame.contentWindow?.postMessage({
type: 'rspace:identity',
session: JSON.parse(raw),
space: '${escapeAttr(shellOpts.spaceSlug)}',
module: '${escapeAttr(shellOpts.moduleId)}',
}, 'https://${escapeAttr(standaloneDomain)}');
}
} catch(e) {}
});
// Also detect load failure via error event
frame.addEventListener('error', () => {
if (!loaded) {
loaded = true;
clearTimeout(timeout);
loadingEl?.remove();
if (errorEl) errorEl.style.display = 'flex';
}
});
// Listen for navigation messages from the iframe
window.addEventListener('message', (e) => {
if (e.origin !== 'https://${escapeAttr(standaloneDomain)}') return;
if (e.data?.type === 'rspace:navigate') {
const { space, module } = e.data;
if (space && module && window.__rspaceNavUrl) {
window.location.href = window.__rspaceNavUrl(space, module);
}
}
});
}
</script>`,
});
}
function escapeHtml(s: string): string {
return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function escapeAttr(s: string): string {
return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}