basecoat-css 0.1.1 → 0.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ (() => {
2
+ const initSelect = (selectComponent) => {
3
+ const trigger = selectComponent.querySelector(':scope > [popovertarget]');
4
+ const selectedValue = trigger.querySelector(':scope > span');
5
+ const popover = selectComponent.querySelector(':scope > [popover]');
6
+ const listbox = popover.querySelector('[role="listbox"]');
7
+ const input = selectComponent.querySelector(':scope > input[type="hidden"]');
8
+ const filter = selectComponent.querySelector('header input[type="text"]');
9
+ if (!trigger || !popover || !listbox || !input) return;
10
+
11
+ const options = Array.from(listbox.querySelectorAll('[role="option"]'));
12
+ let visibleOptions = [...options];
13
+ let activeIndex = -1;
14
+
15
+ const updateValue = (option) => {
16
+ if (option) {
17
+ selectedValue.innerHTML = option.dataset.label || option.innerHTML;
18
+ input.value = option.dataset.value;
19
+ listbox.querySelector('[role="option"][aria-selected="true"]')?.removeAttribute('aria-selected');
20
+ option.setAttribute('aria-selected', 'true');
21
+ }
22
+ };
23
+
24
+ const selectOption = (option) => {
25
+ if (!option) return;
26
+
27
+ updateValue(option);
28
+
29
+ trigger.removeAttribute('aria-activedescendant');
30
+ options.forEach(opt => opt.classList.remove('active'));
31
+ activeIndex = -1;
32
+ popover.hidePopover();
33
+ };
34
+
35
+ if (filter) {
36
+ const filterOptions = () => {
37
+ const searchTerm = filter.value.trim().toLowerCase();
38
+
39
+ if (activeIndex > -1) {
40
+ options[activeIndex].classList.remove('active');
41
+ trigger.removeAttribute('aria-activedescendant');
42
+ activeIndex = -1;
43
+ }
44
+
45
+ visibleOptions = [];
46
+ options.forEach(option => {
47
+ const optionText = (option.dataset.label || option.textContent).trim().toLowerCase();
48
+ const matches = optionText.includes(searchTerm);
49
+ option.setAttribute('aria-hidden', String(!matches));
50
+ if (matches) {
51
+ visibleOptions.push(option);
52
+ }
53
+ });
54
+ };
55
+
56
+ filter.addEventListener('input', filterOptions);
57
+ }
58
+
59
+ let initialOption = options.find(opt => input.value && opt.dataset.value === input.value);
60
+ if (!initialOption && options.length > 0) initialOption = options[0];
61
+
62
+ updateValue(initialOption);
63
+
64
+ const handleKeyNavigation = (e) => {
65
+ if (!['ArrowDown', 'ArrowUp', 'Enter', 'Home', 'End'].includes(e.key)) {
66
+ return;
67
+ }
68
+
69
+ if (!popover.matches(':popover-open')) {
70
+ if (e.currentTarget === trigger && e.key !== 'Enter') {
71
+ e.preventDefault();
72
+ trigger.click();
73
+ }
74
+ return;
75
+ }
76
+
77
+ e.preventDefault();
78
+
79
+ if (e.key === 'Enter') {
80
+ if (activeIndex > -1) {
81
+ selectOption(options[activeIndex]);
82
+ }
83
+ return;
84
+ }
85
+
86
+ if (visibleOptions.length === 0) return;
87
+
88
+ const currentVisibleIndex = activeIndex > -1 ? visibleOptions.indexOf(options[activeIndex]) : -1;
89
+ let nextVisibleIndex = currentVisibleIndex;
90
+
91
+ switch (e.key) {
92
+ case 'ArrowDown':
93
+ if (currentVisibleIndex < visibleOptions.length - 1) {
94
+ nextVisibleIndex = currentVisibleIndex + 1;
95
+ }
96
+ break;
97
+ case 'ArrowUp':
98
+ if (currentVisibleIndex > 0) {
99
+ nextVisibleIndex = currentVisibleIndex - 1;
100
+ } else if (currentVisibleIndex === -1) {
101
+ nextVisibleIndex = 0; // Start from top if nothing is active
102
+ }
103
+ break;
104
+ case 'Home':
105
+ nextVisibleIndex = 0;
106
+ break;
107
+ case 'End':
108
+ nextVisibleIndex = visibleOptions.length - 1;
109
+ break;
110
+ }
111
+
112
+ if (nextVisibleIndex !== currentVisibleIndex) {
113
+ if (currentVisibleIndex > -1) {
114
+ visibleOptions[currentVisibleIndex].classList.remove('active');
115
+ }
116
+
117
+ const newActiveOption = visibleOptions[nextVisibleIndex];
118
+ newActiveOption.classList.add('active');
119
+ activeIndex = options.indexOf(newActiveOption);
120
+
121
+ if (newActiveOption.id) {
122
+ trigger.setAttribute('aria-activedescendant', newActiveOption.id);
123
+ }
124
+ newActiveOption.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
125
+ }
126
+ };
127
+
128
+ trigger.addEventListener('keydown', handleKeyNavigation);
129
+ if (filter) {
130
+ filter.addEventListener('keydown', handleKeyNavigation);
131
+ }
132
+
133
+ listbox.addEventListener('click', (e) => {
134
+ const clickedOption = e.target.closest('[role="option"]');
135
+ if (clickedOption) {
136
+ selectOption(clickedOption);
137
+ }
138
+ });
139
+
140
+ popover.addEventListener('toggle', (e) => {
141
+ trigger.setAttribute('aria-expanded', e.newState === 'open');
142
+
143
+ if (e.newState === 'open') {
144
+ if (filter) filter.focus();
145
+
146
+ const selectedOption = listbox.querySelector('[role="option"][aria-selected="true"]');
147
+ let startingOption = null;
148
+
149
+ if (selectedOption && visibleOptions.includes(selectedOption)) {
150
+ startingOption = selectedOption;
151
+ } else if (visibleOptions.length > 0) {
152
+ startingOption = visibleOptions[0];
153
+ }
154
+
155
+ if (activeIndex > -1) options[activeIndex]?.classList.remove('active');
156
+
157
+ if (startingOption) {
158
+ activeIndex = options.indexOf(startingOption);
159
+ startingOption.classList.add('active');
160
+ if (startingOption.id) {
161
+ trigger.setAttribute('aria-activedescendant', startingOption.id);
162
+ }
163
+ startingOption.scrollIntoView({ block: 'nearest' });
164
+ } else {
165
+ activeIndex = -1;
166
+ }
167
+ } else if (e.newState === 'closed') {
168
+ if (filter) {
169
+ filter.value = '';
170
+ visibleOptions = [...options];
171
+ options.forEach(opt => opt.setAttribute('aria-hidden', 'false'));
172
+ }
173
+
174
+ trigger.removeAttribute('aria-activedescendant');
175
+ if (activeIndex > -1) options[activeIndex]?.classList.remove('active');
176
+ activeIndex = -1;
177
+ }
178
+ });
179
+
180
+ selectComponent.dataset.selectInitialized = true;
181
+ };
182
+
183
+ document.querySelectorAll('div.select:not([data-select-initialized])').forEach(initSelect);
184
+
185
+ const observer = new MutationObserver((mutations) => {
186
+ mutations.forEach((mutation) => {
187
+ mutation.addedNodes.forEach((node) => {
188
+ if (node.nodeType === Node.ELEMENT_NODE) {
189
+ if (node.matches('div.select:not([data-select-initialized])')) {
190
+ initSelect(node);
191
+ }
192
+ node.querySelectorAll('div.select:not([data-select-initialized])').forEach(initSelect);
193
+ }
194
+ });
195
+ });
196
+ });
197
+
198
+ observer.observe(document.body, { childList: true, subtree: true });
199
+ })();
@@ -0,0 +1 @@
1
+ (()=>{const e=e=>{const t=e.querySelector(":scope > [popovertarget]"),r=t.querySelector(":scope > span"),a=e.querySelector(":scope > [popover]"),i=a.querySelector('[role="listbox"]'),o=e.querySelector(':scope > input[type="hidden"]'),n=e.querySelector('header input[type="text"]');if(!(t&&a&&i&&o))return;const s=Array.from(i.querySelectorAll('[role="option"]'));let c=[...s],l=-1;const d=e=>{e&&(r.innerHTML=e.dataset.label||e.innerHTML,o.value=e.dataset.value,i.querySelector('[role="option"][aria-selected="true"]')?.removeAttribute("aria-selected"),e.setAttribute("aria-selected","true"))},u=e=>{e&&(d(e),t.removeAttribute("aria-activedescendant"),s.forEach((e=>e.classList.remove("active"))),l=-1,a.hidePopover())};if(n){const e=()=>{const e=n.value.trim().toLowerCase();l>-1&&(s[l].classList.remove("active"),t.removeAttribute("aria-activedescendant"),l=-1),c=[],s.forEach((t=>{const r=(t.dataset.label||t.textContent).trim().toLowerCase().includes(e);t.setAttribute("aria-hidden",String(!r)),r&&c.push(t)}))};n.addEventListener("input",e)}let v=s.find((e=>o.value&&e.dataset.value===o.value));!v&&s.length>0&&(v=s[0]),d(v);const p=e=>{if(!["ArrowDown","ArrowUp","Enter","Home","End"].includes(e.key))return;if(!a.matches(":popover-open"))return void(e.currentTarget===t&&"Enter"!==e.key&&(e.preventDefault(),t.click()));if(e.preventDefault(),"Enter"===e.key)return void(l>-1&&u(s[l]));if(0===c.length)return;const r=l>-1?c.indexOf(s[l]):-1;let i=r;switch(e.key){case"ArrowDown":r<c.length-1&&(i=r+1);break;case"ArrowUp":r>0?i=r-1:-1===r&&(i=0);break;case"Home":i=0;break;case"End":i=c.length-1}if(i!==r){r>-1&&c[r].classList.remove("active");const e=c[i];e.classList.add("active"),l=s.indexOf(e),e.id&&t.setAttribute("aria-activedescendant",e.id),e.scrollIntoView({block:"nearest",behavior:"smooth"})}};t.addEventListener("keydown",p),n&&n.addEventListener("keydown",p),i.addEventListener("click",(e=>{const t=e.target.closest('[role="option"]');t&&u(t)})),a.addEventListener("toggle",(e=>{if(t.setAttribute("aria-expanded","open"===e.newState),"open"===e.newState){n&&n.focus();const e=i.querySelector('[role="option"][aria-selected="true"]');let r=null;e&&c.includes(e)?r=e:c.length>0&&(r=c[0]),l>-1&&s[l]?.classList.remove("active"),r?(l=s.indexOf(r),r.classList.add("active"),r.id&&t.setAttribute("aria-activedescendant",r.id),r.scrollIntoView({block:"nearest"})):l=-1}else"closed"===e.newState&&(n&&(n.value="",c=[...s],s.forEach((e=>e.setAttribute("aria-hidden","false")))),t.removeAttribute("aria-activedescendant"),l>-1&&s[l]?.classList.remove("active"),l=-1)})),e.dataset.selectInitialized=!0};document.querySelectorAll("div.select:not([data-select-initialized])").forEach(e);new MutationObserver((t=>{t.forEach((t=>{t.addedNodes.forEach((t=>{t.nodeType===Node.ELEMENT_NODE&&(t.matches("div.select:not([data-select-initialized])")&&e(t),t.querySelectorAll("div.select:not([data-select-initialized])").forEach(e))}))}))})).observe(document.body,{childList:!0,subtree:!0})})();
@@ -0,0 +1,110 @@
1
+ (() => {
2
+ // Monkey patching the history API to detect client-side navigation
3
+ if (!window.history.__basecoatPatched) {
4
+ const originalPushState = window.history.pushState;
5
+ window.history.pushState = function(...args) {
6
+ originalPushState.apply(this, args);
7
+ window.dispatchEvent(new Event('basecoat:locationchange'));
8
+ };
9
+
10
+ const originalReplaceState = window.history.replaceState;
11
+ window.history.replaceState = function(...args) {
12
+ originalReplaceState.apply(this, args);
13
+ window.dispatchEvent(new Event('basecoat:locationchange'));
14
+ };
15
+
16
+ window.history.__basecoatPatched = true;
17
+ }
18
+
19
+ const initSidebar = (sidebarComponent) => {
20
+ const initialOpen = sidebarComponent.dataset.initialOpen !== 'false';
21
+ const initialMobileOpen = sidebarComponent.dataset.initialMobileOpen === 'true';
22
+ const breakpoint = parseInt(sidebarComponent.dataset.breakpoint) || 768;
23
+
24
+ let open = breakpoint > 0
25
+ ? (window.innerWidth >= breakpoint ? initialOpen : initialMobileOpen)
26
+ : initialOpen;
27
+
28
+ const updateCurrentPageLinks = () => {
29
+ const currentPath = window.location.pathname.replace(/\/$/, '');
30
+ sidebarComponent.querySelectorAll('a').forEach(link => {
31
+ if (link.hasAttribute('data-ignore-current')) return;
32
+
33
+ const linkPath = new URL(link.href).pathname.replace(/\/$/, '');
34
+ if (linkPath === currentPath) {
35
+ link.setAttribute('aria-current', 'page');
36
+ } else {
37
+ link.removeAttribute('aria-current');
38
+ }
39
+ });
40
+ };
41
+
42
+ const updateState = () => {
43
+ sidebarComponent.setAttribute('aria-hidden', !open);
44
+ if (open) {
45
+ sidebarComponent.removeAttribute('inert');
46
+ } else {
47
+ sidebarComponent.setAttribute('inert', '');
48
+ }
49
+ };
50
+
51
+ const setState = (state) => {
52
+ open = state;
53
+ updateState();
54
+ };
55
+
56
+ const sidebarId = sidebarComponent.id;
57
+
58
+ window.addEventListener('sidebar:open', (e) => {
59
+ if (!e.detail?.id || e.detail.id === sidebarId) setState(true);
60
+ });
61
+ window.addEventListener('sidebar:close', (e) => {
62
+ if (!e.detail?.id || e.detail.id === sidebarId) setState(false);
63
+ });
64
+ window.addEventListener('sidebar:toggle', (e) => {
65
+ if (!e.detail?.id || e.detail.id === sidebarId) setState(!open);
66
+ });
67
+
68
+ sidebarComponent.addEventListener('click', (e) => {
69
+ const target = e.target;
70
+ const nav = sidebarComponent.querySelector('nav');
71
+
72
+ const isMobile = window.innerWidth < breakpoint;
73
+
74
+ if (isMobile && (target.closest('a, button') && !target.closest('[data-keep-mobile-sidebar-open]'))) {
75
+ if (document.activeElement) document.activeElement.blur();
76
+ setState(false);
77
+ return;
78
+ }
79
+
80
+ if (target === sidebarComponent || (nav && !nav.contains(target))) {
81
+ if (document.activeElement) document.activeElement.blur();
82
+ setState(false);
83
+ }
84
+ });
85
+
86
+ window.addEventListener('popstate', updateCurrentPageLinks);
87
+ window.addEventListener('basecoat:locationchange', updateCurrentPageLinks);
88
+
89
+ updateState();
90
+ updateCurrentPageLinks();
91
+ sidebarComponent.dataset.sidebarInitialized = true;
92
+ };
93
+
94
+ document.querySelectorAll('.sidebar:not([data-sidebar-initialized])').forEach(initSidebar);
95
+
96
+ const observer = new MutationObserver((mutations) => {
97
+ mutations.forEach((mutation) => {
98
+ mutation.addedNodes.forEach((node) => {
99
+ if (node.nodeType === Node.ELEMENT_NODE) {
100
+ if (node.matches('.sidebar:not([data-sidebar-initialized])')) {
101
+ initSidebar(node);
102
+ }
103
+ node.querySelectorAll('.sidebar:not([data-sidebar-initialized])').forEach(initSidebar);
104
+ }
105
+ });
106
+ });
107
+ });
108
+
109
+ observer.observe(document.body, { childList: true, subtree: true });
110
+ })();
@@ -0,0 +1 @@
1
+ (()=>{if(!window.history.__basecoatPatched){const e=window.history.pushState;window.history.pushState=function(...t){e.apply(this,t),window.dispatchEvent(new Event("basecoat:locationchange"))};const t=window.history.replaceState;window.history.replaceState=function(...e){t.apply(this,e),window.dispatchEvent(new Event("basecoat:locationchange"))},window.history.__basecoatPatched=!0}const e=e=>{const t="false"!==e.dataset.initialOpen,i="true"===e.dataset.initialMobileOpen,a=parseInt(e.dataset.breakpoint)||768;let n=a>0?window.innerWidth>=a?t:i:t;const d=()=>{const t=window.location.pathname.replace(/\/$/,"");e.querySelectorAll("a").forEach((e=>{if(e.hasAttribute("data-ignore-current"))return;new URL(e.href).pathname.replace(/\/$/,"")===t?e.setAttribute("aria-current","page"):e.removeAttribute("aria-current")}))},o=()=>{e.setAttribute("aria-hidden",!n),n?e.removeAttribute("inert"):e.setAttribute("inert","")},r=e=>{n=e,o()},s=e.id;window.addEventListener("sidebar:open",(e=>{e.detail?.id&&e.detail.id!==s||r(!0)})),window.addEventListener("sidebar:close",(e=>{e.detail?.id&&e.detail.id!==s||r(!1)})),window.addEventListener("sidebar:toggle",(e=>{e.detail?.id&&e.detail.id!==s||r(!n)})),e.addEventListener("click",(t=>{const i=t.target,n=e.querySelector("nav");if(window.innerWidth<a&&i.closest("a, button")&&!i.closest("[data-keep-mobile-sidebar-open]"))return document.activeElement&&document.activeElement.blur(),void r(!1);(i===e||n&&!n.contains(i))&&(document.activeElement&&document.activeElement.blur(),r(!1))})),window.addEventListener("popstate",d),window.addEventListener("basecoat:locationchange",d),o(),d(),e.dataset.sidebarInitialized=!0};document.querySelectorAll(".sidebar:not([data-sidebar-initialized])").forEach(e);new MutationObserver((t=>{t.forEach((t=>{t.addedNodes.forEach((t=>{t.nodeType===Node.ELEMENT_NODE&&(t.matches(".sidebar:not([data-sidebar-initialized])")&&e(t),t.querySelectorAll(".sidebar:not([data-sidebar-initialized])").forEach(e))}))}))})).observe(document.body,{childList:!0,subtree:!0})})();
@@ -0,0 +1,75 @@
1
+ (() => {
2
+ const initTabs = (tabsComponent) => {
3
+ const tablist = tabsComponent.querySelector('[role="tablist"]');
4
+ if (!tablist) return;
5
+
6
+ const tabs = Array.from(tablist.querySelectorAll('[role="tab"]'));
7
+ const panels = tabs.map(tab => document.getElementById(tab.getAttribute('aria-controls'))).filter(Boolean);
8
+
9
+ const selectTab = (tabToSelect) => {
10
+ tabs.forEach((tab, index) => {
11
+ tab.setAttribute('aria-selected', 'false');
12
+ tab.setAttribute('tabindex', '-1');
13
+ if (panels[index]) panels[index].hidden = true;
14
+ });
15
+
16
+ tabToSelect.setAttribute('aria-selected', 'true');
17
+ tabToSelect.setAttribute('tabindex', '0');
18
+ const activePanel = document.getElementById(tabToSelect.getAttribute('aria-controls'));
19
+ if (activePanel) activePanel.hidden = false;
20
+ };
21
+
22
+ tablist.addEventListener('click', (e) => {
23
+ const clickedTab = e.target.closest('[role="tab"]');
24
+ if (clickedTab) selectTab(clickedTab);
25
+ });
26
+
27
+ tablist.addEventListener('keydown', (e) => {
28
+ const currentTab = e.target;
29
+ if (!tabs.includes(currentTab)) return;
30
+
31
+ let nextTab;
32
+ const currentIndex = tabs.indexOf(currentTab);
33
+
34
+ switch (e.key) {
35
+ case 'ArrowRight':
36
+ nextTab = tabs[(currentIndex + 1) % tabs.length];
37
+ break;
38
+ case 'ArrowLeft':
39
+ nextTab = tabs[(currentIndex - 1 + tabs.length) % tabs.length];
40
+ break;
41
+ case 'Home':
42
+ nextTab = tabs[0];
43
+ break;
44
+ case 'End':
45
+ nextTab = tabs[tabs.length - 1];
46
+ break;
47
+ default:
48
+ return;
49
+ }
50
+
51
+ e.preventDefault();
52
+ selectTab(nextTab);
53
+ nextTab.focus();
54
+ });
55
+
56
+ tabsComponent.dataset.tabsInitialized = true;
57
+ };
58
+
59
+ document.querySelectorAll('.tabs:not([data-tabs-initialized])').forEach(initTabs);
60
+
61
+ const observer = new MutationObserver((mutations) => {
62
+ mutations.forEach((mutation) => {
63
+ mutation.addedNodes.forEach((node) => {
64
+ if (node.nodeType === Node.ELEMENT_NODE) {
65
+ if (node.matches('.tabs:not([data-tabs-initialized])')) {
66
+ initTabs(node);
67
+ }
68
+ node.querySelectorAll('.tabs:not([data-tabs-initialized])').forEach(initTabs);
69
+ }
70
+ });
71
+ });
72
+ });
73
+
74
+ observer.observe(document.body, { childList: true, subtree: true });
75
+ })();
@@ -0,0 +1 @@
1
+ (()=>{const e=e=>{const t=e.querySelector('[role="tablist"]');if(!t)return;const a=Array.from(t.querySelectorAll('[role="tab"]')),r=a.map((e=>document.getElementById(e.getAttribute("aria-controls")))).filter(Boolean),n=e=>{a.forEach(((e,t)=>{e.setAttribute("aria-selected","false"),e.setAttribute("tabindex","-1"),r[t]&&(r[t].hidden=!0)})),e.setAttribute("aria-selected","true"),e.setAttribute("tabindex","0");const t=document.getElementById(e.getAttribute("aria-controls"));t&&(t.hidden=!1)};t.addEventListener("click",(e=>{const t=e.target.closest('[role="tab"]');t&&n(t)})),t.addEventListener("keydown",(e=>{const t=e.target;if(!a.includes(t))return;let r;const o=a.indexOf(t);switch(e.key){case"ArrowRight":r=a[(o+1)%a.length];break;case"ArrowLeft":r=a[(o-1+a.length)%a.length];break;case"Home":r=a[0];break;case"End":r=a[a.length-1];break;default:return}e.preventDefault(),n(r),r.focus()})),e.dataset.tabsInitialized=!0};document.querySelectorAll(".tabs:not([data-tabs-initialized])").forEach(e);new MutationObserver((t=>{t.forEach((t=>{t.addedNodes.forEach((t=>{t.nodeType===Node.ELEMENT_NODE&&(t.matches(".tabs:not([data-tabs-initialized])")&&e(t),t.querySelectorAll(".tabs:not([data-tabs-initialized])").forEach(e))}))}))})).observe(document.body,{childList:!0,subtree:!0})})();
@@ -0,0 +1,196 @@
1
+ (() => {
2
+ let toaster;
3
+ const toasts = new WeakMap();
4
+ let isPaused = false;
5
+ const ICONS = {
6
+ success: '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>',
7
+ error: '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>',
8
+ info: '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>',
9
+ warning: '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>'
10
+ };
11
+
12
+ function initToaster(toasterElement) {
13
+ if (toasterElement.dataset.toasterInitialized) return;
14
+ toaster = toasterElement;
15
+
16
+ toaster.addEventListener('mouseenter', pauseAllTimeouts);
17
+ toaster.addEventListener('mouseleave', resumeAllTimeouts);
18
+ toaster.addEventListener('click', (e) => {
19
+ const actionLink = e.target.closest('.toast footer a');
20
+ const actionButton = e.target.closest('.toast footer button');
21
+ if (actionLink || actionButton) {
22
+ closeToast(e.target.closest('.toast'));
23
+ }
24
+ });
25
+
26
+ toaster.querySelectorAll('.toast:not([data-toast-initialized])').forEach(initToast);
27
+ toaster.dataset.toasterInitialized = 'true';
28
+ }
29
+
30
+ function initToast(element) {
31
+ if (element.dataset.toastInitialized) return;
32
+
33
+ const duration = parseInt(element.dataset.duration);
34
+ const timeoutDuration = duration !== -1
35
+ ? duration || (element.dataset.category === 'error' ? 5000 : 3000)
36
+ : -1;
37
+
38
+ const state = {
39
+ remainingTime: timeoutDuration,
40
+ timeoutId: null,
41
+ startTime: null,
42
+ };
43
+
44
+ if (timeoutDuration !== -1) {
45
+ if (isPaused) {
46
+ state.timeoutId = null;
47
+ } else {
48
+ state.startTime = Date.now();
49
+ state.timeoutId = setTimeout(() => closeToast(element), timeoutDuration);
50
+ }
51
+ }
52
+ toasts.set(element, state);
53
+
54
+ element.dataset.toastInitialized = 'true';
55
+ }
56
+
57
+ function pauseAllTimeouts() {
58
+ if (isPaused) return;
59
+
60
+ isPaused = true;
61
+
62
+ toaster.querySelectorAll('.toast:not([aria-hidden="true"])').forEach(element => {
63
+ if (!toasts.has(element)) return;
64
+
65
+ const state = toasts.get(element);
66
+ if (state.timeoutId) {
67
+ clearTimeout(state.timeoutId);
68
+ state.timeoutId = null;
69
+ state.remainingTime -= Date.now() - state.startTime;
70
+ }
71
+ });
72
+ }
73
+
74
+ function resumeAllTimeouts() {
75
+ if (!isPaused) return;
76
+
77
+ isPaused = false;
78
+
79
+ toaster.querySelectorAll('.toast:not([aria-hidden="true"])').forEach(element => {
80
+ if (!toasts.has(element)) return;
81
+
82
+ const state = toasts.get(element);
83
+ if (state.remainingTime !== -1 && !state.timeoutId) {
84
+ if (state.remainingTime > 0) {
85
+ state.startTime = Date.now();
86
+ state.timeoutId = setTimeout(() => closeToast(element), state.remainingTime);
87
+ } else {
88
+ closeToast(element);
89
+ }
90
+ }
91
+ });
92
+ }
93
+
94
+ function closeToast(element) {
95
+ if (!toasts.has(element)) return;
96
+
97
+ const state = toasts.get(element);
98
+ clearTimeout(state.timeoutId);
99
+ toasts.delete(element);
100
+
101
+ if (document.activeElement) document.activeElement.blur();
102
+ element.setAttribute('aria-hidden', 'true');
103
+ element.addEventListener('transitionend', () => element.remove(), { once: true });
104
+ }
105
+
106
+ function executeAction(button, toast) {
107
+ const actionString = button.dataset.toastAction;
108
+ if (!actionString) return;
109
+ try {
110
+ const func = new Function('close', actionString);
111
+ func(() => closeToast(toast));
112
+ } catch (e) {
113
+ console.error('Error executing toast action:', e);
114
+ }
115
+ }
116
+
117
+ function createToast(config) {
118
+ const {
119
+ category = 'info',
120
+ title,
121
+ description,
122
+ action,
123
+ cancel,
124
+ duration,
125
+ icon,
126
+ } = config;
127
+
128
+ const iconHtml = icon || (category && ICONS[category]) || '';
129
+ const titleHtml = title ? `<h2>${title}</h2>` : '';
130
+ const descriptionHtml = description ? `<p>${description}</p>` : '';
131
+ const actionHtml = action?.href
132
+ ? `<a href="${action.href}" class="btn" data-toast-action>${action.label}</a>`
133
+ : action?.onclick
134
+ ? `<button type="button" class="btn" data-toast-action onclick="${action.onclick}">${action.label}</button>`
135
+ : '';
136
+ const cancelHtml = cancel
137
+ ? `<button type="button" class="btn-outline h-6 text-xs px-2.5 rounded-sm" data-toast-cancel onclick="${cancel?.onclick}">${cancel.label}</button>`
138
+ : '';
139
+
140
+ const footerHtml = actionHtml || cancelHtml ? `<footer>${actionHtml}${cancelHtml}</footer>` : '';
141
+
142
+ const html = `
143
+ <div
144
+ class="toast"
145
+ role="${category === 'error' ? 'alert' : 'status'}"
146
+ aria-atomic="true"
147
+ ${category ? `data-category="${category}"` : ''}
148
+ ${duration !== undefined ? `data-duration="${duration}"` : ''}
149
+ >
150
+ <div class="toast-content">
151
+ ${iconHtml}
152
+ <section>
153
+ ${titleHtml}
154
+ ${descriptionHtml}
155
+ </section>
156
+ ${footerHtml}
157
+ </div>
158
+ </div>
159
+ </div>
160
+ `;
161
+ const template = document.createElement('template');
162
+ template.innerHTML = html.trim();
163
+ return template.content.firstChild;
164
+ }
165
+
166
+ const initialToaster = document.getElementById('toaster');
167
+ if (initialToaster) initToaster(initialToaster);
168
+
169
+ window.addEventListener('basecoat:toast', (e) => {
170
+ if (!toaster) {
171
+ console.error('Cannot create toast: toaster container not found on page.');
172
+ return;
173
+ }
174
+ const config = e.detail?.config || {};
175
+ const toastElement = createToast(config);
176
+ toaster.appendChild(toastElement);
177
+ });
178
+
179
+ const observer = new MutationObserver((mutations) => {
180
+ mutations.forEach((mutation) => {
181
+ mutation.addedNodes.forEach((node) => {
182
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
183
+
184
+ if (node.matches('#toaster')) {
185
+ initToaster(node);
186
+ }
187
+
188
+ if (toaster && node.matches('.toast:not([data-toast-initialized])')) {
189
+ initToast(node);
190
+ }
191
+ });
192
+ });
193
+ });
194
+
195
+ observer.observe(document.body, { childList: true, subtree: true });
196
+ })();
@@ -0,0 +1 @@
1
+ (()=>{let t;const e=new WeakMap;let n=!1;const o={success:'<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>',error:'<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>',info:'<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>',warning:'<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>'};function i(e){e.dataset.toasterInitialized||(t=e,t.addEventListener("mouseenter",r),t.addEventListener("mouseleave",s),t.addEventListener("click",(t=>{const e=t.target.closest(".toast footer a"),n=t.target.closest(".toast footer button");(e||n)&&d(t.target.closest(".toast"))})),t.querySelectorAll(".toast:not([data-toast-initialized])").forEach(a),t.dataset.toasterInitialized="true")}function a(t){if(t.dataset.toastInitialized)return;const o=parseInt(t.dataset.duration),i=-1!==o?o||("error"===t.dataset.category?5e3:3e3):-1,a={remainingTime:i,timeoutId:null,startTime:null};-1!==i&&(n?a.timeoutId=null:(a.startTime=Date.now(),a.timeoutId=setTimeout((()=>d(t)),i))),e.set(t,a),t.dataset.toastInitialized="true"}function r(){n||(n=!0,t.querySelectorAll('.toast:not([aria-hidden="true"])').forEach((t=>{if(!e.has(t))return;const n=e.get(t);n.timeoutId&&(clearTimeout(n.timeoutId),n.timeoutId=null,n.remainingTime-=Date.now()-n.startTime)})))}function s(){n&&(n=!1,t.querySelectorAll('.toast:not([aria-hidden="true"])').forEach((t=>{if(!e.has(t))return;const n=e.get(t);-1===n.remainingTime||n.timeoutId||(n.remainingTime>0?(n.startTime=Date.now(),n.timeoutId=setTimeout((()=>d(t)),n.remainingTime)):d(t))})))}function d(t){if(!e.has(t))return;const n=e.get(t);clearTimeout(n.timeoutId),e.delete(t),document.activeElement&&document.activeElement.blur(),t.setAttribute("aria-hidden","true"),t.addEventListener("transitionend",(()=>t.remove()),{once:!0})}const c=document.getElementById("toaster");c&&i(c),window.addEventListener("basecoat:toast",(e=>{if(!t)return void console.error("Cannot create toast: toaster container not found on page.");const n=function(t){const{category:e="info",title:n,description:i,action:a,cancel:r,duration:s,icon:d}=t,c=d||e&&o[e]||"",l=n?`<h2>${n}</h2>`:"",u=i?`<p>${i}</p>`:"",h=a?.href?`<a href="${a.href}" class="btn" data-toast-action>${a.label}</a>`:a?.onclick?`<button type="button" class="btn" data-toast-action onclick="${a.onclick}">${a.label}</button>`:"",m=r?`<button type="button" class="btn-outline h-6 text-xs px-2.5 rounded-sm" data-toast-cancel onclick="${r?.onclick}">${r.label}</button>`:"",g=`\n <div\n class="toast"\n role="${"error"===e?"alert":"status"}"\n aria-atomic="true"\n ${e?`data-category="${e}"`:""}\n ${void 0!==s?`data-duration="${s}"`:""}\n >\n <div class="toast-content">\n ${c}\n <section>\n ${l}\n ${u}\n </section>\n ${h||m?`<footer>${h}${m}</footer>`:""}\n </div>\n </div>\n </div>\n `,v=document.createElement("template");return v.innerHTML=g.trim(),v.content.firstChild}(e.detail?.config||{});t.appendChild(n)}));new MutationObserver((e=>{e.forEach((e=>{e.addedNodes.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&(e.matches("#toaster")&&i(e),t&&e.matches(".toast:not([data-toast-initialized])")&&a(e))}))}))})).observe(document.body,{childList:!0,subtree:!0})})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basecoat-css",
3
- "version": "0.1.1",
3
+ "version": "0.2.0-beta.1",
4
4
  "description": "Tailwind CSS for Basecoat components",
5
5
  "author": {
6
6
  "name": "hunvreus",