All Downloads are FREE. Search and download functionalities are using the official Maven repository.

META-INF.resources.js.api.LocalizationSelect.js Maven / Gradle / Ivy

The newest version!
/**
 * SPDX-FileCopyrightText: (c) 2024 Liferay, Inc. https://liferay.com
 * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06
 */

import {LanguagePicker} from '@clayui/core';
import React, {useEffect, useMemo, useState} from 'react';

import './LocalizationSelect.scss';

const EVENT_TRANSLATION_STATUS = 'localizationSelect:updateTranslationStatus';

export function LocalizationSelect({
	defaultLanguageId,
	editMode,
	hideLanguageLabel,
	locales,
	size,
}) {
	const [active, setActive] = useState(false);
	const [selectedLocaleId, setSelectedLocaleId] = useState(defaultLanguageId);
	const [translations, setTranslations] = useState({});

	const localizableInputsTotal = useMemo(
		() => document.querySelectorAll('[data-localizable="true"]').length,
		[]
	);

	const onSelectedLocaleChange = (localeId) => {
		setSelectedLocaleId(localeId);
		setActive(false);
	};

	useEffect(() => {
		const updateTranslationStatus = ({languageId}) => {
			const totalTranslatedInputs = new Set([
				...Array.from(
					document.querySelectorAll(
						`[data-localizable="true"] [type="file"][name$="_${languageId}"]`
					)
				),
				...Array.from(
					document.querySelectorAll(
						`[data-localizable="true"] [type="hidden"][name$="_${languageId}"]`
					)
				)
					.filter((input) => input.getAttribute('value') !== null)
					.map((input) => input.name),
			]).size;

			const label = locales.find(
				(locale) => locale.id === languageId
			).label;

			setTranslations((previousState) => ({
				...previousState,
				...(totalTranslatedInputs && {
					[label]: {
						total: localizableInputsTotal,
						translated: totalTranslatedInputs,
					},
				}),
			}));
		};

		Liferay.on(EVENT_TRANSLATION_STATUS, updateTranslationStatus);

		for (const locale of locales) {
			updateTranslationStatus({languageId: locale.id});
		}

		return () => {
			Liferay.detach(EVENT_TRANSLATION_STATUS);
		};
	}, [defaultLanguageId, locales, localizableInputsTotal]);

	useEffect(() => {
		const onLocaleChanged = ({languageId}) => {
			if (selectedLocaleId !== languageId) {
				setSelectedLocaleId(languageId);
			}
		};

		Liferay.on('localizationSelect:localeChanged', onLocaleChanged);

		return () => {
			Liferay.detach('localizationSelect:localeChanged', onLocaleChanged);
		};
	}, [selectedLocaleId]);

	return (
		 {
				if (!editMode) {
					setActive(active);
				}
			}}
			onSelectedLocaleChange={(id) => {
				onSelectedLocaleChange(id);

				Liferay.fire('localizationSelect:localeChanged', {
					languageId: id,
				});
			}}
			selectedLocaleId={selectedLocaleId}
			small={size === 'small'}
			translations={translations}
		/>
	);
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy