Skip to content

Commit

Permalink
Implement frequency tracking for frequently used emojis
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanceriu committed Dec 16, 2024
1 parent e04c874 commit 60e9412
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
2 changes: 1 addition & 1 deletion ElementX/Sources/Application/AppSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ final class AppSettings {
@UserPreference(key: UserDefaultsKeys.hasRunIdentityConfirmationOnboarding, defaultValue: false, storageType: .userDefaults(store))
var hasRunIdentityConfirmationOnboarding

@UserPreference(key: UserDefaultsKeys.frequentlyUsedSystemEmojis, defaultValue: [String](), storageType: .userDefaults(store))
@UserPreference(key: UserDefaultsKeys.frequentlyUsedSystemEmojis, defaultValue: [FrequentlyUsedEmoji](), storageType: .userDefaults(store))
var frequentlyUsedSystemEmojis

// MARK: - Home Screen
Expand Down
18 changes: 13 additions & 5 deletions ElementX/Sources/Services/Emojis/EmojiProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import Emojibase
import Foundation
import OrderedCollections

class EmojiProvider: EmojiProviderProtocol {
private let maxFrequentEmojis = 20
Expand Down Expand Up @@ -61,18 +60,27 @@ class EmojiProvider: EmojiProviderProtocol {
return []
}

return appSettings.frequentlyUsedSystemEmojis
return appSettings.frequentlyUsedSystemEmojis.map(\.key)
}

func markEmojiAsFrequentlyUsed(_ emoji: String) {
guard !ProcessInfo.processInfo.isiOSAppOnMac else {
return
}

var uniqueOrderedRecents = OrderedSet(appSettings.frequentlyUsedSystemEmojis)
uniqueOrderedRecents.insert(emoji, at: 0)
let frequentlyUsed = if !frequentlyUsedSystemEmojis().contains(emoji) {
appSettings.frequentlyUsedSystemEmojis + [.init(count: 0, key: emoji)]
} else {
appSettings.frequentlyUsedSystemEmojis.map { frequentlyUsedEmoji in
if frequentlyUsedEmoji.key == emoji {
return FrequentlyUsedEmoji(count: frequentlyUsedEmoji.count + 1, key: emoji)
}

return frequentlyUsedEmoji
}
}

appSettings.frequentlyUsedSystemEmojis = Array(uniqueOrderedRecents)
appSettings.frequentlyUsedSystemEmojis = frequentlyUsed.sorted { $0.count > $1.count }
}

// MARK: - Private
Expand Down
9 changes: 9 additions & 0 deletions ElementX/Sources/Services/Emojis/EmojiProviderProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ enum EmojiProviderState {
case loaded([EmojiCategory])
}

struct FrequentlyUsedEmoji: Codable, Hashable {
let count: UInt
let key: String

static func == (lhs: FrequentlyUsedEmoji, rhs: FrequentlyUsedEmoji) -> Bool {
lhs.key == rhs.key
}
}

@MainActor
protocol EmojiProviderProtocol {
var state: EmojiProviderState { get }
Expand Down

0 comments on commit 60e9412

Please sign in to comment.