hallo-kit 0.3.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 (128) hide show
  1. package/README.md +168 -0
  2. package/bin/cli.mjs +136 -0
  3. package/fonts/Manrope/Manrope-VariableFont_wght.woff2 +0 -0
  4. package/fonts/Manrope/OFL.txt +93 -0
  5. package/fonts/index.ts +30 -0
  6. package/package.json +77 -0
  7. package/src/config.ts +11 -0
  8. package/src/hooks/index.ts +14 -0
  9. package/src/hooks/useAutoHideOnScroll.ts +26 -0
  10. package/src/hooks/useCountdown.ts +44 -0
  11. package/src/hooks/useDevice.ts +63 -0
  12. package/src/hooks/useIsTelegramMiniApp.ts +17 -0
  13. package/src/hooks/useIsTouch.ts +23 -0
  14. package/src/hooks/useKeyboardOpen.ts +35 -0
  15. package/src/hooks/useMediaQuery.ts +24 -0
  16. package/src/hooks/usePlatform.ts +102 -0
  17. package/src/hooks/useQueryParams.tsx +70 -0
  18. package/src/hooks/useRevealOnce.ts +21 -0
  19. package/src/hooks/useScrolledPast.ts +19 -0
  20. package/src/hooks/useSettleOnce.ts +26 -0
  21. package/src/hooks/useTelegram.tsx +57 -0
  22. package/src/i18n/index.tsx +92 -0
  23. package/src/index.ts +35 -0
  24. package/src/lib/device.ts +28 -0
  25. package/src/lib/platform.ts +19 -0
  26. package/src/lib/utils.ts +36 -0
  27. package/src/logo/LogoFull.tsx +59 -0
  28. package/src/logo/LogoMark.tsx +31 -0
  29. package/src/logo/index.ts +2 -0
  30. package/src/next.ts +13 -0
  31. package/src/server.ts +4 -0
  32. package/src/theme-color-sync.tsx +43 -0
  33. package/src/theme-provider.tsx +31 -0
  34. package/src/types/css.d.ts +6 -0
  35. package/src/types/globals.d.ts +47 -0
  36. package/src/ui/Icon/Icon.module.css +25 -0
  37. package/src/ui/Icon/Icon.tsx +45 -0
  38. package/src/ui/Icon/Icon.types.ts +60 -0
  39. package/src/ui/Icon/data/brand.data.tsx +75 -0
  40. package/src/ui/Icon/data/index.ts +2 -0
  41. package/src/ui/Icon/data/ui.data.tsx +780 -0
  42. package/src/ui/Icon/index.ts +3 -0
  43. package/src/ui/badge/badge.tsx +185 -0
  44. package/src/ui/badge/index.ts +1 -0
  45. package/src/ui/breadcrumbs/breadcrumbs.tsx +63 -0
  46. package/src/ui/breadcrumbs/index.ts +1 -0
  47. package/src/ui/burger-icon/burger-icon.tsx +22 -0
  48. package/src/ui/burger-icon/index.ts +1 -0
  49. package/src/ui/button/button.tsx +179 -0
  50. package/src/ui/button/index.ts +1 -0
  51. package/src/ui/card/card.tsx +100 -0
  52. package/src/ui/card/index.ts +1 -0
  53. package/src/ui/confirm/confirm-dialog-host.tsx +89 -0
  54. package/src/ui/confirm/index.ts +1 -0
  55. package/src/ui/count-up/count-up.tsx +96 -0
  56. package/src/ui/count-up/index.ts +1 -0
  57. package/src/ui/data-list/data-list.tsx +331 -0
  58. package/src/ui/data-list/index.ts +1 -0
  59. package/src/ui/drawer/drawer.tsx +166 -0
  60. package/src/ui/drawer/index.ts +1 -0
  61. package/src/ui/flag/flag.data.ts +240 -0
  62. package/src/ui/flag/flag.tsx +57 -0
  63. package/src/ui/flag/index.ts +1 -0
  64. package/src/ui/image/image.tsx +67 -0
  65. package/src/ui/image/index.ts +1 -0
  66. package/src/ui/input/amount-input.tsx +55 -0
  67. package/src/ui/input/index.ts +2 -0
  68. package/src/ui/input/input.tsx +391 -0
  69. package/src/ui/label/index.ts +1 -0
  70. package/src/ui/label/label.tsx +34 -0
  71. package/src/ui/method-card/index.ts +1 -0
  72. package/src/ui/method-card/method-card.tsx +101 -0
  73. package/src/ui/modal/index.ts +1 -0
  74. package/src/ui/modal/modal.tsx +128 -0
  75. package/src/ui/otp-input/index.ts +1 -0
  76. package/src/ui/otp-input/otp-input.tsx +78 -0
  77. package/src/ui/pagination/index.ts +1 -0
  78. package/src/ui/pagination/pagination.tsx +138 -0
  79. package/src/ui/radio-group/index.ts +1 -0
  80. package/src/ui/radio-group/radio-group.tsx +81 -0
  81. package/src/ui/select/index.ts +1 -0
  82. package/src/ui/select/select.tsx +215 -0
  83. package/src/ui/separator/index.ts +1 -0
  84. package/src/ui/separator/separator.tsx +54 -0
  85. package/src/ui/skeleton/index.ts +1 -0
  86. package/src/ui/skeleton/skeleton.tsx +44 -0
  87. package/src/ui/spinner/index.ts +1 -0
  88. package/src/ui/spinner/spinner.tsx +33 -0
  89. package/src/ui/switch/index.ts +1 -0
  90. package/src/ui/switch/switch.tsx +48 -0
  91. package/src/ui/tabs/index.ts +1 -0
  92. package/src/ui/tabs/tabs.tsx +190 -0
  93. package/src/ui/textarea/index.ts +1 -0
  94. package/src/ui/textarea/textarea.tsx +151 -0
  95. package/src/ui/theme-switch/index.ts +1 -0
  96. package/src/ui/theme-switch/theme-switch.tsx +161 -0
  97. package/src/ui/toast/index.ts +1 -0
  98. package/src/ui/toast/toast.tsx +159 -0
  99. package/src/utils/api/stringFormat.ts +5 -0
  100. package/src/utils/clearAllCookies.ts +7 -0
  101. package/src/utils/clsx.ts +18 -0
  102. package/src/utils/confirm.ts +48 -0
  103. package/src/utils/copy-to-clipboard.ts +12 -0
  104. package/src/utils/date/convertTimestamp.ts +44 -0
  105. package/src/utils/date/formatCountdown.ts +9 -0
  106. package/src/utils/date/formatDayLabel.ts +50 -0
  107. package/src/utils/date/formatRelativeDateTime.ts +34 -0
  108. package/src/utils/date/locales.ts +9 -0
  109. package/src/utils/form/validationSchema.ts +46 -0
  110. package/src/utils/getByKeyString.ts +15 -0
  111. package/src/utils/getCssVar.ts +2 -0
  112. package/src/utils/getDeepType.ts +3 -0
  113. package/src/utils/getQueryParams.ts +21 -0
  114. package/src/utils/inAppBrowser.ts +151 -0
  115. package/src/utils/index.ts +28 -0
  116. package/src/utils/isRTL.ts +29 -0
  117. package/src/utils/notify.ts +46 -0
  118. package/src/utils/openExternal.ts +27 -0
  119. package/src/utils/system/getMillisecondsPeriod.ts +31 -0
  120. package/src/utils/validation/authValidators.ts +23 -0
  121. package/src/utils/validation/refCode.ts +30 -0
  122. package/styles/base.css +97 -0
  123. package/styles/brand.css +36 -0
  124. package/styles/index.css +19 -0
  125. package/styles/motion.css +207 -0
  126. package/styles/semantic.css +151 -0
  127. package/styles/theme.css +143 -0
  128. package/styles/utilities.css +289 -0
package/README.md ADDED
@@ -0,0 +1,168 @@
1
+ # hallo-kit
2
+
3
+ Дизайн-система Hallo: UI-кит, токены, хуки и утилиты. Один источник правды для кабинета
4
+ и сайтов проекта — вместо копирования файлов между репозиториями.
5
+
6
+ Публикуется в npm как `hallo-kit`.
7
+
8
+ ## Установка
9
+
10
+ ```bash
11
+ yarn add hallo-kit
12
+ npx hallo-kit init
13
+ ```
14
+
15
+ Обычный публичный пакет: ставится везде без ключей и токенов — локально, в CI, в Docker.
16
+
17
+ ## Подключение одной командой
18
+
19
+ ```bash
20
+ npx hallo-kit init
21
+ ```
22
+
23
+ Пропишет транспиляцию в `next.config` и подключит стили с `@source` в `globals.css`.
24
+ Запускать можно повторно — ничего не задвоится.
25
+
26
+ `npx hallo-kit doctor` — проверить уже подключённый проект: частая причина «стили
27
+ поехали» это потерянный `@source`.
28
+
29
+ Дальше — что делает init, если понадобится вручную.
30
+
31
+ ### 1. Транспиляция
32
+
33
+ Кит отдаётся исходниками (TS/TSX), без сборки — так не теряются директивы `'use client'`
34
+ и работает нормальный HMR при правке кита. Next должен его транспилировать:
35
+
36
+ ```ts
37
+ // next.config.ts
38
+ const nextConfig: NextConfig = {
39
+ transpilePackages: ['hallo-kit'],
40
+ }
41
+ ```
42
+
43
+ ### 2. Стили
44
+
45
+ ```css
46
+ /* src/app/globals.css */
47
+ @import 'tailwindcss';
48
+ @import 'hallo-kit/styles.css';
49
+
50
+ @source '../../node_modules/hallo-kit/src';
51
+ ```
52
+
53
+ Строка `@source` **обязательна**. Без неё Tailwind не сканирует классы внутри пакета,
54
+ и половина стилей компонентов не попадёт в бандл — кнопки приедут без размеров.
55
+
56
+ ### 3. Шрифт и провайдеры
57
+
58
+ ```tsx
59
+ import { manrope } from 'hallo-kit/fonts'
60
+ import { ConfirmDialogHost, ThemeColorSync, ThemeProvider, Toaster } from 'hallo-kit'
61
+
62
+ <html className={manrope.variable}>
63
+ <body>
64
+ <ThemeProvider>
65
+ {children}
66
+ <ConfirmDialogHost />
67
+ <Toaster />
68
+ <ThemeColorSync />
69
+ </ThemeProvider>
70
+ </body>
71
+ </html>
72
+ ```
73
+
74
+ ## Точки входа
75
+
76
+ | Импорт | Что внутри | Нужен Next |
77
+ | --- | --- | --- |
78
+ | `hallo-kit` | UI-компоненты, логотип, тема | нет |
79
+ | `hallo-kit/hooks` | `useDevice`, `usePlatform`, `useMediaQuery`, `useCountdown`, `useTelegram` … | нет |
80
+ | `hallo-kit/utils` | `cn`, даты, буфер обмена, валидация, `notify` | нет |
81
+ | `hallo-kit/i18n` | порт локализации | нет |
82
+ | `hallo-kit/next` | крошки, `Image`, `useQueryParams` | да |
83
+ | `hallo-kit/fonts` | Manrope через `next/font` | да |
84
+ | `hallo-kit/server` | `getInitialDevice` — только для Server Components | да |
85
+ | `hallo-kit/styles.css` | токены, утилиты, анимации | нет |
86
+
87
+ Next-зависимости собраны в три последних входа намеренно: основная часть кита — обычный
88
+ React, и держать её свободной от фреймворка дешевле, чем потом расплетать.
89
+
90
+ ## Не только Next
91
+
92
+ Кит собирается в Vite — проверено сборкой: компоненты, токены и fluid-утилиты доезжают.
93
+ `next-themes`, вопреки названию, к Next не привязан: в его peerDependencies только react.
94
+
95
+ ```ts
96
+ // vite.config.ts
97
+ export default defineConfig({
98
+ plugins: [react(), tailwindcss()],
99
+ // кит отдаётся исходниками TSX — исключаем из pre-bundling, чтобы Vite прогонял
100
+ // его через свой transform, а не через esbuild-предсборку зависимостей
101
+ optimizeDeps: { exclude: ['hallo-kit'] },
102
+ })
103
+ ```
104
+
105
+ ```css
106
+ /* src/index.css */
107
+ @import 'tailwindcss';
108
+ @import 'hallo-kit/styles.css';
109
+
110
+ @source '../node_modules/hallo-kit/src';
111
+ ```
112
+
113
+ Шрифт вне Next подключается своим `@font-face` — файл лежит в `hallo-kit/fonts/Manrope/`.
114
+
115
+ ## Свой бренд
116
+
117
+ Кит красится двумя десятками переменных из [`styles/brand.css`](styles/brand.css).
118
+ Переопредели их в своём css **после** импорта кита — семантический слой и все компоненты
119
+ подхватят новые цвета сами:
120
+
121
+ ```css
122
+ @import 'hallo-kit/styles.css';
123
+
124
+ :root {
125
+ --brand-blue: #7c3aed;
126
+ --deep-navy: #1e1b4b;
127
+ }
128
+ ```
129
+
130
+ Менять `--primary`, `--background` и прочую семантику не нужно — она считается от бренда.
131
+
132
+ ## Локализация
133
+
134
+ Кит не знает, чем приложение переводит тексты: он объявляет порт, приложение подключает
135
+ свою реализацию. Без провайдера работает встроенный словарь (ru/en) — новый лендинг
136
+ заводится без настройки i18n вообще.
137
+
138
+ ```tsx
139
+ import { KitI18nProvider } from 'hallo-kit/i18n'
140
+
141
+ <KitI18nProvider locale={locale} t={(scope, key) => /* ваш перевод или undefined */}>
142
+ ```
143
+
144
+ Переопределяемые ключи: `ui.confirm.{cancel,confirm}`,
145
+ `ui.actions.{clear,paste,copy,copied}`, `ui.toast.copied`.
146
+
147
+ Рабочий пример подключения — `src/config/providers/KitI18nBridge.tsx` в кабинете.
148
+
149
+ ## Уведомления
150
+
151
+ `notify()` — порт без привязки к UI: инфраструктурный код зовёт его, не зная о тостах.
152
+ `<Toaster />` подключает реальный показ. До подключения — сообщения в консоль.
153
+
154
+ ## Разработка
155
+
156
+ ```bash
157
+ yarn install
158
+ yarn typecheck
159
+ ```
160
+
161
+ Править кит вместе с приложением удобно через `yarn link`. Учти: при линковке
162
+ подтягиваются `node_modules` самого кита, и приложение может получить вторую копию
163
+ React — если пойдут ошибки хуков, ставь кит из ветки git вместо линка.
164
+
165
+ ## Что сюда НЕ входит
166
+
167
+ Домен: API-клиент, запросы и мутации react-query, авторизация, тарифы, платежи,
168
+ устройства, поддержка. Всё это остаётся в приложениях.
package/bin/cli.mjs ADDED
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ // Подключение кита к проекту одной командой: npx hallo-kit init
3
+ //
4
+ // Делает то же, что руками: transpilePackages в next.config, импорт стилей и @source
5
+ // в globals.css. Отдельной командой, а не postinstall-хуком: пакет, который сам правит
6
+ // файлы проекта, ломается на --ignore-scripts и молча переписывает то, чего не просили.
7
+ //
8
+ // Скрипт идемпотентный — повторный запуск ничего не дублирует.
9
+
10
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
11
+ import { join, relative, dirname } from 'node:path'
12
+
13
+ const PKG = 'hallo-kit'
14
+ const cwd = process.cwd()
15
+ const cmd = process.argv[2]
16
+
17
+ const ok = (m) => console.log(' ✓ ' + m)
18
+ const skip = (m) => console.log(' · ' + m)
19
+ const warn = (m) => console.log(' ! ' + m)
20
+
21
+ const findFile = (names) => names.map((f) => join(cwd, f)).find(existsSync)
22
+
23
+ const NEXT_CONFIGS = ['next.config.ts', 'next.config.mjs', 'next.config.js']
24
+ const CSS_FILES = ['src/app/globals.css', 'app/globals.css', 'src/index.css', 'src/styles/globals.css']
25
+
26
+ // ── next.config: транспиляция ────────────────────────────────────────────────
27
+ // Кит отдаётся исходниками TS/TSX, поэтому Next обязан прогнать его через свой
28
+ // конвейер — иначе сборка споткнётся на первом же .tsx из node_modules.
29
+ function patchNextConfig() {
30
+ const file = findFile(NEXT_CONFIGS)
31
+ if (!file) return warn('next.config не найден — не Next-проект? Для Vite см. README')
32
+
33
+ const src = readFileSync(file, 'utf8')
34
+ if (src.includes(`'${PKG}'`) && src.includes('transpilePackages')) {
35
+ return skip('next.config: транспиляция уже настроена')
36
+ }
37
+
38
+ if (src.includes('transpilePackages')) {
39
+ writeFileSync(file, src.replace(/transpilePackages:\s*\[/, `transpilePackages: ['${PKG}', `))
40
+ return ok(`next.config: ${PKG} добавлен в transpilePackages`)
41
+ }
42
+
43
+ const m = src.match(/(const\s+\w+(?::\s*NextConfig)?\s*=\s*\{|export default\s*\{|defineConfig\(\{)/)
44
+ if (!m) return warn(`next.config: не понял структуру — добавь вручную transpilePackages: ['${PKG}']`)
45
+
46
+ const insert = `${m[0]}\n\t// Кит отдаётся исходниками (TS/TSX) — Next транспилирует его сам: так не теряются\n\t// директивы 'use client' и работает HMR при локальной правке кита.\n\ttranspilePackages: ['${PKG}'],`
47
+ writeFileSync(file, src.replace(m[0], insert))
48
+ ok('next.config: транспиляция настроена')
49
+ }
50
+
51
+ // ── globals.css: стили и сканирование классов ────────────────────────────────
52
+ function patchCss() {
53
+ const file = findFile(CSS_FILES)
54
+ if (!file) return warn('globals.css не найден — подключи стили кита в свой корневой css вручную')
55
+
56
+ const src = readFileSync(file, 'utf8')
57
+ if (src.includes(`${PKG}/styles.css`)) return skip('css: стили кита уже подключены')
58
+
59
+ // @source считается ОТНОСИТЕЛЬНО css-файла, иначе Tailwind не найдёт исходники
60
+ // и классы кита не попадут в бандл — кнопки приедут без размеров.
61
+ const rel = relative(dirname(file), join(cwd, 'node_modules', PKG, 'src')).split('\\').join('/')
62
+
63
+ const block = [
64
+ `@import '${PKG}/styles.css';`,
65
+ '',
66
+ '/* Без @source Tailwind не сканирует классы внутри node_modules, и половина стилей',
67
+ ' компонентов кита не попадёт в бандл. */',
68
+ `@source '${rel}';`,
69
+ '',
70
+ ].join('\n')
71
+
72
+ // строго после @import 'tailwindcss': иначе сброс Tailwind перекроет токены кита
73
+ if (/@import\s+['"]tailwindcss['"];?/.test(src)) {
74
+ writeFileSync(file, src.replace(/(@import\s+['"]tailwindcss['"];?\r?\n)/, `$1\n${block}`))
75
+ } else {
76
+ writeFileSync(file, `@import 'tailwindcss';\n\n${block}${src}`)
77
+ }
78
+ ok('css: стили и @source подключены')
79
+ }
80
+
81
+ // ── подсказка по layout ──────────────────────────────────────────────────────
82
+ // JSX-дерево не трогаем: воткнуть провайдер не в тот уровень контекстов слишком легко,
83
+ // а ловить потом тяжело. Показываем, что дописать.
84
+ function hintLayout() {
85
+ const file = findFile(['src/app/layout.tsx', 'app/layout.tsx'])
86
+ if (!file) return
87
+ if (readFileSync(file, 'utf8').includes(PKG)) return skip('layout: провайдеры кита уже подключены')
88
+
89
+ console.log('\n Осталось вручную — в ' + relative(cwd, file) + ':\n')
90
+ console.log(` import { manrope } from '${PKG}/fonts'`)
91
+ console.log(` import { ThemeProvider, Toaster, ConfirmDialogHost } from '${PKG}'`)
92
+ console.log('')
93
+ console.log(' <html className={manrope.variable}>')
94
+ console.log(' <body>')
95
+ console.log(' <ThemeProvider>')
96
+ console.log(' {children}')
97
+ console.log(' <ConfirmDialogHost />')
98
+ console.log(' <Toaster />')
99
+ console.log(' </ThemeProvider>')
100
+ console.log(' </body>')
101
+ console.log(' </html>')
102
+ }
103
+
104
+ if (cmd === 'init') {
105
+ console.log(`\nПодключаю ${PKG}:\n`)
106
+ patchNextConfig()
107
+ patchCss()
108
+ hintLayout()
109
+ console.log('\nГотово. Свой бренд — переопредели --brand-blue и --deep-navy после импорта кита.\n')
110
+ } else if (cmd === 'doctor') {
111
+ console.log('\nПроверка:\n')
112
+ const css = findFile(CSS_FILES)
113
+ if (!css) warn('корневой css не найден')
114
+ else if (readFileSync(css, 'utf8').includes('@source')) ok('css: @source на месте')
115
+ else warn('css: нет @source — стили компонентов приедут не полностью')
116
+
117
+ const cfg = findFile(NEXT_CONFIGS)
118
+ if (!cfg) skip('next.config не найден (не Next-проект)')
119
+ else if (readFileSync(cfg, 'utf8').includes('transpilePackages')) ok('next.config: транспиляция на месте')
120
+ else warn('next.config: нет transpilePackages — сборка споткнётся на .tsx из пакета')
121
+
122
+ const pkg = join(cwd, 'node_modules', PKG, 'package.json')
123
+ if (existsSync(pkg)) ok(`установлен ${PKG}@${JSON.parse(readFileSync(pkg, 'utf8')).version}`)
124
+ else warn(`${PKG} не установлен: yarn add ${PKG}`)
125
+ console.log('')
126
+ } else {
127
+ console.log(`
128
+ ${PKG} — дизайн-система Hallo
129
+
130
+ npx ${PKG} init подключить кит к проекту (next.config + стили)
131
+ npx ${PKG} doctor проверить, всё ли подключено
132
+
133
+ Установка пакета:
134
+ yarn add ${PKG}
135
+ `)
136
+ }
@@ -0,0 +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.
package/fonts/index.ts ADDED
@@ -0,0 +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
+ })
package/package.json ADDED
@@ -0,0 +1,77 @@
1
+ {
2
+ "name": "hallo-kit",
3
+ "version": "0.3.0",
4
+ "description": "Дизайн-система Hallo: UI-кит, токены, хуки и утилиты для сайтов проекта",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "sideEffects": [
8
+ "*.css"
9
+ ],
10
+ "files": [
11
+ "src",
12
+ "styles",
13
+ "fonts",
14
+ "bin",
15
+ "README.md"
16
+ ],
17
+ "bin": {
18
+ "hallo-kit": "./bin/cli.mjs"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "exports": {
24
+ ".": "./src/index.ts",
25
+ "./hooks": "./src/hooks/index.ts",
26
+ "./utils": "./src/utils/index.ts",
27
+ "./i18n": "./src/i18n/index.tsx",
28
+ "./next": "./src/next.ts",
29
+ "./fonts": "./fonts/index.ts",
30
+ "./server": "./src/server.ts",
31
+ "./styles.css": "./styles/index.css",
32
+ "./package.json": "./package.json"
33
+ },
34
+ "peerDependencies": {
35
+ "next": ">=16",
36
+ "react": ">=19",
37
+ "react-dom": ">=19",
38
+ "tailwindcss": ">=4"
39
+ },
40
+ "dependencies": {
41
+ "@hookform/resolvers": "^5.4.0",
42
+ "@radix-ui/react-dialog": "^1.1.17",
43
+ "@radix-ui/react-label": "^2.1.10",
44
+ "@radix-ui/react-one-time-password-field": "^0.1.11",
45
+ "@radix-ui/react-radio-group": "^1.4.2",
46
+ "@radix-ui/react-select": "^2.3.0",
47
+ "@radix-ui/react-separator": "^1.1.10",
48
+ "@radix-ui/react-slot": "^1.2.5",
49
+ "@radix-ui/react-switch": "^1.3.1",
50
+ "@radix-ui/react-tabs": "^1.1.14",
51
+ "@radix-ui/react-toast": "^1.2.16",
52
+ "@tanstack/react-virtual": "^3.14.3",
53
+ "class-variance-authority": "^0.7.1",
54
+ "clsx": "^2.1.1",
55
+ "date-fns": "^4.4.0",
56
+ "js-cookie": "^3.0.8",
57
+ "next-themes": "^0.4.6",
58
+ "react-hook-form": "^7.80.0",
59
+ "tailwind-merge": "^3.6.0",
60
+ "tw-animate-css": "^1.4.0",
61
+ "validator": "^13.15.35",
62
+ "vaul": "^1.1.2",
63
+ "yup": "^1.7.1",
64
+ "zustand": "^5.0.14"
65
+ },
66
+ "devDependencies": {
67
+ "@types/js-cookie": "^3.0.6",
68
+ "@types/node": "^20",
69
+ "@types/react": "^19",
70
+ "@types/react-dom": "^19",
71
+ "@types/validator": "^13.15.10",
72
+ "typescript": "^5"
73
+ },
74
+ "scripts": {
75
+ "typecheck": "tsc --noEmit"
76
+ }
77
+ }
package/src/config.ts ADDED
@@ -0,0 +1,11 @@
1
+ // Общие константы кита. Имена совпадают с кабинетом (@/config/namespaces), чтобы
2
+ // перенос кабинета на кит не менял поведение уже выставленных у пользователей кук.
3
+
4
+ /** Куки, которые кит пишет и читает сам. */
5
+ export const KitCookies = {
6
+ /**
7
+ * Тип устройства по реальной ширине вьюпорта. Пишет DeviceProvider на клиенте,
8
+ * читает getInitialDevice на сервере — так SSR отдаёт правильную версию без вспышки.
9
+ */
10
+ DEVICE: 'device',
11
+ } as const
@@ -0,0 +1,14 @@
1
+ // Хуки кита: платформа, адаптив, скролл, таймеры.
2
+
3
+ export * from './useAutoHideOnScroll'
4
+ export * from './useCountdown'
5
+ export * from './useDevice'
6
+ export * from './useIsTelegramMiniApp'
7
+ export * from './useIsTouch'
8
+ export * from './useKeyboardOpen'
9
+ export * from './useMediaQuery'
10
+ export * from './usePlatform'
11
+ export * from './useRevealOnce'
12
+ export * from './useScrolledPast'
13
+ export * from './useSettleOnce'
14
+ export * from './useTelegram'
@@ -0,0 +1,26 @@
1
+ 'use client'
2
+
3
+ import { useEffect, useState } from 'react'
4
+
5
+ // Автопрятание sticky-шапки: глубже threshold px от верха скролл ВНИЗ прячет (true),
6
+ // скролл ВВЕРХ больше чем на upDelta px (отсекает дрожание тач-скролла) или возврат
7
+ // к верху — показывает. Слушатель passive; setState с тем же boolean ре-рендер не даёт.
8
+ export function useAutoHideOnScroll(threshold = 120, upDelta = 6): boolean {
9
+ const [hidden, setHidden] = useState(false)
10
+
11
+ useEffect(() => {
12
+ let lastY = window.scrollY
13
+ const onScroll = () => {
14
+ // iOS bounce отдаёт отрицательный scrollY — клампим, иначе ложный «скролл вверх».
15
+ const y = Math.max(window.scrollY, 0)
16
+ if (y <= threshold) setHidden(false)
17
+ else if (y > lastY) setHidden(true)
18
+ else if (lastY - y > upDelta) setHidden(false)
19
+ lastY = y
20
+ }
21
+ window.addEventListener('scroll', onScroll, { passive: true })
22
+ return () => window.removeEventListener('scroll', onScroll)
23
+ }, [threshold, upDelta])
24
+
25
+ return hidden
26
+ }
@@ -0,0 +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
+ }