Blame view

泰额版/Food Labeling Management Platform/src/lib/labelTemplateStorage.ts 1.53 KB
884054fb   “wangming”   项目初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  /**
   * 标签模板 LocalStorage 读写
   * Key: label-template-{id}
   * 列表: label-template-ids = string[]
   */
  
  import type { LabelTemplate } from '../types/labelTemplate';
  import { getStorageKey, getIdsKey } from '../types/labelTemplate';
  
  export function getTemplateIds(): string[] {
    try {
      const raw = localStorage.getItem(getIdsKey());
      if (!raw) return [];
      const ids = JSON.parse(raw) as string[];
      return Array.isArray(ids) ? ids : [];
    } catch {
      return [];
    }
  }
  
  export function getTemplate(id: string): LabelTemplate | null {
    try {
      const raw = localStorage.getItem(getStorageKey(id));
      if (!raw) return null;
      return JSON.parse(raw) as LabelTemplate;
    } catch {
      return null;
    }
  }
  
  export function getTemplateList(): LabelTemplate[] {
    const ids = getTemplateIds();
    const list: LabelTemplate[] = [];
    for (const id of ids) {
      const t = getTemplate(id);
      if (t) list.push(t);
    }
    return list.sort((a, b) => (b.id > a.id ? 1 : -1));
  }
  
  function setTemplateIds(ids: string[]): void {
    localStorage.setItem(getIdsKey(), JSON.stringify(ids));
  }
  
  export function saveTemplate(template: LabelTemplate): void {
    const key = getStorageKey(template.id);
    localStorage.setItem(key, JSON.stringify(template));
    const ids = getTemplateIds();
    if (!ids.includes(template.id)) {
      ids.push(template.id);
      setTemplateIds(ids);
    }
  }
  
  export function deleteTemplate(id: string): void {
    localStorage.removeItem(getStorageKey(id));
    const ids = getTemplateIds().filter((x) => x !== id);
    setTemplateIds(ids);
  }