metatext-app-ios-iphone-ipad/Mastodon/Sources/Mastodon/Entities/Filter.swift

64 lines
1.9 KiB
Swift
Raw Normal View History

2020-08-29 12:26:26 +02:00
// Copyright © 2020 Metabolist. All rights reserved.
import Foundation
2020-08-31 01:33:11 +02:00
public struct Filter: Codable, Hashable, Identifiable {
public enum Context: String, Codable, Unknowable {
2020-08-29 12:26:26 +02:00
case home
case notifications
case `public`
case thread
case account
case unknown
2020-08-31 01:33:11 +02:00
public static var unknownCase: Self { .unknown }
2020-08-29 12:26:26 +02:00
}
2020-08-31 01:33:11 +02:00
public let id: String
public var phrase: String
public var context: [Context]
public var expiresAt: Date?
public var irreversible: Bool
public var wholeWord: Bool
2020-08-29 12:26:26 +02:00
}
2020-08-31 01:33:11 +02:00
public extension Filter {
2020-08-29 12:26:26 +02:00
static let newFilterID: String = "com.metabolist.metatext.new-filter-id"
static let new = Self(id: newFilterID,
phrase: "",
context: [],
expiresAt: nil,
irreversible: false,
wholeWord: true)
}
2020-08-30 07:31:30 +02:00
extension Array where Element == Filter {
2020-08-30 08:49:32 +02:00
// swiftlint:disable line_length
2020-08-30 07:31:30 +02:00
// Adapted from https://github.com/tootsuite/mastodon/blob/bf477cee9f31036ebf3d164ddec1cebef5375513/app/javascript/mastodon/selectors/index.js#L43
2020-08-30 08:49:32 +02:00
// swiftlint:enable line_length
2020-08-31 01:33:11 +02:00
public func regularExpression() -> String? {
2020-08-30 07:31:30 +02:00
guard !isEmpty else { return nil }
return map {
var expression = NSRegularExpression.escapedPattern(for: $0.phrase)
if $0.wholeWord {
if expression.range(of: #"^[\w]"#, options: .regularExpression) != nil {
expression = #"\b"# + expression
}
if expression.range(of: #"[\w]$"#, options: .regularExpression) != nil {
expression += #"\b"#
}
}
return expression
}
.joined(separator: "|")
}
}
2020-08-29 12:26:26 +02:00
extension Filter.Context: Identifiable {
2020-08-31 01:33:11 +02:00
public var id: Self { self }
2020-08-29 12:26:26 +02:00
}