From bd19ae71f0719f20600d8e438f34e529613e19da Mon Sep 17 00:00:00 2001 From: Jaifroid Date: Thu, 2 Nov 2023 11:34:37 +0000 Subject: [PATCH] Make auto focus search bar depend on home key option (#1144) --- i18n/en.jsonp.js | 7 +++--- i18n/es.jsonp.js | 7 +++--- i18n/fr.jsonp.js | 7 +++--- www/css/app.css | 2 +- www/index.html | 4 ++-- www/js/app.js | 53 +++++++++++++++++++++++--------------------- www/js/lib/uiUtil.js | 25 +++++++++++---------- 7 files changed, 56 insertions(+), 49 deletions(-) diff --git a/i18n/en.jsonp.js b/i18n/en.jsonp.js index 4fbd95ca6..2f4b691c6 100644 --- a/i18n/en.jsonp.js +++ b/i18n/en.jsonp.js @@ -35,8 +35,8 @@ document.localeJson = { "configure-display-slideaway-tip": "Header and footer will slide away when scrolling or (on fixed pages, swiping) down at least 50 pixels, and will slide back when you scroll up. On fixed pages, you can also use Ctrl/Command + UpArrow or DownArrow. The option is now on by default.", "configure-display-uianimations": "Animate transition between app pages", "configure-display-uianimations-tip": "The animation is on by default and can be disabled by unchecking this option.", - "configure-display-homekeyfocus": "Use Home key to focus search bar (may rarely have side effects on ZIM files that handle Home key)", - "configure-display-homekeyfocus-tip": "Enables quick access to search, no matter where you are in an article.", + "configure-display-homekeyfocus": "Home key and Home tab focus search bar (may have side effects on ZIMs that handle Home key)", + "configure-display-homekeyfocus-tip": "Auto-focuses the search bar when you press the Home key, and also when you click or tap on the Home tab. Enables quick access to search, no matter where you are in an article.", "configure-display-openexternallinks": "Open external links in new tabs. Disabling this might break kiwix-js UI in some specific cases", "configure-display-openexternallinks-tip": "Opens the external links outside kiwix-js (avoids some side-effects affecting kiwix-js UI).", "configure-display-selectapptheme": "Select app theme (content inversion is experimental):", @@ -132,6 +132,7 @@ document.localeJson = { "dialog-error-title": "Error!", "dialog-file-notset-message": "Data files not set", "dialog-file-notset-title": "Archive not ready", + "dialog-focussearchbarcheck-message": "Please note that this setting focuses the search bar when you go to a ZIM landing page, disabling sliding away of header and footer on that page (only).", "dialog-invalid-archivelocation-title": "Error: invalid archive files location", "dialog-invalid-archivelocation-message": "It looks like you have put some archive files at the root of your sdcard (or internal storage). Please move them to a subdirectory", "dialog-invalid-zim-title": "Invalid file format", @@ -162,10 +163,10 @@ document.localeJson = { "dialog-serviceworker-unsupported-fallback": "Use JQuery mode", "dialog-serviceworker-defaultmodechange-title": "Change of default content injection mode", "dialog-serviceworker-defaultmodechange-message": "

We have switched you to ServiceWorker mode (this is now the default). It supports more types of ZIM archives and is much more robust.

If you experience problems with this mode, you can switch back to the (now deprecated) JQuery mode. In that case, please report the problems you experienced to us (see About section).

", - "dialog-slideawaycheck-title": "Warning", "dialog-slideawaycheck-message": "This setting may not work correctly on Firefox OS. If you find that some ZIM links become unresponsive, try turning this setting off.", "dialog-unsupported-archivetype-message": "

You are attempting to open a Zimit-style archive, which is currently unsupported in this app.

There is experimental support for this kind of archive in the Kiwix JS PWA. Go to: https://pwa.kiwix.org.

Alternatively, you can use Kiwix Serve to serve this archive to your browser from localhost. Kiwix Serve is included with Kiwix Desktop.

", "dialog-unsupported-archivetype-title": "Unsupported archive type!", + "dialog-warning": "Warning", "dialog-welcome-title": "Welcome", "dialog-welcome-message": "Welcome to Kiwix! This application needs at least a ZIM file in your SD-card (or internal storage). Please download one and put it on the device (see About section). Also check that your device is not connected to a computer through USB device storage (which often locks the SD-card content)", "about": "About", diff --git a/i18n/es.jsonp.js b/i18n/es.jsonp.js index c28d89504..ba3a173bf 100644 --- a/i18n/es.jsonp.js +++ b/i18n/es.jsonp.js @@ -35,8 +35,8 @@ document.localeJson = { "configure-display-slideaway-tip": "El encabezado y el pie de página se ocultarán al desplazarse o (en páginas fijas, deslizar) hacia abajo al menos 50 píxeles, y volverán a aparecer al desplazarse hacia arriba. En las páginas fijas, también puede usar Ctrl/Command + FlechaArriba o FlechaAbajo. La opción está activada por defecto.", "configure-display-uianimations": "Animar transición entre páginas de la aplicación", "configure-display-uianimations-tip": "La animación está activada por defecto y puede ser desactivada desmarcando esta opción.", - "configure-display-homekeyfocus": "Usar tecla Inicio para enfocar la barra de búsqueda (puede tener efectos secundarios en archivos ZIM que manejen la tecla Inicio)", - "configure-display-homekeyfocus-tip": "Habilita acceso rápido a la búsqueda con el teclado, sin importar en qué parte del artículo esté.", + "configure-display-homekeyfocus": "La tecla y la pestaña Inicio enfocan la barra de búsqueda (puede tener efectos secundarios en archivos que manejen la tecla Inicio)", + "configure-display-homekeyfocus-tip": "Enfoca automáticamente la barra de búsqueda al pulsar la tecla Inicio, y también al hacer clic o tocar en la pestaña Inicio. Habilita acceso rápido a la búsqueda con el teclado, sin importar en qué parte del artículo esté.", "configure-display-openexternallinks": "Abrir enlaces externos en nuevas pestañas. Si desactiva esto, se puede romper la interfaz de kiwix-js en algunos casos específicos", "configure-display-openexternallinks-tip": "Abre los enlaces externos fuera de kiwix-js (evita algunos efectos secundarios que afectan la interfaz de kiwix-js).", "configure-display-selectapptheme": "Seleccionar tema de la aplicación (la inversión de contenido es experimental):", @@ -132,6 +132,7 @@ document.localeJson = { "dialog-error-title": "¡Error!", "dialog-file-notset-message": "El archivo no está cargado correctamente", "dialog-file-notset-title": "Archivo no listo", + "dialog-focussearchbarcheck-message": "Tenga en cuenta que esta configuración enfoca la barra de búsqueda cuando abre la página de inicio de un archivo, y por eso desactiva el deslizamiento del encabezado y pie en esta página (únicamente).", "dialog-invalid-archivelocation-title": "Error: ubicación de archivos no válida", "dialog-invalid-archivelocation-message": "Parece que ha puesto algunos archivos de archivo en la raíz de su tarjeta SD (o almacenamiento interno). Por favor, muévalos a un subdirectorio", "dialog-invalid-zim-title": "Formato de archivo inválido", @@ -162,10 +163,10 @@ document.localeJson = { "dialog-serviceworker-unsupported-fallback": "Use modo JQuery", "dialog-serviceworker-defaultmodechange-title": "Cambio del modo de inyección de contenido predeterminado", "dialog-serviceworker-defaultmodechange-message": "

Le hemos cambiado al modo ServiceWorker (ahora es el modo predeterminado). Soporta más tipos de archivo ZIM y es mucho más robusto.

Si tiene problemas con este modo, puede volver al modo JQuery (ahora obsoleto). En tal caso, por favor, informe de los problemas que ha experimentado (véase la página Información).

", - "dialog-slideawaycheck-title": "¡Aviso!", "dialog-slideawaycheck-message": "Esta configuración puede no funcionar correctamente en Firefox OS. Si encuentra que algunos enlaces ZIM no responden, se recomienda desactivar esta configuración.", "dialog-unsupported-archivetype-message": "

Está intentando abrir un archivo de estilo Zimit, que actualmente no es compatible con esta aplicación.

Hay soporte experimental para este tipo de archivo en la PWA de Kiwix JS. Vaya a: https://pwa.kiwix.org.

Alternativamente, puede usar Kiwix Serve para servir este archivo a su navegador desde localhost. Kiwix Serve está incluido con Kiwix Desktop.

", "dialog-unsupported-archivetype-title": "¡Tipo de archivo no compatible!", + "dialog-warning": "¡Aviso!", "dialog-welcome-title": "Bienvenide", "dialog-welcome-message": "¡Bienvenide a Kiwix! Esta aplicación necesita al menos un archivo ZIM en su tarjeta SD (o almacenamiento interno). Por favor, descargue uno y póngalo en el dispositivo (véase la sección Información). También compruebe que su dispositivo no está conectado a un ordenador a través del almacenamiento de dispositivos USB (que a menudo bloquea el contenido de la tarjeta SD).", "about": "Información", diff --git a/i18n/fr.jsonp.js b/i18n/fr.jsonp.js index 0a8475423..abec3ef36 100644 --- a/i18n/fr.jsonp.js +++ b/i18n/fr.jsonp.js @@ -35,8 +35,8 @@ document.localeJson = { "configure-display-slideaway-tip": "L'en-tête et le pied de page disparaîtront lors du défilement ou du balayage vers le bas d'au moins 50 pixels, et réapparaîtront lorsque vous remonterez. Sur les pages fixes, vous pouvez également utiliser Ctrl/Command + Flèche haut ou bas. L'option est maintenant activée par défaut.", "configure-display-uianimations": "Animer la transition entre les pages de l'application", "configure-display-uianimations-tip": "L'animation est activée par défaut et peut être désactivée en décochant cette option.", - "configure-display-homekeyfocus": "Utiliser la touche Accueil pour mettre le focus sur la barre de recherche (peut avoir des effets secondaires sur les fichiers ZIM qui gèrent la touche Accueil)", - "configure-display-homekeyfocus-tip": "Active l'accès rapide à la recherche par clavier, quel que soit l'endroit où vous vous trouvez dans l'article.", + "configure-display-homekeyfocus": "La touche et l'onglet Accueil mettent le focus sur la barre de recherche (peut avoir des effets secondaires chez les fichiers qui gèrent la touche Accueil)", + "configure-display-homekeyfocus-tip": "La barre de recherche se focalise automatiquement lorsque vous appuyez sur la touche Accueil, ainsi que lorsque vous cliquez ou tapez sur l'onglet Accueil. Active l'accès rapide à la recherche par clavier, quel que soit l'endroit où vous vous trouvez dans l'article.", "configure-display-openexternallinks": "Ouvrir les liens externes dans de nouveaux onglets. Si vous désactivez cette option, l'interface de kiwix-js peut être cassée dans certains cas spécifiques", "configure-display-openexternallinks-tip": "Ouvre les liens externes en dehors de kiwix-js (évite certains effets secondaires affectant l'interface de kiwix-js).", "configure-display-selectapptheme": "Sélectionner le thème de l'application (le mode inversé est expérimentale) :", @@ -132,6 +132,7 @@ document.localeJson = { "dialog-error-title": "Erreur !", "dialog-file-notset-message": "Le fichier n'est pas chargé correctement", "dialog-file-notset-title": "Fichier non chargé", + "dialog-focussearchbarcheck-message": "Veuillez noter que ce paramètre met le focus sur la barre de recherche lorsque vous allez sur la page d'accueil d'un ZIM, désactivant le glissement de l'en-tête et du pied sur cette page (uniquement).", "dialog-invalid-archivelocation-title": "Erreur : emplacement d'archive non valide", "dialog-invalid-archivelocation-message": "Il semble que vous ayez placé des fichiers d'archive à la racine de votre carte SD (ou de votre stockage interne). Veuillez les déplacer dans un sous-répertoire", "dialog-invalid-zim-title": "Format de fichier non valide", @@ -162,10 +163,10 @@ document.localeJson = { "dialog-serviceworker-unsupported-fallback": "Utiliser le mode JQuery", "dialog-serviceworker-defaultmodechange-title": "Changement du mode d'injection de contenu par défaut", "dialog-serviceworker-defaultmodechange-message": "

Nous vous avons basculé en mode ServiceWorker (c'est maintenant le mode par défaut). Il prend en charge plus de types de fichiers ZIM et est beaucoup plus robuste.

Si vous rencontrez des problèmes avec ce mode, vous pouvez revenir au mode JQuery (maintenant obsolète). Dans ce cas, veuillez signaler les problèmes que vous avez rencontrés (voir la page Informations).

", - "dialog-slideawaycheck-title": "Avertissement", "dialog-slideawaycheck-message": "Ce paramètre peut ne pas fonctionner correctement chez Firefox OS. Si vous constatez que certains liens ZIM deviennent inactifs, veuillez désactiver ce paramètre.", "dialog-unsupported-archivetype-message": "

Vous essayez d'ouvrir un fichier de style Zimit, qui n'est actuellement pas pris en charge par cette application.

Il existe une prise en charge expérimentale de ce type de fichier dans la PWA de Kiwix JS. Allez sur : https://pwa.kiwix.org.

Alternativement, vous pouvez utiliser Kiwix Serve pour servir ce fichier à votre navigateur à partir de localhost. Kiwix Serve est inclus dans Kiwix Desktop.

", "dialog-unsupported-archivetype-title": "Type de fichier non pris en charge !", + "dialog-warning": "Avertissement", "dialog-welcome-title": "Bienvenue", "dialog-welcome-message": "Bienvenue dans Kiwix ! Cette application a besoin d'au moins un fichier ZIM sur votre carte SD (ou stockage interne). Veuillez en télécharger un et le placer sur l'appareil (voir la section Informations). Veuillez également vérifier que votre appareil n'est pas connecté à un ordinateur via le stockage USB (ce qui bloque souvent le contenu de la carte SD).", "about": "Informations", diff --git a/www/css/app.css b/www/css/app.css index 1f1d0fa0d..620093e7e 100644 --- a/www/css/app.css +++ b/www/css/app.css @@ -72,7 +72,7 @@ margin-bottom: 12px !important; } -#top, #articleContent, #footer { +#top, #articleContent, #footer, article { transition: transform 0.3s ease; } diff --git a/www/index.html b/www/index.html index e758c1a36..0944c1328 100644 --- a/www/index.html +++ b/www/index.html @@ -522,10 +522,10 @@

Display settings

-
diff --git a/www/js/app.js b/www/js/app.js index 179b7c8d7..2b6e5242d 100644 --- a/www/js/app.js +++ b/www/js/app.js @@ -146,27 +146,28 @@ function resizeIFrame () { const libraryContent = document.getElementById('libraryContent'); const liHomeNav = document.getElementById('liHomeNav'); const nestedFrame = libraryContent.contentWindow.document.getElementById('libraryIframe'); - uiUtil.showSlidingUIElements(); - if (library.style.display !== 'none') { - // We are in Library, so we set the height of the library iframes to the window height minus the header height - const headerHeight = parseFloat(headerStyles.height) + parseFloat(headerStyles.marginBottom); - libraryContent.style.height = window.innerHeight + 'px'; - nestedFrame.style.height = window.innerHeight - headerHeight + 'px'; - region.style.overflowY = 'hidden'; - } else if (!liHomeNav.classList.contains('active')) { - // We are not in Home, so we reset the region height - region.style.height = window.innerHeight + 'px'; - region.style.overflowY = 'auto'; - } else { - // IE cannot retrieve computed headerStyles till the next paint, so we wait a few ticks - setTimeout(function () { + // There is a race condition with the slide animations, so we have to wait more than 300ms + setTimeout(function () { + uiUtil.showSlidingUIElements(); + if (library.style.display !== 'none') { + // We are in Library, so we set the height of the library iframes to the window height minus the header height + const headerHeight = parseFloat(headerStyles.height) + parseFloat(headerStyles.marginBottom); + libraryContent.style.height = window.innerHeight + 'px'; + nestedFrame.style.height = window.innerHeight - headerHeight + 'px'; + region.style.overflowY = 'hidden'; + } else if (!liHomeNav.classList.contains('active')) { + // We are not in Home, so we reset the region height + region.style.height = window.innerHeight + 'px'; + region.style.overflowY = 'auto'; + } else { // Get header height *including* its bottom margin const headerHeight = parseFloat(headerStyles.height) + parseFloat(headerStyles.marginBottom); articleContainer.style.height = window.innerHeight - headerHeight + 'px'; // Hide the scrollbar of Configure / About region.style.overflowY = 'hidden'; - }, 100); - } + } + // IE cannot retrieve computed headerStyles till the next paint, so we wait a few ticks even if UI animations are disabled + }, params.showUIAnimations ? 400 : 100); // Remove and add the scroll event listener to the new article window // Note that IE11 doesn't support wheel or touch events on the iframe, but it does support keydown and scroll @@ -386,7 +387,7 @@ document.getElementById('btnHome').addEventListener('click', function (event) { // Give the focus to the search field, and clean up the page contents document.getElementById('prefix').value = ''; - document.getElementById('prefix').focus(); + if (params.useHomeKeyToFocusSearchBar) document.getElementById('prefix').focus(); var articleList = document.getElementById('articleList'); var articleListHeaderMessage = document.getElementById('articleListHeaderMessage'); while (articleList.firstChild) articleList.removeChild(articleList.firstChild); @@ -489,7 +490,7 @@ document.getElementById('slideAwayCheck').addEventListener('change', function (e if (typeof navigator.getDeviceStorages === 'function') { // We are in Firefox OS, which may have a bug with this setting turned on - see [kiwix-js #1140] uiUtil.systemAlert(translateUI.t('dialog-slideawaycheck-message') || ('This setting may not work correctly on Firefox OS. ' + - 'If you find that some ZIM links become unresponsive, try turning this setting off.'), translateUI.t('dialog-slideawaycheck-title') || 'Warning'); + 'If you find that some ZIM links become unresponsive, try turning this setting off.'), translateUI.t('dialog-warning') || 'Warning'); } settingsStore.setItem('slideAway', params.slideAway, Infinity); // This has methods to add or remove the event listeners needed @@ -501,13 +502,15 @@ document.querySelectorAll('input[type="checkbox"][name=showUIAnimations]').forEa settingsStore.setItem('showUIAnimations', params.showUIAnimations, Infinity); }) }); -document.querySelectorAll('input[type="checkbox"][name=useHomeKeyToFocusSearchBar]').forEach(function (element) { - element.addEventListener('change', function () { - params.useHomeKeyToFocusSearchBar = !!this.checked; - settingsStore.setItem('useHomeKeyToFocusSearchBar', params.useHomeKeyToFocusSearchBar, Infinity); - switchHomeKeyToFocusSearchBar(); - }) -}) +document.getElementById('useHomeKeyToFocusSearchBarCheck').addEventListener('change', function (e) { + params.useHomeKeyToFocusSearchBar = e.target.checked; + settingsStore.setItem('useHomeKeyToFocusSearchBar', params.useHomeKeyToFocusSearchBar, Infinity); + switchHomeKeyToFocusSearchBar(); + if (params.useHomeKeyToFocusSearchBar && params.slideAway) { + uiUtil.systemAlert(translateUI.t('dialog-focussearchbarcheck-message') || 'Please note that this setting focuses the search bar when you go to a ZIM landing page, disabling sliding away of header and footer on that page (only).', + translateUI.t('dialog-warning') || 'Warning'); + } +}); document.querySelectorAll('input[type="checkbox"][name=openExternalLinksInNewTabs]').forEach(function (element) { element.addEventListener('change', function () { params.openExternalLinksInNewTabs = !!this.checked; diff --git a/www/js/lib/uiUtil.js b/www/js/lib/uiUtil.js index 0e5ca68bd..0bb61665d 100644 --- a/www/js/lib/uiUtil.js +++ b/www/js/lib/uiUtil.js @@ -38,15 +38,16 @@ const footer = document.getElementById('footer'); */ function hideSlidingUIElements () { const articleContainer = document.getElementById('articleContent'); - const headerStyles = getComputedStyle(header); - const headerHeight = parseFloat(headerStyles.height) + parseFloat(headerStyles.marginBottom) - 2; + const articleElement = document.querySelector('article'); const footerStyles = getComputedStyle(footer); const footerHeight = parseFloat(footerStyles.height) + parseFloat(footerStyles.marginTop) - 2; - header.style.transform = 'translateY(-' + headerHeight + 'px)'; - articleContainer.style.transform = 'translateY(-' + headerHeight + 'px)'; - const iframeHeight = parseFloat(articleContainer.style.height.replace('px', '')); - articleContainer.style.height = iframeHeight + headerHeight + 'px'; + const headerStyles = getComputedStyle(header); + const headerHeight = parseFloat(headerStyles.height) + parseFloat(headerStyles.marginBottom) - 2; + const iframeHeight = parseFloat(articleElement.style.height.replace('px', '')); footer.style.transform = 'translateY(' + footerHeight + 'px)'; + articleContainer.style.height = iframeHeight + headerHeight + 'px'; + header.style.transform = 'translateY(-' + headerHeight + 'px)'; + articleElement.style.transform = 'translateY(-' + headerHeight + 'px)'; } /** @@ -54,15 +55,15 @@ function hideSlidingUIElements () { */ function showSlidingUIElements () { const articleContainer = document.getElementById('articleContent'); + const articleElement = document.querySelector('article'); + const headerStyles = getComputedStyle(document.getElementById('top')); + const headerHeight = parseFloat(headerStyles.height) + parseFloat(headerStyles.marginBottom); header.style.transform = 'translateY(0)'; // Needed for Windows Mobile to prevent header disappearing beneath iframe - articleContainer.style.transform = 'translateY(-1px)'; + articleElement.style.transform = 'translateY(-1px)'; footer.style.transform = 'translateY(0)'; - setTimeout(function () { - const headerStyles = getComputedStyle(document.getElementById('top')); - const headerHeight = parseFloat(headerStyles.height) + parseFloat(headerStyles.marginBottom); - articleContainer.style.height = window.innerHeight - headerHeight + 'px'; - }, 200); + articleElement.style.height = window.innerHeight - headerHeight + 'px'; + articleContainer.style.height = window.innerHeight - headerHeight + 'px'; } let scrollThrottle = false;