mobx#autorun TypeScript Examples

The following examples show how to use mobx#autorun. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: demo-mode-panel.tsx    From ya-webadb with MIT License 6 votes vote down vote up
constructor() {
        makeAutoObservable(this);

        reaction(
            () => GlobalState.device,
            async (device) => {
                if (device) {
                    runInAction(() => this.demoMode = new DemoMode(device));
                    const allowed = await this.demoMode!.getAllowed();
                    runInAction(() => this.allowed = allowed);
                    if (allowed) {
                        const enabled = await this.demoMode!.getEnabled();
                        runInAction(() => this.enabled = enabled);
                    }
                } else {
                    this.demoMode = undefined;
                    this.allowed = false;
                    this.enabled = false;
                    this.features.clear();
                }
            },
            { fireImmediately: true }
        );

        // Apply all features when enable
        autorun(() => {
            if (this.enabled) {
                for (const group of FEATURES) {
                    for (const feature of group) {
                        feature.onChange(this.features.get(feature.key) ?? feature.initial);
                    }
                }
            }
        });
    }
Example #2
Source File: autorunTrackDisposables.ts    From vscode-drawio with GNU General Public License v3.0 6 votes vote down vote up
export function autorunTrackDisposables(
	reaction: (track: TrackFunction) => void
): Disposable {
	let lastDisposable: Disposable | undefined;
	return {
		dispose: autorun(() => {
			if (lastDisposable) {
				lastDisposable.dispose();
			}
			lastDisposable = Disposable.fn(reaction);
		}),
	};
}
Example #3
Source File: autorunDisposable.ts    From vscode-lean4 with Apache License 2.0 6 votes vote down vote up
/**
 * Like `autorun`, but more suited for working with Disposables.
 * The `disposables` passed to `reaction` will be disposed when the reaction is triggered again.
 */
export function autorunDisposable(
	reaction: (disposables: Disposable[]) => void
): Disposable {
	let lastDisposable = new Array<Disposable>();
	return {
		dispose: autorun(() => {
			for (const d of lastDisposable) {
				d.dispose();
			}
			lastDisposable = [];
			reaction(lastDisposable);
		}),
	};
}
Example #4
Source File: Config.ts    From vscode-drawio with GNU General Public License v3.0 6 votes vote down vote up
constructor(private readonly globalState: Memento) {
		autorun(() => {
			setContext(
				experimentalFeaturesEnabled,
				this.experimentalFeaturesEnabled
			);
		});

		this._vscodeTheme = window.activeColorTheme;
		window.onDidChangeActiveColorTheme((theme) => {
			this._vscodeTheme = theme;
		});
	}
Example #5
Source File: settingsStore.ts    From lightning-terminal with MIT License 6 votes vote down vote up
/**
   * initialized the settings and auto-save when a setting is changed
   */
  init() {
    this.load();
    autorun(
      () => {
        const settings: PersistentSettings = {
          sidebarVisible: this.sidebarVisible,
          unit: this.unit,
          balanceMode: this.balanceMode,
          tourAutoShown: this.tourAutoShown,
          bitcoinTxUrl: this.bitcoinTxUrl,
          lnNodeUrl: this.lnNodeUrl,
          minChanSize: this.minChanSize,
          maxBatchFeeRate: this.maxBatchFeeRate,
          minNodeTier: this.minNodeTier,
          channelSort: toJS(this.channelSort),
          historySort: toJS(this.historySort),
          orderSort: toJS(this.orderSort),
          leaseSort: toJS(this.leaseSort),
          sessionSort: toJS(this.sessionSort),
        };
        this._store.storage.set('settings', settings);
        this._store.log.info('saved settings to localStorage', settings);
      },
      { name: 'settingsAutorun' },
    );
  }
Example #6
Source File: User.ts    From companion-kit with MIT License 6 votes vote down vote up
constructor(auth: IAuthController) {
        super(auth);

        const self = this;
        this.notifications = new NotificationsController(this._localSettings, {
            get firstName() { return self.user?.firstName; },
            get lastName() { return self.user?.lastName; },
        });

        if (process.appFeatures.EDITABLE_PROMPTS_ENABLED === true) {
            this._prompts = new PromptsController(this._journal.entries);
        }

        this.disposer.add(auth.onPreProcessUser.on(u => this.onPreProcessAuthUser(u)), 'onPreProcessAuthUser');

        // TODO: Make prettier
        this.disposer.add(autorun(() => {
            const userId = this.user?.id;
            const acccountId = (this._activeAccount && this._activeAccount.id) || null;
            const coachId = (this._activeAccount && this._activeAccount.coachId) || null;

            this._journal.setAccount(userId, acccountId, coachId);
        }));
    }
Example #7
Source File: swapStore.ts    From lightning-terminal with MIT License 6 votes vote down vote up
/**
   * initialize the swap state and auto-save when the state is changed
   */
  init() {
    this.load();
    autorun(
      () => {
        const swapState: PersistentSwapState = {
          swappedChannels: (this.swappedChannels.toJSON() as unknown) as Record<
            string,
            string[]
          >,
          dismissedSwapIds: this.dismissedSwapIds,
        };
        this._store.storage.set('swapState', swapState);
        this._store.log.info('saved swapState to localStorage', swapState);
      },
      { name: 'swapStoreAutorun' },
    );
  }
Example #8
Source File: BlockDAG.tsx    From casper-clarity with Apache License 2.0 6 votes vote down vote up
constructor(props: Props) {
    super(props);
    autorun(
      () => {
        this.renderGraph();
      },
      {
        delay: 400
      }
    );
  }
Example #9
Source File: analytics.ts    From mysterium-vpn-desktop with MIT License 6 votes vote down vote up
initialize(): void {
        this.client.app_version = packageJson.version
        autorun(() => {
            this.client.os = rootStore.os
        })
        autorun(() => {
            this.client.country = rootStore.connection.originalLocation?.country
        })
        autorun(() => {
            this.client.consumer_id = rootStore.identity.identity?.id
        })
        ipcRenderer.invoke(MainIpcListenChannels.GetMachineId).then((machineId) => {
            this.client.machine_id = machineId
        })
        ipcRenderer.invoke(MainIpcListenChannels.GetOS).then((os) => {
            this.client.os = os
        })
        ipcRenderer.invoke(MainIpcListenChannels.GetOSVersion).then((os_version) => {
            this.client.os_version = os_version
        })
    }
Example #10
Source File: AudioItem.ts    From companion-kit with MIT License 6 votes vote down vote up
onActive(cb: () => void) {
        if (this._onActiveUnsubsriber) {
            this._onActiveUnsubsriber();
            this._onActiveUnsubsriber = null;
        }

        if (cb) {
            this._onActiveUnsubsriber = autorun(() => {
                if (this.active) {
                    cb();
                }
            });
        }

        return this;
    }
Example #11
Source File: connections.ts    From config-generator with MIT License 6 votes vote down vote up
function autoSave(store: any, save: any) {
  let firstRun = true;
  autorun(() => {
    const connectionsStore = toJS(store);
    delete connectionsStore.rootStore;
    const json = JSON.stringify(connectionsStore);
    if (!firstRun) {
      save(json);
    }
    firstRun = false;
  });
}
Example #12
Source File: Clients.ts    From companion-kit with MIT License 6 votes vote down vote up
constructor(private readonly getCoachId: () => string) {

        // re-fetch clients if coach id changes
        this._unsubscribers.push(autorun(() => {
            const coachId = this.getCoachId();
            if (coachId !== this._coachId) {
                this.fetchClients(coachId);
            }
            this._coachId = coachId;
        }));

        this.splitByStatus();
    }
Example #13
Source File: destinationsList.ts    From config-generator with MIT License 6 votes vote down vote up
function autoSave(store: any, save: any) {
  let firstRun = true;
  autorun(() => {
    const destinationsListStore = toJS(store);
    delete destinationsListStore.rootStore;
    destinationsListStore.destinations.forEach(
      (destination: IDestinationStore) => {
        delete destination.rootStore;
      },
    );
    const json = JSON.stringify(destinationsListStore);
    if (!firstRun) {
      save(json);
    }
    firstRun = false;
  });
}
Example #14
Source File: BlockDAG.tsx    From clarity with Apache License 2.0 6 votes vote down vote up
constructor(props: Props) {
    super(props);
    autorun(
      () => {
        this.renderGraph();
      },
      {
        delay: 400
      }
    );
  }
Example #15
Source File: chooseDevice.ts    From binaural-meet with GNU General Public License v3.0 6 votes vote down vote up
/*
//  microphone or audio input device update
autorun(() => {
  const did = participants.local.devicePreference.audioInputDevice
  const muted = participants.local.muteAudio
  if (participants.localId && !muted && urlParameters.testBot === null) {
    const track = connection.conference.getLocalMicTrack()
    if (track && track.getDeviceId() === did) { return }
    createLocalMic().finally(getNotificationPermission)
  }
})
*/

//  headphone or audio output device update
autorun(() => {
  const did = participants.local.devicePreference.audioOutputDevice
  if (did) {
    audioManager.setAudioOutput(did)
  }
})
Example #16
Source File: tcpip.tsx    From ya-webadb with MIT License 6 votes vote down vote up
constructor() {
        makeAutoObservable(this, {
            initial: false,
            queryInfo: false,
            applyServicePort: false,
        });


        autorun(() => {
            if (GlobalState.device) {
                if (this.initial && this.visible) {
                    this.initial = false;
                    this.queryInfo();
                }
            } else {
                this.initial = true;
            }
        });
    }
Example #17
Source File: Recorder.ts    From binaural-meet with GNU General Public License v3.0 6 votes vote down vote up
start(stores: Stores){
    this.clear()
    //  start recording
    this.recording = true
    this.startTime = Date.now()
    //  list all track related to participants and contents
    this.disposers.push(autorun(()=>{
      this.updateMediaRecorders()
    }))

    //  Record all contents
    const cs = extractContentDataAndIds(stores.contents.all)
    this.messages.push({msg:{t:MessageType.CONTENT_UPDATE_REQUEST, v:JSON.stringify(cs)}, time: Date.now()})
    //  Record all participants
    const participants:ParticipantBase[] = Array.from(stores.participants.remote.values())
    participants.unshift(stores.participants.local)
    for(const p of participants){
      this.messages.push(
        {msg:{t:MessageType.PARTICIPANT_INFO, p:p.id, v:JSON.stringify(p.information)}, time: Date.now()})
      this.messages.push(
        {msg:{t:MessageType.PARTICIPANT_POSE, p: p.id, v:JSON.stringify(pose2Str(p.pose))}, time: Date.now()})
      this.messages.push(
        {msg:{t:MessageType.PARTICIPANT_MOUSE, p: p.id, v:JSON.stringify(mouse2Str(p.mouse))}, time: Date.now()})
    }
  }
Example #18
Source File: packet-log.tsx    From ya-webadb with MIT License 6 votes vote down vote up
state = new class {
    get empty() {
        return !GlobalState.logs.length;
    }

    get commandBarItems(): ICommandBarItemProps[] {
        return [
            {
                key: 'clear',
                disabled: this.empty,
                iconProps: { iconName: Icons.Delete },
                text: 'Clear',
                onClick: () => GlobalState.clearLog(),
            }
        ];
    }

    selectedPacket: PacketLogItem | undefined = undefined;

    constructor() {
        makeAutoObservable(
            this,
            {
                selectedPacket: observable.ref,
            }
        );

        autorun(() => {
            if (GlobalState.logs.length === 0) {
                this.selectedPacket = undefined;
            }
        });
    }
}
Example #19
Source File: chooseDevice.ts    From binaural-meet with GNU General Public License v3.0 6 votes vote down vote up
autorun(() => {
  const did = participants.local.devicePreference.audioInputDevice
  const muted = participants.local.muteAudio || participants.local.physics.awayFromKeyboard
  if (participants.localId && !muted && urlParameters.testBot === null) {
    const track = connection.conference.getLocalMicTrack()
    if (track && track.getDeviceId() === did) { return }
    createLocalMic().finally(getNotificationPermission)
  }else{
    if (DELETE_MIC_TRACK){
      connection.conference.setLocalMicTrack(undefined).then(track => {
        track?.dispose()
        participants.local.audioLevel = 0
      })
    } else {
      const track = connection.conference.getLocalMicTrack()
      if (track) { connection.conference.removeTrack(track) }
      participants.local.audioLevel = 0
    }
  }
})
Example #20
Source File: logcat.tsx    From ya-webadb with MIT License 6 votes vote down vote up
autorun(() => {
    if (GlobalState.device) {
        runInAction(() => {
            state.logcat = new Logcat(GlobalState.device!);
        });
    } else {
        runInAction(() => {
            state.logcat = undefined;
            if (state.running) {
                state.stop();
            }
        });
    }
});
Example #21
Source File: ErrorInfo.ts    From binaural-meet with GNU General Public License v3.0 6 votes vote down vote up
constructor() {
    makeObservable(this)
    if (urlParameters['testBot'] !== null) {
      this.clear()
    }
    autorun(() => {
      if (this.show()) {
        map.keyInputUsers.add('errorDialog')
      }else {
        map.keyInputUsers.delete('errorDialog')
      }
    })
    autorun(() => {
      if (participants.local.physics.awayFromKeyboard){
        this.setType('afk')
      }
    })
  }
Example #22
Source File: CodeLinkFeature.ts    From vscode-drawio with GNU General Public License v3.0 5 votes vote down vote up
constructor(
		private readonly editorManager: DrawioEditorService,
		private readonly config: Config
	) {
		this.dispose.track([
			editorManager.onEditorOpened.sub(({ editor }) =>
				this.handleDrawioEditor(editor)
			),
			{
				dispose: autorun(
					() => {
						const activeEditor = editorManager.activeDrawioEditor;
						this.statusBar.command =
							toggleCodeLinkActivationCommandName;

						if (activeEditor) {
							this.statusBar.text = `$(link) ${
								activeEditor.config.codeLinkActivated
									? "$(circle-filled)"
									: "$(circle-outline)"
							} Code Link`;
							this.statusBar.show();
						} else {
							this.statusBar.hide();
						}
					},
					{ name: "Update UI" }
				),
			},
			window.onDidChangeActiveTextEditor(() => {
				if (window.activeTextEditor) {
					this.lastActiveTextEditor = window.activeTextEditor;
				}
			}),
			registerFailableCommand(
				linkCodeWithSelectedNodeCommandName,
				this.linkCodeWithSelectedNode
			),
			registerFailableCommand(
				toggleCodeLinkActivationCommandName,
				this.toggleCodeLinkEnabled
			),
			registerFailableCommand(
				linkFileWithSelectedNodeCommandName,
				this.linkFileWithSelectedNode
			),
			registerFailableCommand(
				linkSymbolWithSelectedNodeCommandName,
				this.linkSymbolWithSelectedNode
			),
			registerFailableCommand(
				linkWsSymbolWithSelectedNodeCommandName,
				this.linkWsSymbolWithSelectedNode
			),
		]);
	}
Example #23
Source File: store.ts    From lightning-terminal with MIT License 5 votes vote down vote up
/**
   * load initial data to populate the store
   */
  async init() {
    this.settingsStore.init();
    this.swapStore.init();
    this.batchStore.init();
    await this.authStore.init();
    runInAction(() => {
      this.initialized = true;
    });

    // this function will automatically run whenever the authenticated
    // flag is changed
    autorun(
      async () => {
        if (this.authStore.authenticated) {
          // go to the Loop page when the user is authenticated. it can be from
          // entering a password or from loading the credentials from storage.
          // only do this if the auth page is currently being viewed, otherwise
          // stay on the current page (ex: history, settings)
          if (document.location.pathname === `${PUBLIC_URL}/`) {
            runInAction(() => {
              this.appView.goToLoop();
            });
          }
          // also fetch all the data we need
          this.fetchAllData();
          // connect and subscribe to the server-side streams
          this.connectToStreams();
          this.subscribeToStreams();
        } else {
          // go to auth page if we are not authenticated
          this.appView.gotoAuth();
          // unsubscribe from streams since we are no longer authenticated
          this.unsubscribeFromStreams();
        }
      },
      { name: 'authenticatedAutorun' },
    );
  }
Example #24
Source File: LocaleStore.ts    From react-enterprise-starter-pack with MIT License 5 votes vote down vote up
constructor() {
    this.locale = ""

    autorun(() => {
      this.setLocale(navigator.language.split(/[-_]/)[0])
    })
  }
Example #25
Source File: scrcpy.tsx    From ya-webadb with MIT License 5 votes vote down vote up
constructor() {
        makeAutoObservable(this, {
            decoders: observable.shallow,
            settings: observable.deep,
            start: false,
            stop: action.bound,
            dispose: action.bound,
            handleDeviceViewRef: action.bound,
            handleRendererContainerRef: action.bound,
            handleBackPointerDown: false,
            handleBackPointerUp: false,
            handleHomePointerDown: false,
            handleHomePointerUp: false,
            handleAppSwitchPointerDown: false,
            handleAppSwitchPointerUp: false,
            calculatePointerPosition: false,
            injectTouch: false,
            handlePointerDown: false,
            handlePointerMove: false,
            handlePointerUp: false,
            handleWheel: false,
            handleContextMenu: false,
            handleKeyDown: false,
        });

        autorun(() => {
            if (GlobalState.device) {
                runInAction(() => {
                    this.encoders = [];
                    this.settings.encoderName = undefined;

                    this.displays = [];
                    this.settings.displayId = undefined;
                });
            } else {
                this.dispose();
            }
        });

        autorun(() => {
            if (this.rendererContainer && this.decoder) {
                while (this.rendererContainer.firstChild) {
                    this.rendererContainer.firstChild.remove();
                }
                this.rendererContainer.appendChild(this.decoder.renderer);
            }
        });

        autorun(() => {
            this.settings.decoder = this.decoders[0].key;
        });

        if (typeof window !== 'undefined' && typeof window.VideoDecoder === 'function') {
            setTimeout(action(() => {
                this.decoders.unshift({
                    key: 'webcodecs',
                    name: 'WebCodecs',
                    Constructor: WebCodecsDecoder,
                });
            }), 0);
        }
    }
Example #26
Source File: StereoManager.ts    From binaural-meet with GNU General Public License v3.0 5 votes vote down vote up
switchPlayMode(playMode: PlayMode, muted: boolean) {
    assert(playMode !== 'Pause')
    if (this.playMode === 'Pause') {
      //  this occurs only once when valid playMode has been set
      autorun(() => {
        const accepts = new Set(priorityCalculator.tracksToAccept[1].map(info => info.endpointId))
        for (const id in this.nodes) {
          if (accepts.has(id) || this.nodes[id] instanceof NodeGroupForPlayback) {
            this.nodes[id].setPlayMode(this.playMode)
          }else {
            this.nodes[id].setPlayMode('Pause')
          }
        }
      })
    }

    if (playMode === this.playMode && muted === this.audioOutputMuted) {
      return
    }
    this.playMode = playMode

    switch (playMode) {
      case 'Context':
        // For Chrome, resume audio context when loaded (https://goo.gl/7K7WLu)
        // AudioContext must be resumed (or created) after a user gesture on the page.
        const interval = setInterval(
          () => {
            if (errorInfo.type) { return }
            // console.log(`Audio context = ${this.audioContext.state}  element = ${this.audioElement.played}`)
            if (this.audioContext.state !== 'suspended') {
              //  console.log('AudioContext successfully resumed')
              clearInterval(interval)
            }
            this.audioContext.resume()
            this.audioElement.play()  //  play() must be delayed
          },
          1000,
        )

        for (const id in this.nodes) {
          this.nodes[id].setPlayMode(playMode)
        }
        break

      case 'Element':
        this.audioContext.suspend()
        this.audioElement.pause()

        for (const id in this.nodes) {
          this.nodes[id].setPlayMode(playMode)
        }
        break

      default:
        console.error(`Unsupported play mode: ${playMode}`)
        break
    }

    this.audioOutputMuted = muted
  }
Example #27
Source File: background.ts    From clarity with Apache License 2.0 5 votes vote down vote up
// Setup RPC server for Popup
async function setupPopupAPIServer() {
  const rpc = new Rpc({
    addListener: browser.runtime.onMessage.addListener,
    destination: 'popup',
    postMessage: browser.runtime.sendMessage,
    source: 'background'
  });
  // once appState update, send updated appState to popup
  autorun(() => {
    rpc.call<void>('popup.updateState', appState).catch(e => {
      console.log(e);
    });
    updateBadge(appState);
  });
  rpc.register(
    'account.unlock',
    accountController.unlock.bind(accountController)
  );
  rpc.register(
    'account.createNewVault',
    accountController.createNewVault.bind(accountController)
  );
  rpc.register('account.lock', accountController.lock.bind(accountController));
  rpc.register(
    'account.importUserAccount',
    accountController.importUserAccount.bind(accountController)
  );
  rpc.register(
    'account.removeUserAccount',
    accountController.removeUserAccount.bind(accountController)
  );
  rpc.register(
    'account.renameUserAccount',
    accountController.renameUserAccount.bind(accountController)
  );
  rpc.register(
    'account.reorderAccount',
    accountController.reorderAccount.bind(accountController)
  );
  rpc.register(
    'account.getSelectUserAccount',
    accountController.getSelectUserAccount.bind(accountController)
  );
  rpc.register(
    'account.resetVault',
    accountController.resetVault.bind(accountController)
  );
  rpc.register(
    'account.switchToAccount',
    accountController.switchToAccount.bind(accountController)
  );
  rpc.register('background.getState', () => {
    return appState;
  });
  rpc.register(
    'sign.signMessage',
    signMessageManager.approveMsg.bind(signMessageManager)
  );
  rpc.register(
    'sign.rejectMessage',
    signMessageManager.rejectMsg.bind(signMessageManager)
  );
  rpc.register(
    'connection.requestConnection',
    connectionManager.requestConnection.bind(connectionManager)
  );
  rpc.register(
    'connection.resetConnectionRequest',
    connectionManager.resetConnectionRequest.bind(connectionManager)
  );
  rpc.register(
    'connection.connectToSite',
    connectionManager.connectToSite.bind(connectionManager)
  );
  rpc.register(
    'connection.disconnectFromSite',
    connectionManager.disconnectFromSite.bind(connectionManager)
  );
}
Example #28
Source File: trafficControl.ts    From binaural-meet with GNU General Public License v3.0 5 votes vote down vote up
autorun(() => {
  const local = participantsStore.local
  priorityCalculator.setLimits([local.remoteVideoLimit, local.remoteAudioLimit])
})
Example #29
Source File: DrawioEditorService.ts    From vscode-drawio with GNU General Public License v3.0 5 votes vote down vote up
constructor(
		private readonly config: Config,
		private readonly drawioClientFactory: DrawioClientFactory
	) {
		autorun(() => {
			const a = this.activeDrawioEditor;
			if (a) {
				this._lastActiveDrawioEditor = a;
			}
			commands.executeCommand(
				"setContext",
				"hediet.vscode-drawio.active",
				!!a
			);
		});

		this.dispose.track(
			registerFailableCommand(drawioChangeThemeCommand, () => {
				const activeDrawioEditor = this.activeDrawioEditor;
				if (!activeDrawioEditor) {
					return;
				}
				activeDrawioEditor.handleChangeThemeCommand();
			})
		);

		this.dispose.track(
			registerFailableCommand("hediet.vscode-drawio.convert", () => {
				const activeDrawioEditor = this.activeDrawioEditor;
				if (!activeDrawioEditor) {
					return;
				}
				activeDrawioEditor.handleConvertCommand();
			})
		);

		this.dispose.track(
			registerFailableCommand(
				"hediet.vscode-drawio.reload-webview",
				() => {
					for (const e of this.openedEditors) {
						e.drawioClient.reloadWebview();
					}
				}
			)
		);

		this.dispose.track(
			registerFailableCommand("hediet.vscode-drawio.export", () => {
				const activeDrawioEditor = this.activeDrawioEditor;
				if (!activeDrawioEditor) {
					return;
				}
				activeDrawioEditor.handleExportCommand();
			})
		);

		this.dispose.track({
			dispose: autorun(
				() => {
					const activeEditor = this.activeDrawioEditor;
					this.statusBar.command = drawioChangeThemeCommand;

					if (activeEditor) {
						this.statusBar.text = `Theme: ${activeEditor.config.theme}`;
						this.statusBar.show();
					} else {
						this.statusBar.hide();
					}
				},
				{ name: "Update UI" }
			),
		});
	}