diff --git a/src/login/i18n/noJsx/getI18n.tsx b/src/login/i18n/noJsx/getI18n.tsx index 56fded1c..2c310776 100644 --- a/src/login/i18n/noJsx/getI18n.tsx +++ b/src/login/i18n/noJsx/getI18n.tsx @@ -1,5 +1,6 @@ import "keycloakify/tools/Object.fromEntries"; import { assert, is } from "tsafe/assert"; +import { extractLastParenthesisContent } from "keycloakify/tools/extractLastParenthesisContent"; import messages_defaultSet_fallbackLanguage from "../messages_defaultSet/en"; import { fetchMessages_defaultSet } from "../messages_defaultSet"; import type { KcContext } from "../../KcContext"; @@ -168,12 +169,10 @@ export function createGetI18n< break from_server; } - // cspell: disable-next-line - // from "Espagnol (Español)" we want to extract "Español" - const match = supportedEntry.label.match(/[^(]+\(([^)]+)\)/); + const lastParenthesisContent = extractLastParenthesisContent(supportedEntry.label); - if (match !== null) { - return match[1]; + if (lastParenthesisContent !== undefined) { + return lastParenthesisContent; } return supportedEntry.label; diff --git a/src/tools/extractLastParenthesisContent.ts b/src/tools/extractLastParenthesisContent.ts new file mode 100644 index 00000000..42643dbc --- /dev/null +++ b/src/tools/extractLastParenthesisContent.ts @@ -0,0 +1,43 @@ +/** + * "Hello (world)" => "world" + * "Hello (world) (foo)" => "foo" + * "Hello (world (foo))" => "world (foo)" + */ +export function extractLastParenthesisContent(str: string): string | undefined { + const chars: string[] = []; + + for (const char of str) { + chars.push(char); + } + + const extractedChars: string[] = []; + let openingCount = 0; + + loop_through_char: for (let i = chars.length - 1; i >= 0; i--) { + const char = chars[i]; + + if (i === chars.length - 1) { + if (char !== ")") { + return undefined; + } + + continue; + } + + switch (char) { + case ")": + openingCount++; + break; + case "(": + if (openingCount === 0) { + return extractedChars.join(""); + } + openingCount--; + break; + } + + extractedChars.unshift(char); + } + + return undefined; +}