From ecaca7c138119da55f3c4c1854d1f94eab229259 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:21:25 +0100 Subject: [PATCH 1/5] Add bookmarks - Implement bookmarks screen: list synced with 4PDA account, nested folders, opening links via deeplink handler, copy link and delete (context menu / swipe) - Add bookmarks as a separate tab bar item (keeps `more` raw value for saved start page) - Add "Add to bookmarks" to topic, forum, article and articles list menus - Add addBookmark/deleteBookmark to APIClient (full links, as the site stores them) - Make BookmarksParser resilient to malformed entries instead of force casting Co-Authored-By: Claude Opus 5.5 --- Modules/Sources/APIClient/APIClient.swift | 47 ++++- .../AnalyticsClient/Events/ForumEvent.swift | 5 +- .../AnalyticsClient/Events/TopicEvent.swift | 1 + Modules/Sources/AppFeature/AppFeature.swift | 18 +- Modules/Sources/AppFeature/AppView.swift | 15 +- .../Sources/AppFeature/Navigation/Path.swift | 6 + .../AppFeature/Navigation/StackTab.swift | 7 + .../Analytics/ArticleFeature+Analytics.swift | 2 + .../ArticleFeature/ArticleFeature.swift | 13 ++ .../Resources/Localizable.xcstrings | 10 + .../ArticleFeature/Views/ArticleMenu.swift | 8 + .../ArticlesListFeature.swift | 11 +- .../ArticlesListScreen.swift | 10 +- .../BookmarksFeature/BookmarksFeature.swift | 175 +++++++++++++++-- .../BookmarksFeature/BookmarksScreen.swift | 181 +++++++++++++----- .../Resources/Localizable.xcstrings | 61 ++++-- .../Analytics/ForumFeature+Analytics.swift | 2 +- .../Sources/ForumFeature/ForumFeature.swift | 14 +- .../Sources/ForumFeature/ForumScreen.swift | 8 + .../Resources/Localizable.xcstrings | 10 + Modules/Sources/Models/App/AppTab.swift | 8 +- .../Sources/Models/Bookmarks/Bookmark.swift | 21 ++ .../Models/Notifications/Notifications.swift | 1 + .../Models/Resources/Localizable.xcstrings | 10 + .../Parsers/BookmarksParser.swift | 75 +++++--- .../SharedUI/Articles/ArticleRowView.swift | 13 +- .../SharedUI/Resources/Localizable.xcstrings | 10 + .../ToastClient/Models/ToastMessage.swift | 8 + .../Resources/Localizable.xcstrings | 10 + .../Analytics/TopicFeature+Analytics.swift | 2 + .../Models/TopicContextMenuAction.swift | 1 + .../Resources/Localizable.xcstrings | 10 + .../Sources/TopicFeature/TopicFeature.swift | 11 ++ .../Sources/TopicFeature/TopicScreen.swift | 4 + Project.swift | 2 + 35 files changed, 679 insertions(+), 111 deletions(-) diff --git a/Modules/Sources/APIClient/APIClient.swift b/Modules/Sources/APIClient/APIClient.swift index 4bf37979..b44a2a9c 100644 --- a/Modules/Sources/APIClient/APIClient.swift +++ b/Modules/Sources/APIClient/APIClient.swift @@ -60,6 +60,8 @@ public struct APIClient: Sendable { // Bookmarks public var getBookmarksList: @Sendable () async throws -> [Bookmark] + public var addBookmark: @Sendable (_ parentId: Int, _ name: String, _ format: Bookmark.Format) async throws -> Bool + public var deleteBookmark: @Sendable (_ bookmark: Bookmark) async throws -> Bool // Forum public var getForumsList: @Sendable (_ policy: CachePolicy) async throws -> AsyncThrowingStream<[ForumInfo], any Error> @@ -355,6 +357,28 @@ extension APIClient: DependencyKey { let response = try await api.send(MemberCommand.Bookmarks.list) return try await parser.parseBookmarksList(response) }, + addBookmark: { parentId, name, format in + let request = BookmarkRequest( + parentId: parentId, + name: name, + number: 0, + format: format.asRequestFormat, + isDeleted: false + ) + let response = try await api.send(MemberCommand.Bookmarks.add(data: request)) + return Int(response.getResponseStatus()) == 0 + }, + deleteBookmark: { bookmark in + let request = BookmarkRequest( + parentId: bookmark.parentId, + name: bookmark.name, + number: bookmark.number, + format: bookmark.format.asRequestFormat, + isDeleted: true + ) + let response = try await api.send(MemberCommand.Bookmarks.modify(id: bookmark.id, data: request)) + return Int(response.getResponseStatus()) == 0 + }, // MARK: - Forum @@ -817,7 +841,13 @@ extension APIClient: DependencyKey { return true }, getBookmarksList: { - return [.mockArticle, .mockForum, .mockUser] + return [.mockFolder, .mockSubFolder, .mockArticle, .mockForum, .mockUser] + }, + addBookmark: { _, _, _ in + return true + }, + deleteBookmark: { _ in + return true }, getForumsList: { _ in return .finished() @@ -1047,3 +1077,18 @@ extension String { .components(separatedBy: ",")[number] } } + +// MARK: - Bookmark Format Mapping + +private extension Bookmark.Format { + var asRequestFormat: BookmarkRequest.BookmarkFormat { + switch self { + case .folder: + return .folder + case let .url(url): + // Site stores bookmarks with full links + let absolute = url.scheme == nil ? URL(string: url.absoluteString, relativeTo: Bookmark.baseURL)?.absoluteURL : url + return .url(url: (absolute ?? url).absoluteString) + } + } +} diff --git a/Modules/Sources/AnalyticsClient/Events/ForumEvent.swift b/Modules/Sources/AnalyticsClient/Events/ForumEvent.swift index ab778974..4ed2db27 100644 --- a/Modules/Sources/AnalyticsClient/Events/ForumEvent.swift +++ b/Modules/Sources/AnalyticsClient/Events/ForumEvent.swift @@ -17,7 +17,7 @@ public enum ForumEvent: Event { case sectionExpandTapped(String) // case menuSort - // case menuBookmarks + case menuAddToBookmarks(Int) case menuOpen(Int) case menuGoToEnd(Int) @@ -61,7 +61,8 @@ public enum ForumEvent: Event { case let .menuGoToEnd(id): return ["id": String(id)] - case let .menuEdit(id): + case let .menuEdit(id), + let .menuAddToBookmarks(id): return ["id": String(id)] case let .menuStat(id, isForum): diff --git a/Modules/Sources/AnalyticsClient/Events/TopicEvent.swift b/Modules/Sources/AnalyticsClient/Events/TopicEvent.swift index e4b23ad0..540af077 100644 --- a/Modules/Sources/AnalyticsClient/Events/TopicEvent.swift +++ b/Modules/Sources/AnalyticsClient/Events/TopicEvent.swift @@ -20,6 +20,7 @@ public enum TopicEvent: Event { case menuOpenInBrowser case menuGoToEnd case menuSetFavorite + case menuAddToBookmarks case menuAboutTopic case menuEditTopic case menuWritePost diff --git a/Modules/Sources/AppFeature/AppFeature.swift b/Modules/Sources/AppFeature/AppFeature.swift index f2325464..40507b14 100644 --- a/Modules/Sources/AppFeature/AppFeature.swift +++ b/Modules/Sources/AppFeature/AppFeature.swift @@ -68,6 +68,7 @@ public struct AppFeature: Reducer, Sendable { public var articlesTab: StackTab.State public var favoritesTab: StackTab.State public var forumTab: StackTab.State + public var bookmarksTab: StackTab.State public var moreTab: StackTab.State @Presents public var logStore: LogStoreFeature.State? @@ -102,6 +103,7 @@ public struct AppFeature: Reducer, Sendable { articlesTab: StackTab.State = StackTab.State(root: .articles(.articlesList(ArticlesListFeature.State()))), favoritesTab: StackTab.State = StackTab.State(root: .favorites(FavoritesFeature.State())), forumTab: StackTab.State = StackTab.State(root: .forum(.forumList(ForumsListFeature.State()))), + bookmarksTab: StackTab.State = StackTab.State(root: .more(.bookmarks(BookmarksFeature.State()))), moreTab: StackTab.State = StackTab.State(root: .more(.more(MoreFeature.State()))), alert: AlertState? = nil, selectedTab: AppTab = .articles, @@ -114,6 +116,7 @@ public struct AppFeature: Reducer, Sendable { self.articlesTab = articlesTab self.favoritesTab = favoritesTab self.forumTab = forumTab + self.bookmarksTab = bookmarksTab self.moreTab = moreTab self.alert = alert @@ -139,6 +142,7 @@ public struct AppFeature: Reducer, Sendable { case articlesTab(StackTab.Action) case favoritesTab(StackTab.Action) case forumTab(StackTab.Action) + case bookmarksTab(StackTab.Action) case moreTab(StackTab.Action) case logStore(PresentationAction) @@ -203,6 +207,10 @@ public struct AppFeature: Reducer, Sendable { StackTab() } + Scope(\.bookmarksTab, action: \.bookmarksTab) { + StackTab() + } + Scope(\.moreTab, action: \.moreTab) { StackTab() } @@ -516,6 +524,7 @@ public struct AppFeature: Reducer, Sendable { case let .articlesTab(.delegate(.showTabBar(show))), let .favoritesTab(.delegate(.showTabBar(show))), let .forumTab(.delegate(.showTabBar(show))), + let .bookmarksTab(.delegate(.showTabBar(show))), let .moreTab(.delegate(.showTabBar(show))): state.showTabBar = show return .none @@ -523,12 +532,13 @@ public struct AppFeature: Reducer, Sendable { case let .articlesTab(.delegate(.switchTab(to: tab))), let .favoritesTab(.delegate(.switchTab(to: tab))), let .forumTab(.delegate(.switchTab(to: tab))), + let .bookmarksTab(.delegate(.switchTab(to: tab))), let .moreTab(.delegate(.switchTab(to: tab))): state.previousTab = state.selectedTab state.selectedTab = tab return .none - case .articlesTab, .favoritesTab, .forumTab, .moreTab: + case .articlesTab, .favoritesTab, .forumTab, .bookmarksTab, .moreTab: return .none case .appDelegate: @@ -558,6 +568,9 @@ public struct AppFeature: Reducer, Sendable { case .forum: state.forumTab.path.removeAll() + case .bookmarks: + state.bookmarksTab.path.removeAll() + case .more: state.moreTab.path.removeAll() } @@ -575,7 +588,7 @@ public struct AppFeature: Reducer, Sendable { private func removeNotifications(_ state: inout State) -> Effect { return .run { [tab = state.selectedTab] _ in switch tab { - case .articles, .forum, .more: + case .articles, .forum, .bookmarks, .more: break case .favorites: break @@ -594,6 +607,7 @@ public struct AppFeature: Reducer, Sendable { case .articles: return .send(.articlesTab(action)) case .favorites: return .send(.favoritesTab(action)) case .forum: return .send(.forumTab(action)) + case .bookmarks: return .send(.bookmarksTab(action)) case .more: return .send(.moreTab(action)) } } diff --git a/Modules/Sources/AppFeature/AppView.swift b/Modules/Sources/AppFeature/AppView.swift index f085f867..74325f17 100644 --- a/Modules/Sources/AppFeature/AppView.swift +++ b/Modules/Sources/AppFeature/AppView.swift @@ -164,6 +164,14 @@ struct LiquidTabView: View { StackTabView(store: store.scope(\.forumTab, action: \.forumTab)) } + Tab( + AppTab.bookmarks.title, + systemSymbol: AppTab.bookmarks.iconSymbol, + value: .bookmarks + ) { + StackTabView(store: store.scope(\.bookmarksTab, action: \.bookmarksTab)) + } + Tab( AppTab.more.title, systemSymbol: AppTab.more.iconSymbol, @@ -202,7 +210,7 @@ struct LiquidTabView: View { struct OldTabView: View { @Perception.Bindable var store: StoreOf - @State private var shouldAnimatedTabItem: [Bool] = [false, false, false, false] + @State private var shouldAnimatedTabItem: [Bool] = Array(repeating: false, count: AppTab.allCases.count) @Environment(\.backgroundColors) private var backgroundColors var body: some View { @@ -217,6 +225,9 @@ struct OldTabView: View { StackTabView(store: store.scope(\.forumTab, action: \.forumTab)) .tag(AppTab.forum) + StackTabView(store: store.scope(\.bookmarksTab, action: \.bookmarksTab)) + .tag(AppTab.bookmarks) + StackTabView(store: store.scope(\.moreTab, action: \.moreTab)) .tag(AppTab.more) } @@ -431,6 +442,8 @@ extension LiquidTabView { return getPage(for: store.scope(\.favoritesTab, action: \.favoritesTab)) case .forum: return getPage(for: store.scope(\.forumTab, action: \.forumTab)) + case .bookmarks: + return getPage(for: store.scope(\.bookmarksTab, action: \.bookmarksTab)) case .more: return getPage(for: store.scope(\.moreTab, action: \.moreTab)) } diff --git a/Modules/Sources/AppFeature/Navigation/Path.swift b/Modules/Sources/AppFeature/Navigation/Path.swift index 3ad6ca25..41b127cc 100644 --- a/Modules/Sources/AppFeature/Navigation/Path.swift +++ b/Modules/Sources/AppFeature/Navigation/Path.swift @@ -10,6 +10,7 @@ import ComposableArchitecture import AnnouncementFeature import ArticleFeature import ArticlesListFeature +import BookmarksFeature import DeveloperFeature import DeviceSpecificationsFeature import DeviceTypeFeature @@ -64,6 +65,7 @@ public enum Path { case more(MoreFeature) case profile(ProfileFeature) case history(HistoryFeature) + case bookmarks(BookmarksFeature) case mentions(MentionsFeature) case reputation(ReputationFeature) } @@ -193,6 +195,10 @@ extension Path { HistoryScreen(store: store) .tracking(for: HistoryScreen.self) + case let .bookmarks(store): + BookmarksScreen(store: store) + .tracking(for: BookmarksScreen.self) + case let .mentions(store): MentionsScreen(store: store) .tracking(for: MentionsScreen.self) diff --git a/Modules/Sources/AppFeature/Navigation/StackTab.swift b/Modules/Sources/AppFeature/Navigation/StackTab.swift index d04d8967..7dd73d10 100644 --- a/Modules/Sources/AppFeature/Navigation/StackTab.swift +++ b/Modules/Sources/AppFeature/Navigation/StackTab.swift @@ -8,6 +8,7 @@ import Foundation import AnalyticsClient +import BookmarksFeature import DeeplinkHandler import Models import TCAExtensions @@ -411,6 +412,12 @@ public struct StackTab: Reducer, Sendable { case let .history(.delegate(.openTopic(id: id, name: name, goTo: goTo))): state.path.append(.forum(.topic(TopicFeature.State(topicId: id, topicName: name, goTo: goTo)))) + case let .bookmarks(.delegate(.openFolder(id: id, name: name))): + state.path.append(.more(.bookmarks(BookmarksFeature.State(folderId: id, folderName: name)))) + + case let .bookmarks(.delegate(.openURL(url))): + return handleInnerDeeplink(url: url, state: &state) + case let .mentions(.delegate(.openArticle(sourceId: sourceId, targetId: targetId))): let articlePreview = ArticlePreview.innerDeeplink(id: sourceId) state.path.append(.articles(.article(ArticleFeature.State.init(articlePreview: articlePreview, scrollToId: targetId)))) diff --git a/Modules/Sources/ArticleFeature/Analytics/ArticleFeature+Analytics.swift b/Modules/Sources/ArticleFeature/Analytics/ArticleFeature+Analytics.swift index 983d9593..25212c30 100644 --- a/Modules/Sources/ArticleFeature/Analytics/ArticleFeature+Analytics.swift +++ b/Modules/Sources/ArticleFeature/Analytics/ArticleFeature+Analytics.swift @@ -53,6 +53,8 @@ extension ArticleFeature { analytics.log(ArticleEvent.linkCopied(state.articlePreview.url)) case .shareLink: analytics.log(ArticleEvent.linkShareOpened(state.articlePreview.url)) + case .addToBookmarks: + analytics.log(ArticleEvent.bookmarkButtonTapped(state.articlePreview.url)) } case let .linkShared(success, url): diff --git a/Modules/Sources/ArticleFeature/ArticleFeature.swift b/Modules/Sources/ArticleFeature/ArticleFeature.swift index d348b34a..32cc970c 100644 --- a/Modules/Sources/ArticleFeature/ArticleFeature.swift +++ b/Modules/Sources/ArticleFeature/ArticleFeature.swift @@ -29,6 +29,7 @@ public struct ArticleFeature: Reducer, Sendable { public enum ArticleMenuAction: Sendable { case copyLink case shareLink + case addToBookmarks } // MARK: - Localizations @@ -168,6 +169,7 @@ public struct ArticleFeature: Reducer, Sendable { @Dependency(\.analyticsClient) var analyticsClient @Dependency(\.pasteboardClient) var pasteboardClient @Dependency(\.notificationsClient) var notificationsClient + @Dependency(\.notificationCenter) var notificationCenter @Dependency(\.openURL) var openURL @Dependency(\.dismiss) var dismiss @Dependency(\.continuousClock) var clock @@ -474,6 +476,17 @@ public struct ArticleFeature: Reducer, Sendable { case .shareLink: state.destination = .share(state.articlePreview.url) + + case .addToBookmarks: + let title = state.article?.title ?? state.articlePreview.title + return .run { [url = state.articlePreview.url, title] _ in + let status = try await apiClient.addBookmark(0, title, .url(url: url)) + await toastClient.showToast(status ? .addedToBookmarks : .whoopsSomethingWentWrong) + if status { notificationCenter.post(name: .bookmarksUpdated, object: nil) } + } catch: { error, _ in + analyticsClient.capture(error) + await toastClient.showToast(.whoopsSomethingWentWrong) + } } return .none diff --git a/Modules/Sources/ArticleFeature/Resources/Localizable.xcstrings b/Modules/Sources/ArticleFeature/Resources/Localizable.xcstrings index 3f7f49d9..dbb03fa5 100644 --- a/Modules/Sources/ArticleFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/ArticleFeature/Resources/Localizable.xcstrings @@ -31,6 +31,16 @@ } } }, + "Add to bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить в закладки" + } + } + } + }, "Comment has been deleted" : { "localizations" : { "ru" : { diff --git a/Modules/Sources/ArticleFeature/Views/ArticleMenu.swift b/Modules/Sources/ArticleFeature/Views/ArticleMenu.swift index 480b9604..d124d604 100644 --- a/Modules/Sources/ArticleFeature/Views/ArticleMenu.swift +++ b/Modules/Sources/ArticleFeature/Views/ArticleMenu.swift @@ -28,6 +28,14 @@ public struct ArticleMenu: View { ContextButton(text: LocalizedStringResource("Share Link", bundle: .module), symbol: .squareAndArrowUp) { store.send(.menuActionTapped(.shareLink)) } + + if store.isAuthorized { + Section { + ContextButton(text: LocalizedStringResource("Add to bookmarks", bundle: .module), symbol: .bookmark) { + store.send(.menuActionTapped(.addToBookmarks)) + } + } + } } label: { Image(systemSymbol: .ellipsis) .font(.body) diff --git a/Modules/Sources/ArticlesListFeature/ArticlesListFeature.swift b/Modules/Sources/ArticlesListFeature/ArticlesListFeature.swift index 5968f5df..648559d5 100644 --- a/Modules/Sources/ArticlesListFeature/ArticlesListFeature.swift +++ b/Modules/Sources/ArticlesListFeature/ArticlesListFeature.swift @@ -138,6 +138,7 @@ public struct ArticlesListFeature: Reducer, Sendable { @Dependency(\.pasteboardClient) private var pasteboardClient @Dependency(\.hapticClient) private var hapticClient @Dependency(\.continuousClock) private var clock + @Dependency(\.notificationCenter) private var notificationCenter // MARK: - Body @@ -252,8 +253,14 @@ public struct ArticlesListFeature: Reducer, Sendable { return .run { _ in await open(url: article.url) } case .addToBookmarks: - assertionFailure("Not implemented") - return .run { _ in await hapticClient.play(.rigid) } + return .run { _ in + let status = try await apiClient.addBookmark(0, article.title, .url(url: article.url)) + await toastClient.showToast(status ? .addedToBookmarks : .whoopsSomethingWentWrong) + if status { notificationCenter.post(name: .bookmarksUpdated, object: nil) } + } catch: { error, _ in + analyticsClient.capture(error) + await toastClient.showToast(.whoopsSomethingWentWrong) + } } return .none } diff --git a/Modules/Sources/ArticlesListFeature/ArticlesListScreen.swift b/Modules/Sources/ArticlesListFeature/ArticlesListScreen.swift index a6826bd5..1107a220 100644 --- a/Modules/Sources/ArticlesListFeature/ArticlesListScreen.swift +++ b/Modules/Sources/ArticlesListFeature/ArticlesListScreen.swift @@ -101,12 +101,14 @@ public struct ArticlesListScreen: View { date: article.date ), rowType: settingsToRow(store.listRowType), - bundle: .module + bundle: .module, + isBookmarkSupported: store.isAuthorized ) { action in switch action { - case .shareLink: store.send(.cellMenuOpened(article, .shareLink)) - case .copyLink: store.send(.cellMenuOpened(article, .copyLink)) - case .openInBrowser: store.send(.cellMenuOpened(article, .openInBrowser)) + case .shareLink: store.send(.cellMenuOpened(article, .shareLink)) + case .copyLink: store.send(.cellMenuOpened(article, .copyLink)) + case .openInBrowser: store.send(.cellMenuOpened(article, .openInBrowser)) + case .addToBookmarks: store.send(.cellMenuOpened(article, .addToBookmarks)) } } } diff --git a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift index 1729538b..771b11c0 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift @@ -9,38 +9,187 @@ import Foundation import ComposableArchitecture import TCAExtensions import APIClient +import AnalyticsClient import PasteboardClient +import ToastClient import Models import PersistenceKeys @Reducer public struct BookmarksFeature: Reducer, Sendable { - + public init() {} - + + // MARK: - Localizations + + public enum Localization { + static let linkCopied = LocalizedStringResource("Link copied", bundle: .module) + static let bookmarkDeleted = LocalizedStringResource("Bookmark deleted", bundle: .module) + } + + // MARK: - Context Menu + + public enum ContextMenuAction: Equatable, Sendable { + case copyLink + case delete + } + // MARK: - State - + @ObservableState public struct State: Equatable { - public init() {} + @Shared(.userSession) var userSession: UserSession? + + /// Id of the folder that is being displayed, `0` is the root level + public let folderId: Int + public let folderName: String? + + public var bookmarks: [Bookmark] = [] + public var isLoading = true + public var isRefreshing = false + + public var isUserAuthorized: Bool { + return userSession != nil + } + + public var shouldShowEmptyState: Bool { + return !isLoading && bookmarks.isEmpty + } + + public init( + folderId: Int = 0, + folderName: String? = nil, + bookmarks: [Bookmark] = [] + ) { + self.folderId = folderId + self.folderName = folderName + self.bookmarks = bookmarks + } } - + // MARK: - Action - - public enum Action { - case onAppear + + public enum Action: ViewAction { + case view(View) + public enum View { + case onFirstAppear + case onRefresh + case bookmarkTapped(Bookmark) + case contextMenu(ContextMenuAction, Bookmark) + } + + case `internal`(Internal) + public enum Internal { + case loadBookmarks + case bookmarksResponse(Result<[Bookmark], any Error>) + } + + case delegate(Delegate) + public enum Delegate { + case openFolder(id: Int, name: String) + case openURL(URL) + } } - + // MARK: - Dependencies - + @Dependency(\.apiClient) private var apiClient - + @Dependency(\.analyticsClient) private var analyticsClient + @Dependency(\.pasteboardClient) private var pasteboardClient + @Dependency(\.toastClient) private var toastClient + @Dependency(\.notificationCenter) private var notificationCenter + // MARK: - Body - + public var body: some Reducer { Reduce { state, action in switch action { - case .onAppear: + case .view(.onFirstAppear): + guard state.isUserAuthorized else { + state.isLoading = false + analyticsClient.reportFullyDisplayed() + return .none + } + return .merge( + .send(.internal(.loadBookmarks)), + .run { send in + for await _ in notificationCenter.notifications(named: .bookmarksUpdated) { + await send(.internal(.loadBookmarks)) + } + } + ) + + case .view(.onRefresh): + guard state.isUserAuthorized, !state.isLoading else { return .none } + state.isRefreshing = true + return .send(.internal(.loadBookmarks)) + + case let .view(.bookmarkTapped(bookmark)): + switch bookmark.format { + case .folder: + return .send(.delegate(.openFolder(id: bookmark.id, name: bookmark.name))) + case .url: + guard let url = bookmark.absoluteURL else { + return .run { _ in await toastClient.showToast(.whoopsSomethingWentWrong) } + } + return .send(.delegate(.openURL(url))) + } + + case let .view(.contextMenu(action, bookmark)): + switch action { + case .copyLink: + guard let url = bookmark.absoluteURL else { return .none } + pasteboardClient.copy(url.absoluteString) + return .run { _ in + await toastClient.showToast(ToastMessage(text: Localization.linkCopied, haptic: .success)) + } + + case .delete: + // Optimistically hide the bookmark (and folder contents) right away + state.bookmarks.removeAll { $0.id == bookmark.id } + return .run { _ in + let status = try await apiClient.deleteBookmark(bookmark) + let success = ToastMessage(text: Localization.bookmarkDeleted, haptic: .success) + await toastClient.showToast(status ? success : .whoopsSomethingWentWrong) + notificationCenter.post(name: .bookmarksUpdated, object: nil) + } catch: { _, send in + await toastClient.showToast(.whoopsSomethingWentWrong) + await send(.internal(.loadBookmarks)) + } + } + + case .internal(.loadBookmarks): + if !state.isRefreshing && state.bookmarks.isEmpty { + state.isLoading = true + } + return .run { send in + let result = await Result { try await apiClient.getBookmarksList() } + await send(.internal(.bookmarksResponse(result))) + } + + case let .internal(.bookmarksResponse(.success(bookmarks))): + state.bookmarks = bookmarks + .filter { !$0.deleted && $0.parentId == state.folderId } + .sorted { lhs, rhs in + // Folders first, then by user-defined order on the site + if lhs.isFolder != rhs.isFolder { return lhs.isFolder } + return lhs.number < rhs.number + } + state.isLoading = false + state.isRefreshing = false + analyticsClient.reportFullyDisplayed() + return .none + + case let .internal(.bookmarksResponse(.failure(error))): + state.isLoading = false + state.isRefreshing = false + analyticsClient.capture(error) + analyticsClient.reportFullyDisplayed() + return .run { _ in + await toastClient.showToast(.whoopsSomethingWentWrong) + } + + case .delegate: return .none } } diff --git a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift index db2a04b9..c60a1f0d 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift @@ -11,86 +11,173 @@ import SFSafeSymbols import SharedUI import Models +@ViewAction(for: BookmarksFeature.self) public struct BookmarksScreen: View { - + + // MARK: - Properties + @Perception.Bindable public var store: StoreOf @Environment(\.tintColor) private var tintColor @Environment(\.backgroundColors) private var backgroundColors - + + // MARK: - Init + public init(store: StoreOf) { self.store = store } - + + // MARK: - Body + public var body: some View { WithPerceptionTracking { ZStack { backgroundColors.primary .ignoresSafeArea() - - VStack(spacing: 0) { - ComingSoonTape() - .rotationEffect(Angle(degrees: 12)) - .padding(.bottom, 100) - - EmptyBookmarks() - - ComingSoonTape() - .rotationEffect(Angle(degrees: -20)) - .padding(.top, 80) + + if !store.isUserAuthorized { + EmptyState( + title: LocalizedStringResource("Log in to see bookmarks", bundle: .module), + subtitle: LocalizedStringResource("Bookmarks are synced with your 4PDA account", bundle: .module) + ) + } else if store.shouldShowEmptyState { + EmptyState( + title: LocalizedStringResource("No bookmarks", bundle: .module), + subtitle: LocalizedStringResource("Tap “Add To Bookmarks” in topic, forum or article menu, to save it here", bundle: .module) + ) + } else if !store.isLoading { + List { + Section { + ForEach(store.bookmarks, id: \.id) { bookmark in + BookmarkRow(bookmark) + } + } + .listRowBackground(backgroundColors.tertiary) + } + .scrollContentBackground(.hidden) + .refreshable { + await send(.onRefresh).finish() + } + } else { + PDALoader() + .frame(width: 24, height: 24) + } + } + .animation(.default, value: store.bookmarks) + .navigationTitle(navigationTitle) + ._toolbarTitleDisplayMode(store.folderName == nil ? .large : .inline) + .onFirstAppear { + send(.onFirstAppear) + } + } + } + + private var navigationTitle: Text { + if let folderName = store.folderName { + return Text(folderName) + } + return Text("Bookmarks", bundle: .module) + } + + // MARK: - Bookmark Row + + @ViewBuilder + private func BookmarkRow(_ bookmark: Bookmark) -> some View { + Button { + send(.bookmarkTapped(bookmark)) + } label: { + HStack(spacing: 12) { + Image(systemSymbol: bookmark.isFolder ? .folder : bookmark.symbol) + .font(.body) + .foregroundStyle(tintColor) + .frame(width: 24) + + VStack(alignment: .leading, spacing: 2) { + Text(bookmark.name) + .font(.body) + .foregroundStyle(Color(.Labels.primary)) + .lineLimit(2) + + if !bookmark.isFolder, let url = bookmark.absoluteURL { + Text(url.absoluteString) + .font(.caption) + .foregroundStyle(Color(.Labels.teritary)) + .lineLimit(1) + } } - .frame(width: UIScreen.main.bounds.width) + + Spacer(minLength: 0) + + if bookmark.isFolder { + Image(systemSymbol: .chevronRight) + .font(.footnote.weight(.semibold)) + .foregroundStyle(Color(.Labels.quintuple)) + } + } + .padding(.vertical, 10) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .contextMenu { + if !bookmark.isFolder { + ContextButton(text: LocalizedStringResource("Copy Link", bundle: .module), symbol: .docOnDoc) { + send(.contextMenu(.copyLink, bookmark)) + } + } + + ContextButton(text: LocalizedStringResource("Delete", bundle: .module), symbol: .trash, role: .destructive) { + send(.contextMenu(.delete, bookmark)) } - .navigationTitle(Text("Bookmarks", bundle: .module)) - ._toolbarTitleDisplayMode(.large) - .toolbarBackground(backgroundColors.primary, for: .navigationBar) - .onAppear { - store.send(.onAppear) + } + .swipeActions(edge: .trailing, allowsFullSwipe: true) { + Button(role: .destructive) { + send(.contextMenu(.delete, bookmark)) + } label: { + Label { + Text("Delete", bundle: .module) + } icon: { + Image(systemSymbol: .trash) + } } } } - - // MARK: - Empty Screen - + + // MARK: - Empty State + @ViewBuilder - private func EmptyBookmarks() -> some View { + private func EmptyState(title: LocalizedStringResource, subtitle: LocalizedStringResource) -> some View { VStack(spacing: 0) { Image(systemSymbol: .bookmark) .font(.title) .foregroundStyle(tintColor) .frame(width: 48, height: 48) .padding(.bottom, 8) - -// Text("No bookmarks", bundle: .module) - Text("Bookmarks will appear soon", bundle: .module) + + Text(title) .font(.title3) .bold() .foregroundColor(Color(.Labels.primary)) .padding(.bottom, 6) - -// Text("Tap “Add To Bookmarks” in article menu, to save it here", bundle: .module) - Text("They're currently in development, stay tuned for updates", bundle: .module) + + Text(subtitle) .font(.footnote) .multilineTextAlignment(.center) .foregroundStyle(Color(.Labels.teritary)) .padding(.horizontal, 55) } } - - // MARK: Coming Soon Tape - - @ViewBuilder - private func ComingSoonTape() -> some View { - HStack(spacing: 8) { - ForEach(0..<6, id: \.self) { index in - Text("COMING SOON") - .font(.footnote) - .foregroundStyle(Color(.Labels.primaryInvariably)) - .fixedSize(horizontal: true, vertical: false) - .lineLimit(1) - } - } - .frame(width: UIScreen.main.bounds.width * 2, height: 26) - .background(tintColor) +} + +// MARK: - Helpers + +private extension Bookmark { + var symbol: SFSymbol { + guard let url = absoluteURL?.absoluteString else { return .link } + if url.contains("showtopic=") { return .textBubble } + if url.contains("showforum=") || url.contains("act=idx") { return .bubbleLeftAndBubbleRight } + if url.contains("showuser=") { return .person } + if url.contains("act=qms") { return .person2 } + if url.contains("devdb") { return .iphone } + return .docText } } @@ -103,6 +190,8 @@ public struct BookmarksScreen: View { initialState: BookmarksFeature.State() ) { BookmarksFeature() + } withDependencies: { + $0.apiClient = .previewValue } ) } diff --git a/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings b/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings index 640081ee..62e40b7a 100644 --- a/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings @@ -1,6 +1,16 @@ { "sourceLanguage" : "en", "strings" : { + "Bookmark deleted" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закладка удалена" + } + } + } + }, "Bookmarks" : { "localizations" : { "ru" : { @@ -11,51 +21,76 @@ } } }, - "Bookmarks will appear soon" : { + "Bookmarks are synced with your 4PDA account" : { "localizations" : { "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Скоро появятся закладки" + "value" : "Закладки синхронизируются с вашим аккаунтом 4PDA" } } } }, - "COMING SOON" : { - + "Copy Link" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Скопировать ссылку" + } + } + } }, - "No bookmarks" : { - "extractionState" : "stale", + "Delete" : { "localizations" : { "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Нет закладок" + "value" : "Удалить" } } } }, - "Tap “Add To Bookmarks” in article menu, to save it here" : { - "extractionState" : "stale", + "Link copied" : { "localizations" : { "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Нажмите в меню статьи пункт “Добавить в закладки”, чтобы сохранить ее сюда" + "value" : "Ссылка скопирована" + } + } + } + }, + "Log in to see bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Войдите, чтобы увидеть закладки" + } + } + } + }, + "No bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нет закладок" } } } }, - "They're currently in development, stay tuned for updates" : { + "Tap “Add To Bookmarks” in topic, forum or article menu, to save it here" : { "localizations" : { "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Пока они находятся в разработке, следите за обновлениями" + "value" : "Нажмите «В закладки» в меню темы, форума или статьи, чтобы сохранить ее сюда" } } } } }, "version" : "1.0" -} \ No newline at end of file +} diff --git a/Modules/Sources/ForumFeature/Analytics/ForumFeature+Analytics.swift b/Modules/Sources/ForumFeature/Analytics/ForumFeature+Analytics.swift index 652c016c..14891cf4 100644 --- a/Modules/Sources/ForumFeature/Analytics/ForumFeature+Analytics.swift +++ b/Modules/Sources/ForumFeature/Analytics/ForumFeature+Analytics.swift @@ -65,7 +65,7 @@ extension ForumFeature { case .sort: break // TODO: Add case .toBookmarks: - break // TODO: Add + analytics.log(ForumEvent.menuAddToBookmarks(state.forumId)) case .createTopic: break // TODO: Add case .tickets: diff --git a/Modules/Sources/ForumFeature/ForumFeature.swift b/Modules/Sources/ForumFeature/ForumFeature.swift index 387954c1..de14e25f 100644 --- a/Modules/Sources/ForumFeature/ForumFeature.swift +++ b/Modules/Sources/ForumFeature/ForumFeature.swift @@ -309,7 +309,19 @@ public struct ForumFeature: Reducer, Sendable { case .tickets: return .send(.delegate(.openTickets(forumId: state.forumId))) - // TODO: sort, to bookmarks + case .toBookmarks: + let name = state.forum?.name ?? state.forumName ?? "" + return .run { [id = state.forumId, name] _ in + let url = URL(string: "https://4pda.to/forum/index.php?showforum=\(id)")! + let status = try await apiClient.addBookmark(0, name, .url(url: url)) + await toastClient.showToast(status ? .addedToBookmarks : .whoopsSomethingWentWrong) + if status { notificationCenter.post(name: .bookmarksUpdated, object: nil) } + } catch: { error, _ in + analyticsClient.capture(error) + await toastClient.showToast(.whoopsSomethingWentWrong) + } + + // TODO: sort // TODO: Add analytics default: return .none } diff --git a/Modules/Sources/ForumFeature/ForumScreen.swift b/Modules/Sources/ForumFeature/ForumScreen.swift index 99cf5317..ba44d206 100644 --- a/Modules/Sources/ForumFeature/ForumScreen.swift +++ b/Modules/Sources/ForumFeature/ForumScreen.swift @@ -130,6 +130,14 @@ public struct ForumScreen: View { isForum: true ) + if store.isUserAuthorized { + Section { + ContextButton(text: LocalizedStringResource("Add to bookmarks", bundle: .module), symbol: .bookmark) { + send(.contextOptionMenu(.toBookmarks)) + } + } + } + if forum.canModerate { Section { ContextButton(text: LocalizedStringResource("Forum Tickets", bundle: .module), symbol: .exclamationmarkBubble) { diff --git a/Modules/Sources/ForumFeature/Resources/Localizable.xcstrings b/Modules/Sources/ForumFeature/Resources/Localizable.xcstrings index fac17ab2..c3da18a4 100644 --- a/Modules/Sources/ForumFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/ForumFeature/Resources/Localizable.xcstrings @@ -11,6 +11,16 @@ } } }, + "Add to bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить в закладки" + } + } + } + }, "Add to favorites" : { "localizations" : { "ru" : { diff --git a/Modules/Sources/Models/App/AppTab.swift b/Modules/Sources/Models/App/AppTab.swift index e5453bdf..70f94062 100644 --- a/Modules/Sources/Models/App/AppTab.swift +++ b/Modules/Sources/Models/App/AppTab.swift @@ -12,7 +12,9 @@ public enum AppTab: Int, CaseIterable, Sendable, Codable { case articles = 0 case favorites case forum - case more + // Explicit raw values keep `AppSettings.startPage` stored values valid + case bookmarks = 4 + case more = 3 public var iconSymbol: SFSymbol { switch self { @@ -22,6 +24,8 @@ public enum AppTab: Int, CaseIterable, Sendable, Codable { return .starBubble case .forum: return .bubbleLeftAndBubbleRight + case .bookmarks: + return .bookmark case .more: return .squareGrid2x2Fill } @@ -35,6 +39,8 @@ public enum AppTab: Int, CaseIterable, Sendable, Codable { return LocalizedStringResource("Favorites", bundle: .module) case .forum: return LocalizedStringResource("Forum", bundle: .module) + case .bookmarks: + return LocalizedStringResource("Bookmarks", bundle: .module) case .more: return LocalizedStringResource("More", bundle: .module) } diff --git a/Modules/Sources/Models/Bookmarks/Bookmark.swift b/Modules/Sources/Models/Bookmarks/Bookmark.swift index 7fcf5e1c..a4d7e60d 100644 --- a/Modules/Sources/Models/Bookmarks/Bookmark.swift +++ b/Modules/Sources/Models/Bookmarks/Bookmark.swift @@ -147,3 +147,24 @@ public extension Bookmark { deleted: false ) } + +// MARK: - Helpers + +public extension Bookmark { + + static let baseURL = URL(string: "https://4pda.to/")! + + var isFolder: Bool { + if case .folder = format { return true } + return false + } + + /// Site stores full links, but relative ones (e.g. `forum/index.php?showtopic=1`) + /// are resolved against 4pda.to just in case. + var absoluteURL: URL? { + guard case let .url(url) = format else { return nil } + if url.scheme != nil { return url } + let path = url.absoluteString.hasPrefix("/") ? String(url.absoluteString.dropFirst()) : url.absoluteString + return URL(string: path, relativeTo: Bookmark.baseURL)?.absoluteURL + } +} diff --git a/Modules/Sources/Models/Notifications/Notifications.swift b/Modules/Sources/Models/Notifications/Notifications.swift index db730734..36d7dc77 100644 --- a/Modules/Sources/Models/Notifications/Notifications.swift +++ b/Modules/Sources/Models/Notifications/Notifications.swift @@ -9,5 +9,6 @@ import Foundation public extension Notification.Name { static let favoritesUpdated = Notification.Name("favoritesUpdated") + static let bookmarksUpdated = Notification.Name("bookmarksUpdated") static let sceneBecomeActive = Notification.Name("sceneBecomeActive") } diff --git a/Modules/Sources/Models/Resources/Localizable.xcstrings b/Modules/Sources/Models/Resources/Localizable.xcstrings index 26394260..e496b900 100644 --- a/Modules/Sources/Models/Resources/Localizable.xcstrings +++ b/Modules/Sources/Models/Resources/Localizable.xcstrings @@ -11,6 +11,16 @@ } } }, + "Bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закладки" + } + } + } + }, "Comment has been added" : { "localizations" : { "ru" : { diff --git a/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift b/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift index 416e8822..d9e9f890 100644 --- a/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift +++ b/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift @@ -10,32 +10,61 @@ import Models public struct BookmarksParser { public static func parse(from string: String) throws -> [Bookmark] { - if let data = string.data(using: .utf8) { - do { - guard let array = try JSONSerialization.jsonObject(with: data, options: []) as? [Any] else { throw ParsingError.failedToCastDataToAny } - - return (array[4] as! [[Any]]).map { bookmark in - return Bookmark( - id: bookmark[0] as! Int, - parentId: bookmark[4] as! Int, - name: bookmark[6] as! String, - number: bookmark[5] as! Int, - format: bookmarkFormat(bookmark), - updatedAt: Date(timeIntervalSince1970: bookmark[1] as! TimeInterval), - deleted: (bookmark[2] as! Int) == 0 ? false : true - ) - } - } catch { - throw ParsingError.failedToSerializeData(error) - } - } else { + guard let data = string.data(using: .utf8) else { throw ParsingError.failedToCreateDataFromString } + + let json: Any + do { + json = try JSONSerialization.jsonObject(with: data, options: []) + } catch { + throw ParsingError.failedToSerializeData(error) + } + + guard let array = json as? [Any], array.count > 4 else { + throw ParsingError.failedToCastDataToAny + } + + // Empty bookmarks list may come as an empty array or be absent + guard let rawBookmarks = array[4] as? [[Any]] else { return [] } + + // Skipping malformed entries instead of failing the whole list + return rawBookmarks.compactMap(parseBookmark) } - - private static func bookmarkFormat(_ array: [Any]) -> Bookmark.Format { - return if (array[3] as! Int) == 1 { .folder } else { - .url(url: URL(string: array[7] as! String)!) + + // Bookmark layout: [id, updatedAt, isDeleted, type, parentId, number, name, url] + private static func parseBookmark(_ bookmark: [Any]) -> Bookmark? { + guard bookmark.count > 6, + let id = bookmark[0] as? Int, + let updatedAt = bookmark[1] as? TimeInterval, + let deleted = bookmark[2] as? Int, + let type = bookmark[3] as? Int, + let parentId = bookmark[4] as? Int, + let number = bookmark[5] as? Int, + let name = bookmark[6] as? String else { + return nil } + + let format: Bookmark.Format + if type == 1 { + format = .folder + } else { + guard bookmark.count > 7, + let link = bookmark[7] as? String, + let url = URL(string: link) ?? link.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed).flatMap(URL.init(string:)) else { + return nil + } + format = .url(url: url) + } + + return Bookmark( + id: id, + parentId: parentId, + name: name.convertCodes(), + number: number, + format: format, + updatedAt: Date(timeIntervalSince1970: updatedAt), + deleted: deleted != 0 + ) } } diff --git a/Modules/Sources/SharedUI/Articles/ArticleRowView.swift b/Modules/Sources/SharedUI/Articles/ArticleRowView.swift index bd4ba74c..d7e93a18 100644 --- a/Modules/Sources/SharedUI/Articles/ArticleRowView.swift +++ b/Modules/Sources/SharedUI/Articles/ArticleRowView.swift @@ -14,7 +14,7 @@ public struct ArticleRowView: View { // MARK: - Enums public enum ContextAction { - case shareLink, copyLink, openInBrowser + case shareLink, copyLink, openInBrowser, addToBookmarks } // MARK: - Properties @@ -30,6 +30,7 @@ public struct ArticleRowView: View { public let rowType: RowType public let bundle: Bundle public let isContextMenuSupported: Bool // used for search + public let isBookmarkSupported: Bool public let action: (ContextAction) -> Void private var isShort: Bool { @@ -47,12 +48,14 @@ public struct ArticleRowView: View { rowType: RowType, bundle: Bundle, isContextMenuSupported: Bool = true, + isBookmarkSupported: Bool = false, action: @escaping (ContextAction) -> Void ) { self.state = state self.rowType = rowType self.bundle = bundle self.isContextMenuSupported = isContextMenuSupported + self.isBookmarkSupported = isBookmarkSupported self.action = action } @@ -270,6 +273,14 @@ public struct ArticleRowView: View { action(.openInBrowser) } } + + if isBookmarkSupported { + Section { + ContextButton(text: LocalizedStringResource("Add to bookmarks", bundle: .module), symbol: .bookmark) { + action(.addToBookmarks) + } + } + } } } } diff --git a/Modules/Sources/SharedUI/Resources/Localizable.xcstrings b/Modules/Sources/SharedUI/Resources/Localizable.xcstrings index 5baee0a3..08a331de 100644 --- a/Modules/Sources/SharedUI/Resources/Localizable.xcstrings +++ b/Modules/Sources/SharedUI/Resources/Localizable.xcstrings @@ -1,6 +1,16 @@ { "sourceLanguage" : "en", "strings" : { + "Add to bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить в закладки" + } + } + } + }, "Code" : { "localizations" : { "ru" : { diff --git a/Modules/Sources/ToastClient/Models/ToastMessage.swift b/Modules/Sources/ToastClient/Models/ToastMessage.swift index 59d592a9..f08f0739 100644 --- a/Modules/Sources/ToastClient/Models/ToastMessage.swift +++ b/Modules/Sources/ToastClient/Models/ToastMessage.swift @@ -50,6 +50,14 @@ public extension ToastMessage { priority: .low ) + static let addedToBookmarks = ToastMessage( + text: LocalizedStringResource("Added to bookmarks", bundle: .module), + isError: false, + haptic: .success, + duration: 3, + priority: .low + ) + static let whoopsSomethingWentWrong = ToastMessage( text: LocalizedStringResource("Whoops, something went wrong..", bundle: .module), isError: true, diff --git a/Modules/Sources/ToastClient/Resources/Localizable.xcstrings b/Modules/Sources/ToastClient/Resources/Localizable.xcstrings index 592cff6a..f5ca9719 100644 --- a/Modules/Sources/ToastClient/Resources/Localizable.xcstrings +++ b/Modules/Sources/ToastClient/Resources/Localizable.xcstrings @@ -11,6 +11,16 @@ } } }, + "Added to bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавлено в закладки" + } + } + } + }, "Whoops, something went wrong.." : { "localizations" : { "ru" : { diff --git a/Modules/Sources/TopicFeature/Analytics/TopicFeature+Analytics.swift b/Modules/Sources/TopicFeature/Analytics/TopicFeature+Analytics.swift index 7c2972bb..650519ec 100644 --- a/Modules/Sources/TopicFeature/Analytics/TopicFeature+Analytics.swift +++ b/Modules/Sources/TopicFeature/Analytics/TopicFeature+Analytics.swift @@ -101,6 +101,8 @@ extension TopicFeature { analytics.log(TopicEvent.menuGoToEnd) case .setFavorite: analytics.log(TopicEvent.menuSetFavorite) + case .addToBookmarks: + analytics.log(TopicEvent.menuAddToBookmarks) case .about: analytics.log(TopicEvent.menuAboutTopic) case .edit: diff --git a/Modules/Sources/TopicFeature/Models/TopicContextMenuAction.swift b/Modules/Sources/TopicFeature/Models/TopicContextMenuAction.swift index 64d9b5e8..c3b6ead8 100644 --- a/Modules/Sources/TopicFeature/Models/TopicContextMenuAction.swift +++ b/Modules/Sources/TopicFeature/Models/TopicContextMenuAction.swift @@ -12,6 +12,7 @@ public enum TopicContextMenuAction { case openInBrowser case goToEnd case setFavorite + case addToBookmarks case about case edit } diff --git a/Modules/Sources/TopicFeature/Resources/Localizable.xcstrings b/Modules/Sources/TopicFeature/Resources/Localizable.xcstrings index def89a8e..8a92c246 100644 --- a/Modules/Sources/TopicFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/TopicFeature/Resources/Localizable.xcstrings @@ -21,6 +21,16 @@ } } }, + "Add to bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить в закладки" + } + } + } + }, "Add to favorites" : { "localizations" : { "ru" : { diff --git a/Modules/Sources/TopicFeature/TopicFeature.swift b/Modules/Sources/TopicFeature/TopicFeature.swift index 80ebe304..9758652d 100644 --- a/Modules/Sources/TopicFeature/TopicFeature.swift +++ b/Modules/Sources/TopicFeature/TopicFeature.swift @@ -459,6 +459,17 @@ public struct TopicFeature: Reducer, Sendable { await toastClient.showToast(ToastMessage(text: Localization.linkCopied, haptic: .success)) } + case .addToBookmarks: + return .run { [id = state.topicId, name = topic.name] _ in + let url = URL(string: "https://4pda.to/forum/index.php?showtopic=\(id)")! + let status = try await apiClient.addBookmark(0, name, .url(url: url)) + await toastClient.showToast(status ? .addedToBookmarks : .whoopsSomethingWentWrong) + if status { notificationCenter.post(name: .bookmarksUpdated, object: nil) } + } catch: { error, _ in + analyticsClient.capture(error) + await toastClient.showToast(.whoopsSomethingWentWrong) + } + case .setFavorite: return .run { [id = state.topicId] send in let request = SetFavoriteRequest(id: id, action: topic.isFavorite ? .delete : .add, type: .topic) diff --git a/Modules/Sources/TopicFeature/TopicScreen.swift b/Modules/Sources/TopicFeature/TopicScreen.swift index 0284db7c..6db769ca 100644 --- a/Modules/Sources/TopicFeature/TopicScreen.swift +++ b/Modules/Sources/TopicFeature/TopicScreen.swift @@ -225,6 +225,10 @@ public struct TopicScreen: View { send(.contextMenu(.setFavorite)) } + ContextButton(text: LocalizedStringResource("Add to bookmarks", bundle: .module), symbol: .bookmark) { + send(.contextMenu(.addToBookmarks)) + } + ContextButton(text: LocalizedStringResource("About Topic", bundle: .module), symbol: .infoCircle) { send(.contextMenu(.about)) } diff --git a/Project.swift b/Project.swift index 785371eb..e8a2df20 100644 --- a/Project.swift +++ b/Project.swift @@ -179,12 +179,14 @@ let project = Project( .feature( name: "BookmarksFeature", dependencies: [ + .Internal.AnalyticsClient, .Internal.APIClient, .Internal.Models, .Internal.PasteboardClient, .Internal.PersistenceKeys, .Internal.SharedUI, .Internal.TCAExtensions, + .Internal.ToastClient, .SPM.NukeUI, .SPM.SFSafeSymbols, .SPM.SkeletonUI, From a5c662803555ba424172d19b4903b5c55314a3a6 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:34:36 +0100 Subject: [PATCH 2/5] Add folder creation, renaming and moving to bookmarks - New folder button on bookmarks screens (root and nested folders) - Rename and "Move To Folder" in bookmark context menu - APIClient.modifyBookmark over MemberCommand.Bookmarks.modify - Site default bookmarks (type 2, e.g. forum rules) are read-only Co-Authored-By: Claude Opus 5.5 --- Modules/Sources/APIClient/APIClient.swift | 15 ++ .../BookmarksFeature/BookmarksFeature.swift | 146 ++++++++++++++++- .../BookmarksFeature/BookmarksScreen.swift | 95 +++++++++-- .../Resources/Localizable.xcstrings | 150 ++++++++++++++++++ .../Sources/Models/Bookmarks/Bookmark.swift | 6 +- .../Parsers/BookmarksParser.swift | 4 +- 6 files changed, 404 insertions(+), 12 deletions(-) diff --git a/Modules/Sources/APIClient/APIClient.swift b/Modules/Sources/APIClient/APIClient.swift index b44a2a9c..2ebe15f4 100644 --- a/Modules/Sources/APIClient/APIClient.swift +++ b/Modules/Sources/APIClient/APIClient.swift @@ -62,6 +62,7 @@ public struct APIClient: Sendable { public var getBookmarksList: @Sendable () async throws -> [Bookmark] public var addBookmark: @Sendable (_ parentId: Int, _ name: String, _ format: Bookmark.Format) async throws -> Bool public var deleteBookmark: @Sendable (_ bookmark: Bookmark) async throws -> Bool + public var modifyBookmark: @Sendable (_ bookmark: Bookmark, _ parentId: Int, _ name: String) async throws -> Bool // Forum public var getForumsList: @Sendable (_ policy: CachePolicy) async throws -> AsyncThrowingStream<[ForumInfo], any Error> @@ -379,6 +380,17 @@ extension APIClient: DependencyKey { let response = try await api.send(MemberCommand.Bookmarks.modify(id: bookmark.id, data: request)) return Int(response.getResponseStatus()) == 0 }, + modifyBookmark: { bookmark, parentId, name in + let request = BookmarkRequest( + parentId: parentId, + name: name, + number: bookmark.number, + format: bookmark.format.asRequestFormat, + isDeleted: false + ) + let response = try await api.send(MemberCommand.Bookmarks.modify(id: bookmark.id, data: request)) + return Int(response.getResponseStatus()) == 0 + }, // MARK: - Forum @@ -849,6 +861,9 @@ extension APIClient: DependencyKey { deleteBookmark: { _ in return true }, + modifyBookmark: { _, _, _ in + return true + }, getForumsList: { _ in return .finished() }, diff --git a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift index 771b11c0..3ad53daf 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift @@ -25,12 +25,35 @@ public struct BookmarksFeature: Reducer, Sendable { public enum Localization { static let linkCopied = LocalizedStringResource("Link copied", bundle: .module) static let bookmarkDeleted = LocalizedStringResource("Bookmark deleted", bundle: .module) + static let folderCreated = LocalizedStringResource("Folder created", bundle: .module) + static let bookmarkRenamed = LocalizedStringResource("Bookmark renamed", bundle: .module) + static let folderRenamed = LocalizedStringResource("Folder renamed", bundle: .module) + static let bookmarkMoved = LocalizedStringResource("Bookmark moved", bundle: .module) + } + + // MARK: - Destinations + + @Reducer + public enum Destination { + case createFolder + @ReducerCaseIgnored + case rename(Bookmark) + @ReducerCaseIgnored + case move(Bookmark) + } + + /// Folder that bookmark can be moved to, `id == 0` is the root level + public struct MoveTarget: Equatable, Identifiable, Sendable { + public let id: Int + public let title: String } // MARK: - Context Menu public enum ContextMenuAction: Equatable, Sendable { case copyLink + case rename + case move case delete } @@ -39,12 +62,16 @@ public struct BookmarksFeature: Reducer, Sendable { @ObservableState public struct State: Equatable { @Shared(.userSession) var userSession: UserSession? + @Presents public var destination: Destination.State? /// Id of the folder that is being displayed, `0` is the root level public let folderId: Int public let folderName: String? public var bookmarks: [Bookmark] = [] + /// All folders of the account, used to pick where to move a bookmark + public var allFolders: [Bookmark] = [] + public var nameInput = "" public var isLoading = true public var isRefreshing = false @@ -56,6 +83,38 @@ public struct BookmarksFeature: Reducer, Sendable { return !isLoading && bookmarks.isEmpty } + /// Folders (with full path) the bookmark can be moved to + public func moveTargets(for bookmark: Bookmark) -> [MoveTarget] { + let foldersById = Dictionary(allFolders.map { ($0.id, $0) }, uniquingKeysWith: { lhs, _ in lhs }) + + func path(of folder: Bookmark) -> [Bookmark]? { + var result: [Bookmark] = [] + var current: Bookmark? = folder + var visited = Set() + while let node = current { + // Folder can't be moved into itself or its own subfolders + if node.id == bookmark.id { return nil } + guard visited.insert(node.id).inserted else { return nil } + result.insert(node, at: 0) + current = node.parentId == 0 ? nil : foldersById[node.parentId] + } + return result + } + + var targets: [MoveTarget] = [] + if bookmark.parentId != 0 { + targets.append(MoveTarget(id: 0, title: String(localized: "Bookmarks", bundle: .module))) + } + let folderTargets = allFolders + .filter { $0.id != bookmark.parentId } + .compactMap { folder -> MoveTarget? in + guard let path = path(of: folder) else { return nil } + return MoveTarget(id: folder.id, title: path.map(\.name).joined(separator: " / ")) + } + .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } + return targets + folderTargets + } + public init( folderId: Int = 0, folderName: String? = nil, @@ -69,19 +128,27 @@ public struct BookmarksFeature: Reducer, Sendable { // MARK: - Action - public enum Action: ViewAction { + public enum Action: ViewAction, BindableAction { + case binding(BindingAction) + case destination(PresentationAction) + case view(View) public enum View { case onFirstAppear case onRefresh case bookmarkTapped(Bookmark) case contextMenu(ContextMenuAction, Bookmark) + case createFolderButtonTapped + case createFolderConfirmed + case renameConfirmed(Bookmark) + case moveConfirmed(Bookmark, toFolderId: Int) } case `internal`(Internal) public enum Internal { case loadBookmarks case bookmarksResponse(Result<[Bookmark], any Error>) + case modifyResponse(Bool, success: LocalizedStringResource) } case delegate(Delegate) @@ -102,8 +169,64 @@ public struct BookmarksFeature: Reducer, Sendable { // MARK: - Body public var body: some Reducer { + BindingReducer() + Reduce { state, action in switch action { + case .binding, .destination: + return .none + + case .view(.createFolderButtonTapped): + state.nameInput = "" + state.destination = .createFolder + return .none + + case .view(.createFolderConfirmed): + let name = state.nameInput.trimmingCharacters(in: .whitespacesAndNewlines) + state.nameInput = "" + guard !name.isEmpty else { return .none } + return .run { [folderId = state.folderId] send in + let status = try await apiClient.addBookmark(folderId, name, .folder) + await send(.internal(.modifyResponse(status, success: Localization.folderCreated))) + } catch: { _, send in + await send(.internal(.modifyResponse(false, success: Localization.folderCreated))) + } + + case let .view(.renameConfirmed(bookmark)): + let name = state.nameInput.trimmingCharacters(in: .whitespacesAndNewlines) + state.nameInput = "" + guard !name.isEmpty, name != bookmark.name else { return .none } + if let index = state.bookmarks.firstIndex(where: { $0.id == bookmark.id }) { + state.bookmarks[index] = bookmark.with(parentId: bookmark.parentId, name: name) + } + let renamed = bookmark.isFolder ? Localization.folderRenamed : Localization.bookmarkRenamed + return .run { send in + let status = try await apiClient.modifyBookmark(bookmark, bookmark.parentId, name) + await send(.internal(.modifyResponse(status, success: renamed))) + } catch: { _, send in + await send(.internal(.modifyResponse(false, success: renamed))) + } + + case let .view(.moveConfirmed(bookmark, toFolderId)): + guard toFolderId != bookmark.parentId else { return .none } + state.bookmarks.removeAll { $0.id == bookmark.id } + return .run { send in + let status = try await apiClient.modifyBookmark(bookmark, toFolderId, bookmark.name) + await send(.internal(.modifyResponse(status, success: Localization.bookmarkMoved))) + } catch: { _, send in + await send(.internal(.modifyResponse(false, success: Localization.bookmarkMoved))) + } + + case let .internal(.modifyResponse(status, success)): + return .run { send in + await toastClient.showToast(status ? ToastMessage(text: success, haptic: .success) : .whoopsSomethingWentWrong) + if status { + notificationCenter.post(name: .bookmarksUpdated, object: nil) + } else { + await send(.internal(.loadBookmarks)) + } + } + case .view(.onFirstAppear): guard state.isUserAuthorized else { state.isLoading = false @@ -144,6 +267,15 @@ public struct BookmarksFeature: Reducer, Sendable { await toastClient.showToast(ToastMessage(text: Localization.linkCopied, haptic: .success)) } + case .rename: + state.nameInput = bookmark.name + state.destination = .rename(bookmark) + return .none + + case .move: + state.destination = .move(bookmark) + return .none + case .delete: // Optimistically hide the bookmark (and folder contents) right away state.bookmarks.removeAll { $0.id == bookmark.id } @@ -168,6 +300,7 @@ public struct BookmarksFeature: Reducer, Sendable { } case let .internal(.bookmarksResponse(.success(bookmarks))): + state.allFolders = bookmarks.filter { !$0.deleted && $0.isFolder } state.bookmarks = bookmarks .filter { !$0.deleted && $0.parentId == state.folderId } .sorted { lhs, rhs in @@ -193,5 +326,16 @@ public struct BookmarksFeature: Reducer, Sendable { return .none } } + .ifLet(\.$destination, action: \.destination) + } +} + +extension BookmarksFeature.Destination.State: Equatable {} + +// MARK: - Helpers + +private extension Bookmark { + func with(parentId: Int, name: String) -> Bookmark { + Bookmark(id: id, parentId: parentId, name: name, number: number, format: format, updatedAt: updatedAt, deleted: deleted, isSystem: isSystem) } } diff --git a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift index c60a1f0d..5adc7db0 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift @@ -65,6 +65,54 @@ public struct BookmarksScreen: View { .animation(.default, value: store.bookmarks) .navigationTitle(navigationTitle) ._toolbarTitleDisplayMode(store.folderName == nil ? .large : .inline) + .toolbar { + if store.isUserAuthorized { + ToolbarItem(placement: .topBarTrailing) { + Button { + send(.createFolderButtonTapped) + } label: { + Image(systemSymbol: .folderBadgePlus) + } + .accessibilityLabel(Text("New Folder", bundle: .module)) + } + } + } + .alert( + item: $store.destination.createFolder, + title: { _ in Text("New Folder", bundle: .module) } + ) { _ in + NameInput(confirmTitle: LocalizedStringResource("Create", bundle: .module)) { + send(.createFolderConfirmed) + } + } + .alert( + item: $store.destination.rename, + title: { bookmark in + bookmark.isFolder ? Text("Rename Folder", bundle: .module) : Text("Rename Bookmark", bundle: .module) + } + ) { bookmark in + NameInput(confirmTitle: LocalizedStringResource("Save", bundle: .module)) { + send(.renameConfirmed(bookmark)) + } + } + .confirmationDialog( + item: $store.destination.move, + titleVisibility: .visible, + title: { _ in Text("Move To", bundle: .module) } + ) { bookmark in + WithPerceptionTracking { + ForEach(store.state.moveTargets(for: bookmark)) { target in + Button(target.title) { + send(.moveConfirmed(bookmark, toFolderId: target.id)) + } + } + Button(LocalizedStringResource("Cancel", bundle: .module), role: .cancel) { } + } + } message: { bookmark in + if store.state.moveTargets(for: bookmark).isEmpty { + Text("Create a folder first", bundle: .module) + } + } .onFirstAppear { send(.onFirstAppear) } @@ -124,23 +172,52 @@ public struct BookmarksScreen: View { } } - ContextButton(text: LocalizedStringResource("Delete", bundle: .module), symbol: .trash, role: .destructive) { - send(.contextMenu(.delete, bookmark)) + if !bookmark.isSystem { + ContextButton(text: LocalizedStringResource("Rename", bundle: .module), symbol: .pencil) { + send(.contextMenu(.rename, bookmark)) + } + + ContextButton(text: LocalizedStringResource("Move To Folder", bundle: .module), symbol: .folder) { + send(.contextMenu(.move, bookmark)) + } + + ContextButton(text: LocalizedStringResource("Delete", bundle: .module), symbol: .trash, role: .destructive) { + send(.contextMenu(.delete, bookmark)) + } } } .swipeActions(edge: .trailing, allowsFullSwipe: true) { - Button(role: .destructive) { - send(.contextMenu(.delete, bookmark)) - } label: { - Label { - Text("Delete", bundle: .module) - } icon: { - Image(systemSymbol: .trash) + if !bookmark.isSystem { + Button(role: .destructive) { + send(.contextMenu(.delete, bookmark)) + } label: { + Label { + Text("Delete", bundle: .module) + } icon: { + Image(systemSymbol: .trash) + } } } } } + // MARK: - Name Input + + @ViewBuilder + private func NameInput(confirmTitle: LocalizedStringResource, _ action: @escaping () -> Void) -> some View { + WithPerceptionTracking { + TextField(String(localized: "Name", bundle: .module), text: $store.nameInput) + + Button(LocalizedStringResource("Cancel", bundle: .module), role: .cancel) { } + + // No `.disabled` here: alert doesn't re-evaluate it while typing, + // empty names are ignored by the reducer instead + Button(confirmTitle) { + action() + } + } + } + // MARK: - Empty State @ViewBuilder diff --git a/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings b/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings index 62e40b7a..699e27c3 100644 --- a/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings @@ -11,6 +11,26 @@ } } }, + "Bookmark moved" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закладка перемещена" + } + } + } + }, + "Bookmark renamed" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закладка переименована" + } + } + } + }, "Bookmarks" : { "localizations" : { "ru" : { @@ -31,6 +51,16 @@ } } }, + "Cancel" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отмена" + } + } + } + }, "Copy Link" : { "localizations" : { "ru" : { @@ -41,6 +71,26 @@ } } }, + "Create" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создать" + } + } + } + }, + "Create a folder first" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сначала создайте папку" + } + } + } + }, "Delete" : { "localizations" : { "ru" : { @@ -51,6 +101,26 @@ } } }, + "Folder created" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Папка создана" + } + } + } + }, + "Folder renamed" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Папка переименована" + } + } + } + }, "Link copied" : { "localizations" : { "ru" : { @@ -71,6 +141,46 @@ } } }, + "Move To" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переместить в" + } + } + } + }, + "Move To Folder" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переместить в папку" + } + } + } + }, + "Name" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Название" + } + } + } + }, + "New Folder" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Новая папка" + } + } + } + }, "No bookmarks" : { "localizations" : { "ru" : { @@ -81,6 +191,46 @@ } } }, + "Rename" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переименовать" + } + } + } + }, + "Rename Bookmark" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переименовать закладку" + } + } + } + }, + "Rename Folder" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переименовать папку" + } + } + } + }, + "Save" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сохранить" + } + } + } + }, "Tap “Add To Bookmarks” in topic, forum or article menu, to save it here" : { "localizations" : { "ru" : { diff --git a/Modules/Sources/Models/Bookmarks/Bookmark.swift b/Modules/Sources/Models/Bookmarks/Bookmark.swift index a4d7e60d..5b763a90 100644 --- a/Modules/Sources/Models/Bookmarks/Bookmark.swift +++ b/Modules/Sources/Models/Bookmarks/Bookmark.swift @@ -15,6 +15,8 @@ public struct Bookmark: Codable, Hashable, Sendable { public let format: Format public let updatedAt: Date public let deleted: Bool + /// Default bookmark added by the site itself (e.g. forum rules), can't be edited + public let isSystem: Bool public enum Format: Codable, Sendable, Hashable { case folder @@ -28,7 +30,8 @@ public struct Bookmark: Codable, Hashable, Sendable { number: Int, format: Format, updatedAt: Date, - deleted: Bool + deleted: Bool, + isSystem: Bool = false ) { self.id = id self.parentId = parentId @@ -37,6 +40,7 @@ public struct Bookmark: Codable, Hashable, Sendable { self.format = format self.updatedAt = updatedAt self.deleted = deleted + self.isSystem = isSystem } } diff --git a/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift b/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift index d9e9f890..1f3c7cd7 100644 --- a/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift +++ b/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift @@ -33,6 +33,7 @@ public struct BookmarksParser { } // Bookmark layout: [id, updatedAt, isDeleted, type, parentId, number, name, url] + // Type: 0 - link, 1 - folder, 2 - default link added by the site (not editable) private static func parseBookmark(_ bookmark: [Any]) -> Bookmark? { guard bookmark.count > 6, let id = bookmark[0] as? Int, @@ -64,7 +65,8 @@ public struct BookmarksParser { number: number, format: format, updatedAt: Date(timeIntervalSince1970: updatedAt), - deleted: deleted != 0 + deleted: deleted != 0, + isSystem: type == 2 ) } } From 7428b1b74f59ce5a391e45a63dd9d44af76c8a57 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:37:14 +0100 Subject: [PATCH 3/5] Make bookmark rows compact and match list design - Row height 60 with 8pt vertical padding, as other lists - Separator starts under the icon - Hide link URL, show only the bookmark name Co-Authored-By: Claude Opus 5.5 --- .../BookmarksFeature/BookmarksScreen.swift | 23 ++++++++----------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift index 5adc7db0..eb1d553c 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift @@ -139,19 +139,10 @@ public struct BookmarksScreen: View { .foregroundStyle(tintColor) .frame(width: 24) - VStack(alignment: .leading, spacing: 2) { - Text(bookmark.name) - .font(.body) - .foregroundStyle(Color(.Labels.primary)) - .lineLimit(2) - - if !bookmark.isFolder, let url = bookmark.absoluteURL { - Text(url.absoluteString) - .font(.caption) - .foregroundStyle(Color(.Labels.teritary)) - .lineLimit(1) - } - } + Text(bookmark.name) + .font(.body) + .foregroundStyle(Color(.Labels.primary)) + .lineLimit(2) Spacer(minLength: 0) @@ -161,10 +152,14 @@ public struct BookmarksScreen: View { .foregroundStyle(Color(.Labels.quintuple)) } } - .padding(.vertical, 10) + .padding(.vertical, 8) + .frame(minHeight: 60) .contentShape(Rectangle()) } .buttonStyle(.plain) + .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)) + // Separator goes under the icon too, as in other lists + .alignmentGuide(.listRowSeparatorLeading) { _ in 0 } .contextMenu { if !bookmark.isFolder { ContextButton(text: LocalizedStringResource("Copy Link", bundle: .module), symbol: .docOnDoc) { From 92373bc4de8326aa1a644cb9767935ca5d17c803 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:16:39 +0100 Subject: [PATCH 4/5] Bookmarks: third tab, reload on login, error state, previews - Bookmarks tab moved to third position (raw values kept for startPage) - Reload bookmarks on login and clear them on logout - Full screen error with retry when nothing is loaded, toast otherwise - Use shared GenericView for unauthorized/empty/error states - Bigger row icons - Previews for authorized, folder, unauthorized, empty, loading, error Co-Authored-By: Claude Opus 5.5 --- Modules/Sources/AppFeature/AppView.swift | 22 ++--- .../BookmarksFeature/BookmarksFeature.swift | 56 +++++++++-- .../BookmarksFeature/BookmarksScreen.swift | 96 ++++++++++++------- Modules/Sources/Models/App/AppTab.swift | 7 +- 4 files changed, 122 insertions(+), 59 deletions(-) diff --git a/Modules/Sources/AppFeature/AppView.swift b/Modules/Sources/AppFeature/AppView.swift index 74325f17..24b2f511 100644 --- a/Modules/Sources/AppFeature/AppView.swift +++ b/Modules/Sources/AppFeature/AppView.swift @@ -156,14 +156,6 @@ struct LiquidTabView: View { } .badge(store.favoritesBadges) - Tab( - AppTab.forum.title, - systemSymbol: AppTab.forum.iconSymbol, - value: .forum - ) { - StackTabView(store: store.scope(\.forumTab, action: \.forumTab)) - } - Tab( AppTab.bookmarks.title, systemSymbol: AppTab.bookmarks.iconSymbol, @@ -172,6 +164,14 @@ struct LiquidTabView: View { StackTabView(store: store.scope(\.bookmarksTab, action: \.bookmarksTab)) } + Tab( + AppTab.forum.title, + systemSymbol: AppTab.forum.iconSymbol, + value: .forum + ) { + StackTabView(store: store.scope(\.forumTab, action: \.forumTab)) + } + Tab( AppTab.more.title, systemSymbol: AppTab.more.iconSymbol, @@ -222,12 +222,12 @@ struct OldTabView: View { StackTabView(store: store.scope(\.favoritesTab, action: \.favoritesTab)) .tag(AppTab.favorites) - StackTabView(store: store.scope(\.forumTab, action: \.forumTab)) - .tag(AppTab.forum) - StackTabView(store: store.scope(\.bookmarksTab, action: \.bookmarksTab)) .tag(AppTab.bookmarks) + StackTabView(store: store.scope(\.forumTab, action: \.forumTab)) + .tag(AppTab.forum) + StackTabView(store: store.scope(\.moreTab, action: \.moreTab)) .tag(AppTab.more) } diff --git a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift index 3ad53daf..cf163086 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift @@ -74,13 +74,15 @@ public struct BookmarksFeature: Reducer, Sendable { public var nameInput = "" public var isLoading = true public var isRefreshing = false + /// Shown instead of the list when bookmarks failed to load and there is nothing to show + public var hasError = false public var isUserAuthorized: Bool { return userSession != nil } public var shouldShowEmptyState: Bool { - return !isLoading && bookmarks.isEmpty + return !isLoading && !hasError && bookmarks.isEmpty } /// Folders (with full path) the bookmark can be moved to @@ -118,11 +120,15 @@ public struct BookmarksFeature: Reducer, Sendable { public init( folderId: Int = 0, folderName: String? = nil, - bookmarks: [Bookmark] = [] + bookmarks: [Bookmark] = [], + isLoading: Bool = true, + hasError: Bool = false ) { self.folderId = folderId self.folderName = folderName self.bookmarks = bookmarks + self.isLoading = isLoading + self.hasError = hasError } } @@ -136,6 +142,7 @@ public struct BookmarksFeature: Reducer, Sendable { public enum View { case onFirstAppear case onRefresh + case retryButtonTapped case bookmarkTapped(Bookmark) case contextMenu(ContextMenuAction, Bookmark) case createFolderButtonTapped @@ -147,6 +154,7 @@ public struct BookmarksFeature: Reducer, Sendable { case `internal`(Internal) public enum Internal { case loadBookmarks + case userSessionChanged(isAuthorized: Bool) case bookmarksResponse(Result<[Bookmark], any Error>) case modifyResponse(Bool, success: LocalizedStringResource) } @@ -228,19 +236,42 @@ public struct BookmarksFeature: Reducer, Sendable { } case .view(.onFirstAppear): - guard state.isUserAuthorized else { - state.isLoading = false - analyticsClient.reportFullyDisplayed() - return .none - } - return .merge( - .send(.internal(.loadBookmarks)), + let sessionPublisher = state.$userSession.publisher + let observers: Effect = .merge( + // Reload after login and clear after logout + .publisher { + sessionPublisher + .dropFirst() + .map { $0 != nil } + .removeDuplicates() + .map { Action.internal(.userSessionChanged(isAuthorized: $0)) } + }, .run { send in for await _ in notificationCenter.notifications(named: .bookmarksUpdated) { await send(.internal(.loadBookmarks)) } } ) + guard state.isUserAuthorized else { + state.isLoading = false + analyticsClient.reportFullyDisplayed() + return observers + } + return .merge(.send(.internal(.loadBookmarks)), observers) + + case let .internal(.userSessionChanged(isAuthorized)): + state.hasError = false + state.bookmarks = [] + state.allFolders = [] + guard isAuthorized else { + state.isLoading = false + return .none + } + return .send(.internal(.loadBookmarks)) + + case .view(.retryButtonTapped): + state.hasError = false + return .send(.internal(.loadBookmarks)) case .view(.onRefresh): guard state.isUserAuthorized, !state.isLoading else { return .none } @@ -291,6 +322,7 @@ public struct BookmarksFeature: Reducer, Sendable { } case .internal(.loadBookmarks): + guard state.isUserAuthorized else { return .none } if !state.isRefreshing && state.bookmarks.isEmpty { state.isLoading = true } @@ -310,6 +342,7 @@ public struct BookmarksFeature: Reducer, Sendable { } state.isLoading = false state.isRefreshing = false + state.hasError = false analyticsClient.reportFullyDisplayed() return .none @@ -318,6 +351,11 @@ public struct BookmarksFeature: Reducer, Sendable { state.isRefreshing = false analyticsClient.capture(error) analyticsClient.reportFullyDisplayed() + // Nothing to show - full screen error with retry, otherwise keep stale list and show toast + guard !state.bookmarks.isEmpty else { + state.hasError = true + return .none + } return .run { _ in await toastClient.showToast(.whoopsSomethingWentWrong) } diff --git a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift index eb1d553c..7e07a39b 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift @@ -35,15 +35,24 @@ public struct BookmarksScreen: View { .ignoresSafeArea() if !store.isUserAuthorized { - EmptyState( + GenericView( + systemSymbol: .bookmark, title: LocalizedStringResource("Log in to see bookmarks", bundle: .module), - subtitle: LocalizedStringResource("Bookmarks are synced with your 4PDA account", bundle: .module) + description: LocalizedStringResource("Bookmarks are synced with your 4PDA account", bundle: .module) ) + .padding(.horizontal, 55) + } else if store.hasError { + GenericView.GenericError { + send(.retryButtonTapped) + } + .padding(.horizontal, 55) } else if store.shouldShowEmptyState { - EmptyState( + GenericView( + systemSymbol: .bookmark, title: LocalizedStringResource("No bookmarks", bundle: .module), - subtitle: LocalizedStringResource("Tap “Add To Bookmarks” in topic, forum or article menu, to save it here", bundle: .module) + description: LocalizedStringResource("Tap “Add To Bookmarks” in topic, forum or article menu, to save it here", bundle: .module) ) + .padding(.horizontal, 55) } else if !store.isLoading { List { Section { @@ -135,9 +144,9 @@ public struct BookmarksScreen: View { } label: { HStack(spacing: 12) { Image(systemSymbol: bookmark.isFolder ? .folder : bookmark.symbol) - .font(.body) + .font(.title2) .foregroundStyle(tintColor) - .frame(width: 24) + .frame(width: 32) Text(bookmark.name) .font(.body) @@ -212,31 +221,6 @@ public struct BookmarksScreen: View { } } } - - // MARK: - Empty State - - @ViewBuilder - private func EmptyState(title: LocalizedStringResource, subtitle: LocalizedStringResource) -> some View { - VStack(spacing: 0) { - Image(systemSymbol: .bookmark) - .font(.title) - .foregroundStyle(tintColor) - .frame(width: 48, height: 48) - .padding(.bottom, 8) - - Text(title) - .font(.title3) - .bold() - .foregroundColor(Color(.Labels.primary)) - .padding(.bottom, 6) - - Text(subtitle) - .font(.footnote) - .multilineTextAlignment(.center) - .foregroundStyle(Color(.Labels.teritary)) - .padding(.horizontal, 55) - } - } } // MARK: - Helpers @@ -255,16 +239,56 @@ private extension Bookmark { // MARK: - Previews -#Preview { - NavigationStack { +@MainActor +private func bookmarksPreview( + isAuthorized: Bool = true, + state: BookmarksFeature.State = BookmarksFeature.State(), + bookmarks: @escaping @Sendable () async throws -> [Bookmark] = { + [.mockFolder, .mockForum, .mockTopic, .mockTopicPost, .mockUser, .mockArticle] + } +) -> some View { + @Shared(.userSession) var userSession + $userSession.withLock { $0 = isAuthorized ? UserSession.mock : nil } + + return NavigationStack { BookmarksScreen( - store: Store( - initialState: BookmarksFeature.State() - ) { + store: Store(initialState: state) { BookmarksFeature() } withDependencies: { $0.apiClient = .previewValue + $0.apiClient.getBookmarksList = bookmarks } ) } + .environment(\.tintColor, Color(.Theme.primary)) +} + +#Preview("Authorized") { + bookmarksPreview() +} + +#Preview("Folder") { + bookmarksPreview( + state: BookmarksFeature.State(folderId: Bookmark.mockFolder.id, folderName: Bookmark.mockFolder.name), + bookmarks: { [.mockSubFolder] } + ) +} + +#Preview("Unauthorized") { + bookmarksPreview(isAuthorized: false) +} + +#Preview("Empty") { + bookmarksPreview(bookmarks: { [] }) +} + +#Preview("Loading") { + bookmarksPreview(bookmarks: { + try await Task.sleep(for: .seconds(1000)) + return [] + }) +} + +#Preview("Error") { + bookmarksPreview(bookmarks: { throw URLError(.notConnectedToInternet) }) } diff --git a/Modules/Sources/Models/App/AppTab.swift b/Modules/Sources/Models/App/AppTab.swift index 70f94062..a0d335be 100644 --- a/Modules/Sources/Models/App/AppTab.swift +++ b/Modules/Sources/Models/App/AppTab.swift @@ -9,11 +9,12 @@ import SwiftUI import SFSafeSymbols public enum AppTab: Int, CaseIterable, Sendable, Codable { + // Declaration order is the order of tabs in tab bar, + // explicit raw values keep `AppSettings.startPage` stored values valid case articles = 0 - case favorites - case forum - // Explicit raw values keep `AppSettings.startPage` stored values valid + case favorites = 1 case bookmarks = 4 + case forum = 2 case more = 3 public var iconSymbol: SFSymbol { From 0e21fc5427521dd3aee8eeffa73567aeb528522c Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:23:46 +0100 Subject: [PATCH 5/5] Refactor bookmarks feature - Single effect for bookmark modifications (toast, notify, reload on failure) - Drop optimistic rename, list reloads after success anyway - Simpler move targets path building - BookmarkRequest convenience init instead of three copies - Absolute URL resolving lives in Bookmark.Format only - Parser uses BookmarkType enum instead of magic numbers - Screen states extracted to Content() Co-Authored-By: Claude Opus 5.5 --- Modules/Sources/APIClient/APIClient.swift | 45 +-- .../BookmarksFeature/BookmarksFeature.swift | 342 ++++++++---------- .../BookmarksFeature/BookmarksScreen.swift | 127 ++++--- Modules/Sources/Models/App/AppTab.swift | 3 +- .../Sources/Models/Bookmarks/Bookmark.swift | 27 +- .../Parsers/BookmarksParser.swift | 32 +- 6 files changed, 282 insertions(+), 294 deletions(-) diff --git a/Modules/Sources/APIClient/APIClient.swift b/Modules/Sources/APIClient/APIClient.swift index 2ebe15f4..2a504596 100644 --- a/Modules/Sources/APIClient/APIClient.swift +++ b/Modules/Sources/APIClient/APIClient.swift @@ -359,35 +359,17 @@ extension APIClient: DependencyKey { return try await parser.parseBookmarksList(response) }, addBookmark: { parentId, name, format in - let request = BookmarkRequest( - parentId: parentId, - name: name, - number: 0, - format: format.asRequestFormat, - isDeleted: false - ) + let request = BookmarkRequest(parentId: parentId, name: name, number: 0, format: format.request, isDeleted: false) let response = try await api.send(MemberCommand.Bookmarks.add(data: request)) return Int(response.getResponseStatus()) == 0 }, deleteBookmark: { bookmark in - let request = BookmarkRequest( - parentId: bookmark.parentId, - name: bookmark.name, - number: bookmark.number, - format: bookmark.format.asRequestFormat, - isDeleted: true - ) + let request = BookmarkRequest(bookmark, isDeleted: true) let response = try await api.send(MemberCommand.Bookmarks.modify(id: bookmark.id, data: request)) return Int(response.getResponseStatus()) == 0 }, modifyBookmark: { bookmark, parentId, name in - let request = BookmarkRequest( - parentId: parentId, - name: name, - number: bookmark.number, - format: bookmark.format.asRequestFormat, - isDeleted: false - ) + let request = BookmarkRequest(bookmark, parentId: parentId, name: name) let response = try await api.send(MemberCommand.Bookmarks.modify(id: bookmark.id, data: request)) return Int(response.getResponseStatus()) == 0 }, @@ -1093,17 +1075,28 @@ extension String { } } -// MARK: - Bookmark Format Mapping +// MARK: - Bookmark Request + +private extension BookmarkRequest { + init(_ bookmark: Bookmark, parentId: Int? = nil, name: String? = nil, isDeleted: Bool = false) { + self.init( + parentId: parentId ?? bookmark.parentId, + name: name ?? bookmark.name, + number: bookmark.number, + format: bookmark.format.request, + isDeleted: isDeleted + ) + } +} private extension Bookmark.Format { - var asRequestFormat: BookmarkRequest.BookmarkFormat { + /// Site expects absolute links + var request: BookmarkRequest.BookmarkFormat { switch self { case .folder: return .folder case let .url(url): - // Site stores bookmarks with full links - let absolute = url.scheme == nil ? URL(string: url.absoluteString, relativeTo: Bookmark.baseURL)?.absoluteURL : url - return .url(url: (absolute ?? url).absoluteString) + return .url(url: (absoluteURL ?? url).absoluteString) } } } diff --git a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift index cf163086..391268b1 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift @@ -22,13 +22,14 @@ public struct BookmarksFeature: Reducer, Sendable { // MARK: - Localizations - public enum Localization { + enum Localization { static let linkCopied = LocalizedStringResource("Link copied", bundle: .module) static let bookmarkDeleted = LocalizedStringResource("Bookmark deleted", bundle: .module) - static let folderCreated = LocalizedStringResource("Folder created", bundle: .module) static let bookmarkRenamed = LocalizedStringResource("Bookmark renamed", bundle: .module) - static let folderRenamed = LocalizedStringResource("Folder renamed", bundle: .module) static let bookmarkMoved = LocalizedStringResource("Bookmark moved", bundle: .module) + static let folderCreated = LocalizedStringResource("Folder created", bundle: .module) + static let folderRenamed = LocalizedStringResource("Folder renamed", bundle: .module) + static let rootFolder = LocalizedStringResource("Bookmarks", bundle: .module) } // MARK: - Destinations @@ -42,14 +43,11 @@ public struct BookmarksFeature: Reducer, Sendable { case move(Bookmark) } - /// Folder that bookmark can be moved to, `id == 0` is the root level public struct MoveTarget: Equatable, Identifiable, Sendable { public let id: Int public let title: String } - // MARK: - Context Menu - public enum ContextMenuAction: Equatable, Sendable { case copyLink case rename @@ -64,59 +62,26 @@ public struct BookmarksFeature: Reducer, Sendable { @Shared(.userSession) var userSession: UserSession? @Presents public var destination: Destination.State? - /// Id of the folder that is being displayed, `0` is the root level + /// `0` stands for the root level public let folderId: Int public let folderName: String? public var bookmarks: [Bookmark] = [] - /// All folders of the account, used to pick where to move a bookmark - public var allFolders: [Bookmark] = [] + public var folders: [Bookmark] = [] public var nameInput = "" + public var isLoading = true public var isRefreshing = false - /// Shown instead of the list when bookmarks failed to load and there is nothing to show public var hasError = false public var isUserAuthorized: Bool { return userSession != nil } - public var shouldShowEmptyState: Bool { + public var isEmpty: Bool { return !isLoading && !hasError && bookmarks.isEmpty } - /// Folders (with full path) the bookmark can be moved to - public func moveTargets(for bookmark: Bookmark) -> [MoveTarget] { - let foldersById = Dictionary(allFolders.map { ($0.id, $0) }, uniquingKeysWith: { lhs, _ in lhs }) - - func path(of folder: Bookmark) -> [Bookmark]? { - var result: [Bookmark] = [] - var current: Bookmark? = folder - var visited = Set() - while let node = current { - // Folder can't be moved into itself or its own subfolders - if node.id == bookmark.id { return nil } - guard visited.insert(node.id).inserted else { return nil } - result.insert(node, at: 0) - current = node.parentId == 0 ? nil : foldersById[node.parentId] - } - return result - } - - var targets: [MoveTarget] = [] - if bookmark.parentId != 0 { - targets.append(MoveTarget(id: 0, title: String(localized: "Bookmarks", bundle: .module))) - } - let folderTargets = allFolders - .filter { $0.id != bookmark.parentId } - .compactMap { folder -> MoveTarget? in - guard let path = path(of: folder) else { return nil } - return MoveTarget(id: folder.id, title: path.map(\.name).joined(separator: " / ")) - } - .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } - return targets + folderTargets - } - public init( folderId: Int = 0, folderName: String? = nil, @@ -130,6 +95,39 @@ public struct BookmarksFeature: Reducer, Sendable { self.isLoading = isLoading self.hasError = hasError } + + /// Every folder except the current parent, the bookmark itself and its subfolders + public func moveTargets(for bookmark: Bookmark) -> [MoveTarget] { + let foldersById = Dictionary(folders.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + + func path(to folder: Bookmark) -> [String]? { + var names: [String] = [] + var node: Bookmark? = folder + while let current = node { + guard current.id != bookmark.id, names.count <= foldersById.count else { return nil } + names.append(current.name) + node = foldersById[current.parentId] + } + return names.reversed() + } + + let targets = folders + .filter { $0.id != bookmark.parentId } + .compactMap { folder in + path(to: folder).map { MoveTarget(id: folder.id, title: $0.joined(separator: " / ")) } + } + .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } + + guard bookmark.parentId != 0 else { return targets } + return [MoveTarget(id: 0, title: String(localized: Localization.rootFolder))] + targets + } + + /// Trimmed name from the input, `nil` if it's blank + mutating func takeNameInput() -> String? { + defer { nameInput = "" } + let name = nameInput.trimmingCharacters(in: .whitespacesAndNewlines) + return name.isEmpty ? nil : name + } } // MARK: - Action @@ -154,9 +152,8 @@ public struct BookmarksFeature: Reducer, Sendable { case `internal`(Internal) public enum Internal { case loadBookmarks - case userSessionChanged(isAuthorized: Bool) case bookmarksResponse(Result<[Bookmark], any Error>) - case modifyResponse(Bool, success: LocalizedStringResource) + case userSessionUpdated(isAuthorized: Bool) } case delegate(Delegate) @@ -181,77 +178,8 @@ public struct BookmarksFeature: Reducer, Sendable { Reduce { state, action in switch action { - case .binding, .destination: - return .none - - case .view(.createFolderButtonTapped): - state.nameInput = "" - state.destination = .createFolder - return .none - - case .view(.createFolderConfirmed): - let name = state.nameInput.trimmingCharacters(in: .whitespacesAndNewlines) - state.nameInput = "" - guard !name.isEmpty else { return .none } - return .run { [folderId = state.folderId] send in - let status = try await apiClient.addBookmark(folderId, name, .folder) - await send(.internal(.modifyResponse(status, success: Localization.folderCreated))) - } catch: { _, send in - await send(.internal(.modifyResponse(false, success: Localization.folderCreated))) - } - - case let .view(.renameConfirmed(bookmark)): - let name = state.nameInput.trimmingCharacters(in: .whitespacesAndNewlines) - state.nameInput = "" - guard !name.isEmpty, name != bookmark.name else { return .none } - if let index = state.bookmarks.firstIndex(where: { $0.id == bookmark.id }) { - state.bookmarks[index] = bookmark.with(parentId: bookmark.parentId, name: name) - } - let renamed = bookmark.isFolder ? Localization.folderRenamed : Localization.bookmarkRenamed - return .run { send in - let status = try await apiClient.modifyBookmark(bookmark, bookmark.parentId, name) - await send(.internal(.modifyResponse(status, success: renamed))) - } catch: { _, send in - await send(.internal(.modifyResponse(false, success: renamed))) - } - - case let .view(.moveConfirmed(bookmark, toFolderId)): - guard toFolderId != bookmark.parentId else { return .none } - state.bookmarks.removeAll { $0.id == bookmark.id } - return .run { send in - let status = try await apiClient.modifyBookmark(bookmark, toFolderId, bookmark.name) - await send(.internal(.modifyResponse(status, success: Localization.bookmarkMoved))) - } catch: { _, send in - await send(.internal(.modifyResponse(false, success: Localization.bookmarkMoved))) - } - - case let .internal(.modifyResponse(status, success)): - return .run { send in - await toastClient.showToast(status ? ToastMessage(text: success, haptic: .success) : .whoopsSomethingWentWrong) - if status { - notificationCenter.post(name: .bookmarksUpdated, object: nil) - } else { - await send(.internal(.loadBookmarks)) - } - } - case .view(.onFirstAppear): - let sessionPublisher = state.$userSession.publisher - let observers: Effect = .merge( - // Reload after login and clear after logout - .publisher { - sessionPublisher - .dropFirst() - .map { $0 != nil } - .removeDuplicates() - .map { Action.internal(.userSessionChanged(isAuthorized: $0)) } - }, - .run { send in - for await _ in notificationCenter.notifications(named: .bookmarksUpdated) { - await send(.internal(.loadBookmarks)) - } - } - ) + let observers = observeUpdates(of: state) guard state.isUserAuthorized else { state.isLoading = false analyticsClient.reportFullyDisplayed() @@ -259,66 +187,69 @@ public struct BookmarksFeature: Reducer, Sendable { } return .merge(.send(.internal(.loadBookmarks)), observers) - case let .internal(.userSessionChanged(isAuthorized)): - state.hasError = false - state.bookmarks = [] - state.allFolders = [] - guard isAuthorized else { - state.isLoading = false - return .none - } + case .view(.onRefresh): + guard state.isUserAuthorized, !state.isLoading else { return .none } + state.isRefreshing = true return .send(.internal(.loadBookmarks)) case .view(.retryButtonTapped): state.hasError = false return .send(.internal(.loadBookmarks)) - case .view(.onRefresh): - guard state.isUserAuthorized, !state.isLoading else { return .none } - state.isRefreshing = true - return .send(.internal(.loadBookmarks)) - case let .view(.bookmarkTapped(bookmark)): - switch bookmark.format { - case .folder: + if bookmark.isFolder { return .send(.delegate(.openFolder(id: bookmark.id, name: bookmark.name))) - case .url: - guard let url = bookmark.absoluteURL else { - return .run { _ in await toastClient.showToast(.whoopsSomethingWentWrong) } - } - return .send(.delegate(.openURL(url))) + } + guard let url = bookmark.absoluteURL else { + return .run { _ in await toastClient.showToast(.whoopsSomethingWentWrong) } + } + return .send(.delegate(.openURL(url))) + + case let .view(.contextMenu(.copyLink, bookmark)): + guard let url = bookmark.absoluteURL else { return .none } + pasteboardClient.copy(url.absoluteString) + return .run { _ in + await toastClient.showToast(ToastMessage(text: Localization.linkCopied, haptic: .success)) + } + + case let .view(.contextMenu(.rename, bookmark)): + state.nameInput = bookmark.name + state.destination = .rename(bookmark) + return .none + + case let .view(.contextMenu(.move, bookmark)): + state.destination = .move(bookmark) + return .none + + case let .view(.contextMenu(.delete, bookmark)): + state.bookmarks.removeAll { $0.id == bookmark.id } + return perform(success: Localization.bookmarkDeleted) { + try await apiClient.deleteBookmark(bookmark) + } + + case .view(.createFolderButtonTapped): + state.nameInput = "" + state.destination = .createFolder + return .none + + case .view(.createFolderConfirmed): + guard let name = state.takeNameInput() else { return .none } + return perform(success: Localization.folderCreated) { [folderId = state.folderId] in + try await apiClient.addBookmark(folderId, name, .folder) } - case let .view(.contextMenu(action, bookmark)): - switch action { - case .copyLink: - guard let url = bookmark.absoluteURL else { return .none } - pasteboardClient.copy(url.absoluteString) - return .run { _ in - await toastClient.showToast(ToastMessage(text: Localization.linkCopied, haptic: .success)) - } - - case .rename: - state.nameInput = bookmark.name - state.destination = .rename(bookmark) - return .none - - case .move: - state.destination = .move(bookmark) - return .none - - case .delete: - // Optimistically hide the bookmark (and folder contents) right away - state.bookmarks.removeAll { $0.id == bookmark.id } - return .run { _ in - let status = try await apiClient.deleteBookmark(bookmark) - let success = ToastMessage(text: Localization.bookmarkDeleted, haptic: .success) - await toastClient.showToast(status ? success : .whoopsSomethingWentWrong) - notificationCenter.post(name: .bookmarksUpdated, object: nil) - } catch: { _, send in - await toastClient.showToast(.whoopsSomethingWentWrong) - await send(.internal(.loadBookmarks)) - } + case let .view(.renameConfirmed(bookmark)): + guard let name = state.takeNameInput(), name != bookmark.name else { return .none } + let success = bookmark.isFolder ? Localization.folderRenamed : Localization.bookmarkRenamed + return perform(success: success) { + try await apiClient.modifyBookmark(bookmark, bookmark.parentId, name) + } + + case let .view(.moveConfirmed(bookmark, folderId)): + guard folderId != bookmark.parentId else { return .none } + state.bookmarks.removeAll { $0.id == bookmark.id } + return perform(success: Localization.bookmarkMoved) { + try await apiClient.modifyBookmark(bookmark, folderId, bookmark.name) } case .internal(.loadBookmarks): @@ -331,15 +262,12 @@ public struct BookmarksFeature: Reducer, Sendable { await send(.internal(.bookmarksResponse(result))) } - case let .internal(.bookmarksResponse(.success(bookmarks))): - state.allFolders = bookmarks.filter { !$0.deleted && $0.isFolder } + case let .internal(.bookmarksResponse(.success(response))): + let bookmarks = response.filter { !$0.deleted } + state.folders = bookmarks.filter(\.isFolder) state.bookmarks = bookmarks - .filter { !$0.deleted && $0.parentId == state.folderId } - .sorted { lhs, rhs in - // Folders first, then by user-defined order on the site - if lhs.isFolder != rhs.isFolder { return lhs.isFolder } - return lhs.number < rhs.number - } + .filter { $0.parentId == state.folderId } + .sorted(by: Bookmark.displayOrder) state.isLoading = false state.isRefreshing = false state.hasError = false @@ -349,31 +277,77 @@ public struct BookmarksFeature: Reducer, Sendable { case let .internal(.bookmarksResponse(.failure(error))): state.isLoading = false state.isRefreshing = false + state.hasError = state.bookmarks.isEmpty analyticsClient.capture(error) analyticsClient.reportFullyDisplayed() - // Nothing to show - full screen error with retry, otherwise keep stale list and show toast - guard !state.bookmarks.isEmpty else { - state.hasError = true - return .none - } - return .run { _ in - await toastClient.showToast(.whoopsSomethingWentWrong) - } + guard !state.hasError else { return .none } + return .run { _ in await toastClient.showToast(.whoopsSomethingWentWrong) } + + case let .internal(.userSessionUpdated(isAuthorized)): + state.bookmarks = [] + state.folders = [] + state.hasError = false + state.isLoading = isAuthorized + return isAuthorized ? .send(.internal(.loadBookmarks)) : .none - case .delegate: + case .binding, .destination, .delegate: return .none } } .ifLet(\.$destination, action: \.destination) } + + // MARK: - Effects + + private func observeUpdates(of state: State) -> Effect { + let userSession = state.$userSession.publisher + return .merge( + .publisher { + userSession + .dropFirst() + .map { $0 != nil } + .removeDuplicates() + .map { Action.internal(.userSessionUpdated(isAuthorized: $0)) } + }, + .run { send in + for await _ in notificationCenter.notifications(named: .bookmarksUpdated) { + await send(.internal(.loadBookmarks)) + } + } + ) + } + + /// Runs bookmark modification, on success notifies all bookmark screens, otherwise reloads current one + private func perform( + success: LocalizedStringResource, + _ operation: @escaping @Sendable () async throws -> Bool + ) -> Effect { + return .run { send in + do { + guard try await operation() else { throw BookmarkError.rejected } + await toastClient.showToast(ToastMessage(text: success, haptic: .success)) + notificationCenter.post(name: .bookmarksUpdated, object: nil) + } catch { + analyticsClient.capture(error) + await toastClient.showToast(.whoopsSomethingWentWrong) + await send(.internal(.loadBookmarks)) + } + } + } } extension BookmarksFeature.Destination.State: Equatable {} // MARK: - Helpers +private enum BookmarkError: Error { + case rejected +} + private extension Bookmark { - func with(parentId: Int, name: String) -> Bookmark { - Bookmark(id: id, parentId: parentId, name: name, number: number, format: format, updatedAt: updatedAt, deleted: deleted, isSystem: isSystem) + /// Folders first, then in order set by user on the site + static func displayOrder(_ lhs: Bookmark, _ rhs: Bookmark) -> Bool { + if lhs.isFolder != rhs.isFolder { return lhs.isFolder } + return lhs.number < rhs.number } } diff --git a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift index 7e07a39b..e458f692 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift @@ -34,42 +34,7 @@ public struct BookmarksScreen: View { backgroundColors.primary .ignoresSafeArea() - if !store.isUserAuthorized { - GenericView( - systemSymbol: .bookmark, - title: LocalizedStringResource("Log in to see bookmarks", bundle: .module), - description: LocalizedStringResource("Bookmarks are synced with your 4PDA account", bundle: .module) - ) - .padding(.horizontal, 55) - } else if store.hasError { - GenericView.GenericError { - send(.retryButtonTapped) - } - .padding(.horizontal, 55) - } else if store.shouldShowEmptyState { - GenericView( - systemSymbol: .bookmark, - title: LocalizedStringResource("No bookmarks", bundle: .module), - description: LocalizedStringResource("Tap “Add To Bookmarks” in topic, forum or article menu, to save it here", bundle: .module) - ) - .padding(.horizontal, 55) - } else if !store.isLoading { - List { - Section { - ForEach(store.bookmarks, id: \.id) { bookmark in - BookmarkRow(bookmark) - } - } - .listRowBackground(backgroundColors.tertiary) - } - .scrollContentBackground(.hidden) - .refreshable { - await send(.onRefresh).finish() - } - } else { - PDALoader() - .frame(width: 24, height: 24) - } + Content() } .animation(.default, value: store.bookmarks) .navigationTitle(navigationTitle) @@ -97,7 +62,9 @@ public struct BookmarksScreen: View { .alert( item: $store.destination.rename, title: { bookmark in - bookmark.isFolder ? Text("Rename Folder", bundle: .module) : Text("Rename Bookmark", bundle: .module) + bookmark.isFolder + ? Text("Rename Folder", bundle: .module) + : Text("Rename Bookmark", bundle: .module) } ) { bookmark in NameInput(confirmTitle: LocalizedStringResource("Save", bundle: .module)) { @@ -115,7 +82,7 @@ public struct BookmarksScreen: View { send(.moveConfirmed(bookmark, toFolderId: target.id)) } } - Button(LocalizedStringResource("Cancel", bundle: .module), role: .cancel) { } + Button(LocalizedStringResource("Cancel", bundle: .module), role: .cancel) {} } } message: { bookmark in if store.state.moveTargets(for: bookmark).isEmpty { @@ -135,6 +102,48 @@ public struct BookmarksScreen: View { return Text("Bookmarks", bundle: .module) } + // MARK: - Content + + @ViewBuilder + private func Content() -> some View { + if !store.isUserAuthorized { + GenericView( + systemSymbol: .bookmark, + title: LocalizedStringResource("Log in to see bookmarks", bundle: .module), + description: LocalizedStringResource("Bookmarks are synced with your 4PDA account", bundle: .module) + ) + .padding(.horizontal, 55) + } else if store.hasError { + GenericView.GenericError { + send(.retryButtonTapped) + } + .padding(.horizontal, 55) + } else if store.isEmpty { + GenericView( + systemSymbol: .bookmark, + title: LocalizedStringResource("No bookmarks", bundle: .module), + description: LocalizedStringResource("Tap “Add To Bookmarks” in topic, forum or article menu, to save it here", bundle: .module) + ) + .padding(.horizontal, 55) + } else if store.isLoading { + PDALoader() + .frame(width: 24, height: 24) + } else { + List { + Section { + ForEach(store.bookmarks, id: \.id) { bookmark in + BookmarkRow(bookmark) + } + } + .listRowBackground(backgroundColors.tertiary) + } + .scrollContentBackground(.hidden) + .refreshable { + await send(.onRefresh).finish() + } + } + } + // MARK: - Bookmark Row @ViewBuilder @@ -143,7 +152,7 @@ public struct BookmarksScreen: View { send(.bookmarkTapped(bookmark)) } label: { HStack(spacing: 12) { - Image(systemSymbol: bookmark.isFolder ? .folder : bookmark.symbol) + Image(systemSymbol: bookmark.symbol) .font(.title2) .foregroundStyle(tintColor) .frame(width: 32) @@ -167,7 +176,6 @@ public struct BookmarksScreen: View { } .buttonStyle(.plain) .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)) - // Separator goes under the icon too, as in other lists .alignmentGuide(.listRowSeparatorLeading) { _ in 0 } .contextMenu { if !bookmark.isFolder { @@ -208,17 +216,14 @@ public struct BookmarksScreen: View { // MARK: - Name Input @ViewBuilder - private func NameInput(confirmTitle: LocalizedStringResource, _ action: @escaping () -> Void) -> some View { + private func NameInput(confirmTitle: LocalizedStringResource, onConfirm: @escaping () -> Void) -> some View { WithPerceptionTracking { TextField(String(localized: "Name", bundle: .module), text: $store.nameInput) - Button(LocalizedStringResource("Cancel", bundle: .module), role: .cancel) { } + Button(LocalizedStringResource("Cancel", bundle: .module), role: .cancel) {} - // No `.disabled` here: alert doesn't re-evaluate it while typing, - // empty names are ignored by the reducer instead - Button(confirmTitle) { - action() - } + // Alert doesn't update `.disabled` while typing, so blank names are dropped in reducer + Button(confirmTitle, action: onConfirm) } } } @@ -227,13 +232,23 @@ public struct BookmarksScreen: View { private extension Bookmark { var symbol: SFSymbol { - guard let url = absoluteURL?.absoluteString else { return .link } - if url.contains("showtopic=") { return .textBubble } - if url.contains("showforum=") || url.contains("act=idx") { return .bubbleLeftAndBubbleRight } - if url.contains("showuser=") { return .person } - if url.contains("act=qms") { return .person2 } - if url.contains("devdb") { return .iphone } - return .docText + if isFolder { return .folder } + guard let link = absoluteURL?.absoluteString else { return .link } + + switch true { + case link.contains("showtopic="): + return .textBubble + case link.contains("showforum="), link.contains("act=idx"): + return .bubbleLeftAndBubbleRight + case link.contains("showuser="): + return .person + case link.contains("act=qms"): + return .person2 + case link.contains("devdb"): + return .iphone + default: + return .docText + } } } @@ -248,7 +263,7 @@ private func bookmarksPreview( } ) -> some View { @Shared(.userSession) var userSession - $userSession.withLock { $0 = isAuthorized ? UserSession.mock : nil } + $userSession.withLock { $0 = isAuthorized ? .mock : nil } return NavigationStack { BookmarksScreen( @@ -284,7 +299,7 @@ private func bookmarksPreview( #Preview("Loading") { bookmarksPreview(bookmarks: { - try await Task.sleep(for: .seconds(1000)) + try await Task.sleep(for: .seconds(3600)) return [] }) } diff --git a/Modules/Sources/Models/App/AppTab.swift b/Modules/Sources/Models/App/AppTab.swift index a0d335be..715a8a04 100644 --- a/Modules/Sources/Models/App/AppTab.swift +++ b/Modules/Sources/Models/App/AppTab.swift @@ -9,8 +9,7 @@ import SwiftUI import SFSafeSymbols public enum AppTab: Int, CaseIterable, Sendable, Codable { - // Declaration order is the order of tabs in tab bar, - // explicit raw values keep `AppSettings.startPage` stored values valid + // Order of cases defines tab bar order, raw values are persisted in `AppSettings.startPage` case articles = 0 case favorites = 1 case bookmarks = 4 diff --git a/Modules/Sources/Models/Bookmarks/Bookmark.swift b/Modules/Sources/Models/Bookmarks/Bookmark.swift index 5b763a90..30c60409 100644 --- a/Modules/Sources/Models/Bookmarks/Bookmark.swift +++ b/Modules/Sources/Models/Bookmarks/Bookmark.swift @@ -15,7 +15,7 @@ public struct Bookmark: Codable, Hashable, Sendable { public let format: Format public let updatedAt: Date public let deleted: Bool - /// Default bookmark added by the site itself (e.g. forum rules), can't be edited + /// Added by the site itself (e.g. forum rules), can't be edited public let isSystem: Bool public enum Format: Codable, Sendable, Hashable { @@ -155,20 +155,23 @@ public extension Bookmark { // MARK: - Helpers public extension Bookmark { - - static let baseURL = URL(string: "https://4pda.to/")! - var isFolder: Bool { - if case .folder = format { return true } - return false + return format == .folder } - /// Site stores full links, but relative ones (e.g. `forum/index.php?showtopic=1`) - /// are resolved against 4pda.to just in case. var absoluteURL: URL? { - guard case let .url(url) = format else { return nil } - if url.scheme != nil { return url } - let path = url.absoluteString.hasPrefix("/") ? String(url.absoluteString.dropFirst()) : url.absoluteString - return URL(string: path, relativeTo: Bookmark.baseURL)?.absoluteURL + return format.absoluteURL + } +} + +public extension Bookmark.Format { + private static let baseURL = URL(string: "https://4pda.to/")! + + /// Relative links (e.g. `forum/index.php?showtopic=1`) resolved against 4pda.to + var absoluteURL: URL? { + guard case let .url(url) = self else { return nil } + guard url.scheme == nil else { return url } + let path = url.relativeString.hasPrefix("/") ? String(url.relativeString.dropFirst()) : url.relativeString + return URL(string: path, relativeTo: Self.baseURL)?.absoluteURL } } diff --git a/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift b/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift index 1f3c7cd7..2431cda7 100644 --- a/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift +++ b/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift @@ -25,21 +25,23 @@ public struct BookmarksParser { throw ParsingError.failedToCastDataToAny } - // Empty bookmarks list may come as an empty array or be absent guard let rawBookmarks = array[4] as? [[Any]] else { return [] } - - // Skipping malformed entries instead of failing the whole list return rawBookmarks.compactMap(parseBookmark) } - // Bookmark layout: [id, updatedAt, isDeleted, type, parentId, number, name, url] - // Type: 0 - link, 1 - folder, 2 - default link added by the site (not editable) + private enum BookmarkType: Int { + case link = 0 + case folder = 1 + case system = 2 + } + + /// `[id, updatedAt, isDeleted, type, parentId, number, name, url?]` private static func parseBookmark(_ bookmark: [Any]) -> Bookmark? { guard bookmark.count > 6, let id = bookmark[0] as? Int, let updatedAt = bookmark[1] as? TimeInterval, let deleted = bookmark[2] as? Int, - let type = bookmark[3] as? Int, + let type = (bookmark[3] as? Int).flatMap(BookmarkType.init), let parentId = bookmark[4] as? Int, let number = bookmark[5] as? Int, let name = bookmark[6] as? String else { @@ -47,14 +49,11 @@ public struct BookmarksParser { } let format: Bookmark.Format - if type == 1 { + switch type { + case .folder: format = .folder - } else { - guard bookmark.count > 7, - let link = bookmark[7] as? String, - let url = URL(string: link) ?? link.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed).flatMap(URL.init(string:)) else { - return nil - } + case .link, .system: + guard bookmark.count > 7, let link = bookmark[7] as? String, let url = makeURL(from: link) else { return nil } format = .url(url: url) } @@ -66,7 +65,12 @@ public struct BookmarksParser { format: format, updatedAt: Date(timeIntervalSince1970: updatedAt), deleted: deleted != 0, - isSystem: type == 2 + isSystem: type == .system ) } + + private static func makeURL(from link: String) -> URL? { + return URL(string: link) + ?? link.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed).flatMap(URL.init(string:)) + } }