@@ -26,7 +26,8 @@ interface TranspileOptions {
2626export function transpileToJS ( ast : Program , options : TranspileOptions = { } ) : string {
2727 const ctx = new TranspileContext ( options ) ;
2828 const programCode = transpileProgram ( ast , ctx ) ;
29- // State management runtime //
29+
30+ // Enhanced State management runtime with subscribe and getValue
3031 const runtime =
3132 options . injectRuntime !== false
3233 ? `// JistScript Runtime
@@ -42,20 +43,40 @@ function useState(initialValue, typeInfo) {
4243 const stateId = __jist_state_counter.value++;
4344
4445 if (!__jist_state_store.has(stateId)) {
45- __jist_state_store.set(stateId, initialValue);
46+ __jist_state_store.set(stateId, {
47+ value: initialValue,
48+ listeners: []
49+ });
4650 }
4751
48- const currentValue = __jist_state_store.get(stateId);
52+ const stateEntry = __jist_state_store.get(stateId);
4953
5054 const setState = (newValue) => {
5155 if (typeInfo && !validateType(newValue, typeInfo)) {
52- console.warn(\`[JistScript] Type mismatch: expected \${typeInfo.type }, got \${typeof newValue}\`);
56+ console.warn(\`[JistScript] Type mismatch: expected \${typeInfo.typeName }, got \${typeof newValue}\`);
5357 }
54- __jist_state_store.set(stateId, newValue);
58+ stateEntry.value = newValue;
59+
60+ stateEntry.listeners.forEach(listener => {
61+ try {
62+ listener();
63+ } catch (e) {
64+ console.error('[JistScript] Error in listener:', e);
65+ }
66+ });
67+
5568 return newValue;
5669 };
5770
58- return [currentValue, setState];
71+ setState.subscribe = (callback) => {
72+ stateEntry.listeners.push(callback);
73+ };
74+
75+ setState.getValue = () => {
76+ return stateEntry.value;
77+ };
78+
79+ return [stateEntry.value, setState];
5980}
6081
6182function validateType(value, typeInfo) {
@@ -145,6 +166,7 @@ function transpileStatement(stmt: Statement, ctx: TranspileContext): string {
145166 ctx . indent -- ;
146167 return `${ indent } function ${ fn . name } (${ params } ) {\n${ body } \n${ indent } }` ;
147168 }
169+
148170 case "ReturnStatement" : {
149171 const returnStmt = stmt as ReturnStatement ;
150172 if ( returnStmt . value ) {
0 commit comments