dev #21
@ -705,14 +705,10 @@ export default function ContractTemplateList({ refreshKey = 0, onEdit }: Props)
|
|||||||
<section className="overflow-hidden rounded-4xl border border-slate-200 bg-white shadow-[0_24px_70px_-45px_rgba(15,23,42,0.45)]">
|
<section className="overflow-hidden rounded-4xl border border-slate-200 bg-white shadow-[0_24px_70px_-45px_rgba(15,23,42,0.45)]">
|
||||||
<div className="border-b border-slate-200 bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.18),transparent_30%),radial-gradient(circle_at_top_right,rgba(56,189,248,0.18),transparent_28%),linear-gradient(180deg,#ffffff_0%,#f8fafc_100%)] px-6 py-6 md:px-7 md:py-7 xl:px-8">
|
<div className="border-b border-slate-200 bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.18),transparent_30%),radial-gradient(circle_at_top_right,rgba(56,189,248,0.18),transparent_28%),linear-gradient(180deg,#ffffff_0%,#f8fafc_100%)] px-6 py-6 md:px-7 md:py-7 xl:px-8">
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white/85 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.26em] text-slate-500 shadow-sm">
|
<div className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white/85 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.26em] text-slate-500 shadow-sm">{t('autofix.k66b39536')}</div>
|
||||||
Template overview
|
|
||||||
</div>
|
|
||||||
<div>
|
<div>
|
||||||
<h3 className="text-2xl font-semibold tracking-tight text-slate-950 md:text-3xl">Organized by template family</h3>
|
<h3 className="text-2xl font-semibold tracking-tight text-slate-950 md:text-3xl">{t('autofix.k429d94bf')}</h3>
|
||||||
<p className="mt-2 max-w-2xl text-sm leading-6 text-slate-600 md:text-[15px]">
|
<p className="mt-2 max-w-2xl text-sm leading-6 text-slate-600 md:text-[15px]">{t('autofix.k7e4ef084')}</p>
|
||||||
Jump between template families, spot the currently active versions immediately and keep language-specific revisions in one place.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-2 pt-1">
|
<div className="flex flex-wrap gap-2 pt-1">
|
||||||
<MetricChip label="Families" value={familyGroups.length} />
|
<MetricChip label="Families" value={familyGroups.length} />
|
||||||
@ -795,9 +791,7 @@ export default function ContractTemplateList({ refreshKey = 0, onEdit }: Props)
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{activeFamily.key === 'contract' && (
|
{activeFamily.key === 'contract' && (
|
||||||
<div className="mt-4 rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700">
|
<div className="mt-4 rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700">{t('autofix.k766a5504')}</div>
|
||||||
Contracts are grouped by type again. Language now sits in the main header area of each track as a direct selector, so you can switch faster without digging into nested cards.
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{activeFamily.key === 'contract' ? (
|
{activeFamily.key === 'contract' ? (
|
||||||
@ -810,9 +804,7 @@ export default function ContractTemplateList({ refreshKey = 0, onEdit }: Props)
|
|||||||
{section.meta.shortLabel}
|
{section.meta.shortLabel}
|
||||||
</span>
|
</span>
|
||||||
<div>
|
<div>
|
||||||
<div className={`inline-flex items-center gap-2 rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] ${section.meta.headerClass}`}>
|
<div className={`inline-flex items-center gap-2 rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] ${section.meta.headerClass}`}>{t('autofix.kf962066f')}</div>
|
||||||
Contract type
|
|
||||||
</div>
|
|
||||||
<h5 className="mt-3 text-2xl font-semibold tracking-tight text-slate-950">{section.meta.label}</h5>
|
<h5 className="mt-3 text-2xl font-semibold tracking-tight text-slate-950">{section.meta.label}</h5>
|
||||||
<p className="mt-2 max-w-2xl text-sm leading-5 text-slate-600">{section.meta.description}</p>
|
<p className="mt-2 max-w-2xl text-sm leading-5 text-slate-600">{section.meta.description}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -88,9 +88,7 @@ export default function ContractManagementPage() {
|
|||||||
<main className="flex-1 space-y-6 md:space-y-8 xl:space-y-9">
|
<main className="flex-1 space-y-6 md:space-y-8 xl:space-y-9">
|
||||||
<header className="rounded-[30px] border border-white/80 bg-white/85 px-5 py-6 shadow-[0_24px_70px_-40px_rgba(15,23,42,0.38)] backdrop-blur md:px-8 md:py-8 xl:px-10">
|
<header className="rounded-[30px] border border-white/80 bg-white/85 px-5 py-6 shadow-[0_24px_70px_-40px_rgba(15,23,42,0.38)] backdrop-blur md:px-8 md:py-8 xl:px-10">
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.28em] text-slate-500">
|
<div className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.28em] text-slate-500">{t('autofix.k8351e02f')}</div>
|
||||||
Admin workspace
|
|
||||||
</div>
|
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-black tracking-tight text-slate-950 md:text-5xl">{t('autofix.k67cb36a4')}</h1>
|
<h1 className="text-3xl font-black tracking-tight text-slate-950 md:text-5xl">{t('autofix.k67cb36a4')}</h1>
|
||||||
<p className="mt-3 max-w-2xl text-sm leading-6 text-slate-600 md:text-base">
|
<p className="mt-3 max-w-2xl text-sm leading-6 text-slate-600 md:text-base">
|
||||||
@ -98,9 +96,9 @@ export default function ContractManagementPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-2 text-xs text-slate-600">
|
<div className="flex flex-wrap gap-2 text-xs text-slate-600">
|
||||||
<span className="inline-flex items-center rounded-full border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 shadow-sm">Grouped library</span>
|
<span className="inline-flex items-center rounded-full border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 shadow-sm">{t('autofix.k61d66984')}</span>
|
||||||
<span className="inline-flex items-center rounded-full border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 shadow-sm">Stronger language switching</span>
|
<span className="inline-flex items-center rounded-full border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 shadow-sm">{t('autofix.k74823841')}</span>
|
||||||
<span className="inline-flex items-center rounded-full border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 shadow-sm">Faster edit flow</span>
|
<span className="inline-flex items-center rounded-full border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 shadow-sm">{t('autofix.kccff045c')}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useTranslation } from '../../../i18n/useTranslation';
|
import { useTranslation } from '../../../i18n/useTranslation';
|
||||||
|
import { useModalAnimation } from '../hooks/useModalAnimation';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@ -26,12 +27,17 @@ export default function AddLanguageModal({
|
|||||||
onAdd,
|
onAdd,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { isRendered, isVisible } = useModalAnimation(isOpen);
|
||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isRendered) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
<div className={`fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity duration-200 ${
|
||||||
<div className="mx-4 w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl">
|
isVisible ? 'opacity-100' : 'opacity-0'
|
||||||
|
}`}>
|
||||||
|
<div className={`mx-4 w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl transform transition-all duration-200 ${
|
||||||
|
isVisible ? 'opacity-100 translate-y-0 scale-100' : 'opacity-0 translate-y-2 scale-[0.98]'
|
||||||
|
}`}>
|
||||||
<h2 className="text-lg font-bold text-[#1C2B4A] mb-4">{t('autofix.kf4e45236')}</h2>
|
<h2 className="text-lg font-bold text-[#1C2B4A] mb-4">{t('autofix.kf4e45236')}</h2>
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useTranslation } from '../../../i18n/useTranslation';
|
import { useTranslation } from '../../../i18n/useTranslation';
|
||||||
import type { NamespaceCategory } from '../hooks/useNamespaceCategories';
|
import type { NamespaceCategory } from '../hooks/useNamespaceCategories';
|
||||||
|
import { useModalAnimation } from '../hooks/useModalAnimation';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@ -43,12 +44,17 @@ export default function CategoryManagerModal({
|
|||||||
deleteCategory,
|
deleteCategory,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { isRendered, isVisible } = useModalAnimation(isOpen);
|
||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isRendered) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-[150] flex items-center justify-center bg-black/45 backdrop-blur-sm">
|
<div className={`fixed inset-0 z-[150] flex items-center justify-center bg-black/45 backdrop-blur-sm transition-opacity duration-200 ${
|
||||||
<div className="mx-4 w-full max-w-5xl rounded-2xl border border-slate-200 bg-white shadow-2xl overflow-hidden">
|
isVisible ? 'opacity-100' : 'opacity-0'
|
||||||
|
}`}>
|
||||||
|
<div className={`mx-4 w-full max-w-5xl rounded-2xl border border-slate-200 bg-white shadow-2xl overflow-hidden transform transition-all duration-200 ${
|
||||||
|
isVisible ? 'opacity-100 translate-y-0 scale-100' : 'opacity-0 translate-y-2 scale-[0.98]'
|
||||||
|
}`}>
|
||||||
<div className="px-6 py-4 border-b border-slate-200 bg-slate-50 flex items-start justify-between gap-4">
|
<div className="px-6 py-4 border-b border-slate-200 bg-slate-50 flex items-start justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-lg font-bold text-[#1C2B4A]">{t('autofix.kef9de7f0')}</h2>
|
<h2 className="text-lg font-bold text-[#1C2B4A]">{t('autofix.kef9de7f0')}</h2>
|
||||||
|
|||||||
@ -1,7 +1,9 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
import type { LanguageEntry } from '../hooks/useLanguageManagementTranslations';
|
import type { LanguageEntry } from '../hooks/useLanguageManagementTranslations';
|
||||||
import { useTranslation } from '../../../i18n/useTranslation';
|
import { useTranslation } from '../../../i18n/useTranslation';
|
||||||
|
import { useModalAnimation } from '../hooks/useModalAnimation';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
deleteTarget: string | null;
|
deleteTarget: string | null;
|
||||||
@ -12,22 +14,35 @@ type Props = {
|
|||||||
|
|
||||||
export default function DeleteLanguageModal({ deleteTarget, allLanguages, onClose, onDelete }: Props) {
|
export default function DeleteLanguageModal({ deleteTarget, allLanguages, onClose, onDelete }: Props) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [displayTarget, setDisplayTarget] = useState<string | null>(deleteTarget);
|
||||||
|
const isOpen = Boolean(deleteTarget);
|
||||||
|
const { isRendered, isVisible } = useModalAnimation(isOpen);
|
||||||
|
|
||||||
if (!deleteTarget) return null;
|
useEffect(() => {
|
||||||
|
if (deleteTarget) setDisplayTarget(deleteTarget);
|
||||||
|
}, [deleteTarget]);
|
||||||
|
|
||||||
|
if (!isRendered || !displayTarget) return null;
|
||||||
|
|
||||||
|
const languageName = allLanguages.find((l) => l.code === displayTarget)?.name ?? displayTarget;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
<div className={`fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity duration-200 ${
|
||||||
<div className="mx-4 w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl">
|
isVisible ? 'opacity-100' : 'opacity-0'
|
||||||
|
}`}>
|
||||||
|
<div className={`mx-4 w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl transform transition-all duration-200 ${
|
||||||
|
isVisible ? 'opacity-100 translate-y-0 scale-100' : 'opacity-0 translate-y-2 scale-[0.98]'
|
||||||
|
}`}>
|
||||||
<h2 className="text-lg font-bold text-red-600 mb-3">{t('autofix.kda5f982e')}</h2>
|
<h2 className="text-lg font-bold text-red-600 mb-3">{t('autofix.kda5f982e')}</h2>
|
||||||
<p className="text-sm text-gray-600 mb-5">
|
<p className="text-sm text-gray-600 mb-5">
|
||||||
Delete <strong>{allLanguages.find((l) => l.code === deleteTarget)?.name ?? deleteTarget}</strong>?
|
Delete <strong>{languageName}</strong>?
|
||||||
All translations for this language will be removed.
|
All translations for this language will be removed.
|
||||||
</p>
|
</p>
|
||||||
<div className="flex justify-end gap-3">
|
<div className="flex justify-end gap-3">
|
||||||
<button onClick={onClose} className="rounded-md border border-gray-300 px-4 py-2 text-sm hover:bg-gray-50">
|
<button onClick={onClose} className="rounded-md border border-gray-300 px-4 py-2 text-sm hover:bg-gray-50">
|
||||||
Cancel
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
<button onClick={() => onDelete(deleteTarget)} className="rounded-md bg-red-600 text-white px-4 py-2 text-sm font-semibold hover:bg-red-700">
|
<button onClick={() => onDelete(displayTarget)} className="rounded-md bg-red-600 text-white px-4 py-2 text-sm font-semibold hover:bg-red-700">
|
||||||
Delete
|
Delete
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import type { RefObject } from 'react';
|
import type { RefObject } from 'react';
|
||||||
|
import { useMemo } from 'react';
|
||||||
import { useTranslation } from '../../../i18n/useTranslation';
|
import { useTranslation } from '../../../i18n/useTranslation';
|
||||||
|
|
||||||
type LanguageEntry = {
|
type LanguageEntry = {
|
||||||
@ -55,6 +56,53 @@ export default function LanguageManagementTopSection({
|
|||||||
}: Props) {
|
}: Props) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const prioritizedLanguages = useMemo(() => {
|
||||||
|
const byCode = new Map(allLanguages.map((lang) => [lang.code, lang]));
|
||||||
|
const english = byCode.get('en');
|
||||||
|
const german = byCode.get('de');
|
||||||
|
|
||||||
|
const rest = allLanguages
|
||||||
|
.filter((lang) => lang.code !== 'en' && lang.code !== 'de')
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
|
||||||
|
return [english, german, ...rest].filter((lang): lang is LanguageEntry => Boolean(lang));
|
||||||
|
}, [allLanguages]);
|
||||||
|
|
||||||
|
const englishLanguage = prioritizedLanguages.find((lang) => lang.code === 'en');
|
||||||
|
const germanLanguage = prioritizedLanguages.find((lang) => lang.code === 'de');
|
||||||
|
const otherLanguages = prioritizedLanguages.filter((lang) => lang.code !== 'en' && lang.code !== 'de');
|
||||||
|
|
||||||
|
const renderLanguageButton = (lang: LanguageEntry) => (
|
||||||
|
<button
|
||||||
|
key={lang.code}
|
||||||
|
onClick={() => setActiveLang(lang.code)}
|
||||||
|
className={`relative rounded-lg px-4 py-2 text-sm font-medium transition flex items-center gap-2 ${
|
||||||
|
activeLang === lang.code
|
||||||
|
? 'bg-[#1C2B4A] text-white shadow'
|
||||||
|
: 'border border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{lang.name}
|
||||||
|
<span className="text-xs opacity-60">({lang.code})</span>
|
||||||
|
{!isBuiltin(lang.code) && (
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onDeleteLanguageRequest(lang.code);
|
||||||
|
}}
|
||||||
|
title={t('autofix.k5fcc9b0e')}
|
||||||
|
className={`ml-1 inline-flex items-center justify-center rounded-full w-4 h-4 text-xs leading-none ${
|
||||||
|
activeLang === lang.code
|
||||||
|
? 'bg-white/20 hover:bg-white/40 text-white'
|
||||||
|
: 'bg-gray-200 hover:bg-red-100 text-gray-500 hover:text-red-600'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div ref={headerRef} className="flex items-center justify-between flex-wrap gap-4">
|
<div ref={headerRef} className="flex items-center justify-between flex-wrap gap-4">
|
||||||
@ -100,42 +148,15 @@ export default function LanguageManagementTopSection({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
{allLanguages.map((lang) => (
|
{englishLanguage && renderLanguageButton(englishLanguage)}
|
||||||
<button
|
{germanLanguage && renderLanguageButton(germanLanguage)}
|
||||||
key={lang.code}
|
|
||||||
onClick={() => setActiveLang(lang.code)}
|
|
||||||
className={`relative rounded-lg px-4 py-2 text-sm font-medium transition flex items-center gap-2 ${
|
|
||||||
activeLang === lang.code
|
|
||||||
? 'bg-[#1C2B4A] text-white shadow'
|
|
||||||
: 'border border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{lang.name}
|
|
||||||
<span className="text-xs opacity-60">({lang.code})</span>
|
|
||||||
{!isBuiltin(lang.code) && (
|
|
||||||
<button
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
onDeleteLanguageRequest(lang.code);
|
|
||||||
}}
|
|
||||||
title={t('autofix.k5fcc9b0e')}
|
|
||||||
className={`ml-1 inline-flex items-center justify-center rounded-full w-4 h-4 text-xs leading-none ${
|
|
||||||
activeLang === lang.code
|
|
||||||
? 'bg-white/20 hover:bg-white/40 text-white'
|
|
||||||
: 'bg-gray-200 hover:bg-red-100 text-gray-500 hover:text-red-600'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
<button
|
<button
|
||||||
onClick={onOpenAddLanguage}
|
onClick={onOpenAddLanguage}
|
||||||
className="rounded-lg border-2 border-dashed border-gray-300 px-4 py-2 text-sm text-gray-500 hover:border-[#1C2B4A] hover:text-[#1C2B4A] transition"
|
className="rounded-lg border-2 border-dashed border-gray-300 px-4 py-2 text-sm text-gray-500 hover:border-[#1C2B4A] hover:text-[#1C2B4A] transition"
|
||||||
>
|
>
|
||||||
+ Add language
|
+ Add language
|
||||||
</button>
|
</button>
|
||||||
|
{otherLanguages.map((lang) => renderLanguageButton(lang))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{activeLang !== 'en' && (
|
{activeLang !== 'en' && (
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
import ScanFixPanel from './ScanFixPanel';
|
import ScanFixPanel from './ScanFixPanel';
|
||||||
import { useTranslation } from '../../../i18n/useTranslation';
|
import { useTranslation } from '../../../i18n/useTranslation';
|
||||||
import type { WorkspaceScanResult } from '../hooks/useI18nScanWorkflow';
|
import type { WorkspaceScanResult } from '../hooks/useI18nScanWorkflow';
|
||||||
|
import { useModalAnimation } from '../hooks/useModalAnimation';
|
||||||
|
|
||||||
type LanguageEntry = {
|
type LanguageEntry = {
|
||||||
code: string;
|
code: string;
|
||||||
@ -62,8 +63,9 @@ export default function ScanResultsModal({
|
|||||||
onRunFixSelected,
|
onRunFixSelected,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { isRendered, isVisible } = useModalAnimation(isOpen);
|
||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isRendered) return null;
|
||||||
|
|
||||||
const totalTranslated = scanResults.reduce((sum, row) => sum + row.translated, 0);
|
const totalTranslated = scanResults.reduce((sum, row) => sum + row.translated, 0);
|
||||||
const coveragePercent = totalKeys === 0
|
const coveragePercent = totalKeys === 0
|
||||||
@ -71,8 +73,12 @@ export default function ScanResultsModal({
|
|||||||
: Math.round((totalTranslated / totalKeys) * 100);
|
: Math.round((totalTranslated / totalKeys) * 100);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-[9999] flex items-start justify-center pt-14 pb-6 bg-black/50 backdrop-blur-sm">
|
<div className={`fixed inset-0 z-[9999] flex items-start justify-center pt-14 pb-6 bg-black/50 backdrop-blur-sm transition-opacity duration-200 ${
|
||||||
<div className="mx-3 w-full max-w-[1400px] rounded-3xl border border-slate-200 bg-white shadow-2xl flex flex-col max-h-[calc(100vh-5rem)] overflow-hidden">
|
isVisible ? 'opacity-100' : 'opacity-0'
|
||||||
|
}`}>
|
||||||
|
<div className={`mx-3 w-full max-w-[1400px] rounded-3xl border border-slate-200 bg-white shadow-2xl flex flex-col max-h-[calc(100vh-5rem)] overflow-hidden transform transition-all duration-200 ${
|
||||||
|
isVisible ? 'opacity-100 translate-y-0 scale-100' : 'opacity-0 translate-y-2 scale-[0.98]'
|
||||||
|
}`}>
|
||||||
<div className="px-8 pt-6 pb-5 border-b border-slate-200 bg-gradient-to-b from-slate-50 to-white">
|
<div className="px-8 pt-6 pb-5 border-b border-slate-200 bg-gradient-to-b from-slate-50 to-white">
|
||||||
<div className="flex items-start justify-between gap-4">
|
<div className="flex items-start justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@ -404,12 +404,14 @@ export default function TranslationCoverageEditor({
|
|||||||
{filteredGroups[activeNamespacePanel].map((key) => {
|
{filteredGroups[activeNamespacePanel].map((key) => {
|
||||||
const enVal = getEnglishValue(key);
|
const enVal = getEnglishValue(key);
|
||||||
const currentVal = getDisplayValue(key);
|
const currentVal = getDisplayValue(key);
|
||||||
|
const isGlobal = globalKeySet.has(key);
|
||||||
const visibleValue = activeLang === 'en'
|
const visibleValue = activeLang === 'en'
|
||||||
? currentVal
|
? currentVal
|
||||||
: (translations[activeLang]?.[key] ?? '');
|
: (translations[activeLang]?.[key] ?? '');
|
||||||
const hasOverride = (translations[activeLang]?.[key] ?? '') !== '';
|
const hasOverride = (translations[activeLang]?.[key] ?? '') !== '';
|
||||||
const isMissingInOpenedPanel =
|
const isMissingInOpenedPanel =
|
||||||
activeLang !== 'en' && (
|
activeLang !== 'en' &&
|
||||||
|
!isGlobal && (
|
||||||
visibleValue.trim() === '' ||
|
visibleValue.trim() === '' ||
|
||||||
visibleValue.trim() === enVal.trim()
|
visibleValue.trim() === enVal.trim()
|
||||||
);
|
);
|
||||||
@ -421,13 +423,28 @@ export default function TranslationCoverageEditor({
|
|||||||
<td className={`px-5 py-2 font-mono text-xs align-top pt-3 ${
|
<td className={`px-5 py-2 font-mono text-xs align-top pt-3 ${
|
||||||
isMissingInOpenedPanel ? 'text-red-700' : 'text-gray-500'
|
isMissingInOpenedPanel ? 'text-red-700' : 'text-gray-500'
|
||||||
}`}>
|
}`}>
|
||||||
<div className="flex items-start justify-between gap-2">
|
<div className="space-y-1.5">
|
||||||
<span>{key}</span>
|
<div className="flex items-center gap-1.5">
|
||||||
{globalKeySet.has(key) && (
|
<span className="block">{key}</span>
|
||||||
<span className="rounded-full border border-indigo-200 bg-indigo-50 px-1.5 py-0.5 text-[10px] font-semibold text-indigo-700">
|
{isGlobal && (
|
||||||
Global
|
<span className="rounded-full border border-indigo-200 bg-indigo-50 px-1.5 py-0.5 text-[10px] font-semibold text-indigo-700">
|
||||||
</span>
|
Global
|
||||||
)}
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<label className="inline-flex items-center gap-1.5 text-[11px] font-sans text-slate-600">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={isGlobal}
|
||||||
|
onChange={(e) => {
|
||||||
|
if (e.target.checked) {
|
||||||
|
addGlobalKey(key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
removeGlobalKey(key);
|
||||||
|
}}
|
||||||
|
className="h-3.5 w-3.5 rounded border-slate-300 text-[#1C2B4A] focus:ring-[#1C2B4A]"
|
||||||
|
/>{t('autofix.kb1cf599b')}</label>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
{activeLang !== 'en' && (
|
{activeLang !== 'en' && (
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useTranslation } from '../../../i18n/useTranslation';
|
import { useTranslation } from '../../../i18n/useTranslation';
|
||||||
import type { LanguageEntry } from '../hooks/useLanguageManagementTranslations';
|
import type { LanguageEntry } from '../hooks/useLanguageManagementTranslations';
|
||||||
|
import { useModalAnimation } from '../hooks/useModalAnimation';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@ -15,6 +16,8 @@ type Props = {
|
|||||||
wizardMarkGlobal: boolean;
|
wizardMarkGlobal: boolean;
|
||||||
setWizardMarkGlobal: (value: boolean) => void;
|
setWizardMarkGlobal: (value: boolean) => void;
|
||||||
englishValue: string;
|
englishValue: string;
|
||||||
|
addGlobalKey: (key: string) => void;
|
||||||
|
removeGlobalKey: (key: string) => void;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onPrevious: () => void;
|
onPrevious: () => void;
|
||||||
onSkip: () => void;
|
onSkip: () => void;
|
||||||
@ -33,18 +36,25 @@ export default function TranslationWizardModal({
|
|||||||
wizardMarkGlobal,
|
wizardMarkGlobal,
|
||||||
setWizardMarkGlobal,
|
setWizardMarkGlobal,
|
||||||
englishValue,
|
englishValue,
|
||||||
|
addGlobalKey,
|
||||||
|
removeGlobalKey,
|
||||||
onClose,
|
onClose,
|
||||||
onPrevious,
|
onPrevious,
|
||||||
onSkip,
|
onSkip,
|
||||||
onNext,
|
onNext,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { isRendered, isVisible } = useModalAnimation(isOpen && Boolean(currentWizardKey));
|
||||||
|
|
||||||
if (!isOpen || !currentWizardKey) return null;
|
if (!isRendered || !currentWizardKey) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-[120] flex items-center justify-center bg-black/45 backdrop-blur-sm">
|
<div className={`fixed inset-0 z-[120] flex items-center justify-center bg-black/45 backdrop-blur-sm transition-opacity duration-200 ${
|
||||||
<div className="mx-4 w-full max-w-2xl rounded-2xl border border-slate-200 bg-white shadow-2xl overflow-hidden">
|
isVisible ? 'opacity-100' : 'opacity-0'
|
||||||
|
}`}>
|
||||||
|
<div className={`mx-4 w-full max-w-2xl rounded-2xl border border-slate-200 bg-white shadow-2xl overflow-hidden transform transition-all duration-200 ${
|
||||||
|
isVisible ? 'opacity-100 translate-y-0 scale-100' : 'opacity-0 translate-y-2 scale-[0.98]'
|
||||||
|
}`}>
|
||||||
<div className="px-6 py-4 border-b border-slate-200 bg-slate-50 flex items-start justify-between gap-4">
|
<div className="px-6 py-4 border-b border-slate-200 bg-slate-50 flex items-start justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-lg font-bold text-[#1C2B4A]">{t('autofix.kcd190bdd')}</h2>
|
<h2 className="text-lg font-bold text-[#1C2B4A]">{t('autofix.kcd190bdd')}</h2>
|
||||||
@ -83,10 +93,19 @@ export default function TranslationWizardModal({
|
|||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
checked={wizardMarkGlobal}
|
checked={wizardMarkGlobal}
|
||||||
onChange={(e) => setWizardMarkGlobal(e.target.checked)}
|
onChange={(e) => {
|
||||||
|
const checked = e.target.checked;
|
||||||
|
setWizardMarkGlobal(checked);
|
||||||
|
if (!currentWizardKey) return;
|
||||||
|
if (checked) {
|
||||||
|
addGlobalKey(currentWizardKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
removeGlobalKey(currentWizardKey);
|
||||||
|
}}
|
||||||
className="h-4 w-4 rounded border-slate-300 text-[#1C2B4A] focus:ring-[#1C2B4A]"
|
className="h-4 w-4 rounded border-slate-300 text-[#1C2B4A] focus:ring-[#1C2B4A]"
|
||||||
/>
|
/>
|
||||||
Mark as global term (for shared words like IBAN)
|
Counts as global key (same value as English)
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -110,7 +129,7 @@ export default function TranslationWizardModal({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onNext}
|
onClick={onNext}
|
||||||
disabled={wizardInput.trim() === ''}
|
disabled={wizardInput.trim() === '' && !wizardMarkGlobal}
|
||||||
className="rounded-md bg-[#1C2B4A] text-white px-4 py-2 text-sm font-semibold hover:bg-[#1C2B4A]/90 disabled:opacity-50"
|
className="rounded-md bg-[#1C2B4A] text-white px-4 py-2 text-sm font-semibold hover:bg-[#1C2B4A]/90 disabled:opacity-50"
|
||||||
>
|
>
|
||||||
{wizardIndex >= wizardMissingCount - 1 ? 'Save and finish' : 'Save and next'}
|
{wizardIndex >= wizardMissingCount - 1 ? 'Save and finish' : 'Save and next'}
|
||||||
|
|||||||
@ -12,9 +12,10 @@ export type FileBackedI18nData = {
|
|||||||
|
|
||||||
type UseLanguageManagementTranslationsOptions = {
|
type UseLanguageManagementTranslationsOptions = {
|
||||||
coreLanguages: Set<string>;
|
coreLanguages: Set<string>;
|
||||||
|
onAction?: (notice: { variant: 'success' | 'error' | 'info' | 'warning'; message: string }) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useLanguageManagementTranslations({ coreLanguages }: UseLanguageManagementTranslationsOptions) {
|
export function useLanguageManagementTranslations({ coreLanguages, onAction }: UseLanguageManagementTranslationsOptions) {
|
||||||
const [data, setData] = useState<FileBackedI18nData>({ languages: [], translations: {} });
|
const [data, setData] = useState<FileBackedI18nData>({ languages: [], translations: {} });
|
||||||
const [isDirty, setIsDirty] = useState(false);
|
const [isDirty, setIsDirty] = useState(false);
|
||||||
const [saved, setSaved] = useState(false);
|
const [saved, setSaved] = useState(false);
|
||||||
@ -106,12 +107,15 @@ export function useLanguageManagementTranslations({ coreLanguages }: UseLanguage
|
|||||||
setData({ languages, translations });
|
setData({ languages, translations });
|
||||||
setIsDirty(false);
|
setIsDirty(false);
|
||||||
setSaved(true);
|
setSaved(true);
|
||||||
|
onAction?.({ variant: 'success', message: 'Translations saved successfully.' });
|
||||||
setTimeout(() => setSaved(false), 2500);
|
setTimeout(() => setSaved(false), 2500);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setSaveError(error instanceof Error ? error.message : 'Failed to save translation files.');
|
const message = error instanceof Error ? error.message : 'Failed to save translation files.';
|
||||||
|
setSaveError(message);
|
||||||
|
onAction?.({ variant: 'error', message });
|
||||||
setSaved(false);
|
setSaved(false);
|
||||||
}
|
}
|
||||||
}, [data.translations]);
|
}, [data.translations, onAction]);
|
||||||
|
|
||||||
const handleAddLanguage = useCallback(async () => {
|
const handleAddLanguage = useCallback(async () => {
|
||||||
const code = newCode.trim().toLowerCase();
|
const code = newCode.trim().toLowerCase();
|
||||||
@ -152,10 +156,13 @@ export function useLanguageManagementTranslations({ coreLanguages }: UseLanguage
|
|||||||
setActiveLang(code);
|
setActiveLang(code);
|
||||||
setIsDirty(false);
|
setIsDirty(false);
|
||||||
setSaved(false);
|
setSaved(false);
|
||||||
|
onAction?.({ variant: 'success', message: `Language ${name} (${code}) added successfully.` });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setAddError(error instanceof Error ? error.message : 'Failed to create language file.');
|
const message = error instanceof Error ? error.message : 'Failed to create language file.';
|
||||||
|
setAddError(message);
|
||||||
|
onAction?.({ variant: 'error', message });
|
||||||
}
|
}
|
||||||
}, [allLanguages, newCode, newName]);
|
}, [allLanguages, newCode, newName, onAction]);
|
||||||
|
|
||||||
const handleDeleteLanguage = useCallback(async (code: string) => {
|
const handleDeleteLanguage = useCallback(async (code: string) => {
|
||||||
if (coreLanguages.has(code)) return;
|
if (coreLanguages.has(code)) return;
|
||||||
@ -181,11 +188,14 @@ export function useLanguageManagementTranslations({ coreLanguages }: UseLanguage
|
|||||||
setIsDirty(false);
|
setIsDirty(false);
|
||||||
setSaved(false);
|
setSaved(false);
|
||||||
setDeleteTarget(null);
|
setDeleteTarget(null);
|
||||||
|
onAction?.({ variant: 'success', message: `Language ${code} deleted successfully.` });
|
||||||
if (activeLang === code) setActiveLang('en');
|
if (activeLang === code) setActiveLang('en');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setAddError(error instanceof Error ? error.message : 'Failed to delete language file.');
|
const message = error instanceof Error ? error.message : 'Failed to delete language file.';
|
||||||
|
setAddError(message);
|
||||||
|
onAction?.({ variant: 'error', message });
|
||||||
}
|
}
|
||||||
}, [activeLang, coreLanguages]);
|
}, [activeLang, coreLanguages, onAction]);
|
||||||
|
|
||||||
const isBuiltin = useCallback((code: string) => coreLanguages.has(code), [coreLanguages]);
|
const isBuiltin = useCallback((code: string) => coreLanguages.has(code), [coreLanguages]);
|
||||||
|
|
||||||
|
|||||||
34
src/app/admin/language-management/hooks/useModalAnimation.ts
Normal file
34
src/app/admin/language-management/hooks/useModalAnimation.ts
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
type UseModalAnimationResult = {
|
||||||
|
isRendered: boolean;
|
||||||
|
isVisible: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useModalAnimation(isOpen: boolean, durationMs = 220): UseModalAnimationResult {
|
||||||
|
const [isRendered, setIsRendered] = useState(isOpen);
|
||||||
|
const [isVisible, setIsVisible] = useState(isOpen);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
|
if (isOpen) {
|
||||||
|
setIsRendered(true);
|
||||||
|
const frameId = requestAnimationFrame(() => setIsVisible(true));
|
||||||
|
return () => cancelAnimationFrame(frameId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isRendered) {
|
||||||
|
setIsVisible(false);
|
||||||
|
timeoutId = setTimeout(() => {
|
||||||
|
setIsRendered(false);
|
||||||
|
}, durationMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (timeoutId) clearTimeout(timeoutId);
|
||||||
|
};
|
||||||
|
}, [isOpen, isRendered, durationMs]);
|
||||||
|
|
||||||
|
return { isRendered, isVisible };
|
||||||
|
}
|
||||||
@ -1,7 +1,4 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
|
||||||
const CATEGORY_LAYOUT_STORAGE_KEY = 'pp_i18n_category_layout_v1';
|
|
||||||
const GLOBAL_KEYS_STORAGE_KEY = 'pp_i18n_global_keys_v1';
|
|
||||||
|
|
||||||
type NamespaceCategorySeed = { label: string; namespaces: string[] };
|
type NamespaceCategorySeed = { label: string; namespaces: string[] };
|
||||||
|
|
||||||
@ -32,16 +29,44 @@ type UseNamespaceCategoriesOptions = {
|
|||||||
namespaces: string[];
|
namespaces: string[];
|
||||||
allKeys: string[];
|
allKeys: string[];
|
||||||
defaultCategories: NamespaceCategorySeed[];
|
defaultCategories: NamespaceCategorySeed[];
|
||||||
|
onAction?: (notice: { variant: 'success' | 'error' | 'info' | 'warning'; message: string }) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useNamespaceCategories({ namespaces, allKeys, defaultCategories }: UseNamespaceCategoriesOptions) {
|
function normalizeCategories(value: unknown): NamespaceCategory[] {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
|
||||||
|
return value
|
||||||
|
.filter((c): c is { id: string; label: string; namespaces: string[]; isCustom: boolean } => {
|
||||||
|
return Boolean(c) && typeof c === 'object' && typeof c.id === 'string' && typeof c.label === 'string';
|
||||||
|
})
|
||||||
|
.map((c) => ({
|
||||||
|
id: c.id,
|
||||||
|
label: c.label,
|
||||||
|
namespaces: Array.isArray(c.namespaces) ? c.namespaces.filter((ns): ns is string => typeof ns === 'string') : [],
|
||||||
|
isCustom: Boolean(c.isCustom),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeGlobalKeys(value: unknown): string[] {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
return value.filter((k): k is string => typeof k === 'string');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useNamespaceCategories({ namespaces, allKeys, defaultCategories, onAction }: UseNamespaceCategoriesOptions) {
|
||||||
|
const fallbackCategories = useMemo(() => createDefaultCategories(defaultCategories), [defaultCategories]);
|
||||||
|
const skipFirstPersistRef = useRef(true);
|
||||||
|
const onActionRef = useRef(onAction);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onActionRef.current = onAction;
|
||||||
|
}, [onAction]);
|
||||||
|
|
||||||
const [activeCategory, setActiveCategory] = useState<string>('all');
|
const [activeCategory, setActiveCategory] = useState<string>('all');
|
||||||
const [showCategoryManagerModal, setShowCategoryManagerModal] = useState(false);
|
const [showCategoryManagerModal, setShowCategoryManagerModal] = useState(false);
|
||||||
const [categories, setCategories] = useState<NamespaceCategory[]>(() => createDefaultCategories(defaultCategories));
|
const [categories, setCategories] = useState<NamespaceCategory[]>(fallbackCategories);
|
||||||
const [categoriesHydrated, setCategoriesHydrated] = useState(false);
|
|
||||||
|
|
||||||
const [globalKeys, setGlobalKeys] = useState<string[]>([]);
|
const [globalKeys, setGlobalKeys] = useState<string[]>([]);
|
||||||
const [globalKeysHydrated, setGlobalKeysHydrated] = useState(false);
|
const [preferencesHydrated, setPreferencesHydrated] = useState(false);
|
||||||
|
|
||||||
const [newCategoryLabel, setNewCategoryLabel] = useState('');
|
const [newCategoryLabel, setNewCategoryLabel] = useState('');
|
||||||
const [assignNamespaceByCategory, setAssignNamespaceByCategory] = useState<Record<string, string>>({});
|
const [assignNamespaceByCategory, setAssignNamespaceByCategory] = useState<Record<string, string>>({});
|
||||||
@ -49,55 +74,82 @@ export function useNamespaceCategories({ namespaces, allKeys, defaultCategories
|
|||||||
const [dragNamespace, setDragNamespace] = useState<string | null>(null);
|
const [dragNamespace, setDragNamespace] = useState<string | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (typeof window !== 'undefined') {
|
let cancelled = false;
|
||||||
|
|
||||||
|
const loadPreferences = async () => {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(CATEGORY_LAYOUT_STORAGE_KEY);
|
const response = await fetch('/api/i18n/preferences', { cache: 'no-store' });
|
||||||
if (raw) {
|
const result = await response.json().catch(() => null);
|
||||||
const parsed = JSON.parse(raw) as Array<{ id: string; label: string; namespaces: string[]; isCustom: boolean }>;
|
|
||||||
if (Array.isArray(parsed) && parsed.length > 0) {
|
if (!response.ok || !result?.ok) {
|
||||||
const normalized = parsed
|
throw new Error(result?.message || 'Failed to load language preferences.');
|
||||||
.filter((c) => c && typeof c.id === 'string' && typeof c.label === 'string')
|
|
||||||
.map((c) => ({
|
|
||||||
id: c.id,
|
|
||||||
label: c.label,
|
|
||||||
namespaces: Array.isArray(c.namespaces) ? c.namespaces : [],
|
|
||||||
isCustom: Boolean(c.isCustom),
|
|
||||||
}));
|
|
||||||
if (normalized.length > 0) setCategories(normalized);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawGlobalKeys = localStorage.getItem(GLOBAL_KEYS_STORAGE_KEY);
|
if (cancelled) return;
|
||||||
if (rawGlobalKeys) {
|
|
||||||
const parsedGlobalKeys = JSON.parse(rawGlobalKeys) as unknown;
|
const payload = result.preferences && typeof result.preferences === 'object'
|
||||||
if (Array.isArray(parsedGlobalKeys)) {
|
? result.preferences
|
||||||
const normalizedGlobalKeys = parsedGlobalKeys.filter((k): k is string => typeof k === 'string');
|
: result;
|
||||||
setGlobalKeys(normalizedGlobalKeys);
|
|
||||||
}
|
const loadedCategories = normalizeCategories(payload?.categories);
|
||||||
|
const loadedGlobalKeys = normalizeGlobalKeys(payload?.globalKeys);
|
||||||
|
|
||||||
|
setCategories(loadedCategories.length > 0 ? loadedCategories : fallbackCategories);
|
||||||
|
setGlobalKeys(loadedGlobalKeys);
|
||||||
|
} catch (error) {
|
||||||
|
if (!cancelled) {
|
||||||
|
setCategories(fallbackCategories);
|
||||||
|
setGlobalKeys([]);
|
||||||
|
onActionRef.current?.({
|
||||||
|
variant: 'warning',
|
||||||
|
message: error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: 'Failed to load language preferences from backend.',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} catch {
|
|
||||||
// Ignore corrupted local storage.
|
|
||||||
} finally {
|
} finally {
|
||||||
setCategoriesHydrated(true);
|
if (!cancelled) setPreferencesHydrated(true);
|
||||||
setGlobalKeysHydrated(true);
|
|
||||||
}
|
}
|
||||||
} else {
|
};
|
||||||
setCategoriesHydrated(true);
|
|
||||||
setGlobalKeysHydrated(true);
|
void loadPreferences();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [fallbackCategories]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!preferencesHydrated) return;
|
||||||
|
if (skipFirstPersistRef.current) {
|
||||||
|
skipFirstPersistRef.current = false;
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
const timeoutId = setTimeout(async () => {
|
||||||
if (typeof window === 'undefined') return;
|
try {
|
||||||
if (!categoriesHydrated) return;
|
const response = await fetch('/api/i18n/preferences', {
|
||||||
localStorage.setItem(CATEGORY_LAYOUT_STORAGE_KEY, JSON.stringify(categories));
|
method: 'PUT',
|
||||||
}, [categories, categoriesHydrated]);
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ categories, globalKeys }),
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
const result = await response.json().catch(() => null);
|
||||||
if (typeof window === 'undefined') return;
|
if (!response.ok || !result?.ok) {
|
||||||
if (!globalKeysHydrated) return;
|
throw new Error(result?.message || 'Failed to save language preferences.');
|
||||||
localStorage.setItem(GLOBAL_KEYS_STORAGE_KEY, JSON.stringify(globalKeys));
|
}
|
||||||
}, [globalKeys, globalKeysHydrated]);
|
} catch (error) {
|
||||||
|
onActionRef.current?.({
|
||||||
|
variant: 'error',
|
||||||
|
message: error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: 'Failed to save language preferences.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, 350);
|
||||||
|
|
||||||
|
return () => clearTimeout(timeoutId);
|
||||||
|
}, [categories, globalKeys, preferencesHydrated]);
|
||||||
|
|
||||||
const categoriesWithKnownNamespaces = useMemo(() => {
|
const categoriesWithKnownNamespaces = useMemo(() => {
|
||||||
const namespaceSet = new Set(namespaces);
|
const namespaceSet = new Set(namespaces);
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import PageLayout from '../../components/PageLayout';
|
import PageLayout from '../../components/PageLayout';
|
||||||
import TranslationWizardModal from './components/TranslationWizardModal';
|
import TranslationWizardModal from './components/TranslationWizardModal';
|
||||||
@ -13,6 +13,7 @@ import LanguageManagementTopSection from './components/LanguageManagementTopSect
|
|||||||
import { useI18nScanWorkflow } from './hooks/useI18nScanWorkflow';
|
import { useI18nScanWorkflow } from './hooks/useI18nScanWorkflow';
|
||||||
import { useLanguageManagementTranslations } from './hooks/useLanguageManagementTranslations';
|
import { useLanguageManagementTranslations } from './hooks/useLanguageManagementTranslations';
|
||||||
import { useNamespaceCategories } from './hooks/useNamespaceCategories';
|
import { useNamespaceCategories } from './hooks/useNamespaceCategories';
|
||||||
|
import { useToast } from '../../components/toast/toastComponent';
|
||||||
import {
|
import {
|
||||||
getAllTranslationKeys,
|
getAllTranslationKeys,
|
||||||
getEnglishValue,
|
getEnglishValue,
|
||||||
@ -45,6 +46,15 @@ function groupKeys(keys: string[]): Record<string, string[]> {
|
|||||||
export default function LanguageManagementPage() {
|
export default function LanguageManagementPage() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { showToast } = useToast();
|
||||||
|
|
||||||
|
const notifyAction = useCallback((notice: { variant: 'success' | 'error' | 'info' | 'warning'; message: string }) => {
|
||||||
|
showToast({
|
||||||
|
variant: notice.variant,
|
||||||
|
message: notice.message,
|
||||||
|
duration: notice.variant === 'error' ? 6000 : 3500,
|
||||||
|
});
|
||||||
|
}, [showToast]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
showScanModal,
|
showScanModal,
|
||||||
@ -94,7 +104,10 @@ export default function LanguageManagementPage() {
|
|||||||
setDeleteTarget,
|
setDeleteTarget,
|
||||||
handleDeleteLanguage,
|
handleDeleteLanguage,
|
||||||
isBuiltin,
|
isBuiltin,
|
||||||
} = useLanguageManagementTranslations({ coreLanguages: CORE_LANGUAGES });
|
} = useLanguageManagementTranslations({
|
||||||
|
coreLanguages: CORE_LANGUAGES,
|
||||||
|
onAction: notifyAction,
|
||||||
|
});
|
||||||
|
|
||||||
const [showTranslationWizard, setShowTranslationWizard] = useState(false);
|
const [showTranslationWizard, setShowTranslationWizard] = useState(false);
|
||||||
const [wizardIndex, setWizardIndex] = useState(0);
|
const [wizardIndex, setWizardIndex] = useState(0);
|
||||||
@ -102,6 +115,8 @@ export default function LanguageManagementPage() {
|
|||||||
const [wizardMarkGlobal, setWizardMarkGlobal] = useState(false);
|
const [wizardMarkGlobal, setWizardMarkGlobal] = useState(false);
|
||||||
|
|
||||||
const [newGlobalKeySelection, setNewGlobalKeySelection] = useState('');
|
const [newGlobalKeySelection, setNewGlobalKeySelection] = useState('');
|
||||||
|
const [reloadAfterScanClose, setReloadAfterScanClose] = useState(false);
|
||||||
|
const [pendingAutoFixResult, setPendingAutoFixResult] = useState(false);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
activeCategory,
|
activeCategory,
|
||||||
@ -126,7 +141,12 @@ export default function LanguageManagementPage() {
|
|||||||
globalKeySet,
|
globalKeySet,
|
||||||
addGlobalKey,
|
addGlobalKey,
|
||||||
removeGlobalKey,
|
removeGlobalKey,
|
||||||
} = useNamespaceCategories({ namespaces, allKeys, defaultCategories: NAMESPACE_CATEGORIES });
|
} = useNamespaceCategories({
|
||||||
|
namespaces,
|
||||||
|
allKeys,
|
||||||
|
defaultCategories: NAMESPACE_CATEGORIES,
|
||||||
|
onAction: notifyAction,
|
||||||
|
});
|
||||||
|
|
||||||
// ── search / filter
|
// ── search / filter
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
@ -199,6 +219,15 @@ export default function LanguageManagementPage() {
|
|||||||
|
|
||||||
const totalKeys = allKeys.length;
|
const totalKeys = allKeys.length;
|
||||||
|
|
||||||
|
const isMissingForLanguage = (key: string, languageCode: string) => {
|
||||||
|
if (languageCode === 'en') return false;
|
||||||
|
if (globalKeySet.has(key)) return false;
|
||||||
|
|
||||||
|
const value = (data.translations[languageCode]?.[key] ?? '').trim();
|
||||||
|
const englishValue = getEnglishValue(key).trim();
|
||||||
|
return value === '' || value === englishValue;
|
||||||
|
};
|
||||||
|
|
||||||
const namespaceTranslationStats = useMemo(() => {
|
const namespaceTranslationStats = useMemo(() => {
|
||||||
const stats: Record<string, { total: number; translated: number; missing: number }> = {};
|
const stats: Record<string, { total: number; translated: number; missing: number }> = {};
|
||||||
|
|
||||||
@ -210,18 +239,14 @@ export default function LanguageManagementPage() {
|
|||||||
if (activeLang === 'en') {
|
if (activeLang === 'en') {
|
||||||
translated = total;
|
translated = total;
|
||||||
} else {
|
} else {
|
||||||
translated = keys.filter((k) => {
|
translated = keys.filter((k) => !isMissingForLanguage(k, activeLang)).length;
|
||||||
const visibleValue = data.translations[activeLang]?.[k] ?? '';
|
|
||||||
const englishValue = getEnglishValue(k);
|
|
||||||
return visibleValue.trim() !== '' && visibleValue.trim() !== englishValue.trim();
|
|
||||||
}).length;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stats[ns] = { total, translated, missing: Math.max(total - translated, 0) };
|
stats[ns] = { total, translated, missing: Math.max(total - translated, 0) };
|
||||||
}
|
}
|
||||||
|
|
||||||
return stats;
|
return stats;
|
||||||
}, [namespaces, keyGroups, activeLang, data.translations]);
|
}, [namespaces, keyGroups, activeLang, data.translations, globalKeySet]);
|
||||||
|
|
||||||
const allTabStats = useMemo(() => {
|
const allTabStats = useMemo(() => {
|
||||||
return Object.values(namespaceTranslationStats).reduce(
|
return Object.values(namespaceTranslationStats).reduce(
|
||||||
@ -259,11 +284,8 @@ export default function LanguageManagementPage() {
|
|||||||
|
|
||||||
const wizardMissingKeys = useMemo(() => {
|
const wizardMissingKeys = useMemo(() => {
|
||||||
if (activeLang === 'en') return [] as string[];
|
if (activeLang === 'en') return [] as string[];
|
||||||
return allKeys.filter((k) => {
|
return allKeys.filter((k) => isMissingForLanguage(k, activeLang));
|
||||||
const v = getDisplayValue(k);
|
}, [activeLang, allKeys, data.translations, globalKeySet]);
|
||||||
return v === '' || v === getEnglishValue(k);
|
|
||||||
});
|
|
||||||
}, [activeLang, allKeys, getDisplayValue]);
|
|
||||||
|
|
||||||
const currentWizardKey = showTranslationWizard ? wizardMissingKeys[wizardIndex] ?? null : null;
|
const currentWizardKey = showTranslationWizard ? wizardMissingKeys[wizardIndex] ?? null : null;
|
||||||
|
|
||||||
@ -282,21 +304,9 @@ export default function LanguageManagementPage() {
|
|||||||
|
|
||||||
const globalTabStats = useMemo(() => {
|
const globalTabStats = useMemo(() => {
|
||||||
const total = globalKnownKeys.length;
|
const total = globalKnownKeys.length;
|
||||||
if (total === 0) return { total: 0, translated: 0, missing: 0 };
|
// Global keys are intentionally the same across languages — never count as missing
|
||||||
|
return { total, translated: total, missing: 0 };
|
||||||
let translated = 0;
|
}, [globalKnownKeys]);
|
||||||
if (activeLang === 'en') {
|
|
||||||
translated = total;
|
|
||||||
} else {
|
|
||||||
translated = globalKnownKeys.filter((k) => {
|
|
||||||
const visibleValue = data.translations[activeLang]?.[k] ?? '';
|
|
||||||
const englishValue = getEnglishValue(k);
|
|
||||||
return visibleValue.trim() !== '' && visibleValue.trim() !== englishValue.trim();
|
|
||||||
}).length;
|
|
||||||
}
|
|
||||||
|
|
||||||
return { total, translated, missing: Math.max(total - translated, 0) };
|
|
||||||
}, [globalKnownKeys, activeLang, data.translations]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!showTranslationWizard) return;
|
if (!showTranslationWizard) return;
|
||||||
@ -316,7 +326,16 @@ export default function LanguageManagementPage() {
|
|||||||
|
|
||||||
const saveCurrentWizardValue = () => {
|
const saveCurrentWizardValue = () => {
|
||||||
if (!currentWizardKey) return;
|
if (!currentWizardKey) return;
|
||||||
handleChange(currentWizardKey, wizardInput.trim());
|
|
||||||
|
const trimmedWizardInput = wizardInput.trim();
|
||||||
|
const englishValue = getEnglishValue(currentWizardKey).trim();
|
||||||
|
|
||||||
|
// Global keys intentionally reuse the source term and don't require a local override.
|
||||||
|
const nextValue = wizardMarkGlobal && trimmedWizardInput === englishValue
|
||||||
|
? ''
|
||||||
|
: trimmedWizardInput;
|
||||||
|
|
||||||
|
handleChange(currentWizardKey, nextValue);
|
||||||
if (wizardMarkGlobal) {
|
if (wizardMarkGlobal) {
|
||||||
addGlobalKey(currentWizardKey);
|
addGlobalKey(currentWizardKey);
|
||||||
} else {
|
} else {
|
||||||
@ -369,6 +388,47 @@ export default function LanguageManagementPage() {
|
|||||||
languageManagementHeaderRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
languageManagementHeaderRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pendingAutoFixResult || !workspaceScan) return;
|
||||||
|
|
||||||
|
const changedFiles = workspaceScan.changedFileCount ?? 0;
|
||||||
|
const createdKeys = workspaceScan.createdKeyCount ?? 0;
|
||||||
|
if (changedFiles > 0 || createdKeys > 0) {
|
||||||
|
setReloadAfterScanClose(true);
|
||||||
|
showToast({
|
||||||
|
variant: 'success',
|
||||||
|
message: `Auto-fix finished: ${changedFiles} files updated, ${createdKeys} keys created.`,
|
||||||
|
duration: 4200,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setPendingAutoFixResult(false);
|
||||||
|
}, [pendingAutoFixResult, workspaceScan, showToast]);
|
||||||
|
|
||||||
|
const handleRunFixSelected = async () => {
|
||||||
|
setPendingAutoFixResult(true);
|
||||||
|
await runFixSelected();
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeScanModal = () => {
|
||||||
|
setShowScanModal(false);
|
||||||
|
if (!reloadAfterScanClose) return;
|
||||||
|
|
||||||
|
showToast({
|
||||||
|
variant: 'info',
|
||||||
|
message: 'Reloading page to refresh namespace and key updates from auto-fix output.',
|
||||||
|
duration: 1800,
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
}, 260);
|
||||||
|
|
||||||
|
setReloadAfterScanClose(false);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageLayout contentClassName="flex-1 relative w-full">
|
<PageLayout contentClassName="flex-1 relative w-full">
|
||||||
<div className="mx-auto max-w-7xl px-4 py-8 space-y-6">
|
<div className="mx-auto max-w-7xl px-4 py-8 space-y-6">
|
||||||
@ -457,6 +517,8 @@ export default function LanguageManagementPage() {
|
|||||||
wizardMarkGlobal={wizardMarkGlobal}
|
wizardMarkGlobal={wizardMarkGlobal}
|
||||||
setWizardMarkGlobal={setWizardMarkGlobal}
|
setWizardMarkGlobal={setWizardMarkGlobal}
|
||||||
englishValue={currentWizardKey ? getEnglishValue(currentWizardKey) : ''}
|
englishValue={currentWizardKey ? getEnglishValue(currentWizardKey) : ''}
|
||||||
|
addGlobalKey={addGlobalKey}
|
||||||
|
removeGlobalKey={removeGlobalKey}
|
||||||
onClose={() => setShowTranslationWizard(false)}
|
onClose={() => setShowTranslationWizard(false)}
|
||||||
onPrevious={goToPreviousWizardStep}
|
onPrevious={goToPreviousWizardStep}
|
||||||
onSkip={skipWizardStep}
|
onSkip={skipWizardStep}
|
||||||
@ -504,7 +566,7 @@ export default function LanguageManagementPage() {
|
|||||||
|
|
||||||
<ScanResultsModal
|
<ScanResultsModal
|
||||||
isOpen={showScanModal}
|
isOpen={showScanModal}
|
||||||
onClose={() => setShowScanModal(false)}
|
onClose={closeScanModal}
|
||||||
lastScanTime={lastScanTime}
|
lastScanTime={lastScanTime}
|
||||||
workspaceScan={workspaceScan}
|
workspaceScan={workspaceScan}
|
||||||
totalKeys={totalKeys}
|
totalKeys={totalKeys}
|
||||||
@ -522,7 +584,7 @@ export default function LanguageManagementPage() {
|
|||||||
onSelectAll={selectAllFiles}
|
onSelectAll={selectAllFiles}
|
||||||
onClear={clearSelectedFiles}
|
onClear={clearSelectedFiles}
|
||||||
onToggleForceConvertToClient={() => setForceConvertToClient((prev) => !prev)}
|
onToggleForceConvertToClient={() => setForceConvertToClient((prev) => !prev)}
|
||||||
onRunFixSelected={runFixSelected}
|
onRunFixSelected={handleRunFixSelected}
|
||||||
/>
|
/>
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
);
|
);
|
||||||
|
|||||||
227
src/app/api/_utils/backendAuth.ts
Normal file
227
src/app/api/_utils/backendAuth.ts
Normal file
@ -0,0 +1,227 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
type BackendAuthPayload = {
|
||||||
|
user?: {
|
||||||
|
id?: string;
|
||||||
|
role?: string;
|
||||||
|
roles?: string[];
|
||||||
|
isAdmin?: boolean;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
role?: string;
|
||||||
|
roles?: string[];
|
||||||
|
isAdmin?: boolean;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
type BackendSessionResult = {
|
||||||
|
ok: boolean;
|
||||||
|
status: number;
|
||||||
|
payload: BackendAuthPayload | null;
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type BackendTokenResult = {
|
||||||
|
ok: boolean;
|
||||||
|
status: number;
|
||||||
|
accessToken: string | null;
|
||||||
|
setCookies: string[];
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function splitSetCookieHeader(header: string): string[] {
|
||||||
|
const parts: string[] = [];
|
||||||
|
let start = 0;
|
||||||
|
let inExpires = false;
|
||||||
|
|
||||||
|
for (let i = 0; i < header.length; i += 1) {
|
||||||
|
const lower = header.slice(i, i + 8).toLowerCase();
|
||||||
|
if (lower === 'expires=') inExpires = true;
|
||||||
|
if (inExpires && header[i] === ';') inExpires = false;
|
||||||
|
if (!inExpires && header[i] === ',') {
|
||||||
|
parts.push(header.slice(start, i).trim());
|
||||||
|
start = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const last = header.slice(start).trim();
|
||||||
|
if (last) parts.push(last);
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readSetCookies(response: Response): string[] {
|
||||||
|
const anyHeaders = response.headers as unknown as { getSetCookie?: () => string[] };
|
||||||
|
if (typeof anyHeaders.getSetCookie === 'function') {
|
||||||
|
return anyHeaders.getSetCookie();
|
||||||
|
}
|
||||||
|
|
||||||
|
const single = response.headers.get('set-cookie');
|
||||||
|
return single ? splitSetCookieHeader(single) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveBackendAuthPath(): string {
|
||||||
|
const configured = process.env.BACKEND_AUTH_VALIDATE_PATH?.trim();
|
||||||
|
if (configured) return configured.startsWith('/') ? configured : `/${configured}`;
|
||||||
|
return '/api/auth/validate';
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveBackendBaseUrl(): string | null {
|
||||||
|
const value = process.env.NEXT_PUBLIC_API_BASE_URL?.trim();
|
||||||
|
return value || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveBackendRefreshPath(): string {
|
||||||
|
const configured = process.env.BACKEND_REFRESH_PATH?.trim();
|
||||||
|
if (configured) return configured.startsWith('/') ? configured : `/${configured}`;
|
||||||
|
return '/api/refresh';
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasAdminRole(payload: BackendAuthPayload | null): boolean {
|
||||||
|
if (!payload) return false;
|
||||||
|
|
||||||
|
const roleCandidates = [
|
||||||
|
payload.role,
|
||||||
|
payload.user?.role,
|
||||||
|
...(Array.isArray(payload.roles) ? payload.roles : []),
|
||||||
|
...(Array.isArray(payload.user?.roles) ? payload.user.roles : []),
|
||||||
|
]
|
||||||
|
.map((v) => String(v ?? '').toLowerCase())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
const explicitAdminFlag = Boolean(payload.isAdmin) || Boolean(payload.user?.isAdmin);
|
||||||
|
return explicitAdminFlag || roleCandidates.includes('admin') || roleCandidates.includes('superadmin');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchBackendSession(request: Request): Promise<BackendSessionResult> {
|
||||||
|
const apiBase = resolveBackendBaseUrl();
|
||||||
|
if (!apiBase) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
payload: null,
|
||||||
|
message: 'Missing NEXT_PUBLIC_API_BASE_URL.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const cookie = request.headers.get('cookie') ?? '';
|
||||||
|
const authPath = resolveBackendAuthPath();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${apiBase}${authPath}`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
cookie,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
cache: 'no-store',
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = (await response.json().catch(() => null)) as BackendAuthPayload | null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: response.ok,
|
||||||
|
status: response.status,
|
||||||
|
payload,
|
||||||
|
message: !response.ok
|
||||||
|
? (payload && typeof payload.message === 'string' ? payload.message : 'Authentication failed.')
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 502,
|
||||||
|
payload: null,
|
||||||
|
message: 'Failed to reach backend auth endpoint.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchBackendAccessToken(request: Request): Promise<BackendTokenResult> {
|
||||||
|
const apiBase = resolveBackendBaseUrl();
|
||||||
|
if (!apiBase) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
accessToken: null,
|
||||||
|
setCookies: [],
|
||||||
|
message: 'Missing NEXT_PUBLIC_API_BASE_URL.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const cookie = request.headers.get('cookie') ?? '';
|
||||||
|
const refreshPath = resolveBackendRefreshPath();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${apiBase}${refreshPath}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
cookie,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
cache: 'no-store',
|
||||||
|
});
|
||||||
|
|
||||||
|
const setCookies = readSetCookies(response);
|
||||||
|
const payload = (await response.json().catch(() => null)) as { accessToken?: string; message?: string } | null;
|
||||||
|
const accessToken = typeof payload?.accessToken === 'string' ? payload.accessToken : null;
|
||||||
|
|
||||||
|
if (!response.ok || !accessToken) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: response.status,
|
||||||
|
accessToken: null,
|
||||||
|
setCookies,
|
||||||
|
message: payload?.message ?? 'Failed to refresh backend access token.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: response.status,
|
||||||
|
accessToken,
|
||||||
|
setCookies,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 502,
|
||||||
|
accessToken: null,
|
||||||
|
setCookies: [],
|
||||||
|
message: 'Failed to reach backend refresh endpoint.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requireAdminSession(request: Request): Promise<{ ok: true; payload: BackendAuthPayload | null } | { ok: false; response: NextResponse }> {
|
||||||
|
const session = await fetchBackendSession(request);
|
||||||
|
if (!session.ok) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json(
|
||||||
|
{ ok: false, message: session.message ?? 'Unauthorized.' },
|
||||||
|
{ status: session.status === 401 ? 401 : 403 }
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasAdminRole(session.payload)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json(
|
||||||
|
{ ok: false, message: 'Admin access required.' },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: true, payload: session.payload };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extractAdminState(payload: BackendAuthPayload | null): { authenticated: boolean; isAdmin: boolean; user: BackendAuthPayload['user'] | null } {
|
||||||
|
const authenticated = Boolean(payload);
|
||||||
|
return {
|
||||||
|
authenticated,
|
||||||
|
isAdmin: hasAdminRole(payload),
|
||||||
|
user: payload?.user ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
28
src/app/api/auth/validate/route.ts
Normal file
28
src/app/api/auth/validate/route.ts
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { extractAdminState, fetchBackendSession } from '../../_utils/backendAuth';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const session = await fetchBackendSession(request);
|
||||||
|
|
||||||
|
if (!session.ok) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
ok: false,
|
||||||
|
authenticated: false,
|
||||||
|
isAdmin: false,
|
||||||
|
user: null,
|
||||||
|
message: session.message ?? 'Unauthorized.',
|
||||||
|
},
|
||||||
|
{ status: session.status }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = extractAdminState(session.payload);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
ok: true,
|
||||||
|
...state,
|
||||||
|
});
|
||||||
|
}
|
||||||
94
src/app/api/i18n/preferences/route.ts
Normal file
94
src/app/api/i18n/preferences/route.ts
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { fetchBackendAccessToken, requireAdminSession } from '../../_utils/backendAuth';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
|
||||||
|
function resolvePreferencesBackendPath(): string {
|
||||||
|
const configured = process.env.BACKEND_I18N_PREFERENCES_PATH?.trim();
|
||||||
|
if (configured) return configured.startsWith('/') ? configured : `/${configured}`;
|
||||||
|
return '/api/admin/i18n/preferences';
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveBackendBaseUrl(): string | null {
|
||||||
|
const value = process.env.NEXT_PUBLIC_API_BASE_URL?.trim();
|
||||||
|
return value || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function proxyPreferencesRequest(request: Request, method: 'GET' | 'POST' | 'PUT' | 'DELETE') {
|
||||||
|
const access = await requireAdminSession(request);
|
||||||
|
if (!access.ok) return access.response;
|
||||||
|
|
||||||
|
const tokenResult = await fetchBackendAccessToken(request);
|
||||||
|
if (!tokenResult.ok || !tokenResult.accessToken) {
|
||||||
|
const denied = NextResponse.json(
|
||||||
|
{ ok: false, message: tokenResult.message ?? 'Unable to obtain backend access token.' },
|
||||||
|
{ status: tokenResult.status === 401 ? 401 : 403 }
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const setCookie of tokenResult.setCookies) {
|
||||||
|
denied.headers.append('set-cookie', setCookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
return denied;
|
||||||
|
}
|
||||||
|
|
||||||
|
const apiBase = resolveBackendBaseUrl();
|
||||||
|
if (!apiBase) {
|
||||||
|
return NextResponse.json({ ok: false, message: 'Missing NEXT_PUBLIC_API_BASE_URL.' }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const cookie = request.headers.get('cookie') ?? '';
|
||||||
|
const backendPath = resolvePreferencesBackendPath();
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
cookie,
|
||||||
|
Authorization: `Bearer ${tokenResult.accessToken}`,
|
||||||
|
};
|
||||||
|
let body: string | undefined;
|
||||||
|
|
||||||
|
if (method !== 'GET' && method !== 'DELETE') {
|
||||||
|
const payload = await request.json().catch(() => ({}));
|
||||||
|
body = JSON.stringify(payload ?? {});
|
||||||
|
headers['Content-Type'] = 'application/json';
|
||||||
|
}
|
||||||
|
|
||||||
|
const backendResponse = await fetch(`${apiBase}${backendPath}`, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
cache: 'no-store',
|
||||||
|
}).catch(() => null);
|
||||||
|
|
||||||
|
if (!backendResponse) {
|
||||||
|
const failed = NextResponse.json({ ok: false, message: 'Preferences backend is unreachable.' }, { status: 502 });
|
||||||
|
for (const setCookie of tokenResult.setCookies) {
|
||||||
|
failed.headers.append('set-cookie', setCookie);
|
||||||
|
}
|
||||||
|
return failed;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = await backendResponse.json().catch(() => null);
|
||||||
|
const out = NextResponse.json(payload ?? { ok: backendResponse.ok }, { status: backendResponse.status });
|
||||||
|
|
||||||
|
for (const setCookie of tokenResult.setCookies) {
|
||||||
|
out.headers.append('set-cookie', setCookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
return proxyPreferencesRequest(request, 'GET');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
return proxyPreferencesRequest(request, 'POST');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(request: Request) {
|
||||||
|
return proxyPreferencesRequest(request, 'PUT');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(request: Request) {
|
||||||
|
return proxyPreferencesRequest(request, 'DELETE');
|
||||||
|
}
|
||||||
@ -4,6 +4,7 @@ import path from 'path';
|
|||||||
|
|
||||||
import { en } from '@/app/i18n/translations/en';
|
import { en } from '@/app/i18n/translations/en';
|
||||||
import { flattenObject } from '@/app/i18n/dynamicTranslations';
|
import { flattenObject } from '@/app/i18n/dynamicTranslations';
|
||||||
|
import { requireAdminSession } from '../../_utils/backendAuth';
|
||||||
|
|
||||||
const EXCLUDED_DIRS = new Set([
|
const EXCLUDED_DIRS = new Set([
|
||||||
'.git',
|
'.git',
|
||||||
@ -673,7 +674,10 @@ async function runWorkspaceScan(): Promise<ScanResult> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(request: Request) {
|
||||||
|
const access = await requireAdminSession(request);
|
||||||
|
if (!access.ok) return access.response;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await runWorkspaceScan();
|
const result = await runWorkspaceScan();
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
@ -694,6 +698,9 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
const access = await requireAdminSession(request);
|
||||||
|
if (!access.ok) return access.response;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let targetFilesSet: Set<string> | undefined;
|
let targetFilesSet: Set<string> | undefined;
|
||||||
let forceConvertToClient = false;
|
let forceConvertToClient = false;
|
||||||
|
|||||||
@ -3,6 +3,7 @@ import { promises as fs } from 'fs';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
import { flattenObject, unflattenObject } from '@/app/i18n/dynamicTranslations';
|
import { flattenObject, unflattenObject } from '@/app/i18n/dynamicTranslations';
|
||||||
|
import { requireAdminSession } from '../../_utils/backendAuth';
|
||||||
|
|
||||||
const TRANSLATIONS_DIR = path.join(process.cwd(), 'src', 'app', 'i18n', 'translations');
|
const TRANSLATIONS_DIR = path.join(process.cwd(), 'src', 'app', 'i18n', 'translations');
|
||||||
const CORE_LANGUAGE_CODES = new Set(['en', 'de']);
|
const CORE_LANGUAGE_CODES = new Set(['en', 'de']);
|
||||||
@ -203,7 +204,10 @@ async function writeLanguageFile(
|
|||||||
await fs.writeFile(filePath, content, 'utf8');
|
await fs.writeFile(filePath, content, 'utf8');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(request: Request) {
|
||||||
|
const access = await requireAdminSession(request);
|
||||||
|
if (!access.ok) return access.response;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await readAllTranslations();
|
const data = await readAllTranslations();
|
||||||
return NextResponse.json({ ok: true, ...data });
|
return NextResponse.json({ ok: true, ...data });
|
||||||
@ -216,6 +220,9 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
const access = await requireAdminSession(request);
|
||||||
|
if (!access.ok) return access.response;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json().catch(() => ({}));
|
const body = await request.json().catch(() => ({}));
|
||||||
const code = String(body?.code ?? '').trim().toLowerCase();
|
const code = String(body?.code ?? '').trim().toLowerCase();
|
||||||
@ -248,6 +255,9 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT(request: Request) {
|
export async function PUT(request: Request) {
|
||||||
|
const access = await requireAdminSession(request);
|
||||||
|
if (!access.ok) return access.response;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json().catch(() => ({}));
|
const body = await request.json().catch(() => ({}));
|
||||||
const payload = body?.translations;
|
const payload = body?.translations;
|
||||||
@ -287,6 +297,9 @@ export async function PUT(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function DELETE(request: Request) {
|
export async function DELETE(request: Request) {
|
||||||
|
const access = await requireAdminSession(request);
|
||||||
|
if (!access.ok) return access.response;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json().catch(() => ({}));
|
const body = await request.json().catch(() => ({}));
|
||||||
const code = String(body?.code ?? '').trim().toLowerCase();
|
const code = String(body?.code ?? '').trim().toLowerCase();
|
||||||
|
|||||||
@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
import { useTranslation } from '../../i18n/useTranslation';
|
|
||||||
import React, {
|
import React, {
|
||||||
createContext,
|
createContext,
|
||||||
useCallback,
|
useCallback,
|
||||||
@ -48,7 +47,6 @@ let toastPortalRoot: ReturnType<typeof createRoot> | null = null
|
|||||||
let toastPortalMounted = false
|
let toastPortalMounted = false
|
||||||
|
|
||||||
function notifyToastListeners() {
|
function notifyToastListeners() {
|
||||||
const { t } = useTranslation();
|
|
||||||
for (const listener of toastListeners) {
|
for (const listener of toastListeners) {
|
||||||
listener(globalToasts)
|
listener(globalToasts)
|
||||||
}
|
}
|
||||||
@ -275,7 +273,7 @@ function ToastItem({ toast, onClose }: ToastItemProps) {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="ml-1 mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full text-xs text-slate-300 hover:bg-slate-800/70 hover:text-white focus:outline-none focus:ring-2 focus:ring-slate-500"
|
className="ml-1 mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full text-xs text-slate-300 hover:bg-slate-800/70 hover:text-white focus:outline-none focus:ring-2 focus:ring-slate-500"
|
||||||
aria-label={t('autofix.k77767b9e')}
|
aria-label="Close notification"
|
||||||
>
|
>
|
||||||
×
|
×
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user