-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathonboarding.component.tsx
More file actions
192 lines (169 loc) · 5.12 KB
/
onboarding.component.tsx
File metadata and controls
192 lines (169 loc) · 5.12 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { createContext, useEffect, useMemo, useState } from "react";
import { OnboardingAPI, OnboardingState } from "./onboarding.types";
import { AnonymousUser, Errors, JsonObject } from "@slashid/slashid";
import { ensureError } from "../../domain/errors";
import { Loading } from "@slashid/react-primitives";
import { useSlashID } from "../../hooks/use-slash-id";
const initialOnboardingState: OnboardingState = {
currentStepId: "",
attributes: {},
stepIndex: 0,
completionState: "incomplete",
};
const initialOnboardingContext: OnboardingContextType = {
state: initialOnboardingState,
api: {
nextStep: () => {},
previousStep: () => {},
registerStep: () => {},
updateAttributes: async () => {},
},
};
export type OnboardingContextType = {
state: OnboardingState;
api: OnboardingAPI;
};
export const OnboardingContext = createContext<OnboardingContextType>(
initialOnboardingContext
);
export type OnboardingProps = {
children: React.ReactNode;
onError?: () => void;
};
type Result<T> =
| { error: undefined; value: T }
| { error: Error; value: undefined };
type UiState = "initial" | "loadingAttributes" | "ready" | "error";
async function fetchAttributes(
user: AnonymousUser
): Promise<Result<JsonObject>> {
// TODO use an onboarding bucket to namespace the values
try {
const attributes = await user.getBucket().get();
return { error: undefined, value: attributes };
} catch (e) {
const error = Errors.createSlashIDError({
message: "Failed fetching user attributes during onboarding",
name: "APIResponseError",
cause: ensureError(e),
});
return { error, value: undefined };
}
}
async function updateAttributes({
user,
newAttributes,
oldAttributes,
}: {
user: AnonymousUser;
newAttributes: JsonObject;
oldAttributes: JsonObject;
}): Promise<Result<JsonObject>> {
// TODO use an onboarding bucket to namespace the values
try {
const attributes = { ...oldAttributes, ...newAttributes };
await user.getBucket().set(attributes);
return { error: undefined, value: attributes };
} catch (e) {
const error = Errors.createSlashIDError({
message: "Failed updating user attributes during onboarding",
name: "APIResponseError",
cause: ensureError(e),
});
return { error, value: undefined };
}
}
function getSetItemByIndex<T>(set: Set<T>, index: number): T | undefined {
if (index < 0 || index >= set.size) {
return undefined;
}
return Array.from(set)[index];
}
/**
* Renders the onboarding flow based on the children provided.
* Wrap any step you want to render in the <OnboardgingStep> component.
* They will be rendered in the order they are provided.
*/
export function Onboarding({ children, onError }: OnboardingProps) {
const { anonymousUser } = useSlashID();
const [steps, setSteps] = useState<Set<string>>(new Set());
const [stepIndex, setStepIndex] = useState<number>(0);
const [attributes, setAttributes] = useState<JsonObject>({});
const [uiState, setUiState] = useState<UiState>("initial");
const [completionState, setCompletionState] = useState<
"incomplete" | "complete"
>("incomplete");
useEffect(() => {
async function loadAttributes(user: AnonymousUser) {
const result = await fetchAttributes(user);
if (result.error) {
setUiState("error");
return;
}
setAttributes(result.value);
setUiState("ready");
}
if (uiState === "initial" && anonymousUser) {
setUiState("loadingAttributes");
loadAttributes(anonymousUser);
}
}, [anonymousUser, uiState]);
useEffect(() => {
if (uiState === "error" && typeof onError === "function") {
onError();
}
}, [onError, uiState]);
const contextValue = useMemo(() => {
const state: OnboardingState = {
currentStepId:
steps.size > 0 ? getSetItemByIndex(steps, stepIndex) || "" : "",
attributes,
completionState,
stepIndex,
};
const api: OnboardingAPI = {
nextStep: () => {
if (stepIndex + 1 >= steps.size) {
setCompletionState("complete");
} else {
setStepIndex((index) => index + 1);
}
},
previousStep: () => {
setStepIndex((index) => index - 1);
},
registerStep: (stepId: string) => {
setSteps((steps) => new Set(steps).add(stepId));
},
updateAttributes: async (newAttributes: JsonObject) => {
if (!anonymousUser) {
return;
}
const result = await updateAttributes({
user: anonymousUser,
newAttributes,
oldAttributes: attributes,
});
if (result.error) {
setUiState("error");
return;
}
setAttributes(result.value);
},
};
return {
state,
api,
};
}, [anonymousUser, attributes, completionState, stepIndex, steps]);
return (
<OnboardingContext.Provider value={contextValue}>
{uiState === "loadingAttributes" && (
<div className="sid-onboarding--loading">
<Loading />
</div>
)}
{uiState === "ready" && children}
</OnboardingContext.Provider>
);
}