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

feat(Input, Combobox, Autocomplete): add showCleanCross prop #3594

Open
wants to merge 14 commits into
base: next
Choose a base branch
from

Conversation

SchwJ
Copy link
Member

@SchwJ SchwJ commented Feb 3, 2025

Проблема

Необходимо отрисовывать в инпуте крестик и очищать значение по клику на него.

Решение

Добавила пропы в Input и Combobox, отнаследовала проп в Autocomplete, написала скриншотные тесты и добавила примеры в документацию.

Ссылки

Задача
Гайд для Input с крестикой очистки
Тред в маттермосте с обсуждением дизайна

Чек-лист перед запросом ревью

  1. Добавлены тесты на все изменения
    ✅ unit-тесты для логики
    ✅ скриншоты для верстки и кросс-браузерности
    ⬜ нерелевантно

  2. Добавлена (обновлена) документация
    ✅ styleguidist для пропов и примеров использования компонентов
    ⬜ jsdoc для утилит и хелперов
    ⬜ комментарии для неочевидных мест в коде
    ⬜ прочие инструкции (README.md, contributing.md и др.)
    ⬜ нерелевантно

  3. Изменения корректно типизированы
    ✅ без использования any (см. PR 2856)
    ⬜ нерелевантно

  4. Прочее
    ✅ все тесты и линтеры на CI проходят
    ✅ в коде нет лишних изменений
    ✅ заголовок PR кратко и доступно отражает суть изменений (он попадет в changelog)

@SchwJ SchwJ force-pushed the add-clean-cross-in-input-and-combobox branch from 8432121 to 4cf6e49 Compare February 5, 2025 13:41
Copy link
Member Author

Choose a reason for hiding this comment

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

Пример в доку Autocomplete, так как он наследует свойство инпута showCleanCross

Copy link
Member Author

Choose a reason for hiding this comment

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

Тест, проверяющий что в Autocomplete работает свойство showCleanCross. Достаточно selenium теста, так как визуально всё аналогично инпуту

Copy link
Member Author

Choose a reason for hiding this comment

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

Creevey-тест, проверяющий Combobox:

  • появление крестика при вводе в инпут
  • очистка при клике на крестик
  • фокусировка по табу на крестике

Copy link
Member Author

Choose a reason for hiding this comment

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

Пример в доку ComboBox

Copy link
Member Author

Choose a reason for hiding this comment

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

История для теста Combobox

@@ -446,6 +453,20 @@ export class Input extends React.Component<InputProps, InputState> {

return (
<InputLayout
clearInput={() => {
if (this.props.onValueChange) {
this.props.onValueChange('');
Copy link
Member Author

Choose a reason for hiding this comment

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

для управляемого инпута и для оповещения при неуправляемом

if (this.props.onValueChange) {
this.props.onValueChange('');
}
if (this.input) {
Copy link
Member Author

Choose a reason for hiding this comment

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

для неуправляемого инпута

@SchwJ SchwJ changed the title feat(Input): add clean cross prop feat(Input, Combobox): add showCleanCross prop Feb 7, 2025
@Funkicide Funkicide self-requested a review February 10, 2025 15:25
@Funkicide Funkicide assigned Funkicide and unassigned Funkicide Feb 10, 2025
<Input showCleanCross size="small" value={valueSmall} onValueChange={setValueSmall} data-tid="small" />
<Input showCleanCross size="medium" value={valueMedium} onValueChange={setValueMedium} data-tid="medium" />
<Input showCleanCross size="large" value={valueLarge} onValueChange={setValueLarge} data-tid="large" />
</Gapped>
Copy link
Member

Choose a reason for hiding this comment

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

Кажется, можно оставить скриншоты только для размеров, а функциональность можно проверить через RTL.

Copy link
Member Author

@SchwJ SchwJ Feb 12, 2025

Choose a reason for hiding this comment

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

Функциональность я тоже решила проверить скриншотами, так как:
а) нужно проверить обводку крестика по табу (и в этом же тесте удобно проверить что при последующем нажатии enter происходит очистка поля)
б) мне в целом не очень хочется плодить тесты, связанные с одним и тем же пропом.

Но твое предложение и мой пункт б) натолкнули меня на мысль, что стоит сделать один скриншотный тест, который в целом будет проверять работу пропа с крестиком: размеры, работу на по-разному управляемых контролах и фокус по табу.

Copy link
Member

Choose a reason for hiding this comment

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

Сейчас получается, что скриншот обводки по фокусу есть только для среднего размера, если поедет маленький или большой, то не увидим.

Copy link
Member

@Funkicide Funkicide left a comment

Choose a reason for hiding this comment

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

В целом всё хорошо, на мой взгляд. Единственное, кажется что много избыточных комментариев. Практически везде, где они есть, и так понятно, что происходит, исходя из контекста и названий переменных.

@SchwJ SchwJ requested a review from Funkicide February 13, 2025 05:57
Copy link
Member

@Funkicide Funkicide left a comment

Choose a reason for hiding this comment

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

У меня замечаний, кроме тех двух нет. Можно Мишу звать.

@SchwJ
Copy link
Member Author

SchwJ commented Feb 13, 2025

После Роминого ревью:

  • убрала лишний фокус по совету Ромы
  • согласно апдейту со стороны дизайна: обновила иконку и обновила цвета (цвет иконки по умолчанию -- Secondary Text #757575 и по ховеру -- Text #222222, также по уточнению Андрея). Соответственно, обновились скрины.

Copy link
Member

@mshatikhin mshatikhin left a comment

Choose a reason for hiding this comment

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

еще общее замечание:
в заголовке есть Input и Combobox, но фича добавить еще и в Autocomplete

и странная работа с фокусировкой крестика:

  • он фокусируется мышкой, рисуется обводка -- зачем?
    обычно достаточно показывать рамку при фокусировке с клавиатуры
browser_SKA5YzKGo3.mp4

@@ -24,7 +24,7 @@ export interface CurrencyInputProps
extends Pick<AriaAttributes, 'aria-label'>,
CommonProps,
Override<
InputProps,
Omit<InputProps, 'showCleanCross'>,
Copy link
Member

Choose a reason for hiding this comment

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

хочется понять, почему в CurrencyInput не добавили крестик?

Copy link
Member Author

Choose a reason for hiding this comment

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

Решили с Андреем что он не нужен

@@ -444,8 +451,23 @@ export class Input extends React.Component<InputProps, InputState> {
<FocusControlWrapper onBlurWhenDisabled={this.resetFocus}>{this.getInput(inputProps)}</FocusControlWrapper>
);

const clearInputAndFocusInput = () => {
Copy link
Member

Choose a reason for hiding this comment

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

давай перенесем этот метод в методы класса и сдеаем его private handleClearInput

Copy link
Member Author

Choose a reason for hiding this comment

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

Перенесла

return (
<InputLayout
clearInput={clearInputAndFocusInput}
Copy link
Member

Choose a reason for hiding this comment

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

clearInput -- это callback, давай его назовем onClearInput

Copy link
Member Author

Choose a reason for hiding this comment

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

Переименовала

return (
<InputLayout
clearInput={clearInputAndFocusInput}
showCleanCross={showCleanCross && this.state.needsShowCleanCross}
onCrossBlur={() => {
Copy link
Member

Choose a reason for hiding this comment

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

onCrossBlur лучше назвать по аналогии onCleanCrossBlur

Copy link
Member Author

Choose a reason for hiding this comment

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

Переименовала

@@ -532,6 +558,7 @@ export class Input extends React.Component<InputProps, InputState> {
private handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
this.setState({
focused: true,
needsShowCleanCross: !!this.input?.value,
Copy link
Member

Choose a reason for hiding this comment

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

image

правда ли это нормальная проверка?, если в value будет 0 числом, то крестик не покажется

Copy link
Member Author

Choose a reason for hiding this comment

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

Решила заменить на такое: !!this.input?.value || this.input?.value === '0'

Copy link
Member

Choose a reason for hiding this comment

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

а может ли случиться ситуация что в input.value будет число 0 ?
со строкой то все будет работать нормально

Copy link
Member

Choose a reason for hiding this comment

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

image

Copy link
Member

Choose a reason for hiding this comment

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

image

смог сделать такое в песочнице

Copy link
Member

Choose a reason for hiding this comment

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

image

}
};

const [focusedByTab, setFocusedByTab] = React.useState(false);
Copy link
Member

Choose a reason for hiding this comment

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

давай явно затипизируем useState -- это вообще лучше всегда делать, чтобы более сильно типизировать и ускорять компиляцию ts

Copy link
Member Author

Choose a reason for hiding this comment

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

Добавила

size?: SizeProp;
}

export const CleanCrossIcon: React.FunctionComponent<CleanCrossIconProps> = ({ size = 'small', style, ...rest }) => {
Copy link
Member

Choose a reason for hiding this comment

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

не вижу автотестов на CleanCrossIcon
лучше добавить, на react-testing-library

Copy link
Member Author

Choose a reason for hiding this comment

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

Добавила

rest.disabled && styles.rootDisabled(theme),
getSizeClassName(size),
)}
style={{ ...style }}
Copy link
Member

Choose a reason for hiding this comment

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

зачем тут { ...style } ?

можно просто style={style}

Copy link
Member Author

Choose a reason for hiding this comment

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

Убрала

};
const handleBlur = () => setFocusedByTab(false);

const tabIndex = rest.disabled ? -1 : 0;
Copy link
Member

Choose a reason for hiding this comment

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

tabIndex можно заинлайнить, нет практического смысла в этой переменной

Copy link
Member Author

Choose a reason for hiding this comment

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

Согласна

@@ -0,0 +1,13 @@
import React from 'react';
import { XIcon16Light, XIcon20Light, XIcon24Regular } from '@skbkontur/icons/icons/XIcon';
Copy link
Member

Choose a reason for hiding this comment

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

иконки для контроллов нужно импортировать из папки /internal/icons2022 и там вроде даже уже есть папка XIcon
image

например вот как тут
image

Copy link
Member Author

Choose a reason for hiding this comment

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

Сделала

@SchwJ SchwJ changed the title feat(Input, Combobox): add showCleanCross prop feat(Input, Combobox, Autocomplete): add showCleanCross prop Feb 17, 2025
@mshatikhin
Copy link
Member

image

странность, что два раза setFocusedByTab вызывается

return (
<CommonWrapper {...rest}>
<button
tabIndex={tabIndex}
Copy link
Member

Choose a reason for hiding this comment

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

Для button нам не нужен tabindex, поскольку он интерактивный

Copy link
Member

Choose a reason for hiding this comment

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

Предлагаю указать tabindex="-1", чтобы кнпока фокусилась и не попадалась скринридеру.

Иначе переживаю, что мы очень усложним ввод с клавиатуры лишним табом — с учетом тех привычек, которые есть у пользователей

Screen.Recording.2025-02-18.at.15.09.23.mov

Copy link
Member

Choose a reason for hiding this comment

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

Я сделал небольшую демку с нативным input[type=search] с крестиком, где видно, что крестик не фокусится с клавиатуры.

И переадресовал вопрос ребятам из кружка доступности!

Copy link
Member Author

Choose a reason for hiding this comment

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

Кружок доступности предложил, а мы с Мишей и Егором заапрувили: от таба избавляемся и оставляем tabIndex={-1}

Copy link
Member

Choose a reason for hiding this comment

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

И type="button" :)

@@ -53,6 +53,9 @@ export interface InputProps
Override<
React.InputHTMLAttributes<HTMLInputElement>,
{
/** Устанавливает иконку крестика, при нажатии на который инпут очищается. */
showCleanCross?: boolean;
Copy link
Member

Choose a reason for hiding this comment

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

А давай уберем слово show по аналогии с другими пропами. Например, у Input есть leftIcon и rightIcon без этого слова

@@ -149,10 +152,12 @@ export interface InputState {
blinking: boolean;
focused: boolean;
needsPolyfillPlaceholder: boolean;
needsShowCleanCross: boolean;
Copy link
Member

@sashachabin sashachabin Feb 18, 2025

Choose a reason for hiding this comment

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

Кажется, эта штука отвечает за показ, а не за needs. Я думаю, что правильней назвать это cleanCrossShowed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

4 participants