Gemini/Gemini-iOS/NavigationBarView.swift

86 lines
3.0 KiB
Swift

//
// NavigationBarView.swift
// Gemini-iOS
//
// Created by Shadowfacts on 12/19/20.
//
import UIKit
import BrowserCore
import Combine
class NavigationBarView: UIView {
let navigator: NavigationManager
private var border: UIView!
private var textField: UITextField!
private var cancellables = [AnyCancellable]()
init(navigator: NavigationManager) {
self.navigator = navigator
super.init(frame: .zero)
backgroundColor = .systemBackground
border = UIView()
border.backgroundColor = UIColor(white: traitCollection.userInterfaceStyle == .dark ? 0.25 : 0.75, alpha: 1)
border.translatesAutoresizingMaskIntoConstraints = false
addSubview(border)
NSLayoutConstraint.activate([
border.leadingAnchor.constraint(equalTo: leadingAnchor),
border.trailingAnchor.constraint(equalTo: trailingAnchor),
border.bottomAnchor.constraint(equalTo: bottomAnchor),
border.heightAnchor.constraint(equalToConstant: 1),
])
textField = UITextField()
textField.text = navigator.displayURL
textField.borderStyle = .roundedRect
textField.keyboardType = .URL
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
textField.addTarget(self, action: #selector(commitURL), for: .editingDidEnd)
textField.translatesAutoresizingMaskIntoConstraints = false
addSubview(textField)
NSLayoutConstraint.activate([
textField.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
textField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
textField.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
textField.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -9),
])
navigator.$currentURL
.sink { (newURL) in
// can't use navigator.displayURL because the publisher fires before the underlying value is updated, so the displayURL getter returns the old value
var components = URLComponents(url: newURL, resolvingAgainstBaseURL: false)!
if components.port == 1965 {
components.port = nil
}
self.textField.text = components.string!
}
.store(in: &cancellables)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
border.backgroundColor = UIColor(white: traitCollection.userInterfaceStyle == .dark ? 0.25 : 0.75, alpha: 1)
}
@objc private func commitURL() {
if let text = textField.text, let url = URL(string: text) {
navigator.changeURL(url)
} else {
textField.text = navigator.displayURL
}
}
}