-
Notifications
You must be signed in to change notification settings - Fork 0
/
machine.ts
132 lines (131 loc) · 3.34 KB
/
machine.ts
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
import { Effect } from "effect";
import { assign, setup } from "xstate";
import { onError, onLoad, onPause, onPlay, onRestart } from "./effect";
import { Context, Events } from "./machine-types";
export const machine = setup({
types: {
events: {} as Events,
context: {} as Context,
},
actions: {
onPlay: ({ context: { audioRef, audioContext } }) =>
onPlay({ audioContext, audioRef }).pipe(Effect.runPromise),
onPause: ({ context: { audioRef } }) =>
onPause({ audioRef }).pipe(Effect.runSync),
onRestart: ({ context: { audioRef } }) =>
onRestart({ audioRef }).pipe(Effect.runPromise),
onError: (_, { message }: { message: unknown }) =>
onError({ message }).pipe(Effect.runPromise),
onLoad: assign(({ self }, { audioRef }: { audioRef: HTMLAudioElement }) =>
onLoad({ audioRef, context: null, trackSource: null }).pipe(
Effect.tap(() => Effect.sync(() => self.send({ type: "loaded" }))),
Effect.tapError(({ message }) =>
Effect.sync(() => self.send({ type: "error", params: { message } }))
),
Effect.map(({ context }) => context),
Effect.catchTag("OnLoadError", ({ context }) =>
Effect.succeed(context)
),
Effect.runSync
)
),
onUpdateTime: assign((_, { updatedTime }: { updatedTime: number }) => ({
currentTime: updatedTime,
})),
},
}).createMachine({
context: {
audioContext: null,
trackSource: null,
audioRef: null,
currentTime: 0,
},
id: "Audio Player",
initial: "Init",
states: {
Init: {
on: {
loading: {
target: "Loading",
actions: {
type: "onLoad",
params: ({ event }) => ({ audioRef: event.params.audioRef }),
},
},
"init-error": {
target: "Error",
actions: {
type: "onError",
params: ({ event }) => ({ message: event.params.message }),
},
},
},
},
Loading: {
on: {
loaded: {
target: "Active",
},
error: {
target: "Error",
actions: {
type: "onError",
params: ({ event }) => ({ message: event.params.message }),
},
},
},
},
Active: {
initial: "Paused",
states: {
Paused: {
entry: {
type: "onPause",
},
on: {
play: {
target: "Playing",
},
restart: {
target: "Playing",
actions: {
type: "onRestart",
},
},
},
},
Playing: {
entry: {
type: "onPlay",
},
on: {
restart: {
target: "Playing",
actions: {
type: "onRestart",
},
},
end: {
target: "Paused",
},
pause: {
target: "Paused",
},
time: {
target: "Playing",
actions: {
type: "onUpdateTime",
params: ({ event }) => ({
updatedTime: event.params.updatedTime,
}),
},
},
},
},
},
},
Error: {
type: "final",
},
},
});