示例工程 20-routing-and-panels

20-routing-and-panels/demo-02-history-stack/history.ts

typescript · 1.4 KB

class RouterHistory {
  private stack: string[];
  private index = 0;

  constructor(initial: string) {
    this.stack = [initial];
  }

  get current(): string {
    return this.stack[this.index] ?? "";
  }

  get canBack(): boolean {
    return this.index > 0;
  }

  get canForward(): boolean {
    return this.index < this.stack.length - 1;
  }

  push(path: string): string {
    if (path === this.current) return this.current;
    this.stack = this.stack.slice(0, this.index + 1);
    this.stack.push(path);
    this.index = this.stack.length - 1;
    return this.current;
  }

  back(): string {
    if (this.canBack) this.index -= 1;
    return this.current;
  }

  forward(): string {
    if (this.canForward) this.index += 1;
    return this.current;
  }
}

const nav = new RouterHistory("#/docs/intro");
const steps = [
  nav.push("#/docs/layout"),
  nav.push("#/settings"),
  nav.back(),
  nav.back(),
  nav.forward(),
  nav.push("#/docs/commands"),
  nav.forward(),
];

const expected = [
  "#/docs/layout",
  "#/settings",
  "#/docs/layout",
  "#/docs/intro",
  "#/docs/layout",
  "#/docs/commands",
  "#/docs/commands",
];

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      steps.every((value, index) => value === expected[index]) &&
      !nav.canForward &&
      nav.current === "#/docs/commands",
    steps,
    canBack: nav.canBack,
    canForward: nav.canForward,
    current: nav.current,
  }),
);