Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/upgradefileupload #1633

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions frontend/src/Components/InputFile/InputFile.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
white-space: nowrap;
overflow: hidden;
text-align: right;
pointer-events: all;
@include for-mobile-only {
flex-direction: column;
}
Expand Down
85 changes: 55 additions & 30 deletions frontend/src/Components/InputFile/InputFile.tsx
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Behold kommentarene som var på line 87, 89 og 99

Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,46 @@ import classNames from 'classnames';
import { type ChangeEvent, type ReactNode, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { KEY } from '~/i18n/constants';
import { getFileNameFromUrl, isFileImage } from '~/utils';
import { Link } from '../Link';
import { TimeDisplay } from '../TimeDisplay';
import styles from './InputFile.module.scss';

export type InputFileType = 'image' | 'pdf';
export type InputFileType = 'image' | 'pdf' | 'any';

export type InputFileProps = {
fileType: InputFileType;
fileType?: InputFileType;
label?: ReactNode;
existing_url?: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
existing_url?: string;
localFileUrl?: string;

og for resten seff.

error?: boolean | string;
onSelected: (file: File) => void;
acceptedTypes?: string;
onSelected?: (file: File) => void;
};

export function InputFile({ fileType, label, error = false, onSelected }: InputFileProps) {
export function InputFile({
fileType = 'any',
acceptedTypes,
label,
existing_url,
error = false,
onSelected,
}: InputFileProps) {
const { t } = useTranslation();
const [selectedFile, setSelectedFile] = useState<File | undefined>(undefined);
const [preview, setPreview] = useState<string | undefined>(undefined);
const [isImage, setIsImage] = useState<boolean>(false);

function handleOnChange(e?: ChangeEvent<HTMLInputElement>) {
if (e === undefined) return;
if (e === undefined || onSelected === undefined) return;
if (!e.target.files || e.target.files.length === 0) {
setSelectedFile(undefined);
} else {
setSelectedFile(e.target.files?.[0]);
if (e.target.files?.[0] !== undefined) {
onSelected(e.target.files?.[0]);
setIsImage(isFileImage(e.target.files?.[0].name));
} else {
setIsImage(false);
}
}
}
Expand All @@ -45,23 +60,31 @@ export function InputFile({ fileType, label, error = false, onSelected }: InputF
return () => URL.revokeObjectURL(objectUrl);
}, [selectedFile]);

useEffect(() => {
if (existing_url && isFileImage(existing_url)) {
setIsImage(true);
setPreview(existing_url);
}
}, [existing_url]);

function acceptTypes() {
switch (fileType) {
case 'image':
return 'image/*';
case 'pdf':
return 'application/pdf';
if (fileType === 'any' && !acceptedTypes) {
return '*';
}
return '*';
let types = acceptedTypes ? acceptedTypes : '';
if (fileType === 'image') types += ', image/*';
if (fileType === 'pdf') types += ', application/pdf';
return types;
}

const icons: Record<InputFileType, string> = {
image: 'mdi:image',
pdf: 'mdi:file',
any: 'mdi:file',
};

const horizontalPreview = fileType === 'pdf';
const typePreviewClass = `preview_${fileType.toLowerCase()}`;
const typePreviewClass = `preview_${fileType?.toLowerCase()}`;
const fileSizeMb = ((selectedFile?.size ?? 0) / 1024 / 1024).toFixed(2);
const isError = error !== false;

Expand All @@ -79,28 +102,30 @@ export function InputFile({ fileType, label, error = false, onSelected }: InputF
<Icon icon={icons[fileType] ?? ''} />
{t(KEY.inputfile_choose_a_file)}
</div>
{fileType === 'image' && (
{existing_url && !selectedFile ? (
<Link className={styles.title} url={existing_url} target="external">
{getFileNameFromUrl(existing_url)}
</Link>
) : (
<span className={styles.title}>{selectedFile?.name ?? t(KEY.inputfile_no_file_selected)}</span>
)}
</div>

{/* File Preview */}
<div className={classNames(styles.selected_container, fileType === 'pdf' && styles.pdf)}>
{/* PDF shows additional information */}
{fileType === 'pdf' && (
<div className={styles.preview_meta}>
<p className={styles.title}>{selectedFile?.name ?? t(KEY.inputfile_no_file_selected)}</p>
<p>
<TimeDisplay timestamp={new Date(selectedFile?.lastModified ?? 0)} />
</p>
<p>{fileSizeMb} MB</p>
</div>
)}
{/* Image/pdf preview. Shows empty preview for pdf type */}
{(fileType === 'pdf' || preview) && (
<div className={classNames(styles.preview_container, styles[typePreviewClass])}>
{preview && <img className={styles.preview} src={preview} alt="Preview" />}
</div>
<div className={styles.selected_container}>
{preview && (
<>
<div className={styles.preview_meta}>
<p>
<TimeDisplay timestamp={new Date(selectedFile?.lastModified ?? 0)} />
</p>
<p>{fileSizeMb} MB</p>
</div>
{isImage && (
<div className={classNames(styles.preview_container, styles[typePreviewClass])}>
{preview && <img className={styles.preview} src={preview} alt="Preview" />}
</div>
)}
</>
)}
</div>
</label>
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/Forms/SamfFormFieldTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export type SamfFormFieldType =
| 'date_time'
| 'date'
| 'time'
| 'file'
| 'upload_image'
| 'upload_pdf'
| 'phonenumber';
Expand Down Expand Up @@ -132,6 +133,7 @@ export const SamfFormGenerators: Record<SamfFormFieldType, GeneratorFunction<any
date_time: makeStandardInputFunction<Date>('datetime-local'),
date: makeStandardInputFunction<Date>('date'),
time: makeStandardInputFunction<Date>('time'),
file: makeFilePickerFunction('any'),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vi bruker ikke Samfform lengre btw. Gått over til ReactHook-form

upload_image: makeFilePickerFunction('image'),
upload_pdf: makeFilePickerFunction('pdf'),
phonenumber: makePhoneNumberInput,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,11 @@ export function RecruitmentApplicationFormPage() {
>
<h2 className={styles.label}>{t(KEY.recruitment_application)}:</h2>
<SamfFormField field="application_text" type="text_long" />{' '}
<SamfFormField
field="file"
type="file"
props={{ existing_url: 'http://localhost:3000/src/assets/logos/uka.png' }}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

trengs det en default her?

/>
Comment on lines +212 to +216
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dette bør vel kun rendres hvis stillingen har mulighet for fil opplasting.

Vi bruker ikke Samfform lengre btw. Gått over til ReactHook-form

</SamfForm>
) : (
<div>
Expand Down
9 changes: 9 additions & 0 deletions frontend/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ export function getFullName(u: UserDto): string {
return `${u.first_name} ${u.last_name}`.trim();
}

export function getFileNameFromUrl(url: string): string {
const url_split = url.split('/');
return url_split[url_split.length - 1];
}

export function isFileImage(file_name: string): boolean {
return file_name.match(/\.(jpg|jpeg|png|gif)$/i) != null;
}

/** Helper to determine if a KeyValue is truthy. */
export function isTruthy(value = ''): boolean {
const falsy = ['', 'no', 'zero', '0'];
Expand Down
Loading