File size: 2,092 Bytes
25058c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { Page, PageTemplateDefinition } from "../types/session";

export const BUILTIN_PAGE_TEMPLATES: PageTemplateDefinition[] = [
  {
    id: "repex:standard",
    name: "Standard Job Sheet",
    description: "Observations + up to two photos.",
    blank: false,
    variant: "full",
    source: "builtin",
  },
  {
    id: "repex:photos",
    name: "Photo Continuation",
    description: "Photo-only continuation page.",
    blank: false,
    variant: "photos",
    source: "builtin",
  },
  {
    id: "repex:blank",
    name: "Blank Canvas",
    description: "Blank white page.",
    blank: true,
    variant: "full",
    source: "builtin",
  },
];

export function mergePageTemplates(
  customTemplates?: PageTemplateDefinition[],
): PageTemplateDefinition[] {
  const byId = new Map<string, PageTemplateDefinition>();
  BUILTIN_PAGE_TEMPLATES.forEach((template) => {
    byId.set(template.id, template);
  });
  (customTemplates ?? []).forEach((template) => {
    if (!template?.id) return;
    byId.set(template.id, { ...template, source: "custom" });
  });
  return Array.from(byId.values());
}

export function inferPageTemplateId(page?: Page | null): string {
  if (page?.page_template) return page.page_template;
  if (page?.blank) return "repex:blank";
  if (page?.variant === "photos") return "repex:photos";
  return "repex:standard";
}

export function resolvePageTemplate(
  page: Page | null | undefined,
  templates: PageTemplateDefinition[],
): PageTemplateDefinition {
  const id = inferPageTemplateId(page);
  return (
    templates.find((template) => template.id === id) ??
    BUILTIN_PAGE_TEMPLATES[0]
  );
}

export function applyPageTemplateToPage(
  page: Page,
  template: PageTemplateDefinition,
): Page {
  const next: Page = {
    ...page,
    page_template: template.id,
    blank: Boolean(template.blank),
    variant: template.variant ?? "full",
  };
  if (template.photo_layout) {
    next.photo_layout = template.photo_layout;
  }
  return next;
}

export function createCustomTemplateId() {
  return `tpl_${crypto.randomUUID().replace(/-/g, "")}`;
}