Skip to content

Commit

Permalink
Fix link char count (IOS-285) (#1336)
Browse files Browse the repository at this point in the history
This PR fixes the link char count which should be static (by default 23
chars per link) rather than the length of the link itself.
  • Loading branch information
kimar authored Jul 31, 2024
2 parents 42b47af + f15311f commit 8543142
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
11 changes: 11 additions & 0 deletions MastodonSDK/Sources/MastodonCore/MastodonAuthentication.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import CoreDataStack
import MastodonSDK

public struct MastodonAuthentication: Codable, Hashable, UserIdentifier {
public static let fallbackCharactersReservedPerURL = 23

public enum InstanceConfiguration: Codable, Hashable {
case v1(Mastodon.Entity.Instance)
case v2(Mastodon.Entity.V2.Instance, TranslationLanguages)
Expand Down Expand Up @@ -38,6 +40,15 @@ public struct MastodonAuthentication: Codable, Hashable, UserIdentifier {
}
return version?.majorServerVersion(greaterThanOrEquals: 4) ?? false // following Tags is support beginning with Mastodon v4.0.0
}

public var charactersReservedPerURL: Int {
switch self {
case let .v1(instance):
return instance.configuration?.statuses?.charactersReservedPerURL ?? fallbackCharactersReservedPerURL
case let .v2(instance, _):
return instance.configuration?.statuses?.charactersReservedPerURL ?? fallbackCharactersReservedPerURL
}
}
}

public typealias ID = UUID
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,26 @@ extension ComposeContentViewModel {

// bind text
$content
.map { $0.count }
.receive(on: DispatchQueue.global(qos: .background))
.map { [weak self] input in
guard let self, let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
return input.count
}
let matches = detector.matches(in: input, options: [], range: NSRange(location: 0, length: input.count))
let lengthWithoutLinks = input.count - matches.map({ match in
guard let range = Range(match.range, in: input) else {
return 0
}
let url = input[range]
return url.count
}).reduce(0, +)
let charactersReservedPerURL = authContext.mastodonAuthenticationBox
.authentication
.instanceConfiguration?
.charactersReservedPerURL ?? MastodonAuthentication.fallbackCharactersReservedPerURL
return lengthWithoutLinks + (matches.count * charactersReservedPerURL)
}
.receive(on: DispatchQueue.main)
.assign(to: &$contentWeightedLength)

Publishers.CombineLatest(
Expand Down

0 comments on commit 8543142

Please sign in to comment.