types#FileState TypeScript Examples

The following examples show how to use types#FileState. 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: useMetadataField.tsx    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
useMetadataField = (): UseMetadataField => {
  const navigate = useNavigate();
  const { codeHash: codeHashUrlParam } = useParams<{ codeHash: string }>();

  const [file, setFile] = useState<OrFalsy<FileState>>(null);

  const codeBundleQuery = useCodeBundle(codeHashUrlParam || '');
  const codeBundle = codeBundleQuery.data;
  const metadata = useMetadata(codeBundle?.document?.abi, {
    isWasmRequired: !codeBundle,
    onChange: setFile,
  });

  const isLoading = useMemo(
    () => !!codeHashUrlParam && codeBundleQuery.isLoading,
    [codeHashUrlParam, codeBundleQuery.isLoading]
  );

  const isStored = useMemo((): boolean => !!codeBundle?.document, [codeBundle?.document]);

  useEffect((): void => {
    if (codeHashUrlParam && !codeBundleQuery.isValid) {
      navigate(`/instantiate/${codeHashUrlParam}`);
    }
  }, [codeHashUrlParam, codeBundleQuery.isValid, navigate]);

  return {
    file,
    isLoading,
    isStored,
    ...metadata,
  };
}
Example #2
Source File: useMetadata.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export function useMetadata(
  initialValue?: Record<string, unknown>,
  options: Options & Callbacks = {}
): UseMetadata {
  const { api } = useApi();

  const { isWasmRequired = false, ...callbacks } = options;
  const [state, setState] = useState<MetadataState>(() =>
    deriveFromJson({ isWasmRequired }, initialValue, api)
  );

  function onChange(file: FileState): void {
    try {
      const json = JSON.parse(u8aToString(file.data)) as Record<string, unknown>;
      const name = file.name.replace('.contract', '').replace('.json', '').replace('_', ' ');

      const newState = deriveFromJson({ isWasmRequired, name }, json, api);

      setState(newState);

      callbacks.onChange && callbacks.onChange(file, json);
    } catch (error) {
      console.error(error);

      setState({
        ...EMPTY,
        message: 'This contract file is not in a valid format.',
        isError: true,
        isSupplied: true,
        isValid: false,
      });
    }
  }

  function onRemove(): void {
    setState(EMPTY);

    callbacks.onChange && callbacks.onChange(undefined);
    callbacks.onRemove && callbacks.onRemove();
  }

  useEffect((): void => {
    setState(deriveFromJson({ isWasmRequired }, initialValue, api));
  }, [api, initialValue, isWasmRequired]);

  return {
    ...state,
    onChange,
    onRemove,
  };
}
Example #3
Source File: InputFile.tsx    From contracts-ui with GNU General Public License v3.0 4 votes vote down vote up
export function InputFile({
  className = '',
  errorMessage,
  value: propsFile,
  isError,
  onChange,
  placeholder,
  onRemove,
}: Props) {
  const ref = createRef<DropzoneRef>();
  const [file, setFile] = useState<OrFalsy<FileState>>(propsFile);

  const onDrop = useCallback(
    (files: File[]): void => {
      files.forEach((file): void => {
        const reader = new FileReader();

        reader.onabort = NOOP;
        reader.onerror = NOOP;

        reader.onload = ({ target }: ProgressEvent<FileReader>): void => {
          if (target && target.result) {
            const name = file.name;
            const data = convertResult(target.result as ArrayBuffer);
            const size = data.length;

            onChange && onChange({ data, name, size });
            ref &&
              !propsFile &&
              setFile({
                data,
                name,
                size: data.length,
              });
          }
        };

        reader.readAsArrayBuffer(file);
      });
    },
    [ref, onChange, propsFile]
  );

  const removeHandler = useCallback((): void => {
    onRemove && onRemove();

    !propsFile && setFile(undefined);
  }, [onRemove, propsFile]);

  useEffect((): void => {
    if (file !== propsFile) {
      setFile(propsFile);
    }
  }, [file, propsFile]);

  return file ? (
    <div className={`${className} flex`}>
      <div className="p-6 border dark:bg-elevation-1 dark:border-gray-700 border-gray-300 inline-flex items-center rounded shadow">
        <DocumentTextIcon
          className="w-7 h-7 mr-2 text-gray-500 justify-self-start"
          aria-hidden="true"
        />
        <span className="dark:text-gray-300 text-gray-500 text-xs min-w-600 justify-self-start mr-20">
          {file.name} ({(file.size / 1000).toFixed(2)}kb)
        </span>
        {errorMessage && isError && (
          <span className="dark:text-gray-300 text-gray-500 text-xs min-w-600 justify-self-start mr-20">
            {errorMessage}
          </span>
        )}
        <XIcon
          className="w-5 h-5 mr-2 text-gray-500 justify-self-end cursor-pointer"
          aria-hidden="true"
          onClick={removeHandler}
        />
      </div>
    </div>
  ) : (
    <Dropzone multiple={false} onDrop={onDrop} ref={ref}>
      {({ getInputProps, getRootProps }) => {
        return (
          <div className={className} {...getRootProps()}>
            <label
              className="dark:text-gray-700 text-gray-400 font-normal py-2 px-4 border dark:border-gray-700 border-gray-200 rounded flex flex-col h-36 items-center cursor-pointer justify-center"
              htmlFor="file"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-8 mb-2 dark:text-gray-500"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"
                />
              </svg>
              <span className="text-sm dark:text-gray-500 text-gray-400">{placeholder}</span>
            </label>
            <input {...getInputProps()} data-cy="file-input" />
          </div>
        );
      }}
    </Dropzone>
  );
}