@rock555/frontend-core 3.1.2 → 3.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.
package/README.md CHANGED
@@ -33,6 +33,8 @@ plugins: [frontendCore(), /* ... */],
33
33
 
34
34
  Залежності ядра (`peerDependencies`) ставить сам проєкт. Необов'язкові: `vis-data` і `vis-timeline` для `TimelineChart`, `vue-sonner` для `ExportButton`, `motion-v` для `SortControlPanel`.
35
35
 
36
+ Глобальні стилі ядра проєкт імпортує один раз в `app.ts`: `@/_shared/styles/table.scss` і `@/_shared/styles/toast.scss`.
37
+
36
38
  Підключати конфіг так, щоб `SharedConfig.configure()` спрацював до першого рендера. На рівні модуля читати тексти не можна, це перевіряє `tests/core/config-timing.test.ts`.
37
39
 
38
40
  ## Що проєкт зобов'язаний дати
@@ -46,18 +48,19 @@ plugins: [frontendCore(), /* ... */],
46
48
  - `$color-accent-ink`: текст акцентом і заливка під білим текстом, не менше 4,5:1 до `$color-surface` і `$color-accent-dim`.
47
49
  - `$color-accent-dim`: фон вибраного.
48
50
  - `$color-green-ink`, `$color-danger`: текст, не менше 4,5:1 до `$color-surface`.
49
- - Бейджі: `$color-green`, `$color-green-soft`, `$color-danger-soft`, `$color-danger-ink`, `$color-warning-soft`, `$color-warning-ink`, `$color-neutral-soft`, `$color-neutral-ink`, `$color-teal-soft`, `$color-teal-ink`.
51
+ - Бейджі й тости: `$color-green`, `$color-green-soft`, `$color-danger-soft`, `$color-danger-ink`, `$color-warning`, `$color-warning-soft`, `$color-warning-ink`, `$color-neutral-soft`, `$color-neutral-ink`, `$color-teal-soft`, `$color-teal-ink`.
50
52
  - `$color-selected`, `$color-on-selected`: заливка вибраного (день у календарі, плитка) і текст на ній, не менше 4,5:1.
51
- - Інше: `$radius`, `$anim-small-time`, `$table-cell-padding-x`, `$table-cell-padding-y`.
52
- - Міксини: `scrollbarStyle`, `bigMobile` і `buttonPrimary` (вигляд головної кнопки, бренд проєкту).
53
+ - Інше: `$radius`, `$table-cell-padding-x`, `$table-cell-padding-y`.
54
+ - Міксини: спільні (`bigMobile`, `anim`, `sectionCaption`, `scrollbarStyle`, `$anim-small-time` і брейкпоінти) дає ядро, проєкт лише пересилає їх у своєму `_mixins.scss`: `@forward '@/_shared/styles/mixins' with ($muted: $color-muted);`. Своє тільки `buttonPrimary` (вигляд головної кнопки, бренд проєкту).
53
55
 
54
56
  Через `SharedConfig.configure()`, повний список у [src/config.ts](src/config.ts):
55
57
 
56
- - `labels`: усі тексти інтерфейсу ядра, `formatNumber`, `formatMoney`.
58
+ - `labels`: усі тексти інтерфейсу ядра. Числа й гроші ядро форматує само (`NumberHelper`, `MoneyHelper`); `formatNumber` і `formatMoney` — лише щоб замінити формат.
57
59
  - `errors`: словник кодів бека, тексти за HTTP-статусом, текст за правилом валідації. Логіка ланцюжка в `errors/apiError.helper`, слова в проєкту.
58
60
  - `notifyError`: як показати помилку (тост, стор сповіщень, кнопка «Увійти»).
59
61
  - `link`: компонент посилання для `UiButton`: `{ component: RouterLink, prop: 'to' }` чи `{ component: Link, prop: 'href' }`.
60
62
  - `goBack`: «Назад» у `UiBackLink`.
63
+ - `currentPath` (необов'язково): шлях поточної сторінки для `UiPageTabs`, реактивно. Без нього — `window.location.pathname`.
61
64
 
62
65
  Свій варіант кнопки (`<UiButton variant="violet">`) проєкт описує глобально. Селектор `.ui-btn.ui-btn--violet.ui-btn--violet`: scoped-стилі кнопки в ядрі сильніші за один клас.
63
66
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rock555/frontend-core",
3
- "version": "3.1.2",
3
+ "version": "3.3.0",
4
4
  "description": "Спільне фронтове ядро: API-клієнт, таблиці, форми, модалки, хелпери",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { Loader2 } from '@lucide/vue'
8
8
  import { SharedConfig } from '../../config'
9
+ import { NumberHelper } from '../../helpers/number.helper'
9
10
 
10
11
  defineProps<{
11
12
  /** «Усього», «Водіїв», «Звітів». */
@@ -17,7 +18,8 @@ defineProps<{
17
18
  total: number | null
18
19
  isLoadingMore: boolean
19
20
  }>()
20
- const { labels, formatNumber } = SharedConfig.get()
21
+ const { labels } = SharedConfig.get()
22
+ const formatNumber = SharedConfig.get().formatNumber ?? NumberHelper.format
21
23
  </script>
22
24
 
23
25
  <template>
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { Loader2 } from '@lucide/vue'
6
6
  import { SharedConfig } from '../../config'
7
+ import { NumberHelper } from '../../helpers/number.helper'
7
8
 
8
9
  defineProps<{
9
10
  loaded: number
@@ -11,7 +12,8 @@ defineProps<{
11
12
  total: number | null
12
13
  isLoadingMore: boolean
13
14
  }>()
14
- const { labels, formatNumber } = SharedConfig.get()
15
+ const { labels } = SharedConfig.get()
16
+ const formatNumber = SharedConfig.get().formatNumber ?? NumberHelper.format
15
17
  </script>
16
18
 
17
19
  <template>
@@ -5,6 +5,7 @@
5
5
  import { ChevronLeft, ChevronRight } from '@lucide/vue'
6
6
  import UiIconButton from '../ui/UiIconButton.vue'
7
7
  import { SharedConfig } from '../../config'
8
+ import { NumberHelper } from '../../helpers/number.helper'
8
9
 
9
10
  interface Props {
10
11
  page: number
@@ -25,7 +26,8 @@ const emit = defineEmits<{
25
26
  'update:perPage': [perPage: number]
26
27
  }>()
27
28
 
28
- const { labels, formatNumber } = SharedConfig.get()
29
+ const { labels } = SharedConfig.get()
30
+ const formatNumber = SharedConfig.get().formatNumber ?? NumberHelper.format
29
31
  </script>
30
32
 
31
33
  <template>
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { computed } from 'vue'
6
6
  import { SharedConfig } from '../../../config'
7
+ import { NumberHelper } from '../../../helpers/number.helper'
7
8
 
8
9
  interface Props {
9
10
  value: number | null
@@ -20,7 +21,7 @@ const formatted = computed(() => {
20
21
  const rounded = props.precision === 0
21
22
  ? Math.round(props.value)
22
23
  : Number(props.value.toFixed(props.precision))
23
- const num = SharedConfig.get().formatNumber(rounded)
24
+ const num = (SharedConfig.get().formatNumber ?? NumberHelper.format)(rounded)
24
25
  return props.suffix ? `${num} ${props.suffix}` : num
25
26
  })
26
27
  </script>
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { computed } from 'vue'
10
10
  import { SharedConfig } from '../../../config'
11
+ import { MoneyHelper } from '../../../helpers/money.helper'
11
12
 
12
13
  interface Props {
13
14
  value: number | null
@@ -15,7 +16,7 @@ interface Props {
15
16
  }
16
17
 
17
18
  const props = defineProps<Props>()
18
- const formatted = computed(() => props.value === null ? '—' : SharedConfig.get().formatMoney(props.value))
19
+ const formatted = computed(() => props.value === null ? '—' : (SharedConfig.get().formatMoney ?? MoneyHelper.format)(props.value))
19
20
 
20
21
  // 'positive' зі знаком: дохід >= 0 → зелений, < 0 → червоний.
21
22
  const tone = computed<'positive' | 'negative' | 'muted' | 'danger' | null>(() => {
@@ -0,0 +1,34 @@
1
+ <script setup lang="ts">
2
+ // Дані запису списком «підпис — значення» з тонкими роздільниками. Рядки —
3
+ // UiDetailsRow: підписи колонкою однакової ширини, значення ліворуч з однієї вертикалі.
4
+ withDefaults(
5
+ defineProps<{
6
+ /** Дві колонки рядків на сторінці; одна — у вузькій панелі. На телефоні завжди одна. */
7
+ columns?: 1 | 2
8
+ }>(),
9
+ { columns: 2 },
10
+ )
11
+ </script>
12
+
13
+ <template>
14
+ <dl class="ui-details" :class="{ 'ui-details--single': columns === 1 }"><slot /></dl>
15
+ </template>
16
+
17
+ <style lang="scss" scoped>
18
+ .ui-details {
19
+ display: grid;
20
+ grid-template-columns: repeat(2, minmax(0, 1fr));
21
+ column-gap: 2rem;
22
+ margin: 0;
23
+ }
24
+
25
+ .ui-details--single {
26
+ grid-template-columns: minmax(0, 1fr);
27
+ }
28
+
29
+ @media (max-width: 760px) {
30
+ .ui-details {
31
+ grid-template-columns: minmax(0, 1fr);
32
+ }
33
+ }
34
+ </style>
@@ -0,0 +1,64 @@
1
+ <script setup lang="ts">
2
+ withDefaults(
3
+ defineProps<{
4
+ label: string
5
+ /** Число (сума, пробіг, кількість): цифри однакової ширини, без переносу. */
6
+ numeric?: boolean
7
+ /** Рядок на всю ширину — довгий текст (коментар). */
8
+ wide?: boolean
9
+ }>(),
10
+ { numeric: false, wide: false },
11
+ )
12
+ </script>
13
+
14
+ <template>
15
+ <div
16
+ class="ui-details-row"
17
+ :class="{ 'ui-details-row--numeric': numeric, 'ui-details-row--wide': wide }"
18
+ >
19
+ <dt>{{ label }}</dt>
20
+ <dd><slot /></dd>
21
+ </div>
22
+ </template>
23
+
24
+ <style lang="scss" scoped>
25
+ // Усі значення ліворуч, з однієї вертикалі після колонки підписів — і текст, і
26
+ // числа. «Числа праворуч» — правило таблиць: там у колонці одна величина. Тут у
27
+ // кожному рядку своя, і значення, що стрибають то вліво, то вправо, читаються гірше.
28
+ .ui-details-row {
29
+ display: grid;
30
+ // Ширина колонки підписів: вузька панель задає свою через `--ui-details-label`.
31
+ grid-template-columns: var(--ui-details-label, 12rem) minmax(0, 1fr);
32
+ align-items: baseline;
33
+ gap: 1rem;
34
+ min-width: 0;
35
+ padding: 0.7rem 0;
36
+ border-bottom: 1px solid $color-border;
37
+
38
+ dt {
39
+ color: $color-muted;
40
+ }
41
+
42
+ dd {
43
+ min-width: 0;
44
+ margin: 0;
45
+ font-weight: 500;
46
+ overflow-wrap: anywhere;
47
+ }
48
+ }
49
+
50
+ .ui-details-row--numeric dd {
51
+ font-variant-numeric: tabular-nums;
52
+ white-space: nowrap;
53
+ }
54
+
55
+ .ui-details-row--wide {
56
+ grid-column: 1 / -1;
57
+ grid-template-columns: minmax(0, 1fr);
58
+ gap: 0.25rem;
59
+
60
+ dd {
61
+ font-weight: 400;
62
+ }
63
+ }
64
+ </style>
@@ -0,0 +1,81 @@
1
+ <script setup lang="ts">
2
+ // Вкладки розділу поруч із заголовком сторінки: «Водії · Список | Підозріла активність».
3
+ //
4
+ // Кожна вкладка — окрема адреса, тому це навігація з посиланнями й
5
+ // aria-current, а не WAI-ARIA tablist: у вкладок різні дані й права, «Назад» і
6
+ // посилання колезі мають працювати. Перемикач у межах однієї сторінки —
7
+ // reka-ui Tabs; значення фільтра — UiSegmented.
8
+ //
9
+ // Вкладки без права проєкт прибирає сам, до передачі сюди: права знає він.
10
+ // Лишилась одна вкладка — не малюємо нічого, бо перемикати нема між чим.
11
+
12
+ import { computed } from 'vue'
13
+ import UiCount from './UiCount.vue'
14
+ import type { UiPageTab } from './uiPageTabs.types'
15
+ import { SharedConfig } from '../../config'
16
+
17
+ defineProps<{
18
+ items: UiPageTab[]
19
+ /** Назва навігації для скрінрідера. */
20
+ label: string
21
+ }>()
22
+
23
+ const { link, currentPath } = SharedConfig.get()
24
+
25
+ // Без `currentPath` у конфігу — адреса вкладки браузера: годиться, коли
26
+ // сторінка з вкладками перемонтовується на кожен перехід.
27
+ const pathname = computed(() => currentPath?.() ?? window.location.pathname)
28
+ </script>
29
+
30
+ <template>
31
+ <nav v-if="items.length > 1" class="ui-page-tabs" :aria-label="label">
32
+ <component
33
+ :is="link.component"
34
+ v-for="tab in items"
35
+ :key="tab.href"
36
+ v-bind="{ [link.prop]: tab.href }"
37
+ class="ui-page-tabs__item"
38
+ :class="{ 'ui-page-tabs__item--active': pathname === tab.href }"
39
+ :aria-current="pathname === tab.href ? 'page' : undefined"
40
+ >
41
+ {{ tab.label }}
42
+ <UiCount v-if="tab.count" :value="tab.count" :is-strong="pathname === tab.href" />
43
+ </component>
44
+ </nav>
45
+ </template>
46
+
47
+ <style scoped lang="scss">
48
+ .ui-page-tabs {
49
+ display: flex;
50
+ align-items: center;
51
+ gap: 2px;
52
+ min-width: 0;
53
+ overflow-x: auto;
54
+ scrollbar-width: none;
55
+
56
+ &::-webkit-scrollbar { display: none; }
57
+
58
+ &__item {
59
+ display: inline-flex;
60
+ align-items: center;
61
+ gap: 6px;
62
+ padding: 5px 10px;
63
+ border: 1px solid transparent;
64
+ border-radius: 8px;
65
+ font-size: 13px;
66
+ color: $color-muted;
67
+ white-space: nowrap;
68
+ text-decoration: none;
69
+ transition: color 0.15s ease, background 0.15s ease;
70
+
71
+ &:hover { color: $color-text; }
72
+
73
+ &--active {
74
+ border-color: $color-border;
75
+ background: $color-surface;
76
+ color: $color-text;
77
+ font-weight: 600;
78
+ }
79
+ }
80
+ }
81
+ </style>
@@ -3,8 +3,9 @@ import { Upload, File as FileIcon, X } from '@lucide/vue';
3
3
  import { ref } from 'vue';
4
4
  import SmartField from './SmartField.vue';
5
5
  import { SharedConfig } from '../../../config'
6
+ import { FileHelper } from '../../../helpers/file.helper';
6
7
 
7
- defineProps<{
8
+ const props = defineProps<{
8
9
  label: string,
9
10
  name: string,
10
11
  accept?: string,
@@ -16,20 +17,38 @@ const labels = SharedConfig.get().labels
16
17
  const isDragging = ref(false);
17
18
 
18
19
  const onDragOver = (val: boolean) => isDragging.value = val;
20
+
21
+ // Діалог вибору сам фільтрує за `accept`, а перетягнутий файл і «Усі файли»
22
+ // в діалозі — ні. Не той файл зупиняємо тут, а не відповіддю бека після завантаження.
23
+ function pick(
24
+ file: File | undefined,
25
+ handleChange: (value: unknown) => void,
26
+ setErrors: (message: string) => void,
27
+ ): void {
28
+ if (!file) return;
29
+
30
+ if (!FileHelper.isAccepted(file, props.accept)) {
31
+ const accept = (props.accept ?? '').split(',').map(token => token.trim()).join(', ');
32
+ setErrors(labels.fileWrongType?.(accept) ?? accept);
33
+ return;
34
+ }
35
+
36
+ handleChange(file);
37
+ }
19
38
  </script>
20
39
 
21
40
  <template>
22
41
  <SmartField
23
42
  :name="name"
24
43
  :label="label"
25
- v-slot="{ handleChange, value, inputId }"
44
+ v-slot="{ handleChange, setErrors, value, inputId }"
26
45
  >
27
46
  <div
28
47
  class="file-field"
29
48
  :class="{ 'dragging': isDragging, 'has-file': !!value }"
30
49
  @dragover.prevent="onDragOver(true)"
31
50
  @dragleave.prevent="onDragOver(false)"
32
- @drop.prevent="onDragOver(false); handleChange($event.dataTransfer?.files[0])"
51
+ @drop.prevent="onDragOver(false); pick($event.dataTransfer?.files[0], handleChange, setErrors)"
33
52
  >
34
53
  <input
35
54
  type="file"
@@ -38,7 +57,7 @@ const onDragOver = (val: boolean) => isDragging.value = val;
38
57
  class="file-field__input"
39
58
  @change="(e) => {
40
59
  const input = e.target as HTMLInputElement;
41
- handleChange(input.files?.[0]);
60
+ pick(input.files?.[0], handleChange, setErrors);
42
61
  // Файл уже у формі. Без скидання той самий файл після «Прибрати»
43
62
  // вибрати знову не вийшло б: значення не змінилось — change немає.
44
63
  input.value = '';
@@ -0,0 +1,9 @@
1
+ // Окремим .ts, а не експортом з UiPageTabs.vue: для plain `tsc` `*.vue` — заглушка без іменованих експортів.
2
+
3
+ export interface UiPageTab {
4
+ label: string
5
+ /** Шлях сторінки: за ним і посилання, і активна вкладка. */
6
+ href: string
7
+ /** Лічильник черги («чекає перевірки»). null/0 — не показуємо. */
8
+ count?: number | null
9
+ }
package/src/config.ts CHANGED
@@ -16,6 +16,11 @@ export type SharedLabels = {
16
16
  dateTo: string
17
17
  fileDrop: string
18
18
  fileRemove: string
19
+ /**
20
+ * Файл не того типу, що в `accept` поля: «Підходять лише .csv, .xlsx».
21
+ * Без нього під полем буде сам перелік типів.
22
+ */
23
+ fileWrongType?: (accept: string) => string
19
24
  /** Пустое обязательное поле (zod: undefined / null). */
20
25
  required: string
21
26
  /** «Сторінка 2 з 9»: номер страницы ядро выделяет само, поэтому две части. */
@@ -125,8 +130,9 @@ export type SharedErrorTexts = {
125
130
 
126
131
  export type SharedConfigValue = {
127
132
  labels: SharedLabels
128
- formatNumber: (value: number) => string
129
- formatMoney: (value: number) => string
133
+ /** Свій формат чисел і грошей. Без них — `NumberHelper.format` і `MoneyHelper.format` ядра. */
134
+ formatNumber?: (value: number) => string
135
+ formatMoney?: (value: number) => string
130
136
  /** Тексти помилок API. */
131
137
  errors: SharedErrorTexts
132
138
  /**
@@ -138,6 +144,11 @@ export type SharedConfigValue = {
138
144
  link: { component: Component; prop: string }
139
145
  /** «Назад» у `UiBackLink`: по історії, а якщо її немає — на `fallback`. Роутер знає проєкт. */
140
146
  goBack: (fallback: string | object) => void
147
+ /**
148
+ * Шлях поточної сторінки для `UiPageTabs`, реактивно (`usePage().url`, `route.path`).
149
+ * Без нього — `window.location.pathname`.
150
+ */
151
+ currentPath?: () => string
141
152
  /** Сбой, который ядро уже показало на месте (список фильтра): только в трекинг. */
142
153
  reportError?: (error: unknown) => void
143
154
  }
@@ -11,4 +11,22 @@ export class FileHelper {
11
11
 
12
12
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
13
13
  }
14
+
15
+ /**
16
+ * Чи підходить файл під атрибут `accept`: розширення (`.xlsx`), група
17
+ * (`image/*`) чи точний тип (`application/pdf`). Без `accept` — будь-який.
18
+ */
19
+ static isAccepted(file: File, accept?: string): boolean {
20
+ const tokens = (accept ?? '').split(',').map(token => token.trim().toLowerCase()).filter(Boolean);
21
+ if (!tokens.length) return true;
22
+
23
+ const name = file.name.toLowerCase();
24
+ const type = file.type.toLowerCase();
25
+
26
+ return tokens.some(token => {
27
+ if (token.startsWith('.')) return name.endsWith(token);
28
+ if (token.endsWith('/*')) return type.startsWith(token.slice(0, -1));
29
+ return type === token;
30
+ });
31
+ }
14
32
  }
@@ -0,0 +1,56 @@
1
+ // Гроші для людини, однаково в усіх проєктах:
2
+ // - немає значення (null, порожньо, не число) — «—»: даних немає;
3
+ // - справжній нуль — «0 ₴», без копійок: видно, що це нуль, а не пропуск;
4
+ // - решта завжди з копійками, «1 500,00 ₴», щоб числа в колонці стояли рівно.
5
+ // Сума приходить числом чи десятковим рядком (`"1500.00"`): рядок Intl форматує
6
+ // як є, без заокруглення через float.
7
+
8
+ import { NumberHelper, numericValue } from './number.helper'
9
+
10
+ const LOCALE = 'uk-UA'
11
+
12
+ type Amount = number | string | null | undefined
13
+
14
+ const formatters = new Map<string, Intl.NumberFormat>()
15
+
16
+ function formatter(currency: string | null, fractionDigits: 0 | 2): Intl.NumberFormat {
17
+ const key = `${currency ?? ''}:${fractionDigits}`
18
+ let value = formatters.get(key)
19
+ if (!value) {
20
+ value = new Intl.NumberFormat(LOCALE, {
21
+ ...(currency ? { style: 'currency', currency, currencyDisplay: 'narrowSymbol' } : {}),
22
+ minimumFractionDigits: fractionDigits,
23
+ maximumFractionDigits: fractionDigits,
24
+ })
25
+ formatters.set(key, value)
26
+ }
27
+ return value
28
+ }
29
+
30
+ function render(amount: Amount, currency: string | null): string {
31
+ const numeric = numericValue(amount)
32
+ if (numeric === null) return '—'
33
+ if (Number(numeric) === 0) return formatter(currency, 0).format(0)
34
+ const value = typeof numeric === 'number' ? NumberHelper.round(numeric) : numeric
35
+ return formatter(currency, 2).format(value as number)
36
+ }
37
+
38
+ export class MoneyHelper {
39
+ /** 3274.34 -> "3 274,34 ₴", 0 -> "0 ₴", null -> «—». Валюта — код ISO: UAH, EUR, USD. */
40
+ static format(amount: Amount, currency = 'UAH'): string {
41
+ return render(amount, currency)
42
+ }
43
+
44
+ /** Те саме, але порожнє лишається `null`: KPI відрізняють «немає даних» від нуля. */
45
+ static formatOrNull(amount: Amount, currency = 'UAH'): string | null {
46
+ return numericValue(amount) === null ? null : render(amount, currency)
47
+ }
48
+
49
+ /**
50
+ * Без символу валюти: "3 274,34". Для пари в одній комірці ("12 800,00 / 5 400,00 ₴"),
51
+ * де символ ставиться раз у кінці. Одиночна сума — лише `format`.
52
+ */
53
+ static formatBare(amount: Amount): string {
54
+ return render(amount, null)
55
+ }
56
+ }
@@ -0,0 +1,72 @@
1
+ // Числа для людини: розряди пробілом, кома, слово в правильній формі. Локаль
2
+ // одна на всі проєкти — українська.
3
+
4
+ const LOCALE = 'uk-UA'
5
+
6
+ const pluralRules = new Intl.PluralRules(LOCALE)
7
+ const percentFormatter = new Intl.NumberFormat(LOCALE, { minimumFractionDigits: 1, maximumFractionDigits: 1 })
8
+ const formatters = new Map<number | undefined, Intl.NumberFormat>()
9
+
10
+ function formatter(maximumFractionDigits?: number): Intl.NumberFormat {
11
+ let value = formatters.get(maximumFractionDigits)
12
+ if (!value) {
13
+ value = new Intl.NumberFormat(LOCALE, maximumFractionDigits === undefined ? {} : { maximumFractionDigits })
14
+ formatters.set(maximumFractionDigits, value)
15
+ }
16
+ return value
17
+ }
18
+
19
+ /** Число з бека: число чи десятковий рядок (`"1500.00"`). Порожнє й нечислове — `null`. */
20
+ export function numericValue(value: number | string | null | undefined): number | string | null {
21
+ if (value === null || value === undefined) return null
22
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null
23
+ const trimmed = value.trim()
24
+ return trimmed !== '' && Number.isFinite(Number(trimmed)) ? trimmed : null
25
+ }
26
+
27
+ export class NumberHelper {
28
+ /**
29
+ * Розряди пробілом: 1482 -> "1 482". Рядок з бека (`"1500.50"`) Intl бере як є,
30
+ * без заокруглення через float. Порожнє й нечислове — «—».
31
+ */
32
+ static format(value: number | string | null | undefined, maximumFractionDigits?: number): string {
33
+ const numeric = numericValue(value)
34
+ if (numeric === null) return '—'
35
+ return formatter(maximumFractionDigits).format(numeric as number)
36
+ }
37
+
38
+ /** Те саме, але порожнє лишається `null`: KPI відрізняють «немає даних» від нуля. */
39
+ static formatOrNull(value: number | string | null | undefined, maximumFractionDigits?: number): string | null {
40
+ return numericValue(value) === null ? null : NumberHelper.format(value, maximumFractionDigits)
41
+ }
42
+
43
+ /** Частка у відсотках з однією десятою: 12.34 -> "12,3%". */
44
+ static percent(value: number): string {
45
+ return `${percentFormatter.format(value)}%`
46
+ }
47
+
48
+ /** Ставка дробом (як шле бек) у відсотках, до сотих: 0.14 -> "14%", 0.4725 -> "47,25%". */
49
+ static rate(fraction: number): string {
50
+ return `${NumberHelper.format(NumberHelper.round(fraction * 100))}%`
51
+ }
52
+
53
+ /** Число зі словом у правильній формі: 1 день, 3 дні, 5 днів. Форми — [одна, кілька, багато]. */
54
+ static plural(value: number, forms: readonly [one: string, few: string, many: string]): string {
55
+ const rule = pluralRules.select(value)
56
+ const word = rule === 'one' ? forms[0] : rule === 'few' ? forms[1] : forms[2]
57
+ return `${NumberHelper.format(value)} ${word}`
58
+ }
59
+
60
+ /** До двох знаків: 0.1 + 0.2 -> 0.3. */
61
+ static round(value: number): number {
62
+ return Math.round((value + Number.EPSILON) * 100) / 100
63
+ }
64
+
65
+ /** Введення людини: кома чи крапка, пробіли між розрядами. Порожнє й нечислове — 0. */
66
+ static parseDecimal(raw: string | number | null | undefined): number {
67
+ if (raw === null || raw === undefined || raw === '') return 0
68
+ if (typeof raw === 'number') return Number.isFinite(raw) ? raw : 0
69
+ const num = Number(String(raw).replace(/\s/g, '').replace(',', '.'))
70
+ return Number.isFinite(num) ? num : 0
71
+ }
72
+ }
@@ -0,0 +1,56 @@
1
+ // Спільні міксини й брейкпоінти проєктів. Проєкт підключає їх у своєму `_mixins.scss`:
2
+ //
3
+ // @use 'variables' as *;
4
+ // @forward '@/_shared/styles/mixins' with ($muted: $color-muted);
5
+ //
6
+ // і поруч описує лише своє — `buttonPrimary` (бренд). Колір другорядного тексту
7
+ // приходить через `with`: палітри проєкту ядро не знає.
8
+
9
+ $muted: null !default;
10
+
11
+ $mobile-big-width: 1024px;
12
+ $mobile-width: 680px;
13
+ $mobile-height: 600px;
14
+
15
+ $anim-time: 0.3s;
16
+ $anim-small-time: 0.2s;
17
+
18
+ @mixin bigMobile {
19
+ @media (max-width: $mobile-big-width), (max-height: $mobile-height) {
20
+ @content;
21
+ }
22
+ }
23
+
24
+ @mixin anim($duration: $anim-time) {
25
+ transition: $duration ease-in-out;
26
+
27
+ &::before,
28
+ &::after {
29
+ transition: $duration ease-in-out;
30
+ }
31
+ }
32
+
33
+ // Підпис секції: «ДОХОДИ ЗА АГРЕГАТОРАМИ», «ІСТОРІЯ ЗМІН». Один на всі картки,
34
+ // розкриті рядки й модалки, щоб розміри не розходились.
35
+ @mixin sectionCaption {
36
+ font-size: 11px;
37
+ font-weight: 600;
38
+ text-transform: uppercase;
39
+ letter-spacing: 0.06em;
40
+ color: $muted;
41
+ }
42
+
43
+ @mixin scrollbarStyle($width: 5px) {
44
+ scrollbar-color: $muted transparent;
45
+ scrollbar-width: thin;
46
+
47
+ &::-webkit-scrollbar {
48
+ width: $width;
49
+ height: $width;
50
+ }
51
+
52
+ &::-webkit-scrollbar-thumb {
53
+ background-color: $muted;
54
+ border-radius: 3px;
55
+ }
56
+ }
@@ -0,0 +1,128 @@
1
+ // Вигляд тостів vue-sonner під палітру застосунку.
2
+ //
3
+ // ЧОМУ ТУТ, А НЕ В КОМПОНЕНТІ: sonner рендерить тости в портал на <body>,
4
+ // тож scoped-стилі до них не дістануть — потрібен глобальний файл (як
5
+ // _shared/styles/table.scss). Проєкт імпортує його один раз у app.ts.
6
+ //
7
+ // richColors у <Toaster> вимкнений навмисно: він заливає весь тост кольором
8
+ // типу, а тут акцент дає ліва смуга і плашка іконки.
9
+ //
10
+ // NB: змінні $color-* доступні через preprocessorOptions.additionalData (vite.config).
11
+
12
+ // Селектор з [data-sonner-theme], а не голий [data-sonner-toaster]: свою
13
+ // палітру sonner задає саме так, і без другого атрибута наші значення
14
+ // програють за специфічністю.
15
+ //
16
+ // --width тут не задаємо: sonner пише його інлайном на елементі, і CSS його
17
+ // не перебʼє (лише !important). Дефолтних 356px вистачає.
18
+ [data-sonner-toaster][data-sonner-theme] {
19
+ --border-radius: 12px;
20
+ --normal-bg: #{$color-surface};
21
+ --normal-border: #{$color-border};
22
+ --normal-text: #{$color-text};
23
+ }
24
+
25
+ // Наведення не має міняти висоту тоста.
26
+ // sonner при hover розгортає стек і фіксує висоту в `--initial-height`, а та
27
+ // вимірюється ОДИН раз при монтуванні. У `toast.promise` текст після цього ще
28
+ // змінюється (loading → success), довший рядок переноситься на другий — і
29
+ // висота без курсора (auto) розходиться із зафіксованою. З `transition: height
30
+ // 400ms` тост через це смикається туди-сюди під курсором. `auto` — той самий
31
+ // режим, який sonner вмикає собі сам при expand-by-default.
32
+ [data-sonner-toast][data-mounted='true'][data-expanded='true'] { height: auto; }
33
+
34
+ [data-sonner-toast][data-styled='true'] {
35
+ gap: 10px;
36
+ // Справа більше — там сидить хрестик закриття.
37
+ padding: 12px 40px 12px 14px;
38
+ border-left: 3px solid $color-muted;
39
+ box-shadow: 0 10px 28px rgba(15, 20, 30, 0.14);
40
+ font-size: 13px;
41
+
42
+ [data-icon] {
43
+ width: 30px;
44
+ height: 30px;
45
+ margin: 0;
46
+ justify-content: center;
47
+ border-radius: 9px;
48
+ background: $color-page-bg;
49
+ color: $color-muted;
50
+
51
+ svg {
52
+ width: 18px;
53
+ height: 18px;
54
+ margin: 0;
55
+ }
56
+ }
57
+
58
+ [data-title] {
59
+ font-size: 13px;
60
+ font-weight: 500;
61
+ line-height: 1.4;
62
+ }
63
+
64
+ [data-description] {
65
+ font-size: 12px;
66
+ line-height: 1.4;
67
+ color: $color-muted;
68
+ }
69
+
70
+ // Дія-кнопка (напр. «Перейти» під повідомленням) — тихе посилання, а не
71
+ // друга за яскравістю кнопка на екрані.
72
+ [data-button] {
73
+ height: auto;
74
+ padding: 0;
75
+ background: none;
76
+ color: $color-accent-ink;
77
+ font-size: 12px;
78
+ font-weight: 500;
79
+
80
+ &:hover { text-decoration: underline; }
81
+ }
82
+
83
+ // Всередину картки замість кружечка, що звисає з кута (дефолт sonner):
84
+ // тост і так стоїть у кутку екрана, і виступ ліз би за його межі.
85
+ [data-close-button] {
86
+ top: 8px;
87
+ right: 8px;
88
+ left: auto;
89
+ bottom: auto;
90
+ width: 24px;
91
+ height: 24px;
92
+ transform: none;
93
+ border: none;
94
+ border-radius: 6px;
95
+ background: transparent;
96
+ color: $color-muted;
97
+
98
+ &:hover {
99
+ background: $color-page-bg;
100
+ color: $color-text;
101
+ }
102
+ }
103
+
104
+ &[data-type='success'] {
105
+ border-left-color: $color-green;
106
+ [data-icon] { background: rgba($color-green, 0.12); color: $color-green-ink; }
107
+ }
108
+
109
+ &[data-type='error'] {
110
+ border-left-color: $color-danger;
111
+ [data-icon] { background: rgba($color-danger, 0.12); color: $color-danger; }
112
+ }
113
+
114
+ &[data-type='warning'] {
115
+ border-left-color: $color-warning;
116
+ [data-icon] { background: rgba($color-warning, 0.12); color: $color-warning-ink; }
117
+ }
118
+
119
+ &[data-type='info'] {
120
+ border-left-color: $color-accent;
121
+ [data-icon] { background: $color-accent-dim; color: $color-accent-ink; }
122
+ }
123
+
124
+ &[data-type='loading'] {
125
+ border-left-color: $color-accent;
126
+ [data-icon] { background: $color-accent-dim; color: $color-accent-ink; }
127
+ }
128
+ }