rspace-online/server/shell.ts

496 lines
17 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 ──
const tabBar = document.querySelector('rstack-tab-bar');
const spaceSlug = '${escapeAttr(spaceSlug)}';
const currentModuleId = '${escapeAttr(moduleId)}';
if (tabBar) {
// Default layer: current module (bootstrap if no layers saved yet)
const defaultLayer = {
id: 'layer-' + currentModuleId,
moduleId: currentModuleId,
label: ${JSON.stringify(modules.find((m: any) => m.id === moduleId)?.name || moduleId)},
order: 0,
color: '',
visible: true,
createdAt: Date.now(),
};
// Set the current module as the active layer
tabBar.setLayers([defaultLayer]);
tabBar.setAttribute('active', defaultLayer.id);
// Listen for tab events
tabBar.addEventListener('layer-switch', (e) => {
const { moduleId } = e.detail;
window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
});
tabBar.addEventListener('layer-add', (e) => {
const { moduleId } = e.detail;
// Navigate to the new module (layer will be persisted when sync connects)
window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
});
tabBar.addEventListener('layer-close', (e) => {
const { layerId } = e.detail;
tabBar.removeLayer(layerId);
// If we closed the active layer, switch to first remaining
const remaining = tabBar.querySelectorAll?.('[data-layer-id]');
// The tab bar handles this internally
});
tabBar.addEventListener('view-toggle', (e) => {
const { mode } = e.detail;
// When switching to stack view, emit event for canvas to connect
document.dispatchEvent(new CustomEvent('layer-view-mode', { detail: { mode } }));
});
// Expose tabBar for CommunitySync integration
window.__rspaceTabBar = tabBar;
// If CommunitySync is available, wire up layer persistence
document.addEventListener('community-sync-ready', (e) => {
const sync = e.detail?.sync;
if (!sync) return;
// Load persisted layers
const layers = sync.getLayers();
if (layers.length > 0) {
tabBar.setLayers(layers);
const activeId = sync.doc.activeLayerId;
if (activeId) tabBar.setAttribute('active', activeId);
tabBar.setFlows(sync.getFlows());
} else {
// First visit: save the default layer
sync.addLayer(defaultLayer);
sync.setActiveLayer(defaultLayer.id);
}
// Sync layer changes back to Automerge
tabBar.addEventListener('layer-switch', (e) => {
sync.setActiveLayer(e.detail.layerId);
});
// Layer add via tab bar (persist new layer)
tabBar.addEventListener('layer-add', (e) => {
const { moduleId } = e.detail;
const newLayer = {
id: 'layer-' + moduleId,
moduleId,
label: moduleId,
order: sync.getLayers().length,
color: '',
visible: true,
createdAt: Date.now(),
};
sync.addLayer(newLayer);
});
// Layer close (remove from Automerge)
tabBar.addEventListener('layer-close', (e) => {
sync.removeLayer(e.detail.layerId);
});
// Layer reorder
tabBar.addEventListener('layer-reorder', (e) => {
const { layerId, newIndex } = e.detail;
sync.updateLayer(layerId, { order: newIndex });
// Reindex all layers
const layers = sync.getLayers();
layers.forEach((l, i) => {
if (l.order !== i) sync.updateLayer(l.id, { order: i });
});
});
// Flow creation from stack view drag-to-connect
tabBar.addEventListener('flow-create', (e) => {
sync.addFlow(e.detail.flow);
});
// Flow removal from stack view right-click
tabBar.addEventListener('flow-remove', (e) => {
sync.removeFlow(e.detail.flowId);
});
// View mode persistence
tabBar.addEventListener('view-toggle', (e) => {
sync.setLayerViewMode(e.detail.mode);
});
// Listen for remote layer/flow changes
sync.addEventListener('change', () => {
tabBar.setLayers(sync.getLayers());
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);
});
});
}
</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}`;
return renderShell({
...shellOpts,
body: `<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;
}
.rspace-iframe {
flex: 1;
width: 100%;
border: none;
background: #0a0a0a;
}
</style>`,
scripts: `<script type="module">
document.getElementById('app')?.classList.add('iframe-layout');
// Identity bridge: forward EncryptID session to the embedded app
const frame = document.getElementById('rspace-module-frame');
if (frame) {
frame.addEventListener('load', () => {
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) {}
});
// 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;");
}