@@ -11,18 +11,45 @@ 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 > ( unsafelyWrapping: encode ( this: textEncoder, textInputElement. value) . object!)
34
+ encodeResultElement. innerText = . string( encodedData. withUnsafeBytes { bytes in
35
+ bytes. map { hex ( $0) } . joined ( separator: " " )
36
+ } )
37
+ return . undefined
38
+ }
39
+ )
40
+ let encoderContainer = document. createElement ( " div " )
41
+ _ = encoderContainer. appendChild ( textInputElement)
42
+ _ = encoderContainer. appendChild ( encodeResultElement)
43
+ _ = document. body. appendChild ( encoderContainer)
25
44
26
45
func print( _ message: String ) {
27
46
_ = JSObject . global. console. log ( message)
28
47
}
48
+
49
+ func hex( _ value: UInt8 ) -> String {
50
+ var result = " 0x "
51
+ let hexChars : [ Character ] = [ " 0 " , " 1 " , " 2 " , " 3 " , " 4 " , " 5 " , " 6 " , " 7 " , " 8 " , " 9 " , " A " , " B " , " C " , " D " , " E " , " F " ]
52
+ result. append ( hexChars [ Int ( value / 16 ) ] )
53
+ result. append ( hexChars [ Int ( value % 16 ) ] )
54
+ return result
55
+ }
0 commit comments