Previews

No matching results.

x
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="2AP4WaWN5NUbJICzvlbZOsG9YqPELkQlSDPwLpq6DHbjX0W25JEmSXxz_VihY8De5aN6XxNAqnbeyMJixuoAXA" />
<!-- ATTENTION: The following line is required for Turbo dialog works see: https://github.com/hotwired/turbo/issues/1191#issuecomment-1952959217 -->
<meta name="turbo-prefetch" content="false">
<link rel="stylesheet" href="/assets/tailwind-9cb6b476.css" data-turbo-track="reload" />
<link rel="stylesheet" href="/assets/elevate-dcd69e91.css" />
<script src="/vite/assets/application-CtGL6t6B.js" crossorigin="anonymous" type="module"></script><link rel="modulepreload" href="/vite/assets/monaco-editor-RrX1fzMb.js" as="script" crossorigin="anonymous">
<link rel="modulepreload" href="/vite/assets/elevate-forms-vendors-Cy0M7dtl.js" as="script" crossorigin="anonymous"><link rel="stylesheet" href="/vite/assets/application-ChPJkT_7.css" media="screen" />
<link rel="stylesheet" href="/vite/assets/monaco-editor-D3kjxRyo.css" media="screen" />
</head>
<body>
<div id="elevate-toast-host" data-controller="toast" data-turbo-permanent="true" data-toast-position-value="top-center" data-toast-layout-value="default" data-toast-auto-dismiss-duration-value="4000" data-toast-limit-value="3" data-toast-gap-value="14" class="elevate-toast elevate-toast--position--top-center">
<ol data-toast-target="container" class="relative flex flex-col-reverse sm:flex-col gap-0 pointer-events-auto [&>li]:pointer-events-auto" style="height: 0px;"></ol>
<div data-toast-target="livePolite" role="status" aria-live="polite" aria-atomic="true" class="sr-only"></div>
<div data-toast-target="liveAssertive" role="alert" aria-live="assertive" aria-atomic="true" class="sr-only"></div>
<template data-toast-template data-toast-type="default">
<li class="toast-item">
<div class="elevate-toast--content">
<div class="elevate-toast--row">
<div class="elevate-toast--plate elevate-toast--plate--default"
aria-hidden="true">
<span class="elevate-toast--plate-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" focusable="false" aria-hidden="true">
<circle cx="9" cy="9" r="7.4"></circle>
<circle cx="9" cy="9" r="1.4" fill="currentColor" stroke="none"></circle>
</svg>
</span>
</div>
<div class="elevate-toast--text">
<p class="elevate-toast--title" data-toast-slot="message"></p>
<p class="elevate-toast--description" data-toast-slot="description"></p>
</div>
<button type="button" class="elevate-toast--close" data-toast-slot="close" aria-label="Close">
<span class="elevate-toast--close-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 14 14" fill="none" focusable="false" aria-hidden="true">
<path d="M3.5 3.5 L10.5 10.5 M10.5 3.5 L3.5 10.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path>
</svg>
</span>
</button>
</div>
</div>
</li>
</template>
<template data-toast-template data-toast-type="success">
<li class="toast-item">
<div class="elevate-toast--content">
<div class="elevate-toast--row">
<div class="elevate-toast--plate elevate-toast--plate--success"
aria-hidden="true">
<span class="elevate-toast--plate-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" focusable="false" aria-hidden="true">
<circle cx="9" cy="9" r="7.4"></circle>
<path d="M5.6 9.2 L8 11.6 L12.4 6.8"></path>
</svg>
</span>
</div>
<div class="elevate-toast--text">
<p class="elevate-toast--title" data-toast-slot="message"></p>
<p class="elevate-toast--description" data-toast-slot="description"></p>
</div>
<button type="button" class="elevate-toast--close" data-toast-slot="close" aria-label="Close">
<span class="elevate-toast--close-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 14 14" fill="none" focusable="false" aria-hidden="true">
<path d="M3.5 3.5 L10.5 10.5 M10.5 3.5 L3.5 10.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path>
</svg>
</span>
</button>
</div>
</div>
</li>
</template>
<template data-toast-template data-toast-type="error">
<li class="toast-item">
<div class="elevate-toast--content">
<div class="elevate-toast--row">
<div class="elevate-toast--plate elevate-toast--plate--error"
aria-hidden="true">
<span class="elevate-toast--plate-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" focusable="false" aria-hidden="true">
<circle cx="9" cy="9" r="7.4"></circle>
<path d="M6.2 6.2 L11.8 11.8 M11.8 6.2 L6.2 11.8"></path>
</svg>
</span>
</div>
<div class="elevate-toast--text">
<p class="elevate-toast--title" data-toast-slot="message"></p>
<p class="elevate-toast--description" data-toast-slot="description"></p>
</div>
<button type="button" class="elevate-toast--close" data-toast-slot="close" aria-label="Close">
<span class="elevate-toast--close-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 14 14" fill="none" focusable="false" aria-hidden="true">
<path d="M3.5 3.5 L10.5 10.5 M10.5 3.5 L3.5 10.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path>
</svg>
</span>
</button>
</div>
</div>
</li>
</template>
<template data-toast-template data-toast-type="info">
<li class="toast-item">
<div class="elevate-toast--content">
<div class="elevate-toast--row">
<div class="elevate-toast--plate elevate-toast--plate--info"
aria-hidden="true">
<span class="elevate-toast--plate-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" focusable="false" aria-hidden="true">
<circle cx="9" cy="9" r="7.4"></circle>
<path d="M9 8 L9 12.4"></path>
<circle cx="9" cy="5.6" r="0.5" fill="currentColor" stroke="none"></circle>
</svg>
</span>
</div>
<div class="elevate-toast--text">
<p class="elevate-toast--title" data-toast-slot="message"></p>
<p class="elevate-toast--description" data-toast-slot="description"></p>
</div>
<button type="button" class="elevate-toast--close" data-toast-slot="close" aria-label="Close">
<span class="elevate-toast--close-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 14 14" fill="none" focusable="false" aria-hidden="true">
<path d="M3.5 3.5 L10.5 10.5 M10.5 3.5 L3.5 10.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path>
</svg>
</span>
</button>
</div>
</div>
</li>
</template>
<template data-toast-template data-toast-type="warning">
<li class="toast-item">
<div class="elevate-toast--content">
<div class="elevate-toast--row">
<div class="elevate-toast--plate elevate-toast--plate--warning"
aria-hidden="true">
<span class="elevate-toast--plate-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" focusable="false" aria-hidden="true">
<path d="M9 2.4 L16.2 14.6 L1.8 14.6 Z"></path>
<path d="M9 7.2 L9 10.6"></path>
<circle cx="9" cy="12.6" r="0.5" fill="currentColor" stroke="none"></circle>
</svg>
</span>
</div>
<div class="elevate-toast--text">
<p class="elevate-toast--title" data-toast-slot="message"></p>
<p class="elevate-toast--description" data-toast-slot="description"></p>
</div>
<button type="button" class="elevate-toast--close" data-toast-slot="close" aria-label="Close">
<span class="elevate-toast--close-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 14 14" fill="none" focusable="false" aria-hidden="true">
<path d="M3.5 3.5 L10.5 10.5 M10.5 3.5 L3.5 10.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path>
</svg>
</span>
</button>
</div>
</div>
</li>
</template>
<template data-toast-template data-toast-type="danger">
<li class="toast-item">
<div class="elevate-toast--content">
<div class="elevate-toast--row">
<div class="elevate-toast--plate elevate-toast--plate--danger"
aria-hidden="true">
<span class="elevate-toast--plate-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" focusable="false" aria-hidden="true">
<path d="M9 1.8 L15.6 5.4 L15.6 10 C15.6 13.4 12.6 15.6 9 16.6 C5.4 15.6 2.4 13.4 2.4 10 L2.4 5.4 Z"></path>
<path d="M9 6.4 L9 10"></path>
<circle cx="9" cy="12" r="0.5" fill="currentColor" stroke="none"></circle>
</svg>
</span>
</div>
<div class="elevate-toast--text">
<p class="elevate-toast--title" data-toast-slot="message"></p>
<p class="elevate-toast--description" data-toast-slot="description"></p>
</div>
<button type="button" class="elevate-toast--close" data-toast-slot="close" aria-label="Close">
<span class="elevate-toast--close-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 14 14" fill="none" focusable="false" aria-hidden="true">
<path d="M3.5 3.5 L10.5 10.5 M10.5 3.5 L3.5 10.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path>
</svg>
</span>
</button>
</div>
</div>
</li>
</template>
<template data-toast-template data-toast-type="loading">
<li class="toast-item">
<div class="elevate-toast--content">
<div class="elevate-toast--row">
<div class="elevate-toast--plate elevate-toast--plate--loading"
role="progressbar" aria-label="Loading…">
<span class="elevate-toast--plate-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 18 18" fill="none" focusable="false" aria-hidden="true">
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-opacity="0.2" stroke-width="1.6"></circle>
<path d="M9 2 A7 7 0 0 1 16 9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"></path>
</svg>
</span>
</div>
<div class="elevate-toast--text">
<p class="elevate-toast--title" data-toast-slot="message"></p>
<p class="elevate-toast--description" data-toast-slot="description"></p>
</div>
<button type="button" class="elevate-toast--close" data-toast-slot="close" aria-label="Close">
<span class="elevate-toast--close-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 14 14" fill="none" focusable="false" aria-hidden="true">
<path d="M3.5 3.5 L10.5 10.5 M10.5 3.5 L3.5 10.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path>
</svg>
</span>
</button>
</div>
</div>
</li>
</template>
<template data-toast-template-rich>
<li class="toast-item">
<div class="elevate-toast--content elevate-toast--content--rich">
<div data-toast-slot="content"></div>
<button type="button" class="elevate-toast--close elevate-toast--close--floating" data-toast-slot="close" aria-label="Close"><span class="elevate-toast--close-icon elevate-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewbox="0 0 14 14" fill="none" focusable="false" aria-hidden="true">
<path d="M3.5 3.5 L10.5 10.5 M10.5 3.5 L3.5 10.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path>
</svg>
</span></button></div>
</li>
</template>
</div>
<main class="container mx-auto mt-12 px-5">
<button onclick="toast('Toast Notification', { description: 'This is an example toast notification with a longer description that provides additional context.' })" type="button" class="elevate-button elevate-button--default elevate-button--size-l elevate-button--align-center shadow-xs hover:cursor-pointer">
Show with description
</button>
</main>
</body>
<script>
/* see this fix: https://github.com/rails/importmap-rails/issues/65#issuecomment-999939960 */
window.process = { env: { NODE_ENV: 'production'} }
</script>
</html>
1
2
3
<%= elevate_button(size: :large,
classes: "shadow-xs hover:cursor-pointer",
onclick: "toast('Toast Notification', { description: 'This is an example toast notification with a longer description that provides additional context.' })") { 'Show with description' } %>

app/components/elevate/toast/toast.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
@layer components {
.elevate-toast {
/* Reset popover user-agent defaults so position modifiers can anchor the host correctly */
@apply fixed z-[99999] w-full max-w-[380px] px-4 sm:px-0 py-0 pointer-events-none transition-all duration-300 ease-in-out inset-auto m-0 h-auto bg-transparent border-0 overflow-visible;
}
/* Placement */
.elevate-toast--position--top-left {
@apply left-0 top-0 mt-4 ml-4 sm:mt-6 sm:ml-6;
}
.elevate-toast--position--top-center {
@apply left-1/2 -translate-x-1/2 top-0 mt-4 sm:mt-6;
}
.elevate-toast--position--top-right {
@apply right-0 top-0 mt-4 mr-4 sm:mt-6 sm:mr-6;
}
.elevate-toast--position--bottom-left {
@apply left-0 bottom-0 mb-4 ml-4 sm:ml-6 sm:mb-6;
}
.elevate-toast--position--bottom-center {
@apply left-1/2 -translate-x-1/2 bottom-0 mb-4 sm:mb-6;
}
.elevate-toast--position--bottom-right {
@apply right-0 bottom-0 mb-4 mr-4 sm:mr-6 sm:mb-6;
}
}
/* Toast Notifications */
.toast-item {
/* Position + visual state are driven by CSS custom properties set by data-attribute rules below.
The transition list mirrors Sonner: separate timings for transform/opacity/scale/top/bottom and a faster height tween. */
@apply absolute w-full left-0 select-none z-[var(--toast-z-index,100)] top-[var(--toast-top,auto)] bottom-[var(--toast-bottom,auto)] [transform:var(--toast-transform,translateY(0))] [scale:var(--toast-scale,100%)] opacity-[var(--toast-opacity,1)] [transition:transform_400ms_ease,opacity_400ms_ease,scale_400ms_ease,top_400ms_ease,bottom_400ms_ease,height_200ms_ease];
}
/* Initial hidden state for enter animation */
.toast-item[data-mounted="false"] {
@apply opacity-0;
}
.toast-item[data-mounted="false"][data-position*="bottom"] {
@apply [transform:translateY(100%)];
}
.toast-item[data-mounted="false"][data-position*="top"] {
@apply [transform:translateY(-100%)];
}
/* Removed state for exit animation */
.toast-item[data-removed="true"] {
@apply opacity-0 [scale:95%] pointer-events-none;
}
/* In stacked mode, removed toasts should slide away */
.toast-item[data-removed="true"][data-expanded="false"][data-position*="bottom"] {
@apply [transform:translateY(calc(var(--toast-index)_*_14px_+_5%))];
}
.toast-item[data-removed="true"][data-expanded="false"][data-position*="top"] {
@apply [transform:translateY(calc(-1_*_(var(--toast-index)_*_14px_+_5%)))];
}
/* Overflow toasts (removed due to limit) slide in opposite direction */
.toast-item[data-removed="true"][data-overflow="true"][data-expanded="false"][data-position*="bottom"] {
@apply [transform:translateY(calc(-1_*_(var(--toast-index)_*_14px_+_25%)))] [scale:78%];
}
.toast-item[data-removed="true"][data-overflow="true"][data-expanded="false"][data-position*="top"] {
@apply [transform:translateY(calc(var(--toast-index)_*_14px_+_25%))] [scale:78%];
}
/* Pointer events based on visibility */
.toast-item[data-visible="false"] {
@apply pointer-events-none;
}
/* Expanded mode styles */
.toast-item[data-expanded="true"] {
@apply [--toast-scale:100%] h-[var(--initial-height)];
}
.toast-item[data-expanded="true"][data-position*="bottom"] {
@apply [--toast-top:auto] [--toast-bottom:var(--toast-offset,0px)] [--toast-transform:translateY(0)];
}
.toast-item[data-expanded="true"][data-position*="top"] {
@apply [--toast-top:var(--toast-offset,0px)] [--toast-bottom:auto] [--toast-transform:translateY(0)];
}
/* Stacked mode styles */
.toast-item[data-expanded="false"][data-front="true"] {
@apply [--toast-scale:100%] [--toast-opacity:1] h-[var(--initial-height)];
}
.toast-item[data-expanded="false"][data-front="true"][data-position*="bottom"] {
@apply [--toast-top:auto] [--toast-bottom:0px] [--toast-transform:translateY(0)];
}
.toast-item[data-expanded="false"][data-front="true"][data-position*="top"] {
@apply [--toast-top:0px] [--toast-bottom:auto] [--toast-transform:translateY(0)];
}
/* Non-front toasts in stack - Sonner approach */
.toast-item[data-expanded="false"]:not([data-front="true"]) {
@apply h-[var(--front-toast-height)] overflow-hidden [--toast-scale:calc(100%_-_(var(--toast-index)_*_6%))] flex flex-col;
}
.toast-item[data-expanded="false"]:not([data-front="true"])[data-position*="bottom"] {
/* Content at top, bottom gets cut */
@apply [--toast-top:auto] [--toast-bottom:0px] [--toast-transform:translateY(calc(-1_*_var(--toast-index)_*_14px))] justify-start;
}
.toast-item[data-expanded="false"]:not([data-front="true"])[data-position*="top"] {
/* Content at bottom, top gets cut */
@apply [--toast-top:0px] [--toast-bottom:auto] [--toast-transform:translateY(calc(var(--toast-index)_*_14px))] justify-end;
}
/* Hidden toasts (beyond 3rd) */
.toast-item[data-expanded="false"][data-visible="false"] {
@apply [--toast-opacity:0] [--toast-scale:82%];
}
.toast-item[data-expanded="false"][data-visible="false"][data-position*="bottom"] {
@apply [--toast-top:auto] [--toast-bottom:-200px] [--toast-transform:translateY(0)];
}
.toast-item[data-expanded="false"][data-visible="false"][data-position*="top"] {
@apply [--toast-top:-200px] [--toast-bottom:auto] [--toast-transform:translateY(0)];
}
/* Toast content card */
.elevate-toast--content {
@apply relative w-full bg-white p-3 sm:max-w-[380px] border border-[var(--color-secondary-200,rgba(72,72,72,0.20))] rounded-[14px] shadow-[0_16px_40px_-12px_rgba(56,56,56,0.20),0_2px_6px_rgba(56,56,56,0.05)] [transition:all_200ms_cubic-bezier(0.4,0,0.2,1)] overflow-hidden;
}
.elevate-toast--content--rich {
@apply p-0;
}
/* Layout row: plate + text + close.
Default to items-center so plate, title, and close align perfectly when there is no description.
When a description is present (no .toast-no-description class), switch to items-start and offset
the text column / close button so they line up with the 32px plate's vertical center. */
.elevate-toast--row {
@apply flex items-center gap-3;
}
.toast-item:not(.toast-no-description) .elevate-toast--row {
@apply items-start;
}
.toast-item:not(.toast-no-description) .elevate-toast--text {
@apply pt-[7px];
}
.toast-item:not(.toast-no-description) .elevate-toast--close {
@apply mt-[5px];
}
/* Icon plate (32x32 status-tinted square) */
.elevate-toast--plate {
@apply flex items-center justify-center flex-shrink-0 w-8 h-8 rounded-lg;
}
.elevate-toast--plate-icon {
@apply w-[18px] h-[18px];
}
.elevate-toast--plate--default,
.elevate-toast--plate--loading {
@apply bg-tertiary-50 text-secondary-700;
}
.elevate-toast--plate--success {
@apply bg-success-50 text-success-800;
}
.elevate-toast--plate--error,
.elevate-toast--plate--danger {
@apply bg-danger-50 text-danger-800;
}
.elevate-toast--plate--info {
@apply bg-info-50 text-info-800;
}
.elevate-toast--plate--warning {
@apply bg-warning-50 text-warning-800;
}
.elevate-toast--plate--loading svg {
@apply animate-[elevate-toast-spin_1.1s_linear_infinite];
}
@keyframes elevate-toast-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* Text column */
.elevate-toast--text {
@apply flex-1 min-w-0;
}
.elevate-toast--title {
@apply text-sm font-semibold tracking-[-0.01em] leading-[1.35] text-secondary-900 m-0;
}
.elevate-toast--description {
@apply text-[13px] font-normal leading-[1.45] text-secondary-700 m-0 mt-0.5;
}
/* Close button — vertical alignment is driven by the row container (items-center / items-start + offset). */
.elevate-toast--close {
@apply flex-shrink-0 cursor-pointer appearance-none bg-transparent border-0 p-1 m-0 text-secondary-500 leading-[0] [transition:color_100ms_ease-in-out] hover:text-secondary-900;
}
.elevate-toast--close-icon {
@apply w-3.5 h-3.5;
}
/* Floating variant for rich (custom html) toasts where close overlays content */
.elevate-toast--close--floating {
@apply absolute top-[10px] right-[10px] m-0;
}

app/components/elevate/toast/toast_controller.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
import { Controller } from "@hotwired/stimulus";
import { generateUUID } from "../shared/uuid";
// Matches the 400ms transition declared on `.toast-item` in toast.css for both
// the entry (mount) and exit (remove) animations.
const MOUNT_TRANSITION_MS = 400;
// Per-host state lives at module scope so it survives the disconnect/connect
// cycle Stimulus runs when Turbo's permanent-element swap detaches and
// re-inserts the host. Indexed by host id so multiple hosts (rare) don't
// share a queue.
const hostStates = new Map();
function getHostState (hostId) {
if (!hostStates.has(hostId)) {
hostStates.set(hostId, {
toasts: [],
heights: [],
autoDismissTimers: {},
removeTimeouts: new Map(),
timersPaused: false,
});
}
return hostStates.get(hostId);
}
export default class extends Controller {
static targets = ["container", "livePolite", "liveAssertive"];
static values = {
position: { type: String, default: "top-center" },
layout: { type: String, default: "default" }, // "default" (stacked) or "expanded" (all visible)
gap: { type: Number, default: 14 }, // Gap between toasts in expanded mode
autoDismissDuration: { type: Number, default: 4000 },
limit: { type: Number, default: 3 }, // Maximum number of visible toasts
};
static POSITION_VALUES = [
"top-left",
"top-center",
"top-right",
"bottom-left",
"bottom-center",
"bottom-right",
];
static TOAST_TYPES = [
"default",
"success",
"error",
"info",
"warning",
"danger",
"loading",
];
static ASSERTIVE_TYPES = new Set(["error", "warning", "danger"]);
connect () {
this.hostId = this.element.id || "default";
this.state = getHostState(this.hostId);
this.bindStateAccessors();
this.expanded = this.layoutValue === "expanded";
this.interacting = false;
this.isPrimaryController = false;
this.defaultMountParent = this.element?.parentNode || null;
this.defaultMountNextSibling = this.element?.nextSibling || null;
this.hoverZonePadding = 10;
this._templates = this.collectTemplates();
this.registerController();
this.activatePrimaryIfNeeded();
}
// Map `this.toasts`, `this.heights`, `this.autoDismissTimers`,
// `this.removeTimeouts`, `this.timersPaused` to the shared state object so
// every other method keeps working unchanged while the data persists across
// controller disconnect/reconnect.
bindStateAccessors () {
const state = this.state;
Object.defineProperties(this, {
toasts: { get () { return state.toasts; }, set (v) { state.toasts = v; }, configurable: true },
heights: { get () { return state.heights; }, set (v) { state.heights = v; }, configurable: true },
autoDismissTimers: { get () { return state.autoDismissTimers; }, set (v) { state.autoDismissTimers = v; }, configurable: true },
removeTimeouts: { get () { return state.removeTimeouts; }, set (v) { state.removeTimeouts = v; }, configurable: true },
timersPaused: { get () { return state.timersPaused; }, set (v) { state.timersPaused = v; }, configurable: true },
});
}
collectTemplates () {
const map = {};
for (const type of this.constructor.TOAST_TYPES) {
map[type] = this.element.querySelector(
`template[data-toast-template][data-toast-type="${type}"]`,
);
}
map.rich = this.element.querySelector("template[data-toast-template-rich]");
return map;
}
updatePositionClasses () {
const host = this.element;
if (!host) return;
for (const value of this.constructor.POSITION_VALUES) {
host.classList.toggle(`elevate-toast--position--${value}`, value === this.positionValue);
}
}
disconnect () {
// Stop receiving primary-only events FIRST so no in-flight toast-show
// can land on a half-torn-down DOM (Turbo navigations can fire mid-disconnect).
const wasPrimary = this.isPrimaryController;
if (wasPrimary) {
this.removePrimaryListeners();
if (window.toast === this.boundShowToast) {
delete window.toast;
}
if (window.__toastPrimaryController === this) {
window.__toastPrimaryController = null;
}
}
// NOTE: don't clear toasts or auto-dismiss timers here. The host element
// is `data-turbo-permanent`, but Turbo still detaches/re-inserts it during
// navigation, which Stimulus surfaces as disconnect→connect. Persisted
// state and pending setTimeouts are intentionally left alive so that
// active toasts survive the swap.
this.unregisterController();
this.isPrimaryController = false;
if (wasPrimary) this.promoteNextPrimaryController();
}
showToast (message, options = {}) {
const detail = {
type: options.type || "default",
message: message,
description: options.description || "",
position: options.position || window.currentToastPosition || this.positionValue, // Use stored position
html: options.html || "",
dangerouslyAllowHtml: options.dangerouslyAllowHtml === true,
};
window.dispatchEvent(new CustomEvent("toast-show", { detail }));
}
handleToastShow (event) {
if (!this.isPrimaryController) return;
event.stopPropagation();
this.ensureGlobalHostVisible();
// Update container position if a position is specified for this toast
if (event.detail.position) {
this.positionValue = event.detail.position;
window.currentToastPosition = event.detail.position; // Store globally
this.updatePositionClasses();
}
const toast = {
id: `toast-${generateUUID()}`,
mounted: false,
removed: false,
message: event.detail.message,
description: event.detail.description,
type: event.detail.type,
html: event.detail.html,
dangerouslyAllowHtml: event.detail.dangerouslyAllowHtml === true,
};
// Add toast at the beginning of the array (newest first)
this.toasts.unshift(toast);
// Enforce toast limit synchronously to prevent race conditions
const activeToasts = this.activeToasts;
if (activeToasts.length > this.limitValue) {
const oldestActiveToast = activeToasts[activeToasts.length - 1];
if (oldestActiveToast && !oldestActiveToast.removed) {
this.removeToast(oldestActiveToast.id, true);
}
}
this.renderToast(toast);
}
handleLayoutChange (event) {
if (!this.isPrimaryController) return;
this.layoutValue = event.detail.layout;
this.expanded = this.layoutValue === "expanded";
this.updateAllToasts();
}
clearAllToasts () {
// Remove all toast elements from DOM
const container = this.containerTarget;
if (container) {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
}
// Clear arrays
this.toasts = [];
this.heights = [];
if (this.layoutValue === "default") {
this.expanded = false;
}
this.clearAllAutoDismissTimers();
if (this.removeTimeouts) {
for (const timeoutId of this.removeTimeouts.values()) {
clearTimeout(timeoutId);
}
this.removeTimeouts.clear();
}
this.hideGlobalHostIfIdle();
}
get activeToasts () {
return this.toasts.filter((t) => !t.removed);
}
renderToast (toast) {
// Three-phase mount, scheduled across two animation frames + one timeout:
// Frame 1 — element is now in DOM with data-mounted="false"; measure its
// natural height via getBoundingClientRect for layout math.
// Frame 2 — flip data-mounted="true" so the CSS transition defined in
// toast.css (400ms) animates from the off-screen state to visible.
// +400ms — once the entry animation has completed, arm the auto-dismiss
// timer. This makes the user-configured autoDismissDuration
// measure *visible* time, not total lifetime, so even a 1ms
// value yields a perceivable toast (fade-in → 1ms → fade-out)
// instead of being swallowed by the entry animation.
this.ensureGlobalHostVisible();
const container = this.containerTarget;
const li = this.createToastElement(toast);
container.insertBefore(li, container.firstChild);
this.announceToLiveRegion(toast);
requestAnimationFrame(() => {
const toastEl = document.getElementById(toast.id);
if (toastEl) {
const height = toastEl.getBoundingClientRect().height;
this.heights.unshift({
toastId: toast.id,
height: height,
});
const activeToasts = this.activeToasts;
requestAnimationFrame(() => {
toast.mounted = true;
toastEl.dataset.mounted = "true";
this.updateAllToasts();
const activeToastIndex = activeToasts.findIndex((t) => t.id === toast.id);
if (activeToastIndex < this.limitValue) {
setTimeout(() => this.scheduleAutoDismiss(toast.id), MOUNT_TRANSITION_MS);
}
});
}
});
}
announceToLiveRegion (toast) {
const isAssertive = this.constructor.ASSERTIVE_TYPES.has(toast.type);
const target = isAssertive
? (this.hasLiveAssertiveTarget ? this.liveAssertiveTarget : null)
: (this.hasLivePoliteTarget ? this.livePoliteTarget : null);
if (!target) return;
const text = this.extractAnnouncement(toast);
if (!text) return;
target.textContent = "";
requestAnimationFrame(() => { target.textContent = text; });
}
extractAnnouncement (toast) {
if (toast.message) {
return toast.description ? `${toast.message}. ${toast.description}` : toast.message;
}
if (toast.html) {
if (!toast.dangerouslyAllowHtml) {
return toast.html.trim();
}
const parsed = new DOMParser().parseFromString(toast.html, "text/html");
return (parsed.body.textContent || "").trim();
}
return "";
}
scheduleAutoDismiss (toastId) {
this.clearAutoDismiss(toastId);
this.autoDismissTimers[toastId] = {
remainingMs: this.autoDismissDurationValue,
startedAt: null,
timeoutId: null,
};
if (!this.timersPaused) {
this.startAutoDismissTimer(toastId);
}
}
startAutoDismissTimer (toastId) {
const record = this.autoDismissTimers[toastId];
if (!record || record.timeoutId !== null) return;
record.startedAt = Date.now();
record.timeoutId = setTimeout(() => {
delete this.autoDismissTimers[toastId];
this.removeToast(toastId);
}, record.remainingMs);
}
clearAutoDismiss (toastId) {
const record = this.autoDismissTimers[toastId];
if (!record) return;
if (record.timeoutId !== null) clearTimeout(record.timeoutId);
delete this.autoDismissTimers[toastId];
}
clearAllAutoDismissTimers () {
for (const toastId of Object.keys(this.autoDismissTimers || {})) {
this.clearAutoDismiss(toastId);
}
}
pauseAllAutoDismiss () {
if (this.timersPaused) return;
this.timersPaused = true;
for (const toastId of Object.keys(this.autoDismissTimers)) {
const record = this.autoDismissTimers[toastId];
if (record.timeoutId !== null) {
clearTimeout(record.timeoutId);
const elapsed = Date.now() - record.startedAt;
record.remainingMs = Math.max(0, record.remainingMs - elapsed);
record.timeoutId = null;
record.startedAt = null;
}
}
}
resumeAllAutoDismiss () {
if (!this.timersPaused) return;
this.timersPaused = false;
for (const toastId of Object.keys(this.autoDismissTimers)) {
this.startAutoDismissTimer(toastId);
}
}
createToastElement (toast) {
const li = toast.html
? this.cloneRichTemplate()
: this.cloneTypeTemplate(toast.type);
if (!li) return null;
li.id = toast.id;
li.style.pointerEvents = "auto";
li.dataset.mounted = "false";
li.dataset.removed = "false";
li.dataset.position = this.positionValue;
li.dataset.expanded = this.expanded.toString();
li.dataset.visible = "true";
li.dataset.front = "false";
li.dataset.index = "0";
if (toast.html) {
this.fillRichToast(li, toast);
} else {
this.fillStandardToast(li, toast);
}
this.attachCloseHandler(li, toast);
return li;
}
cloneTypeTemplate (type) {
const safeType = this.constructor.TOAST_TYPES.includes(type) ? type : "default";
const template = this._templates[safeType] || this._templates.default;
const node = template?.content.querySelector("li");
return node ? node.cloneNode(true) : null;
}
cloneRichTemplate () {
const template = this._templates.rich;
const node = template?.content.querySelector("li");
return node ? node.cloneNode(true) : null;
}
fillStandardToast (li, toast) {
const messageEl = li.querySelector('[data-toast-slot="message"]');
if (messageEl) messageEl.textContent = toast.message;
if (toast.description) {
const descEl = li.querySelector('[data-toast-slot="description"]');
if (descEl) descEl.textContent = toast.description;
} else {
li.classList.add("toast-no-description");
li.querySelector('[data-toast-slot="description"]')?.remove();
}
}
fillRichToast (li, toast) {
const contentEl = li.querySelector('[data-toast-slot="content"]');
if (!contentEl) return;
if (toast.dangerouslyAllowHtml) {
contentEl.innerHTML = toast.html;
} else {
console.warn(
"[Elevate Toast] `html` option ignored: pass `dangerouslyAllowHtml: true` " +
"to opt into raw HTML rendering. The string was rendered as text instead."
);
contentEl.textContent = toast.html;
}
}
attachCloseHandler (li, toast) {
const closeBtn = li.querySelector('[data-toast-slot="close"]');
if (!closeBtn) return;
closeBtn.dataset.toastId = toast.id;
closeBtn.addEventListener("click", (e) => {
e.stopPropagation();
this.removeToast(toast.id);
});
}
removeToast (id, isOverflow = false) {
const toast = this.toasts.find((t) => t.id === id);
if (!toast || toast.removed) return;
const toastEl = document.getElementById(id);
if (!toastEl) return;
// Mark as removed
toast.removed = true;
toastEl.dataset.removed = "true";
// Mark if this is an overflow removal
if (isOverflow) {
toastEl.dataset.overflow = "true";
}
this.clearAutoDismiss(id);
// Wait for exit animation to complete. Tracked so disconnect()/clearAllToasts()
// can cancel it before it touches a torn-down DOM.
const timeoutId = setTimeout(() => {
this.removeTimeouts.delete(id);
this.toasts = this.toasts.filter((t) => t.id !== id);
this.heights = this.heights.filter((h) => h.toastId !== id);
if (toastEl.parentNode) {
toastEl.parentNode.removeChild(toastEl);
}
this.updateAllToasts();
this.hideGlobalHostIfIdle();
if (this.toasts.length >= this.limitValue) {
const newlyVisibleToast = this.toasts[this.limitValue - 1];
if (newlyVisibleToast && !this.autoDismissTimers[newlyVisibleToast.id]) {
this.scheduleAutoDismiss(newlyVisibleToast.id);
}
}
}, MOUNT_TRANSITION_MS);
this.removeTimeouts.set(id, timeoutId);
}
updateAllToasts () {
requestAnimationFrame(() => {
const visibleToasts = this.limitValue;
// Calculate visual index (excluding removed toasts)
let visualIndex = 0;
this.toasts.forEach((toast, index) => {
const toastEl = document.getElementById(toast.id);
if (!toastEl) return;
// Handle overflow toasts (removed due to limit) separately
if (toast.removed && toastEl.dataset.overflow === "true") {
// Position as if it's the last visible toast
toastEl.dataset.index = String(this.limitValue - 1);
toastEl.dataset.visible = "true";
toastEl.dataset.expanded = this.expanded.toString();
toastEl.dataset.position = this.positionValue;
// Set lowest z-index so it appears behind all active toasts
toastEl.style.setProperty("--toast-z-index", "0");
toastEl.style.setProperty("--toast-index", String(this.limitValue - 1));
return;
}
// Skip other removed toasts
if (toast.removed) return;
const isVisible = visualIndex < visibleToasts;
const isFront = visualIndex === 0;
// Calculate offset (cumulative height of non-removed toasts before this one)
let offset = 0;
for (let i = 0; i < index; i++) {
if (this.toasts[i].removed) continue;
const heightInfo = this.heights.find((h) => h.toastId === this.toasts[i].id);
if (heightInfo) {
offset += heightInfo.height + this.gapValue;
}
}
// Update data attributes - CSS will handle styling
toastEl.dataset.expanded = this.expanded.toString();
toastEl.dataset.visible = isVisible.toString();
toastEl.dataset.front = isFront.toString();
toastEl.dataset.index = visualIndex.toString();
toastEl.dataset.position = this.positionValue;
// Set CSS custom properties for dynamic values
toastEl.style.setProperty("--toast-z-index", String(100 - visualIndex));
toastEl.style.setProperty("--toast-offset", `${offset}px`);
toastEl.style.setProperty("--toast-index", String(visualIndex));
// Set the initial height of this specific toast
const heightInfo = this.heights.find((h) => h.toastId === toast.id);
if (heightInfo) {
toastEl.style.setProperty("--initial-height", `${heightInfo.height}px`);
}
// In stacked mode, set all toasts to front toast height for uniform appearance
if (!this.expanded) {
const frontHeight = this.heights[0]?.height || 0;
toastEl.style.setProperty("--front-toast-height", `${frontHeight}px`);
} else {
toastEl.style.removeProperty("--front-toast-height");
}
// Increment visual index for next non-removed toast
visualIndex++;
});
// Update container height immediately and after transitions complete
this.updateContainerHeight();
setTimeout(() => this.updateContainerHeight(), MOUNT_TRANSITION_MS);
});
}
updateContainerHeight () {
// Count non-removed toasts
const activeToasts = this.activeToasts;
if (activeToasts.length === 0) {
this.containerTarget.style.height = "0px";
this.hideGlobalHostIfIdle();
return;
}
if (this.expanded) {
// In expanded mode, calculate total height of all visible non-removed toasts
let totalHeight = 0;
const visibleToasts = Math.min(activeToasts.length, this.limitValue);
for (let i = 0; i < visibleToasts; i++) {
const heightInfo = this.heights.find((h) => h.toastId === activeToasts[i].id);
if (heightInfo) {
totalHeight += heightInfo.height;
if (i < visibleToasts - 1) {
totalHeight += this.gapValue;
}
}
}
this.containerTarget.style.height = totalHeight + "px";
} else {
// In stacked mode, calculate based on front non-removed toast + peek amounts
const frontToast = activeToasts[0];
const frontHeight = frontToast ? this.heights.find((h) => h.toastId === frontToast.id)?.height || 0 : 0;
const peekAmount = 24;
const visibleCount = Math.min(activeToasts.length, this.limitValue);
const totalHeight = frontHeight + peekAmount * (visibleCount - 1);
this.containerTarget.style.height = totalHeight + "px";
}
}
registerController () {
if (!window.__toastControllers) {
window.__toastControllers = new Set();
}
window.__toastControllers.add(this);
}
unregisterController () {
if (window.__toastControllers) {
window.__toastControllers.delete(this);
}
}
activatePrimaryIfNeeded () {
const existingPrimary = window.__toastPrimaryController;
const existingPrimaryConnected = existingPrimary?.element?.isConnected;
if (existingPrimary && existingPrimary !== this && existingPrimaryConnected) {
return;
}
this.becomePrimaryController();
}
becomePrimaryController () {
if (this.isPrimaryController) return;
this.isPrimaryController = true;
window.__toastPrimaryController = this;
this.initializePositionState();
this.updatePositionClasses();
this.mountToGlobalHost();
this.applyPointerEventPolicy();
this.boundShowToast = this.showToast.bind(this);
window.toast = this.boundShowToast;
this.boundHandleToastShow = this.handleToastShow.bind(this);
this.boundHandleLayoutChange = this.handleLayoutChange.bind(this);
this.boundPointerMove = this.handleGlobalPointerMove.bind(this);
this.boundPointerLeave = this.handleGlobalPointerLeave.bind(this);
this.boundHandleDialogStateChange = this.handleDialogStateChange.bind(this);
this.boundPauseTimers = this.pauseAllAutoDismiss.bind(this);
this.boundResumeTimers = this.resumeAllAutoDismiss.bind(this);
this.boundVisibilityChange = () => {
if (document.visibilityState === "hidden") this.pauseAllAutoDismiss();
else this.resumeAllAutoDismiss();
};
window.addEventListener("toast-show", this.boundHandleToastShow);
window.addEventListener("set-toasts-layout", this.boundHandleLayoutChange);
window.addEventListener("pointermove", this.boundPointerMove, { passive: true });
window.addEventListener("pointerleave", this.boundPointerLeave);
window.addEventListener("blur", this.boundPointerLeave);
document.addEventListener("visibilitychange", this.boundVisibilityChange);
if (this.hasContainerTarget) {
this.containerTarget.addEventListener("focusin", this.boundPauseTimers);
this.containerTarget.addEventListener("focusout", this.boundResumeTimers);
}
this.startDialogStateObserver();
}
removePrimaryListeners () {
if (this.boundHandleToastShow) {
window.removeEventListener("toast-show", this.boundHandleToastShow);
}
if (this.boundHandleLayoutChange) {
window.removeEventListener("set-toasts-layout", this.boundHandleLayoutChange);
}
if (this.boundPointerMove) {
window.removeEventListener("pointermove", this.boundPointerMove);
}
if (this.boundPointerLeave) {
window.removeEventListener("pointerleave", this.boundPointerLeave);
window.removeEventListener("blur", this.boundPointerLeave);
}
if (this.boundVisibilityChange) {
document.removeEventListener("visibilitychange", this.boundVisibilityChange);
}
if (this.hasContainerTarget) {
if (this.boundPauseTimers) {
this.containerTarget.removeEventListener("focusin", this.boundPauseTimers);
}
if (this.boundResumeTimers) {
this.containerTarget.removeEventListener("focusout", this.boundResumeTimers);
}
}
this.stopDialogStateObserver();
}
promoteNextPrimaryController () {
if (!window.__toastControllers?.size) return;
const candidates = Array.from(window.__toastControllers).filter(
(controller) => controller?.element?.isConnected,
);
if (candidates.length === 0) return;
// Preference order:
// 1) inside an open <dialog> (modal flows: toast must mount above the dialog)
// 2) most recently connected (latest mounted host = most likely the active view)
const inOpenDialog = candidates.find((c) => c.element.closest("dialog[open]"));
const next = inOpenDialog || candidates[candidates.length - 1];
next.becomePrimaryController();
}
initializePositionState () {
const hostPosition = this.detectHostPosition();
if (hostPosition) {
this.positionValue = hostPosition;
} else if (window.currentToastPosition) {
this.positionValue = window.currentToastPosition;
}
window.currentToastPosition = this.positionValue;
}
detectHostPosition () {
if (!this.element) return null;
for (const value of this.constructor.POSITION_VALUES) {
if (this.element.classList.contains(`elevate-toast--position--${value}`)) {
return value;
}
}
return null;
}
mountToGlobalHost () {
this.globalHost = this.element;
if (!this.globalHost) return;
if (typeof this.globalHost.showPopover === "function" && !this.globalHost.hasAttribute("popover")) {
this.globalHost.setAttribute("popover", "manual");
}
const mountRoot = this.preferredMountRoot();
if (!mountRoot) return;
if (this.globalHost.parentNode !== mountRoot) {
if (typeof this.globalHost.hidePopover === "function") {
try {
if (this.globalHost.matches(":popover-open")) {
this.globalHost.hidePopover();
}
} catch {
// Ignore popover state errors before remount.
}
}
if (mountRoot === this.defaultMountParent && this.defaultMountNextSibling?.parentNode === mountRoot) {
mountRoot.insertBefore(this.globalHost, this.defaultMountNextSibling);
} else {
mountRoot.appendChild(this.globalHost);
}
}
}
preferredMountRoot () {
const openDialog = this.topmostOpenDialog();
if (openDialog) return openDialog;
const parentDialog = this.defaultMountParent instanceof Element ? this.defaultMountParent.closest("dialog") : null;
if (parentDialog && !parentDialog.open) return document.body;
if (this.defaultMountParent?.tagName === "DIALOG" && !this.defaultMountParent.open) {
return document.body;
}
return this.defaultMountParent || document.body;
}
topmostOpenDialog () {
const openDialogs = Array.from(document.querySelectorAll("dialog[open]")).filter((dialog) => dialog.isConnected);
if (openDialogs.length === 0) return null;
return openDialogs[openDialogs.length - 1];
}
applyPointerEventPolicy () {
// Make the host and container "click-through" so the page below the toast
// overlay stays interactive. Individual toast <li>s re-enable pointer-events
// in createToastElement (li.style.pointerEvents = "auto") so close buttons
// and focus still work. Keep these two policies in sync if you change one.
if (this.element) {
this.element.style.pointerEvents = "none";
}
if (this.hasContainerTarget) {
this.containerTarget.style.pointerEvents = "none";
}
}
ensureGlobalHostVisible () {
this.mountToGlobalHost();
if (!this.globalHost || typeof this.globalHost.showPopover !== "function") return;
try {
if (this.globalHost.matches(":popover-open")) {
this.globalHost.hidePopover();
}
} catch {
// Ignore popover close errors.
}
try {
this.globalHost.showPopover();
} catch {
// No-op: keep standard DOM rendering when Popover API isn't available.
}
}
hideGlobalHostIfIdle () {
if (!this.globalHost || typeof this.globalHost.hidePopover !== "function") return;
const hasActiveToasts = this.activeToasts.length > 0;
if (hasActiveToasts) return;
try {
if (this.globalHost.matches(":popover-open")) {
this.globalHost.hidePopover();
}
} catch {
// No-op: host stays visible when popover state isn't available.
}
}
startDialogStateObserver () {
if (this.dialogStateObserver) return;
if (!document.body) return;
this.dialogStateObserver = new MutationObserver(this.boundHandleDialogStateChange);
this.dialogStateObserver.observe(document.body, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ["open"],
});
}
stopDialogStateObserver () {
if (!this.dialogStateObserver) return;
this.dialogStateObserver.disconnect();
this.dialogStateObserver = null;
}
handleDialogStateChange () {
if (!this.isPrimaryController) return;
this.mountToGlobalHost();
const hasActiveToasts = this.activeToasts.length > 0;
if (hasActiveToasts) {
this.ensureGlobalHostVisible();
} else {
this.hideGlobalHostIfIdle();
}
}
setExpandedState (nextExpanded) {
if (this.layoutValue !== "default") return;
if (nextExpanded === this.expanded) return;
if (!nextExpanded && this.interacting) return;
this.expanded = nextExpanded;
this.updateAllToasts();
}
handleGlobalPointerMove (event) {
if (!this.isPrimaryController) return;
if (!this.hasContainerTarget) return;
// Latch coordinates and resolve once per frame: getBoundingClientRect is
// a layout read, and pointermove can fire at >100 Hz on modern trackpads.
this._lastPointer = { x: event.clientX, y: event.clientY };
if (this._pointerRafScheduled) return;
this._pointerRafScheduled = true;
requestAnimationFrame(() => {
this._pointerRafScheduled = false;
if (!this.isPrimaryController || !this.hasContainerTarget) return;
if (this.activeToasts.length === 0) {
this.setExpandedState(false);
return;
}
const { x, y } = this._lastPointer;
this.setExpandedState(this.isInHoverZone(x, y));
});
}
handleGlobalPointerLeave () {
if (!this.isPrimaryController) return;
this.setExpandedState(false);
}
isInHoverZone (clientX, clientY) {
const rect = this.containerTarget.getBoundingClientRect();
const pad = this.hoverZonePadding;
return (
clientX >= rect.left - pad &&
clientX <= rect.right + pad &&
clientY >= rect.top - pad &&
clientY <= rect.bottom + pad
);
}
}