Skip to content
Closed
79 changes: 79 additions & 0 deletions packages/input-box/src/InputBoxContext/InputBoxContext.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import React from 'react';

import { isReact17, renderHook } from '@leafygreen-ui/testing-lib';
import { Size } from '@leafygreen-ui/tokens';

import {
charsPerSegmentMock,
SegmentObjMock,
segmentRefsMock,
segmentsMock,
} from '../testutils/testutils.mocks';

import { InputBoxProvider, useInputBoxContext } from './InputBoxContext';

describe('InputBoxContext', () => {
const mockOnChange = jest.fn();
const mockOnBlur = jest.fn();

beforeEach(() => {
jest.clearAllMocks();
});

test('throws error when used outside of InputBoxProvider', () => {
/**
* The version of `renderHook` imported from "@testing-library/react-hooks", (used in React 17)
* has an error boundary, and doesn't throw errors as expected:
* https://github.com/testing-library/react-hooks-testing-library/blob/main/src/index.ts#L5
* */
if (isReact17()) {
const { result } = renderHook(() => useInputBoxContext<SegmentObjMock>());
expect(result.error.message).toEqual(
'useInputBoxContext must be used within a InputBoxProvider',
);
} else {
expect(() =>
renderHook(() => useInputBoxContext<SegmentObjMock>()),
).toThrow('useInputBoxContext must be used within a InputBoxProvider');
}
});

test('provides context values that match the props passed to the provider', () => {
const { result } = renderHook(() => useInputBoxContext<SegmentObjMock>(), {
wrapper: ({ children }) => (
<InputBoxProvider
charsPerSegment={charsPerSegmentMock}
segmentEnum={SegmentObjMock}
onChange={mockOnChange}
onBlur={mockOnBlur}
segmentRefs={segmentRefsMock}
segments={segmentsMock}
size={Size.Default}
disabled={false}
>
{children}
</InputBoxProvider>
),
});

const {
charsPerSegment,
segmentEnum,
onChange,
onBlur,
segmentRefs,
segments,
size,
disabled,
} = result.current;

expect(charsPerSegment).toBe(charsPerSegmentMock);
expect(segmentEnum).toBe(SegmentObjMock);
expect(onChange).toBe(mockOnChange);
expect(onBlur).toBe(mockOnBlur);
expect(segmentRefs).toBe(segmentRefsMock);
expect(segments).toBe(segmentsMock);
expect(size).toBe(Size.Default);
expect(disabled).toBe(false);
});
});
78 changes: 78 additions & 0 deletions packages/input-box/src/InputBoxContext/InputBoxContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import React, {
createContext,
PropsWithChildren,
useContext,
useMemo,
} from 'react';

import {
InputBoxContextType,
InputBoxProviderProps,
} from './InputBoxContext.types';

// The Context constant is defined with the default/fixed type, which is string. This is the loose type because we don't know the type of the string yet.
export const InputBoxContext = createContext<InputBoxContextType | null>(null);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was there a final decision on naming this package/components ? Even thinking DateInputBox is a fine name considering it aligns with the Date web api which applies to both date and time

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We briefly discussed the name InputBox, but it was never finalized, so I'm not opposed to changing the name.

As for DateInputBox, at first it made me think of only DatePicker because DateInputBox is a component within DatePicker, but, as you've just mentioned, the API aligns with both date and time, so this name makes sense.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whatever we choose, I would prefer to update the component name after the chain of PRs has been merged. I can open a PR just for the name change.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gotcha, that sounds fine if that's easier than doing it now. Can we make a ticket to capture that work?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


// Provider is generic over T, the string union
export const InputBoxProvider = <Segment extends string>({
charsPerSegment,
children,
disabled,
labelledBy,
onChange,
onBlur,
segments,
segmentEnum,
segmentRefs,
size,
}: PropsWithChildren<InputBoxProviderProps<Segment>>) => {
const value = useMemo(
() => ({
charsPerSegment,
children,
disabled,
labelledBy,
onChange,
onBlur,
segments,
segmentEnum,
segmentRefs,
size,
}),
[
charsPerSegment,
children,
disabled,
labelledBy,
onChange,
onBlur,
segments,
segmentEnum,
segmentRefs,
size,
],
);

// The provider passes a strict type of T but the context is defined as a loose type of string so TS sees a potential type mismatch. This assertion says that we know that the types do not overlap but we guarantee that the strict provider value satisfies the fixed context requirement.
return (
<InputBoxContext.Provider value={value as unknown as InputBoxContextType}>
{children}
</InputBoxContext.Provider>
);
};

// The hook is generic over T, the string union
export const useInputBoxContext = <Segment extends string>() => {
// Assert the context type to the specific generic T
const context = useContext(
InputBoxContext,
) as InputBoxContextType<Segment> | null;

if (!context) {
throw new Error(
'useInputBoxContext must be used within a InputBoxProvider',
);
}

return context;
};
20 changes: 20 additions & 0 deletions packages/input-box/src/InputBoxContext/InputBoxContext.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {
InputSegmentChangeEventHandler,
SharedInputBoxTypes,
} from '../shared/types';

export interface InputBoxContextType<Segment extends string = string>
extends SharedInputBoxTypes<Segment> {
/**
* The handler for the onChange event that will be read in the InputSegment component
*/
onChange: InputSegmentChangeEventHandler<Segment, string>;

/**
* The handler for the onBlur event that will be read by the InputSegment component
*/
onBlur: (event: React.FocusEvent<HTMLInputElement>) => void;
}

export interface InputBoxProviderProps<Segment extends string>
extends InputBoxContextType<Segment> {}
9 changes: 9 additions & 0 deletions packages/input-box/src/InputBoxContext/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export {
InputBoxContext,
InputBoxProvider,
useInputBoxContext,
} from './InputBoxContext';
export type {
InputBoxContextType,
InputBoxProviderProps,
} from './InputBoxContext.types';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// This file is a placeholder for the InputSegment types.
1 change: 1 addition & 0 deletions packages/input-box/src/InputSegment/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// Export the InputSegment component
22 changes: 22 additions & 0 deletions packages/input-box/src/shared/types/InputSegment.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { keyMap } from '@leafygreen-ui/lib';

export interface InputSegmentChangeEvent<
Segment extends string,
Value extends string,
> {
segment: Segment;
value: Value;
meta?: {
key?: (typeof keyMap)[keyof typeof keyMap];
min: number;
[key: string]: any;
};
}

/**
* The type for the onChange handler
*/
export type InputSegmentChangeEventHandler<
Segment extends string,
Value extends string,
> = (inputSegmentChangeEvent: InputSegmentChangeEvent<Segment, Value>) => void;
5 changes: 5 additions & 0 deletions packages/input-box/src/shared/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type {
InputSegmentChangeEvent,
InputSegmentChangeEventHandler,
} from './InputSegment.types';
export type { SharedInputBoxTypes } from './types';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the reason not to consolidate these all in a single shared.types.ts file? I see that InputSegment.types.ts types are used in InputBoxContext.types.ts as well, so it seems like a premature split to make shared/types/ subdir. Why not just packages/input-box/src/shared.types.ts?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was mainly just to make things a little more organized. If it's overkill, I can switch to shared.types.ts

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated!

55 changes: 55 additions & 0 deletions packages/input-box/src/shared/types/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Size } from '@leafygreen-ui/tokens';

export interface SharedInputBoxTypes<Segment extends string> {
/**
* The number of characters per segment
*
* @example
* { day: 2, month: 2, year: 4 }
*/
charsPerSegment: Record<Segment, number>;

/**
* An enumerable object that maps the segment names to their values
*
* @example
* { Day: 'day', Month: 'month', Year: 'year' }
*/
segmentEnum: Record<string, Segment>;

/**
* An object that maps the segment names to their refs
*
* @example
* { day: ref, month: ref, year: ref }
*/
segmentRefs: Record<Segment, React.RefObject<HTMLInputElement>>;

/**
* An object containing the values of the segments
*
* @example
* { day: '1', month: '2', year: '2025' }
*/
segments: Record<Segment, string>;

/**
* The size of the input box
*
* @example
* Size.Default
* Size.Small
* Size.Large
*/
size: Size;

/**
* Whether the input box is disabled
*/
disabled: boolean;

/**
* id of the labelling element
*/
labelledBy?: string;
}
85 changes: 85 additions & 0 deletions packages/input-box/src/testutils/testutils.mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { createRef } from 'react';

import { css } from '@leafygreen-ui/emotion';
import { DynamicRefGetter } from '@leafygreen-ui/hooks';

import { ExplicitSegmentRule } from '../utils';

export const SegmentObjMock = {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wondering if this may also benefit from time mocks in addition to the date mocks

Copy link
Collaborator Author

@shaneeza shaneeza Nov 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I add time mocks, I think it would make more sense to add it in #3285, so I can adjust the current tests.

Month: 'month',
Day: 'day',
Year: 'year',
} as const;
export type SegmentObjMock =
(typeof SegmentObjMock)[keyof typeof SegmentObjMock];

export type SegmentRefsMock = Record<
SegmentObjMock,
ReturnType<DynamicRefGetter<HTMLInputElement>>
>;

export const segmentRefsMock: SegmentRefsMock = {
month: createRef<HTMLInputElement>(),
day: createRef<HTMLInputElement>(),
year: createRef<HTMLInputElement>(),
};

export const segmentsMock: Record<SegmentObjMock, string> = {
month: '02',
day: '02',
year: '2025',
};
export const charsPerSegmentMock: Record<SegmentObjMock, number> = {
month: 2,
day: 2,
year: 4,
};
export const segmentRulesMock: Record<SegmentObjMock, ExplicitSegmentRule> = {
month: { maxChars: 2, minExplicitValue: 2 },
day: { maxChars: 2, minExplicitValue: 4 },
year: { maxChars: 4, minExplicitValue: 1970 },
};
export const defaultMinMock: Record<SegmentObjMock, number> = {
month: 1,
day: 0,
year: 1970,
};
export const defaultMaxMock: Record<SegmentObjMock, number> = {
month: 12,
day: 31,
year: 2038,
};

export const defaultPlaceholderMock: Record<SegmentObjMock, string> = {
day: 'DD',
month: 'MM',
year: 'YYYY',
} as const;

export const defaultFormatPartsMock: Array<Intl.DateTimeFormatPart> = [
{ type: 'month', value: '' },
{ type: 'literal', value: '-' },
{ type: 'day', value: '' },
{ type: 'literal', value: '-' },
{ type: 'year', value: '' },
];

/** The percentage of 1ch these specific characters take up */
export const characterWidth = {
// Standard font
D: 46 / 40,
M: 55 / 40,
Y: 50 / 40,
} as const;

export const segmentWidthStyles: Record<SegmentObjMock, string> = {
day: css`
width: ${charsPerSegmentMock.day * characterWidth.D}ch;
`,
month: css`
width: ${charsPerSegmentMock.month * characterWidth.M}ch;
`,
year: css`
width: ${charsPerSegmentMock.year * characterWidth.Y}ch;
`,
};
Loading
Loading