Skip to content

Commit

Permalink
move to lineFragment+offset API
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmassicotte committed Dec 13, 2024
1 parent e81ce4c commit 06690a3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 14 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func characterIndexes(within rect: CGRect) -> IndexSet
func enumerateLineFragments(for rect: CGRect, strictIntersection: Bool, block: (CGRect, NSRange, inout Bool) -> Void)
func enumerateLineFragments(in range: NSRange, block: (CGRect, NSRange, inout Bool) -> Void)
func enumerateLineFragments(from index: Int, forward: Bool = true, block: (CGRect, NSRange, inout Bool) -> Void)
func lineFragment(after index: Int, forward: Bool = true) -> (CGRect, NSRange)?
func lineFragment(for index: Int, offset: Int) -> (CGRect, NSRange)?
func boundingRect(for range: NSRange) -> CGRect?
```

Expand Down
22 changes: 9 additions & 13 deletions Sources/Glyph/NSTextContainer+Additions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,27 +81,23 @@ extension NSTextContainer {
tk1EnumerateLineFragments(from: index, forward: forward, block: block)
}

/// Find line fragment details immediately above or below a character index.
public func lineFragment(after index: Int, forward: Bool = true) -> (CGRect, NSRange)? {
var pairs: [(CGRect, NSRange)] = []
/// Find line fragment offset from the first fragment containing index.
public func lineFragment(for index: Int, offset: Int) -> (CGRect, NSRange)? {
var fragment: (CGRect, NSRange)?
let forward = offset >= 0
var targetCount = abs(offset)

enumerateLineFragments(from: index, forward: forward) { rect, range, stop in
if pairs.count == 2 {
if targetCount == 0 {
fragment = (rect, range)
stop = true
return
}

pairs.append((rect, range))
targetCount -= 1
}

guard
pairs.count == 2,
let lastLine = pairs.last
else {
return nil
}

return lastLine
return fragment
}
}

Expand Down

0 comments on commit 06690a3

Please sign in to comment.