Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 2 additions & 3 deletions examples/CRUD - Authentication/www/currencies_item_form.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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;

-- =============================================================================
Expand Down
5 changes: 2 additions & 3 deletions examples/CRUD - Authentication/www/currencies_list.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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;

-- =============================================================================
Expand Down
7 changes: 5 additions & 2 deletions examples/custom form component/form_action.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
select 'Go back' as title, 'index.sql' as link;
8 changes: 5 additions & 3 deletions examples/multiple-choice-question/admin.sql
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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;
select 'Create new question' as title, 'create_question.sql' as link;
49 changes: 49 additions & 0 deletions examples/official-site/sqlpage/migrations/76_toast.sql
Original file line number Diff line number Diff line change
@@ -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 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 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),
('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 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":"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":"<strong>This fallback stays escaped</strong>","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":"<strong>Plain text stays escaped</strong>","color":"white","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"}
]'));
12 changes: 7 additions & 5 deletions examples/todo application (PostgreSQL)/batch.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
select 'checkbox' as type, 'Remove previous labels' as label, 'remove_label' as name;
9 changes: 9 additions & 0 deletions sqlpage/sqlpage.css
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,12 @@ See https://github.com/tabler/tabler/issues/2404
.text-black-fg {
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;
}
81 changes: 81 additions & 0 deletions sqlpage/sqlpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -325,11 +325,92 @@ function add_init_fn(f) {
if (document.readyState !== "loading") setTimeout(f, 0);
}

const toast_instances = new WeakMap();

function normalize_hash(hash) {
const normalized = hash?.replace(/^#/, "");
try {
return decodeURIComponent(normalized);
} catch {
return normalized;
}
}

function open_toasts_for_hash(toasts) {
const hash = normalize_hash(window.location.hash);
if (!hash) return;
for (const toast of toasts) {
if (normalize_hash(toast.dataset.toastTrigger) === hash) {
toast_instances.get(toast)?.show();
Comment thread
lovasoa marked this conversation as resolved.
}
}
}

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;
let container = document.querySelector(
`.toast-container[data-sqlpage-toast-position="${position}"]:not([data-pre-init])`,
);
if (!container) {
container = source_container;
container.removeAttribute("data-pre-init");
} else {
container.appendChild(toast);
source_container.remove();
}

toast.removeAttribute("data-pre-init");
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);
initialized_toasts.push(toast);
toast.addEventListener("hidden.bs.toast", () => {
if (toast.dataset.toastTrigger) {
if (
normalize_hash(window.location.hash) ===
normalize_hash(toast.dataset.toastTrigger)
) {
window.history.replaceState(window.history.state, "", "#");
}
return;
}
instance.dispose();
toast_instances.delete(toast);
toast.remove();
Comment thread
lovasoa marked this conversation as resolved.
if (!container.querySelector(".toast")) {
container.remove();
}
});
if (!toast.dataset.toastTrigger) {
instance.show();
}
}
open_toasts_for_hash(initialized_toasts);
}

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);
window.addEventListener("hashchange", () =>
open_toasts_for_hash(document.querySelectorAll("[data-toast-trigger]")),
);

function init_bootstrap_components(event) {
const bootstrap = window.bootstrap || window.tabler.bootstrap;
Expand Down
26 changes: 26 additions & 0 deletions sqlpage/templates/toast.handlebars
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<div data-pre-init="toast-container"
{{~#if (eq position 'top-start')}} class="toast-container position-fixed p-3 top-0 start-0" data-sqlpage-toast-position="top-start"
{{~else}}{{#if (eq position 'top-center')}} class="toast-container position-fixed p-3 top-0 start-50 translate-middle-x" data-sqlpage-toast-position="top-center"
{{~else}}{{#if (eq position 'bottom-start')}} class="toast-container position-fixed p-3 bottom-0 start-0" data-sqlpage-toast-position="bottom-start"
{{~else}}{{#if (eq position 'bottom-center')}} class="toast-container position-fixed p-3 bottom-0 start-50 translate-middle-x" data-sqlpage-toast-position="bottom-center"
{{~else}}{{#if (eq position 'bottom-end')}} class="toast-container position-fixed p-3 bottom-0 end-0" data-sqlpage-toast-position="bottom-end"
{{~else}} class="toast-container position-fixed p-3 top-0 end-0" data-sqlpage-toast-position="top-end"{{/if}}{{/if}}{{/if}}{{/if}}{{/if}}>
<div{{#if id}} id="{{id}}"{{/if}} class="toast{{#if color}} toast-colored bg-{{color}} text-{{color}}-fg{{/if}}{{#if class}} {{class}}{{/if}}" role="status" aria-live="polite" aria-atomic="true" data-pre-init="toast" data-duration="{{default duration 5000}}"{{#if trigger}} data-toast-trigger="{{trigger}}"{{/if}}>
Comment thread
lovasoa marked this conversation as resolved.
<div class="toast-body d-flex align-items-start gap-2">
{{~#if icon~}}
<span class="flex-shrink-0" aria-hidden="true">{{~icon_img icon~}}</span>
{{~/if~}}
<div class="flex-fill overflow-auto">
{{~#if title~}}<div class="fw-bold mb-1">{{title}}</div>{{~/if~}}
{{~#if description_md~}}
<div class="toast-description toast-description-markdown">{{{markdown description_md}}}</div>
Comment thread
lovasoa marked this conversation as resolved.
{{~else~}}
{{~#if description~}}<div class="toast-description">{{description}}</div>{{~/if~}}
{{~/if~}}
</div>
{{~#if (default dismissible true)~}}
<button type="button" class="btn-close flex-shrink-0" data-bs-dismiss="toast" aria-label="Close notification"></button>
{{~/if~}}
</div>
</div>
</div>
Loading