示例工程 16-shadcn-ui-component-layer

16-shadcn-ui-component-layer/demo-03-select-toast/state.ts

typescript · 1.6 KB

type Option = { value: string; label: string };
type Toast = { id: string; title: string };

function resolveLabel(options: Option[], value: string): string {
  return options.find((option) => option.value === value)?.label ?? value;
}

function createToastQueue(limit: number) {
  const items: Toast[] = [];
  return {
    add(toast: Toast): void {
      const index = items.findIndex((item) => item.id === toast.id);
      if (index >= 0) items.splice(index, 1);
      items.push(toast);
      while (items.length > limit) items.shift();
    },
    close(id: string): void {
      const index = items.findIndex((item) => item.id === id);
      if (index >= 0) items.splice(index, 1);
    },
    list(): Toast[] {
      return [...items];
    },
  };
}

const options = [
  { value: "sans", label: "Sans-serif" },
  { value: "serif", label: "Serif" },
  { value: "mono", label: "Monospace" },
];

const queue = createToastQueue(3);
queue.add({ id: "a", title: "保存成功" });
queue.add({ id: "b", title: "已导出" });
queue.add({ id: "c", title: "同步完成" });
queue.add({ id: "d", title: "更新可用" });
queue.add({ id: "d", title: "更新可用(替换)" });
const list = queue.list();

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      resolveLabel(options, "serif") === "Serif" &&
      resolveLabel(options, "unknown") === "unknown" &&
      list.length === 3 &&
      !list.some((item) => item.id === "a") &&
      list.filter((item) => item.id === "d").length === 1,
    label: resolveLabel(options, "serif"),
    ids: list.map((item) => item.id),
  }),
);