From 3f00182d78d782843ab81eeb24e88fececa33be9 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Thu, 19 Nov 2026 17:27:42 -0500 Subject: [PATCH] Lists and windows: a window with unsaved typing asks before a click outside it, Esc, its X or Cancel closes it; long lists keep their column headings at the top of the screen; active filters get a yellow edge with an x in the search box that clears them all; shift-click ticks a run of rows; and Compact rows in Preferences, with database 4.0.0 --- CHANGELOG.md | 12 ++- admin/database_updates/4.0.0.php | 20 +++++ agent/user/post/profile.php | 4 + agent/user/user_preferences.php | 16 +++- css/itflow_custom.css | 27 ++++++ db.sql | 1 + functions/user.php | 19 ++++- includes/footer.php | 2 + includes/header.php | 2 +- includes/load_user_session.php | 3 +- js/app.js | 134 +++++++++++++++++++++++++++++ js/bulk_actions.js | 23 ++++- js/list_filters.js | 77 +++++++++++++++++ js/sticky_table_head.js | 142 +++++++++++++++++++++++++++++++ 14 files changed, 475 insertions(+), 7 deletions(-) create mode 100644 admin/database_updates/4.0.0.php create mode 100644 js/list_filters.js create mode 100644 js/sticky_table_head.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a3cd78e32..f586e83db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's thirty-two database changes (3.6.6 to 3.9.9) in the same pass. They add four tables for RMM providers and their alerts, a setting for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and eight tables, three columns and two settings for the Knowledge Base, who can read its articles, what its readers think of them and their files, a column on documents for how often each is reviewed, and change nothing that is there. Nothing else is required, but it is a big release, so take a backup before you update. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has thirteen security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's thirty-three database changes (3.6.6 to 4.0.0) in the same pass. They add four tables for RMM providers and their alerts, a setting for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and eight tables, three columns and two settings for the Knowledge Base, who can read its articles, what its readers think of them and their files, a column on documents for how often each is reviewed, a column on agents' settings for compact rows, and change nothing that is there. Nothing else is required, but it is a big release, so take a backup before you update. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has thirteen security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. ### Security @@ -137,6 +137,11 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Invoices: an invoice a recurring invoice's autopay pays now says so - beside its number and under Payment on its page, and under its due date in the invoices list: which card and when (Autopay Dec 1), once it's sent for a draft, Autopay won't charge when the card runs out before the due date or the payment provider is turned off, and Autopay didn't pay it for one still owed after its due date, with why when the card was declined. An invoice that fell due before autopay was set up isn't marked. The client's link to the invoice says autopay will pay it, and when, so they don't pay it twice - as the client portal already did. - Documents: how often a document is reviewed can be set on the document itself, from How often beside its review - every 3 months to every 2 years, never, or as its template says. A document with no template can be reviewed on a schedule too; it shows Review due on Files, its client's overview and the reports like any other. Changing it doesn't count as reviewing it. - Files: drag a file or document onto a folder on the left to move it there - tick several first and drag one of them to move them all. A folder drags onto another to go inside it, with everything in it, or onto Top level to come out. Holding over a closed folder opens it, and the folders in the path above the list take a drop too. Files from your computer dropped on a folder on the left upload into it. Each move goes in the audit log. +- Windows ask before closing when something typed in them hasn't been saved. A click outside the window, Escape, its X and Cancel all ask first; saving doesn't. +- Long lists keep their column names at the top of the screen as you scroll down. Sorting and Select all still work from there. +- A list's filters that are on now stand out with a yellow edge, and an x at the end of the search box clears the search and every filter at once. +- Shift-click a list's tick boxes to tick, or untick, every row between two clicks. +- Compact rows: Your account > Preferences can show lists with tighter rows, so more fit on screen. - Modules: Admin > Settings > Modules has five more switches, to take out of ITFlow what your business doesn't use - Dispatch, which comes with Ticketing; Bookkeeping, Purchasing and Trips, which come with invoicing; and the Calendar. Each part is off while the one it comes with is, and shows faded under it. Switched off, a part leaves the menus, the dashboard, search, the reports and the API, and its pages and windows say it is off. Nothing in it is deleted - switched back on, it is all there. Dispatch, Bookkeeping, Trips and the Calendar start on, as before. - Bookkeeping: switch it off when your books are kept somewhere else. Accounts, Transactions, Transfers, Reconcile and the statement imports go, and nobody picks an account: payments and income go into the default payment account, and expenses come out of the default expense account - both in Admin > Settings > Defaults, or the first account when there's no default. An expense is paid by The business or Paid personally. The dashboard leaves out the account balances, and the Tax Package its Accounts section. - Calendar: switched off, the calendar, its events and the calendar feeds go - a subscribed calendar stops getting them. Tickets are still booked from the ticket and on Dispatch, and booked work still shows on the dashboard. @@ -305,6 +310,11 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Stripe customers Stripe no longer has: new `billingStripeCustomerGone($e)` in `functions/billing_pay.php` - an `InvalidRequestException` with code `resource_missing` on the `customer` parameter ("No such customer: 'cus_...'") - and `billingStripeCustomerForget($client_id, $customer_id)`, which deletes the `client_payment_provider` row only while it still holds that customer, removes the client's saved cards through `paymentCardRemove()` (so the autopay on them goes with each recurring invoice's history saying why), and logs, audits and `appNotify()`s it. Used where the stored customer goes to Stripe: `billingStripeCheckoutIntent()` and the guest pay page's PaymentIntent (`guest/guest_ajax.php`) retry once without a customer; `billingStripeChargeSaved()` returns a message for the client; the portal's `create_stripe_checkout` answers `{reload: true}` with a flash, and `js/portal_stripe.js` reloads into the Add a card step; `stripe_save_card`, Charge Saved Card (`agent/post/payment.php`) and the nightly autopay (`cron/nightly_tasks.php`) record what happened. Any other Stripe error is handled as before. `js/autopay_setup_stripe.js` is gone - nothing has loaded it since `js/portal_stripe.js` took over the portal's card form, and it was the version that never checked the server's answer. - `Clients-Template.csv` is gone from the top folder - nothing linked to it, and the Import window gives each kind's template. - Files: `agent/js/files.js` drags list rows and grid cards (`[data-files-item]`, with `data-id` and `data-folder-id`) and tree folders (`[data-folder-drag]`) onto `[data-folder-drop]` - the tree's rows and the path's crumbs, only for agents with Modify on Support. Files and documents post `bulk_move_files`, which now leaves an item already in the folder alone rather than logging a move. A folder posts the new `move_folder` (`agent/post/folder.php`) with `folder_id` and `parent_folder`, refused for a folder that isn't the client's or one inside the folder moved; the same parent is a no-op. Files from the computer dropped on a tree folder open Upload with that folder (`[data-files-upload]`). +- Windows: `js/app.js` asks before a `.modal` closes with unsaved typing, but only when the close came from the person - a mousedown on the shade, Escape or a `[data-bs-dismiss="modal"]` click in the last 1.5 seconds - so a script's `hide()` after a save never asks. Typing counts in text fields and textareas of `method="post"` forms whose value differs from when they were first focused (not hidden, checkbox, radio, search, file, readonly, `[data-no-guard]` or picker fields), and in TinyMCE editors by `isDirty()`. The question is SweetAlert2 with `target` set to the window, so Bootstrap's focus trap leaves it alone; Discard sets `data-itflow-discard` and hides again. +- Lists: `js/sticky_table_head.js` (every page) shows a fixed copy of the header row of each `.app-main .table-responsive > table` once the real one scrolls off, with column widths copied from the real cells and moved with the table's sideways scroll. CSS sticky can't do it: `.table-responsive` and `.app-main` are scroll boxes. Clicks on the copy (sort links, Select all) are passed to the same element in the real header by position. Tables in windows are left alone. +- Lists: `js/list_filters.js` (every page) reads which filters are applied from the address - the GET form in a card header, its selects, text and search fields, and hidden fields inside its `.collapse` - and gives their fields `.itflow-filter-on`. The x it adds to the search's input group links to the same address without them and `page`. Hidden fields outside the collapse, `show_column`, `view`, `show`, `sort` and `order` are kept. Lists with their own "Clear all" get no x. +- Lists: `js/bulk_actions.js` ticks a shift-clicked range of `.bulk-select` boxes within one form, firing `change` on each box it changes. +- Database 4.0.0 adds `user_settings.user_config_compact_rows` (`compactRowsReady()` in `functions/user.php`), which puts `itflow-compact` on ``. ## [26.11.8] diff --git a/admin/database_updates/4.0.0.php b/admin/database_updates/4.0.0.php new file mode 100644 index 000000000..d965a1cde --- /dev/null +++ b/admin/database_updates/4.0.0.php @@ -0,0 +1,20 @@ + Preferences > Compact rows: lists drawn + * with tighter rows, so more fit on screen (the itflow-compact class on ). Off to start. + * + * Re-runnable: the column is added only where it isn't there yet. + */ + +defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); + + $itflow_compact_column = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'user_settings' AND COLUMN_NAME = 'user_config_compact_rows' LIMIT 1"); + + if ($itflow_compact_column && mysqli_num_rows($itflow_compact_column) === 0) { + mysqli_query($mysqli, "ALTER TABLE `user_settings` ADD `user_config_compact_rows` tinyint(1) NOT NULL DEFAULT 0 AFTER `user_config_theme_dark`"); + } diff --git a/agent/user/post/profile.php b/agent/user/post/profile.php index 1fa73c267..4fd2f3ea7 100644 --- a/agent/user/post/profile.php +++ b/agent/user/post/profile.php @@ -123,6 +123,10 @@ if (isset($_POST['edit_your_user_preferences'])) { mysqli_query($mysqli, "INSERT INTO user_settings SET user_id = $session_user_id, user_config_calendar_first_day = $calendar_first_day, user_config_theme_dark = $dark_mode, user_config_records_per_page = $per_page ON DUPLICATE KEY UPDATE user_config_calendar_first_day = $calendar_first_day, user_config_theme_dark = $dark_mode, user_config_records_per_page = $per_page"); + if (compactRowsReady()) { + $compact_rows = intval($_POST['compact_rows'] ?? 0) === 1 ? 1 : 0; + mysqli_query($mysqli, "UPDATE user_settings SET user_config_compact_rows = $compact_rows WHERE user_id = $session_user_id"); + } calendarAgentColorSave($session_user_id, $_POST); timezoneSave($session_user_id, $_POST); diff --git a/agent/user/user_preferences.php b/agent/user/user_preferences.php index 102f33c97..dbb8dbc6a 100644 --- a/agent/user/user_preferences.php +++ b/agent/user/user_preferences.php @@ -2,8 +2,8 @@ /* * Your account > Preferences - how ITFlow looks and behaves for you: light - * or dark, the day calendars start on, your time zone, your colour on the - * calendar, and how many rows a list shows. + * or dark, compact rows, the day calendars start on, your time zone, your + * colour on the calendar, and how many rows a list shows. */ require_once "includes/inc_all_user.php"; @@ -11,6 +11,7 @@ require_once "includes/inc_all_user.php"; $me = userRow($session_user_id); $calendar_first_day = intval($me['user_config_calendar_first_day']); $per_page = intval($me['user_config_records_per_page']) ?: 10; +$compact_rows = intval($me['user_config_compact_rows'] ?? 0); ?> @@ -37,6 +38,17 @@ $per_page = intval($me['user_config_records_per_page']) ?: 10; + +
+
+ + > + +
+
Tighter rows on lists, so more fit on screen.
+
+ +
diff --git a/css/itflow_custom.css b/css/itflow_custom.css index 95748af9f..47dc0cf52 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -10166,3 +10166,30 @@ a.itflow-portal-request:focus-visible { margin: 0; color: var(--bs-secondary-color); } + +/* A list's column names, kept at the top of the window once the real ones scroll off (js/sticky_table_head.js) */ +.itflow-float-head { + position: fixed; + top: 0; + z-index: 1020; + overflow: hidden; + background-color: var(--bs-body-bg); + box-shadow: 0 .25rem .5rem -.25rem rgba(0, 0, 0, .25); +} +.itflow-float-head > table { + table-layout: fixed; +} + +/* A filter that is on (js/list_filters.js) - the same yellow as the extra-filters button when they are */ +.itflow-select:has(> select.itflow-filter-on) > .itflow-select-control, +input.itflow-filter-on { + border-color: var(--bs-warning); + box-shadow: inset 0 0 0 1px var(--bs-warning); +} + +/* Your account > Preferences > Compact rows */ +.itflow-compact .app-main .table > :not(caption) > * > *, +.itflow-compact .app-main .itflow-asset-table td { + padding-top: .3rem; + padding-bottom: .3rem; +} diff --git a/db.sql b/db.sql index 055da93d1..50d987c2c 100644 --- a/db.sql +++ b/db.sql @@ -4960,6 +4960,7 @@ CREATE TABLE `user_settings` ( `user_config_timezone` varchar(64) DEFAULT NULL, `user_config_signature` text DEFAULT NULL, `user_config_theme_dark` tinyint(1) NOT NULL DEFAULT 0, + `user_config_compact_rows` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; diff --git a/functions/user.php b/functions/user.php index 714eb62bc..8b8fdb684 100644 --- a/functions/user.php +++ b/functions/user.php @@ -56,6 +56,22 @@ function userMfaPill($token, $forced) { return 'No MFA'; } +/** Whether the 4.0.0 update has run - user_settings.user_config_compact_rows. */ +function compactRowsReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '4.0.0', '>='); + } + return $ready; +} + /** One agent by id, with their settings and role - raw, or null. */ function userRow($user_id) { global $mysqli; @@ -65,7 +81,8 @@ function userRow($user_id) { } $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT users.user_id, user_name, user_email, user_auth_method, user_type, user_status, user_token, user_avatar, user_created_at, user_updated_at, user_archived_at, user_role_id, role_name, role_is_admin, role_archived_at, - user_config_force_mfa, user_config_calendar_first_day, user_config_theme_dark, user_config_records_per_page, user_config_signature + user_config_force_mfa, user_config_calendar_first_day, user_config_theme_dark, user_config_records_per_page, user_config_signature" + . (compactRowsReady() ? ', user_config_compact_rows' : '') . " FROM users LEFT JOIN user_settings ON user_settings.user_id = users.user_id LEFT JOIN user_roles ON role_id = user_role_id diff --git a/includes/footer.php b/includes/footer.php index b4c57d27c..da45c38ef 100644 --- a/includes/footer.php +++ b/includes/footer.php @@ -94,6 +94,8 @@ try { + + diff --git a/includes/header.php b/includes/header.php index 99c060966..44c693538 100644 --- a/includes/header.php +++ b/includes/header.php @@ -75,7 +75,7 @@ header("X-Frame-Options: DENY"); moved to this body utility, so the migration dropped it silently. It matters because --bs-card-bg is --bs-body-bg - without it every card is the exact colour of the page and only its border separates the two. */ ?> -
diff --git a/includes/load_user_session.php b/includes/load_user_session.php index 36fdd87cd..7d335a39d 100644 --- a/includes/load_user_session.php +++ b/includes/load_user_session.php @@ -7,7 +7,7 @@ $session_user_id = intval($_SESSION['user_id']); $sql = mysqli_query( $mysqli, "SELECT role_is_admin, role_name, user_archived_at, user_avatar, user_config_force_mfa," . (serviceAccountsReady() ? ' user_service_account,' : '') . " - user_config_records_per_page, user_config_theme_dark, user_email, user_name, user_role_id, + user_config_records_per_page, user_config_theme_dark," . (compactRowsReady() ? ' user_config_compact_rows,' : '') . " user_email, user_name, user_role_id, user_password, user_status, user_token, user_type FROM users LEFT JOIN user_settings ON users.user_id = user_settings.user_id LEFT JOIN user_roles ON user_role_id = role_id @@ -34,6 +34,7 @@ $session_is_admin = isset($row['role_is_admin']) && $row['role_is_admin'] == 1; $session_user_config_force_mfa = intval($row['user_config_force_mfa']); $user_config_records_per_page = max(1, intval($row['user_config_records_per_page'])); $user_config_theme_dark = intval($row['user_config_theme_dark']); +$user_config_compact_rows = intval($row['user_config_compact_rows'] ?? 0); // Check user type is agent aka 1 if ($session_user_type !== 1) { diff --git a/js/app.js b/js/app.js index 9a94e1fd0..b62cf1abb 100644 --- a/js/app.js +++ b/js/app.js @@ -965,6 +965,140 @@ itflowBindOnce('itflowModalStackHidden', 'hidden.bs.modal', '.modal', function ( } }); +/** + * A window with something typed in it asks before it closes on a click outside it, Escape, its X + * or Cancel - what was typed would be gone. Only text typed into a form that saves (method post) + * counts, and only if it differs from what the field held when it was first clicked into, or an + * editor in the window has changes. Saving, and a script closing the window after a save, never + * ask: the question is only put when the person asked for the window to close. + */ +if (!window.itflowWindowGuard) { + window.itflowWindowGuard = true; + + const itflowGuardFields = new WeakMap(); // window -> the fields typed in + const itflowGuardBefore = new WeakMap(); // field -> its value when first clicked into + let itflowCloseAsked = null; // the window the person last asked to close, and when + + const itflowGuardTyped = function (el) { + return !!(el && el.matches && el.matches('input, textarea') + && !el.matches('[type=hidden], [type=checkbox], [type=radio], [type=search], [type=file], [type=button], [type=submit], [type=reset], [readonly], [data-no-guard]') + && el.form && (el.form.getAttribute('method') || '').toLowerCase() === 'post' + && !el.closest('.itflow-select')); + }; + + document.addEventListener('focusin', function (e) { + const el = e.target; + const modal = el.closest ? el.closest('.modal') : null; + if (!modal || !itflowGuardTyped(el) || itflowGuardBefore.has(el)) { + return; + } + itflowGuardBefore.set(el, el.value); + if (!itflowGuardFields.has(modal)) { + itflowGuardFields.set(modal, new Set()); + } + itflowGuardFields.get(modal).add(el); + }); + + const itflowGuardChanged = function (modal) { + const fields = itflowGuardFields.get(modal); + if (fields) { + for (const el of fields) { + if (el.isConnected && modal.contains(el) && el.value !== itflowGuardBefore.get(el)) { + return true; + } + } + } + if (window.tinymce) { + return tinymce.get().some(function (editor) { + const el = editor.getElement(); + return el && modal.contains(el) && el.form && (el.form.getAttribute('method') || '').toLowerCase() === 'post' && editor.isDirty(); + }); + } + return false; + }; + + const itflowAskedToClose = function (modal) { + if (modal) { + itflowCloseAsked = { modal: modal, at: Date.now() }; + } + }; + // A click on the shade around the window, its X or Cancel, or Escape + document.addEventListener('mousedown', function (e) { + if (e.target.classList && e.target.classList.contains('modal')) { + itflowAskedToClose(e.target); + } + }, true); + document.addEventListener('click', function (e) { + const dismiss = e.target.closest ? e.target.closest('[data-bs-dismiss="modal"]') : null; + if (dismiss) { + itflowAskedToClose(dismiss.closest('.modal')); + } + }, true); + document.addEventListener('keydown', function (e) { + if (e.key === 'Escape') { + const open = document.querySelectorAll('.modal.show'); + itflowAskedToClose(open[open.length - 1]); + } + }, true); + + document.addEventListener('hide.bs.modal', function (e) { + const modal = e.target; + if (!modal.classList || !modal.classList.contains('modal')) { + return; + } + if (modal.dataset.itflowDiscard === '1') { + delete modal.dataset.itflowDiscard; + return; + } + const asked = itflowCloseAsked; + itflowCloseAsked = null; + if (!asked || asked.modal !== modal || Date.now() - asked.at > 1500) { + return; + } + // Escape on the question itself closes the question, not the window under it + if (typeof Swal !== 'undefined' && Swal.isVisible()) { + e.preventDefault(); + return; + } + if (!itflowGuardChanged(modal)) { + return; + } + e.preventDefault(); + const discard = function () { + modal.dataset.itflowDiscard = '1'; + bootstrap.Modal.getOrCreateInstance(modal).hide(); + }; + if (typeof Swal === 'undefined') { + if (window.confirm('Discard what you typed in this window?')) { + discard(); + } + return; + } + Swal.fire({ + theme: document.documentElement.getAttribute('data-bs-theme') === 'dark' ? 'dark' : 'light', + // Inside the window, so its focus trap leaves the question's buttons alone + target: modal, + title: 'Discard your changes?', + text: "What you typed in this window hasn't been saved.", + icon: 'warning', + showCancelButton: true, + confirmButtonText: 'Discard', + cancelButtonText: 'Keep editing', + reverseButtons: true, + focusCancel: true, + buttonsStyling: false, + customClass: { + confirmButton: 'btn btn-danger mx-1', + cancelButton: 'btn btn-secondary mx-1' + } + }).then(function (result) { + if (result.isConfirmed) { + discard(); + } + }); + }); +} + /** * A required field left empty on a tab that isn't showing - the Ticket tab of * a template while Sets up is open, a fill-in on Details while Tasks is - diff --git a/js/bulk_actions.js b/js/bulk_actions.js index 7b3449506..7616e0d53 100644 --- a/js/bulk_actions.js +++ b/js/bulk_actions.js @@ -47,10 +47,31 @@ document.addEventListener('DOMContentLoaded', function () { }); } - // Per-row checkbox handling + // Per-row checkbox handling. Shift-click ticks (or unticks) every box between this one and the + // last one clicked, as the clicked one now is. + let lastClicked = null; document.addEventListener('click', function (e) { const cb = e.target.closest('input[type="checkbox"].bulk-select'); if (!cb) return; + if (e.shiftKey && lastClicked && lastClicked !== cb && lastClicked.isConnected && lastClicked.form === cb.form) { + const boxes = getBulkCheckboxes().filter(box => box.form === cb.form); + const from = boxes.indexOf(lastClicked); + const to = boxes.indexOf(cb); + if (from !== -1 && to !== -1) { + boxes.slice(Math.min(from, to), Math.max(from, to) + 1).forEach(box => { + if (box.checked !== cb.checked) { + box.checked = cb.checked; + box.dispatchEvent(new Event('change', { bubbles: true })); + } + }); + // Shift-click also selects the text between the two clicks + const selection = window.getSelection ? window.getSelection() : null; + if (selection) { + selection.removeAllRanges(); + } + } + } + lastClicked = cb; updateSelectedCount(); }); diff --git a/js/list_filters.js b/js/list_filters.js new file mode 100644 index 000000000..985f77b6e --- /dev/null +++ b/js/list_filters.js @@ -0,0 +1,77 @@ +/* + * A list's filters that are on stand out - their field gets a coloured edge - and an x at the end + * of the search box takes them all off at once. What is on is read from the page's address, so a + * filter only counts once it has been applied, against the filter form above the list (a GET form + * in a card header): its dropdowns, its search box and anything in its collapsed extra filters. + * Hidden fields outside those - the client the list is for, the view tab - are where you are, not + * filters, and stay, as do the columns, view and sort picked. A list that has its own "Clear all" keeps it and gets no x. + */ +(function () { + 'use strict'; + + function start() { + var params = new URLSearchParams(window.location.search); + + document.querySelectorAll('.app-main .card-header form').forEach(function (form) { + if ((form.getAttribute('method') || 'get').toLowerCase() !== 'get') { + return; + } + var on = []; + Array.prototype.forEach.call(form.elements, function (el) { + // How the list is shown (its columns, view, sort) isn't a filter + if (!el.name || el.disabled || /^(show_column|view|show|sort|order)\b/.test(el.name)) { + return; + } + var isFilter = el.tagName === 'SELECT' + || (el.tagName === 'INPUT' && ['search', 'text'].indexOf(el.type) !== -1) + || (el.type === 'hidden' && el.closest('.collapse')); + if (!isFilter) { + return; + } + var applied = params.getAll(el.name).filter(function (value) { + return value !== '' && !(el.name === 'canned_date' && ['custom', 'alltime'].indexOf(value) !== -1); + }); + if (!applied.length) { + return; + } + if (on.indexOf(el.name) === -1) { + on.push(el.name); + } + if (el.type !== 'hidden') { + el.classList.add('itflow-filter-on'); + } + }); + if (!on.length) { + return; + } + + var header = form.closest('.card-header') || form; + var hasOwnClear = Array.prototype.some.call(header.querySelectorAll('a'), function (a) { + return /^\s*clear all\s*$/i.test(a.textContent); + }); + var search = form.querySelector('input[name="q"]'); + var group = search && search.closest('.input-group'); + if (hasOwnClear || !group) { + return; + } + var keep = new URLSearchParams(window.location.search); + on.concat(['page']).forEach(function (name) { + keep.delete(name); + }); + var onlySearch = on.length === 1 && on[0] === 'q'; + var clear = document.createElement('a'); + clear.className = 'btn btn-outline-danger'; + clear.href = window.location.pathname + (keep.toString() ? '?' + keep.toString() : ''); + clear.title = onlySearch ? 'Clear the search' : 'Clear search and filters'; + clear.setAttribute('aria-label', clear.title); + clear.innerHTML = ''; + group.appendChild(clear); + }); + } + + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', start); + } else { + start(); + } +})(); diff --git a/js/sticky_table_head.js b/js/sticky_table_head.js new file mode 100644 index 000000000..78c1a9fda --- /dev/null +++ b/js/sticky_table_head.js @@ -0,0 +1,142 @@ +/* + * A long list keeps its column names in view. The table sits in .table-responsive, which scrolls + * sideways - and .app-main is a scroll box too - so a CSS sticky header would stick to those, not + * the window. Instead a copy of the header row is shown fixed at the top of the window once the + * real one has scrolled off, each column as wide as the real one and moved sideways with the + * table. Clicks on it (sort links, the tick-all box) go to the real header. Windows are left out. + */ +(function () { + 'use strict'; + + var heads = []; + var queued = false; + + function pathTo(node, root) { + var path = []; + while (node && node !== root) { + path.unshift(Array.prototype.indexOf.call(node.parentNode.children, node)); + node = node.parentNode; + } + return node === root ? path : null; + } + + function nodeAt(root, path) { + var node = root; + for (var i = 0; node && i < path.length; i++) { + node = node.children[path[i]]; + } + return node; + } + + function setUp(wrap) { + var table = wrap.querySelector(':scope > table'); + var thead = table && table.tHead; + if (!thead || !thead.rows.length || wrap.closest('.modal') || wrap.dataset.itflowFloatHead) { + return; + } + wrap.dataset.itflowFloatHead = '1'; + + var box = document.createElement('div'); + box.className = 'itflow-float-head d-print-none'; + box.hidden = true; + var copy = document.createElement('table'); + copy.className = table.className + ' mb-0'; + copy.setAttribute('aria-hidden', 'true'); + var headCopy = thead.cloneNode(true); + headCopy.classList.remove('d-none'); + headCopy.querySelectorAll('[id]').forEach(function (node) { + node.removeAttribute('id'); + }); + headCopy.querySelectorAll('[onclick]').forEach(function (node) { + node.removeAttribute('onclick'); + }); + headCopy.querySelectorAll('a, button, input').forEach(function (node) { + node.tabIndex = -1; + }); + copy.appendChild(headCopy); + box.appendChild(copy); + document.body.appendChild(box); + + var head = { wrap: wrap, table: table, thead: thead, box: box, copy: copy }; + heads.push(head); + + box.addEventListener('click', function (e) { + var target = e.target.closest('a, button, input, label'); + if (!target || !headCopy.contains(target)) { + return; + } + var path = pathTo(target, headCopy); + var real = path && nodeAt(thead, path); + if (!real) { + return; + } + e.preventDefault(); + real.click(); + setTimeout(function () { + place(head); + }); + }); + wrap.addEventListener('scroll', queue, { passive: true }); + } + + function place(head) { + var body = head.table.tBodies[0]; + var rect = head.wrap.getBoundingClientRect(); + var headHeight = head.thead.getBoundingClientRect().height; + var show = !head.thead.classList.contains('d-none') && body && body.rows.length > 0 + && rect.top < 0 && rect.bottom > headHeight * 2 && head.wrap.offsetParent !== null; + head.box.hidden = !show; + if (!show) { + return; + } + head.box.style.left = rect.left + 'px'; + head.box.style.width = head.wrap.clientWidth + 'px'; + head.copy.style.width = head.table.getBoundingClientRect().width + 'px'; + head.copy.style.transform = 'translateX(' + (-head.wrap.scrollLeft) + 'px)'; + var from = head.thead.rows[0].cells; + var to = head.copy.tHead.rows[0].cells; + for (var i = 0; i < from.length && i < to.length; i++) { + var width = from[i].getBoundingClientRect().width + 'px'; + to[i].style.width = width; + to[i].style.minWidth = width; + to[i].style.maxWidth = width; + } + // The tick-all box shows what the real one does + var realBoxes = head.thead.querySelectorAll('input[type=checkbox]'); + var copyBoxes = head.copy.tHead.querySelectorAll('input[type=checkbox]'); + for (var j = 0; j < realBoxes.length && j < copyBoxes.length; j++) { + copyBoxes[j].checked = realBoxes[j].checked; + copyBoxes[j].indeterminate = realBoxes[j].indeterminate; + } + } + + function placeAll() { + queued = false; + heads.forEach(place); + } + + function queue() { + if (!queued) { + queued = true; + window.requestAnimationFrame(placeAll); + } + } + + function start() { + document.querySelectorAll('.app-main .table-responsive').forEach(setUp); + window.addEventListener('scroll', queue, { passive: true }); + var main = document.querySelector('.app-main'); + if (main) { + main.addEventListener('scroll', queue, { passive: true }); + } + window.addEventListener('resize', queue); + document.addEventListener('change', queue); + queue(); + } + + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', start); + } else { + start(); + } +})();