77// Former goog.module ID: Blockly.serialization.variables
88
99import type { ISerializer } from '../interfaces/i_serializer.js' ;
10+ import type { IVariableState } from '../interfaces/i_variable_model.js' ;
1011import type { Workspace } from '../workspace.js' ;
1112
1213import * as priorities from './priorities.js' ;
14+ import * as registry from '../registry.js' ;
1315import * as serializationRegistry from './registry.js' ;
1416
15- /**
16- * Represents the state of a given variable.
17- */
18- export interface State {
19- name : string ;
20- id : string ;
21- type : string | undefined ;
22- }
23-
2417/**
2518 * Serializer for saving and loading variable state.
2619 */
@@ -40,23 +33,9 @@ export class VariableSerializer implements ISerializer {
4033 * @returns The state of the workspace's variables, or null if there are no
4134 * variables.
4235 */
43- save ( workspace : Workspace ) : State [ ] | null {
44- const variableStates = [ ] ;
45- for ( const variable of workspace . getAllVariables ( ) ) {
46- const state = {
47- 'name' : variable . name ,
48- 'id' : variable . getId ( ) ,
49- } ;
50- if ( variable . type ) {
51- ( state as AnyDuringMigration ) [ 'type' ] = variable . type ;
52- }
53- variableStates . push ( state ) ;
54- }
55- // AnyDuringMigration because: Type '{ name: string; id: string; }[] |
56- // null' is not assignable to type 'State[] | null'.
57- return (
58- variableStates . length ? variableStates : null
59- ) as AnyDuringMigration ;
36+ save ( workspace : Workspace ) : IVariableState [ ] | null {
37+ const variableStates = workspace . getAllVariables ( ) . map ( ( v ) => v . save ( ) ) ;
38+ return variableStates . length ? variableStates : null ;
6039 }
6140
6241 /**
@@ -66,14 +45,14 @@ export class VariableSerializer implements ISerializer {
6645 * @param state The state of the variables to deserialize.
6746 * @param workspace The workspace to deserialize into.
6847 */
69- load ( state : State [ ] , workspace : Workspace ) {
70- for ( const varState of state ) {
71- workspace . createVariable (
72- varState [ 'name' ] ,
73- varState [ 'type' ] ,
74- varState [ 'id' ] ,
75- ) ;
76- }
48+ load ( state : IVariableState [ ] , workspace : Workspace ) {
49+ const VariableModel = registry . getObject (
50+ registry . Type . VARIABLE_MODEL ,
51+ registry . DEFAULT ,
52+ ) ;
53+ state . forEach ( ( s ) => {
54+ VariableModel ?. load ( s , workspace ) ;
55+ } ) ;
7756 }
7857
7958 /**
0 commit comments