1+ import { PlainJs } from "@mendix/filter-commons/typings/settings" ;
12import { action , autorun , computed , makeObservable , observable , runInAction } from "mobx" ;
23import { ObservableSortStore , SortInstruction } from "../types/store" ;
34
45export class SortStoreHost {
56 private _usedBy : string [ ] = [ ] ;
67 private _state : SortInstruction [ ] ;
78 private _cleanup : ( ( ) => void ) | null = null ;
9+ private _store : ObservableSortStore | null = null ;
10+ private _jsonBuffer : PlainJs | null = null ;
811
912 constructor ( spec : { initSort ?: SortInstruction [ ] } = { } ) {
1013 this . _state = spec . initSort ?? [ ] ;
1114
12- makeObservable < this, "_usedBy" | "_state" | "_setState" > ( this , {
15+ makeObservable < this, "_usedBy" | "_state" | "_setState" | "_jsonBuffer" > ( this , {
1316 _state : observable . ref ,
17+ _jsonBuffer : observable . ref ,
1418 sortOrder : computed ,
1519 lock : action ,
1620 _usedBy : observable ,
1721 usedBy : computed ,
1822 observe : action ,
1923 unobserve : action ,
20- _setState : action
24+ _setState : action ,
25+ fromJSON : action
2126 } ) ;
2227 }
2328
@@ -30,17 +35,34 @@ export class SortStoreHost {
3035 }
3136
3237 observe ( store : ObservableSortStore ) : void {
33- if ( this . _cleanup ) {
34- this . _cleanup ( ) ;
35- }
36- this . _cleanup = autorun ( ( ) => {
38+ this . unobserve ( ) ;
39+
40+ // Set the initial state from the json buffer if available
41+ const clearJson = autorun ( ( ) => {
42+ const data = this . _jsonBuffer ;
43+ if ( data == null || ! Array . isArray ( data ) ) {
44+ return ;
45+ }
46+ store . fromJSON ( data ) ;
47+ } ) ;
48+
49+ // Sync the store's sort order with the host's state
50+ const clearSync = autorun ( ( ) => {
3751 this . _setState ( store . sortOrder ) ;
3852 } ) ;
53+
54+ this . _store = store ;
55+ this . _cleanup = ( ) => {
56+ this . _store = null ;
57+ this . _jsonBuffer = null ;
58+ this . _cleanup = null ;
59+ clearJson ( ) ;
60+ clearSync ( ) ;
61+ } ;
3962 }
4063
4164 unobserve ( ) : void {
4265 this . _cleanup ?.( ) ;
43- this . _cleanup = null ;
4466 }
4567
4668 lock ( id : string ) : ( ) => void {
@@ -62,16 +84,11 @@ export class SortStoreHost {
6284 return this . _usedBy . at ( 0 ) ?? null ;
6385 }
6486
65- // toJSON(): PlainJs {
66- // return this._store ? this._store.toJSON() : null;
67- // }
87+ toJSON ( ) : PlainJs {
88+ return this . _store ? this . _store . toJSON ( ) : null ;
89+ }
6890
69- // fromJSON(data: PlainJs): void {
70- // if (data == null || !Array.isArray(data)) {
71- // return;
72- // }
73- // if (this._store) {
74- // this._store.fromJSON(data);
75- // }
76- // }
91+ fromJSON ( data : PlainJs ) : void {
92+ this . _jsonBuffer = data ;
93+ }
7794}
0 commit comments