Fix `EditTagGroupView` (#1686)

* refactor data of `EditTagGroupView`

* lower case tags before saving because API is case-insensitive

* fix: "add new tag" `TextField` is not focused after adding the first tag (on both macOS and iOS)

* perf: improve symbol search performance

* improve layout and animation of symbol search

* fix: sort tags and remove duplicate tags

* fix: crash when open timeline for an empty tag group

* fix: revert concurrency code because performance issue at 1d3f271 is a false alarm

* add warning labels to help the users

* fix: state `tagGroup`

* fix: selecting symbol logic and warning labels

* refactor `EditTagGroupView.body`

* refactor warning labels

* Fix theme

* Move to its own folder

---------

Co-authored-by: Thomas Ricouard <ricouard77@gmail.com>
This commit is contained in:
Thai D. V 2023-11-27 15:13:07 +07:00 committed by GitHub
parent ea5480ef46
commit de83b8ec90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 455 additions and 234 deletions

View File

@ -108,7 +108,6 @@
E9DF420329830FEC0003AAD2 /* Action.js in Resources */ = {isa = PBXBuildFile; fileRef = E9DF420229830FEC0003AAD2 /* Action.js */; };
E9DF420729830FEC0003AAD2 /* IceCubesActionExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = E9DF41FA29830FEC0003AAD2 /* IceCubesActionExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
FA31A9AB2A66BF7C00D5F662 /* EditTagGroupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA31A9AA2A66BF7C00D5F662 /* EditTagGroupView.swift */; };
FAD203D02A66D8A80030A7FD /* Symbols.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAD203CF2A66D8A80030A7FD /* Symbols.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@ -248,7 +247,6 @@
E9DF420229830FEC0003AAD2 /* Action.js */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.javascript; path = Action.js; sourceTree = "<group>"; };
E9DF420429830FEC0003AAD2 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
FA31A9AA2A66BF7C00D5F662 /* EditTagGroupView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EditTagGroupView.swift; sourceTree = "<group>"; };
FAD203CF2A66D8A80030A7FD /* Symbols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Symbols.swift; sourceTree = "<group>"; };
FF8259FC298E42E000BEAB69 /* ko */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ko; path = ko.lproj/InfoPlist.strings; sourceTree = "<group>"; };
/* End PBXFileReference section */
@ -331,6 +329,14 @@
path = Plurals;
sourceTree = "<group>";
};
9F0811402B14869F0020F85E /* TagGroup */ = {
isa = PBXGroup;
children = (
FA31A9AA2A66BF7C00D5F662 /* EditTagGroupView.swift */,
);
path = TagGroup;
sourceTree = "<group>";
};
9F2A5417296AB631009B2D7C /* IceCubesNotifications */ = {
isa = PBXGroup;
children = (
@ -377,8 +383,6 @@
children = (
9F398AB229360A4C00A889F2 /* TimelineTab.swift */,
9F7335F12967608F00AFF0BA /* AddRemoteTimelineView.swift */,
FA31A9AA2A66BF7C00D5F662 /* EditTagGroupView.swift */,
FAD203CF2A66D8A80030A7FD /* Symbols.swift */,
);
path = Timeline;
sourceTree = "<group>";
@ -415,6 +419,7 @@
9FAE4AC9293783A200772766 /* Tabs */ = {
isa = PBXGroup;
children = (
9F0811402B14869F0020F85E /* TagGroup */,
9F7335F02967607A00AFF0BA /* Timeline */,
9FE151A4293C90EA00E9683D /* Settings */,
9F35DB4629506F6600B3281A /* NotificationTab.swift */,
@ -827,7 +832,6 @@
9FB183292AE9449100BBB692 /* IceCubesApp+Scene.swift in Sources */,
9F2B92F6295AE04800DE16D0 /* Tabs.swift in Sources */,
FA31A9AB2A66BF7C00D5F662 /* EditTagGroupView.swift in Sources */,
FAD203D02A66D8A80030A7FD /* Symbols.swift in Sources */,
9F398AB329360A4C00A889F2 /* TimelineTab.swift in Sources */,
9F398AA62935FE8A00A889F2 /* AppRegistry.swift in Sources */,
9FBFE63D292A715500C250E9 /* IceCubesApp.swift in Sources */,

View File

@ -117,7 +117,7 @@ extension View {
case let .shareImage(image, status):
ActivityView(image: image, status: status)
case let .editTagGroup(tagGroup, onSaved):
EditTagGroupView(editingTagGroup: tagGroup, onSaved: onSaved)
EditTagGroupView(tagGroup: tagGroup, onSaved: onSaved)
.withEnvironments()
}
}

View File

@ -0,0 +1,436 @@
import Combine
import DesignSystem
import Env
import Models
import Network
import NukeUI
import Shimmer
import SwiftUI
import SwiftData
import SFSafeSymbols
@MainActor
struct EditTagGroupView: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.modelContext) private var context
@Environment(Theme.self) private var theme
@State private var tagGroup: TagGroup
private let onSaved: ((TagGroup) -> Void)?
private let isNewGroup: Bool
@FocusState private var focusedField: Focus?
var body: some View {
NavigationStack {
Form {
Section {
TitleInputView(
title: $tagGroup.title,
titleValidationStatus: tagGroup.titleValidationStatus,
focusedField: $focusedField,
isNewGroup: isNewGroup
)
SymbolInputView(
selectedSymbol: $tagGroup.symbolName,
selectedSymbolValidationStatus: tagGroup.symbolNameValidationStatus,
focusedField: $focusedField
)
}
.listRowBackground(theme.primaryBackgroundColor)
Section("add-tag-groups.edit.tags") {
TagsInputView(
tags: $tagGroup.tags,
tagsValidationStatus: tagGroup.tagsValidationStatus,
focusedField: $focusedField
)
}
.listRowBackground(theme.primaryBackgroundColor)
}
.formStyle(.grouped)
.navigationTitle(
isNewGroup
? "timeline.filter.add-tag-groups"
: "timeline.filter.edit-tag-groups"
)
.navigationBarTitleDisplayMode(.inline)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("action.cancel", action: { dismiss() })
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("action.save", action: { save() })
.disabled(!tagGroup.isValid)
}
}
.onAppear {
focusedField = .title
}
}
}
init(tagGroup: TagGroup = .emptyGroup(), onSaved: ((TagGroup) -> Void)? = nil) {
self._tagGroup = State(wrappedValue: tagGroup)
self.onSaved = onSaved
self.isNewGroup = tagGroup.title.isEmpty
}
private func save() {
tagGroup.format()
context.insert(tagGroup)
onSaved?(tagGroup)
dismiss()
}
enum Focus {
case title
case symbol
case new
}
}
struct AddTagGroupView_Previews: PreviewProvider {
static var previews: some View {
let container = try? ModelContainer(for: TagGroup.self, configurations: ModelConfiguration())
// need to use `sheet` to show `symbolsSuggestionView` in preview
return Text("parent view for EditTagGroupView")
.sheet(isPresented: .constant(true)) {
EditTagGroupView()
.withEnvironments()
.modelContainer(container!)
}
}
}
private struct TitleInputView: View {
@Binding var title: String
let titleValidationStatus: TagGroup.TitleValidationStatus
@FocusState.Binding var focusedField: EditTagGroupView.Focus?
@Query var tagGroups: [TagGroup]
let isNewGroup: Bool
var body: some View {
VStack(alignment: .leading) {
TextField("add-tag-groups.edit.title.field", text: $title, axis: .horizontal)
.focused($focusedField, equals: .title)
.onSubmit {
focusedField = .symbol
}
if focusedField == .title, !warningText.isEmpty {
Text(warningText).warningLabel()
}
}
}
var warningText: String {
if case let .invalid(description) = titleValidationStatus {
return description
} else if
isNewGroup,
tagGroups.contains(where: { $0.title == title })
{
return "\(title) already exists"
}
return ""
}
}
private struct SymbolInputView: View {
@State private var symbolQuery = ""
@Binding var selectedSymbol: String
let selectedSymbolValidationStatus: TagGroup.SymbolNameValidationStatus
@FocusState.Binding var focusedField: EditTagGroupView.Focus?
var body: some View {
VStack(alignment: .leading) {
HStack {
TextField("add-tag-groups.edit.icon.field", text: $symbolQuery, axis: .horizontal)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.focused($focusedField, equals: .symbol)
.onSubmit {
if TagGroup.allSymbols.contains(symbolQuery) {
selectedSymbol = symbolQuery
}
focusedField = .new
}
.onChange(of: focusedField) {
symbolQuery = selectedSymbol
}
Image(systemName: selectedSymbol)
.frame(height: 30)
}
if case let .invalid(description) = selectedSymbolValidationStatus,
focusedField == .symbol
{
Text(description).warningLabel()
}
if focusedField == .symbol {
SymbolSearchResultsView(
symbolQuery: $symbolQuery,
selectedSymbol: $selectedSymbol,
focusedField: $focusedField
)
.frame(maxWidth: .infinity, alignment: .leading)
.frame(height: 40)
}
}
}
}
private struct TagsInputView: View {
@State private var newTag: String = ""
@Binding var tags: [String]
let tagsValidationStatus: TagGroup.TagsValidationStatus
@FocusState.Binding var focusedField: EditTagGroupView.Focus?
var body: some View {
ForEach(tags, id: \.self) { tag in
HStack {
Text(tag)
Spacer()
Button { deleteTag(tag) } label: {
Image(systemName: "trash")
.foregroundStyle(.red)
}
.buttonStyle(.plain)
}
}
.onDelete { indexes in
if let index = indexes.first {
let tag = tags[index]
deleteTag(tag)
}
}
// this `VStack` need to be here to overcome a SwiftUI bug
// "add new tag" `TextField` is not focused after adding the first tag
VStack(alignment: .leading) {
HStack {
// this condition is using to overcome a SwiftUI bug
// "add new tag" `TextField` is not focused after adding the first tag
if tags.isEmpty {
addNewTagTextField()
} else {
addNewTagTextField()
.onAppear { focusedField = .new }
}
Spacer()
if !newTag.isEmpty, !tags.contains(newTag) {
Button { addNewTag() } label: {
Image(systemName: "checkmark.circle.fill").tint(.green)
}
}
}
if focusedField == .new, !warningText.isEmpty {
Text(warningText).warningLabel()
}
}
var warningText: String {
if tags.contains(newTag) {
return "duplicated tag"
} else if case let .invalid(description) = tagsValidationStatus {
return description
}
return ""
}
}
private func addNewTagTextField() -> some View {
VStack(alignment: .leading) {
TextField("add-tag-groups.edit.tags.add", text: $newTag, axis: .horizontal)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.onSubmit {
addNewTag()
}
.focused($focusedField, equals: .new)
}
}
private func addNewTag() {
addTag(newTag.trimmingCharacters(in: .whitespaces).lowercased())
newTag = ""
focusedField = .new
}
private func addTag(_ tag: String) {
guard !tag.isEmpty,
!tags.contains(tag)
else { return }
tags.append(tag)
tags.sort()
}
private func deleteTag(_ tag: String) {
tags.removeAll(where: { $0 == tag })
}
}
private struct SymbolSearchResultsView: View {
@Binding var symbolQuery: String
@Binding var selectedSymbol: String
@State private var results: [String] = []
@FocusState.Binding var focusedField: EditTagGroupView.Focus?
var body: some View {
Group {
switch validationStatus {
case .valid:
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack {
ForEach(results, id: \.self) { name in
Button {
results = TagGroup.searchSymbol(for: symbolQuery, exclude: selectedSymbol)
selectedSymbol = name
symbolQuery = name
focusedField = .new
} label: {
Image(systemName: name)
}
.buttonStyle(.plain)
}
}
.animation(.spring(duration: 0.2), value: results)
}
.onAppear {
results = TagGroup.searchSymbol(for: symbolQuery, exclude: selectedSymbol)
}
case .invalid(let description):
Text(description)
.font(.subheadline)
.foregroundStyle(.secondary)
}
}
.onAppear {
results = TagGroup.searchSymbol(for: symbolQuery, exclude: selectedSymbol)
}
.onChange(of: symbolQuery) {
results = TagGroup.searchSymbol(for: symbolQuery, exclude: selectedSymbol)
}
}
// MARK: search results validation
enum ValidationStatus: Equatable {
case valid
case invalid(description: String)
}
var validationStatus: ValidationStatus {
if results.isEmpty {
if symbolQuery == selectedSymbol
&& !symbolQuery.isEmpty
&& results.count == 0
{
return .invalid(description: "\(symbolQuery) is already selected")
} else {
return .invalid(description: "No Symbol Found")
}
} else {
return .valid
}
}
}
extension TagGroup {
// MARK: title validation
enum TitleValidationStatus: Equatable {
case valid
case invalid(description: String)
}
var titleValidationStatus: TitleValidationStatus {
title.isEmpty ? .invalid(description: "title is empty") : .valid
}
// MARK: symbolName validation
enum SymbolNameValidationStatus: Equatable {
case valid
case invalid(description: String)
}
var symbolNameValidationStatus: SymbolNameValidationStatus {
if symbolName.isEmpty {
return .invalid(description: "no symbol is selected yet")
} else if !Self.allSymbols.contains(symbolName) {
return .invalid(description: "\(symbolName) is not a valid FSSymbol name")
}
return .valid
}
// MARK: tags validation
enum TagsValidationStatus: Equatable {
case valid
case invalid(description: String)
}
var tagsValidationStatus: TagsValidationStatus {
if tags.count < 2 {
return .invalid(description: "the number of tags is smaller than 2")
}
return .valid
}
// MARK: TagGroup validation
var isValid: Bool {
titleValidationStatus == .valid
&& symbolNameValidationStatus == .valid
&& tagsValidationStatus == .valid
}
// MARK: format
func format() {
title = title.trimmingCharacters(in: .whitespacesAndNewlines)
tags = tags.map { $0.lowercased() }
}
// MARK: static members
static func emptyGroup() -> TagGroup {
TagGroup(title: "", symbolName: "", tags: [])
}
static func searchSymbol(for query: String, exclude excludedSymbol: String) -> [String] {
guard !query.isEmpty else { return [] }
return Self.allSymbols.filter {
$0.contains(query) &&
$0 != excludedSymbol
}
}
static let allSymbols: [String] = SFSymbol.allSymbols.map { symbol in
symbol.rawValue
}
}
extension Text {
func warningLabel() -> Text {
self.font(.caption)
.foregroundStyle(.red)
}
}

View File

@ -1,213 +0,0 @@
import Combine
import DesignSystem
import Env
import Models
import Network
import NukeUI
import Shimmer
import SwiftUI
@MainActor
struct EditTagGroupView: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.modelContext) private var context
@Environment(Theme.self) private var theme
@State private var title: String = ""
@State private var sfSymbolName: String = ""
@State private var tags: [String] = []
@State private var newTag: String = ""
@State private var popupTagsPresented = false
private var editingTagGroup: TagGroup?
private var onSaved: ((TagGroup) -> Void)?
private var canSave: Bool {
!title.isEmpty &&
// At least have 2 tags, one main and one additional.
tags.count >= 2
}
@FocusState private var focusedField: Focus?
enum Focus {
case title
case symbol
case new
}
init(editingTagGroup: TagGroup? = nil, onSaved: ((TagGroup) -> Void)? = nil) {
self.editingTagGroup = editingTagGroup
self.onSaved = onSaved
}
var body: some View {
NavigationStack {
ZStack(alignment: .bottom) {
Form {
metadataSection
keywordsSection
}
.formStyle(.grouped)
.navigationTitle(editingTagGroup != nil ? "timeline.filter.edit-tag-groups" : "timeline.filter.add-tag-groups")
.navigationBarTitleDisplayMode(.inline)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("action.cancel", action: { dismiss() })
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("action.save", action: { save() })
.disabled(!canSave)
}
}
symbolsSuggestionView
}
.onAppear {
focusedField = .title
if let editingTagGroup {
title = editingTagGroup.title
sfSymbolName = editingTagGroup.symbolName
tags = editingTagGroup.tags
}
}
}
}
@ViewBuilder
private var metadataSection: some View {
Section {
TextField("add-tag-groups.edit.title.field", text: $title, axis: .horizontal)
.focused($focusedField, equals: Focus.title)
.onSubmit {
focusedField = Focus.symbol
}
HStack {
TextField("add-tag-groups.edit.icon.field", text: $sfSymbolName, axis: .horizontal)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.focused($focusedField, equals: Focus.symbol)
.onSubmit {
focusedField = Focus.new
}
.onChange(of: sfSymbolName) {
popupTagsPresented = true
}
Image(systemName: sfSymbolName)
}
}
.listRowBackground(theme.primaryBackgroundColor)
}
private var keywordsSection: some View {
Section("add-tag-groups.edit.tags") {
ForEach(tags, id: \.self) { tag in
HStack {
Text(tag)
Spacer()
Button {
deleteTag(tag)
} label: {
Image(systemName: "trash")
.tint(.red)
}
}
}
.onDelete { indexes in
if let index = indexes.first {
let tag = tags[index]
deleteTag(tag)
}
}
HStack {
TextField("add-tag-groups.edit.tags.add", text: $newTag, axis: .horizontal)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.onSubmit {
addNewTag()
}
.focused($focusedField, equals: Focus.new)
Spacer()
if !newTag.isEmpty {
Button {
addNewTag()
} label: {
Image(systemName: "checkmark.circle.fill")
.tint(.green)
}
}
}
}
.listRowBackground(theme.primaryBackgroundColor)
}
private func addNewTag() {
addTag(newTag.trimmingCharacters(in: .whitespaces))
newTag = ""
focusedField = Focus.new
}
private func addTag(_ tag: String) {
guard !tag.isEmpty else { return }
tags.append(tag)
}
private func deleteTag(_ tag: String) {
tags.removeAll(where: { $0 == tag })
}
private func save() {
if let editingTagGroup {
editingTagGroup.title = title
editingTagGroup.symbolName = sfSymbolName
editingTagGroup.tags = tags
onSaved?(editingTagGroup)
} else {
let tagGroup = TagGroup(title: title.trimmingCharacters(in: .whitespacesAndNewlines),
symbolName: sfSymbolName,
tags: tags)
context.insert(tagGroup)
onSaved?(tagGroup)
}
dismiss()
}
@ViewBuilder
private var symbolsSuggestionView: some View {
if focusedField == .symbol, !sfSymbolName.isEmpty {
let filteredMatches = allSymbols
.filter { $0.contains(sfSymbolName) }
if !filteredMatches.isEmpty {
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack {
ForEach(filteredMatches, id: \.self) { symbolName in
Button {
sfSymbolName = symbolName
} label: {
Image(systemName: symbolName)
}
}
}
.padding(.horizontal, .layoutPadding)
}
.frame(height: 40)
.background(.ultraThinMaterial)
}
} else {
EmptyView()
}
}
}
struct AddTagGroupView_Previews: PreviewProvider {
static var previews: some View {
EditTagGroupView()
.withEnvironments()
}
}

View File

@ -1,13 +0,0 @@
//
// Symbols.swift
// IceCubesApp
//
// Created by Alejandro Martinez on 18/7/23.
//
import Foundation
import SFSafeSymbols
let allSymbols: [String] = SFSymbol.allSymbols.map { symbol in
symbol.rawValue
}

View File

@ -34734,6 +34734,9 @@
}
}
}
},
"parent view for EditTagGroupView" : {
},
"placeholder.loading.long" : {
"localizations" : {

View File

@ -151,8 +151,12 @@ public enum TimelineFilter: Hashable, Equatable {
}
case let .tagGroup(_, tags):
var tags = tags
let tag = tags.removeFirst()
return Timelines.hashtag(tag: tag, additional: tags, maxId: maxId)
if !tags.isEmpty {
let tag = tags.removeFirst()
return Timelines.hashtag(tag: tag, additional: tags, maxId: maxId)
} else {
return Timelines.hashtag(tag: "", additional: tags, maxId: maxId)
}
}
}
}