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

fix: Support undefined text resource in text resource selector #14495

Merged
merged 5 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const meta: Meta<typeof StudioTextResourceInput> = {
};
export default meta;

export const Preview: Story = {
export const WithId: Story = {
args: {
currentId: 'land.NO',
textResources: textResourcesMock,
Expand All @@ -45,3 +45,10 @@ export const Preview: Story = {
},
},
};

export const WithoutId: Story = {
args: {
...WithId.args,
currentId: undefined,
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ const defaultProps: StudioTextResourceInputProps = {
currentId,
};
const currentTextResource = getTextResourceById(textResources, currentId);
const noCurrentIdCases: Array<[string, StudioTextResourceInputProps['currentId']]> = [
['an empty string', ''],
['null', null],
['undefined', undefined],
];

describe('StudioTextResourceInput', () => {
afterEach(jest.clearAllMocks);
Expand All @@ -44,6 +49,14 @@ describe('StudioTextResourceInput', () => {
expect(getValueField()).toBeInTheDocument();
});

it.each(noCurrentIdCases)(
'Renders the search field by default when the current ID is %s',
(_, id) => {
renderTextResourceInput({ currentId: id });
expect(getTextResourcePicker()).toBeInTheDocument();
},
);

it('Calls the onChangeTextResource callback with the updated text resource when the value is changed', async () => {
const user = userEvent.setup();
renderTextResourceInput();
Expand Down Expand Up @@ -77,11 +90,24 @@ describe('StudioTextResourceInput', () => {
expect(onChangeCurrentId).toHaveBeenCalledWith(newResource.id);
});

it('Calls the onChangeCurrentId callback with null when a the user selects to not connect a text resource', async () => {
const user = userEvent.setup();
renderTextResourceInput();

await switchToSearchMode(user);
await user.click(getTextResourcePicker());
await user.click(screen.getByRole('option', { name: texts.noTextResourceOptionLabel }));
await waitFor(expect(onChangeCurrentId).toHaveBeenCalled);

expect(onChangeCurrentId).toHaveBeenCalledTimes(1);
expect(onChangeCurrentId).toHaveBeenCalledWith(null);
});

it('Renders the "edit value" input field when the user switches back from search mode', async () => {
const user = userEvent.setup();
renderTextResourceInput();
await switchToSearchMode(user);
await user.click(screen.getByRole('radio', { name: texts.editValue }));
await switchToEditMode(user);
expect(getValueField()).toBeInTheDocument();
});

Expand All @@ -97,6 +123,13 @@ describe('StudioTextResourceInput', () => {
expect(screen.getByText(currentId)).toBeInTheDocument();
});

it.each(noCurrentIdCases)('Disables the value field when the ID is %s', async (_, id) => {
const user = userEvent.setup();
renderTextResourceInput({ currentId: id });
await switchToEditMode(user);
expect(getValueField()).toBeDisabled();
});

it('Forwards the ref if given', () => {
testRefForwarding<HTMLInputElement>((ref) => renderTextResourceInput({}, ref), getValueField);
});
Expand Down Expand Up @@ -128,6 +161,10 @@ function switchToSearchMode(user: UserEvent): Promise<void> {
return user.click(screen.getByRole('radio', { name: texts.search }));
}

function switchToEditMode(user: UserEvent): Promise<void> {
return user.click(screen.getByRole('radio', { name: texts.editValue }));
}

function getTextResourcePicker(): HTMLInputElement {
return screen.getByRole('combobox', { name: texts.textResourcePickerLabel });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,25 @@ import { PencilIcon, MagnifyingGlassIcon } from '@studio/icons';
import classes from './StudioTextResourceInput.module.css';
import type { StudioTextfieldProps } from '../StudioTextfield';
import { StudioTextfield } from '../StudioTextfield';
import { changeTextResourceInList, editTextResourceValue, getTextResourceById } from './utils';
import {
changeTextResourceInList,
determineDefaultMode,
editTextResourceValue,
getTextResourceById,
} from './utils';
import { usePropState } from '@studio/hooks';
import type { TextResourceInputTexts } from './types/TextResourceInputTexts';
import cn from 'classnames';
import { Mode } from './types/Mode';

export type StudioTextResourceInputProps = TextResourceInputPropsBase &
HTMLAttributes<HTMLInputElement>;

type TextResourceInputPropsBase = {
currentId: string;
currentId?: string | null;
currentIdClass?: string;
inputClass?: string;
onChangeCurrentId: (id: string) => void;
onChangeCurrentId: (id: string | null) => void;
onChangeTextResource: (textResource: TextResource) => void;
textResources: TextResource[];
texts: TextResourceInputTexts;
Expand All @@ -44,9 +50,9 @@ export const StudioTextResourceInput = forwardRef<HTMLInputElement, StudioTextRe
},
ref,
): ReactElement => {
const [mode, setMode] = useState<Mode>(Mode.EditValue);
const [currentId, setCurrentId] = usePropState<string>(givenCurrentId);
const [currentId, setCurrentId] = usePropState<string | null | undefined>(givenCurrentId);
const [textResources, setTextResources] = usePropState<TextResource[]>(givenTextResources);
const [mode, setMode] = useState<Mode>(determineDefaultMode(currentId));

const handleChangeCurrentId = (id: string): void => {
setCurrentId(id);
Expand Down Expand Up @@ -84,11 +90,6 @@ export const StudioTextResourceInput = forwardRef<HTMLInputElement, StudioTextRe

StudioTextResourceInput.displayName = 'StudioTextResourceInput';

enum Mode {
EditValue = 'editValue',
Search = 'search',
}

type InputBoxProps = StudioTextResourceInputProps & {
mode: Mode;
};
Expand Down Expand Up @@ -145,11 +146,36 @@ const InputBox = forwardRef<HTMLInputElement, InputBoxProps>(
InputBox.displayName = 'InputBox';

type ValueFieldProps = StudioTextfieldProps & {
textResource: TextResource;
textResource?: TextResource;
onChangeTextResource: (textResource: TextResource) => void;
};

const ValueField = forwardRef<HTMLInputElement, ValueFieldProps>(
({ textResource, onChangeTextResource, ...rest }, ref): ReactElement => {
const generalProps: StudioTextfieldProps = {
hideLabel: true,
size: 'sm',
...rest,
};

if (textResource) {
return (
<EnabledValueField
ref={ref}
onChangeTextResource={onChangeTextResource}
textResource={textResource}
{...generalProps}
/>
);
} else {
return <DisabledValueField ref={ref} {...generalProps} />;
}
},
);

ValueField.displayName = 'ValueField';

const EnabledValueField = forwardRef<HTMLInputElement, ValueFieldProps>(
({ textResource, onChange, onChangeTextResource, ...rest }, ref): ReactElement => {
const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
const { value } = event.target;
Expand All @@ -159,19 +185,18 @@ const ValueField = forwardRef<HTMLInputElement, ValueFieldProps>(
};

return (
<StudioTextfield
hideLabel
onChange={handleChange}
ref={ref}
size='sm'
value={textResource.value}
{...rest}
/>
<StudioTextfield onChange={handleChange} ref={ref} value={textResource.value} {...rest} />
);
},
);

ValueField.displayName = 'ValueField';
EnabledValueField.displayName = 'EnabledValueField';

const DisabledValueField = forwardRef<HTMLInputElement, StudioTextfieldProps>(
(props, ref): ReactElement => <StudioTextfield disabled ref={ref} {...props} />,
);

DisabledValueField.displayName = 'DisabledValueField';

type InputModeToggleProps = {
className?: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { changeTextResourceInList, editTextResourceValue, getTextResourceById } from './utils';
import {
changeTextResourceInList,
editTextResourceValue,
getTextResourceById,
determineDefaultMode,
} from './utils';
import { textResourcesMock } from '../../test-data/textResourcesMock';
import type { TextResource } from '../../types/TextResource';
import { Mode } from './types/Mode';

describe('utils', () => {
describe('getTextResourceById', () => {
Expand Down Expand Up @@ -49,4 +55,20 @@ describe('utils', () => {
expect(result).not.toBe(textResources);
});
});

describe('determineDefaultMode', () => {
it('Returns "editValue" when a valid ID is given', () => {
const result = determineDefaultMode('land.NO');
expect(result).toBe(Mode.EditValue);
});

it.each([
['an empty string', ''],
['null', null],
['undefined', undefined],
])('Returns "search" when the ID is %s', (_, id) => {
const result = determineDefaultMode(id);
expect(result).toBe(Mode.Search);
});
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import type { TextResource } from '../../types/TextResource';
import { ArrayUtils } from '@studio/pure-functions';
import { Mode } from './types/Mode';

export function getTextResourceById(textResources: TextResource[], id: string): TextResource {
export function getTextResourceById(
textResources: TextResource[],
id: string,
): TextResource | undefined {
return textResources.find((textResource) => textResource.id === id);
}

Expand All @@ -22,3 +26,7 @@ export function changeTextResourceInList(
newTextResource,
);
}

export function determineDefaultMode(currentId?: string | null): Mode {
return currentId ? Mode.EditValue : Mode.Search;
}