HarmonyOS色票对照台连载19:色票收藏与主题切换【共创稿事节】
HarmonyOS色票对照台连载03:色票收藏与主题切换【共创稿事节】
配色检查页面加入收藏和深浅主题以后,容易把两类颜色混在一起:一类是正在分析的前景与背景,另一类是工具面板自身的界面配色。如果切换深色主题时顺手替换样本背景,原来的对比度结论就失去了对象。本篇让色票对照台继续保留前背景身份,把收藏与工具主题作为独立会话状态维护。

分析配色继续使用已有服务
PaletteDesk沿用墨色、纸白、钴蓝和浅灰四张色票,Swatch的身份、名称和hex保持不变。Pair仍指向前背景身份,颜色解析与对比度服务继续接收对应hex。新增收藏不会改变某张色票的颜色,切换工具主题也不会改写Pair。
下面保留前两章的模型和计算服务,文件路径相对于entry/src/main/ets。钴蓝与纸白仍显示约5.17:1,分类仍根据原始比值判断,显示精度没有进入业务模型。
// 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};
}
收藏保存的是色票身份,而不是当前名称或数组下标。界面需要显示收藏项时,再通过swatchById查出名称。这样以后调整色票显示顺序,不会让原来收藏的钴蓝变成浅灰,也不会因为名称调整而创建另一份相同收藏。
会话对象同时表达三个独立维度
新增PaletteSession包含pair、favoriteIds和theme。pair描述分析对象,favoriteIds描述收藏集合,theme描述工具主题。三个维度放在同一份会话中便于复制和恢复,但每个动作只改变自己负责的字段,不让切换主题顺带清空收藏。
// 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;
}
createSession返回独立对象,默认使用钴蓝前景、纸白背景、空收藏和浅色主题。copySession复制嵌套的Pair和收藏数组,同时核对所有身份、主题值以及重复收藏。调用方得到的是一份经过检查的新会话,可以在修改后整体发布。
这种复制不是为了让每次操作都显得复杂,而是给状态更新建立清晰边界。若两个会话共用同一个favoriteIds数组,在一个窗口里点击收藏可能改变另一份尚未发布的草稿。嵌套Pair也需要复制,不能只复制外层对象后继续共享内部引用。
收藏动作采用切换语义
toggleFavorite先复制并校验原会话,再查询目标身份。身份已经存在时移除,不存在时追加;连续点击两次便回到原集合。数组只允许四张内置色票的身份,未知项和重复项在服务入口被拒绝,页面不负责修补错误集合。
收藏顺序保留用户添加的顺序。移除再添加会把该项放到末尾,这与按钮切换的操作含义一致。当前实现没有把收藏数量当作另一份长期状态保存,而是在显示时读取favoriteIds.length,避免列表变了但计数忘记同步。

收藏当前前景按钮读取session.pair.foregroundId,因此它收藏的是当前分析前景,而不是最近点击过的任意色票。前景换成墨色后再点击,收藏集合会追加墨色;交换前背景以后按钮目标也随新的前景身份变化。动作名称与数据来源需要保持对应。
工具主题用明确的颜色角色
themeColors只接受light和dark,返回背景、面板和文字三种角色。浅色工具背景为井号F3F4F6,面板为白色,文字为深灰;深色工具背景为井号111827,面板为井号1F2937,文字为井号F9FAFB。返回值用于工具控件,不写入Swatch集合。
这里选择页面内明确的配色角色,页面根据会话值设置颜色属性。系统提供的应用主题机制可用于统一组件资源风格;当前工具主题则由页面自己的theme字段驱动,切换按钮不会隐式改变系统外观设置。新增界面控件时,应继续决定它属于工具角色还是分析样本。
样本文字与背景保持原值
resultPanel中的样本文字显式使用result.foreground,样本背景显式使用result.background。其他摘要、分类和状态文字使用工具主题的text角色。即使工具已经切到深色,钴蓝配纸白仍然显示为蓝字白底,原始对比度与四项分类保持不变。
// 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';
@Entry
@Component
struct Index {
@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)
}
build() {
Scroll() {
Column({space:16}) {
Text('色票对照台').fontSize(26).fontColor(themeColors(this.session.theme).text)
Text('色票收藏与主题切换').fontColor(themeColors(this.session.theme).text)
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、替换Pair并整体发布。切换主题与收藏只返回新的会话,不重新计算对比度。数学结果取决于前背景hex,界面角色变化不应触发另一套颜色计算。
按钮事件继续进入服务,不在页面内直接splice收藏数组。这样收藏、主题和后续恢复操作能够复用相同校验规则。出错时应保留当前会话与结果,并在相应交互入口给出提示,避免一半状态已经改变后才发现身份无效。

示例界面可以通过两次操作得到:在默认配色下收藏当前前景,再切换主题。此时收藏数量为一、收藏项为钴蓝、主题为深色,而前景仍是井号2563EB、背景仍是井号FFFFFF、比值仍显示5.17:1。这个状态同时覆盖了独立性和组合更新。
宽窄布局共享同一会话
页面仍以八百四十为分栏阈值,窗口宽度变化只调整Flex方向与面板宽度。收藏摘要放在配色操作之前,窄屏可以先看到主题和收藏状态,宽屏则有更大的空间同时查看选择区与结果。布局不重新创建默认会话,也不把已选Pair换回默认值。
检查时可以先收藏两个不同身份,再切换主题和窗口宽度,观察收藏顺序、数量与前背景是否保持。把第二份会话通过copySession生成后修改,原会话也应保持不变。这类组合序列比只检查某个按钮有没有改变颜色,更容易发现引用共享的问题。
为恢复保留可重建字段
当前会话只保存Pair、收藏身份和主题,不保存格式化比值,也不保存工具面板宽度。下一章将把这三个维度编码为恢复文本,并在对照窗口中显式加载。恢复后通过同一组色票与计算服务重建结果,可以避免保存数据与显示派生值逐渐分离。
收藏和主题加入以后,色票对照台仍保持同一条工程主线:稳定身份确定分析对象,纯服务校验会话,页面负责空间与发布。工具外观可以变化,分析事实始终来自同一对颜色,后续多窗口对照也就有了清楚的数据依据。
还可以把收藏与主题组合成一组回归样本:四张色票共有十六种收藏子集,分别在深浅主题下做复制和恢复比较。每种情况都核对Pair身份、收藏顺序和主题值,而不是只比较收藏数量。数量相同的集合可能包含不同身份,这类检查能够发现把列表错误转换成计数,或在复制时丢失某一项的情况。
相关资料
更多推荐




所有评论(0)