@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.
- package/CHANGELOG.md +8 -0
- package/LICENSE +201 -0
- package/README.md +195 -0
- package/dist/cjs/components/AdaptiveProvider/AdaptiveProvider.d.ts +15 -0
- package/dist/cjs/components/AdaptiveProvider/AdaptiveProvider.js +17 -0
- package/dist/cjs/components/AdaptiveProvider/index.d.ts +1 -0
- package/dist/cjs/components/AdaptiveProvider/index.js +17 -0
- package/dist/cjs/components/index.d.ts +2 -0
- package/dist/cjs/components/index.js +18 -0
- package/dist/cjs/components/withLayoutType/index.d.ts +1 -0
- package/dist/cjs/components/withLayoutType/index.js +17 -0
- package/dist/cjs/components/withLayoutType/withLayoutType.d.ts +14 -0
- package/dist/cjs/components/withLayoutType/withLayoutType.js +20 -0
- package/dist/cjs/constants/adaptive.d.ts +57 -0
- package/dist/cjs/constants/adaptive.js +61 -0
- package/dist/cjs/constants/index.d.ts +1 -0
- package/dist/cjs/constants/index.js +17 -0
- package/dist/cjs/context/adaptiveContext.d.ts +15 -0
- package/dist/cjs/context/adaptiveContext.js +15 -0
- package/dist/cjs/context/index.d.ts +2 -0
- package/dist/cjs/context/index.js +5 -0
- package/dist/cjs/hooks/index.d.ts +4 -0
- package/dist/cjs/hooks/index.js +20 -0
- package/dist/cjs/hooks/useAdaptiveBootstrap.d.ts +18 -0
- package/dist/cjs/hooks/useAdaptiveBootstrap.js +22 -0
- package/dist/cjs/hooks/useClientLayoutType.d.ts +10 -0
- package/dist/cjs/hooks/useClientLayoutType.js +35 -0
- package/dist/cjs/hooks/useLayoutDefaults.d.ts +14 -0
- package/dist/cjs/hooks/useLayoutDefaults.js +21 -0
- package/dist/cjs/hooks/useMatchMedia.d.ts +18 -0
- package/dist/cjs/hooks/useMatchMedia.js +42 -0
- package/dist/cjs/index.d.ts +7 -0
- package/dist/cjs/index.js +23 -0
- package/dist/cjs/keys.d.ts +4 -0
- package/dist/cjs/keys.js +19 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/ssr.d.ts +10 -0
- package/dist/cjs/ssr.js +32 -0
- package/dist/cjs/store/createAdaptiveStore.d.ts +22 -0
- package/dist/cjs/store/createAdaptiveStore.js +29 -0
- package/dist/cjs/store/globalStore.d.ts +20 -0
- package/dist/cjs/store/globalStore.js +43 -0
- package/dist/cjs/store/index.d.ts +2 -0
- package/dist/cjs/store/index.js +18 -0
- package/dist/cjs/types/adaptive.d.ts +6 -0
- package/dist/cjs/types/adaptive.js +2 -0
- package/dist/cjs/types/index.d.ts +3 -0
- package/dist/cjs/types/index.js +19 -0
- package/dist/cjs/types/layoutTypes.d.ts +13 -0
- package/dist/cjs/types/layoutTypes.js +10 -0
- package/dist/cjs/types/presets.d.ts +6 -0
- package/dist/cjs/types/presets.js +2 -0
- package/dist/cjs/types/valueOf.d.ts +2 -0
- package/dist/cjs/types/valueOf.js +2 -0
- package/dist/cjs/utils/getAdaptive.d.ts +15 -0
- package/dist/cjs/utils/getAdaptive.js +39 -0
- package/dist/cjs/utils/getLayoutBootstrapScript.d.ts +2 -0
- package/dist/cjs/utils/getLayoutBootstrapScript.js +9 -0
- package/dist/cjs/utils/getMatchMedia.d.ts +12 -0
- package/dist/cjs/utils/getMatchMedia.js +24 -0
- package/dist/cjs/utils/getSSRInitialLayoutType.d.ts +21 -0
- package/dist/cjs/utils/getSSRInitialLayoutType.js +32 -0
- package/dist/cjs/utils/getUserAgentInfo.d.ts +43 -0
- package/dist/cjs/utils/getUserAgentInfo.js +114 -0
- package/dist/cjs/utils/index.d.ts +6 -0
- package/dist/cjs/utils/index.js +22 -0
- package/dist/cjs/utils/isBrowser.d.ts +3 -0
- package/dist/cjs/utils/isBrowser.js +9 -0
- package/dist/cjs/utils/layoutTypeFromMatchMedia.d.ts +4 -0
- package/dist/cjs/utils/layoutTypeFromMatchMedia.js +18 -0
- package/dist/cjs/utils/layoutTypeFromUserAgent.d.ts +6 -0
- package/dist/cjs/utils/layoutTypeFromUserAgent.js +20 -0
- package/dist/cjs/utils/layoutTypeFromWidth.d.ts +3 -0
- package/dist/cjs/utils/layoutTypeFromWidth.js +18 -0
- package/dist/cjs/utils/resolveByLayout.d.ts +28 -0
- package/dist/cjs/utils/resolveByLayout.js +49 -0
- package/dist/cjs/utils/resolveLayoutType.d.ts +11 -0
- package/dist/cjs/utils/resolveLayoutType.js +19 -0
- package/dist/esm/components/AdaptiveProvider/AdaptiveProvider.d.ts +15 -0
- package/dist/esm/components/AdaptiveProvider/AdaptiveProvider.js +14 -0
- package/dist/esm/components/AdaptiveProvider/index.d.ts +1 -0
- package/dist/esm/components/AdaptiveProvider/index.js +1 -0
- package/dist/esm/components/index.d.ts +2 -0
- package/dist/esm/components/index.js +2 -0
- package/dist/esm/components/withLayoutType/index.d.ts +1 -0
- package/dist/esm/components/withLayoutType/index.js +1 -0
- package/dist/esm/components/withLayoutType/withLayoutType.d.ts +14 -0
- package/dist/esm/components/withLayoutType/withLayoutType.js +17 -0
- package/dist/esm/constants/adaptive.d.ts +57 -0
- package/dist/esm/constants/adaptive.js +57 -0
- package/dist/esm/constants/index.d.ts +1 -0
- package/dist/esm/constants/index.js +1 -0
- package/dist/esm/context/adaptiveContext.d.ts +15 -0
- package/dist/esm/context/adaptiveContext.js +11 -0
- package/dist/esm/context/index.d.ts +2 -0
- package/dist/esm/context/index.js +1 -0
- package/dist/esm/hooks/index.d.ts +4 -0
- package/dist/esm/hooks/index.js +4 -0
- package/dist/esm/hooks/useAdaptiveBootstrap.d.ts +18 -0
- package/dist/esm/hooks/useAdaptiveBootstrap.js +19 -0
- package/dist/esm/hooks/useClientLayoutType.d.ts +10 -0
- package/dist/esm/hooks/useClientLayoutType.js +32 -0
- package/dist/esm/hooks/useLayoutDefaults.d.ts +14 -0
- package/dist/esm/hooks/useLayoutDefaults.js +18 -0
- package/dist/esm/hooks/useMatchMedia.d.ts +18 -0
- package/dist/esm/hooks/useMatchMedia.js +37 -0
- package/dist/esm/index.d.ts +7 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/keys.d.ts +4 -0
- package/dist/esm/keys.js +16 -0
- package/dist/esm/ssr.d.ts +10 -0
- package/dist/esm/ssr.js +16 -0
- package/dist/esm/store/createAdaptiveStore.d.ts +22 -0
- package/dist/esm/store/createAdaptiveStore.js +26 -0
- package/dist/esm/store/globalStore.d.ts +20 -0
- package/dist/esm/store/globalStore.js +40 -0
- package/dist/esm/store/index.d.ts +2 -0
- package/dist/esm/store/index.js +2 -0
- package/dist/esm/types/adaptive.d.ts +6 -0
- package/dist/esm/types/adaptive.js +1 -0
- package/dist/esm/types/index.d.ts +3 -0
- package/dist/esm/types/index.js +3 -0
- package/dist/esm/types/layoutTypes.d.ts +13 -0
- package/dist/esm/types/layoutTypes.js +7 -0
- package/dist/esm/types/presets.d.ts +6 -0
- package/dist/esm/types/presets.js +1 -0
- package/dist/esm/types/valueOf.d.ts +2 -0
- package/dist/esm/types/valueOf.js +1 -0
- package/dist/esm/utils/getAdaptive.d.ts +15 -0
- package/dist/esm/utils/getAdaptive.js +36 -0
- package/dist/esm/utils/getLayoutBootstrapScript.d.ts +2 -0
- package/dist/esm/utils/getLayoutBootstrapScript.js +6 -0
- package/dist/esm/utils/getMatchMedia.d.ts +12 -0
- package/dist/esm/utils/getMatchMedia.js +18 -0
- package/dist/esm/utils/getSSRInitialLayoutType.d.ts +21 -0
- package/dist/esm/utils/getSSRInitialLayoutType.js +28 -0
- package/dist/esm/utils/getUserAgentInfo.d.ts +43 -0
- package/dist/esm/utils/getUserAgentInfo.js +110 -0
- package/dist/esm/utils/index.d.ts +6 -0
- package/dist/esm/utils/index.js +6 -0
- package/dist/esm/utils/isBrowser.d.ts +3 -0
- package/dist/esm/utils/isBrowser.js +6 -0
- package/dist/esm/utils/layoutTypeFromMatchMedia.d.ts +4 -0
- package/dist/esm/utils/layoutTypeFromMatchMedia.js +15 -0
- package/dist/esm/utils/layoutTypeFromUserAgent.d.ts +6 -0
- package/dist/esm/utils/layoutTypeFromUserAgent.js +17 -0
- package/dist/esm/utils/layoutTypeFromWidth.d.ts +3 -0
- package/dist/esm/utils/layoutTypeFromWidth.js +15 -0
- package/dist/esm/utils/resolveByLayout.d.ts +28 -0
- package/dist/esm/utils/resolveByLayout.js +45 -0
- package/dist/esm/utils/resolveLayoutType.d.ts +11 -0
- package/dist/esm/utils/resolveLayoutType.js +15 -0
- package/dist/tsconfig.cjs.tsbuildinfo +1 -0
- package/dist/tsconfig.esm.tsbuildinfo +1 -0
- package/package.json +45 -0
- package/src/components/AdaptiveProvider/AdaptiveProvider.tsx +28 -0
- package/src/components/AdaptiveProvider/index.ts +1 -0
- package/src/components/index.ts +2 -0
- package/src/components/withLayoutType/index.ts +1 -0
- package/src/components/withLayoutType/withLayoutType.tsx +26 -0
- package/src/constants/adaptive.ts +73 -0
- package/src/constants/index.ts +1 -0
- package/src/context/adaptiveContext.ts +27 -0
- package/src/context/index.ts +2 -0
- package/src/hooks/index.ts +4 -0
- package/src/hooks/useAdaptiveBootstrap.ts +38 -0
- package/src/hooks/useClientLayoutType.ts +51 -0
- package/src/hooks/useLayoutDefaults.ts +21 -0
- package/src/hooks/useMatchMedia.ts +52 -0
- package/src/index.ts +7 -0
- package/src/keys.ts +18 -0
- package/src/ssr.ts +16 -0
- package/src/store/createAdaptiveStore.ts +42 -0
- package/src/store/globalStore.ts +57 -0
- package/src/store/index.ts +2 -0
- package/src/types/adaptive.ts +8 -0
- package/src/types/index.ts +3 -0
- package/src/types/layoutTypes.ts +15 -0
- package/src/types/presets.ts +7 -0
- package/src/types/valueOf.ts +2 -0
- package/src/utils/getAdaptive.ts +46 -0
- package/src/utils/getLayoutBootstrapScript.ts +8 -0
- package/src/utils/getMatchMedia.ts +36 -0
- package/src/utils/getSSRInitialLayoutType.ts +50 -0
- package/src/utils/getUserAgentInfo.ts +145 -0
- package/src/utils/index.ts +6 -0
- package/src/utils/isBrowser.ts +6 -0
- package/src/utils/layoutTypeFromMatchMedia.ts +20 -0
- package/src/utils/layoutTypeFromUserAgent.ts +19 -0
- package/src/utils/layoutTypeFromWidth.ts +20 -0
- package/src/utils/resolveByLayout.ts +72 -0
- package/src/utils/resolveLayoutType.ts +18 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./layoutTypes"), exports);
|
|
18
|
+
__exportStar(require("./adaptive"), exports);
|
|
19
|
+
__exportStar(require("./presets"), exports);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ValueOf } from './valueOf';
|
|
2
|
+
/** Константы типов раскладки adaptive-компонентов (mobile / tablet / desktopSmall / desktop). */
|
|
3
|
+
export declare const LAYOUT_TYPE: {
|
|
4
|
+
readonly Desktop: "desktop";
|
|
5
|
+
readonly DesktopSmall: "desktopSmall";
|
|
6
|
+
readonly Tablet: "tablet";
|
|
7
|
+
readonly Mobile: "mobile";
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Union типов раскладки adaptive-компонентов
|
|
11
|
+
* @function type
|
|
12
|
+
*/
|
|
13
|
+
export type LayoutType = ValueOf<typeof LAYOUT_TYPE>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LAYOUT_TYPE = void 0;
|
|
4
|
+
/** Константы типов раскладки adaptive-компонентов (mobile / tablet / desktopSmall / desktop). */
|
|
5
|
+
exports.LAYOUT_TYPE = {
|
|
6
|
+
Desktop: 'desktop',
|
|
7
|
+
DesktopSmall: 'desktopSmall',
|
|
8
|
+
Tablet: 'tablet',
|
|
9
|
+
Mobile: 'mobile',
|
|
10
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { LayoutType } from './layoutTypes';
|
|
2
|
+
/**
|
|
3
|
+
* Карта пресетов дефолтов по раскладке: для каждого `layoutType` — частичный набор пропов поверх
|
|
4
|
+
* базовых дефолтов. Обычно непуст только `mobile`. Резолв — `resolveByLayout` / `useLayoutDefaults`.
|
|
5
|
+
*/
|
|
6
|
+
export type LayoutPresets<P> = Partial<Record<LayoutType, Partial<P>>>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AdaptiveQuery, MatchMediaGeneric } from '../types/adaptive';
|
|
2
|
+
import { LayoutType } from '../types/layoutTypes';
|
|
3
|
+
/**
|
|
4
|
+
* Вычисляет `layoutType` по типу устройства из user-agent + media-query (гибрид «UA + ширина»):
|
|
5
|
+
* - `mobile` → всегда `mobile`;
|
|
6
|
+
* - `tablet` → `mobile` при узком окне (`isTablet`), иначе `tablet`;
|
|
7
|
+
* - desktop / неизвестное → каскад по ширине: `isMobile` → `mobile`, `isTablet` → `tablet`,
|
|
8
|
+
* `isSmallDesktop` → `desktopSmall`, иначе `desktop`.
|
|
9
|
+
*
|
|
10
|
+
* SSR: передайте `userAgent` из заголовка запроса для корректной ветки в HTML без скачка после
|
|
11
|
+
* гидрации; media-query на сервере нет → `INITIAL_ADAPTIVE_QUERIES_VALUE`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function getAdaptive(matchMedia: MatchMediaGeneric<AdaptiveQuery>, userAgent?: string): {
|
|
14
|
+
layoutType: LayoutType;
|
|
15
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getAdaptive = getAdaptive;
|
|
4
|
+
const adaptive_1 = require("../constants/adaptive");
|
|
5
|
+
const layoutTypes_1 = require("../types/layoutTypes");
|
|
6
|
+
const getUserAgentInfo_1 = require("./getUserAgentInfo");
|
|
7
|
+
/**
|
|
8
|
+
* Вычисляет `layoutType` по типу устройства из user-agent + media-query (гибрид «UA + ширина»):
|
|
9
|
+
* - `mobile` → всегда `mobile`;
|
|
10
|
+
* - `tablet` → `mobile` при узком окне (`isTablet`), иначе `tablet`;
|
|
11
|
+
* - desktop / неизвестное → каскад по ширине: `isMobile` → `mobile`, `isTablet` → `tablet`,
|
|
12
|
+
* `isSmallDesktop` → `desktopSmall`, иначе `desktop`.
|
|
13
|
+
*
|
|
14
|
+
* SSR: передайте `userAgent` из заголовка запроса для корректной ветки в HTML без скачка после
|
|
15
|
+
* гидрации; media-query на сервере нет → `INITIAL_ADAPTIVE_QUERIES_VALUE`.
|
|
16
|
+
*/
|
|
17
|
+
function getAdaptive(matchMedia, userAgent) {
|
|
18
|
+
const { device } = (0, getUserAgentInfo_1.getUserAgentInfo)(userAgent);
|
|
19
|
+
const isMobile = matchMedia[adaptive_1.ADAPTIVE_QUERY.IsMobile];
|
|
20
|
+
const isTablet = matchMedia[adaptive_1.ADAPTIVE_QUERY.IsTablet];
|
|
21
|
+
const isSmallDesktop = matchMedia[adaptive_1.ADAPTIVE_QUERY.IsSmallDesktop];
|
|
22
|
+
if (device.type === 'mobile') {
|
|
23
|
+
return { layoutType: layoutTypes_1.LAYOUT_TYPE.Mobile };
|
|
24
|
+
}
|
|
25
|
+
if (device.type === 'tablet') {
|
|
26
|
+
return { layoutType: isTablet ? layoutTypes_1.LAYOUT_TYPE.Mobile : layoutTypes_1.LAYOUT_TYPE.Tablet };
|
|
27
|
+
}
|
|
28
|
+
// desktop / неизвестное устройство — каскад по ширине через все пороги.
|
|
29
|
+
if (isMobile) {
|
|
30
|
+
return { layoutType: layoutTypes_1.LAYOUT_TYPE.Mobile };
|
|
31
|
+
}
|
|
32
|
+
if (isTablet) {
|
|
33
|
+
return { layoutType: layoutTypes_1.LAYOUT_TYPE.Tablet };
|
|
34
|
+
}
|
|
35
|
+
if (isSmallDesktop) {
|
|
36
|
+
return { layoutType: layoutTypes_1.LAYOUT_TYPE.DesktopSmall };
|
|
37
|
+
}
|
|
38
|
+
return { layoutType: layoutTypes_1.LAYOUT_TYPE.Desktop };
|
|
39
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getLayoutBootstrapScript = getLayoutBootstrapScript;
|
|
4
|
+
const adaptive_1 = require("../constants/adaptive");
|
|
5
|
+
const layoutTypes_1 = require("../types/layoutTypes");
|
|
6
|
+
function getLayoutBootstrapScript(breakpoints) {
|
|
7
|
+
const queries = (0, adaptive_1.buildAdaptiveQueries)({ ...adaptive_1.ADAPTIVE_BREAKPOINT, ...breakpoints });
|
|
8
|
+
return `(function(){try{var d=document.documentElement;if(matchMedia('${queries.isMobile}').matches){d.dataset.layoutType='${layoutTypes_1.LAYOUT_TYPE.Mobile}';}else if(matchMedia('${queries.isTablet}').matches){d.dataset.layoutType='${layoutTypes_1.LAYOUT_TYPE.Tablet}';}else if(matchMedia('${queries.isSmallDesktop}').matches){d.dataset.layoutType='${layoutTypes_1.LAYOUT_TYPE.DesktopSmall}';}else{d.dataset.layoutType='${layoutTypes_1.LAYOUT_TYPE.Desktop}';}}catch(e){}})();`;
|
|
9
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { MatchMediaGeneric } from '../types/adaptive';
|
|
2
|
+
/** Возвращает пары `[query-key, MediaQueryList]` для подписки на `change`. */
|
|
3
|
+
export declare function getMediaQueryListGeneric<T extends string>({ queryValues }: {
|
|
4
|
+
queryValues: Record<T, string>;
|
|
5
|
+
}): Array<[T, MediaQueryList]>;
|
|
6
|
+
/** Снимок текущего состояния media-query (`query-key → matched?`); SSR → `initialValues`. */
|
|
7
|
+
export declare function getMatchMediaGeneric<T extends string>({ queryValues, initialValues, }: {
|
|
8
|
+
queryValues: Record<T, string>;
|
|
9
|
+
initialValues: MatchMediaGeneric<T>;
|
|
10
|
+
}): MatchMediaGeneric<T>;
|
|
11
|
+
/** Снимок adaptive media-query (`isMobile` / `isTablet` / …). */
|
|
12
|
+
export declare const getAdaptiveMatchMedia: () => MatchMediaGeneric<"isMobile" | "isTablet" | "isSmallDesktop" | "isDesktop" | "isLarge">;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getAdaptiveMatchMedia = void 0;
|
|
4
|
+
exports.getMediaQueryListGeneric = getMediaQueryListGeneric;
|
|
5
|
+
exports.getMatchMediaGeneric = getMatchMediaGeneric;
|
|
6
|
+
const adaptive_1 = require("../constants/adaptive");
|
|
7
|
+
const isBrowser_1 = require("./isBrowser");
|
|
8
|
+
function getMediaQueries({ queryValues }) {
|
|
9
|
+
return Object.keys(queryValues).reduce((acc, key) => ({
|
|
10
|
+
...acc,
|
|
11
|
+
[key]: (0, isBrowser_1.isBrowser)() ? globalThis.matchMedia(queryValues[key]) : undefined,
|
|
12
|
+
}), {});
|
|
13
|
+
}
|
|
14
|
+
/** Возвращает пары `[query-key, MediaQueryList]` для подписки на `change`. */
|
|
15
|
+
function getMediaQueryListGeneric({ queryValues }) {
|
|
16
|
+
return Object.entries(getMediaQueries({ queryValues }));
|
|
17
|
+
}
|
|
18
|
+
/** Снимок текущего состояния media-query (`query-key → matched?`); SSR → `initialValues`. */
|
|
19
|
+
function getMatchMediaGeneric({ queryValues, initialValues, }) {
|
|
20
|
+
return getMediaQueryListGeneric({ queryValues }).reduce((acc, [key, q]) => ({ ...acc, [key]: q?.matches || false }), initialValues);
|
|
21
|
+
}
|
|
22
|
+
/** Снимок adaptive media-query (`isMobile` / `isTablet` / …). */
|
|
23
|
+
const getAdaptiveMatchMedia = () => getMatchMediaGeneric({ queryValues: adaptive_1.ADAPTIVE_QUERIES, initialValues: adaptive_1.INITIAL_ADAPTIVE_QUERIES_VALUE });
|
|
24
|
+
exports.getAdaptiveMatchMedia = getAdaptiveMatchMedia;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { AdaptiveBreakpoints } from '../constants/adaptive';
|
|
2
|
+
import { LayoutType } from '../types/layoutTypes';
|
|
3
|
+
/** Заголовок Client Hints с шириной viewport (Chromium). См. `Critical-CH` в `next.config`. */
|
|
4
|
+
export declare const SEC_CH_VIEWPORT_WIDTH_HEADER = "sec-ch-viewport-width";
|
|
5
|
+
export type GetSSRInitialLayoutTypeOptions = {
|
|
6
|
+
/** `Sec-CH-Viewport-Width` или другое значение ширины (строка из заголовка или число в px). */
|
|
7
|
+
viewportWidth?: string | number | null;
|
|
8
|
+
/** `User-Agent` запроса для SSR-фолбэка без Client Hints. */
|
|
9
|
+
userAgent?: string | null;
|
|
10
|
+
/** Переопределение брейкпоинтов — только для ветки с `viewportWidth`. */
|
|
11
|
+
breakpoints?: AdaptiveBreakpoints;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Стартовый `layoutType` для SSR в Next.js App Router.
|
|
15
|
+
*
|
|
16
|
+
* 1. Есть валидная ширина (Client Hints на Chromium) → каскад по брейкпоинтам (4 тира).
|
|
17
|
+
* 2. Иначе → `layoutTypeFromUserAgent` (mobile / tablet / desktop).
|
|
18
|
+
*
|
|
19
|
+
* Пара с `getLayoutBootstrapScript()` (pre-paint) и `useLayoutTypeState(initialLayoutType)` на клиенте.
|
|
20
|
+
*/
|
|
21
|
+
export declare function getSSRInitialLayoutType({ viewportWidth, userAgent, breakpoints, }: GetSSRInitialLayoutTypeOptions): LayoutType;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SEC_CH_VIEWPORT_WIDTH_HEADER = void 0;
|
|
4
|
+
exports.getSSRInitialLayoutType = getSSRInitialLayoutType;
|
|
5
|
+
const layoutTypeFromUserAgent_1 = require("./layoutTypeFromUserAgent");
|
|
6
|
+
const layoutTypeFromWidth_1 = require("./layoutTypeFromWidth");
|
|
7
|
+
/** Заголовок Client Hints с шириной viewport (Chromium). См. `Critical-CH` в `next.config`. */
|
|
8
|
+
exports.SEC_CH_VIEWPORT_WIDTH_HEADER = 'sec-ch-viewport-width';
|
|
9
|
+
function parseViewportWidth(viewportWidth) {
|
|
10
|
+
const width = typeof viewportWidth === 'number' ? viewportWidth : Number(viewportWidth);
|
|
11
|
+
if (!Number.isFinite(width) || width <= 0) {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
return width;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Стартовый `layoutType` для SSR в Next.js App Router.
|
|
18
|
+
*
|
|
19
|
+
* 1. Есть валидная ширина (Client Hints на Chromium) → каскад по брейкпоинтам (4 тира).
|
|
20
|
+
* 2. Иначе → `layoutTypeFromUserAgent` (mobile / tablet / desktop).
|
|
21
|
+
*
|
|
22
|
+
* Пара с `getLayoutBootstrapScript()` (pre-paint) и `useLayoutTypeState(initialLayoutType)` на клиенте.
|
|
23
|
+
*/
|
|
24
|
+
function getSSRInitialLayoutType({ viewportWidth, userAgent, breakpoints, }) {
|
|
25
|
+
if (viewportWidth != null && viewportWidth !== '') {
|
|
26
|
+
const width = parseViewportWidth(viewportWidth);
|
|
27
|
+
if (width != null) {
|
|
28
|
+
return (0, layoutTypeFromWidth_1.layoutTypeFromWidth)(width, breakpoints);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return (0, layoutTypeFromUserAgent_1.layoutTypeFromUserAgent)(userAgent ?? '');
|
|
32
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { ValueOf } from '../types/valueOf';
|
|
2
|
+
/** Тип устройства из user-agent. */
|
|
3
|
+
export declare const DEVICE_TYPE: {
|
|
4
|
+
readonly Console: "console";
|
|
5
|
+
readonly Mobile: "mobile";
|
|
6
|
+
readonly Tablet: "tablet";
|
|
7
|
+
readonly Smarttv: "smarttv";
|
|
8
|
+
readonly Wearable: "wearable";
|
|
9
|
+
readonly Embedded: "embedded";
|
|
10
|
+
readonly Desktop: "desktop";
|
|
11
|
+
};
|
|
12
|
+
export type DeviceType = ValueOf<typeof DEVICE_TYPE>;
|
|
13
|
+
/** Операционная система из user-agent. Поля пустые, если UA не распознан. */
|
|
14
|
+
export type UserAgentOs = {
|
|
15
|
+
name?: string;
|
|
16
|
+
version?: string;
|
|
17
|
+
};
|
|
18
|
+
/** Браузер из user-agent. Поля пустые, если UA не распознан. */
|
|
19
|
+
export type UserAgentBrowser = {
|
|
20
|
+
name?: string;
|
|
21
|
+
version?: string;
|
|
22
|
+
/** Мажорная часть `version` — удобна для проверок вида «Safari младше 16». */
|
|
23
|
+
major?: string;
|
|
24
|
+
};
|
|
25
|
+
export type UserAgentInfo = {
|
|
26
|
+
device: {
|
|
27
|
+
model?: string;
|
|
28
|
+
type: DeviceType;
|
|
29
|
+
};
|
|
30
|
+
os: UserAgentOs;
|
|
31
|
+
browser: UserAgentBrowser;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Разбирает user-agent и возвращает тип устройства, ОС и браузер.
|
|
35
|
+
* Источник UA: аргумент `userAgent` (для SSR — заголовок запроса), иначе `navigator.userAgent`.
|
|
36
|
+
* На сервере без аргумента `device.type` нормализуется к `desktop`.
|
|
37
|
+
*
|
|
38
|
+
* Детектор целенаправленно узкий: он покрывает раскладку (`device.type` — единственное, что читает
|
|
39
|
+
* адаптив) и популярные браузеры/ОС. Для экзотических устройств `device.type` деградирует к
|
|
40
|
+
* `desktop`, а `os`/`browser` остаются пустыми — это осознанный размен на отсутствие внешней
|
|
41
|
+
* зависимости с базой UA.
|
|
42
|
+
*/
|
|
43
|
+
export declare function getUserAgentInfo(userAgent?: string): UserAgentInfo;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEVICE_TYPE = void 0;
|
|
4
|
+
exports.getUserAgentInfo = getUserAgentInfo;
|
|
5
|
+
const isBrowser_1 = require("./isBrowser");
|
|
6
|
+
/** Тип устройства из user-agent. */
|
|
7
|
+
exports.DEVICE_TYPE = {
|
|
8
|
+
Console: 'console',
|
|
9
|
+
Mobile: 'mobile',
|
|
10
|
+
Tablet: 'tablet',
|
|
11
|
+
Smarttv: 'smarttv',
|
|
12
|
+
Wearable: 'wearable',
|
|
13
|
+
Embedded: 'embedded',
|
|
14
|
+
Desktop: 'desktop',
|
|
15
|
+
};
|
|
16
|
+
const TV_PATTERN = /\b(?:SmartTV|SMART-TV|GoogleTV|AppleTV|HbbTV|NetCast|Web0S|webOS TV|BRAVIA|Roku|CrKey)\b/i;
|
|
17
|
+
const CONSOLE_PATTERN = /\b(?:Nintendo|PlayStation|Xbox)\b/i;
|
|
18
|
+
const WEARABLE_PATTERN = /\b(?:Watch|Wear OS|Glass)\b/i;
|
|
19
|
+
const TABLET_PATTERN = /\b(?:iPad|Tablet|PlayBook|Kindle|Silk)\b/i;
|
|
20
|
+
const MOBILE_PATTERN = /\b(?:iPhone|iPod|Windows Phone|IEMobile|BlackBerry|BB10|Opera Mini|Mobi)\b/i;
|
|
21
|
+
function detectDeviceType(userAgent) {
|
|
22
|
+
if (TV_PATTERN.test(userAgent))
|
|
23
|
+
return exports.DEVICE_TYPE.Smarttv;
|
|
24
|
+
if (CONSOLE_PATTERN.test(userAgent))
|
|
25
|
+
return exports.DEVICE_TYPE.Console;
|
|
26
|
+
if (WEARABLE_PATTERN.test(userAgent))
|
|
27
|
+
return exports.DEVICE_TYPE.Wearable;
|
|
28
|
+
if (TABLET_PATTERN.test(userAgent))
|
|
29
|
+
return exports.DEVICE_TYPE.Tablet;
|
|
30
|
+
// Android без токена `Mobi` — планшет: так это размечает сам Android (WebView ставит `Mobile`
|
|
31
|
+
// только на телефонах).
|
|
32
|
+
if (/Android/i.test(userAgent))
|
|
33
|
+
return /Mobi/i.test(userAgent) ? exports.DEVICE_TYPE.Mobile : exports.DEVICE_TYPE.Tablet;
|
|
34
|
+
if (MOBILE_PATTERN.test(userAgent))
|
|
35
|
+
return exports.DEVICE_TYPE.Mobile;
|
|
36
|
+
return exports.DEVICE_TYPE.Desktop;
|
|
37
|
+
}
|
|
38
|
+
function detectModel(userAgent) {
|
|
39
|
+
const apple = /\b(iPhone|iPad|iPod)\b/.exec(userAgent);
|
|
40
|
+
if (apple)
|
|
41
|
+
return apple[1];
|
|
42
|
+
// Android держит модель в комментарии: `(Linux; Android 14; SM-S911B) ...` или `... Build/...`.
|
|
43
|
+
const android = /Android[^;)]*;\s*([^;)]+?)(?:\s+Build\/[^;)]*)?\s*[;)]/.exec(userAgent);
|
|
44
|
+
return android?.[1]?.trim() || undefined;
|
|
45
|
+
}
|
|
46
|
+
const WINDOWS_NT_NAMES = {
|
|
47
|
+
'10.0': '10',
|
|
48
|
+
'6.3': '8.1',
|
|
49
|
+
'6.2': '8',
|
|
50
|
+
'6.1': '7',
|
|
51
|
+
};
|
|
52
|
+
function detectOs(userAgent) {
|
|
53
|
+
const ios = /\b(?:iPhone|iPad|iPod)\b.*?\bOS (\d+(?:[._]\d+)*)/.exec(userAgent);
|
|
54
|
+
if (ios)
|
|
55
|
+
return { name: 'iOS', version: ios[1].replace(/_/g, '.') };
|
|
56
|
+
const android = /Android (\d+(?:\.\d+)*)/.exec(userAgent);
|
|
57
|
+
if (android)
|
|
58
|
+
return { name: 'Android', version: android[1] };
|
|
59
|
+
const windows = /Windows NT (\d+\.\d+)/.exec(userAgent);
|
|
60
|
+
if (windows)
|
|
61
|
+
return { name: 'Windows', version: WINDOWS_NT_NAMES[windows[1]] ?? windows[1] };
|
|
62
|
+
const macos = /Mac OS X (\d+(?:[._]\d+)*)/.exec(userAgent);
|
|
63
|
+
if (macos)
|
|
64
|
+
return { name: 'macOS', version: macos[1].replace(/_/g, '.') };
|
|
65
|
+
if (/Macintosh/i.test(userAgent))
|
|
66
|
+
return { name: 'macOS' };
|
|
67
|
+
if (/Linux/i.test(userAgent))
|
|
68
|
+
return { name: 'Linux' };
|
|
69
|
+
return {};
|
|
70
|
+
}
|
|
71
|
+
// Порядок важен: Edge и Opera представляются Chrome'ом, Chrome — Safari.
|
|
72
|
+
const BROWSER_PATTERNS = [
|
|
73
|
+
{ name: 'Edge', pattern: /\bEdgi?[A-Za-z]*\/([\d.]+)/ },
|
|
74
|
+
{ name: 'Opera', pattern: /\b(?:OPR|Opera)\/([\d.]+)/ },
|
|
75
|
+
{ name: 'Yandex Browser', pattern: /\bYaBrowser\/([\d.]+)/ },
|
|
76
|
+
{ name: 'Samsung Internet', pattern: /\bSamsungBrowser\/([\d.]+)/ },
|
|
77
|
+
{ name: 'Firefox', pattern: /\b(?:Firefox|FxiOS)\/([\d.]+)/ },
|
|
78
|
+
{ name: 'Chrome', pattern: /\b(?:Chrome|CriOS|Chromium)\/([\d.]+)/ },
|
|
79
|
+
{ name: 'Safari', pattern: /\bVersion\/([\d.]+).*\bSafari\b/ },
|
|
80
|
+
];
|
|
81
|
+
function detectBrowser(userAgent) {
|
|
82
|
+
for (const { name, pattern } of BROWSER_PATTERNS) {
|
|
83
|
+
const match = pattern.exec(userAgent);
|
|
84
|
+
if (match) {
|
|
85
|
+
const version = match[1];
|
|
86
|
+
return { name, version, major: version.split('.')[0] };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return {};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Разбирает user-agent и возвращает тип устройства, ОС и браузер.
|
|
93
|
+
* Источник UA: аргумент `userAgent` (для SSR — заголовок запроса), иначе `navigator.userAgent`.
|
|
94
|
+
* На сервере без аргумента `device.type` нормализуется к `desktop`.
|
|
95
|
+
*
|
|
96
|
+
* Детектор целенаправленно узкий: он покрывает раскладку (`device.type` — единственное, что читает
|
|
97
|
+
* адаптив) и популярные браузеры/ОС. Для экзотических устройств `device.type` деградирует к
|
|
98
|
+
* `desktop`, а `os`/`browser` остаются пустыми — это осознанный размен на отсутствие внешней
|
|
99
|
+
* зависимости с базой UA.
|
|
100
|
+
*/
|
|
101
|
+
function getUserAgentInfo(userAgent) {
|
|
102
|
+
const resolvedUserAgent = userAgent ?? ((0, isBrowser_1.isBrowser)() ? globalThis.navigator.userAgent : undefined);
|
|
103
|
+
if (!resolvedUserAgent) {
|
|
104
|
+
return { device: { type: exports.DEVICE_TYPE.Desktop }, os: {}, browser: {} };
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
device: {
|
|
108
|
+
model: detectModel(resolvedUserAgent),
|
|
109
|
+
type: detectDeviceType(resolvedUserAgent),
|
|
110
|
+
},
|
|
111
|
+
os: detectOs(resolvedUserAgent),
|
|
112
|
+
browser: detectBrowser(resolvedUserAgent),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./getAdaptive"), exports);
|
|
18
|
+
__exportStar(require("./getMatchMedia"), exports);
|
|
19
|
+
__exportStar(require("./getUserAgentInfo"), exports);
|
|
20
|
+
__exportStar(require("./layoutTypeFromMatchMedia"), exports);
|
|
21
|
+
__exportStar(require("./resolveLayoutType"), exports);
|
|
22
|
+
__exportStar(require("./resolveByLayout"), exports);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isBrowser = isBrowser;
|
|
4
|
+
/** Проверка браузерной среды (SSR-safe). Локальная копия — чтобы SSR-путь `@cloud-ru/ds-adaptive/ssr`
|
|
5
|
+
* не тянул баррель `@cloud-ru/ds-utils` (createContext/хуки) в React Server Components. */
|
|
6
|
+
function isBrowser() {
|
|
7
|
+
// eslint-disable-next-line @cloud-ru/ssr-safe-react/domApi
|
|
8
|
+
return Boolean(typeof window !== 'undefined' && window.document && window.document.createElement);
|
|
9
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { AdaptiveQuery, MatchMediaGeneric } from '../types/adaptive';
|
|
2
|
+
import { LayoutType } from '../types/layoutTypes';
|
|
3
|
+
/** Каскад `layoutType` по adaptive media-query (без учёта user-agent). */
|
|
4
|
+
export declare function layoutTypeFromMatchMedia(matchMedia: MatchMediaGeneric<AdaptiveQuery>): LayoutType;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.layoutTypeFromMatchMedia = layoutTypeFromMatchMedia;
|
|
4
|
+
const adaptive_1 = require("../constants/adaptive");
|
|
5
|
+
const layoutTypes_1 = require("../types/layoutTypes");
|
|
6
|
+
/** Каскад `layoutType` по adaptive media-query (без учёта user-agent). */
|
|
7
|
+
function layoutTypeFromMatchMedia(matchMedia) {
|
|
8
|
+
if (matchMedia[adaptive_1.ADAPTIVE_QUERY.IsMobile]) {
|
|
9
|
+
return layoutTypes_1.LAYOUT_TYPE.Mobile;
|
|
10
|
+
}
|
|
11
|
+
if (matchMedia[adaptive_1.ADAPTIVE_QUERY.IsTablet]) {
|
|
12
|
+
return layoutTypes_1.LAYOUT_TYPE.Tablet;
|
|
13
|
+
}
|
|
14
|
+
if (matchMedia[adaptive_1.ADAPTIVE_QUERY.IsSmallDesktop]) {
|
|
15
|
+
return layoutTypes_1.LAYOUT_TYPE.DesktopSmall;
|
|
16
|
+
}
|
|
17
|
+
return layoutTypes_1.LAYOUT_TYPE.Desktop;
|
|
18
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { LayoutType } from '../types/layoutTypes';
|
|
2
|
+
/**
|
|
3
|
+
* Грубый `layoutType` по user-agent (три тира: mobile / tablet / desktop).
|
|
4
|
+
* Без ширины окна `desktopSmall` не выводится — для SSR-фолбэка, когда нет Client Hints.
|
|
5
|
+
*/
|
|
6
|
+
export declare function layoutTypeFromUserAgent(userAgent: string): LayoutType;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.layoutTypeFromUserAgent = layoutTypeFromUserAgent;
|
|
4
|
+
const layoutTypes_1 = require("../types/layoutTypes");
|
|
5
|
+
const getUserAgentInfo_1 = require("./getUserAgentInfo");
|
|
6
|
+
/**
|
|
7
|
+
* Грубый `layoutType` по user-agent (три тира: mobile / tablet / desktop).
|
|
8
|
+
* Без ширины окна `desktopSmall` не выводится — для SSR-фолбэка, когда нет Client Hints.
|
|
9
|
+
*/
|
|
10
|
+
function layoutTypeFromUserAgent(userAgent) {
|
|
11
|
+
const { device } = (0, getUserAgentInfo_1.getUserAgentInfo)(userAgent);
|
|
12
|
+
switch (device.type) {
|
|
13
|
+
case getUserAgentInfo_1.DEVICE_TYPE.Mobile:
|
|
14
|
+
return layoutTypes_1.LAYOUT_TYPE.Mobile;
|
|
15
|
+
case getUserAgentInfo_1.DEVICE_TYPE.Tablet:
|
|
16
|
+
return layoutTypes_1.LAYOUT_TYPE.Tablet;
|
|
17
|
+
default:
|
|
18
|
+
return layoutTypes_1.LAYOUT_TYPE.Desktop;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.layoutTypeFromWidth = layoutTypeFromWidth;
|
|
4
|
+
const adaptive_1 = require("../constants/adaptive");
|
|
5
|
+
const types_1 = require("../types");
|
|
6
|
+
function layoutTypeFromWidth(width, breakpoints) {
|
|
7
|
+
const mergedBreakpoints = { ...adaptive_1.ADAPTIVE_BREAKPOINT, ...breakpoints };
|
|
8
|
+
if (width <= mergedBreakpoints.mobile) {
|
|
9
|
+
return types_1.LAYOUT_TYPE.Mobile;
|
|
10
|
+
}
|
|
11
|
+
if (width <= mergedBreakpoints.tablet) {
|
|
12
|
+
return types_1.LAYOUT_TYPE.Tablet;
|
|
13
|
+
}
|
|
14
|
+
if (width <= mergedBreakpoints.desktopSmall) {
|
|
15
|
+
return types_1.LAYOUT_TYPE.DesktopSmall;
|
|
16
|
+
}
|
|
17
|
+
return types_1.LAYOUT_TYPE.Desktop;
|
|
18
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { LayoutType } from '../types/layoutTypes';
|
|
2
|
+
import { LayoutPresets } from '../types/presets';
|
|
3
|
+
/**
|
|
4
|
+
* Сливает несколько `LayoutPresets` в один пер-tier: для каждого тира ключи пропов объединяются
|
|
5
|
+
* поверхностным spread'ом, поздний аргумент побеждает (`undefined`-пресет пропускается). Вложенные
|
|
6
|
+
* объекты-значения пропов не мёржатся рекурсивно — поздний целиком перетирает ранний.
|
|
7
|
+
* Накладывает per-instance override (`layoutPresets`) поверх DS-пресетов компонента (`X_LAYOUT_PRESETS`).
|
|
8
|
+
*/
|
|
9
|
+
export declare function mergePresets<P>(...presets: (LayoutPresets<P> | undefined)[]): LayoutPresets<P>;
|
|
10
|
+
/** Аргументы {@link resolveByLayout}. */
|
|
11
|
+
export type ResolveByLayoutOptions<P extends object> = {
|
|
12
|
+
/** Текущая раскладка (`undefined` → desktop-baseline). */
|
|
13
|
+
layoutType: LayoutType | undefined;
|
|
14
|
+
/** Базовые desktop-дефолты. */
|
|
15
|
+
base: P;
|
|
16
|
+
/** Пресеты пер-tier (instance ⊕ DS, обычно через {@link mergePresets}). */
|
|
17
|
+
presets: LayoutPresets<P>;
|
|
18
|
+
/** Явно переданные пропы (= desktop-значения). */
|
|
19
|
+
explicit: Partial<P>;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Резолвит итоговые значения пропов по раскладке — desktop-first. Чистая функция.
|
|
23
|
+
*
|
|
24
|
+
* Приоритет ключа: `presets[layoutType]` (пресет раскладки, instance > DS) > `explicit` (явный проп) >
|
|
25
|
+
* `base` (desktop-дефолт). Перетирают только определённые (`!== undefined`) ключи. Пресет выше пропа,
|
|
26
|
+
* потому что перенесённый из desktop-макета проп = desktop-значение и не должен ломать mobile.
|
|
27
|
+
*/
|
|
28
|
+
export declare function resolveByLayout<P extends object>({ layoutType, base, presets, explicit, }: ResolveByLayoutOptions<P>): P;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mergePresets = mergePresets;
|
|
4
|
+
exports.resolveByLayout = resolveByLayout;
|
|
5
|
+
const resolveLayoutType_1 = require("./resolveLayoutType");
|
|
6
|
+
/**
|
|
7
|
+
* Сливает несколько `LayoutPresets` в один пер-tier: для каждого тира ключи пропов объединяются
|
|
8
|
+
* поверхностным spread'ом, поздний аргумент побеждает (`undefined`-пресет пропускается). Вложенные
|
|
9
|
+
* объекты-значения пропов не мёржатся рекурсивно — поздний целиком перетирает ранний.
|
|
10
|
+
* Накладывает per-instance override (`layoutPresets`) поверх DS-пресетов компонента (`X_LAYOUT_PRESETS`).
|
|
11
|
+
*/
|
|
12
|
+
function mergePresets(...presets) {
|
|
13
|
+
const result = {};
|
|
14
|
+
for (const preset of presets) {
|
|
15
|
+
if (!preset) {
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
for (const tier of Object.keys(preset)) {
|
|
19
|
+
result[tier] = { ...result[tier], ...preset[tier] };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Резолвит итоговые значения пропов по раскладке — desktop-first. Чистая функция.
|
|
26
|
+
*
|
|
27
|
+
* Приоритет ключа: `presets[layoutType]` (пресет раскладки, instance > DS) > `explicit` (явный проп) >
|
|
28
|
+
* `base` (desktop-дефолт). Перетирают только определённые (`!== undefined`) ключи. Пресет выше пропа,
|
|
29
|
+
* потому что перенесённый из desktop-макета проп = desktop-значение и не должен ломать mobile.
|
|
30
|
+
*/
|
|
31
|
+
function resolveByLayout({ layoutType, base, presets, explicit, }) {
|
|
32
|
+
const preset = presets[(0, resolveLayoutType_1.resolveLayoutType)(layoutType)] ?? {};
|
|
33
|
+
const result = { ...base };
|
|
34
|
+
// explicit поверх base…
|
|
35
|
+
for (const key of Object.keys(explicit)) {
|
|
36
|
+
const value = explicit[key];
|
|
37
|
+
if (value !== undefined) {
|
|
38
|
+
result[key] = value;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// …а пресет раскладки поверх explicit (mobile-дефолт защищён от перенесённого desktop-пропа).
|
|
42
|
+
for (const key of Object.keys(preset)) {
|
|
43
|
+
const value = preset[key];
|
|
44
|
+
if (value !== undefined) {
|
|
45
|
+
result[key] = value;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { LayoutType } from '../types/layoutTypes';
|
|
2
|
+
/**
|
|
3
|
+
* Нормализует опциональный `layoutType` к desktop-дефолту. Единая точка SSR-решения:
|
|
4
|
+
* на сервере и до mount, когда раскладка не передана, считаем desktop.
|
|
5
|
+
*/
|
|
6
|
+
export declare function resolveLayoutType(layoutType?: LayoutType): LayoutType;
|
|
7
|
+
/**
|
|
8
|
+
* Канон ветвления `Adaptive*`-обёрток: mobile-путь строго на `mobile`,
|
|
9
|
+
* tablet/desktopSmall/desktop → desktop-ветка.
|
|
10
|
+
*/
|
|
11
|
+
export declare function isMobileLayout(layoutType?: LayoutType): boolean;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveLayoutType = resolveLayoutType;
|
|
4
|
+
exports.isMobileLayout = isMobileLayout;
|
|
5
|
+
const adaptive_1 = require("../constants/adaptive");
|
|
6
|
+
/**
|
|
7
|
+
* Нормализует опциональный `layoutType` к desktop-дефолту. Единая точка SSR-решения:
|
|
8
|
+
* на сервере и до mount, когда раскладка не передана, считаем desktop.
|
|
9
|
+
*/
|
|
10
|
+
function resolveLayoutType(layoutType) {
|
|
11
|
+
return layoutType ?? adaptive_1.DEFAULT_LAYOUT_TYPE;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Канон ветвления `Adaptive*`-обёрток: mobile-путь строго на `mobile`,
|
|
15
|
+
* tablet/desktopSmall/desktop → desktop-ветка.
|
|
16
|
+
*/
|
|
17
|
+
function isMobileLayout(layoutType) {
|
|
18
|
+
return adaptive_1.LAYOUT_SPLIT_MOBILE_TIERS.mobileOnly.includes(resolveLayoutType(layoutType));
|
|
19
|
+
}
|