const Demo = SubscriptionDemo;
const params = new URLSearchParams(location.search);
const knownScenarios = ['new', 'waiting', 'failed', 'advanced', 'quota', 'expired', 'enterprise'];
let state = Demo.initial(knownScenarios.includes(params.get('scenario')) ? params.get('scenario') : 'new');
const views = { plans: '套餐与开通', waiting: '开通进度', containers: '我的容器', access: '接入信息', enterprise: '加入企业', account: '我的账号', expired: '继续使用 Fmode', chat: '开始协作' };
const requestedView = params.get('screen') || location.hash.slice(1);
if (views[requestedView]) state = Demo.reduce(state, { type: 'view', view: requestedView });
if (params.get('theme') === 'dark') document.documentElement.classList.add('dark');
const main = document.getElementById('main');
const dialog = document.getElementById('dialog');
const dialogBody = document.getElementById('dialogBody');
let dialogContext = null;
let dialogTrigger = null;
let toastTimer;
const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]);
const paths = {
grid: '',
server: '',
arrow: '',
check: '',
clock: '',
shield: '',
person: '',
people: '',
key: '',
copy: '',
plus: '',
refresh: '',
spark: '',
cloud: '',
chat: '',
info: '',
warning: '',
wifi: '',
close: '',
building: '',
link: '',
};
const icon = (name) => ``;
const button = (text, action, kind = '', extra = '') => ``;
const notice = (title, text, tone = '', name = 'info') => `
${icon(name)}
${title}${text ? `
${text}
` : ''}
`;
const planName = () => state.plan ? Demo.PLANS[state.plan].name : '尚未开通';
const stateLabel = () => state.offline ? '网络未连接' : ({ unopened: '尚未开通', provisioning: '正在开通', active: state.plan === 'trial' ? '试用中' : '已开通', expired: '试用已到期' })[state.access];
const priceNotice = '具体价格请咨询客服。';
function nav() {
const items = [{ view: 'plans', label: '套餐与开通', mobile: '套餐', icon: 'grid' }, { view: 'containers', label: '我的容器', mobile: '容器', icon: 'server' }, { view: 'access', label: '接入信息', mobile: '接入', icon: 'key' }, { view: 'enterprise', label: state.company || state.companyAccount ? '企业空间' : '加入企业', mobile: '企业', icon: 'people' }];
document.getElementById('desktopNav').innerHTML = items.map((item) => ``).join('');
document.getElementById('mobileNav').innerHTML = items.map((item) => ``).join('');
}
function planCards() {
const cards = [
{ key: 'starter', icon: 'server', name: '入门版', short: '入门', sub: '一个专属空间,从这里开始。', unit: '/ 月', note: '支持 1 个容器', mobileQuota: '1 个专属容器 · 2 核 4G', mobileBenefit: '独立云资源 · 含完整接入信息', quota: '1', quotaLabel: '个容器', perks: ['1 个专属容器', '2 核 4G 标准规格', '独立云资源', '完整接入信息', '手机与电脑均可使用'] },
{ key: 'advanced', icon: 'spark', name: '进阶版', short: '进阶', sub: '更多空间,接住不同的想法。', unit: '/ 年', note: '含一年资源费用', mobileQuota: '3 个专属容器 · 2 核 4G', mobileBenefit: '独立云资源 · 支持加购名额', quota: '3', quotaLabel: '个容器', perks: ['3 个专属容器', '2 核 4G 标准规格', '独立云资源与接入信息', '支持加购容器名额'] },
{ key: 'enterprise', icon: 'building', name: '企业版', short: '企业', sub: '让整个团队,有序地协作。', unit: '', note: '团队共享', mobileQuota: '5 个共享容器 · 2 核 4G', mobileBenefit: '成员管理 · 通讯录与容器共享', quota: '5', quotaLabel: '个共享', perks: ['5 个企业容器', '2 核 4G 标准规格(新容器)', '企业成员管理', '通讯录与容器共享', '支持加购容器名额'] },
];
const cta = (card) => state.access === 'expired' ? '恢复' : state.plan === card.key ? '当前' : '开通';
return `${cards.map((card) => {
const disabled = state.plan === card.key && state.access === 'active';
const current = state.plan === card.key && state.access === 'active';
return `
${card.key === 'advanced' ? '推荐' : ''}
${card.name}
${card.key === 'advanced' ? '推荐' : ''}${card.mobileQuota}
${card.mobileBenefit}
价格待定${card.unit || card.note}
${button(cta(card), 'apply', card.key === 'advanced' ? '' : 'secondary', `data-plan="${card.key}" ${disabled ? 'disabled' : ''}`)}
${icon(card.icon)}
${card.name}${card.short}
${card.sub}
${card.quota}${card.quotaLabel}
价格待定${card.unit}
${card.note}
${button(cta(card), 'apply', card.key === 'advanced' ? '' : 'secondary', `data-plan="${card.key}" ${disabled ? 'disabled' : ''}`)}
${card.perks.map((perk) => `- ${icon('check')}${perk}
`).join('')}
`;
}).join('')}
`;
}
function applicationNotice() {
if (!state.application) return '';
const addon = state.application.kind === 'addon';
return notice(addon ? '增配申请已提交' : '开通申请已提交', '等待确认。', 'info', 'clock');
}
function plansPage() {
let trial = '';
if (!state.trialClaimed && state.access === 'unopened') {
trial = `${icon('spark')}
先体验,再决定。两天试用
1 个专属容器,开通后开始体验。
${button('开始两天试用 ' + icon('arrow'), 'trial')}`;
} else if (state.job && state.job.status !== 'ready') {
trial = `${icon('clock')}
正在开通
${esc(state.job.name)}
${button('查看进度 ' + icon('arrow'), 'waiting')}`;
} else if (state.access === 'active') {
trial = `${icon('check')}
${esc(planName())}${state.plan === 'trial' ? '试用中' : '使用中'}
已使用 ${Demo.used(state)} / ${Demo.limit(state)} 个名额
${button('我的容器 ' + icon('arrow'), 'containers')}`;
}
return `${icon('grid')}套餐与开通选择适合你的协作方式。
按需选择,随时升级。
${applicationNotice()}${trial}
为下一步,准备合适的空间
个人专属 · 企业共享 · 按需增配
${planCards()}
${icon('info')}${priceNotice}
${icon('building')}加入企业
使用企业容器
`;
}
function waitingPage() {
const job = state.job;
if (!job) return `${icon('clock')}
暂无开通记录
${button('查看套餐', 'plans')}
`;
const ready = job.status === 'ready', failed = job.status === 'failed';
const percent = ready ? 100 : Math.min(99, Math.floor(job.completed / Demo.STAGES.length * 100));
const label = ready ? '已就绪' : failed ? '开通失败' : job.status === 'queued' ? '等待开通' : job.status === 'verifying' ? '即将就绪' : '正在开通';
const elapsed = Math.floor((state.now - job.createdAt) / 60000);
const feedback = state.offline ? notice('网络连接已断开', '请检查网络后重试。', 'warning', 'wifi') : failed ? notice('暂时未能完成开通', '请稍后重试。', 'warning', 'warning') : job.delayed ? notice('仍在处理中', '请稍后查看。', '', 'clock') : '';
return `${feedback}
${icon(ready ? 'check' : failed ? 'warning' : 'server')}${label}
${esc(job.name)}
${esc(planName())} - ${ready ? '状态' : '已等待'}
- ${ready ? '已就绪' : elapsed + ' 分钟'}
- ${ready ? '当前套餐' : '预计完成'}
- ${ready ? esc(planName()) : '稍后更新'}
${ready ? button('开始使用 ' + icon('arrow'), 'chat') : failed ? button(icon('refresh') + '重试', 'retry', '', state.offline ? 'disabled' : '') : button(icon('refresh') + '检查进度', 'check', '', state.offline ? 'disabled' : '')}${button('我的容器', 'containers', 'secondary')}
`;
}
function quotaPanel() {
const used = Demo.used(state), reserved = Demo.reserved(state), max = Demo.limit(state);
return `${state.company ? '企业共享名额' : '我的容器名额'} ${esc(planName())}
已用 ${used} 个${reserved ? `,开通中 ${reserved} 个` : ''}${state.addon ? `,已含加购 ${state.addon} 个` : ''}。
${used + reserved} / ${max} 个名额
${['advanced', 'enterprise'].includes(state.plan) ? button('增加名额', 'addon', 'secondary') : button('查看套餐', 'plans', 'secondary')}`;
}
function containerCard(container) {
return `${esc(container.name.slice(0,1))}${esc(container.name)}
${container.company ? '企业共享' : '归属于我'}已就绪 2 核 CPU4 GB 内存平台容器
可以开始使用。
${button('进入会话 ' + icon('arrow'), 'chat', '', `data-id="${esc(container.id)}"`)}${button('设置', 'settings', 'secondary', `data-id="${esc(container.id)}"`)}
`;
}
function containersPage() {
if (!state.plan) return `${icon('server')}我的容器我的容器
管理你的专属空间。
${icon('server')}
还没有容器
选择套餐,开始使用。
${button('领取两天试用 ' + icon('arrow'), 'trial')}
`;
const activeJob = state.job && state.job.status !== 'ready';
return `${icon('server')}${state.company ? '企业容器' : '我的容器'}${state.company ? '企业容器' : '我的容器'}
${state.company ? '团队共享的容器。' : '管理你的专属空间。'}
${button(icon('plus') + '创建容器', 'create', '', !Demo.canCreate(state) ? 'disabled' : '')}${applicationNotice()}${quotaPanel()}${activeJob ? notice('有一个容器正在开通', '', 'info', 'clock') + button('查看开通进度 ' + icon('arrow'), 'waiting', 'secondary') : ''}${Demo.used(state) >= Demo.limit(state) && !activeJob ? notice('名额已用完', ['advanced','enterprise'].includes(state.plan) ? '可申请增加名额。' : '升级套餐,获取更多名额。', '', 'info') : ''}
${state.containers.map(containerCard).join('')}${Demo.canCreate(state) ? `
` : ''}
${!state.containers.length ? '
正在开通,请稍后查看。
' : ''}
`;
}
const fakeCredentials = [
{ group: 'matrix', label: 'agentMxId', value: '@demo-agent:example.invalid' },
{ group: 'matrix', label: 'userMxId', value: '@demo-user:example.invalid' },
{ group: 'matrix', label: 'homeserver', value: 'https://matrix.example.invalid' },
{ group: 'matrix', label: 'roomId', value: '!demo-room:example.invalid' },
{ group: 'matrix', label: 'accessToken', value: 'DEMO_ONLY_NOT_A_REAL_MATRIX_TOKEN' },
{ group: 'backend', label: 'appId', value: 'DEMO_APP_ID_NOT_REAL' },
{ group: 'backend', label: 'serverURL', value: 'https://backend.example.invalid/parse' },
{ group: 'backend', label: 'functionsURL', value: 'https://backend.example.invalid/functions' },
{ group: 'backend', label: '独立资源专属凭据', value: 'DEMO_ONLY_RESOURCE_SCOPED_CREDENTIAL' },
];
function credentialsPage() {
if (!Demo.hasAccess(state) || !state.containers.length) return `${icon('key')}
${state.job ? '正在准备' : '暂无接入信息'}
开通完成后可查看。
${button(state.job ? '查看开通进度' : '查看套餐', state.job ? 'waiting' : 'plans')}
`;
const panel = (group, heading, text, name) => `${icon(name)}${heading}
${text}
${fakeCredentials.filter((field) => field.group === group).map((field) => `- ${field.label}
- ••••••••••••${button(icon('copy') + '查看与复制', 'credential', 'ghost', `data-field="${esc(field.label)}"`)}
`).join('')}
`;
const backendPanel = state.company ? `${icon('cloud')}企业资源
请联系企业管理员。
` : panel('backend', '独立云资源', '', 'cloud');
return `${icon('key')}接入信息接入信息
当前容器:${esc(state.containers[0].name)}。
${notice('请勿分享密钥', '', '', 'shield')}
${panel('matrix', '通信信息', '', 'chat')}${backendPanel}
`;
}
function expiredPage() {
return `${icon('clock')}
两天试用已结束试用已结束
开通套餐后继续使用。
${icon('shield')}${esc(state.containers[0]?.name || '我的协作伙伴')}容器和数据已保留。
待开通${applicationNotice()}${planCards()}
${icon('info')}${priceNotice}
`;
}
function enterprisePage() {
const org = state.company;
if (!org && state.companyAccount) return `${icon('building')}企业空间企业空间
${icon('building')}
示例企业
5 个共享容器名额
${button('进入企业空间 ' + icon('arrow'), 'switch-company')} `;
return `${icon('building')}${org ? '企业空间' : '加入企业'}${org ? '企业空间' : '加入企业'}
${org ? '' : '联系管理员完成邀请。'}
${org ? quotaPanel() : ''}
${org ? `${['产品协作组','内容协作组'].map((name,index) => `${index ? '内' : '产'}${name}示例成员 · 名下 1 个企业容器
可协作 `).join('')}${button('查看企业容器 ' + icon('arrow'), 'containers', 'secondary', 'style="margin-top:var(--sp-5)"')}` : `等待加入
将用户 ID 发给管理员。
用户 IDDEMO_USER_001
${button(icon('copy') + '复制', 'copy-user', 'secondary')}
${button(icon('refresh') + '我已被邀请,立即检查', 'check-org')}
`} `;
}
function accountPage() {
return `当前套餐
${stateLabel()}- 套餐
- ${esc(planName())}
- 容器名额
- ${Demo.used(state)} / ${Demo.limit(state)}
- 试用状态
- ${state.plan === 'trial' ? stateLabel() : '—'}
- 当前空间
- ${state.company ? '示例企业' : '个人空间'}
${button('查看套餐', 'plans')}${button('我的容器', 'containers', 'secondary')}
`;
}
function chatPage() {
if (!Demo.hasAccess(state) || !state.containers.length) return state.access === 'expired' ? expiredPage() : waitingPage();
return `${icon('chat')}
已就绪
${esc(state.containers[0].name)}
${button('我的容器', 'containers', 'secondary')}
`;
}
function render(resetScroll = false) {
nav();
document.getElementById('pageLabel').textContent = views[state.view] || views.plans;
document.getElementById('headerStatus').innerHTML = icon(state.offline ? 'wifi' : 'shield') + esc(stateLabel());
const pages = { plans: plansPage, waiting: waitingPage, containers: containersPage, access: credentialsPage, enterprise: enterprisePage, account: accountPage, expired: expiredPage, chat: chatPage };
const subjectSwitcher = state.company || state.companyAccount ? `当前空间
` : '';
main.innerHTML = subjectSwitcher + (pages[state.view] || plansPage)();
if (resetScroll) main.scrollTop = 0;
document.getElementById('reviewState').textContent = `当前演示:${state.company ? '企业' : '个人'}空间 · ${planName()} · ${stateLabel()} · 容器 ${Demo.used(state)} 个 · 任务预占 ${Demo.reserved(state)} 个 · 配额 ${Demo.limit(state)} 个${state.job ? ' · 任务 ' + state.job.id + ' · 尝试 ' + state.job.attempt + ' 次' : ''}。所有状态均为本地模拟。`;
document.querySelector('[data-event="advance"]').disabled = !state.job || ['ready','failed'].includes(state.job.status) || state.offline;
document.querySelector('[data-event="fail"]').disabled = !state.job || state.job.status === 'ready';
document.querySelector('[data-event="slow"]').disabled = !state.job || ['ready','failed'].includes(state.job.status);
document.querySelector('[data-event="approve"]').disabled = !state.application;
document.querySelector('[data-event="expire"]').disabled = state.plan !== 'trial' || state.access !== 'active';
document.querySelector('[data-event="join"]').disabled = state.view !== 'enterprise' || state.company;
document.querySelector('[data-event="offline"]').textContent = state.offline ? '恢复网络' : '模拟断网';
document.getElementById('themeToggle').textContent = document.documentElement.classList.contains('dark') ? '浅色' : '深色';
}
function toast(message) {
clearTimeout(toastTimer);
const element = document.getElementById('toast');
element.textContent = message; element.classList.add('visible');
toastTimer = setTimeout(() => element.classList.remove('visible'), 3400);
}
function dispatch(action) {
const oldView = state.view;
state = Demo.reduce(state, action);
render(state.view !== oldView);
if (state.note) toast(state.note);
}
function go(view) { dispatch({ type: 'view', view }); }
function closeDialog() { if (dialog.open) dialog.close(); }
function openDialog(kind, data = {}, trigger = document.activeElement) {
dialogContext = { kind, ...data }; dialogTrigger = trigger;
const cancel = '';
if (kind === 'create') {
const trial = data.trial;
dialogBody.innerHTML = ``;
} else if (kind === 'apply') {
const name = Demo.PLANS[data.plan].name;
dialogBody.innerHTML = ``;
} else if (kind === 'addon') {
dialogBody.innerHTML = ``;
} else if (kind === 'credential') {
dialogBody.innerHTML = `${icon('shield')}敏感信息确认仅供本人使用,请勿外发。
即将查看并复制「${esc(data.field)}」。请妥善保管。
${notice('仅供本人使用', '', '', 'info')}${cancel}
`;
} else if (kind === 'settings') {
const container = state.containers.find((item) => item.id === data.id);
if (!container) return;
dialogBody.innerHTML = ``;
}
dialog.showModal(); document.getElementById('dialogClose').focus();
}
async function copyText(value, message = '已复制') {
try {
if (!navigator.clipboard?.writeText) throw new Error('unavailable');
await navigator.clipboard.writeText(value);
return message;
} catch { return '浏览器未允许自动复制,可选中文本手动复制。'; }
}
document.getElementById('dialogClose').addEventListener('click', closeDialog);
dialog.addEventListener('close', () => { if (dialogTrigger?.isConnected) dialogTrigger.focus({ preventScroll: true }); else main.focus({ preventScroll: true }); });
dialog.addEventListener('click', (event) => {
const rect = dialog.getBoundingClientRect();
if (event.target === dialog && (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom)) closeDialog();
});
document.addEventListener('click', async (event) => {
const target = event.target.closest('button, a');
if (!target || target.disabled) return;
if (target.hasAttribute('data-close-dialog')) return closeDialog();
if (target.dataset.subject) return dispatch({ type: 'subject', subject: target.dataset.subject });
if (target.dataset.view) return go(target.dataset.view);
if (target.dataset.scenario) { state = Demo.initial(target.dataset.scenario); render(true); return; }
if (target.dataset.event) return dispatch({ type: target.dataset.event });
if (target.hasAttribute('data-confirm-credential')) {
const field = fakeCredentials.find((item) => item.label === dialogContext?.field);
if (!field) return;
const result = document.getElementById('credentialResult');
result.hidden = false; result.replaceChildren();
const code = document.createElement('code'); code.className = 'demo-secret'; code.textContent = field.value;
const feedback = document.createElement('p'); feedback.className = 'dialog-feedback'; feedback.setAttribute('role', 'status');
result.append(code, feedback); target.disabled = true;
feedback.textContent = await copyText(field.value, '原型假数据已复制,请勿用于实际接入。');
return;
}
const action = target.dataset.action;
if (!action) return;
if (['plans','waiting','containers','chat'].includes(action)) return go(action === 'plans' && state.access === 'expired' ? 'expired' : action);
if (action === 'trial') return openDialog('create', { trial: true }, target);
if (action === 'create') {
if (Demo.canCreate(state)) openDialog('create', { trial: false }, target);
else toast('当前名额不可用,请查看套餐或开通中的任务。');
return;
}
if (action === 'apply') {
const plan = target.dataset.plan;
if (plan === 'enterprise' && !state.company) return go('enterprise');
if (state.company && plan !== 'enterprise') dispatch({ type: 'subject', subject: 'personal', view: 'plans' });
if (state.access === 'active' && state.plan !== 'trial' && Demo.PLANS[plan].limit < Demo.limit(state)) return toast('更换套餐请联系客服。');
return openDialog('apply', { plan }, target);
}
if (action === 'switch-company') return dispatch({ type: 'subject', subject: 'company', view: 'enterprise' });
if (action === 'addon') return openDialog('addon', {}, target);
if (action === 'credential') return openDialog('credential', { field: target.dataset.field }, target);
if (action === 'settings') return openDialog('settings', { id: target.dataset.id }, target);
if (action === 'retry') return dispatch({ type: 'retry' });
if (action === 'check') return toast(state.offline ? '网络暂时不可用,原任务仍在平台保留。' : '仍在开通中,请稍后查看。');
if (action === 'check-org') return toast('仍在等待邀请。');
if (action === 'copy-job') return toast(await copyText(state.job?.id || '', '演示任务编号已复制'));
if (action === 'copy-user') return toast(await copyText('DEMO_USER_001', '演示用户 ID 已复制'));
});
document.addEventListener('submit', (event) => {
event.preventDefault();
const id = event.target.id;
if (id === 'createForm') {
const name = document.getElementById('containerName').value.trim();
if (!name) return;
const trial = dialogContext.trial; closeDialog(); dispatch({ type: 'start', name, plan: trial ? 'trial' : state.plan });
}
if (id === 'applyForm') { const plan = dialogContext.plan; closeDialog(); dispatch({ type: 'apply', plan }); }
if (id === 'addonForm') { const quantity = Number(document.getElementById('addonQuantity').value); closeDialog(); dispatch({ type: 'addon', quantity }); }
if (id === 'renameForm') {
const name = document.getElementById('renameInput').value.trim(); if (!name) return;
const containerId = dialogContext.id; closeDialog(); dispatch({ type: 'rename', id: containerId, name }); toast('演示容器名称已修改');
}
});
document.getElementById('reviewToggle').addEventListener('click', () => {
const controls = document.getElementById('reviewControls'); controls.hidden = !controls.hidden;
document.getElementById('reviewToggle').setAttribute('aria-expanded', String(!controls.hidden));
});
document.getElementById('themeToggle').addEventListener('click', () => { document.documentElement.classList.toggle('dark'); render(); });
document.querySelector('.brand').addEventListener('click', (event) => { event.preventDefault(); go('plans'); });
render(true);