Skip to content

Commit

Permalink
Merge branch 'main' into add-redirected-to-visit-response
Browse files Browse the repository at this point in the history
* main: (44 commits)
  Remove not needed parentheses.
  Move the configuration of the custom user agent prefix to the AppDelegate.
  Register the WebView instance with the bridge when each WKWebView instance is created
  Swap order of parameters
  Fine tune custom user agent setting
  Set session's path config from the global path config.
  Consolidate all global config by moving it in app delegate.
  Add utility func to load path config to the Hotwire enum.
  Move `matchQueryStrings` to `PathConfiguration`.
  Move `registerBridgeComponents` to `AppDelegate`.
  Move comment out of if statements.
  Update documentation for the default navigation controller.
  Document `HotwireNavigationController`.
  Revert "Temporarily configure app to have a tab bar as the root view."
  Remove tab switched check from session.
  Extract `HotwireNavigationController` in its own file.
  Handle tab switched in session.
  Use `viewIsAppearing` instead of `viewWillAppear` to have the correct call sequence.
  Make AppearReason a property on the Visitable protocol.
  Temporarily configure app to have a tab bar as the root view.
  ...
  • Loading branch information
jayohms committed Dec 16, 2024
2 parents eafb13f + 21313e4 commit 8c7f3c5
Show file tree
Hide file tree
Showing 24 changed files with 373 additions and 184 deletions.
File renamed without changes.
19 changes: 17 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,30 @@
# Contributing to Hotwire Native iOS

To set up your development environment:
Note that we have a [code of conduct](/CODE_OF_CONDUCT.md). Please follow it in your interactions with this project.

## Developing locally

Hotwire Native for iOS is built using Swift 5.3 and iOS 14 as its minimum version. To set up your development environment:

1. Clone the repo
1. Open the directory in Xcode to install Swift packages
1. Open the directory in Xcode 15+ to install Swift packages

To run the test suite:

1. Open the directory in Xcode
1. Click Product → Test or <kbd>⌘</kbd>+<kbd>U</kbd>

## Sending a Pull Request

The core team is monitoring for pull requests. We will review your pull request and either merge it, request changes to it, or close it with an explanation.

Before submitting a pull request, please:

1. Fork the repository and create your branch.
2. Follow the setup instructions in this file.
3. If you’re fixing a bug or adding code that should be tested, add tests!
4. Ensure the test suite passes.

## Feature parity with Android

New features will not be merged until also added to [Hotwire Native Android](https://github.com/hotwired/hotwire-native-android).
Expand Down
32 changes: 25 additions & 7 deletions Demo/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,7 @@ import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Hotwire.config.backButtonDisplayMode = .minimal
Hotwire.config.showDoneButtonOnModals = true

#if DEBUG
Hotwire.config.debugLoggingEnabled = true
#endif

configureHotwire()
return true
}

Expand All @@ -19,4 +13,28 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

private func configureHotwire() {
// Load the path configuration
Hotwire.loadPathConfiguration(from: [
.file(Bundle.main.url(forResource: "path-configuration", withExtension: "json")!)
])

// Set an optional custom user agent application prefix.
Hotwire.config.applicationUserAgentPrefix = "Hotwire Demo;"

// Register bridge components
Hotwire.registerBridgeComponents([
FormComponent.self,
MenuComponent.self,
OverflowMenuComponent.self,
])

// Set configuration options
Hotwire.config.backButtonDisplayMode = .minimal
Hotwire.config.showDoneButtonOnModals = true
#if DEBUG
Hotwire.config.debugLoggingEnabled = true
#endif
}
}
6 changes: 3 additions & 3 deletions Demo/Assets.xcassets/AccentColor.colorset/Contents.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "229",
"green" : "216",
"red" : "92"
"blue" : "244",
"green" : "139",
"red" : "193"
}
},
"idiom" : "universal"
Expand Down
7 changes: 2 additions & 5 deletions Demo/Demo.swift
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import Foundation

struct Demo {
static let basic = URL(string: "https://turbo-native-demo.glitch.me")!
static let turbolinks5 = URL(string: "https://turbo-native-demo.glitch.me?turbolinks=1")!

static let remote = URL(string: "https://hotwire-native-demo.dev")!
static let local = URL(string: "http://localhost:45678")!
static let turbolinks5Local = URL(string: "http://localhost:45678?turbolinks=1")!

/// Update this to choose which demo is run
static var current: URL {
basic
remote
}
}
10 changes: 0 additions & 10 deletions Demo/README.md

This file was deleted.

44 changes: 16 additions & 28 deletions Demo/SceneController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,50 +7,24 @@ final class SceneController: UIResponder {
var window: UIWindow?

private let rootURL = Demo.current
private lazy var navigator = Navigator(pathConfiguration: pathConfiguration, delegate: self)

// MARK: - Setup

private func configureBridge() {
Hotwire.registerBridgeComponents([
FormComponent.self,
MenuComponent.self,
OverflowMenuComponent.self,
])
}

private func configureRootViewController() {
guard let window = window else {
fatalError()
}

window.rootViewController = navigator.rootViewController
}
private lazy var navigator = Navigator(delegate: self)

// MARK: - Authentication

private func promptForAuthentication() {
let authURL = rootURL.appendingPathComponent("/signin")
navigator.route(authURL)
}

// MARK: - Path Configuration

private lazy var pathConfiguration = PathConfiguration(sources: [
.file(Bundle.main.url(forResource: "path-configuration", withExtension: "json")!),
])
}

extension SceneController: UIWindowSceneDelegate {
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else { return }

window = UIWindow(windowScene: windowScene)
window?.rootViewController = navigator.rootViewController
window?.makeKeyAndVisible()

configureBridge()
configureRootViewController()

navigator.route(rootURL)
}
}
Expand All @@ -70,4 +44,18 @@ extension SceneController: NavigatorDelegate {
return .acceptCustom(HotwireWebViewController(url: proposal.url))
}
}

func visitableDidFailRequest(_ visitable: any Visitable, error: any Error, retryHandler: RetryBlock?) {
if let turboError = error as? TurboError, case let .http(statusCode) = turboError, statusCode == 401 {
promptForAuthentication()
} else if let errorPresenter = visitable as? ErrorPresenter {
errorPresenter.presentError(error) {
retryHandler?()
}
} else {
let alert = UIAlertController(title: "Visit failed!", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
navigator.rootViewController.present(alert, animated: true)
}
}
}
45 changes: 9 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,21 @@
# Hotwire Native for iOS

**Build high-fidelity hybrid apps with native navigation and a single shared web view.** Hotwire Native for iOS provides the tooling to wrap your [Turbo 7](https://github.com/hotwired/turbo)-enabled web app in a native iOS shell. It manages a single WKWebView instance across multiple view controllers, giving you native navigation UI with all the client-side performance benefits of Turbo.
![Swift](https://img.shields.io/badge/Swift-5.3-blue)
![iOS](https://img.shields.io/badge/iOS-14+-green)
![Turbo](https://img.shields.io/badge/Turbo-7+-purple)

## Features
[Hotwire Native](https://native.hotwired.dev) is a high-level native framework, available for iOS and Android, that provides you with all the tools you need to leverage your web app and build great mobile apps.

- **Deliver fast, efficient hybrid apps.** Avoid reloading JavaScript and CSS. Save memory by sharing one WKWebView.
- **Reuse mobile web views across platforms.** Create your views once, on the server, in HTML. Deploy them to iOS, [Android](https://github.com/hotwired/turbo-android), and mobile browsers simultaneously. Ship new features without waiting on App Store approval.
- **Enhance web views with native UI.** Navigate web views using native patterns. Augment web UI with native controls.
- **Produce large apps with small teams.** Achieve baseline HTML coverage for free. Upgrade to native views as needed.
This native Swift library integrates with your [Hotwire](https://hotwired.dev) web app by wrapping it in a native iOS shell. It manages a single WKWebView instance across multiple view controllers, giving you native navigation UI with all the client-side performance benefits of Hotwire.

## Requirements

Hotwire Native iOS is written in Swift 5.3 and requires iOS 14 or higher. It supports web apps using either Turbo 7 or Turbolinks 5.

**Note:** You should understand how Turbo works with web applications in the browser before attempting to use Hotwire Native. See the [Turbo 7 documentation](https://github.com/hotwired/turbo) for details. Ensure that your web app sets the `window.Turbo` global variable as it's required by the native apps:

```javascript
import { Turbo } from "@hotwired/turbo-rails"
window.Turbo = Turbo
```

## Getting Started

The best way to get started with Hotwire Native iOS to try out the demo app first to get familiar with the framework. The demo app walks you through all the basic Hotwire Native flows as well as some advanced features. To run the demo, clone this repo and open `Demo/Demo.xcodeproj` in Xcode and run the Demo target. See [Demo/README.md](Demo/README.md) for more details about the demo. When you’re ready to start your own application, read through the rest of the documentation.

## Installation

Add Hotwire Native as a dependency through Xcode or directly to a Package.swift:

```
.package(url: "https://github.com/hotwired/hotwire-native-ios", from: "<latest-version>")
```

You can also integrate the framework manually if your prefer, such as by adding the repo as a submodule, and linking `Hotwire.framework` to your project.
Read more on [native.hotwired.dev](https://native.hotwired.dev).

## Contributing

Hotwire Native iOS is open-source software, freely distributable under the terms of an [MIT-style license](LICENSE). The [source code is hosted on GitHub](https://github.com/hotwired/hotwire-native-ios).
Development is sponsored by [37signals](https://37signals.com/).

We welcome contributions in the form of bug reports, pull requests, or thoughtful discussions in the [GitHub issue tracker](https://github.com/hotwired/hotwire-native-ios/issues).
Hotwire Native for iOS is open-source software, freely distributable under the terms of an [MIT-style license](LICENSE). The [source code is hosted on GitHub](https://github.com/hotwired/hotwire-native-bridge). Development is sponsored by [37signals](https://37signals.com/).

Please note that this project is released with a [Contributor Code of Conduct](CONDUCT.md). By participating in this project you agree to abide by its terms.
We welcome contributions in the form of bug reports, pull requests, or thoughtful discussions in the [GitHub issue tracker](https://github.com/hotwired/hotwire-native-bridge/issues).

---
---------

© 2024 37signals LLC
13 changes: 10 additions & 3 deletions Source/Bridge/UserAgent.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import Foundation

public enum UserAgent {
public static func userAgentSubstring(for componentTypes: [BridgeComponent.Type]) -> String {
enum UserAgent {
static func build(applicationPrefix: String?, componentTypes: [BridgeComponent.Type]) -> String {
let components = componentTypes.map { $0.name }.joined(separator: " ")
return "bridge-components: [\(components)]"
let componentsSubstring = "bridge-components: [\(components)]"

return [
applicationPrefix,
"Hotwire Native iOS;",
"Turbo Native iOS;",
componentsSubstring
].compactMap { $0 }.joined(separator: " ")
}
}
14 changes: 8 additions & 6 deletions Source/Hotwire.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ public enum Hotwire {
/// Use `Hotwire.config.makeCustomWebView` to customize the web view or web view
/// configuration further, making sure to call `Bridge.initialize()`.
public static func registerBridgeComponents(_ componentTypes: [BridgeComponent.Type]) {
Hotwire.config.userAgent += " \(UserAgent.userAgentSubstring(for: componentTypes))"
bridgeComponentTypes = componentTypes
}


Hotwire.config.makeCustomWebView = { configuration in
let webView = WKWebView.debugInspectable(configuration: configuration)
Bridge.initialize(webView)
return webView
}
/// Loads the `PathConfiguration` JSON file(s) from the provided sources
/// to configure navigation rules
/// - Parameter sources: An array of `PathConfiguration.Source` objects representing
/// the sources to load.
public static func loadPathConfiguration(from sources: [PathConfiguration.Source]) {
config.pathConfiguration.sources = sources
}

static var bridgeComponentTypes = [BridgeComponent.Type]()
Expand Down
39 changes: 23 additions & 16 deletions Source/HotwireConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@ import WebKit
public struct HotwireConfig {
public typealias WebViewBlock = (_ configuration: WKWebViewConfiguration) -> WKWebView

/// Override to set a custom user agent.
/// - Important: Include "Hotwire Native" or "Turbo Native" to use `turbo_native_app?`
/// on your Rails server.
public var userAgent = "Hotwire Native iOS; Turbo Native iOS"
/// Set a custom user agent application prefix for every WKWebView instance.
///
/// The library will automatically append a substring to your prefix
/// which includes:
/// - "Hotwire Native iOS; Turbo Native iOS;"
/// - "bridge-components: [your bridge components];"
///
/// WKWebView's default user agent string will also appear at the
/// beginning of the user agent.
public var applicationUserAgentPrefix: String? = nil

/// When enabled, adds a `UIBarButtonItem` of type `.done` to the left
/// navigation bar button item on screens presented modally.
Expand Down Expand Up @@ -36,9 +42,9 @@ public struct HotwireConfig {
}

/// The navigation controller used in `Navigator` for the main and modal stacks.
/// Must be a `UINavigationController` or subclass.
/// Must be a `HotwireNavigationController` or subclass.
public var defaultNavigationController: () -> UINavigationController = {
UINavigationController()
HotwireNavigationController()
}

/// Optionally customize the web views used by each Turbo Session.
Expand All @@ -62,7 +68,13 @@ public struct HotwireConfig {
// MARK: - Internal

public func makeWebView() -> WKWebView {
makeCustomWebView(makeWebViewConfiguration())
let webView = makeCustomWebView(makeWebViewConfiguration())

if !Hotwire.bridgeComponentTypes.isEmpty {
Bridge.initialize(webView)
}

return webView
}

// MARK: - Private
Expand All @@ -73,16 +85,11 @@ public struct HotwireConfig {
private func makeWebViewConfiguration() -> WKWebViewConfiguration {
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences?.preferredContentMode = .mobile
configuration.applicationNameForUserAgent = userAgent
configuration.applicationNameForUserAgent = UserAgent.build(
applicationPrefix: applicationUserAgentPrefix,
componentTypes: Hotwire.bridgeComponentTypes
)
configuration.processPool = sharedProcessPool
return configuration
}
}

public extension HotwireConfig {
class PathConfiguration {
/// Enable to include the query string (in addition to the path) when applying rules.
/// Disable to only consider the path when applying rules.
public var matchQueryStrings = true
}
}
Loading

0 comments on commit 8c7f3c5

Please sign in to comment.