恢复一份阅读记录后,返回键应该回到哪里?如果恢复的只是当前资料,用户会失去之前的阅读路径;如果把整个页面对象保存下来,又会把请求序号、滚动控制器和临时展示状态带进恢复数据。先从期望的返回效果倒推,就能看出这两种做法都缺少明确边界。

返回路径与快照白名单封面

一、从返回行为反推快照内容

阅读工作台允许依次打开layout与state,两条路径使用同一个reading目的页名称,参数分别是稳定资料id。恢复以后,返回顺序应继续遵守这条历史,而不是仅保留最后显示的标题。因此快照需要有序路径数组,不能用目的页名称作为唯一键,也不能用一个“当前资料”字段代替完整历史。

段落锚点又属于另一维度。上一节AnchorBook按资料记录最近首段,同一资料的多个历史实例共享该位置。快照因此保存资料与段落标识,不为每次入栈生成独立书签。这个约定决定了同一资料在历史里出现两次时,恢复后会消费同一个最近阅读锚点;要改变产品语义,需要增加会话身份。

资料标题和正文没有进入快照。它们由当前仓储重新读取,经过已有请求接收检查后显示。恢复数据只说用户想去哪里,不把一份旧正文当作当前事实。这样内容更新与导航恢复可以分别演进,页面不会因为旧标题还在JSON中就跳过仓储。

可恢复数据与运行期对象的边界

二、从对象结构反推需要丢弃什么

版本一的业务快照只允许version、paths、anchors与lastSelectedId。路径条目只复制name和itemId,锚点只复制itemId和paragraphId。输入中即使带了其他属性,解码器也不把它们传给路由。白名单的意义是重新构造需要的数据,而不是检查几个字段以后直接返回原对象。

requestVersion、visible、Scroller与heldParagraphId都留在运行期。旧请求的编号跨进程没有意义,滚动控制器更不是可以序列化的业务对象。字号切换期间的冻结目标只保护当前交互,恢复时由新页面重新建立,不把尚未完成的一半交互带进下一次显示。

示例资料集合仍然只有layout与state,段落后缀沿用上一节的固定语义标签。解码时要求锚点属于对应资料,拒绝把state的条目指向layout:intro。真实内容层接入后,应从经过校验的资料目录取得标识白名单,并处理删除、修订和访问权限变化;不能长期把开发样本名单当作完整产品目录。

三、先完整解码,再改变当前栈

沿用API12及以上Stage工程,不新增权限和依赖。以下完整Index.ets替换上一节同名文件。AnchorBook增加导出副本与替换副本的方法,ReadingDetail的请求门禁和段落恢复逻辑保持不变。Navigation仍由Index持有,路由参数仍是字符串id。

interface ReadingItem {
  id: string;
  title: string;
  content: string;
}

class ReadingRepository {
  private items: ReadingItem[] = [
    { id: 'layout', title: '布局约束', content: '先确定父容器约束,再分析子节点尺寸。' },
    { id: 'state', title: '状态边界', content: '让状态归属与业务生命周期保持一致。' }
  ];

  get(id: string): Promise<ReadingItem | undefined> {
    return new Promise<ReadingItem | undefined>((resolve) => {
      const delay = id === 'layout' ? 600 : 80;
      setTimeout(() => {
        resolve(this.items.find((item: ReadingItem) => item.id === id));
      }, delay);
    });
  }
}

@Entry
@Component
struct Index {
  private paths: NavPathStack = new NavPathStack();
  private repository: ReadingRepository = new ReadingRepository();
  @State private lastSelectedId: string = '';
  @State private availableWidth: number = 0;
  @State private snapshotText: string = '';
  @State private restoreMessage: string = '';
  private items: ReadingItem[] = [
    { id: 'layout', title: '布局约束', content: '' },
    { id: 'state', title: '状态边界', content: '' }
  ];

  private openItem(id: string): void {
    if (!this.items.some((item: ReadingItem) => item.id === id)) {
      return;
    }
    this.lastSelectedId = id;
    this.paths.pushPath({ name: 'reading', param: id });
  }

  private exportSnapshot(): void {
    try {
      const names = this.paths.getAllPathName();
      const entries: SavedReadingPath[] = [];
      for (let index = 0; index < names.length; index++) {
        const param = this.paths.getParamByIndex(index);
        if (names[index] !== 'reading' || typeof param !== 'string' || !knownItem(param)) {
          throw new Error('当前栈包含不支持的路径');
        }
        entries.push({ name: 'reading', itemId: param });
      }
      const value: ReadingSnapshot = { version: 1, paths: entries,
        anchors: readingAnchors.exportValues(), lastSelectedId: this.lastSelectedId };
      this.snapshotText = JSON.stringify(decodeSnapshot(JSON.stringify(value)));
      this.restoreMessage = '已导出当前业务快照';
    } catch (_) { this.restoreMessage = '导出失败,请检查当前路径'; }
  }
  private importSnapshot(): void {
    let value: ReadingSnapshot;
    try { value = decodeSnapshot(this.snapshotText); }
    catch (_) { this.restoreMessage = '恢复文本无效,当前栈保持原样'; return; }
    try {
      readingAnchors.replaceValues(value.anchors);
      this.paths.clear();
      for (const entry of value.paths) this.paths.pushPath({ name: 'reading', param: entry.itemId }, false);
      this.lastSelectedId = value.lastSelectedId;
      this.restoreMessage = '业务路径已恢复,正文按当前请求重新读取';
    } catch (_) {
      this.paths.clear();
      this.restoreMessage = '路径应用失败,已返回资料库';
    }
  }

  @Builder
  private destination(name: string, param: Object) {
    if (name === 'reading' && typeof param === 'string') {
      ReadingDetail({ itemId: param, repository: this.repository })
    } else {
      NavDestination() {
        Text('页面入口无效,请返回资料列表')
      }.title('入口检查')
    }
  }

  build() {
    Navigation(this.paths) {
      Column({ space: 16 }) {
        Text('资料库').fontSize(24)
        Text('容器宽度:' + this.availableWidth.toFixed(0) + 'vp')
        ForEach(this.items, (item: ReadingItem) => {
          Button((this.lastSelectedId === item.id ? '最近选择 · ' : '') + item.title)
            .width('90%').onClick(() => this.openItem(item.id))
        }, (item: ReadingItem) => item.id)
        Button('最近阅读:布局约束').onClick(() => this.openItem('layout'))
        Button('导出阅读快照').onClick(() => { this.exportSnapshot(); })
        TextArea({ text: this.snapshotText, placeholder: '粘贴阅读快照JSON' })
          .height(110).onChange((value: string) => { this.snapshotText = value; })
        Button('恢复阅读快照').onClick(() => { this.importSnapshot(); })
        Text(this.restoreMessage)
      }.width('100%').padding(20)
    }
    .title('阅读工作台')
    .mode(NavigationMode.Auto)
    .navBarWidth(280)
    .navDestination(this.destination)
    .width('100%').height('100%')
    .onAreaChange((oldArea: Area, newArea: Area) => {
      const width = Number(newArea.width);
      if (Number.isFinite(width) && width !== this.availableWidth) {
        this.availableWidth = width;
      }
    })
  }
}

interface ReadingParagraph { id: string; text: string; }
interface ReadingAnchor { itemId: string; paragraphId: string; }
class AnchorBook {
  private values: ReadingAnchor[] = [];
  exportValues(): ReadingAnchor[] {
    return this.values.map((value: ReadingAnchor) => ({ itemId: value.itemId, paragraphId: value.paragraphId }));
  }
  replaceValues(values: ReadingAnchor[]): void {
    this.values = values.map((value: ReadingAnchor) => ({ itemId: value.itemId, paragraphId: value.paragraphId }));
  }
  read(id: string): string {
    const found = this.values.find((value: ReadingAnchor) => value.itemId === id);
    return found === undefined ? '' : found.paragraphId;
  }
  write(id: string, paragraphId: string): void {
    this.values = this.values.filter((value: ReadingAnchor) => value.itemId !== id);
    this.values.push({ itemId: id, paragraphId });
  }
}
const readingAnchors: AnchorBook = new AnchorBook();
function paragraphsFor(item: ReadingItem): ReadingParagraph[] {
  return [
    { id: item.id + ':intro', text: item.content },
    { id: item.id + ':scope', text: '阅读位置属于资料,而不是当前窗口宽度。窗口变化时保留资料标识。' },
    { id: item.id + ':owner', text: '段落标识由内容结构提供。显示字号改变时,标识及其含义保持一致。' },
    { id: item.id + ':layout', text: '同一段文字可能重新换行。字号与可用宽度共同决定段落高度。' },
    { id: item.id + ':async', text: '异步正文必须通过当前请求的接收检查,再进入可定位状态。' },
    { id: item.id + ':failure', text: '目标段落不再存在时退回开头,不沿用另一份资料的数组下标。' },
    { id: item.id + ':restore', text: '本次恢复以段落顶部为单位,段落内部的精确字词位置需要另行建模。' }
  ];
}

@Component
struct ReadingDetail {
  @Prop @Watch('onIdChanged') itemId: string = '';
  repository: ReadingRepository = new ReadingRepository();
  @State private phase: string = 'idle';
  @State private titleText: string = '';
  @State private paragraphs: ReadingParagraph[] = [];
  @State private fontSizeValue: number = 18;
  @State private heldParagraphId: string = '';
  private scroller: Scroller = new Scroller();
  private requestVersion: number = 0;
  private visible: boolean = false;
  private firstIndex: number = 0;

  private onIdChanged(): void {
    this.requestVersion++;
    if (this.visible) this.reload();
  }
  private invalidate(): void { this.visible = false; this.requestVersion++; }
  aboutToDisappear(): void { this.invalidate(); }
  private indexFor(id: string): number {
    const index = this.paragraphs.findIndex((p: ReadingParagraph) => p.id === id);
    return index < 0 ? 0 : index;
  }
  private async reload(): Promise<void> {
    if (!this.visible) return;
    const version = ++this.requestVersion;
    const id = this.itemId;
    this.phase = 'loading';
    this.heldParagraphId = '';
    try {
      const item = await this.repository.get(id);
      if (!this.visible || version !== this.requestVersion || id !== this.itemId) return;
      if (item === undefined) { this.phase = 'empty'; return; }
      this.titleText = item.title;
      this.paragraphs = paragraphsFor(item);
      this.firstIndex = this.indexFor(readingAnchors.read(id));
      this.phase = 'ready';
    } catch (_) {
      if (this.visible && version === this.requestVersion && id === this.itemId) this.phase = 'error';
    }
  }
  private changeFont(): void {
    if (this.phase !== 'ready' || this.heldParagraphId !== '') return;
    this.heldParagraphId = readingAnchors.read(this.itemId);
    if (this.heldParagraphId === '' && this.paragraphs.length > 0) {
      this.heldParagraphId = this.paragraphs[0].id;
    }
    this.fontSizeValue = this.fontSizeValue === 18 ? 26 : 18;
  }
  private restore(): void {
    if (this.phase !== 'ready' || this.heldParagraphId === '') return;
    const index = this.indexFor(this.heldParagraphId);
    this.scroller.scrollToIndex(index, false, ScrollAlign.START);
    readingAnchors.write(this.itemId, this.paragraphs[index].id);
    this.heldParagraphId = '';
  }
  build() {
    NavDestination() {
      Column({ space: 12 }) {
        if (this.phase === 'ready') {
          Text(this.titleText).fontSize(24)
          Button('切换字号').enabled(this.heldParagraphId === '')
            .onClick(() => { this.changeFont(); })
          Button('恢复到原段落').enabled(this.heldParagraphId !== '')
            .onClick(() => { this.restore(); })
          List({ scroller: this.scroller, initialIndex: this.firstIndex, space: 16 }) {
            ForEach(this.paragraphs, (paragraph: ReadingParagraph) => {
              ListItem() { Text(paragraph.text).fontSize(this.fontSizeValue).width('100%').padding(16) }
            }, (paragraph: ReadingParagraph) => paragraph.id)
          }.layoutWeight(1).width('100%').enabled(this.heldParagraphId === '')
          .onScrollIndex((first: number) => {
            if (this.visible && this.phase === 'ready' && this.heldParagraphId === '' && first >= 0 && first < this.paragraphs.length) {
              readingAnchors.write(this.itemId, this.paragraphs[first].id);
            }
          })
        } else {
          Text(this.phase === 'loading' ? '正在读取资料' : '资料暂不可用')
        }
        Button('重新读取').onClick(() => { this.reload(); })
      }.padding(24).width('100%').height('100%')
    }.title('阅读详情')
    .onShown(() => { this.visible = true; this.reload(); })
    .onHidden(() => { this.invalidate(); })
  }
}

interface SavedReadingPath { name: string; itemId: string; }
interface ReadingSnapshot {
  version: number;
  paths: SavedReadingPath[];
  anchors: ReadingAnchor[];
  lastSelectedId: string;
}
const knownReadingIds: string[] = ['layout', 'state'];
const knownParagraphTags: string[] = ['intro', 'scope', 'owner', 'layout', 'async', 'failure', 'restore'];
function knownItem(id: string): boolean { return knownReadingIds.includes(id); }
function decodeSnapshot(text: string): ReadingSnapshot {
  if (text.length > 20000) throw new Error('恢复文本过长');
  const input = JSON.parse(text) as ReadingSnapshot;
  if (input === null || typeof input !== 'object' || input.version !== 1 ||
    !Array.isArray(input.paths) || input.paths.length > 20 ||
    !Array.isArray(input.anchors) || input.anchors.length > 2 ||
    typeof input.lastSelectedId !== 'string' ||
    (input.lastSelectedId !== '' && !knownItem(input.lastSelectedId))) {
    throw new Error('恢复快照结构无效');
  }
  const paths: SavedReadingPath[] = [];
  for (const entry of input.paths) {
    if (entry === null || typeof entry !== 'object' || entry.name !== 'reading' ||
      typeof entry.itemId !== 'string' || !knownItem(entry.itemId)) {
      throw new Error('恢复路径不在白名单内');
    }
    paths.push({ name: 'reading', itemId: entry.itemId });
  }
  const anchors: ReadingAnchor[] = [];
  const seen: string[] = [];
  for (const entry of input.anchors) {
    if (entry === null || typeof entry !== 'object' || typeof entry.itemId !== 'string' ||
      !knownItem(entry.itemId) || typeof entry.paragraphId !== 'string' ||
      !knownParagraphTags.some((tag: string) => entry.paragraphId === entry.itemId + ':' + tag) ||
      seen.includes(entry.itemId)) throw new Error('锚点无效或重复');
    seen.push(entry.itemId);
    anchors.push({ itemId: entry.itemId, paragraphId: entry.paragraphId });
  }
  return { version: 1, paths, anchors, lastSelectedId: input.lastSelectedId };
}

导出时通过getAllPathName取得顺序,再通过getParamByIndex读取对应参数。若出现不支持的目的页或非法资料参数,导出失败,不把半份历史写成可恢复快照。导出结果也走一次相同解码器,避免内部对象将来增加字段后悄悄绕开格式约定。

恢复时先在局部变量里完成全部结构和白名单校验。格式失败只改变提示,不清栈、不替换锚点。通过之后,先安装锚点,再清空旧目的页,最后按数组顺序压入路径。新详情接受当前正文后,继续使用initialIndex消费对应段落,恢复逻辑不直接操作详情内部的Scroller。

导出与恢复的具体操作位置

清栈和压栈是界面操作,并不是一个数据库事务。输入校验通过不意味着每个运行期操作都必然成功;代码在应用路径失败时回到资料库并显示失败提示,不向用户保证已完整恢复。产品需要更强的恢复体验时,应增加恢复阶段与可重试入口,而不是隐藏异常继续报告成功。

四、从异常快照反推验证用例

未知版本必须拒绝。版本号描述的是快照字段的解释方式,不能在读到未来版本时仍按版本一处理。当前代码没有迁移分支,未来需要升级时应显式新增转换,并保留旧版本用例。不要只改一个常量让旧解码器接受新结构。

数组长度与文本长度也有界限。这里最多二十条路径、两份资料锚点,文本最多两万个字符。这些是当前示例的工程约束,不是HarmonyOS路由上限;它们用于限制恢复操作规模。若产品扩大资料集合,应一起调整范围与验证用例,而不是仅删除限制。

同名目的页重复出现是合法历史,不应为了数组去重而丢掉返回路径;同一资料锚点重复出现则会带来解释歧义,因此拒绝。两个数组采用不同重复策略,来自它们不同的业务含义。把所有数组都统一去重,看似整洁,却会改变用户能观察到的返回行为。

恢复快照的接受与拒绝条件

可以直接对纯解码函数做回放:合法快照保持路径顺序,额外属性被丢弃,未知版本与未知目的页被拒绝,跨资料锚点被拒绝。再在目标工程中执行导出、粘贴、恢复、返回,观察目的页生命周期与异步读取。这两组检查分别验证数据协议和界面接入,不用一组逻辑结果代替另一组。

五、恢复能力还没有等于持久化能力

本节通过文本框导出和导入JSON,方便检查协议;它没有自动监听系统保存事件,也没有把快照落盘。手工复制文本后重新打开工程页面,可以再次导入,但进程退出不会自动保留当前文本。接入文件或偏好存储时,应在同一个编解码边界外增加持久化适配器。

保存时机应由产品交互和生命周期共同决定。把每一次滚动回调都变成全量JSON写入,会增加无意义工作;只在进程结束时保存,又可能错过可用时机。更合理的下一步是定义业务检查点、合并更新和失败重试,并说明保存成功具体意味着哪一层完成。

恢复文本也可能包含敏感的业务标识。当前样本只使用公开示例id,实际产品需要最小化记录、控制导出入口与日志内容。不要因为快照没有正文,就推断它永远不包含用户阅读偏好。协议白名单降低了意外字段扩散,却不替代产品的数据管理规则。

还有一个容易混淆的字段是lastSelectedId。它继续表示入口最近选择,返回操作并不一定把它改成当前栈顶,因此不能在导出时直接用栈顶覆盖它。快照分别记录路径与最近选择,恢复后各自回到原来的语义,避免为了减少一个字段而让入口提示发生变化。

导入动作也应与普通打开动作分开。普通openItem包含用户选择的语义,恢复则在白名单验证后按顺序重建已有路径。如果循环调用openItem,会顺带重写最近选择,并把恢复过程混入选择记录。当前代码直接使用经过校验的条目重建栈,后续若增加埋点,也需要给恢复动作单独分类。

沿着返回效果倒推下来,需要保存的是有序业务路径和有限锚点,需要重建的是请求、组件与控制器。下一节将用完整场景检查收尾,验证导航、异步读取、字号变化和快照恢复之间的边界,避免每个局部功能单独正确、组合以后却互相改写状态。

参考资料:Navigation与NavPathStack、Navigation路由操作、List。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐