Files
bakery-ia/frontend/src/utils/alertI18n.ts

82 lines
2.0 KiB
TypeScript
Raw Normal View History

/**
* Alert i18n Translation Utility
*
* Handles translation of alert titles and messages using i18n keys from backend enrichment.
* Falls back to raw title/message if i18n data is not available.
*/
import { TFunction } from 'i18next';
export interface AlertI18nData {
title_key?: string;
title_params?: Record<string, any>;
message_key?: string;
message_params?: Record<string, any>;
}
/**
* Translates alert title only
*
* @param alert - Alert object
* @param t - i18next translation function
* @returns Translated or fallback title
*/
export function translateAlertTitle(
alert: {
2025-12-05 20:07:01 +01:00
i18n?: AlertI18nData;
},
t: TFunction
): string {
2025-12-05 20:07:01 +01:00
if (!alert.i18n?.title_key) {
return 'Alert';
}
try {
2025-12-05 20:07:01 +01:00
const translated = t(alert.i18n.title_key, alert.i18n.title_params || {});
return translated !== alert.i18n.title_key ? translated : alert.i18n.title_key;
} catch (error) {
2025-12-05 20:07:01 +01:00
console.warn(`Failed to translate alert title with key: ${alert.i18n.title_key}`, error);
return alert.i18n.title_key;
}
}
/**
* Translates alert message only
*
* @param alert - Alert object
* @param t - i18next translation function
* @returns Translated or fallback message
*/
export function translateAlertMessage(
alert: {
2025-12-05 20:07:01 +01:00
i18n?: AlertI18nData;
},
t: TFunction
): string {
2025-12-05 20:07:01 +01:00
if (!alert.i18n?.message_key) {
return 'No message';
}
try {
2025-12-05 20:07:01 +01:00
const translated = t(alert.i18n.message_key, alert.i18n.message_params || {});
return translated !== alert.i18n.message_key ? translated : alert.i18n.message_key;
} catch (error) {
2025-12-05 20:07:01 +01:00
console.warn(`Failed to translate alert message with key: ${alert.i18n.message_key}`, error);
return alert.i18n.message_key;
}
}
/**
* Checks if alert has i18n data available
*
* @param alert - Alert object
* @returns True if i18n data is present
*/
2025-12-05 20:07:01 +01:00
export function hasI18nData(alert: {
i18n?: AlertI18nData;
}): boolean {
return !!(alert.i18n && (alert.i18n.title_key || alert.i18n.message_key));
}