Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions MagazineLayout.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
93A1C04E21ACED1100DED67D /* ElementLocationFramePairsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93A1C00F21ACED0100DED67D /* ElementLocationFramePairsTests.swift */; };
93A1C04F21ACED1100DED67D /* ModelStateUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93A1C01021ACED0100DED67D /* ModelStateUpdateTests.swift */; };
93A868552EE0D7870027691E /* IDGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93A868542EE0D7870027691E /* IDGenerator.swift */; };
93F8D8B22FD38BBF005325C0 /* Array+SafeSubscript.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93F8D8B12FD38BBF005325C0 /* Array+SafeSubscript.swift */; };
93F8DAE62FD76026005325C0 /* Signposting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93F8DAE52FD76026005325C0 /* Signposting.swift */; };
FCAC642622085AF100973F4C /* MagazineLayoutHeaderVisibilityMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCAC642522085AF100973F4C /* MagazineLayoutHeaderVisibilityMode.swift */; };
FCAC642822085B0E00973F4C /* FooterModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCAC642722085B0E00973F4C /* FooterModel.swift */; };
Expand Down Expand Up @@ -97,6 +98,7 @@
93A1C05321ACEDFC00DED67D /* LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE; sourceTree = SOURCE_ROOT; };
93A1C05421ACEDFC00DED67D /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = SOURCE_ROOT; };
93A868542EE0D7870027691E /* IDGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IDGenerator.swift; sourceTree = "<group>"; };
93F8D8B12FD38BBF005325C0 /* Array+SafeSubscript.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Array+SafeSubscript.swift"; sourceTree = "<group>"; };
93F8DAE52FD76026005325C0 /* Signposting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Signposting.swift; sourceTree = "<group>"; };
FCAC642522085AF100973F4C /* MagazineLayoutHeaderVisibilityMode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MagazineLayoutHeaderVisibilityMode.swift; sourceTree = "<group>"; };
FCAC642722085B0E00973F4C /* FooterModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FooterModel.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -234,6 +236,7 @@
FDABC2572B23D0A000C9B8EF /* TargetContentOffsetAnchor.swift */,
FD244FEE28B41F9900046C0D /* UITraitCollection+DisplayScale.swift */,
93A868542EE0D7870027691E /* IDGenerator.swift */,
93F8D8B12FD38BBF005325C0 /* Array+SafeSubscript.swift */,
);
path = Types;
sourceTree = "<group>";
Expand Down Expand Up @@ -362,6 +365,7 @@
FCAC642822085B0E00973F4C /* FooterModel.swift in Sources */,
93A1C03C21ACED0100DED67D /* UICollectionViewDelegateMagazineLayout.swift in Sources */,
93A1C03721ACED0100DED67D /* MagazineLayoutItemSizeMode.swift in Sources */,
93F8D8B22FD38BBF005325C0 /* Array+SafeSubscript.swift in Sources */,
FD4DFF0A21B0D182001F46CE /* MagazineLayoutCollectionReusableView.swift in Sources */,
93A1C04321ACED0100DED67D /* MagazineLayoutItemWidthMode+WidthDivisor.swift in Sources */,
93A1C03D21ACED0100DED67D /* MagazineLayout+Default.swift in Sources */,
Expand Down
213 changes: 169 additions & 44 deletions MagazineLayout/LayoutCore/ModelState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -134,18 +134,24 @@ final class ModelState {
}

func itemLocationFramePairs(forItemsIn rect: CGRect) -> ElementLocationFramePairs {
prepareElementLocationsForFlattenedIndicesIfNeeded()

return elementLocationFramePairsForElements(
in: rect,
withElementLocationsForFlattenedIndices: itemLocationsForFlattenedIndices,
newElementLocationsForFlattenedIndices: newItemLocationsForFlattenedIndices,
andFramesProvidedBy: { itemLocation -> CGRect in
return frameForItem(at: itemLocation)
})
}

func headerLocationFramePairs(forHeadersIn rect: CGRect) -> ElementLocationFramePairs {
prepareElementLocationsForFlattenedIndicesIfNeeded()

return elementLocationFramePairsForElements(
in: rect,
withElementLocationsForFlattenedIndices: headerLocationsForFlattenedIndices,
newElementLocationsForFlattenedIndices: newHeaderLocationsForFlattenedIndices,
andFramesProvidedBy: { headerLocation -> CGRect in
guard
let headerFrame = frameForHeader(
Expand All @@ -160,9 +166,12 @@ final class ModelState {
}

func footerLocationFramePairs(forFootersIn rect: CGRect) -> ElementLocationFramePairs {
prepareElementLocationsForFlattenedIndicesIfNeeded()

return elementLocationFramePairsForElements(
in: rect,
withElementLocationsForFlattenedIndices: footerLocationsForFlattenedIndices,
newElementLocationsForFlattenedIndices: newFooterLocationsForFlattenedIndices,
andFramesProvidedBy: { footerLocation -> CGRect in
guard
let footerFrame = frameForFooter(
Expand All @@ -177,9 +186,12 @@ final class ModelState {
}

func backgroundLocationFramePairs(forBackgroundsIn rect: CGRect) -> ElementLocationFramePairs {
prepareElementLocationsForFlattenedIndicesIfNeeded()

return elementLocationFramePairsForElements(
in: rect,
withElementLocationsForFlattenedIndices: backgroundLocationsForFlattenedIndices,
newElementLocationsForFlattenedIndices: newBackgroundLocationsForFlattenedIndices,
andFramesProvidedBy: { backgroundLocation -> CGRect in
guard
let backgroundFrame = frameForBackground(
Expand All @@ -194,15 +206,25 @@ final class ModelState {
}

func sectionMaxY(forSectionAtIndex targetSectionIndex: Int) -> CGFloat {
flushSectionMaxYsCacheInvalidationIfNeeded()

var sectionMaxY: CGFloat {
guard targetSectionIndex >= 0 && targetSectionIndex < numberOfSections else {
assertionFailure("`targetSectionIndex` is not within the bounds of the section models array")
return 0
}

var totalHeight: CGFloat = 0
for sectionIndex in 0...targetSectionIndex {
totalHeight += sectionModels[sectionIndex].calculateHeight()
if MagazineLayout._enableExperimentalOptimizations {
sectionModels.withUnsafeMutableBufferPointer { sectionModels in
for sectionIndex in 0...targetSectionIndex {
totalHeight += sectionModels[sectionIndex].calculateHeight()
}
}
} else {
for sectionIndex in 0...targetSectionIndex {
totalHeight += sectionModels[sectionIndex].calculateHeight()
}
}

return totalHeight
Expand Down Expand Up @@ -299,10 +321,19 @@ final class ModelState {
let currentVisibleBounds = currentVisibleBoundsProvider()
let newModelState = ModelState(currentVisibleBoundsProvider: { currentVisibleBounds })
newModelState.sectionModels = sectionModels

prepareElementLocationsForFlattenedIndicesIfNeeded()

newModelState.headerLocationsForFlattenedIndices = headerLocationsForFlattenedIndices
newModelState.footerLocationsForFlattenedIndices = footerLocationsForFlattenedIndices
newModelState.backgroundLocationsForFlattenedIndices = backgroundLocationsForFlattenedIndices
newModelState.itemLocationsForFlattenedIndices = itemLocationsForFlattenedIndices

newModelState.newHeaderLocationsForFlattenedIndices = newHeaderLocationsForFlattenedIndices
newModelState.newFooterLocationsForFlattenedIndices = newFooterLocationsForFlattenedIndices
newModelState.newBackgroundLocationsForFlattenedIndices = newBackgroundLocationsForFlattenedIndices
newModelState.newItemLocationsForFlattenedIndices = newItemLocationsForFlattenedIndices

return newModelState
}

Expand Down Expand Up @@ -596,51 +627,105 @@ final class ModelState {
private var backgroundLocationsForFlattenedIndices = [Int: ElementLocation]()
private var itemLocationsForFlattenedIndices = [Int: ElementLocation]()

private var newHeaderLocationsForFlattenedIndices = [ElementLocation]()
private var newFooterLocationsForFlattenedIndices = [ElementLocation]()
private var newBackgroundLocationsForFlattenedIndices = [ElementLocation]()
private var newItemLocationsForFlattenedIndices = [ElementLocation]()

// When experimental optimizations are enabled, these defer the corresponding bookkeeping work
// until the next read that depends on it, coalescing repeated invalidations during a single
// round of section model mutations.
private var needsPrepareElementLocationsForFlattenedIndices = false
private var firstInvalidatedSectionMaxYIndex: Int?

private func prepareElementLocationsForFlattenedIndices() {
headerLocationsForFlattenedIndices.removeAll()
footerLocationsForFlattenedIndices.removeAll()
backgroundLocationsForFlattenedIndices.removeAll()
itemLocationsForFlattenedIndices.removeAll()

var flattenedHeaderIndex = 0
var flattenedFooterIndex = 0
var flattenedBackgroundIndex = 0
var flattenedItemIndex = 0
for sectionIndex in 0..<sectionModels.count {
if sectionModels[sectionIndex].headerModel != nil {
headerLocationsForFlattenedIndices[flattenedHeaderIndex] = ElementLocation(
elementIndex: 0,
sectionIndex: sectionIndex)
flattenedHeaderIndex += 1
}
if MagazineLayout._enableExperimentalOptimizations {
needsPrepareElementLocationsForFlattenedIndices = true
} else {
rebuildElementLocationsForFlattenedIndices()
}
}

if sectionModels[sectionIndex].footerModel != nil {
footerLocationsForFlattenedIndices[flattenedFooterIndex] = ElementLocation(
elementIndex: 0,
sectionIndex: sectionIndex)
flattenedFooterIndex += 1
}
private func prepareElementLocationsForFlattenedIndicesIfNeeded() {
guard needsPrepareElementLocationsForFlattenedIndices else { return }
rebuildElementLocationsForFlattenedIndices()
needsPrepareElementLocationsForFlattenedIndices = false
}

private func rebuildElementLocationsForFlattenedIndices() {
if MagazineLayout._enableExperimentalOptimizations {
newHeaderLocationsForFlattenedIndices.removeAll(keepingCapacity: true)
newFooterLocationsForFlattenedIndices.removeAll(keepingCapacity: true)
newBackgroundLocationsForFlattenedIndices.removeAll(keepingCapacity: true)
newItemLocationsForFlattenedIndices.removeAll(keepingCapacity: true)

for sectionIndex in 0..<sectionModels.count {
if sectionModels[sectionIndex].headerModel != nil {
let elementLocation = ElementLocation(elementIndex: 0, sectionIndex: sectionIndex)
newHeaderLocationsForFlattenedIndices.append(elementLocation)
}

if sectionModels[sectionIndex].footerModel != nil {
let elementLocation = ElementLocation(elementIndex: 0, sectionIndex: sectionIndex)
newFooterLocationsForFlattenedIndices.append(elementLocation)
}

if sectionModels[sectionIndex].backgroundModel != nil {
backgroundLocationsForFlattenedIndices[flattenedBackgroundIndex] = ElementLocation(
elementIndex: 0,
sectionIndex: sectionIndex)
flattenedBackgroundIndex += 1
if sectionModels[sectionIndex].backgroundModel != nil {
let elementLocation = ElementLocation(elementIndex: 0, sectionIndex: sectionIndex)
newBackgroundLocationsForFlattenedIndices.append(elementLocation)
}

for itemIndex in 0..<sectionModels[sectionIndex].numberOfItems {
let elementLocation = ElementLocation(elementIndex: itemIndex, sectionIndex: sectionIndex)
newItemLocationsForFlattenedIndices.append(elementLocation)
}
Comment on lines +656 to +681

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same logic as the existing else branch, but using the new arrays instead of dictionaries

}
} else {
headerLocationsForFlattenedIndices.removeAll()
footerLocationsForFlattenedIndices.removeAll()
backgroundLocationsForFlattenedIndices.removeAll()
itemLocationsForFlattenedIndices.removeAll()

var flattenedHeaderIndex = 0
var flattenedFooterIndex = 0
var flattenedBackgroundIndex = 0
var flattenedItemIndex = 0
for sectionIndex in 0..<sectionModels.count {
if sectionModels[sectionIndex].headerModel != nil {
headerLocationsForFlattenedIndices[flattenedHeaderIndex] = ElementLocation(
elementIndex: 0,
sectionIndex: sectionIndex)
flattenedHeaderIndex += 1
}

if sectionModels[sectionIndex].footerModel != nil {
footerLocationsForFlattenedIndices[flattenedFooterIndex] = ElementLocation(
elementIndex: 0,
sectionIndex: sectionIndex)
flattenedFooterIndex += 1
}

if sectionModels[sectionIndex].backgroundModel != nil {
backgroundLocationsForFlattenedIndices[flattenedBackgroundIndex] = ElementLocation(
elementIndex: 0,
sectionIndex: sectionIndex)
flattenedBackgroundIndex += 1
}

for itemIndex in 0..<sectionModels[sectionIndex].numberOfItems {
itemLocationsForFlattenedIndices[flattenedItemIndex] = ElementLocation(
elementIndex: itemIndex,
sectionIndex: sectionIndex)
flattenedItemIndex += 1
for itemIndex in 0..<sectionModels[sectionIndex].numberOfItems {
itemLocationsForFlattenedIndices[flattenedItemIndex] = ElementLocation(
elementIndex: itemIndex,
sectionIndex: sectionIndex)
flattenedItemIndex += 1
}
Comment on lines +684 to +720

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

existing code, just indented and put in an else branch

}
}
}

private func elementLocationFramePairsForElements(
in rect: CGRect,
withElementLocationsForFlattenedIndices elementLocationsForFlattenedIndices: [Int: ElementLocation],
newElementLocationsForFlattenedIndices: [ElementLocation],
andFramesProvidedBy frameProvider: ((ElementLocation) -> CGRect))
-> ElementLocationFramePairs
{
Expand All @@ -650,6 +735,7 @@ final class ModelState {
let indexOfFirstFoundElement = indexOfFirstFoundElement(
in: rect,
withElementLocationsForFlattenedIndices: elementLocationsForFlattenedIndices,
newElementLocationsForFlattenedIndices: newElementLocationsForFlattenedIndices,
andFramesProvidedBy: frameProvider) else
{
return elementLocationFramePairs
Expand All @@ -663,7 +749,8 @@ final class ModelState {
for elementLocationIndex in (0..<indexOfFirstFoundElement).reversed() {
let elementLocation = self.elementLocation(
forFlattenedIndex: elementLocationIndex,
in: elementLocationsForFlattenedIndices)
in: elementLocationsForFlattenedIndices,
newElementLocationsForFlattenedIndices: newElementLocationsForFlattenedIndices)
let frame = frameProvider(elementLocation)

guard frame.maxY > rect.minY else {
Expand All @@ -684,10 +771,17 @@ final class ModelState {
}

// Look forward to find visible elements
for elementLocationIndex in indexOfFirstFoundElement..<elementLocationsForFlattenedIndices.count {
let numberOfElementLocations =
if MagazineLayout._enableExperimentalOptimizations {
newElementLocationsForFlattenedIndices.count
} else {
elementLocationsForFlattenedIndices.count
}
for elementLocationIndex in indexOfFirstFoundElement..<numberOfElementLocations {
let elementLocation = self.elementLocation(
forFlattenedIndex: elementLocationIndex,
in: elementLocationsForFlattenedIndices)
in: elementLocationsForFlattenedIndices,
newElementLocationsForFlattenedIndices: newElementLocationsForFlattenedIndices)
let frame = frameProvider(elementLocation)
guard frame.minY < rect.maxY else { break }

Expand All @@ -701,17 +795,26 @@ final class ModelState {
private func indexOfFirstFoundElement(
in rect: CGRect,
withElementLocationsForFlattenedIndices elementLocationsForFlattenedIndices: [Int: ElementLocation],
newElementLocationsForFlattenedIndices: [ElementLocation],
andFramesProvidedBy frameProvider: ((ElementLocation) -> CGRect))
-> Int?
{
let numberOfElementLocations =
if MagazineLayout._enableExperimentalOptimizations {
newElementLocationsForFlattenedIndices.count
} else {
elementLocationsForFlattenedIndices.count
}

var lowerBound = 0
var upperBound = elementLocationsForFlattenedIndices.count - 1
var upperBound = numberOfElementLocations - 1

while lowerBound <= upperBound {
let index = (lowerBound + upperBound) / 2
let elementLocation = self.elementLocation(
forFlattenedIndex: index,
in: elementLocationsForFlattenedIndices)
in: elementLocationsForFlattenedIndices,
newElementLocationsForFlattenedIndices: newElementLocationsForFlattenedIndices)
let elementFrame = frameProvider(elementLocation)
if elementFrame.maxY <= rect.minY {
lowerBound = index + 1
Expand All @@ -727,14 +830,19 @@ final class ModelState {

private func elementLocation(
forFlattenedIndex index: Int,
in elementLocationsForFlattenedIndices: [Int: ElementLocation])
in elementLocationsForFlattenedIndices: [Int: ElementLocation],
newElementLocationsForFlattenedIndices: [ElementLocation])
-> ElementLocation
{
guard let elementLocation = elementLocationsForFlattenedIndices[index] else {
preconditionFailure("`elementLocationsForFlattenedIndices` must have a complete mapping of indices in 0..<\(elementLocationsForFlattenedIndices.count) to element locations")
}
if MagazineLayout._enableExperimentalOptimizations {
return newElementLocationsForFlattenedIndices[index]
} else {
guard let elementLocation = elementLocationsForFlattenedIndices[index] else {
preconditionFailure("`elementLocationsForFlattenedIndices` must have a complete mapping of indices in 0..<\(elementLocationsForFlattenedIndices.count) to element locations")
}

return elementLocation
return elementLocation
}
}

private func allocateMemoryForSectionMaxYsCache() {
Expand Down Expand Up @@ -770,6 +878,23 @@ final class ModelState {
}

func invalidateSectionMaxYsCacheForSectionIndices(startingAt sectionIndex: Int) {
if MagazineLayout._enableExperimentalOptimizations {
firstInvalidatedSectionMaxYIndex = min(
firstInvalidatedSectionMaxYIndex ?? sectionIndex,
sectionIndex)
} else {
clearSectionMaxYsCache(startingAt: sectionIndex)
}
}

private func flushSectionMaxYsCacheInvalidationIfNeeded() {
guard let firstInvalidatedSectionMaxYIndex else { return }
clearSectionMaxYsCache(startingAt: firstInvalidatedSectionMaxYIndex)
self.firstInvalidatedSectionMaxYIndex = nil
}

/// Clears cached section max-Y values from `sectionIndex` through the end of the cache.
private func clearSectionMaxYsCache(startingAt sectionIndex: Int) {
guard sectionIndex >= 0, sectionIndex < sectionMaxYsCache.count else {
assertionFailure("Cannot invalidate `sectionMaxYsCache` starting at an invalid (negative or out-of-bounds) `sectionIndex` (\(sectionIndex)).")
return
Expand Down
Loading
Loading