forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import {type Messages} from '@lingui/core'
2
3import * as persisted from '#/state/persisted'
4
5// Helper to apply the replacement to a single string
6function replaceInString(text: string): string {
7 const {string: replacement, enabled} = persisted.get('postReplacement')
8 if (!enabled) return text
9 let repl = replacement?.length ? replacement.toLowerCase() : 'skeet'
10 return text
11 .replaceAll('Post', repl[0].toUpperCase() + repl.slice(1))
12 .replaceAll('post', repl)
13}
14
15// Recursive helper to traverse and replace strings in nested structures
16function traverseAndReplace(value: any): any {
17 if (typeof value === 'string') {
18 return replaceInString(value)
19 }
20 if (Array.isArray(value)) {
21 return value.map(item => traverseAndReplace(item))
22 }
23 if (typeof value === 'object' && value !== null) {
24 const newObject: Record<string, any> = {}
25 for (const key in value) {
26 if (Object.prototype.hasOwnProperty.call(value, key)) {
27 newObject[key] = traverseAndReplace(value[key])
28 }
29 }
30 return newObject
31 }
32 return value
33}
34
35/**
36 * Applies "Post" to "Skeet" replacements (case-insensitive) to messages
37 * for English locales.
38 * @param messages The raw messages object loaded from Lingui.
39 * @param locale The current locale string.
40 * @returns The messages object with replacements applied if the locale is English,
41 * otherwise the original messages object.
42 */
43export function applySkeetReplacements(
44 messages: Messages,
45 locale: string,
46): Messages {
47 const {enabled} = persisted.get('postReplacement')
48 console.log('replacements enabled:', enabled)
49 if (!enabled || !locale.startsWith('en')) {
50 return messages
51 }
52
53 // Traverse the entire messages catalog and apply replacements
54 const transformedCatalog: Messages = {}
55 for (const key in messages) {
56 if (Object.prototype.hasOwnProperty.call(messages, key)) {
57 transformedCatalog[key] = traverseAndReplace(messages[key])
58 }
59 }
60 return transformedCatalog
61}