HarmonyOS数独候选台连载15:宽屏键盘输入与可访问性【共创稿事节】
HarmonyOS数独候选台连载07:宽屏键盘输入与可访问性【共创稿事节】
数独页面在宽屏上保留了更多候选与历史信息,但如果用户仍要反复用鼠标点击提交、查询和撤销,键盘输入就会被切成许多零散动作。数独候选台继续复用合法编辑、历史与缓存入口,为主要按钮配置快捷键,并把当前格的位置、固定身份和数字组成清晰的可访问性描述。

输入方式共用同一条提交链
本篇保留行、列、填入值三个输入框,数字可以通过键盘输入草稿。F6提交草稿,F7查询候选,F8撤销,F9重做;触控与鼠标点击继续使用原按钮。快捷键触发按钮动作,而不是绕过按钮再直接改动棋盘数组。
这种分工让固定格保护、冲突检查、步骤合并与候选增量刷新保持原规则。按F6提交非法数字仍然会被拒绝,按F8恢复题面仍然重新计算受影响缓存。快捷键只是另一种交互入口,不能拥有另一套更宽松的编辑条件。
SudokuDesk继续使用前文七个完整服务与模型文件。下面保留题面、候选、编辑事务、提示、历史、搜索和缓存,路径均相对于entry/src/main/ets。新增可访问性辅助服务负责位置移动与描述,页面负责按钮绑定与界面发布。
// model/Puzzle.ets
export function initialPuzzle(): number[] {
const rows: string[] = ['530070000','600195000','098000060',
'800060003','400803001','700020006','060000280','000419005','000080079'];
const board: number[] = [];
for (const row of rows) for (let col: number = 0; col<9; col++) board.push(Number(row[col]));
return board;
}
export function requireBoard(board: number[]): void {
if (board.length!==81) throw new Error('题面需为81格');
for (const value of board) if (!Number.isInteger(value) || value<0 || value>9)
throw new Error('题面格值需为0至9');
}
export function parseCell(rowText: string,colText: string): number {
const row: string = rowText.trim(); const col: string = colText.trim();
if (!/^[1-9]$/.test(row) || !/^[1-9]$/.test(col)) throw new Error('行列需为1至9');
return (Number(row)-1)*9+Number(col)-1;
}
// service/Candidates.ets
import { requireBoard } from '../model/Puzzle';
export interface CandidateInfo { rowUsed: number[]; colUsed: number[]; boxUsed: number[]; values: number[]; }
function uniqueDigits(values: number[]): number[] {
const result: number[] = [];
for (let value: number = 1; value<=9; value++) if (values.indexOf(value)>=0) result.push(value);
return result;
}
export function queryCandidates(board: number[],index: number): CandidateInfo {
requireBoard(board);
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
if (board[index]!==0) throw new Error('目标格已有数字');
const row: number = Math.floor(index/9); const col: number = index%9;
const rowValues: number[] = []; const colValues: number[] = []; const boxValues: number[] = [];
for (let offset: number = 0; offset<9; offset++) {
rowValues.push(board[row*9+offset]); colValues.push(board[offset*9+col]);
}
const top: number = Math.floor(row/3)*3; const left: number = Math.floor(col/3)*3;
for (let dr: number = 0; dr<3; dr++) for (let dc: number = 0; dc<3; dc++)
boxValues.push(board[(top+dr)*9+left+dc]);
const rowUsed: number[] = uniqueDigits(rowValues);
const colUsed: number[] = uniqueDigits(colValues);
const boxUsed: number[] = uniqueDigits(boxValues);
const used: boolean[] = [false,false,false,false,false,false,false,false,false,false];
for (const value of rowUsed.concat(colUsed,boxUsed)) used[value]=true;
const result: number[] = [];
for (let value: number = 1; value<=9; value++) {
if (!used[value]) result.push(value);
}
return {rowUsed,colUsed,boxUsed,values:result};
}
export function digitsText(values: number[]): string { return values.length===0 ? '无' : values.join('、'); }
// service/PuzzleEdit.ets
import { initialPuzzle, requireBoard } from '../model/Puzzle';
export interface PuzzleState { board: number[]; givens: boolean[]; }
export type UnitKind = 'row' | 'col' | 'box';
export interface Conflict { kind: UnitKind; unit: number; digit: number; indices: number[]; }
export function createPuzzleState(): PuzzleState {
const board: number[] = initialPuzzle();
return {board,givens:board.map((value: number) => value!==0)};
}
export function requirePuzzleState(state: PuzzleState): void {
requireBoard(state.board);
if (state.givens.length!==81) throw new Error('固定格标记长度错误');
const seed: number[] = initialPuzzle();
for (let i: number = 0; i<81; i++) {
if (state.givens[i] !== (seed[i]!==0) || (seed[i]!==0 && state.board[i]!==seed[i]))
throw new Error('固定题面不一致');
}
}
export function unitIndices(kind: UnitKind,unit: number): number[] {
if (!Number.isInteger(unit) || unit<0 || unit>=9) throw new Error('区域位置错误');
if (kind!=='row' && kind!=='col' && kind!=='box') throw new Error('区域类型错误');
const result: number[] = [];
for (let offset: number = 0; offset<9; offset++) {
if (kind==='row') result.push(unit*9+offset);
else if (kind==='col') result.push(offset*9+unit);
else result.push((Math.floor(unit/3)*3+Math.floor(offset/3))*9+(unit%3)*3+offset%3);
}
return result;
}
export function findConflicts(board: number[]): Conflict[] {
requireBoard(board);
const result: Conflict[] = [];
const kinds: UnitKind[] = ['row','col','box'];
for (const kind of kinds) for (let unit: number = 0; unit<9; unit++) {
const points: number[] = unitIndices(kind,unit);
for (let digit: number = 1; digit<=9; digit++) {
const matches: number[] = points.filter((index: number) => board[index]===digit);
if (matches.length>1) result.push({kind,unit,digit,indices:matches});
}
}
return result;
}
export function conflictText(conflict: Conflict): string {
const name: string = conflict.kind==='row' ? '行' : conflict.kind==='col' ? '列' : '宫';
return `第${conflict.unit+1}${name}数字${conflict.digit}重复`;
}
export function parseDigit(text: string): number {
const value: string = text.trim();
if (!/^[0-9]$/.test(value)) throw new Error('填入值需为0至9,0表示清空');
return Number(value);
}
export function commitEdit(state: PuzzleState,index: number,value: number): PuzzleState {
requirePuzzleState(state);
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
if (!Number.isInteger(value) || value<0 || value>9) throw new Error('填入值超出范围');
if (state.givens[index]) throw new Error('固定题面格不可修改');
if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
const next: number[] = state.board.slice(); next[index]=value;
const conflicts: Conflict[] = findConflicts(next);
if (conflicts.length>0) throw new Error(conflictText(conflicts[0]));
return {board:next,givens:state.givens.slice()};
}
// service/SingleHint.ets
import { CandidateInfo, queryCandidates } from './Candidates';
import { PuzzleState, requirePuzzleState, findConflicts, commitEdit } from './PuzzleEdit';
export interface SingleHint { index: number; value: number; boardKey: string; info: CandidateInfo; }
export function findSingleHints(state: PuzzleState): SingleHint[] {
requirePuzzleState(state);
if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
const result: SingleHint[] = [];
const boardKey: string = state.board.join('');
for (let index: number = 0; index<81; index++) {
if (state.board[index]!==0) continue;
const info: CandidateInfo = queryCandidates(state.board,index);
if (info.values.length===1) {
result.push({index,value:info.values[0],boardKey,info});
}
}
return result;
}
export function applySingleHint(state: PuzzleState,hint: SingleHint): PuzzleState {
requirePuzzleState(state);
if (state.board.join('')!==hint.boardKey) throw new Error('题面已变化,请刷新提示');
const current: CandidateInfo = queryCandidates(state.board,hint.index);
if (current.values.length!==1 || current.values[0]!==hint.value)
throw new Error('当前格不满足单格唯一候选');
return commitEdit(state,hint.index,hint.value);
}
export function hintText(hint: SingleHint): string {
return `${Math.floor(hint.index/9)+1}行${hint.index%9+1}列填${hint.value}`;
}
// service/History.ets
import { PuzzleState, createPuzzleState, commitEdit } from './PuzzleEdit';
export interface EditStep { index: number; before: number; after: number; group: string; }
export interface PuzzleHistory { state: PuzzleState; steps: EditStep[]; cursor: number; }
export function createHistory(): PuzzleHistory { return {state:createPuzzleState(),steps:[],cursor:0}; }
function copyStep(step: EditStep): EditStep {
return {index:step.index,before:step.before,after:step.after,group:step.group};
}
export function recordEdit(history: PuzzleHistory,index: number,value: number,group: string): PuzzleHistory {
const next: PuzzleState = commitEdit(history.state,index,value);
const before: number = history.state.board[index];
if (before===value) return history;
const steps: EditStep[] = history.steps.slice(0,history.cursor).map(copyStep);
const last: EditStep | undefined = steps.length>0 ? steps[steps.length-1] : undefined;
const atEnd: boolean = history.cursor===history.steps.length;
if (atEnd && group.length>0 && last!==undefined && last.index===index && last.group===group && last.after===before) {
if (last.before===value) steps.pop();
else steps[steps.length-1]={index,before:last.before,after:value,group};
} else steps.push({index,before,after:value,group});
return {state:next,steps,cursor:steps.length};
}
export function undo(history: PuzzleHistory): PuzzleHistory {
if (history.cursor===0) throw new Error('没有可撤销步骤');
const step: EditStep = history.steps[history.cursor-1];
if (history.state.board[step.index]!==step.after) throw new Error('历史与题面不一致');
return {state:commitEdit(history.state,step.index,step.before),steps:history.steps.map(copyStep),cursor:history.cursor-1};
}
export function redo(history: PuzzleHistory): PuzzleHistory {
if (history.cursor===history.steps.length) throw new Error('没有可重做步骤');
const step: EditStep = history.steps[history.cursor];
if (history.state.board[step.index]!==step.before) throw new Error('历史与题面不一致');
return {state:commitEdit(history.state,step.index,step.after),steps:history.steps.map(copyStep),cursor:history.cursor+1};
}
// service/Search.ets
import { requireBoard } from '../model/Puzzle';
import { queryCandidates } from './Candidates';
import { findConflicts } from './PuzzleEdit';
export interface SearchReport { status: string; solutions: number; nodes: number; cutoff: boolean; first: number[]; boardKey: string; }
export function idleReport(): SearchReport {
return {status:'待分析',solutions:0,nodes:0,cutoff:false,first:[],boardKey:''};
}
export function parseBudget(text: string): number {
const value: string = text.trim();
if (!/^[1-9][0-9]{0,4}$/.test(value) || Number(value)>10000) throw new Error('节点预算需为1至10000');
return Number(value);
}
export function analyzePuzzle(source: number[],budget: number): SearchReport {
requireBoard(source);
if (findConflicts(source).length>0) throw new Error('当前题面存在冲突');
if (!Number.isInteger(budget) || budget<1 || budget>10000) throw new Error('节点预算超出范围');
const board: number[] = source.slice();
const report: SearchReport = idleReport(); report.boardKey=source.join('');
function visit(): void {
if (report.solutions>=2 || report.cutoff) return;
if (report.nodes>=budget) { report.cutoff=true; return; }
report.nodes++;
let target: number = -1; let values: number[] = [];
for (let i: number = 0; i<81; i++) {
if (board[i]!==0) continue;
const options: number[] = queryCandidates(board,i).values;
if (options.length===0) return;
if (target<0 || options.length<values.length) { target=i; values=options; }
}
if (target<0) {
report.solutions++;
if (report.solutions===1) report.first=board.slice();
return;
}
for (const value of values) {
board[target]=value; visit(); board[target]=0;
if (report.solutions>=2 || report.cutoff) return;
}
}
visit();
report.status=report.solutions>=2 ? '至少两解' : report.cutoff ? '尚未判定' : report.solutions===1 ? '唯一解' : '无解';
return report;
}
// service/CandidateCache.ets
import { requireBoard } from '../model/Puzzle';
import { CandidateInfo, queryCandidates } from './Candidates';
import { PuzzleState, requirePuzzleState, findConflicts, unitIndices } from './PuzzleEdit';
import { SingleHint } from './SingleHint';
export interface CandidateCache { board: number[]; entries: (CandidateInfo | null)[]; }
export interface CacheUpdate { cache: CandidateCache; changed: number; affected: number; recomputed: number; }
function copyInfo(info: CandidateInfo): CandidateInfo {
return {rowUsed:info.rowUsed.slice(),colUsed:info.colUsed.slice(),boxUsed:info.boxUsed.slice(),values:info.values.slice()};
}
export function createCache(board: number[]): CandidateCache {
requireBoard(board);
const entries: (CandidateInfo | null)[] = [];
for (let i: number = 0; i<81; i++) entries.push(board[i]===0 ? queryCandidates(board,i) : null);
return {board:board.slice(),entries};
}
export function updateCache(previous: CandidateCache,board: number[]): CacheUpdate {
requireBoard(previous.board); requireBoard(board);
if (previous.entries.length!==81) throw new Error('候选缓存长度错误');
const flags: boolean[] = [];
for (let i: number = 0; i<81; i++) flags.push(false);
let changed: number = 0;
for (let i: number = 0; i<81; i++) {
if (previous.board[i]===board[i]) continue;
changed++;
const row: number = Math.floor(i/9); const col: number = i%9;
const points: number[] = unitIndices('row',row).concat(unitIndices('col',col),unitIndices('box',Math.floor(row/3)*3+Math.floor(col/3)));
for (const point of points) flags[point]=true;
}
const entries: (CandidateInfo | null)[] = [];
let affected: number = 0; let recomputed: number = 0;
for (let i: number = 0; i<81; i++) {
if (flags[i]) affected++;
if (board[i]!==0) { entries.push(null); continue; }
const old: CandidateInfo | null = previous.entries[i];
if (flags[i] || old===null) { entries.push(queryCandidates(board,i)); recomputed++; }
else entries.push(copyInfo(old));
}
return {cache:{board:board.slice(),entries},changed,affected,recomputed};
}
export function readCandidate(cache: CandidateCache,index: number): CandidateInfo {
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('缓存位置错误');
const entry: CandidateInfo | null = cache.entries[index];
if (entry===null) throw new Error('目标格已有数字');
return copyInfo(entry);
}
export function hintsFromCache(cache: CandidateCache,state: PuzzleState): SingleHint[] {
requirePuzzleState(state);
if (cache.board.join('')!==state.board.join('')) throw new Error('缓存题面不一致');
if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
const hints: SingleHint[] = []; const boardKey: string = state.board.join('');
for (let index: number = 0; index<81; index++) {
if (state.board[index]!==0) continue;
const info: CandidateInfo = readCandidate(cache,index);
if (info.values.length===1) hints.push({index,value:info.values[0],boardKey,info});
}
return hints;
}
当前格描述包含位置与身份
只读出数字一,无法判断它位于哪一格、是否属于固定题面。describeCell把行列、固定身份与当前值合成一段文本。空格明确读为空格,非零值说明当前数字;固定格与可编辑格也使用不同名称,避免仅靠颜色表达编辑权限。
该函数沿用原PuzzleState校验,行列由零起点下标换算。它不会读取输入框中的行列草稿,因为草稿尚未查询或提交时可能指向另一个位置。页面描述始终与selected对应,失败请求也不会让旧题面套上新位置。
// service/AccessibleEdit.ets
import { PuzzleState, requirePuzzleState } from './PuzzleEdit';
export function moveCell(index: number,delta: number): number {
if (!Number.isInteger(index) || index<0 || index>=81 || (delta!==-1 && delta!==1))
throw new Error('位置移动参数错误');
return Math.max(0,Math.min(80,index+delta));
}
export function describeCell(state: PuzzleState,index: number): string {
requirePuzzleState(state);
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
const role: string = state.givens[index] ? '固定题面格' : '可编辑格';
const value: string = state.board[index]===0 ? '空格' : `当前数字${state.board[index]}`;
return `第${Math.floor(index/9)+1}行第${index%9+1}列,${role},${value}`;
}
上一格与下一格按行优先下标移动,边界处保持首格或末格。它们选择目标但不修改数字,同时把行列草稿同步为新目标。移到空格时从当前缓存读取候选,移到已有数字时显示目标格已填,候选摘要不会继续描述之前的空格。
位置移动与编辑历史分别处理。浏览不同目标不会增加有效步骤,也不会使重做分支失效;只有合法内容变化才进入recordEdit。对读屏用户而言,先定位、再输入、再提交的顺序与可见页面保持一致。
快捷键绑定在实际操作按钮上
页面通过keyboardShortcut为原按钮配置功能键。撤销与重做按钮继续由历史游标控制enabled状态,无法撤销时按钮禁用,快捷键也不应绕过禁用条件。提交与查询则保留解析错误提示,用户可以修正输入后重试。
华为快捷键文档说明,快捷键与普通按键事件有优先关系,隐藏组件也可能继续响应绑定。本篇每种动作只保留一个按钮实例,宽窄屏分支只展示其中一组。后续把页面拆成隐藏标签或多窗口内容时,应继续核对是否存在重复注册的同一组合。
// pages/Index.ets
import { initialPuzzle, parseCell } from '../model/Puzzle';
import { CandidateInfo, queryCandidates, digitsText } from '../service/Candidates';
import { PuzzleState, createPuzzleState, commitEdit, findConflicts, parseDigit } from '../service/PuzzleEdit';
import { SingleHint, findSingleHints, applySingleHint, hintText } from '../service/SingleHint';
import { PuzzleHistory, createHistory, recordEdit, undo, redo } from '../service/History';
import { SearchReport, idleReport, analyzePuzzle, parseBudget } from '../service/Search';
import { CandidateCache, CacheUpdate, createCache, updateCache, readCandidate, hintsFromCache } from '../service/CandidateCache';
import { moveCell, describeCell } from '../service/AccessibleEdit';
@Entry
@Component
struct Index {
@State cache: CandidateCache = createCache(initialPuzzle());
@State changedCount: number = 0;
@State affectedCount: number = 0;
@State recomputedCount: number = 51;
@State report: SearchReport = idleReport();
@State budgetText: string = '10000';
@State history: PuzzleHistory = createHistory();
@State hints: SingleHint[] = hintsFromCache(createCache(initialPuzzle()),createPuzzleState());
@State hintIndex: number = 40;
@State digitText: string = '1';
@State candidateText: string = '候选:1、2、4';
@State rowText: string = '1';
@State colText: string = '3';
@State selected: number = 2;
@State info: CandidateInfo = queryCandidates(initialPuzzle(),2);
@State status: string = '已更新';
@State areaWidth: number = 360;
private moveTarget(delta: number): void {
const index: number = moveCell(this.selected,delta);
this.selected=index; this.rowText=`${Math.floor(index/9)+1}`; this.colText=`${index%9+1}`;
if (this.history.state.board[index]===0) {
this.info=readCandidate(this.cache,index); this.candidateText=`候选:${digitsText(this.info.values)}`;
} else this.candidateText='目标格已填';
this.status='已切换目标';
}
private publishCache(update: CacheUpdate): void {
this.cache=update.cache; this.changedCount=update.changed;
this.affectedCount=update.affected; this.recomputedCount=update.recomputed;
}
private analyze(): void {
try {
const report: SearchReport = analyzePuzzle(this.history.state.board,parseBudget(this.budgetText));
this.report=report; this.status='分析完成';
} catch (error) { this.status=error instanceof Error ? error.message : '分析失败'; }
}
private query(): void {
try {
const index: number = parseCell(this.rowText,this.colText);
const next: CandidateInfo = readCandidate(this.cache,index);
this.selected=index; this.info=next; this.candidateText=`候选:${digitsText(next.values)}`; this.status='已查询';
} catch (error) { this.status=error instanceof Error ? error.message : '查询失败'; }
}
private submit(): void {
try {
const index: number = parseCell(this.rowText,this.colText);
const value: number = parseDigit(this.digitText);
const history: PuzzleHistory = recordEdit(this.history,index,value,`manual:${index}`);
const next: PuzzleState = history.state;
const update: CacheUpdate = updateCache(this.cache,next.board);
const hints: SingleHint[] = hintsFromCache(update.cache,next);
this.publishCache(update);
this.history=history; this.refreshHints(hints); this.selected=index;
if (value===0) {
this.info=readCandidate(update.cache,index);
this.candidateText=`候选:${digitsText(this.info.values)}`;
} else this.candidateText='目标格已填';
this.status=`已写入${Math.floor(index/9)+1}行${index%9+1}列`;
} catch (error) { this.status=error instanceof Error ? error.message : '提交失败'; }
}
private refreshHints(hints: SingleHint[]): void {
const retained: boolean = hints.some((hint: SingleHint) => hint.index===this.hintIndex);
this.hints=hints;
if (!retained) this.hintIndex=hints.length>0 ? hints[0].index : -1;
}
private applyHint(hint: SingleHint): void {
try {
const next: PuzzleState = applySingleHint(this.history.state,hint);
const history: PuzzleHistory = recordEdit(this.history,hint.index,hint.value,'hint');
const update: CacheUpdate = updateCache(this.cache,next.board);
const hints: SingleHint[] = hintsFromCache(update.cache,next);
this.publishCache(update);
this.history=history; this.refreshHints(hints); this.selected=hint.index;
this.candidateText='目标格已填'; this.status=`已应用${hintText(hint)}`;
} catch (error) { this.status=error instanceof Error ? error.message : '提示应用失败'; }
}
private travel(back: boolean): void {
try {
const next: PuzzleHistory = back ? undo(this.history) : redo(this.history);
const update: CacheUpdate = updateCache(this.cache,next.state.board);
const hints: SingleHint[] = hintsFromCache(update.cache,next.state);
this.publishCache(update);
const index: number = back ? this.history.steps[this.history.cursor-1].index : this.history.steps[this.history.cursor].index;
this.history=next; this.refreshHints(hints); this.selected=index;
if (next.state.board[index]===0) {
this.info=readCandidate(update.cache,index); this.candidateText=`候选:${digitsText(this.info.values)}`;
} else this.candidateText='目标格已填';
this.status=back ? '已撤销' : '已重做';
} catch (error) { this.status=error instanceof Error ? error.message : '历史操作失败'; }
}
private reset(): void {
this.history=createHistory(); this.cache=createCache(this.history.state.board); this.changedCount=0; this.affectedCount=81; this.recomputedCount=51; this.refreshHints(hintsFromCache(this.cache,this.history.state)); this.selected=2;
this.rowText='1'; this.colText='3'; this.digitText='1';
this.info=queryCandidates(this.history.state.board,2); this.candidateText='候选:1、2、4'; this.status='已恢复题面';
}
@Builder
accessiblePanel(width: number) {
Column({space:12}) {
Text(describeCell(this.history.state,this.selected)).fontSize(22)
.accessibilityText(describeCell(this.history.state,this.selected))
Text(this.candidateText)
Text('F6提交 · F7查询 · F8撤销 · F9重做')
Button('上一格').accessibilityText('选择前一个格子,不改动数字').onClick(() => { this.moveTarget(-1); })
Button('下一格').accessibilityText('选择后一个格子,不改动数字').onClick(() => { this.moveTarget(1); })
Text(`有效步骤:${this.history.cursor}`)
Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
Text(this.status)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
cachePanel(width: number) {
Column({space:12}) {
Text(`当前:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
Text(`当前格值:${this.history.state.board[this.selected]}`)
Text(`变化格数:${this.changedCount}`)
Text(`影响格数:${this.affectedCount}`)
Text(`重算空格:${this.recomputedCount}`)
Text(`缓存空格:${this.cache.entries.filter((item: CandidateInfo | null) => item!==null).length}`)
Text(this.candidateText)
Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
searchPanel(width: number) {
Column({space:12}) {
if (this.report.boardKey===this.history.state.board.join('')) {
Text(`分析结论:${this.report.status}`).fontSize(26)
Text(`已找到解数:${this.report.solutions}`)
Text(`搜索节点:${this.report.nodes}`)
Text(`预算截断:${this.report.cutoff ? '是' : '否'}`)
} else { Text('分析结论:待分析').fontSize(26) }
Text(`当前已填:${this.history.state.board.filter((v: number) => v!==0).length}`)
Text(`当前空格:${this.history.state.board.filter((v: number) => v===0).length}`)
Text(`已应用步骤:${this.history.cursor}`)
Text('搜索参数').fontSize(22)
TextInput({text:this.budgetText,placeholder:'节点预算1至10000'})
.onChange((v: string) => { this.budgetText=v; })
Button('分析当前题面').backgroundColor('#445F97').onClick(() => { this.analyze(); })
Text(this.status)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
historyPanel(width: number) {
Column({space:12}) {
Text(`当前:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
Text(`当前格值:${this.history.state.board[this.selected]}`)
Text(`已应用步骤:${this.history.cursor}`)
Text(`可撤销:${this.history.cursor} · 可重做:${this.history.steps.length-this.history.cursor}`)
if (this.history.cursor>0) {
Text(`最近步骤:${this.history.steps[this.history.cursor-1].before}→${this.history.steps[this.history.cursor-1].after}`)
}
Button('撤销').keyboardShortcut(FunctionKey.F8,[]).accessibilityText('撤销上一条已应用步骤,快捷键F8').enabled(this.history.cursor>0).onClick(() => { this.travel(true); })
Button('重做').keyboardShortcut(FunctionKey.F9,[]).accessibilityText('重做下一条历史步骤,快捷键F9').enabled(this.history.cursor<this.history.steps.length).onClick(() => { this.travel(false); })
Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
hintDetail(hint: SingleHint) {
Column({space:12}) {
Text(`提示:${hintText(hint)}`).fontSize(22)
Text(`行已用:${digitsText(hint.info.rowUsed)}`)
Text(`列已用:${digitsText(hint.info.colUsed)}`)
Text(`宫已用:${digitsText(hint.info.boxUsed)}`)
Text(`剩余候选:${hint.value}`).fontSize(26).fontColor('#445F97')
Button('应用当前提示').backgroundColor('#445F97').onClick(() => { this.applyHint(hint); })
}.width('100%')
}
@Builder
hintPanel(width: number) {
Column({space:12}) {
Text('宽屏键盘输入与可访问性').fontSize(22)
Text(`单格唯一候选:${this.hints.length}处`)
Flex({direction:FlexDirection.Row,wrap:FlexWrap.Wrap}) {
ForEach(this.hints,(hint: SingleHint) => {
Button(hintText(hint)).fontSize(12).width((width-56)/3).margin(4)
.backgroundColor(hint.index===this.hintIndex ? '#445F97' : '#A8B8D7')
.onClick(() => { this.hintIndex=hint.index; })
},(hint: SingleHint) => `${hint.index}`)
}.width('100%')
ForEach(this.hints.filter((hint: SingleHint) => hint.index===this.hintIndex),(hint: SingleHint) => {
this.hintDetail(hint)
},(hint: SingleHint) => `${hint.boardKey}:${hint.index}`)
if (this.hints.length===0) { Text('当前没有单格唯一候选') }
Text(`已填格:${this.history.state.board.filter((value: number) => value!==0).length} · 空格:${this.history.state.board.filter((value: number) => value===0).length}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
inputPanel(width: number) {
Column({space:12}) {
Text('目标格输入').fontSize(22)
TextInput({text:this.rowText,placeholder:'行'}).accessibilityText('目标行,输入一至九')
.onChange((value: string) => { this.rowText=value; this.status='输入待查询'; })
TextInput({text:this.colText,placeholder:'列'}).accessibilityText('目标列,输入一至九')
.onChange((value: string) => { this.colText=value; this.status='输入待查询'; })
TextInput({text:this.digitText,placeholder:'填入0至9,0清空'}).accessibilityText('填入值,零表示清空')
.onChange((value: string) => { this.digitText=value; this.status='输入待提交'; })
Button('提交填数').keyboardShortcut(FunctionKey.F6,[]).accessibilityText('提交当前行列与填入值,快捷键F6').backgroundColor('#445F97').onClick(() => { this.submit(); })
Button('查询候选').keyboardShortcut(FunctionKey.F7,[]).accessibilityText('查询输入行列的候选,快捷键F7').backgroundColor('#445F97').onClick(() => { this.query(); })
Text(this.status)
Text(`已填格:${this.history.state.board.filter((value: number) => value!==0).length}`)
Text(`空格:${this.history.state.board.filter((value: number) => value===0).length}`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
resultPanel(width: number) {
Column({space:14}) {
Text(`目标:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
Text(`当前格值:${this.history.state.board[this.selected]}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
Text(`有效修改:${this.history.cursor}`)
if (this.history.state.board[this.selected]===0) {
Text(`行已用:${digitsText(this.info.rowUsed)}`)
Text(`列已用:${digitsText(this.info.colUsed)}`)
Text(`宫已用:${digitsText(this.info.boxUsed)}`)
}
Text(this.candidateText).fontSize(26).fontColor('#445F97')
Button('恢复题面').onClick(() => { this.reset(); })
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
build() {
Scroll() {
Column({space:16}) {
Text('数独候选台').fontSize(26).fontWeight(FontWeight.Bold)
Text('宽屏键盘输入与可访问性')
if (this.areaWidth>=840) {
Row({space:16}) {
Column({space:16}) {
this.accessiblePanel((this.areaWidth-56)/2)
this.cachePanel((this.areaWidth-56)/2)
this.searchPanel((this.areaWidth-56)/2)
this.historyPanel((this.areaWidth-56)/2)
this.hintPanel((this.areaWidth-56)/2)
}
Column({space:16}) {
this.inputPanel((this.areaWidth-56)/2)
this.resultPanel((this.areaWidth-56)/2)
}
}.alignItems(VerticalAlign.Top)
} else {
this.accessiblePanel(this.areaWidth-40)
this.cachePanel(this.areaWidth-40)
this.searchPanel(this.areaWidth-40)
this.historyPanel(this.areaWidth-40)
this.hintPanel(this.areaWidth-40)
this.inputPanel(this.areaWidth-40)
this.resultPanel(this.areaWidth-40)
}
}.width('100%').padding(20)
}.width('100%').height('100%').backgroundColor('#F1F4FA')
.onAreaChange((oldArea: Area,newArea: Area) => {
const width: number = Number(newArea.width);
if (Number.isFinite(width) && width>40 && width!==this.areaWidth) this.areaWidth=width;
})
}
}

本篇使用F6至F9,避免把文本编辑常用组合直接绑定为题面操作。输入框内的字符编辑和系统走焦继续由组件处理,不在整个页面捕获数字键后立即写题面。这样用户在行列框修改数字时,不会意外把同一个按键也填到当前格。
快捷键应与真实设备的功能键行为一起检查。有些键盘需要配合Fn键输出功能键,页面保留按钮与明确的文字说明,使核心动作仍可通过其他输入方式完成。代码中的动作绑定与业务正确性分别核对,不能只凭快捷键说明文字判断操作链已经接通。
为输入与按钮补充语义
行输入框说明目标行、一至九;列输入框说明目标列、一至九;填入值说明零用于清空。提交与查询按钮的可访问性文本同时说明动作和快捷键,上一格与下一格则明确说明只是选择位置,不改动数字。
当前格摘要使用与可见文本相同的完整描述,使视觉用户与读屏用户都能获得位置、身份和数字信息。没有把整个操作区域合并为一个不可细分的大控件,输入框与操作按钮仍可分别被访问,避免用户只能听到摘要却找不到执行入口。
用一次提交核对入口等价性
从初始题面的一行三列开始,填入值设为一,通过提交按钮或F6触发相同处理。成功后描述为第一行第三列、可编辑格、当前数字一,有效步骤为一,已填格三十一、空格五十,缓存刷新仍按上一章的规则进行。

接着使用撤销按钮或F8,目标恢复为空格,候选重新显示一、二、四;再使用重做按钮或F9,恢复数字一。两种输入方式都应得到同样的历史游标、题面数字和缓存摘要,不能让快捷键只更新显示文本而遗漏实际状态。
对固定题面格尝试提交零,或在一行三列填入已有的五,原编辑入口应拒绝。当前描述、有效步骤与棋盘保持原值,提示区域给出错误。对快捷入口也执行这些拒绝样本,可以发现某个绑定是否误连到了直接数组修改函数。
目标浏览与草稿查询各有用途
上一格、下一格浏览的是当前selected附近位置,查询候选使用输入框草稿。用户把行列改为另一空格但尚未查询时,顶部描述仍对应原目标;按F7查询成功后再切换selected和候选。这样草稿编辑与结果身份保持明确的提交边界。
如果查询的目标已有数字,原查询服务会拒绝,当前摘要保留此前成功目标。用户仍可以通过上一格、下一格浏览到已填位置并获得身份描述。查询空格候选与浏览所有格子的用途不同,页面分别保留入口。
分栏不复制操作状态
窄屏前置目标描述、浏览按钮与状态摘要,宽屏把它们放在结果侧,输入和原查询区放在另一侧。两种布局继续共享history、cache、selected和输入草稿,不因为窗口变宽而产生另一份当前格。布局回调只更新有效宽度,不触发提交或撤销。
核对可访问性时,还要检查焦点顺序、按钮可达性和错误提示内容。描述文本应随着目标与数字变化,而不是使用固定的一行三列样本。字号、颜色和控件间距可以改进可见体验,但不能替代对固定身份与执行后果的文字表达。
本篇将键盘、点击与可访问性语义接到同一组工程入口:输入框保存草稿,按钮执行动作,历史与缓存处理事实变化,描述服务表达当前目标。下一章导入导出题面时,也可以沿用这些入口核对加载后的身份、候选和编辑状态。
位置描述还要覆盖首格、末格、固定格和清空后的可编辑格。边界按钮保持同一目标时,历史游标应保持原值;从已填位置移动到空格时,候选说明应立刻对应新目标。把这类序列与提交失败、撤销后重做并列检查,可以区分浏览信息变化和题面事实变化,避免将读屏文本更新误接成一次编辑步骤。
相关资料
更多推荐




所有评论(0)