-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrid.ts
More file actions
246 lines (207 loc) · 7.22 KB
/
Grid.ts
File metadata and controls
246 lines (207 loc) · 7.22 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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import './Grid.css'
import { Component } from './internal/Component.ts'
import { Square } from './Square.ts'
import { type Animation } from '$game/grid/index.ts'
import baseLog from '$util/log.ts'
import { isDefined, wait } from '$util/index.ts'
import { map as mapAsync } from '$util/async.ts'
export interface GridProperties {
animationDelay?: number
colors: string[]
}
export type GridResizeData = { anchor: [number, number]; cols: number; sideLength: number; numSquares: number }
export type GridResizeCallback = (ev: GridResizeData) => void
const log = baseLog.extend('Grid')
const getDelay = (base: number, current: number, total: number): number => {
const exp = Math.floor(total / 2)
const magnitude = Math.floor((10 * exp) / 9)
const progress = current / total
const delay = base + Math.floor(Math.pow(progress, exp) * magnitude * base)
return delay
}
const defaultProps: Required<GridProperties> = {
animationDelay: 50,
colors: [],
}
type SquareData = { sideLength: number; cols: number; offset: number }
export class Grid extends Component<HTMLDivElement> {
private readonly properties: Required<GridProperties>
private initialNumSquares = 0
private squares: Square[] = []
private readonly resizeObserver: ResizeObserver
private resizeListener?: GridResizeCallback
constructor(properties: GridProperties) {
super({ tag: 'div', classList: ['grid'] })
this.properties = { ...defaultProps, ...properties }
log('Grid properties: %O', this.properties)
this.resizeObserver = new ResizeObserver(() => {
const data = this.squareData()
this.setSquaresPosition(data)
this.callResize(data)
})
}
public onResize(cb: GridResizeCallback | null) {
if (cb == null) {
this.resizeListener = undefined
} else {
this.resizeListener = cb
this.callResize(this.squareData())
}
}
private callResize({ sideLength, offset, cols }: SquareData) {
const { top, left } = this.rect
this.resizeListener?.({ anchor: [left + offset, top], cols, sideLength, numSquares: this.squares.length })
}
private async setSquaresPosition({ sideLength: size, offset, cols }: SquareData, start = 0, end = this.squares.length) {
this.setStyle('--offset', `${offset}px`)
this.setStyle('--size', `${size}px`)
await mapAsync(this.squares.slice(start, end), (s, i) => {
const j = start + i
s.row = (j / cols) | 0
s.col = j % cols
return this.eventsRace(['transitionend', 'transitioncancel'])
})
}
get activeSquares(): Square[] {
return this.squares
}
get numTotalSquares(): number {
return this.initialNumSquares
}
get colors(): readonly string[] {
return this.properties.colors
}
setColors(colors: string[], seq: number[]) {
this.properties.colors = colors
for (let i = 0; i < this.squares.length; i++) {
this.squares[i].color = colors[seq[i]]
}
}
async removeSquare(square: Square): Promise<void> {
const i = this.squares.indexOf(square)
if (i == -1) {
throw new Error('Square does not exist in grid')
}
log('Square %d removed', i)
await Promise.all([this.squares.splice(i, 1)[0].destroy('long'), this.setSquaresPosition(this.squareData(), i)])
}
addGridEventListener<E extends keyof HTMLElementEventMap>(
event: E,
callback: (ev: HTMLElementEventMap[E]) => void,
options?: AddEventListenerOptions,
) {
this.addEventListener(event, callback, options)
}
removeGridEventListener<E extends keyof HTMLElementEventMap>(
event: E,
callback: (ev: HTMLElementEventMap[E]) => void,
options?: AddEventListenerOptions,
): void {
this.removeEventListener(event, callback, options)
}
addSquareEventListener<E extends keyof HTMLElementEventMap>(
event: E,
callback: (ev: HTMLElementEventMap[E], square: Square) => unknown,
options?: AddEventListenerOptions,
) {
const cb = (e: Event) => {
if (!isHTMLDivElement(e.target) || !e.target.classList.contains('grid__square') || !e.isTrusted) {
return
}
const row = parseInt(e.target.style.getPropertyValue('--row'), 10)
const col = parseInt(e.target.style.getPropertyValue('--col'), 10)
const square = this.squares.find((v) => v.row === row && v.col === col)
if (!square) {
return
}
callback(e as HTMLElementEventMap[E], square)
}
this.addEventListener(event, cb, options)
}
async create(parent: Component, animate: Animation, squaresColorSequence: number[]): Promise<void> {
if (this.activeSquares.length > 0) {
return
}
log('Creating grid')
this.appendTo(parent)
this.resizeObserver.observe(this.element)
this.addClass('grid--no-interaction')
await this.appendSquares(
squaresColorSequence.map((i) => new Square({ color: this.properties.colors[i] })),
animate,
)
this.removeClass('grid--no-interaction')
}
async destroy(animate: Animation): Promise<void> {
log('Destroying grid')
this.resizeObserver.disconnect()
this.addClass('grid--no-interaction')
if (animate !== 'none') {
let promise: Promise<void> | undefined
for (let square = this.squares.pop(); square; square = this.squares.pop()) {
promise = square.destroy(animate)
if (animate === 'long') {
await wait(this.properties.animationDelay)
}
}
await promise
}
this.removeClass('grid--no-interaction')
this.remove()
this.initialNumSquares = 0
}
toggleInteraction(enabled: boolean) {
if (enabled) {
this.removeClass('grid--no-interaction')
} else {
this.addClass('grid--no-interaction')
}
}
private async appendSquares(squares: Square[], animate: Animation): Promise<void> {
let promise: Promise<void> | undefined
let i = this.squares.length
this.squares.push(...squares)
if (this.squares.length > this.initialNumSquares) {
this.initialNumSquares = this.squares.length
}
for (; i < this.squares.length; i++) {
const square = this.squares[i]
promise = square.create(this as unknown as Component, animate)
if (animate === 'long') {
await Promise.race([promise, wait(getDelay(this.properties.animationDelay, i, this.squares.length))])
}
}
await promise
}
private get width(): number {
return parseInt(this.getComputedStyle('width'))
}
private get height(): number {
return parseInt(this.getComputedStyle('height'))
}
private squareData() {
const { s: sideLength, a: cols } = gridDimensions(this.initialNumSquares, this.width, this.height)
const offset = (this.width - cols * sideLength) / 2
return { sideLength, cols, offset }
}
}
const isHTMLDivElement = (v: unknown): v is HTMLDivElement => {
return isDefined(v) && (v as any).__proto__.constructor.name === 'HTMLDivElement'
}
function gridDimensions(n: number, w: number, h: number): { s: number; a: number; b: number } {
const r = w / h
if (r < 1) {
const { s, a, b } = gridDimensions(n, h, w)
return { s, a: b, b: a }
}
const b0 = Math.ceil(Math.sqrt(n / r))
let res = { s: 0, a: 0, b: 0 }
for (let b = b0 - 1; b <= b0 + 1; b++) {
const a = Math.ceil(n / b)
const s = Math.min(w / a, h / b)
if (s > res.s) {
res = { s, a, b }
}
}
return res
}