Skip to content
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

add hummingbird example app #1

Merged
merged 3 commits into from
Jun 25, 2024
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
29 changes: 29 additions & 0 deletions .github/workflows/ci-examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Build Examples

on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:

defaults:
run:
working-directory: ./Examples/HummingbirdDemo

jobs:
ci:
name: Build Examples
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/cache@v4
with:
path: .build
key: ${{ runner.os }}-spm-${{ hashFiles('**/Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-

- name: Build
run: swift build
5 changes: 5 additions & 0 deletions Examples/HummingbirdDemo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/.build
xcuserdata/
DerivedData/
.vscode
Package.resolved
28 changes: 28 additions & 0 deletions Examples/HummingbirdDemo/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// swift-tools-version: 5.10
import PackageDescription

let package = Package(
name: "HummingbirdDemo",
platforms: [
.macOS(.v14),
],
products: [
.executable(name: "App", targets: ["App"]),
],
dependencies: [
.package(url: "https://github.com/hummingbird-project/hummingbird.git", from: "2.0.0-beta.6"),
.package(path: "../../"),
],
targets: [
.executableTarget(
name: "App",
dependencies: [
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "ElementaryHTMX", package: "elementary-htmx"),
],
resources: [
.copy("Public"),
]
),
]
)
32 changes: 32 additions & 0 deletions Examples/HummingbirdDemo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# ElementaryHTMX + Hummingbird Demo

## Running the example

Run the app and open http://localhost:8080 in the browser

```sh
swift run App
```

## Dev mode with auto-reload on save

The `swift-dev` script auto-reloads open browser tabs on source file changes.

It is using [watchexec](https://github.com/watchexec/watchexec) and [browsersync](https://browsersync.io/).

### Install required tools

Use homebrew and npm to install the following (tested on macOS):

```sh
npm install -g browser-sync
brew install watchexec
```

### Run app in watch-mode

This will watch all swift files in the demo package, build on-demand, and re-sync the browser page

```sh
swift dev
```
35 changes: 35 additions & 0 deletions Examples/HummingbirdDemo/Sources/App/App.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import Foundation
import Hummingbird

@main
struct App {
static func main() async throws {
let router = Router(context: URLEncodedRequestContext.self)

let assetsURL = Bundle.module.resourcePath!.appending("/Public")
router.middlewares.add(FileMiddleware(assetsURL, searchForIndexHtml: false))

addRoutes(to: router)

let app = Application(
router: router,
onServerRunning: { _ in
print("Server running on http://localhost:8080/")
#if DEBUG
browserSyncReload()
#endif
}
)
try await app.runService()
}
}

struct URLEncodedRequestContext: RequestContext {
var coreContext: CoreRequestContextStorage

init(source: ApplicationRequestContextSource) {
coreContext = .init(source: source)
}

var requestDecoder: URLEncodedFormDecoder { .init() }
}
14 changes: 14 additions & 0 deletions Examples/HummingbirdDemo/Sources/App/BrowserSync.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import Foundation

#if DEBUG
func browserSyncReload() {
let p = Process()
p.executableURL = URL(string: "file:///bin/sh")
p.arguments = ["-c", "browser-sync reload"]
do {
try p.run()
} catch {
print("Could not auto-reload: \(error)")
}
}
#endif
21 changes: 21 additions & 0 deletions Examples/HummingbirdDemo/Sources/App/Database.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
actor Database {
var model = Model()
static let shared = Database()

func addItem(_ item: String) {
model.items.append(item)
}

func removeItem(at index: Int) -> Bool {
if model.items.indices.contains(index) == false {
return false
}

model.items.remove(at: index)
return true
}
}

struct Model {
var items: [String] = []
}
16 changes: 16 additions & 0 deletions Examples/HummingbirdDemo/Sources/App/Elementary+Hummingbird.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Elementary
import Hummingbird

struct HTMLResponse<Content: HTML> {
@HTMLBuilder var content: Content
}

extension HTMLResponse: ResponseGenerator {
func response(from request: Request, context: some RequestContext) throws -> Response {
.init(
status: .ok,
headers: [.contentType: "text/html"],
body: .init(byteBuffer: .init(string: content.render()))
)
}
}
1 change: 1 addition & 0 deletions Examples/HummingbirdDemo/Sources/App/Public/htmx.min.js

Large diffs are not rendered by default.

45 changes: 45 additions & 0 deletions Examples/HummingbirdDemo/Sources/App/Routes.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import Hummingbird

func addRoutes(to router: Router<some RequestContext>) {
router.get("") { _, _ in
let model = await Database.shared.model

return HTMLResponse {
MainPage(model: model)
}
}

router.post("/items") { request, context in
let body = try await request.decode(as: AddItemRequest.self, context: context)
await Database.shared.addItem(body.item)
let items = await Database.shared.model.items

return HTMLResponse {
ItemList(items: items)
}
}

router.delete("items/{index}") { _, context in
guard let index = context.parameters.get("index", as: Int.self) else {
throw HTTPError(.badRequest)
}

let wasRemoved = await Database.shared.removeItem(at: index)

guard wasRemoved else {
throw HTTPError(.notFound)
}

let items = await Database.shared.model.items

return HTMLResponse {
// exmple of using OOB swaps
ItemList(items: items)
.attributes(.hx.swapOOB(.outerHTML, "#list"))
}
}
}

struct AddItemRequest: Decodable {
var item: String
}
47 changes: 47 additions & 0 deletions Examples/HummingbirdDemo/Sources/App/Views.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Elementary
import ElementaryHTMX

struct MainPage: HTMLDocument {
var title: String { "Hummingbird + Elementary + HTMX" }

var model: Model

var head: some HTML {
meta(.charset(.utf8))
script(.src("/htmx.min.js")) {}
}

var body: some HTML {
h1 { "Hummingbird + Elementary + HTMX Demo" }
main {
div {
// example of using hx-target and hx-swap
form(.hx.post("/items"), .hx.target("#list"), .hx.swap(.outerHTML)) {
input(.type(.text), .name("item"), .value("New Item"))
input(.type(.submit), .value("Add Item"))
}
}
ItemList(items: model.items)
}
}
}

struct ItemList: HTML {
var items: [String]

var content: some HTML<HTMLTag.div> {
div(.id("list")) {
h4 { "Items" }
p { "Count: \(items.count)" }

for (index, item) in items.enumerated() {
div {
// this hx-delete will use OOB swap
button(.hx.delete("items/\(index)")) { "❌" }
" "
item
}
}
}
}
}
6 changes: 6 additions & 0 deletions Examples/HummingbirdDemo/swift-dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
touch .build/browser-dev-sync
browser-sync start -p localhost:8080 &

watchexec -w Sources -e .swift -r 'swift build --product App && touch .build/browser-dev-sync' &
watchexec -w .build/browser-dev-sync --ignore-nothing -r '.build/debug/App'
6 changes: 3 additions & 3 deletions Package.resolved
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"originHash" : "4916c3a028a5efa58d9dba2f8c0b3f63c8da6c49e13d636d995a5e41d0db6eff",
"originHash" : "eff6d695b2e02c4d623e165f451257d00daf8d0032fd2b69636aef6fa72480ae",
"pins" : [
{
"identity" : "elementary",
"kind" : "remoteSourceControl",
"location" : "https://github.com/sliemeobn/elementary.git",
"state" : {
"revision" : "fe837e0b813794a5f7066dc7c36dfb34e60d7de3",
"version" : "0.1.0-beta.4"
"revision" : "e92923b74201289fbed5a4bca273887faa36e39a",
"version" : "0.1.0-beta.5"
}
}
],
Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ let package = Package(
),
],
dependencies: [
.package(url: "https://github.com/sliemeobn/elementary.git", .upToNextMajor(from: "0.1.0-beta.4")),
.package(url: "https://github.com/sliemeobn/elementary.git", .upToNextMajor(from: "0.1.0-beta.5")),
],
targets: [
.target(
Expand Down