This repository has been archived by the owner on Oct 12, 2019. It is now read-only.
generated from theatrejs-labs/npm-package-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
222 lines (193 loc) · 6.97 KB
/
index.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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { getProject, NumberPropTypeDescriptor, Project, Timeline } from 'theatre'
import {
$FixMe,
$IntentionalAny,
IPlayOptions,
IStaggerOptions,
ITheatreStaggerFinalAPI,
TCreateTheatreStagger,
TDefaultSortTypes,
TSortFunction,
} from './types'
const propsArrayToObject = (props: string[]) => {
const str = `{${props.map((value: string) => `"${value}": { "type": "number" }`)}}`
return JSON.parse(str) as Record<string, NumberPropTypeDescriptor>
}
const arrToIndex = <T = $IntentionalAny>(array: T[]): number[] => {
return array.map((value: T, index: number) => index)
}
const GUESSED_TIMELINE_DURATION = 2000
const defaultSortFunctions: Record<TDefaultSortTypes, TSortFunction<$IntentionalAny>> = {
center: (elements: $IntentionalAny[]) => {
const steps = []
const count = elements.length
for (let i = 0; i < Math.ceil(count / 2); i++) {
const side = count - (i + 1)
steps.push(side === i ? [i] : [i, count - (i + 1)])
}
return steps.reverse()
},
normal: (elements: $IntentionalAny[]) => arrToIndex(elements),
shuffle: (elements: $IntentionalAny[]) => arrToIndex(elements).sort(() => 0.5 - Math.random()),
}
const DEFAULT_PLAY_OPTIONS: IPlayOptions = {
delay: 0,
gap: 30,
mode: 'continue',
rate: 1,
reverse: false,
sort: 'normal',
}
const DEFAULT_STAGGER_OPTIONS: Partial<IStaggerOptions<$IntentionalAny>> = {}
class TheatreStagger<T> {
public playing: boolean = false
private name: string
private mode: string
private options: IStaggerOptions<T>
private previousSortingMethod?: IPlayOptions['sort']
private currentPlayingOptions: IPlayOptions = DEFAULT_PLAY_OPTIONS
private timelines: Timeline[]
private steps: number[] | number[][] = []
private currentStep: number = 0
private timeouts: NodeJS.Timeout[] = []
constructor(name: string, options: IStaggerOptions<T>, mode: string) {
this.name = name
this.mode = mode
this.options = { ...DEFAULT_STAGGER_OPTIONS, ...options }
const { filter, middlewares } = this.options
let { project, elements } = this.options
project = typeof project === 'string' ? getProject(project) : project
if (filter) {
elements = elements.filter(filter)
}
this.calculateSteps()
this.timelines = []
elements.forEach((element: T, index: number) => {
const timeline = (project as Project).getTimeline(`${this.name} / ${this.mode}`, `Element ${index}`)
for (const middleware of middlewares) {
const tObject = timeline.getObject(middleware.name, element, {
props: propsArrayToObject(middleware.props),
})
tObject.onValuesChange((values: $FixMe) => {
middleware.onValueChanges(element, values, () => {})
})
}
this.timelines.push(timeline)
})
}
public play(options: Partial<IPlayOptions> = {}) {
this.currentPlayingOptions = {
...DEFAULT_PLAY_OPTIONS,
...options,
}
const { reverse, rate, delay, mode, gap } = this.currentPlayingOptions
this.calculateSteps()
if (reverse) {
this.steps.reverse()
}
if (mode === 'reset') {
this.stop()
}
this.steps.forEach((index: number | number[], step: number) => {
const indexes = typeof index === 'number' ? [index] : index
for (const i of indexes) {
const timeline = this.timelines[i]
const timeout = Math.max(0, delay + step * gap - this.time)
this.setTimeout(() => {
this.currentStep = step
if (timeline.time < GUESSED_TIMELINE_DURATION) {
// FIXME
timeline.play({ rate })
}
}, timeout)
}
})
this.playing = true
}
public pause() {
this.clearAllTimeouts()
this.timelines.forEach(timeline => {
if (timeline.playing) {
timeline.pause()
}
})
this.playing = false
}
public get duration() {
const { delay, gap } = this.currentPlayingOptions
return delay + (this.steps.length - 1) * gap + GUESSED_TIMELINE_DURATION // FIXME;
}
public get time() {
const { delay, gap } = this.currentPlayingOptions
const stepTime = delay + this.currentStep * gap
const step = this.steps[this.currentStep]
const playingTimeline: Timeline = typeof step === 'number' ? this.timelines[step] : this.timelines[step[0]]
return stepTime + playingTimeline.time
}
public set time(value: number) {
const { delay, gap } = this.currentPlayingOptions
this.steps.forEach((index: number | number[], step: number) => {
const indexes = typeof index === 'number' ? [index] : index
this.currentStep = 0
for (const i of indexes) {
const startTime = delay + step * gap
const timelineTime = Math.max(0, value - startTime)
this.timelines[i].time = timelineTime
if (timelineTime > 0) {
this.currentStep = step
}
}
})
this.playing = false
}
public stop() {
this.clearAllTimeouts()
this.time = 0
this.playing = false
}
private calculateSteps() {
const { sort } = this.currentPlayingOptions
if (this.previousSortingMethod === sort) {
return
}
const { elements } = this.options
if (typeof sort === 'string') {
this.steps = defaultSortFunctions[sort as TDefaultSortTypes](elements)
return
}
this.previousSortingMethod = sort
this.steps = sort(elements)
}
private setTimeout(cb: () => void, time: number) {
const timeout = setTimeout(() => {
cb()
}, time)
this.timeouts.push(timeout)
}
private removeTimeout(timeout: NodeJS.Timeout) {
clearTimeout(timeout)
}
private clearAllTimeouts() {
for (const timeout of this.timeouts) {
this.removeTimeout(timeout)
}
this.timeouts = []
}
}
const createTheatreStagger: TCreateTheatreStagger = (name, options, mode = 'default') => {
const stagger = new TheatreStagger(name, options, mode)
const api: ITheatreStaggerFinalAPI<any> = {
clone: newMode => createTheatreStagger(name, options, newMode),
pause: () => stagger.pause(),
play: playOptions => stagger.play(playOptions),
playing: false,
stop: () => stagger.stop(),
time: 0,
}
Object.defineProperty(api, 'time', {
get: () => stagger.time,
set: (value: number) => (stagger.time = value),
})
return api
}
export default createTheatreStagger