Skip to content

Commit 9dbab78

Browse files
Add an example of using TypedArray in an embedded app
1 parent 4c7ea17 commit 9dbab78

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

Examples/Embedded/Sources/EmbeddedApp/main.swift

+31-4
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,45 @@ var divElement = document.createElement("div")
1111
divElement.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>(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)
2544

2645
func print(_ message: String) {
2746
_ = JSObject.global.console.log(message)
2847
}
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

Comments
 (0)