@@ -102,9 +102,44 @@ export class BlocklyLayout extends PanelLayout {
102102 return ;
103103 }
104104
105+ /**
106+ * Return the extra coded (if it exists), composed of the individual
107+ * data from each block in the workspace, which are defined in the
108+ * toplevel_init property. (e.g. : imports needed for the block)
109+ *
110+ * Add extra code example:
111+ * Blockly.Blocks['block_name'].toplevel_init = `import numpy`
112+ */
113+ getBlocksToplevelInit ( ) : string {
114+ // Initalize string which will return the extra code provided
115+ // by the blocks, in the toplevel_init property.
116+ let finalToplevelInit = '' ;
117+
118+ // Get all the blocks in the workspace in order.
119+ const ordered = true ;
120+ const used_blocks = this . _workspace . getAllBlocks ( ordered ) ;
121+
122+ // For each block in the workspace, check if theres is a toplevel_init,
123+ // if there is, add it to the final string.
124+ for ( const block in used_blocks ) {
125+ const current_block = used_blocks [ block ] . type ;
126+ if ( Blockly . Blocks [ current_block ] . toplevel_init ) {
127+ // console.log(Blockly.Blocks[current_block].toplevel_init);
128+ // Attach it to the final string
129+ const string = Blockly . Blocks [ current_block ] . toplevel_init ;
130+ finalToplevelInit = finalToplevelInit + string ;
131+ }
132+ }
133+ // console.log(finalToplevelInit);
134+ return finalToplevelInit ;
135+ }
136+
105137 run ( ) : void {
138+ // Get extra code from the blocks in the workspace.
139+ const extra_init = this . getBlocksToplevelInit ( ) ;
106140 // Serializing our workspace into the chosen language generator.
107- const code = this . _manager . generator . workspaceToCode ( this . _workspace ) ;
141+ const code =
142+ extra_init + this . _manager . generator . workspaceToCode ( this . _workspace ) ;
108143 this . _cell . model . sharedModel . setSource ( code ) ;
109144 this . addWidget ( this . _cell ) ;
110145 this . _resizeWorkspace ( ) ;
@@ -181,8 +216,11 @@ export class BlocklyLayout extends PanelLayout {
181216 change : BlocklyManager . Change
182217 ) {
183218 if ( change === 'kernel' ) {
219+ // Get extra code from the blocks in the workspace.
220+ const extra_init = this . getBlocksToplevelInit ( ) ;
184221 // Serializing our workspace into the chosen language generator.
185- const code = this . _manager . generator . workspaceToCode ( this . _workspace ) ;
222+ const code =
223+ extra_init + this . _manager . generator . workspaceToCode ( this . _workspace ) ;
186224 this . _cell . model . sharedModel . setSource ( code ) ;
187225 this . _cell . model . mimeType = this . _manager . mimeType ;
188226 }
0 commit comments