diff --git a/pages/catalog/CatalogBookHandler.php b/pages/catalog/CatalogBookHandler.php index 7926b6d704a..3836c31c9e5 100755 --- a/pages/catalog/CatalogBookHandler.php +++ b/pages/catalog/CatalogBookHandler.php @@ -30,6 +30,9 @@ use APP\security\authorization\OmpPublishedSubmissionAccessPolicy; use APP\submission\Submission; use APP\template\TemplateManager; +use Illuminate\Support\Arr; +use Illuminate\Support\LazyCollection; +use PKP\author\Author; use PKP\citation\CitationDAO; use PKP\core\Core; use PKP\core\PKPApplication; @@ -41,6 +44,7 @@ use PKP\plugins\PluginRegistry; use PKP\security\authorization\ContextRequiredPolicy; use PKP\security\Validation; +use PKP\services\PKPSchemaService; use PKP\submission\Genre; use PKP\submission\GenreDAO; use PKP\submission\PKPSubmission; @@ -310,6 +314,18 @@ public function book($args, $request) $templateMgr->addHeader('canonical', ''); } + $templateMgr->assign('pubLocaleData', $this->getMultilingualMetadataOpts( + $this->publication, + $templateMgr->getTemplateVars('currentLocale'), + $templateMgr->getTemplateVars('activeTheme')->getOption('showMultilingualMetadata') ?: [], + )); + + $templateMgr->registerPlugin('modifier', 'wrapData', fn (...$args) => $this->smartyWrapData($templateMgr, ...$args)); + $templateMgr->registerPlugin('modifier', 'useFilters', fn (...$args) => $this->smartyUseFilters($templateMgr, ...$args)); + $templateMgr->registerPlugin('modifier', 'getAuthorFullNames', $this->smartyGetAuthorFullNames(...)); + $templateMgr->registerPlugin('modifier', 'getAffiliationNamesWithRors', $this->smartyGetAffiliationNamesWithRors(...)); + $templateMgr->registerPlugin('modifier', 'getAuthorsFullNamesWithAffiliations', $this->smartyGetAuthorsFullNamesWithAffiliations(...)); + // Display if (!Hook::call('CatalogBookHandler::book', [&$request, &$submission, &$this->publication, &$this->chapter])) { $templateMgr->display('frontend/pages/book.tpl'); @@ -621,4 +637,150 @@ protected function getChaptersFirstPublishedDate(Submission $submission, Chapter return null; } + + /** + * Multilingual publication metadata for template: + * showMultilingualMetadataOpts - Show metadata in other languages: title (+ subtitle), keywords, abstract, etc. + */ + protected function getMultilingualMetadataOpts(Publication $publication, string $currentUILocale, array $showMultilingualMetadataOpts): array + { + // Affiliation languages are not in multiligual props + $authorsAffiliationLangs = collect($publication->getData('authors')) + ->map(fn ($author): array => $author->getAffiliations()) + ->flatten() + ->map(fn ($affiliation): array => array_keys(($affiliation->getRorObject() ?? $affiliation)->getData('name'))) + ->flatten() + ->unique() + ->values() + ->toArray(); + $langNames = collect($publication->getLanguageNames() + Locale::getSubmissionLocaleDisplayNames($authorsAffiliationLangs)) + ->sortKeys(); + $langs = $langNames->keys(); + + return [ + 'opts' => array_flip($showMultilingualMetadataOpts), + 'localeNames' => $langNames, + 'langAttrs' => $langNames->map(fn ($_, $l) => preg_replace(['/@.+$/', '/_/'], ['', '-'], $l))->toArray() /* remove @ and text after */, + 'localeOrder' => collect($publication->getLocalePrecedence()) + ->intersect($langs) /* remove locales not in publication's languages */ + ->concat($langs) + ->unique() + ->values() + ->toArray(), + ]; + } + + /** + * Publication's multilingual data to array for js and page + */ + protected function smartyWrapData(TemplateManager $templateMgr, array $data, string $switcher, ?array $filters = null, ?string $separator = null): array + { + return [ + 'switcher' => $switcher, + 'data' => collect($data) + ->map( + fn ($value): string => collect(Arr::wrap($value)) + ->when($filters, fn ($value) => $value->map(fn ($v) => $this->smartyUseFilters($templateMgr, $v, $filters))) + ->when($separator, fn ($value): string => $value->join($separator), fn ($value): string => $value->first()) + ) + ->toArray(), + 'defaultLocale' => collect($templateMgr->getTemplateVars('pubLocaleData')['localeOrder']) + ->first(fn (string $locale) => isset($data[$locale])), + ]; + } + + /** + * Smarty template: Apply filters to given value + */ + protected function smartyUseFilters(TemplateManager $templateMgr, string $value, ?array $filters): string + { + if (!$filters) { + return $value; + } + foreach ($filters as $filter) { + $params = Arr::wrap($filter); + $funcName = array_shift($params); + if ($func = $templateMgr->registered_plugins['modifier'][$funcName][0] ?? null) { + $value = $func($value, ...$params); + } + } + return $value; + } + + /** + * Smarty template: Get author's full names to multilingual array including all multilingual and affiliation languages as default localized name + */ + protected function smartyGetAuthorFullNames(Author $author): array + { + return collect($this->getAuthorLocales($author)) + ->mapWithKeys(fn (string $locale) => [$locale => $author->getFullName(preferredLocale: $locale)]) + ->toArray(); + } + + /** + * Smarty template: Get authors' affiliations with rors + */ + protected function smartyGetAffiliationNamesWithRors(Author $author): array + { + $affiliations = collect($author->getAffiliations()); + + return collect($this->getAuthorLocales($author)) + ->flip() + ->map( + fn ($_, string $locale) => $affiliations + ->map(fn ($affiliation): array => [ + 'name' => $affiliation->getAffiliationName($locale), + 'ror' => $affiliation->getRor(), + ]) + ->filter(fn (array $nameRor) => $nameRor['name']) + ->toArray() + ) + ->filter() + ->toArray(); + } + + /** + * Smarty template: Get authors' full names to multilingual array including multilingual prop and affiliation languages as default localized name, + * and affiliations with rors + */ + protected function smartyGetAuthorsFullNamesWithAffiliations(LazyCollection $authors): array + { + $locales = $authors + ->map(fn (Author $author): array => $this->getAuthorLocales($author)) + ->flatten() + ->unique() + ->values() + ->flip(); + $affiliations = $authors + ->map(fn (Author $author): array => $this->smartyGetAffiliationNamesWithRors($author)); + + return $locales + ->map( + fn ($_, $locale): array => $authors + ->map(fn (Author $author, $id): array => [ + 'name' => $author->getFullName(preferredLocale: $locale), + 'affiliations' => Arr::only($affiliations->get($id), [$locale]), + ]) + ->toArray() + ) + ->toArray(); + } + + /** + * Aux for smarty template functions: Get author's locales from multilingual props and affiliations + */ + protected function getAuthorLocales(Author $author): array + { + $multilingualLocales = collect(app()->get('schema')->getMultilingualProps(PKPSchemaService::SCHEMA_AUTHOR)) + ->map(fn (string $prop): array => array_keys($author->getData($prop) ?? [])); + $affiliationLocales = collect($author->getAffiliations()) + ->flatten() + ->map(fn ($affiliation): array => array_keys(($affiliation->getRorObject() ?? $affiliation)->getData('name'))); + + return $multilingualLocales + ->concat($affiliationLocales) + ->flatten() + ->unique() + ->toArray(); + } } diff --git a/plugins/themes/default/DefaultThemePlugin.php b/plugins/themes/default/DefaultThemePlugin.php index 63937bf6d35..f97f03f503d 100644 --- a/plugins/themes/default/DefaultThemePlugin.php +++ b/plugins/themes/default/DefaultThemePlugin.php @@ -3,8 +3,8 @@ /** * @file plugins/themes/default/DefaultThemePlugin.php * - * Copyright (c) 2014-2022 Simon Fraser University - * Copyright (c) 2003-2022 John Willinsky + * Copyright (c) 2014-2025 Simon Fraser University + * Copyright (c) 2003-2025 John Willinsky * Distributed under the GNU GPL v3. For full terms see the file docs/COPYING. * * @class DefaultThemePlugin @@ -126,6 +126,30 @@ public function init() 'default' => 'none', ]); + $this->addOption('showMultilingualMetadata', 'FieldOptions', [ + 'label' => __('plugins.themes.default.option.metadata.label'), + 'description' => __('plugins.themes.default.option.metadata.description'), + 'options' => [ + [ + 'value' => 'title', + 'label' => __('submission.title'), + ], + [ + 'value' => 'keywords', + 'label' => __('common.keywords'), + ], + [ + 'value' => 'abstract', + 'label' => __('submission.synopsis'), + ], + [ + 'value' => 'author', + 'label' => __('default.groups.name.author'), + ], + ], + 'default' => [], + ]); + // Load primary stylesheet $this->addStyle('stylesheet', 'styles/index.less'); diff --git a/plugins/themes/default/js/main.js b/plugins/themes/default/js/main.js index 3ba07ac5d14..e40f4d156ab 100644 --- a/plugins/themes/default/js/main.js +++ b/plugins/themes/default/js/main.js @@ -1,8 +1,8 @@ /** * @file plugins/themes/default/js/main.js * - * Copyright (c) 2014-2021 Simon Fraser University - * Copyright (c) 2000-2021 John Willinsky + * Copyright (c) 2014-2025 Simon Fraser University + * Copyright (c) 2000-2025 John Willinsky * Distributed under the GNU GPL v3. For full terms see the file docs/COPYING. * * @brief Handle JavaScript functionality unique to this theme. @@ -100,3 +100,177 @@ }); })(jQuery); + +/** + * Create language buttons to show multilingual metadata + * [data-pkp-switcher-data]: Publication data for the switchers to control + * [data-pkp-switcher]: Switchers' containers + */ +(() => { + function createSwitcher(switcherContainer, data, localeOrder, localeNames) { + // Get all locales for the switcher from the data + const locales = Object.keys(Object.assign({}, ...Object.values(data))); + // The initially selected locale + let selectedLocale = null; + // Create and sort to alphabetical order + const buttons = localeOrder + .map((locale) => { + if (locales.indexOf(locale) === -1) { + return null; + } + if (!selectedLocale) { + selectedLocale = locale; + } + + const isSelectedLocale = locale === selectedLocale; + const button = document.createElement('button'); + + button.type = 'button'; + button.classList.add('pkpBadge', 'pkpBadge--button'); + button.value = locale; + button.tabIndex = '-1'; + button.role = 'option'; + button.ariaHidden = `${!isSelectedLocale}`; + button.textContent = localeNames[locale]; + if (isSelectedLocale) { + button.ariaPressed = 'false'; + button.ariaCurrent = 'true'; + button.tabIndex = '0'; + } + return button; + }) + .filter((btn) => btn) + .sort((a, b) => a.value.localeCompare(b.value)); + + // If only one button, set it disabled + if (buttons.length === 1) { + buttons[0].disabled = true; + } + + buttons.forEach((btn, i) => { + switcherContainer.appendChild(btn); + }); + + return buttons; + } + + /** + * Sync data in elements to match the selected locale + */ + function syncDataElContents(locale, propsData, langAttrs) { + for (prop in propsData.data) { + propsData.dataEls[prop].lang = langAttrs[locale]; + propsData.dataEls[prop].innerHTML = propsData.data[prop][locale] ?? ''; + } + } + + /** + * Toggle visibility of the buttons + * setValue == true => aria-hidden == true, aria-expanded == false + */ + function setVisibility(switcherContainer, buttons, currentSelected, setValue) { + // Toggle switcher container's listbox/none-role + // Listbox when buttons visible and none when hidden + switcherContainer.role = setValue ? 'none' : 'listbox'; + currentSelected.btn.ariaPressed = `${!setValue}`; + buttons.forEach((btn) => { + if (btn !== currentSelected.btn) { + btn.ariaHidden = `${setValue}`; + } + }); + switcherContainer.ariaExpanded = `${!setValue}`; + } + + function setSwitcher(propsData, switcherContainer, localeOrder, localeNames, langAttrs) { + // Create buttons and append them to the switcher container + const buttons = createSwitcher(switcherContainer, propsData.data, localeOrder, localeNames); + const currentSelected = {btn: switcherContainer.querySelector('[tabindex="0"]')}; + const focused = {btn: currentSelected.btn}; + + // Sync contents in data elements to match the selected locale (currentSelected.btn.value) + syncDataElContents(currentSelected.btn.value, propsData, langAttrs); + + // Do not add listeners if just one button, it is disabled + if (buttons.length < 2) { + return; + } + + // New button switches language and syncs data contents. Same button hides buttons. + switcherContainer.addEventListener('click', (evt) => { + const newSelectedBtn = evt.target; + if (newSelectedBtn.type === 'button') { + if (newSelectedBtn !== currentSelected.btn) { + syncDataElContents(newSelectedBtn.value, propsData, langAttrs); + // Aria + currentSelected.btn.ariaCurrent = null; + newSelectedBtn.ariaCurrent = 'true'; + currentSelected.btn.ariaPressed = null; + newSelectedBtn.ariaPressed = 'true'; + // Tab index + currentSelected.btn.tabIndex = '-1'; + newSelectedBtn.tabIndex = '0'; + // Update current and focused button + currentSelected.btn = focused.btn = newSelectedBtn; + focused.btn.focus(); + } else { + setVisibility(switcherContainer, buttons, currentSelected, switcherContainer.ariaExpanded === 'true'); + } + } + }); + + // Hide buttons when focus out + switcherContainer.addEventListener('focusout', (evt) => { + // For safari losing button focus + if (evt.target.parentElement === switcherContainer && switcherContainer.ariaExpanded === 'true') { + focused.btn.focus(); + } + if (!evt.relatedTarget || evt.relatedTarget && evt.relatedTarget.parentElement !== switcherContainer) { + setVisibility(switcherContainer, buttons, currentSelected, 'true'); + } + }); + + // Arrow keys left and right cycles button focus when buttons visible. Set focused button. + switcherContainer.addEventListener("keydown", (evt) => { + if (switcherContainer.ariaExpanded === 'true' && evt.target.type === 'button' && (evt.key === "ArrowRight" || evt.key === "ArrowLeft")) { + focused.btn = (evt.key === "ArrowRight") + ? (focused.btn.nextElementSibling ?? buttons[0]) + : (focused.btn.previousElementSibling ?? buttons[buttons.length - 1]); + focused.btn.focus(); + } + }); + } + + /** + * Set all multilingual data and elements for the switchers + */ + function setSwitchersData(dataEls, pubLocaleData) { + const propsData = {}; + dataEls.forEach((dataEl) => { + const propName = dataEl.getAttribute('data-pkp-switcher-data'); + const switcherName = pubLocaleData[propName].switcher; + if (!propsData[switcherName]) { + propsData[switcherName] = {data: [], dataEls: []}; + } + propsData[switcherName].data[propName] = pubLocaleData[propName].data; + propsData[switcherName].dataEls[propName] = dataEl; + }); + return propsData; + } + + (() => { + const switcherContainers = document.querySelectorAll('[data-pkp-switcher]'); + + if (!switcherContainers.length) return; + + const pubLocaleData = JSON.parse(pubLocaleDataJson); + const switchersDataEls = document.querySelectorAll('[data-pkp-switcher-data]'); + const switchersData = setSwitchersData(switchersDataEls, pubLocaleData); + // Create and set switchers, and sync data on the page + switcherContainers.forEach((switcherContainer) => { + const switcherName = switcherContainer.getAttribute('data-pkp-switcher'); + if (switchersData[switcherName]) { + setSwitcher(switchersData[switcherName], switcherContainer, pubLocaleData.localeOrder, pubLocaleData.localeNames, pubLocaleData.langAttrs); + } + }); + })(); +})(); \ No newline at end of file diff --git a/plugins/themes/default/locale/en/locale.po b/plugins/themes/default/locale/en/locale.po index 92ba3303c69..92ecf32ab44 100644 --- a/plugins/themes/default/locale/en/locale.po +++ b/plugins/themes/default/locale/en/locale.po @@ -101,3 +101,21 @@ msgstr "Next slide" msgid "plugins.themes.default.prevSlide" msgstr "Previous slide" + +msgid "plugins.themes.default.option.metadata.label" +msgstr "Show book metadata on the book landing page" + +msgid "plugins.themes.default.option.metadata.description" +msgstr "Select the book metadata to show in other languages." + +msgid "plugins.themes.default.languageSwitcher.ariaDescription.titles" +msgstr "The article title and subtitle languages:" + +msgid "plugins.themes.default.languageSwitcher.ariaDescription.author" +msgstr "The author's affiliation languages:" + +msgid "plugins.themes.default.languageSwitcher.ariaDescription.keywords" +msgstr "The keywords languages:" + +msgid "plugins.themes.default.languageSwitcher.ariaDescription.abstract" +msgstr "The abstract languages:" diff --git a/plugins/themes/default/styles/objects/monograph_full.less b/plugins/themes/default/styles/objects/monograph_full.less index 057bc84e016..3bd58b712d1 100644 --- a/plugins/themes/default/styles/objects/monograph_full.less +++ b/plugins/themes/default/styles/objects/monograph_full.less @@ -38,6 +38,12 @@ font-size: @font-base; font-weight: @bold; } + + .keywords .label, + .abstract .label { + display: inline-flex; + font-size: @font-base; + } } .sub_item { @@ -236,6 +242,71 @@ } } + /** + * Language switcher + */ + + .pkpBadge { + padding: 0.25em 1em; + font-size: @font-tiny; + font-weight: @normal; + line-height: 1.5em; + border: 1px solid @bg-border-color-light; + border-radius: 1.2em; + color: @text; + } + + .pkpBadge--button { + background: inherit; + text-decoration: none; + cursor: pointer; + + &:hover { + border-color: @text; + outline: 0; + } + &:disabled, + &:disabled:hover { + color: #fff; + background: @bg-dark; + border-color: @bg-dark; + cursor: not-allowed; + } + } + + [data-pkp-switcher] [tabindex="0"] { + font-weight: @bold; + } + + [data-pkp-switcher], + [data-pkp-switcher] * { + display: inline-flex; + } + + [data-pkp-switcher] [aria-hidden="true"] { + display: none; + } + + [data-pkp-switcher] [aria-hidden="false"] { + animation: fadeIn 0.7s ease-in-out; + + @keyframes fadeIn { + 0% { + display: none; + opacity: 0; + } + + 1% { + display: inline-flex; + opacity: 0; + } + + 100% { + opacity: 1; + } + } + } + @media(min-width: @screen-phone) { .entry_details { diff --git a/templates/frontend/components/authors.tpl b/templates/frontend/components/authors.tpl index 4f62108ca7a..1e1bd79dbe3 100644 --- a/templates/frontend/components/authors.tpl +++ b/templates/frontend/components/authors.tpl @@ -14,6 +14,76 @@ * @uses $isChapterRequest bool Is true, if a chapter landing page is requested and not a monograph landing page *} +{** + * Add as editor to author's name + * @param array $authorFullNames, Required + * @param bool $identifyAsEditors, Required + * @return array, As variable $authorFullNames +*} +{function addAuthorAsEditor} + {foreach from=$authorFullNames item=$authorFullName key=$locale} + {if $identifyAsEditors} + {capture assign="authorFullName"}{translate key="submission.editorName" editorName=$authorFullName}{/capture} + {$authorFullNames[$locale]=$authorFullName} + {/if} + {/foreach} + {assign "authorFullNames" value=$authorFullNames scope="parent" nocache} +{/function} + +{** + * Authors' affiliations: concat affiliation and ror icon + * @param array $affiliationNamesWithRors, Required + * @param string $rorIdIcon, Required + * @param array $filters, Optional, E.g. ['escape'] + * @return array, As variable $affiliationNamesWithRors + *} +{function concatAuthorAffiliationsWithRors} + {foreach from=$affiliationNamesWithRors item=$namesPerLocale key=$locale} + {foreach from=$namesPerLocale item=$nameWithRor key=$key} + {* Affiliation name *} + {$affiliationRor=$nameWithRor.name|useFilters:$filters} + {* Ror *} + {if $nameWithRor.ror} + {capture assign="ror"}{$rorIdIcon}{/capture} + {$affiliationRor="{$affiliationRor}{$ror}"} + {/if} + {$affiliationNamesWithRors[$locale][$key]=$affiliationRor} + {/foreach} + {/foreach} + {assign "affiliationNamesWithRors" value=$affiliationNamesWithRors scope="parent" nocache} +{/function} + +{** + * Concat authors' name and affiliation + * Filters texts using function filterPubPropValue + * @param array $authorsWithAffiliationData, Required + * @param bool $identifyAsEditors, Required + * @param string $rorIdIcon, Required + * @param string $separator, Required + * @param array $filters, Optional, E.g. ['escape'] + * @return array, As varaible $authorsWithAffiliationData + *} +{function concatAuthorsWithAffiliationData} + {foreach from=$authorsWithAffiliationData item=$namesWithAffiliationsPerLocale key=$locale} + {foreach from=$namesWithAffiliationsPerLocale item=$nameWithAffiliations key=$key} + {* Author's name *} + {$authorName=$nameWithAffiliations.name} + {if $identifyAsEditors} + {capture assign="authorName"}{translate key="submission.editorName" editorName=$authorName}{/capture} + {/if} + {capture assign="nameAffiliation"}{$authorName|useFilters:$filters}{/capture} + {* Author's affiliations *} + {if isset($nameWithAffiliations.affiliations[$locale])} + {concatAuthorAffiliationsWithRors affiliationNamesWithRors=$nameWithAffiliations.affiliations rorIdIcon=$rorIdIcon filters=$filters} + {capture assign="affiliation"}{$separator|join:$affiliationNamesWithRors[$locale]}{/capture} + {capture assign="nameAffiliation"}{translate key="submission.authorWithAffiliation" name=$nameAffiliation affiliation=$affiliation}{/capture} + {/if} + {$authorsWithAffiliationData[$locale][$key]=$nameAffiliation} + {/foreach} + {/foreach} + {assign "authorsWithAffiliationData" value=$authorsWithAffiliationData scope="parent"} +{/function} +