rspace-online/server/shell.ts

408 lines
15 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.
*/
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">
<style>
/* When loaded inside an iframe (e.g. standalone domain redirecting back),
hide the shell chrome — the parent rSpace page already provides it. */
html.rspace-embedded .rstack-header { display: none !important; }
html.rspace-embedded .rstack-tab-row { display: none !important; }
html.rspace-embedded #app { padding-top: 0 !important; }
html.rspace-embedded .rspace-iframe-loading,
html.rspace-embedded .rspace-iframe-error { top: 0 !important; }
</style>
<script>if (window.self !== window.parent) document.documentElement.classList.add('rspace-embedded');</script>
${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>`;
}
// ── 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; }
}
`;
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;");
}