diff --git a/Modules/Sources/BBPanelFeature/BBPanelFeature.swift b/Modules/Sources/BBPanelFeature/BBPanelFeature.swift index b9ab6d14..6502e317 100644 --- a/Modules/Sources/BBPanelFeature/BBPanelFeature.swift +++ b/Modules/Sources/BBPanelFeature/BBPanelFeature.swift @@ -69,7 +69,7 @@ public struct BBPanelFeature: Reducer, Sendable { var alertInput = "" var textSize = 1 - var isUploading = false + public internal(set) var isUploading = false var uploadedFiles = 0 var showUploadBox = false @@ -83,6 +83,7 @@ public struct BBPanelFeature: Reducer, Sendable { self.supportsUpload = supportsUpload self.allowedExtensions = allowedExtensions self.existsFiles = existsFiles + self.upload.isQms = panelType == .qms } } @@ -192,6 +193,8 @@ public struct BBPanelFeature: Reducer, Sendable { return .send(.delegate(.tagTapped(tag))) case let .upload(.delegate(.fileHasBeenTapped(id, name))): + // QMS sends files as message attachments, not inline tags + guard state.panelWith != .qms else { return .none } return .send(.delegate(.tagTapped(("[attachment=\"\(id):\(name)\"]", "")))) case .upload(.delegate(.someFileUploading)): diff --git a/Modules/Sources/ParsingClient/Parsers/QMSParser.swift b/Modules/Sources/ParsingClient/Parsers/QMSParser.swift index fe0a4ad7..0d6f9ffc 100644 --- a/Modules/Sources/ParsingClient/Parsers/QMSParser.swift +++ b/Modules/Sources/ParsingClient/Parsers/QMSParser.swift @@ -44,7 +44,7 @@ public struct QMSChatParser { senderId: message[1] as! Int, date: Date(timeIntervalSince1970: message[2] as! TimeInterval), text: message[3] as! String, - attachments: try! AttachmentParser.parseAttachment(message[4] as! [[Any]]) + attachments: (try? AttachmentParser.parseAttachment(message[4] as? [[Any]] ?? [])) ?? [] ) } } diff --git a/Modules/Sources/QMSClient/QMSClient.swift b/Modules/Sources/QMSClient/QMSClient.swift index 7f3d6e6c..4ef0ab0a 100644 --- a/Modules/Sources/QMSClient/QMSClient.swift +++ b/Modules/Sources/QMSClient/QMSClient.swift @@ -21,7 +21,7 @@ public struct QMSClient: Sendable { public var createChat: @Sendable (_ opponentId: Int, _ title: String, _ message: String) async throws -> String public var deleteAllChats: @Sendable (_ userId: Int) async throws -> String public var deleteChat: @Sendable (_ chatId: Int) async throws -> String - public var sendMessage: @Sendable (_ chatId: Int, _ message: String) async throws -> Void + public var sendMessage: @Sendable (_ chatId: Int, _ message: String, _ attachments: [Int]) async throws -> Void public var deleteMessage: @Sendable (_ chatId: Int, _ messageId: Int, _ forAll: Bool) async throws -> String public var blacklist: @Sendable () async throws -> String public var addToBlacklist: @Sendable (_ id: Int, _ add: Bool) async throws -> String @@ -69,8 +69,8 @@ extension QMSClient: DependencyKey { return response }, - sendMessage: { chatId, message in - let _ = try await api.send(QMSCommand.Message.send(message: message, dialogId: chatId, attaches: [])) + sendMessage: { chatId, message, attachments in + let _ = try await api.send(QMSCommand.Message.send(message: message, dialogId: chatId, attaches: attachments)) }, deleteMessage: { chatId, messageId, forAll in @@ -117,7 +117,7 @@ extension QMSClient: DependencyKey { deleteChat: { _ in return "" }, - sendMessage: { chatId, message in + sendMessage: { chatId, message, _ in return try await mock.sendQMSMessage(chatId: chatId, message: message) }, deleteMessage: { _, _, _ in @@ -146,7 +146,7 @@ extension QMSClient: DependencyKey { createChat: unimplemented(), deleteAllChats: unimplemented(), deleteChat: unimplemented(), - sendMessage: { chatId, message in + sendMessage: { chatId, message, _ in return try await mock.sendQMSMessage(chatId: chatId, message: message) }, deleteMessage: unimplemented(), diff --git a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift index 62ab8b8b..79ad6f9e 100644 --- a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift +++ b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift @@ -17,13 +17,13 @@ extension QMSFeature { @Dependency(\.analyticsClient) var analytics var body: some Reducer { - Reduce { _, action in + Reduce { state, action in switch action { - case .view(.onAppear), .internal, .delegate, .binding, .alert: + case .view(.onAppear), .view(.bbPanelButtonTapped), .internal, .delegate, .binding, .alert, .bbPanel: break - case let .view(.sendMessageButtonTapped(draft)): - analytics.log(QMSEvent.sendMessageTapped(isEmpty: draft.text.isEmpty)) + case .view(.sendMessageButtonTapped): + analytics.log(QMSEvent.sendMessageTapped(isEmpty: state.draftText.isEmpty)) case .view(.loadMoreTriggered): analytics.log(QMSEvent.loadMoreTriggered) diff --git a/Modules/Sources/QMSFeature/QMSFeature.swift b/Modules/Sources/QMSFeature/QMSFeature.swift index c2671413..9a3d94af 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -15,6 +15,9 @@ import AnalyticsClient import NotificationsClient import TCAExtensions import ExyteChat +import BBPanelFeature +import SharedUI +import TopicBuilder @Reducer public struct QMSFeature: Reducer, Sendable { @@ -41,7 +44,17 @@ public struct QMSFeature: Reducer, Sendable { public let chatId: Int public var chat: QMSChat? - public var messages: [Message] = [] + public var messages: [ExyteChat.Message] = [] + + /// BB-code trees for each message, keyed by message id + var nodes: [String: [UITopicType]] = [:] + /// Non-image attachments for each message, keyed by message id + var files: [String: [Models.Attachment]] = [:] + + var bbPanel = BBPanelFeature.State(for: .qms, supportsUpload: true) + var textRange: NSRange? + var isInputFocused = false + var isBBPanelShown = false var hasMoreOlderMessages = true var isLoadingMore = false @@ -50,6 +63,15 @@ public struct QMSFeature: Reducer, Sendable { var draftText = "" var draftSnapshot = "" + var attachmentIds: [Int] { + bbPanel.existsFiles.compactMap(\.serverId) + } + + var canSend: Bool { + let hasText = !draftText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + return !isSending && !bbPanel.isUploading && (hasText || !attachmentIds.isEmpty) + } + public var title: String { if let chat { return chat.partnerName + " - " + chat.name @@ -67,6 +89,7 @@ public struct QMSFeature: Reducer, Sendable { public enum Action: BindableAction, ViewAction { case binding(BindingAction) + case bbPanel(BBPanelFeature.Action) case alert(PresentationAction) public enum Alert { @@ -76,7 +99,8 @@ public struct QMSFeature: Reducer, Sendable { case view(View) public enum View { case onAppear - case sendMessageButtonTapped(DraftMessage) + case sendMessageButtonTapped + case bbPanelButtonTapped case loadMoreTriggered case urlTapped(URL) } @@ -85,6 +109,7 @@ public struct QMSFeature: Reducer, Sendable { public enum Internal { case loadChat case chatLoaded(Result, LoadKind) + case messageSent case messageSendError(any Error) } @@ -107,11 +132,27 @@ public struct QMSFeature: Reducer, Sendable { public var body: some Reducer { BindingReducer() + Scope(\.bbPanel, action: \.bbPanel) { + BBPanelFeature() + } + Reduce { state, action in switch action { case .alert, .delegate: return .none + case .view(.bbPanelButtonTapped): + state.isBBPanelShown.toggle() + return .none + + case let .bbPanel(.delegate(.tagTapped(tag))): + insertTag(tag, state: &state) + state.isInputFocused = true + return .none + + case .bbPanel: + return .none + case .view(.onAppear): return .merge([ .send(.internal(.loadChat)), @@ -129,19 +170,31 @@ public struct QMSFeature: Reducer, Sendable { } ]) - case let .view(.sendMessageButtonTapped(draftMessage)): - guard !state.isSending, !draftMessage.text.isEmpty else { return .none } + case .view(.sendMessageButtonTapped): + guard state.canSend else { return .none } + let message = state.draftText state.draftText = "" - state.draftSnapshot = draftMessage.text + state.textRange = nil + state.draftSnapshot = message state.isSending = true - return .run { [chatId = state.chatId, message = draftMessage.text] send in - try await qmsClient.sendMessage(chatId: chatId, message: message) + return .run { [chatId = state.chatId, attachments = state.attachmentIds] send in + try await qmsClient.sendMessage(chatId: chatId, message: message, attachments: attachments) + await send(.internal(.messageSent)) } catch: { error, send in await send(.internal(.messageSendError(error))) } + case .internal(.messageSent): + // Fresh panel drops already sent files from the upload box + state.bbPanel = BBPanelFeature.State(for: .qms, supportsUpload: true) + state.isBBPanelShown = false + return .merge( + .send(.bbPanel(.view(.onAppear))), + .send(.internal(.loadChat)) + ) + case .view(.loadMoreTriggered): guard !state.isLoadingMore else { return .none } guard state.hasMoreOlderMessages else { return .none } @@ -207,6 +260,19 @@ public struct QMSFeature: Reducer, Sendable { var mergedChat = chat mergedChat.messages = mergeResult.messages + for message in mergeResult.messages { + let id = String(message.id) + guard state.nodes[id] == nil else { continue } + // Attachments not referenced in text are shown separately as images/files, + // so builder gets only inline ones (otherwise it adds an extra spoiler with them) + let inline = message.inlineAttachmentIds + let inlineAttachments = message.attachments.filter { inline.contains($0.id) } + state.nodes[id] = message.text.isEmpty + ? [] + : TopicNodeBuilder(text: message.text, attachments: inlineAttachments).build() + state.files[id] = message.attachments.filter { $0.type == .file && !inline.contains($0.id) } + } + state.messages = makeLocalMessages( from: mergeResult.messages, chat: mergedChat, @@ -285,7 +351,7 @@ public struct QMSFeature: Reducer, Sendable { from remoteMessages: [QMSMessage], chat: QMSChat, currentUserId: Int - ) -> [Message] { + ) -> [ExyteChat.Message] { var localMessages = remoteMessages.map { remoteMessage in let isCurrentUser = currentUserId == remoteMessage.senderId let user = User( @@ -295,12 +361,27 @@ public struct QMSFeature: Reducer, Sendable { isCurrentUser: isCurrentUser ) - return Message( + // Images go to the chat's own media grid with fullscreen viewer + let inline = remoteMessage.inlineAttachmentIds + let images: [ExyteChat.Attachment] = remoteMessage.attachments.compactMap { attachment in + guard attachment.type == .image, + !inline.contains(attachment.id), + let metadata = attachment.metadata else { return nil } + return ExyteChat.Attachment( + id: String(attachment.id), + thumbnail: metadata.url, + full: metadata.fullUrl ?? metadata.url, + type: .image + ) + } + + return ExyteChat.Message( id: String(remoteMessage.id), user: user, status: .none, createdAt: remoteMessage.date, - text: remoteMessage.processedText + text: remoteMessage.text, + attachments: images ) } @@ -316,4 +397,42 @@ public struct QMSFeature: Reducer, Sendable { return localMessages } + + // MARK: - BB Tags + + private func insertTag(_ tag: (String, String), state: inout State) { + if let nsRange = state.textRange, + let range = Range(nsRange, in: state.draftText), + !state.draftText.isEmpty { + if range.isEmpty { + let location = nsRange.location + tag.0.utf16.count + state.draftText.insert(contentsOf: "\(tag.0)\(tag.1)", at: range.lowerBound) + state.textRange = NSRange(location: location, length: 0) + } else { + // Wrap selected text into the tag + state.draftText.insert(contentsOf: tag.1, at: range.upperBound) + state.draftText.insert(contentsOf: tag.0, at: range.lowerBound) + state.textRange = NSRange(location: nsRange.location + tag.0.utf16.count, length: nsRange.length) + } + } else { + state.draftText += "\(tag.0)\(tag.1)" + state.textRange = NSRange(location: state.draftText.utf16.count - tag.1.utf16.count, length: 0) + } + } +} + +// MARK: - Helpers + +private extension QMSMessage { + /// Ids of attachments that are already referenced in text via `[attachment="id:name"]` + var inlineAttachmentIds: Set { + guard text.contains("attachment") else { return [] } + let regex = try? NSRegularExpression(pattern: #"\[attachment=(?:"|")?(\d+)"#, options: .caseInsensitive) + let range = NSRange(text.startIndex..., in: text) + let ids = regex?.matches(in: text, range: range).compactMap { match -> Int? in + guard let idRange = Range(match.range(at: 1), in: text) else { return nil } + return Int(text[idRange]) + } ?? [] + return Set(ids) } +} diff --git a/Modules/Sources/QMSFeature/QMSScreen.swift b/Modules/Sources/QMSFeature/QMSScreen.swift index 15624e7e..8620f65d 100644 --- a/Modules/Sources/QMSFeature/QMSScreen.swift +++ b/Modules/Sources/QMSFeature/QMSScreen.swift @@ -10,78 +10,88 @@ import ComposableArchitecture import SharedUI import SFSafeSymbols import ExyteChat +import BBPanelFeature +import Models +import NukeUI @ViewAction(for: QMSFeature.self) public struct QMSScreen: 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() - + if store.chat != nil { - ChatView(messages: store.messages) { message in - // send(.sendMessageButtonTapped(message)) - } inputViewBuilder: { text, _, _, inputViewStyle, inputViewActionClosure, _ in - WithPerceptionTracking { - Group { + ChatView( + messages: store.messages, + messageBuilder: { message, positionInGroup, _, _, showContextMenu, _, showAttachment in + WithPerceptionTracking { + QMSMessageView( + message: message, + positionInGroup: positionInGroup, + nodes: store.nodes[message.id] ?? [], + files: store.files[message.id] ?? [], + onUrlTap: { url in send(.urlTapped(url)) }, + onAttachmentTap: showAttachment, + onLongPress: showContextMenu + ) + } + }, + inputViewBuilder: { _, _, _, inputViewStyle, _, _ in + WithPerceptionTracking { switch inputViewStyle { case .message: - InputView(text: text) + Composer() case .signature: EmptyView() } } - } - } messageMenuAction: { (action: ChatAction, _, message) in - if case .copy = action { - UIPasteboard.general.string = message.text - } - } + }, + messageMenuAction: { (action: ChatAction, _, message) in + if case .copy = action { + UIPasteboard.general.string = message.text + } + }, + localization: Self.chatLocalization, + didSendMessage: { _ in } + ) .keyboardDismissMode(.interactive) .enableLoadMore { _ in await send(.loadMoreTriggered) } .linkPreviewsDisabled() - .messageUseStyler { string in - return QMSBuilder(text: string).build() - } .setAvailableInputs([.text]) .chatTheme( ChatTheme( - colors: ChatTheme - .Colors( - mainBG: backgroundColors.primary, - messageMyBG: Color(.Background.quaternary), - messageMyText: Color(.Labels.primary), - messageMyTimeText: Color(.systemGray), - messageFriendBG: Color(.Background.quaternary), - messageFriendText: Color(.Labels.primary), - messageFriendTimeText: Color(.systemGray), - statusGray: Color(.Theme.primary), - sendButtonBackground: Color(.Theme.primary) - ) + colors: ChatTheme.Colors( + mainBG: backgroundColors.primary, + messageMyBG: Color(.Background.quaternary), + messageMyText: Color(.Labels.primary), + messageMyTimeText: Color(.systemGray), + messageFriendBG: Color(.Background.quaternary), + messageFriendText: Color(.Labels.primary), + messageFriendTimeText: Color(.systemGray), + statusGray: Color(.Theme.primary), + sendButtonBackground: Color(.Theme.primary) + ) ) ) - .environment(\.openURL, OpenURLAction(handler: { url in - send(.urlTapped(url)) - return .handled - })) } else { PDALoader() .frame(width: 24, height: 24) @@ -95,48 +105,272 @@ public struct QMSScreen: View { } } } - - private func InputView(text: Binding) -> some View { - HStack { - #if DEBUG - if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" { - Button(String("+")) { text.wrappedValue += "text" } - .buttonStyle(.borderedProminent) + + // MARK: - Composer + + @ViewBuilder + private func Composer() -> some View { + VStack(spacing: 8) { + if store.isBBPanelShown { + BBPanelView(store: store.scope(\.bbPanel, action: \.bbPanel)) + .transition(.move(edge: .bottom).combined(with: .opacity)) + } else if !store.bbPanel.existsFiles.isEmpty { + AttachedFilesBadge() } - #endif - - TextField(String(""), text: text, prompt: Text("qms.textfield.placeholder", bundle: .module)) - .padding() - .background(Color(.Background.quaternary), in: .rect(cornerRadius: 16)) - - Button { - if !text.wrappedValue.isEmpty { - send(.sendMessageButtonTapped( - DraftMessage(text: text.wrappedValue, medias: [], giphyMedia: nil, recording: nil, replyMessage: nil, createdAt: .now) - )) + + HStack(alignment: .bottom, spacing: 8) { + Button { + send(.bbPanelButtonTapped) + } label: { + Image(systemSymbol: store.isBBPanelShown ? .xmark : .paperclip) + .font(.body.weight(.semibold)) + .foregroundStyle(tintColor) + .frame(width: 44, height: 44) + .background(Color(.Background.quaternary), in: Circle()) } - } label: { - Circle() - .tint(Color(.Theme.primary)) - .frame(width: 44, height: 44) - .overlay { - if store.isSending { - ProgressView() - .progressViewStyle(.circular) - .tint(.white) - } else { - Image(systemSymbol: .arrowUp) - .bold() - .tint(.white) + + SelectableTextView( + content: $store.draftText, + selection: $store.textRange, + placeholder: LocalizedStringResource("qms.textfield.placeholder", bundle: .module), + isFocused: $store.isInputFocused + ) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 14) + .padding(.vertical, 11) + .frame(minHeight: 44) + .background(Color(.Background.quaternary), in: .rect(cornerRadius: 22)) + + Button { + send(.sendMessageButtonTapped) + } label: { + Circle() + .fill(store.canSend || store.isSending ? Color(.Theme.primary) : Color(.Labels.quintuple)) + .frame(width: 44, height: 44) + .overlay { + if store.isSending || store.bbPanel.isUploading { + ProgressView() + .progressViewStyle(.circular) + .tint(.white) + } else { + Image(systemSymbol: .arrowUp) + .bold() + .foregroundStyle(.white) + } } - } + } + .disabled(!store.canSend) } - .disabled(store.isSending) } - .padding() + .padding(.horizontal, 12) + .padding(.vertical, 8) .animation(.default, value: store.isSending) - .animation(.default, value: text.wrappedValue) - .bind(text, to: $store.draftText) + .animation(.default, value: store.isBBPanelShown) + } + + @ViewBuilder + private func AttachedFilesBadge() -> some View { + Button { + send(.bbPanelButtonTapped) + } label: { + HStack(spacing: 6) { + Image(systemSymbol: .paperclip) + Text("qms.attachments.count \(store.bbPanel.existsFiles.count)", bundle: .module) + } + .font(.footnote.weight(.medium)) + .foregroundStyle(tintColor) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(Color(.Background.quaternary), in: Capsule()) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + + // MARK: - Localization + + private static let chatLocalization = ChatLocalization( + inputPlaceholder: "", + signatureText: "", + cancelButtonText: String(localized: "Cancel", bundle: .module), + recentToggleText: "", + waitingForNetwork: "", + recordingText: "", + replyToText: "" + ) +} + +// MARK: - Message View + +struct QMSMessageView: View { + + @Environment(\.tintColor) private var tintColor + + let message: ExyteChat.Message + let positionInGroup: PositionInUserGroup + let nodes: [UITopicType] + let files: [Models.Attachment] + let onUrlTap: (URL) -> Void + let onAttachmentTap: (ExyteChat.Attachment) -> Void + let onLongPress: () -> Void + + private static let avatarSize: CGFloat = 32 + + private var isCurrentUser: Bool { message.user.isCurrentUser } + + /// Avatar is shown once per group of consecutive messages, next to the last one + private var isLastInGroup: Bool { + positionInGroup == .last || positionInGroup == .single + } + + private var isFirstInGroup: Bool { + positionInGroup == .first || positionInGroup == .single + } + + var body: some View { + HStack(alignment: .bottom, spacing: 8) { + if isCurrentUser { + Spacer(minLength: 48) + } else { + Avatar() + } + + VStack(alignment: .leading, spacing: 6) { + if !message.attachments.isEmpty { + Images() + } + + ForEach(files, id: \.id) { file in + FileRow(file) + } + + if let plainText { + // Simple text hugs its content and keeps time on the same line + HStack(alignment: .lastTextBaseline, spacing: 8) { + Text(plainText) + .environment(\.openURL, OpenURLAction { url in + onUrlTap(url) + return .handled + }) + TimeLabel() + } + } else { + ForEach(nodes, id: \.self) { node in + TopicView(type: node, nestLevel: 3, userSession: nil, onUrlTap: onUrlTap) + } + + HStack(spacing: 0) { + Spacer(minLength: 0) + TimeLabel() + } + } + } + .padding(.horizontal, 12) + .padding(.vertical, 7) + .background( + isCurrentUser ? AnyShapeStyle(tintColor.opacity(0.15)) : AnyShapeStyle(Color(.Background.quaternary)), + in: .rect(cornerRadius: 18) + ) + .contentShape(.rect(cornerRadius: 18)) + .onLongPressGesture(perform: onLongPress) + + if !isCurrentUser { Spacer(minLength: 40) } + } + .padding(.horizontal, 12) + .padding(.top, isFirstInGroup ? 6 : 1) + .padding(.bottom, 1) + } + + /// Message that is just a formatted text (no quotes, code, spoilers etc.) + private var plainText: AttributedString? { + guard nodes.count == 1, case let .text(text) = nodes[0] else { return nil } + return text + } + + // MARK: - Time + + @ViewBuilder + private func TimeLabel() -> some View { + HStack(spacing: 3) { + Text(message.createdAt, style: .time) + if isCurrentUser, let status = message.status { + Image(systemSymbol: status == .read ? .checkmarkCircleFill : .checkmarkCircle) + .foregroundStyle(tintColor) + } + } + .font(.caption2) + .foregroundStyle(Color(.systemGray)) + .fixedSize() + } + + // MARK: - Avatar + + @ViewBuilder + private func Avatar() -> some View { + if isLastInGroup, let url = message.user.avatarURL { + LazyImage(url: url) { state in + if let image = state.image { + image.resizable().scaledToFill() + } else { + Color(.Labels.quintuple).opacity(0.3) + } + } + .frame(width: Self.avatarSize, height: Self.avatarSize) + .clipShape(Circle()) + } else { + Color.clear.frame(width: Self.avatarSize, height: Self.avatarSize) + } + } + + // MARK: - Images + + @ViewBuilder + private func Images() -> some View { + VStack(spacing: 4) { + ForEach(message.attachments) { attachment in + AsyncImage(url: attachment.thumbnail) { phase in + if let image = phase.image { + image.resizable().scaledToFit() + } else { + Color(.Labels.quintuple).opacity(0.2) + .frame(height: 160) + .overlay { ProgressView() } + } + } + .frame(maxWidth: 260) + .clipShape(.rect(cornerRadius: 12)) + .onTapGesture { + onAttachmentTap(attachment) + } + } + } + } + + // MARK: - File Row + + @ViewBuilder + private func FileRow(_ file: Models.Attachment) -> some View { + Button { + let link = "https://4pda.to/forum/dl/post/\(file.id)/\(file.name)" + if let url = URL(string: link.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? link) { + onUrlTap(url) + } + } label: { + HStack(spacing: 8) { + Image(systemSymbol: .arrowDownDoc) + .font(.title3) + .foregroundStyle(tintColor) + VStack(alignment: .leading, spacing: 2) { + Text(file.name) + .font(.subheadline) + .foregroundStyle(Color(.Labels.primary)) + .lineLimit(2) + Text(file.sizeString) + .font(.caption) + .foregroundStyle(Color(.Labels.teritary)) + } + } + } + .buttonStyle(.plain) } } @@ -145,7 +379,7 @@ public struct QMSScreen: View { #Preview { @Shared(.userSession) var userSession $userSession.withLock { $0 = .init(userId: 1, token: "", isHidden: false) } - + return NavigationStack { QMSScreen( store: Store( @@ -153,7 +387,7 @@ public struct QMSScreen: View { ) { QMSFeature() } withDependencies: { _ in - + } ) } @@ -164,7 +398,7 @@ public struct QMSScreen: View { #Preview("Error On Send") { @Shared(.userSession) var userSession $userSession.withLock { $0 = .init(userId: 1, token: "", isHidden: false) } - + return QMSScreen( store: Store(initialState: QMSFeature.State(chatId: 0)) { QMSFeature() diff --git a/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings b/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings index 541e4af4..4a12695d 100644 --- a/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings @@ -1,6 +1,16 @@ { "sourceLanguage" : "en", "strings" : { + "Cancel" : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отмена" + } + } + } + }, "Copy" : { "localizations" : { "en" : { @@ -17,6 +27,22 @@ } } }, + "qms.attachments.count %lld" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Files: %lld" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файлов: %lld" + } + } + } + }, "qms.textfield.placeholder" : { "localizations" : { "en" : { @@ -35,4 +61,4 @@ } }, "version" : "1.1" -} \ No newline at end of file +} diff --git a/Modules/Sources/SharedUI/Field.swift b/Modules/Sources/SharedUI/Field.swift index 5ad9319c..ab5b19d3 100644 --- a/Modules/Sources/SharedUI/Field.swift +++ b/Modules/Sources/SharedUI/Field.swift @@ -181,15 +181,31 @@ public struct FieldContainer: View { // MARK: - Selectable Text View -private struct SelectableTextView: UIViewRepresentable { +public struct SelectableTextView: UIViewRepresentable { @Binding var content: String @Binding var selection: NSRange? let placeholder: LocalizedStringResource let characterLimit: Int? + /// Optional focus control, e.g. to show keyboard after inserting a BB tag + let isFocused: Binding? + + public init( + content: Binding, + selection: Binding, + placeholder: LocalizedStringResource, + characterLimit: Int? = nil, + isFocused: Binding? = nil + ) { + self._content = content + self._selection = selection + self.placeholder = placeholder + self.characterLimit = characterLimit + self.isFocused = isFocused + } static let placeholderColor = UIColor.lightGray - func makeUIView(context: Context) -> UITextView { + public func makeUIView(context: Context) -> UITextView { let view = UITextView() view.text = content.isEmpty ? String(localized: placeholder) : content view.textColor = content.isEmpty ? Self.placeholderColor : UIColor.label @@ -198,13 +214,16 @@ private struct SelectableTextView: UIViewRepresentable { view.textContainer.lineFragmentPadding = 0 view.textContainerInset = .zero view.isScrollEnabled = false + // BB-codes need plain quotes and dashes, e.g. [url="..."] + view.smartQuotesType = .no + view.smartDashesType = .no view.font = UIFont.preferredFont(forTextStyle: .body) return view } - func updateUIView(_ uiView: UITextView, context: Context) { + public func updateUIView(_ uiView: UITextView, context: Context) { if content.isEmpty { if !uiView.isFirstResponder { let placeholderText = String(localized: placeholder) @@ -214,6 +233,9 @@ private struct SelectableTextView: UIViewRepresentable { } uiView.textColor = Self.placeholderColor + } else if uiView.textColor != Self.placeholderColor, !uiView.text.isEmpty { + // Content was cleared externally while editing (e.g. after sending) + uiView.text = "" } } else { if uiView.text != content { @@ -228,9 +250,13 @@ private struct SelectableTextView: UIViewRepresentable { uiView.selectedRange != externalSelection { uiView.selectedRange = externalSelection } + + if isFocused?.wrappedValue == true, !uiView.isFirstResponder { + DispatchQueue.main.async { uiView.becomeFirstResponder() } + } } - func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextView, context: Context) -> CGSize? { + public func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextView, context: Context) -> CGSize? { guard let width = proposal.width else { return nil } let size = uiView.sizeThatFits( CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) @@ -238,56 +264,62 @@ private struct SelectableTextView: UIViewRepresentable { return CGSize(width: width, height: ceil(size.height)) } - func makeCoordinator() -> Coordinator { + public func makeCoordinator() -> Coordinator { return Coordinator( content: $content, selection: $selection, characterLimit: characterLimit, - placeholder: placeholder + placeholder: placeholder, + isFocused: isFocused ) } - final class Coordinator: NSObject, UITextViewDelegate { + public final class Coordinator: NSObject, UITextViewDelegate { var content: Binding var selection: Binding let characterLimit: Int? let placeholder: LocalizedStringResource + let isFocused: Binding? init( content: Binding, selection: Binding, characterLimit: Int?, - placeholder: LocalizedStringResource + placeholder: LocalizedStringResource, + isFocused: Binding? = nil ) { self.content = content self.selection = selection self.characterLimit = characterLimit self.placeholder = placeholder + self.isFocused = isFocused } - func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText: String) -> Bool { + public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText: String) -> Bool { if let characterLimit = characterLimit { return textView.text.count + replacementText.count <= characterLimit } return true } - func textViewDidChangeSelection(_ textView: UITextView) { + public func textViewDidChangeSelection(_ textView: UITextView) { selection.wrappedValue = textView.selectedRange } - func textViewDidChange(_ textView: UITextView) { + public func textViewDidChange(_ textView: UITextView) { content.wrappedValue = textView.text } - func textViewDidBeginEditing(_ textView: UITextView) { + public func textViewDidBeginEditing(_ textView: UITextView) { + if isFocused?.wrappedValue == false { isFocused?.wrappedValue = true } if textView.textColor == placeholderColor { textView.text = nil textView.textColor = UIColor.label } } - func textViewDidEndEditing(_ textView: UITextView) { + public func textViewDidEndEditing(_ textView: UITextView) { + if isFocused?.wrappedValue == true { isFocused?.wrappedValue = false } if textView.text.isEmpty { textView.text = String(localized: placeholder) textView.textColor = placeholderColor diff --git a/Modules/Sources/UploadBoxFeature/Resources/Localizable.xcstrings b/Modules/Sources/UploadBoxFeature/Resources/Localizable.xcstrings index 065a21cf..57bcfb48 100644 --- a/Modules/Sources/UploadBoxFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/UploadBoxFeature/Resources/Localizable.xcstrings @@ -141,6 +141,16 @@ } } }, + "The selected files will be sent along with the message." : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбранные файлы будут отправлены вместе с сообщением." + } + } + } + }, "Try Again" : { "localizations" : { "ru" : { diff --git a/Modules/Sources/UploadBoxFeature/UploadBoxFeature.swift b/Modules/Sources/UploadBoxFeature/UploadBoxFeature.swift index 0f269b82..3d86c2eb 100644 --- a/Modules/Sources/UploadBoxFeature/UploadBoxFeature.swift +++ b/Modules/Sources/UploadBoxFeature/UploadBoxFeature.swift @@ -61,6 +61,8 @@ public struct UploadBoxFeature: Reducer, Sendable { @Presents public var destination: Destination.State? let type: UploadBoxType + /// Files for private messages are uploaded to a separate QMS storage + public var isQms = false public var allowedExtensions: [String] public var files: [UploadBoxFile] @@ -337,7 +339,7 @@ public struct UploadBoxFeature: Reducer, Sendable { case let .internal(.uploadFile(file, url)): state.isAnyFileUploading = true - return .run(priority: .userInitiated, name: file.name) { send in + return .run(priority: .userInitiated, name: file.name) { [isQms = state.isQms] send in if file.type == .file { guard url.startAccessingSecurityScopedResource() else { await send(.view(.fileUploadCanceled(file.id, .noAccessToSSR))) @@ -358,7 +360,7 @@ public struct UploadBoxFeature: Reducer, Sendable { return } - let request = UploadRequest(fileName: file.name, fileData: data, isQms: false) + let request = UploadRequest(fileName: file.name, fileData: data, isQms: isQms) await send(.delegate(.someFileUploading)) diff --git a/Modules/Sources/UploadBoxFeature/UploadBoxView.swift b/Modules/Sources/UploadBoxFeature/UploadBoxView.swift index b4946272..c139f23f 100644 --- a/Modules/Sources/UploadBoxFeature/UploadBoxView.swift +++ b/Modules/Sources/UploadBoxFeature/UploadBoxView.swift @@ -147,8 +147,14 @@ public struct UploadBoxView: View { .font(.body) .foregroundStyle(Color(.Labels.teritary)) - Text("The selected file will be inserted into the text as code wherever your cursor is located. Or it will also be automatically added to the end of the post.", bundle: .module) - .font(.footnote) + Group { + if store.isQms { + Text("The selected files will be sent along with the message.", bundle: .module) + } else { + Text("The selected file will be inserted into the text as code wherever your cursor is located. Or it will also be automatically added to the end of the post.", bundle: .module) + } + } + .font(.footnote) .foregroundStyle(Color(.Labels.teritary)) } .padding(.leading, 6) diff --git a/Project.swift b/Project.swift index 785371eb..9005586c 100644 --- a/Project.swift +++ b/Project.swift @@ -523,12 +523,15 @@ let project = Project( .Internal.APIClient, .Internal.AnalyticsClient, .Internal.BBBuilder, + .Internal.BBPanelFeature, .Internal.Models, .Internal.NotificationsClient, .Internal.PersistenceKeys, .Internal.QMSClient, .Internal.SharedUI, .Internal.TCAExtensions, + .Internal.TopicBuilder, + .Internal.UploadBoxFeature, .SPM.ExyteChat, .SPM.NukeUI, .SPM.SFSafeSymbols,