From 9f551bc48393fcf1981edec1b662f3d93f05c5fe Mon Sep 17 00:00:00 2001 From: Ophir LOJKINE Date: Fri, 31 Jul 2026 21:35:22 +0200 Subject: [PATCH 1/5] Support hash-triggered toasts --- CHANGELOG.md | 1 + .../www/currencies_item_form.sql | 5 +- .../www/currencies_list.sql | 5 +- .../custom form component/form_action.sql | 7 +- examples/multiple-choice-question/admin.sql | 8 +- .../sqlpage/migrations/76_toast.sql | 49 ++++++++++ .../todo application (PostgreSQL)/batch.sql | 12 ++- sqlpage/sqlpage.js | 93 +++++++++++++++++++ sqlpage/templates/toast.handlebars | 18 ++++ tests/end-to-end/official-site.spec.ts | 74 +++++++++++++++ .../component_rendering/toast.sql | 8 ++ 11 files changed, 264 insertions(+), 16 deletions(-) create mode 100644 examples/official-site/sqlpage/migrations/76_toast.sql create mode 100644 sqlpage/templates/toast.handlebars create mode 100644 tests/sql_test_files/component_rendering/toast.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index b7b9126b3..855607ecd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## unreleased + - Added a `toast` component with plain-text or Markdown content, icons, colors, six screen placements, configurable auto-dismiss timing, optional manual dismissal, URL-fragment triggers, and automatic stacking of queued notifications. - `sqlpage.send_mail` now supports rich email bodies. Use `body_html` for a caller-provided HTML alternative, or `body_md` to render Markdown as HTML. Messages retain a plain-text alternative; `body` may be omitted when `body_md` is used, and `body_md` and `body_html` cannot be combined. - Form `options_source` URLs now preserve existing query parameters when adding the dynamic `search` parameter. diff --git a/examples/CRUD - Authentication/www/currencies_item_form.sql b/examples/CRUD - Authentication/www/currencies_item_form.sql index 435332c80..b67b5c03a 100644 --- a/examples/CRUD - Authentication/www/currencies_item_form.sql +++ b/examples/CRUD - Authentication/www/currencies_item_form.sql @@ -279,12 +279,11 @@ SELECT -- DELETE button -- ============================================================================= SELECT - 'alert' AS component, + 'toast' AS component, 'green' AS color, 'check' AS icon, 'Success' AS title, - $info AS description, - True AS dismissible + $info AS description WHERE $info IS NOT NULL; -- ============================================================================= diff --git a/examples/CRUD - Authentication/www/currencies_list.sql b/examples/CRUD - Authentication/www/currencies_list.sql index 12839e115..dbb9fc3a4 100644 --- a/examples/CRUD - Authentication/www/currencies_list.sql +++ b/examples/CRUD - Authentication/www/currencies_list.sql @@ -24,12 +24,11 @@ set _item_form = 'currencies_item_form.sql'; -- ============================================================================= SELECT - 'alert' AS component, + 'toast' AS component, 'green' AS color, 'check' AS icon, 'Success' AS title, - $info AS description, - TRUE AS dismissible + $info AS description WHERE $info IS NOT NULL; -- ============================================================================= diff --git a/examples/custom form component/form_action.sql b/examples/custom form component/form_action.sql index bb71cd3f7..6a286880b 100644 --- a/examples/custom form component/form_action.sql +++ b/examples/custom form component/form_action.sql @@ -15,7 +15,10 @@ from json_table( '$[*]' columns (id int path '$') ) as submitted_items; -select 'alert' as component, 'Group members successfully updated !' as title, 'success' as color; +select 'toast' as component, + 'Group members successfully updated !' as title, + 'green' as color, + 'check' as icon; select 'list' as component, 'Users in this group' as title; @@ -25,4 +28,4 @@ join group_members on users.id = group_members.user_id where group_members.group_id = 1; select 'button' as component; -select 'Go back' as title, 'index.sql' as link; \ No newline at end of file +select 'Go back' as title, 'index.sql' as link; diff --git a/examples/multiple-choice-question/admin.sql b/examples/multiple-choice-question/admin.sql index 37b6b2467..f118a7b5e 100644 --- a/examples/multiple-choice-question/admin.sql +++ b/examples/multiple-choice-question/admin.sql @@ -1,7 +1,9 @@ select 'dynamic' as component, sqlpage.read_file_as_text('website_header.json') as properties; -select 'alert' as component, 'Saved' as title, 'success' as color where $saved is not null; -select 'alert' as component, 'Deleted' as title, 'danger' as color where $deleted is not null; +-- Successful actions are transient feedback, so they use toasts instead of occupying page content. +select 'toast' as component, 'Saved' as title, 'green' as color, 'check' as icon where $saved is not null; +select 'toast' as component, 'Deleted' as title, 'green' as color, 'trash' as icon where $deleted is not null; +-- A failed deletion needs the user's attention and remains an inline alert. select 'alert' as component, 'This option cannot be deleted' as title, 'danger' as color, 'If an option has already been chosen by at least one respondant, then it cannot be deleted' as description where $cannot_delete is not null; select 'dynamic' as component, @@ -33,4 +35,4 @@ select 'dynamic' as component, from dog_lover_profiles; select 'button' as component, 'center' as justify; -select 'Create new question' as title, 'create_question.sql' as link; \ No newline at end of file +select 'Create new question' as title, 'create_question.sql' as link; diff --git a/examples/official-site/sqlpage/migrations/76_toast.sql b/examples/official-site/sqlpage/migrations/76_toast.sql new file mode 100644 index 000000000..3cd48e1fb --- /dev/null +++ b/examples/official-site/sqlpage/migrations/76_toast.sql @@ -0,0 +1,49 @@ +INSERT INTO component(name, icon, description, introduced_in_version) VALUES + ('toast', 'notification', ' +Displays a brief notification above the page. Each top-level `toast` row creates one notification, and consecutive toasts at the same position are queued in a shared stack. + +Ordinary notifications use `role="status"` and `aria-live="polite"`. Colored variants retain a readable contrasting foreground. Automatic dismissal and the optional manual close control are configured independently.', '0.46.0'); + +INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'toast', * FROM (VALUES + ('title', 'Optional notification heading.', 'TEXT', TRUE, TRUE), + ('description', 'Escaped plain-text body. This is used only when `description_md` is not supplied.', 'TEXT', TRUE, TRUE), + ('description_md', 'Rich-text alternative to `description`, rendered as Markdown. When both properties are supplied, `description_md` takes precedence.', 'TEXT', TRUE, TRUE), + ('icon', 'Optional [Tabler icon](https://tabler.io/icons) name.', 'ICON', TRUE, TRUE), + ('color', 'Optional Tabler color. The default is the neutral toast appearance; colored variants use the matching contrasting foreground utility.', 'COLOR', TRUE, TRUE), + ('dismissible', 'Whether to render an accessible manual close button. Defaults to false and is independent of automatic dismissal.', 'BOOLEAN', TRUE, TRUE), + ('duration', 'Automatic dismissal delay in milliseconds. Defaults to 5000. Set to 0 to keep the toast visible until manually dismissed (when `dismissible` is true) or the page is left.', 'INTEGER', TRUE, TRUE), + ('position', 'Screen placement: `top-start`, `top-center`, `top-end`, `bottom-start`, `bottom-center`, or `bottom-end`. Defaults to `top-end`; invalid values safely fall back to that default.', 'TEXT', TRUE, TRUE), + ('trigger', 'Optional URL fragment that opens the toast without reloading the page, with or without the leading `#`. When set, the toast does not open on page load and can be opened repeatedly by a link or button whose target is that fragment. Multiple toasts can share a trigger to open as a stack.', 'TEXT', TRUE, TRUE), + ('id', 'Optional stable HTML ID for the toast.', 'TEXT', TRUE, TRUE), + ('class', 'Optional custom CSS class appended to the toast.', 'TEXT', TRUE, TRUE) +) x; + +INSERT INTO example(component, description, properties) VALUES + ('toast', 'A “Changes saved” confirmation that disappears automatically after the default 5000 milliseconds.', json('[ + {"component":"toast","id":"toast-auto","title":"Changes saved","description":"Your changes have been saved.","icon":"check","color":"green"} + ]')), + ('toast', 'A persistent error notification that disables automatic dismissal and requires the user to activate its close button.', json('[ + {"component":"toast","id":"toast-dismissible","trigger":"persistent-error","title":"Could not save","description":"Review the highlighted fields and try again.","icon":"alert-triangle","color":"red","duration":0,"dismissible":true}, + {"component":"toast","id":"toast-nondismissible","trigger":"persistent-status","title":"Connection unavailable","description":"This persistent notification has no manual close control.","duration":0,"dismissible":false}, + {"component":"button"}, + {"title":"Show dismissible error","link":"#persistent-error","color":"red"}, + {"title":"Show non-dismissible status","link":"#persistent-status"} + ]')), + ('toast', 'A persistent rich Markdown notification. Markdown takes precedence over plain text and renders emphasis and a link as HTML, while plain-text content remains escaped.', json('[ + {"component":"toast","id":"toast-markdown","trigger":"rich-notifications","title":"Release available","description":"This fallback stays escaped","description_md":"Version **2.0** is ready. [Read the notes](https://example.com/releases).","duration":0}, + {"component":"toast","id":"toast-plain","trigger":"rich-notifications","description":"Plain text stays escaped","duration":0}, + {"component":"button"}, + {"title":"Show rich notifications","link":"#rich-notifications"} + ]')), + ('toast', 'Several persistent queued notifications. Toasts with the same position share a container and stack instead of overlapping.', json('[ + {"component":"toast","id":"toast-stack-one","trigger":"queued-notifications","title":"Import started","description":"Preparing records.","duration":0}, + {"component":"toast","id":"toast-stack-two","trigger":"queued-notifications","title":"Import running","description":"Processing records.","duration":0}, + {"component":"toast","id":"toast-short","trigger":"queued-notifications","title":"Temporary update","description":"This message closes shortly.","duration":2000}, + {"component":"button"}, + {"title":"Show queued notifications","link":"#queued-notifications"} + ]')), + ('toast', 'A notification placed at the bottom center of the screen instead of the default top end.', json('[ + {"component":"toast","id":"toast-bottom-center","trigger":"bottom-notification","title":"Download ready","description":"Your export is ready.","position":"bottom-center","duration":0}, + {"component":"button"}, + {"title":"Show bottom notification","link":"#bottom-notification"} + ]')); diff --git a/examples/todo application (PostgreSQL)/batch.sql b/examples/todo application (PostgreSQL)/batch.sql index 28e6d4b27..e213122d9 100644 --- a/examples/todo application (PostgreSQL)/batch.sql +++ b/examples/todo application (PostgreSQL)/batch.sql @@ -45,14 +45,16 @@ with updated as ( -- Return all updated rows for counting and potential further use returning * ) --- Generate an alert component to inform the user about the update result +-- Generate a toast component to inform the user about the update result -- This provides immediate feedback on the operation's outcome -select 'alert' as component, +select 'toast' as component, + 'green' as color, + 'check' as icon, 'Batch update' as title, -- Create a dynamic message with the count of updated todos format('%s todos updated', (select count(*) from updated)) as description --- Only display the alert if at least one todo was updated --- This prevents showing unnecessary alerts for no-op updates +-- Only display the toast if at least one todo was updated +-- This prevents showing unnecessary toasts for no-op updates where exists (select * from updated); -- Create a form component for the batch update interface @@ -95,4 +97,4 @@ select 'new_label' as name, 'New label' as label; -- Create a checkbox for optionally removing existing labels -- This gives users the choice to strip old labels before adding a new one -select 'checkbox' as type, 'Remove previous labels' as label, 'remove_label' as name; \ No newline at end of file +select 'checkbox' as type, 'Remove previous labels' as label, 'remove_label' as name; diff --git a/sqlpage/sqlpage.js b/sqlpage/sqlpage.js index 07ccd3495..df1fa07c9 100644 --- a/sqlpage/sqlpage.js +++ b/sqlpage/sqlpage.js @@ -325,11 +325,104 @@ function add_init_fn(f) { if (document.readyState !== "loading") setTimeout(f, 0); } +const toast_positions = { + "top-start": ["top-0", "start-0"], + "top-center": ["top-0", "start-50", "translate-middle-x"], + "top-end": ["top-0", "end-0"], + "bottom-start": ["bottom-0", "start-0"], + "bottom-center": ["bottom-0", "start-50", "translate-middle-x"], + "bottom-end": ["bottom-0", "end-0"], +}; +const toast_instances = new WeakMap(); + +function normalize_hash(hash) { + return hash?.replace(/^#/, ""); +} + +function open_toasts_for_hash() { + const hash = normalize_hash(window.location.hash); + if (!hash) return; + for (const toast of document.querySelectorAll("[data-toast-trigger]")) { + if (normalize_hash(toast.dataset.toastTrigger) === hash) { + toast_instances.get(toast)?.show(); + } + } +} + +function sqlpage_toast() { + const bootstrap = window.bootstrap || window.tabler?.bootstrap; + if (!bootstrap?.Toast) return; + + for (const toast of document.querySelectorAll('[data-pre-init="toast"]')) { + const requested_position = toast.dataset.position; + const position = toast_positions[requested_position] + ? requested_position + : "top-end"; + toast.dataset.position = position; + + let container = document.querySelector( + `.toast-container[data-sqlpage-toast-position="${position}"]`, + ); + if (!container) { + container = document.createElement("div"); + container.classList.add( + "toast-container", + "position-fixed", + "p-3", + ...toast_positions[position], + ); + container.dataset.sqlpageToastPosition = position; + container.dataset.sqlpageGenerated = "toast-container"; + document.body.appendChild(container); + } + + toast.removeAttribute("data-pre-init"); + container.appendChild(toast); + const requested_duration = Number.parseInt(toast.dataset.duration, 10); + const duration = + Number.isFinite(requested_duration) && requested_duration >= 0 + ? requested_duration + : 5000; + toast.dataset.duration = String(duration); + const instance = new bootstrap.Toast(toast, { + autohide: duration !== 0, + delay: duration > 0 ? duration : 5000, + }); + toast_instances.set(toast, instance); + toast.addEventListener("hidden.bs.toast", () => { + if (toast.dataset.toastTrigger) { + if ( + normalize_hash(window.location.hash) === + normalize_hash(toast.dataset.toastTrigger) + ) { + window.history.replaceState(null, "", "#"); + } + return; + } + toast.remove(); + if ( + container.dataset.sqlpageGenerated === "toast-container" && + !container.querySelector(".toast") + ) { + container.remove(); + } + }); + if (toast.dataset.toastTrigger) { + open_toasts_for_hash(); + } else { + instance.show(); + } + } +} + add_init_fn(sqlpage_table); add_init_fn(sqlpage_map); add_init_fn(sqlpage_card); add_init_fn(sqlpage_form); add_init_fn(load_scripts); +add_init_fn(sqlpage_toast); +add_init_fn(open_toasts_for_hash); +window.addEventListener("hashchange", open_toasts_for_hash); function init_bootstrap_components(event) { const bootstrap = window.bootstrap || window.tabler.bootstrap; diff --git a/sqlpage/templates/toast.handlebars b/sqlpage/templates/toast.handlebars new file mode 100644 index 000000000..a7feeca5c --- /dev/null +++ b/sqlpage/templates/toast.handlebars @@ -0,0 +1,18 @@ + +
+ {{~#if icon~}} + + {{~/if~}} +
+ {{~#if title~}}
{{title}}
{{~/if~}} + {{~#if description_md~}} +
{{{markdown description_md}}}
+ {{~else~}} + {{~#if description~}}
{{description}}
{{~/if~}} + {{~/if~}} +
+ {{~#if dismissible~}} + + {{~/if~}} +
+ diff --git a/tests/end-to-end/official-site.spec.ts b/tests/end-to-end/official-site.spec.ts index c7f8c728e..af3a5e0d6 100644 --- a/tests/end-to-end/official-site.spec.ts +++ b/tests/end-to-end/official-site.spec.ts @@ -41,6 +41,80 @@ test("map", async ({ page }) => { await expect(page.locator(".leaflet-marker-icon").first()).toBeVisible(); }); +test("toast notifications initialize, stack, dismiss, and render safely", async ({ + page, +}) => { + await page.goto(`${BASE}/documentation.sql?component=toast#component`); + + const automatic = page.locator("#toast-auto"); + await expect(automatic).toBeVisible(); + await expect(page.locator(".toast.show")).toHaveCount(1); + + const stackOne = page.locator("#toast-stack-one"); + const stackTwo = page.locator("#toast-stack-two"); + await expect(stackOne).toBeHidden(); + await page.getByRole("link", { name: "Show queued notifications" }).click(); + await expect(stackOne).toBeVisible(); + await expect(stackTwo).toBeVisible(); + const stackContainer = stackOne.locator("xpath=.."); + await expect(stackContainer).toHaveAttribute( + "data-sqlpage-toast-position", + "top-end", + ); + expect( + await stackTwo + .locator("xpath=..") + .getAttribute("data-sqlpage-toast-position"), + ).toBe("top-end"); + const firstBox = await stackOne.boundingBox(); + const secondBox = await stackTwo.boundingBox(); + expect(firstBox).not.toBeNull(); + expect(secondBox).not.toBeNull(); + expect(secondBox?.y).toBeGreaterThanOrEqual( + (firstBox?.y ?? 0) + (firstBox?.height ?? 0), + ); + + const temporary = page.locator("#toast-short"); + await expect(temporary).toBeVisible(); + await expect(temporary).toBeHidden({ timeout: 5000 }); + await expect(stackOne).toBeVisible(); + + const dismissible = page.locator("#toast-dismissible"); + await page.getByRole("link", { name: "Show dismissible error" }).click(); + await expect( + dismissible.getByRole("button", { name: "Close notification" }), + ).toBeVisible(); + await dismissible.getByRole("button", { name: "Close notification" }).click(); + await expect(dismissible).toBeHidden(); + await page.getByRole("link", { name: "Show dismissible error" }).click(); + await expect(dismissible).toBeVisible(); + await dismissible.getByRole("button", { name: "Close notification" }).click(); + await page.getByRole("link", { name: "Show non-dismissible status" }).click(); + await expect( + page.locator("#toast-nondismissible").getByRole("button"), + ).toHaveCount(0); + + await page.getByRole("link", { name: "Show rich notifications" }).click(); + await expect(page.locator("#toast-markdown strong")).toHaveText("2.0"); + await expect(page.locator("#toast-markdown a")).toHaveAttribute( + "href", + "https://example.com/releases", + ); + await expect(page.locator("#toast-plain strong")).toHaveCount(0); + await expect(page.locator("#toast-plain")).toContainText( + "Plain text stays escaped", + ); + + const bottomContainer = page.locator( + '[data-sqlpage-toast-position="bottom-center"]', + ); + await page.getByRole("link", { name: "Show bottom notification" }).click(); + await expect(page.locator("#toast-bottom-center")).toBeVisible(); + await expect(bottomContainer).toHaveClass(/\bbottom-0\b/); + await expect(bottomContainer).toHaveClass(/\bstart-50\b/); + await expect(bottomContainer).toHaveClass(/\btranslate-middle-x\b/); +}); + test("form example", async ({ page }) => { await page.goto(`${BASE}/examples/multistep-form`); // Single selection matching the value or label diff --git a/tests/sql_test_files/component_rendering/toast.sql b/tests/sql_test_files/component_rendering/toast.sql new file mode 100644 index 000000000..fbf9413b5 --- /dev/null +++ b/tests/sql_test_files/component_rendering/toast.sql @@ -0,0 +1,8 @@ +SELECT 'toast' AS component, 'Default toast' AS title, 'It works !' AS description; +SELECT 'toast' AS component, 'Persistent' AS title, 'It works !' AS description, 0 AS duration, 1 AS dismissible; +SELECT 'toast' AS component, 'No close control' AS title, 'It works !' AS description, 0 AS dismissible; +SELECT 'toast' AS component, 'Colored' AS title, 'It works !' AS description, 'check' AS icon, 'green' AS color; +SELECT 'toast' AS component, 'Escaped It works !' AS description; +SELECT 'toast' AS component, '**Markdown** [link](https://example.com) It works !' AS description_md; +SELECT 'toast' AS component, 'Alternate position' AS title, 'It works !' AS description, 'bottom-center' AS position; +SELECT 'toast' AS component, 'Hash-triggered' AS title, 'It works !' AS description, 'notice' AS id, 'notice' AS trigger; From 5743665ed4a180d1855bd519676877a2c38ab0d9 Mon Sep 17 00:00:00 2001 From: Ophir LOJKINE Date: Fri, 31 Jul 2026 22:16:06 +0200 Subject: [PATCH 2/5] Address toast review feedback --- .../sqlpage/migrations/76_toast.sql | 20 ++--- sqlpage/sqlpage.css | 5 ++ sqlpage/sqlpage.js | 17 ++-- sqlpage/templates/toast.handlebars | 6 +- tests/end-to-end/official-site.spec.ts | 89 ++++++++++++++++--- .../component_rendering/toast.sql | 2 +- 6 files changed, 109 insertions(+), 30 deletions(-) diff --git a/examples/official-site/sqlpage/migrations/76_toast.sql b/examples/official-site/sqlpage/migrations/76_toast.sql index 3cd48e1fb..cee518d69 100644 --- a/examples/official-site/sqlpage/migrations/76_toast.sql +++ b/examples/official-site/sqlpage/migrations/76_toast.sql @@ -2,7 +2,7 @@ INSERT INTO component(name, icon, description, introduced_in_version) VALUES ('toast', 'notification', ' Displays a brief notification above the page. Each top-level `toast` row creates one notification, and consecutive toasts at the same position are queued in a shared stack. -Ordinary notifications use `role="status"` and `aria-live="polite"`. Colored variants retain a readable contrasting foreground. Automatic dismissal and the optional manual close control are configured independently.', '0.46.0'); +Ordinary notifications use `role="status"` and `aria-live="polite"`. Colored variants retain a readable contrasting foreground. Automatic dismissal and the manual close control are configured independently.', '0.46.0'); INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'toast', * FROM (VALUES ('title', 'Optional notification heading.', 'TEXT', TRUE, TRUE), @@ -10,7 +10,7 @@ INSERT INTO parameter(component, name, description, type, top_level, optional) S ('description_md', 'Rich-text alternative to `description`, rendered as Markdown. When both properties are supplied, `description_md` takes precedence.', 'TEXT', TRUE, TRUE), ('icon', 'Optional [Tabler icon](https://tabler.io/icons) name.', 'ICON', TRUE, TRUE), ('color', 'Optional Tabler color. The default is the neutral toast appearance; colored variants use the matching contrasting foreground utility.', 'COLOR', TRUE, TRUE), - ('dismissible', 'Whether to render an accessible manual close button. Defaults to false and is independent of automatic dismissal.', 'BOOLEAN', TRUE, TRUE), + ('dismissible', 'Whether to render an accessible manual close button. Defaults to true and is independent of automatic dismissal.', 'BOOLEAN', TRUE, TRUE), ('duration', 'Automatic dismissal delay in milliseconds. Defaults to 5000. Set to 0 to keep the toast visible until manually dismissed (when `dismissible` is true) or the page is left.', 'INTEGER', TRUE, TRUE), ('position', 'Screen placement: `top-start`, `top-center`, `top-end`, `bottom-start`, `bottom-center`, or `bottom-end`. Defaults to `top-end`; invalid values safely fall back to that default.', 'TEXT', TRUE, TRUE), ('trigger', 'Optional URL fragment that opens the toast without reloading the page, with or without the leading `#`. When set, the toast does not open on page load and can be opened repeatedly by a link or button whose target is that fragment. Multiple toasts can share a trigger to open as a stack.', 'TEXT', TRUE, TRUE), @@ -19,28 +19,28 @@ INSERT INTO parameter(component, name, description, type, top_level, optional) S ) x; INSERT INTO example(component, description, properties) VALUES - ('toast', 'A “Changes saved” confirmation that disappears automatically after the default 5000 milliseconds.', json('[ - {"component":"toast","id":"toast-auto","title":"Changes saved","description":"Your changes have been saved.","icon":"check","color":"green"} + ('toast', 'A toast that opens when the page loads and disappears automatically after the default 5000 milliseconds.', json('[ + {"component":"toast","id":"toast-auto","title":"This is a SQLPage toast","description":"This toast will open automatically when the page loads.","icon":"check","color":"green"} ]')), ('toast', 'A persistent error notification that disables automatic dismissal and requires the user to activate its close button.', json('[ - {"component":"toast","id":"toast-dismissible","trigger":"persistent-error","title":"Could not save","description":"Review the highlighted fields and try again.","icon":"alert-triangle","color":"red","duration":0,"dismissible":true}, + {"component":"toast","id":"toast-dismissible","trigger":"persistent-error","title":"Could not save","description":"Review the highlighted fields and try again.","icon":"alert-triangle","color":"black","duration":0,"dismissible":true}, {"component":"toast","id":"toast-nondismissible","trigger":"persistent-status","title":"Connection unavailable","description":"This persistent notification has no manual close control.","duration":0,"dismissible":false}, {"component":"button"}, {"title":"Show dismissible error","link":"#persistent-error","color":"red"}, {"title":"Show non-dismissible status","link":"#persistent-status"} ]')), ('toast', 'A persistent rich Markdown notification. Markdown takes precedence over plain text and renders emphasis and a link as HTML, while plain-text content remains escaped.', json('[ - {"component":"toast","id":"toast-markdown","trigger":"rich-notifications","title":"Release available","description":"This fallback stays escaped","description_md":"Version **2.0** is ready. [Read the notes](https://example.com/releases).","duration":0}, + {"component":"toast","id":"toast-markdown","trigger":"rich-notifications","title":"Release available","description":"This fallback stays escaped","description_md":"Version **2.0** is ready. [Read the notes](https://example.com/releases).","color":"blue","duration":0}, {"component":"toast","id":"toast-plain","trigger":"rich-notifications","description":"Plain text stays escaped","duration":0}, {"component":"button"}, {"title":"Show rich notifications","link":"#rich-notifications"} ]')), ('toast', 'Several persistent queued notifications. Toasts with the same position share a container and stack instead of overlapping.', json('[ - {"component":"toast","id":"toast-stack-one","trigger":"queued-notifications","title":"Import started","description":"Preparing records.","duration":0}, - {"component":"toast","id":"toast-stack-two","trigger":"queued-notifications","title":"Import running","description":"Processing records.","duration":0}, - {"component":"toast","id":"toast-short","trigger":"queued-notifications","title":"Temporary update","description":"This message closes shortly.","duration":2000}, + {"component":"toast","id":"toast-stack-one","trigger":"queued notifications","title":"Import started","description":"Preparing records.","duration":0}, + {"component":"toast","id":"toast-stack-two","trigger":"queued notifications","title":"Import running","description":"Processing records.","duration":0}, + {"component":"toast","id":"toast-short","trigger":"queued notifications","title":"Temporary update","description":"This message closes shortly.","duration":2000}, {"component":"button"}, - {"title":"Show queued notifications","link":"#queued-notifications"} + {"title":"Show queued notifications","link":"#queued notifications"} ]')), ('toast', 'A notification placed at the bottom center of the screen instead of the default top end.', json('[ {"component":"toast","id":"toast-bottom-center","trigger":"bottom-notification","title":"Download ready","description":"Your export is ready.","position":"bottom-center","duration":0}, diff --git a/sqlpage/sqlpage.css b/sqlpage/sqlpage.css index f0aabf05f..f1c32cdd3 100644 --- a/sqlpage/sqlpage.css +++ b/sqlpage/sqlpage.css @@ -191,3 +191,8 @@ See https://github.com/tabler/tabler/issues/2404 .text-black-fg { color: var(--tblr-dark-fg) !important; } + +.toast-colored .toast-description a { + color: inherit; + text-decoration: underline; +} diff --git a/sqlpage/sqlpage.js b/sqlpage/sqlpage.js index df1fa07c9..9759a88f6 100644 --- a/sqlpage/sqlpage.js +++ b/sqlpage/sqlpage.js @@ -336,7 +336,12 @@ const toast_positions = { const toast_instances = new WeakMap(); function normalize_hash(hash) { - return hash?.replace(/^#/, ""); + const normalized = hash?.replace(/^#/, ""); + try { + return decodeURIComponent(normalized); + } catch { + return normalized; + } } function open_toasts_for_hash() { @@ -395,10 +400,12 @@ function sqlpage_toast() { normalize_hash(window.location.hash) === normalize_hash(toast.dataset.toastTrigger) ) { - window.history.replaceState(null, "", "#"); + window.history.replaceState(window.history.state, "", "#"); } return; } + instance.dispose(); + toast_instances.delete(toast); toast.remove(); if ( container.dataset.sqlpageGenerated === "toast-container" && @@ -407,12 +414,11 @@ function sqlpage_toast() { container.remove(); } }); - if (toast.dataset.toastTrigger) { - open_toasts_for_hash(); - } else { + if (!toast.dataset.toastTrigger) { instance.show(); } } + open_toasts_for_hash(); } add_init_fn(sqlpage_table); @@ -421,7 +427,6 @@ add_init_fn(sqlpage_card); add_init_fn(sqlpage_form); add_init_fn(load_scripts); add_init_fn(sqlpage_toast); -add_init_fn(open_toasts_for_hash); window.addEventListener("hashchange", open_toasts_for_hash); function init_bootstrap_components(event) { diff --git a/sqlpage/templates/toast.handlebars b/sqlpage/templates/toast.handlebars index a7feeca5c..14088ada5 100644 --- a/sqlpage/templates/toast.handlebars +++ b/sqlpage/templates/toast.handlebars @@ -1,4 +1,4 @@ - +
{{~#if icon~}} @@ -11,8 +11,8 @@ {{~#if description~}}
{{description}}
{{~/if~}} {{~/if~}}
- {{~#if dismissible~}} - + {{~#if (default dismissible true)~}} + {{~/if~}} diff --git a/tests/end-to-end/official-site.spec.ts b/tests/end-to-end/official-site.spec.ts index af3a5e0d6..76ca59770 100644 --- a/tests/end-to-end/official-site.spec.ts +++ b/tests/end-to-end/official-site.spec.ts @@ -1,6 +1,6 @@ import { expect, type Page, test } from "@playwright/test"; -const BASE = "http://localhost:8080/"; +const BASE = process.env.SQLPAGE_TEST_BASE ?? "http://localhost:8080/"; test("Open documentation", async ({ page }) => { await page.goto(BASE); @@ -48,14 +48,35 @@ test("toast notifications initialize, stack, dismiss, and render safely", async const automatic = page.locator("#toast-auto"); await expect(automatic).toBeVisible(); + await expect( + automatic.getByRole("button", { name: "Close notification" }), + ).toBeVisible(); await expect(page.locator(".toast.show")).toHaveCount(1); + const automaticHandle = await automatic.elementHandle(); const stackOne = page.locator("#toast-stack-one"); const stackTwo = page.locator("#toast-stack-two"); await expect(stackOne).toBeHidden(); - await page.getByRole("link", { name: "Show queued notifications" }).click(); + await page.evaluate(() => { + document.addEventListener("shown.bs.toast", (event) => { + const toast = event.target as HTMLElement; + toast.dataset.shownCount = String( + Number(toast.dataset.shownCount ?? 0) + 1, + ); + }); + }); + await page.getByRole("button", { name: "Show queued notifications" }).click(); await expect(stackOne).toBeVisible(); await expect(stackTwo).toBeVisible(); + await expect(stackOne).toHaveAttribute("data-shown-count", "1"); + await expect(stackTwo).toHaveAttribute("data-shown-count", "1"); + await expect(page.locator("#toast-short")).toHaveAttribute( + "data-shown-count", + "1", + ); + expect(decodeURIComponent(new URL(page.url()).hash)).toBe( + "#queued notifications", + ); const stackContainer = stackOne.locator("xpath=.."); await expect(stackContainer).toHaveAttribute( "data-sqlpage-toast-position", @@ -78,28 +99,76 @@ test("toast notifications initialize, stack, dismiss, and render safely", async await expect(temporary).toBeVisible(); await expect(temporary).toBeHidden({ timeout: 5000 }); await expect(stackOne).toBeVisible(); + await expect(automatic).toBeHidden({ timeout: 7000 }); + expect( + await automaticHandle?.evaluate((element) => { + const testWindow = window as Window & { + tabler: { + bootstrap: { + Toast: { getInstance(element: Element): unknown }; + }; + }; + }; + return testWindow.tabler.bootstrap.Toast.getInstance(element) === null; + }), + ).toBe(true); const dismissible = page.locator("#toast-dismissible"); - await page.getByRole("link", { name: "Show dismissible error" }).click(); - await expect( - dismissible.getByRole("button", { name: "Close notification" }), - ).toBeVisible(); + await page.getByRole("button", { name: "Show dismissible error" }).click(); + const closeButton = dismissible.getByRole("button", { + name: "Close notification", + }); + await expect(closeButton).toBeVisible(); + const closeStyle = await closeButton.evaluate((button) => { + const style = getComputedStyle(button); + const toastStyle = getComputedStyle( + button.closest(".toast") as HTMLElement, + ); + return { + backgroundColor: style.backgroundColor, + color: style.color, + filter: style.filter, + maskImage: style.maskImage, + toastColor: toastStyle.color, + }; + }); + expect(closeStyle.filter).toBe("none"); + expect(closeStyle.maskImage).not.toBe("none"); + expect(closeStyle.color).toBe(closeStyle.toastColor); + expect(closeStyle.backgroundColor).toBe(closeStyle.toastColor); + await page.evaluate(() => { + window.history.replaceState({ toastTest: true }, "", window.location.href); + }); await dismissible.getByRole("button", { name: "Close notification" }).click(); await expect(dismissible).toBeHidden(); - await page.getByRole("link", { name: "Show dismissible error" }).click(); + expect(await page.evaluate(() => window.history.state)).toEqual({ + toastTest: true, + }); + await page.getByRole("button", { name: "Show dismissible error" }).click(); await expect(dismissible).toBeVisible(); await dismissible.getByRole("button", { name: "Close notification" }).click(); - await page.getByRole("link", { name: "Show non-dismissible status" }).click(); + await page + .getByRole("button", { name: "Show non-dismissible status" }) + .click(); await expect( page.locator("#toast-nondismissible").getByRole("button"), ).toHaveCount(0); - await page.getByRole("link", { name: "Show rich notifications" }).click(); + await page.getByRole("button", { name: "Show rich notifications" }).click(); await expect(page.locator("#toast-markdown strong")).toHaveText("2.0"); await expect(page.locator("#toast-markdown a")).toHaveAttribute( "href", "https://example.com/releases", ); + const linkStyle = await page + .locator("#toast-markdown a") + .evaluate((link) => ({ + color: getComputedStyle(link).color, + parentColor: getComputedStyle(link.parentElement as HTMLElement).color, + textDecorationLine: getComputedStyle(link).textDecorationLine, + })); + expect(linkStyle.color).toBe(linkStyle.parentColor); + expect(linkStyle.textDecorationLine).toBe("underline"); await expect(page.locator("#toast-plain strong")).toHaveCount(0); await expect(page.locator("#toast-plain")).toContainText( "Plain text stays escaped", @@ -108,7 +177,7 @@ test("toast notifications initialize, stack, dismiss, and render safely", async const bottomContainer = page.locator( '[data-sqlpage-toast-position="bottom-center"]', ); - await page.getByRole("link", { name: "Show bottom notification" }).click(); + await page.getByRole("button", { name: "Show bottom notification" }).click(); await expect(page.locator("#toast-bottom-center")).toBeVisible(); await expect(bottomContainer).toHaveClass(/\bbottom-0\b/); await expect(bottomContainer).toHaveClass(/\bstart-50\b/); diff --git a/tests/sql_test_files/component_rendering/toast.sql b/tests/sql_test_files/component_rendering/toast.sql index fbf9413b5..644b9de9c 100644 --- a/tests/sql_test_files/component_rendering/toast.sql +++ b/tests/sql_test_files/component_rendering/toast.sql @@ -1,6 +1,6 @@ SELECT 'toast' AS component, 'Default toast' AS title, 'It works !' AS description; SELECT 'toast' AS component, 'Persistent' AS title, 'It works !' AS description, 0 AS duration, 1 AS dismissible; -SELECT 'toast' AS component, 'No close control' AS title, 'It works !' AS description, 0 AS dismissible; +SELECT 'toast' AS component, 'No close control' AS title, 'It works !' AS description, 0 AS duration, 0 AS dismissible; SELECT 'toast' AS component, 'Colored' AS title, 'It works !' AS description, 'check' AS icon, 'green' AS color; SELECT 'toast' AS component, 'Escaped It works !' AS description; SELECT 'toast' AS component, '**Markdown** [link](https://example.com) It works !' AS description_md; From 500e2f39e0fcf20280c36d20f7060f414116feaf Mon Sep 17 00:00:00 2001 From: Ophir LOJKINE Date: Fri, 31 Jul 2026 22:44:40 +0200 Subject: [PATCH 3/5] Render toast positioning in template --- sqlpage/sqlpage.js | 39 +++++++----------------------- sqlpage/templates/toast.handlebars | 10 +++++++- 2 files changed, 18 insertions(+), 31 deletions(-) diff --git a/sqlpage/sqlpage.js b/sqlpage/sqlpage.js index 9759a88f6..6526299e8 100644 --- a/sqlpage/sqlpage.js +++ b/sqlpage/sqlpage.js @@ -325,14 +325,6 @@ function add_init_fn(f) { if (document.readyState !== "loading") setTimeout(f, 0); } -const toast_positions = { - "top-start": ["top-0", "start-0"], - "top-center": ["top-0", "start-50", "translate-middle-x"], - "top-end": ["top-0", "end-0"], - "bottom-start": ["bottom-0", "start-0"], - "bottom-center": ["bottom-0", "start-50", "translate-middle-x"], - "bottom-end": ["bottom-0", "end-0"], -}; const toast_instances = new WeakMap(); function normalize_hash(hash) { @@ -359,30 +351,20 @@ function sqlpage_toast() { if (!bootstrap?.Toast) return; for (const toast of document.querySelectorAll('[data-pre-init="toast"]')) { - const requested_position = toast.dataset.position; - const position = toast_positions[requested_position] - ? requested_position - : "top-end"; - toast.dataset.position = position; - + const source_container = toast.parentElement; + const position = source_container.dataset.sqlpageToastPosition; let container = document.querySelector( - `.toast-container[data-sqlpage-toast-position="${position}"]`, + `.toast-container[data-sqlpage-toast-position="${position}"]:not([data-pre-init])`, ); if (!container) { - container = document.createElement("div"); - container.classList.add( - "toast-container", - "position-fixed", - "p-3", - ...toast_positions[position], - ); - container.dataset.sqlpageToastPosition = position; - container.dataset.sqlpageGenerated = "toast-container"; - document.body.appendChild(container); + container = source_container; + container.removeAttribute("data-pre-init"); + } else { + container.appendChild(toast); + source_container.remove(); } toast.removeAttribute("data-pre-init"); - container.appendChild(toast); const requested_duration = Number.parseInt(toast.dataset.duration, 10); const duration = Number.isFinite(requested_duration) && requested_duration >= 0 @@ -407,10 +389,7 @@ function sqlpage_toast() { instance.dispose(); toast_instances.delete(toast); toast.remove(); - if ( - container.dataset.sqlpageGenerated === "toast-container" && - !container.querySelector(".toast") - ) { + if (!container.querySelector(".toast")) { container.remove(); } }); diff --git a/sqlpage/templates/toast.handlebars b/sqlpage/templates/toast.handlebars index 14088ada5..65fbe068a 100644 --- a/sqlpage/templates/toast.handlebars +++ b/sqlpage/templates/toast.handlebars @@ -1,4 +1,11 @@ - +
+
{{~#if icon~}} @@ -16,3 +23,4 @@ {{~/if~}}
+ From 93c9f0884393c49c6c181610ca0a4ca88a510175 Mon Sep 17 00:00:00 2001 From: Ophir LOJKINE Date: Fri, 31 Jul 2026 23:01:40 +0200 Subject: [PATCH 4/5] Avoid reopening initialized toasts --- sqlpage/sqlpage.js | 12 ++++++++---- tests/end-to-end/official-site.spec.ts | 8 ++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/sqlpage/sqlpage.js b/sqlpage/sqlpage.js index 6526299e8..95187816c 100644 --- a/sqlpage/sqlpage.js +++ b/sqlpage/sqlpage.js @@ -336,10 +336,10 @@ function normalize_hash(hash) { } } -function open_toasts_for_hash() { +function open_toasts_for_hash(toasts) { const hash = normalize_hash(window.location.hash); if (!hash) return; - for (const toast of document.querySelectorAll("[data-toast-trigger]")) { + for (const toast of toasts) { if (normalize_hash(toast.dataset.toastTrigger) === hash) { toast_instances.get(toast)?.show(); } @@ -350,6 +350,7 @@ function sqlpage_toast() { const bootstrap = window.bootstrap || window.tabler?.bootstrap; if (!bootstrap?.Toast) return; + const initialized_toasts = []; for (const toast of document.querySelectorAll('[data-pre-init="toast"]')) { const source_container = toast.parentElement; const position = source_container.dataset.sqlpageToastPosition; @@ -376,6 +377,7 @@ function sqlpage_toast() { delay: duration > 0 ? duration : 5000, }); toast_instances.set(toast, instance); + initialized_toasts.push(toast); toast.addEventListener("hidden.bs.toast", () => { if (toast.dataset.toastTrigger) { if ( @@ -397,7 +399,7 @@ function sqlpage_toast() { instance.show(); } } - open_toasts_for_hash(); + open_toasts_for_hash(initialized_toasts); } add_init_fn(sqlpage_table); @@ -406,7 +408,9 @@ add_init_fn(sqlpage_card); add_init_fn(sqlpage_form); add_init_fn(load_scripts); add_init_fn(sqlpage_toast); -window.addEventListener("hashchange", open_toasts_for_hash); +window.addEventListener("hashchange", () => + open_toasts_for_hash(document.querySelectorAll("[data-toast-trigger]")), +); function init_bootstrap_components(event) { const bootstrap = window.bootstrap || window.tabler.bootstrap; diff --git a/tests/end-to-end/official-site.spec.ts b/tests/end-to-end/official-site.spec.ts index 76ca59770..6ae9dbd33 100644 --- a/tests/end-to-end/official-site.spec.ts +++ b/tests/end-to-end/official-site.spec.ts @@ -74,6 +74,14 @@ test("toast notifications initialize, stack, dismiss, and render safely", async "data-shown-count", "1", ); + await page.evaluate(() => + document.dispatchEvent(new CustomEvent("fragment-loaded")), + ); + await page.waitForTimeout(250); + await expect(page.locator("#toast-short")).toHaveAttribute( + "data-shown-count", + "1", + ); expect(decodeURIComponent(new URL(page.url()).hash)).toBe( "#queued notifications", ); From 276b9680d1b0ced1f1fd90311e547de67be1d5b6 Mon Sep 17 00:00:00 2001 From: Ophir LOJKINE Date: Fri, 31 Jul 2026 23:21:11 +0200 Subject: [PATCH 5/5] Fix white toast foreground color --- .../sqlpage/migrations/76_toast.sql | 2 +- sqlpage/sqlpage.css | 4 ++++ tests/end-to-end/official-site.spec.ts | 23 +++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/examples/official-site/sqlpage/migrations/76_toast.sql b/examples/official-site/sqlpage/migrations/76_toast.sql index cee518d69..38393dcc2 100644 --- a/examples/official-site/sqlpage/migrations/76_toast.sql +++ b/examples/official-site/sqlpage/migrations/76_toast.sql @@ -31,7 +31,7 @@ INSERT INTO example(component, description, properties) VALUES ]')), ('toast', 'A persistent rich Markdown notification. Markdown takes precedence over plain text and renders emphasis and a link as HTML, while plain-text content remains escaped.', json('[ {"component":"toast","id":"toast-markdown","trigger":"rich-notifications","title":"Release available","description":"This fallback stays escaped","description_md":"Version **2.0** is ready. [Read the notes](https://example.com/releases).","color":"blue","duration":0}, - {"component":"toast","id":"toast-plain","trigger":"rich-notifications","description":"Plain text stays escaped","duration":0}, + {"component":"toast","id":"toast-plain","trigger":"rich-notifications","description":"Plain text stays escaped","color":"white","duration":0}, {"component":"button"}, {"title":"Show rich notifications","link":"#rich-notifications"} ]')), diff --git a/sqlpage/sqlpage.css b/sqlpage/sqlpage.css index f1c32cdd3..440275f28 100644 --- a/sqlpage/sqlpage.css +++ b/sqlpage/sqlpage.css @@ -192,6 +192,10 @@ See https://github.com/tabler/tabler/issues/2404 color: var(--tblr-dark-fg) !important; } +.text-white-fg { + color: var(--tblr-light-fg) !important; +} + .toast-colored .toast-description a { color: inherit; text-decoration: underline; diff --git a/tests/end-to-end/official-site.spec.ts b/tests/end-to-end/official-site.spec.ts index 6ae9dbd33..9ca26f369 100644 --- a/tests/end-to-end/official-site.spec.ts +++ b/tests/end-to-end/official-site.spec.ts @@ -181,6 +181,29 @@ test("toast notifications initialize, stack, dismiss, and render safely", async await expect(page.locator("#toast-plain")).toContainText( "Plain text stays escaped", ); + const whiteToast = page.locator("#toast-plain"); + const whiteToastStyle = await whiteToast.evaluate((toast) => { + const style = getComputedStyle(toast); + const closeStyle = getComputedStyle( + toast.querySelector(".btn-close") as HTMLElement, + ); + const rgba = (color: string) => { + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + if (!context) throw new Error("Canvas 2D context is unavailable"); + context.fillStyle = color; + context.fillRect(0, 0, 1, 1); + return Array.from(context.getImageData(0, 0, 1, 1).data); + }; + return { + backgroundColor: rgba(style.backgroundColor), + closeColor: rgba(closeStyle.backgroundColor), + color: rgba(style.color), + }; + }); + expect(whiteToastStyle.backgroundColor).toEqual([255, 255, 255, 255]); + expect(whiteToastStyle.color).toEqual([31, 41, 55, 255]); + expect(whiteToastStyle.closeColor).toEqual(whiteToastStyle.color); const bottomContainer = page.locator( '[data-sqlpage-toast-position="bottom-center"]',