diff --git a/plugin/src/codes.ts b/plugin/src/codes.ts index 91f1ec3..eb9fdfe 100644 --- a/plugin/src/codes.ts +++ b/plugin/src/codes.ts @@ -24,6 +24,38 @@ import qrcode from "qrcode-generator"; +/* ================================================================== */ +/* 出图缓存 */ +/* ================================================================== */ + +/** + * 为什么要缓存。 + * + * 页面每次重渲染都会重新构造「标签上下文」对象(`labelContext(slot)`), + * 子组件的 computed 跟着失效、重算 —— 也就是**每一格都会重新拼一遍 SVG**。 + * 一个 25×25 的二维码是 600 多个 ``,44 格就是 2 万多个节点; + * 用户点一下格子、改一下数量,浏览器就得重新解析一遍这些字符串, + * 表现为「点一下卡半秒」。 + * + * 而真正变化的东西很少:同一个 SN、同一套参数,出来的 SVG 必然一模一样。 + * 所以按「参数指纹」缓存字符串。用 FIFO 封顶,避免长时间换参数导致无限增长。 + */ +const CACHE_LIMIT = 400; +const svgCache = new Map(); + +function cached(key: string, build: () => string): string { + const hit = svgCache.get(key); + if (hit !== undefined) return hit; + const svg = build(); + if (svgCache.size >= CACHE_LIMIT) { + // Map 保持插入顺序,删最老的那个即可 + const oldest = svgCache.keys().next().value; + if (oldest !== undefined) svgCache.delete(oldest); + } + svgCache.set(key, svg); + return svg; +} + /* ================================================================== */ /* Code 128 Set B */ /* ================================================================== */ @@ -139,6 +171,14 @@ export const LABEL_BARCODE_STRIP_MM = code128HeightMm(LABEL_BARCODE_OPTS); * (`ZP-260928-0001-R` 是 16 位,短码只有 12 位),固定模块宽度会时宽时窄。 */ export function code128Svg(text: string, opts: BarcodeOptions = {}): string { + // 指纹按**解析后的默认值**拼,避免 `{}` 与显式默认值产生两份缓存 + const key = + `b|${text}|${opts.widthMm ?? 46}|${opts.heightMm ?? 7}|` + + `${opts.showText !== false}|${opts.textMm ?? 1.9}`; + return cached(key, () => buildCode128Svg(text, opts)); +} + +function buildCode128Svg(text: string, opts: BarcodeOptions = {}): string { const widthMm = opts.widthMm ?? 46; const heightMm = opts.heightMm ?? 7; const showText = opts.showText !== false; @@ -239,6 +279,11 @@ export interface QrOptions { * 二维码会自己跟着缩,不需要在 JS 里重复算一遍布局。 */ export function qrSvg(text: string, opts: QrOptions = {}): string { + const key = `q|${text}|${opts.ec ?? "M"}|${opts.quiet ?? 4}|${opts.dark ?? "#000"}`; + return cached(key, () => buildQrSvg(text, opts)); +} + +function buildQrSvg(text: string, opts: QrOptions = {}): string { const quiet = opts.quiet ?? 4; const dark = opts.dark ?? "#000";