1
1
import { $ } from '@/utils/selector'
2
2
import { warn } from '@/utils/log'
3
3
4
+ const docsLang = matchLang ( location . pathname )
5
+ const supports = getSupports ( )
6
+ warn ( docsLang )
7
+ warn ( supports )
8
+
4
9
function main ( ) {
5
10
window . addEventListener ( 'click' , event => {
6
11
// 标记是否自行切换语言
@@ -9,19 +14,52 @@ function main() {
9
14
}
10
15
} , true )
11
16
12
- const docsLang = matchLang ( location . pathname )
13
- warn ( docsLang )
17
+ changeLang ( )
18
+ addLangButton ( )
19
+ }
20
+
21
+ function changeLang ( ) {
14
22
if ( isChinese ( docsLang ) ) return
15
23
// 是否自行切换过语言
16
24
if ( sessionStorage . getItem ( 'hand-control-language' ) === 'true' ) return
17
25
18
- const supports = getSupports ( )
19
- warn ( supports )
20
26
for ( const item of supports ) {
21
27
isChinese ( matchLang ( item ) ) && location . replace ( item )
22
28
}
23
29
}
24
30
31
+ function addLangButton ( ) {
32
+ const values = [ ] // 中英 排序
33
+ for ( const item of supports ) {
34
+ const lang = matchLang ( item )
35
+ if ( isChinese ( lang ) ) {
36
+ values [ 0 ] = item
37
+ } else if ( isEnglish ( lang ) ) {
38
+ values [ 1 ] = item
39
+ }
40
+ }
41
+ warn ( values )
42
+ if ( values . length < 2 ) return
43
+
44
+ const a = document . createElement ( 'a' )
45
+ a . innerText = '中-英'
46
+ a . href = isChinese ( docsLang ) ? values [ 1 ] : values [ 0 ]
47
+ a . classList . add ( 'button' )
48
+ a . style = [
49
+ 'position: fixed' ,
50
+ 'right: 0' ,
51
+ 'bottom: 15vh' ,
52
+ 'min-height: auto' ,
53
+ 'padding: 0px 2px' ,
54
+ 'font-size: 12px' ,
55
+ 'letter-spacing: 2px' ,
56
+ ] . join ( ';' )
57
+ a . onclick = function ( ) {
58
+ sessionStorage . setItem ( 'hand-control-language' , true )
59
+ }
60
+ document . body . append ( a )
61
+ }
62
+
25
63
function matchLang ( str ) {
26
64
// 匹配 pathname 或字符串
27
65
// /en-US/docs/Web/API/ 或 en-us
@@ -32,8 +70,12 @@ function isChinese(lang) {
32
70
return / z h - c n / i. test ( lang )
33
71
}
34
72
73
+ function isEnglish ( lang ) {
74
+ return / e n - U S / i. test ( lang )
75
+ }
76
+
35
77
function getSupports ( ) {
36
- return [ ...$ ( '#select_language ' ) . options ] . map ( opt => opt . value )
78
+ return [ ...$ ( '#language-selector ' ) . options ] . map ( opt => opt . value )
37
79
}
38
80
39
81
main ( )
0 commit comments