Skip to content

Commit

Permalink
Fix link char count (IOS-285)
Browse files Browse the repository at this point in the history
  • Loading branch information
kimar committed Jul 31, 2024
1 parent 42b47af commit d84ca7b
Show file tree
Hide file tree
Showing 2 changed files with 29 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,24 @@ extension ComposeContentViewModel {

// bind text
$content
.map { $0.count }
.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)
}
.assign(to: &$contentWeightedLength)

Publishers.CombineLatest(
Expand Down

0 comments on commit d84ca7b

Please sign in to comment.