forked from source-academy/frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrame.tsx
More file actions
310 lines (275 loc) · 11 KB
/
Copy pathFrame.tsx
File metadata and controls
310 lines (275 loc) · 11 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import React from 'react';
import { Group, Rect } from 'react-konva';
import CseMachine from '../CseMachine';
import { CseAnimation } from '../CseMachineAnimation';
import { Config, ShapeDefaultProps } from '../CseMachineConfig';
import { Layout } from '../CseMachineLayout';
import { Env, EnvTreeNode, IHoverable } from '../CseMachineTypes';
import {
defaultActiveColor,
defaultStrokeColor,
fadedStrokeColor,
getTextWidth,
getUnreferencedObjects,
isClosure,
isDataArray,
isDummyKey,
isMainReference,
isPrimitiveData,
isSourceObject,
isUnassigned
} from '../CseMachineUtils';
import { isContinuation } from '../utils/continuation';
import { ArrowFromFrame } from './arrows/ArrowFromFrame';
import { GenericArrow } from './arrows/GenericArrow';
import { Binding } from './Binding';
import { Level } from './Level';
import { Text } from './Text';
import { ArrayValue } from './values/ArrayValue';
import { ContValue } from './values/ContValue';
import { FnValue } from './values/FnValue';
import { GlobalFnValue } from './values/GlobalFnValue';
import { Visible } from './Visible';
const frameNames = new Map([
['global', 'Global'],
['programEnvironment', 'Program'],
['forLoopEnvironment', 'Body of for-loop'],
['forBlockEnvironment', 'Control variable of for-loop'],
['blockEnvironment', 'Block'],
['functionBodyEnvironment', 'Function Body']
]);
/** this class encapsulates a frame of key-value bindings to be drawn on canvas */
export class Frame extends Visible implements IHoverable {
private static envFrameMap: Map<string, Frame> = new Map();
public static getFrom(environment: Env): Frame | undefined {
return Frame.envFrameMap.get(environment.id);
}
/** total height = frame height + frame title height */
readonly totalHeight: number;
/** width budget of this frame block (excluding right-side data overflow) */
readonly totalWidth: number;
/** width of data beside frame */
readonly totalDataWidth: number;
/** the bindings this frame contains */
readonly bindings: Binding[] = [];
/** name of this frame to display */
private _name!: Text; // removed readonly to allow reassignment for fixed layout
private readonly rectRef = React.createRef<any>();
/** the level in which this frame resides */
readonly level: Level | undefined;
/** environment associated with this frame */
readonly environment: Env;
/** the parent/enclosing frame of this frame (the frame above it) */
readonly parentFrame: Frame | undefined;
/** arrow that is drawn from this frame to the parent frame */
readonly arrow: GenericArrow<Frame, Frame> | undefined;
/** check if this frame is live */
readonly isLive: boolean;
constructor(
/** environment tree node that contains this frame */
readonly envTreeNode: EnvTreeNode,
/** the frame to the left of this frame, on the same level. used for calculating this frame's position */
readonly leftSiblingFrame: Frame | null
) {
super();
this.totalDataWidth = 0;
this.level = envTreeNode.level as Level;
this.parentFrame = envTreeNode.parent?.frame;
this.environment = envTreeNode.environment;
Frame.envFrameMap.set(this.environment.id, this);
this._x = this.leftSiblingFrame
? this.leftSiblingFrame.x() +
this.leftSiblingFrame.totalWidth +
this.leftSiblingFrame.totalDataWidth +
Config.FrameMarginX
: this.level.x();
// ensure x coordinate cannot be less than that of parent frame during default alignment
if (!CseMachine.getCenterAlignment() && this.parentFrame)
this._x = Math.max(this._x, this.parentFrame.x()); // added condition for center alignment
this._y = this.level.y() + Config.FontSize + Config.TextPaddingY / 2;
// get all keys and object descriptors of each value inside the head
const entries = Object.entries(Object.getOwnPropertyDescriptors(this.environment.head));
// move the global frame default text to the first position if it isn't in there already
if (this.environment.name === 'global' && entries[0][0] !== Config.GlobalFrameDefaultText) {
const index = entries.findIndex(([key]) => key === Config.GlobalFrameDefaultText);
entries.unshift(entries.splice(index, 1)[0]);
}
// get values that are unreferenced, which will used to created dummy bindings
const unreferencedValues = [...getUnreferencedObjects(this.environment)];
// TODO: find out why values are not added to heap on the correct order in JS Slang
// For now, sorting is a good workaround since id also increases in insertion order
unreferencedValues.sort((v1, v2) => Number(v1.id) - Number(v2.id));
// find objects that are nested inside other arrays, and prevent them from creating new
// dummy bindings by removing them from unreferencedValues, as they should be drawn
// around the original parent array instead
let i = 0;
while (i < unreferencedValues.length) {
const value = unreferencedValues[i];
if (isDataArray(value)) {
for (const data of value) {
if ((isDataArray(data) && data !== value) || isClosure(data) || isContinuation(data)) {
const prev = unreferencedValues.findIndex(value => value.id === data.id);
if (prev > -1) {
unreferencedValues.splice(prev, 1);
if (prev <= i) i--;
}
}
}
}
i++;
}
// Add dummy bindings to `entries`
for (const value of unreferencedValues) {
const descriptor: TypedPropertyDescriptor<any> & PropertyDescriptor = {
value,
configurable: false,
enumerable: true,
writable: false
};
// The key is a number string to "disguise" as a dummy binding
entries.push([`${i++}`, descriptor]);
}
// Find the correct width of the frame before creating the bindings.
// This pass sizes only the frame body (text and primitive values inside the frame).
this._width = Config.FrameMinWidth;
for (const [key, data] of entries) {
if (isDummyKey(key)) continue;
const constant =
this.environment.head[key]?.description === 'const declaration' || !data.writable;
let bindingTextWidth = getTextWidth(
key + (constant ? Config.ConstantColon : Config.VariableColon)
);
if (isUnassigned(data.value)) {
bindingTextWidth += Config.TextPaddingX + getTextWidth(Config.UnassignedData);
} else if (isPrimitiveData(data.value)) {
bindingTextWidth +=
Config.TextPaddingX +
getTextWidth(
isSourceObject(data.value)
? data.value.toReplString()
: JSON.stringify(data.value) || String(data.value)
);
}
this._width = Math.max(this._width, bindingTextWidth + Config.FramePaddingX * 2);
}
// Create all the bindings and values
let prevBinding: Binding | null = null;
this.isLive = this.environment ? Layout.liveEnvIDs.has(this.environment.id) : false;
for (const [key, data] of entries) {
const constant =
this.environment.head[key]?.description === 'const declaration' || !data.writable;
const currBinding: Binding = new Binding(
key,
data.value,
this,
prevBinding,
constant,
this.isLive
);
prevBinding = currBinding;
this.bindings.push(currBinding);
}
// Post-process using actual created values to get robust spacing for nested arrays/functions.
// `totalDataWidth` is measured strictly as overflow beyond the frame's right edge.
const frameRightX = this.x() + this.width();
for (const binding of this.bindings) {
const value = binding.value;
if (!isMainReference(value, binding)) continue;
let valueRightX: number | undefined;
if (value instanceof ArrayValue) {
valueRightX = value.x() + value.totalWidth;
} else if (value instanceof FnValue || value instanceof GlobalFnValue) {
valueRightX = CseMachine.getPrintableMode()
? value.x() + value.totalWidth
: value.x() + value.width();
} else if (value instanceof ContValue) {
valueRightX = value.x() + value.width() + value.tooltipWidth;
}
if (valueRightX !== undefined) {
const overflow = Math.max(0, valueRightX - frameRightX);
this.totalDataWidth = Math.max(this.totalDataWidth, overflow);
}
}
this.totalWidth = this.width();
// derive the height of the frame from the the position of the last binding
this._height = prevBinding
? prevBinding.y() - this.y() + prevBinding.height() + Config.FramePaddingY
: Config.FramePaddingY * 2;
this._name = new Text(
frameNames.get(this.environment.name) ?? this.environment.name,
this.x(),
this.level.y(),
{ maxWidth: this.width(), faded: !this.isLive }
);
this.totalHeight = this.height() + this.name.height() + Config.TextPaddingY / 2;
if (this.parentFrame) this.arrow = new ArrowFromFrame(this).to(this.parentFrame);
if (CseMachine.getCurrentEnvId() === this.environment.id) {
CseAnimation.setCurrentFrame(this);
}
}
public get name(): Text {
return this._name;
}
/**
* Reassigns the coordinates according to the final position of this frame
* @param newX taken from cached layout
*/
reassignCoordinates(newX: number): void {
this._x = newX;
let textOffset = 0;
if (CseMachine.getCenterAlignment()) {
textOffset += Math.floor(this.width() / 2) - Math.floor(this.name.width() / 2);
}
this._name = new Text(
frameNames.get(this.environment.name) ?? this.environment.name,
this.x() + textOffset,
this.level!.y(), // this method is only called after the frame is drawn
{ maxWidth: this.width(), faded: !this.isLive }
);
}
onMouseEnter = () => {};
onMouseLeave = () => {};
setArrowSourceHighlightedStyle(): void {
this.rectRef.current?.stroke(Config.HoverColor);
this.name.setArrowSourceHighlightedStyle();
}
setArrowSourceNormalStyle(): void {
this.rectRef.current?.stroke(
CseMachine.getCurrentEnvId() === this.environment?.id
? defaultActiveColor()
: this.isLive
? defaultStrokeColor()
: fadedStrokeColor()
);
this.name.setArrowSourceNormalStyle();
}
draw(): React.ReactNode {
return (
<Group ref={this.ref} key={Layout.key++}>
{this.name.draw()}
<Rect
{...ShapeDefaultProps}
ref={this.rectRef}
x={this.x()}
y={this.y()}
width={this.width()}
height={this.height()}
stroke={
CseMachine.getCurrentEnvId() === this.environment?.id
? defaultActiveColor()
: this.isLive
? defaultStrokeColor()
: fadedStrokeColor()
}
cornerRadius={Config.FrameCornerRadius}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
listening={false}
key={Layout.key++}
/>
{this.bindings.map(binding => binding.draw())}
{this.arrow?.draw()}
</Group>
);
}
}