inogen/app/admin/components/Ui.tsx

113 lines
5.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createContext, isValidElement, useContext, useState, type ButtonHTMLAttributes, type ChangeEvent, type InputHTMLAttributes, type ReactNode, type SelectHTMLAttributes } from "react";
import { PersianDateInput } from "./PersianDateInput";
export function Card({ children, className = "", dataTab }: { children: ReactNode; className?: string; dataTab?: string }) {
return <section className={`card ${className}`} data-tab={dataTab}>{children}</section>;
}
const formErrors = createContext<Record<string, string>>({});
export function FormErrorProvider({ errors, children }: { errors: Record<string, string>; children: ReactNode }) {
return <formErrors.Provider value={errors}>{children}</formErrors.Provider>;
}
export function Field({ label, hint, error, name, children }: { label: string; hint?: string; error?: string; name?: string; children: ReactNode }) {
const errors = useContext(formErrors);
const childName = isValidElement<{name?: string}>(children) ? children.props.name : undefined;
const key = name ?? childName;
const inlineError = error ?? (key
? errors[key] ?? errors[key.charAt(0).toUpperCase() + key.slice(1)] ??
Object.entries(errors).find(([field]) => field.toLowerCase().endsWith(`.${key.toLowerCase()}`))?.[1]
: undefined);
const unit = hint?.startsWith("واحد:") ? hint.slice("واحد:".length).trim() : undefined;
return <label data-field={key} className={`field ${inlineError ? "has-error" : ""}`}><span className="field-label">{label}{unit && <em>{unit}</em>}</span>{children}{hint && !unit && <small>{hint}</small>}{inlineError && <small className="field-error">{inlineError}</small>}</label>;
}
type InputProps = InputHTMLAttributes<HTMLInputElement> & { groupDigits?: boolean };
const latinDigits = (value: string) => value
.replace(/[۰-۹]/g, digit => String("۰۱۲۳۴۵۶۷۸۹".indexOf(digit)))
.replace(/[٠-٩]/g, digit => String("٠١٢٣٤٥٦٧٨٩".indexOf(digit)));
function rawNumber(value: unknown) {
return latinDigits(value == null ? "" : String(value)).replace(/[٬,\s]/g, "");
}
function groupedNumber(value: string) {
if (!value || value === "-") return value;
if (!/^-?\d*(?:\.\d*)?$/.test(value)) return value;
const sign = value.startsWith("-") ? "-" : "";
const unsigned = sign ? value.slice(1) : value;
const [integer, fraction] = unsigned.split(".");
const grouped = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return `${sign}${grouped}${fraction === undefined ? "" : `.${fraction}`}`;
}
function GroupedNumberInput({ name, value, defaultValue, onChange, className, ...props }: InputProps) {
const [uncontrolledValue, setUncontrolledValue] = useState(() => rawNumber(defaultValue));
const controlled = value !== undefined;
const rawValue = controlled ? rawNumber(value) : uncontrolledValue;
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const next = rawNumber(event.target.value);
event.currentTarget.setCustomValidity(next === "" || /^-?\d+(?:\.\d+)?$/.test(next)
? "" : "عدد معتبر وارد کنید؛ از حرف و نشانه‌های دیگر استفاده نکنید.");
if (!controlled) setUncontrolledValue(next);
if (onChange) {
onChange({
...event,
target: { ...event.target, value: next },
currentTarget: { ...event.currentTarget, value: next },
} as ChangeEvent<HTMLInputElement>);
}
};
return <>
<input
{...props}
type="text"
className={className ?? "input"}
inputMode="decimal"
dir="ltr"
value={groupedNumber(rawValue)}
onChange={handleChange}
/>
{name && <input type="hidden" name={name} value={rawValue}/>}
</>;
}
export function Input({ groupDigits = false, ...props }: InputProps) {
if (props.type === "date") {
const { name, value, defaultValue, required, disabled, placeholder, onChange } = props;
return <PersianDateInput
name={name}
value={value === undefined ? undefined : String(value)}
defaultValue={defaultValue === undefined ? undefined : String(defaultValue)}
required={required}
disabled={disabled}
placeholder={placeholder}
onChange={next => onChange?.({ target: { value: next, name: name ?? "" } } as ChangeEvent<HTMLInputElement>)}
/>;
}
if (groupDigits) return <GroupedNumberInput {...props}/>;
const limits: Record<string, number> = {
projectNumber: 100, title: 1000, innovatorFullName: 500, fullName: 1000,
writer: 500, writerOrTranslator: 500, publishingOrganization: 500,
publicationPlace: 500, registrationPlace: 500, place: 500, organizer: 500,
area: 500, specializedField: 500, email: 320,
website: 2048, socialPage: 2048, link: 2048, directLink: 2048,
};
const maxLength = props.maxLength ?? (props.name ? limits[props.name] : undefined);
return <input className="input" {...props} maxLength={maxLength}/>;
}
export function Select(props: SelectHTMLAttributes<HTMLSelectElement>) { return <select className="input" {...props}/>; }
export function Button({ className = "", ...props }: ButtonHTMLAttributes<HTMLButtonElement>) { return <button className={`button ${className}`} {...props}/>; }
export function PageTitle({ title, description, action }: { title: string; description: string; action?: ReactNode }) {
return <div className="page-title"><div><h2>{title}</h2><p>{description}</p></div>{action}</div>;
}
export function EmptyState({ title, description }: { title: string; description: string }) {
return <div className="empty-state"><strong>{title}</strong><p>{description}</p></div>;
}
export function ErrorBanner({ message }: { message: string }) { return <div className="error-banner" role="alert">{message}</div>; }