@mrktg-common/internal-ui 1.13.0 → 1.15.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/dist/Toast.d.ts CHANGED
@@ -5,6 +5,10 @@ export type TToastAction = {
5
5
  label: string;
6
6
  onClick: () => void;
7
7
  icon?: LucideIcon;
8
+ /** Действие идёт: спиннер вместо иконки, нажатия не проходят, таймер тоста стоит. */
9
+ busy?: boolean;
10
+ /** Нажатие не закрывает тост: результат придёт позже, через update. */
11
+ keepOpen?: boolean;
8
12
  };
9
13
  export type TToast = {
10
14
  /** neutral — сохранено, удалено, скопировано; success — только «vN is live» (на Production или Test). */
@@ -20,9 +24,16 @@ export type TToast = {
20
24
  /** Сколько висит, мс; null — пока не закроют. По умолчанию 6 с, с Undo 10 с, ошибки висят. */
21
25
  duration?: number | null;
22
26
  };
27
+ /** Поле со значением undefined убирается: `{ action: undefined }` снимает кнопку. */
28
+ export type TToastPatch = Partial<Pick<TToast, 'tone' | 'icon' | 'title' | 'description' | 'action' | 'duration'>>;
23
29
  export type TToastApi = {
24
30
  show: (toast: TToast) => number;
25
31
  dismiss: (id: number) => void;
32
+ /**
33
+ * Меняет показанный тост на месте и запускает его таймер заново. false — тоста уже нет (закрыли или
34
+ * вытеснили из стопки), ничего не изменилось: итог, который нужен человеку, продукт показывает новым тостом.
35
+ */
36
+ update: (id: number, patch: TToastPatch) => boolean;
26
37
  };
27
38
  export declare const TOAST_MS = 6000;
28
39
  export declare const TOAST_UNDO_MS = 10000;
@@ -36,7 +47,7 @@ export declare function useToast(): TToastApi;
36
47
  export declare function useToastInsetEnd(width: number | null): void;
37
48
  /**
38
49
  * Что только что произошло: справа снизу, до трёх штук, новый внизу. Таймеры стоят, пока указатель
39
- * над стопкой или фокус внутри неё. Закрыть можно всегда.
50
+ * над стопкой или в ней фокус с клавиатуры, и пока идёт действие тоста. Закрыть можно всегда.
40
51
  */
41
52
  export declare function ToastProvider({ children }: {
42
53
  children: ReactNode;
package/dist/Toast.js CHANGED
@@ -1,7 +1,8 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
3
+ import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
4
4
  import { Check, CircleCheck, CircleX, Info, TriangleAlert, Undo2, X } from 'lucide-react';
5
+ import { Button } from './Button.js';
5
6
  import { cx } from './cx.js';
6
7
  import { FixedPortal } from './portal.js';
7
8
  export const TOAST_MS = 6000;
@@ -39,43 +40,92 @@ export function useToastInsetEnd(width) {
39
40
  }
40
41
  /**
41
42
  * Что только что произошло: справа снизу, до трёх штук, новый внизу. Таймеры стоят, пока указатель
42
- * над стопкой или фокус внутри неё. Закрыть можно всегда.
43
+ * над стопкой или в ней фокус с клавиатуры, и пока идёт действие тоста. Закрыть можно всегда.
43
44
  */
44
45
  export function ToastProvider({ children }) {
45
46
  const [toasts, setToasts] = useState([]);
46
47
  const [insetEnd, setInsetEnd] = useState(0);
47
48
  const nextId = useRef(1);
48
- const dismiss = useCallback((id) => setToasts((current) => current.filter((toast) => toast.id !== id)), []);
49
+ // Зеркало состояния: update отвечает сразу, есть ли ещё тост, не дожидаясь рендера
50
+ const shown = useRef([]);
51
+ const commit = useCallback((next) => {
52
+ shown.current = next;
53
+ setToasts(next);
54
+ }, []);
55
+ const dismiss = useCallback((id) => {
56
+ if (shown.current.some((toast) => toast.id === id))
57
+ commit(shown.current.filter((toast) => toast.id !== id));
58
+ }, [commit]);
49
59
  const show = useCallback((toast) => {
50
60
  const id = nextId.current++;
51
- setToasts((current) => [...current, { ...toast, id }].slice(-MAX_TOASTS));
61
+ commit([...shown.current, { ...toast, id, node: 0, revision: 0 }].slice(-MAX_TOASTS));
52
62
  return id;
53
- }, []);
54
- const api = useMemo(() => ({ show, dismiss }), [show, dismiss]);
63
+ }, [commit]);
64
+ const update = useCallback((id, patch) => {
65
+ const current = shown.current.find((toast) => toast.id === id);
66
+ if (current === undefined)
67
+ return false;
68
+ const next = { ...current, ...patch, revision: current.revision + 1 };
69
+ // role="alert" читается, только если стоит на узле в момент появления: ошибка приходит новым тостом
70
+ if (next.tone === 'danger' && current.tone !== 'danger') {
71
+ commit([...shown.current.filter((toast) => toast !== current), { ...next, node: current.node + 1 }]);
72
+ }
73
+ else {
74
+ commit(shown.current.map((toast) => (toast === current ? next : toast)));
75
+ }
76
+ return true;
77
+ }, [commit]);
78
+ const api = useMemo(() => ({ show, dismiss, update }), [show, dismiss, update]);
55
79
  return (_jsx(ToastContext.Provider, { value: api, children: _jsxs(ToastInsetContext.Provider, { value: setInsetEnd, children: [children, _jsx(ToastStack, { toasts: toasts, insetEnd: insetEnd, onDismiss: dismiss })] }) }));
56
80
  }
81
+ /**
82
+ * Таймеры держит только фокус с клавиатуры. Фокус, который клик мышью оставил на кнопке (и который потом
83
+ * перешёл на Dismiss), не держит: пока указатель над стопкой, это уже делает наведение.
84
+ */
85
+ function isKeyboardFocus(element) {
86
+ return element.matches(':focus-visible');
87
+ }
57
88
  function ToastStack({ toasts, insetEnd, onDismiss }) {
58
89
  const [hovered, setHovered] = useState(false);
59
90
  const [focused, setFocused] = useState(false);
60
91
  const paused = hovered || focused;
92
+ const stack = useRef(null);
93
+ // Тост ушёл вместе с кнопкой, на которой был фокус: blur не приходит, а таймеры остальных стоять не должны
94
+ useEffect(() => {
95
+ if (stack.current?.contains(document.activeElement) !== true)
96
+ setFocused(false);
97
+ }, [toasts]);
61
98
  if (toasts.length === 0)
62
99
  return null;
63
100
  const style = { '--toast-inset-end': `${insetEnd}px` };
64
- return (_jsx(FixedPortal, { children: _jsx("div", { className: "toasts is-fixed", style: style, onMouseEnter: () => setHovered(true), onMouseLeave: () => setHovered(false), onFocus: () => setFocused(true), onBlur: (event) => {
101
+ return (_jsx(FixedPortal, { children: _jsx("div", { ref: stack, className: "toasts is-fixed", style: style, onMouseEnter: () => setHovered(true), onMouseLeave: () => setHovered(false), onFocus: (event) => setFocused(isKeyboardFocus(event.target)), onBlur: (event) => {
65
102
  if (!event.currentTarget.contains(event.relatedTarget))
66
103
  setFocused(false);
67
- }, children: toasts.map((toast) => (_jsx(ToastItem, { toast: toast, paused: paused, onDismiss: () => onDismiss(toast.id) }, toast.id))) }) }));
104
+ }, children: toasts.map((toast) => (_jsx(ToastItem, { toast: toast, paused: paused, onDismiss: () => onDismiss(toast.id) }, `${toast.id}:${toast.node}`))) }) }));
68
105
  }
69
106
  function ToastItem({ toast, paused, onDismiss }) {
70
107
  const duration = toastDuration(toast);
108
+ const tone = toast.tone ?? 'neutral';
109
+ const Icon = toast.icon ?? TONE_ICON[tone];
110
+ const action = toast.undo === undefined ? toast.action : { label: 'Undo', onClick: toast.undo, icon: Undo2 };
111
+ const ActionIcon = action?.icon;
112
+ const busy = action?.busy === true;
113
+ const hasAction = action !== undefined;
114
+ const stopped = paused || busy;
71
115
  // Остаток времени копится между паузами: наведение не сбрасывает таймер на полный срок
72
116
  const remaining = useRef(duration);
117
+ const revision = useRef(toast.revision);
73
118
  const dismissRef = useRef(onDismiss);
74
119
  useEffect(() => {
75
120
  dismissRef.current = onDismiss;
76
121
  });
77
122
  useEffect(() => {
78
- if (paused || remaining.current === null)
123
+ // После update срок идёт заново, по правилам нового содержимого
124
+ if (revision.current !== toast.revision) {
125
+ revision.current = toast.revision;
126
+ remaining.current = duration;
127
+ }
128
+ if (stopped || remaining.current === null)
79
129
  return;
80
130
  const startedAt = Date.now();
81
131
  const timer = window.setTimeout(() => dismissRef.current(), remaining.current);
@@ -84,13 +134,23 @@ function ToastItem({ toast, paused, onDismiss }) {
84
134
  if (remaining.current !== null)
85
135
  remaining.current = Math.max(0, remaining.current - (Date.now() - startedAt));
86
136
  };
87
- }, [paused]);
88
- const tone = toast.tone ?? 'neutral';
89
- const Icon = toast.icon ?? TONE_ICON[tone];
90
- const action = toast.undo === undefined ? toast.action : { label: 'Undo', onClick: toast.undo, icon: Undo2 };
91
- const ActionIcon = action?.icon;
92
- return (_jsxs("div", { className: "toast", role: tone === 'danger' ? 'alert' : 'status', children: [_jsx(Icon, { className: cx('ic', `t-${tone}`), "aria-hidden": true }), _jsxs("div", { className: "toast-body", children: [_jsx("span", { className: "toast-title", children: toast.title }), toast.description !== undefined && _jsx("span", { className: "toast-desc", children: toast.description }), action !== undefined && (_jsx("div", { className: "toast-act", children: _jsxs("button", { type: "button", className: "btn btn-secondary btn-sm", onClick: () => {
93
- onDismiss();
137
+ }, [stopped, toast.revision, duration]);
138
+ // update убрал кнопку, на которой был фокус: он не должен уйти из тоста на страницу
139
+ const dismissButton = useRef(null);
140
+ const actionFocused = useRef(false);
141
+ useLayoutEffect(() => {
142
+ if (hasAction || !actionFocused.current)
143
+ return;
144
+ actionFocused.current = false;
145
+ dismissButton.current?.focus();
146
+ }, [hasAction]);
147
+ return (_jsxs("div", { className: "toast", role: tone === 'danger' ? 'alert' : 'status', "aria-atomic": "true", children: [_jsx(Icon, { className: cx('ic', `t-${tone}`), "aria-hidden": true }), _jsxs("div", { className: "toast-body", children: [_jsx("span", { className: "toast-title", children: toast.title }), toast.description !== undefined && _jsx("span", { className: "toast-desc", children: toast.description }), action !== undefined && (_jsx("div", { className: "toast-act", children: _jsxs(Button, { size: "sm", busy: busy, onFocus: () => {
148
+ actionFocused.current = true;
149
+ }, onBlur: () => {
150
+ actionFocused.current = false;
151
+ }, onClick: () => {
152
+ if (action.keepOpen !== true)
153
+ onDismiss();
94
154
  action.onClick();
95
- }, children: [ActionIcon && _jsx(ActionIcon, { className: "ic ic-sm", "aria-hidden": true }), action.label] }) }))] }), _jsx("button", { type: "button", className: "btn btn-ghost btn-sm btn-icon", "aria-label": "Dismiss", onClick: onDismiss, children: _jsx(X, { className: "ic", "aria-hidden": true }) })] }));
155
+ }, children: [ActionIcon && !busy && _jsx(ActionIcon, { className: "ic ic-sm", "aria-hidden": true }), action.label] }) }))] }), _jsx("button", { ref: dismissButton, type: "button", className: "btn btn-ghost btn-sm btn-icon", "aria-label": "Dismiss", onClick: onDismiss, children: _jsx(X, { className: "ic", "aria-hidden": true }) })] }));
96
156
  }
package/dist/index.d.ts CHANGED
@@ -42,7 +42,7 @@ export type { IAlertProps, TAlertTone } from './Alert.tsx';
42
42
  export { Banner } from './Banner.tsx';
43
43
  export type { IBannerProps, TBannerTone } from './Banner.tsx';
44
44
  export { ToastProvider, useToast, useToastInsetEnd, toastDuration, TOAST_MS, TOAST_UNDO_MS, MAX_TOASTS } from './Toast.tsx';
45
- export type { TToast, TToastApi, TToastTone, TToastAction } from './Toast.tsx';
45
+ export type { TToast, TToastApi, TToastTone, TToastAction, TToastPatch } from './Toast.tsx';
46
46
  export { Tooltip, TOOLTIP_DELAY_MS } from './Tooltip.tsx';
47
47
  export type { ITooltipProps } from './Tooltip.tsx';
48
48
  export { Skeleton } from './Skeleton.tsx';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrktg-common/internal-ui",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "description": "Общий интерфейс внутренних инструментов маркетинга (Landings Admin, LP Constructor): токены, классы компонентов и тонкие React-обёртки над ними.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -2,7 +2,7 @@
2
2
  "name": "Internal ui",
3
3
  "version": 1,
4
4
  "meta": {
5
- "release": "1.13.0",
5
+ "release": "1.15.0",
6
6
  "source": "lp-constructor src/styles/tokens.css + Landings Admin admin.css, merged 2026-10-12"
7
7
  },
8
8
  "color": {