tldraw/state/code/control.ts

57 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-05-17 10:01:11 +00:00
import {
CodeControl,
ControlType,
NumberCodeControl,
VectorCodeControl,
} from 'types'
2021-06-17 11:26:20 +00:00
import { uniqueId } from 'utils/utils'
2021-05-17 10:01:11 +00:00
export const controls: Record<string, any> = {}
export const codeControls = new Set<CodeControl>([])
export class Control<T extends CodeControl> {
control: T
constructor(control: Omit<T, 'id'>) {
this.control = { ...control, id: uniqueId() } as T
2021-05-17 10:01:11 +00:00
codeControls.add(this.control)
// Could there be a better way to prevent this?
// When updating, constructor should just bind to
// the existing control rather than creating a new one?
if (!(window as any).isUpdatingCode) {
controls[this.control.label] = this.control.value
}
}
2021-06-21 21:35:28 +00:00
destroy(): void {
2021-05-17 10:01:11 +00:00
codeControls.delete(this.control)
delete controls[this.control.label]
}
}
export class NumberControl extends Control<NumberCodeControl> {
constructor(options: Omit<NumberCodeControl, 'id' | 'type'>) {
2021-05-17 10:01:11 +00:00
const { value = 0, step = 1 } = options
super({
type: ControlType.Number,
...options,
value,
step,
})
}
}
export class VectorControl extends Control<VectorCodeControl> {
constructor(options: Omit<VectorCodeControl, 'id' | 'type'>) {
2021-05-17 10:01:11 +00:00
const { value = [0, 0], isNormalized = false } = options
super({
type: ControlType.Vector,
...options,
value,
isNormalized,
})
}
}