diff --git a/Modules/Sources/APIClient/APIClient.swift b/Modules/Sources/APIClient/APIClient.swift index 4bf37979..2a504596 100644 --- a/Modules/Sources/APIClient/APIClient.swift +++ b/Modules/Sources/APIClient/APIClient.swift @@ -60,6 +60,9 @@ 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 + 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> @@ -355,6 +358,21 @@ 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.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(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(bookmark, parentId: parentId, name: name) + let response = try await api.send(MemberCommand.Bookmarks.modify(id: bookmark.id, data: request)) + return Int(response.getResponseStatus()) == 0 + }, // MARK: - Forum @@ -817,7 +835,16 @@ extension APIClient: DependencyKey { return true }, getBookmarksList: { - return [.mockArticle, .mockForum, .mockUser] + return [.mockFolder, .mockSubFolder, .mockArticle, .mockForum, .mockUser] + }, + addBookmark: { _, _, _ in + return true + }, + deleteBookmark: { _ in + return true + }, + modifyBookmark: { _, _, _ in + return true }, getForumsList: { _ in return .finished() @@ -1047,3 +1074,29 @@ extension String { .components(separatedBy: ",")[number] } } + +// 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 { + /// Site expects absolute links + var request: BookmarkRequest.BookmarkFormat { + switch self { + case .folder: + return .folder + case let .url(url): + return .url(url: (absoluteURL ?? 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..24b2f511 100644 --- a/Modules/Sources/AppFeature/AppView.swift +++ b/Modules/Sources/AppFeature/AppView.swift @@ -156,6 +156,14 @@ struct LiquidTabView: View { } .badge(store.favoritesBadges) + Tab( + AppTab.bookmarks.title, + systemSymbol: AppTab.bookmarks.iconSymbol, + value: .bookmarks + ) { + StackTabView(store: store.scope(\.bookmarksTab, action: \.bookmarksTab)) + } + Tab( AppTab.forum.title, systemSymbol: AppTab.forum.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 { @@ -214,6 +222,9 @@ struct OldTabView: View { StackTabView(store: store.scope(\.favoritesTab, action: \.favoritesTab)) .tag(AppTab.favorites) + StackTabView(store: store.scope(\.bookmarksTab, action: \.bookmarksTab)) + .tag(AppTab.bookmarks) + StackTabView(store: store.scope(\.forumTab, action: \.forumTab)) .tag(AppTab.forum) @@ -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..391268b1 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksFeature.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksFeature.swift @@ -9,40 +9,345 @@ 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 + + enum Localization { + static let linkCopied = LocalizedStringResource("Link copied", bundle: .module) + static let bookmarkDeleted = LocalizedStringResource("Bookmark deleted", bundle: .module) + static let bookmarkRenamed = LocalizedStringResource("Bookmark 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 + + @Reducer + public enum Destination { + case createFolder + @ReducerCaseIgnored + case rename(Bookmark) + @ReducerCaseIgnored + case move(Bookmark) + } + + public struct MoveTarget: Equatable, Identifiable, Sendable { + public let id: Int + public let title: String + } + + public enum ContextMenuAction: Equatable, Sendable { + case copyLink + case rename + case move + case delete + } + // MARK: - State - + @ObservableState public struct State: Equatable { - public init() {} + @Shared(.userSession) var userSession: UserSession? + @Presents public var destination: Destination.State? + + /// `0` stands for the root level + public let folderId: Int + public let folderName: String? + + public var bookmarks: [Bookmark] = [] + public var folders: [Bookmark] = [] + public var nameInput = "" + + public var isLoading = true + public var isRefreshing = false + public var hasError = false + + public var isUserAuthorized: Bool { + return userSession != nil + } + + public var isEmpty: Bool { + return !isLoading && !hasError && bookmarks.isEmpty + } + + public init( + folderId: Int = 0, + folderName: String? = nil, + bookmarks: [Bookmark] = [], + isLoading: Bool = true, + hasError: Bool = false + ) { + self.folderId = folderId + self.folderName = folderName + self.bookmarks = bookmarks + 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 - - public enum Action { - case onAppear + + public enum Action: ViewAction, BindableAction { + case binding(BindingAction) + case destination(PresentationAction) + + case view(View) + public enum View { + case onFirstAppear + case onRefresh + case retryButtonTapped + 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 userSessionUpdated(isAuthorized: Bool) + } + + 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 { + BindingReducer() + Reduce { state, action in switch action { - case .onAppear: + case .view(.onFirstAppear): + let observers = observeUpdates(of: state) + guard state.isUserAuthorized else { + state.isLoading = false + analyticsClient.reportFullyDisplayed() + return observers + } + return .merge(.send(.internal(.loadBookmarks)), observers) + + 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 let .view(.bookmarkTapped(bookmark)): + if bookmark.isFolder { + return .send(.delegate(.openFolder(id: bookmark.id, name: bookmark.name))) + } + 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(.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): + guard state.isUserAuthorized else { return .none } + 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(response))): + let bookmarks = response.filter { !$0.deleted } + state.folders = bookmarks.filter(\.isFolder) + state.bookmarks = bookmarks + .filter { $0.parentId == state.folderId } + .sorted(by: Bookmark.displayOrder) + state.isLoading = false + state.isRefreshing = false + state.hasError = false + analyticsClient.reportFullyDisplayed() + return .none + + case let .internal(.bookmarksResponse(.failure(error))): + state.isLoading = false + state.isRefreshing = false + state.hasError = state.bookmarks.isEmpty + analyticsClient.capture(error) + analyticsClient.reportFullyDisplayed() + 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 .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 { + /// 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 db2a04b9..e458f692 100644 --- a/Modules/Sources/BookmarksFeature/BookmarksScreen.swift +++ b/Modules/Sources/BookmarksFeature/BookmarksScreen.swift @@ -11,99 +11,299 @@ 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) + + Content() + } + .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) } - .frame(width: UIScreen.main.bounds.width) } - .navigationTitle(Text("Bookmarks", bundle: .module)) - ._toolbarTitleDisplayMode(.large) - .toolbarBackground(backgroundColors.primary, for: .navigationBar) - .onAppear { - store.send(.onAppear) + .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) + } + } + } + + private var navigationTitle: Text { + if let folderName = store.folderName { + return Text(folderName) } + return Text("Bookmarks", bundle: .module) } - - // MARK: - Empty Screen - + + // MARK: - Content + @ViewBuilder - private func EmptyBookmarks() -> 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) - .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) - .font(.footnote) - .multilineTextAlignment(.center) - .foregroundStyle(Color(.Labels.teritary)) - .padding(.horizontal, 55) + 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: Coming Soon Tape - + + // MARK: - Bookmark Row + @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) + private func BookmarkRow(_ bookmark: Bookmark) -> some View { + Button { + send(.bookmarkTapped(bookmark)) + } label: { + HStack(spacing: 12) { + Image(systemSymbol: bookmark.symbol) + .font(.title2) + .foregroundStyle(tintColor) + .frame(width: 32) + + Text(bookmark.name) + .font(.body) + .foregroundStyle(Color(.Labels.primary)) + .lineLimit(2) + + Spacer(minLength: 0) + + if bookmark.isFolder { + Image(systemSymbol: .chevronRight) + .font(.footnote.weight(.semibold)) + .foregroundStyle(Color(.Labels.quintuple)) + } + } + .padding(.vertical, 8) + .frame(minHeight: 60) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)) + .alignmentGuide(.listRowSeparatorLeading) { _ in 0 } + .contextMenu { + if !bookmark.isFolder { + ContextButton(text: LocalizedStringResource("Copy Link", bundle: .module), symbol: .docOnDoc) { + send(.contextMenu(.copyLink, 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)) + } } } - .frame(width: UIScreen.main.bounds.width * 2, height: 26) - .background(tintColor) + .swipeActions(edge: .trailing, allowsFullSwipe: true) { + 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, onConfirm: @escaping () -> Void) -> some View { + WithPerceptionTracking { + TextField(String(localized: "Name", bundle: .module), text: $store.nameInput) + + Button(LocalizedStringResource("Cancel", bundle: .module), role: .cancel) {} + + // Alert doesn't update `.disabled` while typing, so blank names are dropped in reducer + Button(confirmTitle, action: onConfirm) + } + } +} + +// MARK: - Helpers + +private extension Bookmark { + var symbol: SFSymbol { + 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 + } } } // 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 ? .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(3600)) + return [] + }) +} + +#Preview("Error") { + bookmarksPreview(bookmarks: { throw URLError(.notConnectedToInternet) }) } diff --git a/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings b/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings index 640081ee..699e27c3 100644 --- a/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/BookmarksFeature/Resources/Localizable.xcstrings @@ -1,6 +1,36 @@ { "sourceLanguage" : "en", "strings" : { + "Bookmark deleted" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закладка удалена" + } + } + } + }, + "Bookmark moved" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закладка перемещена" + } + } + } + }, + "Bookmark renamed" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закладка переименована" + } + } + } + }, "Bookmarks" : { "localizations" : { "ru" : { @@ -11,21 +41,147 @@ } } }, - "Bookmarks will appear soon" : { + "Bookmarks are synced with your 4PDA account" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закладки синхронизируются с вашим аккаунтом 4PDA" + } + } + } + }, + "Cancel" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отмена" + } + } + } + }, + "Copy Link" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Скопировать ссылку" + } + } + } + }, + "Create" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создать" + } + } + } + }, + "Create a folder first" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сначала создайте папку" + } + } + } + }, + "Delete" : { "localizations" : { "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Скоро появятся закладки" + "value" : "Удалить" } } } }, - "COMING SOON" : { - + "Folder created" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Папка создана" + } + } + } + }, + "Folder renamed" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Папка переименована" + } + } + } + }, + "Link copied" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ссылка скопирована" + } + } + } + }, + "Log in to see bookmarks" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Войдите, чтобы увидеть закладки" + } + } + } + }, + "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" : { - "extractionState" : "stale", "localizations" : { "ru" : { "stringUnit" : { @@ -35,27 +191,56 @@ } } }, - "Tap “Add To Bookmarks” in article menu, to save it here" : { - "extractionState" : "stale", + "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" : "Нажмите в меню статьи пункт “Добавить в закладки”, чтобы сохранить ее сюда" + "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..715a8a04 100644 --- a/Modules/Sources/Models/App/AppTab.swift +++ b/Modules/Sources/Models/App/AppTab.swift @@ -9,10 +9,12 @@ import SwiftUI import SFSafeSymbols public enum AppTab: Int, CaseIterable, Sendable, Codable { + // Order of cases defines tab bar order, raw values are persisted in `AppSettings.startPage` case articles = 0 - case favorites - case forum - case more + case favorites = 1 + case bookmarks = 4 + case forum = 2 + 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..30c60409 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 + /// 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 } } @@ -147,3 +151,27 @@ public extension Bookmark { deleted: false ) } + +// MARK: - Helpers + +public extension Bookmark { + var isFolder: Bool { + return format == .folder + } + + var absoluteURL: URL? { + 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/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..2431cda7 100644 --- a/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift +++ b/Modules/Sources/ParsingClient/Parsers/BookmarksParser.swift @@ -10,32 +10,67 @@ 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 + } + + guard let rawBookmarks = array[4] as? [[Any]] else { return [] } + return rawBookmarks.compactMap(parseBookmark) + } + + private enum BookmarkType: Int { + case link = 0 + case folder = 1 + case system = 2 } - - 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)!) + + /// `[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).flatMap(BookmarkType.init), + 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 + switch type { + case .folder: + format = .folder + 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) } + + return Bookmark( + id: id, + parentId: parentId, + name: name.convertCodes(), + number: number, + format: format, + updatedAt: Date(timeIntervalSince1970: updatedAt), + deleted: deleted != 0, + isSystem: type == .system + ) + } + + private static func makeURL(from link: String) -> URL? { + return URL(string: link) + ?? link.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed).flatMap(URL.init(string:)) } } 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,