finish implementation for iOS

This commit is contained in:
2025-09-29 16:09:00 -07:00
parent 265d393cdc
commit 62e36359b8
5 changed files with 369 additions and 105 deletions

View File

@@ -109,60 +109,56 @@ class GeneralSettingsViewController: UIViewController
case searchEngine = "Search Engine"
case syncServer = "Sync Server"
}
typealias Item = String
static let SearchProviderPopupItem = "searchProvider.popup"
static let SearchEngineNameFieldItem = "searchEngine.add.name"
static let SearchEngineURLFieldItem = "searchEngine.add.url"
static let SyncServerItem = "syncServer.field"
let dataSource: UICollectionViewDiffableDataSource<Section, Item>
let collectionView: UICollectionView
private var pendingEngineName: String = ""
private var pendingEngineURL: String = ""
let viewModel: ViewModel
static func createLayout(forIdiom idiom: UIUserInterfaceIdiom) -> UICollectionViewLayout {
#if targetEnvironment(macCatalyst)
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
#if targetEnvironment(macCatalyst)
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.60),
heightDimension: .absolute(44))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 1)
group.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: .flexible(1.0), top: nil, trailing: nil, bottom: nil)
let insets = NSDirectionalEdgeInsets(top: 24.0, leading: 64.0, bottom: 24.0, trailing: 64.0)
let headerFooterSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.40),
heightDimension: .estimated(44.0))
let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: headerFooterSize,
elementKind: UICollectionView.elementKindSectionHeader,
alignment: .topLeading,
absoluteOffset: CGPoint(x: insets.leading, y: insets.top + 5.0)
)
sectionHeader.extendsBoundary = false
sectionHeader.contentInsets = insets
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.60),
heightDimension: .absolute(44))
let section = NSCollectionLayoutSection(group: group)
// section.interGroupSpacing = spacing
section.contentInsets = insets
section.supplementariesFollowContentInsets = true
section.boundarySupplementaryItems = [ sectionHeader ]
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 1)
group.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: .flexible(1.0), top: nil, trailing: nil, bottom: nil)
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
#else
var listConfiguration = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
listConfiguration.headerMode = .supplementary
return UICollectionViewCompositionalLayout.list(using: listConfiguration)
#endif
let insets = NSDirectionalEdgeInsets(top: 24.0, leading: 64.0, bottom: 24.0, trailing: 64.0)
let headerFooterSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.40),
heightDimension: .estimated(44.0))
let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: headerFooterSize,
elementKind: UICollectionView.elementKindSectionHeader,
alignment: .topLeading,
absoluteOffset: CGPoint(x: insets.leading, y: insets.top + 5.0)
)
sectionHeader.extendsBoundary = false
sectionHeader.contentInsets = insets
let section = NSCollectionLayoutSection(group: group)
// section.interGroupSpacing = spacing
section.contentInsets = insets
section.supplementariesFollowContentInsets = true
section.boundarySupplementaryItems = [ sectionHeader ]
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
#else
var listConfiguration = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
listConfiguration.headerMode = .supplementary
return UICollectionViewCompositionalLayout.list(using: listConfiguration)
#endif
}
static func sectionHeaderConfiguration(forIdiom idiom: UIUserInterfaceIdiom, sectionName: String) -> UIContentConfiguration {
if idiom == .mac {
return LabelContentConfiguration(
@@ -171,59 +167,42 @@ class GeneralSettingsViewController: UIViewController
textAlignment: .right
)
} else {
var config = UIListContentConfiguration.plainHeader()
var config = UIListContentConfiguration.header()
config.text = sectionName
return config
}
}
#if targetEnvironment(macCatalyst)
#if targetEnvironment(macCatalyst)
static let staticIdiom = UIUserInterfaceIdiom.mac
#else
#else
static let staticIdiom = UIUserInterfaceIdiom.pad
#endif
#endif
init() {
let actionHandler = { (action: UIAction) in
let engineName = action.title
Settings.shared.defaultSearchEngineName = engineName
}
let viewModel = ViewModel()
let itemCellRegistry = UICollectionView.CellRegistration<UICollectionViewCell, Item> { cell, indexPath, identifier in
if identifier == Self.SearchProviderPopupItem {
let names = Settings.shared.searchEngines.keys.sorted()
let menu = UIMenu(children: names.map { name in
var engineMenuItems: [UIMenuElement] = names.map { name in
let action = UIAction(title: name, handler: actionHandler)
action.state = (Settings.shared.defaultSearchEngineName == name) ? .on : .off
return action
})
}
engineMenuItems.append(UIMenu(options: .displayInline, children: [
UIAction(title: "Manage Search Engines…", handler: { _ in
viewModel.onManageSearchEngines()
})
]))
let menu = UIMenu(children: engineMenuItems)
cell.contentConfiguration = ButtonContentConfiguration(menu: menu)
} else if identifier == Self.SearchEngineNameFieldItem {
cell.contentConfiguration = TextFieldContentConfiguration(
text: self.pendingEngineName,
placeholderText: "Name (e.g., Startpage)",
textChanged: { [weak self] newString in
self?.pendingEngineName = newString
},
pressedReturn: { $0.resignFirstResponder() },
keyboardType: .default,
returnKeyType: .next
)
} else if identifier == Self.SearchEngineURLFieldItem {
cell.contentConfiguration = TextFieldContentConfiguration(
text: self.pendingEngineURL,
placeholderText: "URL template (use %q or %s)",
textChanged: { [weak self] newString in
self?.pendingEngineURL = newString
},
pressedReturn: { [weak self] textField in
guard let self = self else { return }
self.tryAddPendingSearchEngine()
textField.resignFirstResponder()
},
keyboardType: .URL,
returnKeyType: .done
)
} else if identifier == Self.SyncServerItem {
cell.contentConfiguration = TextFieldContentConfiguration(
text: Settings.shared.syncServer ?? "",
@@ -236,51 +215,114 @@ class GeneralSettingsViewController: UIViewController
returnKeyType: .done
)
}
#if !targetEnvironment(macCatalyst)
cell.backgroundConfiguration = UIBackgroundConfiguration.listGroupedCell()
cell.backgroundConfiguration = UIBackgroundConfiguration.listCell()
#endif
}
let sectionHeaderRegistry = UICollectionView.SupplementaryRegistration<UICollectionViewCell>(elementKind: UICollectionView.elementKindSectionHeader, handler: {
(cell, string, indexPath) in
(cell, string, indexPath) in
let sectionName = Section.allCases[indexPath.section].rawValue
cell.contentConfiguration = Self.sectionHeaderConfiguration(forIdiom: Self.staticIdiom, sectionName: sectionName)
})
let layout = Self.createLayout(forIdiom: Self.staticIdiom)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .systemGroupedBackground
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) {
(collectionView, indexPath, identifier) in
(collectionView, indexPath, identifier) in
return collectionView.dequeueConfiguredReusableCell(using: itemCellRegistry, for: indexPath, item: identifier)
}
dataSource.supplementaryViewProvider = { collectionView, elementKind, indexPath in
return collectionView.dequeueConfiguredReusableSupplementary(using: sectionHeaderRegistry, for: indexPath)
}
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
collectionView.delegate = self
tabBarItem.title = "General"
tabBarItem.image = UIImage(systemName: "gear")
let resetPopup = { [weak self] in
guard let self else { return }
var snapshot = dataSource.snapshot()
snapshot.reloadItems([ Self.SearchProviderPopupItem ])
dataSource.apply(snapshot, animatingDifferences: false)
}
viewModel.onManageSearchEngines = { [weak self] in
guard let self else { return }
// Reset menu item (to show currently selected search engine)
resetPopup()
let viewController = ManageSearchEnginesViewController()
viewController.title = "Manage Search Engines"
viewController.model.onAddSearchEngine = { [weak self] in
guard let self else { return }
let addSearchEngineViewController = AddSearchEngineViewController()
let navController = UINavigationController(rootViewController: addSearchEngineViewController)
// Cancel
addSearchEngineViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(systemItem: .cancel, primaryAction: UIAction { _ in
navController.dismiss(animated: true)
})
// Done
addSearchEngineViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in
self?.saveCustomSearchEngine(model: addSearchEngineViewController.viewModel)
navController.dismiss(animated: true)
resetPopup()
viewController.model.reloadConfiguredEngines()
})
self.present(navController, animated: true)
}
viewController.model.onChangeEngines = {
resetPopup()
}
#if targetEnvironment(macCatalyst)
let alertController = UIAlertController(title: "Not yet implemented for macOS.", message: nil, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in alertController.dismiss(animated: true) }))
present(alertController, animated: true)
#else
navigationController?.pushViewController(viewController, animated: true)
#endif
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
self.view = collectionView
}
override func viewDidLoad() {
super.viewDidLoad()
applySnapshot(animatingDifferences: false)
}
// MARK: - Types
@MainActor
@Observable
class ViewModel
{
var onManageSearchEngines: () -> Void = {}
}
}
extension GeneralSettingsViewController : UICollectionViewDelegate {
@@ -293,17 +335,16 @@ private extension GeneralSettingsViewController {
func applySnapshot(animatingDifferences: Bool) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections(Section.allCases)
snapshot.appendItems([ Self.SearchProviderPopupItem,
Self.SearchEngineNameFieldItem,
Self.SearchEngineURLFieldItem ], toSection: .searchEngine)
snapshot.appendItems([ Self.SearchProviderPopupItem ], toSection: .searchEngine)
snapshot.appendItems([ Self.SyncServerItem ], toSection: .syncServer)
dataSource.apply(snapshot, animatingDifferences: animatingDifferences)
}
func tryAddPendingSearchEngine() {
let name = pendingEngineName.trimmingCharacters(in: .whitespacesAndNewlines)
let url = pendingEngineURL.trimmingCharacters(in: .whitespacesAndNewlines)
func saveCustomSearchEngine(model: AddSearchEngineView.ViewModel) {
let name = model.name.trimmingCharacters(in: .whitespacesAndNewlines)
let url = model.url.trimmingCharacters(in: .whitespacesAndNewlines)
guard !name.isEmpty, !url.isEmpty else { return }
// Require placeholder
guard url.contains("%q") || url.contains("%s") else { return }
@@ -311,10 +352,14 @@ private extension GeneralSettingsViewController {
var engines = Settings.shared.searchEngines
engines[name] = url
Settings.shared.searchEngines = engines
if model.makeDefault {
Settings.shared.defaultSearchEngineName = name
}
// Reset inputs and refresh UI
pendingEngineName = ""
pendingEngineURL = ""
applySnapshot(animatingDifferences: true)
var snapshot = dataSource.snapshot()
snapshot.reloadItems([ Self.SearchProviderPopupItem ])
dataSource.apply(snapshot, animatingDifferences: false)
}
}