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(FileInput): added new input file input #24

Merged
merged 6 commits into from
Apr 11, 2023
Merged
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
9 changes: 9 additions & 0 deletions docs/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ type Spec = ArraySpec | BooleanSpec | NumberSpec | ObjectSpec | StringSpec;
| viewSpec.monacoParams | `object` | | [Parameters](#monacoparams) that must be passed to Monaco editor |
| viewSpec.placeholder | `string` | | A short hint displayed in the field before the user enters the value |
| viewSpec.themeLabel | `'normal'` `'info'` `'danger'` `'warning'` `'success'` `'unknown'` | | Label color |
| viewSpec.fileInput | `object` | | [Parameters](#FileInput) that must be passed to file input |

#### SizeParams

Expand All @@ -127,6 +128,14 @@ type Spec = ArraySpec | BooleanSpec | NumberSpec | ObjectSpec | StringSpec;
| language | `string` | yes | Syntax highlighting language |
| fontSize | `string` | | Font size |

#### FileInput

| Property | Type | Required | Description |
| :----------- | :---------------------------------------------------------------------------- | :------: | :------------------------------------------------------------------------------------- |
| accept | `string` | | Acceptable file extensions, for example: `'.png'`, `'audio/\*'`, `'.jpg, .jpeg, .png'` |
| readAsMethod | `'readAsArrayBuffer'` `'readAsBinaryString'` `'readAsDataURL'` `'readAsText'` | | File reading method |
| ignoreText | `boolean` | | For `true`, will show the `File uploaded` stub instead of the field value |

#### Link

A component that serves as a wrapper for the value, if necessary, rendering the value as a link.
Expand Down
6 changes: 6 additions & 0 deletions src/lib/core/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ export enum SpecTypes {
Object = 'object',
String = 'string',
}

export type ReadAsMethod =
| 'readAsArrayBuffer'
| 'readAsBinaryString'
| 'readAsDataURL'
| 'readAsText';
7 changes: 6 additions & 1 deletion src/lib/core/types/specs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {LabelProps} from '@gravity-ui/uikit';

import {SpecTypes} from '../constants';
import {ReadAsMethod, SpecTypes} from '../constants';

import {ArrayValue, ObjectValue} from './';

Expand Down Expand Up @@ -118,6 +118,11 @@ export interface StringSpec<LinkType = any> {
hideValues?: string[];
placeholder?: string;
themeLabel?: LabelProps['theme'];
fileInput?: {
accept?: string;
readAsMethod?: ReadAsMethod;
ignoreText?: boolean;
};
};
}

Expand Down
24 changes: 24 additions & 0 deletions src/lib/kit/components/Inputs/FileInput/FileInput.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
@import '../../../styles/variables.scss';

.#{$ns}file-input {
display: flex;

&__input {
opacity: 0;
position: absolute;
clip: rect(0 0 0 0);
width: 1px;
height: 1px;
margin: -1px;
}

&__file-name {
display: block;
margin: auto 10px;
max-width: 160px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
color: var(--yc-color-text-secondary);
}
}
89 changes: 89 additions & 0 deletions src/lib/kit/components/Inputs/FileInput/FileInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React from 'react';

import {Xmark} from '@gravity-ui/icons';
import {Button, Icon, Label} from '@gravity-ui/uikit';

import {StringInputProps} from '../../../../core';
import i18n from '../../../../kit/i18n';
import {block} from '../../../utils';

import {readFile} from './utils';

import './FileInput.scss';

const b = block('file-input');

export const FileInput: React.FC<StringInputProps> = ({input, spec}) => {
const {value, onChange} = input;

const inputRef = React.useRef<HTMLInputElement>(null);

const [fileName, setFileName] = React.useState<string>('');

const handleClick = React.useCallback(() => {
inputRef.current?.click();
}, []);

const handleDownload = React.useCallback(
async (file: Blob) => await readFile(file, spec.viewSpec.fileInput?.readAsMethod),
[spec.viewSpec.fileInput?.readAsMethod],
);

const handleReset = React.useCallback(() => {
setFileName('');
onChange('');
}, [onChange]);

const handleInputChange = React.useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files;

if (file && file.length > 0) {
setFileName(file[0].name);
const data = (await handleDownload(file[0])) as string;
onChange(data);
}
},
[handleDownload, onChange],
);

const fileNameContent = React.useMemo(() => {
if (value) {
if (fileName) {
return <React.Fragment>{fileName}</React.Fragment>;
}

return (
<Label size="m" theme="info">
{i18n('label-data_loaded')}
</Label>
);
}

return null;
}, [fileName, value]);

return (
<div className={b()}>
<Button disabled={spec.viewSpec.disabled} onClick={handleClick}>
{i18n('button-upload_file')}
</Button>
<input
type="file"
ref={inputRef}
autoComplete="off"
disabled={spec.viewSpec.disabled}
onChange={handleInputChange}
className={b('input')}
tabIndex={-1}
accept={spec.viewSpec.fileInput?.accept}
/>
<span className={b('file-name')}>{fileNameContent}</span>
{value ? (
<Button view="flat" onClick={handleReset} disabled={spec.viewSpec.disabled}>
<Icon data={Xmark} size={16} />
</Button>
) : null}
</div>
);
};
1 change: 1 addition & 0 deletions src/lib/kit/components/Inputs/FileInput/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './FileInput';
20 changes: 20 additions & 0 deletions src/lib/kit/components/Inputs/FileInput/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {ReadAsMethod} from '../../../../core';

export function readFile(
file: Blob,
readAsMethod: ReadAsMethod = 'readAsBinaryString',
): Promise<string | ArrayBuffer | null> {
return new Promise((resolve, reject) => {
const reader = new FileReader();

if (typeof reader[readAsMethod] !== 'function') {
reject(new Error(`Unknown parameter: ${readAsMethod}`));
return;
}

reader.addEventListener('load', () => resolve(reader.result));
reader.addEventListener('error', () => reject(reader.error));

reader[readAsMethod](file);
});
}
1 change: 1 addition & 0 deletions src/lib/kit/components/Inputs/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './ArrayBase';
export * from './CardOneOf';
export * from './Checkbox';
export * from './FileInput';
export * from './MultiSelect';
export * from './ObjectBase';
export * from './OneOf';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react';

import {StringViewProps} from '../../../../core';
import i18n from '../../../../kit/i18n';
import {LongValue} from '../../../components';

export const FileInputView: React.FC<StringViewProps> = ({value, spec}) => (
<LongValue value={spec.viewSpec.fileInput?.ignoreText ? i18n('label-data_loaded') : value} />
);
1 change: 1 addition & 0 deletions src/lib/kit/components/Views/FileInputView/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './FileInputView';
1 change: 1 addition & 0 deletions src/lib/kit/components/Views/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './ArrayBaseView';
export * from './BaseView';
export * from './CardOneOfView';
export * from './FileInputView';
export * from './MonacoInputView';
export * from './MultiSelectView';
export * from './NumberWithScaleView';
Expand Down
6 changes: 6 additions & 0 deletions src/lib/kit/constants/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
CardOneOfView,
CardSection,
Checkbox,
FileInput,
FileInputView,
Group,
Group2,
MonacoInput,
Expand Down Expand Up @@ -151,6 +153,7 @@ export const dynamicConfig: DynamicFormConfig = {
textarea: {Component: TextArea},
select: {Component: Select},
base: {Component: Text},
file_input: {Component: FileInput},
number_with_scale: {Component: NumberWithScale},
monaco_input: {Component: MonacoInput},
text_content: {Component: TextContent, independent: true},
Expand Down Expand Up @@ -245,6 +248,7 @@ export const dynamicCardConfig: DynamicFormConfig = {
textarea: {Component: TextArea},
select: {Component: Select},
base: {Component: Text},
file_input: {Component: FileInput},
number_with_scale: {Component: NumberWithScale},
monaco_input: {Component: MonacoInputCard},
text_content: {Component: TextContent, independent: true},
Expand Down Expand Up @@ -330,6 +334,7 @@ export const dynamicViewConfig: DynamicViewConfig = {
textarea: {Component: TextAreaView},
select: {Component: BaseView},
base: {Component: BaseView},
file_input: {Component: FileInputView},
number_with_scale: {Component: NumberWithScaleView},
monaco_input: {Component: MonacoView},
text_content: undefined,
Expand Down Expand Up @@ -407,6 +412,7 @@ export const dynamicViewCardConfig: DynamicViewConfig = {
textarea: {Component: TextAreaView},
select: {Component: BaseView},
base: {Component: BaseView},
file_input: {Component: FileInputView},
number_with_scale: {Component: NumberWithScaleView},
monaco_input: {Component: MonacoViewCard},
text_content: undefined,
Expand Down
4 changes: 3 additions & 1 deletion src/lib/kit/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,7 @@
"label_error-zero-start": "Value must not start with a zero",
"label_error-dot-end": "Value must not end with a dot",
"label_delete": "Delete",
"button_cancel": "Close"
"button_cancel": "Close",
"button-upload_file": "Upload file",
"label-data_loaded": "Data uploaded"
}
4 changes: 3 additions & 1 deletion src/lib/kit/i18n/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,7 @@
"label_error-zero-start": "Значение не должно начинаться с нуля",
"label_error-dot-end": "Значение не должно заканчиваться точкой",
"label_delete": "Удалить",
"button_cancel": "Закрыть"
"button_cancel": "Закрыть",
"button-upload_file": "Загрузить файл",
"label-data_loaded": "Данные загружены"
}
1 change: 1 addition & 0 deletions src/stories/StringBase.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const excludeOptions = [
'viewSpec.sizeParams',
'viewSpec.monacoParams',
'viewSpec.themeLabel',
'viewSpec.fileInput',
];

const template = (spec: StringSpec = baseSpec) => {
Expand Down
45 changes: 45 additions & 0 deletions src/stories/StringFileInput.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React from 'react';

import {ComponentStory} from '@storybook/react';

import {FileInput as FileInputBase, SpecTypes, StringSpec} from '../lib';

import {InputPreview} from './components';

export default {
title: 'String/FileInput',
component: FileInputBase,
};

const baseSpec: StringSpec = {
type: SpecTypes.String,
viewSpec: {
type: 'file_input',
layout: 'row',
layoutTitle: 'File Input',
},
};

const excludeOptions = [
'maximum',
'minimum',
'format',
'enum',
'description',
'viewSpec.type',
'viewSpec.sizeParams',
'viewSpec.monacoParams',
'viewSpec.themeLabel',
'viewSpec.placeholder',
'viewSpec.layoutOpen',
];

const template = (spec: StringSpec = baseSpec) => {
const Template: ComponentStory<typeof FileInputBase> = (__, {viewMode}) => (
<InputPreview spec={spec} excludeOptions={excludeOptions} viewMode={viewMode} />
);

return Template;
};

export const FileInput = template();
1 change: 1 addition & 0 deletions src/stories/StringMonaco.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const excludeOptions = [
'viewSpec.sizeParams',
'viewSpec.placeholder',
'viewSpec.themeLabel',
'viewSpec.fileInput',
];

const template = (spec: StringSpec = baseSpec) => {
Expand Down
1 change: 1 addition & 0 deletions src/stories/StringNumberWithScale.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const excludeOptions = [
'viewSpec.type',
'viewSpec.monacoParams',
'viewSpec.themeLabel',
'viewSpec.fileInput',
];

const template = (spec: StringSpec = baseSpec) => {
Expand Down
1 change: 1 addition & 0 deletions src/stories/StringPassword.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const excludeOptions = [
'viewSpec.sizeParams',
'viewSpec.monacoParams',
'viewSpec.themeLabel',
'viewSpec.fileInput',
];

const template = (spec: StringSpec = baseSpec) => {
Expand Down
1 change: 1 addition & 0 deletions src/stories/StringSelect.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const excludeOptions = [
'viewSpec.sizeParams',
'viewSpec.monacoParams',
'viewSpec.themeLabel',
'viewSpec.fileInput',
];

const template = (spec: StringSpec = baseSpec) => {
Expand Down
1 change: 1 addition & 0 deletions src/stories/StringTextArea.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const excludeOptions = [
'viewSpec.sizeParams',
'viewSpec.monacoParams',
'viewSpec.themeLabel',
'viewSpec.fileInput',
];

const template = (spec: StringSpec = baseSpec) => {
Expand Down
1 change: 1 addition & 0 deletions src/stories/StringTextContent.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const excludeOptions = [
'viewSpec.sizeParams',
'viewSpec.monacoParams',
'viewSpec.placeholder',
'viewSpec.fileInput',
];

const template = (spec: StringSpec = baseSpec) => {
Expand Down
Loading