You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/UserAnnouncementDrawerViewT...

164 lines
12 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?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);
}
return false;
});
// Rendering and browser fixtures use synthetic accounts and announcements only.
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/user-announcement-view-' . bin2hex(random_bytes(6));
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' => '演示用户']);
$smarty->assign('admin_can_manage', false);
$smarty->assign('user_iso_enabled', false);
$preview = '<section class="host-card"><h1>用户页面预览</h1><p>此处仅使用合成数据,公告首屏使用安全摘要并在打开后静默校验。</p></section>'
. str_repeat('<section class="host-card"><h2>预览内容</h2><p>用于检查打开公告前后页面滚动位置。</p></section>', 8);
$smarty->assign('cloud_page', 'fixture');
$smarty->assign('cloud_title', '我的实例');
$smarty->assign('cloud_vm_id', '');
$smarty->assign('cloud_invoice_id', '');
$now = time();
$items = [];
for ($id = 12; $id >= 1; --$id) {
$kind = $id === 12 ? 'maintenance' : ($id === 11 ? 'incident' : 'notice');
$publishedAt = '2026-09-' . str_pad((string) (17 + $id), 2, '0', STR_PAD_LEFT) . ' 10:00:00';
$items[] = ['id' => $id, 'title' => $id === 12 ? '香港区域计划维护通知' : ($id === 11 ? '区域网络故障说明' : '站点服务通知 ' . $id),
'type' => $kind, 'type_label' => ['notice' => '通知', 'maintenance' => '维护', 'incident' => '故障'][$kind],
'body' => $id === 12 ? "维护时间:2026-10-01 02:00 至 03:00(站点时间)。\n维护期间可能短暂中断,请提前保存工作。\n这是一条预览公告,不代表真实维护安排。"
: ($id === 11 ? "历史故障说明,仅用于预览。\nHTML 不执行:<img src=x onerror=alert(1)>\n<script>window.announcementUnsafe=1</script>"
: "服务通知正文。\n保持段落换行,使用原有用户页面主题。"),
'status' => 'published', 'published_at' => $publishedAt,
'published_at_epoch' => strtotime($publishedAt),
'updated_at' => $publishedAt, 'updated_at_epoch' => strtotime($publishedAt)];
}
$pages = [];
foreach ([1, 2] as $page) {
$pages[$page] = ['items' => array_slice($items, ($page - 1) * 10, 10),
'pagination' => ['page' => $page, 'per_page' => 10, 'total' => 12, 'total_pages' => 2], 'generated_at' => $now];
}
$empty = ['items' => [], 'pagination' => ['page' => 1, 'per_page' => 10, 'total' => 0, 'total_pages' => 1], 'generated_at' => $now];
$smarty->assign('panel_announcements_bootstrap_json', json_encode($pages[1],
JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR));
$accountHtml = $smarty->fetch('string:{include file="user/layout_header.tpl" vu_title="账户设置" vu_active="edit"}')
. $preview . $smarty->fetch('string:{include file="user/layout_footer.tpl"}{include file="user/layout_scripts.tpl"}</body></html>');
$cloudHtml = $smarty->fetch('cloud/page.tpl');
$cloudFixture = str_replace('<main class="content">', '<main class="content">' . $preview, $cloudHtml);
$cloudFixture = preg_replace('#<script type="module" src="/cloud/app\.js\?[^\"]*"></script>#', '', $cloudFixture);
if (in_array('--fixture', $argv ?? [], true)) {
echo json_encode(['html' => ['account' => $accountHtml, 'cloud' => $cloudFixture], 'pages' => $pages, 'empty' => $empty],
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
exit;
}
$assert = static function (bool $condition, string $message): void { if (!$condition) throw new RuntimeException($message); };
$parse = static function (string $html): DOMXPath {
$dom = new DOMDocument(); libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
return new DOMXPath($dom);
};
foreach (['account' => $accountHtml, 'cloud' => $cloudHtml] as $mode => $html) {
$xpath = $parse($html);
$assert($xpath->query('//dialog[@id="panel-announcements-drawer"]')->length === 1, $mode . ': drawer missing or duplicated.');
$assert($xpath->query('//script[contains(@src,"/cloud/announcements.js?")]')->length === 1, $mode . ': shared module must load once.');
$assert($xpath->query('//header[contains(@class,"panel-topbar")]//button[@data-announcements-open]')->length === 1,
$mode . ': global topbar announcement trigger missing.');
$announcementTrigger = $xpath->query('//header[contains(@class,"panel-topbar")]//button[@data-announcements-open]')->item(0);
$languageMenu = $xpath->query('//header[contains(@class,"panel-topbar")]//details[contains(concat(" ",normalize-space(@class)," ")," panel-language-menu ")]');
$accountMenu = $xpath->query('//header[contains(@class,"panel-topbar")]//details[contains(concat(" ",normalize-space(@class)," ")," panel-user-menu ") and not(contains(concat(" ",normalize-space(@class)," ")," panel-language-menu "))]');
$assert($languageMenu->length === 1 && $accountMenu->length === 1,
$mode . ': language and account menus must be separate topbar controls.');
$assert($announcementTrigger !== null
&& $announcementTrigger->compareDocumentPosition($languageMenu->item(0)) === DOMNode::DOCUMENT_POSITION_FOLLOWING
&& $languageMenu->item(0)->compareDocumentPosition($accountMenu->item(0)) === DOMNode::DOCUMENT_POSITION_FOLLOWING,
$mode . ': language menu must sit between announcements and account controls.');
$assert($xpath->query('.//summary[contains(concat(" ",normalize-space(@class)," ")," panel-language-trigger ") and @aria-haspopup="menu"]', $languageMenu->item(0))->length === 1,
$mode . ': language icon trigger accessibility contract missing.');
$assert($xpath->query('.//*[@role="menu"]/*[@role="menuitem" and @lang="zh-CN" and @hreflang="zh-CN"]', $languageMenu->item(0))->length === 1
&& $xpath->query('.//*[@role="menu"]/*[@role="menuitem" and @lang="en" and @hreflang="en"]', $languageMenu->item(0))->length === 1,
$mode . ': language dropdown must retain Chinese and English links.');
$assert($xpath->query('.//*[@role="menu"]/*[@lang="en" and normalize-space(.)="English"]', $languageMenu->item(0))->length === 1,
$mode . ': English language option must be written in English.');
$assert($xpath->query('.//*[contains(concat(" ",normalize-space(@class)," ")," panel-user-menu-language ")]', $accountMenu->item(0))->length === 0,
$mode . ': account menu still contains the retired language selector.');
$assert($xpath->query('//button[@data-announcements-open and @aria-controls="panel-announcements-drawer" and @aria-haspopup="dialog"]')->length === 1,
$mode . ': trigger accessibility contract missing.');
$assert($xpath->query('//a[@href="/user/announcement"]')->length === 0, $mode . ': retired announcement navigation remains.');
$assert($xpath->query('//*[@id="panel-announcements-list"]/*')->length === 0,
$mode . ': announcement markup should be created through the safe text renderer.');
$assert($xpath->query('//*[@id="panel-announcements-bootstrap"]')->length === 1
&& trim($xpath->query('//*[@id="panel-announcements-bootstrap"]')->item(0)->textContent) !== '{}',
$mode . ': announcement bootstrap payload missing.');
$assert($xpath->query('//*[@data-account-frame]')->length === 3,
$mode . ': account drawers should be prepared together.');
$assert($xpath->query('//*[@data-account-frame and @loading="eager"]')->length === 3,
$mode . ': account drawer frames must not use lazy loading.');
$assert($xpath->query('//*[@id="panel-announcements-state" and @hidden and @role="alert"]')->length === 1
&& trim($xpath->query('//*[@id="panel-announcements-state"]')->item(0)->textContent) === '',
$mode . ': routine announcement loading and refresh must not display status messages.');
$assert($xpath->query('//button[@id="panel-announcements-refresh" and not(@hidden)]')->length === 1,
$mode . ': retain the manual refresh button.');
$assert($xpath->query('//*[@id="panel-announcements-read-time" and @hidden and not(@role) and not(@aria-live)]')->length === 1,
$mode . ': show read time only after a successful response, without recurring live announcements.');
$assert($xpath->query('//link[contains(@href,"admin-home.css")]')->length === 0,
$mode . ': user shell must not load the administrator theme.');
$assert($xpath->query('//button[@id="panel-announcements-close" and @autofocus]')->length === 1,
$mode . ': drawer needs an accessible initial close control.');
$assert(!str_contains($html, '未读') && !str_contains($html, 'new-announcement-dot'),
$mode . ': do not fabricate unread state.');
}
$smarty->assign('user', (object) ['user_name' => '<img src=x onerror=alert(1)>']);
$unsafeHtml = $smarty->fetch('user/panel_topbar.tpl');
$assert($parse($unsafeHtml)->query('//*[@onerror]')->length === 0, 'The shared topbar must retain username escaping.');
$invite = file_get_contents(dirname(__DIR__) . '/resources/views/venix/user/invite.tpl');
$topbar = file_get_contents(dirname(__DIR__) . '/resources/views/venix/user/panel_topbar.tpl');
$assert(!str_contains($invite, '/user/announcement')
&& str_contains($invite, "include file='user/layout_header.tpl'")
&& $topbar !== false
&& str_contains($topbar, 'data-announcements-open'),
'Invite rules must use the drawer instead of the removed page.');
$script = file_get_contents(dirname(__DIR__) . '/public/cloud/announcements.js');
$assert(!str_contains($script, '.innerHTML') && !str_contains($script, 'insertAdjacentHTML')
&& str_contains($script, 'node.textContent = String(value)'), 'Announcement title and body must be plain text.');
$assert(str_contains($script, '/api/v1/announcements?page=') && !str_contains($script, '/session')
&& !str_contains($script, 'from \'./runtime.js\''), 'Announcements must not depend on a VM session.');
$assert(str_contains($script, "item.status !== 'published'") && str_contains($script, 'visibilitychange'),
'Visible drawers must revalidate published content without background polling when hidden.');
$assert(str_contains($script, "void load(1, state.pagination ? 'auto' : 'initial');"),
'Every drawer open must immediately revalidate existing content without displaying progress.');
foreach (['旧内容', '正在刷新', '正在读取最新公告', '正在加载更多公告'] as $retiredMessage) {
$assert(!str_contains($script, $retiredMessage), 'Retired announcement status message remains: ' . $retiredMessage);
}
$css = file_get_contents(dirname(__DIR__) . '/public/cloud/client.css');
$assert(preg_match('/\.panel-announcements-trigger\.button,\s*\.panel-task-trigger\.button,\s*\.panel-language-trigger\.button \{[^}]*width: 30px;[^}]*height: 30px;[^}]*background: transparent;/', $css) === 1,
'Topbar icon triggers must match the 30px avatar without a large button background.');
$assert(preg_match('/\.panel-announcements-close\.button \{[^}]*width: 44px;[^}]*height: 44px;/', $css) === 1,
'The drawer close control must retain its 44px touch size.');
$assert(str_contains($css, '.panel-announcements-close.button:focus')
&& str_contains($css, '.panel-account-drawer-close.button:focus')
&& str_contains($css, '-webkit-tap-highlight-color: transparent'),
'Touch drawer close controls must not retain a focus ring.');
$accountCss = file_get_contents(dirname(__DIR__) . '/public/cloud/account.css');
$assert(str_contains($accountCss, 'details.vu-compact-panel > summary *')
&& str_contains($accountCss, '-webkit-tap-highlight-color: transparent'),
'Compact drawer summaries must suppress the mobile tap highlight.');
echo "User announcement shared shell, silent drawer, plain-text contract and retired navigation checks passed.\n";