@@ -11,18 +11,49 @@ var divElement = document.createElement("div")
11
11
divElement. innerText = . string( " Count \( count) " )
12
12
_ = document. body. appendChild ( divElement)
13
13
14
- var buttonElement = document. createElement ( " button " )
15
- buttonElement . innerText = " Click me "
16
- buttonElement . onclick = JSValue . object (
14
+ var clickMeElement = document. createElement ( " button " )
15
+ clickMeElement . innerText = " Click me "
16
+ clickMeElement . onclick = JSValue . object (
17
17
JSClosure { _ in
18
18
count += 1
19
19
divElement. innerText = . string( " Count \( count) " )
20
20
return . undefined
21
21
}
22
22
)
23
+ _ = document. body. appendChild ( clickMeElement)
23
24
24
- _ = document. body. appendChild ( buttonElement)
25
+ var encodeResultElement = document. createElement ( " pre " )
26
+ var textInputElement = document. createElement ( " input " )
27
+ textInputElement. type = " text "
28
+ textInputElement. placeholder = " Enter text to encode to UTF-8 "
29
+ textInputElement. oninput = JSValue . object (
30
+ JSClosure { _ in
31
+ let textEncoder = JSObject . global. TextEncoder. function!. new ( )
32
+ let encode = textEncoder. encode. function!
33
+ let encodedData = JSTypedArray < UInt8 > (
34
+ unsafelyWrapping: encode ( this: textEncoder, textInputElement. value) . object!
35
+ )
36
+ encodeResultElement. innerText = . string(
37
+ encodedData. withUnsafeBytes { bytes in
38
+ bytes. map { hex ( $0) } . joined ( separator: " " )
39
+ }
40
+ )
41
+ return . undefined
42
+ }
43
+ )
44
+ let encoderContainer = document. createElement ( " div " )
45
+ _ = encoderContainer. appendChild ( textInputElement)
46
+ _ = encoderContainer. appendChild ( encodeResultElement)
47
+ _ = document. body. appendChild ( encoderContainer)
25
48
26
49
func print( _ message: String ) {
27
50
_ = JSObject . global. console. log ( message)
28
51
}
52
+
53
+ func hex( _ value: UInt8 ) -> String {
54
+ var result = " 0x "
55
+ let hexChars : [ Character ] = [ " 0 " , " 1 " , " 2 " , " 3 " , " 4 " , " 5 " , " 6 " , " 7 " , " 8 " , " 9 " , " A " , " B " , " C " , " D " , " E " , " F " ]
56
+ result. append ( hexChars [ Int ( value / 16 ) ] )
57
+ result. append ( hexChars [ Int ( value % 16 ) ] )
58
+ return result
59
+ }
0 commit comments