@cloud-ru/ds-adaptive 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +201 -0
  3. package/README.md +195 -0
  4. package/dist/cjs/components/AdaptiveProvider/AdaptiveProvider.d.ts +15 -0
  5. package/dist/cjs/components/AdaptiveProvider/AdaptiveProvider.js +17 -0
  6. package/dist/cjs/components/AdaptiveProvider/index.d.ts +1 -0
  7. package/dist/cjs/components/AdaptiveProvider/index.js +17 -0
  8. package/dist/cjs/components/index.d.ts +2 -0
  9. package/dist/cjs/components/index.js +18 -0
  10. package/dist/cjs/components/withLayoutType/index.d.ts +1 -0
  11. package/dist/cjs/components/withLayoutType/index.js +17 -0
  12. package/dist/cjs/components/withLayoutType/withLayoutType.d.ts +14 -0
  13. package/dist/cjs/components/withLayoutType/withLayoutType.js +20 -0
  14. package/dist/cjs/constants/adaptive.d.ts +57 -0
  15. package/dist/cjs/constants/adaptive.js +61 -0
  16. package/dist/cjs/constants/index.d.ts +1 -0
  17. package/dist/cjs/constants/index.js +17 -0
  18. package/dist/cjs/context/adaptiveContext.d.ts +15 -0
  19. package/dist/cjs/context/adaptiveContext.js +15 -0
  20. package/dist/cjs/context/index.d.ts +2 -0
  21. package/dist/cjs/context/index.js +5 -0
  22. package/dist/cjs/hooks/index.d.ts +4 -0
  23. package/dist/cjs/hooks/index.js +20 -0
  24. package/dist/cjs/hooks/useAdaptiveBootstrap.d.ts +18 -0
  25. package/dist/cjs/hooks/useAdaptiveBootstrap.js +22 -0
  26. package/dist/cjs/hooks/useClientLayoutType.d.ts +10 -0
  27. package/dist/cjs/hooks/useClientLayoutType.js +35 -0
  28. package/dist/cjs/hooks/useLayoutDefaults.d.ts +14 -0
  29. package/dist/cjs/hooks/useLayoutDefaults.js +21 -0
  30. package/dist/cjs/hooks/useMatchMedia.d.ts +18 -0
  31. package/dist/cjs/hooks/useMatchMedia.js +42 -0
  32. package/dist/cjs/index.d.ts +7 -0
  33. package/dist/cjs/index.js +23 -0
  34. package/dist/cjs/keys.d.ts +4 -0
  35. package/dist/cjs/keys.js +19 -0
  36. package/dist/cjs/package.json +3 -0
  37. package/dist/cjs/ssr.d.ts +10 -0
  38. package/dist/cjs/ssr.js +32 -0
  39. package/dist/cjs/store/createAdaptiveStore.d.ts +22 -0
  40. package/dist/cjs/store/createAdaptiveStore.js +29 -0
  41. package/dist/cjs/store/globalStore.d.ts +20 -0
  42. package/dist/cjs/store/globalStore.js +43 -0
  43. package/dist/cjs/store/index.d.ts +2 -0
  44. package/dist/cjs/store/index.js +18 -0
  45. package/dist/cjs/types/adaptive.d.ts +6 -0
  46. package/dist/cjs/types/adaptive.js +2 -0
  47. package/dist/cjs/types/index.d.ts +3 -0
  48. package/dist/cjs/types/index.js +19 -0
  49. package/dist/cjs/types/layoutTypes.d.ts +13 -0
  50. package/dist/cjs/types/layoutTypes.js +10 -0
  51. package/dist/cjs/types/presets.d.ts +6 -0
  52. package/dist/cjs/types/presets.js +2 -0
  53. package/dist/cjs/types/valueOf.d.ts +2 -0
  54. package/dist/cjs/types/valueOf.js +2 -0
  55. package/dist/cjs/utils/getAdaptive.d.ts +15 -0
  56. package/dist/cjs/utils/getAdaptive.js +39 -0
  57. package/dist/cjs/utils/getLayoutBootstrapScript.d.ts +2 -0
  58. package/dist/cjs/utils/getLayoutBootstrapScript.js +9 -0
  59. package/dist/cjs/utils/getMatchMedia.d.ts +12 -0
  60. package/dist/cjs/utils/getMatchMedia.js +24 -0
  61. package/dist/cjs/utils/getSSRInitialLayoutType.d.ts +21 -0
  62. package/dist/cjs/utils/getSSRInitialLayoutType.js +32 -0
  63. package/dist/cjs/utils/getUserAgentInfo.d.ts +43 -0
  64. package/dist/cjs/utils/getUserAgentInfo.js +114 -0
  65. package/dist/cjs/utils/index.d.ts +6 -0
  66. package/dist/cjs/utils/index.js +22 -0
  67. package/dist/cjs/utils/isBrowser.d.ts +3 -0
  68. package/dist/cjs/utils/isBrowser.js +9 -0
  69. package/dist/cjs/utils/layoutTypeFromMatchMedia.d.ts +4 -0
  70. package/dist/cjs/utils/layoutTypeFromMatchMedia.js +18 -0
  71. package/dist/cjs/utils/layoutTypeFromUserAgent.d.ts +6 -0
  72. package/dist/cjs/utils/layoutTypeFromUserAgent.js +20 -0
  73. package/dist/cjs/utils/layoutTypeFromWidth.d.ts +3 -0
  74. package/dist/cjs/utils/layoutTypeFromWidth.js +18 -0
  75. package/dist/cjs/utils/resolveByLayout.d.ts +28 -0
  76. package/dist/cjs/utils/resolveByLayout.js +49 -0
  77. package/dist/cjs/utils/resolveLayoutType.d.ts +11 -0
  78. package/dist/cjs/utils/resolveLayoutType.js +19 -0
  79. package/dist/esm/components/AdaptiveProvider/AdaptiveProvider.d.ts +15 -0
  80. package/dist/esm/components/AdaptiveProvider/AdaptiveProvider.js +14 -0
  81. package/dist/esm/components/AdaptiveProvider/index.d.ts +1 -0
  82. package/dist/esm/components/AdaptiveProvider/index.js +1 -0
  83. package/dist/esm/components/index.d.ts +2 -0
  84. package/dist/esm/components/index.js +2 -0
  85. package/dist/esm/components/withLayoutType/index.d.ts +1 -0
  86. package/dist/esm/components/withLayoutType/index.js +1 -0
  87. package/dist/esm/components/withLayoutType/withLayoutType.d.ts +14 -0
  88. package/dist/esm/components/withLayoutType/withLayoutType.js +17 -0
  89. package/dist/esm/constants/adaptive.d.ts +57 -0
  90. package/dist/esm/constants/adaptive.js +57 -0
  91. package/dist/esm/constants/index.d.ts +1 -0
  92. package/dist/esm/constants/index.js +1 -0
  93. package/dist/esm/context/adaptiveContext.d.ts +15 -0
  94. package/dist/esm/context/adaptiveContext.js +11 -0
  95. package/dist/esm/context/index.d.ts +2 -0
  96. package/dist/esm/context/index.js +1 -0
  97. package/dist/esm/hooks/index.d.ts +4 -0
  98. package/dist/esm/hooks/index.js +4 -0
  99. package/dist/esm/hooks/useAdaptiveBootstrap.d.ts +18 -0
  100. package/dist/esm/hooks/useAdaptiveBootstrap.js +19 -0
  101. package/dist/esm/hooks/useClientLayoutType.d.ts +10 -0
  102. package/dist/esm/hooks/useClientLayoutType.js +32 -0
  103. package/dist/esm/hooks/useLayoutDefaults.d.ts +14 -0
  104. package/dist/esm/hooks/useLayoutDefaults.js +18 -0
  105. package/dist/esm/hooks/useMatchMedia.d.ts +18 -0
  106. package/dist/esm/hooks/useMatchMedia.js +37 -0
  107. package/dist/esm/index.d.ts +7 -0
  108. package/dist/esm/index.js +7 -0
  109. package/dist/esm/keys.d.ts +4 -0
  110. package/dist/esm/keys.js +16 -0
  111. package/dist/esm/ssr.d.ts +10 -0
  112. package/dist/esm/ssr.js +16 -0
  113. package/dist/esm/store/createAdaptiveStore.d.ts +22 -0
  114. package/dist/esm/store/createAdaptiveStore.js +26 -0
  115. package/dist/esm/store/globalStore.d.ts +20 -0
  116. package/dist/esm/store/globalStore.js +40 -0
  117. package/dist/esm/store/index.d.ts +2 -0
  118. package/dist/esm/store/index.js +2 -0
  119. package/dist/esm/types/adaptive.d.ts +6 -0
  120. package/dist/esm/types/adaptive.js +1 -0
  121. package/dist/esm/types/index.d.ts +3 -0
  122. package/dist/esm/types/index.js +3 -0
  123. package/dist/esm/types/layoutTypes.d.ts +13 -0
  124. package/dist/esm/types/layoutTypes.js +7 -0
  125. package/dist/esm/types/presets.d.ts +6 -0
  126. package/dist/esm/types/presets.js +1 -0
  127. package/dist/esm/types/valueOf.d.ts +2 -0
  128. package/dist/esm/types/valueOf.js +1 -0
  129. package/dist/esm/utils/getAdaptive.d.ts +15 -0
  130. package/dist/esm/utils/getAdaptive.js +36 -0
  131. package/dist/esm/utils/getLayoutBootstrapScript.d.ts +2 -0
  132. package/dist/esm/utils/getLayoutBootstrapScript.js +6 -0
  133. package/dist/esm/utils/getMatchMedia.d.ts +12 -0
  134. package/dist/esm/utils/getMatchMedia.js +18 -0
  135. package/dist/esm/utils/getSSRInitialLayoutType.d.ts +21 -0
  136. package/dist/esm/utils/getSSRInitialLayoutType.js +28 -0
  137. package/dist/esm/utils/getUserAgentInfo.d.ts +43 -0
  138. package/dist/esm/utils/getUserAgentInfo.js +110 -0
  139. package/dist/esm/utils/index.d.ts +6 -0
  140. package/dist/esm/utils/index.js +6 -0
  141. package/dist/esm/utils/isBrowser.d.ts +3 -0
  142. package/dist/esm/utils/isBrowser.js +6 -0
  143. package/dist/esm/utils/layoutTypeFromMatchMedia.d.ts +4 -0
  144. package/dist/esm/utils/layoutTypeFromMatchMedia.js +15 -0
  145. package/dist/esm/utils/layoutTypeFromUserAgent.d.ts +6 -0
  146. package/dist/esm/utils/layoutTypeFromUserAgent.js +17 -0
  147. package/dist/esm/utils/layoutTypeFromWidth.d.ts +3 -0
  148. package/dist/esm/utils/layoutTypeFromWidth.js +15 -0
  149. package/dist/esm/utils/resolveByLayout.d.ts +28 -0
  150. package/dist/esm/utils/resolveByLayout.js +45 -0
  151. package/dist/esm/utils/resolveLayoutType.d.ts +11 -0
  152. package/dist/esm/utils/resolveLayoutType.js +15 -0
  153. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  154. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  155. package/package.json +45 -0
  156. package/src/components/AdaptiveProvider/AdaptiveProvider.tsx +28 -0
  157. package/src/components/AdaptiveProvider/index.ts +1 -0
  158. package/src/components/index.ts +2 -0
  159. package/src/components/withLayoutType/index.ts +1 -0
  160. package/src/components/withLayoutType/withLayoutType.tsx +26 -0
  161. package/src/constants/adaptive.ts +73 -0
  162. package/src/constants/index.ts +1 -0
  163. package/src/context/adaptiveContext.ts +27 -0
  164. package/src/context/index.ts +2 -0
  165. package/src/hooks/index.ts +4 -0
  166. package/src/hooks/useAdaptiveBootstrap.ts +38 -0
  167. package/src/hooks/useClientLayoutType.ts +51 -0
  168. package/src/hooks/useLayoutDefaults.ts +21 -0
  169. package/src/hooks/useMatchMedia.ts +52 -0
  170. package/src/index.ts +7 -0
  171. package/src/keys.ts +18 -0
  172. package/src/ssr.ts +16 -0
  173. package/src/store/createAdaptiveStore.ts +42 -0
  174. package/src/store/globalStore.ts +57 -0
  175. package/src/store/index.ts +2 -0
  176. package/src/types/adaptive.ts +8 -0
  177. package/src/types/index.ts +3 -0
  178. package/src/types/layoutTypes.ts +15 -0
  179. package/src/types/presets.ts +7 -0
  180. package/src/types/valueOf.ts +2 -0
  181. package/src/utils/getAdaptive.ts +46 -0
  182. package/src/utils/getLayoutBootstrapScript.ts +8 -0
  183. package/src/utils/getMatchMedia.ts +36 -0
  184. package/src/utils/getSSRInitialLayoutType.ts +50 -0
  185. package/src/utils/getUserAgentInfo.ts +145 -0
  186. package/src/utils/index.ts +6 -0
  187. package/src/utils/isBrowser.ts +6 -0
  188. package/src/utils/layoutTypeFromMatchMedia.ts +20 -0
  189. package/src/utils/layoutTypeFromUserAgent.ts +19 -0
  190. package/src/utils/layoutTypeFromWidth.ts +20 -0
  191. package/src/utils/resolveByLayout.ts +72 -0
  192. package/src/utils/resolveLayoutType.ts +18 -0
@@ -0,0 +1,73 @@
1
+ import { LAYOUT_TYPE, LayoutType } from '../types/layoutTypes';
2
+
3
+ /** Брейкпоинты adaptive-раскладки (max-width в px). Форма дефолта `ADAPTIVE_BREAKPOINT`. */
4
+ export type AdaptiveBreakpoints = {
5
+ mobile: number;
6
+ tablet: number;
7
+ desktopSmall: number;
8
+ desktop: number;
9
+ };
10
+
11
+ /** Брейкпоинты adaptive-раскладки (max-width в px), по которым `useAdaptiveBootstrap` выбирает `layoutType`. */
12
+ export const ADAPTIVE_BREAKPOINT: AdaptiveBreakpoints = {
13
+ mobile: 767,
14
+ tablet: 1023,
15
+ desktopSmall: 1279,
16
+ desktop: 1439,
17
+ };
18
+
19
+ /** CSS media-query строки, собранные из `ADAPTIVE_BREAKPOINT`. */
20
+ export const CSS_BREAKPOINTS = {
21
+ mobile: `(max-width: ${ADAPTIVE_BREAKPOINT.mobile}px)`,
22
+ tablet: `(max-width: ${ADAPTIVE_BREAKPOINT.tablet}px)`,
23
+ desktopSmall: `(max-width: ${ADAPTIVE_BREAKPOINT.desktopSmall}px)`,
24
+ desktop: `(max-width: ${ADAPTIVE_BREAKPOINT.desktop}px)`,
25
+ large: `(min-width: ${ADAPTIVE_BREAKPOINT.desktop + 1}px)`,
26
+ } as const;
27
+
28
+ /** Ключи media-query, отслеживаемых `useAdaptiveMatchMedia`. */
29
+ export const ADAPTIVE_QUERY = {
30
+ IsMobile: 'isMobile',
31
+ IsTablet: 'isTablet',
32
+ IsSmallDesktop: 'isSmallDesktop',
33
+ IsDesktop: 'isDesktop',
34
+ IsLarge: 'isLarge',
35
+ } as const;
36
+
37
+ /** Карта `query-key → media-query строка` для подписки. */
38
+ export const ADAPTIVE_QUERIES = {
39
+ [ADAPTIVE_QUERY.IsMobile]: CSS_BREAKPOINTS.mobile,
40
+ [ADAPTIVE_QUERY.IsTablet]: CSS_BREAKPOINTS.tablet,
41
+ [ADAPTIVE_QUERY.IsSmallDesktop]: CSS_BREAKPOINTS.desktopSmall,
42
+ [ADAPTIVE_QUERY.IsDesktop]: CSS_BREAKPOINTS.desktop,
43
+ [ADAPTIVE_QUERY.IsLarge]: CSS_BREAKPOINTS.large,
44
+ } as const;
45
+
46
+ /** Собирает карту adaptive media-query из произвольных брейкпоинтов — для per-app override. */
47
+ export function buildAdaptiveQueries(breakpoints: AdaptiveBreakpoints) {
48
+ return {
49
+ [ADAPTIVE_QUERY.IsMobile]: `(max-width: ${breakpoints.mobile}px)`,
50
+ [ADAPTIVE_QUERY.IsTablet]: `(max-width: ${breakpoints.tablet}px)`,
51
+ [ADAPTIVE_QUERY.IsSmallDesktop]: `(max-width: ${breakpoints.desktopSmall}px)`,
52
+ [ADAPTIVE_QUERY.IsDesktop]: `(max-width: ${breakpoints.desktop}px)`,
53
+ [ADAPTIVE_QUERY.IsLarge]: `(min-width: ${breakpoints.desktop + 1}px)`,
54
+ };
55
+ }
56
+
57
+ /** SSR-safe начальные значения (на сервере ни один media-query не матчится). */
58
+ export const INITIAL_ADAPTIVE_QUERIES_VALUE = {
59
+ [ADAPTIVE_QUERY.IsMobile]: false,
60
+ [ADAPTIVE_QUERY.IsTablet]: false,
61
+ [ADAPTIVE_QUERY.IsSmallDesktop]: false,
62
+ [ADAPTIVE_QUERY.IsDesktop]: false,
63
+ [ADAPTIVE_QUERY.IsLarge]: false,
64
+ } as const;
65
+
66
+ /** SSR-baseline раскладки адаптивных компонентов: на сервере и до mount — desktop. */
67
+ export const DEFAULT_LAYOUT_TYPE: LayoutType = LAYOUT_TYPE.Desktop;
68
+
69
+ /** Наборы `layoutType`, уходящие по mobile-ветке surface-swap. Один источник для runtime, stories и docs. */
70
+ export const LAYOUT_SPLIT_MOBILE_TIERS = {
71
+ /** Только phone уходит в mobile-ветку. */
72
+ mobileOnly: [LAYOUT_TYPE.Mobile],
73
+ } as const;
@@ -0,0 +1 @@
1
+ export * from './adaptive';
@@ -0,0 +1,27 @@
1
+ import { createSharedStoreContext, ExternalStore } from '@cloud-ru/ds-context-kit';
2
+
3
+ import { ADAPTIVE_KEYS } from '../keys';
4
+ import { getGlobalAdaptiveStore } from '../store/globalStore';
5
+ import { LayoutType } from '../types/layoutTypes';
6
+
7
+ /** Значение adaptive-контекста: текущая раскладка. */
8
+ export type AdaptiveContextValue = {
9
+ layoutType: LayoutType;
10
+ };
11
+
12
+ /** Внешний стор раскладки (формат `useSyncExternalStore`). Адаптер над любым реактивным источником — см. `createAdaptiveStore`. */
13
+ export type AdaptiveStore = ExternalStore<AdaptiveContextValue>;
14
+
15
+ // Дефолт контекста = глобальный singleton-стор: потребитель без `AdaptiveProvider` в своём дереве
16
+ // читает раскладку, выставленную шеллом в `getGlobalAdaptiveStore`. Явный `<AdaptiveProvider>` затеняет дефолт.
17
+ const { StoreProvider, useStoreValue } = createSharedStoreContext<AdaptiveContextValue>(
18
+ ADAPTIVE_KEYS.context,
19
+ getGlobalAdaptiveStore().store,
20
+ );
21
+
22
+ export { StoreProvider as AdaptiveStoreProvider };
23
+
24
+ /** Возвращает текущую раскладку из `AdaptiveProvider`. Реактивно к внешнему стору, если он задан. */
25
+ export function useAdaptiveLayout(): AdaptiveContextValue {
26
+ return useStoreValue();
27
+ }
@@ -0,0 +1,2 @@
1
+ export { useAdaptiveLayout } from './adaptiveContext';
2
+ export type { AdaptiveContextValue, AdaptiveStore } from './adaptiveContext';
@@ -0,0 +1,4 @@
1
+ export * from './useAdaptiveBootstrap';
2
+ export * from './useLayoutDefaults';
3
+ export * from './useClientLayoutType';
4
+ export * from './useMatchMedia';
@@ -0,0 +1,38 @@
1
+ import { useMemo } from 'react';
2
+
3
+ import {
4
+ ADAPTIVE_BREAKPOINT,
5
+ ADAPTIVE_QUERIES,
6
+ AdaptiveBreakpoints,
7
+ buildAdaptiveQueries,
8
+ } from '../constants/adaptive';
9
+ import { LayoutType } from '../types/layoutTypes';
10
+ import { getAdaptive } from '../utils/getAdaptive';
11
+ import { useAdaptiveMatchMedia } from './useMatchMedia';
12
+
13
+ export type UseAdaptiveBootstrapOptions = {
14
+ /** Переопределение брейкпоинтов (max-width в px), напр. `{ mobile: 480 }`. Меняет только пороги, набор тиров прежний. */
15
+ breakpoints?: Partial<AdaptiveBreakpoints>;
16
+ /** User-agent для SSR (на клиенте берётся из `navigator`). См. `getAdaptive`. */
17
+ userAgent?: string;
18
+ };
19
+
20
+ /**
21
+ * Возвращает текущий `layoutType` по типу устройства из user-agent + media-query. SSR-safe: до mount `desktop`.
22
+ * Вызывается один раз в корне приложения, результат передаётся в `<AdaptiveProvider layoutType={...}>`.
23
+ * Не путать с `useAdaptiveLayout` — тем читают уже посчитанную раскладку из контекста внутри компонентов.
24
+ * Для per-app порогов передайте `breakpoints` (мемоизировать объект не нужно).
25
+ * @function React hook
26
+ */
27
+ export function useAdaptiveBootstrap(options?: UseAdaptiveBootstrapOptions): { layoutType: LayoutType } {
28
+ const { breakpoints, userAgent } = options ?? {};
29
+
30
+ const queryValues = useMemo(
31
+ () => (breakpoints ? buildAdaptiveQueries({ ...ADAPTIVE_BREAKPOINT, ...breakpoints }) : ADAPTIVE_QUERIES),
32
+ // Зависим от значений брейкпоинтов, а не от ссылки объекта — иначе инлайн-`{ mobile: 480 }` переподписывает matchMedia.
33
+ // eslint-disable-next-line react-hooks/exhaustive-deps
34
+ [breakpoints?.mobile, breakpoints?.tablet, breakpoints?.desktopSmall, breakpoints?.desktop],
35
+ );
36
+
37
+ return getAdaptive(useAdaptiveMatchMedia(queryValues), userAgent);
38
+ }
@@ -0,0 +1,51 @@
1
+ import { useLayoutEffect } from '@cloud-ru/ds-utils';
2
+ import { useMemo, useState } from 'react';
3
+
4
+ import {
5
+ ADAPTIVE_BREAKPOINT,
6
+ ADAPTIVE_QUERIES,
7
+ AdaptiveBreakpoints,
8
+ buildAdaptiveQueries,
9
+ INITIAL_ADAPTIVE_QUERIES_VALUE,
10
+ } from '../constants/adaptive';
11
+ import { LayoutType } from '../types';
12
+ import { getMatchMediaGeneric, getMediaQueryListGeneric } from '../utils/getMatchMedia';
13
+ import { layoutTypeFromMatchMedia } from '../utils/layoutTypeFromMatchMedia';
14
+
15
+ /**
16
+ * Раскладка с коррекцией ДО первой отрисовки. Старт — `initialLayoutType` с сервера (Client Hints
17
+ * → точная ширина на Chromium; иначе desktop), поэтому первый клиентский рендер совпадает с SSR
18
+ * (чистая гидратация). Уточнение по media-query — в `useLayoutEffect` (синхронно перед paint), а не
19
+ * в `useEffect`: на узком окне в FF/Safari переключение происходит до отрисовки, без видимого прыжка.
20
+ * `<html data-layout-type>` держим синхронизированным для адаптивного CSS (его же ставит pre-paint скрипт).
21
+ */
22
+ export function useClientLayoutType(initialLayoutType: LayoutType, breakpoints?: AdaptiveBreakpoints): LayoutType {
23
+ const [layoutType, setLayoutType] = useState<LayoutType>(initialLayoutType);
24
+
25
+ const queryValues = useMemo(
26
+ () => (breakpoints ? buildAdaptiveQueries({ ...ADAPTIVE_BREAKPOINT, ...breakpoints }) : ADAPTIVE_QUERIES),
27
+ // Зависим от значений брейкпоинтов, а не от ссылки объекта — иначе инлайн-override переподписывает matchMedia.
28
+ // eslint-disable-next-line react-hooks/exhaustive-deps
29
+ [breakpoints?.mobile, breakpoints?.tablet, breakpoints?.desktopSmall, breakpoints?.desktop],
30
+ );
31
+
32
+ useLayoutEffect(() => {
33
+ const apply = () => {
34
+ const next = layoutTypeFromMatchMedia(
35
+ getMatchMediaGeneric({ queryValues, initialValues: INITIAL_ADAPTIVE_QUERIES_VALUE }),
36
+ );
37
+ document.documentElement.dataset.layoutType = next;
38
+ setLayoutType(next);
39
+ };
40
+
41
+ apply();
42
+ const handler = () => apply();
43
+ const mediaQueryList = getMediaQueryListGeneric({ queryValues });
44
+
45
+ mediaQueryList.forEach(([, mql]) => mql.addEventListener('change', handler));
46
+
47
+ return () => mediaQueryList.forEach(([, mql]) => mql.removeEventListener('change', handler));
48
+ }, [queryValues]);
49
+
50
+ return layoutType;
51
+ }
@@ -0,0 +1,21 @@
1
+ import { useAdaptiveLayout } from '../context/adaptiveContext';
2
+ import { LayoutPresets } from '../types/presets';
3
+ import { resolveByLayout } from '../utils/resolveByLayout';
4
+
5
+ /**
6
+ * React-хук preset-класса адаптивности: резолвит дефолты пропов по раскладке из `AdaptiveProvider`.
7
+ * desktop-first приоритет: пресет раскладки (instance > DS) > явный проп инстанса > базовый дефолт.
8
+ * Preset-участвующие пропы передавай в `explicit` без destructure-дефолта.
9
+ *
10
+ * @example
11
+ * const { collapsible } = useLayoutDefaults(
12
+ * { collapsible: false }, // база (desktop)
13
+ * mergePresets(ALERT_TOP_LAYOUT_PRESETS, layoutPresets), // DS-пресет ⊕ instance-override
14
+ * { collapsible }, // явный проп инстанса = desktop-значение (может быть undefined)
15
+ * );
16
+ */
17
+ export function useLayoutDefaults<P extends object>(base: P, presets: LayoutPresets<P>, explicit: Partial<P>): P {
18
+ const { layoutType } = useAdaptiveLayout();
19
+
20
+ return resolveByLayout({ layoutType, base, presets, explicit });
21
+ }
@@ -0,0 +1,52 @@
1
+ import { useLayoutEffect } from '@cloud-ru/ds-utils';
2
+ import { useState } from 'react';
3
+
4
+ import { ADAPTIVE_QUERIES, INITIAL_ADAPTIVE_QUERIES_VALUE } from '../constants/adaptive';
5
+ import { AdaptiveQuery, MatchMediaGeneric } from '../types/adaptive';
6
+ import { getMatchMediaGeneric, getMediaQueryListGeneric } from '../utils/getMatchMedia';
7
+
8
+ /**
9
+ * Подписывается на набор media-query и возвращает их состояние (`query-key → matched?`).
10
+ * SSR-safe: первый рендер — и на сервере, и при гидрации на клиенте — берёт `initialValues`, что
11
+ * совпадает с серверным HTML и не даёт hydration mismatch. Реальное состояние media-query читается
12
+ * уже после mount в `useLayoutEffect` (синхронно, до paint — без видимого скачка), там же — подписка
13
+ * на `change`.
14
+ * @function React hook
15
+ */
16
+ export const useMatchMediaGeneric = <T extends string>({
17
+ queryValues,
18
+ initialValues,
19
+ }: {
20
+ queryValues: Record<T, string>;
21
+ initialValues: MatchMediaGeneric<T>;
22
+ }): MatchMediaGeneric<T> => {
23
+ const [value, setValue] = useState<MatchMediaGeneric<T>>(initialValues);
24
+
25
+ useLayoutEffect(() => {
26
+ const read = () => getMatchMediaGeneric({ queryValues, initialValues });
27
+ // Синхронизируемся с реальным matchMedia на клиенте — устраняем рассинхрон с SSR-initialValues.
28
+ setValue(read());
29
+
30
+ const handler = () => setValue(read());
31
+ const mediaQueryList = getMediaQueryListGeneric({ queryValues });
32
+
33
+ mediaQueryList.forEach(([, mql]) => mql.addEventListener('change', handler));
34
+
35
+ return (): void => mediaQueryList.forEach(([, mql]) => mql.removeEventListener('change', handler));
36
+ // queryValues/initialValues стабильны по ссылке (useAdaptiveBootstrap мемоизирует queryValues); смена
37
+ // breakpoints на лету пере-подписывает на новые media-query.
38
+ }, [queryValues, initialValues]);
39
+
40
+ return value;
41
+ };
42
+
43
+ /**
44
+ * Состояние adaptive media-query (`isMobile` / `isTablet` / …). По умолчанию — дефолтные брейкпоинты DS.
45
+ * Для per-app override передайте свою карту запросов; она должна быть стабильной по ссылке.
46
+ */
47
+ export function useAdaptiveMatchMedia(queryValues: Record<AdaptiveQuery, string> = ADAPTIVE_QUERIES) {
48
+ return useMatchMediaGeneric({
49
+ queryValues,
50
+ initialValues: INITIAL_ADAPTIVE_QUERIES_VALUE,
51
+ });
52
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from './components';
2
+ export * from './context';
3
+ export * from './store';
4
+ export * from './hooks';
5
+ export * from './utils';
6
+ export * from './types';
7
+ export * from './constants';
package/src/keys.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { providerKey } from '@cloud-ru/ds-context-kit';
2
+
3
+ /**
4
+ * `Symbol.for`-ключи домена adaptive — обе системы синглтонов в одном месте:
5
+ * - `context` — объект React-контекста (через `providerKey` → есть dev-warn о смешанных версиях);
6
+ * - `store` — глобальный мутабельный стор раскладки (кросс-root мост хост→MFE).
7
+ *
8
+ * Одна контракт-версия на домен повышается ТОЛЬКО при несовместимом сломе формы значения и двигает
9
+ * ОБА ключа вместе — забыть половину нельзя. Ортогонально мажору ПАКЕТА (разные мажоры делят ключ,
10
+ * пока shape аддитивен). Строки менять НЕЛЬЗЯ — это форк синглтона (случайный `:v2`). См.
11
+ * providers-standard.md.
12
+ */
13
+ const CONTRACT_VERSION = 1;
14
+
15
+ export const ADAPTIVE_KEYS = {
16
+ context: providerKey('adaptive-context', CONTRACT_VERSION),
17
+ store: `@cloud-ru/ds:global-adaptive-store:v${CONTRACT_VERSION}`,
18
+ } as const;
package/src/ssr.ts ADDED
@@ -0,0 +1,16 @@
1
+ // Server-safe подмножество публичного API @cloud-ru/ds-adaptive: чистые функции и константы адаптива БЕЗ
2
+ // React-импортов. Барель `@cloud-ru/ds-adaptive` (src/index.ts) реэкспортит хуки и контексты
3
+ // (`createContext`/`useEffect`), поэтому его нельзя импортировать в React Server Component (Next App
4
+ // Router завершается с ошибкой «needs use client»). Этот вход безопасно импортировать на сервере —
5
+ // например, чтобы вычислить `layoutType` из request User-Agent в `layout.tsx`
6
+ // (`getSSRInitialLayoutType({ viewportWidth, userAgent })` + `getLayoutBootstrapScript()`).
7
+ export * from './constants/adaptive';
8
+ export * from './types/layoutTypes';
9
+ export * from './types/presets';
10
+ export * from './utils/getAdaptive';
11
+ export * from './utils/getLayoutBootstrapScript';
12
+ export * from './utils/getSSRInitialLayoutType';
13
+ export * from './utils/getUserAgentInfo';
14
+ export * from './utils/layoutTypeFromUserAgent';
15
+ export * from './utils/resolveByLayout';
16
+ export * from './utils/resolveLayoutType';
@@ -0,0 +1,42 @@
1
+ import { AdaptiveContextValue, AdaptiveStore } from '../context/adaptiveContext';
2
+ import { LayoutType } from '../types/layoutTypes';
3
+
4
+ export type CreateAdaptiveStoreOptions = {
5
+ /** Текущая раскладка из внешнего источника. */
6
+ getLayoutType(): LayoutType;
7
+ /** Подписка на изменения внешнего источника; возвращает функцию отписки. */
8
+ subscribe(onChange: () => void): () => void;
9
+ /** Раскладка для SSR (request-scoped). Нужен только при server-render; в чистом CSR — нет. */
10
+ getServerLayoutType?(): LayoutType;
11
+ };
12
+
13
+ /**
14
+ * Адаптер внешнего реактивного источника раскладки (redux / zustand / signals / observable) в
15
+ * `AdaptiveStore` (формат `useSyncExternalStore`) для `<AdaptiveProvider store={...} />`.
16
+ * Кэширует snapshot по `layoutType` ради стабильной ссылки.
17
+ *
18
+ * @example
19
+ * const adaptiveStore = createAdaptiveStore({
20
+ * getLayoutType: () => layoutSource.current,
21
+ * subscribe: (onChange) => layoutSource.on('change', onChange),
22
+ * });
23
+ */
24
+ export function createAdaptiveStore(options: CreateAdaptiveStoreOptions): AdaptiveStore {
25
+ let cache: AdaptiveContextValue | undefined;
26
+
27
+ const read = (layoutType: LayoutType): AdaptiveContextValue => {
28
+ if (!cache || cache.layoutType !== layoutType) {
29
+ cache = { layoutType };
30
+ }
31
+
32
+ return cache;
33
+ };
34
+
35
+ const { getServerLayoutType } = options;
36
+
37
+ return {
38
+ subscribe: options.subscribe,
39
+ getSnapshot: () => read(options.getLayoutType()),
40
+ getServerSnapshot: getServerLayoutType ? () => read(getServerLayoutType()) : undefined,
41
+ };
42
+ }
@@ -0,0 +1,57 @@
1
+ import { DEFAULT_LAYOUT_TYPE } from '../constants/adaptive';
2
+ import { AdaptiveStore } from '../context/adaptiveContext';
3
+ import { ADAPTIVE_KEYS } from '../keys';
4
+ import { LayoutType } from '../types/layoutTypes';
5
+ import { createAdaptiveStore } from './createAdaptiveStore';
6
+
7
+ export type GlobalAdaptiveStore = {
8
+ /** Стор для `<AdaptiveProvider store={...} />`. */
9
+ store: AdaptiveStore;
10
+ /** Текущая раскладка. */
11
+ getLayoutType(): LayoutType;
12
+ /** Установить раскладку и уведомить все подписанные `AdaptiveProvider`. */
13
+ setLayoutType(layoutType: LayoutType): void;
14
+ };
15
+
16
+ const REGISTRY_KEY = Symbol.for(ADAPTIVE_KEYS.store);
17
+
18
+ type Registry = { [REGISTRY_KEY]?: GlobalAdaptiveStore };
19
+
20
+ /**
21
+ * Глобальный singleton-стор раскладки, общий для всех React-корней процесса (микрофронты single-spa,
22
+ * острова Astro). Хранится в `globalThis` через `Symbol.for`, переживает несколько копий пакета.
23
+ * Нужен только для multi-root; при одном корне — обычный `AdaptiveProvider` или `createAdaptiveStore`.
24
+ *
25
+ * @example
26
+ * getGlobalAdaptiveStore().setLayoutType(useAdaptiveBootstrap().layoutType);
27
+ * <AdaptiveProvider store={getGlobalAdaptiveStore().store}>{root}</AdaptiveProvider>;
28
+ */
29
+ export function getGlobalAdaptiveStore(): GlobalAdaptiveStore {
30
+ const registry = globalThis as Registry;
31
+
32
+ if (!registry[REGISTRY_KEY]) {
33
+ let currentLayout: LayoutType = DEFAULT_LAYOUT_TYPE;
34
+ const listeners = new Set<() => void>();
35
+
36
+ registry[REGISTRY_KEY] = {
37
+ store: createAdaptiveStore({
38
+ getLayoutType: () => currentLayout,
39
+ subscribe: onChange => {
40
+ listeners.add(onChange);
41
+ return () => {
42
+ listeners.delete(onChange);
43
+ };
44
+ },
45
+ getServerLayoutType: () => DEFAULT_LAYOUT_TYPE,
46
+ }),
47
+ getLayoutType: () => currentLayout,
48
+ setLayoutType: layoutType => {
49
+ if (layoutType === currentLayout) return;
50
+ currentLayout = layoutType;
51
+ listeners.forEach(listener => listener());
52
+ },
53
+ };
54
+ }
55
+
56
+ return registry[REGISTRY_KEY];
57
+ }
@@ -0,0 +1,2 @@
1
+ export * from './globalStore';
2
+ export * from './createAdaptiveStore';
@@ -0,0 +1,8 @@
1
+ import { ADAPTIVE_QUERY } from '../constants/adaptive';
2
+ import { ValueOf } from './valueOf';
3
+
4
+ /** Ключ одного из adaptive media-query (`isMobile` / `isTablet` / …). */
5
+ export type AdaptiveQuery = ValueOf<typeof ADAPTIVE_QUERY>;
6
+
7
+ /** Карта `query-key → matched?` для произвольного набора media-query. */
8
+ export type MatchMediaGeneric<T extends string> = Record<T, boolean>;
@@ -0,0 +1,3 @@
1
+ export * from './layoutTypes';
2
+ export * from './adaptive';
3
+ export * from './presets';
@@ -0,0 +1,15 @@
1
+ import { ValueOf } from './valueOf';
2
+
3
+ /** Константы типов раскладки adaptive-компонентов (mobile / tablet / desktopSmall / desktop). */
4
+ export const LAYOUT_TYPE = {
5
+ Desktop: 'desktop',
6
+ DesktopSmall: 'desktopSmall',
7
+ Tablet: 'tablet',
8
+ Mobile: 'mobile',
9
+ } as const;
10
+
11
+ /**
12
+ * Union типов раскладки adaptive-компонентов
13
+ * @function type
14
+ */
15
+ export type LayoutType = ValueOf<typeof LAYOUT_TYPE>;
@@ -0,0 +1,7 @@
1
+ import { LayoutType } from './layoutTypes';
2
+
3
+ /**
4
+ * Карта пресетов дефолтов по раскладке: для каждого `layoutType` — частичный набор пропов поверх
5
+ * базовых дефолтов. Обычно непуст только `mobile`. Резолв — `resolveByLayout` / `useLayoutDefaults`.
6
+ */
7
+ export type LayoutPresets<P> = Partial<Record<LayoutType, Partial<P>>>;
@@ -0,0 +1,2 @@
1
+ /** Значение объекта-константы как union. Локальная копия (см. isBrowser.ts — SSR-purity). */
2
+ export type ValueOf<T> = T[keyof T];
@@ -0,0 +1,46 @@
1
+ import { ADAPTIVE_QUERY } from '../constants/adaptive';
2
+ import { AdaptiveQuery, MatchMediaGeneric } from '../types/adaptive';
3
+ import { LAYOUT_TYPE, LayoutType } from '../types/layoutTypes';
4
+ import { getUserAgentInfo } from './getUserAgentInfo';
5
+
6
+ /**
7
+ * Вычисляет `layoutType` по типу устройства из user-agent + media-query (гибрид «UA + ширина»):
8
+ * - `mobile` → всегда `mobile`;
9
+ * - `tablet` → `mobile` при узком окне (`isTablet`), иначе `tablet`;
10
+ * - desktop / неизвестное → каскад по ширине: `isMobile` → `mobile`, `isTablet` → `tablet`,
11
+ * `isSmallDesktop` → `desktopSmall`, иначе `desktop`.
12
+ *
13
+ * SSR: передайте `userAgent` из заголовка запроса для корректной ветки в HTML без скачка после
14
+ * гидрации; media-query на сервере нет → `INITIAL_ADAPTIVE_QUERIES_VALUE`.
15
+ */
16
+ export function getAdaptive(
17
+ matchMedia: MatchMediaGeneric<AdaptiveQuery>,
18
+ userAgent?: string,
19
+ ): { layoutType: LayoutType } {
20
+ const { device } = getUserAgentInfo(userAgent);
21
+
22
+ const isMobile = matchMedia[ADAPTIVE_QUERY.IsMobile];
23
+ const isTablet = matchMedia[ADAPTIVE_QUERY.IsTablet];
24
+ const isSmallDesktop = matchMedia[ADAPTIVE_QUERY.IsSmallDesktop];
25
+
26
+ if (device.type === 'mobile') {
27
+ return { layoutType: LAYOUT_TYPE.Mobile };
28
+ }
29
+
30
+ if (device.type === 'tablet') {
31
+ return { layoutType: isTablet ? LAYOUT_TYPE.Mobile : LAYOUT_TYPE.Tablet };
32
+ }
33
+
34
+ // desktop / неизвестное устройство — каскад по ширине через все пороги.
35
+ if (isMobile) {
36
+ return { layoutType: LAYOUT_TYPE.Mobile };
37
+ }
38
+ if (isTablet) {
39
+ return { layoutType: LAYOUT_TYPE.Tablet };
40
+ }
41
+ if (isSmallDesktop) {
42
+ return { layoutType: LAYOUT_TYPE.DesktopSmall };
43
+ }
44
+
45
+ return { layoutType: LAYOUT_TYPE.Desktop };
46
+ }
@@ -0,0 +1,8 @@
1
+ import { ADAPTIVE_BREAKPOINT, AdaptiveBreakpoints, buildAdaptiveQueries } from '../constants/adaptive';
2
+ import { LAYOUT_TYPE } from '../types/layoutTypes';
3
+
4
+ export function getLayoutBootstrapScript(breakpoints?: AdaptiveBreakpoints): string {
5
+ const queries = buildAdaptiveQueries({ ...ADAPTIVE_BREAKPOINT, ...breakpoints });
6
+
7
+ return `(function(){try{var d=document.documentElement;if(matchMedia('${queries.isMobile}').matches){d.dataset.layoutType='${LAYOUT_TYPE.Mobile}';}else if(matchMedia('${queries.isTablet}').matches){d.dataset.layoutType='${LAYOUT_TYPE.Tablet}';}else if(matchMedia('${queries.isSmallDesktop}').matches){d.dataset.layoutType='${LAYOUT_TYPE.DesktopSmall}';}else{d.dataset.layoutType='${LAYOUT_TYPE.Desktop}';}}catch(e){}})();`;
8
+ }
@@ -0,0 +1,36 @@
1
+ import { ADAPTIVE_QUERIES, INITIAL_ADAPTIVE_QUERIES_VALUE } from '../constants/adaptive';
2
+ import { MatchMediaGeneric } from '../types/adaptive';
3
+ import { isBrowser } from './isBrowser';
4
+
5
+ function getMediaQueries<T extends string>({ queryValues }: { queryValues: Record<T, string> }) {
6
+ return Object.keys(queryValues).reduce(
7
+ (acc, key) => ({
8
+ ...acc,
9
+ [key]: isBrowser() ? globalThis.matchMedia(queryValues[key as T]) : undefined,
10
+ }),
11
+ {} as Record<T, MediaQueryList>,
12
+ );
13
+ }
14
+
15
+ /** Возвращает пары `[query-key, MediaQueryList]` для подписки на `change`. */
16
+ export function getMediaQueryListGeneric<T extends string>({ queryValues }: { queryValues: Record<T, string> }) {
17
+ return Object.entries(getMediaQueries({ queryValues })) as Array<[T, MediaQueryList]>;
18
+ }
19
+
20
+ /** Снимок текущего состояния media-query (`query-key → matched?`); SSR → `initialValues`. */
21
+ export function getMatchMediaGeneric<T extends string>({
22
+ queryValues,
23
+ initialValues,
24
+ }: {
25
+ queryValues: Record<T, string>;
26
+ initialValues: MatchMediaGeneric<T>;
27
+ }): MatchMediaGeneric<T> {
28
+ return getMediaQueryListGeneric<T>({ queryValues }).reduce(
29
+ (acc, [key, q]) => ({ ...acc, [key]: q?.matches || false }),
30
+ initialValues,
31
+ );
32
+ }
33
+
34
+ /** Снимок adaptive media-query (`isMobile` / `isTablet` / …). */
35
+ export const getAdaptiveMatchMedia = () =>
36
+ getMatchMediaGeneric({ queryValues: ADAPTIVE_QUERIES, initialValues: INITIAL_ADAPTIVE_QUERIES_VALUE });
@@ -0,0 +1,50 @@
1
+ import { AdaptiveBreakpoints } from '../constants/adaptive';
2
+ import { LayoutType } from '../types/layoutTypes';
3
+ import { layoutTypeFromUserAgent } from './layoutTypeFromUserAgent';
4
+ import { layoutTypeFromWidth } from './layoutTypeFromWidth';
5
+
6
+ /** Заголовок Client Hints с шириной viewport (Chromium). См. `Critical-CH` в `next.config`. */
7
+ export const SEC_CH_VIEWPORT_WIDTH_HEADER = 'sec-ch-viewport-width';
8
+
9
+ export type GetSSRInitialLayoutTypeOptions = {
10
+ /** `Sec-CH-Viewport-Width` или другое значение ширины (строка из заголовка или число в px). */
11
+ viewportWidth?: string | number | null;
12
+ /** `User-Agent` запроса для SSR-фолбэка без Client Hints. */
13
+ userAgent?: string | null;
14
+ /** Переопределение брейкпоинтов — только для ветки с `viewportWidth`. */
15
+ breakpoints?: AdaptiveBreakpoints;
16
+ };
17
+
18
+ function parseViewportWidth(viewportWidth: string | number): number | null {
19
+ const width = typeof viewportWidth === 'number' ? viewportWidth : Number(viewportWidth);
20
+
21
+ if (!Number.isFinite(width) || width <= 0) {
22
+ return null;
23
+ }
24
+
25
+ return width;
26
+ }
27
+
28
+ /**
29
+ * Стартовый `layoutType` для SSR в Next.js App Router.
30
+ *
31
+ * 1. Есть валидная ширина (Client Hints на Chromium) → каскад по брейкпоинтам (4 тира).
32
+ * 2. Иначе → `layoutTypeFromUserAgent` (mobile / tablet / desktop).
33
+ *
34
+ * Пара с `getLayoutBootstrapScript()` (pre-paint) и `useLayoutTypeState(initialLayoutType)` на клиенте.
35
+ */
36
+ export function getSSRInitialLayoutType({
37
+ viewportWidth,
38
+ userAgent,
39
+ breakpoints,
40
+ }: GetSSRInitialLayoutTypeOptions): LayoutType {
41
+ if (viewportWidth != null && viewportWidth !== '') {
42
+ const width = parseViewportWidth(viewportWidth);
43
+
44
+ if (width != null) {
45
+ return layoutTypeFromWidth(width, breakpoints);
46
+ }
47
+ }
48
+
49
+ return layoutTypeFromUserAgent(userAgent ?? '');
50
+ }