-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathGridCell.swift
418 lines (350 loc) · 15.1 KB
/
GridCell.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//
// GridCell.swift
// Proton
//
// Created by Rajdeep Kwatra on 5/6/2022.
// Copyright © 2022 Rajdeep Kwatra. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import OSLog
/// Style configuration for the grid
public struct GridStyle {
/// Border color for grid
public var borderColor: UIColor
/// Border width for the grid
public var borderWidth: CGFloat
/// Default style
public static var `default` = GridStyle(borderColor: .gray, borderWidth: 1)
public init(
borderColor: UIColor,
borderWidth: CGFloat) {
self.borderColor = borderColor
self.borderWidth = borderWidth
}
}
/// Style configuration for the `GridCell`
public struct GridCellStyle {
/// Border style for individual cells. This may be used to override the style provided in the `GridStyle` for individual cells
public struct BorderStyle {
public var color: UIColor
public var width: CGFloat
public init(color: UIColor, width: CGFloat) {
self.color = color
self.width = width
}
}
/// Default background color for the cell.
public var backgroundColor: UIColor?
/// Default text color for the cell
public var textColor: UIColor?
/// Default font for the cell
public var font: UIFont?
public var borderStyle: BorderStyle?
public init(
backgroundColor: UIColor? = nil,
textColor: UIColor? = nil,
font: UIFont? = nil,
borderStyle: BorderStyle? = nil
) {
self.backgroundColor = backgroundColor
self.textColor = textColor
self.font = font
self.borderStyle = borderStyle
}
/// Creates a merged styles from given styles with precedence to the first style and any missing values used from the second style
/// - Parameters:
/// - style: Primary style
/// - other: Secondary style
/// - Returns: Merged style
public static func merged(style: GridCellStyle, other: GridCellStyle) -> GridCellStyle {
GridCellStyle(
backgroundColor: style.backgroundColor ?? other.backgroundColor,
textColor: style.textColor ?? other.textColor,
font: style.font ?? other.font,
borderStyle: style.borderStyle ?? other.borderStyle
)
}
}
protocol GridCellDelegate: AnyObject {
func cell(_ cell: GridCell, didChangeBounds bounds: CGRect)
func cell(_ cell: GridCell, didReceiveFocusAt range: NSRange)
func cell(_ cell: GridCell, didLoseFocusFrom range: NSRange)
func cell(_ cell: GridCell, didTapAtLocation location: CGPoint, characterRange: NSRange?)
func cell(_ cell: GridCell, didChangeSelectionAt range: NSRange, attributes: [NSAttributedString.Key : Any], contentType: EditorContent.Name)
func cell(_ cell: GridCell, didReceiveKey key: EditorKey, at range: NSRange)
func cell(_ cell: GridCell, didChangeSelected isSelected: Bool)
func cell(_ cell: GridCell, didChangeBackgroundColor color: UIColor?, oldColor: UIColor?)
}
/// Denotes a cell in the `GridView`
open class GridCell {
public typealias EditorInitializer = () -> EditorView
var id: String {
"{\(rowSpan),\(columnSpan)}"
}
/// Additional attributes that can be stored on Cell to identify various aspects like Header, Numbered etc.
public var additionalAttributes: [String: Any] = [:]
/// Row indexes spanned by the cell. In case of a merged cell, this will contain all the rows= indexes which are merged.
public internal(set) var rowSpan: [Int]
/// Column indexes spanned by the cell. In case of a merged cell, this will contain all the column indexes which are merged.
public internal(set) var columnSpan: [Int]
/// Frame of the cell within `GridView`
public internal(set) var frame: CGRect = .zero
public var backgroundColor: UIColor? = nil {
didSet {
contentView.backgroundColor = backgroundColor
editor.backgroundColor = backgroundColor
}
}
private var selectionView: SelectionView?
private let editorInitializer: EditorInitializer
var isRunningTests: Bool {
#if DEBUG
return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
#else
return false
#endif
}
/// Sets the cell selected
public var isSelected: Bool {
get { selectionView?.superview != nil }
set {
guard isSelectable,
newValue != isSelected else { return }
if newValue {
selectionView?.addTo(parent: contentView)
} else {
selectionView?.removeFromSuperview()
}
self.delegate?.cell(self, didChangeSelected: isSelected)
}
}
/// Controls if the cell can be selected or not.
public var isSelectable: Bool = true
/// Invoked when Editor in contained in the Cell is initialized.
public var onEditorInitialized: ((GridCell, EditorView) -> Void)?
/// Confirms if Editor within Cell has been initialized or not.
public var isEditorInitialized: Bool {
_editor != nil
}
private(set) var editorSetupComplete = false
private var _editor: EditorView?
/// Editor within the cell
public var editor: EditorView {
assertEditorSetupCompleted()
if let _editor {
return _editor
}
let editor = editorInitializer()
// backing var needs to be set before invoking onEditorInitialized
_editor = editor
onEditorInitialized?(self, editor)
return editor
}
/// Denotes if the cell can be split i.e. is a merged cell.
public var isSplittable: Bool {
rowSpan.count > 1 || columnSpan.count > 1
}
/// Content size of the cell
public var contentSize: CGSize {
editor.frame.size
}
/// Content view for the cell
public let contentView = UIView()
public let gridStyle: GridStyle
public let style: GridCellStyle
public let ignoresOptimizedInit: Bool
let widthAnchorConstraint: NSLayoutConstraint
let heightAnchorConstraint: NSLayoutConstraint
var topAnchorConstraint: NSLayoutConstraint!
var leadingAnchorConstraint: NSLayoutConstraint!
weak var delegate: GridCellDelegate?
let initialHeight: CGFloat
/// Initializes the cell
/// - Parameters:
/// - rowSpan: Array of row indexes the cells spans. For e.g. a cell with first two rows as merged, will have a value of [0, 1] denoting 0th and 1st index.
/// - columnSpan: Array of column indexes the cells spans. For e.g. a cell with first two columns as merged, will have a value of [0, 1] denoting 0th and 1st index.
/// - initialHeight: Initial height of the cell. This will be updated based on size of editor content on load,
/// - style: Visual style of the cell
/// - gridStyle: Visual style for grid containing cell border color and width
/// - ignoresOptimizedInit: Ignores optimization to initialize editor within the cell. With optimization, the editor is not initialized until the cell is ready to be rendered on the UI thereby not incurring any overheads when creating
/// attributedText containing a `GridView` in an attachment. Defaults to `false`.
/// - editorInitializer: Closure for setting up the `EditorView` within the cell.
/// - Important:
/// Creating a `GridView` with 100s of cells can result in slow performance when creating an attributed string containing the GridView attachment. Using the closure defers the creation until the view is ready to be rendered in the UI.
/// It is recommended to setup all the parts of editor in closure where possible, or wait until after the GridView is rendered. In case, editor must be initialized before the rendering is complete and it is not possible to configure an aspect within the closure itself,
/// `setupEditor()` may be invoked. Use of `setupEditor()` is discouraged.
public init(rowSpan: [Int],
columnSpan: [Int],
initialHeight: CGFloat = 40,
style: GridCellStyle = .init(),
gridStyle: GridStyle = .default,
ignoresOptimizedInit: Bool = false,
editorInitializer: EditorInitializer? = nil) {
self.editorInitializer = editorInitializer ?? { EditorView(allowAutogrowing: false) }
self.rowSpan = rowSpan
self.columnSpan = columnSpan
self.gridStyle = gridStyle
self.style = style
self.initialHeight = initialHeight
// Ensure Editor frame is .zero as otherwise it conflicts with some layout calculations
// self.editor.frame = .zero
self.contentView.layoutMargins = .zero
self.ignoresOptimizedInit = ignoresOptimizedInit
widthAnchorConstraint = contentView.widthAnchor.constraint(equalToConstant: 0)
heightAnchorConstraint = contentView.heightAnchor.constraint(equalToConstant: 0)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(contentViewTapped))
contentView.addGestureRecognizer(tapGestureRecognizer)
self.selectionView = SelectionView { [weak self] in
guard let self else { return }
self.isSelected = false
}
setup()
if isEditorInitialized {
onEditorInitialized?(self, editor)
}
}
/// Sets the focus in the `Editor` within the cell.
public func setFocus() {
editor.setFocus()
}
/// Removes the focus from the `Editor` within the cell.
public func removeFocus() {
editor.resignFocus()
}
/// Applies the given style to the cell
/// - Parameter style: Style to apply
public func applyStyle(_ style: GridCellStyle) {
contentView.layer.borderColor = style.borderStyle?.color.cgColor ?? gridStyle.borderColor.cgColor
contentView.layer.borderWidth = style.borderStyle?.width ?? gridStyle.borderWidth
if let font = style.font {
editor.font = font
editor.addAttributes([.font: font], at: editor.attributedText.fullRange)
}
if let textColor = style.textColor {
editor.textColor = textColor
}
if let backgroundColor = style.backgroundColor {
editor.backgroundColor = backgroundColor
contentView.backgroundColor = backgroundColor
}
}
func updateBackgroundColorFromParent(color: UIColor?, oldColor: UIColor?) {
// check for same color is required. In absence of that, the rendering causes
// collapsed cells to still show text even though cell is collapsed
guard backgroundColor == oldColor, backgroundColor != color else { return }
backgroundColor = color
}
private func assertEditorSetupCompleted() {
guard editorSetupComplete == false,
ignoresOptimizedInit == false else {
return
}
guard !isRunningTests else {
if #available(iOS 14.0, *) {
Logger.gridView.info(
"""
Editor setup is not complete as Grid containing cell is not in a window.
Set `ignoresOptimizedInit` to true in GridConfig or GridCell to suppress this message.
"""
)}
return
}
assertionFailure(
"""
Editor setup is not complete as Grid containing cell is not in a window.
Refer to initialiser documentation for additional details.
""")
}
@objc
private func contentViewTapped() {
editor.becomeFirstResponder()
}
private func setup() {
NSLayoutConstraint.activate([
widthAnchorConstraint,
heightAnchorConstraint
])
}
func setupEditor() {
editorSetupComplete = true
applyStyle(style)
editor.translatesAutoresizingMaskIntoConstraints = false
editor.boundsObserver = self
editor.delegate = self
contentView.addSubview(editor)
NSLayoutConstraint.activate([
editor.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor),
editor.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
editor.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
editor.heightAnchor.constraint(greaterThanOrEqualToConstant: initialHeight)
])
}
func hideEditor() {
editor.removeFromSuperview()
}
func showEditor() {
contentView.addSubview(editor)
}
}
extension GridCell: BoundsObserving {
public func didChangeBounds(_ bounds: CGRect, oldBounds: CGRect) {
delegate?.cell(self, didChangeBounds: bounds)
}
}
extension GridCell: EditorViewDelegate {
public func editor(_ editor: EditorView, didReceiveFocusAt range: NSRange) {
delegate?.cell(self, didReceiveFocusAt: range)
}
public func editor(_ editor: EditorView, didLoseFocusFrom range: NSRange) {
delegate?.cell(self, didLoseFocusFrom: range)
}
public func editor(_ editor: EditorView, didTapAtLocation location: CGPoint, characterRange: NSRange?) {
delegate?.cell(self, didTapAtLocation: location, characterRange: characterRange)
}
public func editor(_ editor: EditorView, didChangeSelectionAt range: NSRange, attributes: [NSAttributedString.Key : Any], contentType: EditorContent.Name) {
delegate?.cell(self, didChangeSelectionAt: range, attributes: attributes, contentType: contentType)
}
public func editor(_ editor: EditorView, didReceiveKey key: EditorKey, at range: NSRange) {
delegate?.cell(self, didReceiveKey: key, at: range)
}
public func editor(_ editor: EditorView, didChangeBackgroundColor color: UIColor?, oldColor: UIColor?) {
contentView.backgroundColor = color
delegate?.cell(self, didChangeBackgroundColor: color, oldColor: oldColor)
}
}
extension GridCell: Equatable {
public static func ==(lhs: GridCell, rhs: GridCell) -> Bool {
return lhs.id == rhs.id
}
}
extension GridCell: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
extension GridCellStyle.BorderStyle: Equatable {
public static func == (lhs: GridCellStyle.BorderStyle, rhs: GridCellStyle.BorderStyle) -> Bool {
return lhs.color == rhs.color && lhs.width == rhs.width
}
}
extension GridCellStyle: Equatable {
public static func == (lhs: GridCellStyle, rhs: GridCellStyle) -> Bool {
return lhs.backgroundColor == rhs.backgroundColor &&
lhs.textColor == rhs.textColor &&
lhs.font == rhs.font &&
lhs.borderStyle == rhs.borderStyle
}
}