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.
*/
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);
const currentMod = modules.find((m) => m.id === moduleId);
const shellDemoUrl = currentMod?.standaloneDomain
? `https://${escapeAttr(currentMod.standaloneDomain)}`
: `https://demo.rspace.online/${escapeAttr(moduleId)}`;
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">
<a class="rstack-header__demo-btn" ${spaceSlug === "demo" ? 'data-hide' : ''} href="${shellDemoUrl}">Try Demo</a>
<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});
// ── Bare-domain "Try Demo" button visibility ──
// On rspace.online (bare domain), the server internally rewrites to demo space,
// but we still want the "Try Demo" button visible since it links to the explicit demo subdomain.
(function() {
var host = window.location.host.split(':')[0];
if (host === 'rspace.online' || host === 'www.rspace.online') {
var btn = document.querySelector('.rstack-header__demo-btn');
if (btn) btn.removeAttribute('data-hide');
}
})();
// ── 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; }
}
`;
// ── Module landing page (bare-domain rspace.online/{moduleId}) ──
export interface ModuleLandingOptions {
/** The module to render a landing page for */
module: ModuleInfo;
/** All available modules (for app switcher) */
modules: ModuleInfo[];
/** Theme */
theme?: "dark" | "light";
}
export function renderModuleLanding(opts: ModuleLandingOptions): string {
const { module: mod, modules, theme = "dark" } = opts;
const moduleListJSON = JSON.stringify(modules);
// Prefer standalone domain for demo (better styling, more updated features)
const demoUrl = mod.standaloneDomain
? `https://${mod.standaloneDomain}`
: `https://demo.rspace.online/${mod.id}`;
const standaloneLinkHtml = mod.standaloneDomain
? `<a class="ml-standalone" href="https://demo.rspace.online/${escapeAttr(mod.id)}">Also available inside rSpace demo ↗</a>`
: "";
let feedsHtml = "";
if (mod.feeds && mod.feeds.length > 0) {
feedsHtml = `
<div class="ml-feeds">
<h3 class="ml-feeds-title">Capabilities</h3>
<div class="ml-feeds-grid">
${mod.feeds
.map(
(f) => `
<div class="ml-feed-card">
<div class="ml-feed-name">${escapeHtml(f.name)}</div>
<div class="ml-feed-desc">${escapeHtml(f.description)}</div>
<span class="ml-feed-kind">${escapeHtml(f.kind)}</span>
</div>`,
)
.join("")}
</div>
</div>`;
}
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'>${mod.icon}</text></svg>">
<title>${escapeHtml(mod.name)} — rSpace</title>
<link rel="stylesheet" href="/shell.css">
<style>${MODULE_LANDING_CSS}</style>
<script defer src="https://rdata.online/collect.js" data-website-id="6ee7917b-0ed7-44cb-a4c8-91037638526b"></script>
</head>
<body data-theme="${theme}">
<header class="rstack-header" data-theme="${theme}">
<div class="rstack-header__left">
<rstack-app-switcher current="${escapeAttr(mod.id)}"></rstack-app-switcher>
</div>
<div class="rstack-header__center"></div>
<div class="rstack-header__right">
<a class="rstack-header__demo-btn" href="${demoUrl}">Try Demo</a>
<rstack-identity></rstack-identity>
</div>
</header>
<div class="ml-hero">
<div class="ml-container">
<span class="ml-icon">${mod.icon}</span>
<h1 class="ml-name">${escapeHtml(mod.name)}</h1>
<p class="ml-desc">${escapeHtml(mod.description)}</p>
<div class="ml-ctas">
<a href="${demoUrl}" class="ml-cta-primary" id="ml-primary">Try Demo</a>
<a href="/create-space" class="ml-cta-secondary">Create a Space</a>
</div>
${standaloneLinkHtml}
</div>
</div>
${feedsHtml}
<div class="ml-back">
<a href="/">← Back to rSpace</a>
</div>
<script type="module">
import '/shell.js';
document.querySelector('rstack-app-switcher')?.setModules(${moduleListJSON});
// If logged in, update CTA to personal space
try {
var raw = localStorage.getItem('encryptid_session');
if (raw) {
var session = JSON.parse(raw);
if (session?.claims?.username) {
var username = session.claims.username.toLowerCase();
var primary = document.getElementById('ml-primary');
if (primary) {
primary.textContent = 'Go to My Space';
primary.href = 'https://' + username + '.rspace.online/${escapeAttr(mod.id)}';
}
}
}
} catch(e) {}
</script>
</body>
</html>`;
}
const MODULE_LANDING_CSS = `
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
color: white; min-height: 100vh;
display: flex; flex-direction: column; align-items: center;
padding-top: 56px;
}
.ml-hero {
display: flex; flex-direction: column; align-items: center;
justify-content: center; min-height: calc(80vh - 56px); width: 100%;
}
.ml-container {
text-align: center; max-width: 560px; padding: 40px 20px;
}
.ml-icon {
font-size: 4rem; display: block; margin-bottom: 1rem;
}
.ml-name {
font-size: 2.5rem; margin-bottom: 0.75rem;
background: linear-gradient(135deg, #14b8a6, #22d3ee);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
.ml-desc {
font-size: 1.15rem; color: #94a3b8; margin-bottom: 2.5rem; line-height: 1.6;
}
.ml-ctas {
display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;
}
.ml-cta-primary {
display: inline-block; padding: 14px 32px; border-radius: 8px;
background: linear-gradient(135deg, #14b8a6, #0d9488);
color: white; font-size: 1rem; font-weight: 600;
text-decoration: none; transition: transform 0.2s, box-shadow 0.2s;
}
.ml-cta-primary:hover {
transform: translateY(-2px); box-shadow: 0 8px 20px rgba(20,184,166,0.3);
}
.ml-cta-secondary {
display: inline-block; padding: 14px 32px; border-radius: 8px;
background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.2);
color: #94a3b8; font-size: 1rem; font-weight: 600;
text-decoration: none; transition: transform 0.2s, border-color 0.2s, color 0.2s;
}
.ml-cta-secondary:hover {
transform: translateY(-2px); border-color: rgba(255,255,255,0.4); color: white;
}
.ml-standalone {
display: inline-block; margin-top: 1.5rem;
font-size: 0.85rem; color: #64748b; text-decoration: none;
transition: color 0.2s;
}
.ml-standalone:hover { color: #22d3ee; }
.ml-feeds {
width: 100%; max-width: 640px; padding: 0 20px 3rem;
margin: 0 auto;
}
.ml-feeds-title {
font-size: 1rem; font-weight: 600; color: #94a3b8;
text-transform: uppercase; letter-spacing: 0.05em;
margin-bottom: 1rem; text-align: center;
}
.ml-feeds-grid {
display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 0.75rem;
}
.ml-feed-card {
background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);
border-radius: 10px; padding: 1rem;
}
.ml-feed-name {
font-weight: 600; font-size: 0.9rem; margin-bottom: 0.3rem; color: #e2e8f0;
}
.ml-feed-desc {
font-size: 0.8rem; color: #94a3b8; line-height: 1.5; margin-bottom: 0.5rem;
}
.ml-feed-kind {
display: inline-block; font-size: 0.65rem; font-weight: 600;
text-transform: uppercase; letter-spacing: 0.05em;
padding: 2px 8px; border-radius: 4px;
background: rgba(20,184,166,0.15); color: #14b8a6;
}
.ml-back {
padding: 2rem 0 3rem; text-align: center;
}
.ml-back a {
font-size: 0.85rem; color: #64748b; text-decoration: none; transition: color 0.2s;
}
.ml-back a:hover { color: #e2e8f0; }
@media (max-width: 600px) {
.ml-name { font-size: 2rem; }
.ml-icon { font-size: 3rem; }
.ml-feeds-grid { grid-template-columns: 1fr; }
}
`;
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;");
}