Skip to content
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
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);

// 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;
};
21 changes: 21 additions & 0 deletions packages/input-box/src/InputBoxContext/InputBoxContext.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { DynamicRefGetter } from '@leafygreen-ui/hooks';
import { Size } from '@leafygreen-ui/tokens';

import { InputSegmentChangeEventHandler } from '../InputSegment/InputSegment.types';

type SegmentEnumObject<Segment extends string> = Record<string, Segment>;

export interface InputBoxContextType<Segment extends string = string> {
charsPerSegment: Record<Segment, number>;
disabled: boolean;
segmentEnum: SegmentEnumObject<Segment>;
onChange: InputSegmentChangeEventHandler<Segment, string>;
onBlur: (event: React.FocusEvent<HTMLInputElement>) => void;
segmentRefs: Record<Segment, ReturnType<DynamicRefGetter<HTMLInputElement>>>;
segments: Record<Segment, string>;
labelledBy?: string;
size: Size;
Comment on lines +9 to +17
Copy link
Collaborator

Choose a reason for hiding this comment

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

If any of these will be exposed by InputBox, they can also be shared in the shared.types.ts file

Any tsdocs worth adding?

}

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';
22 changes: 22 additions & 0 deletions packages/input-box/src/InputSegment/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;
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 { type InputSegmentChangeEventHandler } from './InputSegment.types';
Copy link
Collaborator

Choose a reason for hiding this comment

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

This will create a circular import between InputBoxContext and InputSegment. This could be addressed by having a shared.types.ts file for types like this change event handler type

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

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