hallo-kit 0.3.0 → 0.3.1

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/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # hallo-kit
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/hallo-kit)](https://www.npmjs.com/package/hallo-kit)
4
+
3
5
  Дизайн-система Hallo: UI-кит, токены, хуки и утилиты. Один источник правды для кабинета
4
6
  и сайтов проекта — вместо копирования файлов между репозиториями.
5
7
 
@@ -1,93 +1,93 @@
1
- Copyright 2018 The Manrope Project Authors (https://github.com/sharanda/manrope)
2
-
3
- This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
- This license is copied below, and is also available with a FAQ at:
5
- https://openfontlicense.org
6
-
7
-
8
- -----------------------------------------------------------
9
- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
- -----------------------------------------------------------
11
-
12
- PREAMBLE
13
- The goals of the Open Font License (OFL) are to stimulate worldwide
14
- development of collaborative font projects, to support the font creation
15
- efforts of academic and linguistic communities, and to provide a free and
16
- open framework in which fonts may be shared and improved in partnership
17
- with others.
18
-
19
- The OFL allows the licensed fonts to be used, studied, modified and
20
- redistributed freely as long as they are not sold by themselves. The
21
- fonts, including any derivative works, can be bundled, embedded,
22
- redistributed and/or sold with any software provided that any reserved
23
- names are not used by derivative works. The fonts and derivatives,
24
- however, cannot be released under any other type of license. The
25
- requirement for fonts to remain under this license does not apply
26
- to any document created using the fonts or their derivatives.
27
-
28
- DEFINITIONS
29
- "Font Software" refers to the set of files released by the Copyright
30
- Holder(s) under this license and clearly marked as such. This may
31
- include source files, build scripts and documentation.
32
-
33
- "Reserved Font Name" refers to any names specified as such after the
34
- copyright statement(s).
35
-
36
- "Original Version" refers to the collection of Font Software components as
37
- distributed by the Copyright Holder(s).
38
-
39
- "Modified Version" refers to any derivative made by adding to, deleting,
40
- or substituting -- in part or in whole -- any of the components of the
41
- Original Version, by changing formats or by porting the Font Software to a
42
- new environment.
43
-
44
- "Author" refers to any designer, engineer, programmer, technical
45
- writer or other person who contributed to the Font Software.
46
-
47
- PERMISSION & CONDITIONS
48
- Permission is hereby granted, free of charge, to any person obtaining
49
- a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
- redistribute, and sell modified and unmodified copies of the Font
51
- Software, subject to the following conditions:
52
-
53
- 1) Neither the Font Software nor any of its individual components,
54
- in Original or Modified Versions, may be sold by itself.
55
-
56
- 2) Original or Modified Versions of the Font Software may be bundled,
57
- redistributed and/or sold with any software, provided that each copy
58
- contains the above copyright notice and this license. These can be
59
- included either as stand-alone text files, human-readable headers or
60
- in the appropriate machine-readable metadata fields within text or
61
- binary files as long as those fields can be easily viewed by the user.
62
-
63
- 3) No Modified Version of the Font Software may use the Reserved Font
64
- Name(s) unless explicit written permission is granted by the corresponding
65
- Copyright Holder. This restriction only applies to the primary font name as
66
- presented to the users.
67
-
68
- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
- Software shall not be used to promote, endorse or advertise any
70
- Modified Version, except to acknowledge the contribution(s) of the
71
- Copyright Holder(s) and the Author(s) or with their explicit written
72
- permission.
73
-
74
- 5) The Font Software, modified or unmodified, in part or in whole,
75
- must be distributed entirely under this license, and must not be
76
- distributed under any other license. The requirement for fonts to
77
- remain under this license does not apply to any document created
78
- using the Font Software.
79
-
80
- TERMINATION
81
- This license becomes null and void if any of the above conditions are
82
- not met.
83
-
84
- DISCLAIMER
85
- THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
- OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
- COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
- INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
- DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
- FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
- OTHER DEALINGS IN THE FONT SOFTWARE.
1
+ Copyright 2018 The Manrope Project Authors (https://github.com/sharanda/manrope)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://openfontlicense.org
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
package/fonts/index.ts CHANGED
@@ -1,30 +1,30 @@
1
- import localFont from 'next/font/local'
2
-
3
- // Manrope — переменный шрифт (один файл на весь диапазон весов 200–800).
4
- // Self-hosted через next/font/local: запросов к Google в рантайме нет.
5
- // Экспонируется как CSS-переменная --font-manrope (см. globals.css → --font-sans).
6
- //
7
- // Формат woff2, а не ttf. Тот же файл в ttf весит 163 КБ против 53 КБ — это самый
8
- // тяжёлый ресурс страницы. Замерено на канале 300 кбит/с: DOM готов на 2 с, а ttf
9
- // доезжал на 8.4 с, то есть шесть с половиной секунд текст жил в подменном шрифте и
10
- // потом перерисовывался. woff2 поддерживают все целевые браузеры с 2016 года,
11
- // держать ttf «на всякий случай» незачем.
12
- //
13
- // Пересобрать из ttf при обновлении шрифта:
14
- // npx wawoff2 — см. scripts/ttf-to-woff2.mjs в sub-page.
15
- export const manrope = localFont({
16
- src: './Manrope/Manrope-VariableFont_wght.woff2',
17
- variable: '--font-manrope',
18
- weight: '200 800',
19
- display: 'swap',
20
- // preload явно: без него браузер узнаёт о шрифте только разобрав CSS, и запрос
21
- // встаёт в очередь за скриптами. На медленном канале это откладывало подмену
22
- // шрифта на секунды.
23
- preload: true,
24
- // adjustFontFallback синтезирует подменный шрифт с ПОДОГНАННЫМИ метриками
25
- // (по Arial). Без него момент подмены сдвигает текст: строки меняют ширину и
26
- // высоту, и страница «дёргается» уже после того, как выглядела готовой. С ним
27
- // подмена происходит почти незаметно.
28
- adjustFontFallback: 'Arial',
29
- fallback: ['Arial', 'Helvetica', 'sans-serif'],
30
- })
1
+ import localFont from 'next/font/local'
2
+
3
+ // Manrope — переменный шрифт (один файл на весь диапазон весов 200–800).
4
+ // Self-hosted через next/font/local: запросов к Google в рантайме нет.
5
+ // Экспонируется как CSS-переменная --font-manrope (см. globals.css → --font-sans).
6
+ //
7
+ // Формат woff2, а не ttf. Тот же файл в ttf весит 163 КБ против 53 КБ — это самый
8
+ // тяжёлый ресурс страницы. Замерено на канале 300 кбит/с: DOM готов на 2 с, а ttf
9
+ // доезжал на 8.4 с, то есть шесть с половиной секунд текст жил в подменном шрифте и
10
+ // потом перерисовывался. woff2 поддерживают все целевые браузеры с 2016 года,
11
+ // держать ttf «на всякий случай» незачем.
12
+ //
13
+ // Пересобрать из ttf при обновлении шрифта:
14
+ // npx wawoff2 — см. scripts/ttf-to-woff2.mjs в sub-page.
15
+ export const manrope = localFont({
16
+ src: './Manrope/Manrope-VariableFont_wght.woff2',
17
+ variable: '--font-manrope',
18
+ weight: '200 800',
19
+ display: 'swap',
20
+ // preload явно: без него браузер узнаёт о шрифте только разобрав CSS, и запрос
21
+ // встаёт в очередь за скриптами. На медленном канале это откладывало подмену
22
+ // шрифта на секунды.
23
+ preload: true,
24
+ // adjustFontFallback синтезирует подменный шрифт с ПОДОГНАННЫМИ метриками
25
+ // (по Arial). Без него момент подмены сдвигает текст: строки меняют ширину и
26
+ // высоту, и страница «дёргается» уже после того, как выглядела готовой. С ним
27
+ // подмена происходит почти незаметно.
28
+ adjustFontFallback: 'Arial',
29
+ fallback: ['Arial', 'Helvetica', 'sans-serif'],
30
+ })
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "hallo-kit",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Дизайн-система Hallo: UI-кит, токены, хуки и утилиты для сайтов проекта",
5
5
  "license": "UNLICENSED",
6
+ "engines": {
7
+ "node": ">=20"
8
+ },
6
9
  "type": "module",
7
10
  "sideEffects": [
8
11
  "*.css"
@@ -1,44 +1,44 @@
1
- 'use client'
2
-
3
- import { useEffect, useState } from 'react'
4
-
5
- /**
6
- * Обратный отсчёт до момента `deadline` (epoch, мс).
7
- *
8
- * Отсчёт стартует от СЕРВЕРНОГО `initialNow` — тогда первый кадр совпадает с SSR, и число
9
- * не прыгает при гидрации; дальше тикает по часам браузера. Часы клиента могут отставать
10
- * или спешить, поэтому источником правды остаётся сервер: даже если здесь показано «ещё
11
- * 2 минуты», просроченный токен всё равно получит отказ на оплате.
12
- *
13
- * @param deadline Момент окончания (epoch, мс) либо null — отсчёта нет.
14
- * @param initialNow Серверное «сейчас» (epoch, мс) для первого кадра.
15
- * @returns Осталось миллисекунд (0 — вышло) либо null, если дедлайна нет.
16
- */
17
- export function useCountdown(deadline: number | null, initialNow: number): number | null {
18
- const [leftMs, setLeftMs] = useState(() =>
19
- deadline === null ? 0 : Math.max(0, deadline - initialNow),
20
- )
21
-
22
- useEffect(() => {
23
- if (deadline === null) {
24
- return
25
- }
26
-
27
- const tick = () => setLeftMs(Math.max(0, deadline - Date.now()))
28
- tick()
29
- const timer = window.setInterval(tick, 1000)
30
- return () => window.clearInterval(timer)
31
- }, [deadline])
32
-
33
- // «Нет дедлайна» отдаём вычислением, а не состоянием: setState прямо в эффекте плодит
34
- // каскадные рендеры, и React это отдельно запрещает.
35
- return deadline === null ? null : leftMs
36
- }
37
-
38
- /** мм:сс из миллисекунд — подпись рядом с ценой. */
39
- export function formatCountdown(ms: number): string {
40
- const total = Math.max(0, Math.ceil(ms / 1000))
41
- const m = Math.floor(total / 60)
42
- const s = total % 60
43
- return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
44
- }
1
+ 'use client'
2
+
3
+ import { useEffect, useState } from 'react'
4
+
5
+ /**
6
+ * Обратный отсчёт до момента `deadline` (epoch, мс).
7
+ *
8
+ * Отсчёт стартует от СЕРВЕРНОГО `initialNow` — тогда первый кадр совпадает с SSR, и число
9
+ * не прыгает при гидрации; дальше тикает по часам браузера. Часы клиента могут отставать
10
+ * или спешить, поэтому источником правды остаётся сервер: даже если здесь показано «ещё
11
+ * 2 минуты», просроченный токен всё равно получит отказ на оплате.
12
+ *
13
+ * @param deadline Момент окончания (epoch, мс) либо null — отсчёта нет.
14
+ * @param initialNow Серверное «сейчас» (epoch, мс) для первого кадра.
15
+ * @returns Осталось миллисекунд (0 — вышло) либо null, если дедлайна нет.
16
+ */
17
+ export function useCountdown(deadline: number | null, initialNow: number): number | null {
18
+ const [leftMs, setLeftMs] = useState(() =>
19
+ deadline === null ? 0 : Math.max(0, deadline - initialNow),
20
+ )
21
+
22
+ useEffect(() => {
23
+ if (deadline === null) {
24
+ return
25
+ }
26
+
27
+ const tick = () => setLeftMs(Math.max(0, deadline - Date.now()))
28
+ tick()
29
+ const timer = window.setInterval(tick, 1000)
30
+ return () => window.clearInterval(timer)
31
+ }, [deadline])
32
+
33
+ // «Нет дедлайна» отдаём вычислением, а не состоянием: setState прямо в эффекте плодит
34
+ // каскадные рендеры, и React это отдельно запрещает.
35
+ return deadline === null ? null : leftMs
36
+ }
37
+
38
+ /** мм:сс из миллисекунд — подпись рядом с ценой. */
39
+ export function formatCountdown(ms: number): string {
40
+ const total = Math.max(0, Math.ceil(ms / 1000))
41
+ const m = Math.floor(total / 60)
42
+ const s = total % 60
43
+ return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
44
+ }
@@ -1,102 +1,102 @@
1
- 'use client'
2
-
3
- import { createContext, useContext } from 'react'
4
-
5
- import { getTelegram } from './useTelegram'
6
-
7
- export type PlatformType = 'telegram' | 'browser'
8
-
9
- // Launch-параметры Mini App (tgWebApp* в query/hash) — их подставляет ТОЛЬКО запуск
10
- // мини-аппа, в inapp-браузере Telegram их нет. Нужны как ранний сигнал, пока SDK ещё
11
- // не распарсил initData (первый рендер до/во время загрузки telegram-web-app.js).
12
- function hasMiniAppLaunchParams(): boolean {
13
- if (typeof window === 'undefined') return false
14
- const href = window.location?.href || ''
15
- return /[?#&]tgWebApp(Data|Version|Platform)=/i.test(href)
16
- }
17
-
18
- // Мок платформы для локальной отладки MiniApp-веток в браузере (таб-бар, telegram-only и т.д.).
19
- // Включается в .env.local: NEXT_PUBLIC_MOCK_TELEGRAM=true. В прод-окружении переменной нет.
20
- const MOCK_TELEGRAM = process.env.NEXT_PUBLIC_MOCK_TELEGRAM === 'true'
21
-
22
- // 'telegram' = ТОЛЬКО настоящий Mini App: initData с user (SDK) либо launch-параметры
23
- // tgWebApp*. UA «Telegram» и window.TelegramWebviewProxy сигналами НЕ являются — они
24
- // есть и в inapp-браузере Telegram (открытие обычной ссылки), где нет ни initData,
25
- // ни сессии: такой «telegram» давал фейковую авторизацию и цикл login↔home.
26
- function computePlatform(): PlatformType {
27
- if (MOCK_TELEGRAM) return 'telegram'
28
- return getTelegram() || hasMiniAppLaunchParams() ? 'telegram' : 'browser'
29
- }
30
-
31
- // ── Внешнее хранилище платформы ──────────────────────────────────────────────
32
- // SDK Telegram грузится по сети со стороннего домена (см. лоадер в layout.tsx), поэтому
33
- // на первом клиентском рендере window.Telegram может ещё не существовать. Раньше здесь
34
- // стояла пустая подписка: значение считалось один раз и застревало на 'browser' навсегда,
35
- // даже когда SDK через мгновение приезжал. Мини-апп в этом случае оставался без маркера
36
- // сессии, и сервер уводил его на /login — «раз через раз», в зависимости от того, успел
37
- // ли скрипт до гидрации. Теперь ждём SDK и уведомляем подписчиков.
38
- const POLL_INTERVAL_MS = 100
39
- const POLL_TIMEOUT_MS = 10_000
40
-
41
- let cachedPlatform: PlatformType | null = null
42
- const listeners = new Set<() => void>()
43
- let stopWaiting: (() => void) | null = null
44
-
45
- /** Снимок платформы. Значение стабильно: 'telegram' обратно в 'browser' не превращается. */
46
- export function getPlatform(): PlatformType {
47
- if (cachedPlatform === null) {
48
- cachedPlatform = computePlatform()
49
- }
50
-
51
- return cachedPlatform
52
- }
53
-
54
- function waitForTelegram(): void {
55
- if (stopWaiting || cachedPlatform === 'telegram' || typeof window === 'undefined') {
56
- return
57
- }
58
-
59
- const startedAt = Date.now()
60
- const timer = window.setInterval(() => {
61
- if (computePlatform() === 'telegram') {
62
- cachedPlatform = 'telegram'
63
- stopWaiting?.()
64
- listeners.forEach((listener) => listener())
65
- return
66
- }
67
-
68
- // Не крутим таймер вечно: вне Telegram SDK не появится никогда.
69
- if (Date.now() - startedAt >= POLL_TIMEOUT_MS) {
70
- stopWaiting?.()
71
- }
72
- }, POLL_INTERVAL_MS)
73
-
74
- stopWaiting = () => {
75
- window.clearInterval(timer)
76
- stopWaiting = null
77
- }
78
- }
79
-
80
- export function subscribePlatform(listener: () => void): () => void {
81
- listeners.add(listener)
82
- waitForTelegram()
83
-
84
- return () => {
85
- listeners.delete(listener)
86
- }
87
- }
88
-
89
- /** Снимок для SSR и гидрации: на сервере Telegram-окружения нет. */
90
- export function getServerPlatform(): PlatformType {
91
- return 'browser'
92
- }
93
-
94
- export const PlatformContext = createContext<PlatformType>('browser')
95
-
96
- export function usePlatform(): PlatformType {
97
- return useContext(PlatformContext)
98
- }
99
-
100
- export function isTelegram(): boolean {
101
- return getTelegram() !== null || hasMiniAppLaunchParams()
102
- }
1
+ 'use client'
2
+
3
+ import { createContext, useContext } from 'react'
4
+
5
+ import { getTelegram } from './useTelegram'
6
+
7
+ export type PlatformType = 'telegram' | 'browser'
8
+
9
+ // Launch-параметры Mini App (tgWebApp* в query/hash) — их подставляет ТОЛЬКО запуск
10
+ // мини-аппа, в inapp-браузере Telegram их нет. Нужны как ранний сигнал, пока SDK ещё
11
+ // не распарсил initData (первый рендер до/во время загрузки telegram-web-app.js).
12
+ function hasMiniAppLaunchParams(): boolean {
13
+ if (typeof window === 'undefined') return false
14
+ const href = window.location?.href || ''
15
+ return /[?#&]tgWebApp(Data|Version|Platform)=/i.test(href)
16
+ }
17
+
18
+ // Мок платформы для локальной отладки MiniApp-веток в браузере (таб-бар, telegram-only и т.д.).
19
+ // Включается в .env.local: NEXT_PUBLIC_MOCK_TELEGRAM=true. В прод-окружении переменной нет.
20
+ const MOCK_TELEGRAM = process.env.NEXT_PUBLIC_MOCK_TELEGRAM === 'true'
21
+
22
+ // 'telegram' = ТОЛЬКО настоящий Mini App: initData с user (SDK) либо launch-параметры
23
+ // tgWebApp*. UA «Telegram» и window.TelegramWebviewProxy сигналами НЕ являются — они
24
+ // есть и в inapp-браузере Telegram (открытие обычной ссылки), где нет ни initData,
25
+ // ни сессии: такой «telegram» давал фейковую авторизацию и цикл login↔home.
26
+ function computePlatform(): PlatformType {
27
+ if (MOCK_TELEGRAM) return 'telegram'
28
+ return getTelegram() || hasMiniAppLaunchParams() ? 'telegram' : 'browser'
29
+ }
30
+
31
+ // ── Внешнее хранилище платформы ──────────────────────────────────────────────
32
+ // SDK Telegram грузится по сети со стороннего домена (см. лоадер в layout.tsx), поэтому
33
+ // на первом клиентском рендере window.Telegram может ещё не существовать. Раньше здесь
34
+ // стояла пустая подписка: значение считалось один раз и застревало на 'browser' навсегда,
35
+ // даже когда SDK через мгновение приезжал. Мини-апп в этом случае оставался без маркера
36
+ // сессии, и сервер уводил его на /login — «раз через раз», в зависимости от того, успел
37
+ // ли скрипт до гидрации. Теперь ждём SDK и уведомляем подписчиков.
38
+ const POLL_INTERVAL_MS = 100
39
+ const POLL_TIMEOUT_MS = 10_000
40
+
41
+ let cachedPlatform: PlatformType | null = null
42
+ const listeners = new Set<() => void>()
43
+ let stopWaiting: (() => void) | null = null
44
+
45
+ /** Снимок платформы. Значение стабильно: 'telegram' обратно в 'browser' не превращается. */
46
+ export function getPlatform(): PlatformType {
47
+ if (cachedPlatform === null) {
48
+ cachedPlatform = computePlatform()
49
+ }
50
+
51
+ return cachedPlatform
52
+ }
53
+
54
+ function waitForTelegram(): void {
55
+ if (stopWaiting || cachedPlatform === 'telegram' || typeof window === 'undefined') {
56
+ return
57
+ }
58
+
59
+ const startedAt = Date.now()
60
+ const timer = window.setInterval(() => {
61
+ if (computePlatform() === 'telegram') {
62
+ cachedPlatform = 'telegram'
63
+ stopWaiting?.()
64
+ listeners.forEach((listener) => listener())
65
+ return
66
+ }
67
+
68
+ // Не крутим таймер вечно: вне Telegram SDK не появится никогда.
69
+ if (Date.now() - startedAt >= POLL_TIMEOUT_MS) {
70
+ stopWaiting?.()
71
+ }
72
+ }, POLL_INTERVAL_MS)
73
+
74
+ stopWaiting = () => {
75
+ window.clearInterval(timer)
76
+ stopWaiting = null
77
+ }
78
+ }
79
+
80
+ export function subscribePlatform(listener: () => void): () => void {
81
+ listeners.add(listener)
82
+ waitForTelegram()
83
+
84
+ return () => {
85
+ listeners.delete(listener)
86
+ }
87
+ }
88
+
89
+ /** Снимок для SSR и гидрации: на сервере Telegram-окружения нет. */
90
+ export function getServerPlatform(): PlatformType {
91
+ return 'browser'
92
+ }
93
+
94
+ export const PlatformContext = createContext<PlatformType>('browser')
95
+
96
+ export function usePlatform(): PlatformType {
97
+ return useContext(PlatformContext)
98
+ }
99
+
100
+ export function isTelegram(): boolean {
101
+ return getTelegram() !== null || hasMiniAppLaunchParams()
102
+ }