Skip to content

Add .swift-format configuration and add a script to format #308

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,18 @@ jobs:
- run: swift build
env:
DEVELOPER_DIR: /Applications/${{ matrix.xcode }}.app/Contents/Developer/

format:
runs-on: ubuntu-latest
container:
image: swift:6.0.3
steps:
- uses: actions/checkout@v4
- run: ./Utilities/format.swift
- name: Check for formatting changes
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git diff --exit-code || {
echo "::error::The formatting changed some files. Please run \`./Utilities/format.swift\` and commit the changes."
exit 1
}
13 changes: 13 additions & 0 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": 1,
"lineLength": 120,
"indentation": {
"spaces": 4
},
"lineBreakBeforeEachArgument": true,
"indentConditionalCompilationBlocks": false,
"prioritizeKeepingFunctionOutputTogether": true,
"rules": {
"AlwaysUseLowerCamelCase": false
}
}
4 changes: 2 additions & 2 deletions Examples/ActorOnWebWorker/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ let package = Package(
name: "Example",
platforms: [.macOS("15"), .iOS("18"), .watchOS("11"), .tvOS("18"), .visionOS("2")],
dependencies: [
.package(path: "../../"),
.package(path: "../../")
],
targets: [
.executableTarget(
Expand All @@ -15,6 +15,6 @@ let package = Package(
.product(name: "JavaScriptKit", package: "JavaScriptKit"),
.product(name: "JavaScriptEventLoop", package: "JavaScriptKit"),
]
),
)
]
)
57 changes: 31 additions & 26 deletions Examples/ActorOnWebWorker/Sources/MyApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -144,17 +144,21 @@ final class App {
}

private func setupEventHandlers() {
indexButton.onclick = .object(JSClosure { [weak self] _ in
guard let self else { return .undefined }
self.performIndex()
return .undefined
})

searchButton.onclick = .object(JSClosure { [weak self] _ in
guard let self else { return .undefined }
self.performSearch()
return .undefined
})
indexButton.onclick = .object(
JSClosure { [weak self] _ in
guard let self else { return .undefined }
self.performIndex()
return .undefined
}
)

searchButton.onclick = .object(
JSClosure { [weak self] _ in
guard let self else { return .undefined }
self.performSearch()
return .undefined
}
)
}

private func performIndex() {
Expand Down Expand Up @@ -221,7 +225,8 @@ final class App {
"padding: 10px; margin: 5px 0; background: #f5f5f5; border-left: 3px solid blue;"
)
resultItem.innerHTML = .string(
"<strong>Result \(index + 1):</strong> \(result.context)")
"<strong>Result \(index + 1):</strong> \(result.context)"
)
_ = resultsElement.appendChild(resultItem)
}
}
Expand All @@ -245,18 +250,18 @@ final class App {
}

#if canImport(wasi_pthread)
import wasi_pthread
import WASILibc

/// Trick to avoid blocking the main thread. pthread_mutex_lock function is used by
/// the Swift concurrency runtime.
@_cdecl("pthread_mutex_lock")
func pthread_mutex_lock(_ mutex: UnsafeMutablePointer<pthread_mutex_t>) -> Int32 {
// DO NOT BLOCK MAIN THREAD
var ret: Int32
repeat {
ret = pthread_mutex_trylock(mutex)
} while ret == EBUSY
return ret
}
import wasi_pthread
import WASILibc

/// Trick to avoid blocking the main thread. pthread_mutex_lock function is used by
/// the Swift concurrency runtime.
@_cdecl("pthread_mutex_lock")
func pthread_mutex_lock(_ mutex: UnsafeMutablePointer<pthread_mutex_t>) -> Int32 {
// DO NOT BLOCK MAIN THREAD
var ret: Int32
repeat {
ret = pthread_mutex_trylock(mutex)
} while ret == EBUSY
return ret
}
#endif
2 changes: 1 addition & 1 deletion Examples/Basic/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ let package = Package(
name: "Basic",
dependencies: [
"JavaScriptKit",
.product(name: "JavaScriptEventLoop", package: "JavaScriptKit")
.product(name: "JavaScriptEventLoop", package: "JavaScriptKit"),
]
)
],
Expand Down
38 changes: 21 additions & 17 deletions Examples/Basic/Sources/main.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import JavaScriptKit
import JavaScriptEventLoop
import JavaScriptKit

let alert = JSObject.global.alert.function!
let document = JSObject.global.document
Expand All @@ -10,10 +10,12 @@ _ = document.body.appendChild(divElement)

var buttonElement = document.createElement("button")
buttonElement.innerText = "Alert demo"
buttonElement.onclick = .object(JSClosure { _ in
alert("Swift is running on browser!")
return .undefined
})
buttonElement.onclick = .object(
JSClosure { _ in
alert("Swift is running on browser!")
return .undefined
}
)

_ = document.body.appendChild(buttonElement)

Expand All @@ -30,19 +32,21 @@ struct Response: Decodable {

var asyncButtonElement = document.createElement("button")
asyncButtonElement.innerText = "Fetch UUID demo"
asyncButtonElement.onclick = .object(JSClosure { _ in
Task {
do {
let response = try await fetch("https://httpbin.org/uuid").value
let json = try await JSPromise(response.json().object!)!.value
let parsedResponse = try JSValueDecoder().decode(Response.self, from: json)
alert(parsedResponse.uuid)
} catch {
print(error)
asyncButtonElement.onclick = .object(
JSClosure { _ in
Task {
do {
let response = try await fetch("https://httpbin.org/uuid").value
let json = try await JSPromise(response.json().object!)!.value
let parsedResponse = try JSValueDecoder().decode(Response.self, from: json)
alert(parsedResponse.uuid)
} catch {
print(error)
}
}
}

return .undefined
})
return .undefined
}
)

_ = document.body.appendChild(asyncButtonElement)
6 changes: 3 additions & 3 deletions Examples/Embedded/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ let package = Package(
name: "Embedded",
dependencies: [
.package(name: "JavaScriptKit", path: "../../"),
.package(url: "https://github.com/swiftwasm/swift-dlmalloc", branch: "0.1.0")
.package(url: "https://github.com/swiftwasm/swift-dlmalloc", branch: "0.1.0"),
],
targets: [
.executableTarget(
name: "EmbeddedApp",
dependencies: [
"JavaScriptKit",
.product(name: "dlmalloc", package: "swift-dlmalloc")
.product(name: "dlmalloc", package: "swift-dlmalloc"),
],
cSettings: [.unsafeFlags(["-fdeclspec"])],
swiftSettings: [
Expand All @@ -28,7 +28,7 @@ let package = Package(
.unsafeFlags([
"-Xclang-linker", "-nostdlib",
"-Xlinker", "--no-entry",
"-Xlinker", "--export-if-defined=__main_argc_argv"
"-Xlinker", "--export-if-defined=__main_argc_argv",
])
]
)
Expand Down
12 changes: 7 additions & 5 deletions Examples/Embedded/Sources/EmbeddedApp/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ _ = document.body.appendChild(divElement)

var buttonElement = document.createElement("button")
buttonElement.innerText = "Click me"
buttonElement.onclick = JSValue.object(JSClosure { _ in
count += 1
divElement.innerText = .string("Count \(count)")
return .undefined
})
buttonElement.onclick = JSValue.object(
JSClosure { _ in
count += 1
divElement.innerText = .string("Count \(count)")
return .undefined
}
)

_ = document.body.appendChild(buttonElement)

Expand Down
7 changes: 5 additions & 2 deletions Examples/Multithreading/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ let package = Package(
platforms: [.macOS("15"), .iOS("18"), .watchOS("11"), .tvOS("18"), .visionOS("2")],
dependencies: [
.package(path: "../../"),
.package(url: "https://github.com/kateinoigakukun/chibi-ray", revision: "c8cab621a3338dd2f8e817d3785362409d3b8cf1"),
.package(
url: "https://github.com/kateinoigakukun/chibi-ray",
revision: "c8cab621a3338dd2f8e817d3785362409d3b8cf1"
),
],
targets: [
.executableTarget(
Expand All @@ -17,6 +20,6 @@ let package = Package(
.product(name: "JavaScriptEventLoop", package: "JavaScriptKit"),
.product(name: "ChibiRay", package: "chibi-ray"),
]
),
)
]
)
4 changes: 2 additions & 2 deletions Examples/Multithreading/Sources/MyApp/Scene.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func createDemoScene(size: Int) -> Scene {
surface: .diffuse
)
)
)
),
],
lights: [
.spherical(
Expand All @@ -83,7 +83,7 @@ func createDemoScene(size: Int) -> Scene {
color: Color(red: 0.8, green: 0.8, blue: 0.8),
intensity: 0.2
)
)
),
],
shadowBias: 1e-13,
maxRecursionDepth: 10
Expand Down
53 changes: 35 additions & 18 deletions Examples/Multithreading/Sources/MyApp/main.swift
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import ChibiRay
import JavaScriptKit
import JavaScriptEventLoop
import JavaScriptKit

JavaScriptEventLoop.installGlobalExecutor()
WebWorkerTaskExecutor.installGlobalExecutor()

func renderInCanvas(ctx: JSObject, image: ImageView) {
let imageData = ctx.createImageData!(image.width, image.height).object!
let data = imageData.data.object!

for y in 0..<image.height {
for x in 0..<image.width {
let index = (y * image.width + x) * 4
let pixel = image[x, y]
data[index] = .number(Double(pixel.red * 255))
data[index] = .number(Double(pixel.red * 255))
data[index + 1] = .number(Double(pixel.green * 255))
data[index + 2] = .number(Double(pixel.blue * 255))
data[index + 3] = .number(Double(255))
Expand Down Expand Up @@ -57,7 +57,13 @@ struct Work: Sendable {
}
}

func render(scene: Scene, ctx: JSObject, renderTimeElement: JSObject, concurrency: Int, executor: (some TaskExecutor)?) async {
func render(
scene: Scene,
ctx: JSObject,
renderTimeElement: JSObject,
concurrency: Int,
executor: (some TaskExecutor)?
) async {

let imageBuffer = UnsafeMutableBufferPointer<Color>.allocate(capacity: scene.width * scene.height)
// Initialize the buffer with black color
Expand All @@ -73,12 +79,15 @@ func render(scene: Scene, ctx: JSObject, renderTimeElement: JSObject, concurrenc
}

var checkTimer: JSValue?
checkTimer = JSObject.global.setInterval!(JSClosure { _ in
print("Checking thread work...")
renderInCanvas(ctx: ctx, image: imageView)
updateRenderTime()
return .undefined
}, 250)
checkTimer = JSObject.global.setInterval!(
JSClosure { _ in
print("Checking thread work...")
renderInCanvas(ctx: ctx, image: imageView)
updateRenderTime()
return .undefined
},
250
)

await withTaskGroup(of: Void.self) { group in
let yStride = scene.height / concurrency
Expand Down Expand Up @@ -117,10 +126,16 @@ func onClick() async throws {

let scene = createDemoScene(size: size)
let executor = background ? try await WebWorkerTaskExecutor(numberOfThreads: concurrency) : nil
canvasElement.width = .number(Double(scene.width))
canvasElement.width = .number(Double(scene.width))
canvasElement.height = .number(Double(scene.height))

await render(scene: scene, ctx: ctx, renderTimeElement: renderTimeElement, concurrency: concurrency, executor: executor)
await render(
scene: scene,
ctx: ctx,
renderTimeElement: renderTimeElement,
concurrency: concurrency,
executor: executor
)
executor?.terminate()
print("Render done")
}
Expand All @@ -130,19 +145,21 @@ func main() async throws {
let concurrencyElement = JSObject.global.document.getElementById("concurrency").object!
concurrencyElement.value = JSObject.global.navigator.hardwareConcurrency

_ = renderButtonElement.addEventListener!("click", JSClosure { _ in
Task {
try await onClick()
_ = renderButtonElement.addEventListener!(
"click",
JSClosure { _ in
Task {
try await onClick()
}
return JSValue.undefined
}
return JSValue.undefined
})
)
}

Task {
try await main()
}


#if canImport(wasi_pthread)
import wasi_pthread
import WASILibc
Expand Down
4 changes: 2 additions & 2 deletions Examples/OffscrenCanvas/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ let package = Package(
name: "Example",
platforms: [.macOS("15"), .iOS("18"), .watchOS("11"), .tvOS("18"), .visionOS("2")],
dependencies: [
.package(path: "../../"),
.package(path: "../../")
],
targets: [
.executableTarget(
Expand All @@ -15,6 +15,6 @@ let package = Package(
.product(name: "JavaScriptKit", package: "JavaScriptKit"),
.product(name: "JavaScriptEventLoop", package: "JavaScriptKit"),
]
),
)
]
)
Loading