-
Notifications
You must be signed in to change notification settings - Fork 627
Expand file tree
/
Copy pathfieldVariable.ts
More file actions
419 lines (356 loc) · 15.5 KB
/
fieldVariable.ts
File metadata and controls
419 lines (356 loc) · 15.5 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import * as Blockly from "blockly";
import { showEditorMixin } from "./fieldDropdownMixin";
import { EXPORTED_VARIABLE_TYPE, IMPORTED_VARIABLE_TYPE } from "../../blocksProgram";
import { getGlobalProgram } from "../../external";
import svg = pxt.svgUtil;
const ICON_WIDTH = 20;
const ICON_PADDING = 8;
const TEXT_ARROW_PADDING = 15; // Extra padding between text end and arrow
/**
* This is the same as the Blockly variable field but with the addition
* of a "New Variable" option in the dropdown
*/
export class FieldVariable extends Blockly.FieldVariable {
static CREATE_VARIABLE_ID = "CREATE_VARIABLE";
static CREATE_GLOBAL_VARIABLE_ID = "CREATE_GLOBAL_VARIABLE";
static TOGGLE_VARIABLE_SCOPE_ID = "TOGGLE_VARIABLE_SCOPE";
static dropdownCreate(this: FieldVariable): Blockly.MenuOption[] {
const options = Blockly.FieldVariable.dropdownCreate.call(this) as Blockly.MenuOption[];
const insertIndex = options.findIndex(e => e[1] === "RENAME_VARIABLE_ID");
options.splice(
insertIndex,
0,
[Blockly.Msg['NEW_VARIABLE_DROPDOWN'], FieldVariable.CREATE_VARIABLE_ID],
[undefined, 'SEPARATOR']
);
options.splice(
insertIndex + 1,
0,
[Blockly.Msg['NEW_GLOBAL_VARIABLE_DROPDOWN'], FieldVariable.CREATE_GLOBAL_VARIABLE_ID]
);
// Add "Make variable global/local" option next to rename/delete
const variable = this.getVariable();
if (variable) {
const varName = variable.getName();
const varType = variable.getType();
const isGlobal = varType === EXPORTED_VARIABLE_TYPE;
const isImported = varType === IMPORTED_VARIABLE_TYPE;
// Only show toggle for local or exported variables (not for imported ones)
if (!isImported) {
const toggleLabel = isGlobal
? Blockly.Msg['MAKE_VARIABLE_LOCAL'].replace('%1', varName)
: Blockly.Msg['MAKE_VARIABLE_GLOBAL'].replace('%1', varName);
// Insert after rename, grouped with the other universal variable options
const renameIndex = options.findIndex(e => e[1] === "RENAME_VARIABLE_ID");
options.splice(
renameIndex + 1,
0,
[toggleLabel, FieldVariable.TOGGLE_VARIABLE_SCOPE_ID]
);
}
}
return options;
}
constructor(
varName: string | null | typeof Blockly.Field.SKIP_SETUP,
validator?: Blockly.FieldVariableValidator,
variableTypes?: string[],
defaultType?: string,
config?: Blockly.FieldVariableConfig,
) {
super(varName, validator, variableTypes, defaultType, config);
this.menuGenerator_ = FieldVariable.dropdownCreate;
}
protected override onItemSelected_(menu: Blockly.Menu, menuItem: Blockly.MenuItem) {
if (this.sourceBlock_ && !this.sourceBlock_.isDeadOrDying()) {
const id = menuItem.getValue();
// Handle variable creation (local or global)
if (id === FieldVariable.CREATE_VARIABLE_ID || id === FieldVariable.CREATE_GLOBAL_VARIABLE_ID) {
const variableType = id === FieldVariable.CREATE_GLOBAL_VARIABLE_ID ? EXPORTED_VARIABLE_TYPE : undefined;
Blockly.Variables.createVariableButtonHandler(this.sourceBlock_.workspace, name => {
const newVar = this.sourceBlock_.workspace.getVariableMap().getVariable(name, variableType);
if (newVar) {
this.setValue(newVar.getId());
}
}, variableType);
return;
}
// Handle toggling variable scope (global <-> local)
if (id === FieldVariable.TOGGLE_VARIABLE_SCOPE_ID) {
this.toggleVariableScope();
return;
}
}
super.onItemSelected_(menu, menuItem);
}
protected toggleVariableScope(): void {
const variable = this.getVariable();
if (!variable) return;
const workspace = this.sourceBlock_.workspace;
const map = workspace.getVariableMap();
const varName = variable.getName();
const varId = variable.getId();
const isGlobal = variable.getType() === EXPORTED_VARIABLE_TYPE;
const newType = isGlobal ? '' : EXPORTED_VARIABLE_TYPE;
if (isGlobal) {
// Check if the variable is referenced in other workspaces
const program = getGlobalProgram();
if (program) {
const allWorkspaces = program.getAllWorkspaces();
for (const fileWs of allWorkspaces) {
if (fileWs.workspace === workspace) continue;
const importedVar = fileWs.workspace.getVariableMap().getVariableById(varId);
if (importedVar) {
const uses = Blockly.Variables.getVariableUsesById(fileWs.workspace, varId);
if (uses.length > 0) {
Blockly.dialog.alert(
Blockly.Msg['CANNOT_MAKE_VARIABLE_LOCAL'].replace('%1', varName)
);
return;
}
}
}
}
}
map.changeVariableType(variable, newType);
// Re-render all blocks that reference this variable so the globe icon updates
const uses = Blockly.Variables.getVariableUsesById(workspace, varId);
for (const block of uses) {
const field = block.getField("VAR");
if (field) {
field.forceRerender();
}
}
// Propagate changes across workspaces
const program = getGlobalProgram();
if (program) {
program.refreshSymbols?.();
}
// Refresh the flyout so variable blocks there reflect the updated type
if (workspace instanceof Blockly.WorkspaceSvg) {
const toolbox = workspace.getToolbox();
if (toolbox) {
(toolbox as Blockly.Toolbox).refreshSelection();
}
}
}
// Everything in this class below this line is duplicated in pxtblocks/fields/field_dropown
// and should be kept in sync with FieldDropdown in that file
private svgRootBinding: Blockly.browserEvents.Data | null = null;
private fieldRootBinding: Blockly.browserEvents.Data | null = null;
private clickTargetRect: SVGRectElement;
private globeIcon: svg.Text;
private globeIconVisible: boolean = false;
/**
* Check if the current variable is a global variable (exported or imported)
*/
protected isGlobalVariable(): boolean {
const variable = this.getVariable();
if (!variable) return false;
const varType = variable.getType();
return varType === EXPORTED_VARIABLE_TYPE || varType === IMPORTED_VARIABLE_TYPE;
}
override initView() {
super.initView();
this.globeIcon = new svg.Text("\uf0ac")
.setClass("semanticIcon")
.setAttribute("alignment-baseline", "middle")
.setAttribute("dy", "3.5")
.anchor("middle");
this.fieldGroup_.appendChild(this.globeIcon.el);
// Add globe icon only for global variables
if (this.isGlobalVariable()) {
this.globeIconVisible = true;
}
else {
this.globeIconVisible = false;
this.globeIcon.el.style.display = "none";
}
if (this.shouldAddBorderRect_()) {
return;
}
// Repurpose the border rect as a transparent click target
this.createBorderRect_();
this.clickTargetRect = this.borderRect_!;
this.clickTargetRect.setAttribute("stroke-opacity", "0");
this.clickTargetRect.setAttribute("fill-opacity", "0");
// Make sure to unset the border rect so that it isn't included in size
// calculations
this.borderRect_ = undefined;
}
override shouldAddBorderRect_() {
if (this.sourceBlock_.type === "variables_get") {
return false;
}
// Returning false for this function will turn the entire block into
// a click target for this field. If there are other editable fields
// in this block, make sure we return true so that we don't make them
// inaccessible
for (const input of this.sourceBlock_.inputList) {
for (const field of input.fieldRow) {
if (field === this) continue;
if (field.EDITABLE) {
return true;
}
}
}
if (!this.sourceBlock_.getInputsInline()) {
return true;
}
return super.shouldAddBorderRect_();
}
protected override bindEvents_() {
if (this.shouldAddBorderRect_()) {
super.bindEvents_();
return;
}
// If shouldAddBorderRect_ returns false, we want the block
// to act as one big click target except if the block has icons
// on it (e.g. comments, warnings, etc). In that case, we want
// to go back to the default behavior of only respecting clicks
// on the field itself so that we don't block clikcing on the
// icons. To accomplish this, we register two event handlers
// one on the sourceblock and one on the field root and check
// the sourceblock icons to make sure only one ever runs
this.svgRootBinding = Blockly.browserEvents.conditionalBind(
(this.sourceBlock_ as Blockly.BlockSvg).getSvgRoot(),
'pointerdown',
this,
(e: PointerEvent) => {
if (this.sourceBlock_.icons.length) {
return;
}
this.onMouseDown_(e);
},
false
);
this.fieldRootBinding = Blockly.browserEvents.conditionalBind(
this.getSvgRoot(),
'pointerdown',
this,
(e: PointerEvent) => {
if (!this.sourceBlock_.icons.length) {
return;
}
this.onMouseDown_(e);
},
false
);
}
override dispose() {
super.dispose();
if (this.svgRootBinding) {
Blockly.browserEvents.unbind(this.svgRootBinding);
Blockly.browserEvents.unbind(this.fieldRootBinding);
}
}
protected override updateSize_(margin?: number): void {
// Let parent calculate the base size first
super.updateSize_(margin);
// Then add extra width for the icon if we're rendering it
if (this.globeIconVisible) {
// Add space for: icon + padding between icon and text + extra padding after text for arrow
this.size_.width += ICON_WIDTH + ICON_PADDING + TEXT_ARROW_PADDING;
}
}
protected override positionBorderRect_() {
super.positionBorderRect_();
// Position globe icon
if (this.globeIcon) {
this.globeIcon.at(ICON_WIDTH / 2, this.size_.height / 2);
if (this.globeIconVisible && this.borderRect_) {
this.globeIcon.at(ICON_PADDING + ICON_WIDTH / 2, this.size_.height / 2);
this.borderRect_.setAttribute("x", String(Number(this.borderRect_.getAttribute("x") || 0) - ICON_WIDTH - ICON_PADDING));
this.borderRect_.setAttribute("width", String(Number(this.borderRect_.getAttribute("width") || 0) + ICON_WIDTH + ICON_PADDING));
}
}
// The logic below is duplicated from the blockly implementation
if (!this.clickTargetRect) {
return;
}
this.clickTargetRect.setAttribute('width', String(this.size_.width));
this.clickTargetRect.setAttribute('height', String(this.size_.height));
this.clickTargetRect.setAttribute(
'rx',
String(this.getConstants()!.FIELD_BORDER_RECT_RADIUS),
);
this.clickTargetRect.setAttribute(
'ry',
String(this.getConstants()!.FIELD_BORDER_RECT_RADIUS),
);
}
protected override render_() {
if (this.globeIcon) {
if (this.isGlobalVariable()) {
if (!this.globeIconVisible) {
this.globeIconVisible = true;
this.globeIcon.el.style.display = "";
}
}
else if (this.globeIconVisible) {
this.globeIconVisible = false;
this.globeIcon.el.style.display = "none";
}
}
super.render_();
// After parent renders, shift all children (except the icon) to make room for icon
if (this.globeIcon && this.globeIconVisible && this.fieldGroup_) {
const children = this.fieldGroup_.children;
for (let i = 0; i < children.length; i++) {
const child = children[i] as SVGElement;
// Skip the globe icon itself
if (child === this.globeIcon.el) {
continue;
}
// Shift elements with x attribute (like text)
if (child.hasAttribute('x')) {
const currentX = parseFloat(child.getAttribute('x') || '0');
child.setAttribute('x', String(currentX + ICON_WIDTH + ICON_PADDING));
}
// Shift elements with transform attribute (like arrow)
const transform = child.getAttribute('transform');
if (transform) {
const match = transform.match(/translate\(([-\d.]+),\s*([-\d.]+)\)/);
if (match) {
const x = parseFloat(match[1]);
const y = parseFloat(match[2]);
child.setAttribute('transform', `translate(${x + ICON_WIDTH + ICON_PADDING}, ${y})`);
}
}
}
// Update the width to account for the icon and shifted elements
this.size_.width += ICON_WIDTH + ICON_PADDING;
}
// Update the click target rect to cover the new width
if (this.clickTargetRect) {
this.clickTargetRect.setAttribute('width', String(this.size_.width));
}
}
protected showEditor_(e?: MouseEvent): void {
const varMap = this.sourceBlock_?.workspace?.getVariableMap();
let iconValues: string[] = [];
if (varMap) {
iconValues = varMap.getAllVariables()
.filter(v => v.getType() === EXPORTED_VARIABLE_TYPE || v.getType() === IMPORTED_VARIABLE_TYPE)
.map(v => v.getId());
}
showEditorMixin.call(this, e, "icon globe", iconValues);
}
getValue(): string | null {
const id = super.getValue();
// this is a workaround for to prevent blockly's flyout clearing behavior from
// deleting recycled blocks in the flyout. by returning a fake variable name,
// we get blockly to skip over this field's source block when it tries to delete
// all usages of the variable
if (this.sourceBlock_?.isInFlyout) {
const potentialMap = this.sourceBlock_.workspace?.getPotentialVariableMap();
if (potentialMap.getVariableById(id)) {
return "potential_" + id;
}
}
return id;
}
}
// Override the default variable field
Blockly.fieldRegistry.unregister("field_variable");
Blockly.fieldRegistry.register("field_variable", FieldVariable);