### Install Vite and Swift WebAssembly Plugin Source: https://elementary.codes/guide/get-started Install the required development dependencies for the project. ```shell npm install -D vite @elementary-swift/vite-plugin-swift-wasm ``` ```shell pnpm add -D vite @elementary-swift/vite-plugin-swift-wasm ``` -------------------------------- ### Start Vite development mode Source: https://elementary.codes/guide/get-started Launch the development server to enable hot-reloading for Swift source changes. ```sh $ npm run dev ``` ```sh $ pnpm dev ``` -------------------------------- ### Install project dependencies Source: https://elementary.codes/guide/get-started Install required packages using npm or pnpm. ```sh $ npm install ``` ```sh $ pnpm preinstall $ pnpm install ``` -------------------------------- ### Run Development Server Source: https://elementary.codes/guide/get-started Start the Vite development server to watch for changes and rebuild the application. ```shell npx vite --open ``` ```shell pnpm vite --open ``` -------------------------------- ### Resolve Browser Runtime Dependencies Source: https://elementary.codes/guide/get-started Resolve Swift packages and install the necessary browser WASI shim and runtime components. ```shell swift package resolve npm install @bjorn3/browser_wasi_shim@~0.4 ./.build/checkouts/elementary-ui/BrowserRuntime ``` ```shell swift package resolve pnpm add @bjorn3/browser_wasi_shim@~0.4 ./.build/checkouts/elementary-ui/BrowserRuntime ``` -------------------------------- ### SwiftUI-Inspired Love Counter View Source: https://elementary.codes/ This example demonstrates a basic counter component using ElementaryUI's SwiftUI-inspired syntax. It utilizes @State for managing the count and conditional rendering for button logic. ```swift @View struct LoveCounter { @State var count = 1 var body: some View { p { String(repeating: "❤️", count: count) } if count < 10 { button { "More Love" } .onClick { count += 1 } } else { p { "Enough love for you!" } button { "Less Love" } .onClick { count = 1 } } } } ``` -------------------------------- ### TinyCounter View in ElementaryUI Source: https://elementary.codes/guide/introduction A basic 'Hello, world!' example demonstrating a stateful counter component. It uses the @View macro for UI definition and @State for managing mutable state within the component. ```swift @View struct TinyCounter { @State var count = 1 var body: some View { button { "Count: \(count)" } .onClick { count += 1 } } } ``` -------------------------------- ### Conditional Rendering with `switch` Source: https://elementary.codes/guide/essentials/conditional-rendering.html Utilize the `switch` statement for more complex conditional rendering based on different states. This example handles loading, error, and ready states. ```swift switch state { case .loading: "Loading…" case .error: "Something went wrong." case .ready: Content() } ``` -------------------------------- ### Conditional Rendering with `if` in ElementaryUI Source: https://elementary.codes/guide/essentials/conditional-rendering.html Use the `if` statement to conditionally render UI elements based on a boolean state. This example toggles a span element. ```swift @View struct IfView { @State var shouldShow = false var body: some View { button { "Toggle" } .onClick { shouldShow.toggle() } if shouldShow { span { " Hello, world!" } } } } ``` -------------------------------- ### Initialize Swift package and dependencies Source: https://elementary.codes/guide/get-started Create a new Swift executable package and add ElementaryUI as a dependency. ```sh # Initialize a package swift package init --type executable --name MyApp # Add dependency swift package add-dependency https://github.com/elementary-swift/elementary-ui --from 0.2.0 swift package add-target-dependency ElementaryUI MyApp --package elementary-ui ``` -------------------------------- ### Mount an application to the body Source: https://elementary.codes/guide/essentials/application.html Initializes the application and attaches the root view to the document body. ```swift @main struct MyApp { static func main() { Application(ContentView()) .mount(in: .body) } } ``` -------------------------------- ### Mounting a Single Application Source: https://elementary.codes/guide/essentials/application.html Demonstrates how to mount a root ElementaryUI application to the DOM using a CSS selector. ```APIDOC ## Mounting an application ### Description Mounting an application means attaching its rendered output to the DOM. After mounting, ElementaryUI keeps the DOM in sync as your views change. ### Method `mount(in:)` ### Endpoint N/A (This is a programmatic API call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift @main struct MyApp { static func main() { Application(ContentView()) .mount(in: .body) } } ``` ### Response N/A (This is a programmatic API call) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Configure Application entrypoint and Package manifest Source: https://elementary.codes/guide/get-started Define the root view in the Swift entrypoint and specify platform requirements in the package manifest. ```swift import ElementaryUI @main struct MyApp { static func main() { Application(h1 { "Hello, world!" }) .mount(in: .body) } } ``` ```swift let package = Package( name: "MyApp", platforms: [.macOS(.v15)], dependencies: [ .package(url: "https://github.com/elementary-swift/elementary-ui", from: "0.2.0") ``` -------------------------------- ### Mounting Multiple Applications Source: https://elementary.codes/guide/essentials/application.html Illustrates how to create and mount multiple independent ElementaryUI applications on the same page. ```APIDOC ## Multiple applications ### Description You can create and mount multiple applications on the same page. This is useful for adding "islands" of interactivity to an otherwise static page. Each call to `mount(in:)` creates an independent application instance with its own state and lifecycle. ### Method `mount(in:)` ### Endpoint N/A (This is a programmatic API call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift @main struct IslandsApp { static func main() { Application(Navigation()) .mount(in: "#nav-container") Application(CommentsSection()) .mount(in: "#comments-island") } } ``` ### Response N/A (This is a programmatic API call) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Create HTML and TypeScript Entry Points Source: https://elementary.codes/guide/get-started Define the HTML structure and the TypeScript entry point to initialize the WebAssembly application. ```html MyApp ``` ```typescript import { runApplication } from "elementary-ui-browser-runtime"; import appInit from "virtual:swift-wasm?init"; await runApplication(appInit); ``` -------------------------------- ### Mounting with CSS Selectors Source: https://elementary.codes/guide/essentials/application.html Shows how to mount an ElementaryUI application into a specific DOM element using a CSS selector. ```APIDOC ## Mounting with CSS Selectors ### Description The `mount(in:)` method supports arbitrary CSS selectors. You can mount an application into any parent element. ### Method `mount(in:)` ### Endpoint N/A (This is a programmatic API call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift Application(ContentView()) .mount(in: "#app") ``` ### Response N/A (This is a programmatic API call) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Mount multiple applications Source: https://elementary.codes/guide/essentials/application.html Demonstrates mounting multiple independent application instances to different containers on the same page. ```swift @main struct IslandsApp { static func main() { Application(Navigation()) .mount(in: "#nav-container") Application(CommentsSection()) .mount(in: "#comments-island") } } ``` -------------------------------- ### Build Swift project for WebAssembly Source: https://elementary.codes/guide/get-started Compile the Swift package using the specific WebAssembly SDK. ```sh # Make sure to use the Swift SDK matching your toolchain version swift build --swift-sdk swift-6.3-RELEASE_wasm ``` -------------------------------- ### Scaffold a project with degit Source: https://elementary.codes/guide/get-started Use the degit utility to clone the Vite starter template for ElementaryUI. ```sh npx degit elementary-swift/starter-vite my-elementary-project cd my-elementary-project ``` -------------------------------- ### Mount an application to a specific selector Source: https://elementary.codes/guide/essentials/application.html Attaches the application output to a specific DOM element identified by a CSS selector. ```swift Application(ContentView()) .mount(in: "#app") ``` -------------------------------- ### Configure Vite and TypeScript Source: https://elementary.codes/guide/get-started Set up the Vite configuration and TypeScript compiler options for the project. ```typescript import { defineConfig } from "vite"; import swiftWasm from "@elementary-swift/vite-plugin-swift-wasm"; export default defineConfig({ plugins: [swiftWasm()], }); ``` ```json { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "lib": ["ES2022", "DOM"], "types": ["vite/client", "@elementary-swift/vite-plugin-swift-wasm/client"], "isolatedModules": true, "strict": true, "noEmit": true } } ``` -------------------------------- ### ForEach for Stable List Items Source: https://elementary.codes/guide/essentials/list-rendering.html Demonstrates using ForEach with a stable key for list items, suitable for reordering, insertions, and animations. It supports Identifiable elements or a key closure. ```APIDOC ## ForEach ### Description Use `ForEach` when you need a stable key for your list items (reordering, insertions, animations). You can either use elements that implement `Identifiable`, or the `init(_:key:content:)` initializer that takes a `key` closure. NOTE: To maintain _Embedded Swift_ support, only types that are `LosslessStringConvertible` can be used as keys. Keys are considered equal if their UTF8 represenatations are equal. ### Method N/A (UI Component) ### Endpoint N/A (UI Component) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift @State var items = [String]() @State var next = 1 var body: some View { button { "Add" } .onClick { items.insert("Item \(next)", at: 0) next += 1 } ul { ForEach(items.enumerated(), key: { $0.element }) { item in li { item.element } .onClick { items.remove(at: item.offset) } } } } ``` ### Response #### Success Response (200) N/A (UI Component) #### Response Example N/A ``` -------------------------------- ### Basic HTML Element Structure Source: https://elementary.codes/guide/dom-interaction/html-elements.html Use lower-case HTML element types to build your view hierarchy. Ensure you have the @View macro and a body property. ```swift @View struct MyView { var body: some View { div { h1 { "Title" } p { "Paragraph text" } button { "Click me" } } } } ``` -------------------------------- ### Render dynamic lists with ForEach Source: https://elementary.codes/guide/essentials/list-rendering.html Use ForEach when list items require stable keys for reordering or animations. Keys must be LosslessStringConvertible to maintain Embedded Swift support. ```swift @State var items = [String]() @State var next = 1 var body: some View { button { "Add" } .onClick { items.insert("Item \(next)", at: 0) next += 1 } ul { ForEach(items.enumerated(), key: { $0.element }) { item in li { item.element } .onClick { items.remove(at: item.offset) } } } } ``` -------------------------------- ### Render simple lists with for-in Source: https://elementary.codes/guide/essentials/list-rendering.html Use standard for-in loops for simple iterations where stable identity is not required. ```swift div { for item in items { p { item.title } } } ``` -------------------------------- ### Provide Environment Value Source: https://elementary.codes/guide/essentials/environment.html Use the `.environment(_:_:)` modifier to provide a value for a custom environment key. This value will be available to all descendant views. ```swift MyView() .environment(#Key(\..themeColor), "rebeccapurple") ``` -------------------------------- ### Setting HTML Attributes via Initializer Source: https://elementary.codes/guide/dom-interaction/html-elements.html Set attributes like class, id, style, type, and placeholder directly in the element's initializer. Styles can be provided as a dictionary. ```swift div(.class("container"), .id("main")) { p(.style(["color": "crimson"])) { "Styled text" } input(.type(.text), .placeholder("Enter something")) } ``` -------------------------------- ### Provide Reactive Object in Environment Source: https://elementary.codes/guide/essentials/environment.html Pass reactive objects directly into the environment. The object's type will serve as the environment key, making its properties accessible. ```swift @Reactive final class UserProfile { var name: String = "Anonymous" } // Providing the object let profile = UserProfile() ContentView() .environment(profile) ``` -------------------------------- ### Triggering Animations with withAnimation Source: https://elementary.codes/guide/animation/transactions-and-animations.html Demonstrates how to trigger state changes within a transaction block to apply default or custom bouncy animations. ```swift @State var isOffset = false var body: some View { div { p { "🚀" } .offset(x: isOffset ? 190.0 : 0.0) } button { "Default" } .onClick { withAnimation { isOffset.toggle() } } button { "Bouncy" } .onClick { withAnimation(.bouncy.speed(0.5)) { isOffset.toggle() } } } ``` -------------------------------- ### for...in for Simple Iteration Source: https://elementary.codes/guide/essentials/list-rendering.html Illustrates using a simple `for...in` loop for iterating over a collection when a stable identity for list items is not required. ```APIDOC ## for ... in ### Description For simple cases where a stable identity does not matter, you can also just iterate a collection. ### Method N/A (UI Component) ### Endpoint N/A (UI Component) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift div { for item in items { p { item.title } } } ``` ### Response #### Success Response (200) N/A (UI Component) #### Response Example N/A ``` -------------------------------- ### Trigger action on view appearance Source: https://elementary.codes/guide/essentials/lifecycle-events.html Executes a closure when the view is first added to the hierarchy. ```swift @View struct MyView { var body: some View { div { "Hello" } .onAppear { print("View appeared!") } } } ``` -------------------------------- ### Manage focus with keyed FocusState Source: https://elementary.codes/guide/dom-interaction/controlling-focus.html Uses an enum to track and switch focus between multiple input fields. ```swift enum Field: Hashable { case name case email } @FocusState var focusedField: Field? var body: some View { p { "Focused: \(focusedField, default: "-")" } input(.type(.text), .placeholder("Your name")) .focused($focusedField, equals: .name) input(.type(.text), .placeholder("you@example.com")) .focused($focusedField, equals: .email) br() button { "Focus name" }.onClick { focusedField = .name } } ``` -------------------------------- ### Conditional Rendering with `if / else` Source: https://elementary.codes/guide/essentials/conditional-rendering.html Implement `if / else` logic to render one of two different views based on a condition, such as user login status. ```swift if isLoggedIn { LogOutButton() } else { LogInButton() } ``` -------------------------------- ### Share state with child views using @Binding Source: https://elementary.codes/guide/essentials/state-and-reactivity.html Use @Binding to allow child views to read and write state owned by a parent. The $ syntax creates a binding from a @State variable. ```swift @View struct BindingCounterButton { @State var count = 0 var body: some View { CounterButton(prefix: "Pirates:", count: $count) } } @View struct CounterButton { var prefix: String @Binding var count: Int var body: some View { button { "\(prefix) \(count)" } .onClick { count += 1 } } } ``` -------------------------------- ### Define a custom view with @View Source: https://elementary.codes/guide/essentials/views Use the @View attribute on a struct to define a custom component. The body property must return the view hierarchy. ```swift @View struct Greeting { var name: String var body: some View { p { "Hello \(name)" } } } ``` -------------------------------- ### Execute asynchronous task on appearance Source: https://elementary.codes/guide/essentials/lifecycle-events.html Runs an asynchronous operation when the view enters the hierarchy, with automatic cancellation upon removal. ```swift @View struct MyView { @State var data: String? var body: some View { div { if let data = data { data } else { "Loading..." } } .task { data = await fetchData() } } } ``` -------------------------------- ### Define Custom Environment Property Source: https://elementary.codes/guide/essentials/environment.html Extend `EnvironmentValues` to create a typed environment key with a default value. This sets up a custom property accessible throughout the view hierarchy. ```swift extension EnvironmentValues { @Entry var themeColor: String = "blue" } ``` -------------------------------- ### Trigger action on state change Source: https://elementary.codes/guide/essentials/lifecycle-events.html Executes a closure whenever the specified value changes. ```swift @View struct CounterView { @State var count = 0 var body: some View { button { "Increment" } .onClick { count += 1 } .onChange(of: count) { print("Count is now \(count)") } } } ``` -------------------------------- ### Read Reactive Object from Environment Source: https://elementary.codes/guide/essentials/environment.html Access a reactive object provided in the environment using the `@Environment` wrapper, specifying the object's type. This allows subviews to read and react to changes in the object. ```swift @View struct ProfileHeader { @Environment(UserProfile.self) var profile var body: some View { p { "User: \(profile.name)" } } } ``` -------------------------------- ### Compose views into a hierarchy Source: https://elementary.codes/guide/essentials/views Combine custom views and HTML elements by nesting them within the body property of a parent view. ```swift @View struct Screen { var body: some View { div { h1 { "Welcome, mighty pirate" } Greeting(name: "Guybrush Threepwood") } } } ``` -------------------------------- ### Use Environment Value in a View Source: https://elementary.codes/guide/essentials/environment.html Access environment values within a view using the `@Environment` property wrapper. Ensure the view is annotated with `@View` for this to work. ```swift @View struct Greeting { @Environment(#Key(\..themeColor)) var color var body: some View { p(.style(["color": color])) { "Hello" } } } ``` -------------------------------- ### Define reference type state with @Reactive Source: https://elementary.codes/guide/essentials/state-and-reactivity.html Use the @Reactive macro for reference types to enable automatic view re-evaluation when properties change. This is compatible with Embedded Swift. ```swift @Reactive final class CounterModel { private var count = 0 var label: String { "Count: \(count)" } func increment() { count += 1 } func reset() { count = 0 } } @View struct ReactiveCounter { var model: CounterModel var body: some View { button { model.label } .onClick { model.increment() } button { "Reset" } .onClick { model.reset() } } } ``` -------------------------------- ### Trigger action on view disappearance Source: https://elementary.codes/guide/essentials/lifecycle-events.html Executes a closure when the view is removed from the hierarchy. ```swift @View struct MyView { var body: some View { div { "Goodbye" } .onDisappear { print("View disappeared!") } } } ``` -------------------------------- ### Track Mouse Movement with onMouseMove Source: https://elementary.codes/guide/dom-interaction/handling-events.html Use the `onMouseMove` modifier to update state variables with the mouse's X and Y coordinates relative to the target element. Ensure the element is visible and interactive for the event to trigger. ```swift @State var x = 0.0 @State var y = 0.0 var body: some View { div { p { "Move your mouse over this area" } p { "X: \(x), Y: \(y)" } } .onMouseMove { event in x = event.offsetX y = event.offsetY } } ``` -------------------------------- ### Animate layout container changes Source: https://elementary.codes/guide/animation/animate-layout-and-css.html Apply the `animateContainerLayout()` modifier to a container to automatically animate the position and size of its children when they are added, removed, or moved within an animation transaction. The container's size is also animated by default if it changes. ```swift import SwiftUI struct ContentView: View { @State var items: [Int] = [] @State var next = 1 func addItem() { items.append(next) next += 1 } var body: some View { VStack { Button("Add") { addItem() } Button("Shuffle") { items.shuffle() } List { ForEach(items.enumerated(), id: \.offset) { index, item in Text("Item \(item)") .onTapGesture { items.remove(at: index) } } } .animateContainerLayout() .animation(.snappy, value: items) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } ``` -------------------------------- ### Modifying Attributes with Modifier Syntax Source: https://elementary.codes/guide/dom-interaction/html-elements.html Alter attributes using the modifier syntax, which is useful for handling conditional attributes. The `.attributes` modifier can be chained. ```swift div { p { "Hello" } .attributes(.id("maybe-fancy")) .attributes(.class("fancy"), when: isFancy) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.