react-icons/fi#FiUpload JavaScript Examples

The following examples show how to use react-icons/fi#FiUpload. 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: FolderTools.js    From sailplane-web with GNU General Public License v3.0 4 votes vote down vote up
export function FolderTools({
  currentDirectory,
  sharedFs,
  setCurrentDirectory,
  handleOpenUpload,
  isEncrypted,
}) {
  const [addFolderMode, setAddFolderMode] = useState(false);
  const dispatch = useDispatch();
  const pathSplit = currentDirectory.split('/');
  const folderName = pathSplit[pathSplit.length - 1];
  const isSmallScreen = useIsSmallScreen();
  const hasWrite = doesUserHaveWriteInInstance(sharedFs.current);

  const createFolder = async (newFolderName) => {
    try {
      await sharedFs.current.mkdir(currentDirectory, newFolderName);
      setAddFolderMode(false);
    } catch (e) {
      console.log('Mkdir error', e);
      // Todo: handle error
    }
  };

  const InputComponent = useTextInput(
    addFolderMode,
    (newFolderName) => createFolder(newFolderName),
    () => setAddFolderMode(false),
    '',
    {
      placeholder: 'folder name',
    },
  );

  return (
    <div>
      <div style={styles.tools}>
        <div style={styles.leftTools}>
          {isSmallScreen && addFolderMode ? null : (
            <Breadcrumb
              currentDirectory={currentDirectory}
              setCurrentDirectory={setCurrentDirectory}
            />
          )}
        </div>
        <div style={styles.rightTools}>
          {!addFolderMode ? (
            <>
              {currentDirectory !== '/r' ? (
                <ToolItem
                  id={'folderShare'}
                  disabled={isEncrypted}
                  iconComponent={FiShare2}
                  size={18}
                  changeColor={isEncrypted ? '#DDD' : primary4}
                  onClick={() => {
                    dispatch(
                      setShareData({
                        name: folderName,
                        path: currentDirectory,
                        pathType: 'dir',
                      }),
                    );
                  }}
                />
              ) : null}
              <ToolItem
                iconComponent={FiUpload}
                size={18}
                changeColor={primary4}
                onClick={() => {
                  handleOpenUpload();
                }}
              />
              {hasWrite ? (
                <ToolItem
                  id={'addFolder'}
                  iconComponent={FiFolderPlus}
                  size={18}
                  changeColor={primary4}
                  onClick={() => setAddFolderMode(true)}
                />
              ) : null}
            </>
          ) : null}

          {addFolderMode ? <>{InputComponent}</> : null}
        </div>
      </div>
    </div>
  );
}
Example #2
Source File: Instances.js    From sailplane-web with GNU General Public License v3.0 4 votes vote down vote up
export function Instances({sailplane, sharedFS}) {
  const [isImportDialogVisible, setIsImportDialogVisible] = useState(false);
  const [isCreateDialogVisible, setIsCreateDialogVisible] = useState(false);
  const [instanceToModifyAccess, setInstanceToModifyAccess] = useState(null);
  const dispatch = useDispatch();
  const main = useSelector((state) => state.main);
  const {instances, instanceIndex} = main;
  const prevInstanceLength = usePrevious(instances.length);

  useEffect(() => {
    if (prevInstanceLength && prevInstanceLength < instances.length) {
      dispatch(setInstanceIndex(instances.length - 1));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [instances.length, prevInstanceLength]);

  const createInstance = async (isEncrypted) => {
    setIsCreateDialogVisible(false);

    const address = await sailplaneUtil.determineAddress(sailplane, {
      enc: isEncrypted,
    });
    const driveName = sailplaneUtil.driveName(address);

    dispatch(addInstance(driveName, address.toString(), false, isEncrypted));
  };

  return (
    <div style={styles.container}>
      <UserHeader
        sailplane={sailplane}
        title={'Drives'}
        iconComponent={FaServer}
      />

      <div style={styles.toolsContainer}>
        <div style={styles.tools}>
          <>
            <ToolItem
              className={'importInstance'}
              defaultColor={primary45}
              changeColor={primary4}
              iconComponent={FiUpload}
              title={'Import drive'}
              onClick={() => setIsImportDialogVisible(true)}
            />

            <ToolItem
              className={'addInstance'}
              defaultColor={primary45}
              changeColor={primary4}
              iconComponent={FiPlusCircle}
              title={'Create drive'}
              onClick={() => setIsCreateDialogVisible(true)}
            />
          </>
        </div>
      </div>

      <div style={styles.instances}>
        {instances.map((instance, index) => (
          <Instance
            instanceIndex={index}
            key={instance.address.toString()}
            data={instance}
            selected={instance === instances[instanceIndex]}
            onClick={() => {
              dispatch(setInstanceIndex(index));
            }}
            onDelete={() => {
              dispatch(removeInstance(index));
            }}
            onAccess={() => {
              dispatch(setInstanceIndex(index));
              setTimeout(() => setInstanceToModifyAccess(instance), 500);
            }}
          />
        ))}
      </div>

      {instanceToModifyAccess ? (
        <InstanceAccessDialog
          onClose={() => setInstanceToModifyAccess(null)}
          instanceToModifyAccess={instanceToModifyAccess}
          sharedFS={sharedFS}
        />
      ) : null}

      <NewDriveDialog
        isVisible={isCreateDialogVisible}
        onClose={() => setIsCreateDialogVisible(false)}
        onPrivate={() => createInstance(true)}
        onPublic={() => createInstance(false)}
      />

      {isImportDialogVisible ? (
        <ImportDriveDialog
          sharedFS={sharedFS}
          onClose={() => setIsImportDialogVisible(false)}
          isVisible={isImportDialogVisible}
          sailplane={sailplane}
          instances={instances}
        />
      ) : null}

      <StatusBar />
    </div>
  );
}
Example #3
Source File: index.js    From plataforma-sabia with MIT License 4 votes vote down vote up
EditServiceModal = ({
	closeModal,
	id,
	name,
	thumbnail,
	keywords,
	description,
	measure_unit,
	price,
	type,
	revalidateServices,
	revalidateKeywords,
	keywordsOptions,
}) => {
	const [isSubmitting, setIsSubmitting] = useState(false);
	const [uploadError, setUploadError] = useState(null);

	const form = useForm({
		defaultValues: {
			name,
			keywords,
			thumbnail: { id: thumbnail?.id, url: thumbnail?.url },
			description,
			measure_unit,
			price,
			type,
		},
	});
	const formThumbnail = form.watch('thumbnail');

	const onSubmit = async (values) => {
		setIsSubmitting(true);

		const serviceToEdit = {
			...values,
			measure_unit: values.measure_unit.value,
			thumbnail_id: values.thumbnail.id,
			type: values.type.value,
			keywords: values.keywords?.map((item) => item.value) ?? [],
			price: formatCurrencyToInt(values.price),
		};

		const result = await updateService(id, serviceToEdit);

		if (result.success) {
			toast.success('Serviço atualizado com sucesso');
			revalidateServices();
			revalidateKeywords();
			closeModal();
		} else {
			toast.error(result.error);
		}

		setIsSubmitting(false);
	};

	const onDropAttachment = async (acceptedFiles) => {
		if (!acceptedFiles) return null;

		setUploadError(false);

		const formData = new FormData();
		if (acceptedFiles.length !== 0) {
			formData.append(`files[0]`, acceptedFiles[0], acceptedFiles[0].name);
		}

		const response = await upload(formData);

		if (response.status === 200) {
			const { id: uploadId, url } = response.data[0];
			form.setValue('thumbnail.id', uploadId);
			form.setValue('thumbnail.url', url);
		} else {
			setUploadError(response.data?.error?.message[0]?.message);
		}

		return true;
	};

	const handleRemoveAttachment = async () => {
		const response = await deleteUpload(formThumbnail.id);

		if (response?.success) {
			form.setValue('thumbnail.id', '');
			form.setValue('thumbnail.url', '');
		} else {
			toast.error(response.data?.error?.message[0]?.message);
		}
	};

	const { getRootProps, getInputProps } = useDropzone({
		accept: 'image/*',
		onDrop: onDropAttachment,
	});

	const onCreateTerm = async (inputValue) => {
		const term = await createTerm(inputValue, 'KEYWORDS');
		revalidateKeywords();
		return { label: term.term, value: `${term.id}` };
	};

	return (
		<S.Modal onSubmit={form.handleSubmit(onSubmit)} noValidate>
			<Title>Editar serviço</Title>

			<Row>
				<S.Column noPadding mr={1.2} noMarginMobile>
					<InputField
						form={form}
						name="name"
						label="Nome do serviço"
						variant="gray"
						fullWidth
					/>

					<SelectField
						form={form}
						name="keywords"
						placeholder="Busque por palavras chaves (pode adicionar mais de um)"
						label="Palavras-chave"
						isMulti
						creatable
						onCreate={(inputValue) => onCreateTerm(inputValue)}
						options={mapArrayOfObjectToSelect(keywordsOptions, 'term', 'id')}
						variant="gray"
					/>

					<TextField
						form={form}
						name="description"
						label="Descrição do serviço"
						resize="none"
						variant="gray"
					/>
				</S.Column>
				<Column noPadding ml={1.2} noMarginMobile>
					<S.Row mb={1.6}>
						<InputHiddenField form={form} name="thumbnail.id" />
						<InputHiddenField form={form} name="thumbnail.url" />
						<S.ImageContainer>
							<Image
								src={formThumbnail?.url || '/card-image.jpg'}
								alt={name}
								layout="fill"
								objectFit="cover"
							/>
						</S.ImageContainer>
						<S.ImageActions>
							<S.UploadBox {...getRootProps()}>
								<input {...getInputProps()} />
								<RectangularButton colorVariant="green">
									<FiUpload fontSize={14} strokeWidth={4} />
									Alterar imagem
								</RectangularButton>
							</S.UploadBox>

							<RectangularButton
								colorVariant="red"
								onClick={handleRemoveAttachment}
								disabled={!formThumbnail?.id}
							>
								<FiTrash2 fontSize={14} strokeWidth={3} />
								Remover
							</RectangularButton>
						</S.ImageActions>
					</S.Row>
					{!!uploadError && (
						<Row>
							<S.UploadError>{uploadError}</S.UploadError>
						</Row>
					)}

					<S.Row mb={1.6}>
						<SelectField
							form={form}
							name="measure_unit"
							label="Unidade de medida"
							placeholder="Escolha a unidade de medida"
							options={measureUnitOptions}
							variant="rounded"
						/>
						<CurrencyInputField form={form} name="price" label="Preço" variant="gray" />
					</S.Row>
					<SelectField
						form={form}
						name="type"
						label="Tipo"
						placeholder="Escolha um tipo"
						options={typeOptions}
						variant="rounded"
					/>
				</Column>
			</Row>
			<S.Actions>
				<RectangularButton variant="outlined" colorVariant="red" onClick={closeModal}>
					Cancelar
				</RectangularButton>
				<RectangularButton
					type="submit"
					variant="filled"
					colorVariant="green"
					disabled={isSubmitting}
				>
					Editar Serviço
				</RectangularButton>
			</S.Actions>
		</S.Modal>
	);
}