Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Craft.cp.announce() and implement for various loading states #15569

Merged
merged 14 commits into from
Aug 29, 2024
Merged
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-WIP.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
- Deprecated `craft\db\mysql\Schema::quoteDatabaseName()`.
- Deprecated `craft\db\pgqsl\Schema::quoteDatabaseName()`.
- Deprecated `craft\helpers\ElementHelper::rootElement()`. `craft\base\ElementInterface::getRootOwner()` should be used instead.
- Added `Craft.cp.announce()`, simplifying live region announcements for screen readers. ([#15569](https://github.com/craftcms/cms/pull/15569))
- Element action menu items returned by `craft\base\Element::safeActionMenuItems()` and `destructiveActionMenuItems()` can now include a `showInChips` key to explicitly opt into/out of being shown within element chips and cards.
- Control panel CSS selectors that take orientation into account now use logical properties. ([#15522](https://github.com/craftcms/cms/pull/15522))

Expand Down
3 changes: 2 additions & 1 deletion src/templates/_includes/forms/button.twig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
{% set failureMessage = failureMessage ?? false %}
{% set retryMessage = retryMessage ?? false %}
{% set successMessage = successMessage ?? false %}
{% set enableLiveRegion = busyMessage or failureMessage or retryMessage or successMessage %}
{% set label = label ?? null %}
{% set labelHtml = labelHtml ?? null %}
{% set attributes = {
Expand All @@ -22,7 +23,7 @@
}|merge(attributes ?? {}) -%}

{% apply spaceless %}
{% if spinner %}
{% if spinner and enableLiveRegion %}
<div role="status" class="visually-hidden"></div>
{% endif %}
{% tag 'button' with attributes %}
Expand Down
2 changes: 1 addition & 1 deletion src/templates/_special/login.twig
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
</form>
{% endif %}

<div class="login-errors hidden" role="status"></div>
<div class="login-errors hidden"></div>
</div>

<div class="flex alternative-login-methods hidden">
Expand Down
1 change: 1 addition & 0 deletions src/translations/en/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -2114,6 +2114,7 @@
'{name} should be at least {value}.' => '{name} should be at least {value}.',
'{name} sorted by {attribute}, {direction}' => '{name} sorted by {attribute}, {direction}',
'{nestedType} can only be created after the {ownerType} has been saved.' => '{nestedType} can only be created after the {ownerType} has been saved.',
'{num, number} {num, plural, =1{result} other{results}}' => '{num, number} {num, plural, =1{result} other{results}}',
'{num, number} {num, plural, =1{Available Update} other{Available Updates}}' => '{num, number} {num, plural, =1{Available Update} other{Available Updates}}',
'{num, number} {num, plural, =1{column} other{columns}}' => '{num, number} {num, plural, =1{column} other{columns}}',
'{num, number} {num, plural, =1{day} other{days}}' => '{num, number} {num, plural, =1{day} other{days}}',
Expand Down
2 changes: 1 addition & 1 deletion src/web/assets/authmethodsetup/dist/auth.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/web/assets/authmethodsetup/dist/auth.js.map

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions src/web/assets/authmethodsetup/src/AuthMethodSetup.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Craft.AuthMethodSetup = Garnish.Base.extend(
}

button.classList.add('loading');
Craft.cp.announce(Craft.t('app', 'Loading'));

Craft.elevatedSessionManager.requireElevatedSession(
() => {
Expand Down
4 changes: 4 additions & 0 deletions src/web/assets/authmethodsetup/src/RecoveryCodesSetup.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Craft.RecoveryCodesSetup = Garnish.Base.extend({

button.on('activate', () => {
button.addClass('loading');
Craft.cp.announce(Craft.t('app', 'Loading'));

Craft.sendActionRequest('post', 'auth/generate-recovery-codes')
.then(({data}) => {
Expand Down Expand Up @@ -39,6 +40,7 @@ Craft.RecoveryCodesSetup = Garnish.Base.extend({

this.addListener($downloadBtn, 'activate', () => {
$downloadBtn.addClass('loading');
Craft.cp.announce(Craft.t('app', 'Loading'));

const data = Craft.filterObject({
[Craft.csrfTokenName]: Craft.csrfTokenValue,
Expand All @@ -59,11 +61,13 @@ Craft.RecoveryCodesSetup = Garnish.Base.extend({
})
.finally(() => {
$downloadBtn.removeClass('loading');
Craft.cp.announce(Craft.t('app', 'Loading complete'));
});
});
})
.finally(() => {
button.removeClass('loading');
Craft.cp.announce(Craft.t('app', 'Loading complete'));
});
});
},
Expand Down
1 change: 1 addition & 0 deletions src/web/assets/cp/CpAsset.php
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,7 @@ private function _registerTranslations(View $view): void
'{name} active, more info',
'{name} folder',
'{name} sorted by {attribute}, {direction}',
'{num, number} {num, plural, =1{result} other{results}}',
'{num, number} {num, plural, =1{Available Update} other{Available Updates}}',
'{num, number} {num, plural, =1{degree} other{degrees}}',
'{num, number} {num, plural, =1{notification} other{notifications}}',
Expand Down
2 changes: 1 addition & 1 deletion src/web/assets/cp/dist/cp.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/web/assets/cp/dist/cp.js.map

Large diffs are not rendered by default.

75 changes: 65 additions & 10 deletions src/web/assets/cp/src/js/CP.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ Craft.CP = Garnish.Base.extend(
{
elementThumbLoader: null,
authManager: null,
announcerTimeout: null,
modalLayers: [],

$nav: null,
$navToggle: null,
$globalLiveRegion: null,
$activeLiveRegion: null,
$globalSidebar: null,
$globalContainer: null,
$mainContainer: null,
Expand Down Expand Up @@ -79,6 +82,7 @@ Craft.CP = Garnish.Base.extend(
this.$nav = $('#nav');
this.$navToggle = $('#primary-nav-toggle');
this.$globalLiveRegion = $('#global-live-region');
this.$activeLiveRegion = this.$globalLiveRegion;
this.$globalSidebar = $('#global-sidebar');
this.$globalContainer = $('#global-container');
this.$mainContainer = $('#main-container');
Expand Down Expand Up @@ -157,6 +161,15 @@ Craft.CP = Garnish.Base.extend(
this.addListener(this.$navToggle, 'click', 'toggleNav');
this.addListener(this.$sidebarToggle, 'click', 'toggleSidebar');

// Layers
Garnish.uiLayerManager.on('addLayer', () => {
this.handleLayerUpdates();
});

Garnish.uiLayerManager.on('removeLayer', () => {
this.handleLayerUpdates();
});

// Does this page have a primary form?
if (!this.$primaryForm.length) {
this.$primaryForm = $('form[data-saveshortcut]:first');
Expand Down Expand Up @@ -784,6 +797,46 @@ Craft.CP = Garnish.Base.extend(
this.handleBreadcrumbVisibility();
},

handleLayerUpdates: function () {
// Exit if the number of modal layers remains the same
if (Garnish.uiLayerManager.modalLayers.length === this.modalLayers.length)
return;

// Store modal layers
this.modalLayers = Garnish.uiLayerManager.modalLayers;

if (this.announcerTimeout) {
clearTimeout(this.announcerTimeout);
}

if (Garnish.uiLayerManager.modalLayers.length === 0) {
this.$activeLiveRegion = this.$globalLiveRegion;
} else {
const $modal = Garnish.uiLayerManager.highestModalLayer.$container;
let modalObj;

if ($modal.hasClass('modal')) {
modalObj = $modal.data('modal');
} else if ($modal.hasClass('slideout-container')) {
modalObj = $modal.find('.slideout').data('slideout');
}

if (!modalObj) {
console.warn('There is no modal object');
}

if (!modalObj.$liveRegion) {
console.warn('There is no live region in the active modal layer.');
this.$activeLiveRegion = null;
} else {
this.$activeLiveRegion = modalObj.$liveRegion;
}
}

// Empty in case it was already populated and not cleared
this.$activeLiveRegion.empty();
},

updateResponsiveTables: function () {
for (
this.updateResponsiveTables._i = 0;
Expand Down Expand Up @@ -924,23 +977,25 @@ Craft.CP = Garnish.Base.extend(
},

/**
* Updates the global live region with a screen reader announcement
* Updates the active live region with a screen reader announcement
*
* @param {string} message
*/
announce: function (message) {
if (!message) return;

this.$globalLiveRegion.empty().text(message);
if (!message || !this.$activeLiveRegion) {
console.warn('There was an error announcing this message.');
return;
}

// Clear message after interval
setTimeout(() => {
const currentMessage = this.$globalLiveRegion.text();
if (this.announcerTimeout) {
clearTimeout(this.announcerTimeout);
}

// Check that this is the same message and hasn't been updated since
if (message !== currentMessage) return;
this.$activeLiveRegion.empty().text(message);

this.$globalLiveRegion.empty();
// Clear message after interval
this.announcerTimeout = setTimeout(() => {
this.$activeLiveRegion.empty();
}, 5000);
},

Expand Down
6 changes: 3 additions & 3 deletions src/web/assets/cp/src/js/EntryMover.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ Craft.EntryMover = Garnish.Base.extend({
}

this.$selectBtn.addClass('loading');
this.modal.updateLiveRegion(Craft.t('app', 'Loading'));
Craft.cp.announce(Craft.t('app', 'Loading'));

let data = {
sectionId: this.sectionSelect.$selectedItems.data('id'),
Expand All @@ -149,15 +149,15 @@ Craft.EntryMover = Garnish.Base.extend({
})
.then((response) => {
Craft.cp.displaySuccess(response.data.message);
this.modal.updateLiveRegion(response.data.message);
Craft.cp.announce(response.data.message);

this.elementIndex.updateElements();
this.elementIndex.$elements.attr('tabindex', '-1').focus();
this.modal.hide();
})
.catch((e) => {
Craft.cp.displayError(e?.response?.data?.message);
this.modal.updateLiveRegion(e?.response?.data?.message);
Craft.cp.announce(e?.response?.data?.message);
})
.finally(() => {
this.$selectBtn.removeClass('loading');
Expand Down
19 changes: 15 additions & 4 deletions src/web/assets/cp/src/js/IconPicker.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ Craft.IconPicker = Craft.BaseInputGenerator.extend(
$iconList: null,
defaultListHtml: null,

get listLength() {
return this.$iconList.find('li').length;
},

init(container, settings) {
this.$container = $(container);
this.setSettings(settings, Craft.IconPicker.defaults);
Expand Down Expand Up @@ -77,10 +81,7 @@ Craft.IconPicker = Craft.BaseInputGenerator.extend(
const $spinner = $('<div class="spinner spinner-absolute"/>').appendTo(
this.$iconListContainer
);
$('<span class="visually-hidden"/>')
.text(Craft.t('app', 'Loading'))
.appendTo($spinner);

Craft.cp.announce(Craft.t('app', 'Loading'));
const formObserver = new Craft.FormObserver($searchContainer, () => {
this.updateIcons();
});
Expand Down Expand Up @@ -119,6 +120,15 @@ Craft.IconPicker = Craft.BaseInputGenerator.extend(
async updateIcons() {
const listHtml = await this.loadIcons();
this.$iconList.html(listHtml);
const message = `${Craft.t('app', 'Loading complete')} - ${Craft.t(
'app',
'{num, number} {num, plural, =1{result} other{results}}',
{
num: this.listLength,
}
)}`;

Craft.cp.announce(message);
},

async loadIcons() {
Expand All @@ -132,6 +142,7 @@ Craft.IconPicker = Craft.BaseInputGenerator.extend(
}

this.$iconListContainer.addClass('loading');
Craft.cp.announce(Craft.t('app', 'Loading'));
this.cancelToken = axios.CancelToken.source();

try {
Expand Down
12 changes: 10 additions & 2 deletions src/web/assets/cp/src/js/LoginForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Craft.LoginForm = Garnish.Base.extend(
$errors: null,
$altMethodContainer: null,
$passkeyBtn: null,
passkeyBtn: null,

modal: null,
resetPasswordForm: null,
Expand Down Expand Up @@ -47,6 +48,7 @@ Craft.LoginForm = Garnish.Base.extend(
this.submitBtn = new Garnish.MultiFunctionBtn(this.$submitBtn, {
changeButtonText: true,
});
this.passkeyBtn = new Garnish.MultiFunctionBtn(this.$passkeyBtn);

this.$spinner = document.createElement('craft-spinner');
this.$spinner.setAttribute('visible', false);
Expand Down Expand Up @@ -297,6 +299,7 @@ Craft.LoginForm = Garnish.Base.extend(
.velocity('fadeIn');

this.$errors.removeClass('hidden');
Craft.cp.announce(error);
this.onResize();
},

Expand All @@ -318,7 +321,7 @@ Craft.LoginForm = Garnish.Base.extend(
return;
}

this.$passkeyBtn.addClass('loading');
this.passkeyBtn.busyEvent();

try {
const optionsResponse = await Craft.sendActionRequest(
Expand All @@ -339,14 +342,18 @@ Craft.LoginForm = Garnish.Base.extend(
}
);

this.passkeyBtn.successEvent();
this.settings.onLogin(loginResponse.data.returnUrl);
} catch (e) {
const message = e?.response?.data?.message;

this.passkeyBtn.failureEvent();

if (message) {
this.showError(message);
}
} finally {
this.$passkeyBtn.removeClass('loading');
this.passkeyBtn.endBusyState();
}
},
},
Expand Down Expand Up @@ -422,6 +429,7 @@ Craft.LoginForm.ResetPasswordForm = Garnish.Base.extend({

this.loginForm.clearErrors();
this.$submitBtn.addClass('loading');
Craft.cp.announce(Craft.t('app', 'Loading'));

const data = {
loginName: this.$usernameInput.val(),
Expand Down
2 changes: 2 additions & 0 deletions src/web/assets/cp/src/js/PreviewFileModal.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ Craft.PreviewFileModal = Garnish.Modal.extend(
)
);

Craft.cp.announce(Craft.t('app', 'Loading'));

// Cut the flicker, just show the nice person the preview.
this.$container.velocity('stop');
this.$container.show().css('opacity', 1);
Expand Down
5 changes: 5 additions & 0 deletions src/web/assets/cp/src/js/Slideout.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import $ from 'jquery';

(function ($) {
/** global: Craft */
/** global: Garnish */
Expand All @@ -9,6 +11,7 @@
$outerContainer: null,
$container: null,
$shade: null,
$liveRegion: $('<span class="visually-hidden" role="status"></span>'),
isOpen: false,
useMobileStyles: null,

Expand Down Expand Up @@ -36,6 +39,8 @@

Craft.trapFocusWithin(this.$container);

this.$liveRegion.appendTo(this.$container);

if (this.settings.autoOpen) {
this.open();
}
Expand Down
2 changes: 1 addition & 1 deletion src/web/assets/garnish/dist/garnish.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/web/assets/garnish/dist/garnish.js.map

Large diffs are not rendered by default.

Loading