feat(i18n): bind user pages to published copy

go
codex 2 weeks ago
parent c980b4da73
commit 337e1d3ea4

@ -19,6 +19,7 @@ use App\Services\Cloud\CloudUserPageView;
use App\Services\Cloud\CloudVpcFeature;
use App\Services\Cloud\CloudVpcService;
use App\Services\UserDrawerService;
use App\Services\UserCopy\UserCopyViewRuntime;
use App\Services\View;
/** User pages deliberately do not load the administrator theme styles. */
@ -400,6 +401,20 @@ final class CloudPageController
private function render($response, $page, $title, $vmId = '', $invoiceId = '', array $values = [])
{
$smarty = View::getSmarty('venix');
$copyPage = [
'instances' => 'cloud.instances', 'detail' => 'cloud.detail',
'deploy' => 'cloud.deploy', 'backups' => 'cloud.backups',
'cloud-snapshots' => 'cloud.snapshots',
'traffic' => 'cloud.traffic', 'vpcs' => 'cloud.vpcs',
'isos' => 'cloud.isos', 'keys' => 'cloud.keys',
'invoices' => 'cloud.invoices',
'invoice-detail' => 'cloud.invoice_detail',
'reinstall' => 'cloud.reinstall',
][$page] ?? null;
UserCopyViewRuntime::production()->bindCurrentRequest(
$smarty,
$copyPage
);
$smarty->assign('cloud_page', $page);
$smarty->assign('cloud_page_module', [
'instances' => 'instances', 'detail' => 'detail', 'deploy' => 'deploy',

@ -42,6 +42,7 @@ use App\Services\Ticket\TicketThreadQuery;
use App\Services\Ticket\TicketViewer;
use App\Services\Ticket\TicketReadCommand;
use App\Services\UserDrawerService;
use App\Services\UserCopy\UserCopyViewRuntime;
/**
* Account and ticket pages.
@ -88,6 +89,14 @@ class UserController extends BaseController
public function smarty()
{
$smarty = parent::smarty();
$requestPath = parse_url(
isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '/',
PHP_URL_PATH
);
if (!is_string($requestPath)
|| !str_starts_with($requestPath, '/admin')) {
UserCopyViewRuntime::production()->bindCurrentRequest($smarty);
}
$smarty->assign('cdn', isset($this->cdn) ? $this->cdn : '');
$smarty->assign('backup_cdn', isset($this->backup_cdn) ? $this->backup_cdn : '');
$smarty->assign('account_csrf_token', AdminCsrf::token());

@ -0,0 +1,106 @@
<?php
namespace App\Services\UserCopy;
use App\Services\PublicLocale;
use App\Utils\Cookie;
use Smarty;
/**
* User-page runtime seam for locale selection, Smarty copy and browser data.
*
* The implementation reads only the immutable runtime catalog and the
* source-owned Chinese fallback. Target-locale copy never lives in source.
*/
final class UserCopyViewRuntime
{
public function __construct(private readonly UserCopyRuntimeReader $reader)
{
}
public static function production(): self
{
$webRoot = dirname(__DIR__, 3);
$source = new UserCopySourceCatalog(UserCopyManifest::load());
return new self(new UserCopyRuntimeReader(
$webRoot . '/storage/framework/user-copy',
$source
));
}
public function bindCurrentRequest(
Smarty $smarty,
?string $page = null
): UserCopyCatalog {
$query = is_array($_GET) ? $_GET : [];
$cookies = is_array($_COOKIE) ? $_COOKIE : [];
$requested = PublicLocale::requestedLocale($query);
if ($requested !== null) {
Cookie::set([
PublicLocale::COOKIE_NAME => $requested,
], time() + PublicLocale::COOKIE_TTL);
$cookies[PublicLocale::COOKIE_NAME] = $requested;
}
$locale = PublicLocale::resolve(
$query,
$cookies,
isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])
? (string) $_SERVER['HTTP_ACCEPT_LANGUAGE'] : ''
);
$requestUri = isset($_SERVER['REQUEST_URI'])
? (string) $_SERVER['REQUEST_URI'] : '/';
return $this->bind($smarty, $locale, $requestUri, $page);
}
public function bind(
Smarty $smarty,
string $locale,
string $requestUri,
?string $page = null
): UserCopyCatalog {
$catalog = $page === null
? new UserCopyCatalog($this->reader, $locale, ['common'])
: UserCopyCatalog::forPage($this->reader, $locale, $page);
$snapshot = $catalog->catalog();
$bootstrap = json_encode([
'schema' => 1,
'locale' => $catalog->locale(),
'generation' => $catalog->generation(),
'messages' => $snapshot['messages'],
'metadata' => $snapshot['metadata'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
| JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_THROW_ON_ERROR);
$smarty->assign([
'user_copy_locale' => $catalog->locale(),
'user_copy_generation' => $catalog->generation(),
'user_copy_bootstrap_json' => $bootstrap,
'user_copy_language_zh_url' => PublicLocale::switchUrl(
PublicLocale::CHINESE,
$requestUri
),
'user_copy_language_en_url' => PublicLocale::switchUrl(
PublicLocale::ENGLISH,
$requestUri
),
]);
$smarty->registerPlugin(
'function',
'user_copy',
static function (array $parameters) use ($catalog): string {
$key = isset($parameters['key'])
? (string) $parameters['key'] : '';
unset($parameters['key']);
return htmlspecialchars(
$catalog->text($key, $parameters),
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
}
);
return $catalog;
}
}

@ -197,6 +197,11 @@ html.panel-task-open .panel-sidebar { transform: translate3d(0, calc(0px - var(-
.panel-user-menu-options button:hover,
.panel-user-menu-options button:focus-visible { background: #edf6f6; color: #117f88; outline: none; }
.panel-user-menu-options button i { width: 18px; color: #2b9da5; font-size: 17px; text-align: center; }
.panel-user-menu-language { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 4px; margin-top: 3px; padding-top: 7px; border-top: 1px solid #e6edf1; }
.panel-user-menu-language a { display: grid; min-height: 32px; place-items: center; border-radius: 7px; color: #6f8190; font-size: 11px; font-weight: 800; text-decoration: none; }
.panel-user-menu-language a:hover,
.panel-user-menu-language a:focus-visible { background: #edf6f6; color: #117f88; outline: none; }
.panel-user-menu-language a[aria-current="true"] { background: #def4f2; color: #0d858e; }
html.panel-account-open { overflow: hidden; overscroll-behavior: none; scroll-behavior: auto !important; }
html.panel-account-open body { position: fixed; top: var(--panel-account-scroll-top, 0px); left: 0; right: 0; width: 100%; overflow: hidden; }
.panel-account-drawer { position: fixed; inset: 0 0 0 auto; display: none; width: min(540px, 100%); max-width: 100%; height: 100vh; height: 100dvh; max-height: none; margin: 0; padding: 0; border: 0; border-radius: 0; background: #f4f7fb; color: #25384e; box-shadow: -14px 0 52px rgba(19,42,65,.18); overflow: hidden; }

@ -1,6 +1,7 @@
let activeToast = null;
let activeTimer = null;
let toastSequence = 0;
const i18n = globalThis.VenixUserCopy;
const ICONS = Object.freeze({
success: 'mdi-check-circle-outline',
@ -28,7 +29,7 @@ export function toast(message, kind = '', title = '') {
if (!region) return;
const type = kind === 'error' || kind === 'warning' ? kind : 'success';
const heading = title || (type === 'error' ? '操作失败' : '操作完成');
const heading = title || i18n.text(`common.toast.${type}.title`);
const duration = type === 'error' ? 4600 : 3200;
if (activeToast) dismiss(activeToast);
@ -50,10 +51,10 @@ export function toast(message, kind = '', title = '') {
titleElement.className = 'cloud-toast-title';
titleElement.textContent = heading;
messageElement.className = 'cloud-toast-message';
messageElement.textContent = message || '操作已完成。';
messageElement.textContent = message || i18n.text('common.toast.success.body');
close.className = 'cloud-toast-close';
close.type = 'button';
close.setAttribute('aria-label', '关闭提示');
close.setAttribute('aria-label', i18n.text('common.toast.close.aria'));
close.innerHTML = '<i class="mdi mdi-close" aria-hidden="true"></i>';
copy.append(titleElement, messageElement);

@ -0,0 +1,230 @@
(function (root) {
'use strict';
const source = root.document?.getElementById('user-copy-bootstrap');
let payload = {};
try {
payload = JSON.parse(source?.textContent || '{}');
} catch {
payload = {};
}
const locale = typeof payload.locale === 'string' && payload.locale
? payload.locale : 'zh-CN';
const messages = payload.messages && typeof payload.messages === 'object'
? payload.messages : {};
const metadata = payload.metadata && typeof payload.metadata === 'object'
? payload.metadata : {};
function matchingBrace(pattern, start) {
let depth = 0;
let quoted = false;
for (let index = start; index < pattern.length; index += 1) {
const character = pattern[index];
if (character === "'") {
if (pattern[index + 1] === "'") {
index += 1;
} else {
quoted = !quoted;
}
continue;
}
if (quoted) continue;
if (character === '{') depth += 1;
if (character === '}') {
depth -= 1;
if (depth === 0) return index;
}
}
return -1;
}
function splitArgument(argument) {
const parts = [];
let depth = 0;
let quoted = false;
let start = 0;
for (let index = 0; index < argument.length; index += 1) {
const character = argument[index];
if (character === "'") {
if (argument[index + 1] === "'") index += 1;
else quoted = !quoted;
continue;
}
if (quoted) continue;
if (character === '{') depth += 1;
else if (character === '}') depth -= 1;
else if (character === ',' && depth === 0 && parts.length < 2) {
parts.push(argument.slice(start, index).trim());
start = index + 1;
}
}
parts.push(argument.slice(start).trim());
return parts;
}
function choices(style) {
const result = {};
let offset = 0;
let cursor = 0;
const offsetMatch = style.match(/^\s*offset\s*:\s*(\d+(?:\.\d+)?)\s*/);
if (offsetMatch) {
offset = Number(offsetMatch[1]);
cursor = offsetMatch[0].length;
}
while (cursor < style.length) {
while (/\s/.test(style[cursor] || '')) cursor += 1;
const selectorStart = cursor;
while (cursor < style.length && !/[\s{]/.test(style[cursor])) cursor += 1;
const selector = style.slice(selectorStart, cursor);
while (/\s/.test(style[cursor] || '')) cursor += 1;
if (!selector || style[cursor] !== '{') return null;
const end = matchingBrace(style, cursor);
if (end < 0) return null;
result[selector] = style.slice(cursor + 1, end);
cursor = end + 1;
}
return { offset, values: result };
}
function formatArgument(argument, parameters, pluralValue) {
const parts = splitArgument(argument);
const name = parts[0];
if (!Object.prototype.hasOwnProperty.call(parameters, name)) {
return `{${argument}}`;
}
const value = parameters[name];
if (parts.length === 1) return String(value);
const type = String(parts[1] || '').toLowerCase();
const style = parts[2] || '';
if (type === 'plural' || type === 'selectordinal') {
const parsed = choices(style);
const numeric = Number(value);
if (!parsed || !Number.isFinite(numeric)) return `{${argument}}`;
const exact = `=${numeric}`;
const adjusted = numeric - parsed.offset;
const category = new Intl.PluralRules(locale, {
type: type === 'selectordinal' ? 'ordinal' : 'cardinal',
}).select(adjusted);
const selected = parsed.values[exact]
?? parsed.values[category] ?? parsed.values.other;
return typeof selected === 'string'
? formatPattern(selected, parameters, adjusted) : `{${argument}}`;
}
if (type === 'select') {
const parsed = choices(style);
if (!parsed) return `{${argument}}`;
const selected = parsed.values[String(value)] ?? parsed.values.other;
return typeof selected === 'string'
? formatPattern(selected, parameters, pluralValue) : `{${argument}}`;
}
if (type === 'number') {
const numeric = Number(value);
if (!Number.isFinite(numeric)) return `{${argument}}`;
if (style === 'integer') {
return number(numeric, { maximumFractionDigits: 0 });
}
if (style === 'percent') {
return number(numeric, { style: 'percent' });
}
return number(numeric);
}
if (type === 'date' || type === 'time') {
const parsed = new Date(Number(value) < 1e12
? Number(value) * 1000 : value);
if (!Number.isFinite(parsed.getTime())) return `{${argument}}`;
const options = type === 'date'
? { dateStyle: style || 'medium' }
: { timeStyle: style || 'medium', hour12: false };
return new Intl.DateTimeFormat(locale, options).format(parsed);
}
return `{${argument}}`;
}
function formatPattern(pattern, parameters, pluralValue = null) {
let output = '';
for (let index = 0; index < pattern.length; index += 1) {
const character = pattern[index];
if (character === "'") {
if (pattern[index + 1] === "'") {
output += "'";
index += 1;
continue;
}
const end = pattern.indexOf("'", index + 1);
if (end >= 0) {
output += pattern.slice(index + 1, end);
index = end;
continue;
}
}
if (character === '{') {
const end = matchingBrace(pattern, index);
if (end >= 0) {
output += formatArgument(
pattern.slice(index + 1, end), parameters, pluralValue
);
index = end;
continue;
}
}
if (character === '#' && pluralValue !== null) {
output += number(pluralValue);
} else {
output += character;
}
}
return output;
}
function text(key, parameters = {}) {
const message = typeof messages[key] === 'string' ? messages[key] : key;
const descriptor = metadata[key] && typeof metadata[key] === 'object'
? metadata[key] : {};
if (descriptor.hidden === true) return '';
if (descriptor.format !== 'icu') return message;
return formatPattern(message, parameters);
}
function number(value, options = {}) {
const parsed = Number(value);
return Number.isFinite(parsed)
? new Intl.NumberFormat(locale, options).format(parsed) : '—';
}
function currency(value, currencyCode = 'USD', options = {}) {
return number(value, {
style: 'currency', currency: currencyCode, ...options,
});
}
function date(value, options = {}) {
const numeric = Number(value);
const timestamp = Number.isFinite(numeric) && numeric > 0
? (numeric < 1e12 ? numeric * 1000 : numeric)
: Date.parse(String(value || ''));
const parsed = new Date(timestamp);
return Number.isFinite(parsed.getTime())
? new Intl.DateTimeFormat(locale, {
dateStyle: 'medium', timeStyle: 'medium', hour12: false, ...options,
}).format(parsed)
: '—';
}
function bytes(value, options = {}) {
let amount = Number(value);
if (!Number.isFinite(amount) || amount < 0) return '—';
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
let unit = 0;
while (amount >= 1024 && unit < units.length - 1) {
amount /= 1024;
unit += 1;
}
const maximumFractionDigits = unit === 0 ? 0 : amount >= 100 ? 0
: amount >= 10 ? 1 : 2;
return `${number(amount, { maximumFractionDigits, ...options })} ${units[unit]}`;
}
root.VenixUserCopy = Object.freeze({
locale, text, number, currency, date, bytes,
});
}(globalThis));

@ -44,8 +44,8 @@
if (toggle) {
toggle.setAttribute("aria-pressed", next === "dark" ? "true" : "false");
toggle.innerHTML = next === "dark"
? '<i class="mdi mdi-white-balance-sunny"></i><span>亮色</span>'
: '<i class="mdi mdi-weather-night"></i><span>暗色</span>';
? '<i class="mdi mdi-white-balance-sunny"></i><span>' + window.VenixUserCopy.text("common.theme.light") + '</span>'
: '<i class="mdi mdi-weather-night"></i><span>' + window.VenixUserCopy.text("common.theme.dark") + '</span>';
}
}
@ -65,11 +65,12 @@
function showToast(options) {
var config = options || {};
var userCopy = window.VenixUserCopy;
var region = qs("#vuToastRegion");
var mode = config.mode === "confirm" ? "confirm" : "alert";
var type = config.type === "error" || config.type === "warning" ? config.type : "success";
var title = config.title || (type === "error" ? "操作失败" : mode === "confirm" ? "确认操作" : "操作完成");
var message = config.message || (mode === "confirm" ? "确认继续?" : "操作已完成");
var title = config.title || (mode === "confirm" ? userCopy.text("common.dialog.confirm.title") : userCopy.text("common.toast." + type + ".title"));
var message = config.message || (mode === "confirm" ? userCopy.text("common.dialog.confirm.body") : userCopy.text("common.toast.success.body"));
var defaultDuration = mode === "confirm" ? 8000 : type === "error" ? 4600 : 2800;
var duration = Number(config.duration);
@ -112,7 +113,7 @@
body.textContent = message;
close.className = "vu-toast-close";
close.type = "button";
close.setAttribute("aria-label", "关闭提示");
close.setAttribute("aria-label", userCopy.text("common.toast.close.aria"));
close.innerHTML = '<i class="mdi mdi-close" aria-hidden="true"></i>';
copy.appendChild(heading);
@ -146,10 +147,10 @@
actions.className = "vu-toast-actions";
cancel.className = "vu-btn vu-btn-ghost vu-btn-small";
cancel.type = "button";
cancel.textContent = config.cancelText || "取消";
cancel.textContent = config.cancelText || userCopy.text("common.dialog.cancel");
confirm.className = "vu-btn vu-btn-small";
confirm.type = "button";
confirm.textContent = config.confirmText || "确认";
confirm.textContent = config.confirmText || userCopy.text("common.dialog.confirm");
cancel.addEventListener("click", function () { finish(false); });
confirm.addEventListener("click", function () { finish(true); });
actions.appendChild(cancel);
@ -175,9 +176,9 @@
return openModal({
mode: "alert",
type: type || "success",
title: title || (type === "error" ? "操作失败" : "操作完成"),
message: message || "操作已完成",
confirmText: "知道了"
title: title || window.VenixUserCopy.text("common.toast." + (type === "error" ? "error" : "success") + ".title"),
message: message || window.VenixUserCopy.text("common.toast.success.body"),
confirmText: window.VenixUserCopy.text("common.dialog.acknowledge")
});
}
@ -185,10 +186,10 @@
return openModal({
mode: "confirm",
type: type || "warning",
title: title || "确认操作",
message: message || "确认继续?",
confirmText: "确认",
cancelText: "取消"
title: title || window.VenixUserCopy.text("common.dialog.confirm.title"),
message: message || window.VenixUserCopy.text("common.dialog.confirm.body"),
confirmText: window.VenixUserCopy.text("common.dialog.confirm"),
cancelText: window.VenixUserCopy.text("common.dialog.cancel")
});
}
@ -229,11 +230,11 @@
});
}
return response.text().then(function (text) {
if (!text) return { ret: 1, msg: "操作已提交" };
if (!text) return { ret: 1, msg: window.VenixUserCopy.text("common.request.submitted") };
try {
return JSON.parse(text);
} catch (error) {
return { ret: 1, msg: "操作已提交" };
return { ret: 1, msg: window.VenixUserCopy.text("common.request.submitted") };
}
});
}
@ -277,7 +278,7 @@
function copyText(text) {
if (!text) {
alertModal("没有可复制的内容", "error");
alertModal(window.VenixUserCopy.text("common.copy.empty"), "error");
return Promise.resolve(false);
}
if (navigator.clipboard && window.isSecureContext) {
@ -317,9 +318,9 @@
if (!button) return;
event.preventDefault();
copyText(button.getAttribute("data-copy")).then(function (ok) {
if (!ok) alertModal("复制失败,请手动复制", "error");
if (!ok) alertModal(window.VenixUserCopy.text("common.copy.failed"), "error");
}).catch(function () {
alertModal("复制失败,请手动复制", "error");
alertModal(window.VenixUserCopy.text("common.copy.failed"), "error");
});
});

@ -7,6 +7,25 @@
* here. English and every other target-locale translation are maintained by
* administrators and must never be committed to this source manifest.
*/
$common = static function (
string $key,
string $source,
string $kind = 'label'
): array {
return [
'key' => $key,
'scope' => 'common',
'page' => 'cloud.instances',
'kind' => $kind,
'source' => $source,
'format' => 'plain_text',
'parameters' => [],
'criticality' => 'required',
'allow_hide' => false,
'toast_tone' => null,
];
};
return [
'version' => 1,
'pages' => [
@ -36,6 +55,53 @@ return [
'user.tickets' => ['label' => '工单页', 'scopes' => ['common', 'tickets']],
],
'entries' => [
$common('common.shell.user_center', '用户中心', 'navigation'),
$common('common.shell.sidebar.aria', '用户中心侧栏', 'aria_label'),
$common('common.shell.navigation.aria', '用户中心主导航', 'aria_label'),
$common('common.shell.navigation.toggle', '导航', 'button'),
$common('common.shell.navigation.expand.aria', '展开用户中心导航', 'aria_label'),
$common('common.shell.navigation.collapse.aria', '收起用户中心导航', 'aria_label'),
$common('common.shell.section.cloud', '云资源', 'navigation'),
$common('common.shell.section.support', '支持', 'navigation'),
$common('common.shell.nav.instances', '我的实例', 'navigation'),
$common('common.shell.nav.deploy', '部署实例', 'navigation'),
$common('common.shell.nav.backups', '云备份', 'navigation'),
$common('common.shell.nav.snapshots', '云快照', 'navigation'),
$common('common.shell.nav.traffic', '流量池', 'navigation'),
$common('common.shell.nav.vpc', 'VPC 私网', 'navigation'),
$common('common.shell.nav.iso', 'ISO 上传', 'navigation'),
$common('common.shell.nav.ssh_keys', 'SSH 公钥', 'navigation'),
$common('common.shell.nav.billing', '账单信息', 'navigation'),
$common('common.shell.nav.tickets', '工单支持', 'navigation'),
$common('common.shell.nav.admin', '管理员后台', 'navigation'),
$common('common.shell.nav.logout', '退出登录', 'navigation'),
$common('common.shell.task_center.open.aria', '打开任务中心', 'aria_label'),
$common('common.shell.task_center.title', '任务中心', 'tooltip'),
$common('common.shell.announcements.open.aria', '查看公告与维护信息', 'aria_label'),
$common('common.shell.announcements.title', '公告与维护信息', 'tooltip'),
$common('common.shell.account.menu.aria', '打开账户菜单', 'aria_label'),
$common('common.shell.account.menu', '账户菜单', 'aria_label'),
$common('common.shell.account.fallback', '账户', 'label'),
$common('common.shell.account.settings', '账户设置', 'navigation'),
$common('common.shell.account.settings.description', '管理双重认证、登录邮箱和密码', 'description'),
$common('common.shell.account.balance', '余额充值', 'navigation'),
$common('common.shell.account.balance.description', '选择充值金额和可用支付方式', 'description'),
$common('common.shell.account.promotion', '推广', 'navigation'),
$common('common.shell.account.promotion.description', '分享邀请链接并查看推广返利', 'description'),
$common('common.shell.language.aria', '选择语言', 'aria_label'),
$common('common.shell.language.chinese', '简体中文', 'label'),
$common('common.shell.language.english', '英语', 'label'),
$common('common.shell.powered_by', '由 libvirt 提供虚拟化支持', 'description'),
$common('common.theme.light', '亮色', 'label'),
$common('common.theme.dark', '暗色', 'label'),
$common('common.dialog.confirm.title', '确认操作', 'title'),
$common('common.dialog.confirm.body', '确认继续?', 'confirmation'),
$common('common.dialog.cancel', '取消', 'button'),
$common('common.dialog.confirm', '确认', 'button'),
$common('common.dialog.acknowledge', '知道了', 'button'),
$common('common.request.submitted', '操作已提交', 'status'),
$common('common.copy.empty', '没有可复制的内容', 'notice'),
$common('common.copy.failed', '复制失败,请手动复制', 'warning'),
[
'key' => 'common.toast.close.aria',
'scope' => 'common',

@ -1,6 +1,6 @@
{include file='layout_assets.tpl'}
<!doctype html>
<html lang="zh-CN">
<html lang="{$user_copy_locale|default:'zh-CN'|escape:'html'}">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
@ -57,6 +57,7 @@
{/if}
{if $cloud_page == 'detail'}{include file='cloud/console.tpl'}{/if}
<div id="toast" class="cloud-toast-region" role="region" aria-live="polite" aria-atomic="false" hidden></div>
{include file='user/user_copy_bootstrap.tpl'}
<script type="module" src="/cloud/app.js?v={$venix_asset_version}"></script>
</body>
</html>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026110605' scope='global'}
{assign var=venix_asset_version value='2026110701' scope='global'}

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="{$user_copy_locale|default:'zh-CN'|escape:'html'}">
{include file='user/layout_assets.tpl'}
{assign var=vu_page_title value=$vu_title|default:''}
{assign var=vu_active_key value=$vu_active|default:'' scope='global'}
@ -20,6 +20,7 @@
<link href="/theme/venix/css/site-brand.css?v={$vu_asset_version}" rel="stylesheet">
</head>
<body class="vu-body{if !empty($smarty.get.drawer)} vu-embedded{/if}">
{include file='user/user_copy_bootstrap.tpl'}
<div class="dashboard user-dashboard">
{include file='user/panel_sidebar.tpl' panel_active=$vu_active_key panel_cloud_page=0}
<div class="main-area">

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="{$user_copy_locale|default:'zh-CN'|escape:'html'}">
{include file='user/layout_assets.tpl'}
{assign var=vu_page_title value=$vu_title|default:''}
<head>
@ -27,3 +27,4 @@
<link href="/theme/venix/css/site-brand.css?v={$vu_asset_version}" rel="stylesheet">
</head>
<body class="vu-body">
{include file='user/user_copy_bootstrap.tpl'}

@ -1,71 +1,71 @@
{assign var=panel_cloud_mode value=$panel_cloud_page|default:0}
{assign var=panel_active_key value=$panel_active|default:''}
{assign var=panel_cloud_active_key value=$panel_cloud_active|default:''}
<aside class="sidebar panel-sidebar" aria-label="用户中心侧栏">
<aside class="sidebar panel-sidebar" aria-label="{user_copy key='common.shell.sidebar.aria'}">
<div class="panel-sidebar-header">
<a class="sidebar-brand" href="/user/cloud/instances" aria-label="{$config["appName"]|escape:"html"}用户中心">
<a class="sidebar-brand" href="/user/cloud/instances" aria-label="{$config["appName"]|escape:"html"} {user_copy key='common.shell.user_center'}">
{include file='components/site_brand_mark.tpl'}
<span>{$config["appName"]|escape:"html"}</span>
</a>
<button class="panel-nav-toggle" type="button" aria-controls="panel-user-navigation" aria-expanded="false" aria-label="展开用户中心导航">
<i class="mdi mdi-menu" aria-hidden="true"></i><span>导航</span>
<button class="panel-nav-toggle" type="button" aria-controls="panel-user-navigation" aria-expanded="false" aria-label="{user_copy key='common.shell.navigation.expand.aria'}" data-expand-label="{user_copy key='common.shell.navigation.expand.aria'}" data-collapse-label="{user_copy key='common.shell.navigation.collapse.aria'}">
<i class="mdi mdi-menu" aria-hidden="true"></i><span>{user_copy key='common.shell.navigation.toggle'}</span>
</button>
</div>
<nav class="cloud-sidebar-nav panel-sidebar-nav" id="panel-user-navigation" aria-label="用户中心主导航">
<div class="sidebar-section-label">云资源</div>
<nav class="cloud-sidebar-nav panel-sidebar-nav" id="panel-user-navigation" aria-label="{user_copy key='common.shell.navigation.aria'}">
<div class="sidebar-section-label">{user_copy key='common.shell.section.cloud'}</div>
<a class="sidebar-link{if $panel_cloud_active_key == 'instances' || $panel_cloud_active_key == 'detail' || $panel_cloud_active_key == 'reinstall' || $panel_cloud_active_key == 'rescue' || (!$panel_cloud_mode && $panel_active_key == 'cloud')} active{/if}" href="/user/cloud/instances">
<i class="mdi mdi-server nav-icon" aria-hidden="true"></i><span>我的实例</span>
<i class="mdi mdi-server nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.instances'}</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'deploy'} active{/if}" href="/user/cloud/deploy">
<i class="mdi mdi-cart-outline nav-icon" aria-hidden="true"></i><span>部署实例</span>
<i class="mdi mdi-cart-outline nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.deploy'}</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'backups'} active{/if}" href="/user/cloud/backups">
<i class="mdi mdi-cloud-upload-outline nav-icon" aria-hidden="true"></i><span>云备份</span>
<i class="mdi mdi-cloud-upload-outline nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.backups'}</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'cloud-snapshots'} active{/if}" href="/user/cloud/cloud-snapshots">
<i class="mdi mdi-layers-triple-outline nav-icon" aria-hidden="true"></i><span>云快照</span>
<i class="mdi mdi-layers-triple-outline nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.snapshots'}</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'traffic'} active{/if}" href="/user/cloud/traffic">
<i class="mdi mdi-chart-donut-variant nav-icon" aria-hidden="true"></i><span>流量池</span>
<i class="mdi mdi-chart-donut-variant nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.traffic'}</span>
</a>
{if !empty($vpc_enabled)}
<a class="sidebar-link{if $panel_cloud_active_key == 'vpcs'} active{/if}" href="/user/cloud/vpcs">
<i class="mdi mdi-lan nav-icon" aria-hidden="true"></i><span>VPC 私网</span>
<i class="mdi mdi-lan nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.vpc'}</span>
</a>
{/if}
{if !empty($user_iso_enabled)}
<a class="sidebar-link{if $panel_cloud_active_key == 'isos'} active{/if}" href="/user/cloud/iso-images">
<i class="mdi mdi-disc nav-icon" aria-hidden="true"></i><span>ISO 上传</span>
<i class="mdi mdi-disc nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.iso'}</span>
</a>
{/if}
<a class="sidebar-link{if $panel_cloud_active_key == 'keys'} active{/if}" href="/user/cloud/ssh-keys">
<i class="mdi mdi-key-outline nav-icon" aria-hidden="true"></i><span>SSH 公钥</span>
<i class="mdi mdi-key-outline nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.ssh_keys'}</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'invoices'} active{/if}" href="/user/cloud/invoices">
<i class="mdi mdi-file-document-outline nav-icon" aria-hidden="true"></i><span>账单信息</span>
<i class="mdi mdi-file-document-outline nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.billing'}</span>
</a>
<div class="sidebar-section-label">支持</div>
<div class="sidebar-section-label">{user_copy key='common.shell.section.support'}</div>
<a class="sidebar-link{if $panel_active_key == 'ticket'} active{/if}" href="/user/ticket">
<i class="mdi mdi-lifebuoy nav-icon" aria-hidden="true"></i><span>工单支持</span>
<i class="mdi mdi-lifebuoy nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.tickets'}</span>
</a>
</nav>
<div class="sidebar-bottom panel-sidebar-bottom">
{if $panel_cloud_mode}
<a id="cloud-admin-link" class="sidebar-link panel-admin-link" href="/admin"{if empty($admin_can_manage)} hidden{/if}>
<i class="mdi mdi-shield-crown-outline nav-icon" aria-hidden="true"></i><span>管理员后台</span>
<i class="mdi mdi-shield-crown-outline nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.admin'}</span>
</a>
{elseif !empty($admin_can_manage)}
<a class="sidebar-link panel-admin-link" href="/admin">
<i class="mdi mdi-shield-crown-outline nav-icon" aria-hidden="true"></i><span>管理员后台</span>
<i class="mdi mdi-shield-crown-outline nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.admin'}</span>
</a>
{/if}
<a class="sidebar-link panel-logout-link" href="/user/logout">
<i class="mdi mdi-logout nav-icon" aria-hidden="true"></i><span>退出登录</span>
<i class="mdi mdi-logout nav-icon" aria-hidden="true"></i><span>{user_copy key='common.shell.nav.logout'}</span>
</a>
<div class="sidebar-caption">Powered by libvirt</div>
<div class="sidebar-caption">{user_copy key='common.shell.powered_by'}</div>
</div>
</aside>
<script>
@ -75,17 +75,19 @@
var navigation = document.getElementById('panel-user-navigation');
if (!sidebar || !toggle || !navigation) return;
var mobile = window.matchMedia('(max-width: 960px)');
var expandLabel = toggle.dataset.expandLabel || '';
var collapseLabel = toggle.dataset.collapseLabel || '';
var closeNavigation = function () {
sidebar.classList.remove('is-open');
toggle.setAttribute('aria-expanded', 'false');
toggle.setAttribute('aria-label', '展开用户中心导航');
toggle.setAttribute('aria-label', expandLabel);
};
toggle.addEventListener('click', function () {
var open = toggle.getAttribute('aria-expanded') !== 'true';
sidebar.classList.toggle('is-open', open);
toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
toggle.setAttribute('aria-label', open ? '收起用户中心导航' : '展开用户中心导航');
toggle.setAttribute('aria-label', open ? collapseLabel : expandLabel);
});
navigation.addEventListener('click', function (event) {
if (event.target.closest('a') && mobile.matches) closeNavigation();

@ -1,27 +1,32 @@
{assign var=panel_cloud_mode value=$panel_cloud_page|default:0}
{capture assign=panel_account_fallback}{user_copy key='common.shell.account.fallback'}{/capture}
<header class="topbar panel-topbar">
<div class="breadcrumb">用户中心 <span>/</span><strong{if $panel_cloud_mode} id="breadcrumb-current"{/if}>{$panel_title|default:'账户'|escape:"html"}</strong></div>
<div class="breadcrumb">{user_copy key='common.shell.user_center'} <span>/</span><strong{if $panel_cloud_mode} id="breadcrumb-current"{/if}>{$panel_title|default:$panel_account_fallback|escape:"html"}</strong></div>
<div class="topbar-right">
{if $panel_cloud_mode}
<button class="button button-ghost panel-task-trigger" id="cloud-task-center-open" type="button" data-task-center-open aria-haspopup="dialog" aria-controls="panel-task-drawer" aria-expanded="false" aria-label="打开任务中心" title="任务中心"><i class="mdi mdi-progress-clock" aria-hidden="true"></i><span id="cloud-task-center-badge" class="panel-task-badge" hidden>0</span></button>
<button class="button button-ghost panel-task-trigger" id="cloud-task-center-open" type="button" data-task-center-open aria-haspopup="dialog" aria-controls="panel-task-drawer" aria-expanded="false" aria-label="{user_copy key='common.shell.task_center.open.aria'}" title="{user_copy key='common.shell.task_center.title'}"><i class="mdi mdi-progress-clock" aria-hidden="true"></i><span id="cloud-task-center-badge" class="panel-task-badge" hidden>0</span></button>
{/if}
<button class="button button-ghost panel-announcements-trigger" type="button" data-announcements-open aria-haspopup="dialog" aria-controls="panel-announcements-drawer" aria-expanded="false" aria-label="查看公告与维护信息" title="公告与维护信息"><i class="mdi mdi-bullhorn-outline" aria-hidden="true"></i></button>
<button class="button button-ghost panel-announcements-trigger" type="button" data-announcements-open aria-haspopup="dialog" aria-controls="panel-announcements-drawer" aria-expanded="false" aria-label="{user_copy key='common.shell.announcements.open.aria'}" title="{user_copy key='common.shell.announcements.title'}"><i class="mdi mdi-bullhorn-outline" aria-hidden="true"></i></button>
<details class="panel-user-menu">
<summary class="topbar-user" aria-label="打开账户菜单" aria-haspopup="menu" aria-expanded="false">
<summary class="topbar-user" aria-label="{user_copy key='common.shell.account.menu.aria'}" aria-haspopup="menu" aria-expanded="false">
<span class="avatar">U</span>
<span{if $panel_cloud_mode} id="current-username"{/if}>{$user->user_name|default:'账户'|escape:"html"}</span>
<span{if $panel_cloud_mode} id="current-username"{/if}>{$user->user_name|default:$panel_account_fallback|escape:"html"}</span>
<i class="mdi mdi-chevron-down panel-user-menu-chevron" aria-hidden="true"></i>
</summary>
<div class="panel-user-menu-options" role="menu" aria-label="账户菜单">
<button type="button" role="menuitem" data-account-drawer-open="account" data-drawer-title="账户设置" data-drawer-description="管理双重认证、登录邮箱和密码"><i class="mdi mdi-shield-account-outline" aria-hidden="true"></i><span>账户设置</span></button>
<button type="button" role="menuitem" data-account-drawer-open="balance" data-drawer-title="余额充值" data-drawer-description="选择充值金额和可用支付方式"><i class="mdi mdi-wallet-plus-outline" aria-hidden="true"></i><span>余额充值</span></button>
<button type="button" role="menuitem" data-account-drawer-open="promotion" data-drawer-title="推广" data-drawer-description="分享邀请链接并查看推广返利"><i class="mdi mdi-account-multiple-plus-outline" aria-hidden="true"></i><span>推广</span></button>
<div class="panel-user-menu-options" role="menu" aria-label="{user_copy key='common.shell.account.menu'}">
<button type="button" role="menuitem" data-account-drawer-open="account" data-drawer-title="{user_copy key='common.shell.account.settings'}" data-drawer-description="{user_copy key='common.shell.account.settings.description'}"><i class="mdi mdi-shield-account-outline" aria-hidden="true"></i><span>{user_copy key='common.shell.account.settings'}</span></button>
<button type="button" role="menuitem" data-account-drawer-open="balance" data-drawer-title="{user_copy key='common.shell.account.balance'}" data-drawer-description="{user_copy key='common.shell.account.balance.description'}"><i class="mdi mdi-wallet-plus-outline" aria-hidden="true"></i><span>{user_copy key='common.shell.account.balance'}</span></button>
<button type="button" role="menuitem" data-account-drawer-open="promotion" data-drawer-title="{user_copy key='common.shell.account.promotion'}" data-drawer-description="{user_copy key='common.shell.account.promotion.description'}"><i class="mdi mdi-account-multiple-plus-outline" aria-hidden="true"></i><span>{user_copy key='common.shell.account.promotion'}</span></button>
<div class="panel-user-menu-language" role="group" aria-label="{user_copy key='common.shell.language.aria'}">
<a href="{$user_copy_language_zh_url|escape:'html'}" lang="zh-CN" hreflang="zh-CN"{if $user_copy_locale != 'en'} aria-current="true"{/if}>{user_copy key='common.shell.language.chinese'}</a>
<a href="{$user_copy_language_en_url|escape:'html'}" lang="en" hreflang="en"{if $user_copy_locale == 'en'} aria-current="true"{/if}>{user_copy key='common.shell.language.english'}</a>
</div>
</div>
</details>
{if $panel_cloud_mode}
<button id="logout-button" class="button button-ghost small" type="button">退出登录</button>
<button id="logout-button" class="button button-ghost small" type="button">{user_copy key='common.shell.nav.logout'}</button>
{else}
<a class="button button-ghost small panel-topbar-logout" href="/user/logout">退出登录</a>
<a class="button button-ghost small panel-topbar-logout" href="/user/logout">{user_copy key='common.shell.nav.logout'}</a>
{/if}
</div>
</header>

@ -0,0 +1,2 @@
<script id="user-copy-bootstrap" type="application/json">{$user_copy_bootstrap_json|default:'{}' nofilter}</script>
<script src="/cloud/user-copy-runtime.js?v={$venix_asset_version|escape:'html'}"></script>

@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void {
};
$assert(is_string($assets)
&& str_contains($assets, "venix_asset_version value='2026110605'")
&& str_contains($assets, "venix_asset_version value='2026110701'")
&& is_string($cloudShell)
&& str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'),
'The cloud application entry must use the shared Venix asset version.');

@ -97,7 +97,7 @@ $assert(str_contains($service, 'public const USER_PAGE_SIZE = 25;'),
'The user invoice list must retain its bounded default page size.');
$assert(!str_contains($shell, '/theme/venix/js/qrcode.min.js'),
'The shared cloud shell must not block first paint on the QR code library.');
$assert(str_contains($topbar, "\$user->user_name|default:'账户'")
$assert(str_contains($topbar, '$user->user_name|default:$panel_account_fallback')
&& !str_contains($topbar, '{if $panel_cloud_mode}账户{else}'),
'Cloud pages must render the authenticated account name without a session API request.');

@ -100,9 +100,9 @@ $assert(str_contains($detailScript,
'Disabling future automatic backups must not disable recovery from a retained ready backup.');
$assert(str_contains($sidebar, 'href="/user/cloud/backups"')
&& str_contains($sidebar, '>云备份</span>')
&& str_contains($sidebar, "common.shell.nav.backups")
&& str_contains($sidebar, 'href="/user/cloud/cloud-snapshots"')
&& str_contains($sidebar, '>云快照</span>')
&& str_contains($sidebar, "common.shell.nav.snapshots")
&& str_contains($shell, "cloud_page == 'backups'")
&& str_contains($shell, "cloud_page == 'cloud-snapshots'")
&& str_contains($app, "backups: '/cloud/backups.js'")

@ -12,6 +12,8 @@ $smarty->setCacheDir($directory);
foreach (['urlencode', 'number_format', 'date'] as $modifier) {
$smarty->registerPlugin('modifier', $modifier, $modifier);
}
$smarty->registerPlugin('function', 'user_copy', static fn (array $parameters): string =>
isset($parameters['key']) ? (string) $parameters['key'] : '');
$count = 0;
$emailCount = 0;
try {

@ -1,6 +1,12 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\UserCopy\UserCopyManifest;
use App\Services\UserCopy\UserCopyRuntimeReader;
use App\Services\UserCopy\UserCopySourceCatalog;
use App\Services\UserCopy\UserCopyViewRuntime;
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING | E_DEPRECATED))) {
throw new ErrorException($message, 0, $severity, $file, $line);
@ -14,6 +20,10 @@ $compileDir = sys_get_temp_dir() . '/user-announcement-view-' . bin2hex(random_b
mkdir($compileDir);
$smarty->setCompileDir($compileDir);
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
(new UserCopyViewRuntime(new UserCopyRuntimeReader(
$compileDir . '/missing-user-copy-runtime',
new UserCopySourceCatalog(UserCopyManifest::load())
)))->bind($smarty, 'zh-CN', '/user/edit', null);
$smarty->assign('config', ['appName' => 'Venix Test', 'jump_delay' => 1000]);
$smarty->assign('cdn', '');
$smarty->assign('user', (object) ['user_name' => '演示用户']);

@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const root = new URL('../', import.meta.url);
const source = await readFile(new URL('public/cloud/user-copy-runtime.js', root), 'utf8');
const payload = {
schema: 1,
locale: 'en',
messages: {
'common.toast.success.title': '运行时成功',
'common.toast.close.aria': '运行时关闭',
'test.greeting': '您好 {name}',
'test.count': '{count, plural, =0 {暂无项目} one {# 个项目} other {# 个项目}}',
'test.role': '{role, select, owner {所有者} other {成员}}',
},
metadata: {
'test.greeting': { format: 'icu', parameters: ['name'] },
'test.count': { format: 'icu', parameters: ['count'] },
'test.role': { format: 'icu', parameters: ['role'] },
},
};
const context = {
Intl, Date, JSON,
document: {
getElementById(id) {
return id === 'user-copy-bootstrap'
? { textContent: JSON.stringify(payload) } : null;
},
},
};
context.globalThis = context;
vm.runInNewContext(source, context, { filename: 'user-copy-runtime.js' });
const runtime = context.VenixUserCopy;
assert.equal(runtime.locale, 'en');
assert.equal(runtime.text('common.toast.success.title'), '运行时成功');
assert.equal(runtime.text('test.greeting', { name: 'Virt' }), '您好 Virt');
assert.equal(runtime.text('test.count', { count: 0 }), '暂无项目');
assert.equal(runtime.text('test.count', { count: 2 }), '2 个项目');
assert.equal(runtime.text('test.role', { role: 'owner' }), '所有者');
assert.equal(runtime.text('missing.copy.key'), 'missing.copy.key');
assert.match(runtime.number(1234), /1,234/);
assert.match(runtime.bytes(1024), /1 KiB/);
const toast = await readFile(new URL('public/cloud/toast.js', root), 'utf8');
assert.match(toast, /VenixUserCopy/);
assert.match(toast, /i18n\.text/,
'Cloud Toast does not read defaults from the browser catalog.');
assert.doesNotMatch(toast, /const copy = globalThis\.VenixUserCopy/,
'The catalog binding must not be shadowed by the Toast copy container.');
assert.doesNotMatch(toast, /操作失败|操作完成|关闭提示/,
'Cloud Toast still owns source-language defaults.');
console.log('User copy browser translator and Toast defaults passed.');

@ -1,10 +1,14 @@
<?php
$root = dirname(__DIR__) . '/app/Services/UserCopy';
$files = glob($root . '/*.php');
if (!is_array($files) || $files === []) {
throw new RuntimeException('User copy runtime module is missing.');
}
$runtimeFiles = [
'UserCopyCatalogException.php',
'UserCopyManifest.php',
'UserCopySourceCatalog.php',
'UserCopyRuntimeReader.php',
'UserCopyCatalog.php',
'UserCopyViewRuntime.php',
];
$forbidden = [
'/Illuminate\\\\Database/',
@ -14,7 +18,11 @@ $forbidden = [
'/\\bRedis(?:Client)?\\b/',
'/\\bDB::/',
];
foreach ($files as $file) {
foreach ($runtimeFiles as $name) {
$file = $root . '/' . $name;
if (!is_file($file)) {
throw new RuntimeException('User copy runtime file is missing: ' . $name);
}
$source = file_get_contents($file);
if (!is_string($source)) {
throw new RuntimeException('Unable to read ' . $file);

@ -0,0 +1,106 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\UserCopy\UserCopyCatalogCompiler;
use App\Services\UserCopy\UserCopyManifest;
use App\Services\UserCopy\UserCopyPublicationStore;
use App\Services\UserCopy\UserCopyRuntimeReader;
use App\Services\UserCopy\UserCopySourceCatalog;
use App\Services\UserCopy\UserCopyViewRuntime;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$removeTree = static function (string $directory): void {
if (!is_dir($directory)) return;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $item) {
$item->isDir() ? rmdir($item->getPathname()) : unlink($item->getPathname());
}
rmdir($directory);
};
$runtimeRoot = sys_get_temp_dir() . '/virt-user-copy-view-'
. bin2hex(random_bytes(8));
$smartyRoot = $runtimeRoot . '/smarty';
mkdir($smartyRoot, 0700, true);
try {
$source = new UserCopySourceCatalog(UserCopyManifest::load());
$compiled = (new UserCopyCatalogCompiler($source))->compile('en', [
// Test fixture copy is runtime publication data, never source copy.
'common.shell.user_center' => '运行时发布的账户外壳',
'common.shell.nav.instances' => '运行时发布的实例导航',
'common.toast.success.title' => '运行时发布的成功标题',
'common.toast.success.body' => '运行时发布的成功内容',
'common.toast.error.title' => '运行时发布的失败标题',
'common.toast.warning.title' => '运行时发布的警告标题',
'common.toast.close.aria' => '运行时发布的关闭标签',
]);
(new UserCopyPublicationStore($runtimeRoot))->publish($compiled);
$reader = new UserCopyRuntimeReader($runtimeRoot, $source);
$runtime = new UserCopyViewRuntime($reader);
$smarty = new Smarty();
$smarty->setCompileDir($smartyRoot);
$smarty->setCacheDir($smartyRoot);
$catalog = $runtime->bind(
$smarty,
'en',
'/user/cloud/instances?page=2',
'cloud.instances'
);
$html = $smarty->fetch(
'string:<html lang="{$user_copy_locale}">'
. '{user_copy key="common.shell.user_center"}|'
. '{user_copy key="common.shell.nav.instances"}|'
. '{$user_copy_language_zh_url}|{$user_copy_language_en_url}'
. '</html>'
);
$assert(str_contains($html, 'lang="en"')
&& str_contains($html, '运行时发布的账户外壳')
&& str_contains($html, '运行时发布的实例导航'),
'Smarty did not render the active runtime publication.');
$assert(str_contains($html, 'page=2&lang=zh-CN')
&& str_contains($html, 'page=2&lang=en'),
'Language switching did not preserve the current query.');
$assert($catalog->generation() === $compiled->generation,
'The user view did not bind the active immutable generation.');
$variables = $smarty->getTemplateVars();
$bootstrap = json_decode(
(string) ($variables['user_copy_bootstrap_json'] ?? ''),
true,
512,
JSON_THROW_ON_ERROR
);
$assert(($bootstrap['locale'] ?? null) === 'en'
&& ($bootstrap['generation'] ?? null) === $compiled->generation
&& ($bootstrap['messages']['common.toast.success.title'] ?? null)
=== '运行时发布的成功标题',
'Browser bootstrap does not match the server request snapshot.');
$fallbackSmarty = new Smarty();
$fallbackSmarty->setCompileDir($smartyRoot);
$fallbackSmarty->setCacheDir($smartyRoot);
$fallback = $runtime->bind(
$fallbackSmarty,
'fr',
'/user/ticket',
null
);
$assert($fallback->generation() === null
&& $fallback->text('common.shell.user_center') === '用户中心',
'An unpublished locale did not fall back to source copy.');
} finally {
$removeTree($runtimeRoot);
}
echo "User copy locale, Smarty and browser-bootstrap runtime checks passed.\n";

@ -236,15 +236,17 @@ $assert(str_contains($baseStyles,
$assert(str_contains($cloudTemplate, '>实例管理</h1>')
&& str_contains($cloudTemplate, '部署实例</a>'),
'Instance page terminology missing');
$assert(str_contains($sharedSidebar, '>我的实例</span>') && str_contains($sharedSidebar, '>部署实例</span>'), 'Shared sidebar instance terminology missing');
$assert(str_contains($sharedSidebar, 'common.shell.nav.instances')
&& str_contains($sharedSidebar, 'common.shell.nav.deploy'),
'Shared sidebar instance terminology missing');
$assert(str_contains($sharedSidebar, 'href="/user/cloud/backups"')
&& str_contains($sharedSidebar, '>云备份</span>')
&& str_contains($sharedSidebar, 'common.shell.nav.backups')
&& str_contains($cloudShell, "cloud_page == 'backups'")
&& str_contains($clientEntry, "backups: '/cloud/backups.js'"),
'User cloud-backup page must be reachable from the shared navigation and module bootstrap.');
$assert(str_contains($sharedSidebar, 'href="/user/cloud/iso-images"')
&& str_contains($sharedSidebar, '{if !empty($user_iso_enabled)}')
&& str_contains($sharedSidebar, '>ISO 上传</span>')
&& str_contains($sharedSidebar, 'common.shell.nav.iso')
&& str_contains($cloudShell, "cloud_page == 'isos'")
&& str_contains($clientEntry, "isos: '/cloud/iso-images.js'"),
'User-owned ISO page must be reachable from shared navigation and module bootstrap.');
@ -975,7 +977,7 @@ foreach (['expired_grace', 'blocked_expired', 'deleting', 'delete_failed',
$assert(str_contains($sharedSidebar, 'href="/user/cloud/invoices"')
&& str_contains($cloudTemplate, 'id="invoices-workspace"')
&& str_contains($cloudTemplate, 'id="invoice-detail-workspace"')
&& str_contains($sharedSidebar, '>账单信息</span>')
&& str_contains($sharedSidebar, 'common.shell.nav.billing')
&& str_contains($invoiceDetailRuntime, '/pay-balance')
&& str_contains($invoiceDetailRuntime, '/payments'),
'Unified invoices must support balance and online payment paths');

Loading…
Cancel
Save