|
@@ -0,0 +1,45 @@
|
|
|
|
|
+export const PREFIX = 'i18n';
|
|
|
|
|
+export function flatRecordKeys(
|
|
|
|
|
+ record: Record<string, any>,
|
|
|
|
|
+ parent: string[] = [],
|
|
|
|
|
+ result: Record<string, string> = {}
|
|
|
|
|
+) {
|
|
|
|
|
+ if (record && typeof record === 'object') {
|
|
|
|
|
+ for (const [key, value] of Object.entries(record)) {
|
|
|
|
|
+ if (Array.isArray(value)) value.forEach((v, i) => {
|
|
|
|
|
+ const keys = [...parent, `${key}[${i}]`];
|
|
|
|
|
+ flatRecordKeys(v, keys, result);
|
|
|
|
|
+ }); else {
|
|
|
|
|
+ const keys = [...parent, key];
|
|
|
|
|
+ flatRecordKeys(value, keys, result);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ } else if (['string', 'boolean', 'number'].includes(typeof record)) result[parent.join('.')] = record;
|
|
|
|
|
+ return result;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+type FormatData = { key: string; value: string; }[];
|
|
|
|
|
+
|
|
|
|
|
+export function formatRecord(record: Record<string, any> | string[]) {
|
|
|
|
|
+ if (Array.isArray(record)) return [record.map(key => ({ key, value: '' })), null] as const;
|
|
|
|
|
+
|
|
|
|
|
+ let reset: FormatData = [];
|
|
|
|
|
+ const gather: FormatData = [];
|
|
|
|
|
+
|
|
|
|
|
+ const result = flatRecordKeys(record);
|
|
|
|
|
+ for (let [key, value] of Object.entries(result)) {
|
|
|
|
|
+ if (typeof value === 'string') {
|
|
|
|
|
+ value = value?.replace(/^_/, '').replace(/\\_/, '_') ?? ''
|
|
|
|
|
+ if (value) reset.push({ key, value });
|
|
|
|
|
+ }
|
|
|
|
|
+ gather.push({ key, value });
|
|
|
|
|
+ }
|
|
|
|
|
+ return [gather, formatData(reset)] as const;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+export function formatData(data?: FormatData, get?: (key: string) => string) {
|
|
|
|
|
+ return data?.reduce((set, { key, value }) => {
|
|
|
|
|
+ const _key = PREFIX ? `${PREFIX}.${key}` : key;
|
|
|
|
|
+ return (set[_key] = get?.(key) ?? value ?? '', set);
|
|
|
|
|
+ }, {} as Record<string, string>) ?? null;
|
|
|
|
|
+}
|