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

refactor: use css outline & new useFocusVisibleClassName() hook to draw visible focus #5876

Merged
merged 22 commits into from
Nov 23, 2023

Conversation

eugpoloz
Copy link
Contributor

@eugpoloz eugpoloz commented Sep 27, 2023

Чеклист

  • e2e-тесты
  • unit-тесты — для нового хука useFocusVisibleClassName()
  • дизайн-ревью — не нужно, поменялся только внутряк

Описание

В рефакторинге FocusVisible мы стали рисовать границу через border, что и приводило к "раздуванию" элемента и появлению скроллов там, где их было быть не должно. В старом подходе с box-shadow такого не было, т.к. box-shadow никак не изменяет границы элемента.

А границу стали рисовать из-за того, что добавили FocusVisible в FormField.

Однако! В процессе я внезапно обнаружила, что поддержку border-radius для outline починили! См.

Поэтому — идем путем graceful degradation. В браузерах, где баг не пофикшен, аутлайн будет без скруглений и не такой красивый, но, кажется, этим стоит пожертвовать.

Изменения

  • переделала обводку с границы на outline,
  • и полностью изменила логику FocusVisible — это теперь компонент-обертка, который передает своему ближайшему дитю на корень нужные классы,
  • с подачи Инома избавилась от компонента FocusVisible в пользу нового хука useFocusVisibleClassName(). Засунуть в useFocusVisible() логику не получилось, т.к. есть места, где для определения фокусного состояния мы используем хук useFocusWithin(),
  • подправила типы и комментарии к коду,
  • подправила ресет аутлайна, чтобы он работал как нужно в Windows High Contrast Mode (см. статью Maintaining Focus Outlines for Windows High Contrast Mode Бена Майерса)
  • добавила новые e2e-тесты на State: Active для:
    • Link
    • Image
    • Switch
    • Tappable
    • Textarea
  • обновила скриншоты:
    • Slider
    • CustomSelect
    • Textarea

@eugpoloz eugpoloz added the v5 Автоматизация: PR продублируется в ветку v5 label Sep 27, 2023
@eugpoloz eugpoloz changed the title fix(FocusVisible): fix(FocusVisible): turn back to box-shadow for drawing visible focus Sep 27, 2023
@eugpoloz eugpoloz changed the title fix(FocusVisible): turn back to box-shadow for drawing visible focus fix(FocusVisible): use box-shadow to draw visible focus Sep 27, 2023
@github-actions
Copy link
Contributor

github-actions bot commented Sep 27, 2023

size-limit report 📦

Path Size
JS 342.43 KB (-0.07% 🔽)
JS (gzip) 104.61 KB (-0.04% 🔽)
JS (brotli) 86.45 KB (+0.07% 🔺)
JS import Div (tree shaking) 2.71 KB (0%)
CSS 256.47 KB (-0.08% 🔽)
CSS (gzip) 33.63 KB (-0.29% 🔽)
CSS (brotli) 27.3 KB (-0.32% 🔽)

@codesandbox-ci
Copy link

codesandbox-ci bot commented Sep 27, 2023

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit b69bef6:

Sandbox Source
VKUI TypeScript Configuration
pensive-ace-n7jwvt Issue #5871

@github-actions
Copy link
Contributor

github-actions bot commented Sep 27, 2023

e2e tests

Playwright Report

@github-actions
Copy link
Contributor

github-actions bot commented Sep 27, 2023

👀 Docs deployed

Commit b69bef6

@codecov
Copy link

codecov bot commented Sep 27, 2023

Codecov Report

All modified and coverable lines are covered by tests ✅

Comparison is base (8d0e56b) 79.10% compared to head (b69bef6) 79.13%.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5876      +/-   ##
==========================================
+ Coverage   79.10%   79.13%   +0.02%     
==========================================
  Files         312      312              
  Lines        9947     9957      +10     
  Branches     3333     3332       -1     
==========================================
+ Hits         7869     7879      +10     
  Misses       2078     2078              
Flag Coverage Δ
unittests 79.13% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@eugpoloz eugpoloz force-pushed the eugpoloz/5981-FocusVisible-bug branch 3 times, most recently from 095a0f4 to a0ca4b5 Compare September 30, 2023 03:36
@eugpoloz eugpoloz changed the title fix(FocusVisible): use box-shadow to draw visible focus fix(FocusVisible): use outline to draw visible focus Oct 4, 2023
@eugpoloz eugpoloz force-pushed the eugpoloz/5981-FocusVisible-bug branch 3 times, most recently from 77bae4a to 3bc2ea7 Compare October 12, 2023 00:26
@github-actions github-actions bot added the patch Автоматизация: PR продублируется в ветку последнего минорного релиза для выпуска патча label Oct 12, 2023
@eugpoloz eugpoloz force-pushed the eugpoloz/5981-FocusVisible-bug branch from 3bc2ea7 to e4db235 Compare October 12, 2023 00:33
@eugpoloz eugpoloz marked this pull request as ready for review October 12, 2023 00:34
@eugpoloz eugpoloz requested a review from a team as a code owner October 12, 2023 00:34
@eugpoloz eugpoloz marked this pull request as draft October 17, 2023 17:42
@eugpoloz eugpoloz force-pushed the eugpoloz/5981-FocusVisible-bug branch from e4db235 to 0158f3e Compare October 17, 2023 18:12
@eugpoloz eugpoloz marked this pull request as ready for review October 19, 2023 04:19
Copy link
Contributor

@mendrew mendrew left a comment

Choose a reason for hiding this comment

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

Отличная работа! 🔥 💯 💠

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

packages/vkui/src/styles/constants.css Outdated Show resolved Hide resolved
Copy link
Contributor

@inomdzhon inomdzhon left a comment

Choose a reason for hiding this comment

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

Получилось вообще шикарно! ✨💖✨ Ещё и обводка ссылки починилась 🙂 Из-за того, что переделывали на отдельный элемент, там бага была.

Из улучшений, т.к. у нас есть хук useFocusVisible(), то я бы его и применил для определения className, который задаёт фокус. И тем самым избежал бы React.cloneElement. По возможности стоит избегать этого метода в компонентах, которые часто встречаются в интерфейсе. Его полезно использовать, например, для тултипов, т.к. реже приходится использовать (хотя даже для тултипов предпочёл бы хук с пробрской рефа).

Добавил коммент на примере компонента Clickable.

packages/vkui/src/components/Clickable/Clickable.tsx Outdated Show resolved Hide resolved
Copy link
Contributor

@inomdzhon inomdzhon left a comment

Choose a reason for hiding this comment

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

Получилось вообще шикарно! ✨💖✨ Ещё и обводка ссылки починилась 🙂 Из-за того, что переделывали на отдельный элемент, там бага была.

Из улучшений, т.к. у нас есть хук useFocusVisible(), то я бы его и применил для определения className, который задаёт фокус. И тем самым избежал бы React.cloneElement. По возможности стоит избегать этого метода в компонентах, которые часто встречаются в интерфейсе. Его полезно использовать, например, для тултипов, т.к. зачастую реже применяется в интерфейсе (хотя даже для тултипов предпочёл бы хук с пробрской рефа).

Добавил коммент на примере компонента Clickable как это может выглядеть если чисто на хуках делать.

@github-actions github-actions bot added the pr-needs-work Автоматизация: PR автоматически закроется через 14 дней при отсутствии активности label Oct 27, 2023
Copy link
Contributor

github-actions bot commented Nov 3, 2023

PR закрыт из-за отсутствия активности в течение последних 14 дней. Если это произошло по ошибке или изменения все ещё актуальны, откройте PR повторно.

@eugpoloz eugpoloz force-pushed the eugpoloz/5981-FocusVisible-bug branch from 07693e1 to 4c28615 Compare November 21, 2023 15:08
- ImageOverlay: adjust overlay visibility on focus
- ImageBase: add negative z-index to <img/>
- Avatar: move initials to get layers under ImageBase isolation
windows high contrast mode compatible
@eugpoloz eugpoloz force-pushed the eugpoloz/5981-FocusVisible-bug branch from 4c28615 to d1690ec Compare November 21, 2023 15:52
@eugpoloz eugpoloz removed the patch Автоматизация: PR продублируется в ветку последнего минорного релиза для выпуска патча label Nov 22, 2023
@eugpoloz eugpoloz requested a review from inomdzhon November 22, 2023 10:56
@BlackySoul
Copy link
Contributor

А почему решили поменять анимации out на in? Кажется, что из-за этого сейчас outline обрезается

Было:

2023-11-22.18.09.22.mov

Стало:

2023-11-22.18.08.31.mov

for proper inside mode animation
@eugpoloz
Copy link
Contributor Author

@BlackySoul

А почему решили поменять анимации out на in? Кажется, что из-за этого сейчас outline обрезается

Спасибо за бдительность! Это я класс в анимашке потеряла, как оказывается, теперь пофиксила. 😉

Copy link
Contributor

@inomdzhon inomdzhon left a comment

Choose a reason for hiding this comment

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

🔥 ❤️‍🔥

@eugpoloz eugpoloz merged commit 9d47c34 into master Nov 23, 2023
24 checks passed
@eugpoloz eugpoloz deleted the eugpoloz/5981-FocusVisible-bug branch November 23, 2023 08:44
@vkcom-publisher
Copy link
Contributor

❌ Patch

Не удалось автоматически применить исправление на ветке v5.

Дальнейшие действия выполняют контрибьютеры из группы @VKCOM/vkui-core

Чтобы изменение попало в ветку v5, выполните следующие действия:

  1. Создайте новую ветку от v5 и примените изменения используя cherry-pick
git stash # опционально
git fetch origin v5
git checkout -b patch/pr5876 origin/v5

git cherry-pick --no-commit 9d47c34ac3e47980e291f7077f5aa46ac9316b3e
git checkout HEAD **/__image_snapshots__/*.png
git diff --quiet HEAD || git commit --no-verify --no-edit
  1. Исправьте конфликты, следуя инструкциям из терминала
  2. Отправьте ветку на GitHub и создайте новый PR с веткой v5 (установка лейбла не требуется!)
git push --set-upstream origin patch/pr5876
gh pr create --base v5 --title "patch: pr5876" --body "- patch #5876"

eugpoloz added a commit that referenced this pull request Nov 23, 2023
@eugpoloz eugpoloz mentioned this pull request Nov 23, 2023
eugpoloz added a commit that referenced this pull request Nov 23, 2023
@BlackySoul BlackySoul mentioned this pull request Feb 12, 2024
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
v5 Автоматизация: PR продублируется в ветку v5
Projects
None yet
6 participants