immutable#fromJS TypeScript Examples

The following examples show how to use immutable#fromJS. 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: loadOutgoingTransactions.ts    From multisig-react with MIT License 6 votes vote down vote up
loadOutgoingTransactions = async (safeAddress: string): Promise<SafeTransactionsType> => {
  const defaultResponse = {
    cancel: Map(),
    outgoing: List(),
  }
  const state = store.getState()

  if (!safeAddress) {
    return defaultResponse
  }

  const currentUser: string = state[PROVIDER_REDUCER_ID].get('account')
  const safe: SafeRecord = state[SAFE_REDUCER_ID].getIn(['safes', safeAddress])

  if (!safe) {
    return defaultResponse
  }

  const { eTag, results }: { eTag: string | null; results: TxServiceModel[] } = await fetchTransactions(
    TransactionTypes.OUTGOING,
    safeAddress,
    previousETag,
  )
  previousETag = eTag
  const { cancellationTxs, outgoingTxs } = extractCancelAndOutgoingTxs(safeAddress, results)

  // this should be only used for the initial load or when paginating
  const { cancel, outgoing } = await batchProcessOutgoingTransactions({
    cancellationTxs,
    currentUser,
    outgoingTxs,
    safe,
  })

  return {
    cancel: fromJS(cancel),
    outgoing: fromJS(outgoing),
  }
}
Example #2
Source File: index.tsx    From outputs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
mapStateToProps = (state: AppState, props: Props) => {
  let currentKernel = selectors.currentKernel(state);
  return {
    modelById: async (model_id: string) => {
      let model = selectors.modelById(state, { commId: model_id });
      //if we can't find the model, request the state from the kernel
      if (!model && currentKernel) {
        let request_state_response = await request_state(
          currentKernel,
          model_id
        );
        model = fromJS(request_state_response.content.data);
      }
      return model;
    },
    kernel: currentKernel
  };
}
Example #3
Source File: resolvePointer.test.ts    From ui-schema with MIT License 6 votes vote down vote up
describe('JSONPointer', () => {
    test.each(testCases)(
        'resolvePointer() %j',
        (testData) => {
            expect(
                resolvePointer(testData.pointer, fromJS(testData.data))
            ).toBe(testData.value)
        }
    )
})
Example #4
Source File: Networks.ts    From compound-protocol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export function parseNetworkFile(data: string | object): Networks {
  return fromJS(typeof data === 'string' ? JSON.parse(data) : data);
}
Example #5
Source File: index.tsx    From aqualink-app with MIT License 4 votes vote down vote up
Apply = ({ classes }: ApplyProps) => {
  const dispatch = useDispatch();
  const user = useSelector(userInfoSelector);
  const [formModel, setFormModel] = useState(Map<string, string | boolean>());
  const [formErrors, setFormErrors] = useState(Map<string, string>());
  const [registerDialogOpen, setRegisterDialogOpen] = useState(false);
  const [signInDialogOpen, setSignInDialogOpen] = useState(false);
  const [snackbarOpenFromDatabase, setSnackbarOpenFromDatabase] =
    useState(false);
  const [snackbarOpenFromCarto, setSnackbarOpenFromCarto] = useState(false);
  const [databaseSubmissionOk, setDatabaseSubmissionOk] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [newSiteId, setNewSiteId] = useState<number>();

  const handleRegisterDialog = (open: boolean) => setRegisterDialogOpen(open);
  const handleSignInDialog = (open: boolean) => setSignInDialogOpen(open);

  useEffect(() => {
    if (user && user.fullName && user.email) {
      setFormModel(
        formModel
          .set("name", user.fullName)
          .set("org", user.organization || " ")
          .set("email", user.email)
      );
    } else {
      setFormModel(formModel.set("name", "").set("org", "").set("email", ""));
    }
  }, [user, formModel]);

  const contactFormElements: FormElement[] = [
    { id: "name", label: "Name" },
    { id: "org", label: "Organization" },
    {
      id: "email",
      label: "Email",
      validator: validators.isEmail,
    },
  ];

  const locationFormElements: FormElement[] = [
    {
      id: "lat",
      label: "Latitude",
      validator: validators.isLat,
    },
    {
      id: "lng",
      label: "Longitude",
      validator: validators.isLong,
    },
    { id: "siteName", label: "Site Name" },
    {
      id: "depth",
      label: "Depth (m)",
      validator: validators.isInt,
    },
  ];

  const joinedFormElements = locationFormElements.concat(contactFormElements);

  function updateFormElement(id: string, value: string | boolean) {
    setFormModel(formModel.set(id, value));
  }

  function updateMarkerPosition(position: L.LatLngTuple) {
    const [lat, lng] = position;
    setFormModel(
      formModel.set("lat", lat.toString()).set("lng", lng.toString())
    );
  }

  function handleFormSubmission() {
    const errors = joinedFormElements.reduce(
      (acc, { id, label, validator }) => {
        const value = formModel.get(id);
        if (!value) {
          return { ...acc, [id]: `"${label}" is required` };
        }

        const errorMessage = validator && validator(value as string);

        if (errorMessage) {
          return { ...acc, [id]: errorMessage };
        }

        return acc;
      },
      {}
    );

    setFormErrors(fromJS(errors));

    if (isEmpty(errors)) {
      const { siteName, lat, lng, depth } = formModel.toJS() as {
        [key: string]: string;
      };

      // Add to database
      if (user && user.token) {
        setSubmitLoading(true);
        siteServices
          .registerSite(
            siteName,
            parseFloat(lat),
            parseFloat(lng),
            parseInt(depth, 10),
            user.token
          )
          .then(({ data }) => {
            setNewSiteId(data.site.id);
            setDatabaseSubmissionOk(true);
            setSnackbarOpenFromDatabase(true);
            if (user?.token) {
              dispatch(getSelf(user.token));
            }
          })
          .catch((error) => {
            setDatabaseSubmissionOk(false);
            setSnackbarOpenFromDatabase(true);
            console.error(error);
          })
          .finally(() => setSubmitLoading(false));
      }
    }
  }

  const textFieldProps = {
    fullWidth: true,
    variant: "outlined" as "outlined",
    size: "small" as "small",
    InputProps: { classes: pick(classes, ["root", "notchedOutline"]) },
  };

  return (
    <>
      {newSiteId && <Redirect to={`/sites/${newSiteId}`} />}
      <NavBar searchLocation={false} />
      <Box className={classes.boxBar} height="100%" pt={4}>
        <Container>
          <Grid container spacing={6}>
            <Grid item xs={12}>
              <Typography variant="h3" gutterBottom>
                Register your local site
              </Typography>

              <Typography>
                To get your local site registered with Aqualink please complete
                the form below. Your site will become immediately available for
                you to see though some of the satellite and model data will take
                up to 24 hours to show up.
              </Typography>
            </Grid>
          </Grid>
        </Container>

        <Box bgcolor="grey.100" mt={8} p={{ xs: 0, md: 4 }}>
          <Container>
            <Grid container spacing={6}>
              <Grid item xs={12} md={7}>
                <LocationMap
                  markerPositionLat={formModel.get("lat", "") as string}
                  markerPositionLng={formModel.get("lng", "") as string}
                  updateMarkerPosition={updateMarkerPosition}
                />
              </Grid>

              <Grid item xs={12} md={5}>
                <Paper elevation={2}>
                  <Box color="text.secondary" p={4}>
                    <Typography variant="h4" gutterBottom>
                      Site Information
                    </Typography>
                    {!user && (
                      <Typography variant="h6" gutterBottom>
                        Please
                        <Button
                          color="primary"
                          onClick={() => handleRegisterDialog(true)}
                        >
                          Sign up
                        </Button>
                        /
                        <Button
                          color="primary"
                          onClick={() => handleSignInDialog(true)}
                        >
                          Sign in
                        </Button>
                        before registering a new site
                      </Typography>
                    )}

                    <Grid container spacing={2}>
                      <>
                        {contactFormElements.map(({ id, label }) => (
                          <Grid item xs={12} key={label}>
                            <TextField
                              id={id}
                              disabled
                              label={label}
                              error={formErrors.get(id, "").length !== 0}
                              helperText={formErrors.get(id, "")}
                              value={formModel.get(id, "")}
                              onChange={(e) =>
                                updateFormElement(id, e.target.value)
                              }
                              {...textFieldProps}
                            />
                          </Grid>
                        ))}

                        <Grid item xs={12}>
                          <Typography>Location: Select point on map</Typography>
                        </Grid>

                        {locationFormElements.map(({ id, label }) => (
                          <Grid
                            item
                            // eslint-disable-next-line no-nested-ternary
                            xs={
                              // eslint-disable-next-line no-nested-ternary
                              id === "siteName" ? 8 : id === "depth" ? 4 : 6
                            }
                            key={label}
                          >
                            <TextField
                              id={id}
                              label={label}
                              error={formErrors.get(id, "").length !== 0}
                              helperText={formErrors.get(id, "")}
                              value={formModel.get(id, "")}
                              onChange={(e) =>
                                updateFormElement(id, e.target.value)
                              }
                              {...textFieldProps}
                            />
                          </Grid>
                        ))}

                        <Grid item xs={12}>
                          <Tooltip
                            disableHoverListener={Boolean(user)}
                            title="Please Sign up before registering a new site"
                          >
                            <div>
                              <Button
                                disabled={!user || submitLoading}
                                fullWidth
                                variant="contained"
                                color="primary"
                                onClick={handleFormSubmission}
                              >
                                {submitLoading ? "Saving..." : "Submit"}
                              </Button>
                            </div>
                          </Tooltip>
                        </Grid>
                      </>
                    </Grid>
                  </Box>
                </Paper>
              </Grid>
            </Grid>
          </Container>
        </Box>
      </Box>
      <Snackbar
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        open={snackbarOpenFromCarto && snackbarOpenFromDatabase}
        autoHideDuration={4000}
        onClose={() => {
          setSnackbarOpenFromCarto(false);
          setSnackbarOpenFromDatabase(false);
        }}
      >
        <Alert
          onClose={() => {
            setSnackbarOpenFromCarto(false);
            setSnackbarOpenFromDatabase(false);
          }}
          severity={databaseSubmissionOk ? "success" : "error"}
          elevation={6}
          variant="filled"
        >
          {databaseSubmissionOk
            ? "Application successfully submitted."
            : "Something went wrong, please try again"}
        </Alert>
      </Snackbar>
      <Footer />
      <RegisterDialog
        open={registerDialogOpen}
        handleRegisterOpen={handleRegisterDialog}
        handleSignInOpen={handleSignInDialog}
      />
      <SignInDialog
        open={signInDialogOpen}
        handleRegisterOpen={handleRegisterDialog}
        handleSignInOpen={handleSignInDialog}
      />
    </>
  );
}
Example #6
Source File: SlateRenderer.tsx    From ui-schema with MIT License 4 votes vote down vote up
SlateRenderer: React.ComponentType<SlateRendererProps & WidgetProps & WithValue & {
    ElementMapper: ElementMapperType
    onFocus: FocusEventHandler
    onBlur: FocusEventHandler
    className?: string
    onlyInline?: boolean
    withPlugins: withPluginsType
    plugins: EditablePluginsProps['plugins']
    renderLeaf?: RenderLeaf[]
}> = (
    {
        value,
        internalValue,
        onChange,
        storeKeys,
        required,
        schema,
        onFocus,
        onBlur,
        ElementMapper,
        className,
        onlyInline = false,
        plugins,
        renderLeaf,
    }
) => {
    const enableOnly = schema.getIn(['editor', 'enableOnly']) as editorEnableOnly
    const renderElements = React.useMemo(() => {
        return [
            ({children, ...props}: RenderElementProps): JSX.Element =>
                <ElementMapper {...props} enableOnly={enableOnly}>
                    {children}
                </ElementMapper>,
        ]
    }, [enableOnly])

    const valueRef = React.useRef(value)
    const handledInitial = React.useRef(false)
    const valueIsSameOrInitialised = handledInitial.current && valueRef.current?.equals(value)
    React.useEffect(() => {
        if (!valueIsSameOrInitialised) {
            const handledInitialTemp = handledInitial.current
            handledInitial.current = true
            onChange({
                storeKeys,
                scopes: ['internal', 'value'],
                type: 'update',
                updater: ({internal: currentInternal = Map(), value: storeValue}) => {
                    if (storeValue && storeValue.size) {
                        // handling setting internal value for keyword `default`
                        // must check for really non empty, e.g. when used in root level `value` and `internal` will be an empty list
                        valueRef.current = storeValue
                    } else {
                        valueRef.current = !handledInitialTemp && schema.get('default') ? schema.get('default') as List<any> : List()
                    }
                    if (valueRef.current.size) {
                        currentInternal = currentInternal.set('value', valueRef.current.toJS())
                    } else {
                        const initial = [...initialValue]
                        initial[0] = {...initial[0]}
                        if (schema.getIn(['editor', 'initialRoot'])) {
                            initial[0].type = schema.getIn(['editor', 'initialRoot']) as string
                        } else if (onlyInline) {
                            initial[0].type = 'span'
                        }
                        currentInternal = currentInternal.set('value', initial)
                    }

                    return {
                        internal: currentInternal,
                        value: valueRef.current,
                    }
                },
                schema,
                required,
            })
        }
    }, [valueIsSameOrInitialised, handledInitial, valueRef, schema, required, onChange, onlyInline, storeKeys])

    // @ts-ignore
    const editor: ReactEditor = React.useMemo(
        () => pipe(createEditor() as ReactEditor, withReact, withHistory, ...withPlugins({enableOnly, onlyInline})),
        [withPlugins, enableOnly, onlyInline]
    )

    const onChangeHandler = React.useCallback((editorValue) => {
        onChange({
            storeKeys,
            scopes: ['value', 'internal'],
            type: 'update',
            updater: ({internal: currentInternal = Map()}) => {
                let newValue = fromJS(editorValue) as List<any>
                if (isSlateEmpty(newValue)) {
                    newValue = List()
                }
                valueRef.current = newValue
                return {
                    value: newValue,
                    internal: currentInternal.set('value', editorValue),
                }
            },
            schema,
            required,
        })
    }, [valueRef, onChange, storeKeys, schema, required])

    return internalValue.get('value') ? <Slate editor={editor} value={internalValue.get('value') || initialValue} onChange={onChangeHandler}>
        {!schema.getIn(['editor', 'hideToolbar']) ?
            <SlateToolbarHead
                enableOnly={enableOnly}
                onlyInline={onlyInline}
                onFocus={onFocus}
                onBlur={onBlur}
            /> : null}
        {!schema.getIn(['editor', 'hideBalloon']) ?
            <SlateToolbarBalloon
                enableOnly={enableOnly}
            /> : null}
        <Editable
            renderElement={renderElements}
            renderLeaf={renderLeaf}
            plugins={plugins}
            onFocus={onFocus}
            onBlur={onBlur}
            placeholder={schema.getIn(['editor', 'placeholder']) as string | undefined}
            spellCheck={schema.getIn(['editor', 'spellCheck']) as boolean}
            autoFocus={schema.getIn(['editor', 'autoFocus']) as boolean}
            className={className}
        />
    </Slate> : null
}