feat(i18n): bind user pages to published copy
parent
c980b4da73
commit
337e1d3ea4
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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));
|
||||
@ -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'}
|
||||
|
||||
@ -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>
|
||||
@ -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.');
|
||||
@ -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";
|
||||
Loading…
Reference in New Issue