Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f47727df52 | |||
| 2cab78dedc | |||
| 64c536b03c | |||
| ed46533740 | |||
| 0e2595e2d4 | |||
| d7b7c112cf | |||
|
|
3b2f8f926c | ||
|
|
ce9c5bf7d1 | ||
| 18f51ffb93 | |||
| 9f50e272f3 | |||
| 681a51110d | |||
| ee92f63f86 | |||
| a8ce63a67f | |||
| 99603193b9 | |||
| b12c02d391 | |||
| 443b942c46 | |||
| cd214f2a7b | |||
|
|
559caa6f55 | ||
| bba63e5224 | |||
| d619c34ed0 | |||
| 6c5769517f | |||
| df275ad987 | |||
| c45a5efb68 | |||
| 473c291b36 | |||
| 60022cdd6f | |||
| 94211b5c87 | |||
| 60b100626b |
@ -4,21 +4,9 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches: ["main"]
|
branches: ["main"]
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
pages: write
|
|
||||||
id-token: write
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: "pages"
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
Deploy:
|
publish:
|
||||||
environment:
|
runs-on: david-macbook
|
||||||
name: github-pages
|
|
||||||
url: ${{ steps.deployment.outputs.page_url }}
|
|
||||||
runs-on: macos-14
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Build Docs
|
- name: Build Docs
|
||||||
@ -31,15 +19,16 @@ jobs:
|
|||||||
xcrun docc process-archive transform-for-static-hosting \
|
xcrun docc process-archive transform-for-static-hosting \
|
||||||
"$PWD/.derivedData/Build/Products/Debug/Meta.doccarchive" \
|
"$PWD/.derivedData/Build/Products/Debug/Meta.doccarchive" \
|
||||||
--output-path "docs" \
|
--output-path "docs" \
|
||||||
--hosting-base-path "Meta"
|
--hosting-base-path "/"
|
||||||
- name: Modify Docs
|
- name: Modify Docs
|
||||||
run: |
|
run: |
|
||||||
echo "<script>window.location.href += \"/documentation/meta\"</script>" > docs/index.html;
|
echo "<script>window.location.href += \"/documentation/meta\"</script><p>Please enable JavaScript to view the documentation <a href='/documentation/meta'>here</a>.</p>" > docs/index.html;
|
||||||
sed -i '' 's/,2px/,10px/g' docs/css/index.*.css
|
sed -i '' 's/,2px/,10px/g' docs/css/index.*.css
|
||||||
- name: Upload Artifact
|
- name: Upload
|
||||||
uses: actions/upload-pages-artifact@v3
|
uses: wangyucode/sftp-upload-action@v2.0.4
|
||||||
with:
|
with:
|
||||||
path: 'docs'
|
host: 'volans.uberspace.de'
|
||||||
- name: Deploy to GitHub Pages
|
username: 'akforum'
|
||||||
id: deployment
|
password: ${{ secrets.password }}
|
||||||
uses: actions/deploy-pages@v4
|
localDir: 'docs'
|
||||||
|
remoteDir: '/var/www/virtual/akforum/meta.aparoksha.dev/'
|
||||||
@ -3,17 +3,17 @@ name: SwiftLint
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
paths:
|
paths:
|
||||||
- '.github/workflows/swiftlint.yml'
|
- '.gitea/workflows/swiftlint.yml'
|
||||||
- '.swiftlint.yml'
|
- '.swiftlint.yml'
|
||||||
- '**/*.swift'
|
- '**/*.swift'
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
paths:
|
||||||
- '.github/workflows/swiftlint.yml'
|
- '.gitea/workflows/swiftlint.yml'
|
||||||
- '.swiftlint.yml'
|
- '.swiftlint.yml'
|
||||||
- '**/*.swift'
|
- '**/*.swift'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
paths:
|
paths:
|
||||||
- '.github/workflows/swiftlint.yml'
|
- '.gitea/workflows/swiftlint.yml'
|
||||||
- '.swiftlint.yml'
|
- '.swiftlint.yml'
|
||||||
- '**/*.swift'
|
- '**/*.swift'
|
||||||
|
|
||||||
@ -21,7 +21,7 @@ jobs:
|
|||||||
SwiftLint:
|
SwiftLint:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v4
|
||||||
- name: SwiftLint
|
- name: SwiftLint
|
||||||
uses: norio-nomura/action-swiftlint@3.2.1
|
uses: norio-nomura/action-swiftlint@3.2.1
|
||||||
with:
|
with:
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -10,5 +10,4 @@ DerivedData/
|
|||||||
/Package.resolved
|
/Package.resolved
|
||||||
.Ulysses-Group.plist
|
.Ulysses-Group.plist
|
||||||
/.docc-build
|
/.docc-build
|
||||||
/io.github.AparokshaUI.Generation.json
|
|
||||||
/.vscode
|
/.vscode
|
||||||
@ -94,11 +94,6 @@ disabled_rules:
|
|||||||
|
|
||||||
# Custom Rules
|
# Custom Rules
|
||||||
custom_rules:
|
custom_rules:
|
||||||
github_issue:
|
|
||||||
name: 'GitHub Issue'
|
|
||||||
regex: '//.(TODO|FIXME):.(?!.*(https://github\.com/AparokshaUI/Meta/issues/\d))'
|
|
||||||
message: 'The related GitHub issue must be included in a TODO or FIXME.'
|
|
||||||
severity: warning
|
|
||||||
|
|
||||||
fatal_error:
|
fatal_error:
|
||||||
name: 'Fatal Error'
|
name: 'Fatal Error'
|
||||||
|
|||||||
14
CMakeLists.txt
Normal file
14
CMakeLists.txt
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.29)
|
||||||
|
project(Meta LANGUAGES Swift)
|
||||||
|
|
||||||
|
if(POLICY CMP0157)
|
||||||
|
cmake_policy(SET CMP0157 NEW)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
|
||||||
|
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||||
|
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||||
|
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||||
|
|
||||||
|
add_subdirectory(Sources)
|
||||||
|
add_subdirectory(Tests)
|
||||||
@ -1,40 +0,0 @@
|
|||||||
# Contributing
|
|
||||||
|
|
||||||
Thank you very much for taking the time for contributing to this project.
|
|
||||||
|
|
||||||
## Report a Bug
|
|
||||||
Just open a new issue on GitHub and describe the bug. It helps if your description is detailed. Thank you very much for your contribution!
|
|
||||||
|
|
||||||
## Suggest a New Feature
|
|
||||||
Just open a new issue on GitHub and describe the idea. Thank you very much for your contribution!
|
|
||||||
|
|
||||||
## Pull Requests
|
|
||||||
I am happy for every pull request, you do not have to follow these guidelines. However, it might help you to understand the project structure and make it easier for me to merge your pull request. Thank you very much for your contribution!
|
|
||||||
|
|
||||||
### 1. Fork & Clone this Project
|
|
||||||
Start by clicking on the `Fork` button at the top of the page. Then, clone this repository to your computer.
|
|
||||||
|
|
||||||
### 2. Open the Project
|
|
||||||
Open the project folder in GNOME Builder, Xcode or another IDE.
|
|
||||||
|
|
||||||
### 3. Understand the Project Structure
|
|
||||||
- The `README.md` file contains a description of the app or package.
|
|
||||||
- The `LICENSE.md` contains an MIT license.
|
|
||||||
- `CONTRIBUTING.md` is this file.
|
|
||||||
- Directory `Icons` that contains SVG files for the images used in the app and guides.
|
|
||||||
- `Sources` contains the source code of the project.
|
|
||||||
- `Model` contains the project's basis.
|
|
||||||
- `Data Flow` contains property wrappers and protocols required for managing the updates of a view.
|
|
||||||
- `Extensions` contains all the extensions of types that are not defined in this project.
|
|
||||||
- `User Interface` contains protocols and structures that are the basis of presenting content to the user.
|
|
||||||
- `View` contains structures that conform to the `AnyView` protocol.
|
|
||||||
- `Tests` contains a sample application using two sample backends for testing the package.
|
|
||||||
|
|
||||||
### 4. Edit the Code
|
|
||||||
Edit the code. If you add a new type, add documentation in the code.
|
|
||||||
|
|
||||||
### 5. Commit to the Fork
|
|
||||||
Commit and push the fork.
|
|
||||||
|
|
||||||
### 6. Pull Request
|
|
||||||
Open GitHub to submit a pull request. Thank you very much for your contribution!
|
|
||||||
@ -1,4 +1,4 @@
|
|||||||
// swift-tools-version: 5.9
|
// swift-tools-version: 6.0
|
||||||
//
|
//
|
||||||
// Package.swift
|
// Package.swift
|
||||||
// Meta
|
// Meta
|
||||||
@ -24,17 +24,27 @@ let package = Package(
|
|||||||
targets: [
|
targets: [
|
||||||
.target(
|
.target(
|
||||||
name: "Meta",
|
name: "Meta",
|
||||||
path: "Sources"
|
path: "Sources",
|
||||||
|
exclude: [
|
||||||
|
"CMakeLists.txt"
|
||||||
|
]
|
||||||
),
|
),
|
||||||
.target(
|
.target(
|
||||||
name: "SampleBackends",
|
name: "SampleBackends",
|
||||||
dependencies: ["Meta"],
|
dependencies: ["Meta"],
|
||||||
path: "Tests/SampleBackends"
|
path: "Tests/SampleBackends",
|
||||||
|
exclude: [
|
||||||
|
"CMakeLists.txt"
|
||||||
|
]
|
||||||
),
|
),
|
||||||
.executableTarget(
|
.executableTarget(
|
||||||
name: "DemoApp",
|
name: "DemoApp",
|
||||||
dependencies: ["SampleBackends"],
|
dependencies: ["SampleBackends"],
|
||||||
path: "Tests/DemoApp"
|
path: "Tests/DemoApp",
|
||||||
|
exclude: [
|
||||||
|
"CMakeLists.txt"
|
||||||
|
]
|
||||||
)
|
)
|
||||||
]
|
],
|
||||||
|
swiftLanguageModes: [.v5]
|
||||||
)
|
)
|
||||||
|
|||||||
10
README.md
10
README.md
@ -3,12 +3,12 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://aparokshaui.github.io/Meta/">
|
<a href="https://meta.aparoksha.dev/">
|
||||||
Documentation
|
Documentation
|
||||||
</a>
|
</a>
|
||||||
·
|
·
|
||||||
<a href="https://github.com/AparokshaUI/Meta">
|
<a href="https://git.aparoksha.dev/aparoksha/meta">
|
||||||
GitHub
|
Code
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@ -34,7 +34,7 @@ It knows the following layers of UI:
|
|||||||
- A scene element is a template for a container holding one or multiple views (e.g., a window).
|
- A scene element is a template for a container holding one or multiple views (e.g., a window).
|
||||||
- A view is a part of the actual UI inside a window, or another view.
|
- A view is a part of the actual UI inside a window, or another view.
|
||||||
|
|
||||||
Detailed information can be found in the [docs](https://aparokshaui.github.io/Meta/).
|
Detailed information can be found in the [docs](https://meta.aparoksha.dev/).
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
@ -46,7 +46,7 @@ Follow those steps if you want to create a UI framework.
|
|||||||
2. Open the `Package.swift` file.
|
2. Open the `Package.swift` file.
|
||||||
3. Into the `Package` initializer, under `dependencies`, paste:
|
3. Into the `Package` initializer, under `dependencies`, paste:
|
||||||
```swift
|
```swift
|
||||||
.package(url: "https://github.com/AparokshaUI/Meta", from: "0.1.0")
|
.package(url: "https://git.aparoksha.dev/aparoksha/meta", from: "0.1.0")
|
||||||
```
|
```
|
||||||
|
|
||||||
## Thanks
|
## Thanks
|
||||||
|
|||||||
26
Sources/CMakeLists.txt
Normal file
26
Sources/CMakeLists.txt
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
file(GLOB META_SOURCES
|
||||||
|
"Model/Data Flow/*.swift"
|
||||||
|
|
||||||
|
"Model/Extensions/*.swift"
|
||||||
|
|
||||||
|
"Model/User Interface/App/*.swift"
|
||||||
|
"Model/User Interface/Scene/*.swift"
|
||||||
|
"Model/User Interface/View/Properties/*.swift"
|
||||||
|
"Model/User Interface/View/*.swift"
|
||||||
|
|
||||||
|
"View/*.swift"
|
||||||
|
)
|
||||||
|
|
||||||
|
add_library(Meta ${META_SOURCES})
|
||||||
|
|
||||||
|
target_compile_options(Meta PUBLIC -enable-testing)
|
||||||
|
|
||||||
|
set_target_properties(Meta PROPERTIES
|
||||||
|
Swift_LANGUAGE_VERSION 5
|
||||||
|
)
|
||||||
|
|
||||||
|
install(TARGETS Meta
|
||||||
|
LIBRARY DESTINATION lib
|
||||||
|
ARCHIVE DESTINATION lib
|
||||||
|
RUNTIME DESTINATION bin
|
||||||
|
)
|
||||||
@ -7,7 +7,7 @@ Multiple UI frameworks can be used in the same code, but the selection of the fr
|
|||||||
A backend is a Swift package. It is a fully functional UI framework on its own, based on the principles of <doc:StateConcept> and <doc:DeclarativeDesign>.
|
A backend is a Swift package. It is a fully functional UI framework on its own, based on the principles of <doc:StateConcept> and <doc:DeclarativeDesign>.
|
||||||
The backend defines an ``AppStorage`` reference type, which implements a function for running and quitting the app.
|
The backend defines an ``AppStorage`` reference type, which implements a function for running and quitting the app.
|
||||||
It implements at least one type conforming to ``SceneElement`` that can be added to an app's scene.
|
It implements at least one type conforming to ``SceneElement`` that can be added to an app's scene.
|
||||||
Most importantly, a backend provides various widgets.
|
Most importantly, a backend usually provides various widgets.
|
||||||
|
|
||||||
Widgets are special views conforming to the ``Widget`` protocol. While other types of views combine other views, as one can see in the articles <doc:DeclarativeDesign> and <doc:StateConcept>, widgets call the underlying UI framework in an imperative fashion. When creating a backend, determine the views available in the UI framework and provide a widget abstraction.
|
Widgets are special views conforming to the ``Widget`` protocol. While other types of views combine other views, as one can see in the articles <doc:DeclarativeDesign> and <doc:StateConcept>, widgets call the underlying UI framework in an imperative fashion. When creating a backend, determine the views available in the UI framework and provide a widget abstraction.
|
||||||
|
|
||||||
@ -24,8 +24,7 @@ import TermKitBackend
|
|||||||
@main
|
@main
|
||||||
struct Subtasks: App {
|
struct Subtasks: App {
|
||||||
|
|
||||||
let id = "io.github.david_swift.Subtasks"
|
let app: TermKitApp() // Render using the TermKitBackend
|
||||||
var app: TermKitApp! // Render using the TermKitBackend
|
|
||||||
|
|
||||||
var scene: Scene {
|
var scene: Scene {
|
||||||
Window {
|
Window {
|
||||||
@ -50,4 +49,4 @@ Pass the correct view render data type (``ViewRenderData``) containing the widge
|
|||||||
|
|
||||||
If some combinations of backends are often used, it might be sensible to create an umbrella backend.
|
If some combinations of backends are often used, it might be sensible to create an umbrella backend.
|
||||||
An umbrella backend is simply a collection of view and scene element definitions with support for a specific set of platforms.
|
An umbrella backend is simply a collection of view and scene element definitions with support for a specific set of platforms.
|
||||||
An alternative to the ``App`` protocol ensures that the right backend is selected on the right platform.
|
An alternative to the ``App`` protocol ensures that the right backend is selected on the right platform. Additionally, it might be sensible to allow the user to overwrite a platform's default selection with an environment variable.
|
||||||
|
|||||||
@ -86,8 +86,7 @@ The following code shows all of the available levels of UI for a typical desktop
|
|||||||
@main
|
@main
|
||||||
struct AwesomeApp: App { // The app (no DSL)
|
struct AwesomeApp: App { // The app (no DSL)
|
||||||
|
|
||||||
let id = "io.github.david_swift.AwesomeApp"
|
let app = SomeBackendApp()
|
||||||
var app: GenericDesktopApp!
|
|
||||||
|
|
||||||
var scene: Scene { // The scene DSL
|
var scene: Scene { // The scene DSL
|
||||||
Window("Awesome App") { // The view DSL
|
Window("Awesome App") { // The view DSL
|
||||||
@ -121,8 +120,7 @@ First, it is possible to create additional computed variables (such as `scene` a
|
|||||||
@main
|
@main
|
||||||
struct AwesomeApp: App {
|
struct AwesomeApp: App {
|
||||||
|
|
||||||
let id = "io.github.david_swift.AwesomeApp"
|
let app = SomeBackendApp()
|
||||||
var app: GenericDesktopApp!
|
|
||||||
|
|
||||||
var scene: Scene {
|
var scene: Scene {
|
||||||
MenuBar {
|
MenuBar {
|
||||||
|
|||||||
@ -16,8 +16,7 @@ An app is built around data it can read and modify. This data is called state. A
|
|||||||
@main
|
@main
|
||||||
struct CounterApp: App {
|
struct CounterApp: App {
|
||||||
|
|
||||||
let id = "io.github.david_swift.CounterApp"
|
let app = SomeBackendApp()
|
||||||
var app: SomePlatformApp!
|
|
||||||
|
|
||||||
@State private var count = 0 // Initialize state
|
@State private var count = 0 // Initialize state
|
||||||
|
|
||||||
@ -50,8 +49,7 @@ For more complex operations, computed variables can be helpful.
|
|||||||
@main
|
@main
|
||||||
struct CounterApp: App {
|
struct CounterApp: App {
|
||||||
|
|
||||||
let id = "io.github.david_swift.CounterApp"
|
let app = SomeBackendApp()
|
||||||
var app: SomePlatformApp!
|
|
||||||
|
|
||||||
@State private var count = 0
|
@State private var count = 0
|
||||||
|
|
||||||
|
|||||||
@ -10,7 +10,7 @@ Add it as a dependency to your package manifest.
|
|||||||
If there is no backend for the UI framework available, you can create one yourself. Help is available under <doc:CreateBackend>.
|
If there is no backend for the UI framework available, you can create one yourself. Help is available under <doc:CreateBackend>.
|
||||||
If you need a specific combination of platforms, creating an umbrella backend may be a solution. Find more information under <doc:Backends>.
|
If you need a specific combination of platforms, creating an umbrella backend may be a solution. Find more information under <doc:Backends>.
|
||||||
|
|
||||||
In this tutorial, [TermKitBackend](https://github.com/david-swift/TermKitBackend) will be used as a sample backend.
|
In this tutorial, [TermKitBackend](https://git.aparoksha.dev/david-swift/term-kit-backend) will be used as a sample backend.
|
||||||
|
|
||||||
## Create the User Interface
|
## Create the User Interface
|
||||||
|
|
||||||
@ -22,8 +22,7 @@ import TermKitBackend
|
|||||||
@main
|
@main
|
||||||
struct AppName: App {
|
struct AppName: App {
|
||||||
|
|
||||||
let id = "com.example.AppName"
|
let app = TermKitApp()
|
||||||
var app: TermKitApp!
|
|
||||||
|
|
||||||
var scene: Scene {
|
var scene: Scene {
|
||||||
Window {
|
Window {
|
||||||
@ -34,7 +33,7 @@ struct AppName: App {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The `id` property holds what is known as the bundle identifier on Apple platforms and as the Application ID on GNOME: a reverse DNS style identifier.
|
The app property holds the platform-specific application object.
|
||||||
Replace the type of the `app` property with the app storage type of your backend. Find the type in the backend's documentation - it conforms to ``AppStorage`` and usually has the suffix "App".
|
Replace the type of the `app` property with the app storage type of your backend. Find the type in the backend's documentation - it conforms to ``AppStorage`` and usually has the suffix "App".
|
||||||
|
|
||||||
Fill `scene` with the UI definition. More information about the UI elements and the organization of the code is available under <doc:DeclarativeDesign>.
|
Fill `scene` with the UI definition. More information about the UI elements and the organization of the code is available under <doc:DeclarativeDesign>.
|
||||||
@ -60,12 +59,10 @@ import TermKitBackend
|
|||||||
@main
|
@main
|
||||||
struct AppName: App {
|
struct AppName: App {
|
||||||
|
|
||||||
let id = "com.example.AppName"
|
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS)
|
||||||
var app: MacApp!
|
let app = MacApp(id: "dev.aparoksha.AppName")
|
||||||
#else
|
#else
|
||||||
var app: AdwaitaApp!
|
let app = AdwaitaApp(id: "dev.aparoksha.AppName")
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
var scene: Scene {
|
var scene: Scene {
|
||||||
|
|||||||
@ -4,7 +4,7 @@ Learn how to implement a backend.
|
|||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
In this tutorial, [TermKitBackend](https://github.com/david-swift/TermKitBackend) will be used as a sample backend to explain the elements of a backend.
|
In this tutorial, [TermKitBackend](https://git.aparoksha.dev/david-swift/term-kit-backend) will be used as a sample backend to explain the elements of a backend.
|
||||||
General information can be found in the <doc:Backends> article.
|
General information can be found in the <doc:Backends> article.
|
||||||
|
|
||||||
## Package Manifest
|
## Package Manifest
|
||||||
@ -13,6 +13,10 @@ Set up a new Swift Package (`swift package init`).
|
|||||||
Add the _Meta_ package as well as other dependencies if required to the dependencies section in the manifest.
|
Add the _Meta_ package as well as other dependencies if required to the dependencies section in the manifest.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
|
// swift-tools-version: 6.0
|
||||||
|
|
||||||
|
import PackageDescription
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "TermKitBackend",
|
name: "TermKitBackend",
|
||||||
platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .macCatalyst(.v13)],
|
platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .macCatalyst(.v13)],
|
||||||
@ -23,65 +27,271 @@ let package = Package(
|
|||||||
)
|
)
|
||||||
],
|
],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.package(url: "https://github.com/AparokshaUI/Meta", from: "0.1.0"),
|
.package(url: "https://git.aparoksha.dev/aparoksha/meta", from: "0.1.0"),
|
||||||
.package(url: "https://github.com/david-swift/TermKit", branch: "main")
|
.package(url: "https://github.com/david-swift/TermKit", branch: "main")
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
.target(
|
.target(
|
||||||
name: "TermKitBackend",
|
name: "TermKitBackend",
|
||||||
dependencies: ["TermKit", "Meta"]
|
dependencies: [
|
||||||
|
"TermKit",
|
||||||
|
.product(name: "Meta", package: "meta")
|
||||||
|
]
|
||||||
)
|
)
|
||||||
]
|
],
|
||||||
|
swiftLanguageModes: [.v5]
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Backend-Specific Protocols
|
## Backend-Specific Scene Type
|
||||||
|
|
||||||
As mentioned in <doc:Backends>, the backend has to define a backend-specific scene element type.
|
An app can contain scenes from multiple backends. To determine which scenes to render, a backend-specific scene protocol is required.
|
||||||
Often, it is sensible to define a widget type for regular views.
|
Simply create a protocol which conforms to the ``SceneElement`` protocol.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
|
// TermKitSceneElement.swift
|
||||||
|
|
||||||
import Meta
|
import Meta
|
||||||
|
|
||||||
public protocol TermKitSceneElement: SceneElement { }
|
public protocol TermKitSceneElement: SceneElement { }
|
||||||
public protocol TermKitWidget: Widget { }
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## The Wrapper Widget
|
## The App Storage
|
||||||
|
|
||||||
In this section, the widget type for regular views will be extended so that it can be used for rendering.
|
When creating an app, the backend is selected via the app storage (more information under <doc:CreateApp>).
|
||||||
|
Furthermore, it offers functions that allow the user to quit the app (``AppStorage/quit()``) and manage which scene elements (often windows) are visible (``AppStorage/addSceneElement(_:)`` or ``AppStorage/addWindow(_:)``, ``AppStorage/showSceneElement(_:)`` or ``AppStorage/showWindow(_:)``).
|
||||||
|
|
||||||
With _Meta_, arrays of ``AnyView`` have to be able to be converted into a single widget.
|
The ``AppStorage/run(setup:)`` method is used by the Meta framework to execute the application, where the `setup` parameter is a closure initializing the scene elements in the app's ``App/scene`` property, based on the initial setup function of your scene elements.
|
||||||
This allows definitions such as the following one:
|
Creating scene elements will be covered later in this article.
|
||||||
|
|
||||||
|
Store additional properties in the app storage. You can fetch the data for the additional properties via the initializer of the app storage (such as the app's identifier).
|
||||||
|
The ``AppStorage/storage`` stores a standard app storage which has to be the same in every backend.
|
||||||
|
|
||||||
|
Add a typealias defining the ``AppStorage/SceneElementType`` to be the backend-specific scene type.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
Window {
|
// TermKitApp.swift
|
||||||
Label("Hello")
|
|
||||||
Label("World")
|
@_exported import Meta // Export the Meta framework (only required in one file)
|
||||||
|
import TermKit
|
||||||
|
|
||||||
|
public class TermKitApp: AppStorage {
|
||||||
|
|
||||||
|
public typealias SceneElementType = TermKitSceneElement
|
||||||
|
|
||||||
|
public var storage: StandardAppStorage = .init()
|
||||||
|
|
||||||
|
public init() { } // Optionally, fetch additional data
|
||||||
|
|
||||||
|
public func run(setup: @escaping () -> Void) {
|
||||||
|
Application.prepare()
|
||||||
|
setup() // Always call the setup closure in the run function
|
||||||
|
Application.run()
|
||||||
|
}
|
||||||
|
|
||||||
|
public func quit() {
|
||||||
|
Application.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Create a widget which arranges the child views next to each other (on most platforms, doing this vertically makes most sense).
|
## Create a Scene Element
|
||||||
It should conform to the platform-specific widget type as well as ``Wrapper``.
|
|
||||||
Read the comments for general information about creating widgets.
|
Each backend defines one or multiple scene elements.
|
||||||
|
A scene element is anything one level below the application.
|
||||||
|
Windows are a common type of scene elements, but there may be other types such as the menu bar on macOS.
|
||||||
|
|
||||||
|
Scene elements are structures conforming to ``SceneElement``.
|
||||||
|
Note that for elements where multiple copies of one type of scene element are _possible_, such as windows, the scene element represents the _type_ of elements, not the individual elements.
|
||||||
|
Add individual copies via the previously mentioned functions on app storages.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
import Meta
|
// Window.swift
|
||||||
|
|
||||||
|
import TermKit
|
||||||
|
|
||||||
|
public struct Window: TermKitSceneElement { // Use the backend-specific scene element type
|
||||||
|
|
||||||
|
public var id: String
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
``SceneElement/id`` is an identifier which uniquely identifies the _type_ of scene element. For instance, use an identifier "main" which represents main windows.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
|
var title: String?
|
||||||
|
var content: Body
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
Those are additional properties required for initializing the scene elements. Common examples are a title displayed in a window's title bar and the window's content.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
|
public init(_ title: String? = nil, id: String = "main", @ViewBuilder content: () -> Body) { // @ViewBuilder enables the DSL to be used
|
||||||
|
self.id = id
|
||||||
|
self.title = title
|
||||||
|
self.content = content()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
A public initializer providing the properties with data.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
|
public func setupInitialContainers<Storage>(app: Storage) where Storage: AppStorage {
|
||||||
|
app.storage.sceneStorage.append(container(app: app))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
The function ``SceneElement/setupInitialContainers(app:)`` is responsible for creating a certain amount of initial instances of the scene element.
|
||||||
|
By convention, if sensible, create one element if no further information is provided, but let the user specify the number in the initializer or via a modifier.
|
||||||
|
Append the scene element's container to the scene storage of the app object.
|
||||||
|
|
||||||
|
In this example, the number of instances cannot be customized as creating additional windows is not supported.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
|
public func container<Storage>(app: Storage) -> SceneStorage where Storage: AppStorage {
|
||||||
|
let win = TermKit.Window(title)
|
||||||
|
win.fill()
|
||||||
|
Application.top.addSubview(win)
|
||||||
|
let storage = SceneStorage(id: id, pointer: win) {
|
||||||
|
win.ensureFocus()
|
||||||
|
}
|
||||||
|
let viewStorage = content.storage(
|
||||||
|
data: .init(sceneStorage: storage, appStorage: app),
|
||||||
|
type: TermKitMainView.self
|
||||||
|
)
|
||||||
|
if let pointer = viewStorage.pointer as? TermKit.View {
|
||||||
|
win.addSubview(pointer)
|
||||||
|
}
|
||||||
|
storage.content = [.mainContent: [viewStorage]]
|
||||||
|
return storage
|
||||||
|
}
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
Scene elements as well as widgets are based on two functions: a function for creating a new instance of the element, and a function for updating a certain instance of an element.
|
||||||
|
|
||||||
|
For scene elements, the function for creating an instance is called ``SceneElement/container(app:)``.
|
||||||
|
|
||||||
|
First, create the instance in the imperative framework (I will refer to it as the native representation).
|
||||||
|
Store the identifier and the native representation (``SceneStorage/pointer``) as well as a function which presents the scene element in a new ``SceneStorage`` object.
|
||||||
|
|
||||||
|
In most frameworks, you have to get a single native representation for the whole content view of a certain scene element or widget.
|
||||||
|
Whenever this is required, store a property of the type ``Body`` and initialize using the ``AnyView/storage(data:type:)`` type.
|
||||||
|
When working with views, you have to pass the backend-specific widget type to the methods. More information on working with widgets under [Widgets](#Widgets).
|
||||||
|
Store view storages in the scene storage (preferably via ``SceneStorage/content``) to access the storages when updating the view.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
|
public func update<Storage>(
|
||||||
|
_ storage: SceneStorage,
|
||||||
|
app: Storage,
|
||||||
|
updateProperties: Bool
|
||||||
|
) where Storage: AppStorage {
|
||||||
|
guard let viewStorage = storage.content[.mainContent]?.first else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
content
|
||||||
|
.updateStorage(
|
||||||
|
viewStorage,
|
||||||
|
data: .init(sceneStorage: storage, appStorage: app),
|
||||||
|
updateProperties: updateProperties,
|
||||||
|
type: TermKitMainView.self
|
||||||
|
)
|
||||||
|
/*
|
||||||
|
// Update additional properties
|
||||||
|
guard updateProperties else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let previousState = storage.previousState as? Self
|
||||||
|
if previousState?.property != property { // Only if equatable
|
||||||
|
nativeRepresentation.doSomething(basedOn: property) // Update the native representation
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
Application.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
In this case, there is only one property which can be modified after creating the widget: the content.
|
||||||
|
Get the view storage from the scene storage and update the view using ``AnyView/updateStorage(_:data:updateProperties:type:)``.
|
||||||
|
|
||||||
|
For properties in general (in scene elements and widgets), follow two simple rules:
|
||||||
|
|
||||||
|
- Update properties in the native representation only if the `updateProperties` parameter is `true`. If state has changed in a parent view, this property will be set to `true`, otherwise, there is nothing to update. Furthermore, if (and only if) the type of the property is equatable, check whether the value has actually changed before updating.
|
||||||
|
- An exception are views: always update views when the parent widget or scene element gets updated. The reason is that child views are able to hold state properties themselves, even though parent views do not know about the change in the state values.
|
||||||
|
|
||||||
|
## Widgets
|
||||||
|
|
||||||
|
Widgets are the basic building blocks of all the elements a scene element can hold.
|
||||||
|
This includes classic views (such as buttons, text fields, etc.) as well as more limited views (such as menus).
|
||||||
|
|
||||||
|
Similarly to the backend-specific scene element protocol, create a view-type-specific protocol conforming to ``Widget`` (e.g. one for "regular" views, one for menus, etc.).
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// TermKitWidget.swift
|
||||||
|
|
||||||
|
public protocol TermKitWidget: Widget { }
|
||||||
|
```
|
||||||
|
|
||||||
|
The widget type (``TermKitMainView/WidgetType``) is not enough for working with view types.
|
||||||
|
Each view type has to provide two special views (usually widgets):
|
||||||
|
|
||||||
|
- ``ViewRenderData/WrapperType`` is a type which is used when multiple views are used in a view body without explicitly specifying the container. If there is only a single element, it usually returns that element, otherwise, it usually aligns the elements vertically.
|
||||||
|
- ``ViewRenderData/EitherViewType`` allows Swift's `if`/`else` syntax to be used inside the bodies. While calling an either view widget like any other widget would work, Swift's `if`/`else` syntax allows more advanced syntax such as unwrapping optionals.
|
||||||
|
|
||||||
|
### The Wrapper Widget
|
||||||
|
|
||||||
|
Let's create the wrapper type first. This illustrates the process of creating complex widgets. For simpler widgets, there is a more concise syntax available.
|
||||||
|
|
||||||
|
We will call the container type `VStack`. This is dervied from SwiftUI and aligns the elements vertically.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// VStack.swift
|
||||||
|
|
||||||
import TermKit
|
import TermKit
|
||||||
|
|
||||||
public struct VStack: Wrapper, TermKitWidget {
|
public struct VStack: Wrapper, TermKitWidget {
|
||||||
|
|
||||||
var content: Body
|
var content: Body
|
||||||
|
|
||||||
public init(@ViewBuilder content: @escaping () -> Body) { // Use functions and mark them with the result builder to allow the domain-specific language to be used
|
public init(@ViewBuilder content: @escaping () -> Body) {
|
||||||
self.content = content()
|
self.content = content()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
A wrapper type has to conform to the ``Wrapper`` protocol.
|
||||||
|
The only requirement of this protocol is the ``Wrapper/init(content:)`` initializer.
|
||||||
|
|
||||||
|
Each widget conforms to the backend-specific widget protocol. As with scene elements, a widget can store "regular" properties as well as view bodies.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
public func container<Data>(
|
public func container<Data>(
|
||||||
data: WidgetData,
|
data: WidgetData,
|
||||||
type: Data.Type
|
type: Data.Type
|
||||||
) -> ViewStorage where Data: ViewRenderData {
|
) -> ViewStorage where Data: ViewRenderData {
|
||||||
let storages = content.storages(data: data, type: type) // Get the storages of child views
|
let storages = content.storages(data: data, type: type)
|
||||||
if storages.count == 1 {
|
if storages.count == 1 {
|
||||||
return .init(storages[0].pointer, content: [.mainContent: storages])
|
return .init(storages[0].pointer, content: [.mainContent: storages])
|
||||||
}
|
}
|
||||||
@ -89,14 +299,29 @@ public struct VStack: Wrapper, TermKitWidget {
|
|||||||
for (index, storage) in storages.enumerated() {
|
for (index, storage) in storages.enumerated() {
|
||||||
if let pointer = storage.pointer as? TermKit.View {
|
if let pointer = storage.pointer as? TermKit.View {
|
||||||
view.addSubview(pointer)
|
view.addSubview(pointer)
|
||||||
if let previous = (storages[safe: index - 1]?.pointer as? TermKit.View) { // The pointer should be a TermKit view
|
if let previous = (storages[safe: index - 1]?.pointer as? TermKit.View) {
|
||||||
pointer.y = .bottom(of: previous)
|
pointer.y = .bottom(of: previous)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return .init(view, content: [.mainContent: storages]) // Save storages of child views in the parent's storage for view updates
|
return .init(view, content: [.mainContent: storages])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
The ``Widget/container(data:type:)`` method is the equivalent to ``SceneElement/container(app:)`` for widgets.
|
||||||
|
Initialize the native representation.
|
||||||
|
|
||||||
|
This is a very complex container function. The reason is that the wrapper is not allowed to use the convenience [storage](https://meta.aparoksha.dev/documentation/meta/anyview/storage(data:type:))
|
||||||
|
function as this method uses the container widget to "combine" multiple views. Therefore, it is important to add the individual views to the native representation.
|
||||||
|
If there is only one item (note that this is checked via `storages`, not via the `content` property, as there might be items from other backends), return this item instead.
|
||||||
|
|
||||||
|
Store the storages for child views in the view storage's `content` property. You will access it in the updating function to update the content.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
public func update<Data>(
|
public func update<Data>(
|
||||||
_ storage: ViewStorage,
|
_ storage: ViewStorage,
|
||||||
data: WidgetData,
|
data: WidgetData,
|
||||||
@ -106,80 +331,299 @@ public struct VStack: Wrapper, TermKitWidget {
|
|||||||
guard let storages = storage.content[.mainContent] else {
|
guard let storages = storage.content[.mainContent] else {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
content.update(storages, data: data, updateProperties: updateProperties, type: type) // Update the storages of child views
|
content.update(storages, data: data, updateProperties: updateProperties, type: type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In the update function, the storages are updated based on the current state of the content.
|
||||||
|
|
||||||
|
### The Either View
|
||||||
|
|
||||||
|
The either view allows standard Swift `if`/`else` syntax to be used in a view body.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// EitherView.swift
|
||||||
|
|
||||||
|
import TermKit
|
||||||
|
|
||||||
|
public struct EitherView: TermKitWidget, Meta.EitherView {
|
||||||
|
|
||||||
|
var condition: Bool
|
||||||
|
var view1: Body
|
||||||
|
var view2: Body
|
||||||
|
|
||||||
|
public init(_ condition: Bool, @ViewBuilder view1: () -> Body, @ViewBuilder else view2: () -> Body) {
|
||||||
|
self.condition = condition
|
||||||
|
self.view1 = view1()
|
||||||
|
self.view2 = view2()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
As always, store relevant properties in the widget.
|
||||||
|
For the ``EitherView``, it is again the initializer that has to match a requirement (``EitherView/init(_:view1:else:)``).
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
|
public func container<Data>(
|
||||||
|
data: WidgetData,
|
||||||
|
type: Data.Type
|
||||||
|
) -> ViewStorage where Data: ViewRenderData {
|
||||||
|
let view = TermKit.View()
|
||||||
|
return .init(view)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
The either view has a quite complicated structure as well (it will get way easier for "normal" widgets, I promise).
|
||||||
|
Normally, you would initialize all your content storages in the container function (as in the wrapper widget).
|
||||||
|
In this case, this does not work. If the either view is called via standard `if`/`else` syntax and the condition is `true`,
|
||||||
|
we can access `view1`, but `view2` is empty (the actual view is not known). If `condition` is `false`, `view1` is empty and `view2` is known.
|
||||||
|
Therefore, we have to wait with the initialization process until `condition` changes, which is why this is handled in the `update` function.
|
||||||
|
Make sure to call the child view's `update` function after constructing a view in the parent view's `update` function.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ...
|
||||||
|
|
||||||
|
public func update<Data>(
|
||||||
|
_ storage: ViewStorage,
|
||||||
|
data: WidgetData,
|
||||||
|
updateProperties: Bool,
|
||||||
|
type: Data.Type
|
||||||
|
) where Data: ViewRenderData {
|
||||||
|
guard let parent = storage.pointer as? TermKit.View else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let view: TermKit.View?
|
||||||
|
let body = condition ? view1 : view2
|
||||||
|
if let content = storage.content[condition.description]?.first {
|
||||||
|
body.updateStorage(content, data: data, updateProperties: updateProperties, type: type)
|
||||||
|
view = content.pointer as? TermKit.View
|
||||||
|
} else {
|
||||||
|
let content = body.storage(data: data, type: type)
|
||||||
|
body.update(content, data: data, updateProperties: true, type: type)
|
||||||
|
storage.content[condition.description] = [content]
|
||||||
|
view = content.pointer as? TermKit.View
|
||||||
|
}
|
||||||
|
if let view, (storage.previousState as? Self)?.condition != condition {
|
||||||
|
parent.removeAllSubviews()
|
||||||
|
parent.addSubview(view)
|
||||||
|
}
|
||||||
|
storage.previousState = self
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Correct Updating
|
If the storage for the current condition has already been initialized, this method calls the children's update function.
|
||||||
|
Otherwise, it is initialized. Here, you can see how the convenient ``AnyView/storage(data:type:)`` and ``AnyView/updateStorage(_:data:updateProperties:type:)`` is being used for this.
|
||||||
|
|
||||||
Note that the type of the ``ViewStorage/pointer`` differs from backend to backend.
|
Assign the correct view to the native representation of the either view if the condition has changed.
|
||||||
It is a reference to the widget in the original UI framework.
|
|
||||||
|
|
||||||
In the update method, update properties of a widget (such as a button's label) only when the `updateProperties` parameter is `true`.
|
### The View Render Data
|
||||||
It indicates that a state variable (see <doc:StateConcept>) of an ancestor view has been updated.
|
|
||||||
If state doesn't change, it is impossible for the UI to change.
|
|
||||||
However, consider the following exceptions:
|
|
||||||
|
|
||||||
- _Always_ update view content (using ``AnyView/updateStorage(_:data:updateProperties:type:)`` or ``Swift/Array/storages(data:type:)``). Child views may contain own state.
|
Each view context (regular views, menus, etc.) has its own view render data type. You could already see it passed to widgets as the `type` parameter.
|
||||||
- _Always_ update closures (such as the action of a button widget). They may contain reference to state which is updated whenever a view update takes place.
|
This allows widgets to behave differently based on the context (in case this is required). Don't forget to make the widget conform to the widget protocol of all the view contexts it supports!
|
||||||
- _Always_ update bindings. As one can see when looking at ``Binding/init(get:set:)``, they contain two closures which, in most cases, contain a reference to state.
|
|
||||||
|
|
||||||
### The Render Data Type
|
Let's create the view context type for our main view context:
|
||||||
|
|
||||||
Now, define a view render data type for the main views.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
public enum MainViewType: ViewRenderData {
|
// TermKitMainView.swift
|
||||||
|
|
||||||
|
public enum TermKitMainView: ViewRenderData {
|
||||||
|
|
||||||
public typealias WidgetType = TermKitWidget
|
public typealias WidgetType = TermKitWidget
|
||||||
public typealias WrapperType = VStack
|
public typealias WrapperType = VStack
|
||||||
|
public typealias EitherViewType = EitherView
|
||||||
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
It is possible to have multiple view render data types in one backend for different situations.
|
### A Regular Widget
|
||||||
As an example, you could add another type for menus.
|
|
||||||
|
|
||||||
## The App Storage
|
Regular widgets are much simpler to implement. Here, we will implement a simple label widget.
|
||||||
|
|
||||||
An app storage object in the app definition determines which backend to use for rendering.
|
While one could use the `container`/`update` methods to implement any widgets, for most wigdets, it might be more sensible to use a more declarative approach.
|
||||||
Therefore, it must contain information about the scene element.
|
One can set the ``Widget/initializeWidget()-9ut4i`` function instead and mark the properties as widget properties with the following property wrappers:
|
||||||
|
|
||||||
Additionally, the function for executing the app is defined on the object, allowing you to put the setup of the UI into the correct context.
|
- ``ViewProperty`` for child views
|
||||||
The quit funtion should terminate the app.
|
- ``BindingProperty`` for bindings (see <doc:StateConcept>)
|
||||||
|
- ``Property`` for other properties (labels, closures, etc.)
|
||||||
|
|
||||||
|
First, create the widget's structure without any backend logic:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
@_exported import Meta // Export the Meta package
|
// Label.swift
|
||||||
|
|
||||||
import TermKit
|
import TermKit
|
||||||
|
|
||||||
public class TermKitApp: AppStorage {
|
public struct Label: TermKitWidget {
|
||||||
|
|
||||||
public typealias SceneElementType = TermKitSceneElement
|
var label: String
|
||||||
|
|
||||||
public var storage: StandardAppStorage = .init()
|
public init(_ label: String) {
|
||||||
|
self.label = label
|
||||||
public required init(id: String) { }
|
|
||||||
|
|
||||||
public func run(setup: @escaping () -> Void) {
|
|
||||||
Application.prepare()
|
|
||||||
setup()
|
|
||||||
Application.run()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func quit() {
|
}
|
||||||
Application.shutdown()
|
```
|
||||||
|
|
||||||
|
Then, create a method for initializing the native representation.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// Label.swift
|
||||||
|
|
||||||
|
import TermKit
|
||||||
|
|
||||||
|
public struct Label: TermKitWidget {
|
||||||
|
|
||||||
|
var label: String
|
||||||
|
|
||||||
|
public init(_ label: String) {
|
||||||
|
self.label = label
|
||||||
|
}
|
||||||
|
|
||||||
|
public func initializeWidget() -> Any {
|
||||||
|
TermKit.Label(label) // You woudn't set properties here usually, but the label initializer needs a label already
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, mark the `label` property with the ``Property`` property wrapper to provide a closure for "translating" the declarative representation into an imperative program.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// Label.swift
|
||||||
|
|
||||||
|
import TermKit
|
||||||
|
|
||||||
|
public struct Label: TermKitWidget {
|
||||||
|
|
||||||
|
@Property(set: { $0.text = $1 }, pointer: TermKit.Label.self) // This is a property
|
||||||
|
var label = ""
|
||||||
|
|
||||||
|
public init(_ label: String) {
|
||||||
|
self.label = label
|
||||||
|
}
|
||||||
|
|
||||||
|
public func initializeWidget() -> Any {
|
||||||
|
TermKit.Label(label)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This is already a functioning label widget!
|
||||||
|
|
||||||
|
### The Binding Property Wrapper
|
||||||
|
|
||||||
|
Whenever a property needs to allow two-way traffic (let the parent view as well as the widget itself modify the property), use a ``Binding``.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// Checkbox.swift
|
||||||
|
|
||||||
|
import TermKit
|
||||||
|
|
||||||
|
public struct Checkbox: TermKitWidget {
|
||||||
|
|
||||||
|
@Property(set: { $0.text = $1 }, pointer: TermKit.Checkbox.self)
|
||||||
|
var label: String
|
||||||
|
var isOn: Binding<Bool> // The binding property
|
||||||
|
|
||||||
|
public init(_ label: String, isOn: Binding<Bool>) {
|
||||||
|
self.label = label
|
||||||
|
self.isOn = isOn
|
||||||
|
}
|
||||||
|
|
||||||
|
public func initializeWidget() -> Any {
|
||||||
|
TermKit.Label(label)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The ``BindingProperty`` initializer accepts two closures.
|
||||||
|
|
||||||
|
The first one, `observe`, is called when setting up the widget (in the `container` method), and should connect the binding to a callback.
|
||||||
|
The second one, `set`, is equivalent to the closure with the same name for ``Property``.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// Checkbox.swift
|
||||||
|
|
||||||
|
import TermKit
|
||||||
|
|
||||||
|
public struct Checkbox: TermKitWidget {
|
||||||
|
|
||||||
|
@Property(set: { $0.text = $1 }, pointer: TermKit.Checkbox.self)
|
||||||
|
var label: String
|
||||||
|
@BindingProperty(
|
||||||
|
observe: { box, value in box.toggled = { value.wrappedValue = $0.checked } },
|
||||||
|
set: { $0.checked = $1 },
|
||||||
|
pointer: TermKit.Checkbox.self
|
||||||
|
)
|
||||||
|
var isOn: Binding<Bool>
|
||||||
|
|
||||||
|
public init(_ label: String, isOn: Binding<Bool>) {
|
||||||
|
self.label = label
|
||||||
|
self.isOn = isOn
|
||||||
|
}
|
||||||
|
|
||||||
|
public func initializeWidget() -> Any {
|
||||||
|
TermKit.Label(label)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### View Properties
|
||||||
|
|
||||||
|
View properties are properties of the type ``Body``.
|
||||||
|
The `set` closure will be called only in the `container` method.
|
||||||
|
|
||||||
|
```swift
|
||||||
|
/// Frame.swift
|
||||||
|
|
||||||
|
import TermKit
|
||||||
|
|
||||||
|
public struct Frame: TermKitWidget {
|
||||||
|
|
||||||
|
@ViewProperty(
|
||||||
|
set: { $0.addSubview($1) },
|
||||||
|
pointer: TermKit.Frame.self,
|
||||||
|
subview: TermKit.View.self,
|
||||||
|
context: MainViewContext.self
|
||||||
|
)
|
||||||
|
var view: Body
|
||||||
|
|
||||||
|
public init(@ViewBuilder content: @escaping () -> Body) { // Use the view builder
|
||||||
|
self.view = content()
|
||||||
|
}
|
||||||
|
|
||||||
|
public func initializeWidget() -> Any {
|
||||||
|
TermKit.Frame()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Next Steps
|
Define the type of the view context with the `context` property.
|
||||||
|
|
||||||
Now, you can start implementing scene elements (windows or other "top-level containers"), and views.
|
Remember not to use this property wrapper in the wrapper widget.
|
||||||
Remember following the instructions for correct updating above for all of the UI element types.
|
|
||||||
|
### Complex Widgets
|
||||||
|
|
||||||
|
More complex widgets (we have already created the two "special" widgets, the wrapper and either view widget, using this method)
|
||||||
|
should be created using the ``Widget/container(data:type:)`` and ``Widget/update(_:data:updateProperties:type:)`` methods.
|
||||||
|
|
||||||
|
## Create Apps
|
||||||
|
|
||||||
|
Now that you have a backend with some scene elements and widgets, learn how to create an app under <doc:CreateApp>.
|
||||||
|
|
||||||
|
Find other backends on the [Aparoksha website](https://www.aparoksha.dev/backends/) or [forums](https://forums.aparoksha.dev/t/projects).
|
||||||
|
|
||||||
If you still have questions, browse code in the [TermKitBackend repository](https://github.com/david-swift/TermKitBackend) or ask a question in the [discussions](https://github.com/AparokshaUI/Meta/discussions). Feedback on the documentation is appreciated!
|
|
||||||
|
|||||||
@ -11,7 +11,6 @@
|
|||||||
"button-text": "#ffffff",
|
"button-text": "#ffffff",
|
||||||
"header": "#7f313b",
|
"header": "#7f313b",
|
||||||
"documentation-intro-accent": "var(--color-header)",
|
"documentation-intro-accent": "var(--color-header)",
|
||||||
"documentation-intro-fill": "radial-gradient(circle at top, var(--color-header) 30%, #000 100%)",
|
|
||||||
"link": "#ea3358",
|
"link": "#ea3358",
|
||||||
"nav-link-color": "#ea3358",
|
"nav-link-color": "#ea3358",
|
||||||
"nav-dark-link-color": "#ea3358",
|
"nav-dark-link-color": "#ea3358",
|
||||||
|
|||||||
49
Sources/Model/Data Flow/Environment.swift
Normal file
49
Sources/Model/Data Flow/Environment.swift
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
//
|
||||||
|
// Environment.swift
|
||||||
|
// Meta
|
||||||
|
//
|
||||||
|
// Created by david-swift on 23.10.24.
|
||||||
|
//
|
||||||
|
|
||||||
|
/// A property wrapper for properties in a view that should be stored throughout view updates.
|
||||||
|
@propertyWrapper
|
||||||
|
public struct Environment<Value>: EnvironmentProtocol {
|
||||||
|
|
||||||
|
/// Access the environment value.
|
||||||
|
public var wrappedValue: Value? {
|
||||||
|
content.value as? Value
|
||||||
|
}
|
||||||
|
/// The value's identifier.
|
||||||
|
var id: String
|
||||||
|
/// The content.
|
||||||
|
let content = EnvironmentContent()
|
||||||
|
|
||||||
|
// swiftlint:disable function_default_parameter_at_end
|
||||||
|
/// Initialize a property representing an environment value in the view.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - wrappedValue: The wrapped value.
|
||||||
|
/// - id: The environment value's identifier.
|
||||||
|
public init(wrappedValue: Value? = nil, _ id: String) {
|
||||||
|
self.id = id
|
||||||
|
}
|
||||||
|
// swiftlint:enable function_default_parameter_at_end
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An environment property's content.
|
||||||
|
class EnvironmentContent {
|
||||||
|
|
||||||
|
/// The value.
|
||||||
|
var value: Any?
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The environment property protocol.
|
||||||
|
protocol EnvironmentProtocol {
|
||||||
|
|
||||||
|
/// The content.
|
||||||
|
var content: EnvironmentContent { get }
|
||||||
|
/// The identifier.
|
||||||
|
var id: String { get }
|
||||||
|
|
||||||
|
}
|
||||||
@ -18,8 +18,11 @@ public struct State<Value>: StateProtocol {
|
|||||||
}
|
}
|
||||||
nonmutating set {
|
nonmutating set {
|
||||||
rawValue = newValue
|
rawValue = newValue
|
||||||
content.update = true
|
if !blockUpdates {
|
||||||
StateManager.updateViews(force: forceUpdates)
|
content.update = true
|
||||||
|
StateManager.updateViews(force: forceUpdates)
|
||||||
|
}
|
||||||
|
writeValue?(newValue)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -46,24 +49,60 @@ public struct State<Value>: StateProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Whether to force update the views when the value changes.
|
/// Whether to force update the views when the value changes.
|
||||||
var forceUpdates: Bool
|
var forceUpdates = false
|
||||||
|
|
||||||
|
/// Whether to block updates.
|
||||||
|
var blockUpdates = false
|
||||||
|
|
||||||
/// The closure for initializing the state property's value.
|
/// The closure for initializing the state property's value.
|
||||||
var getInitialValue: () -> Value
|
var getInitialValue: () -> Value
|
||||||
|
|
||||||
|
/// Perform additional operations when the value changes.
|
||||||
|
var writeValue: ((Value) -> Void)?
|
||||||
|
|
||||||
/// The content.
|
/// The content.
|
||||||
let content: StateContent = .init()
|
let content: StateContent = .init()
|
||||||
|
|
||||||
/// Initialize a property representing a state in the view with an autoclosure.
|
/// Initialize a property representing a state in the view with an autoclosure.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - wrappedValue: The wrapped value.
|
/// - wrappedValue: The wrapped value.
|
||||||
/// - id: An explicit identifier.
|
|
||||||
/// - forceUpdates: Whether to force update all available views when the property gets modified.
|
/// - forceUpdates: Whether to force update all available views when the property gets modified.
|
||||||
public init(wrappedValue: @autoclosure @escaping () -> Value, forceUpdates: Bool = false) {
|
public init(wrappedValue: @autoclosure @escaping () -> Value, forceUpdates: Bool = false) {
|
||||||
getInitialValue = wrappedValue
|
getInitialValue = wrappedValue
|
||||||
self.forceUpdates = forceUpdates
|
self.forceUpdates = forceUpdates
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Initialize a property representing a state in the view with an autoclosure.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - wrappedValue: The wrapped value.
|
||||||
|
/// - blockUpdates: Whether updates to this state value should not update the UI.
|
||||||
|
///
|
||||||
|
/// This can be useful for storing data and reading this data on special occasions, e.g. on startup.
|
||||||
|
public init(wrappedValue: @autoclosure @escaping () -> Value, blockUpdates: Bool) {
|
||||||
|
getInitialValue = wrappedValue
|
||||||
|
self.blockUpdates = blockUpdates
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialize a property representing a state in the view with an explicit closure.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - wrappedValue: Get the wrapped value.
|
||||||
|
/// - writeValue: Perform additional operations when the value changes.
|
||||||
|
/// - forceUpdates: Whether to force update all available views when the property gets modified.
|
||||||
|
/// - blockUpdates: Whether updates to this state value should not update the UI.
|
||||||
|
///
|
||||||
|
/// This initializer can be used e.g. to get data from the disk.
|
||||||
|
public init(
|
||||||
|
wrappedValue: @escaping () -> Value,
|
||||||
|
writeValue: ((Value) -> Void)? = nil,
|
||||||
|
forceUpdates: Bool = false,
|
||||||
|
blockUpdates: Bool = false
|
||||||
|
) {
|
||||||
|
getInitialValue = wrappedValue
|
||||||
|
self.writeValue = writeValue
|
||||||
|
self.forceUpdates = forceUpdates
|
||||||
|
self.blockUpdates = blockUpdates
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the initial value.
|
/// Get the initial value.
|
||||||
/// - Returns: The initial value.
|
/// - Returns: The initial value.
|
||||||
func initialValue() -> Value {
|
func initialValue() -> Value {
|
||||||
|
|||||||
@ -12,8 +12,6 @@ public enum StateManager {
|
|||||||
|
|
||||||
/// Whether to block updates in general.
|
/// Whether to block updates in general.
|
||||||
public static var blockUpdates = false
|
public static var blockUpdates = false
|
||||||
/// The application identifier.
|
|
||||||
static var appID: String?
|
|
||||||
/// The functions handling view updates.
|
/// The functions handling view updates.
|
||||||
static var updateHandlers: [(Bool) -> Void] = []
|
static var updateHandlers: [(Bool) -> Void] = []
|
||||||
|
|
||||||
|
|||||||
@ -11,8 +11,7 @@
|
|||||||
/// @main
|
/// @main
|
||||||
/// struct Test: App {
|
/// struct Test: App {
|
||||||
///
|
///
|
||||||
/// let id = "io.github.AparokshaUI.TestApp"
|
/// let app = BackendApp()
|
||||||
/// var app: BackendApp!
|
|
||||||
///
|
///
|
||||||
/// var scene: Scene {
|
/// var scene: Scene {
|
||||||
/// WindowScene()
|
/// WindowScene()
|
||||||
@ -26,14 +25,10 @@ public protocol App {
|
|||||||
/// The app storage type.
|
/// The app storage type.
|
||||||
associatedtype Storage: AppStorage
|
associatedtype Storage: AppStorage
|
||||||
|
|
||||||
/// The app's application ID.
|
|
||||||
var id: String { get }
|
|
||||||
/// The app's scene.
|
/// The app's scene.
|
||||||
@SceneBuilder var scene: Scene { get }
|
@SceneBuilder var scene: Scene { get }
|
||||||
// swiftlint:disable implicitly_unwrapped_optional
|
|
||||||
/// The app storage.
|
/// The app storage.
|
||||||
var app: Storage! { get set }
|
var app: Storage { get }
|
||||||
// swiftlint:enable implicitly_unwrapped_optional
|
|
||||||
|
|
||||||
/// An app has to have an `init()` initializer.
|
/// An app has to have an `init()` initializer.
|
||||||
init()
|
init()
|
||||||
@ -50,6 +45,7 @@ extension App {
|
|||||||
for element in app.scene where element is Storage.SceneElementType {
|
for element in app.scene where element is Storage.SceneElementType {
|
||||||
element.setupInitialContainers(app: app.app)
|
element.setupInitialContainers(app: app.app)
|
||||||
}
|
}
|
||||||
|
StateManager.updateViews(force: true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,8 +54,7 @@ extension App {
|
|||||||
///
|
///
|
||||||
/// To run the app, call the ``AppStorage/run(setup:)`` function.
|
/// To run the app, call the ``AppStorage/run(setup:)`` function.
|
||||||
public static func setupApp() -> Self {
|
public static func setupApp() -> Self {
|
||||||
var appInstance = self.init()
|
let appInstance = self.init()
|
||||||
appInstance.app = Storage(id: appInstance.id)
|
|
||||||
appInstance.app.storage.app = { appInstance }
|
appInstance.app.storage.app = { appInstance }
|
||||||
StateManager.addUpdateHandler { force in
|
StateManager.addUpdateHandler { force in
|
||||||
let updateProperties = force || appInstance.getState().contains { $0.value.content.update }
|
let updateProperties = force || appInstance.getState().contains { $0.value.content.update }
|
||||||
@ -77,7 +72,6 @@ extension App {
|
|||||||
appInstance.app.storage.sceneStorage.remove(at: index)
|
appInstance.app.storage.sceneStorage.remove(at: index)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
StateManager.appID = appInstance.id
|
|
||||||
let state = appInstance.getState()
|
let state = appInstance.getState()
|
||||||
appInstance.app.storage.stateStorage = state
|
appInstance.app.storage.stateStorage = state
|
||||||
return appInstance
|
return appInstance
|
||||||
|
|||||||
@ -14,10 +14,6 @@ public protocol AppStorage: AnyObject {
|
|||||||
/// The scene storage.
|
/// The scene storage.
|
||||||
var storage: StandardAppStorage { get set }
|
var storage: StandardAppStorage { get set }
|
||||||
|
|
||||||
/// Initialize the app storage.
|
|
||||||
/// - Parameters id: The app's identifier.
|
|
||||||
init(id: String)
|
|
||||||
|
|
||||||
/// Run the application.
|
/// Run the application.
|
||||||
/// - Parameter setup: A closure that is expected to be executed right at the beginning.
|
/// - Parameter setup: A closure that is expected to be executed right at the beginning.
|
||||||
func run(setup: @escaping () -> Void)
|
func run(setup: @escaping () -> Void)
|
||||||
@ -33,7 +29,12 @@ extension AppStorage {
|
|||||||
/// Focus the scene element with a certain id (if supported). Create the element if it doesn't already exist.
|
/// Focus the scene element with a certain id (if supported). Create the element if it doesn't already exist.
|
||||||
/// - Parameter id: The element's id.
|
/// - Parameter id: The element's id.
|
||||||
public func showSceneElement(_ id: String) {
|
public func showSceneElement(_ id: String) {
|
||||||
storage.sceneStorage.last { $0.id == id && !$0.destroy }?.show() ?? addSceneElement(id)
|
guard let storage = storage.sceneStorage.last(where: { $0.id == id && !$0.destroy }) else {
|
||||||
|
addSceneElement(id)
|
||||||
|
StateManager.updateViews(force: true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
storage.show()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add a new scene element with the content of the scene element with a certain id.
|
/// Add a new scene element with the content of the scene element with a certain id.
|
||||||
@ -43,6 +44,7 @@ extension AppStorage {
|
|||||||
let container = element.container(app: self)
|
let container = element.container(app: self)
|
||||||
storage.sceneStorage.append(container)
|
storage.sceneStorage.append(container)
|
||||||
showSceneElement(id)
|
showSceneElement(id)
|
||||||
|
StateManager.updateViews(force: true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -6,6 +6,8 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
/// A view building conditional bodies.
|
/// A view building conditional bodies.
|
||||||
|
///
|
||||||
|
/// Do not forget to call the update function after constructing a new UI.
|
||||||
public protocol EitherView: AnyView {
|
public protocol EitherView: AnyView {
|
||||||
|
|
||||||
/// Initialize the either view.
|
/// Initialize the either view.
|
||||||
|
|||||||
@ -143,7 +143,6 @@ extension Widget {
|
|||||||
) -> ViewStorage where Data: ViewRenderData {
|
) -> ViewStorage where Data: ViewRenderData {
|
||||||
let storage = ViewStorage(initializeWidget())
|
let storage = ViewStorage(initializeWidget())
|
||||||
initProperties(storage, data: data, type: type)
|
initProperties(storage, data: data, type: type)
|
||||||
update(storage, data: data, updateProperties: true, type: type)
|
|
||||||
return storage
|
return storage
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -180,9 +179,7 @@ extension Widget {
|
|||||||
let mirror = Mirror(reflecting: self)
|
let mirror = Mirror(reflecting: self)
|
||||||
for property in mirror.children {
|
for property in mirror.children {
|
||||||
if let value = property.value as? any ViewPropertyProtocol {
|
if let value = property.value as? any ViewPropertyProtocol {
|
||||||
let subview = value.wrappedValue.storage(data: data, type: type)
|
initViewProperty(value, data: data, parent: storage, label: property.label ?? .mainContent, type: type)
|
||||||
initViewProperty(value, view: subview, parent: storage)
|
|
||||||
storage.content[property.label ?? .mainContent] = [subview]
|
|
||||||
}
|
}
|
||||||
if let value = property.value as? any BindingPropertyProtocol {
|
if let value = property.value as? any BindingPropertyProtocol {
|
||||||
initBindingProperty(value, parent: storage)
|
initBindingProperty(value, parent: storage)
|
||||||
@ -193,16 +190,26 @@ extension Widget {
|
|||||||
/// Initialize the properties wrapped with ``ViewProperty``.
|
/// Initialize the properties wrapped with ``ViewProperty``.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - value: The property.
|
/// - value: The property.
|
||||||
/// - view: The subview's view storage.
|
/// - data: The widget data.
|
||||||
/// - parent: The parent's view storage.
|
/// - parent: The parent's view storage.
|
||||||
func initViewProperty<Property>(
|
/// - label: The view content label.
|
||||||
|
/// - type: The view context type of the parent view.
|
||||||
|
func initViewProperty<Property, ParentContext>(
|
||||||
_ value: Property,
|
_ value: Property,
|
||||||
view: ViewStorage,
|
data: WidgetData,
|
||||||
parent: ViewStorage
|
parent: ViewStorage,
|
||||||
) where Property: ViewPropertyProtocol {
|
label: String,
|
||||||
if let view = view.pointer as? Property.ViewPointer, let pointer = parent.pointer as? Property.Pointer {
|
type: ParentContext.Type
|
||||||
|
) where Property: ViewPropertyProtocol, ParentContext: ViewRenderData {
|
||||||
|
var data = data
|
||||||
|
if type != Property.ViewContext.self {
|
||||||
|
data = data.noModifiers
|
||||||
|
}
|
||||||
|
let subview = value.wrappedValue.storage(data: data, type: Property.ViewContext.self)
|
||||||
|
if let view = subview.pointer as? Property.ViewPointer, let pointer = parent.pointer as? Property.Pointer {
|
||||||
value.setView(pointer, view)
|
value.setView(pointer, view)
|
||||||
}
|
}
|
||||||
|
parent.content[label] = [subview]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Initialize a binding property.
|
/// Initialize a binding property.
|
||||||
@ -226,143 +233,6 @@ extension Widget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update the properties wrapped with ``Property``.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - storage: The storage to update.
|
|
||||||
/// - data: The widget data.
|
|
||||||
/// - updateProperties: Whether to update the view's properties.
|
|
||||||
/// - type: The view render data type.
|
|
||||||
public func updateProperties<Data>(
|
|
||||||
_ storage: ViewStorage,
|
|
||||||
data: WidgetData,
|
|
||||||
updateProperties: Bool,
|
|
||||||
type: Data.Type
|
|
||||||
) where Data: ViewRenderData {
|
|
||||||
let mirror = Mirror(reflecting: self)
|
|
||||||
updateNotEquatable(mirror: mirror, storage: storage, data: data, updateProperties: updateProperties, type: type)
|
|
||||||
guard updateProperties else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
updateAlwaysWhenStateUpdate(mirror: mirror, storage: storage)
|
|
||||||
updateEquatable(mirror: mirror, storage: storage)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update the properties which are not equatable and should always be updated (e.g. closures).
|
|
||||||
/// - Parameters:
|
|
||||||
/// - mirror: A mirror of the widget.
|
|
||||||
/// - storage: The view storage.
|
|
||||||
/// - data: The widget data.
|
|
||||||
/// - updateProperties: Whether to update the properties.
|
|
||||||
/// - type: The view render data type.
|
|
||||||
func updateNotEquatable<Data>(
|
|
||||||
mirror: Mirror,
|
|
||||||
storage: ViewStorage,
|
|
||||||
data: WidgetData,
|
|
||||||
updateProperties: Bool,
|
|
||||||
type: Data.Type
|
|
||||||
) where Data: ViewRenderData {
|
|
||||||
for property in mirror.children {
|
|
||||||
if let value = property.value as? any PropertyProtocol {
|
|
||||||
if value.updateStrategy == .always ||
|
|
||||||
value.wrappedValue as? any Equatable == nil && value.updateStrategy != .alwaysWhenStateUpdate {
|
|
||||||
setProperty(property: value, storage: storage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let value = property.value as? any ViewPropertyProtocol,
|
|
||||||
let storage = storage.content[property.label ?? .mainContent]?.first {
|
|
||||||
value.wrappedValue.updateStorage(storage, data: data, updateProperties: updateProperties, type: type)
|
|
||||||
}
|
|
||||||
if let value = property.value as? any BindingPropertyProtocol {
|
|
||||||
setBindingProperty(property: value, storage: storage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update the properties which should always be updated when a state property changed
|
|
||||||
/// (e.g. "regular" properties which are not equatable).
|
|
||||||
/// - Parameters:
|
|
||||||
/// - mirror: A mirror of the widget.
|
|
||||||
/// - storage: The view storage.
|
|
||||||
///
|
|
||||||
/// Initialize the ``Property`` property wrapper with the ``UpdateStrategy/alwaysWhenStateUpdate``.
|
|
||||||
func updateAlwaysWhenStateUpdate(mirror: Mirror, storage: ViewStorage) {
|
|
||||||
for property in mirror.children {
|
|
||||||
if let value = property.value as? any PropertyProtocol {
|
|
||||||
if value.updateStrategy == .alwaysWhenStateUpdate {
|
|
||||||
setProperty(property: value, storage: storage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update equatable properties (most properties).
|
|
||||||
/// - Parameters:
|
|
||||||
/// - mirror: A mirror of the widget.
|
|
||||||
/// - storage: The view storage.
|
|
||||||
func updateEquatable(mirror: Mirror, storage: ViewStorage) {
|
|
||||||
let previousState: Mirror.Children? = if let previousState = storage.previousState {
|
|
||||||
Mirror(reflecting: previousState).children
|
|
||||||
} else {
|
|
||||||
nil
|
|
||||||
}
|
|
||||||
for property in mirror.children {
|
|
||||||
if let value = property.value as? any PropertyProtocol,
|
|
||||||
value.updateStrategy == .automatic,
|
|
||||||
let wrappedValue = value.wrappedValue as? any Equatable {
|
|
||||||
var update = true
|
|
||||||
if let previous = previousState?.first(where: { previousProperty in
|
|
||||||
previousProperty.label == property.label
|
|
||||||
})?.value as? any PropertyProtocol,
|
|
||||||
equal(previous, wrappedValue) {
|
|
||||||
update = false
|
|
||||||
}
|
|
||||||
if update {
|
|
||||||
setProperty(property: value, storage: storage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check whether a property is equal to a value.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - property: The property.
|
|
||||||
/// - value: The value.
|
|
||||||
/// - Returns: Whether the property and value are equal.
|
|
||||||
func equal<Property, Value>(
|
|
||||||
_ property: Property,
|
|
||||||
_ value: Value
|
|
||||||
) -> Bool where Property: PropertyProtocol, Value: Equatable {
|
|
||||||
equal(property.wrappedValue, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check whether a value is equal to another value.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - value1: The first value.
|
|
||||||
/// - value2: The second value.
|
|
||||||
/// - Returns: Whether the values are equal.
|
|
||||||
func equal<Value1, Value2>(
|
|
||||||
_ value1: Value1,
|
|
||||||
_ value2: Value2
|
|
||||||
) -> Bool where Value2: Equatable {
|
|
||||||
if let value1 = value1 as? Value2 {
|
|
||||||
return value1 == value2
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Apply a property to the framework.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - property: The property.
|
|
||||||
/// - storage: The view storage.
|
|
||||||
func setProperty<Property>(property: Property, storage: ViewStorage) where Property: PropertyProtocol {
|
|
||||||
if let optional = property.wrappedValue as? any OptionalProtocol, optional.optionalValue == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if let pointer = storage.pointer as? Property.Pointer {
|
|
||||||
property.setProperty(pointer, property.wrappedValue, storage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A protocol for values which can be optional.
|
/// A protocol for values which can be optional.
|
||||||
|
|||||||
@ -10,7 +10,7 @@
|
|||||||
/// This will be used if you do not provide a custom ``Widget/update(_:data:updateProperties:type:)`` method
|
/// This will be used if you do not provide a custom ``Widget/update(_:data:updateProperties:type:)`` method
|
||||||
/// or call the ``Widget/updateProperties(_:updateProperties:)`` method in your custom update method.
|
/// or call the ``Widget/updateProperties(_:updateProperties:)`` method in your custom update method.
|
||||||
@propertyWrapper
|
@propertyWrapper
|
||||||
public struct ViewProperty<Pointer, ViewPointer>: ViewPropertyProtocol {
|
public struct ViewProperty<Pointer, ViewPointer, ViewContext>: ViewPropertyProtocol where ViewContext: ViewRenderData {
|
||||||
|
|
||||||
/// The wrapped value.
|
/// The wrapped value.
|
||||||
public var wrappedValue: Body = []
|
public var wrappedValue: Body = []
|
||||||
@ -22,10 +22,12 @@ public struct ViewProperty<Pointer, ViewPointer>: ViewPropertyProtocol {
|
|||||||
/// - setView: Set the view.
|
/// - setView: Set the view.
|
||||||
/// - pointer: The pointer type of the parent view (usually a concrete view type).
|
/// - pointer: The pointer type of the parent view (usually a concrete view type).
|
||||||
/// - subview: The pointer type of the child view (usually a protocol, view class, or similar).
|
/// - subview: The pointer type of the child view (usually a protocol, view class, or similar).
|
||||||
|
/// - context: The view render data type.
|
||||||
public init(
|
public init(
|
||||||
set setView: @escaping (Pointer, ViewPointer) -> Void,
|
set setView: @escaping (Pointer, ViewPointer) -> Void,
|
||||||
pointer: Pointer.Type,
|
pointer: Pointer.Type,
|
||||||
subview: ViewPointer.Type
|
subview: ViewPointer.Type,
|
||||||
|
context: ViewContext.Type
|
||||||
) {
|
) {
|
||||||
self.setView = setView
|
self.setView = setView
|
||||||
}
|
}
|
||||||
@ -41,6 +43,8 @@ protocol ViewPropertyProtocol {
|
|||||||
associatedtype Pointer
|
associatedtype Pointer
|
||||||
/// The type of the view's content.
|
/// The type of the view's content.
|
||||||
associatedtype ViewPointer
|
associatedtype ViewPointer
|
||||||
|
/// The view render data type.
|
||||||
|
associatedtype ViewContext: ViewRenderData
|
||||||
|
|
||||||
/// The wrapped value.
|
/// The wrapped value.
|
||||||
var wrappedValue: Body { get }
|
var wrappedValue: Body { get }
|
||||||
|
|||||||
175
Sources/Model/User Interface/View/Properties/Widget+.swift
Normal file
175
Sources/Model/User Interface/View/Properties/Widget+.swift
Normal file
@ -0,0 +1,175 @@
|
|||||||
|
//
|
||||||
|
// Property+.swift
|
||||||
|
// Meta
|
||||||
|
//
|
||||||
|
// Created by david-swift on 14.10.24.
|
||||||
|
//
|
||||||
|
|
||||||
|
extension Widget {
|
||||||
|
|
||||||
|
/// Update the properties wrapped with ``Property``.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - storage: The storage to update.
|
||||||
|
/// - data: The widget data.
|
||||||
|
/// - updateProperties: Whether to update the view's properties.
|
||||||
|
/// - type: The view render data type.
|
||||||
|
public func updateProperties<Data>(
|
||||||
|
_ storage: ViewStorage,
|
||||||
|
data: WidgetData,
|
||||||
|
updateProperties: Bool,
|
||||||
|
type: Data.Type
|
||||||
|
) where Data: ViewRenderData {
|
||||||
|
let mirror = Mirror(reflecting: self)
|
||||||
|
updateNotEquatable(mirror: mirror, storage: storage, data: data, updateProperties: updateProperties, type: type)
|
||||||
|
guard updateProperties else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updateAlwaysWhenStateUpdate(mirror: mirror, storage: storage)
|
||||||
|
updateEquatable(mirror: mirror, storage: storage)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the properties which are not equatable and should always be updated (e.g. closures).
|
||||||
|
/// - Parameters:
|
||||||
|
/// - mirror: A mirror of the widget.
|
||||||
|
/// - storage: The view storage.
|
||||||
|
/// - data: The widget data.
|
||||||
|
/// - updateProperties: Whether to update the properties.
|
||||||
|
/// - type: The view render data type.
|
||||||
|
func updateNotEquatable<Data>(
|
||||||
|
mirror: Mirror,
|
||||||
|
storage: ViewStorage,
|
||||||
|
data: WidgetData,
|
||||||
|
updateProperties: Bool,
|
||||||
|
type: Data.Type
|
||||||
|
) where Data: ViewRenderData {
|
||||||
|
for property in mirror.children {
|
||||||
|
if let value = property.value as? any PropertyProtocol {
|
||||||
|
if value.updateStrategy == .always ||
|
||||||
|
value.wrappedValue as? any Equatable == nil && value.updateStrategy != .alwaysWhenStateUpdate {
|
||||||
|
setProperty(property: value, storage: storage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let value = property.value as? any ViewPropertyProtocol,
|
||||||
|
let storage = storage.content[property.label ?? .mainContent]?.first {
|
||||||
|
updateViewProperty(
|
||||||
|
value: value,
|
||||||
|
storage: storage,
|
||||||
|
data: data,
|
||||||
|
updateProperties: updateProperties,
|
||||||
|
type: type
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if let value = property.value as? any BindingPropertyProtocol {
|
||||||
|
setBindingProperty(property: value, storage: storage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update a view property.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - value: The property.
|
||||||
|
/// - storage: The view storage.
|
||||||
|
/// - data: The widget data.
|
||||||
|
/// - updateProperties: Whether to update the properties.
|
||||||
|
/// - type: The parent context type.
|
||||||
|
func updateViewProperty<Property, ParentContext>(
|
||||||
|
value: Property,
|
||||||
|
storage: ViewStorage,
|
||||||
|
data: WidgetData,
|
||||||
|
updateProperties: Bool,
|
||||||
|
type: ParentContext.Type
|
||||||
|
) where Property: ViewPropertyProtocol, ParentContext: ViewRenderData {
|
||||||
|
var data = data
|
||||||
|
if type != Property.ViewContext.self {
|
||||||
|
data = data.noModifiers
|
||||||
|
}
|
||||||
|
value.wrappedValue
|
||||||
|
.updateStorage(storage, data: data, updateProperties: updateProperties, type: Property.ViewContext.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the properties which should always be updated when a state property changed
|
||||||
|
/// (e.g. "regular" properties which are not equatable).
|
||||||
|
/// - Parameters:
|
||||||
|
/// - mirror: A mirror of the widget.
|
||||||
|
/// - storage: The view storage.
|
||||||
|
///
|
||||||
|
/// Initialize the ``Property`` property wrapper with the ``UpdateStrategy/alwaysWhenStateUpdate``.
|
||||||
|
func updateAlwaysWhenStateUpdate(mirror: Mirror, storage: ViewStorage) {
|
||||||
|
for property in mirror.children {
|
||||||
|
if let value = property.value as? any PropertyProtocol {
|
||||||
|
if value.updateStrategy == .alwaysWhenStateUpdate {
|
||||||
|
setProperty(property: value, storage: storage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update equatable properties (most properties).
|
||||||
|
/// - Parameters:
|
||||||
|
/// - mirror: A mirror of the widget.
|
||||||
|
/// - storage: The view storage.
|
||||||
|
func updateEquatable(mirror: Mirror, storage: ViewStorage) {
|
||||||
|
let previousState: Mirror.Children? = if let previousState = storage.previousState {
|
||||||
|
Mirror(reflecting: previousState).children
|
||||||
|
} else {
|
||||||
|
nil
|
||||||
|
}
|
||||||
|
for property in mirror.children {
|
||||||
|
if let value = property.value as? any PropertyProtocol,
|
||||||
|
value.updateStrategy == .automatic,
|
||||||
|
let wrappedValue = value.wrappedValue as? any Equatable {
|
||||||
|
var update = true
|
||||||
|
if let previous = previousState?.first(where: { previousProperty in
|
||||||
|
previousProperty.label == property.label
|
||||||
|
})?.value as? any PropertyProtocol,
|
||||||
|
equal(previous, wrappedValue) {
|
||||||
|
update = false
|
||||||
|
}
|
||||||
|
if update {
|
||||||
|
setProperty(property: value, storage: storage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether a property is equal to a value.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - property: The property.
|
||||||
|
/// - value: The value.
|
||||||
|
/// - Returns: Whether the property and value are equal.
|
||||||
|
func equal<Property, Value>(
|
||||||
|
_ property: Property,
|
||||||
|
_ value: Value
|
||||||
|
) -> Bool where Property: PropertyProtocol, Value: Equatable {
|
||||||
|
equal(property.wrappedValue, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether a value is equal to another value.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - value1: The first value.
|
||||||
|
/// - value2: The second value.
|
||||||
|
/// - Returns: Whether the values are equal.
|
||||||
|
func equal<Value1, Value2>(
|
||||||
|
_ value1: Value1,
|
||||||
|
_ value2: Value2
|
||||||
|
) -> Bool where Value2: Equatable {
|
||||||
|
if let value1 = value1 as? Value2 {
|
||||||
|
return value1 == value2
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply a property to the framework.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - property: The property.
|
||||||
|
/// - storage: The view storage.
|
||||||
|
func setProperty<Property>(property: Property, storage: ViewStorage) where Property: PropertyProtocol {
|
||||||
|
if let optional = property.wrappedValue as? any OptionalProtocol, optional.optionalValue == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if let pointer = storage.pointer as? Property.Pointer {
|
||||||
|
property.setProperty(pointer, property.wrappedValue, storage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -32,7 +32,7 @@ extension View {
|
|||||||
|
|
||||||
/// The view's content.
|
/// The view's content.
|
||||||
public var viewContent: Body {
|
public var viewContent: Body {
|
||||||
[StateWrapper(content: { view }, state: getState())]
|
[StateWrapper(content: { view }, state: getState(), environment: getEnvironmentVariables())]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the state from the properties.
|
/// Get the state from the properties.
|
||||||
@ -47,4 +47,16 @@ extension View {
|
|||||||
return state
|
return state
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the environment properties.
|
||||||
|
/// - Returns: The environment properties.
|
||||||
|
func getEnvironmentVariables() -> [String: any EnvironmentProtocol] {
|
||||||
|
var environment: [String: any EnvironmentProtocol] = [:]
|
||||||
|
for property in Mirror(reflecting: self).children {
|
||||||
|
if let label = property.label, let value = property.value as? any EnvironmentProtocol {
|
||||||
|
environment[label] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return environment
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -9,7 +9,7 @@
|
|||||||
struct AppearObserver: ConvenienceWidget {
|
struct AppearObserver: ConvenienceWidget {
|
||||||
|
|
||||||
/// The custom code to edit the widget.
|
/// The custom code to edit the widget.
|
||||||
var modify: (ViewStorage) -> Void
|
var modify: (ViewStorage, WidgetData) -> Void
|
||||||
/// The wrapped view.
|
/// The wrapped view.
|
||||||
var content: AnyView
|
var content: AnyView
|
||||||
|
|
||||||
@ -23,7 +23,7 @@ struct AppearObserver: ConvenienceWidget {
|
|||||||
type: Data.Type
|
type: Data.Type
|
||||||
) -> ViewStorage where Data: ViewRenderData {
|
) -> ViewStorage where Data: ViewRenderData {
|
||||||
let storage = content.storage(data: data, type: type)
|
let storage = content.storage(data: data, type: type)
|
||||||
modify(storage)
|
modify(storage, data)
|
||||||
return storage
|
return storage
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,10 +50,17 @@ extension AnyView {
|
|||||||
/// Run a function on the widget when it appears for the first time.
|
/// Run a function on the widget when it appears for the first time.
|
||||||
/// - Parameter closure: The function.
|
/// - Parameter closure: The function.
|
||||||
/// - Returns: A view.
|
/// - Returns: A view.
|
||||||
public func inspectOnAppear(_ closure: @escaping (ViewStorage) -> Void) -> AnyView {
|
public func inspectOnAppear(_ closure: @escaping (ViewStorage, WidgetData) -> Void) -> AnyView {
|
||||||
AppearObserver(modify: closure, content: self)
|
AppearObserver(modify: closure, content: self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Run a function on the widget when it appears for the first time.
|
||||||
|
/// - Parameter closure: The function.
|
||||||
|
/// - Returns: A view.
|
||||||
|
public func inspectOnAppear(_ closure: @escaping (ViewStorage) -> Void) -> AnyView {
|
||||||
|
inspectOnAppear { storage, _ in closure(storage) }
|
||||||
|
}
|
||||||
|
|
||||||
/// Run a function when the view appears for the first time.
|
/// Run a function when the view appears for the first time.
|
||||||
/// - Parameter closure: The function.
|
/// - Parameter closure: The function.
|
||||||
/// - Returns: A view.
|
/// - Returns: A view.
|
||||||
|
|||||||
67
Sources/View/DataWrapper.swift
Normal file
67
Sources/View/DataWrapper.swift
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
//
|
||||||
|
// StateWrapper.swift
|
||||||
|
// Meta
|
||||||
|
//
|
||||||
|
// Created by david-swift on 09.06.24.
|
||||||
|
//
|
||||||
|
|
||||||
|
/// Assign values to the environment.
|
||||||
|
///
|
||||||
|
/// Access the environment in views (``View``) via `@Environment`.
|
||||||
|
struct DataWrapper: ConvenienceWidget {
|
||||||
|
|
||||||
|
/// The content.
|
||||||
|
var content: Body
|
||||||
|
/// The identifier for the new environment value.
|
||||||
|
var label: String
|
||||||
|
/// The environment value.
|
||||||
|
var data: Any
|
||||||
|
|
||||||
|
/// Get a view storage.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - data: Modify views before being updated.
|
||||||
|
/// - type: The view render data type.
|
||||||
|
/// - Returns: The view storage.
|
||||||
|
func container<Data>(
|
||||||
|
data: WidgetData,
|
||||||
|
type: Data.Type
|
||||||
|
) -> ViewStorage where Data: ViewRenderData {
|
||||||
|
content.storage(data: data.modify { $0.fields[label] = self.data }, type: type)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update a view storage.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - storage: The view storage.
|
||||||
|
/// - data: Modify views before being updated.
|
||||||
|
/// - updateProperties: Whether to update properties.
|
||||||
|
/// - type: The view render data type.
|
||||||
|
/// - Returns: The view storage.
|
||||||
|
func update<Data>(
|
||||||
|
_ storage: ViewStorage,
|
||||||
|
data: WidgetData,
|
||||||
|
updateProperties: Bool,
|
||||||
|
type: Data.Type
|
||||||
|
) where Data: ViewRenderData {
|
||||||
|
content
|
||||||
|
.updateStorage(
|
||||||
|
storage,
|
||||||
|
data: data.modify { $0.fields[label] = self.data },
|
||||||
|
updateProperties: updateProperties,
|
||||||
|
type: type
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension AnyView {
|
||||||
|
|
||||||
|
/// Assign a value to an environment label.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - label: The environment label.
|
||||||
|
/// - data: The value.
|
||||||
|
/// - Returns: The view.
|
||||||
|
public func environment(_ label: String, data: Any) -> AnyView {
|
||||||
|
DataWrapper(content: [self], label: label, data: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -9,7 +9,7 @@
|
|||||||
struct InspectorWrapper: ConvenienceWidget {
|
struct InspectorWrapper: ConvenienceWidget {
|
||||||
|
|
||||||
/// The custom code to edit the widget.
|
/// The custom code to edit the widget.
|
||||||
var modify: (ViewStorage, Bool) -> Void
|
var modify: (ViewStorage, WidgetData, Bool) -> Void
|
||||||
/// The wrapped view.
|
/// The wrapped view.
|
||||||
var content: AnyView
|
var content: AnyView
|
||||||
|
|
||||||
@ -22,9 +22,7 @@ struct InspectorWrapper: ConvenienceWidget {
|
|||||||
data: WidgetData,
|
data: WidgetData,
|
||||||
type: Data.Type
|
type: Data.Type
|
||||||
) -> ViewStorage where Data: ViewRenderData {
|
) -> ViewStorage where Data: ViewRenderData {
|
||||||
let storage = content.storage(data: data, type: type)
|
content.storage(data: data, type: type)
|
||||||
modify(storage, true)
|
|
||||||
return storage
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update the stored content.
|
/// Update the stored content.
|
||||||
@ -40,7 +38,7 @@ struct InspectorWrapper: ConvenienceWidget {
|
|||||||
type: Data.Type
|
type: Data.Type
|
||||||
) where Data: ViewRenderData {
|
) where Data: ViewRenderData {
|
||||||
content.updateStorage(storage, data: data, updateProperties: updateProperties, type: type)
|
content.updateStorage(storage, data: data, updateProperties: updateProperties, type: type)
|
||||||
modify(storage, updateProperties)
|
modify(storage, data, updateProperties)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -51,10 +49,17 @@ extension AnyView {
|
|||||||
/// Run a custom code accessing the view's storage when initializing and updating the view.
|
/// Run a custom code accessing the view's storage when initializing and updating the view.
|
||||||
/// - Parameter modify: Modify the storage. The boolean indicates whether state in parent views changed.
|
/// - Parameter modify: Modify the storage. The boolean indicates whether state in parent views changed.
|
||||||
/// - Returns: A view.
|
/// - Returns: A view.
|
||||||
public func inspect(_ modify: @escaping (ViewStorage, Bool) -> Void) -> AnyView {
|
public func inspect(_ modify: @escaping (ViewStorage, WidgetData, Bool) -> Void) -> AnyView {
|
||||||
InspectorWrapper(modify: modify, content: self)
|
InspectorWrapper(modify: modify, content: self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Run a custom code accessing the view's storage when initializing and updating the view.
|
||||||
|
/// - Parameter modify: Modify the storage. The boolean indicates whether state in parent views changed.
|
||||||
|
/// - Returns: A view.
|
||||||
|
public func inspect(_ modify: @escaping (ViewStorage, Bool) -> Void) -> AnyView {
|
||||||
|
inspect { storage, _, updateProperties in modify(storage, updateProperties) }
|
||||||
|
}
|
||||||
|
|
||||||
/// Run a function when the view gets updated.
|
/// Run a function when the view gets updated.
|
||||||
/// - Parameter onUpdate: The function.
|
/// - Parameter onUpdate: The function.
|
||||||
/// - Returns: A view.
|
/// - Returns: A view.
|
||||||
|
|||||||
91
Sources/View/SafeWrapper.swift
Normal file
91
Sources/View/SafeWrapper.swift
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
//
|
||||||
|
// SafeWrapper.swift
|
||||||
|
// Meta
|
||||||
|
//
|
||||||
|
// Created by david-swift on 02.02.26.
|
||||||
|
//
|
||||||
|
|
||||||
|
/// Wrap a widget but keep its pointer.
|
||||||
|
struct SafeWrapper: ConvenienceWidget {
|
||||||
|
|
||||||
|
/// The custom code to edit the wrapper.
|
||||||
|
/// The pointer is the one of the child widget.
|
||||||
|
var modify: (ViewStorage, WidgetData, Bool) -> Void
|
||||||
|
/// The wrapped view.
|
||||||
|
var content: AnyView
|
||||||
|
|
||||||
|
/// The view storage.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - data: Modify views before being updated.
|
||||||
|
/// - type: The view render data type.
|
||||||
|
/// - Returns: The view storage.
|
||||||
|
func container<Data>(
|
||||||
|
data: WidgetData,
|
||||||
|
type: Data.Type
|
||||||
|
) -> ViewStorage where Data: ViewRenderData {
|
||||||
|
let contentStorage = content.storage(data: data, type: type)
|
||||||
|
return .init(contentStorage.pointer, content: [.mainContent: [contentStorage]])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the stored content.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - storage: The storage to update.
|
||||||
|
/// - data: Modify views before being updated
|
||||||
|
/// - updateProperties: Whether to update the view's properties.
|
||||||
|
/// - type: The view render data type.
|
||||||
|
func update<Data>(
|
||||||
|
_ storage: ViewStorage,
|
||||||
|
data: WidgetData,
|
||||||
|
updateProperties: Bool,
|
||||||
|
type: Data.Type
|
||||||
|
) where Data: ViewRenderData {
|
||||||
|
if let contentStorage = storage.content[.mainContent]?.first {
|
||||||
|
content.updateStorage(contentStorage, data: data, updateProperties: updateProperties, type: type)
|
||||||
|
}
|
||||||
|
modify(storage, data, updateProperties)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extend any view.
|
||||||
|
extension AnyView {
|
||||||
|
|
||||||
|
/// Wrap a widget but keep its pointer.
|
||||||
|
/// - Parameter modify: Modify the storage. The boolean indicates whether state in parent views changed.
|
||||||
|
/// - Returns: A view.
|
||||||
|
public func wrap(_ modify: @escaping (ViewStorage, WidgetData, Bool) -> Void) -> AnyView {
|
||||||
|
SafeWrapper(modify: modify, content: self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wrap a widget but keep its pointer.
|
||||||
|
/// - Parameter modify: Modify the storage. The boolean indicates whether state in parent views changed.
|
||||||
|
/// - Returns: A view.
|
||||||
|
public func wrap(_ modify: @escaping (ViewStorage, Bool) -> Void) -> AnyView {
|
||||||
|
wrap { storage, _, updateProperties in modify(storage, updateProperties) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A wrapper for generic simple modifiers.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - properties: The properties will be stored. Do not change the layout throughout updates.
|
||||||
|
/// - update: If properties change, run this function.
|
||||||
|
/// - Returns: A view.
|
||||||
|
public func wrapModifier(properties: [any Hashable], update: @escaping (ViewStorage) -> Void) -> AnyView {
|
||||||
|
wrap { storage, _, updateProperties in
|
||||||
|
guard updateProperties else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var shouldUpdate = false
|
||||||
|
for (index, property) in properties.enumerated() {
|
||||||
|
let update = {
|
||||||
|
shouldUpdate = true
|
||||||
|
storage.fields[index.description] = property
|
||||||
|
}
|
||||||
|
if let equatable = storage.fields[index.description] as? any Hashable {
|
||||||
|
if property.hashValue != equatable.hashValue { update() }
|
||||||
|
} else { update() }
|
||||||
|
}
|
||||||
|
if shouldUpdate { update(storage) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -12,6 +12,8 @@ struct StateWrapper: ConvenienceWidget {
|
|||||||
var content: () -> Body
|
var content: () -> Body
|
||||||
/// The state information (from properties with the `State` wrapper).
|
/// The state information (from properties with the `State` wrapper).
|
||||||
var state: [String: StateProtocol] = [:]
|
var state: [String: StateProtocol] = [:]
|
||||||
|
/// The environment properties.
|
||||||
|
var environment: [String: any EnvironmentProtocol] = [:]
|
||||||
|
|
||||||
/// Initialize a `StateWrapper`.
|
/// Initialize a `StateWrapper`.
|
||||||
/// - Parameter content: The view content.
|
/// - Parameter content: The view content.
|
||||||
@ -23,9 +25,15 @@ struct StateWrapper: ConvenienceWidget {
|
|||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - content: The view content.
|
/// - content: The view content.
|
||||||
/// - state: The state information.
|
/// - state: The state information.
|
||||||
init(content: @escaping () -> Body, state: [String: StateProtocol]) {
|
/// - environment: The environment properties.
|
||||||
|
init(
|
||||||
|
content: @escaping () -> Body,
|
||||||
|
state: [String: StateProtocol],
|
||||||
|
environment: [String: any EnvironmentProtocol]
|
||||||
|
) {
|
||||||
self.content = content
|
self.content = content
|
||||||
self.state = state
|
self.state = state
|
||||||
|
self.environment = environment
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update a view storage.
|
/// Update a view storage.
|
||||||
@ -51,6 +59,7 @@ struct StateWrapper: ConvenienceWidget {
|
|||||||
property.value.content.update = false
|
property.value.content.update = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
assignEnvironment(data: data)
|
||||||
guard let storage = storage.content[.mainContent]?.first else {
|
guard let storage = storage.content[.mainContent]?.first else {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -66,6 +75,7 @@ struct StateWrapper: ConvenienceWidget {
|
|||||||
data: WidgetData,
|
data: WidgetData,
|
||||||
type: Data.Type
|
type: Data.Type
|
||||||
) -> ViewStorage where Data: ViewRenderData {
|
) -> ViewStorage where Data: ViewRenderData {
|
||||||
|
assignEnvironment(data: data)
|
||||||
let content = content().storage(data: data, type: type)
|
let content = content().storage(data: data, type: type)
|
||||||
let storage = ViewStorage(content.pointer, content: [.mainContent: [content]])
|
let storage = ViewStorage(content.pointer, content: [.mainContent: [content]])
|
||||||
storage.state = state
|
storage.state = state
|
||||||
@ -75,4 +85,12 @@ struct StateWrapper: ConvenienceWidget {
|
|||||||
return storage
|
return storage
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Assign an environment value to the environment property.
|
||||||
|
/// - Parameter data: The widget data.
|
||||||
|
func assignEnvironment(data: WidgetData) {
|
||||||
|
for property in environment {
|
||||||
|
property.value.content.value = data.fields[property.value.id]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
2
Tests/CMakeLists.txt
Normal file
2
Tests/CMakeLists.txt
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
add_subdirectory(SampleBackends)
|
||||||
|
add_subdirectory(DemoApp)
|
||||||
13
Tests/DemoApp/CMakeLists.txt
Normal file
13
Tests/DemoApp/CMakeLists.txt
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
add_executable(DemoApp
|
||||||
|
DemoApp.swift
|
||||||
|
)
|
||||||
|
|
||||||
|
target_compile_options(DemoApp PUBLIC
|
||||||
|
-parse-as-library
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(DemoApp PRIVATE SampleBackends)
|
||||||
|
|
||||||
|
set_target_properties(DemoApp PROPERTIES
|
||||||
|
Swift_LANGUAGE_VERSION 5
|
||||||
|
)
|
||||||
@ -14,16 +14,16 @@ struct TestExecutable {
|
|||||||
|
|
||||||
struct DemoApp: App {
|
struct DemoApp: App {
|
||||||
|
|
||||||
let id = "io.github.AparokshaUI.DemoApp"
|
|
||||||
// #if os(...)
|
// #if os(...)
|
||||||
var app: Backend1.Backend1App!
|
var app = Backend1.Backend1App()
|
||||||
// #else
|
// #else
|
||||||
// var app: Backend2.Backend2App!
|
// var app = Backend2.Backend2App()
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
var scene: Scene {
|
var scene: Scene {
|
||||||
Backend1.Window("main", spawn: 1) {
|
Backend1.Window("main", spawn: 1) {
|
||||||
DemoView(app: app)
|
DemoView(app: app)
|
||||||
|
.environment("test", data: 5)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -32,6 +32,8 @@ struct DemoApp: App {
|
|||||||
struct DemoView: View {
|
struct DemoView: View {
|
||||||
|
|
||||||
@State private var model = TestModel()
|
@State private var model = TestModel()
|
||||||
|
@Environment("test")
|
||||||
|
private var test: Int?
|
||||||
var app: any AppStorage
|
var app: any AppStorage
|
||||||
let condition = false
|
let condition = false
|
||||||
|
|
||||||
@ -47,6 +49,7 @@ struct DemoView: View {
|
|||||||
app.addSceneElement("main")
|
app.addSceneElement("main")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.onAppear { print(test ?? 0) }
|
||||||
}
|
}
|
||||||
TestView()
|
TestView()
|
||||||
testContent
|
testContent
|
||||||
|
|||||||
@ -156,7 +156,7 @@ public enum Backend1 {
|
|||||||
|
|
||||||
public var storage: StandardAppStorage = .init()
|
public var storage: StandardAppStorage = .init()
|
||||||
|
|
||||||
public required init(id: String) { }
|
public init() { }
|
||||||
|
|
||||||
public func run(setup: @escaping () -> Void) {
|
public func run(setup: @escaping () -> Void) {
|
||||||
setup()
|
setup()
|
||||||
|
|||||||
@ -71,7 +71,7 @@ public enum Backend2 {
|
|||||||
|
|
||||||
public var storage: StandardAppStorage = .init()
|
public var storage: StandardAppStorage = .init()
|
||||||
|
|
||||||
public required init(id: String) { }
|
public required init() { }
|
||||||
|
|
||||||
public func run(setup: @escaping () -> Void) {
|
public func run(setup: @escaping () -> Void) {
|
||||||
setup()
|
setup()
|
||||||
|
|||||||
12
Tests/SampleBackends/CMakeLists.txt
Normal file
12
Tests/SampleBackends/CMakeLists.txt
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
add_library(SampleBackends
|
||||||
|
Backend1.swift
|
||||||
|
Backend2.swift
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(SampleBackends
|
||||||
|
PRIVATE Meta
|
||||||
|
)
|
||||||
|
|
||||||
|
set_target_properties(SampleBackends PROPERTIES
|
||||||
|
Swift_LANGUAGE_VERSION 5
|
||||||
|
)
|
||||||
Loading…
x
Reference in New Issue
Block a user