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

make components optional un/controllable and init with values #1667

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions frontend/src/Components/Checkbox/Checkbox.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ComponentMeta, ComponentStory } from '@storybook/react';
import { Checkbox } from './Checkbox';
import type { CheckboxProps } from './Checkbox';

// Local component config.
export default {
title: 'Components/Checkbox',
component: Checkbox,
Expand All @@ -11,7 +11,7 @@ export default {
},
} as ComponentMeta<typeof Checkbox>;

const Template: ComponentStory<typeof Checkbox> = (args) => <Checkbox {...args} />;
const Template: ComponentStory<typeof Checkbox> = (args: CheckboxProps) => <Checkbox {...args} />;

export const Basic = Template.bind({});
Basic.args = {};
Expand Down
61 changes: 47 additions & 14 deletions frontend/src/Components/Checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,54 @@ import classNames from 'classnames';
import React from 'react';
import styles from './Checkbox.module.scss';

export type CheckboxProps = {
name?: string;
disabled?: boolean;
checked?: boolean;
export type PrimitiveCheckboxProps = Omit<
React.InputHTMLAttributes<HTMLInputElement>,
'checked' | 'defaultChecked' | 'type'
> & {
className?: string;
onChange?: (...event: unknown[]) => void;
readOnly?: boolean;
};

export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(({ className, ...props }, ref) => {
return (
<label className={styles.checkbox}>
<input type="checkbox" ref={ref} className={classNames(styles.checkbox__input, className)} {...props} />
<div className={styles.checkbox__box} />
</label>
);
});
/**
* Controlled props: requires `checked`, forbids `defaultChecked`.
*/
interface ControlledCheckboxProps extends PrimitiveCheckboxProps {
checked: boolean;
defaultChecked?: never;
}

/**
* Uncontrolled props: requires `defaultChecked`, forbids `checked`.
*/
interface UncontrolledCheckboxProps extends PrimitiveCheckboxProps {
checked?: never;
defaultChecked?: boolean;
}

/**
* Union type for either controlled or uncontrolled usage.
*/
export type CheckboxProps = ControlledCheckboxProps | UncontrolledCheckboxProps;

export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
({ className, checked, defaultChecked, onChange, disabled, ...props }, ref) => {
const isControlled = checked !== undefined;

return (
<label className={styles.checkbox}>
<input
ref={ref}
type="checkbox"
className={classNames(styles.checkbox__input, className)}
checked={isControlled ? checked : undefined}
defaultChecked={!isControlled ? defaultChecked : undefined}
onChange={onChange}
disabled={disabled}
{...props}
/>
<div className={styles.checkbox__box} />
</label>
);
},
);

Checkbox.displayName = 'Checkbox';
87 changes: 61 additions & 26 deletions frontend/src/Components/Input/Input.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,67 @@
import classNames from 'classnames';
import * as React from 'react';
import React from 'react';
import styles from './Input.module.scss';

export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
/**
* Common props shared by both controlled & uncontrolled versions.
*/
interface PrimitiveInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'value' | 'defaultValue'> {
className?: string;
type?: React.HTMLInputTypeAttribute;
}

export const Input = React.forwardRef<HTMLInputElement, InputProps>(({ className, type, ...props }, ref) => {
const classMap: Record<string, string> = {
date: styles.date,
'datetime-local': styles.datetimeLocal,
email: styles.email,
month: styles.month,
number: styles.number,
password: styles.password,
search: styles.search,
tel: styles.tel,
text: styles.text,
time: styles.time,
url: styles.url,
week: styles.week,
} as const;
/**
* Controlled props: requires `value`, forbids `defaultValue`.
*/
interface ControlledInputProps extends PrimitiveInputProps {
value: string | number | readonly string[];
defaultValue?: never;
}

return (
<input
ref={ref}
type={type}
className={classNames(styles.input, type ? classMap[type] : '', className)}
{...props}
/>
);
});
/**
* Uncontrolled props: requires `defaultValue`, forbids `value`.
*/
interface UncontrolledInputProps extends PrimitiveInputProps {
value?: never;
defaultValue?: string | number | readonly string[];
}

/**
* Union type for either controlled or uncontrolled usage.
*/
export type InputProps = ControlledInputProps | UncontrolledInputProps;

export const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, value, defaultValue, ...props }, ref) => {
const isControlled = value !== undefined;

// Optional: Map to specialized classNames based on `type`
const classMap: Record<string, string> = {
date: styles.date,
'datetime-local': styles.datetimeLocal,
email: styles.email,
month: styles.month,
number: styles.number,
password: styles.password,
search: styles.search,
tel: styles.tel,
text: styles.text,
time: styles.time,
url: styles.url,
week: styles.week,
};

return (
<input
ref={ref}
type={type}
className={classNames(styles.input, type && classMap[type], className)}
// If controlled, pass `value`, else pass `defaultValue`.
value={isControlled ? value : undefined}
defaultValue={!isControlled ? defaultValue : undefined}
{...props}
/>
);
},
);
Input.displayName = 'Input';
4 changes: 3 additions & 1 deletion frontend/src/Components/NumberInput/NumberInput.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React, { useEffect, useState } from 'react';
import { Input, type InputProps } from '~/Components';

export interface NumberInputProps extends Omit<InputProps, 'onChange'> {
type ControlledInputProps = Extract<InputProps, { value: string | number | readonly string[] }>;

export interface NumberInputProps extends Omit<ControlledInputProps, 'onChange'> {
onChange?: (...event: unknown[]) => void;
allowDecimal?: boolean;
clamp?: boolean;
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/Forms/SamfFormFieldTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,10 @@ function makeAreaInput(args: SamfFormFieldArgs<string>) {
// Checkbox
function makeCheckboxInput(args: SamfFormFieldArgs<boolean>) {
const safeVal = args.value === undefined ? false : (args.value as boolean);
const { defaultChecked, ...checkboxProps } = (args.props as CheckboxProps) || {};
return (
<Checkbox
{...(args.props as CheckboxProps)}
{...checkboxProps}
checked={safeVal}
className={styles.input_element}
onChange={(e) => args.onChange((e as React.ChangeEvent<HTMLInputElement>).target.checked)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ export function RecruitmentFormAdminPage() {
<FormItem className={styles.item}>
<FormLabel>{t(KEY.max_applications)}</FormLabel>
<FormControl>
<NumberInput allowDecimal={false} {...field} />
<NumberInput allowDecimal={false} {...field} value={field.value ?? 0} />
</FormControl>
<FormMessage />
</FormItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,40 @@ interface FormProps {
users?: UserDto[];
}

/* ----------------------------------------------------- *
* HELPER TO MERGE INITIAL DATA WITH DEFAULTS
* ----------------------------------------------------- */
function getDefaultValues(data: Partial<RecruitmentPositionDto>): SchemaType {
return {
name_nb: data.name_nb ?? '',
name_en: data.name_en ?? '',
norwegian_applicants_only: data.norwegian_applicants_only ?? false,
short_description_nb: data.short_description_nb ?? '',
short_description_en: data.short_description_en ?? '',
long_description_nb: data.long_description_nb ?? '',
long_description_en: data.long_description_en ?? '',
is_funksjonaer_position: data.is_funksjonaer_position ?? false,
default_application_letter_nb: data.default_application_letter_nb ?? '',
default_application_letter_en: data.default_application_letter_en ?? '',
tags: data.tags ?? '',
// Convert 'interviewers' array to an array of IDs or fallback to empty array
interviewer_ids: data.interviewers?.map((i) => i.id) ?? [],
};
}

export function RecruitmentPositionForm({ initialData, positionId, recruitmentId, gangId, users }: FormProps) {
const { t } = useTranslation();
const navigate = useNavigate();

const form = useForm<SchemaType>({
resolver: zodResolver(schema),
defaultValues: getDefaultValues(initialData),
});

const submitText = positionId ? t(KEY.common_save) : t(KEY.common_create);
// If 'initialData' changes (e.g. from async fetch), re-sync form values
useEffect(() => {
form.reset(getDefaultValues(initialData));
}, [initialData, form]);

const onSubmit = (data: SchemaType) => {
const updatedPosition = {
Expand Down Expand Up @@ -89,22 +114,15 @@ export function RecruitmentPositionForm({ initialData, positionId, recruitmentId
});
};

useEffect(() => {
form.reset({
...initialData,
interviewer_ids: initialData.interviewers?.map((interviewer) => interviewer.id) || [],
});
}, [initialData, form]);

// Convert users array to dropdown options
const interviewerOptions =
users?.map((user) => ({
value: user.id,
label: user?.username || `${user?.first_name} ${user?.last_name}`,
})) || [];

// Get currently selected interviewers
const selectedInterviewers = form.watch('interviewer_ids') || [];
// Watch for the current array of interviewer IDs
const selectedInterviewers = form.watch('interviewer_ids') ?? [];

return (
<Form {...form}>
Expand Down Expand Up @@ -290,8 +308,8 @@ export function RecruitmentPositionForm({ initialData, positionId, recruitmentId
)}
/>

<Button type="submit" rounded={true} theme="green">
{submitText}
<Button type="submit" rounded theme="green">
{positionId ? t(KEY.common_save) : t(KEY.common_create)}
</Button>
</div>
</form>
Expand Down