Gemini/BrowserCore/NavigationManager.swift

63 lines
1.5 KiB
Swift

//
// NavigationManager.swift
// Gemini
//
// Created by Shadowfacts on 7/14/20.
//
import Foundation
public protocol NavigationManagerDelegate: class {
func loadNonGeminiURL(_ url: URL)
}
public class NavigationManager: NSObject, ObservableObject {
public weak var delegate: NavigationManagerDelegate?
@Published public var currentURL: URL
@Published public var backStack = [URL]()
@Published public var forwardStack = [URL]()
public init(url: URL) {
self.currentURL = url
}
public func changeURL(_ url: URL) {
guard url.scheme == "gemini" else {
delegate?.loadNonGeminiURL(url)
return
}
backStack.append(currentURL)
currentURL = cannonicalizeURL(url)
forwardStack = []
}
public func reload() {
let url = currentURL
currentURL = url
}
private func cannonicalizeURL(_ url: URL) -> URL {
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
if components.scheme == "gemini" && components.port == 1965 {
components.port = nil
}
return components.url!
}
@objc public func back() {
guard !backStack.isEmpty else { return }
forwardStack.insert(currentURL, at: 0)
currentURL = backStack.removeLast()
}
@objc public func forward() {
guard !forwardStack.isEmpty else { return }
backStack.append(currentURL)
currentURL = forwardStack.removeFirst()
}
}