tldraw/state/code/control.ts

71 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-05-17 10:01:11 +00:00
import {
CodeControl,
ControlType,
NumberCodeControl,
VectorCodeControl,
} from 'types'
2021-06-24 08:18:14 +00:00
import { uniqueId } from 'utils'
2021-05-17 10:01:11 +00:00
export const controls: Record<string, any> = {}
export const codeControls = new Set<CodeControl>([])
/* ----------------- Start Copy Here ---------------- */
2021-05-17 10:01:11 +00:00
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]
}
get value(): T['value'] {
return this.control.value
}
set value(value: T['value']) {
this.control.value = value
}
2021-05-17 10:01:11 +00:00
}
type ControlProps<T extends CodeControl> = Omit<Partial<T>, 'id' | 'type'>
2021-05-17 10:01:11 +00:00
export class NumberControl extends Control<NumberCodeControl> {
constructor(options: ControlProps<NumberCodeControl>) {
const { label = 'Number', value = 0, step = 1 } = options
2021-05-17 10:01:11 +00:00
super({
type: ControlType.Number,
...options,
label,
2021-05-17 10:01:11 +00:00
value,
step,
})
}
}
export class VectorControl extends Control<VectorCodeControl> {
constructor(options: ControlProps<VectorCodeControl>) {
const { label = 'Vector', value = [0, 0], isNormalized = false } = options
2021-05-17 10:01:11 +00:00
super({
type: ControlType.Vector,
...options,
label,
2021-05-17 10:01:11 +00:00
value,
isNormalized,
})
}
}