tldraw/state/code/control.ts

84 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> {
2021-06-25 11:01:22 +00:00
_control: T
2021-05-17 10:01:11 +00:00
2021-06-25 11:01:22 +00:00
constructor(control: T) {
this._control = { ...control }
codeControls.add(this._control)
2021-05-17 10:01:11 +00:00
// 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) {
2021-06-25 11:01:22 +00:00
controls[this._control.label] = this._control.value
2021-05-17 10:01:11 +00:00
}
}
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]
}
2021-06-25 11:01:22 +00:00
get control(): T {
return this._control
}
get id(): string {
return this.control.id
}
2021-06-25 11:01:22 +00:00
get value(): T['value'] {
return this.control.value
}
2021-05-17 10:01:11 +00:00
}
2021-06-25 11:01:22 +00:00
type ControlProps<T extends CodeControl> = Omit<Partial<T>, 'type'>
2021-05-17 10:01:11 +00:00
export class NumberControl extends Control<NumberCodeControl> {
constructor(options: ControlProps<NumberCodeControl>) {
2021-06-25 11:01:22 +00:00
const { id = uniqueId(), 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,
2021-06-25 11:01:22 +00:00
id,
2021-05-17 10:01:11 +00:00
})
}
}
export class VectorControl extends Control<VectorCodeControl> {
constructor(options: ControlProps<VectorCodeControl>) {
2021-06-25 11:01:22 +00:00
const {
id = uniqueId(),
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,
2021-06-25 11:01:22 +00:00
id,
2021-05-17 10:01:11 +00:00
})
}
}