feat(console,admin): kiosk 不再点击穿透 + 压住任务栏;大屏控制页新增「局域网大屏」(链接/复制/二维码)dev_0.4.0

## ① 现场问题:kiosk 窗口点击穿透(原设计方向反了)
`displays.js` 原来对多屏 kiosk 调 `setIgnoreMouseEvents(true)`,注释写的是
「防止现场误触」——但该 API 的语义是「本窗口忽略鼠标」,点击会**落到它后面的
窗口或桌面**,现场想防的误触正好变成误点别的东西;被忽略鼠标的窗口也点不活。
现在窗口**默认吞掉鼠标、不穿透**。

配置项**改名**为 `display.allowClickThrough`(缺省 false;显式 true 才穿透)。
**旧键 `display.ignoreMouse` 完全不读**——老机器的配置文件里还写着旧版模板留下的
`ignoreMouse: true`,而配置策略是「已存在不覆盖」,只改默认值等于老机器升级后
照样穿透;改名才能让默认值真正生效。启动时若发现旧键会记一条中文提示(只记一次),
并在合并后的配置里把它剥掉,防止将来有人再读到那个陈年 true。
(不是自动改写用户配置文件:无法区分「操作员刻意写的 true」与「旧模板留下的 true」。)

## ② 现场问题:任务栏盖住 kiosk 窗口、被盖住后抢不回前台
原顺序是 `setKiosk(true)` 之后又 `setBounds(...)`,在 Windows 上会把窗口从真正的
全屏态拽回「恰好铺满该屏的无边框窗口」→ 不是 topmost,任务栏与拖过去的窗口都盖得住。
现在固定为 **先 `setBounds` 定位 → 再 `setKiosk(true)` → 最后 `setAlwaysOnTop(true,
'screen-saver')`**(默认层级 `floating` 在 Windows 上仍画在任务栏下面),并加了
「已达标就不重复进出 kiosk」的守卫避免重排白闪;非 kiosk 分支会摘掉置顶。
Win 真机行为需现场复核,代码/桩级已验(含顺序与层级的断言)。

## ③ 新功能:大屏控制页「局域网大屏」卡片
- 服务端新增 `GET /api/system/network`(recorder 及以上):回本机可用局域网 IPv4
  (排除回环/link-local/IPv6,去重,按 192.168/10/172.16-31 优先排序)+ 真实监听端口
  + 路径;无地址回 `[]` 不报错。
- 卡片:每个地址一条可点击链接 + 复制按钮,第一个地址配二维码(148px)。
- **二维码是离线自实现的纯 TS 编码器**(版本 1–40 自动、ECC L/M/Q/H、8 种掩码择优),
  正确性用 **Python OpenCV 真解码**验收:29/29 条解出原文(含中文与边界),
  SVG 渲染后再解码 4/4,并把验证过的矩阵冻结成仓库参照用例。
- 复制按**非安全上下文**处理:面板常从 `http://192.168.x.x` 打开,那里
  `navigator.clipboard` 是 undefined,自动回退 `execCommand('copy')`。

## ④ 真机联调抓出并修掉一个时序缺陷(真浏览器 + 真服务端)
`DisplayPage` 的 `refreshLan()` 在挂载时跑,而 `auth` 是异步加载的——那一刻
`auth.readOnly` 必然为 true,卡片把「当前为只读访客」写进一个**普通 ref** 就返回了,
身份落定后没有任何东西再触发它:**管理员登录后卡片永远停在访客态,
`/api/system/network` 一次都没被请求**。
改为「gate 由 computed 直接渲染 + watch gate 变 null 时重跑加载」,并补回归钉子。
(同时修正了一条把该错误结构当成正确行为的源码断言用例。)
端到端证据:真服务 + 局域网 IP(真非安全上下文)→ 卡片列出两个地址、点击复制变
「已复制」(走 execCommand 回退)→ 浏览器渲染的二维码截图经 cv2 解出
`http://10.50.101.85:19861/display`。

## 文档
部署指南配置表与多屏行为、使用手册「大屏控制」与局域网设备段、devdocs 05/07/10/13、
升级说明新增 dev_0.4.0(含旧键废弃与启动提示)。**无数据迁移**,旧赛事包照常导入。

自检:服务端 13 包 ×2;前端 vue-tsc + 645 例 ×2 + build;Console 20 文件 + 68 例。
This commit is contained in:
AskaEth committed 2026-09-12 16:25:04 +08:00
1 parent ed2c0b3f3c
commit 9ef68c2589
33 files changed
+2923 -95

No files matched your search

+14
View File
@@ -13,6 +13,7 @@ import type {
EventSettings,
HealthInfo,
LiveEvents,
NetworkInfo,
Page,
PageQuery,
PointAdjustment,
@@ -328,6 +329,19 @@ export const adminApi = {
() => ({ source: 'auto', eventIds: [], events: [] }),
),
/**
* 本机局域网地址(`GET /api/system/network`,recorder 及以上)。
*
* 这句是给「大屏控制」页的局域网卡片用的:连不上后端时退回示例地址,
* 让示例模式也能看到卡片长什么样;**403 不降级**——访客必须看到「没权限」而不是
* 一条看着能用的假地址(那会让人拿着错的链接去别的设备上试)。
*/
systemNetwork: (): Promise<NetworkInfo> =>
call(
() => client.system.network(),
() => mockDb.network(),
),
login: (username: string, password: string): Promise<CurrentUser> =>
callWrite(() => client.auth.login(username, password)),
+17
View File
@@ -11,6 +11,7 @@ import type {
EventCategory,
EventSettings,
HealthInfo,
NetworkInfo,
Page,
PointAdjustment,
PublishPayload,
@@ -834,6 +835,22 @@ class MockDb {
health(): HealthInfo {
return { version: 'mock' }
}
/**
* 示例模式下的本机网络信息:字段形状与 `GET /api/system/network` 完全一致,
* IP 用私有段里的一条假地址,绝不能让示例数据里出现真机或公网地址。
*/
network(): NetworkInfo {
return {
port: 19540,
displayPath: '/display',
adminPath: '/admin',
addresses: [
{ ip: '192.168.1.23', interface: 'eth0', family: 'ipv4' },
{ ip: '10.0.8.7', interface: 'wlan0', family: 'ipv4' },
],
}
}
}
function round(value: number): number {
+1
View File
@@ -24,6 +24,7 @@ export const ICON_PATHS = {
maximize: 'M5 5h14v14H5z',
restore: 'M8 8h11v11H8zM5 16V5h11',
check: 'M5 12.5 10 17l9-10',
copy: 'M9 9h11v11H9zM15 9V4H4v11h4',
warning: 'M12 4l9 16H3l9-16Zm0 6v4m0 3v.5',
search: 'M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm10 2-4.3-4.3',
chevron: 'M8 10l4 4 4-4',
+254 -59
View File
@@ -1,15 +1,18 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { formatDateTime, type EventSettings, type LiveEvents } from '@/shared'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { formatDateTime, type EventSettings, type LiveEvents, type NetworkInfo } from '@/shared'
import type { DisplayInstance } from '@/shared/api'
import { DISPLAY_PAGES, type DisplayPageKey } from '@/display/types'
import { encodeQr, qrToSvg } from '@/shared/qrcode'
import MxIcon from '../components/MxIcon.vue'
import PageHeader from '../components/PageHeader.vue'
import { adminApi } from '../api/client'
import MockBadge from '../components/system/MockBadge.vue'
import { adminApi, ApiError } from '../api/client'
import { settingsApi } from '../components/system/systemApi'
import { useAuthStore } from '../stores/auth'
import { useEventStore } from '../stores/event'
import { useToastStore } from '../stores/toast'
import { copyText, lanDisplayLinks } from './lanDisplay'
/**
* 页面选项直接取大屏那份清单(`@/display/types`):规范页名与中文标签只维护一处,
@@ -317,17 +320,114 @@ function onVisibilityChange(): void {
if (document.visibilityState === 'visible') void refreshInstances()
}
// ── 局域网大屏(别的设备用浏览器打开就是一块大屏) ────────────────────────────
const lanInfo = ref<NetworkInfo | null>(null)
/**
* 非 null 表示卡片只能给说明、给不出地址:权限不足或接口读不到。
*
* 用 `lanInfo === null` 兼作「还没读到答案」——请求只有「拿到数据」和「拿到一句话」
* 两种结局,所以首帧不会先闪一下「未检测到局域网地址」那个空态。
*/
const lanProblem = ref<string | null>(null)
/** 刚复制成功的地址,1.5 秒后清掉,用来把按钮文案切成「已复制」。 */
const copiedUrl = ref<string | null>(null)
let copiedTimer: ReturnType<typeof setTimeout> | null = null
/** 二维码目标边长(像素):卡片里放得下,也够手机在正常距离扫出来。 */
const QR_PIXELS = 140
const QR_MARGIN = 4
/**
* 访客提前拦住,不去吃那个必然的 403。
*
* `/api/system/network` 是 recorder 及以上,与系统设置各面板同一口径;
* 示例数据模式例外——那时本来就没有会话,但界面要能看到卡片长什么样。
*/
const lanGateReason = computed(() =>
auth.readOnly && !data.isMock ? '只有登录后的录入员 / 管理员能查看局域网地址,当前为只读访客。' : null,
)
const lanLinks = computed(() => (lanInfo.value === null ? [] : lanDisplayLinks(lanInfo.value)))
/** 有地址但服务端没给端口:拼不出链接,这句话要和「没插网线」分开说。 */
const lanPortMissing = computed(() => lanInfo.value !== null && lanInfo.value.port <= 0)
/**
* 第一个地址的小二维码。
*
* 只给第一条地址出码:卡片上摆一排二维码没有意义,现场也只需要一个能随手扫的入口。
* scale 由模块数反推,让不同版本(21–177 模块)渲染出来都落在接近的像素尺寸上。
*/
const lanQrSvg = computed(() => {
const first = lanLinks.value[0]
if (first === undefined) return null
const size = encodeQr(first.url).size
const scale = Math.max(1, Math.round(QR_PIXELS / (size + QR_MARGIN * 2)))
return qrToSvg(first.url, { scale, margin: QR_MARGIN, ecc: 'M' })
})
async function refreshLan(): Promise<void> {
// 身份还没就绪时不要「把访客理由写进 lanProblem 就完事」:auth 是异步加载的,
// 挂载那一刻 readOnly 必然为 true,写死之后即使随后拿到管理员身份也没有东西再触发本函数
// —— 卡片会永远停在「只读访客」,接口一次都不会被请求(真机深链进本页必现)。
// 这里的职责只有「能不能读」;读不了就清空状态,等 watch 在身份就绪后重跑。
if (lanGateReason.value !== null) {
lanInfo.value = null
lanProblem.value = null
return
}
try {
lanInfo.value = await adminApi.systemNetwork()
lanProblem.value = null
} catch (caught) {
// 403 是权限边界,其余是服务端没给答案;两者在现场要做的事完全不同,不能合成一句。
lanInfo.value = null
lanProblem.value =
caught instanceof ApiError && caught.code === 'FORBIDDEN'
? '当前账号没有查看权限,请先登录(该接口需要录入员及以上)。'
: `读不到局域网地址:${caught instanceof Error ? caught.message : '未知错误'}`
}
}
async function copyLanUrl(url: string): Promise<void> {
// 面板多半是从 http://192.168.x.x 打开的,那里 navigator.clipboard 是 undefined,
// copyText 会自己退到 execCommand,这里只负责把结果反馈给操作员。
const copied = await copyText(url)
if (!copied) {
toast.error('复制失败', '浏览器不允许自动复制,请手动选中地址复制')
return
}
copiedUrl.value = url
if (copiedTimer !== null) clearTimeout(copiedTimer)
copiedTimer = setTimeout(() => {
copiedUrl.value = null
copiedTimer = null
}, 1500)
}
onMounted(() => {
void loadDisplays()
void refreshSettings()
void refreshLive()
void refreshInstances()
void refreshLan()
// 身份是异步加载的:挂载那一刻 readOnly 必然为 true,卡片只能先显示「只读访客」。
// 等身份落定(gate 变成 null)必须**主动重跑一次**,否则这张卡会永远停在访客态、
// 接口一次都不请求 —— 真机深链进本页必现(2026-09-12 用真 Chromium 复现)。
watch(lanGateReason, (reason) => {
if (reason === null) void refreshLan()
})
startPolling()
document.addEventListener('visibilitychange', onVisibilityChange)
})
onBeforeUnmount(() => {
stopPolling()
if (copiedTimer !== null) {
clearTimeout(copiedTimer)
copiedTimer = null
}
document.removeEventListener('visibilitychange', onVisibilityChange)
})
@@ -804,69 +904,117 @@ async function send(
</section>
</div>
<section class="mx-card">
<div class="mx-card-head">
<span class="mx-card-title">在线大屏</span>
<span class="mx-badge" :class="onlineCount > 0 ? 'mx-badge-success' : 'mx-badge-neutral'">
{{ onlineCount }} / {{ instances.length }} 在线
</span>
</div>
<div class="mx-card-body">
<div v-if="instancesError !== null" class="board-note">
<MxIcon name="warning" :size="14" />
<span>读取在线大屏失败:{{ instancesError }}</span>
<div class="col">
<section class="mx-card">
<div class="mx-card-head">
<span class="mx-card-title">局域网大屏</span>
<MockBadge v-if="data.isMock" />
<span v-else-if="lanLinks.length > 0" class="mx-badge mx-badge-neutral">
{{ lanLinks.length }} 个可用地址
</span>
</div>
<div class="mx-card-body">
<p class="lan-intro">在别的设备浏览器打开下面的地址,就是一块大屏。</p>
<p v-if="instances.length === 0" class="display-note">
还没有大屏上报。本机用 Console 打开的大屏窗口、以及局域网设备打开 /display 后,都会在这里出现(每 5 秒刷新一次)。
</p>
<p v-if="lanGateReason !== null" class="notice">{{ lanGateReason }}</p>
<p v-else-if="lanProblem !== null" class="notice">{{ lanProblem }}</p>
<p v-else-if="lanInfo === null" class="display-note">读取中…</p>
<p v-else-if="lanPortMissing" class="display-note">
服务端没有下发大屏端口,暂时拼不出能在别的设备打开的地址。
</p>
<div v-for="instance in instances" :key="instance.id" class="display-row">
<div class="display-meta">
<div class="display-name">
<span class="instance-id">{{ instance.id }}</span>
<span class="mx-badge" :class="instance.online ? 'mx-badge-success' : 'mx-badge-error'">
{{ instance.online ? '在线' : '离线' }}
</span>
<span v-if="instance.slow" class="mx-badge mx-badge-warning">落后</span>
<span class="mx-badge mx-badge-neutral">
{{ instance.screen === '' ? '局域网浏览器' : `屏 ${instance.screen}` }}
</span>
<template v-else-if="lanLinks.length > 0">
<div v-for="(item, index) in lanLinks" :key="item.ip" class="lan-row">
<div class="lan-line">
<a class="lan-link" :href="item.url" target="_blank" rel="noopener">{{ item.url }}</a>
<button class="mx-btn mx-btn-secondary mx-btn-sm" type="button" @click="copyLanUrl(item.url)">
<MxIcon :name="copiedUrl === item.url ? 'check' : 'copy'" :size="14" />
{{ copiedUrl === item.url ? '已复制' : '复制' }}
</button>
</div>
<div v-if="index === 0 && lanQrSvg !== null" class="lan-qr">
<!--
内容是自家编码器产出的 SVG 字符串(路径全是数字坐标、aria 里的文本已转义),
不是用户输入;用它换掉几百个 <rect>,卡片首屏才不会被二维码拖慢。
-->
<div class="lan-qr-code" v-html="lanQrSvg"></div>
<div class="lan-qr-note">手机扫码直接打开</div>
</div>
</div>
<div class="display-sub">
当前页:{{ instance.page === '' ? '未上报' : pageLabel(instance.page) }} · 来源:{{ instance.remoteAddr === '' ? '未知' : instance.remoteAddr }}
</div>
<div class="display-sub">最后心跳:{{ formatDateTime(instance.lastHeartbeat) }}</div>
<div v-if="!instance.online" class="display-sub">已离线:指令发不到它,等大屏重新连上再切页。</div>
</template>
<p v-else class="display-note">未检测到局域网地址(可能是没插网线 / 只有回环)。</p>
<p class="hint">
地址由服务端下发的端口与路径拼成;平板上打开后不必登录,大屏本身是只读的。
</p>
</div>
</section>
<section class="mx-card">
<div class="mx-card-head">
<span class="mx-card-title">在线大屏</span>
<span class="mx-badge" :class="onlineCount > 0 ? 'mx-badge-success' : 'mx-badge-neutral'">
{{ onlineCount }} / {{ instances.length }} 在线
</span>
</div>
<div class="mx-card-body">
<div v-if="instancesError !== null" class="board-note">
<MxIcon name="warning" :size="14" />
<span>读取在线大屏失败:{{ instancesError }}</span>
</div>
<div class="display-actions">
<select
class="mx-cell-input instance-page-select"
:value="draftFor(`instance:${instance.id}`, instance.page)"
:disabled="!canWrite || !instance.online || targetPending !== null"
@change="pickPage(`instance:${instance.id}`, $event)"
>
<option v-for="page in DISPLAY_PAGES" :key="page.key" :value="page.key">{{ page.title }}</option>
</select>
<button
class="mx-btn mx-btn-primary mx-btn-sm"
type="button"
:disabled="!canWrite || !instance.online || targetPending !== null"
@click="gotoInstance(instance)"
>
{{ targetPending === `instance:${instance.id}` ? '下发中…' : '切到此页' }}
</button>
<p v-if="instances.length === 0" class="display-note">
还没有大屏上报。本机用 Console 打开的大屏窗口、以及局域网设备打开 /display 后,都会在这里出现(每 5 秒刷新一次)。
</p>
<div v-for="instance in instances" :key="instance.id" class="display-row">
<div class="display-meta">
<div class="display-name">
<span class="instance-id">{{ instance.id }}</span>
<span class="mx-badge" :class="instance.online ? 'mx-badge-success' : 'mx-badge-error'">
{{ instance.online ? '在线' : '离线' }}
</span>
<span v-if="instance.slow" class="mx-badge mx-badge-warning">落后</span>
<span class="mx-badge mx-badge-neutral">
{{ instance.screen === '' ? '局域网浏览器' : `屏 ${instance.screen}` }}
</span>
</div>
<div class="display-sub">
当前页:{{ instance.page === '' ? '未上报' : pageLabel(instance.page) }} · 来源:{{ instance.remoteAddr === '' ? '未知' : instance.remoteAddr }}
</div>
<div class="display-sub">最后心跳:{{ formatDateTime(instance.lastHeartbeat) }}</div>
<div v-if="!instance.online" class="display-sub">已离线:指令发不到它,等大屏重新连上再切页。</div>
</div>
<div class="display-actions">
<select
class="mx-cell-input instance-page-select"
:value="draftFor(`instance:${instance.id}`, instance.page)"
:disabled="!canWrite || !instance.online || targetPending !== null"
@change="pickPage(`instance:${instance.id}`, $event)"
>
<option v-for="page in DISPLAY_PAGES" :key="page.key" :value="page.key">{{ page.title }}</option>
</select>
<button
class="mx-btn mx-btn-primary mx-btn-sm"
type="button"
:disabled="!canWrite || !instance.online || targetPending !== null"
@click="gotoInstance(instance)"
>
{{ targetPending === `instance:${instance.id}` ? '下发中…' : '切到此页' }}
</button>
</div>
</div>
<div class="board-hint">
<p>当前状态:{{ locked ? '已锁定' : '自动轮播' }} · 全部大屏页面 {{ pageLabel(currentPage) }}</p>
<p v-if="instancesUpdatedAt !== null" class="muted">最近一次刷新:{{ formatDateTime(instancesUpdatedAt) }}</p>
<p class="muted">「落后」= 该实例确认的版本落后(大屏可能在卡或网络差);离线实例会在服务端保留一段时间,便于排查。</p>
<p v-if="data.isMock" class="mock">示例数据模式下指令不会真正下发到大屏。</p>
</div>
</div>
<div class="board-hint">
<p>当前状态:{{ locked ? '已锁定' : '自动轮播' }} · 全部大屏页面 {{ pageLabel(currentPage) }}</p>
<p v-if="instancesUpdatedAt !== null" class="muted">最近一次刷新:{{ formatDateTime(instancesUpdatedAt) }}</p>
<p class="muted">「落后」= 该实例确认的版本落后(大屏可能在卡或网络差);离线实例会在服务端保留一段时间,便于排查。</p>
<p v-if="data.isMock" class="mock">示例数据模式下指令不会真正下发到大屏。</p>
</div>
</div>
</section>
</section>
</div>
</div>
</div>
</template>
@@ -943,6 +1091,53 @@ async function send(
background: var(--mx-s3);
margin-bottom: 12px;
}
.lan-intro {
font-size: 12px;
color: var(--mx-t3);
line-height: 1.6;
margin-bottom: 12px;
}
.lan-row {
padding: 10px 12px;
border-radius: var(--mx-r-sm);
background: var(--mx-s3);
}
.lan-row + .lan-row {
margin-top: 8px;
}
.lan-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.lan-link {
flex: 1;
min-width: 0;
font-family: var(--mx-mono);
font-size: 13px;
color: var(--mx-primary);
/* 地址是机器串出来的,窄栏里要能折行,不能把「复制」按钮顶出卡片。 */
overflow-wrap: anywhere;
}
.lan-qr {
margin-top: 10px;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
}
.lan-qr-code {
/* 二维码自带白底留出静区,和卡片底色隔开,避免深色主题下扫不出来。 */
line-height: 0;
padding: 6px;
border-radius: var(--mx-r-xs);
background: #fff;
}
.lan-qr-note {
font-size: 12px;
color: var(--mx-t3);
}
.textarea-wrap {
height: auto;
align-items: flex-start;
+102
View File
@@ -0,0 +1,102 @@
import type { NetworkAddress, NetworkInfo } from '@/shared'
/**
* 「局域网大屏」卡片的纯逻辑。
*
* 抽出来是因为这两件事都没法在组件里测:地址要靠服务端下发的 port / displayPath 拼
* (不能写死),复制要在 `navigator.clipboard` 不存在的老式上下文里退回 execCommand。
* 现场面板正是从 `http://192.168.x.x:<端口>` 这种裸 HTTP 地址打开的——**非安全上下文里
* clipboard 是 undefined**,所以回退不是兼容性洁癖,而是这条路径的常态。
*/
export interface LanDisplayLink {
ip: string
/** 完整地址:`http://<ip>:<port><displayPath>`。 */
url: string
}
/** 拼一条局域网大屏地址;IPv6 要加方括号,否则端口那一段会被当成地址的一部分。 */
export function displayUrl(address: NetworkAddress, network: NetworkInfo): string {
const host = address.ip.includes(':') ? `[${address.ip}]` : address.ip
return `http://${host}:${network.port}${network.displayPath}`
}
/**
* 把服务端返回的网络信息摊平成可点的链接。
*
* 端口缺失(服务端异常 / 老版本接口)时给空数组:拼 `http://ip:0/display` 这种
* 「看着像链接、点开连不上」的东西比空态更糟。
*/
export function lanDisplayLinks(network: NetworkInfo): LanDisplayLink[] {
if (!Number.isFinite(network.port) || network.port <= 0) return []
return network.addresses.map((address) => ({ ip: address.ip, url: displayUrl(address, network) }))
}
/** 复制用到的宿主能力;全部可注入,这样在 node 里也能把回退路径走一遍。 */
export interface CopyDeps {
/** 默认取 `navigator.clipboard`;非安全上下文下它本身就不存在。 */
clipboard?: { writeText?: (text: string) => Promise<void> } | null
/** 默认走「临时 textarea + document.execCommand('copy')」。 */
legacyCopy?: (text: string) => boolean
}
interface ClipboardLike {
writeText?: (text: string) => Promise<void>
}
function navigatorClipboard(): ClipboardLike | null {
const nav = (globalThis as { navigator?: { clipboard?: ClipboardLike } }).navigator
return nav?.clipboard ?? null
}
/**
* 优先用异步剪贴板 API,失败或不存在时退回 execCommand。
*
* 两个坑:一是非安全上下文里 `navigator.clipboard` 直接是 `undefined`(不是抛错),
* 二是即便存在,用户拒绝授权 / 文档失焦时 `writeText` 也会 reject——两种都要落到回退,
* 而不是把「没复制成功」当成已复制提示给操作员。
*/
export async function copyText(text: string, deps: CopyDeps = {}): Promise<boolean> {
const clipboard = 'clipboard' in deps ? deps.clipboard : navigatorClipboard()
if (typeof clipboard?.writeText === 'function') {
try {
await clipboard.writeText(text)
return true
} catch {
// 落到下面的回退
}
}
const fallback = deps.legacyCopy ?? legacyExecCopy
try {
return fallback(text)
} catch {
return false
}
}
/** 老式回退:造一个隐身 textarea 选中再 execCommand('copy')。 */
function legacyExecCopy(text: string): boolean {
const doc = (globalThis as { document?: Document }).document
if (doc === undefined || doc.body === null || typeof doc.execCommand !== 'function') return false
const area = doc.createElement('textarea')
area.value = text
// aria-hidden + 定位到视口外 + 透明:既不改变布局,也不让移动端弹键盘。
area.setAttribute('aria-hidden', 'true')
area.style.position = 'fixed'
area.style.top = '0'
area.style.left = '0'
area.style.opacity = '0'
area.style.pointerEvents = 'none'
doc.body.appendChild(area)
try {
area.focus()
area.select()
area.setSelectionRange(0, area.value.length)
return doc.execCommand('copy')
} finally {
// 无论成败都要摘掉临时节点:否则每点一次复制就在 body 里留一个隐身 textarea。
area.remove()
}
}
@@ -0,0 +1,123 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
/**
* 「局域网大屏」卡片的接线与文案。
*
* 组件本身没有 DOM 测试环境(仓库里只有「纯函数 + 源码断言」这一套),所以这里钉两件事:
* 卡片必须出现的那几句原文,以及它只从 `adminApi.systemNetwork()` 拿地址——
* 现场端口/路径改过时,页面里任何写死的 `19540` / `http://…/display` 都会生成一条假链接。
*/
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
let reply: () => Response = () => jsonResponse({ ok: true, data: null })
// 必须在导入被测模块之前装好:ApiClient 构造时就把当时的 fetch 绑进实例。
globalThis.fetch = (async () => reply()) as typeof fetch
function respondWith(response: () => Response): void {
reply = response
}
const { ApiError, adminApi } = await import('../api/client')
const PAGE = readFileSync(new URL('../pages/DisplayPage.vue', import.meta.url), 'utf8')
test('卡片文案齐全:标题、一句话说明、复制反馈、扫码说明、空态', () => {
assert.match(PAGE, /局域网大屏/)
assert.match(PAGE, /在别的设备浏览器打开下面的地址,就是一块大屏/)
assert.match(PAGE, /手机扫码直接打开/)
assert.match(PAGE, /已复制/)
assert.match(PAGE, /未检测到局域网地址(可能是没插网线 \/ 只有回环)/)
})
test('链接本身就是可点的新窗口链接', () => {
assert.match(PAGE, /<a class="lan-link" :href="item\.url" target="_blank" rel="noopener">/)
})
test('页面的地址只来自 lanDisplayLinks(),不写死端口或路径', () => {
assert.match(PAGE, /import \{ copyText, lanDisplayLinks \} from '\.\/lanDisplay'/)
assert.match(PAGE, /lanDisplayLinks\(lanInfo\.value\)/)
// 19540 一旦出现在页面里,就说明有人在拼地址时替服务端做了决定。
assert.doesNotMatch(PAGE, /19540/)
})
test('二维码只给第一个地址,且用的是矢量 SVG', () => {
assert.match(PAGE, /v-if="index === 0 && lanQrSvg !== null"/)
assert.match(PAGE, /import \{ encodeQr, qrToSvg \} from '@\/shared\/qrcode'/)
assert.match(PAGE, /qrToSvg\(first\.url, \{ scale, margin: QR_MARGIN, ecc: 'M' \}\)/)
})
test('复制按钮走 copyText(含非安全上下文回退),失败有提示', () => {
assert.match(PAGE, /await copyText\(url\)/)
assert.match(PAGE, /toast\.error\('复制失败'/)
})
test('访客按只读说明拦住,不整页报错', () => {
assert.match(PAGE, /只有登录后的录入员 \/ 管理员能查看局域网地址,当前为只读访客。/)
// 提示必须由 computed 直接渲染:写成「挂载时把它复制进一个 ref」会在身份就绪后永远不清
// (2026-09-12 真浏览器复现:管理员登录后卡片仍停在访客态,接口一次都没请求)。
assert.match(PAGE, /<p v-if="lanGateReason !== null" class="notice">/)
})
test('接口不可用时卡片给说明,页面照常渲染其它卡片', () => {
assert.match(PAGE, /读不到局域网地址:/)
// 读失败不能清空其它区域;卡片自己的提示条与在线大屏的提示条是两条独立通路。
assert.match(PAGE, /lanProblem\.value =/)
})
test('systemNetwork:403 不降级成示例地址', async () => {
respondWith(() =>
jsonResponse({ ok: false, error: { code: 'FORBIDDEN', message: '需要录入员及以上权限' } }, 403),
)
await assert.rejects(
() => adminApi.systemNetwork(),
(error: unknown) => {
assert.ok(error instanceof ApiError)
assert.equal(error.code, 'FORBIDDEN')
return true
},
)
})
test('systemNetwork:后端连不上时给示例地址,让示例模式也能看到卡片', async () => {
respondWith(() => {
throw new TypeError('fetch failed')
})
const info = await adminApi.systemNetwork()
assert.equal(info.port, 19540)
assert.equal(info.displayPath, '/display')
assert.ok(info.addresses.length > 0)
// 示例地址必须是私有段,不能是回环或公网地址。
for (const address of info.addresses) {
assert.match(address.ip, /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/)
}
})
test('systemNetwork:接口存在时按服务端下发的端口与路径透传', async () => {
respondWith(() =>
jsonResponse({
ok: true,
data: {
port: 8080,
displayPath: '/screen',
adminPath: '/admin',
addresses: [{ ip: '192.168.1.23', interface: 'eth0', family: 'ipv4' }],
},
}),
)
const info = await adminApi.systemNetwork()
assert.equal(info.port, 8080)
assert.equal(info.displayPath, '/screen')
})
@@ -0,0 +1,38 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
/**
* 「局域网大屏」卡片的加载时机回归钉子。
*
* 真事故(2026-09-12 用真 Chromium + 真服务端复现):`refreshLan()` 在挂载时跑,
* 而 `auth` 是**异步**加载的 —— 那一刻 `auth.readOnly` 必然为 true,于是卡片把
* 「当前为只读访客」写进 `lanProblem` 这个**普通 ref** 就返回了;等身份落定后
* 没有任何东西再触发它,结果:
* - 卡片永远停在访客态(管理员登录后也一样);
* - `/api/system/network` **一次都没被请求**。
* 页面级测试在仓库里跑不起来(没有 jsdom / @vue/test-utils),所以这里退化成源码断言:
* 钉住「gate 由 computed 直接渲染」+「gate 变 null 时会重跑加载」这两件事,
* 防止以后重构又把它改回「写死进 ref 就完事」。
*/
const SOURCE = readFileSync(new URL('../pages/DisplayPage.vue', import.meta.url), 'utf8')
test('访客提示直接由 computed 渲染,不从 ref 里读(否则身份就绪后不会消失)', () => {
assert.match(SOURCE, /<p v-if="lanGateReason !== null" class="notice">/, 'gate 必须直接绑 computed')
assert.match(SOURCE, /const lanGateReason = computed\(/, 'gate 必须是 computed')
// 反面:把 gate 写进 lanProblem 后就 return,是本事故的写法
assert.doesNotMatch(
SOURCE,
/lanProblem\.value = lanGateReason\.value/,
'不允许把 gate 写进 lanProblem:那是个普通 ref,身份就绪后不会自己清掉',
)
})
test('身份就绪(gate 变 null)时必须重跑一次加载', () => {
assert.match(SOURCE, /watch\(lanGateReason,/, '必须 watch gate')
assert.match(
SOURCE,
/watch\(lanGateReason,[\s\S]{0,200}?refreshLan\(\)/,
'watch 的回调里必须调用 refreshLan(),否则接口永远不会被请求',
)
})
+133
View File
@@ -0,0 +1,133 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import type { NetworkInfo } from '@/shared'
import { copyText, displayUrl, lanDisplayLinks } from '../pages/lanDisplay'
/**
* 「局域网大屏」卡片的两条硬要求:
* 1. 地址完全由服务端下发的 port / displayPath 拼出来——现场端口或路径改过时,
* 前端写死的那个数会安静地生成一条打不开的链接;
* 2. 复制在非安全上下文里也得成功。面板就是从 `http://192.168.x.x:19540` 打开的,
* 那里 `navigator.clipboard` 是 undefined,必须退到 execCommand + 临时 textarea。
*/
const NETWORK: NetworkInfo = {
port: 19540,
displayPath: '/display',
adminPath: '/admin',
addresses: [
{ ip: '192.168.1.23', interface: 'eth0', family: 'ipv4' },
{ ip: '10.0.8.7', interface: 'wlan0', family: 'ipv4' },
],
}
test('地址用服务端下发的端口与路径拼,不写死 19540 / /display', () => {
assert.equal(displayUrl(NETWORK.addresses[0]!, NETWORK), 'http://192.168.1.23:19540/display')
// 换个端口与路径,拼出来必须跟着变。
const custom: NetworkInfo = { ...NETWORK, port: 8080, displayPath: '/screen' }
assert.equal(displayUrl(custom.addresses[0]!, custom), 'http://192.168.1.23:8080/screen')
assert.deepEqual(
lanDisplayLinks(custom).map((link) => link.url),
['http://192.168.1.23:8080/screen', 'http://10.0.8.7:8080/screen'],
)
})
test('IPv6 地址加方括号,否则端口会被当成地址的一部分', () => {
const info: NetworkInfo = { ...NETWORK, addresses: [{ ip: 'fe80::1', interface: 'eth0', family: 'ipv6' }] }
assert.equal(displayUrl(info.addresses[0]!, info), 'http://[fe80::1]:19540/display')
})
test('每个地址都摊成一条链接,顺序与服务端一致', () => {
const links = lanDisplayLinks(NETWORK)
assert.deepEqual(
links.map((link) => link.ip),
['192.168.1.23', '10.0.8.7'],
)
})
test('没地址时给空数组(页面据此显示空态)', () => {
assert.deepEqual(lanDisplayLinks({ ...NETWORK, addresses: [] }), [])
})
test('端口为 0 时给空数组,不拼 http://ip:0/display 这种点不开的链接', () => {
assert.deepEqual(lanDisplayLinks({ ...NETWORK, port: 0 }), [])
})
test('复制:navigator.clipboard 不存在时走到 execCommand 回退', async () => {
const seen: string[] = []
const ok = await copyText('http://192.168.1.23:19540/display', {
clipboard: null, // 非安全上下文里就是这个值
legacyCopy: (text) => {
seen.push(text)
return true
},
})
assert.equal(ok, true)
assert.deepEqual(seen, ['http://192.168.1.23:19540/display'])
})
test('复制:clipboard 存在但被拒绝(writeText reject)时也走到回退', async () => {
let legacyCalls = 0
const ok = await copyText('addr', {
clipboard: {
writeText: () => Promise.reject(new Error('NotAllowedError')),
},
legacyCopy: () => {
legacyCalls++
return true
},
})
assert.equal(ok, true)
assert.equal(legacyCalls, 1)
})
test('复制:clipboard 成功时不该再走回退', async () => {
const written: string[] = []
let legacyCalls = 0
const ok = await copyText('addr', {
clipboard: {
writeText: async (text) => {
written.push(text)
},
},
legacyCopy: () => {
legacyCalls++
return true
},
})
assert.equal(ok, true)
assert.deepEqual(written, ['addr'])
assert.equal(legacyCalls, 0)
})
test('复制:两条路都不通时返回 false,不谎报成功', async () => {
assert.equal(await copyText('addr', { clipboard: null, legacyCopy: () => false }), false)
assert.equal(
await copyText('addr', {
clipboard: null,
legacyCopy: () => {
throw new Error('document.execCommand is not a function')
},
}),
false,
)
// node 里既没有 navigator.clipboard 也没有 document:不能抛异常。
assert.equal(await copyText('addr', { clipboard: null }), false)
})
const SOURCE = readFileSync(new URL('../pages/lanDisplay.ts', import.meta.url), 'utf8')
test('回退实现真的用临时 textarea + execCommand,并且会把 DOM 清理干净', () => {
assert.match(SOURCE, /doc\.execCommand\('copy'\)/)
assert.match(SOURCE, /doc\.createElement\('textarea'\)/)
assert.match(SOURCE, /doc\.body\.appendChild\(area\)/)
// 不摘掉临时节点,每点一次复制就在 body 里留一个隐身 textarea。
assert.match(SOURCE, /finally \{[\s\S]*area\.remove\(\)/)
// 先 clipboard 后回退的顺序不能反:优先走异步剪贴板,失败才退。
assert.match(SOURCE, /await clipboard\.writeText\(text\)/)
})
+50 -1
View File
@@ -1,4 +1,4 @@
import { isRawBody, isRecord, readString } from './internal'
import { firstNumberOrNull, isRawBody, isRecord, readString } from './internal'
import { normalizeRulePack } from './rules'
import { readTeamRanksView, readTeamRanksViews } from './teamRanks'
import { parseYaml } from './yaml'
@@ -26,6 +26,8 @@ import type {
HealthInfo,
ImportConflictDecision,
LiveEvents,
NetworkAddress,
NetworkInfo,
Page,
PageQuery,
PointAdjustment,
@@ -433,6 +435,13 @@ export interface SystemApi {
* 不能像普通写操作那样立刻认为已经生效(与切换赛事同一套等待逻辑)。
*/
restore(input: BackupRestoreInput): Promise<BackupRestoreResult>
/**
* 本机局域网地址(`GET /api/system/network`,recorder 及以上可读)。
*
* 交给大屏控制页拼「局域网大屏」地址用;访客请求会吃 403,调用方按权限不足处理。
*/
network(): Promise<NetworkInfo>
}
/**
@@ -703,6 +712,44 @@ function readProjectInfo(value: unknown): ProjectInfo | null {
}
}
function readNetworkAddress(value: unknown): NetworkAddress | null {
if (!isRecord(value)) return null
const ip = readString(value, 'ip')
// 没有 ip 的行拼不出地址,留着只会在卡片上多出一条空链接。
if (ip === null || ip === '') return null
return {
ip,
interface: readString(value, 'interface') ?? '',
family: readString(value, 'family') ?? 'ipv4',
}
}
/**
* 归一化 `GET /api/system/network`。
*
* 端口/路径是拼地址的原料,前端不替服务端猜:缺端口就留 0,由页面判断「读不到可用地址」
* 并给说明——编一个默认端口出来会得到一条看着对、实际打不开的链接。
* addresses 不是数组时按「没检测到地址」处理,交给页面显示空态。
*/
function readNetworkInfo(value: unknown): NetworkInfo {
const port = firstNumberOrNull(isRecord(value) ? value['port'] : null)
const rawAddresses = isRecord(value) && Array.isArray(value['addresses']) ? value['addresses'] : []
return {
port: port !== null && port > 0 ? Math.floor(port) : 0,
displayPath: normalizePath(readString(value, 'displayPath'), '/display'),
adminPath: normalizePath(readString(value, 'adminPath'), '/admin'),
addresses: rawAddresses
.map(readNetworkAddress)
.filter((item): item is NetworkAddress => item !== null),
}
}
/** 服务端没给路径时退回约定值;补前导斜杠,免得拼出 `http://ip:portdisplay`。 */
function normalizePath(value: string | null, fallback: string): string {
const path = value === null || value.trim() === '' ? fallback : value.trim()
return path.startsWith('/') ? path : `/${path}`
}
function createProjectsApi(http: Http): ProjectsApi {
return {
list: async () => {
@@ -904,6 +951,8 @@ export class ApiClient {
body: input,
timeoutMs: RESTORE_TIMEOUT_MS,
}),
// request() 会把 {ok,data} 拆开,这里拿到的是 data 本体,再按字段归一化。
network: async () => readNetworkInfo(await http.request<unknown>('/system/network')),
}
this.projects = createProjectsApi(http)
+549
View File
@@ -0,0 +1,549 @@
/**
* 纯 TypeScript 二维码编码器(字节模式 / UTF-8),零依赖。
*
* 为什么自己写:现场是离线局域网,装不了 npm 包;而「局域网大屏」卡片要的是一个
* 能扫的矢量码,不是一张贴图。实现按 ISO/IEC 18004 走:字节模式、1–40 版自动选版、
* L/M/Q/H 四档纠错、8 种掩码按惩罚分择优,最后输出模块矩阵,可渲染成任意尺寸的 SVG。
*
* 对外只暴露两件事:`encodeQr`(要矩阵)与 `qrToSvg`(要能直接塞进卡片的字符串)。
*/
/** 纠错级别:L≈7% / M≈15% / Q≈25% / H≈30% 的码字可被恢复。 */
export type QrEcc = 'L' | 'M' | 'Q' | 'H'
export interface QrEncodeOptions {
/** 纠错级别,默认 M:屏幕扫码距离近、容错够用,容量也不至于太小。 */
ecc?: QrEcc
/**
* 最低版本(1–40)。默认 1。
*
* 保留给「同一张卡片上多个码尺寸要一致」这类排版需求;正常情况下让它自动选版。
*/
minVersion?: number
}
export interface QrMatrix {
/** 二维码版本 1–40,边长 = version * 4 + 17。 */
version: number
/** 边长(模块数,不含静区)。 */
size: number
ecc: QrEcc
/** 模块矩阵:`modules[y][x]` 为 true 表示深色。不含静区。 */
modules: boolean[][]
}
export interface QrSvgOptions extends QrEncodeOptions {
/** 每个模块占多少像素(SVG 用户单位),默认 4。矢量渲染,放大不糊。 */
scale?: number
/** 静区宽度(模块数),默认 4;低于 4 会显著影响识别率。 */
margin?: number
}
export const ECC_LEVELS: readonly QrEcc[] = ['L', 'M', 'Q', 'H']
/** 版本 1–40 的字节模式容量表(数据码字数、可容纳字节数),由下面的表推出,仅用于报错信息。 */
const MIN_VERSION = 1
const MAX_VERSION = 40
const MODE_BYTE = 0x4
const PENALTY_N1 = 3
const PENALTY_N2 = 3
const PENALTY_N3 = 40
const PENALTY_N4 = 10
// ── 规格表(ISO/IEC 18004 表 9 与表 13–22) ─────────────────────────────────
// 下标是版本号,[0] 是占位 -1。行序与 ECC_LEVELS 一致:L / M / Q / H。
const ECC_CODEWORDS_PER_BLOCK: readonly (readonly number[])[] = [
// L
[-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
// M
[-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
// Q
[-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
// H
[-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
]
const NUM_ERROR_CORRECTION_BLOCKS: readonly (readonly number[])[] = [
// L
[-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
// M
[-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
// Q
[-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
// H
[-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81],
]
/** 格式信息里的纠错指示位(L=01 / M=00 / Q=11 / H=10),与矩阵下标不是同一套编号。 */
const ECC_FORMAT_BITS: readonly number[] = [1, 0, 3, 2]
function eccIndex(ecc: QrEcc): number {
const index = ECC_LEVELS.indexOf(ecc)
if (index < 0) throw new RangeError(`不支持的纠错级别:${String(ecc)}`)
return index
}
function eccCodewordsPerBlock(version: number, index: number): number {
return ECC_CODEWORDS_PER_BLOCK[index]![version]!
}
function numErrorCorrectionBlocks(version: number, index: number): number {
return NUM_ERROR_CORRECTION_BLOCKS[index]![version]!
}
/**
* 该版本「不参与功能的模块」总数(位)。
*
* 由几何推算而不是查表:每加一个版本多出的定位/计时/对齐/版本信息都能用式子表达,
* 少一张 40 行的表就少一处抄错的机会。
*/
function numRawDataModules(version: number): number {
let result = (16 * version + 128) * version + 64
if (version >= 2) {
const numAlign = Math.floor(version / 7) + 2
result -= (25 * numAlign - 10) * numAlign - 55
if (version >= 7) result -= 36
}
return result
}
/** 该版本 + 纠错级别下的数据码字数(纠错码字不算)。 */
function numDataCodewords(version: number, index: number): number {
return (
Math.floor(numRawDataModules(version) / 8) -
eccCodewordsPerBlock(version, index) * numErrorCorrectionBlocks(version, index)
)
}
/** 对齐图案中心坐标;版本 1 没有对齐图案。 */
function alignmentPatternPositions(version: number): number[] {
if (version === 1) return []
const numAlign = Math.floor(version / 7) + 2
// 版本 32 的步长是规格里的特例,按公式算会得到 28 而正确值是 26。
const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (numAlign * 2 - 2)) * 2
const result = [6]
for (let pos = version * 4 + 10; result.length < numAlign; pos -= step) result.splice(1, 0, pos)
return result
}
function getBit(value: number, index: number): boolean {
return ((value >>> index) & 1) !== 0
}
// ── Reed–Solomon(GF(256),本原多项式 0x11D) ───────────────────────────────
function reedSolomonMultiply(x: number, y: number): number {
let z = 0
for (let i = 7; i >= 0; i--) {
z = (z << 1) ^ ((z >>> 7) * 0x11d)
z ^= ((y >>> i) & 1) * x
}
return z & 0xff
}
/** 生成多项式 (x - α^0)(x - α^1)…(x - α^(degree-1)) 的系数,最高次项省略。 */
function reedSolomonComputeDivisor(degree: number): Uint8Array {
const result = new Uint8Array(degree)
result[degree - 1] = 1
let root = 1
for (let i = 0; i < degree; i++) {
for (let j = 0; j < degree; j++) {
result[j] = reedSolomonMultiply(result[j]!, root)
if (j + 1 < degree) result[j] ^= result[j + 1]!
}
root = reedSolomonMultiply(root, 0x02)
}
return result
}
/** 多项式除法取余,得到该块的纠错码字。 */
function reedSolomonComputeRemainder(data: Uint8Array, divisor: Uint8Array): Uint8Array {
const result = new Uint8Array(divisor.length)
for (const byte of data) {
const factor = byte ^ result[0]!
result.copyWithin(0, 1)
result[result.length - 1] = 0
for (let i = 0; i < divisor.length; i++) {
result[i] ^= reedSolomonMultiply(divisor[i]!, factor)
}
}
return result
}
// ── 数据码字 ────────────────────────────────────────────────────────────────
/** 字节模式字符计数指示符的位宽:版本 1–9 是 8 位,10–40 是 16 位。 */
function byteCountBits(version: number): number {
return version <= 9 ? 8 : 16
}
/** 该版本 + 级别下能装下的最大字节数。 */
function byteCapacity(version: number, index: number): number {
const bits = numDataCodewords(version, index) * 8 - 4 - byteCountBits(version)
return Math.max(0, Math.floor(bits / 8))
}
function chooseVersion(byteLength: number, index: number, minVersion: number): number {
const start = Math.max(MIN_VERSION, Math.min(MAX_VERSION, Math.floor(minVersion)))
for (let version = start; version <= MAX_VERSION; version++) {
if (byteLength <= byteCapacity(version, index)) return version
}
throw new RangeError(
`内容过长:${byteLength} 字节超出 ${ECC_LEVELS[index]} 级第 ${MAX_VERSION} 版的容量(${byteCapacity(MAX_VERSION, index)} 字节)`,
)
}
/** 位流拼装:模式指示符 + 字符计数 + 数据 + 终止符 + 补齐字节(0xEC / 0x11 交替)。 */
function buildDataCodewords(bytes: Uint8Array, version: number, index: number): Uint8Array {
const capacityBits = numDataCodewords(version, index) * 8
const result: number[] = []
let accumulator = 0
let bitCount = 0
const pushBits = (value: number, count: number): void => {
for (let i = count - 1; i >= 0; i--) {
accumulator = (accumulator << 1) | ((value >>> i) & 1)
bitCount++
if (bitCount === 8) {
result.push(accumulator)
accumulator = 0
bitCount = 0
}
}
}
pushBits(MODE_BYTE, 4)
pushBits(bytes.length, byteCountBits(version))
for (const byte of bytes) pushBits(byte, 8)
// 终止符最多 4 个 0;剩余空间不足 4 位时按剩余位数补。
pushBits(0, Math.min(4, capacityBits - result.length * 8 - bitCount))
if (bitCount > 0) pushBits(0, 8 - bitCount)
for (let pad = 0xec; result.length < capacityBits / 8; pad ^= 0xec ^ 0x11) result.push(pad)
return Uint8Array.from(result)
}
/**
* 分块算纠错再交错:二维码的纠错是按块做的,读出端逐块恢复,
* 单块损坏不会报销整张码,所以块划分必须与规格表完全一致。
*/
function addEccAndInterleave(data: Uint8Array, version: number, index: number): Uint8Array {
const numBlocks = numErrorCorrectionBlocks(version, index)
const blockEccLength = eccCodewordsPerBlock(version, index)
const rawCodewords = Math.floor(numRawDataModules(version) / 8)
const numShortBlocks = numBlocks - (rawCodewords % numBlocks)
const shortBlockLength = Math.floor(rawCodewords / numBlocks)
const divisor = reedSolomonComputeDivisor(blockEccLength)
const blocks: number[][] = []
for (let i = 0, offset = 0; i < numBlocks; i++) {
const dataLength = shortBlockLength - blockEccLength + (i < numShortBlocks ? 0 : 1)
const dat = Array.from(data.subarray(offset, offset + dataLength))
offset += dataLength
const ecc = reedSolomonComputeRemainder(Uint8Array.from(dat), divisor)
// 短块补一个占位,让所有块等长,交错时再按位置跳过它。
if (i < numShortBlocks) dat.push(0)
blocks.push(dat.concat(Array.from(ecc)))
}
const result: number[] = []
for (let i = 0; i < blocks[0]!.length; i++) {
for (let j = 0; j < blocks.length; j++) {
if (i !== shortBlockLength - blockEccLength || j >= numShortBlocks) result.push(blocks[j]![i]!)
}
}
return Uint8Array.from(result)
}
// ── 掩码与惩罚分 ────────────────────────────────────────────────────────────
function maskBit(mask: number, x: number, y: number): boolean {
switch (mask) {
case 0:
return (x + y) % 2 === 0
case 1:
return y % 2 === 0
case 2:
return x % 3 === 0
case 3:
return (x + y) % 3 === 0
case 4:
return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0
case 5:
return ((x * y) % 2) + ((x * y) % 3) === 0
case 6:
return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0
default:
return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0
}
}
/** 规格里的「1:1:3:1:1 定位图案」扫描历史窗口,长度固定 7。 */
function finderPenaltyAddHistory(runLength: number, runHistory: number[], size: number): void {
// 首段深色之前没有浅色边界,补上整条静区宽度,否则开头/结尾的伪定位图案会漏判。
if (runHistory[0] === 0) runLength += size
runHistory.pop()
runHistory.unshift(runLength)
}
function finderPenaltyCountPatterns(runHistory: number[]): number {
const n = runHistory[1]!
const core = n > 0 && runHistory[2] === n && runHistory[3] === n * 3 && runHistory[4] === n && runHistory[5] === n
if (!core) return 0
return (runHistory[0]! >= n * 4 && runHistory[6]! >= n ? 1 : 0) + (runHistory[6]! >= n * 4 && runHistory[0]! >= n ? 1 : 0)
}
function finderPenaltyTerminateAndCount(currentRunColor: boolean, currentRunLength: number, runHistory: number[], size: number): number {
let length = currentRunLength
if (currentRunColor) {
finderPenaltyAddHistory(length, runHistory, size)
length = 0
}
length += size // 末尾补静区宽度的浅色
finderPenaltyAddHistory(length, runHistory, size)
return finderPenaltyCountPatterns(runHistory)
}
function penaltyScore(modules: boolean[][], size: number): number {
let result = 0
const scoreLine = (get: (i: number) => boolean): void => {
let runColor = false
let runLength = 0
const runHistory = [0, 0, 0, 0, 0, 0, 0]
for (let i = 0; i < size; i++) {
if (get(i) === runColor) {
runLength++
if (runLength === 5) result += PENALTY_N1
else if (runLength > 5) result++
} else {
finderPenaltyAddHistory(runLength, runHistory, size)
if (!runColor) result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3
runColor = get(i)
runLength = 1
}
}
result += finderPenaltyTerminateAndCount(runColor, runLength, runHistory, size) * PENALTY_N3
}
for (let y = 0; y < size; y++) scoreLine((x) => modules[y]![x]!)
for (let x = 0; x < size; x++) scoreLine((y) => modules[y]![x]!)
// 2×2 同色块
for (let y = 0; y < size - 1; y++) {
for (let x = 0; x < size - 1; x++) {
const color = modules[y]![x]!
if (color === modules[y]![x + 1] && color === modules[y + 1]![x] && color === modules[y + 1]![x + 1]) {
result += PENALTY_N2
}
}
}
// 黑白比例偏离 50% 的惩罚
let dark = 0
for (const row of modules) for (const cell of row) if (cell) dark++
const total = size * size
const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1
return result + k * PENALTY_N4
}
// ── 矩阵构建 ────────────────────────────────────────────────────────────────
function formatBits(eccFormatBits: number, mask: number): number {
const data = (eccFormatBits << 3) | mask
let rem = data
for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537)
return ((data << 10) | rem) ^ 0x5412
}
function versionBits(version: number): number {
let rem = version
for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25)
return (version << 12) | rem
}
function buildMatrix(version: number, eccFormatBits: number, codewords: Uint8Array): boolean[][] {
const size = version * 4 + 17
const modules: boolean[][] = Array.from({ length: size }, () => new Array<boolean>(size).fill(false))
const isFunction: boolean[][] = Array.from({ length: size }, () => new Array<boolean>(size).fill(false))
const setFunction = (x: number, y: number, dark: boolean): void => {
modules[y]![x] = dark
isFunction[y]![x] = true
}
/** 定位图案连静区一起画:以中心为原点 9×9,半径 4 是分隔区(浅色)。 */
const drawFinderPattern = (centerX: number, centerY: number): void => {
for (let dy = -4; dy <= 4; dy++) {
for (let dx = -4; dx <= 4; dx++) {
const x = centerX + dx
const y = centerY + dy
if (x < 0 || x >= size || y < 0 || y >= size) continue
const distance = Math.max(Math.abs(dx), Math.abs(dy))
setFunction(x, y, distance !== 2 && distance !== 4)
}
}
}
const drawAlignmentPattern = (centerX: number, centerY: number): void => {
for (let dy = -2; dy <= 2; dy++) {
for (let dx = -2; dx <= 2; dx++) {
setFunction(centerX + dx, centerY + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1)
}
}
}
// 计时图案先画:第 6 行/列交替。三个定位图案随后覆盖它的两端,
// 顺序反了会把定位图案底边/右边那一排误刷成浅色,整张码就直接废了。
for (let i = 0; i < size; i++) {
setFunction(6, i, i % 2 === 0)
setFunction(i, 6, i % 2 === 0)
}
drawFinderPattern(3, 3)
drawFinderPattern(size - 4, 3)
drawFinderPattern(3, size - 4)
const alignments = alignmentPatternPositions(version)
const last = alignments.length - 1
for (let i = 0; i < alignments.length; i++) {
for (let j = 0; j < alignments.length; j++) {
// 三个定位图案的角上不放对齐图案
if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) continue
drawAlignmentPattern(alignments[i]!, alignments[j]!)
}
}
const drawFormat = (mask: number): void => {
const data = formatBits(eccFormatBits, mask)
for (let i = 0; i <= 5; i++) setFunction(8, i, getBit(data, i))
setFunction(8, 7, getBit(data, 6))
setFunction(8, 8, getBit(data, 7))
setFunction(7, 8, getBit(data, 8))
for (let i = 9; i < 15; i++) setFunction(14 - i, 8, getBit(data, i))
for (let i = 0; i < 8; i++) setFunction(size - 1 - i, 8, getBit(data, i))
for (let i = 8; i < 15; i++) setFunction(8, size - 15 + i, getBit(data, i))
setFunction(8, size - 8, true) // 固定的深色模块
}
// 先按掩码 0 占位,把格式信息区域标记成功能模块,数据码字才不会写进去。
drawFormat(0)
if (version >= 7) {
const bits = versionBits(version)
for (let i = 0; i < 18; i++) {
const bit = getBit(bits, i)
const a = size - 11 + (i % 3)
const b = Math.floor(i / 3)
setFunction(a, b, bit)
setFunction(b, a, bit)
}
}
// 数据码字从右下角起,每两列一组蛇形向上/向下填。
let bitIndex = 0
for (let right = size - 1; right >= 1; right -= 2) {
if (right === 6) right = 5 // 第 6 列是计时图案,跳过
for (let vert = 0; vert < size; vert++) {
for (let j = 0; j < 2; j++) {
const x = right - j
const upward = ((right + 1) & 2) === 0
const y = upward ? size - 1 - vert : vert
if (!isFunction[y]![x] && bitIndex < codewords.length * 8) {
modules[y]![x] = getBit(codewords[bitIndex >>> 3]!, 7 - (bitIndex & 7))
bitIndex++
}
}
}
}
const applyMask = (mask: number): void => {
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
if (!isFunction[y]![x] && maskBit(mask, x, y)) modules[y]![x] = !modules[y]![x]
}
}
}
let bestMask = 0
let minPenalty = Number.POSITIVE_INFINITY
for (let mask = 0; mask < 8; mask++) {
applyMask(mask)
drawFormat(mask)
const penalty = penaltyScore(modules, size)
if (penalty < minPenalty) {
bestMask = mask
minPenalty = penalty
}
applyMask(mask) // 撤销,试下一个
}
applyMask(bestMask)
drawFormat(bestMask)
return modules
}
// ── 对外接口 ────────────────────────────────────────────────────────────────
/**
* 把文本编成二维码模块矩阵(字节模式 / UTF-8),自动选版。
*
* 内容超出第 40 版容量时抛 RangeError:与其画一张扫不出来的码,不如让调用方
* 知道「这条内容放不下」(URL 场景下这几乎只会发生在误传整段文本时)。
*/
export function encodeQr(text: string, options: QrEncodeOptions = {}): QrMatrix {
const ecc = options.ecc ?? 'M'
const index = eccIndex(ecc)
const bytes = new TextEncoder().encode(text)
const version = chooseVersion(bytes.length, index, options.minVersion ?? MIN_VERSION)
const data = buildDataCodewords(bytes, version, index)
const codewords = addEccAndInterleave(data, version, index)
const modules = buildMatrix(version, ECC_FORMAT_BITS[index]!, codewords)
return { version, size: modules.length, ecc, modules }
}
/** 该纠错级别下最多能编多少个字节(第 40 版)。 */
export function qrByteCapacity(ecc: QrEcc = 'M'): number {
return byteCapacity(MAX_VERSION, eccIndex(ecc))
}
const SVG_NS = 'http://www.w3.org/2000/svg'
/** 无障碍标签里要放原文,URL 常带 `&` / 引号,不转义会把 aria-label 属性截断。 */
const XML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }
function escapeXml(text: string): string {
return text.replace(/[&<>"]/g, (ch) => XML_ESCAPES[ch]!)
}
/** 把矩阵渲染成 SVG 字符串:一个白底 `<rect>` + 一条深色 `<path>`,任意尺寸都清晰。 */
export function qrToSvg(text: string, options: QrSvgOptions = {}): string {
const scale = options.scale ?? 4
const margin = options.margin ?? 4
const matrix = encodeQr(text, options)
const dimension = matrix.size + margin * 2
let path = ''
for (let y = 0; y < matrix.size; y++) {
const row = matrix.modules[y]!
for (let x = 0; x < matrix.size; x++) {
if (row[x]) path += `M${x + margin} ${y + margin}h1v1h-1z`
}
}
return (
`<svg xmlns="${SVG_NS}" width="${dimension * scale}" height="${dimension * scale}" ` +
`viewBox="0 0 ${dimension} ${dimension}" shape-rendering="crispEdges" role="img" ` +
`aria-label="扫码打开 ${escapeXml(text)}">` +
`<rect width="${dimension}" height="${dimension}" fill="#FFFFFF"/>` +
`<path d="${path}" fill="#000000"/>` +
`</svg>`
)
}
/** 矩阵转成 `1`/`0` 逐行文本,便于测试与冻结参照比对。 */
export function qrMatrixToRows(matrix: QrMatrix): string[] {
return matrix.modules.map((row) => row.map((cell) => (cell ? '1' : '0')).join(''))
}
+94
View File
@@ -0,0 +1,94 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { ApiClient, ApiError } from '../api'
/**
* `GET /api/system/network` 的解析契约。
*
* 「局域网大屏」卡片是完全按这份数据拼地址的:端口 / 路径读错,现场拿到的就是一条
* 打不开的链接;地址行少一个字段也得当脏数据丢掉,不能渲染成空链接。
*/
function jsonResponse(data: unknown, status = 200): Response {
return new Response(JSON.stringify({ ok: true, data }), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
/** 错误响应不走 {ok,data} 包装,服务端直接回 {ok:false,error}。 */
function errorResponse(status: number, code: string, message: string): Response {
return new Response(JSON.stringify({ ok: false, error: { code, message } }), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
const NETWORK = {
port: 19540,
displayPath: '/display',
adminPath: '/admin',
addresses: [{ ip: '192.168.1.23', interface: 'eth0', family: 'ipv4' }],
}
function client(reply: () => Response): ApiClient {
return new ApiClient({ fetchImpl: async () => reply() })
}
test('network 打的是 /api/system/network,端口与路径原样透传', async () => {
let url = ''
let method: string | undefined
const api = new ApiClient({
fetchImpl: async (input, init) => {
url = String(input)
method = init?.method
return jsonResponse(NETWORK)
},
})
const info = await api.system.network()
assert.equal(url, '/api/system/network')
assert.equal(method ?? 'GET', 'GET')
assert.deepEqual(info, NETWORK)
})
test('addresses 缺失或不是数组时按「没有可用地址」处理,不是解析失败', async () => {
// 没插网线 / 只有回环时服务端就回空数组;接口本身是成功的。
assert.deepEqual((await client(() => jsonResponse({ ...NETWORK, addresses: [] })).system.network()).addresses, [])
assert.deepEqual((await client(() => jsonResponse({ port: 19540 })).system.network()).addresses, [])
// 脏数据:没有 ip 的行拼不出地址,丢掉而不是留一条空链接。
const dirty = await client(() =>
jsonResponse({ ...NETWORK, addresses: [{ interface: 'eth0' }, { ip: '', family: 'ipv4' }, 'x'] }),
).system.network()
assert.deepEqual(dirty.addresses, [])
})
test('缺端口时给 0 而不是替服务端编一个端口', async () => {
const info = await client(() => jsonResponse({ displayPath: '/display' })).system.network()
assert.equal(info.port, 0)
// 路径缺失时退回约定值,且一定带前导斜杠,否则会拼出 `...:19540display`。
assert.equal(info.displayPath, '/display')
assert.equal(info.adminPath, '/admin')
const relative = await client(() => jsonResponse({ port: 8080, displayPath: 'screen' })).system.network()
assert.equal(relative.displayPath, '/screen')
})
test('路径是空白串时退回约定值', async () => {
const info = await client(() => jsonResponse({ port: 19540, displayPath: ' ' })).system.network()
assert.equal(info.displayPath, '/display')
})
test('403 原样抛出 FORBIDDEN,不当成「没有地址」', async () => {
await assert.rejects(
() => client(() => errorResponse(403, 'FORBIDDEN', '需要录入员及以上权限')).system.network(),
(error: unknown) => {
assert.ok(error instanceof ApiError)
assert.equal(error.code, 'FORBIDDEN')
assert.equal(error.status, 403)
assert.equal(error.message, '需要录入员及以上权限')
return true
},
)
})
+386
View File
@@ -0,0 +1,386 @@
import type { QrEcc } from '../qrcode'
/**
* 冻结的二维码参照用例(由 `/tmp` 的临时脚本生成,不入库)。
*
* 每条都先用 cv2.QRCodeDetector().detectAndDecode 在 PGM 上解出原文,确认「能扫」之后
* 才把矩阵逐行钉在这里。以后改动 qrcode.ts(掩码、纠错分块、版本表…)只要矩阵变了一位,
* 这些用例就会红——矩阵哈希看不出哪里变了,逐行字符串能直接 diff 出位置。
*/
export interface FrozenQrCase {
name: string
text: string
ecc: QrEcc
version: number
size: number
rows: string[]
}
export const FROZEN_QR_CASES: FrozenQrCase[] = [
{
name: '最小码 · 单字节',
text: 'a',
ecc: 'M',
version: 1,
size: 21,
rows: [
'111111100101101111111',
'100000101011001000001',
'101110101101001011101',
'101110101011001011101',
'101110100100101011101',
'100000100011001000001',
'111111101010101111111',
'000000001100000000000',
'100000101011011001110',
'100110000001110111001',
'001011100110101100000',
'010101011001111101010',
'110100111101111111111',
'000000001100100000101',
'111111100111010011110',
'100000100010001000111',
'101110100111010011100',
'101110100101111101000',
'101110100101110111011',
'100000100011111101000',
'111111101010100100110',
],
},
{
name: '大屏链接(M)',
text: 'http://192.168.1.23:19540/display',
ecc: 'M',
version: 3,
size: 29,
rows: [
'11111110100101110100101111111',
'10000010111011110001001000001',
'10111010101101100001001011101',
'10111010001100110111001011101',
'10111010111001010101101011101',
'10000010001001100100101000001',
'11111110101010101010101111111',
'00000000000010100011100000000',
'10011111101001111111110010111',
'11011100101010100001110010110',
'00101010011000100110100010100',
'01111001101100110111000110001',
'00110010000011101010011000001',
'01100100100000000110111011011',
'10111110110100110101110001101',
'10101101001011101001101100101',
'11101011010000001000010100000',
'11001001100100010111000111110',
'11110011011011110101100100001',
'11000101001001000010101011100',
'11000011001011011101111111110',
'00000000100101010111100011000',
'11111110101001010111101011000',
'10000010110101000100100010011',
'10111010101011001001111110011',
'10111010110111111001000101101',
'10111010010010111110100010011',
'10000010011100101000001110101',
'11111110110010111000100101000',
],
},
{
name: '大屏链接(L)',
text: 'http://192.168.1.23:19540/display',
ecc: 'L',
version: 3,
size: 29,
rows: [
'11111110111101110100101111111',
'10000010000111110001001000001',
'10111010010101100001001011101',
'10111010001100110111001011101',
'10111010001111010101101011101',
'10000010010101100100101000001',
'11111110101010101010101111111',
'00000000110010100011100000000',
'11011010010011111111101000001',
'11110101001000100001110010110',
'11010110110010100110100010100',
'11101000100000110111000110001',
'01000011111001101010011000001',
'11001000101010000110111011011',
'00011110001000110101110001101',
'00100101110011101001101100101',
'00111011010110001000010100000',
'10100101011100010111000111110',
'11110011110011110101100100001',
'11101001101101000010101011100',
'11101010001101011101111111110',
'00000000110011010111100011000',
'11111110001101010111101011000',
'10000010011111000100100010011',
'10111010110111001001111110011',
'10111010100001111001000101101',
'10111010000111011110100010011',
'10000010110100001000001110101',
'11111110110000111000100101000',
],
},
{
name: '大屏链接(H)',
text: 'http://192.168.1.23:19540/display',
ecc: 'H',
version: 4,
size: 33,
rows: [
'111111100010101110011001101111111',
'100000100111110001101111101000001',
'101110100111111010011011101011101',
'101110100011010000000001001011101',
'101110101101010000101010101011101',
'100000100010011100000000101000001',
'111111101010101010101010101111111',
'000000001001000001001001000000000',
'001100111111110100101110111010000',
'110101010100000110000011111000111',
'011110110010010010111001101001101',
'100110011001001110111000100110000',
'111110101010010001000100100011001',
'000101000101100000110100010100000',
'000111100110001111010100010100000',
'111011001001010010111110110101110',
'001100100001101001000100001111101',
'100011001110101010010001001010111',
'001000111111001000101100100110110',
'010101001010001101100010001010010',
'011111101110100111011111000101101',
'110111011110010010101101001100111',
'000111101001011110100001001011101',
'011110011111011111111010110100011',
'101000111011000111100001111110011',
'000000001110011001101100100011010',
'111111101100000101111101101011110',
'100000100110111011000000100010110',
'101110100110001100101011111110101',
'101110101000111010101111010100111',
'101110101010011111101010011001100',
'100000100100110011100100111000001',
'111111100011100110100010011111100',
],
},
{
name: '中文内容',
text: '运动会积分榜',
ecc: 'M',
version: 2,
size: 25,
rows: [
'1111111001101100101111111',
'1000001010010110001000001',
'1011101000110011001011101',
'1011101001011101001011101',
'1011101010001111101011101',
'1000001000101010001000001',
'1111111010101010101111111',
'0000000001011000100000000',
'1010101001010000100010010',
'0100100101001100111011000',
'1110001100001011111000100',
'0011010100100110101110101',
'0110001011010010100110010',
'0000000111110011011110001',
'1001111100100101111011100',
'0110100010110001001011110',
'1011101010001001111110100',
'0000000010111101100011111',
'1111111000111010101010010',
'1000001000101111100011111',
'1011101010110011111110001',
'1011101001110010011011100',
'1011101010000101100000101',
'1000001001110001101100110',
'1111111011101001010110011',
],
},
{
name: '中英混排 + 链接',
text: '2026 职工运动会 · 局域网大屏 http://192.168.1.23:19540/display',
ecc: 'M',
version: 5,
size: 37,
rows: [
'1111111001110101101011010110001111111',
'1000001001111011000101101101001000001',
'1011101011011111010110100100001011101',
'1011101011000001111100001101001011101',
'1011101010001101001110110001001011101',
'1000001010000001101111011100101000001',
'1111111010101010101010101010101111111',
'0000000010001000000001101011100000000',
'1011111000011101001010101101101111100',
'1011000101010101100001110110010001110',
'0110001010011000000011000001011011101',
'0100100100110100111000110100111111001',
'1100101010001100111011011110000011101',
'0100010100111010111001011100110111010',
'1101101010101111010110000100001001101',
'0100100110001111011011110001011111001',
'0110001001110100100100101101001010101',
'1010010110010001001011111010010000110',
'0101111000110001110101001011111010101',
'0001000110010001010110001101010001000',
'1010111011000101010110100101100001101',
'1000000111010110101101011011000010010',
'0100111100011011001111011000111101111',
'0100110001000001000111011010100001001',
'0011111111001101001000100100101111111',
'1000110101111001100001011110010000110',
'1011001101000100000011101011011100101',
'1011100001111100110000100100111011011',
'1001101100011010011101001000111110100',
'0000000010000000010110100110100011010',
'1111111001001101110111111000101011011',
'1000001010110100111111001011100010101',
'1011101011101110100110100100111111111',
'1011101010000011001110011111010001001',
'1011101010110001101010100101100010011',
'1000001001000111010000100001100001001',
'1111111010110111001011001101001010111',
],
},
{
name: '版本 4 满容量边界',
text: 'http://192.168.1.23:19540/display?k=0123456',
ecc: 'M',
version: 4,
size: 33,
rows: [
'111111100001101010010111101111111',
'100000100100000110101100101000001',
'101110101110001000000111001011101',
'101110101011000100100100101011101',
'101110101101001111001010001011101',
'100000101001100000110101101000001',
'111111101010101010101010101111111',
'000000001101100010011101000000000',
'101111100001111011111001001111100',
'110110001111110011010001111101111',
'011000111000011111000010000010100',
'111100010101110101110000101011110',
'111110110010001010011110100011001',
'010011010001100100100000111101011',
'000000110001000110001010100001010',
'111110000101100100000101010101100',
'000000110111010101101000000110001',
'000001000000110010010111111101111',
'010010111110101100101100100010110',
'000000001011110110010111011011110',
'000010111001011100100101000011000',
'101000010100101110001111111100001',
'101110111010111000010100001101010',
'101111011010111010111110010100111',
'101011101011001001111000111111001',
'000000001110010011010000100010101',
'111111100011011111000011101010110',
'100000101101001011110000100010100',
'101110101001111010001110111111011',
'101110101110010100100000000111001',
'101110101100111110101010111101100',
'100000100010010100100101010110100',
'111111101110111101101000100111010',
],
},
{
name: '版本 8 满容量边界',
text: 'http://192.168.1.23:19540/display?k=0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcde',
ecc: 'M',
version: 8,
size: 49,
rows: [
'1111111001101011011010011111110010100100101111111',
'1000001000010010000110101000101111010011101000001',
'1011101010010100111011101010100111000001101011101',
'1011101011011101100001010100011100011001001011101',
'1011101011110100000111111110001111011100001011101',
'1000001011100010100010100010010111100010001000001',
'1111111010101010101010101010101010101010101111111',
'0000000010101100100110100010110011100001000000000',
'1011111000101110101110111110000101011011001111100',
'1001010111010011100001100100111100010100111010010',
'0111001110001011010001110111000111111011100001001',
'1100100100001011011101010101101111110100110111000',
'1000001010110010010100111000001001101001110000101',
'0011010111011100000001011101011100000100001000010',
'1110111101110001100100000110010001110010100010111',
'0010010010111111111001010100001101011001011111001',
'0000111011100100011110011011011000001101110000100',
'0000100100001011100001110100001101011000001010010',
'1010101101010101011110011111011000001100010101001',
'0100010010101010001001000000111010100111000010000',
'0100101000011110011110111100011101111010111000111',
'1010110010111110110001101001001011001001011011010',
'1110111111100001100101111110010110100110111110101',
'0010100010000011000000100010110011100001100011010',
'1001101011111101011111101010010100011111101010101',
'1001100010100000101000100011111000000100100010010',
'0011111111001000110100111111010111111011111110001',
'1000010001000111111111110101101111100101000011011',
'0001111011000110110001011000011000101101101010101',
'1111010001100110001111001110111010001101110101100',
'0011111000000011111010011100110011100011011101011',
'1000100101111101000110101111010000101110100001010',
'0011111010010110110110110100100111110011010110100',
'1011100011001111011000011101110010100110010000010',
'0011011100011000100011101100101111010001001111001',
'1010010101001011010000000110111011000000110100011',
'1100111110011100001110110100001101111101100110111',
'0110100000001111010001111110101101010001001000010',
'0100011111011100000000100101010110111110101101001',
'0111000101111001001000011110101011100100010101000',
'1110001010101101000111111110001101111001111110101',
'0000000011110110011000100010011110011100100010010',
'1111111000000100001111101011010011111011101011101',
'1000001011010100000011100011101110110101100011001',
'1011101011111010101101111111000001001011111110101',
'1011101011101000010000100111011110000101101111110',
'1011101011100011010101011011010001111010011000011',
'1000001001110000011000001110001101011001011000001',
'1111111011101011000111001001011000001100000001111',
],
},
{
name: '长链接',
text: 'http://192.168.100.200:65535/display',
ecc: 'M',
version: 3,
size: 29,
rows: [
'11111110010001101101101111111',
'10000010110110111001001000001',
'10111010001011101010101011101',
'10111010010101101001101011101',
'10111010110010110001101011101',
'10000010011101011011001000001',
'11111110101010101010101111111',
'00000000001101110101000000000',
'10101010001000101110000010010',
'11110100000010101110001101001',
'00101010111011001000111110111',
'01110001000110011110011101010',
'11000010010000011110001101011',
'10101101111111001110001101101',
'10110110111010101000100000011',
'00100101100011110110110011010',
'11000011011000100111101000011',
'00100100111000101110011100101',
'10101111100101000110110001011',
'01110101001110000111011101010',
'10100111001010000110111110000',
'00000000110111001110100010111',
'11111110001000100001101011011',
'10000010010101110111100011010',
'10111010101100111110111111011',
'10111010010000101001010011011',
'10111010100001101100110011101',
'10000010001101011110110001010',
'11111110110101001100111001011',
],
},
]
+164
View File
@@ -0,0 +1,164 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { ECC_LEVELS, encodeQr, qrByteCapacity, qrMatrixToRows, qrToSvg } from '../qrcode'
import type { QrEcc } from '../qrcode'
import { FROZEN_QR_CASES } from './qrcode-frozen'
/**
* 二维码编码器的规格验证。
*
* 真正确认「能扫」的是 cv2(见任务报告里逐条的解码输出);这里钉的是规格结构与几何:
* 版本↔边长、三个定位图案、静区、纠错分块随级别变化,以及一组 cv2 解过的冻结矩阵。
* 冻结矩阵一红就说明编码结果变了——那怕只差一位,也可能让现场扫码失败。
*/
/** 定位图案 7×7 的标准样子(外框 + 中心 3×3)。 */
const FINDER = ['1111111', '1000001', '1011101', '1011101', '1011101', '1000001', '1111111']
function rowsAt(matrix: boolean[][], x0: number, y0: number): string[] {
const out: string[] = []
for (let y = 0; y < 7; y++) {
let row = ''
for (let x = 0; x < 7; x++) row += matrix[y0 + y]![x0 + x] ? '1' : '0'
out.push(row)
}
return out
}
test('边长与版本一一对应(size = version * 4 + 17)', () => {
for (const text of ['a', 'http://192.168.1.23:19540/display', 'x'.repeat(200)]) {
const matrix = encodeQr(text)
assert.equal(matrix.size, matrix.version * 4 + 17)
assert.equal(matrix.modules.length, matrix.size)
assert.ok(matrix.modules.every((row) => row.length === matrix.size))
}
})
test('自动选版:更长的内容不会用更小的版本', () => {
let previous = 0
for (const length of [1, 10, 30, 60, 120, 300, 700, 1200]) {
const version = encodeQr('u'.repeat(length)).version
assert.ok(version >= previous, `长度 ${length} 选出的版本 ${version} 比上一档 ${previous} 还小`)
assert.ok(version >= 1 && version <= 40)
previous = version
}
})
test('三个角上都有标准定位图案,且周围是浅色分隔区', () => {
const matrix = encodeQr('http://192.168.1.23:19540/display')
const size = matrix.size
assert.deepEqual(rowsAt(matrix.modules, 0, 0), FINDER)
assert.deepEqual(rowsAt(matrix.modules, size - 7, 0), FINDER)
assert.deepEqual(rowsAt(matrix.modules, 0, size - 7), FINDER)
// 分隔区:定位图案外侧第 8 行/列必须是浅色,否则扫不出来。
for (let i = 0; i < 8; i++) {
assert.equal(matrix.modules[7]![i], false)
assert.equal(matrix.modules[i]![7], false)
assert.equal(matrix.modules[7]![size - 1 - i], false)
assert.equal(matrix.modules[size - 8]![i], false)
}
})
test('右下角没有定位图案(四角定位是另一种码型)', () => {
const matrix = encodeQr('http://192.168.1.23:19540/display')
const size = matrix.size
assert.notDeepEqual(rowsAt(matrix.modules, size - 7, size - 7), FINDER)
})
test('纠错级别越高,同样内容的版本不会更小', () => {
const text = 'http://192.168.1.23:19540/display'
const versions = ECC_LEVELS.map((ecc) => encodeQr(text, { ecc }).version)
for (let i = 1; i < versions.length; i++) {
assert.ok(versions[i]! >= versions[i - 1]!, `${ECC_LEVELS[i]} 的版本 ${versions[i]} 小于 ${ECC_LEVELS[i - 1]} 的 ${versions[i - 1]}`)
}
assert.equal(versions.length, 4)
})
test('M 与 L 两档都能编,且容量 M < L', () => {
assert.ok(qrByteCapacity('M') < qrByteCapacity('L'))
assert.ok(qrByteCapacity('M') > 0)
})
test('刚好塞满某版本的内容仍在那一版,再多一字节就升版', () => {
// 逐档找出「版本切换点」,确认边界两侧的版本判定刚好差一级。
for (const ecc of ['L', 'M'] as const) {
let previous = encodeQr('a', { ecc }).version
const transitions: Array<[number, number]> = []
for (let length = 2; length <= 1500 && transitions.length < 5; length++) {
const version = encodeQr('a'.repeat(length), { ecc }).version
if (version !== previous) transitions.push([length, version])
previous = version
}
assert.ok(transitions.length >= 5, `${ecc} 档没找到足够的版本切换点`)
for (const [length, version] of transitions) {
assert.equal(encodeQr('a'.repeat(length), { ecc }).version, version)
assert.equal(encodeQr('a'.repeat(length - 1), { ecc }).version, version - 1)
}
}
})
test('内容超出第 40 版容量时抛 RangeError,而不是画一张废码', () => {
const tooLong = 'x'.repeat(qrByteCapacity('M') + 1)
assert.throws(() => encodeQr(tooLong), RangeError)
})
test('UTF-8 多字节按字节计容量(中文一字 3 字节)', () => {
assert.equal(encodeQr('a').version, 1)
// 同一个版本里,中文能放的「字数」必然少于 ASCII。
const ascii = encodeQr('a'.repeat(17)).version
const chinese = encodeQr('中'.repeat(17)).version
assert.ok(chinese >= ascii)
})
test('冻结参照:cv2 解过的矩阵逐行一致', () => {
assert.equal(FROZEN_QR_CASES.length, 9)
for (const reference of FROZEN_QR_CASES) {
const matrix = encodeQr(reference.text, { ecc: reference.ecc as QrEcc })
assert.equal(matrix.version, reference.version, `${reference.name} 版本变了`)
assert.equal(matrix.size, reference.size, `${reference.name} 边长变了`)
assert.deepEqual(qrMatrixToRows(matrix), reference.rows, `${reference.name} 矩阵变了`)
}
})
test('qrToSvg:viewBox / 尺寸按规模与静区算,含白底 rect 与深色 path', () => {
const matrix = encodeQr('http://192.168.1.23:19540/display')
const svg = qrToSvg('http://192.168.1.23:19540/display', { scale: 4, margin: 4 })
const side = matrix.size + 8
assert.match(svg, /^<svg /)
assert.match(svg, /<\/svg>$/)
assert.match(svg, new RegExp(`viewBox="0 0 ${side} ${side}"`))
assert.match(svg, new RegExp(`width="${side * 4}"`))
assert.match(svg, new RegExp(`height="${side * 4}"`))
assert.match(svg, /<rect [^>]*fill="#FFFFFF"/)
assert.match(svg, /<path [^>]*fill="#000000"/)
// 深色模块数与 path 里的子路径数一一对应,不能多画也不能少画。
const dark = matrix.modules.reduce((sum, row) => sum + row.filter(Boolean).length, 0)
const segments = svg.match(/M\d+ \d+h1v1h-1z/g) ?? []
assert.equal(segments.length, dark)
})
test('qrToSvg:静区可调,默认 4;scale 只放大不改变模块数', () => {
const size = encodeQr('a').size
const defaultSvg = qrToSvg('a')
assert.match(defaultSvg, new RegExp(`viewBox="0 0 ${size + 8} ${size + 8}"`))
assert.match(defaultSvg, new RegExp(`width="${(size + 8) * 4}"`))
const tight = qrToSvg('a', { margin: 2, scale: 10 })
assert.match(tight, new RegExp(`viewBox="0 0 ${size + 4} ${size + 4}"`))
assert.match(tight, new RegExp(`width="${(size + 4) * 10}"`))
})
test('qrToSvg:SVG 里的文本按 XML 转义,不破坏属性', () => {
const svg = qrToSvg('http://x/?a=1&b="2"')
const label = svg.match(/aria-label="([^"]*)"/)?.[1] ?? ''
assert.equal(label, '扫码打开 http://x/?a=1&amp;b=&quot;2&quot;')
// 剩下的 & 只能作为实体开头,且不能有裸的 < >,否则属性会被提前截断。
assert.doesNotMatch(label, /&(?!(amp|lt|gt|quot|#\d+);)/)
assert.doesNotMatch(label, /[<>]/)
})
test('ecc 非法时明确报错,不静默退回默认级别', () => {
assert.throws(() => encodeQr('a', { ecc: 'X' as QrEcc }), RangeError)
})
+4 -2
View File
@@ -123,9 +123,11 @@ test('同一个客户端上,普通接口仍按默认超时被掐断', async ()
)
})
test('导出接口只保留「存文件」,恢复接口只保留 restore', () => {
test('导出接口只保留「存文件」,恢复接口只保留 restore / network', () => {
const client = new ApiClient({ fetchImpl: async () => jsonResponse({ ok: true, data: null }) })
assert.deepEqual(Object.keys(client.exports), ['save'])
assert.deepEqual(Object.keys(client.system), ['restore'])
// system 这一组是有意收窄的:只放「不属于任何业务实体」的本机能力。
// network 是本机局域网地址(GET /api/system/network),给大屏控制页拼地址用。
assert.deepEqual(Object.keys(client.system), ['restore', 'network'])
})
+24
View File
@@ -673,6 +673,30 @@ export interface HealthInfo {
version: string
}
/** 本机的一个局域网地址(GET /api/system/network)。 */
export interface NetworkAddress {
/** 形如 `192.168.1.23`;服务端只回可用地址,回环不会被列进来。 */
ip: string
/** 网卡名,如 `eth0` / `wlan0` / Windows 的 `WLAN`。 */
interface: string
/** 地址族,当前只有 `ipv4` 会被列出(大屏地址是 IPv4 点分十进制)。 */
family: string
}
/**
* 本机网络信息(`GET /api/system/network`,recorder 及以上可读)。
*
* 「局域网大屏」卡片直接用这里回的端口与路径拼地址,不在前端硬编码:
* 现场改过端口或把大屏挂在子路径下时,卡片要跟着变。
* 拿不到任何可用地址时 `addresses` 为空数组(没插网线 / 只有回环),不是错误。
*/
export interface NetworkInfo {
port: number
displayPath: string
adminPath: string
addresses: NetworkAddress[]
}
/** 数据目录 `event_projs/` 下的一个赛事项目(GET /api/projects,admin)。 */
export interface ProjectInfo {
name: string