Skip to content

Commit

Permalink
refactor(script-loader): convert loading component to use JSX
Browse files Browse the repository at this point in the history
  • Loading branch information
gizmo-ds committed Mar 19, 2024
1 parent b1b0774 commit 9550458
Show file tree
Hide file tree
Showing 13 changed files with 86 additions and 99 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DEBUG_MODE=false
12 changes: 4 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
all: build-script build-installer build-script-loader compress sha256sum

build-script:
@pnpm esbuild src/index.ts --bundle --minify --format=iife --platform=browser --outfile=cmd/installer/vcc-auto-translate.js
all: build-installer compress sha256sum

build-injector:
@pnpm esbuild src/injector.ts --bundle --format=esm --platform=browser --target=es2017 --minify --outfile=docs/injector.min.js
@pnpm esno scripts/build-injector.ts

build-script-loader:
@pnpm esno scripts/build-script-loader.ts
@rm -rf build/*.css

build-installer: build-script
@mkdir -p build
@cp -r localization/*.json cmd/installer/localization
build-installer: build-script-loader
@cp build/script-loader.js cmd/installer/script-loader.js
@GOOS=windows CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o build/vcc-auto-translate-installer.exe cmd/installer/main.go

sha256sum:
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
"@fluentui/web-components": "^2.5.17",
"ast-walker-scope": "^0.6.1",
"idb-keyval": "^6.2.1",
"jsx-dom": "^8.1.3",
"magic-string-ast": "^0.3.0"
},
"devDependencies": {
"@types/node": "^20.11.28",
"dotenv": "^16.4.5",
"esbuild": "^0.20.2",
"esbuild-css-modules-plugin": "^3.1.0",
"esno": "^4.7.0"
Expand Down
21 changes: 21 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions scripts/build-script-loader.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { config as dotenv_config } from 'dotenv'
import { build } from 'esbuild'
import cssModulesPlugin from 'esbuild-css-modules-plugin'

dotenv_config({ path: ['.env.local', '.env'] })

build({
entryPoints: ['src/script-loader.ts'],
bundle: true,
Expand All @@ -10,6 +13,10 @@ build({
minify: true,
outfile: 'build/script-loader.js',
metafile: true,
jsx: 'automatic',
define: {
'process.env.DEBUG_MODE': JSON.stringify(process.env.DEBUG_MODE),
},
plugins: [
cssModulesPlugin({
emitDeclarationFile: true,
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
29 changes: 29 additions & 0 deletions src/components/loading.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { fluentProgress, provideFluentDesignSystem } from '@fluentui/web-components'
import styles from './loading.module.css'

export function LoadingComponent(props: { text: string }) {
provideFluentDesignSystem().register(fluentProgress())

const app_theme = localStorage.getItem('app_theme')
let color_scheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? styles.dark
: styles.light
switch (app_theme) {
case 'Dark':
color_scheme = styles.dark
break
case 'Light':
color_scheme = styles.light
default:
break
}
return (
<div class={[styles.patchLoadingCover, color_scheme].join(' ')}>
<p class={styles.patchLoadingText} id="text">
{props.text}
</p>
{/* @ts-ignore */}
<fluent-progress class={styles.patchLoadingProgress} />
</div>
)
}
7 changes: 7 additions & 0 deletions src/localization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import zhHans from '../localization/zh-hans.json'
import zhHant from '../localization/zh-hant.json'

export const supported_languages = {
'zh-CN': zhHans,
'zh-TW': zhHant,
}
58 changes: 6 additions & 52 deletions src/script-loader.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,34 @@
import { injector } from './injector'
import { get as kv_get, set as kv_set, createStore, delMany as kv_del } from 'idb-keyval'
import { Translater } from './translate'
import { fluentProgress, provideFluentDesignSystem } from '@fluentui/web-components'

import style from './styles/script-loader.module.css'

import zhHans from '../localization/zh-hans.json'
import zhHant from '../localization/zh-hant.json'
import { LoadingComponent } from './components/loading'
import { supported_languages } from './localization'

const inject_function_name = '__vcc_auto_translate__'
const store = createStore('vcc_auto_translate', 'store')

main()

async function main() {
const index_script_file = document.getElementsByTagName('meta')['index-module'].content
const patched_filename = index_script_file.replace(/\.js$/, '.patched.js')
const local_patched_filename = await kv_get('patched-filename', store)
let patched_code: string | undefined

const supported_languages = {
'zh-CN': zhHans,
'zh-TW': zhHant,
}
const localization = supported_languages[navigator.language]

if (!local_patched_filename || local_patched_filename !== patched_filename) {
const loading = create_loading()
const loading = LoadingComponent({ text: '正在应用翻译补丁...' })
document.querySelector('#root')?.before(loading)

const u = new URL(location.origin)
u.pathname = index_script_file
const code = await fetch(u.href).then((res) => res.text())
patched_code = await injector(code, inject_function_name)

update_loading(loading, '翻译补丁已应用 🎉')

kv_set('patched-filename', patched_filename, store)
await kv_set('patched-content', patched_code, store)

loading.querySelector('fluent-progress')?.remove()
loading.querySelector<HTMLElement>('p#text')!.innerText = '翻译补丁已应用 🎉'
setTimeout(() => loading.remove(), 2000)
}

Expand All @@ -58,40 +48,4 @@ async function load_patched_code(patched_code?: string) {
document.body.appendChild(e)
}

function create_loading(text = '正在应用翻译补丁...') {
provideFluentDesignSystem().register(fluentProgress())

const loading = document.createElement('div')
loading.className = style.patchLoadingCover

const loadingText = document.createElement('p')
loadingText.className = style.patchLoadingText
loadingText.innerText = text

const loadingProgress = document.createElement('fluent-progress')
loadingProgress.className = style.patchLoadingProgress
loadingProgress.setAttribute('indeterminate', '')

loading.appendChild(loadingText)
loading.appendChild(loadingProgress)

switch (localStorage.getItem('app_theme')) {
case 'Light':
loading.classList.add(style.light)
break
case 'Dark':
loading.classList.add(style.dark)
break
}

return loading
}

function update_loading(loadingElement: HTMLElement, text: string) {
const loadingText = document.createElement('p')
loadingText.className = style.patchLoadingText
loadingText.innerText = text

loadingElement.innerHTML = ''
loadingElement.appendChild(loadingText)
}
main()
43 changes: 6 additions & 37 deletions src/translate.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,13 @@
const debug_mode = localStorage.getItem('vcc_auto_translate_debug') === 'true'

export class Translater {
localization: Record<string, string>
localization_matcher: any
// prettier-ignore
supported_element_name = [
'Button',
'SplitButton',
'ToggleButton',
'DataGridHeaderCell',
'TableHeaderCell',
'MenuItem',
'Body1',
'Title1',
'Title3',
'Subtitle2',
'Input',
'DialogTitle',
'DialogContent',
'Caption1',
'Badge',
'Subtitle1',
'Label',
'Option',
'Tab',
'Dropdown',
'Link',
'ToastBody',
'Checkbox',
'Alert',
'TableCellLayout',
'OptionGroup',
'Button', 'SplitButton', 'ToggleButton', 'DataGridHeaderCell', 'TableHeaderCell', 'MenuItem', 'Body1', 'Title1', 'Title3',
'Subtitle2', 'Input', 'DialogTitle', 'DialogContent', 'Caption1', 'Badge', 'Subtitle1', 'Label', 'Option', 'Tab', 'Dropdown',
'Link', 'ToastBody', 'Checkbox', 'Alert', 'TableCellLayout', 'OptionGroup',

'li',
'span',
'label',
'div',
'b',
'input',
'p',
'code',
'li', 'span', 'label', 'div', 'b', 'input', 'p', 'code'
]

constructor(localization: Record<string, string>) {
Expand Down Expand Up @@ -74,7 +43,7 @@ export class Translater {
(e) => e === element_name || `Styled(${e})` === element_name
)
) {
if (element_name && debug_mode)
if (element_name && process.env.DEBUG_MODE === 'true')
console.warn('not supported element:', `[${element_name}]`, t.children ?? t.placeholder)
return t
}
Expand Down
5 changes: 3 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
"module": "ESNext",
"moduleResolution": "Node",
"target": "ES2020",
"jsx": "react",
"strictNullChecks": true,
"strictFunctionTypes": true,
"sourceMap": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"allowArbitraryExtensions": true
"allowArbitraryExtensions": true,
"jsx": "react-jsx",
"jsxImportSource": "jsx-dom"
},
"exclude": ["node_modules", "**/node_modules/*"]
}

0 comments on commit 9550458

Please sign in to comment.