forked from tscircuit/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRenderable.ts
274 lines (245 loc) · 7.47 KB
/
Renderable.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import type {
PcbManualEditConflictError,
PcbPlacementError,
PcbTraceError,
} from "circuit-json"
export const orderedRenderPhases = [
"ReactSubtreesRender",
"InitializePortsFromChildren",
"CreateNetsFromProps",
"CreateTracesFromProps",
"CreateTraceHintsFromProps",
"SourceRender",
"SourceParentAttachment",
"PortDiscovery",
"PortMatching",
"SourceTraceRender",
"SourceAddConnectivityMapKey",
"SchematicComponentRender",
"SchematicPortRender",
"SchematicLayout",
"SchematicTraceRender",
"PcbComponentRender",
"PcbPrimitiveRender",
"PcbFootprintLayout",
"PcbPortRender",
"PcbPortAttachment",
"PcbLayout",
"PcbComponentSizeCalculation",
"PcbTraceRender",
"PcbTraceHintRender",
"PcbRouteNetIslands",
"CadModelRender",
"PartsEngineRender",
] as const
export type RenderPhase = (typeof orderedRenderPhases)[number]
export type RenderPhaseFn<K extends RenderPhase = RenderPhase> =
| `doInitial${K}`
| `update${K}`
| `remove${K}`
export type RenderPhaseStates = Record<
RenderPhase,
{
initialized: boolean
dirty: boolean
}
>
export type AsyncEffect = {
effectName: string
promise: Promise<void>
phase: RenderPhase
complete: boolean
}
export type RenderPhaseFunctions = {
[T in RenderPhaseFn]?: () => void
}
export type IRenderable = RenderPhaseFunctions & {
renderPhaseStates: RenderPhaseStates
runRenderPhase(phase: RenderPhase): void
runRenderPhaseForChildren(phase: RenderPhase): void
shouldBeRemoved: boolean
children: IRenderable[]
runRenderCycle(): void
}
let globalRenderCounter = 0
export abstract class Renderable implements IRenderable {
renderPhaseStates: RenderPhaseStates
shouldBeRemoved = false
children: IRenderable[]
/** PCB-only SMTPads, PlatedHoles, Holes, Silkscreen elements etc. */
isPcbPrimitive = false
/** Schematic-only, lines, boxes, indicators etc. */
isSchematicPrimitive = false
_renderId: string
_currentRenderPhase: RenderPhase | null = null
private _asyncEffects: AsyncEffect[] = []
constructor(props: any) {
this._renderId = `${globalRenderCounter++}`
this.children = []
this.renderPhaseStates = {} as RenderPhaseStates
for (const phase of orderedRenderPhases) {
this.renderPhaseStates[phase] = {
initialized: false,
dirty: false,
}
}
}
protected _markDirty(phase: RenderPhase) {
this.renderPhaseStates[phase].dirty = true
// Mark all subsequent phases as dirty
const phaseIndex = orderedRenderPhases.indexOf(phase)
for (let i = phaseIndex + 1; i < orderedRenderPhases.length; i++) {
this.renderPhaseStates[orderedRenderPhases[i]].dirty = true
}
}
protected _queueAsyncEffect(effectName: string, effect: () => Promise<void>) {
const asyncEffect: AsyncEffect = {
promise: effect(), // TODO don't start effects until end of render cycle
phase: this._currentRenderPhase!,
effectName,
complete: false,
}
this._asyncEffects.push(asyncEffect)
// Set up completion handler
asyncEffect.promise
.then(() => {
asyncEffect.complete = true
// HACK: emit to the root circuit component that an async effect has completed
if ("root" in this && this.root) {
;(this.root as any).emit("asyncEffectComplete", {
effectName,
componentDisplayName: this.getString(),
phase: asyncEffect.phase,
})
}
})
.catch((error) => {
console.error(
`Async effect error in ${asyncEffect.phase} "${effectName}":\n${error.stack}`,
)
asyncEffect.complete = true
// HACK: emit to the root circuit component that an async effect has completed
if ("root" in this && this.root) {
;(this.root as any).emit("asyncEffectComplete", {
effectName,
componentDisplayName: this.getString(),
phase: asyncEffect.phase,
error: error.toString(),
})
}
})
}
protected _emitRenderLifecycleEvent(
phase: RenderPhase,
eventType: "start" | "end",
) {
const eventPayload = {
renderId: this._renderId,
componentDisplayName: this.getString(),
}
const eventName = `renderable:renderLifecycle:${phase}:${eventType}`
if ("root" in this && this.root) {
;(this.root as any).emit(eventName, {
...eventPayload,
type: eventName,
})
;(this.root as any).emit("renderable:renderLifecycle:anyEvent", {
...eventPayload,
type: eventName,
})
}
}
getString() {
return this.constructor.name
}
_hasIncompleteAsyncEffects(): boolean {
return this._asyncEffects.some((effect) => !effect.complete)
}
getCurrentRenderPhase(): RenderPhase | null {
return this._currentRenderPhase
}
getRenderGraph(): Record<string, any> {
return {
id: this._renderId,
currentPhase: this._currentRenderPhase,
renderPhaseStates: this.renderPhaseStates,
shouldBeRemoved: this.shouldBeRemoved,
children: this.children.map((child) =>
(child as Renderable).getRenderGraph(),
),
}
}
runRenderCycle() {
for (const renderPhase of orderedRenderPhases) {
this.runRenderPhaseForChildren(renderPhase)
this.runRenderPhase(renderPhase)
}
}
/**
* This runs all the render methods for a given phase, calling one of:
* - doInitial*
* - update*
* -remove*
* ...depending on the current state of the component.
*/
runRenderPhase(phase: RenderPhase) {
this._currentRenderPhase = phase
const phaseState = this.renderPhaseStates[phase]
const isInitialized = phaseState.initialized
const isDirty = phaseState.dirty
// Skip if component is being removed and not initialized
if (!isInitialized && this.shouldBeRemoved) return
if (this.shouldBeRemoved && isInitialized) {
this._emitRenderLifecycleEvent(phase, "start")
;(this as any)?.[`remove${phase}`]?.()
phaseState.initialized = false
phaseState.dirty = false
this._emitRenderLifecycleEvent(phase, "end")
return
}
// Check for incomplete async effects from previous phases
const prevPhaseIndex = orderedRenderPhases.indexOf(phase) - 1
if (prevPhaseIndex >= 0) {
const prevPhase = orderedRenderPhases[prevPhaseIndex]
const hasIncompleteEffects = this._asyncEffects
.filter((e) => e.phase === prevPhase)
.some((e) => !e.complete)
if (hasIncompleteEffects) return
}
this._emitRenderLifecycleEvent(phase, "start")
// Handle updates
if (isInitialized) {
if (isDirty) {
;(this as any)?.[`update${phase}`]?.()
phaseState.dirty = false
}
this._emitRenderLifecycleEvent(phase, "end")
return
}
// Initial render
phaseState.dirty = false
;(this as any)?.[`doInitial${phase}`]?.()
phaseState.initialized = true
this._emitRenderLifecycleEvent(phase, "end")
}
runRenderPhaseForChildren(phase: RenderPhase): void {
for (const child of this.children) {
child.runRenderPhaseForChildren(phase)
child.runRenderPhase(phase)
}
}
renderError(
message:
| string
| Omit<PcbTraceError, "pcb_error_id">
| Omit<PcbPlacementError, "pcb_error_id">
| Omit<PcbManualEditConflictError, "pcb_error_id">,
) {
// TODO add to render phase error list and try to add position or
// relationships etc
if (typeof message === "string") {
throw new Error(message)
}
throw new Error(JSON.stringify(message, null, 2))
}
}