@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,15 @@
1
+ import { ReactNode } from 'react';
2
+ import { AdaptiveStore } from '../../context/adaptiveContext.js';
3
+ import { LayoutType } from '../../types/layoutTypes.js';
4
+ export type AdaptiveProviderProps = {
5
+ /** Статичная раскладка (SSR — значение на запрос, либо `useAdaptiveBootstrap()` в корне CSR). Реактивный источник — через `store`. */
6
+ layoutType?: LayoutType;
7
+ /** Внешний реактивный стор раскладки; приоритетнее `layoutType`, обновляет подписчиков без перерендера провайдера. */
8
+ store?: AdaptiveStore;
9
+ children: ReactNode;
10
+ };
11
+ /**
12
+ * Провайдер текущей раскладки для `Adaptive*`-компонентов. Ставится один раз в корне; вложенные
13
+ * `Adaptive*` берут `layoutType` из контекста. Принимает статичный `layoutType` либо реактивный `store`.
14
+ */
15
+ export declare function AdaptiveProvider({ layoutType, store, children }: AdaptiveProviderProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,14 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { staticStore } from '@cloud-ru/ds-context-kit';
3
+ import { useMemo } from 'react';
4
+ import { DEFAULT_LAYOUT_TYPE } from '../../constants/adaptive.js';
5
+ import { AdaptiveStoreProvider } from '../../context/adaptiveContext.js';
6
+ /**
7
+ * Провайдер текущей раскладки для `Adaptive*`-компонентов. Ставится один раз в корне; вложенные
8
+ * `Adaptive*` берут `layoutType` из контекста. Принимает статичный `layoutType` либо реактивный `store`.
9
+ */
10
+ export function AdaptiveProvider({ layoutType, store, children }) {
11
+ // Стабильный snapshot: новый объект только при смене layoutType, иначе useSyncExternalStore зациклится.
12
+ const staticAdaptiveStore = useMemo(() => staticStore({ layoutType: layoutType ?? DEFAULT_LAYOUT_TYPE }), [layoutType]);
13
+ return _jsx(AdaptiveStoreProvider, { store: store ?? staticAdaptiveStore, children: children });
14
+ }
@@ -0,0 +1 @@
1
+ export * from './AdaptiveProvider.js';
@@ -0,0 +1 @@
1
+ export * from './AdaptiveProvider.js';
@@ -0,0 +1,2 @@
1
+ export * from './AdaptiveProvider/index.js';
2
+ export * from './withLayoutType/index.js';
@@ -0,0 +1,2 @@
1
+ export * from './AdaptiveProvider/index.js';
2
+ export * from './withLayoutType/index.js';
@@ -0,0 +1 @@
1
+ export * from './withLayoutType.js';
@@ -0,0 +1 @@
1
+ export * from './withLayoutType.js';
@@ -0,0 +1,14 @@
1
+ import { ComponentType } from 'react';
2
+ import { LayoutType } from '../../types/layoutTypes.js';
3
+ /**
4
+ * HOC форса раскладки: оборачивает компонент в `<AdaptiveProvider layoutType=…>`, фиксируя раскладку
5
+ * для него и поддерева. Дженерик-параметры стираются (для них — инлайновый `AdaptiveProvider`).
6
+ * Вызывать на module-scope, не в теле рендера.
7
+ *
8
+ * @example
9
+ * const DesktopSection = withLayoutType(Section, 'desktop');
10
+ */
11
+ export declare function withLayoutType<P extends object>(Component: ComponentType<P>, layoutType: LayoutType): {
12
+ (props: P): import("react/jsx-runtime").JSX.Element;
13
+ displayName: string;
14
+ };
@@ -0,0 +1,17 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { AdaptiveProvider } from '../AdaptiveProvider/index.js';
3
+ /**
4
+ * HOC форса раскладки: оборачивает компонент в `<AdaptiveProvider layoutType=…>`, фиксируя раскладку
5
+ * для него и поддерева. Дженерик-параметры стираются (для них — инлайновый `AdaptiveProvider`).
6
+ * Вызывать на module-scope, не в теле рендера.
7
+ *
8
+ * @example
9
+ * const DesktopSection = withLayoutType(Section, 'desktop');
10
+ */
11
+ export function withLayoutType(Component, layoutType) {
12
+ function Fixed(props) {
13
+ return (_jsx(AdaptiveProvider, { layoutType: layoutType, children: _jsx(Component, { ...props }) }));
14
+ }
15
+ Fixed.displayName = `withLayoutType(${Component.displayName ?? Component.name}, ${layoutType})`;
16
+ return Fixed;
17
+ }
@@ -0,0 +1,57 @@
1
+ import { LayoutType } from '../types/layoutTypes.js';
2
+ /** Брейкпоинты adaptive-раскладки (max-width в px). Форма дефолта `ADAPTIVE_BREAKPOINT`. */
3
+ export type AdaptiveBreakpoints = {
4
+ mobile: number;
5
+ tablet: number;
6
+ desktopSmall: number;
7
+ desktop: number;
8
+ };
9
+ /** Брейкпоинты adaptive-раскладки (max-width в px), по которым `useAdaptiveBootstrap` выбирает `layoutType`. */
10
+ export declare const ADAPTIVE_BREAKPOINT: AdaptiveBreakpoints;
11
+ /** CSS media-query строки, собранные из `ADAPTIVE_BREAKPOINT`. */
12
+ export declare const CSS_BREAKPOINTS: {
13
+ readonly mobile: `(max-width: ${number}px)`;
14
+ readonly tablet: `(max-width: ${number}px)`;
15
+ readonly desktopSmall: `(max-width: ${number}px)`;
16
+ readonly desktop: `(max-width: ${number}px)`;
17
+ readonly large: `(min-width: ${number}px)`;
18
+ };
19
+ /** Ключи media-query, отслеживаемых `useAdaptiveMatchMedia`. */
20
+ export declare const ADAPTIVE_QUERY: {
21
+ readonly IsMobile: "isMobile";
22
+ readonly IsTablet: "isTablet";
23
+ readonly IsSmallDesktop: "isSmallDesktop";
24
+ readonly IsDesktop: "isDesktop";
25
+ readonly IsLarge: "isLarge";
26
+ };
27
+ /** Карта `query-key → media-query строка` для подписки. */
28
+ export declare const ADAPTIVE_QUERIES: {
29
+ readonly isMobile: `(max-width: ${number}px)`;
30
+ readonly isTablet: `(max-width: ${number}px)`;
31
+ readonly isSmallDesktop: `(max-width: ${number}px)`;
32
+ readonly isDesktop: `(max-width: ${number}px)`;
33
+ readonly isLarge: `(min-width: ${number}px)`;
34
+ };
35
+ /** Собирает карту adaptive media-query из произвольных брейкпоинтов — для per-app override. */
36
+ export declare function buildAdaptiveQueries(breakpoints: AdaptiveBreakpoints): {
37
+ isMobile: string;
38
+ isTablet: string;
39
+ isSmallDesktop: string;
40
+ isDesktop: string;
41
+ isLarge: string;
42
+ };
43
+ /** SSR-safe начальные значения (на сервере ни один media-query не матчится). */
44
+ export declare const INITIAL_ADAPTIVE_QUERIES_VALUE: {
45
+ readonly isMobile: false;
46
+ readonly isTablet: false;
47
+ readonly isSmallDesktop: false;
48
+ readonly isDesktop: false;
49
+ readonly isLarge: false;
50
+ };
51
+ /** SSR-baseline раскладки адаптивных компонентов: на сервере и до mount — desktop. */
52
+ export declare const DEFAULT_LAYOUT_TYPE: LayoutType;
53
+ /** Наборы `layoutType`, уходящие по mobile-ветке surface-swap. Один источник для runtime, stories и docs. */
54
+ export declare const LAYOUT_SPLIT_MOBILE_TIERS: {
55
+ /** Только phone уходит в mobile-ветку. */
56
+ readonly mobileOnly: readonly ["mobile"];
57
+ };
@@ -0,0 +1,57 @@
1
+ import { LAYOUT_TYPE } from '../types/layoutTypes.js';
2
+ /** Брейкпоинты adaptive-раскладки (max-width в px), по которым `useAdaptiveBootstrap` выбирает `layoutType`. */
3
+ export const ADAPTIVE_BREAKPOINT = {
4
+ mobile: 767,
5
+ tablet: 1023,
6
+ desktopSmall: 1279,
7
+ desktop: 1439,
8
+ };
9
+ /** CSS media-query строки, собранные из `ADAPTIVE_BREAKPOINT`. */
10
+ export const CSS_BREAKPOINTS = {
11
+ mobile: `(max-width: ${ADAPTIVE_BREAKPOINT.mobile}px)`,
12
+ tablet: `(max-width: ${ADAPTIVE_BREAKPOINT.tablet}px)`,
13
+ desktopSmall: `(max-width: ${ADAPTIVE_BREAKPOINT.desktopSmall}px)`,
14
+ desktop: `(max-width: ${ADAPTIVE_BREAKPOINT.desktop}px)`,
15
+ large: `(min-width: ${ADAPTIVE_BREAKPOINT.desktop + 1}px)`,
16
+ };
17
+ /** Ключи media-query, отслеживаемых `useAdaptiveMatchMedia`. */
18
+ export const ADAPTIVE_QUERY = {
19
+ IsMobile: 'isMobile',
20
+ IsTablet: 'isTablet',
21
+ IsSmallDesktop: 'isSmallDesktop',
22
+ IsDesktop: 'isDesktop',
23
+ IsLarge: 'isLarge',
24
+ };
25
+ /** Карта `query-key → media-query строка` для подписки. */
26
+ export const ADAPTIVE_QUERIES = {
27
+ [ADAPTIVE_QUERY.IsMobile]: CSS_BREAKPOINTS.mobile,
28
+ [ADAPTIVE_QUERY.IsTablet]: CSS_BREAKPOINTS.tablet,
29
+ [ADAPTIVE_QUERY.IsSmallDesktop]: CSS_BREAKPOINTS.desktopSmall,
30
+ [ADAPTIVE_QUERY.IsDesktop]: CSS_BREAKPOINTS.desktop,
31
+ [ADAPTIVE_QUERY.IsLarge]: CSS_BREAKPOINTS.large,
32
+ };
33
+ /** Собирает карту adaptive media-query из произвольных брейкпоинтов — для per-app override. */
34
+ export function buildAdaptiveQueries(breakpoints) {
35
+ return {
36
+ [ADAPTIVE_QUERY.IsMobile]: `(max-width: ${breakpoints.mobile}px)`,
37
+ [ADAPTIVE_QUERY.IsTablet]: `(max-width: ${breakpoints.tablet}px)`,
38
+ [ADAPTIVE_QUERY.IsSmallDesktop]: `(max-width: ${breakpoints.desktopSmall}px)`,
39
+ [ADAPTIVE_QUERY.IsDesktop]: `(max-width: ${breakpoints.desktop}px)`,
40
+ [ADAPTIVE_QUERY.IsLarge]: `(min-width: ${breakpoints.desktop + 1}px)`,
41
+ };
42
+ }
43
+ /** SSR-safe начальные значения (на сервере ни один media-query не матчится). */
44
+ export const INITIAL_ADAPTIVE_QUERIES_VALUE = {
45
+ [ADAPTIVE_QUERY.IsMobile]: false,
46
+ [ADAPTIVE_QUERY.IsTablet]: false,
47
+ [ADAPTIVE_QUERY.IsSmallDesktop]: false,
48
+ [ADAPTIVE_QUERY.IsDesktop]: false,
49
+ [ADAPTIVE_QUERY.IsLarge]: false,
50
+ };
51
+ /** SSR-baseline раскладки адаптивных компонентов: на сервере и до mount — desktop. */
52
+ export const DEFAULT_LAYOUT_TYPE = LAYOUT_TYPE.Desktop;
53
+ /** Наборы `layoutType`, уходящие по mobile-ветке surface-swap. Один источник для runtime, stories и docs. */
54
+ export const LAYOUT_SPLIT_MOBILE_TIERS = {
55
+ /** Только phone уходит в mobile-ветку. */
56
+ mobileOnly: [LAYOUT_TYPE.Mobile],
57
+ };
@@ -0,0 +1 @@
1
+ export * from './adaptive.js';
@@ -0,0 +1 @@
1
+ export * from './adaptive.js';
@@ -0,0 +1,15 @@
1
+ import { ExternalStore } from '@cloud-ru/ds-context-kit';
2
+ import { LayoutType } from '../types/layoutTypes.js';
3
+ /** Значение adaptive-контекста: текущая раскладка. */
4
+ export type AdaptiveContextValue = {
5
+ layoutType: LayoutType;
6
+ };
7
+ /** Внешний стор раскладки (формат `useSyncExternalStore`). Адаптер над любым реактивным источником — см. `createAdaptiveStore`. */
8
+ export type AdaptiveStore = ExternalStore<AdaptiveContextValue>;
9
+ declare const StoreProvider: ({ store, children }: {
10
+ store: ExternalStore<AdaptiveContextValue>;
11
+ children: import("react").ReactNode;
12
+ }) => import("react/jsx-runtime").JSX.Element;
13
+ export { StoreProvider as AdaptiveStoreProvider };
14
+ /** Возвращает текущую раскладку из `AdaptiveProvider`. Реактивно к внешнему стору, если он задан. */
15
+ export declare function useAdaptiveLayout(): AdaptiveContextValue;
@@ -0,0 +1,11 @@
1
+ import { createSharedStoreContext } from '@cloud-ru/ds-context-kit';
2
+ import { ADAPTIVE_KEYS } from '../keys.js';
3
+ import { getGlobalAdaptiveStore } from '../store/globalStore.js';
4
+ // Дефолт контекста = глобальный singleton-стор: потребитель без `AdaptiveProvider` в своём дереве
5
+ // читает раскладку, выставленную шеллом в `getGlobalAdaptiveStore`. Явный `<AdaptiveProvider>` затеняет дефолт.
6
+ const { StoreProvider, useStoreValue } = createSharedStoreContext(ADAPTIVE_KEYS.context, getGlobalAdaptiveStore().store);
7
+ export { StoreProvider as AdaptiveStoreProvider };
8
+ /** Возвращает текущую раскладку из `AdaptiveProvider`. Реактивно к внешнему стору, если он задан. */
9
+ export function useAdaptiveLayout() {
10
+ return useStoreValue();
11
+ }
@@ -0,0 +1,2 @@
1
+ export { useAdaptiveLayout } from './adaptiveContext.js';
2
+ export type { AdaptiveContextValue, AdaptiveStore } from './adaptiveContext.js';
@@ -0,0 +1 @@
1
+ export { useAdaptiveLayout } from './adaptiveContext.js';
@@ -0,0 +1,4 @@
1
+ export * from './useAdaptiveBootstrap.js';
2
+ export * from './useLayoutDefaults.js';
3
+ export * from './useClientLayoutType.js';
4
+ export * from './useMatchMedia.js';
@@ -0,0 +1,4 @@
1
+ export * from './useAdaptiveBootstrap.js';
2
+ export * from './useLayoutDefaults.js';
3
+ export * from './useClientLayoutType.js';
4
+ export * from './useMatchMedia.js';
@@ -0,0 +1,18 @@
1
+ import { AdaptiveBreakpoints } from '../constants/adaptive.js';
2
+ import { LayoutType } from '../types/layoutTypes.js';
3
+ export type UseAdaptiveBootstrapOptions = {
4
+ /** Переопределение брейкпоинтов (max-width в px), напр. `{ mobile: 480 }`. Меняет только пороги, набор тиров прежний. */
5
+ breakpoints?: Partial<AdaptiveBreakpoints>;
6
+ /** User-agent для SSR (на клиенте берётся из `navigator`). См. `getAdaptive`. */
7
+ userAgent?: string;
8
+ };
9
+ /**
10
+ * Возвращает текущий `layoutType` по типу устройства из user-agent + media-query. SSR-safe: до mount `desktop`.
11
+ * Вызывается один раз в корне приложения, результат передаётся в `<AdaptiveProvider layoutType={...}>`.
12
+ * Не путать с `useAdaptiveLayout` — тем читают уже посчитанную раскладку из контекста внутри компонентов.
13
+ * Для per-app порогов передайте `breakpoints` (мемоизировать объект не нужно).
14
+ * @function React hook
15
+ */
16
+ export declare function useAdaptiveBootstrap(options?: UseAdaptiveBootstrapOptions): {
17
+ layoutType: LayoutType;
18
+ };
@@ -0,0 +1,19 @@
1
+ import { useMemo } from 'react';
2
+ import { ADAPTIVE_BREAKPOINT, ADAPTIVE_QUERIES, buildAdaptiveQueries, } from '../constants/adaptive.js';
3
+ import { getAdaptive } from '../utils/getAdaptive.js';
4
+ import { useAdaptiveMatchMedia } from './useMatchMedia.js';
5
+ /**
6
+ * Возвращает текущий `layoutType` по типу устройства из user-agent + media-query. SSR-safe: до mount `desktop`.
7
+ * Вызывается один раз в корне приложения, результат передаётся в `<AdaptiveProvider layoutType={...}>`.
8
+ * Не путать с `useAdaptiveLayout` — тем читают уже посчитанную раскладку из контекста внутри компонентов.
9
+ * Для per-app порогов передайте `breakpoints` (мемоизировать объект не нужно).
10
+ * @function React hook
11
+ */
12
+ export function useAdaptiveBootstrap(options) {
13
+ const { breakpoints, userAgent } = options ?? {};
14
+ const queryValues = useMemo(() => (breakpoints ? buildAdaptiveQueries({ ...ADAPTIVE_BREAKPOINT, ...breakpoints }) : ADAPTIVE_QUERIES),
15
+ // Зависим от значений брейкпоинтов, а не от ссылки объекта — иначе инлайн-`{ mobile: 480 }` переподписывает matchMedia.
16
+ // eslint-disable-next-line react-hooks/exhaustive-deps
17
+ [breakpoints?.mobile, breakpoints?.tablet, breakpoints?.desktopSmall, breakpoints?.desktop]);
18
+ return getAdaptive(useAdaptiveMatchMedia(queryValues), userAgent);
19
+ }
@@ -0,0 +1,10 @@
1
+ import { AdaptiveBreakpoints } from '../constants/adaptive.js';
2
+ import { LayoutType } from '../types/index.js';
3
+ /**
4
+ * Раскладка с коррекцией ДО первой отрисовки. Старт — `initialLayoutType` с сервера (Client Hints
5
+ * → точная ширина на Chromium; иначе desktop), поэтому первый клиентский рендер совпадает с SSR
6
+ * (чистая гидратация). Уточнение по media-query — в `useLayoutEffect` (синхронно перед paint), а не
7
+ * в `useEffect`: на узком окне в FF/Safari переключение происходит до отрисовки, без видимого прыжка.
8
+ * `<html data-layout-type>` держим синхронизированным для адаптивного CSS (его же ставит pre-paint скрипт).
9
+ */
10
+ export declare function useClientLayoutType(initialLayoutType: LayoutType, breakpoints?: AdaptiveBreakpoints): LayoutType;
@@ -0,0 +1,32 @@
1
+ import { useLayoutEffect } from '@cloud-ru/ds-utils';
2
+ import { useMemo, useState } from 'react';
3
+ import { ADAPTIVE_BREAKPOINT, ADAPTIVE_QUERIES, buildAdaptiveQueries, INITIAL_ADAPTIVE_QUERIES_VALUE, } from '../constants/adaptive.js';
4
+ import { getMatchMediaGeneric, getMediaQueryListGeneric } from '../utils/getMatchMedia.js';
5
+ import { layoutTypeFromMatchMedia } from '../utils/layoutTypeFromMatchMedia.js';
6
+ /**
7
+ * Раскладка с коррекцией ДО первой отрисовки. Старт — `initialLayoutType` с сервера (Client Hints
8
+ * → точная ширина на Chromium; иначе desktop), поэтому первый клиентский рендер совпадает с SSR
9
+ * (чистая гидратация). Уточнение по media-query — в `useLayoutEffect` (синхронно перед paint), а не
10
+ * в `useEffect`: на узком окне в FF/Safari переключение происходит до отрисовки, без видимого прыжка.
11
+ * `<html data-layout-type>` держим синхронизированным для адаптивного CSS (его же ставит pre-paint скрипт).
12
+ */
13
+ export function useClientLayoutType(initialLayoutType, breakpoints) {
14
+ const [layoutType, setLayoutType] = useState(initialLayoutType);
15
+ const queryValues = useMemo(() => (breakpoints ? buildAdaptiveQueries({ ...ADAPTIVE_BREAKPOINT, ...breakpoints }) : ADAPTIVE_QUERIES),
16
+ // Зависим от значений брейкпоинтов, а не от ссылки объекта — иначе инлайн-override переподписывает matchMedia.
17
+ // eslint-disable-next-line react-hooks/exhaustive-deps
18
+ [breakpoints?.mobile, breakpoints?.tablet, breakpoints?.desktopSmall, breakpoints?.desktop]);
19
+ useLayoutEffect(() => {
20
+ const apply = () => {
21
+ const next = layoutTypeFromMatchMedia(getMatchMediaGeneric({ queryValues, initialValues: INITIAL_ADAPTIVE_QUERIES_VALUE }));
22
+ document.documentElement.dataset.layoutType = next;
23
+ setLayoutType(next);
24
+ };
25
+ apply();
26
+ const handler = () => apply();
27
+ const mediaQueryList = getMediaQueryListGeneric({ queryValues });
28
+ mediaQueryList.forEach(([, mql]) => mql.addEventListener('change', handler));
29
+ return () => mediaQueryList.forEach(([, mql]) => mql.removeEventListener('change', handler));
30
+ }, [queryValues]);
31
+ return layoutType;
32
+ }
@@ -0,0 +1,14 @@
1
+ import { LayoutPresets } from '../types/presets.js';
2
+ /**
3
+ * React-хук preset-класса адаптивности: резолвит дефолты пропов по раскладке из `AdaptiveProvider`.
4
+ * desktop-first приоритет: пресет раскладки (instance > DS) > явный проп инстанса > базовый дефолт.
5
+ * Preset-участвующие пропы передавай в `explicit` без destructure-дефолта.
6
+ *
7
+ * @example
8
+ * const { collapsible } = useLayoutDefaults(
9
+ * { collapsible: false }, // база (desktop)
10
+ * mergePresets(ALERT_TOP_LAYOUT_PRESETS, layoutPresets), // DS-пресет ⊕ instance-override
11
+ * { collapsible }, // явный проп инстанса = desktop-значение (может быть undefined)
12
+ * );
13
+ */
14
+ export declare function useLayoutDefaults<P extends object>(base: P, presets: LayoutPresets<P>, explicit: Partial<P>): P;
@@ -0,0 +1,18 @@
1
+ import { useAdaptiveLayout } from '../context/adaptiveContext.js';
2
+ import { resolveByLayout } from '../utils/resolveByLayout.js';
3
+ /**
4
+ * React-хук preset-класса адаптивности: резолвит дефолты пропов по раскладке из `AdaptiveProvider`.
5
+ * desktop-first приоритет: пресет раскладки (instance > DS) > явный проп инстанса > базовый дефолт.
6
+ * Preset-участвующие пропы передавай в `explicit` без destructure-дефолта.
7
+ *
8
+ * @example
9
+ * const { collapsible } = useLayoutDefaults(
10
+ * { collapsible: false }, // база (desktop)
11
+ * mergePresets(ALERT_TOP_LAYOUT_PRESETS, layoutPresets), // DS-пресет ⊕ instance-override
12
+ * { collapsible }, // явный проп инстанса = desktop-значение (может быть undefined)
13
+ * );
14
+ */
15
+ export function useLayoutDefaults(base, presets, explicit) {
16
+ const { layoutType } = useAdaptiveLayout();
17
+ return resolveByLayout({ layoutType, base, presets, explicit });
18
+ }
@@ -0,0 +1,18 @@
1
+ import { AdaptiveQuery, MatchMediaGeneric } from '../types/adaptive.js';
2
+ /**
3
+ * Подписывается на набор media-query и возвращает их состояние (`query-key → matched?`).
4
+ * SSR-safe: первый рендер — и на сервере, и при гидрации на клиенте — берёт `initialValues`, что
5
+ * совпадает с серверным HTML и не даёт hydration mismatch. Реальное состояние media-query читается
6
+ * уже после mount в `useLayoutEffect` (синхронно, до paint — без видимого скачка), там же — подписка
7
+ * на `change`.
8
+ * @function React hook
9
+ */
10
+ export declare const useMatchMediaGeneric: <T extends string>({ queryValues, initialValues, }: {
11
+ queryValues: Record<T, string>;
12
+ initialValues: MatchMediaGeneric<T>;
13
+ }) => MatchMediaGeneric<T>;
14
+ /**
15
+ * Состояние adaptive media-query (`isMobile` / `isTablet` / …). По умолчанию — дефолтные брейкпоинты DS.
16
+ * Для per-app override передайте свою карту запросов; она должна быть стабильной по ссылке.
17
+ */
18
+ export declare function useAdaptiveMatchMedia(queryValues?: Record<AdaptiveQuery, string>): MatchMediaGeneric<AdaptiveQuery>;
@@ -0,0 +1,37 @@
1
+ import { useLayoutEffect } from '@cloud-ru/ds-utils';
2
+ import { useState } from 'react';
3
+ import { ADAPTIVE_QUERIES, INITIAL_ADAPTIVE_QUERIES_VALUE } from '../constants/adaptive.js';
4
+ import { getMatchMediaGeneric, getMediaQueryListGeneric } from '../utils/getMatchMedia.js';
5
+ /**
6
+ * Подписывается на набор media-query и возвращает их состояние (`query-key → matched?`).
7
+ * SSR-safe: первый рендер — и на сервере, и при гидрации на клиенте — берёт `initialValues`, что
8
+ * совпадает с серверным HTML и не даёт hydration mismatch. Реальное состояние media-query читается
9
+ * уже после mount в `useLayoutEffect` (синхронно, до paint — без видимого скачка), там же — подписка
10
+ * на `change`.
11
+ * @function React hook
12
+ */
13
+ export const useMatchMediaGeneric = ({ queryValues, initialValues, }) => {
14
+ const [value, setValue] = useState(initialValues);
15
+ useLayoutEffect(() => {
16
+ const read = () => getMatchMediaGeneric({ queryValues, initialValues });
17
+ // Синхронизируемся с реальным matchMedia на клиенте — устраняем рассинхрон с SSR-initialValues.
18
+ setValue(read());
19
+ const handler = () => setValue(read());
20
+ const mediaQueryList = getMediaQueryListGeneric({ queryValues });
21
+ mediaQueryList.forEach(([, mql]) => mql.addEventListener('change', handler));
22
+ return () => mediaQueryList.forEach(([, mql]) => mql.removeEventListener('change', handler));
23
+ // queryValues/initialValues стабильны по ссылке (useAdaptiveBootstrap мемоизирует queryValues); смена
24
+ // breakpoints на лету пере-подписывает на новые media-query.
25
+ }, [queryValues, initialValues]);
26
+ return value;
27
+ };
28
+ /**
29
+ * Состояние adaptive media-query (`isMobile` / `isTablet` / …). По умолчанию — дефолтные брейкпоинты DS.
30
+ * Для per-app override передайте свою карту запросов; она должна быть стабильной по ссылке.
31
+ */
32
+ export function useAdaptiveMatchMedia(queryValues = ADAPTIVE_QUERIES) {
33
+ return useMatchMediaGeneric({
34
+ queryValues,
35
+ initialValues: INITIAL_ADAPTIVE_QUERIES_VALUE,
36
+ });
37
+ }
@@ -0,0 +1,7 @@
1
+ export * from './components/index.js';
2
+ export * from './context/index.js';
3
+ export * from './store/index.js';
4
+ export * from './hooks/index.js';
5
+ export * from './utils/index.js';
6
+ export * from './types/index.js';
7
+ export * from './constants/index.js';
@@ -0,0 +1,7 @@
1
+ export * from './components/index.js';
2
+ export * from './context/index.js';
3
+ export * from './store/index.js';
4
+ export * from './hooks/index.js';
5
+ export * from './utils/index.js';
6
+ export * from './types/index.js';
7
+ export * from './constants/index.js';
@@ -0,0 +1,4 @@
1
+ export declare const ADAPTIVE_KEYS: {
2
+ readonly context: string;
3
+ readonly store: "@cloud-ru/ds:global-adaptive-store:v1";
4
+ };
@@ -0,0 +1,16 @@
1
+ import { providerKey } from '@cloud-ru/ds-context-kit';
2
+ /**
3
+ * `Symbol.for`-ключи домена adaptive — обе системы синглтонов в одном месте:
4
+ * - `context` — объект React-контекста (через `providerKey` → есть dev-warn о смешанных версиях);
5
+ * - `store` — глобальный мутабельный стор раскладки (кросс-root мост хост→MFE).
6
+ *
7
+ * Одна контракт-версия на домен повышается ТОЛЬКО при несовместимом сломе формы значения и двигает
8
+ * ОБА ключа вместе — забыть половину нельзя. Ортогонально мажору ПАКЕТА (разные мажоры делят ключ,
9
+ * пока shape аддитивен). Строки менять НЕЛЬЗЯ — это форк синглтона (случайный `:v2`). См.
10
+ * providers-standard.md.
11
+ */
12
+ const CONTRACT_VERSION = 1;
13
+ export const ADAPTIVE_KEYS = {
14
+ context: providerKey('adaptive-context', CONTRACT_VERSION),
15
+ store: `@cloud-ru/ds:global-adaptive-store:v${CONTRACT_VERSION}`,
16
+ };
@@ -0,0 +1,10 @@
1
+ export * from './constants/adaptive.js';
2
+ export * from './types/layoutTypes.js';
3
+ export * from './types/presets.js';
4
+ export * from './utils/getAdaptive.js';
5
+ export * from './utils/getLayoutBootstrapScript.js';
6
+ export * from './utils/getSSRInitialLayoutType.js';
7
+ export * from './utils/getUserAgentInfo.js';
8
+ export * from './utils/layoutTypeFromUserAgent.js';
9
+ export * from './utils/resolveByLayout.js';
10
+ export * from './utils/resolveLayoutType.js';
@@ -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.js';
8
+ export * from './types/layoutTypes.js';
9
+ export * from './types/presets.js';
10
+ export * from './utils/getAdaptive.js';
11
+ export * from './utils/getLayoutBootstrapScript.js';
12
+ export * from './utils/getSSRInitialLayoutType.js';
13
+ export * from './utils/getUserAgentInfo.js';
14
+ export * from './utils/layoutTypeFromUserAgent.js';
15
+ export * from './utils/resolveByLayout.js';
16
+ export * from './utils/resolveLayoutType.js';
@@ -0,0 +1,22 @@
1
+ import { AdaptiveStore } from '../context/adaptiveContext.js';
2
+ import { LayoutType } from '../types/layoutTypes.js';
3
+ export type CreateAdaptiveStoreOptions = {
4
+ /** Текущая раскладка из внешнего источника. */
5
+ getLayoutType(): LayoutType;
6
+ /** Подписка на изменения внешнего источника; возвращает функцию отписки. */
7
+ subscribe(onChange: () => void): () => void;
8
+ /** Раскладка для SSR (request-scoped). Нужен только при server-render; в чистом CSR — нет. */
9
+ getServerLayoutType?(): LayoutType;
10
+ };
11
+ /**
12
+ * Адаптер внешнего реактивного источника раскладки (redux / zustand / signals / observable) в
13
+ * `AdaptiveStore` (формат `useSyncExternalStore`) для `<AdaptiveProvider store={...} />`.
14
+ * Кэширует snapshot по `layoutType` ради стабильной ссылки.
15
+ *
16
+ * @example
17
+ * const adaptiveStore = createAdaptiveStore({
18
+ * getLayoutType: () => layoutSource.current,
19
+ * subscribe: (onChange) => layoutSource.on('change', onChange),
20
+ * });
21
+ */
22
+ export declare function createAdaptiveStore(options: CreateAdaptiveStoreOptions): AdaptiveStore;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Адаптер внешнего реактивного источника раскладки (redux / zustand / signals / observable) в
3
+ * `AdaptiveStore` (формат `useSyncExternalStore`) для `<AdaptiveProvider store={...} />`.
4
+ * Кэширует snapshot по `layoutType` ради стабильной ссылки.
5
+ *
6
+ * @example
7
+ * const adaptiveStore = createAdaptiveStore({
8
+ * getLayoutType: () => layoutSource.current,
9
+ * subscribe: (onChange) => layoutSource.on('change', onChange),
10
+ * });
11
+ */
12
+ export function createAdaptiveStore(options) {
13
+ let cache;
14
+ const read = (layoutType) => {
15
+ if (!cache || cache.layoutType !== layoutType) {
16
+ cache = { layoutType };
17
+ }
18
+ return cache;
19
+ };
20
+ const { getServerLayoutType } = options;
21
+ return {
22
+ subscribe: options.subscribe,
23
+ getSnapshot: () => read(options.getLayoutType()),
24
+ getServerSnapshot: getServerLayoutType ? () => read(getServerLayoutType()) : undefined,
25
+ };
26
+ }
@@ -0,0 +1,20 @@
1
+ import { AdaptiveStore } from '../context/adaptiveContext.js';
2
+ import { LayoutType } from '../types/layoutTypes.js';
3
+ export type GlobalAdaptiveStore = {
4
+ /** Стор для `<AdaptiveProvider store={...} />`. */
5
+ store: AdaptiveStore;
6
+ /** Текущая раскладка. */
7
+ getLayoutType(): LayoutType;
8
+ /** Установить раскладку и уведомить все подписанные `AdaptiveProvider`. */
9
+ setLayoutType(layoutType: LayoutType): void;
10
+ };
11
+ /**
12
+ * Глобальный singleton-стор раскладки, общий для всех React-корней процесса (микрофронты single-spa,
13
+ * острова Astro). Хранится в `globalThis` через `Symbol.for`, переживает несколько копий пакета.
14
+ * Нужен только для multi-root; при одном корне — обычный `AdaptiveProvider` или `createAdaptiveStore`.
15
+ *
16
+ * @example
17
+ * getGlobalAdaptiveStore().setLayoutType(useAdaptiveBootstrap().layoutType);
18
+ * <AdaptiveProvider store={getGlobalAdaptiveStore().store}>{root}</AdaptiveProvider>;
19
+ */
20
+ export declare function getGlobalAdaptiveStore(): GlobalAdaptiveStore;
@@ -0,0 +1,40 @@
1
+ import { DEFAULT_LAYOUT_TYPE } from '../constants/adaptive.js';
2
+ import { ADAPTIVE_KEYS } from '../keys.js';
3
+ import { createAdaptiveStore } from './createAdaptiveStore.js';
4
+ const REGISTRY_KEY = Symbol.for(ADAPTIVE_KEYS.store);
5
+ /**
6
+ * Глобальный singleton-стор раскладки, общий для всех React-корней процесса (микрофронты single-spa,
7
+ * острова Astro). Хранится в `globalThis` через `Symbol.for`, переживает несколько копий пакета.
8
+ * Нужен только для multi-root; при одном корне — обычный `AdaptiveProvider` или `createAdaptiveStore`.
9
+ *
10
+ * @example
11
+ * getGlobalAdaptiveStore().setLayoutType(useAdaptiveBootstrap().layoutType);
12
+ * <AdaptiveProvider store={getGlobalAdaptiveStore().store}>{root}</AdaptiveProvider>;
13
+ */
14
+ export function getGlobalAdaptiveStore() {
15
+ const registry = globalThis;
16
+ if (!registry[REGISTRY_KEY]) {
17
+ let currentLayout = DEFAULT_LAYOUT_TYPE;
18
+ const listeners = new Set();
19
+ registry[REGISTRY_KEY] = {
20
+ store: createAdaptiveStore({
21
+ getLayoutType: () => currentLayout,
22
+ subscribe: onChange => {
23
+ listeners.add(onChange);
24
+ return () => {
25
+ listeners.delete(onChange);
26
+ };
27
+ },
28
+ getServerLayoutType: () => DEFAULT_LAYOUT_TYPE,
29
+ }),
30
+ getLayoutType: () => currentLayout,
31
+ setLayoutType: layoutType => {
32
+ if (layoutType === currentLayout)
33
+ return;
34
+ currentLayout = layoutType;
35
+ listeners.forEach(listener => listener());
36
+ },
37
+ };
38
+ }
39
+ return registry[REGISTRY_KEY];
40
+ }