Upgrade 1-11.38

This commit is contained in:
xesmyd
2026-03-30 14:10:30 +02:00
parent f2a7e6d1fc
commit ac648ef29d
24665 changed files with 69682 additions and 2205004 deletions
+161 -165
View File
@@ -1,7 +1,5 @@
/*global H5P*/
/* eslint-disable no-param-reassign */
H5P.ConfirmationDialog = (function (EventDispatcher) {
"use strict";
/**
* Create a confirmation dialog
*
@@ -15,21 +13,23 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
* @param [options.hideExit] Hide exit button
* @param [options.skipRestoreFocus] Skip restoring focus when hiding the dialog
* @param [options.classes] Extra classes for popup
* @param [options.theme] Whether to use the new theme (true) or the old design (false)
* @constructor
*/
function ConfirmationDialog(options) {
EventDispatcher.call(this);
var self = this;
const self = this;
// Make sure confirmation dialogs have unique id
H5P.ConfirmationDialog.uniqueId += 1;
var uniqueId = H5P.ConfirmationDialog.uniqueId;
const { uniqueId } = H5P.ConfirmationDialog;
// Default options
options = options || {};
options.headerText = options.headerText || H5P.t('confirmDialogHeader');
options.dialogText = options.dialogText || H5P.t('confirmDialogBody');
options.cancelText = options.cancelText || H5P.t('cancelLabel');
options.closeText = options.closeText || H5P.t('close');
options.confirmText = options.confirmText || H5P.t('confirmLabel');
/**
@@ -44,166 +44,180 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
/**
* Handle dialog canceled
* @param {Event} e
* @param {Event} e Event.
* @param {object} [options] Options.
* @param {boolean} [options.wasExplicitChoice]
* True if user chose cancel explicitly, otherwise (close, esc) false.
*/
function dialogCanceled(e) {
function dialogCanceled(e, options = {}) {
self.hide();
self.trigger('canceled');
self.trigger('canceled', { wasExplicitChoice: options.wasExplicitChoice ?? false });
e.preventDefault();
}
/**
* Flow focus to element
* @param {HTMLElement} element Next element to be focused
* @param {Event} e Original tab event
* Handle tabbing through buttons with focus trapping.
* @param {KeyboardEvent} event Keyboard event.
*/
function flowTo(element, e) {
element.focus();
e.preventDefault();
function handleTabbing(event) {
if (event.key !== 'Tab') {
return;
}
event.preventDefault();
const currentIndex = focusableButtons.indexOf(event.target);
const offset = event.shiftKey ? -1 : 1;
const nextIndex = (currentIndex + offset + focusableButtons.length) % focusableButtons.length;
focusableButtons[nextIndex].focus();
}
// Offset of exit button
var exitButtonOffset = 2 * 16;
var shadowOffset = 8;
const exitButtonOffset = 2 * 16;
const shadowOffset = 8;
// Determine if we are too large for our container and must resize
var resizeIFrame = false;
let resizeIFrame = false;
// Create background
var popupBackground = document.createElement('div');
const popupBackground = document.createElement('div');
popupBackground.classList
.add('h5p-confirmation-dialog-background', 'hidden', 'hiding');
if (options.theme) {
popupBackground.classList.add('h5p-theme');
}
if (window.H5PEditor) {
popupBackground.classList.add('h5peditor');
if (H5PIntegration.theme?.density) {
popupBackground.classList.add(`h5p-${H5PIntegration.theme.density}`);
}
}
// Create outer popup
var popup = document.createElement('div');
const popup = document.createElement('div');
popup.classList.add('h5p-confirmation-dialog-popup', 'hidden');
if (options.classes) {
options.classes.forEach(function (popupClass) {
options.classes.forEach((popupClass) => {
popup.classList.add(popupClass);
});
}
popup.setAttribute('role', 'dialog');
popup.setAttribute('aria-labelledby', 'h5p-confirmation-dialog-dialog-text-' + uniqueId);
popup.setAttribute('role', 'alertdialog');
popup.setAttribute('aria-modal', 'true');
popup.setAttribute('aria-labelledby', `h5p-confirmation-dialog-header-text-${uniqueId}`);
popup.setAttribute('aria-describedby', `h5p-confirmation-dialog-text-${uniqueId}`);
popupBackground.appendChild(popup);
popup.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {// Esc key
popup.addEventListener('keydown', (e) => {
if (e.key === 'Escape') { // Esc key
// Exit dialog
dialogCanceled(e);
}
});
popup.addEventListener('keydown', (event) => {
handleTabbing(event);
});
// Popup header
var header = document.createElement('div');
const header = document.createElement('div');
header.classList.add('h5p-confirmation-dialog-header');
popup.appendChild(header);
// Header text
var headerText = document.createElement('div');
const headerText = document.createElement('div');
headerText.classList.add('h5p-confirmation-dialog-header-text');
headerText.id = `h5p-confirmation-dialog-dialog-header-text-${uniqueId}`;
headerText.innerHTML = options.headerText;
header.appendChild(headerText);
// Popup body
var body = document.createElement('div');
const body = document.createElement('div');
body.classList.add('h5p-confirmation-dialog-body');
popup.appendChild(body);
// Popup text
var text = document.createElement('div');
const text = document.createElement('div');
text.classList.add('h5p-confirmation-dialog-text');
text.innerHTML = options.dialogText;
text.id = 'h5p-confirmation-dialog-dialog-text-' + uniqueId;
text.id = `h5p-confirmation-dialog-dialog-text-${uniqueId}`;
body.appendChild(text);
// Popup buttons
var buttons = document.createElement('div');
const buttons = document.createElement('div');
buttons.classList.add('h5p-confirmation-dialog-buttons');
body.appendChild(buttons);
// Cancel button
var cancelButton = document.createElement('button');
cancelButton.classList.add('h5p-core-cancel-button');
cancelButton.textContent = options.cancelText;
// Confirm button
var confirmButton = document.createElement('button');
confirmButton.classList.add('h5p-core-button');
confirmButton.classList.add('h5p-confirmation-dialog-confirm-button');
confirmButton.textContent = options.confirmText;
// Exit button
var exitButton = document.createElement('button');
exitButton.classList.add('h5p-confirmation-dialog-exit');
exitButton.tabIndex = -1;
exitButton.setAttribute('aria-label', options.cancelText);
// Cancel handler
cancelButton.addEventListener('click', dialogCanceled);
cancelButton.addEventListener('keydown', function (e) {
if (e.key === ' ') { // Space
dialogCanceled(e);
}
else if (e.key === 'Tab' && e.shiftKey) { // Shift-tab
const nextbutton = options.hideExit ? confirmButton : exitButton;
flowTo(nextbutton, e);
}
});
if (!options.hideCancel) {
const cancelButton = document.createElement('button');
if (!options.theme) {
cancelButton.classList.add('h5p-core-cancel-button');
}
else {
cancelButton.classList.add('h5p-theme-button', 'h5p-theme-secondary-cta');
cancelButton.classList.add('h5p-theme-cancel');
}
const cancelText = document.createElement('span');
cancelText.textContent = options.cancelText;
cancelButton.appendChild(cancelText);
cancelButton.addEventListener('click', (event) => {
dialogCanceled(event, { wasExplicitChoice: true });
});
buttons.appendChild(cancelButton);
}
else {
// Center buttons
// Center remaining buttons
buttons.classList.add('center');
}
// Confirm handler
// Confirm button
const confirmButton = document.createElement('button');
if (!options.theme) {
confirmButton.classList.add('h5p-core-button');
}
// confirmButton.classList.add('h5p-confirmation-dialog-confirm-button');
confirmButton.setAttribute('aria-label', options.confirmText);
if (options.theme) {
confirmButton.classList.add('h5p-theme-button', 'h5p-theme-primary-cta');
confirmButton.classList.add('h5p-theme-check');
}
confirmButton.addEventListener('click', dialogConfirmed);
confirmButton.addEventListener('keydown', function (e) {
if (e.key === ' ') { // Space
dialogConfirmed(e);
}
else if (e.key === 'Tab' && !e.shiftKey) { // Tab
let nextButton = confirmButton;
if (!options.hideExit) {
nextButton = exitButton;
}
else if (!options.hideCancel) {
nextButton = cancelButton;
}
flowTo(nextButton, e);
}
});
const confirmText = document.createElement('span');
confirmText.textContent = options.confirmText;
confirmButton.appendChild(confirmText);
buttons.appendChild(confirmButton);
// Exit handler
exitButton.addEventListener('click', dialogCanceled);
exitButton.addEventListener('keydown', function (e) {
if (e.key === ' ') { // Space
dialogCanceled(e);
}
else if (e.key === 'Tab' && !e.shiftKey) { // Tab
const nextButton = options.hideCancel ? confirmButton : cancelButton;
flowTo(nextButton, e);
}
});
let focusableButtons = [...buttons.childNodes];
// Exit button
if (!options.hideExit) {
popup.appendChild(exitButton);
const exitButton = document.createElement('button');
exitButton.classList.add('h5p-confirmation-dialog-exit');
exitButton.setAttribute('aria-label', options.closeText);
exitButton.addEventListener('click', dialogCanceled);
if (options.theme) {
header.appendChild(exitButton);
}
else {
popup.appendChild(exitButton);
}
focusableButtons.push(exitButton);
}
// Wrapper element
var wrapperElement;
// Focus capturing
var focusPredator;
let wrapperElement;
// Maintains hidden state of elements
var wrapperSiblingsHidden = [];
var popupSiblingsHidden = [];
let wrapperSiblingsHidden = [];
let popupSiblingsHidden = [];
// Element with focus before dialog
var previouslyFocused;
let previouslyFocused;
/**
* Set parent of confirmation dialog
@@ -215,34 +229,27 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
return this;
};
/**
* Capture the focus element, send it to confirmation button
* @param {Event} e Original focus event
*/
var captureFocus = function (e) {
if (!popupBackground.contains(e.target)) {
e.preventDefault();
confirmButton.focus();
}
};
/**
* Hide siblings of element from assistive technology
*
* @param {HTMLElement} element
* @returns {Array} The previous hidden state of all siblings
*/
var hideSiblings = function (element) {
var hiddenSiblings = [];
var siblings = element.parentNode.children;
var i;
const hideSiblings = function (element) {
const hiddenSiblings = [];
const siblings = element.parentNode.children;
let i;
for (i = 0; i < siblings.length; i += 1) {
// Preserve hidden state
hiddenSiblings[i] = siblings[i].getAttribute('aria-hidden') ?
true : false;
hiddenSiblings[i] = !!siblings[i].getAttribute('aria-hidden');
if (siblings[i] !== element) {
siblings[i].setAttribute('aria-hidden', true);
if (siblings[i].getAttribute('aria-live')) {
siblings[i].setAttribute('aria-busy', true);
}
else {
siblings[i].setAttribute('aria-hidden', true);
}
}
}
return hiddenSiblings;
@@ -254,36 +261,25 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
* @param {HTMLElement} element
* @param {Array} hiddenSiblings Hidden state of all siblings
*/
var restoreSiblings = function (element, hiddenSiblings) {
var siblings = element.parentNode.children;
var i;
const restoreSiblings = function (element, hiddenSiblings) {
const siblings = element.parentNode.children;
let i;
for (i = 0; i < siblings.length; i += 1) {
if (siblings[i] !== element && !hiddenSiblings[i]) {
siblings[i].removeAttribute('aria-hidden');
if (siblings[i].getAttribute('aria-live')) {
siblings[i].setAttribute('aria-busy', false);
}
else {
siblings[i].removeAttribute('aria-hidden');
}
}
}
};
/**
* Start capturing focus of parent and send it to dialog
*/
var startCapturingFocus = function () {
focusPredator = wrapperElement.parentNode || wrapperElement;
focusPredator.addEventListener('focus', captureFocus, true);
};
/**
* Clean up event listener for capturing focus
*/
var stopCapturingFocus = function () {
focusPredator.removeAttribute('aria-hidden');
focusPredator.removeEventListener('focus', captureFocus, true);
};
/**
* Hide siblings in underlay from assistive technologies
*/
var disableUnderlay = function () {
const disableUnderlay = function () {
wrapperSiblingsHidden = hideSiblings(wrapperElement);
popupSiblingsHidden = hideSiblings(popupBackground);
};
@@ -291,7 +287,7 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
/**
* Restore state of underlay for assistive technologies
*/
var restoreUnderlay = function () {
const restoreUnderlay = function () {
restoreSiblings(wrapperElement, wrapperSiblingsHidden);
restoreSiblings(popupBackground, popupSiblingsHidden);
};
@@ -300,8 +296,8 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
* Fit popup to container. Makes sure it doesn't overflow.
* @params {number} [offsetTop] Offset of popup
*/
var fitToContainer = function (offsetTop) {
var popupOffsetTop = parseInt(popup.style.top, 10);
const fitToContainer = function (offsetTop) {
let popupOffsetTop = parseInt(popup.style.top, 10);
if (offsetTop !== undefined) {
popupOffsetTop = offsetTop;
}
@@ -321,7 +317,7 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
// We are too big and must resize
resizeIFrame = true;
}
popup.style.top = popupOffsetTop + 'px';
popup.style.top = `${popupOffsetTop}px`;
};
/**
@@ -333,28 +329,32 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
// Capture focused item
previouslyFocused = document.activeElement;
wrapperElement.appendChild(popupBackground);
startCapturingFocus();
disableUnderlay();
popupBackground.classList.remove('hidden');
fitToContainer(offsetTop);
setTimeout(function () {
popup.classList.remove('hidden');
popupBackground.classList.remove('hiding');
popup.classList.remove('hidden');
popupBackground.addEventListener('transitionend', () => {
buttons.firstChild.focus();
}, { once: true });
popupBackground.classList.remove('hiding');
disableUnderlay();
setTimeout(function () {
// Focus confirm button
confirmButton.focus();
// Resize iFrame if necessary
if (resizeIFrame && options.instance) {
const minHeight = parseInt(popup.offsetHeight, 10)
+ exitButtonOffset + (2 * shadowOffset);
self.setViewPortMinimumHeight(minHeight);
options.instance.trigger('resize');
resizeIFrame = false;
}
// Resize iFrame if necessary
if (resizeIFrame && options.instance) {
var minHeight = parseInt(popup.offsetHeight, 10) +
exitButtonOffset + (2 * shadowOffset);
self.setViewPortMinimumHeight(minHeight);
options.instance.trigger('resize');
resizeIFrame = false;
}
}, 100);
}, 0);
// Detect if the user prefers reduced motion, because in that case
// we cannot rely on transitionend triggering and we need to manually
// focus the buttons. It should also be checked for each show, since a
// user may change this setting at any time.
const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
if (prefersReducedMotion.matches) {
buttons.firstChild.focus();
}
return this;
};
@@ -364,20 +364,17 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
* @returns {H5P.ConfirmationDialog}
*/
this.hide = function () {
restoreUnderlay();
popupBackground.classList.add('hiding');
popup.classList.add('hidden');
// Restore focus
stopCapturingFocus();
if (!options.skipRestoreFocus) {
previouslyFocused.focus();
}
restoreUnderlay();
setTimeout(function () {
popupBackground.classList.add('hidden');
wrapperElement.removeChild(popupBackground);
self.setViewPortMinimumHeight(null);
}, 100);
popupBackground.classList.add('hidden');
wrapperElement.removeChild(popupBackground);
self.setViewPortMinimumHeight(null);
return this;
};
@@ -405,8 +402,8 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
* @param {number|null} minHeight
*/
this.setViewPortMinimumHeight = function (minHeight) {
var container = document.querySelector('.h5p-container') || document.body;
container.style.minHeight = (typeof minHeight === 'number') ? (minHeight + 'px') : minHeight;
const container = document.querySelector('.h5p-container') || document.body;
container.style.minHeight = (typeof minHeight === 'number') ? (`${minHeight}px`) : minHeight;
};
}
@@ -414,7 +411,6 @@ H5P.ConfirmationDialog = (function (EventDispatcher) {
ConfirmationDialog.prototype.constructor = ConfirmationDialog;
return ConfirmationDialog;
}(H5P.EventDispatcher));
H5P.ConfirmationDialog.uniqueId = -1;
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+274 -114
View File
@@ -1,6 +1,54 @@
/*global H5P*/
/* global H5P */
H5P.Tooltip = (function () {
'use strict';
// Position (allowed and default)
const Position = {
allowed: ['top', 'bottom', 'left', 'right'],
default: 'top',
};
/** {number} DELAY_SHOW_MS Delay before tooltip is shown */
const DELAY_SHOW_MS = 500;
/** {number} DELAY_HIDE_MS Delay before tooltip is hidden */
const DELAY_HIDE_MS = 500;
/**
* Strips html tags and converts special characters.
* Example: "<div>Me &amp; you</div>" is converted to "Me & you".
*
* @param {String} text The text to be parsed
* @returns {String} The parsed text
*/
function parseString(text) {
if (text === null || text === undefined) {
return '';
}
const div = document.createElement('div');
div.innerHTML = text;
return div.textContent;
}
/**
* Keep track of whether the user is using their mouse or keyboard to
* navigate. Will determine whether tooltip should be shown on focus.
*/
let usingMouse;
function debounce(callback, delay) {
let timeout = null;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
callback(...args);
}, delay);
};
}
// The mousemove listener is debounced for performance reasons
document.addEventListener('mousemove', debounce(() => usingMouse = true, 100));
document.addEventListener('mousedown', () => usingMouse = true);
document.addEventListener('keydown', () => usingMouse = false);
/**
* Create an accessible tooltip
@@ -8,196 +56,293 @@ H5P.Tooltip = (function () {
* @param {HTMLElement} triggeringElement The element that should trigger the tooltip
* @param {Object} options Options for tooltip
* @param {String} options.text The text to be displayed in the tooltip
* If not set, will attempt to set text = aria-label of triggeringElement
* If not set, will attempt to set text = options.tooltipSource of triggeringElement
* @param {String[]} options.classes Extra css classes for the tooltip
* @param {Boolean} options.ariaHidden Whether the hover should be read by screen readers or not (default: true)
* @param {String} options.position Where the tooltip should appear in relation to the
* triggeringElement. Accepted positions are "top" (default), "left", "right" and "bottom"
* @param {String} options.tooltipSource
*
* @returns {object} returns all the public functions
*
* @constructor
*/
function Tooltip(triggeringElement, options) {
function Tooltip(triggeringElement, options) {
// Make sure tooltips have unique id
H5P.Tooltip.uniqueId += 1;
const tooltipId = 'h5p-tooltip-' + H5P.Tooltip.uniqueId;
const tooltipId = `h5p-tooltip-${H5P.Tooltip.uniqueId}`;
// Default options
options = options || {};
options.classes = options.classes || [];
options.ariaHidden = options.ariaHidden || true;
options.tooltipSource = options.tooltipSource || 'aria-label';
options.position = (options.position && Position.allowed.includes(options.position))
? options.position
: Position.default;
// Add our internal classes
options.classes.push('h5p-tooltip');
if (options.position === 'left' || options.position === 'right') {
options.classes.push('h5p-tooltip-narrow');
}
// Initiate state
let hover = false;
let focus = false;
// Function used by the escape listener
const escapeFunction = function (e) {
if (e.key === 'Escape') {
const hideOnEscape = function (event) {
if (event.key === 'Escape') {
tooltip.classList.remove('h5p-tooltip-visible');
}
}
};
// Create element
const tooltip = document.createElement('div');
tooltip.classList.add('h5p-tooltip');
tooltip.id = tooltipId;
tooltip.role = 'tooltip';
tooltip.innerHTML = options.text || triggeringElement.getAttribute('aria-label') || '';
tooltip.textContent = parseString(options.text || triggeringElement.getAttribute(options.tooltipSource) || '');
tooltip.setAttribute('aria-hidden', options.ariaHidden);
tooltip.classList.add(...options.classes);
triggeringElement.appendChild(tooltip);
// Set the initial position based on options.position
switch (options.position) {
case 'left':
tooltip.classList.add('h5p-tooltip-left');
break;
case 'right':
tooltip.classList.add('h5p-tooltip-right');
break;
case 'bottom':
tooltip.classList.add('h5p-tooltip-bottom');
break;
default:
options.position = 'top';
}
document.body.appendChild(tooltip);
// Aria-describedby will override aria-hidden
if (!options.ariaHidden) {
triggeringElement.setAttribute('aria-describedby', tooltipId);
}
// Add event listeners to triggeringElement
triggeringElement.addEventListener('mouseenter', function () {
showTooltip(true);
});
triggeringElement.addEventListener('mouseleave', function () {
hideTooltip(true);
});
triggeringElement.addEventListener('focusin', function () {
showTooltip(false);
});
triggeringElement.addEventListener('focusout', function () {
hideTooltip(false);
});
// Prevent clicks on the tooltip from triggering onClick listeners on the triggeringElement
tooltip.addEventListener('click', function (event) {
event.stopPropagation();
});
// Use a mutation observer to listen for aria-label being
// Use a mutation observer to listen for options.tooltipSource being
// changed for the triggering element. If so, update the tooltip.
// Mutation observer will be used even if the original elements
// doesn't have any aria-label.
new MutationObserver(function (mutations) {
const ariaLabel = mutations[0].target.getAttribute('aria-label');
if (ariaLabel) {
tooltip.innerHTML = options.text || ariaLabel;
// doesn't have any options.tooltipSource.
this.observer = new MutationObserver((mutations) => {
const updatedText = mutations[0].target.getAttribute(options.tooltipSource);
if (tooltip.parentNode === null) {
triggeringElement.appendChild(tooltip);
}
}).observe(triggeringElement, {
tooltip.textContent = parseString(options.text || updatedText);
if (tooltip.textContent.trim().length === 0 && tooltip.classList.contains('h5p-tooltip-visible')) {
tooltip.classList.remove('h5p-tooltip-visible');
}
});
this.observer.observe(triggeringElement, {
attributes: true,
attributeFilter: ['aria-label'],
attributeFilter: [options.tooltipSource, 'class'],
});
// Use intersection observer to adjust the tooltip if it is not completely visible
new IntersectionObserver(function (entries) {
entries.forEach((entry) => {
const target = entry.target;
const positionClass = 'h5p-tooltip-' + options.position;
// A reference to the H5P container (if any). If null, it means
// this tooltip is not whithin an H5P.
let h5pContainer;
// Stop adjusting when hidden (to prevent a false positive next time)
if (entry.intersectionRatio === 0) {
['h5p-tooltip-down', 'h5p-tooltip-left', 'h5p-tooltip-right']
.forEach(function (adjustmentClass) {
if (adjustmentClass !== positionClass) {
target.classList.remove(adjustmentClass);
}
});
}
// Adjust if not completely visible when meant to be
else if (entry.intersectionRatio < 1 && (hover || focus)) {
const targetRect = entry.boundingClientRect;
const intersectionRect = entry.intersectionRect;
// Timer responsible for displaying the tooltip x ms after it has been
// triggered (either by mouseenter or focusin)
let showTooltipTimer;
// Going out of screen on left side
if (intersectionRect.left > targetRect.left) {
target.classList.add('h5p-tooltip-right');
target.classList.remove(positionClass);
}
// Going out of screen on right side
else if (intersectionRect.right < targetRect.right) {
target.classList.add('h5p-tooltip-left');
target.classList.remove(positionClass);
}
// Timer responsible for hiding the tooltip x ms after it has been untriggered
let hideTooltipTimer;
// going out of top of screen
if (intersectionRect.top > targetRect.top) {
target.classList.add('h5p-tooltip-down');
target.classList.remove(positionClass);
}
// going out of bottom of screen
else if (intersectionRect.bottom < targetRect.bottom) {
target.classList.add('h5p-tooltip-up');
target.classList.remove(positionClass);
}
}
});
}).observe(tooltip);
// This timer makes sure the tooltip is not hidden when the mouse
// moves from the trigger to the tooltip.
let triggerMouseLeaveTimer;
/**
* Makes the tooltip visible and activates it's functionality
*
* @param {Boolean} triggeredByHover True if triggered by mouse, false if triggered by focus
* @param {UIEvent} event The triggering event
*/
const showTooltip = function (triggeredByHover) {
if (triggeredByHover) {
const showTooltip = function (event, wait = true) {
if (!event.target || event.target.disabled || event.target.getAttribute('aria-disabled') === 'true') {
return;
}
clearTimeout(hideTooltipTimer); // Prevent from hiding while supposed to show
if (wait === true) {
// We don't want to show the tooltip right away.
// Adding a 300 ms waiting period here.
clearTimeout(showTooltipTimer);
showTooltipTimer = setTimeout(() => {
showTooltip(event, false);
}, DELAY_SHOW_MS);
return;
}
// Don't show tooltip if it is empty
if (tooltip.textContent.trim().length === 0) {
return;
}
if (event.type === 'mouseenter') {
hover = true;
}
else {
focus = true;
}
// Reset placement
tooltip.style.left = '';
tooltip.style.top = '';
tooltip.classList.add('h5p-tooltip-visible');
// Add listener to iframe body, as esc keypress would not be detected otherwise
document.body.addEventListener('keydown', escapeFunction, true);
}
document.body.addEventListener('keydown', hideOnEscape, true);
// The section below makes sure the tooltip is completely visible
// H5P.Tooltip can be used both from within an H5P and elsewhere.
// The below code is for figuring out the containing element.
// h5pContainer has to be looked up the first time we show the tooltip,
// since it might not be added to the DOM when H5P.Tooltip is invoked.
if (h5pContainer === undefined) {
// After the below, h5pContainer is either null or a reference to the
// DOM element
h5pContainer = triggeringElement.closest('.h5p-container');
}
const rootRect = h5pContainer ? h5pContainer.getBoundingClientRect() : document.documentElement.getBoundingClientRect();
const triggerRect = triggeringElement.getBoundingClientRect();
let tooltipRect = tooltip.getBoundingClientRect();
if (options.position === 'top') {
// Places it centered above
tooltip.style.left = `${triggerRect.left + (triggerRect.width / 2) - (tooltipRect.width / 2)}px`;
tooltip.style.top = `${triggerRect.top - tooltipRect.height}px`;
}
else if (options.position === 'bottom') {
// Places it centered below
tooltip.style.left = `${triggerRect.left + (triggerRect.width / 2) - (tooltipRect.width / 2)}px`;
tooltip.style.top = `${triggerRect.bottom}px`;
}
else if (options.position === 'left') {
tooltip.style.left = `${triggerRect.left - tooltipRect.width}px`;
tooltip.style.top = `${triggerRect.top + (triggerRect.height - tooltipRect.height) / 2}px`;
// We trust this option makes the tooltip being shown
return;
}
else if (options.position === 'right') {
tooltip.style.left = `${triggerRect.right}px`;
tooltip.style.top = `${triggerRect.top + (triggerRect.height - tooltipRect.height) / 2}px`;
// We trust this option makes the tooltip being shown
return;
}
tooltipRect = tooltip.getBoundingClientRect();
const isVisible = tooltipRect.left >= 0
&& tooltipRect.top >= 0
&& tooltipRect.right <= rootRect.width
&& tooltipRect.bottom <= rootRect.height;
if (!isVisible) {
// The tooltip placement needs to be adjusted. This logic will move the
// tooltip either left or right if it's placed outside the root element
tooltipRect = tooltip.getBoundingClientRect();
if (tooltipRect.left < 0) {
tooltip.style.left = 0;
}
else if (tooltipRect.right > rootRect.width) {
tooltip.style.left = '';
tooltip.style.right = 0;
}
}
};
/**
* Hides the tooltip and removes listeners
*
* @param {Boolean} triggeredByHover True if triggered by mouse, false if triggered by focus
* @param {UIEvent} event The triggering event
*/
const hideTooltip = function (triggeredByHover) {
if (triggeredByHover) {
hover = false;
const hideTooltip = function (event) {
let hide = false;
let wait = false;
if (event.type === 'click') {
hide = true;
}
else {
focus = false;
if (event.type === 'mouseleave') {
wait = true; // Tooltip should not disappear right away
hover = false;
}
else {
focus = false;
}
hide = (!hover && !focus);
}
// Only hide tooltip if neither hovered nor focused
if (!hover && !focus) {
tooltip.classList.remove('h5p-tooltip-visible');
if (hide) {
clearTimeout(showTooltipTimer); // Prevent from showing while supposed to hide
// Remove iframe body listener
document.body.removeEventListener('keydown', escapeFunction, true);
const cleanupTooltip = () => {
tooltip.classList.remove('h5p-tooltip-visible');
document.body.removeEventListener('keydown', hideOnEscape, true); // Remove iframe body listener
};
if (wait) {
clearTimeout(hideTooltipTimer);
hideTooltipTimer = setTimeout(() => {
cleanupTooltip();
}, DELAY_HIDE_MS);
}
else {
cleanupTooltip();
}
}
}
};
// Add event listeners to triggeringElement
triggeringElement.addEventListener('mouseenter', showTooltip);
triggeringElement.addEventListener('mouseleave', (event) => {
triggerMouseLeaveTimer = setTimeout(() => {
hideTooltip(event);
}, 1);
});
triggeringElement.addEventListener('focusin', (event) => {
if (!usingMouse) {
showTooltip(event);
}
});
triggeringElement.addEventListener('focusout', hideTooltip);
triggeringElement.addEventListener('click', hideTooltip);
tooltip.addEventListener('mouseenter', () => {
clearTimeout(triggerMouseLeaveTimer);
});
tooltip.addEventListener('mouseleave', hideTooltip);
tooltip.addEventListener('click', (event) => {
// Prevent clicks on the tooltip from triggering click
// listeners on the triggering element
event.stopPropagation();
event.preventDefault();
// Hide the tooltip when it is clicked
hideTooltip(event);
});
/**
* Change the text displayed by the tooltip
*
* @param {String} text The new text to be displayed
* Set to null to use aria-label of triggeringElement instead
* Set to null to use options.tooltipSource of triggeringElement instead
*/
this.setText = function (text) {
options.text = text;
tooltip.innerHTML = options.text || triggeringElement.getAttribute('aria-label') || '';
tooltip.textContent = parseString(options.text || triggeringElement.getAttribute(options.tooltipSource) || '');
};
/**
* Hide the tooltip
*/
this.hide = function () {
hover = focus = false;
tooltip.classList.remove('h5p-tooltip-visible');
};
/**
@@ -208,10 +353,25 @@ H5P.Tooltip = (function () {
this.getElement = function () {
return tooltip;
};
/**
* Remove tooltip
*/
this.remove = function () {
this.observer?.disconnect();
tooltip.remove();
};
return {
setText: this.setText,
hide: this.hide,
getElement: this.getElement,
remove: this.remove,
observer: this.observer,
};
}
return Tooltip;
})();
}());
H5P.Tooltip.uniqueId = -1;
+23 -3
View File
@@ -104,6 +104,10 @@ H5P.init = function (target) {
metadata: contentData.metadata
};
// Apply theme density
let density = H5PIntegration.theme?.density ?? 'large';
$element.addClass('h5p-' + density);
H5P.getUserData(contentId, 'state', function (err, previousState) {
if (previousState) {
library.userDatas = {
@@ -182,7 +186,11 @@ H5P.init = function (target) {
var $actions = actionBar.getDOMElement();
actionBar.on('reuse', function () {
H5P.openReuseDialog($actions, contentData, library, instance, contentId);
H5P.openReuseDialog($actions, contentData, {
library: contentData.library,
params: JSON.parse(contentData.jsonContent),
metadata: contentData.metadata
}, instance, contentId);
instance.triggerXAPI('accessed-reuse');
});
actionBar.on('copyrights', function () {
@@ -1289,20 +1297,25 @@ H5P.buildMetadataCopyrights = function (metadata) {
*/
H5P.openReuseDialog = function ($element, contentData, library, instance, contentId) {
let html = '';
let buttonCount = 0;
if (contentData.displayOptions.export) {
html += '<button type="button" class="h5p-big-button h5p-download-button"><div class="h5p-button-title">Download as an .h5p file</div><div class="h5p-button-description">.h5p files may be uploaded to any web-site where H5P content may be created.</div></button>';
buttonCount += 1;
}
if (contentData.displayOptions.export && contentData.displayOptions.copy) {
html += '<div class="h5p-horizontal-line-text"><span>or</span></div>';
}
if (contentData.displayOptions.copy) {
html += '<button type="button" class="h5p-big-button h5p-copy-button"><div class="h5p-button-title">Copy content</div><div class="h5p-button-description">Copied content may be pasted anywhere this content type is supported on this website.</div></button>';
buttonCount += 1;
}
const dialog = new H5P.Dialog('reuse', H5P.t('reuseContent'), html, $element);
// Selecting embed code when dialog is opened
H5P.jQuery(dialog).on('dialog-opened', function (e, $dialog) {
const scrollContent = $dialog[0].querySelector('.h5p-scroll-content');
scrollContent.style.setProperty('--button-count', buttonCount);
H5P.jQuery('<a href="https://h5p.org/node/442225" target="_blank">More Info</a>').click(function (e) {
e.stopPropagation();
}).appendTo($dialog.find('h2'));
@@ -1898,7 +1911,7 @@ H5P.MediaCopyright = function (copyright, labels, order, extraFields) {
* @param {string} source
* @param {number} width
* @param {number} height
* @param {string} alt
* @param {string} alt
* alternative text for the thumbnail
*/
H5P.Thumbnail = function (source, width, height, alt) {
@@ -2077,6 +2090,13 @@ H5P.libraryFromString = function (library) {
* The full path to the library.
*/
H5P.getLibraryPath = function (library) {
if (H5PIntegration &&
H5PIntegration.libraryDirectories &&
library in H5PIntegration.libraryDirectories) {
// Use H5PIntegration.libraryDirectories if it exists for this library
library = H5PIntegration.libraryDirectories[library];
}
if (H5PIntegration.urlLibraries !== undefined) {
// This is an override for those implementations that has a different libraries URL, e.g. Moodle
return H5PIntegration.urlLibraries + '/' + library;
@@ -2720,7 +2740,7 @@ H5P.createTitle = function (rawTitle, maxLength) {
}
return path.substr(0, prefix.length) === prefix ? path : prefix + path;
}
return path; // Will automatically be looked for in tmp folder
});