Line data Source code
1 : import { defineStore } from 'pinia'
2 : import { computed, readonly, shallowRef, watch } from 'vue'
3 :
4 : import { t, te } from '@/i18n'
5 : import { useSettingStore } from '@/platform/settings/settingStore'
6 : import { useTelemetry } from '@comfyorg/telemetry'
7 : import type {
8 : OnboardingTourNotStartedReason,
9 : OnboardingTourSkipReason,
10 : OnboardingTourStepStage
11 : } from '@comfyorg/telemetry/types'
12 : import { useToast } from '@/components/ui/toast/toastStore'
13 : import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore'
14 :
15 : import { targetMounted, waitForTarget } from './coachmarkRegistry'
16 : import {
17 : ENTRY_PATHS,
18 : TOUR_SEEN_SETTING,
19 : registerTourHolds,
20 : resolveSteps,
21 : tourDefinition,
22 : tourHolds
23 : } from './onboardingTours'
24 : import type { CoachStep, EntryPath, TourDefinition } from './onboardingTours'
25 : import { IDLE, isRunning, reduceTour, shownIdx } from './tourState'
26 : import type { RunId, TourEvent, TourState } from './tourState'
27 : import { useTourTriggers } from './useTourTriggers'
28 :
29 2355 : const DEFER_TIMEOUT_MS = 8000
30 :
31 : /**
32 : * How the last run of a tour ended. Whatever follows a tour has to know which
33 : * ending it is following: "a tour ran" cannot tell a tour walked to the end
34 : * apart from one the user waved away on step 1, or one a missing target tore
35 : * down.
36 : */
37 : export type TourEnding =
38 : | { tour: EntryPath; outcome: 'completed' }
39 : | {
40 : tour: EntryPath
41 : outcome: 'skipped'
42 : skipReason: OnboardingTourSkipReason
43 : }
44 :
45 : /** Empty when a runtime resolver fails, so one bad graph costs only its own tour. */
46 6 : async function resolveDefinition(
47 : definition: TourDefinition
48 : ): Promise<{ steps: CoachStep[]; reason?: OnboardingTourNotStartedReason }> {
49 6 : if (Array.isArray(definition)) return { steps: definition }
50 6 : try {
51 0 : const resolution = await definition()
52 6 : return Array.isArray(resolution) ? { steps: resolution } : resolution
53 : } catch (error) {
54 0 : console.error('coachmark tour definition failed', error)
55 0 : return { steps: [], reason: 'resolver_failed' }
56 : }
57 : }
58 :
59 : /**
60 : * The tour state machine: which tour starts and when, which steps run, and the
61 : * advance/skip/complete lifecycle.
62 : */
63 2355 : export const useOnboardingTourStore = defineStore('onboardingTour', () => {
64 2355 : const settingStore = useSettingStore()
65 2355 : const telemetry = useTelemetry()
66 :
67 2355 : const state = shallowRef<TourState>(IDLE)
68 2355 : const lastEnding = shallowRef<TourEnding | null>(null)
69 2355 : let stepController: AbortController | null = null
70 2355 : let lastRun = 0
71 :
72 6 : function nextRun(): RunId {
73 6 : return ++lastRun as RunId
74 : }
75 :
76 : /** The only writer of `state`. Returns false when the reducer refused. */
77 43 : function dispatch(event: TourEvent): boolean {
78 43 : const before = state.value
79 43 : state.value = reduceTour(before, event)
80 43 : return state.value !== before
81 : }
82 :
83 5 : function currentRun(): RunId | null {
84 5 : return state.value.phase === 'idle' ? null : state.value.run
85 : }
86 :
87 2355 : const steps = computed<CoachStep[]>(() =>
88 : isRunning(state.value) ? state.value.steps : []
89 : )
90 2355 : const activeTour = computed<EntryPath | null>(() =>
91 : state.value.phase === 'idle' ? null : state.value.tour
92 : )
93 2355 : const waitingForTarget = computed(() => state.value.phase === 'waiting')
94 2355 : const stepSettled = computed(() => state.value.phase === 'showing')
95 :
96 2355 : const stepIdx = computed(() => shownIdx(state.value))
97 :
98 2355 : const step = computed<CoachStep | null>(() =>
99 : stepIdx.value === null ? null : (steps.value[stepIdx.value] ?? null)
100 : )
101 2355 : const isLast = computed(() => stepIdx.value === steps.value.length - 1)
102 :
103 2355 : const countedSteps = computed<CoachStep[]>(() =>
104 : steps.value.filter((s) => s.kind !== 'landing')
105 : )
106 2355 : const countedStepsTotal = computed(() => countedSteps.value.length)
107 2355 : const countedStepIdx = computed(() => {
108 7 : const s = step.value
109 7 : return s ? countedSteps.value.indexOf(s) : 0
110 : })
111 2355 : const previousStep = computed<CoachStep | null>(() =>
112 : stepIdx.value === null ? null : (steps.value[stepIdx.value - 1] ?? null)
113 : )
114 :
115 2355 : const canGoBack = computed(() => {
116 7 : const previous = previousStep.value
117 7 : if (countedStepIdx.value <= 0) return false
118 7 : return previous?.kind !== 'spotlight' || previous.selfAdvancing !== true
119 : })
120 :
121 : /** What telemetry reports, captured before a transition clears it. */
122 23 : function snapshot() {
123 23 : return { tour: activeTour.value, counted: countedSteps.value }
124 : }
125 :
126 23 : function trackTour(
127 : stage: OnboardingTourStepStage,
128 : skipReason?: OnboardingTourSkipReason,
129 : reported: CoachStep | null = step.value,
130 : { tour, counted } = snapshot()
131 : ) {
132 23 : if (!tour) return
133 23 : const reportedIdx = reported ? counted.indexOf(reported) : -1
134 23 : telemetry?.trackOnboardingTour(stage, {
135 : tour,
136 : step_count: counted.length,
137 : ...(stage !== 'started' &&
138 : reportedIdx >= 0 && {
139 : step_number: reportedIdx + 1,
140 : coach_id:
141 : reported?.kind === 'spotlight' ? reported.coachId : undefined
142 : }),
143 : ...(skipReason && { skip_reason: skipReason })
144 : })
145 : }
146 :
147 58 : function stepKey(suffix: string) {
148 58 : return `onboardingCoachmarks.${activeTour.value}.${step.value?.name}.${suffix}`
149 : }
150 :
151 2355 : const title = computed(() => (step.value ? t(stepKey('title')) : ''))
152 2355 : const body = computed(() => (step.value ? t(stepKey('body')) : ''))
153 :
154 : // A step overrides the generic button labels by declaring `primary`/`skip`
155 : // entries under its translation keys.
156 2355 : const primaryLabel = computed(() => {
157 13 : if (step.value && te(stepKey('primary'))) return t(stepKey('primary'))
158 13 : return isLast.value
159 : ? t('onboardingCoachmarks.done')
160 : : t('onboardingCoachmarks.next')
161 : })
162 :
163 2355 : const skipLabel = computed(() =>
164 : step.value && te(stepKey('skip'))
165 : ? t(stepKey('skip'))
166 : : t('onboardingCoachmarks.skip')
167 : )
168 :
169 2355 : const backLabel = computed(() => t('onboardingCoachmarks.back'))
170 :
171 13 : async function showStep(idx: number) {
172 13 : const current = state.value
173 13 : if (!isRunning(current)) return
174 13 : const nextStep = current.steps[idx]
175 :
176 13 : stepController?.abort()
177 13 : const controller = new AbortController()
178 13 : stepController = controller
179 13 : const { signal } = controller
180 :
181 13 : const run = current.run
182 13 : const superseded = () =>
183 : run !== currentRun() || stepController !== controller
184 13 : const fromIdx = shownIdx(current)
185 13 : if (nextStep.kind === 'spotlight' && nextStep.openSidebarTab)
186 1 : openSidebarTab(nextStep.openSidebarTab)
187 :
188 13 : if (
189 : nextStep.kind === 'spotlight' &&
190 : nextStep.deferTarget &&
191 : nextStep.coachId &&
192 : !targetMounted(nextStep.coachId)
193 : ) {
194 1 : if (!dispatch({ type: 'targetAwaited', run, fromIdx })) return
195 1 : const found = await waitForTarget(
196 : nextStep.coachId,
197 : signal,
198 : DEFER_TIMEOUT_MS
199 : )
200 : // The step moved on without us; only a timeout ends it here.
201 1 : if (superseded()) return
202 1 : if (!found) {
203 0 : abandonStep(nextStep)
204 0 : return
205 : }
206 : }
207 :
208 13 : if (!dispatch({ type: 'stepEntering', run, toIdx: idx })) return
209 13 : if (nextStep.onEnter) {
210 0 : try {
211 0 : await nextStep.onEnter(signal)
212 : } catch (error) {
213 0 : if (superseded()) return
214 0 : console.error('coachmark onEnter failed', error)
215 0 : abandonStep(nextStep)
216 0 : return
217 : }
218 0 : if (superseded()) return
219 : }
220 13 : if (!dispatch({ type: 'stepShown', run, idx })) return
221 13 : trackTour('step_shown')
222 : }
223 :
224 : /**
225 : * Ends the tour on a step it could not present, without the seen-flag so the
226 : * user is offered it again rather than losing it to a bad moment.
227 : */
228 0 : function abandonStep(step: CoachStep) {
229 0 : finish('skipped', {
230 : markSeen: false,
231 : skipReason: 'target_timeout',
232 : reported: step
233 : })
234 0 : useToast().error(t('g.error'), {
235 : description: t('onboardingCoachmarks.loadError')
236 : })
237 : }
238 2355 : const lostTarget = computed(() => {
239 2379 : if (state.value.phase !== 'showing') return null
240 13 : const shown = step.value
241 2379 : if (shown?.kind !== 'spotlight') return null
242 2379 : return shown.coachId && !targetMounted(shown.coachId) ? shown : null
243 : })
244 :
245 2355 : watch(lostTarget, (lost) => {
246 0 : if (lost) abandonStep(lost)
247 : })
248 :
249 1 : function openSidebarTab(tabId: string) {
250 1 : const sidebar = useSidebarTabStore()
251 1 : if (sidebar.activeSidebarTabId !== tabId) sidebar.toggleSidebarTab(tabId)
252 : }
253 :
254 8 : function next() {
255 8 : if (waitingForTarget.value) return
256 8 : if (isLast.value) {
257 1 : finish('completed')
258 1 : return
259 : }
260 7 : if (stepIdx.value !== null) void showStep(stepIdx.value + 1)
261 : }
262 :
263 0 : function back() {
264 0 : if (canGoBack.value && stepIdx.value !== null)
265 0 : void showStep(stepIdx.value - 1)
266 : }
267 :
268 2 : function skip() {
269 2 : finish('skipped')
270 : }
271 :
272 : /**
273 : * Ends the tour without marking it seen: something outside it barred the way,
274 : * so the user has not had their tour yet and is offered it again.
275 : */
276 0 : function postpone() {
277 0 : finish('skipped', { markSeen: false, skipReason: 'postponed' })
278 : }
279 :
280 4 : function finish(
281 : outcome: 'completed' | 'skipped',
282 : {
283 : markSeen = true,
284 : skipReason = 'user',
285 : reported
286 : }: {
287 : markSeen?: boolean
288 : skipReason?: OnboardingTourSkipReason
289 : reported?: CoachStep
290 : } = {}
291 : ) {
292 4 : const run = currentRun()
293 4 : if (run === null) return
294 4 : const ending = snapshot()
295 4 : const reportedStep = reported ?? step.value
296 :
297 4 : if (!dispatch({ type: 'ended', run })) return
298 :
299 4 : if (ending.tour)
300 4 : lastEnding.value =
301 : outcome === 'skipped'
302 : ? { tour: ending.tour, outcome, skipReason }
303 : : { tour: ending.tour, outcome }
304 4 : trackTour(
305 : outcome,
306 : outcome === 'skipped' ? skipReason : undefined,
307 : reportedStep,
308 : ending
309 : )
310 4 : stepController?.abort()
311 4 : if (markSeen && ending.tour) markTourSeen(ending.tour)
312 : }
313 :
314 2355 : for (const [entryPath, trigger] of useTourTriggers()) {
315 2355 : registerTourHolds(entryPath, trigger.holds)
316 2355 : watch(
317 : trigger.autoOpen,
318 : (visible) => {
319 2439 : if (visible) void startTour(entryPath)
320 : },
321 : { immediate: true }
322 : )
323 : }
324 :
325 : // One rule for every tour: lose the context its steps point at, lose the tour.
326 2355 : for (const entryPath of ENTRY_PATHS) {
327 4710 : watch(
328 : () => tourHolds(entryPath),
329 : (holding) => {
330 94 : if (!holding && activeTour.value === entryPath)
331 1 : finish('skipped', { markSeen: false, skipReason: 'trigger_lost' })
332 : }
333 : )
334 : }
335 :
336 71 : function hasSeenTour(entryPath: EntryPath): boolean {
337 71 : return settingStore.get(TOUR_SEEN_SETTING).includes(entryPath)
338 : }
339 :
340 3 : function markTourSeen(entryPath: EntryPath) {
341 3 : const seen = settingStore.get(TOUR_SEEN_SETTING)
342 3 : if (seen.includes(entryPath)) return
343 3 : void settingStore.set(TOUR_SEEN_SETTING, [...seen, entryPath])
344 : }
345 :
346 6 : async function begin(entryPath: EntryPath): Promise<boolean> {
347 6 : const definition = tourDefinition(entryPath)
348 6 : if (!definition || !tourHolds(entryPath)) return false
349 6 : const run = nextRun()
350 6 : if (!dispatch({ type: 'requested', tour: entryPath, run })) return false
351 : // A new run has no ending yet; the one before it must not speak for it.
352 6 : lastEnding.value = null
353 6 : const built = await resolveDefinition(definition)
354 6 : const resolved = resolveSteps(built.steps, targetMounted)
355 6 : if (!resolved.length) {
356 0 : dispatch({ type: 'resolvedEmpty', run })
357 0 : reportNotStarted(entryPath, built.reason ?? 'no_steps')
358 0 : return false
359 : }
360 : // Refused when this run ended while its definition was still resolving.
361 6 : if (!dispatch({ type: 'resolved', run, steps: resolved })) return false
362 6 : trackTour('started')
363 6 : void showStep(0)
364 6 : return true
365 : }
366 :
367 2355 : const reportedNotStarted = new Set<EntryPath>()
368 68 : function reportNotStarted(
369 : entryPath: EntryPath,
370 : reason: OnboardingTourNotStartedReason
371 : ) {
372 68 : if (reportedNotStarted.has(entryPath)) return
373 60 : reportedNotStarted.add(entryPath)
374 68 : telemetry?.trackOnboardingTour('not_started', {
375 : tour: entryPath,
376 : step_count: 0,
377 : not_started_reason: reason
378 : })
379 : }
380 :
381 : /** Starts an unseen tour; false when nothing started. */
382 71 : async function startTour(entryPath: EntryPath): Promise<boolean> {
383 71 : if (hasSeenTour(entryPath)) {
384 68 : reportNotStarted(entryPath, 'already_seen')
385 68 : return false
386 : }
387 3 : return begin(entryPath)
388 : }
389 :
390 3 : function replayTour(entryPath: EntryPath) {
391 3 : void begin(entryPath)
392 : }
393 :
394 2355 : return {
395 : activeTour: readonly(activeTour),
396 : lastEnding: readonly(lastEnding),
397 : step,
398 : isLast,
399 : canGoBack,
400 : title,
401 : body,
402 : primaryLabel,
403 : skipLabel,
404 : backLabel,
405 : countedStepIdx,
406 : countedStepsTotal,
407 : waitingForTarget,
408 : stepSettled,
409 : startTour,
410 : replayTour,
411 : next,
412 : back,
413 : skip,
414 : postpone
415 : }
416 : })
|