HarmonyOS色票对照台连载20:多窗口对照与数据恢复【共创稿事节】
HarmonyOS色票对照台连载04:多窗口对照与数据恢复【共创稿事节】
在一个窗口里调整色票、另一个窗口里保留原配色,有助于比较主题与收藏方案。但如果所有页面都直接绑定同一份正在编辑的会话,对照窗口会跟着变化,比较对象便消失了。本篇让色票对照台的每个窗口保留本地会话,只通过明确的共享版本交换参数,并在恢复成功后重新计算对比结果。

本地编辑和共享版本分开
本篇面向同一应用进程、主线程内的主窗口与应用子窗口。每个页面拥有自己的PaletteSession、ContrastResult和布局宽度;AppStorage中只放最近一次发布的PaletteArchive。共享版本变化时,各窗口能看到新的版本号,但本地配色不会自动被覆盖,恢复动作由用户明确触发。
这种关系使两个窗口可以停留在不同方案上。一个窗口切换深色主题或取消收藏,不会立即改变另一个窗口;保存共享版本只是发布一份参数快照,其他窗口点击恢复共享版本以后才加载。AppStorage属于进程内UI状态,长期恢复则可以保留下面的参数文本,在新会话中通过文本入口加载。
下面完整保留此前模型、颜色、对比度与会话服务,路径均相对于entry/src/main/ets。
// model/Swatch.ets
export interface Swatch { id: string; name: string; hex: string; }
export interface Pair { foregroundId: string; backgroundId: string; }
export interface ParsedColor { hex: string; r: number; g: number; b: number; }
export function defaultSwatches(): Swatch[] {
return [{id:'ink',name:'墨色',hex:'#1F2937'},{id:'paper',name:'纸白',hex:'#FFFFFF'},
{id:'accent',name:'钴蓝',hex:'#2563EB'},{id:'muted',name:'浅灰',hex:'#9CA3AF'}];
}
export function swatchById(swatches: Swatch[],id: string): Swatch {
const item: Swatch | undefined = swatches.find((value: Swatch) => value.id===id);
if (item===undefined) throw new Error('色票身份不存在');
return {id:item.id,name:item.name,hex:item.hex};
}
// service/ColorMath.ets
import { ParsedColor } from '../model/Swatch';
export function parseHex(text: string): ParsedColor {
const value: string = text.trim();
if (!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(value)) throw new Error('请输入三位或六位十六进制颜色');
let digits: string = value.substring(1).toUpperCase();
if (digits.length===3) digits=digits[0]+digits[0]+digits[1]+digits[1]+digits[2]+digits[2];
return {hex:'#'+digits,r:parseInt(digits.substring(0,2),16),
g:parseInt(digits.substring(2,4),16),b:parseInt(digits.substring(4,6),16)};
}
export function linearChannel(value: number): number {
if (!Number.isInteger(value) || value<0 || value>255) throw new Error('颜色通道需为零至255整数');
const s: number = value/255;
return s<=0.04045 ? s/12.92 : Math.pow((s+0.055)/1.055,2.4);
}
export function relativeLuminance(color: ParsedColor): number {
return 0.2126*linearChannel(color.r)+0.7152*linearChannel(color.g)+0.0722*linearChannel(color.b);
}
// service/Contrast.ets
import { parseHex, relativeLuminance } from './ColorMath';
export interface ContrastResult {
foreground: string; background: string; foregroundLuminance: number; backgroundLuminance: number;
ratio: number; normalAA: boolean; largeAA: boolean; normalAAA: boolean; largeAAA: boolean;
}
export interface ContrastFlags { normalAA: boolean; largeAA: boolean; normalAAA: boolean; largeAAA: boolean; }
export function classifyRatio(ratio: number): ContrastFlags {
if (!Number.isFinite(ratio) || ratio<1 || ratio>21) throw new Error('对比度需位于一至21');
return {normalAA:ratio>=4.5,largeAA:ratio>=3,normalAAA:ratio>=7,largeAAA:ratio>=4.5};
}
export function contrastFromLuminance(a: number,b: number): number {
if (!Number.isFinite(a) || !Number.isFinite(b) || a<0 || a>1 || b<0 || b>1) throw new Error('亮度需位于零至一');
return (Math.max(a,b)+0.05)/(Math.min(a,b)+0.05);
}
export function evaluatePair(foreground: string,background: string): ContrastResult {
const fg = parseHex(foreground); const bg = parseHex(background);
const a: number = relativeLuminance(fg); const b: number = relativeLuminance(bg);
const ratio: number = contrastFromLuminance(a,b); const flags: ContrastFlags = classifyRatio(ratio);
return {foreground:fg.hex,background:bg.hex,foregroundLuminance:a,backgroundLuminance:b,ratio,
normalAA:flags.normalAA,largeAA:flags.largeAA,normalAAA:flags.normalAAA,largeAAA:flags.largeAAA};
}
// service/PaletteSession.ets
import { Pair, defaultSwatches, swatchById } from '../model/Swatch';
export interface PaletteSession { pair: Pair; favoriteIds: string[]; theme: string; }
export interface ThemeColors { background: string; panel: string; text: string; }
export function createSession(): PaletteSession {
return {pair:{foregroundId:'accent',backgroundId:'paper'},favoriteIds:[],theme:'light'};
}
export function themeColors(theme: string): ThemeColors {
if (theme==='dark') return {background:'#111827',panel:'#1F2937',text:'#F9FAFB'};
if (theme==='light') return {background:'#F3F4F6',panel:'#FFFFFF',text:'#111827'};
throw new Error('主题值无效');
}
export function copySession(session: PaletteSession): PaletteSession {
themeColors(session.theme);
swatchById(defaultSwatches(),session.pair.foregroundId);
swatchById(defaultSwatches(),session.pair.backgroundId);
const ids: string[] = [];
for (const id of session.favoriteIds) {
swatchById(defaultSwatches(),id);
if (ids.indexOf(id)>=0) throw new Error('收藏身份重复');
ids.push(id);
}
return {pair:{foregroundId:session.pair.foregroundId,backgroundId:session.pair.backgroundId},favoriteIds:ids,theme:session.theme};
}
export function toggleFavorite(session: PaletteSession,id: string): PaletteSession {
const next: PaletteSession = copySession(session); swatchById(defaultSwatches(),id);
const index: number = next.favoriteIds.indexOf(id);
if (index>=0) next.favoriteIds.splice(index,1); else next.favoriteIds.push(id);
return next;
}
export function switchTheme(session: PaletteSession): PaletteSession {
const next: PaletteSession = copySession(session); next.theme=next.theme==='light' ? 'dark' : 'light'; return next;
}
共享对象只保存可重建参数
PaletteArchive包含revision和text。revision表示共享发布次数,text保存结构版本、主题、前景身份、背景身份和收藏身份列表。空收藏使用短横线表示,其他收藏按当前顺序用逗号分隔。所有身份来自固定色票集合,因此当前结构无需自由文本转义。
// service/PaletteArchive.ets
import { PaletteSession, copySession } from './PaletteSession';
export interface PaletteArchive { revision: number; text: string; }
export function encodeSession(session: PaletteSession): string {
const valid: PaletteSession = copySession(session);
return ['PALETTE1',valid.theme,valid.pair.foregroundId,valid.pair.backgroundId,
valid.favoriteIds.length===0 ? '-' : valid.favoriteIds.join(',')].join('|');
}
export function decodeSession(text: string): PaletteSession {
if (text.length>200) throw new Error('配色文本过长');
const parts: string[] = text.trim().split('|');
if (parts.length!==5 || parts[0]!=='PALETTE1') throw new Error('配色文本格式或版本错误');
return copySession({pair:{foregroundId:parts[2],backgroundId:parts[3]},
favoriteIds:parts[4]==='-' ? [] : parts[4].split(','),theme:parts[1]});
}
export function publishArchive(current: PaletteArchive,session: PaletteSession): PaletteArchive {
if (!Number.isSafeInteger(current.revision) || current.revision<0 || current.revision>=Number.MAX_SAFE_INTEGER)
throw new Error('共享版本无法继续增加');
return {revision:current.revision+1,text:encodeSession(session)};
}
例如收藏钴蓝、保持浅色主题时,文本为PALETTE1竖线light竖线accent竖线paper竖线accent。结构版本与共享revision分别表达格式和发布顺序,不能合并。decodeSession先限制长度与字段数量,再通过copySession核对主题、身份和重复收藏,返回独立的本地会话。
当前格式的完整示例为:
PALETTE1|light|accent|paper|accent
发布只增加共享版本,不把页面宽度、窗口对象或格式化比值放进文本。恢复结果仍由现有色票和evaluatePair产生,避免保存后的颜色事实与旧的比值字符串互相矛盾。达到安全整数上限时拒绝继续增加版本,不能让计数静默失去精度。
窗口创建沿Stage生命周期接入
EntryAbility在onWindowStageCreate中登记WindowStage并加载主页面。WindowHost负责创建、显示和关闭一个命名对照子窗口,页面按钮只调用它的公开方法。子窗口仍加载pages/Index,因此工程继续使用默认页面路径,不需要引用未提供的页面文件。
// service/WindowHost.ets
import { window } from '@kit.ArkUI';
export class WindowHost {
static stage: window.WindowStage | undefined = undefined;
private static child: window.Window | undefined = undefined;
private static opening: boolean = false;
static async open(): Promise<void> {
if (WindowHost.opening) throw new Error('对照窗正在创建');
if (WindowHost.child!==undefined) {
try { await WindowHost.child.showWindow(); return; }
catch (error) { WindowHost.child=undefined; }
}
const stage: window.WindowStage | undefined = WindowHost.stage;
if (stage===undefined) throw new Error('窗口舞台尚未就绪');
WindowHost.opening=true;
let child: window.Window | undefined = undefined;
try {
child=await stage.createSubWindow('paletteCompare');
const rect=stage.getMainWindowSync().getWindowProperties().windowRect;
await child.resize(Math.min(600,rect.width),Math.min(900,rect.height));
await child.setUIContent('pages/Index');
if (WindowHost.stage!==stage) throw new Error('窗口舞台已变化');
await child.showWindow(); WindowHost.child=child;
} catch (error) {
if (child!==undefined) { try { await child.destroyWindow(); } catch (cleanupError) { WindowHost.child=undefined; } }
throw error;
} finally { WindowHost.opening=false; }
}
static async close(): Promise<void> {
if (WindowHost.opening) throw new Error('请等待对照窗创建完成');
const child: window.Window | undefined = WindowHost.child;
if (child!==undefined) { await child.destroyWindow(); WindowHost.child=undefined; }
}
static reset(): void { WindowHost.stage=undefined; WindowHost.child=undefined; WindowHost.opening=false; }
}
// entryability/EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { WindowHost } from '../service/WindowHost';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(stage: window.WindowStage): void {
WindowHost.stage=stage;
stage.loadContent('pages/Index',(error) => {
if (error.code) { WindowHost.reset(); console.error(`页面加载失败:${error.code}`); }
});
}
onWindowStageDestroy(): void { WindowHost.reset(); }
}
创建流程依次取得子窗口、设置大小、加载页面,再显示。尺寸采用主窗口矩形的像素宽高作为上界,并限制最大尺寸;页面内部仍用各自区域宽度安排控件。创建过程中以opening阻止重复请求,已有窗口优先重新显示,失效对象在重新创建前清理引用。
加载或显示失败时,已经创建的子窗口会尝试销毁,错误交回页面提示。舞台销毁时清理保存的引用,异步加载后也核对舞台是否仍是原对象。这样可以减少窗口生命周期变化后继续发布旧引用的问题,避免只捕获错误却留下一个空白窗口。
恢复成功以后一次发布本地结果
页面用StorageLink关联共享归档,归档本身只有数值和字符串字段。发布时用新对象整体替换归档,避免多个窗口分别修改同一个对象的不同字段。每个页面的session继续使用State,两个存储层承担不同职责。
// pages/Index.ets
import { Swatch, Pair, defaultSwatches, swatchById } from '../model/Swatch';
import { ContrastResult, evaluatePair } from '../service/Contrast';
import { PaletteSession, createSession, copySession, toggleFavorite, switchTheme, themeColors } from '../service/PaletteSession';
import { PaletteArchive, encodeSession, decodeSession, publishArchive } from '../service/PaletteArchive';
import { WindowHost } from '../service/WindowHost';
@Entry
@Component
struct Index {
@StorageLink('paletteArchive') archive: PaletteArchive = {revision:0,text:''};
@State loadedRevision: number = 0;
@State exchangeText: string = '';
@State session: PaletteSession = createSession();
@State result: ContrastResult = evaluatePair('#2563EB','#FFFFFF');
@State status: string = '已更新';
@State areaWidth: number = 360;
private swatches: Swatch[] = defaultSwatches();
private selectPair(foregroundId: string,backgroundId: string): void {
try {
const fg: Swatch = swatchById(this.swatches,foregroundId);
const bg: Swatch = swatchById(this.swatches,backgroundId);
const result: ContrastResult = evaluatePair(fg.hex,bg.hex);
const next: PaletteSession = copySession(this.session); next.pair={foregroundId,backgroundId}; this.session=next; this.result=result; this.status='已更新';
} catch (error) { this.status=error instanceof Error ? error.message : '配色处理失败'; }
}
private panelWidth(): number { return this.areaWidth>=840 ? (this.areaWidth-56)/2 : this.areaWidth-40; }
private label(value: boolean): string { return value ? '通过' : '未达'; }
@Builder
selectPanel() {
Column({space:12}) {
Text(`前景 ${this.result.foreground}`).fontColor(themeColors(this.session.theme).text)
ForEach(this.swatches,(item: Swatch) => {
Button(`前景:${item.name}`).onClick(() => { this.selectPair(item.id,this.session.pair.backgroundId); })
},(item: Swatch) => item.id)
Text(`背景 ${this.result.background}`).fontColor(themeColors(this.session.theme).text)
ForEach(this.swatches,(item: Swatch) => {
Button(`背景:${item.name}`).onClick(() => { this.selectPair(this.session.pair.foregroundId,item.id); })
},(item: Swatch) => item.id)
Button('交换前背景').onClick(() => { this.selectPair(this.session.pair.backgroundId,this.session.pair.foregroundId); })
}.width(this.panelWidth()).padding(16).backgroundColor(themeColors(this.session.theme).panel).borderRadius(16)
}
@Builder
resultPanel() {
Column({space:12}) {
Text('色票对照台').fontSize(24).fontColor(this.result.foreground)
.width('100%').height(100).backgroundColor(this.result.background)
Text(`对比度 ${this.result.ratio.toFixed(2)}:1`).fontSize(28).fontColor(themeColors(this.session.theme).text)
Text(`普通文本 AA:${this.label(this.result.normalAA)}`).fontColor(themeColors(this.session.theme).text)
Text(`大文本 AA:${this.label(this.result.largeAA)}`).fontColor(themeColors(this.session.theme).text)
Text(`普通文本 AAA:${this.label(this.result.normalAAA)}`).fontColor(themeColors(this.session.theme).text)
Text(`大文本 AAA:${this.label(this.result.largeAAA)}`).fontColor(themeColors(this.session.theme).text)
Text('按原始比值分类').fontColor(themeColors(this.session.theme).text)
Text(this.status).fontColor(themeColors(this.session.theme).text)
}.width(this.panelWidth()).padding(16).backgroundColor(themeColors(this.session.theme).panel).borderRadius(16)
}
private favoriteNames(): string {
return this.session.favoriteIds.length===0 ? '无' : this.session.favoriteIds.map((id: string) => swatchById(this.swatches,id).name).join('、');
}
@Builder
sessionPanel() {
Column({space:12}) {
Text(`当前主题:${this.session.theme==='dark' ? '深色' : '浅色'}`).fontColor(themeColors(this.session.theme).text)
Text(`收藏数量:${this.session.favoriteIds.length}`).fontColor(themeColors(this.session.theme).text)
Text(`收藏项:${this.favoriteNames()}`).fontColor(themeColors(this.session.theme).text)
Button('切换主题').onClick(() => { this.session=switchTheme(this.session); })
Button('收藏当前前景').onClick(() => { this.session=toggleFavorite(this.session,this.session.pair.foregroundId); })
}.width('100%').padding(16).backgroundColor(themeColors(this.session.theme).panel).borderRadius(16)
}
private publish(): void {
try { this.archive=publishArchive(this.archive,this.session); this.exchangeText=this.archive.text;
this.status=`已保存共享版本${this.archive.revision}`;
} catch (error) { this.status=error instanceof Error ? error.message : '保存失败'; }
}
private applyText(text: string,revision: number): void {
const next: PaletteSession = decodeSession(text);
const result: ContrastResult = evaluatePair(swatchById(this.swatches,next.pair.foregroundId).hex,swatchById(this.swatches,next.pair.backgroundId).hex);
this.session=next; this.result=result; this.loadedRevision=revision;
}
private restore(): void {
try {
if (!Number.isSafeInteger(this.archive.revision) || this.archive.revision<1) throw new Error('尚无共享版本');
this.applyText(this.archive.text,this.archive.revision); this.exchangeText=this.archive.text;
this.status=`已恢复共享版本${this.archive.revision}`;
} catch (error) { this.status=error instanceof Error ? error.message : '恢复失败'; }
}
private importText(): void {
try { this.applyText(this.exchangeText,0); this.status='已从文本恢复'; }
catch (error) { this.status=error instanceof Error ? error.message : '文本恢复失败'; }
}
private async openCompare(): Promise<void> {
try { await WindowHost.open(); this.status='对照窗已打开'; }
catch (error) { this.status=error instanceof Error ? error.message : '对照窗打开失败'; }
}
private async closeCompare(): Promise<void> {
try { await WindowHost.close(); this.status='对照窗已关闭'; }
catch (error) { this.status=error instanceof Error ? error.message : '对照窗关闭失败'; }
}
@Builder
archivePanel() {
Column({space:12}) {
Text(`共享版本:${this.archive.revision}`).fontColor(themeColors(this.session.theme).text)
Text(`本窗已恢复:${this.loadedRevision}`).fontColor(themeColors(this.session.theme).text)
Button('保存共享版本').onClick(() => { this.publish(); })
Button('恢复共享版本').onClick(() => { this.restore(); })
Button('打开对照窗').onClick(() => { this.openCompare(); })
Button('关闭对照窗').onClick(() => { this.closeCompare(); })
TextArea({text:this.exchangeText,placeholder:'粘贴配色恢复文本'}).height(100)
.onChange((value: string) => { this.exchangeText=value; })
Button('从文本恢复').onClick(() => { this.importText(); })
}.width('100%').padding(16).backgroundColor(themeColors(this.session.theme).panel).borderRadius(16)
}
build() {
Scroll() {
Column({space:16}) {
Text('色票对照台').fontSize(26).fontColor(themeColors(this.session.theme).text)
Text('多窗口对照与数据恢复').fontColor(themeColors(this.session.theme).text)
this.archivePanel()
this.sessionPanel()
Flex({direction:this.areaWidth>=840 ? FlexDirection.Row : FlexDirection.Column}) {
Column() { this.selectPanel() }.margin({right:this.areaWidth>=840 ? 16 : 0,bottom:16})
this.resultPanel()
}.width('100%')
}.padding(20).width('100%')
}.width('100%').height('100%').backgroundColor(themeColors(this.session.theme).background)
.onAreaChange((oldArea: Area,newArea: Area) => {
const width: number = Number(newArea.width);
if (Number.isFinite(width) && width>40 && width!==this.areaWidth) this.areaWidth=width;
})
}
}
恢复先解析文本,再解析前背景身份并计算ContrastResult,两步完成以后才发布session、result和loadedRevision。错误路径只改提示,原本地会话和结果保留。共享归档的版本号不会因为某个窗口恢复而增加,恢复是读取已经发布的事实,不是再次保存。

loadedRevision表示本窗最近一次成功恢复的共享版本。用户随后本地修改主题或收藏时,它仍保留这一来源记录,因此不能把该数字理解为当前内容始终与共享版本相同。新的本地发布和恢复动作各有提示,必要时还可以比较规范文本判断是否存在未保存修改。
文本恢复与共享恢复共用解析链
共享保存成功后,页面把参数文本放进交换输入框,用户可以复制保留。直接粘贴文本再恢复时,沿同一decodeSession和evaluatePair链重建本地状态,loadedRevision记为零,表示来源是文本而非共享版本。格式正确的文本不会凭空占用一个共享发布序号。
这条路径也适合应用重新启动后的参数恢复:重新打开页面,粘贴此前保存的完整文本即可重建配色与收藏。文件持久写入可以另接存储入口,编解码函数保持独立;进程内共享状态与跨启动保留文本的用途需要明确区分。

示例操作为收藏钴蓝、保存共享版本,再在另一个页面点击恢复。浅色主题、钴蓝前景、纸白背景、收藏数量一对应同一份参数,恢复后的比值仍显示5.17:1。共享版本为一,本窗已恢复为一,界面提示已恢复共享版本一。
用两份页面状态检查隔离
可以让主窗口保存版本一,再打开对照窗并恢复。随后在主窗口切换主题、取消收藏但暂不保存,对照窗应继续保留原方案;主窗口发布版本二后,对照窗只更新可见的共享版本号,直到点击恢复才改变自己的会话。这个顺序能够区分共享通知与本地加载。
再尝试未知结构版本、未知色票身份、重复收藏和缺失字段的文本。失败以后比较前背景、主题、收藏和比值,确认没有部分更新。复制一份恢复结果并修改收藏数组,也不能影响此前保存的归档字符串或其他窗口已经加载的本地会话。
布局和窗口资源分别管理
主窗口与子窗口拥有各自的区域变化回调,八百四十阈值只对当前页面宽度生效。不要把某一窗口的areaWidth放进共享归档,否则拖动一个窗口会让另一个窗口错误地切换布局。共享的是参数事实,空间信息由各自UI实例维护。
关闭对照窗时通过WindowHost销毁对应对象,主窗口继续可用。再次打开会创建新的页面实例,本地会话从默认值开始,用户再选择是否恢复共享版本。页面不在每次显示时自动覆盖本地编辑,避免切回窗口就丢掉尚未保存的比较方案。
四篇连载最终形成完整的色票工程链:颜色解析提供规范通道,亮度和对比度服务计算结果,会话保存收藏与工具主题,共享版本和恢复文本连接不同页面。保持稳定身份、明确发布动作和独立本地状态,才能让多窗口对照保留真正有用的比较关系。
共享发布不包含异步网络步骤,因此同一UI线程中的版本读取和归档替换可以保持为一次同步按钮处理。若后续加入远程保存,应额外携带来源版本并在响应回到页面时核对,避免较旧响应覆盖较新发布。窗口创建则属于另一条异步资源链,不能把它完成的先后当成业务版本顺序。
相关资料
更多推荐




所有评论(0)