Skip to content

feat(DateInput): add placeholder prop #8168

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

Merged
merged 10 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 5 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 @@ -13,6 +13,10 @@ export const DateInputPlayground = (props: ComponentPlaygroundProps) => {
{
status: ['error', 'valid'],
},
{
value: [new Date('1970-05-05'), undefined],
placeholder: ['Placeholder'],
},
]}
>
{(props: DateInputProps) => <DateInput {...props} />}
Expand Down
39 changes: 37 additions & 2 deletions packages/vkui/src/components/DateInput/DateInput.module.css
Original file line number Diff line number Diff line change
@@ -1,15 +1,50 @@
.wrapper {
display: flex;
min-block-size: inherit;
min-inline-size: inherit;
position: relative;
flex-grow: 1;

--vkui_internal--DateInput_input_margin_inline_start: 10px;
--vkui_internal--DateInput_input_margin_inline_end: 14px;
}

.input {
display: block;
flex-grow: 1;
align-self: center;
margin-inline: 10px 14px;
margin-inline: var(--vkui_internal--DateInput_input_margin_inline_start)
var(--vkui_internal--DateInput_input_margin_inline_end);
z-index: var(--vkui_internal--z_index_form_field_element);
cursor: text;
white-space: nowrap;
user-select: text;
font-variant-numeric: tabular-nums;
}

.hidden {
opacity: 0;
}

.placeholder {
position: absolute;
margin-inline: var(--vkui_internal--DateInput_input_margin_inline_start)
var(--vkui_internal--DateInput_input_margin_inline_end);
inline-size: calc(
100% - var(--vkui_internal--DateInput_input_margin_inline_start) -
var(--vkui_internal--DateInput_input_margin_inline_end)
);
align-self: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
box-sizing: border-box;
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}

.inputTimeDivider {
/* stylelint-disable-next-line declaration-no-important */
letter-spacing: 6px !important;
Expand All @@ -21,6 +56,6 @@

@media (--sizeY-compact) {
.sizeYNone .input {
margin-inline-end: 22px;
--vkui_internal--DateInput_input_margin_inline_end: 22px;
}
}
42 changes: 42 additions & 0 deletions packages/vkui/src/components/DateInput/DateInput.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { useState } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { noop } from '@vkontakte/vkjs';
import { format, subDays } from 'date-fns';
import { baselineComponent, userEvent } from '../../testing/utils';
import { Button } from '../Button/Button';
import { DateInput, type DateInputPropsTestsProps } from './DateInput';

const date = new Date(2024, 6, 31, 11, 20, 0, 0);
Expand Down Expand Up @@ -261,4 +264,43 @@ describe('DateInput', () => {

expect(onChange).not.toHaveBeenCalled();
});

it('check placeholder visibility', async () => {
const PLACEHOLDER_TEXT = 'Плейсхолдер';
const Fixture = () => {
const [showValue, setShowValue] = useState(false);
return (
<>
<DateInput
value={showValue ? new Date() : undefined}
placeholder={PLACEHOLDER_TEXT}
onChange={noop}
{...testIds}
/>
<Button data-testid="add-date" onClick={() => setShowValue((v) => !v)}>
Добавить дату
</Button>
</>
);
};

render(<Fixture />);
expect(screen.queryByPlaceholderText(PLACEHOLDER_TEXT)).toBeTruthy();
expect(screen.queryByText(PLACEHOLDER_TEXT)).toBeTruthy();

// Добавляем значение в input - placeholder появляется
fireEvent.click(screen.getByTestId('add-date'));
expect(screen.queryByText(PLACEHOLDER_TEXT)).toBeFalsy();

// Убираем значение из input - placeholder исчезает
fireEvent.click(screen.getByTestId('add-date'));
expect(screen.queryByText(PLACEHOLDER_TEXT)).toBeTruthy();

// Ставим фокус в input - placeholder повляется
const inputLikes = getInputsLike();
const [dates] = inputLikes;
await userEvent.click(dates);

expect(screen.queryByText(PLACEHOLDER_TEXT)).toBeFalsy();
});
});
147 changes: 81 additions & 66 deletions packages/vkui/src/components/DateInput/DateInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ export interface DateInputProps
* Колбэк срабатывающий при нажатии на кнопку "Done". Используется совместно с флагом `enableTime`.
*/
onApply?: (value?: Date) => void;
/**
* Текст, который будет отображаться в пустом поле ввода
*/
placeholder?: string;
}

const elementsConfig = (index: number) => {
Expand Down Expand Up @@ -196,6 +200,7 @@ export const DateInput = ({
minuteFieldTestId,
id,
onApply,
placeholder,
...props
}: DateInputProps): React.ReactNode => {
const daysRef = React.useRef<HTMLSpanElement>(null);
Expand Down Expand Up @@ -301,6 +306,8 @@ export const DateInput = ({
removeFocusFromField();
}, [onApply, onChange, removeFocusFromField, value]);

const showPlaceholder = !open && !value && !!placeholder;

return (
<FormField
style={style}
Expand All @@ -322,74 +329,82 @@ export const DateInput = ({
onFocus={callMultiple(handleFieldEnter, onFocus)}
{...props}
>
<VisuallyHidden
id={id}
Component="input"
name={name}
value={value ? format(value, enableTime ? "dd.MM.yyyy'T'HH:mm" : 'dd.MM.yyyy') : ''}
/>
<Text
className={styles.input}
onKeyDown={handleKeyDown}
// Инцидент: в PR https://github.com/VKCOM/VKUI/pull/6649 стабильно ломается порядок стилей
// из-за чего `.Typography--normalize` перебивает стили.
normalize={false}
Component="span" // для <span> нормализация не нужна
>
<InputLike
length={2}
getRootRef={daysRef}
index={0}
onElementSelect={setFocusedElement}
value={internalValue[0]}
label={changeDayLabel}
data-testid={dayFieldTestId}
/>
<InputLikeDivider>.</InputLikeDivider>
<InputLike
length={2}
getRootRef={monthsRef}
index={1}
onElementSelect={setFocusedElement}
value={internalValue[1]}
label={changeMonthLabel}
data-testid={monthFieldTestId}
/>
<InputLikeDivider>.</InputLikeDivider>
<InputLike
length={4}
getRootRef={yearsRef}
index={2}
onElementSelect={setFocusedElement}
value={internalValue[2]}
label={changeYearLabel}
data-testid={yearFieldTestId}
<div className={styles.wrapper}>
<VisuallyHidden
id={id}
Component="input"
placeholder={placeholder}
name={name}
value={value ? format(value, enableTime ? "dd.MM.yyyy'T'HH:mm" : 'dd.MM.yyyy') : ''}
/>
{enableTime && (
<React.Fragment>
<InputLikeDivider className={styles.inputTimeDivider}> </InputLikeDivider>
<InputLike
length={2}
getRootRef={hoursRef}
index={3}
onElementSelect={setFocusedElement}
value={internalValue[3]}
label={changeHoursLabel}
data-testid={hourFieldTestId}
/>
<InputLikeDivider>:</InputLikeDivider>
<InputLike
length={2}
getRootRef={minutesRef}
index={4}
onElementSelect={setFocusedElement}
value={internalValue[4]}
label={changeMinutesLabel}
data-testid={minuteFieldTestId}
/>
</React.Fragment>
<Text
className={classNames(styles.input, showPlaceholder && styles.hidden)}
onKeyDown={handleKeyDown}
// Инцидент: в PR https://github.com/VKCOM/VKUI/pull/6649 стабильно ломается порядок стилей
// из-за чего `.Typography--normalize` перебивает стили.
normalize={false}
Component="span" // для <span> нормализация не нужна
>
<InputLike
length={2}
getRootRef={daysRef}
index={0}
onElementSelect={setFocusedElement}
value={internalValue[0]}
label={changeDayLabel}
data-testid={dayFieldTestId}
/>
<InputLikeDivider>.</InputLikeDivider>
<InputLike
length={2}
getRootRef={monthsRef}
index={1}
onElementSelect={setFocusedElement}
value={internalValue[1]}
label={changeMonthLabel}
data-testid={monthFieldTestId}
/>
<InputLikeDivider>.</InputLikeDivider>
<InputLike
length={4}
getRootRef={yearsRef}
index={2}
onElementSelect={setFocusedElement}
value={internalValue[2]}
label={changeYearLabel}
data-testid={yearFieldTestId}
/>
{enableTime && (
<React.Fragment>
<InputLikeDivider className={styles.inputTimeDivider}> </InputLikeDivider>
<InputLike
length={2}
getRootRef={hoursRef}
index={3}
onElementSelect={setFocusedElement}
value={internalValue[3]}
label={changeHoursLabel}
data-testid={hourFieldTestId}
/>
<InputLikeDivider>:</InputLikeDivider>
<InputLike
length={2}
getRootRef={minutesRef}
index={4}
onElementSelect={setFocusedElement}
value={internalValue[4]}
label={changeMinutesLabel}
data-testid={minuteFieldTestId}
/>
</React.Fragment>
)}
</Text>
{showPlaceholder && (
<Text className={styles.placeholder} aria-hidden>
{placeholder}
</Text>
)}
</Text>
</div>
{open && !disableCalendar && (
<Popper
targetRef={rootRef}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading