@@ -11,18 +11,49 @@ var divElement = document.createElement("div")
1111divElement. innerText = . string( " Count \( count) " )
1212_ = document. body. appendChild ( divElement)
1313
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 (
1717 JSClosure { _ in
1818 count += 1
1919 divElement. innerText = . string( " Count \( count) " )
2020 return . undefined
2121 }
2222)
23+ _ = document. body. appendChild ( clickMeElement)
2324
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)
2548
2649func print( _ message: String ) {
2750 _ = JSObject . global. console. log ( message)
2851}
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