-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathinject.ts
More file actions
429 lines (391 loc) · 12.1 KB
/
inject.ts
File metadata and controls
429 lines (391 loc) · 12.1 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
420
421
422
423
424
425
426
427
428
429
/**
* @license
* Copyright 2011 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
// Former goog.module ID: Blockly.inject
import type {BlocklyOptions} from './blockly_options.js';
import * as browserEvents from './browser_events.js';
import * as bumpObjects from './bump_objects.js';
import * as common from './common.js';
import * as Css from './css.js';
import * as dropDownDiv from './dropdowndiv.js';
import {Msg} from './msg.js';
import {Options} from './options.js';
import {ScrollbarPair} from './scrollbar_pair.js';
import {ShortcutRegistry} from './shortcut_registry.js';
import * as Tooltip from './tooltip.js';
import * as Touch from './touch.js';
import * as aria from './utils/aria.js';
import * as dom from './utils/dom.js';
import {Svg} from './utils/svg.js';
import * as WidgetDiv from './widgetdiv.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
* Inject a Blockly editor into the specified container element (usually a div).
*
* @param container Containing element, or its ID, or a CSS selector.
* @param opt_options Optional dictionary of options.
* @returns Newly created main workspace.
*/
export function inject(
container: Element | string,
opt_options?: BlocklyOptions,
): WorkspaceSvg {
let containerElement: Element | null = null;
if (typeof container === 'string') {
containerElement =
document.getElementById(container) || document.querySelector(container);
} else {
containerElement = container;
}
// Verify that the container is in document.
if (
!document.contains(containerElement) &&
document !== containerElement?.ownerDocument
) {
throw Error('Error: container is not in current document');
}
const options = new Options(opt_options || ({} as BlocklyOptions));
const subContainer = document.createElement('div');
dom.addClass(subContainer, 'injectionDiv');
if (opt_options?.rtl) {
dom.addClass(subContainer, 'blocklyRTL');
}
subContainer.tabIndex = 0;
aria.setState(subContainer, aria.State.LABEL, Msg['WORKSPACE_ARIA_LABEL']);
containerElement!.appendChild(subContainer);
const svg = createDom(subContainer, options);
const workspace = createMainWorkspace(subContainer, svg, options);
init(workspace);
// Keep focus on the first workspace so entering keyboard navigation looks
// correct.
common.setMainWorkspace(workspace);
common.svgResize(workspace);
subContainer.addEventListener('focusin', function () {
common.setMainWorkspace(workspace);
});
browserEvents.conditionalBind(subContainer, 'keydown', null, onKeyDown);
browserEvents.conditionalBind(
dropDownDiv.getContentDiv(),
'keydown',
null,
onKeyDown,
);
const widgetContainer = WidgetDiv.getDiv();
if (widgetContainer) {
browserEvents.conditionalBind(widgetContainer, 'keydown', null, onKeyDown);
}
return workspace;
}
/**
* Create the SVG image.
*
* @param container Containing element.
* @param options Dictionary of options.
* @returns Newly created SVG image.
*/
function createDom(container: Element, options: Options): SVGElement {
// Sadly browsers (Chrome vs Firefox) are currently inconsistent in laying
// out content in RTL mode. Therefore Blockly forces the use of LTR,
// then manually positions content in RTL as needed.
container.setAttribute('dir', 'LTR');
// Load CSS.
Css.inject(options.hasCss, options.pathToMedia);
// Build the SVG DOM.
/*
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:html="http://www.w3.org/1999/xhtml"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1"
class="blocklySvg">
...
</svg>
*/
const svg = dom.createSvgElement(
Svg.SVG,
{
'xmlns': dom.SVG_NS,
'xmlns:html': dom.HTML_NS,
'xmlns:xlink': dom.XLINK_NS,
'version': '1.1',
'class': 'blocklySvg',
'tabindex': '0',
},
container,
);
/*
<defs>
... filters go here ...
</defs>
*/
const defs = dom.createSvgElement(Svg.DEFS, {}, svg);
// Each filter/pattern needs a unique ID for the case of multiple Blockly
// instances on a page. Browser behaviour becomes undefined otherwise.
// https://neil.fraser.name/news/2015/11/01/
const rnd = String(Math.random()).substring(2);
options.gridPattern = options.gridProvider.createDom(
rnd,
options.gridOptions,
defs,
);
return svg;
}
/**
* Create a main workspace and add it to the SVG.
*
* @param svg SVG element with pattern defined.
* @param options Dictionary of options.
* @returns Newly created main workspace.
*/
function createMainWorkspace(
injectionDiv: Element,
svg: SVGElement,
options: Options,
): WorkspaceSvg {
options.parentWorkspace = null;
const mainWorkspace = new WorkspaceSvg(options);
const wsOptions = mainWorkspace.options;
mainWorkspace.scale = wsOptions.zoomOptions.startScale;
svg.appendChild(
mainWorkspace.createDom('blocklyMainBackground', injectionDiv),
);
// Set the theme name and renderer name onto the injection div.
const rendererClassName = mainWorkspace.getRenderer().getClassName();
if (rendererClassName) {
dom.addClass(injectionDiv, rendererClassName);
}
const themeClassName = mainWorkspace.getTheme().getClassName();
if (themeClassName) {
dom.addClass(injectionDiv, themeClassName);
}
if (!wsOptions.hasCategories && wsOptions.languageTree) {
// Add flyout as an <svg> that is a sibling of the workspace SVG.
const flyout = mainWorkspace.addFlyout(Svg.SVG);
dom.insertAfter(flyout, svg);
}
if (wsOptions.hasTrashcan) {
mainWorkspace.addTrashcan();
}
if (wsOptions.zoomOptions && wsOptions.zoomOptions.controls) {
mainWorkspace.addZoomControls();
}
// Register the workspace svg as a UI component.
mainWorkspace
.getThemeManager()
.subscribe(svg, 'workspaceBackgroundColour', 'background-color');
// A null translation will also apply the correct initial scale.
mainWorkspace.translate(0, 0);
mainWorkspace.addChangeListener(
bumpObjects.bumpIntoBoundsHandler(mainWorkspace),
);
// The SVG is now fully assembled.
common.svgResize(mainWorkspace);
WidgetDiv.createDom();
dropDownDiv.createDom();
Tooltip.createDom();
return mainWorkspace;
}
/**
* Initialize Blockly with various handlers.
*
* @param mainWorkspace Newly created main workspace.
*/
function init(mainWorkspace: WorkspaceSvg) {
const options = mainWorkspace.options;
const svg = mainWorkspace.getParentSvg();
// Suppress the browser's context menu.
browserEvents.conditionalBind(
svg.parentNode as Element,
'contextmenu',
null,
function (e: Event) {
if (!browserEvents.isTargetInput(e)) {
e.preventDefault();
}
},
);
const workspaceResizeHandler = browserEvents.conditionalBind(
window,
'resize',
null,
function () {
// Don't hide all the chaff. Leave the dropdown and widget divs open if
// possible.
Tooltip.hide();
mainWorkspace.hideComponents(true);
dropDownDiv.repositionForWindowResize();
WidgetDiv.repositionForWindowResize();
common.svgResize(mainWorkspace);
bumpObjects.bumpTopObjectsIntoBounds(mainWorkspace);
},
);
mainWorkspace.setResizeHandlerWrapper(workspaceResizeHandler);
bindDocumentEvents();
if (options.languageTree) {
const toolbox = mainWorkspace.getToolbox();
const flyout = mainWorkspace.getFlyout(true);
if (toolbox) {
toolbox.init();
} else if (flyout) {
// Build a fixed flyout with the root blocks.
flyout.init(mainWorkspace);
flyout.show(options.languageTree);
if (typeof flyout.scrollToStart === 'function') {
flyout.scrollToStart();
}
}
}
if (options.hasTrashcan) {
mainWorkspace.trashcan!.init();
}
if (options.zoomOptions && options.zoomOptions.controls) {
mainWorkspace.zoomControls_!.init();
}
if (options.moveOptions && options.moveOptions.scrollbars) {
const horizontalScroll =
options.moveOptions.scrollbars === true ||
!!options.moveOptions.scrollbars.horizontal;
const verticalScroll =
options.moveOptions.scrollbars === true ||
!!options.moveOptions.scrollbars.vertical;
mainWorkspace.scrollbar = new ScrollbarPair(
mainWorkspace,
horizontalScroll,
verticalScroll,
'blocklyMainWorkspaceScrollbar',
);
mainWorkspace.scrollbar.resize();
} else {
mainWorkspace.setMetrics({x: 0.5, y: 0.5});
}
// Load the sounds.
if (options.hasSounds) {
loadSounds(options.pathToMedia, mainWorkspace);
}
}
/**
* Handle a key-down on SVG drawing surface. Does nothing if the main workspace
* is not visible.
*
* @param e Key down event.
*/
// TODO (https://github.com/google/blockly/issues/1998) handle cases where there
// are multiple workspaces and non-main workspaces are able to accept input.
function onKeyDown(e: KeyboardEvent) {
const mainWorkspace = common.getMainWorkspace() as WorkspaceSvg;
if (!mainWorkspace) {
return;
}
if (
browserEvents.isTargetInput(e) ||
(mainWorkspace.rendered && !mainWorkspace.isVisible())
) {
// When focused on an HTML text input widget, don't trap any keys.
// Ignore keypresses on rendered workspaces that have been explicitly
// hidden.
return;
}
ShortcutRegistry.registry.onKeyDown(mainWorkspace, e);
}
/**
* Whether event handlers have been bound. Document event handlers will only
* be bound once, even if Blockly is destroyed and reinjected.
*/
let documentEventsBound = false;
/**
* Bind document events, but only once. Destroying and reinjecting Blockly
* should not bind again.
* Bind events for scrolling the workspace.
* Most of these events should be bound to the SVG's surface.
* However, 'mouseup' has to be on the whole document so that a block dragged
* out of bounds and released will know that it has been released.
*/
function bindDocumentEvents() {
if (!documentEventsBound) {
browserEvents.conditionalBind(document, 'scroll', null, function () {
const workspaces = common.getAllWorkspaces();
for (let i = 0, workspace; (workspace = workspaces[i]); i++) {
if (workspace instanceof WorkspaceSvg) {
workspace.updateInverseScreenCTM();
}
}
});
// longStop needs to run to stop the context menu from showing up. It
// should run regardless of what other touch event handlers have run.
browserEvents.bind(document, 'touchend', null, Touch.longStop);
browserEvents.bind(document, 'touchcancel', null, Touch.longStop);
}
documentEventsBound = true;
}
/**
* Load sounds for the given workspace.
*
* @param pathToMedia The path to the media directory.
* @param workspace The workspace to load sounds for.
*/
function loadSounds(pathToMedia: string, workspace: WorkspaceSvg) {
const audioMgr = workspace.getAudioManager();
audioMgr.load(
[
pathToMedia + 'click.mp3',
pathToMedia + 'click.wav',
pathToMedia + 'click.ogg',
],
'click',
);
audioMgr.load(
[
pathToMedia + 'disconnect.wav',
pathToMedia + 'disconnect.mp3',
pathToMedia + 'disconnect.ogg',
],
'disconnect',
);
audioMgr.load(
[
pathToMedia + 'delete.mp3',
pathToMedia + 'delete.ogg',
pathToMedia + 'delete.wav',
],
'delete',
);
// Bind temporary hooks that preload the sounds.
const soundBinds: browserEvents.Data[] = [];
/**
*
*/
function unbindSounds() {
while (soundBinds.length) {
const oldSoundBinding = soundBinds.pop();
if (oldSoundBinding) {
browserEvents.unbind(oldSoundBinding);
}
}
audioMgr.preload();
}
// These are bound on mouse/touch events with
// Blockly.browserEvents.conditionalBind, so they restrict the touch
// identifier that will be recognized. But this is really something that
// happens on a click, not a drag, so that's not necessary.
// Android ignores any sound not loaded as a result of a user action.
soundBinds.push(
browserEvents.conditionalBind(
document,
'pointermove',
null,
unbindSounds,
true,
),
);
soundBinds.push(
browserEvents.conditionalBind(
document,
'touchstart',
null,
unbindSounds,
true,
),
);
}