···102102 return;
103103 }
104104105105+ /**
106106+ * Return the extra coded (if it exists), composed of the individual
107107+ * data from each block in the workspace, which are defined in the
108108+ * toplevel_init property. (e.g. : imports needed for the block)
109109+ *
110110+ * Add extra code example:
111111+ * Blockly.Blocks['block_name'].toplevel_init = `import numpy`
112112+ */
113113+ getBlocksToplevelInit(): string {
114114+ // Initalize string which will return the extra code provided
115115+ // by the blocks, in the toplevel_init property.
116116+ let finalToplevelInit = '';
117117+118118+ // Get all the blocks in the workspace in order.
119119+ const ordered = true;
120120+ const used_blocks = this._workspace.getAllBlocks(ordered);
121121+122122+ // For each block in the workspace, check if theres is a toplevel_init,
123123+ // if there is, add it to the final string.
124124+ for (const block in used_blocks) {
125125+ const current_block = used_blocks[block].type;
126126+ if (Blockly.Blocks[current_block].toplevel_init) {
127127+ // console.log(Blockly.Blocks[current_block].toplevel_init);
128128+ // Attach it to the final string
129129+ const string = Blockly.Blocks[current_block].toplevel_init;
130130+ finalToplevelInit = finalToplevelInit + string;
131131+ }
132132+ }
133133+ // console.log(finalToplevelInit);
134134+ return finalToplevelInit;
135135+ }
136136+105137 run(): void {
138138+ // Get extra code from the blocks in the workspace.
139139+ const extra_init = this.getBlocksToplevelInit();
106140 // Serializing our workspace into the chosen language generator.
107107- const code = this._manager.generator.workspaceToCode(this._workspace);
141141+ const code =
142142+ extra_init + this._manager.generator.workspaceToCode(this._workspace);
108143 this._cell.model.sharedModel.setSource(code);
109144 this.addWidget(this._cell);
110145 this._resizeWorkspace();
···181216 change: BlocklyManager.Change
182217 ) {
183218 if (change === 'kernel') {
219219+ // Get extra code from the blocks in the workspace.
220220+ const extra_init = this.getBlocksToplevelInit();
184221 // Serializing our workspace into the chosen language generator.
185185- const code = this._manager.generator.workspaceToCode(this._workspace);
222222+ const code =
223223+ extra_init + this._manager.generator.workspaceToCode(this._workspace);
186224 this._cell.model.sharedModel.setSource(code);
187225 this._cell.model.mimeType = this._manager.mimeType;
188226 }