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(DirectionProvider): add direction to ConfigProvider #8236

Open
wants to merge 21 commits into
base: master
Choose a base branch
from

Conversation

EldarMuhamethanov
Copy link
Contributor

  • Unit-тесты
  • e2e-тесты
  • Документация фичи
  • Release notes

Описание

Текущий подход использует хук useDirection, который определяет direction через getComputedStyle при каждой первой отрисовке компонента. При большом количестве компонентов это влияет на производительность.

Предлагаемое решение

Добавить direction как параметр в ConfigProvider, который можно:

  • Задать вручную
  • Определить автоматически из стиля direction у body
Преимущества Недостатки
✅ Однократное определение direction при запуске страницы ❌ При использовании DirectionProvider обязательно указывать атрибут dir у children
✅ Получение direction через хук useConfigDirection из контекста ❌ Требуется больше кода по сравнению с текущим решением (прокидывание dir="rtl")
✅ Возможность переопределения направления для части страницы через DirectionProvider
✅ Поддержка изменения направления без перезагрузки страницы

Изменения

  1. Добавлено свойство direction в ConfigProvider
  2. Создан компонент DirectionProvider для переопределения direction
  3. Добавлены:
    • Документация
    • Тесты
    • Storybook stories
  4. Выполнен рефакторинг компонентов для использования useConfigDirection
  5. Доработал ComponentPlayground так чтобы поддерживался рендеринг компонентов в rtl
  6. Удалена функция mockRtlDirection

Release notes

Новые компоненты

  • DirectionProvider: добавлен компонент для переопределения direction

Улучшения

  • ConfigProvider: Добавлен параметр direction, который по умолчанию определяется исходя из атрибута dir в body страницы

Copy link
Contributor

github-actions bot commented Feb 4, 2025

size-limit report 📦

Path Size
JS 396.36 KB (-0.18% 🔽)
JS (gzip) 120.36 KB (-0.2% 🔽)
JS (brotli) 99.04 KB (-0.1% 🔽)
JS import Div (tree shaking) 1.56 KB (0%)
CSS 348.14 KB (0%)
CSS (gzip) 43.1 KB (0%)
CSS (brotli) 34.44 KB (0%)

Copy link

codesandbox-ci bot commented Feb 4, 2025

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.

Copy link
Contributor

github-actions bot commented Feb 4, 2025

e2e tests

⚠️ Some screenshots were failed. See Playwright Report.

Playwright Report

Copy link
Contributor

github-actions bot commented Feb 4, 2025

👀 Docs deployed

Commit 610cc81

Copy link

codecov bot commented Feb 4, 2025

Codecov Report

Attention: Patch coverage is 94.66667% with 4 lines in your changes missing coverage. Please review.

Project coverage is 95.43%. Comparing base (59c9515) to head (610cc81).
Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
packages/vkui/src/hooks/useAutoDetectDirection.ts 63.63% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #8236      +/-   ##
==========================================
- Coverage   95.54%   95.43%   -0.12%     
==========================================
  Files         404      406       +2     
  Lines       11605    11610       +5     
  Branches     3853     3845       -8     
==========================================
- Hits        11088    11080       -8     
- Misses        517      530      +13     
Flag Coverage Δ
unittests 95.43% <94.66%> (-0.12%) ⬇️

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.

@EldarMuhamethanov EldarMuhamethanov marked this pull request as ready for review February 4, 2025 13:58
# Conflicts:
#	packages/vkui/src/components/Pagination/Pagination.tsx
#	packages/vkui/src/testing/e2e/ComponentPlayground.tsx
Copy link
Contributor

@andrey-medvedev-vk andrey-medvedev-vk left a comment

Choose a reason for hiding this comment

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

Отличная работа 🎉

Copy link
Contributor

@andrey-medvedev-vk andrey-medvedev-vk left a comment

Choose a reason for hiding this comment

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

🔥

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.

🚀

if (!window || !document) {
return;
}
const styleDeclaration = window.getComputedStyle(document.body);
Copy link
Contributor

Choose a reason for hiding this comment

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

dir зачастую определяют на <html>, тут либо нужно возможность завязаться на html или body, либо проверять всё же <html> и в доке об этом говорить

https://www.w3.org/International/questions/qa-html-dir#rtlsetup

Copy link
Contributor Author

Choose a reason for hiding this comment

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

если даже dir будет установлен на html, то у body будет то же значение, так что в целом не важно

Copy link
Contributor

@inomdzhon inomdzhon Feb 11, 2025

Choose a reason for hiding this comment

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

раз у нас всё-равно есть ограничение, то что нам мешает значение для автодетекта брать до рендера? 🌚

const getGlobalDir = () => {
  if (!document) {
    return document.body.dir || document.documentElement.dir || 'ltr';
  }
  return 'ltr';
};

// ...

const direction = React.useMemo(getGlobalDir, []);

а для SSR в SSRWrapper завести свойство

<SSRWrapper dir="ltr">
  // ...
</SSRWrapper>

Copy link
Contributor Author

Choose a reason for hiding this comment

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

раз у нас всё-равно есть ограничение, то что нам мешает значение для автодетекта брать до рендера?

Насчет этого согласен

а для SSR в SSRWrapper завести свойство

А вот насчет этого, не совсем понял зачем? Можешь объяснить?

Copy link
Contributor

Choose a reason for hiding this comment

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

а для SSR в SSRWrapper завести свойство

А вот насчет этого, не совсем понял зачем? Можешь объяснить?

в SSR нет доступа к DOM, поэтому нельзя узнать dir, из-за чего в случае разметки:

<html>
  <head></head>
  <body dir="rtl">
  </body>
</html>

на сервере у компонентов не будет CSS классов под RTL, а на клиенте будет – получим ошибку гидрации

Copy link
Contributor Author

Choose a reason for hiding this comment

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

понял, получается надо нам надо с помощью DirectionProvider переопределить dir в SSRWrapper?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Добавил проп direction

Co-authored-by: Inomdzhon Mirdzhamolov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: 👀 In Review
Development

Successfully merging this pull request may close these issues.

3 participants