1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-26 15:52:20 +01:00

80 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-03-24 17:31:50 +01:00
/**
* This component is a template for an input component that wraps the application style
*/
2021-03-30 15:56:36 +02:00
import React, { BaseSyntheticEvent, ReactNode, useCallback, useEffect, useState } from 'react';
2021-03-24 17:31:50 +01:00
import { debounce as _debounce } from 'lodash';
2021-03-30 15:56:36 +02:00
import SettingAPI from '../api/setting';
import { SettingName } from '../models/setting';
import { loadStripe } from '@stripe/stripe-js';
2021-03-24 17:31:50 +01:00
interface FabInputProps {
id: string,
2021-03-30 15:56:36 +02:00
onChange?: (value: any) => void,
2021-03-24 17:31:50 +01:00
value: any,
icon?: ReactNode,
addOn?: ReactNode,
addOnClassName?: string,
className?: string,
disabled?: boolean,
required?: boolean,
debounce?: number,
type?: 'text' | 'date' | 'password' | 'url' | 'time' | 'tel' | 'search' | 'number' | 'month' | 'email' | 'datetime-local' | 'week',
}
export const FabInput: React.FC<FabInputProps> = ({ id, onChange, value, icon, className, disabled, type, required, debounce, addOn, addOnClassName }) => {
const [inputValue, setInputValue] = useState<any>(value);
2021-03-30 15:56:36 +02:00
useEffect(() => {
2021-03-31 16:03:51 +02:00
if (value) {
2021-03-31 17:58:09 +02:00
setInputValue(value);
2021-03-31 16:03:51 +02:00
onChange(value);
}
2021-03-30 15:56:36 +02:00
}, [value]);
2021-03-24 17:31:50 +01:00
/**
* Check if the current component was provided an icon to display
*/
const hasIcon = (): boolean => {
return !!icon;
}
/**
* Check if the current component was provided an add-on element to display, at the end of the input
*/
const hasAddOn = (): boolean => {
return !!addOn;
}
/**
* Debounced (ie. temporised) version of the 'on change' callback.
*/
const handler = useCallback(_debounce(onChange, debounce), []);
/**
* Handle the action of the button
*/
const handleChange = (e: BaseSyntheticEvent): void => {
2021-03-30 15:56:36 +02:00
const newValue = e.target.value;
setInputValue(newValue);
2021-03-24 17:31:50 +01:00
if (typeof onChange === 'function') {
if (debounce) {
2021-03-30 15:56:36 +02:00
handler(newValue);
} else {
2021-03-30 15:56:36 +02:00
onChange(newValue);
}
2021-03-24 17:31:50 +01:00
}
}
return (
<div className={`fab-input ${className ? className : ''}`}>
{hasIcon() && <span className="fab-input--icon">{icon}</span>}
<input id={id} type={type} className="fab-input--input" value={inputValue} onChange={handleChange} disabled={disabled} required={required} />
2021-03-24 17:31:50 +01:00
{hasAddOn() && <span className={`fab-input--addon ${addOnClassName ? addOnClassName : ''}`}>{addOn}</span>}
</div>
);
}
FabInput.defaultProps = { type: 'text', debounce: 0 };