中英文切换 初始化
This commit is contained in:
212
.workbuddy/batch_i18n.py
Normal file
212
.workbuddy/batch_i18n.py
Normal file
@@ -0,0 +1,212 @@
|
||||
"""
|
||||
Batch i18n transformation script.
|
||||
Reads the zh translation file, creates a reverse mapping (Chinese text -> key),
|
||||
then replaces Chinese text in all .tsx/.ts/.jsx files with t() calls.
|
||||
"""
|
||||
import re
|
||||
import os
|
||||
import json
|
||||
|
||||
# Parse the zh translation file to create reverse mapping
|
||||
def parse_translation_file(filepath):
|
||||
"""Extract all key-value pairs from the TypeScript translation object."""
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# Remove the wrapper and export
|
||||
content = re.sub(r'^const \w+ = ', '', content)
|
||||
content = re.sub(r';\s*export default \w+;\s*$', '', content)
|
||||
|
||||
# Parse the nested object structure
|
||||
mapping = {} # Chinese text -> "namespace.key"
|
||||
|
||||
def extract_keys(obj_str, prefix=''):
|
||||
"""Recursively extract keys from nested object string."""
|
||||
# Match key: value pairs
|
||||
# Keys can be: identifier, 'string', or "string"
|
||||
# Values can be: 'string', "string", or nested { }
|
||||
|
||||
i = 0
|
||||
while i < len(obj_str):
|
||||
# Find key
|
||||
key_match = re.match(r'\s*(\w+)\s*:\s*', obj_str[i:])
|
||||
if not key_match:
|
||||
# Try quoted key
|
||||
key_match = re.match(r"\s*'([^']+)'\s*:\s*", obj_str[i:])
|
||||
|
||||
if not key_match:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
key = key_match.group(1)
|
||||
i += key_match.end()
|
||||
|
||||
if i >= len(obj_str):
|
||||
break
|
||||
|
||||
# Check value type
|
||||
if obj_str[i] == '{':
|
||||
# Nested object - find matching brace
|
||||
depth = 1
|
||||
j = i + 1
|
||||
while j < len(obj_str) and depth > 0:
|
||||
if obj_str[j] == '{':
|
||||
depth += 1
|
||||
elif obj_str[j] == '}':
|
||||
depth -= 1
|
||||
j += 1
|
||||
|
||||
# Recurse into nested object
|
||||
nested_content = obj_str[i+1:j-1]
|
||||
full_prefix = f"{prefix}{key}." if prefix else f"{key}."
|
||||
extract_keys(nested_content, full_prefix)
|
||||
i = j
|
||||
elif obj_str[i] == "'" or obj_str[i] == '"':
|
||||
# String value
|
||||
quote = obj_str[i]
|
||||
j = i + 1
|
||||
while j < len(obj_str):
|
||||
if obj_str[j] == '\\':
|
||||
j += 2
|
||||
continue
|
||||
if obj_str[j] == quote:
|
||||
break
|
||||
j += 1
|
||||
|
||||
value = obj_str[i+1:j]
|
||||
full_key = f"{prefix}{key}" if prefix else key
|
||||
if value and len(value) > 1:
|
||||
mapping[value] = full_key
|
||||
i = j + 1
|
||||
else:
|
||||
# Skip non-string values
|
||||
i += 1
|
||||
|
||||
extract_keys(content)
|
||||
return mapping
|
||||
|
||||
# Build the mapping
|
||||
zh_mapping = parse_translation_file('src/locales/zh/index.ts')
|
||||
|
||||
# Sort by length (longest first) to avoid partial replacements
|
||||
sorted_mappings = sorted(zh_mapping.items(), key=lambda x: len(x[0]), reverse=True)
|
||||
|
||||
print(f"Loaded {len(sorted_mappings)} translation keys")
|
||||
|
||||
# Files to process
|
||||
target_dirs = [
|
||||
'src/pages',
|
||||
'src/components',
|
||||
]
|
||||
|
||||
# Files to skip
|
||||
skip_files = [
|
||||
'src/components/LanguageSwitcher.tsx',
|
||||
'src/components/Layout.tsx',
|
||||
]
|
||||
|
||||
def get_target_files():
|
||||
files = []
|
||||
for target_dir in target_dirs:
|
||||
for root, dirs, filenames in os.walk(target_dir):
|
||||
for fname in filenames:
|
||||
if fname.endswith(('.tsx', '.ts', '.jsx', '.js')):
|
||||
filepath = os.path.join(root, fname).replace('\\', '/')
|
||||
if filepath not in skip_files:
|
||||
files.append(filepath)
|
||||
return files
|
||||
|
||||
target_files = get_target_files()
|
||||
print(f"Found {len(target_files)} files to process")
|
||||
|
||||
# Statistics
|
||||
total_replacements = 0
|
||||
files_modified = 0
|
||||
|
||||
for filepath in target_files:
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
except:
|
||||
continue
|
||||
|
||||
original = content
|
||||
file_replacements = 0
|
||||
|
||||
# Check if file already has useTranslation
|
||||
has_i18n = 'useTranslation' in content
|
||||
|
||||
# Do replacements
|
||||
for chinese_text, key in sorted_mappings:
|
||||
if chinese_text not in content:
|
||||
continue
|
||||
|
||||
# Pattern 1: In single-quoted strings: '中文'
|
||||
old1 = f"'{chinese_text}'"
|
||||
new1 = f"t('{key}')"
|
||||
if old1 in content:
|
||||
count = content.count(old1)
|
||||
content = content.replace(old1, new1)
|
||||
file_replacements += count
|
||||
|
||||
# Pattern 2: In double-quoted strings: "中文"
|
||||
old2 = f'"{chinese_text}"'
|
||||
new2 = f"t('{key}')"
|
||||
if old2 in content:
|
||||
count = content.count(old2)
|
||||
content = content.replace(old2, new2)
|
||||
file_replacements += count
|
||||
|
||||
# Pattern 3: In JSX text: >中文<
|
||||
old3 = f'>{chinese_text}<'
|
||||
new3 = f"{{t('{key}')}}<"
|
||||
if old3 in content:
|
||||
count = content.count(old3)
|
||||
content = content.replace(old3, new3)
|
||||
file_replacements += count
|
||||
|
||||
# Pattern 4: In template literals: `中文`
|
||||
old4 = f'`{chinese_text}`'
|
||||
new4 = f"t('{key}')"
|
||||
if old4 in content:
|
||||
count = content.count(old4)
|
||||
content = content.replace(old4, new4)
|
||||
file_replacements += count
|
||||
|
||||
if file_replacements == 0:
|
||||
continue
|
||||
|
||||
# Add useTranslation import if needed
|
||||
if not has_i18n and file_replacements > 0:
|
||||
# Find the last import line
|
||||
import_pattern = r"((?:import .+?;\n)+)"
|
||||
matches = list(re.finditer(import_pattern, content))
|
||||
if matches:
|
||||
last_import = matches[-1]
|
||||
insert_pos = last_import.end()
|
||||
content = content[:insert_pos] + "import { useTranslation } from 'react-i18next';\n" + content[insert_pos:]
|
||||
|
||||
# Add const { t } = useTranslation(); after component declaration
|
||||
# Look for function component patterns
|
||||
# Pattern 1: export default function ComponentName() {
|
||||
func_pattern = r'(export default function \w+\([^)]*\)\s*\{)'
|
||||
match = re.search(func_pattern, content)
|
||||
if match:
|
||||
insert_after = match.end()
|
||||
content = content[:insert_after] + '\n\tconst { t } = useTranslation();' + content[insert_after:]
|
||||
else:
|
||||
# Pattern 2: const ComponentName = () => { or function ComponentName() {
|
||||
func_pattern2 = r'((?:export default )?(?:const|function) \w+\s*(?:=\s*)?(?:\([^)]*\))?\s*(?:=>)?\s*\{)'
|
||||
match = re.search(func_pattern2, content)
|
||||
if match:
|
||||
insert_after = match.end()
|
||||
content = content[:insert_after] + '\n\tconst { t } = useTranslation();' + content[insert_after:]
|
||||
|
||||
if content != original:
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
files_modified += 1
|
||||
total_replacements += file_replacements
|
||||
print(f" {filepath}: {file_replacements} replacements")
|
||||
|
||||
print(f"\nDone! Modified {files_modified} files, {total_replacements} total replacements")
|
||||
161
.workbuddy/fix_i18n.py
Normal file
161
.workbuddy/fix_i18n.py
Normal file
@@ -0,0 +1,161 @@
|
||||
"""
|
||||
Fix script for i18n batch transformation issues:
|
||||
1. Remove misplaced `const { t } = useTranslation();` lines (inside object literals, etc.)
|
||||
2. Fix JSX attributes: `=t('...')` -> `={t('...')}`
|
||||
3. Re-add the hook correctly in the main function component
|
||||
"""
|
||||
import re
|
||||
import os
|
||||
|
||||
target_dirs = ['src/pages', 'src/components']
|
||||
skip_files = [
|
||||
'src/components/LanguageSwitcher.tsx',
|
||||
'src/components/Layout.tsx',
|
||||
'src/i18n/index.ts',
|
||||
'src/locales/zh/index.ts',
|
||||
'src/locales/en/index.ts',
|
||||
]
|
||||
|
||||
def get_target_files():
|
||||
files = []
|
||||
for target_dir in target_dirs:
|
||||
for root, dirs, filenames in os.walk(target_dir):
|
||||
for fname in filenames:
|
||||
if fname.endswith(('.tsx', '.ts', '.jsx', '.js')):
|
||||
filepath = os.path.join(root, fname).replace('\\', '/')
|
||||
if filepath not in skip_files:
|
||||
files.append(filepath)
|
||||
return files
|
||||
|
||||
target_files = get_target_files()
|
||||
total_fixed = 0
|
||||
|
||||
for filepath in target_files:
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
except:
|
||||
continue
|
||||
|
||||
original = content
|
||||
fixes = 0
|
||||
|
||||
# Step 1: Remove ALL `const { t } = useTranslation();` lines
|
||||
# These might be misplaced (inside object literals, etc.)
|
||||
old_hook_line = '\tconst { t } = useTranslation();\n'
|
||||
old_hook_line2 = '\n\tconst { t } = useTranslation();\n'
|
||||
|
||||
hook_count = content.count('const { t } = useTranslation();')
|
||||
if hook_count > 0:
|
||||
# Remove all instances
|
||||
content = content.replace(old_hook_line, '')
|
||||
content = content.replace(old_hook_line2, '\n')
|
||||
# Also handle variations
|
||||
content = re.sub(r'\n\s*const \{ t \} = useTranslation\(\);\n', '\n', content)
|
||||
fixes += hook_count
|
||||
|
||||
# Step 2: Fix JSX attributes: `=t('...')` -> `={t('...')}`
|
||||
# Pattern: word=t('...') where word is a JSX attribute name
|
||||
# But NOT: key: t('...') (JS object property) or return t('...') or = t('...')
|
||||
# JSX attributes look like: placeholder=t('key') or title=t('key')
|
||||
# We need to match: identifier immediately followed by =t('
|
||||
|
||||
# Match patterns like: placeholder=t('some.key') or title=t('some.key')
|
||||
# But not patterns like: :t(' or {t(' or (t(' or = t(' (with space)
|
||||
def fix_jsx_attr(match):
|
||||
prefix = match.group(1)
|
||||
key = match.group(2)
|
||||
return f'{prefix}={{t(\'{key}\')}}'
|
||||
|
||||
# This regex matches: word=t('key') where word is preceded by space or <
|
||||
# and NOT preceded by : or { or (
|
||||
content = re.sub(
|
||||
r'(?<![{:((])(\b\w+)=t\(\'([^\']+)\'\)',
|
||||
fix_jsx_attr,
|
||||
content
|
||||
)
|
||||
|
||||
# Also fix: word=t("key") with double quotes
|
||||
content = re.sub(
|
||||
r'(?<![{:((])(\b\w+)=t\("([^"]+)"\)',
|
||||
lambda m: f'{m.group(1)}={{t(\'{m.group(2)}\')}}',
|
||||
content
|
||||
)
|
||||
|
||||
# Step 3: Re-add useTranslation import if file uses t() but doesn't have the import
|
||||
has_t_calls = bool(re.search(r"\bt\(['\"]", content))
|
||||
has_import = 'useTranslation' in content and 'import' in content
|
||||
|
||||
if has_t_calls and not has_import:
|
||||
# Add import after last import line
|
||||
import_pattern = r"((?:import .+?;\n)+)"
|
||||
matches = list(re.finditer(import_pattern, content))
|
||||
if matches:
|
||||
last_import = matches[-1]
|
||||
insert_pos = last_import.end()
|
||||
content = content[:insert_pos] + "import { useTranslation } from 'react-i18next';\n" + content[insert_pos:]
|
||||
fixes += 1
|
||||
|
||||
# Step 4: Re-add the hook in the correct place (main function component)
|
||||
if has_t_calls and has_import or (has_t_calls and 'useTranslation' in content):
|
||||
# Check if hook is already present
|
||||
if 'const { t } = useTranslation();' not in content:
|
||||
# Find the main function component and add the hook after its opening brace
|
||||
# Pattern 1: export default function ComponentName() {
|
||||
match = re.search(r'(export default function \w+\([^)]*\)\s*\{)', content)
|
||||
if match:
|
||||
insert_pos = match.end()
|
||||
content = content[:insert_pos] + '\n\tconst { t } = useTranslation();' + content[insert_pos:]
|
||||
fixes += 1
|
||||
else:
|
||||
# Pattern 2: function ComponentName() {
|
||||
match = re.search(r'(function \w+\([^)]*\)\s*\{)', content)
|
||||
if match:
|
||||
insert_pos = match.end()
|
||||
content = content[:insert_pos] + '\n\tconst { t } = useTranslation();' + content[insert_pos:]
|
||||
fixes += 1
|
||||
else:
|
||||
# Pattern 3: const ComponentName = () => {
|
||||
# or: const ComponentName = (props) => {
|
||||
match = re.search(r'(const \w+\s*=\s*(?:\([^)]*\))?\s*=>\s*\{)', content)
|
||||
if match:
|
||||
insert_pos = match.end()
|
||||
content = content[:insert_pos] + '\n\tconst { t } = useTranslation();' + content[insert_pos:]
|
||||
fixes += 1
|
||||
else:
|
||||
# Pattern 4: export default () => {
|
||||
match = re.search(r'(export default\s*(?:\([^)]*\))?\s*=>\s*\{)', content)
|
||||
if match:
|
||||
insert_pos = match.end()
|
||||
content = content[:insert_pos] + '\n\tconst { t } = useTranslation();' + content[insert_pos:]
|
||||
fixes += 1
|
||||
|
||||
# Step 5: Also check for files that have the import but the hook was removed
|
||||
# Re-add if needed
|
||||
if 'useTranslation' in content and 'import' in content and 'const { t } = useTranslation();' not in content:
|
||||
if has_t_calls or re.search(r"\bt\(['\"]", content):
|
||||
match = re.search(r'(export default function \w+\([^)]*\)\s*\{)', content)
|
||||
if match:
|
||||
insert_pos = match.end()
|
||||
content = content[:insert_pos] + '\n\tconst { t } = useTranslation();' + content[insert_pos:]
|
||||
fixes += 1
|
||||
else:
|
||||
match = re.search(r'(function \w+\([^)]*\)\s*\{)', content)
|
||||
if match:
|
||||
insert_pos = match.end()
|
||||
content = content[:insert_pos] + '\n\tconst { t } = useTranslation();' + content[insert_pos:]
|
||||
fixes += 1
|
||||
else:
|
||||
match = re.search(r'(const \w+\s*=\s*(?:\([^)]*\))?\s*=>\s*\{)', content)
|
||||
if match:
|
||||
insert_pos = match.end()
|
||||
content = content[:insert_pos] + '\n\tconst { t } = useTranslation();' + content[insert_pos:]
|
||||
fixes += 1
|
||||
|
||||
if content != original:
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
total_fixed += 1
|
||||
print(f" Fixed: {filepath} ({fixes} issues)")
|
||||
|
||||
print(f"\nDone! Fixed {total_fixed} files")
|
||||
63
.workbuddy/fix_jsx_gt.py
Normal file
63
.workbuddy/fix_jsx_gt.py
Normal file
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Fix script 2: Fix consumed '>' in JSX tags.
|
||||
The batch script pattern `>Chinese<` -> `{t('key')}<` consumed the '>' from opening JSX tags.
|
||||
"""
|
||||
import re
|
||||
import os
|
||||
|
||||
target_dirs = ['src/pages', 'src/components']
|
||||
skip_files = [
|
||||
'src/components/LanguageSwitcher.tsx',
|
||||
'src/components/Layout.tsx',
|
||||
'src/i18n/index.ts',
|
||||
'src/locales/zh/index.ts',
|
||||
'src/locales/en/index.ts',
|
||||
]
|
||||
|
||||
def get_target_files():
|
||||
files = []
|
||||
for target_dir in target_dirs:
|
||||
for root, dirs, filenames in os.walk(target_dir):
|
||||
for fname in filenames:
|
||||
if fname.endswith(('.tsx', '.ts', '.jsx', '.js')):
|
||||
filepath = os.path.join(root, fname).replace('\\', '/')
|
||||
if filepath not in skip_files:
|
||||
files.append(filepath)
|
||||
return files
|
||||
|
||||
target_files = get_target_files()
|
||||
total_fixed = 0
|
||||
|
||||
for filepath in target_files:
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
except:
|
||||
continue
|
||||
|
||||
original = content
|
||||
|
||||
# Fix 1: }{t(' -> }>{t(' (consumed > after JSX expression attribute)
|
||||
# Example: <Option value={1}{t('key')}</Option> -> <Option value={1}>{t('key')}</Option>
|
||||
content = re.sub(
|
||||
r'\}\{t\(\'',
|
||||
'}>{t(\'',
|
||||
content
|
||||
)
|
||||
|
||||
# Fix 2: "{t(' -> ">{t(' (consumed > after JSX string attribute)
|
||||
# Example: <Option value="X"{t('key')}</Option> -> <Option value="X">{t('key')}</Option>
|
||||
content = re.sub(
|
||||
r'"\{t\(\'',
|
||||
'">{t(\'',
|
||||
content
|
||||
)
|
||||
|
||||
if content != original:
|
||||
fixes = original.count('}{t(\'') + original.count('"{t(\'')
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
total_fixed += 1
|
||||
print(f" Fixed: {filepath} ({fixes} issues)")
|
||||
|
||||
print(f"\nDone! Fixed {total_fixed} files")
|
||||
82
.workbuddy/fix_jsx_gt2.py
Normal file
82
.workbuddy/fix_jsx_gt2.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
Fix script 3: Fix self-closing tag consumed '>'.
|
||||
Pattern: <Icon /{t('key')} -> <Icon />{t('key')}
|
||||
Also fix any remaining patterns where '>' was consumed.
|
||||
"""
|
||||
import re
|
||||
import os
|
||||
|
||||
target_dirs = ['src/pages', 'src/components']
|
||||
skip_files = [
|
||||
'src/components/LanguageSwitcher.tsx',
|
||||
'src/components/Layout.tsx',
|
||||
'src/i18n/index.ts',
|
||||
'src/locales/zh/index.ts',
|
||||
'src/locales/en/index.ts',
|
||||
]
|
||||
|
||||
def get_target_files():
|
||||
files = []
|
||||
for target_dir in target_dirs:
|
||||
for root, dirs, filenames in os.walk(target_dir):
|
||||
for fname in filenames:
|
||||
if fname.endswith(('.tsx', '.ts', '.jsx', '.js')):
|
||||
filepath = os.path.join(root, fname).replace('\\', '/')
|
||||
if filepath not in skip_files:
|
||||
files.append(filepath)
|
||||
return files
|
||||
|
||||
target_files = get_target_files()
|
||||
total_fixed = 0
|
||||
|
||||
for filepath in target_files:
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
except:
|
||||
continue
|
||||
|
||||
original = content
|
||||
|
||||
# Fix 1: /{t(' -> />{t(' (self-closing tag consumed >)
|
||||
content = re.sub(
|
||||
r'/\{t\(\'',
|
||||
'/>{t(\'',
|
||||
content
|
||||
)
|
||||
|
||||
# Fix 2: Also check for > that was consumed before Chinese text in
|
||||
# other contexts (e.g., >text</Tag> where > was consumed)
|
||||
# Pattern: (letter or >){t(' -> (letter or >)>{t('
|
||||
# But we need to be careful not to break valid JSX expressions like:
|
||||
# <div>{t('key')}</div> -- this is valid, > is before {
|
||||
# So only fix when there's no > between the preceding char and {t(
|
||||
|
||||
# Check for patterns like: d{t(' or n{t(' or />{t(' (already fixed)
|
||||
# where a letter is immediately before {t(' without a > in between
|
||||
# This means the > was consumed from: <Tag>中文 -> <Tag{t('key')
|
||||
# Fix: insert > before {t(' when preceded by a letter (tag name char)
|
||||
# and the {t(' is followed by )}<
|
||||
content = re.sub(
|
||||
r'([a-zA-Z])\{t\(\'([^\']+)\'\)\}(<)',
|
||||
lambda m: f"{m.group(1)}>{m.group(2)}{m.group(3)}",
|
||||
content
|
||||
)
|
||||
# Wait, that removes the t() call structure. Let me fix it:
|
||||
# <Tag{t('key')}</Tag> -> <Tag>{t('key')}</Tag>
|
||||
content = re.sub(
|
||||
r'([a-zA-Z])\{t\(\'',
|
||||
r'\1>{t(\'',
|
||||
content
|
||||
)
|
||||
|
||||
if content != original:
|
||||
fixes = original.count('/{t(\'')
|
||||
# Count letter before {t( pattern too
|
||||
fixes += len(re.findall(r'[a-zA-Z]\{t\(\'', original)) - original.count('/{t(\'')
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
total_fixed += 1
|
||||
print(f" Fixed: {filepath}")
|
||||
|
||||
print(f"\nDone! Fixed {total_fixed} files")
|
||||
29
.workbuddy/update_request.py
Normal file
29
.workbuddy/update_request.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import re
|
||||
|
||||
with open('src/api/request.ts', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# Add i18n import after existing imports
|
||||
content = content.replace(
|
||||
"import utils from '../lib/utils';",
|
||||
"import utils from '../lib/utils';\nimport i18n from '../i18n';"
|
||||
)
|
||||
|
||||
# Replace Chinese error messages
|
||||
content = content.replace(
|
||||
"message?.error('\u767b\u5f55\u5df2\u8fc7\u671f\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55')",
|
||||
"message?.error(i18n.t('api.loginExpired'))"
|
||||
)
|
||||
content = content.replace(
|
||||
"return Promise.reject(new Error('\u767b\u5f55\u5df2\u8fc7\u671f'))",
|
||||
"return Promise.reject(new Error(i18n.t('api.loginExpired')))"
|
||||
)
|
||||
content = content.replace(
|
||||
"message?.error('\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5')",
|
||||
"message?.error(i18n.t('api.networkError'))"
|
||||
)
|
||||
|
||||
with open('src/api/request.ts', 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
|
||||
print("request.ts updated successfully")
|
||||
95
.workbuddy/update_router.py
Normal file
95
.workbuddy/update_router.py
Normal file
@@ -0,0 +1,95 @@
|
||||
import re
|
||||
|
||||
with open('src/router/index.tsx', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# Replace routeMeta titles with i18n keys
|
||||
replacements = {
|
||||
"title: '\u603b\u89c8\u9996\u9875'": "title: 'router.overview'",
|
||||
"title: '\u8bbe\u5907\u7ba1\u7406'": "title: 'router.devices'",
|
||||
"title: '\u5728\u7ebf\u89c6\u9891'": "title: 'router.video'",
|
||||
"title: '\u5b9e\u65f6\u76d1\u63a7'": "title: 'router.monitor'",
|
||||
"title: '\u544a\u8b66\u4e2d\u5fc3'": "title: 'router.alerts'",
|
||||
"title: 'AI\u8bca\u65ad\u5206\u6790'": "title: 'router.aiAnalysis'",
|
||||
"title: '\u6e05\u6d17\u4f18\u5316'": "title: 'router.clean'",
|
||||
"title: '\u5de5\u5355\u4efb\u52a1'": "title: 'router.task'",
|
||||
"title: '\u62a5\u8868\u4e2d\u5fc3'": "title: 'router.table'",
|
||||
"title: '\u7cfb\u7edf\u8bbe\u7f6e'": "title: 'router.systemSetting'",
|
||||
"title: '\u65e5\u5fd7\u7ba1\u7406'": "title: 'router.log'",
|
||||
"title: '\u89c6\u9891\u7ba1\u7406'": "title: 'router.videoManage'",
|
||||
"title: '\u89c6\u9891\u4e0b\u8f7d'": "title: 'router.downloads'",
|
||||
"title: '\u7528\u6237\u7ba1\u7406'": "title: 'router.users'",
|
||||
"title: '\u89d2\u8272\u7ba1\u7406'": "title: 'router.roles'",
|
||||
"title: '\u83dc\u5355\u7ba1\u7406'": "title: 'router.menuList'",
|
||||
"title: '\u7ec4\u7ec7\u7ba1\u7406'": "title: 'router.organization'",
|
||||
"title: '\u573a\u7ad9\u7ba1\u7406'": "title: 'router.station'",
|
||||
"title: '\u4e2a\u4eba\u4e2d\u5fc3'": "title: 'router.profile'",
|
||||
}
|
||||
|
||||
for old, new in replacements.items():
|
||||
content = content.replace(old, new)
|
||||
|
||||
# Replace 404 page text
|
||||
content = content.replace(
|
||||
'<p className="text-lg font-medium">\u6a21\u5757\u5f00\u53d1\u4e2d</p>',
|
||||
'<p className="text-lg font-medium">{t("router.moduleDeveloping")}</p>'
|
||||
)
|
||||
|
||||
# Replace placeholder pages
|
||||
content = content.replace(
|
||||
'<h2>\u901a\u77e5\u7b56\u7565\u9875\u9762</h2>',
|
||||
'<h2>{t("router.noticePolicy")}</h2>'
|
||||
)
|
||||
content = content.replace(
|
||||
'<h2>\u6570\u636e\u4e0e\u5b89\u5168\u9875\u9762</h2>',
|
||||
'<h2>{t("router.dataSafety")}</h2>'
|
||||
)
|
||||
|
||||
# Add useTranslation import and helper components
|
||||
add_after_imports = """
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
function ModuleDeveloping() {
|
||||
\tconst { t } = useTranslation();
|
||||
\treturn (
|
||||
\t\t<div className="flex flex-col items-center justify-center h-full gap-4 text-gray-400 select-none">
|
||||
\t\t\t<span className="text-6xl opacity-20">\ud83c\udde7</span>
|
||||
\t\t\t<p className="text-lg font-medium">{t('router.moduleDeveloping')}</p>
|
||||
\t\t</div>
|
||||
\t);
|
||||
}
|
||||
|
||||
function NoticePolicyPage() {
|
||||
\tconst { t } = useTranslation();
|
||||
\treturn <div style={{ padding: 20 }}><h2>{t('router.noticePolicy')}</h2></div>;
|
||||
}
|
||||
|
||||
function DataSafetyPage() {
|
||||
\tconst { t } = useTranslation();
|
||||
\treturn <div style={{ padding: 20 }}><h2>{t('router.dataSafety')}</h2></div>;
|
||||
}
|
||||
"""
|
||||
|
||||
# Insert after the Profile import line
|
||||
content = re.sub(
|
||||
r"(import Profile from '.*?';\n)",
|
||||
r"\1" + add_after_imports,
|
||||
content,
|
||||
count=1
|
||||
)
|
||||
|
||||
# Replace the inline 404 element with component
|
||||
old_404 = '<div className="flex flex-col items-center justify-center h-full gap-4 text-gray-400 select-none">\n\t\t\t\t\t\t\t<span className="text-6xl opacity-20">\ud83c\udde7</span>\n\t\t\t\t\t\t\t<p className="text-lg font-medium">{t("router.moduleDeveloping")}</p>\n\t\t\t\t\t\t</div>'
|
||||
content = content.replace(old_404, '<ModuleDeveloping />')
|
||||
|
||||
# Replace the inline notice/dataSafety elements
|
||||
old_notice = '<div style={{ padding: 20 }}><h2>{t("router.noticePolicy")}</h2></div>'
|
||||
content = content.replace(old_notice, '<NoticePolicyPage />')
|
||||
|
||||
old_datasafety = '<div style={{ padding: 20 }}><h2>{t("router.dataSafety")}</h2></div>'
|
||||
content = content.replace(old_datasafety, '<DataSafetyPage />')
|
||||
|
||||
with open('src/router/index.tsx', 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
|
||||
print("router/index.tsx updated successfully")
|
||||
119
.workbuddy/update_utils.py
Normal file
119
.workbuddy/update_utils.py
Normal file
@@ -0,0 +1,119 @@
|
||||
import re
|
||||
|
||||
with open('src/lib/utils.ts', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# Add i18n import at the top (after the last import line)
|
||||
i18n_import = "import i18n from '../i18n';\n"
|
||||
# Find the last import line and add after it
|
||||
content = re.sub(
|
||||
r"(import type \{ NotificationInstance \} from 'antd/es/notification/interface';\n)",
|
||||
r"\1" + i18n_import,
|
||||
content,
|
||||
count=1
|
||||
)
|
||||
|
||||
# Replace getLocationQuality labels with i18n getters
|
||||
loc_replacements = {
|
||||
"text: '\u65e0\u6548'": "get text() { return i18n.t('constants.locationInvalid') }",
|
||||
"text: 'GPS \u5355\u70b9\u5b9a\u4f4d'": "get text() { return i18n.t('constants.locationGPS') }",
|
||||
"text: 'DGPS \u4f2a\u8ddd\u5dee\u5206/SBAS'": "get text() { return i18n.t('constants.locationDGPS') }",
|
||||
"text: 'RTK \u56fa\u5b9a\u89e3'": "get text() { return i18n.t('constants.locationRTKFixed') }",
|
||||
"text: 'RTK \u6d6e\u70b9\u89e3'": "get text() { return i18n.t('constants.locationRTKFloat') }",
|
||||
"text: '\u672a\u77e5'": "get text() { return i18n.t('constants.locationUnknown') }",
|
||||
}
|
||||
for old, new in loc_replacements.items():
|
||||
content = content.replace(old, new)
|
||||
|
||||
# Replace errorSourceOptions labels
|
||||
content = content.replace(
|
||||
"{ label: '\u65e0\u4eba\u673a', value: ERROR_SOURCE.UAV }",
|
||||
"{ value: ERROR_SOURCE.UAV, get label() { return i18n.t('constants.uav') } }"
|
||||
)
|
||||
content = content.replace(
|
||||
"{ label: '\u5272\u8349\u673a', value: ERROR_SOURCE.MOWER }",
|
||||
"{ value: ERROR_SOURCE.MOWER, get label() { return i18n.t('constants.mower') } }"
|
||||
)
|
||||
content = content.replace(
|
||||
"{ label: '\u5176\u4ed6', value: ERROR_SOURCE.OTHERS }",
|
||||
"{ value: ERROR_SOURCE.OTHERS, get label() { return i18n.t('constants.others') } }"
|
||||
)
|
||||
|
||||
# Replace errorLevelOptions labels
|
||||
content = content.replace(
|
||||
"{ label: '\u4fe1\u606f', value: 'INFO' }",
|
||||
"{ value: 'INFO', get label() { return i18n.t('constants.infoLevel') } }"
|
||||
)
|
||||
content = content.replace(
|
||||
"{ label: '\u8b66\u544a', value: 'WARNING' }",
|
||||
"{ value: 'WARNING', get label() { return i18n.t('constants.warning') } }"
|
||||
)
|
||||
content = content.replace(
|
||||
"{ label: '\u9519\u8bef', value: 'ERROR' }",
|
||||
"{ value: 'ERROR', get label() { return i18n.t('constants.error') } }"
|
||||
)
|
||||
|
||||
# Replace CompareEnumOptions labels
|
||||
compare_replacements = {
|
||||
"label: '\u7b49\u4e8e'": "get label() { return i18n.t('constants.eq') }",
|
||||
"label: '\u4e0d\u7b49\u4e8e'": "get label() { return i18n.t('constants.neq') }",
|
||||
"label: '\u5927\u4e8e'": "get label() { return i18n.t('constants.gt') }",
|
||||
"label: '\u5c0f\u4e8e'": "get label() { return i18n.t('constants.lt') }",
|
||||
"label: '\u5927\u4e8e\u7b49\u4e8e'": "get label() { return i18n.t('constants.gte') }",
|
||||
"label: '\u5c0f\u4e8e\u7b49\u4e8e'": "get label() { return i18n.t('constants.lte') }",
|
||||
"label: '\u5728\u4e4b\u95f4'": "get label() { return i18n.t('constants.between') }",
|
||||
"label: '\u4e0d\u5728\u4e4b\u95f4'": "get label() { return i18n.t('constants.notBetween') }",
|
||||
"label: '\u5305\u542b'": "get label() { return i18n.t('constants.contain') }",
|
||||
"label: '\u4e0d\u5305\u542b'": "get label() { return i18n.t('constants.notContain') }",
|
||||
}
|
||||
for old, new in compare_replacements.items():
|
||||
content = content.replace(old, new)
|
||||
|
||||
# Replace workOrderTypeOptions labels
|
||||
wo_replacements = {
|
||||
'label: "\u5272\u8349\u673a\u6545\u969c"': "get label() { return i18n.t('workOrder.mowerError') }",
|
||||
'label: "\u65e0\u4eba\u673a\u6545\u969c"': "get label() { return i18n.t('workOrder.uavError') }",
|
||||
'label: "\u5de1\u68c0"': "get label() { return i18n.t('workOrder.typeInspection') }",
|
||||
'label: "\u5149\u4f0f\u7ec4\u4ef6\u6545\u969c"': "get label() { return i18n.t('workOrder.componentDefect') }",
|
||||
'label: "\u6e05\u6d17"': "get label() { return i18n.t('workOrder.typeCleaning') }",
|
||||
'label: "\u7ef4\u62a4"': "get label() { return i18n.t('workOrder.maintainTask') }",
|
||||
'label: "\u7ef4\u4fee"': "get label() { return i18n.t('workOrder.typeRepair') }",
|
||||
'label: "\u5176\u4ed6"': "get label() { return i18n.t('workOrder.other') }",
|
||||
}
|
||||
for old, new in wo_replacements.items():
|
||||
content = content.replace(old, new)
|
||||
|
||||
# Replace alarmHandleResultOptions labels
|
||||
alarm_replacements = {
|
||||
'{ value: "Handled", label: "\u5df2\u5904\u7406" }': '{ value: "Handled", get label() { return i18n.t("constants.handled") } }',
|
||||
'{ value: "Restored", label: "\u5df2\u6062\u590d" }': '{ value: "Restored", get label() { return i18n.t("constants.restored") } }',
|
||||
'{ value: "Ignored", label: "\u5df2\u5ffd\u7565" }': '{ value: "Ignored", get label() { return i18n.t("constants.ignored") } }',
|
||||
'{ value: "UnableToHandle", label: "\u65e0\u6cd5\u5904\u7406" }': '{ value: "UnableToHandle", get label() { return i18n.t("constants.unableToHandle") } }',
|
||||
'{ value: "ManufacturerHandling", label: "\u5382\u5bb6\u5904\u7406\u4e2d" }': '{ value: "ManufacturerHandling", get label() { return i18n.t("constants.manufacturerHandling") } }',
|
||||
'{ value: "FalseAlarm", label: "\u8bef\u62a5" }': '{ value: "FalseAlarm", get label() { return i18n.t("constants.falseAlarm") } }',
|
||||
}
|
||||
for old, new in alarm_replacements.items():
|
||||
content = content.replace(old, new)
|
||||
|
||||
# Replace exportTable default fileName
|
||||
content = content.replace(
|
||||
'fileName = "\u5bfc\u51fa\u6570\u636e"',
|
||||
'fileName = i18n.t("constants.exportData")'
|
||||
)
|
||||
|
||||
# Replace getVal function
|
||||
content = content.replace(
|
||||
'val == "no_rain" ? "\u65e0" : (val || \'-\')',
|
||||
'val == "no_rain" ? i18n.t("constants.none") : (val || \'-\')'
|
||||
)
|
||||
|
||||
# Replace weather error messages
|
||||
content = content.replace(
|
||||
"'[\u5929\u6c14API] \u83b7\u53d6\u5929\u6c14\u6570\u636e\u5931\u8d25\uff1a'",
|
||||
"'[WeatherAPI]'"
|
||||
)
|
||||
|
||||
with open('src/lib/utils.ts', 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
|
||||
print("utils.ts updated successfully")
|
||||
Reference in New Issue
Block a user