-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstate.ts
More file actions
99 lines (84 loc) · 2.27 KB
/
Copy pathstate.ts
File metadata and controls
99 lines (84 loc) · 2.27 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import type { LogLevel } from "@shopify/checkout-kit";
import { buildCartPermalink, type CartLine, type ProductVariantOption } from "./cart";
import type { SourceMode } from "./storage";
export type { SourceMode };
export type NoticeTone = "info" | "success" | "error";
export type LogEntry = {
type: string;
time: string;
snapshot: string;
};
export type ComponentSnapshot = {
checkout: unknown;
error: unknown;
};
export type CartStatus = {
message: string;
tone: NoticeTone;
};
export type SettingsSlice = {
sourceMode: SourceMode;
storefrontDomain: string;
target: string;
appearance: string;
logLevel: LogLevel;
manualSrc: string;
settingsCollapsed: boolean;
eventsCollapsed: boolean;
};
export type AppState = SettingsSlice & {
variants: ProductVariantOption[];
cartLines: CartLine[];
loadState: string;
cartStatus: CartStatus;
component: ComponentSnapshot;
log: LogEntry[];
};
export const INITIAL_LOAD_STATE = "Waiting for domain";
export const INITIAL_CART_STATUS: CartStatus = {
message: "Enter a storefront domain to load products automatically.",
tone: "info",
};
export function createInitialState(settings: SettingsSlice): AppState {
return {
...settings,
variants: [],
cartLines: [],
loadState: INITIAL_LOAD_STATE,
cartStatus: INITIAL_CART_STATUS,
component: { checkout: undefined, error: undefined },
log: [],
};
}
export type Store = {
getState(): AppState;
setState(partial: Partial<AppState>): void;
subscribe(listener: () => void): void;
};
export function createStore(initial: AppState): Store {
let state = initial;
const listeners = new Set<() => void>();
return {
getState: () => state,
setState(partial) {
state = { ...state, ...partial };
for (const listener of listeners) {
listener();
}
},
subscribe(listener) {
listeners.add(listener);
},
};
}
export function selectGeneratedCartUrl(state: AppState): string {
if (state.cartLines.length === 0) return "";
try {
return buildCartPermalink(state.storefrontDomain, state.cartLines);
} catch {
return "";
}
}
export function selectActiveSourceUrl(state: AppState): string {
return state.sourceMode === "manual" ? state.manualSrc.trim() : selectGeneratedCartUrl(state);
}