mobx#toJS TypeScript Examples

The following examples show how to use mobx#toJS. 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: Paging.tsx    From jmix-frontend with Apache License 2.0 7 votes vote down vote up
render() {
    const {paginationConfig, total} = this.props;

    return (
      <Pagination
        {...paginationConfig}
        total={total}
        pageSizeOptions={toJS(paginationConfig.pageSizeOptions)}
        onChange={this.props.onPagingChange}
        onShowSizeChange={this.props.onPagingChange}
      />
    );
  }
Example #2
Source File: settingsStore.ts    From lightning-terminal with MIT License 6 votes vote down vote up
/**
   * Sets the sort field and direction that the channel list should use
   * @param field the channel field to sort by
   * @param descending true of the order should be descending, otherwise false
   */
  setChannelSort(field: SortParams<Channel>['field'], descending: boolean) {
    this.channelSort = { field, descending };
    this._store.log.info('updated channel list sort order', toJS(this.channelSort));
  }
Example #3
Source File: useExistingSettings.ts    From videotranscode.space with Apache License 2.0 6 votes vote down vote up
useExistingSettings: useExistingSettingsType = ({
  main,
  child,
  other,
  defaults
}) => {
  const { configuration } = cluiStore

  const jsConifg = toJS(configuration)
  if (Object.keys(jsConifg).length > 0) {
    const mainOutput = getObject(main, jsConifg)
    const output = { main: mainOutput || defaults.main }
    if (child) {
      const childOutput = getObject(child, jsConifg)

      Object.assign(output, { child: childOutput || defaults.child })
    }
    if (other) {
      const otherOutputs: Output[] = []
      let noFalse = true
      for (const value of other) {
        const otherObj = getObject(value, jsConifg)
        if (otherObj) {
          otherOutputs.push(otherObj)
        } else {
          noFalse = false
          break
        }
      }
      Object.assign(output, { other: noFalse ? otherOutputs : defaults.other })
    }
    return output
  } else {
    return defaults
  }
}
Example #4
Source File: registerSidecarView.ts    From lightning-terminal with MIT License 6 votes vote down vote up
/**
   * submit a request to the Pool API to perform the ticket registration
   */
  registerTicket() {
    const delay =
      process.env.NODE_ENV === 'test'
        ? 1 // use a 1 ms delay for unit tests
        : TICKET_ABORT_DELAY;

    this.processingTimeout = setTimeout(async () => {
      try {
        this._store.log.info(`registering sidecar ticket`, toJS(this.ticket));
        const res = await this._store.api.pool.registerSidecar(this.ticket);
        this.goToNextStep();
        this._store.log.info(`registered ticket successfully`, toJS(res.ticket));
      } catch (error) {
        this._store.appView.handleError(error, `Unable to register ticket`);
        this.goToPrevStep();
      }
    }, delay);
  }
Example #5
Source File: TableContainer.tsx    From generator-earth with MIT License 6 votes vote down vote up
/**
     * table分页信息
     * @override
     * component.pagination {pageSize/rows, pageNo/page, total}
     * 转换为
     * antd.pagination {pageSize, current, total}
     */
    getPagination(): Pagination {
        const dataBase: any = toJS(this.props.store.allDataSource[this.props.sourceId]);

        return {
            pageSize: dataBase[PAGE_SIZE],
            current: dataBase[CURRENT_PAGE],
            total: dataBase[TOTAL],
            showTotal: total => `共 ${total} 条数据`
        }
    }
Example #6
Source File: buildSwapView.ts    From lightning-terminal with MIT License 6 votes vote down vote up
/**
   * fetch the terms, minimum/maximum swap amount allowed, from the Loop API
   */
  async getTerms(): Promise<void> {
    this._store.log.info(`fetching loop terms`);
    try {
      const inTerms = await this._store.api.loop.getLoopInTerms();
      const outTerms = await this._store.api.loop.getLoopOutTerms();
      runInAction(() => {
        this.terms = {
          in: {
            min: Big(inTerms.minSwapAmount),
            max: Big(inTerms.maxSwapAmount),
          },
          out: {
            min: Big(outTerms.minSwapAmount),
            max: Big(outTerms.maxSwapAmount),
            minCltv: outTerms.minCltvDelta,
            maxCltv: outTerms.maxCltvDelta,
          },
        };
        this._store.log.info('updated store.terms', toJS(this.terms));
      });
    } catch (error) {
      this._store.appView.handleError(error, 'Unable to fetch Loop Terms');
      this.goToPrevStep();
    }
  }
Example #7
Source File: main.ts    From hubble-ui with Apache License 2.0 6 votes vote down vote up
// D E B U G
  @action.bound
  public setupDebugTools() {
    setupDebugProp({
      printMapData: () => {
        this.printMapData();
      },
      printLayoutData: () => {
        this.printLayoutData();
      },
      mobxToJs: (obj: any) => toJS(obj),
    });
  }
Example #8
Source File: destinationsList.ts    From config-generator with MIT License 6 votes vote down vote up
public returnWithoutRootStore() {
    const destinationsListStore = toJS(this);
    delete destinationsListStore.rootStore;
    destinationsListStore.destinations.forEach(
      (destination: IDestinationStore) => {
        delete destination.rootStore;
      },
    );
    return destinationsListStore;
  }
Example #9
Source File: ItemsCRUDController.ts    From companion-kit with MIT License 6 votes vote down vote up
async duplicate(id: string) {
        const p = this.types()?.find(lp => lp.id === id);
        if (!p) {
            throw new Error('Item to duplicate was not found');
        }

        return this.submit({
            add: [toJS({...p, id: null })],
        });
        // await Firebase.Instance.getFunction(CoachesFunctions.PromptsEndpoint)
        //     .execute({add: [toJS(p)], type: 'prompt'});
    }
Example #10
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 #11
Source File: BaseEdgeModel.ts    From LogicFlow with Apache License 2.0 6 votes vote down vote up
/**
   * 获取被保存时返回的数据
   */
  getData(): EdgeData {
    const { x, y, value } = this.text;
    const data: EdgeData = {
      id: this.id,
      type: this.type,
      sourceNodeId: this.sourceNode.id,
      targetNodeId: this.targetNode.id,
      startPoint: Object.assign({}, this.startPoint),
      endPoint: Object.assign({}, this.endPoint),
      properties: toJS(this.properties),
    };
    if (value) {
      data.text = {
        x,
        y,
        value,
      };
    }
    if (this.graphModel.overlapMode === OverlapMode.INCREASE) {
      data.zIndex = this.zIndex;
    }
    return data;
  }
Example #12
Source File: store.ts    From generator-earth with MIT License 6 votes vote down vote up
@action setRequestStr = () => {
        const {commonTableStore} =  this.rootStore;

        const result = commonTableStore.getRequestTypeAndUrlBySourceId(SOURCE_ID);

        // console.log(toJS(result));

        this.requestStr = JSON.stringify(toJS(result));

    }
Example #13
Source File: BaseNodeModel.ts    From LogicFlow with Apache License 2.0 6 votes vote down vote up
/**
   * 获取被保存时返回的数据
   * @overridable 支持重写
   */
  getData(): NodeData {
    const { x, y, value } = this.text;
    let { properties } = this;
    if (isObservable(properties)) {
      properties = toJS(properties);
    }
    const data: NodeData = {
      id: this.id,
      type: this.type,
      x: this.x,
      y: this.y,
      properties,
    };
    if (this.graphModel.overlapMode === OverlapMode.INCREASE) {
      data.zIndex = this.zIndex;
    }
    if (value) {
      data.text = {
        x,
        y,
        value,
      };
    }
    return data;
  }
Example #14
Source File: store.ts    From mysterium-vpn-desktop with MIT License 6 votes vote down vote up
async register(id: Identity, referralToken?: string): Promise<void> {
        log.info("Registering MysteriumID: ", toJS(id), referralToken ? `token: ${referralToken}` : "")
        await this.root.payment.fetchTransactorFees()
        try {
            await tequilapi.identityRegister(id.id, { stake: 0, referralToken })
        } catch (err) {
            log.error("Failed to register identity", err)
        }
    }
Example #15
Source File: store.ts    From generator-earth with MIT License 6 votes vote down vote up
@action setParamsStr = () => {
        const {commonTableStore} =  this.rootStore

        const result = commonTableStore.getRequestInfoBySourceId(SOURCE_ID);
        // console.log(toJS(result));

        this.paramsStr = JSON.stringify(toJS(result));

    }
Example #16
Source File: accountStore.ts    From lightning-terminal with MIT License 6 votes vote down vote up
/**
   * Creates an account via the pool API
   * @param amount the amount (sats) to fund the account with
   * @param expiryBlocks the number of blocks from now to expire the account
   */
  async createAccount(amount: Big, expiryBlocks: number, confTarget?: number) {
    this._store.log.info(`creating new account with ${amount}sats`);
    try {
      const acct = await this._store.api.pool.initAccount(
        amount,
        expiryBlocks,
        confTarget,
      );
      runInAction(() => {
        const traderKey = hex(acct.traderKey);
        this.accounts.set(traderKey, new Account(this._store, acct));
        this.setActiveTraderKey(traderKey);
        this._store.log.info('updated accountStore.accounts', toJS(this.accounts));
      });
      return acct.traderKey;
    } catch (error) {
      this._store.appView.handleError(error, 'Unable to create the account');
    }
  }
Example #17
Source File: SettingStore.ts    From electron with MIT License 5 votes vote down vote up
@action public SetSettings = async (newSetting: Partial<SettingJsonTypes>) => {
    runInAction(() => {
      this.settings = Object.assign(toJS(this.settings), newSetting);
      $$.Settings.writeSetting(newSetting);
    });
  };
Example #18
Source File: sourcesList.ts    From config-generator with MIT License 5 votes vote down vote up
public returnWithoutRootStore() {
    const sourcesListStore = toJS(this);
    delete sourcesListStore.rootStore;
    sourcesListStore.sources.forEach((source: ISourceStore) => {
      delete source.rootStore;
    });
    return sourcesListStore;
  }
Example #19
Source File: SettingStore.ts    From electron with MIT License 5 votes vote down vote up
constructor() {
    this.settings = JSON.parse(JSON.stringify(toJS($$.Settings.readSetting())));
  }
Example #20
Source File: appView.ts    From lightning-terminal with MIT License 5 votes vote down vote up
/** removes an existing alert */
  clearAlert(id: number) {
    this.alerts.delete(id);
    this._store.log.info('Cleared alert', id, toJS(this.alerts));
  }
Example #21
Source File: connections.ts    From config-generator with MIT License 5 votes vote down vote up
public returnWithoutRootStore() {
    const connectionsStore = toJS(this);
    delete connectionsStore.rootStore;
    return connectionsStore;
  }
Example #22
Source File: buildSwapView.ts    From lightning-terminal with MIT License 5 votes vote down vote up
/**
   * get a loop quote from the Loop RPC
   */
  async getQuote(): Promise<void> {
    const { amount, direction } = this;
    this._store.log.info(`fetching ${direction} quote for ${amount} sats`);

    try {
      let quote: Quote;
      if (direction === SwapDirection.IN) {
        const inQuote = await this._store.api.loop.getLoopInQuote(
          amount,
          this.confTarget,
        );
        quote = {
          swapFee: Big(inQuote.swapFeeSat),
          minerFee: Big(inQuote.htlcPublishFeeSat),
          prepayAmount: Big(0),
        };
      } else {
        const outQuote = await this._store.api.loop.getLoopOutQuote(
          amount,
          this.confTarget,
        );
        quote = {
          swapFee: Big(outQuote.swapFeeSat),
          minerFee: Big(outQuote.htlcSweepFeeSat),
          prepayAmount: Big(outQuote.prepayAmtSat),
        };
      }

      runInAction(() => {
        this.quote = quote;
        this._store.log.info('updated buildSwapView.quote', toJS(this.quote));
      });
    } catch (error) {
      this._store.appView.handleError(error, 'Unable to fetch Quote');
      this.goToPrevStep();
    }
  }
Example #23
Source File: store.ts    From mysterium-vpn-desktop with MIT License 5 votes vote down vote up
async createOrder(): Promise<void> {
        const id = this.root.identity.identity?.id
        if (!id || !this.topUpAmountUSD || !this.paymentCurrency || !this.paymentMethod) {
            return
        }

        const order = await tequilapi.payment.createOrder(id, this.paymentMethod.gateway, {
            country: this.taxCountry || "",
            amountUsd: new BigNumber(this.topUpAmountUSD).toFixed(2),
            payCurrency: this.paymentCurrency,
            gatewayCallerData: this.buildCallerData(),
        })
        log.info("Payment order created", order)
        this.validateOrderResponse(order)
        log.info("Payment order validated")

        runInAction(() => {
            this.order = order
            if (order.publicGatewayData?.expireAt) {
                this.orderExpiresAt = new Date(order.publicGatewayData.expireAt)
            }
        })

        retry(
            async () => {
                if (!this.order) {
                    return
                }
                const order = await tequilapi.payment.order(id, this.order.id)
                runInAction(() => {
                    this.order = order
                    log.info("Updated order", toJS(this.order))
                    if (this.orderStatus == OrderStatus.PENDING) {
                        throw Error("Order is in pending state")
                    }
                })
            },
            {
                retries: 60,
                factor: 1,
                minTimeout: 10_000,
                onRetry: (e, attempt) => log.warn(`Retrying payment order check (${attempt}): ${e.message}`),
            },
        )
    }
Example #24
Source File: buildSwapView.ts    From lightning-terminal with MIT License 5 votes vote down vote up
/**
   * submit a request to the Loop API to perform a swap. There will be a 3 second
   * delay added to allow the swap to be aborted
   */
  requestSwap() {
    const delay =
      process.env.NODE_ENV === 'test'
        ? 1 // use a 1 ms delay for unit tests
        : this._store.appView.tourVisible
        ? 1500 // use a 1.5 second delay during the tour
        : SWAP_ABORT_DELAY;
    const { amount, direction, quote } = this;
    this._store.log.info(
      `executing ${direction} for ${amount} sats (delaying for ${delay}ms)`,
    );
    this.processingTimeout = setTimeout(async () => {
      try {
        let res: SwapResponse.AsObject;
        if (direction === SwapDirection.IN) {
          res = await this._store.api.loop.loopIn(
            amount,
            quote,
            this.loopInLastHop,
            this.confTarget,
          );
          // save the channels that were used in the swap. for Loop In all channels
          // with the same peer will be used
          this._store.swapStore.addSwappedChannels(res.id, this.selectedChanIds);
        } else {
          // on regtest, set the publication deadline to 0 for faster swaps, otherwise
          // set it to 30 minutes in the future to reduce swap fees
          const thirtyMins = 30 * 60 * 1000;
          const deadline =
            this._store.nodeStore.network === 'regtest' ? 0 : Date.now() + thirtyMins;
          // convert the selected channel ids to numbers
          res = await this._store.api.loop.loopOut(
            amount,
            quote,
            this.selectedChanIds,
            deadline,
            this.confTarget,
            this.loopOutAddress,
          );
          // save the channels that were used in the swap
          this._store.swapStore.addSwappedChannels(res.id, this.selectedChanIds);
        }
        this._store.log.info('completed loop', toJS(res));
        runInAction(() => {
          // hide the swap UI after it is complete
          this.cancel();
          this._store.appView.toggleProcessingSwaps();
          this._store.appView.tourGoToNext();
        });
      } catch (error) {
        this._store.appView.handleError(error, `Unable to Perform ${direction}`);
        this.goToPrevStep();
      }
    }, delay);
  }
Example #25
Source File: store.ts    From mysterium-vpn-desktop with MIT License 5 votes vote down vote up
// Offload to main
    persistConfig = async (): Promise<void> => {
        ipcRenderer.send(MainIpcListenChannels.SaveUserConfig, toJS(this.config))
    }
Example #26
Source File: orderStore.ts    From lightning-terminal with MIT License 5 votes vote down vote up
/**
   * queries the POOL api to fetch the list of leases and stores them
   * in the state
   */
  async fetchLeases() {
    this._store.log.info('fetching leases');

    try {
      const {
        leasesList,
        totalAmtEarnedSat,
        totalAmtPaidSat,
      } = await this._store.api.pool.listLeases();

      runInAction(() => {
        this.earnedSats = Big(totalAmtEarnedSat);
        this.paidSats = Big(totalAmtPaidSat);
        leasesList.forEach(poolLease => {
          // update existing leases or create new ones in state. using this
          // approach instead of overwriting the array will cause fewer state
          // mutations, resulting in better react rendering performance
          const channelPoint = Lease.channelPointToString(poolLease.channelPoint);
          const existing = this.leases.get(channelPoint);
          if (existing) {
            existing.update(poolLease);
          } else {
            this.leases.set(channelPoint, new Lease(poolLease));
          }
        });
        // remove any leases in state that are not in the API response
        const serverIds = leasesList.map(a => Lease.channelPointToString(a.channelPoint));
        const localIds = keys(this.leases).map(key => String(key));
        localIds
          .filter(id => !serverIds.includes(id))
          .forEach(id => this.leases.delete(id));
        this._store.log.info('updated orderStore.leases', toJS(this.leases));
      });
    } catch (error) {
      this._store.appView.handleError(error, 'Unable to fetch leases');
    }
  }
Example #27
Source File: cluiStore.ts    From videotranscode.space with Apache License 2.0 5 votes vote down vote up
/**
   * Recursively Finds Correct Config and Updates it with the value
   *
   * Example, User updates config of Compress-Transcode->Transcode->Format->Codec is AVI
   * This method will create {Transcode : {Format : {Codec : {chosenCodec : "AVI"}}}}
   *
   * @param newConfiguration Object of user set configurations
   * @param parents An Array of keys of parents, this will determine where the object is updated
   *
   * NOTE: THIS WILL MUTATE PARENTS ARRAY, Only Pass Array as a copy
   *
   */
  @action updateConfiguration = (
    newConfiguration: { value: any; [name: string]: any },
    inputParents: Array<string>
  ) => {
    const parents = [...inputParents] // Specifically to prevent mutation of parents
    const { configuration } = this
    function updateObject(object: any) {
      while (parents.length > 1) {
        const key = parents.shift() as string
        if (!(key in object)) {
          object = Object.assign(object, { [key]: {} })
        }
        object = object[key]
      }
      const key = parents.shift() as string
      if (key in object) {
        object[key] = Object.assign(object[key], newConfiguration)
      } else {
        object = Object.assign(object, { [key]: newConfiguration })
      }
    }
    updateObject(configuration)

    this.configuration = configuration

    this.configurationJS = toJS(configuration)
    // console.table(this.configurationJS);
  }
Example #28
Source File: accountStore.ts    From lightning-terminal with MIT License 5 votes vote down vote up
/** switch to a different account */
  setActiveTraderKey(traderKey: string) {
    this.activeTraderKey = traderKey;
    this._store.log.info(
      'updated accountStore.activeTraderKey',
      toJS(this.activeTraderKey),
    );
  }
Example #29
Source File: TableContainer.tsx    From generator-earth with MIT License 5 votes vote down vote up
/**
     * 获取当前本项目的相关数据
     * @desc 具体哪些字段 请查看AllDataSourceParams
     */
    getLocalData = (): AllDataSourceParams => {
        return toJS(this.props.store.allDataSource[this.props.sourceId])
    }