hippofish/packages/client/src/scripts/language-utils.ts

55 lines
1.3 KiB
TypeScript
Raw Normal View History

import { supportedLangs } from "@/scripts/langmap";
import { detect } from "tinyld";
import * as mfm from "mfm-js";
export function detectLanguage(text: string): string {
const nodes = mfm.parse(text);
const filtered = mfm.extract(nodes, (node) => {
return node.type === "text" || node.type === "quote";
});
const purified = mfm.toString(filtered);
return detect(purified);
}
2024-03-24 04:00:49 +01:00
export function isSupportedLang(langCode: string | null) {
if (!langCode) return false;
return supportedLangs[langCode] ?? false;
}
/**
* Compare two language codes to determine whether they are decisively different
* @returns false if they are close enough
*/
2024-03-28 06:26:09 +01:00
export function isSameLanguage(
langCode1: string | null,
langCode2: string | null,
) {
2024-03-24 04:00:49 +01:00
return (
languageContains(langCode1, langCode2) ||
languageContains(langCode2, langCode1)
);
}
/**
* Returns true if langCode1 contains langCode2
*/
2024-03-28 06:26:09 +01:00
export function languageContains(
langCode1: string | null,
langCode2: string | null,
) {
2024-03-24 04:00:49 +01:00
if (!langCode1 || !langCode2) return false;
return parentLanguage(langCode2) === langCode1;
}
export function parentLanguage(langCode: string | null) {
if (!langCode) return null;
if (["zh-hant", "zh-hans", "yue", "nan"].includes(langCode)) {
return "zh";
}
if (["nb", "nn"].includes(langCode)) {
return "no";
}
return langCode;
}