Revision control
Copy as Markdown
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
import UIKit
/// Protocol for caching and providing toolbar buttons with performance optimization.
@MainActor
protocol ToolbarButtonCaching: AnyObject {
/// A cache of `ToolbarButton` instances keyed by their accessibility identifier (`a11yId`).
/// This improves performance by reusing buttons instead of creating new instances.
var cachedButtonReferences: [String: ToolbarButton] { get set }
/// Returns true if a cached button matching the given `ToolbarElement` exists, else false.
/// - Parameter toolbarElement: The `ToolbarElement` to check if cached button exists.
/// - Returns: true if cached button exist, else false.
func hasCachedButton(for toolbarElement: ToolbarElement) -> Bool
/// Retrieves a `ToolbarButton` for the given `ToolbarElement`.
/// If a cached button exists for the element's accessibility identifier, it returns the cached button.
/// Otherwise, it creates a new button, caches it, and then returns it.
/// - Parameter toolbarElement: The `ToolbarElement` for which to retrieve the button.
/// - Returns: A `ToolbarButton` instance configured for the given `ToolbarElement`.
func getToolbarButton(for toolbarElement: ToolbarElement) -> ToolbarButton
}
// MARK: - Default Implementation
extension ToolbarButtonCaching {
func hasCachedButton(for toolbarElement: ToolbarElement) -> Bool {
let cacheKey = toolbarElement.cacheId ?? toolbarElement.a11yId
return cachedButtonReferences[cacheKey] != nil
}
func getToolbarButton(for toolbarElement: ToolbarElement) -> ToolbarButton {
let cacheKey = toolbarElement.cacheId ?? toolbarElement.a11yId
let button: ToolbarButton
if let cachedButton = cachedButtonReferences[cacheKey] {
button = cachedButton
} else {
if toolbarElement.iconName == nil &&
toolbarElement.numberOfTabs != nil {
button = StackedTabButton()
} else if toolbarElement.numberOfTabs != nil {
button = TabNumberButton()
} else {
button = ToolbarButton()
}
cachedButtonReferences[cacheKey] = button
}
return button
}
}