-
Notifications
You must be signed in to change notification settings - Fork 83
/
TableView.swift
1025 lines (854 loc) · 42.5 KB
/
TableView.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// TableView.swift
// Proton
//
// Created by Rajdeep Kwatra on 9/4/2024.
// Copyright © 2024 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
/// An object capable of observing lifecycle events for a cell in a virtualized tableView
public protocol TableCellLifeCycleObserver: AnyObject {
/// Notifies when `TableView` lays out a cell. This is called after the bounds calculation for the cell have been performed.
/// Rendering of cell may not have been completed at this time.
/// - Parameters:
/// - tableView: TableView containing the cell.
/// - cell: Cell being added to viewport
func tableView(_ tableView: TableView, didAddCellToViewport cell: TableCell)
/// Notifies when `TableView` lays out a cell. This is called after the bounds calculation for the cell have been performed.
/// Rendering of cell may not have been completed at this time.
/// - Parameters:
/// - tableView: TableView containing the cell.
/// - cell: Cell removed from viewport
func tableView(_ tableView: TableView, didRemoveCellFromViewport cell: TableCell)
}
public enum ViewportBorderDisplay {
case hidden
case visible(color: UIColor, borderWidth: CGFloat)
}
/// An object capable of handing `TableView` events
public protocol TableViewDelegate: AnyObject {
var containerScrollView: UIScrollView? { get }
var viewport: CGRect? { get }
/// Governs whether resolved viewport is displayed
/// - Note: This may be used for debugging purposes.
/// - Important: It is responsibility of consumer of the API to ensure that this is not displayed in app if not intended to. i.e. display of viewport does not
/// check for DEBUG flags and would be displayed based on value provided.
var resolvedViewportBorderDisplay: ViewportBorderDisplay { get }
/// Invoked when `EditorView` within the cell receives focus
/// - Parameters:
/// - tableView: TableView containing cell
/// - range: Range of content in the `EditorView` within the Cell
/// - cell: Cell containing Editor
func tableView(_ tableView: TableView, didReceiveFocusAt range: NSRange, in cell: TableCell)
/// Invoked when `EditorView` within the cell loses focus
/// - Parameters:
/// - tableView: TableView containing cell
/// - range: Range of content in the `EditorView` within the Cell
/// - cell: Cell containing Editor
func tableView(_ tableView: TableView, didLoseFocusFrom range: NSRange, in cell: TableCell)
/// Invoked when tap event occurs within the Editor contained in the cell.
/// - Parameters:
/// - tableView: TableView containing cell
/// - location: Tapped location
/// - characterRange: Range of characters in the Editor at the tapped location
/// - cell: Cell containing Editor
func tableView(_ tableView: TableView, didTapAtLocation location: CGPoint, characterRange: NSRange?, in cell: TableCell)
/// Invoked on selection changes with in the Editor contained in the cell.
/// - Parameters:
/// - tableView: TableView containing cell
/// - range: Range of selection in the `EditorView` within the Cell
/// - attributes: Attributes at selected range
/// - contentType: `ContentType` at selected range
/// - cell: Cell containing Editor
func tableView(_ tableView: TableView, didChangeSelectionAt range: NSRange, attributes: [NSAttributedString.Key : Any], contentType: EditorContent.Name, in cell: TableCell)
/// Invoked on change of bounds of the Editor within the cell
/// - Parameters:
/// - tableView: TableView containing cell
/// - bounds: Bounds of the EditorView within the cell. Height of EditorView may be less than that of the Cell.
/// - cell: Cell containing Editor
func tableView(_ tableView: TableView, didChangeBounds bounds: CGRect, in cell: TableCell)
/// Invoked when selection of cells is changed.
/// - Parameters:
/// - tableView: TableView containing cell
/// - cells: Selected cells
func tableView(_ tableView: TableView, didSelectCells cells: [TableCell])
/// Invoked when selection of cells is changed.
/// - Parameters:
/// - tableView: TableView containing cell
/// - cells: Cells that are changed from selected to unselected.
func tableView(_ tableView: TableView, didUnselectCells cells: [TableCell])
/// Invoked when special keys are intercepted in the Editor contained in the cell.
/// - Parameters:
/// - tableView: TableView containing cell
/// - key: Special key
/// - range: Range at with the key is intercepted.
/// - cell: Cell containing Editor
func tableView(_ tableView: TableView, didReceiveKey key: EditorKey, at range: NSRange, in cell: TableCell)
/// Invoked when a column in `TableView` is resized.
/// - Parameters:
/// - tableView: TableView containing column
/// - proposedWidth: Proposed column width before the change
/// - columnIndex: Index of column being resized
/// - Returns: `true` if column resizing should be allowed, else false.
func tableView(_ tableView: TableView, shouldChangeColumnWidth proposedWidth: CGFloat, for columnIndex: Int) -> Bool
/// Notifies when `TableView` lays out a cell. This is called after the bounds calculation for the cell have been performed.
/// Rendering of cell may not have been completed at this time.
/// - Parameters:
/// - tableView: TableView containing the cell.
/// - cell: Cell being laid out
func tableView(_ tableView: TableView, didLayoutCell cell: TableCell)
/// Notified that the cell that is being tried to focus using `maintainScrolledPositionLock` or as a result of `scrollTo` needs to be refocussed.
/// A cell may need to be refocussed if it happens to be displayed from originally calculated position on rendering.
/// - Parameters:
/// - tableView: Tableview in which the cells are getting rendered
/// - cell: Locked `TableCell` that may need to be scrolled to.
/// - rect: Rectangle for content within Cell to focus.
/// - isRendered: Informs if the cell is already rendered in viewport. `true` if it is. `false` if cell is not yet in viewport
/// /// - Note:
/// This is only intended to be used in scenarios where Editor is being scrolled to a position within `TableView` and the cell that is being scrolled to may
/// not have been rendered being outside viewport.
func tableView(_ tableView: TableView, needsUpdateScrollPositionOnCell cell: TableCell, rect: CGRect, isRendered: Bool)
/// Notifies when `TableView` lays out a cell. This is called after the bounds calculation for the cell have been performed.
/// Rendering of cell may not have been completed at this time.
/// - Parameters:
/// - tableView: TableView containing the cell.
/// - cell: Cell being added to viewport
func tableView(_ tableView: TableView, didAddCellToViewport cell: TableCell)
/// Notifies when `TableView` lays out a cell. This is called after the bounds calculation for the cell have been performed.
/// Rendering of cell may not have been completed at this time.
/// - Parameters:
/// - tableView: TableView containing the cell.
/// - cell: Cell removed from viewport
func tableView(_ tableView: TableView, didRemoveCellFromViewport cell: TableCell)
}
public extension TableViewDelegate {
var resolvedViewportBorderDisplay: ViewportBorderDisplay { .hidden }
}
/// A view that provides a tabular structure where each cell is an `EditorView`.
/// Since the cells contains an `EditorView` in itself, it is capable of hosting any attachment that `EditorView` can host
/// including another `TableView` as an attachment.
public class TableView: UIView {
let tableView: TableContentView
private let leadingShadowView: UIView
private let trailingShadowView: UIView
private var columnResizingHandles = [TableCellHandleButton]()
private let handleSize: CGFloat = 20
private let config: GridConfiguration
private let selectionView = SelectionView()
private var resizingDragHandleLastLocation: CGPoint? = nil
private var leadingShadowConstraint: NSLayoutConstraint!
private var maintainLockOnCell: (cell: TableCell, rect: CGRect)?
private var observation: NSKeyValueObservation?
private let repository = TableCellRepository()
private weak var _containerScrollView: UIScrollView? {
didSet {
_containerScrollView != nil ? setupScrollObserver() : removeScrollObserver()
}
}
private lazy var columnRightBorderView: UIView = {
makeSelectionBorderView()
}()
private lazy var columnLeftBorderView: UIView = {
makeSelectionBorderView()
}()
private lazy var columnTopBorderView: UIView = {
makeSelectionBorderView()
}()
private lazy var columnBottomBorderView: UIView = {
makeSelectionBorderView()
}()
private var shadowWidth: CGFloat {
10.0
}
/// Observer for lifecycle of tableView cells
public weak var tableCellLifeCycleObserver: TableCellLifeCycleObserver?
/// Delegate for `TableView` which can be used to handle cell specific `EditorView` events
public weak var delegate: TableViewDelegate? {
didSet {
(delegate != nil) ? setupScrollObserver() : removeScrollObserver()
}
}
/// Gets the attachment containing the `TableView`
public var containerAttachment: Attachment? {
attachmentContentView?.attachment
}
/// Determines if column resizing handles are visible or not.
public private(set) var isColumnResizingHandlesVisible = false {
didSet {
if isColumnResizingHandlesVisible == false {
removeColumnResizingHandles()
}
}
}
/// Determines if cell selection using 2-finger drag gesture is enabled
public var isCellSelectionEnabled: Bool {
get { tableView.isCellSelectionEnabled }
set { tableView.isCellSelectionEnabled = newValue }
}
/// Bounds observer for the `TableView`. Typically, this will be the `Attachment` that hosts the `TableView`.
/// - Note: In absence of a `boundObserver`, the `TableView` will not autoresize when the content in the cells
/// are changed.
public var boundsObserver: BoundsObserving? {
get { tableView.boundsObserver }
set { tableView.boundsObserver = newValue }
}
/// Selection color for the `TableView`. Defaults to `tintColor`
public var selectionColor: UIColor?
/// Determines if `TableView` is selected or not.
public var isSelected: Bool = false {
didSet {
if isSelected {
selectionView.addTo(parent: self, selectionColor: selectionColor)
} else {
selectionView.removeFromSuperview()
}
}
}
/// Allows scrolling grid in any direction. Defaults to `false`
/// Default behaviour restricts scrolling to horizontal or vertical direction at a time.
public var isFreeScrollingEnabled: Bool {
get { tableView.isFreeScrollingEnabled }
set { tableView.isFreeScrollingEnabled = newValue }
}
/// Maximum index up till which columns are frozen. Columns are frozen from 0 to this index value.
public var frozenColumnMaxIndex: Int? {
return tableView.frozenColumnMaxIndex
}
/// Maximum index up till which rows are frozen. Rows are frozen from 0 to this index value.
public var frozenRowMaxIndex: Int? {
return tableView.frozenRowMaxIndex
}
/// Determines if there are any frozen columns in the `TableView`
public var containsFrozenColumns: Bool {
tableView.frozenColumnMaxIndex != nil
}
/// Determines if there are any frozen rows in the `TableView`
public var containsFrozenRows: Bool {
tableView.frozenRowMaxIndex != nil
}
/// Collection of cells contained in the `TableView`
public var cells: [TableCell] {
tableView.cells
}
// Collection of cells currently selected in the `TableView`
public var selectedCells: [TableCell] {
tableView.selectedCells
}
/// Number of columns in the `TableView`.
public var numberOfColumns: Int {
tableView.numberOfColumns
}
/// Number of rows in the `TableView`
public var numberOfRows: Int {
tableView.numberOfRows
}
/// Cells visible in current viewport.
public var visibleCells: [TableCell] {
cellsInViewport
}
public override var bounds: CGRect {
didSet {
guard oldValue == bounds else { return }
}
}
/// Initializes `TableView` using the provided configuration.
/// - Parameter
/// - config: Configuration for `TableView`
/// - cellEditorInitializer: Custom initializer for `EditorView` within `TableCell`. This will also be used when creating new cells as a
/// return of adding new row or column, or cells being split.
public convenience init(config: GridConfiguration, cellEditorInitializer: GridCell.EditorInitializer? = nil, isCellSelectionEnabled: Bool = false) {
let tableView = TableContentView(config: config, editorInitializer: cellEditorInitializer)
self.init(config: config, tableView: tableView, isCellSelectionEnabled: isCellSelectionEnabled)
}
/// Initializes `TableView` using the provided configuration.
/// - Parameters:
/// - config: Configuration for `TableView`
/// - cells: Cells contained within `TableView`
/// - cellEditorInitializer: Custom initializer for `EditorView` within `TableCell`. This will also be used when creating new cells as a
/// return of adding new row or column, or cells being split.
/// - Important:
/// Care must be taken that the number of cells are correct per the configuration provided, failing which the `TableView` rendering may be broken.
public convenience init(config: GridConfiguration, cells: [TableCell], cellEditorInitializer: TableCell.EditorInitializer? = nil, isCellSelectionEnabled: Bool = false) {
let tableView = TableContentView(config: config, cells: cells, editorInitializer: cellEditorInitializer)
self.init(config: config, tableView: tableView, isCellSelectionEnabled: isCellSelectionEnabled)
}
private init(config: GridConfiguration, tableView: TableContentView, isCellSelectionEnabled: Bool ) {
self.tableView = tableView
let boundsShadowColors = [
config.boundsLimitShadowColors.primary.cgColor,
config.boundsLimitShadowColors.secondary.cgColor
]
self.leadingShadowView = GradientView(colors: boundsShadowColors)
self.leadingShadowView.alpha = 0.2
self.trailingShadowView = GradientView(colors: boundsShadowColors.reversed())
self.trailingShadowView.alpha = 0.2
self.config = config
super.init(frame: .zero)
self.leadingShadowConstraint = leadingShadowView.leadingAnchor.constraint(equalTo: self.leadingAnchor)
self.isCellSelectionEnabled = isCellSelectionEnabled
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var backgroundColor: UIColor? {
didSet {
tableView.backgroundColor = backgroundColor
}
}
public override func didMoveToWindow() {
guard window != nil else { return }
// Only try to auto resolve container scrollview, if not already provided by the delegate
guard self.containerScrollView == nil else { return }
// If table has the Editor which is scrollable, use that as container for viewport
let containerEditorView = self.containerAttachment?.containerEditorView
if let scrollView = containerEditorView?.scrollView, scrollView.isScrollEnabled {
_containerScrollView = scrollView
return
}
// Else, find the next available scrollview up the hierarchy
if let scrollView = getScrollContainer(from: containerEditorView) {
_containerScrollView = scrollView
}
// If there's still none, default to container editor scrollview
// This would typically be the case where the Editor starts off as non-scrollable but becomes scrollable
// as the content overflows in which case this should resolve correctly.
if _containerScrollView == nil {
_containerScrollView = containerEditorView?.scrollView
}
}
private func getScrollContainer(from view: UIView?) -> UIScrollView? {
guard view != nil else { return nil }
guard let scrollView = view as? UIScrollView else {
return getScrollContainer(from: view?.superview)
}
return scrollView
}
/// Maintains the scroll lock on the cell passed in if the original rect ends up moving as a result of cells getting rendered above this rect position
/// - Parameters:
/// - cell: Cell to lock on
/// - rect: Offset within cell with respect to origin to scroll to.
public func maintainScrolledPositionLock(on cell: TableCell?, rect: CGRect) {
guard let cell = cell else {
maintainLockOnCell = nil
return
}
maintainLockOnCell = (cell, rect)
}
private func setup() {
tableView.translatesAutoresizingMaskIntoConstraints = false
leadingShadowView.translatesAutoresizingMaskIntoConstraints = false
trailingShadowView.translatesAutoresizingMaskIntoConstraints = false
tableView.tableContentViewDelegate = self
tableView.delegate = self
addSubview(tableView)
addSubview(leadingShadowView)
addSubview(trailingShadowView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: topAnchor),
tableView.bottomAnchor.constraint(equalTo: bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: trailingAnchor),
// heightAnchor.constraint(equalTo: tableView.heightAnchor),
// widthAnchor.constraint(equalTo: tableView.widthAnchor),
leadingShadowView.widthAnchor.constraint(equalToConstant: shadowWidth),
leadingShadowConstraint,
leadingShadowView.topAnchor.constraint(equalTo: topAnchor),
leadingShadowView.bottomAnchor.constraint(equalTo: bottomAnchor),
trailingShadowView.widthAnchor.constraint(equalToConstant: shadowWidth),
trailingShadowView.trailingAnchor.constraint(equalTo: trailingAnchor),
trailingShadowView.topAnchor.constraint(equalTo: topAnchor),
trailingShadowView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
public override func layoutSubviews() {
super.layoutSubviews()
if let lockedCell = maintainLockOnCell?.cell,
cellsInViewport.contains(lockedCell) {
maintainLockOnCell = nil
}
}
private func setupScrollObserver() {
observation = containerScrollView?.observe(\.bounds, options: [.new, .old]) { [weak self] container, change in
self?.viewportChanged()
}
}
private func removeScrollObserver() {
observation?.invalidate()
}
deinit {
removeScrollObserver()
}
private var retainedCells = Set<TableCell>()
var cellsInViewport: [TableCell] = [] {
didSet {
reclaimReleasedCells(cellsInViewport)
guard oldValue != cellsInViewport else { return }
let oldCells = Set(oldValue)
let newCells = Set(cellsInViewport)
let toGenerate = newCells.subtracting(oldCells)
let toReclaim = oldCells.subtracting(newCells)
toReclaim.forEach { [weak self] cell in
// Ignore reclaiming the cell if these are retained
// Cell having focus is always retained and released on lost focus
if cell.isRetained == false {
self?.repository.enqueue(cell: cell)
} else {
self?.retainedCells.insert(cell)
}
}
toGenerate.forEach { [weak self] cell in
// Ignore generating the cell if it is already retained. The retained cell is not reclaimed, hence need not be regenerated.
// In absence of this check, there may be cases where the retained cell gets duplicated
if cell.isRetained == false {
self?.repository.dequeue(for: cell)
}
}
}
}
private func viewportChanged() {
guard let attachmentContentView = tableView.attachmentContentView,
// ensure editor is not hidden e.g. inside an Expand in collapsed state
attachmentContentView.attachment?.containerEditorView?.isHidden == false,
tableView.bounds != .zero,
let containerScrollView = self.containerScrollView,
let rootEditorView = containerAttachment?.containerEditorView?.rootEditor else {
cellsInViewport = []
return
}
guard let superView = attachmentContentView.superview else { return }
let adjustedAttachmentViewport = rootEditorView.convert(attachmentContentView.frame, from: superView)
// Convert the nestedView's frame to the scrollView's coordinate space
let nestedViewFrameInScrollView = delegate?.viewport ?? containerScrollView.bounds
// Get the visible part of the scrollView
let visibleRectInScrollView = containerScrollView.bounds
// Intersect the two rectangles to get the visible part of the nestedView
let visibleRectOfNestedViewInScrollView = visibleRectInScrollView.intersection(nestedViewFrameInScrollView)
// Convert the visible rectangle back to the nestedView's coordinate space
let visibleRectOfNestedView = rootEditorView.convert(visibleRectOfNestedViewInScrollView, from: containerScrollView)
if let viewportBorder = delegate?.resolvedViewportBorderDisplay,
case let ViewportBorderDisplay.visible(color, borderWidth) = viewportBorder {
Utility.drawRect(rect: visibleRectOfNestedView, color: color, borderWidth: borderWidth, in: rootEditorView, name: "viewport")
}
let adjustedViewport = visibleRectOfNestedView.offsetBy(dx: tableView.bounds.minX, dy: tableView.bounds.minY)
// Ensure the attachment is in viewport else clear off all the cells
guard adjustedAttachmentViewport.offsetBy(
dx: tableView.bounds.origin.x,
dy: tableView.bounds.origin.y).intersects(adjustedViewport
) else {
cellsInViewport = []
return
}
// TODO: future improvement - needs more work
//cellsInViewport = tableView.table.cellsIn(rect: adjustedViewport, offset: rootOrigin)
//TODO: future improvement - sort by cell.frame.y and filter using binary search
cellsInViewport = tableView.cells.filter {
$0.frame != .zero
&& $0.frame.offsetBy(dx: adjustedAttachmentViewport.origin.x, dy: adjustedAttachmentViewport.origin.y)
.intersects(adjustedViewport) }
}
private func reclaimReleasedCells(_ cellsInViewport: [TableCell]) {
retainedCells
.filter { cellsInViewport.contains($0) == false }
.forEach {
if $0.isRetained == false {
self.repository.enqueue(cell: $0)
retainedCells.remove($0)
}
}
}
func cellBelow(_ cell: TableCell) -> TableCell? {
guard let row = cell.rowSpan.max(),
let column = cell.columnSpan.min() else {
return nil
}
return cellAt(rowIndex: row + 1, columnIndex: column)
}
func cellAbove(_ cell: TableCell) -> TableCell? {
guard let row = cell.rowSpan.max(),
let column = cell.columnSpan.min() else {
return nil
}
return cellAt(rowIndex: row - 1, columnIndex: column)
}
private func makeSelectionBorderView() -> UIView {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = tintColor
view.alpha = 0.4
return view
}
private func addColumnResizingHandles(selectedCell: TableCell) {
guard isColumnResizingHandlesVisible else { return }
for cell in cells where cell.columnSpan.max() == selectedCell.columnSpan.max() {
if let contentView = cell.contentView {
let handleView = makeColumnResizingHandle(cell: cell)
columnResizingHandles.append(handleView)
handleView.translatesAutoresizingMaskIntoConstraints = false
addSubview(handleView)
NSLayoutConstraint.activate([
handleView.widthAnchor.constraint(equalToConstant: handleSize),
handleView.heightAnchor.constraint(equalTo: handleView.widthAnchor),
])
NSLayoutConstraint.activate([
handleView.centerYAnchor.constraint(equalTo: contentView.bottomAnchor),
handleView.centerXAnchor.constraint(equalTo: contentView.trailingAnchor)
])
}
}
addSelectionBorders(grid: self, cell: selectedCell)
}
private func addSelectionBorders(grid: TableView, cell: TableCell) {
guard let contentView = cell.contentView else { return }
addSubview(columnRightBorderView)
addSubview(columnLeftBorderView)
addSubview(columnTopBorderView)
addSubview(columnBottomBorderView)
NSLayoutConstraint.activate([
columnRightBorderView.centerXAnchor.constraint(equalTo: contentView.trailingAnchor),
columnRightBorderView.widthAnchor.constraint(equalToConstant: cell.gridStyle.borderWidth * 2),
columnRightBorderView.heightAnchor.constraint(equalTo: tableView.heightAnchor),
columnRightBorderView.topAnchor.constraint(equalTo: tableView.topAnchor),
columnLeftBorderView.centerXAnchor.constraint(equalTo: contentView.leadingAnchor),
columnLeftBorderView.widthAnchor.constraint(equalToConstant: cell.gridStyle.borderWidth * 2),
columnLeftBorderView.heightAnchor.constraint(equalTo: tableView.heightAnchor),
columnLeftBorderView.topAnchor.constraint(equalTo: tableView.topAnchor),
columnTopBorderView.centerYAnchor.constraint(equalTo: tableView.topAnchor),
columnTopBorderView.widthAnchor.constraint(equalTo: contentView.widthAnchor),
columnTopBorderView.heightAnchor.constraint(equalToConstant: cell.gridStyle.borderWidth * 2),
columnTopBorderView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
columnBottomBorderView.centerYAnchor.constraint(equalTo: tableView.bottomAnchor),
columnBottomBorderView.widthAnchor.constraint(equalTo: contentView.widthAnchor),
columnBottomBorderView.heightAnchor.constraint(equalToConstant: cell.gridStyle.borderWidth * 2),
columnBottomBorderView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
])
}
private func removeColumnResizingHandles() {
columnResizingHandles.forEach { $0.removeFromSuperview() }
columnResizingHandles.removeAll()
removeSelectionBorders()
}
private func removeSelectionBorders() {
columnRightBorderView.removeFromSuperview()
columnLeftBorderView.removeFromSuperview()
columnTopBorderView.removeFromSuperview()
columnBottomBorderView.removeFromSuperview()
}
private func resetColumnResizingHandles(selectedCell: TableCell) {
removeColumnResizingHandles()
addColumnResizingHandles(selectedCell: selectedCell)
}
private func makeColumnResizingHandle(cell: TableCell) -> TableCellHandleButton {
let dragHandle = TableCellHandleButton(cell: cell, cornerRadius: handleSize/2)
dragHandle.translatesAutoresizingMaskIntoConstraints = false
dragHandle.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(dragHandler(gesture:))))
return dragHandle
}
@objc
private func dragHandler(gesture: UIPanGestureRecognizer){
guard let draggedView = gesture.view,
let cell = (draggedView as? TableCellHandleButton)?.cell else { return }
let location = gesture.location(in: self)
if gesture.state == .changed {
if let lastLocation = resizingDragHandleLastLocation {
let deltaX = location.x - lastLocation.x
tableView.changeColumnWidth(index: cell.columnSpan.max() ?? 0, delta: deltaX)
}
resizingDragHandleLastLocation = location
}
if gesture.state == .ended
|| gesture.state == .cancelled
|| gesture.state == .ended {
resizingDragHandleLastLocation = nil
}
}
/// Enables or disables column resizing
/// - Parameter enabled: `true` to enable resizing
public func setColumnResizing(_ enabled: Bool) {
isColumnResizingHandlesVisible = enabled
}
/// Gets the cell for the `EditorView` contained in the current instance
/// - Parameter editor: Editor for which cell needs to be queried.
/// - Returns: `TableCell` that contains the passed in `EditorView`, if present
public func cellFor(_ editor: EditorView) -> TableCell? {
return cells.first(where: { $0.contentView?.editor == editor })
}
/// Selects given cells. Also, deselects any previously selected cells
/// - Parameter cells: Cells to select.
/// - Note:
/// Any combination of cells can be passed in, and will be selected, if possible.
public func selectCells(_ cells: [TableCell]) {
tableView.selectCells(cells)
}
/// Deselects any selected cell.
public func deselectCells() {
tableView.deselectCells()
}
/// Determines if the collection of cells can be merged. For cells to be mergable, they need to
/// be adjacent to each other, and the shape of selection needs to be rectangular.
/// - Parameter cells: Collection of cells to check if these can be merged.
/// - Returns: `true` is cells can be merged.
public func isCellSelectionMergeable(_ cells: [TableCell]) -> Bool {
tableView.isMergeable(cells: cells)
}
/// Merges the cells if the collection is mergeable.
/// - Parameter cells: Cells to merge.
public func merge(cells: [TableCell]) {
if let mergedCell = tableView.merge(cells: cells) {
resetColumnResizingHandles(selectedCell: mergedCell)
}
}
/// Splits the cell into original constituent cells from earlier Merge operation.
/// After split, the contents are held in the first original cell and all new split cells
/// are added as empty,
/// - Parameter cell: Cell to split.
public func split(cell: TableCell) {
if cell.isSplittable {
// Remove cell being split so that it can be regenerated
// to correctly render cells in viewport
cellsInViewport.removeAll(where: { $0 == cell })
}
let cells = tableView.split(cell: cell)
if let cell = cells.last {
resetColumnResizingHandles(selectedCell: cell)
}
}
/// Inserts a new row at given index.
/// - Parameters:
/// - index: Index at which new row should be inserted.
/// If the index is out of bounds, row will be inserted at the top or bottom of the grid based on index value
/// - configuration: Configuration for the new row
/// - Returns: Result with newly added cells for `.success`, error in case of `.failure`
@discardableResult
public func insertRow(at index: Int, configuration: GridRowConfiguration) -> Result<[TableCell], TableViewError> {
tableView.insertRow(at: index, configuration: configuration)
}
/// Inserts a new column at given index.
/// - Parameters:
/// - index: Index at which new column should be inserted.
/// If the index is out of bounds, column will be inserted at the beginning or end of the grid based on index value
/// - configuration: Configuration for the new column
/// - Returns: Result with newly added cells for `.success`, error in case of `.failure`
@discardableResult
public func insertColumn(at index: Int, configuration: GridColumnConfiguration) -> Result<[TableCell], TableViewError> {
tableView.insertColumn(at: index, configuration: configuration)
}
/// Deletes the row at given index
/// - Parameter index: Index to delete
public func deleteRow(at index: Int) {
tableView.deleteRow(at: index)
}
/// Deletes the column at given index
/// - Parameter index: Index to delete
public func deleteColumn(at index: Int) {
tableView.deleteColumn(at: index)
}
/// Freezes all the columns from 0 to the index provided
/// - Parameter maxIndex: Index to freeze upto
public func freezeColumns(upTo maxIndex: Int) {
tableView.frozenColumnMaxIndex = maxIndex
}
/// Freezes all the rows from 0 to the index provided
/// - Parameter maxIndex: Index to freeze upto
public func freezeRows(upTo maxIndex: Int) {
tableView.frozenRowMaxIndex = maxIndex
}
public func unfreezeColumns() {
tableView.frozenColumnMaxIndex = nil
}
public func unfreezeRows() {
tableView.frozenRowMaxIndex = nil
}
public func collapseRow(at index: Int) {
tableView.collapseRow(at: index)
}
func expandRow(at index: Int) {
tableView.expandRow(at: index)
}
func collapseColumn(at index: Int) {
tableView.collapseColumn(at: index)
}
func expandColumn(at index: Int) {
tableView.expandColumn(at: index)
}
func getCollapsedRowIndices() -> [Int] {
return tableView.getCollapsedRowIndices()
}
func getCollapsedColumnIndices() -> [Int] {
return tableView.getCollapsedColumnIndices()
}
/// Gets the cell at given row and column index. Indexes may be contained in a merged cell.
/// - Parameters:
/// - rowIndex: Row index for the cell
/// - columnIndex: Column index for the cell
/// - Returns: Cell at given row and column, if exists`
public func cellAt(rowIndex: Int, columnIndex: Int) -> TableCell? {
return tableView.cellAt(rowIndex: rowIndex, columnIndex: columnIndex)
}
/// Scrolls the cell at given index into viewable area. Indexes may be contained in a merged cell.
/// - Parameters:
/// - rowIndex: Row index of the cell
/// - columnIndex: Column index for the cell
/// - animated: Animates scroll if `true`
public func scrollToCellAt(rowIndex: Int, columnIndex: Int, animated: Bool = false) {
if let cell = cellAt(rowIndex: rowIndex, columnIndex: columnIndex) {
tableView.scrollTo(cell: cell, animated: animated)
}
}
/// Applies style to row at given index
/// - Parameters:
/// - style: Style to apply
/// - index: Index of the row
public func applyStyle(_ style: GridCellStyle, toRow index: Int) {
for cell in cells where cell.rowSpan.contains (index) {
cell.contentView?.applyStyle(style)
}
}
/// Applies style to column at given index
/// - Parameters:
/// - style: Style to apply
/// - index: Index of the column
public func applyStyle(_ style: GridCellStyle, toColumn index: Int) {
for cell in cells where cell.columnSpan.contains (index) {
cell.contentView?.applyStyle(style)
}
}
private func resetShadows() {
if let frozenColumnMaxIndex {
let frozenColumnWidth = tableView.columnWidths.prefix(upTo: frozenColumnMaxIndex + 1).reduce(0) { partialResult, dimension in
let viewport = tableView.bounds
return partialResult + dimension.value(basedOn: frame.size.width, viewportWidth: viewport.width)
}
let borderOffSet = self.config.style.borderWidth
leadingShadowConstraint.constant = frozenColumnWidth + borderOffSet
leadingShadowView.isHidden = tableView.contentOffset.x < 1
} else {
leadingShadowView.isHidden = tableView.contentOffset.x <= 0
}
trailingShadowView.isHidden = tableView.contentOffset.x + tableView.bounds.width >= tableView.contentSize.width
}
}
extension TableView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
resetShadows()
viewportChanged()
}
}
extension TableView: TableContentViewDelegate {
var containerScrollView: UIScrollView? {
delegate?.containerScrollView ?? _containerScrollView
}
var viewport: CGRect? {
self.delegate?.viewport
}
func tableContentView(_ tableContentView: TableContentView, needsUpdateViewport delta: CGPoint) {
viewportChanged()
}
func tableContentView(_ tableContentView: TableContentView, didChangeBounds bounds: CGRect, oldBounds: CGRect) {
viewportChanged()
}
func tableContentView(_ tableContentView: TableContentView, didChangeContentSize contentSize: CGSize, oldContentSize: CGSize) {
if let maintainLockOnCell {
delegate?.tableView(self, needsUpdateScrollPositionOnCell: maintainLockOnCell.cell, rect: maintainLockOnCell.rect, isRendered: maintainLockOnCell.cell.editor != nil)
}
}
func tableContentView(_ tableContentView: TableContentView, didCompleteLayoutWithBounds bounds: CGRect) {
resetShadows()
}
func tableContentView(_ tableContentView: TableContentView, didLayoutCell cell: TableCell) {
delegate?.tableView(self, didLayoutCell: cell)
}
func tableContentView(_ tableContentView: TableContentView, didSelectCells cells: [TableCell]) {
delegate?.tableView(self, didSelectCells: cells)
}
func tableContentView(_ tableContentView: TableContentView, didUnselectCells cells: [TableCell]) {
delegate?.tableView(self, didUnselectCells: cells)
}
func tableContentView(_ tableContentView: TableContentView, didReceiveFocusAt range: NSRange, in cell: TableCell) {
resetColumnResizingHandles(selectedCell: cell)
delegate?.tableView(self, didReceiveFocusAt: range, in: cell)
}
func tableContentView(_ tableContentView: TableContentView, didLoseFocusFrom range: NSRange, in cell: TableCell) {
removeSelectionBorders()
delegate?.tableView(self, didLoseFocusFrom: range, in: cell)
}
func tableContentView(_ tableContentView: TableContentView, didTapAtLocation location: CGPoint, characterRange: NSRange?, in cell: TableCell) {
delegate?.tableView(self, didTapAtLocation: location, characterRange: characterRange, in: cell)
}
func tableContentView(_ tableContentView: TableContentView, didChangeSelectionAt range: NSRange, attributes: [NSAttributedString.Key : Any], contentType: EditorContent.Name, in cell: TableCell) {
delegate?.tableView(self, didChangeSelectionAt: range, attributes: attributes, contentType: contentType, in: cell)
}
func tableContentView(_ tableContentView: TableContentView, didChangeBounds bounds: CGRect, in cell: TableCell) {
delegate?.tableView(self, didChangeBounds: bounds, in: cell)
}
func tableContentView(_ tableContentView: TableContentView, didReceiveKey key: EditorKey, at range: NSRange, in cell: TableCell) {
delegate?.tableView(self, didReceiveKey: key, at: range, in: cell)
}
func tableContentView(_ tableContentView: TableContentView, didAddNewRowAt index: Int) {
if let cell = tableView.cellAt(rowIndex: index, columnIndex: 0) {
cell.setFocus()
tableView.scrollTo(cell: cell)
}
}
func tableContentView(_ tableContentView: TableContentView, didUpdateCells cells: [TableCell]) {
viewportChanged()
}
func tableContentView(_ tableContentView: TableContentView, didAddNewColumnAt index: Int) {
if let cell = tableView.cellAt(rowIndex: 0, columnIndex: index) {
cell.setFocus()
tableView.scrollTo(cell: cell)
}
}
func tableContentView(_ tableContentView: TableContentView, didDeleteRowAt index: Int) {
}
func tableContentView(_ tableContentView: TableContentView, didDeleteColumnAt index: Int) {
}
func tableContentView(_ tableContentView: TableContentView, shouldChangeColumnWidth proposedWidth: CGFloat, for columnIndex: Int) -> Bool {
delegate?.tableView(self, shouldChangeColumnWidth: proposedWidth, for: columnIndex) ?? true
}
func tableContentView(_ tableContentView: TableContentView, cell: TableCell, didChangeBackgroundColor color: UIColor?, oldColor: UIColor?) {
}
func tableContentView(_ tableContentView: TableContentView, didAddCellToViewport cell: TableCell) {
delegate?.tableView(self, didAddCellToViewport: cell)
tableCellLifeCycleObserver?.tableView(self, didAddCellToViewport: cell)
}
func tableContentView(_ tableContentView: TableContentView, didRemoveCellFromViewport cell: TableCell) {
let handleToRemove = columnResizingHandles.first { $0.cell == cell }
handleToRemove?.removeFromSuperview()
columnResizingHandles.removeAll { $0 == handleToRemove }
delegate?.tableView(self, didRemoveCellFromViewport: cell)
tableCellLifeCycleObserver?.tableView(self, didRemoveCellFromViewport: cell)
}