@polkadot/util#isUndefined TypeScript Examples

The following examples show how to use @polkadot/util#isUndefined. 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: Output.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
format = (value: unknown): string => {
  if (isError(value)) {
    return value.stack ? value.stack : value.toString();
  } else if (isUndefined(value)) {
    return 'undefined';
  } else if (isNull(value)) {
    return 'null';
  } else if (Array.isArray(value)) {
    return `[${value.map((value): string => format(value)).join(', ')}]`;
  } else if (value instanceof Map) {
    return `{${[...value.entries()].map(([key, value]): string => (key as string) + ': ' + format(value)).join(', ')}}`;
  }

  return (value as string).toString();
}
Example #2
Source File: valueToText.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default function valueToText (type: string, value: Codec | undefined | null, swallowError = true, contentShorten = true): React.ReactNode {
  if (isNull(value) || isUndefined(value)) {
    return div({}, '<unknown>');
  }

  return div(
    {},
    ['Bytes', 'Raw', 'Option<Keys>', 'Keys'].includes(type)
      ? u8aToHex(value.toU8a(true), contentShorten ? 512 : -1)
      // HACK Handle Keys as hex-only (this should go away once the node value is
      // consistently swapped to `Bytes`)
      : type === 'Vec<(ValidatorId,Keys)>'
        ? toString(formatKeys(value as unknown as [ValidatorId, Keys][]))
        : value instanceof Raw
          ? value.isEmpty
            ? '<empty>'
            : value.toString()
          : (value instanceof Option) && value.isNone
            ? '<none>'
            : toString(toHuman(value))
  );
}
Example #3
Source File: index.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
private onSearch = (filteredOptions: KeyringSectionOptions, _query: string): KeyringSectionOptions => {
    const { isInput = true } = this.props;
    const query = _query.trim();
    const queryLower = query.toLowerCase();
    const matches = filteredOptions.filter(
      (item): boolean =>
        !!item.value &&
        ((item.name.toLowerCase && item.name.toLowerCase().includes(queryLower)) ||
          item.value.toLowerCase().includes(queryLower))
    );

    if (isInput && matches.length === 0) {
      const accountId = transformToAccountId(query);

      if (accountId) {
        matches.push(keyring.saveRecent(accountId.toString()).option);
      }
    }

    return matches.filter((item, index): boolean => {
      const isLast = index === matches.length - 1;
      const nextItem = matches[index + 1];
      const hasNext = nextItem && nextItem.value;

      return !(isNull(item.value) || isUndefined(item.value)) || (!isLast && !!hasNext);
    });
  };
Example #4
Source File: InputBalance.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function reformat(value?: string | BN, isDisabled?: boolean, siDecimals?: number): [string?, SiDef?] {
  if (!value) {
    return [];
  }

  const decimals = isUndefined(siDecimals) ? formatBalance.getDefaults().decimals : siDecimals;
  const si = isDisabled ? formatBalance.calcSi(value.toString(), decimals) : formatBalance.findSi('-');

  return [
    formatBalance(value, { decimals, forceUnit: si.value, withSi: false }).replace(',', isDisabled ? ',' : ''),
    si,
  ];
}
Example #5
Source File: InputNumber.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function getSiPowers(si: SiDef | null, decimals?: number): [BN, number, number] {
  if (!si) {
    return [BN_ZERO, 0, 0];
  }

  const basePower = isUndefined(decimals) ? formatBalance.getDefaults().decimals : decimals;

  return [new BN(basePower + si.power), basePower, si.power];
}
Example #6
Source File: InputNumber.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function getValuesFromBn(
  valueBn: BN,
  si: SiDef | null,
  isZeroable: boolean,
  _decimals?: number
): [string, BN, boolean] {
  const decimals = isUndefined(_decimals) ? formatBalance.getDefaults().decimals : _decimals;
  const value = si ? valueBn.div(BN_TEN.pow(new BN(decimals + si.power))).toString() : valueBn.toString();

  return [value, valueBn, isZeroable ? true : valueBn.gt(BN_ZERO)];
}
Example #7
Source File: useFormField.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export function useFormField<T> (defaultValue: T | null, validate: ValidateFn<T> = defaultValidate): FormField<T> {
  const [value, setValue] = useState<T | null>(defaultValue);
  const isValid = useMemo(
    () => !!value && validate(value),
    [validate, value]
  );
  const setter = useCallback(
    (value?: T | null) => !isUndefined(value) && setValue(value),
    []
  );

  return [value, isValid, setter];
}
Example #8
Source File: useCall.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
// subscribe, trying to play nice with the browser threads
function subscribe <T> (mountedRef: MountedRef, tracker: TrackerRef, fn: TrackFn | undefined, params: CallParams, setValue: (value: T) => void, { transform = transformIdentity, withParams, withParamsTransform }: CallOptions<T> = {}): void {
  const validParams = params.filter((p) => !isUndefined(p));

  unsubscribe(tracker);

  setTimeout((): void => {
    if (mountedRef.current) {
      if (fn && (!fn.meta || !fn.meta.type?.isDoubleMap || validParams.length === 2)) {
        // swap to acive mode
        tracker.current.isActive = true;

        tracker.current.subscriber = (fn as (...params: unknown[]) => Promise<VoidFn>)(...params, (value: Codec): void => {
          // we use the isActive flag here since .subscriber may not be set on immediate callback)
          if (mountedRef.current && tracker.current.isActive) {
            mountedRef.current && tracker.current.isActive && setValue(
              withParams
                ? [params, transform(value)] as any
                : withParamsTransform
                  ? transform([params, value])
                  : transform(value)
            );
          }
        });
      } else {
        tracker.current.subscriber = null;
      }
    }
  }, 0);
}
Example #9
Source File: useCall.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
// extract the serialized and mapped params, all ready for use in our call
function extractParams <T> (fn: unknown, params: unknown[], { paramMap = transformIdentity }: CallOptions<T> = {}): [string, CallParams | null] {
  return [
    JSON.stringify({ f: (fn as { name: string })?.name, p: params }),
    params.length === 0 || !params.some((param) => isNull(param) || isUndefined(param))
      ? paramMap(params)
      : null
  ];
}
Example #10
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
private onSearch = (filteredOptions: KeyringSectionOptions, _query: string): KeyringSectionOptions => {
    const { isInput = true } = this.props;
    const query = _query.trim();
    const queryLower = query.toLowerCase();
    const matches = filteredOptions.filter((item): boolean =>
      !!item.value && (
        (item.name.toLowerCase && item.name.toLowerCase().includes(queryLower)) ||
        item.value.toLowerCase().includes(queryLower)
      )
    );

    if (isInput && matches.length === 0) {
      const accountId = transformToAccountId(query);

      if (accountId) {
        matches.push(
          keyring.saveRecent(
            accountId.toString()
          ).option
        );
      }
    }

    return matches.filter((item, index): boolean => {
      const isLast = index === matches.length - 1;
      const nextItem = matches[index + 1];
      const hasNext = nextItem && nextItem.value;

      return !(isNull(item.value) || isUndefined(item.value)) || (!isLast && !!hasNext);
    });
  }
Example #11
Source File: useCall.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
// extract the serialized and mapped params, all ready for use in our call
function extractParams<T>(
  fn: unknown,
  params: unknown[],
  { paramMap = transformIdentity }: CallOptions<T> = {}
): [string, CallParams | null] {
  return [
    JSON.stringify({ f: (fn as { name: string })?.name, p: params }),
    params.length === 0 || !params.some((param) => isNull(param) || isUndefined(param)) ? paramMap(params) : null,
  ];
}
Example #12
Source File: useWeightFee.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export function useWeightFee(weight: BN | number, apiOverride?: ApiPromise | null): BN {
  const { api } = useApi();

  return useMemo(
    () =>
      isUndefined(apiOverride) || apiOverride
        ? (((apiOverride || api).consts.transactionPayment?.weightToFee as unknown as any[]) || []).reduce(
            (acc, { coeffFrac, coeffInteger, degree, negative }: WeightToFeeCoefficient): BN => {
              const w = bnToBn(weight).pow(degree);
              const frac = coeffFrac.mul(w).div(BN_BILLION);
              const integer = coeffInteger.mul(w);

              if (negative.isTrue) {
                acc.isub(frac);
                acc.isub(integer);
              } else {
                acc.iadd(frac);
                acc.iadd(integer);
              }

              return acc;
            },
            new BN(0)
          )
        : BN_ZERO,
    [api, apiOverride, weight]
  );
}
Example #13
Source File: valueToText.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-unused-vars
// eslint-disable-next-line complexity
export default function valueToText(
  type: string,
  value: Codec | undefined | null,
  _swallowError = true,
  contentShorten = true
): React.ReactNode {
  if (isNull(value) || isUndefined(value)) {
    return div({}, '<unknown>');
  }

  return div(
    {},
    ['Bytes', 'Raw', 'Option<Keys>', 'Keys'].includes(type) && isFunction(value.toU8a)
      ? // eslint-disable-next-line no-magic-numbers
        u8aToHex(value.toU8a(true), contentShorten ? 512 : -1)
      : // HACK Handle Keys as hex-only (this should go away once the node value is
      // consistently swapped to `Bytes`)
      type === 'Vec<(ValidatorId,Keys)>'
      ? toString(formatKeys(value as unknown as [ValidatorId, Keys][]))
      : value instanceof Raw
      ? value.isEmpty
        ? '<empty>'
        : value.toString()
      : value instanceof Option && value.isNone
      ? '<none>'
      : toString(toHuman(value))
  );
}
Example #14
Source File: Modules.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function areParamsValid ({ creator: { meta: { type } } }: QueryableStorageEntry<'promise'>, values: RawParams): boolean {
  return values.reduce((isValid: boolean, value): boolean => {
    return isValid &&
      !isUndefined(value) &&
      !isUndefined(value.value) &&
      value.isValid;
  }, (
    type.isDoubleMap
      ? values.length === 2
      : values.length === (type.isMap ? 1 : 0)
  ));
}
Example #15
Source File: Results.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function Results ({ queue = [] }: Props): React.ReactElement<Props> | null {
  const filtered = queue
    .filter(({ error, result }) => !isUndefined(error) || !isUndefined(result))
    .reverse();

  if (!filtered.length) {
    return null;
  }

  return (
    <section className='rpc--Results'>
      {filtered.map(({ error, id, result, rpc: { method, section } }): React.ReactNode => (
        <Output
          isError={!!error}
          key={id}
          label={`${id}: ${section}.${method}`}
          value={
            error
              ? error.message
              : <pre>{JSON.stringify((result as Codec).toHuman(), null, 2).replace(/"/g, '').replace(/\\/g, '').replace(/\],\[/g, '],\n[')}</pre>
          }
        />
      ))}
    </section>
  );
}
Example #16
Source File: useCall.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
// subscribe, trying to play nice with the browser threads
function subscribe<T>(
  mountedRef: MountedRef,
  tracker: TrackerRef,
  fn: TrackFn | undefined,
  params: CallParams,
  setValue: (value: T) => void,
  { transform = transformIdentity, withParams, withParamsTransform }: CallOptions<T> = {}
): void {
  const validParams = params.filter((p) => !isUndefined(p));

  unsubscribe(tracker);

  setTimeout((): void => {
    if (mountedRef.current) {
      // FIXME NMap support
      // eslint-disable-next-line no-magic-numbers
      if (fn && (!(fn as QueryTrackFn).meta?.type?.isDoubleMap || validParams.length === 2)) {
        // swap to active mode
        tracker.current.isActive = true;

        // eslint-disable-next-line @typescript-eslint/no-shadow
        tracker.current.subscriber = (fn as (...params: unknown[]) => Promise<VoidFn>)(
          ...params,
          // eslint-disable-next-line
          (value: Codec): void => {
            // we use the isActive flag here since .subscriber may not be set on immediate callback)
            if (mountedRef.current && tracker.current.isActive) {
              // eslint-disable-next-line
              mountedRef.current &&
                tracker.current.isActive &&
                setValue(
                  withParams
                    ? ([params, transform(value)] as any)
                    : withParamsTransform
                    ? transform([params, value])
                    : transform(value)
                );
            }
          }
        );
      } else {
        tracker.current.subscriber = null;
      }
    }
  }, 0);
}
Example #17
Source File: useFormField.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function useFormField<T>(defaultValue: T | null, validate: ValidateFn<T> = defaultValidate): FormField<T> {
  const [value, setValue] = useState<T | null>(defaultValue);
  const isValid = useMemo(() => !!value && validate(value), [validate, value]);
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const setter = useCallback((value?: T | null) => !isUndefined(value) && setValue(value), []);

  return [value, isValid, setter];
}
Example #18
Source File: Amount.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function Amount({
  className = '',
  defaultValue: { value },
  isDisabled,
  isError,
  label,
  onChange,
  onEnter,
  registry,
  type,
  withLabel,
}: Props): React.ReactElement<Props> {
  const defaultValue = useMemo(
    () =>
      isDisabled
        ? value instanceof registry.createClass('AccountIndex')
          ? value.toString()
          : formatNumber(value as number)
        : bnToBn((value as number) || 0).toString(),
    [isDisabled, registry, value]
  );

  const bitLength = useMemo((): number => {
    try {
      return registry.createType(type.type as 'u32').bitLength();
    } catch (error) {
      // eslint-disable-next-line no-magic-numbers
      return 32;
    }
  }, [registry, type]);

  const _onChange = useCallback(
    (val?: BN) =>
      onChange &&
      onChange({
        isValid: !isUndefined(val),
        value: val,
      }),
    [onChange]
  );

  return (
    <Bare className={className}>
      {isDisabled ? (
        <Input
          className="full"
          defaultValue={defaultValue}
          isDisabled
          label={label}
          withEllipsis
          withLabel={withLabel}
        />
      ) : (
        <InputNumber
          bitLength={bitLength}
          className="full"
          defaultValue={defaultValue}
          isError={isError}
          isZeroable
          label={label}
          onChange={_onChange}
          onEnter={onEnter}
          withLabel={withLabel}
        />
      )}
    </Bare>
  );
}
Example #19
Source File: index.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function Param({
  className = '',
  defaultValue,
  isDisabled,
  isInOption,
  isOptional,
  name,
  onChange,
  onEnter,
  onEscape,
  overrides,
  registry,
  type,
}: Props): React.ReactElement<Props> | null {
  const Component = useMemo(() => findComponent(registry, type, overrides), [registry, type, overrides]);

  const label = useMemo(
    () =>
      formatJSON(
        isUndefined(name)
          ? `${isDisabled && isInOption ? 'Option<' : ''}${encodeTypeDef(registry, type)}${
              isDisabled && isInOption ? '>' : ''
            }`
          : `${name}: ${isDisabled && isInOption ? 'Option<' : ''}${encodeTypeDef(registry, type)}${
              isDisabled && isInOption ? '>' : ''
            }`
      ),
    [isDisabled, isInOption, name, registry, type]
  );

  if (!Component) {
    return null;
  }

  return isOptional ? (
    <Static defaultValue={defaultValue} label={label} type={type} />
  ) : (
    <Component
      className={`ui--Param ${className}`}
      defaultValue={defaultValue}
      isDisabled={isDisabled}
      isInOption={isInOption}
      key={`${name || 'unknown'}:${type.toString()}`}
      label={label}
      name={name}
      onChange={onChange}
      onEnter={onEnter}
      onEscape={onEscape}
      overrides={overrides}
      registry={registry}
      type={type}
    />
  );
}
Example #20
Source File: values.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function createValue(registry: Registry, param: { type: TypeDef }): RawParam {
  const value = getInitValue(registry, param.type);

  return {
    isValid: !isUndefined(value),
    value,
  };
}
Example #21
Source File: index.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
// eslint-disable-next-line complexity
  public render(): React.ReactNode {
    const {
      className = '',
      defaultValue,
      help,
      hideAddress = false,
      isDisabled = false,
      isError,
      isMultiple,
      label,
      labelExtra,
      options,
      optionsAll,
      placeholder,
      type = DEFAULT_TYPE,
      withEllipsis,
      withLabel,
    } = this.props;
    const hasOptions = (options && options.length !== 0) || (optionsAll && Object.keys(optionsAll[type]).length !== 0);

    // the options could be delayed, don't render without
    if (!hasOptions && !isDisabled) {
      // This is nasty, but since this things is non-functional, there is not much
      // we can do (well, wrap it, however that approach is deprecated here)
      return (
        <Static className={className} help={help} label={label}>
          No accounts are available for selection.
        </Static>
      );
    }

    const { lastValue, value } = this.state;
    const lastOption = this.getLastOptionValue();
    const actualValue = transformToAddress(
      isDisabled || (defaultValue && this.hasValue(defaultValue))
        ? defaultValue
        : this.hasValue(lastValue)
        ? lastValue
        : lastOption && lastOption.value
    );
    const actualOptions: Option[] = options
      ? options.map((o): Option => createItem(o))
      : isDisabled && actualValue
      ? [createOption(actualValue)]
      : this.getFiltered();
    const _defaultValue = isMultiple || !isUndefined(value) ? undefined : actualValue;

    return (
      <Dropdown
        className={`ui--InputAddress${hideAddress ? ' hideAddress' : ''} ${className}`}
        defaultValue={_defaultValue}
        help={help}
        isDisabled={isDisabled}
        isError={isError}
        isMultiple={isMultiple}
        label={label}
        labelExtra={labelExtra}
        onChange={isMultiple ? this.onChangeMulti : this.onChange}
        onSearch={this.onSearch}
        options={actualOptions}
        placeholder={placeholder}
        renderLabel={isMultiple ? this.renderLabel : undefined}
        value={isMultiple && !value ? MULTI_DEFAULT : value}
        withEllipsis={withEllipsis}
        withLabel={withLabel}
      />
    );
  }
Example #22
Source File: Extrinsic.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function ExtrinsicDisplay({
  defaultValue,
  isDisabled,
  isError,
  isPrivate,
  label,
  onChange,
  onEnter,
  onError,
  onEscape,
  withLabel,
}: Props): React.ReactElement<Props> {
  const [extrinsic, setCall] = useState<CallState>({ fn: defaultValue, params: getParams(defaultValue) });
  const [values, setValues] = useState<RawParam[]>([]);

  useEffect((): void => {
    setValues([]);
  }, [extrinsic]);

  // eslint-disable-next-line complexity
  useEffect((): void => {
    const isValid = values.reduce(
      (isValid, value): boolean => isValid && !isUndefined(value) && !isUndefined(value.value) && value.isValid,
      extrinsic.params.length === values.length
    );

    let method;

    if (isValid) {
      try {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        method = extrinsic.fn(...values.map(({ value }): any => value));
      } catch (error: unknown) {
        if (error instanceof Error) {
          // eslint-disable-next-line
          onError && onError(error);
        }
      }
    } else {
      // eslint-disable-next-line
      onError && onError(null);
    }

    onChange(method);
  }, [extrinsic, onChange, onError, values]);

  const _onChangeMethod = useCallback(
    (fn: SubmittableExtrinsicFunction<'promise'>): void => setCall({ fn, params: getParams(fn) }),
    []
  );

  const {
    fn: { meta, method, section },
    params,
  } = extrinsic;

  return (
    <div className="extrinsics--Extrinsic">
      <InputExtrinsic
        defaultValue={defaultValue}
        help={meta?.docs.join(' ')}
        isDisabled={isDisabled}
        isError={isError}
        isPrivate={isPrivate}
        label={label}
        onChange={_onChangeMethod}
        withLabel={withLabel}
      />
      <Params
        key={`${section}.${method}:params` /* force re-render on change */}
        onChange={setValues}
        onEnter={onEnter}
        onEscape={onEscape}
        overrides={paramComponents}
        params={params}
      />
    </div>
  );
}
Example #23
Source File: CardSummary.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function CardSummary({ children, className = '', help, label, progress }: Props): React.ReactElement<Props> | null {
  const value = progress && progress.value;
  const total = progress && progress.total;
  const left =
    progress && !isUndefined(value) && !isUndefined(total) && value.gten(0) && total.gtn(0)
      ? value.gt(total)
        ? `>${progress.isPercent ? '100' : formatNumber(total)}`
        : progress.isPercent
        ? value.mul(BN_HUNDRED).div(total).toString()
        : formatNumber(value)
      : undefined;

  if (progress && isUndefined(left)) {
    return null;
  }

  const isTimed = progress && progress.withTime && !isUndefined(progress.total);

  return (
    <article className={className}>
      <Labelled help={help} isSmall label={label}>
        {children}
        {progress && !progress.hideValue && (
          <>
            {isTimed && !children && <BlockToTime value={progress.total} />}
            <div className={isTimed ? 'isSecondary' : 'isPrimary'}>
              {!left || isUndefined(progress.total) ? (
                '-'
              ) : !isTimed || progress.isPercent || !progress.value ? (
                `${left}${progress.isPercent ? '' : '/'}${progress.isPercent ? '%' : formatNumber(progress.total)}`
              ) : (
                <BlockToTime className="timer" value={progress.total.sub(progress.value)} />
              )}
            </div>
          </>
        )}
      </Labelled>
      {progress && !progress.hideGraph && <Progress {...progress} />}
    </article>
  );
}
Example #24
Source File: useFormField.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export function useFormField<T>(
  defaultValue: T,
  validate: ValidateFn<T> = value => ({ isValid: !isNull(value), message: null })
): ValidFormField<T> {
  const [value, setValue] = useState<T>(defaultValue);
  const [validation, setValidation] = useState<Omit<Validation, 'isError'>>(validate(value));
  const isTouched = useRef(false);

  const isError = useMemo(() => {
    if (!isTouched.current) {
      return false;
    }

    return !validation.isValid;
  }, [validation.isValid]);

  const onChange = useCallback(
    (value?: T | null) => {
      if (!isUndefined(value) && !isNull(value)) {
        setValue(value);
        setValidation(validate(value));
        isTouched.current = true;
      }
    },
    [validate]
  );

  return useMemo(
    () => ({
      value,
      onChange,
      isValid: validation.isValid,
      isTouched: isTouched.current,
      isWarning: validation.isWarning || false,
      message: validation.message,
      isError,
    }),
    [value, onChange, isError, validation.isValid, validation.isWarning, validation.message]
  );
}
Example #25
Source File: values.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function createValue (registry: Registry, param: { type: TypeDef }): RawParam {
  const value = getInitValue(registry, param.type);

  return {
    isValid: !isUndefined(value),
    value
  };
}
Example #26
Source File: index.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Param ({ className = '', defaultValue, isDisabled, isInOption, isOptional, name, onChange, onEnter, onEscape, overrides, registry, type }: Props): React.ReactElement<Props> | null {
  const Component = useMemo(
    () => findComponent(registry, type, overrides),
    [registry, type, overrides]
  );

  const label = useMemo(
    () => isUndefined(name)
      ? encodeTypeDef(type)
      : `${name}: ${encodeTypeDef(type)}`,
    [name, type]
  );

  if (!Component) {
    return null;
  }

  return isOptional
    ? (
      <Static
        defaultValue={defaultValue}
        label={label}
        type={type}
      />
    )
    : (
      <Component
        className={`ui--Param ${className}`}
        defaultValue={defaultValue}
        isDisabled={isDisabled}
        isInOption={isInOption}
        key={`${name || 'unknown'}:${type.toString()}`}
        label={label}
        name={name}
        onChange={onChange}
        onEnter={onEnter}
        onEscape={onEscape}
        overrides={overrides}
        registry={registry}
        type={type}
      />
    );
}
Example #27
Source File: VectorFixed.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function VectorFixed ({ className = '', defaultValue, isDisabled = false, label, onChange, overrides, registry, type, withLabel }: Props): React.ReactElement<Props> | null {
  const inputParams = useParamDefs(registry, type);
  const [params, setParams] = useState<ParamDef[]>([]);
  const [values, setValues] = useState<RawParam[]>([]);

  // build up the list of parameters we are using
  useEffect((): void => {
    if (inputParams.length) {
      const count = (inputParams[0].length || 1);
      const max = isDisabled ? (defaultValue.value as RawParam[] || []).length : count;
      const params: ParamDef[] = [];

      for (let index = 0; index < max; index++) {
        params.push(generateParam(inputParams, index));
      }

      setParams(params);
    }
  }, [defaultValue, isDisabled, inputParams]);

  // when !isDisable, generating an input list based on count
  useEffect((): void => {
    !isDisabled && inputParams.length &&
      setValues((values): RawParam[] => {
        const count = (inputParams[0].length || 1);

        if (values.length === count) {
          return values;
        }

        while (values.length < count) {
          const value = getInitValue(registry, inputParams[0].type);

          values.push({ isValid: !isUndefined(value), value });
        }

        return values.slice(0, count);
      });
  }, [inputParams, isDisabled, registry]);

  // when isDisabled, set the values based on the defaultValue input
  useEffect((): void => {
    isDisabled &&
      setValues(
        (defaultValue.value as RawParam[] || []).map((value: RawParam) =>
          isUndefined(value) || isUndefined(value.isValid)
            ? { isValid: !isUndefined(value), value }
            : value
        )
      );
  }, [defaultValue, isDisabled]);

  // when our values has changed, alert upstream
  useEffect((): void => {
    onChange && onChange({
      isValid: values.reduce((result: boolean, { isValid }) => result && isValid, true),
      value: values.map(({ value }) => value)
    });
  }, [values, onChange]);

  return (
    <Base
      className={className}
      isOuter
      label={label}
      withLabel={withLabel}
    >
      <Params
        isDisabled={isDisabled}
        onChange={setValues}
        overrides={overrides}
        params={params}
        registry={registry}
        values={values}
      />
    </Base>
  );
}
Example #28
Source File: CardSummary.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function CardSummary ({ children, className = '', help, label, progress }: Props): React.ReactElement<Props> | null {
  const value = progress && progress.value;
  const total = progress && progress.total;
  const left = progress && !isUndefined(value) && !isUndefined(total) && value.gten(0) && total.gtn(0)
    ? (
      value.gt(total)
        ? `>${
          progress.isPercent
            ? '100'
            : formatNumber(total)
        }`
        : (
          progress.isPercent
            ? value.mul(BN_HUNDRED).div(total).toString()
            : formatNumber(value)
        )
    )
    : undefined;

  if (progress && isUndefined(left)) {
    return null;
  }

  const isTimed = progress && progress.withTime && !isUndefined(progress.total);

  return (
    <article className={className}>
      <Labelled
        help={help}
        isSmall
        label={label}
      >
        {children}{
          progress && !progress.hideValue && (
            <>
              {isTimed && !children && (
                <BlockToTime value={progress.total} />
              )}
              <div className={isTimed ? 'isSecondary' : 'isPrimary'}>
                {!left || isUndefined(progress.total)
                  ? '-'
                  : !isTimed || progress.isPercent || !progress.value
                    ? `${left}${progress.isPercent ? '' : '/'}${
                      progress.isPercent
                        ? '%'
                        : formatNumber(progress.total)
                    }`
                    : (
                      <BlockToTime
                        className='timer'
                        value={progress.total.sub(progress.value)}
                      />
                    )
                }
              </div>
            </>
          )
        }
      </Labelled>
      {progress && !progress.hideGraph && <Progress {...progress} />}
    </article>
  );
}
Example #29
Source File: Amount.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Amount ({ className = '', defaultValue: { value }, isDisabled, isError, label, onChange, onEnter, registry, type, withLabel }: Props): React.ReactElement<Props> {
  const defaultValue = useMemo(
    () => isDisabled
      ? value instanceof ClassOf(registry, 'AccountIndex')
        ? value.toString()
        : formatNumber(value as number)
      : bnToBn((value as number) || 0).toString(),
    [isDisabled, registry, value]
  );

  const bitLength = useMemo(
    (): number => {
      try {
        return registry.createType(type.type as 'u32').bitLength();
      } catch (error) {
        return 32;
      }
    },
    [registry, type]
  );

  const _onChange = useCallback(
    (value?: BN) => onChange && onChange({
      isValid: !isUndefined(value),
      value
    }),
    [onChange]
  );

  return (
    <Bare className={className}>
      {isDisabled
        ? (
          <Input
            className='full'
            defaultValue={defaultValue}
            isDisabled
            label={label}
            withEllipsis
            withLabel={withLabel}
          />
        )
        : (
          <InputNumber
            bitLength={bitLength}
            className='full'
            defaultValue={defaultValue}
            isError={isError}
            isZeroable
            label={label}
            onChange={_onChange}
            onEnter={onEnter}
            withLabel={withLabel}
          />
        )
      }
    </Bare>
  );
}