mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 07:58:02 +00:00
android, desktop, ios: copy markdown files with line breaks, and the whole file with one button (#8269)
* android, desktop: test copying lines from the markdown text view * android, desktop: keep line breaks in text copied from markdown files * android, desktop: check the last copied text in the markdown view test * android, desktop, ios: button to copy the whole markdown file * android, desktop: test the markdown file copy button * android, desktop, ios: ask before copying markdown files over 128 KB * android, desktop, ios: title the markdown copy alerts File too large * ios: test the markdown file copy button * android, desktop, ios: preview the markdown file view and test the copy limit * android, desktop, ios: snapshot references of the markdown file view
This commit is contained in:
1 parent
1966ac32e3
commit
d08e249ea5
12 files changed
+294
-16
No files matched your search
@@ -3,6 +3,7 @@ import SimpleXChat
|
||||
import Ink
|
||||
|
||||
private let MAX_MARKDOWN_VIEW_SIZE: Int64 = 1_048_576
|
||||
private let MAX_MARKDOWN_COPY_SIZE: Int64 = 131_072
|
||||
private let MAX_MARKDOWN_LINE_LENGTH = 15_000
|
||||
private let MAX_MARKDOWN_NESTING = 16
|
||||
private let MAX_MARKDOWN_LINK_NESTING = 4
|
||||
@@ -27,7 +28,7 @@ func showMarkdownFile(_ file: CIFile) {
|
||||
let hasBidiControls = text.unicodeScalars.contains(where: isBidiControl)
|
||||
await MainActor.run {
|
||||
showAppSheet {
|
||||
MarkdownFileView(file: file, fileSource: fileSource, lines: shownLines, html: html, hasBidiControls: hasBidiControls)
|
||||
MarkdownFileView(file: file, fileSource: fileSource, text: text, lines: shownLines, html: html, hasBidiControls: hasBidiControls)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -166,10 +167,31 @@ private func openMarkdownFileLink(_ url: URL) {
|
||||
}
|
||||
}
|
||||
|
||||
func copyMarkdownFile(_ file: CIFile, _ text: String) {
|
||||
if file.fileSize > MAX_MARKDOWN_COPY_SIZE {
|
||||
showAlert(
|
||||
NSLocalizedString("File too large", comment: "alert title"),
|
||||
message: String.localizedStringWithFormat(
|
||||
NSLocalizedString("Your file is %@. Do you want to copy it?", comment: "alert message"),
|
||||
ByteCountFormatter.string(fromByteCount: file.fileSize, countStyle: .binary)
|
||||
),
|
||||
actions: {[
|
||||
cancelAlertAction,
|
||||
UIAlertAction(title: NSLocalizedString("Copy", comment: "alert button"), style: .default) { _ in
|
||||
UIPasteboard.general.string = text
|
||||
}
|
||||
]}
|
||||
)
|
||||
} else {
|
||||
UIPasteboard.general.string = text
|
||||
}
|
||||
}
|
||||
|
||||
struct MarkdownFileView: View {
|
||||
@AppStorage(DEFAULT_MARKDOWN_FILE_TEXT_VIEW) private var textView = false
|
||||
let file: CIFile
|
||||
let fileSource: CryptoFile
|
||||
let text: String
|
||||
let lines: [String]
|
||||
let html: String?
|
||||
let hasBidiControls: Bool
|
||||
@@ -203,6 +225,11 @@ struct MarkdownFileView: View {
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItemGroup(placement: .navigationBarTrailing) {
|
||||
Button {
|
||||
copyMarkdownFile(file, text)
|
||||
} label: {
|
||||
Image(systemName: "doc.on.doc")
|
||||
}
|
||||
if html != nil {
|
||||
Button {
|
||||
textView.toggle()
|
||||
@@ -221,3 +248,17 @@ struct MarkdownFileView: View {
|
||||
.navigationViewStyle(.stack)
|
||||
}
|
||||
}
|
||||
|
||||
struct MarkdownFileView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let text = "# Release notes\n\n- markdown files in chats\n- a button to copy the file\n"
|
||||
MarkdownFileView(
|
||||
file: CIFile.getSample(fileName: "notes.md", fileSize: Int64(text.utf8.count), filePath: "notes.md"),
|
||||
fileSource: CryptoFile.plain("notes.md"),
|
||||
text: text,
|
||||
lines: text.components(separatedBy: "\n"),
|
||||
html: nil,
|
||||
hasBidiControls: false
|
||||
)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
@@ -728,6 +728,7 @@ private func previewScenes() -> [SnapshotScene] {
|
||||
SnapshotScene(IntegrityErrorItemView_Previews.self, allSizes: true),
|
||||
SnapshotScene(LargeLinkPreview_Previews.self, allSizes: true),
|
||||
SnapshotScene(LocalAuthView_Previews.self),
|
||||
SnapshotScene(MarkdownFileView_Previews.self, device: true),
|
||||
SnapshotScene(MarkdownHelp_Previews.self),
|
||||
SnapshotScene(MarkedDeletedItemView_Previews.self, allSizes: true),
|
||||
SnapshotScene(MemberAdmissionView_Previews.self),
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import XCTest
|
||||
import UIKit
|
||||
@testable import SimpleX
|
||||
@testable import SimpleXChat
|
||||
|
||||
final class MarkdownFileTests: XCTestCase {
|
||||
@MainActor
|
||||
func testCopyAsksAbove128KB() async throws {
|
||||
let text = "alpha\n\ngamma"
|
||||
UIPasteboard.general.string = "unchanged"
|
||||
copyMarkdownFile(CIFile.getSample(fileSize: 131_072), text)
|
||||
XCTAssertEqual(UIPasteboard.general.string, text)
|
||||
UIPasteboard.general.string = "unchanged"
|
||||
copyMarkdownFile(CIFile.getSample(fileSize: 131_073), text)
|
||||
try await waitFor { (getTopViewController() as? UIAlertController)?.isBeingPresented == false }
|
||||
let alert = try XCTUnwrap(getTopViewController() as? UIAlertController)
|
||||
XCTAssertEqual(alert.title, "File too large")
|
||||
XCTAssertEqual(alert.message, "Your file is 128 KB. Do you want to copy it?")
|
||||
XCTAssertEqual(UIPasteboard.general.string, "unchanged")
|
||||
let copy = try XCTUnwrap(alert.actions.first { $0.title == "Copy" })
|
||||
let handler = unsafeBitCast(copy.value(forKey: "handler") as AnyObject, to: (@convention(block) (UIAlertAction) -> Void).self)
|
||||
await withCheckedContinuation { done in alert.dismiss(animated: false) { done.resume() } }
|
||||
handler(copy)
|
||||
XCTAssertEqual(UIPasteboard.general.string, text)
|
||||
}
|
||||
}
|
||||
@@ -272,6 +272,7 @@
|
||||
E5AEC0C22F9C000100270665 /* SnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5AEC0C12F9C000100270665 /* SnapshotTests.swift */; };
|
||||
4E57A1E70000000000000006 /* NameAlertsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E57A1E70000000000000005 /* NameAlertsTests.swift */; };
|
||||
4E57A1E70000000000000014 /* ChatItemUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */; };
|
||||
6D4F1C2A9B3E000000000002 /* MarkdownFileTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */; };
|
||||
E5AEC0AF2F91A73500270665 /* ComposeChatLinkView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5AEC0AE2F91A73500270665 /* ComposeChatLinkView.swift */; };
|
||||
E5C0BBE82F82B45500EA7527 /* SimpleXAssets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E5C0BBE72F82B45500EA7527 /* SimpleXAssets.xcassets */; };
|
||||
E5C0BBEB2F82B45500EA7527 /* SharedAssets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E5C0BBEA2F82B45500EA7527 /* SharedAssets.xcassets */; };
|
||||
@@ -684,6 +685,7 @@
|
||||
E5AEC0C32F9C000100270665 /* SimpleX Snapshots.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SimpleX Snapshots.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
4E57A1E70000000000000005 /* NameAlertsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NameAlertsTests.swift; sourceTree = "<group>"; };
|
||||
4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatItemUpdateTests.swift; sourceTree = "<group>"; };
|
||||
6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownFileTests.swift; sourceTree = "<group>"; };
|
||||
4E57A1E70000000000000007 /* SimpleX Unit Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SimpleX Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
E5AEC0AE2F91A73500270665 /* ComposeChatLinkView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposeChatLinkView.swift; sourceTree = "<group>"; };
|
||||
E5C0BBE72F82B45500EA7527 /* SimpleXAssets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = SimpleXAssets.xcassets; sourceTree = "<group>"; };
|
||||
@@ -1038,6 +1040,7 @@
|
||||
children = (
|
||||
4E57A1E70000000000000005 /* NameAlertsTests.swift */,
|
||||
4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */,
|
||||
6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */,
|
||||
);
|
||||
path = "SimpleX Unit Tests";
|
||||
sourceTree = "<group>";
|
||||
@@ -1926,6 +1929,7 @@
|
||||
files = (
|
||||
4E57A1E70000000000000006 /* NameAlertsTests.swift in Sources */,
|
||||
4E57A1E70000000000000014 /* ChatItemUpdateTests.swift in Sources */,
|
||||
6D4F1C2A9B3E000000000002 /* MarkdownFileTests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
|
||||
+83
-15
@@ -1,18 +1,22 @@
|
||||
package chat.simplex.common.views.chat.item
|
||||
|
||||
import SectionBottomSpacer
|
||||
import androidx.compose.desktop.ui.tooling.preview.Preview
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyListScope
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.painter.BitmapPainter
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalUriHandler
|
||||
import androidx.compose.ui.platform.UriHandler
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
@@ -25,6 +29,7 @@ import chat.simplex.common.model.*
|
||||
import chat.simplex.common.model.ChatController.appPrefs
|
||||
import chat.simplex.common.platform.*
|
||||
import chat.simplex.common.ui.theme.DEFAULT_PADDING
|
||||
import chat.simplex.common.ui.theme.SimpleXTheme
|
||||
import chat.simplex.common.ui.theme.WarningOrange
|
||||
import chat.simplex.common.views.chat.topPaddingToContent
|
||||
import chat.simplex.common.views.helpers.*
|
||||
@@ -41,6 +46,7 @@ import dev.icerock.moko.resources.compose.painterResource
|
||||
import dev.icerock.moko.resources.compose.stringResource
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.intellij.markdown.MarkdownElementTypes
|
||||
import org.intellij.markdown.ast.ASTNode
|
||||
@@ -56,6 +62,8 @@ import java.util.Base64
|
||||
private const val DATA_IMAGE = "data:image/"
|
||||
private val IMAGE_TYPES = listOf(ImageFileType.JPEG, ImageFileType.PNG)
|
||||
private const val MAX_MARKDOWN_VIEW_SIZE: Long = 1_048_576
|
||||
private const val MAX_MARKDOWN_COPY_SIZE = 131_072
|
||||
private const val MAX_ANDROID_COPY_SIZE = 524_288
|
||||
private const val MAX_MARKDOWN_LINE_LENGTH = 15_000
|
||||
private const val MAX_MARKDOWN_DEPTH = 32
|
||||
private const val MAX_MARKDOWN_TABLE_ROWS = 200
|
||||
@@ -67,7 +75,9 @@ private val bidiControlChar = Regex("[\\u061C\\u200E\\u200F\\u202A-\\u202E\\u206
|
||||
|
||||
private val invisibleCharMarkerStyle = SpanStyle(color = WarningOrange)
|
||||
|
||||
private class MarkdownDocument(val lines: List<String>, val formatted: State.Success?, val hasBidiControls: Boolean)
|
||||
internal class MarkdownLine(val text: String, val lineBreak: Boolean)
|
||||
|
||||
internal class MarkdownDocument(val text: String, val lines: List<MarkdownLine>, val formatted: State.Success?, val hasBidiControls: Boolean)
|
||||
|
||||
fun isMarkdownFile(file: CIFile): Boolean =
|
||||
file.fileSize <= MAX_MARKDOWN_VIEW_SIZE && file.fileName.substringAfterLast('.', "").lowercase() in listOf("md", "markdown")
|
||||
@@ -90,26 +100,31 @@ fun showMarkdownFile(file: CIFile) {
|
||||
AlertManager.shared.showAlertMsg(generalGetString(MR.strings.error), e.message)
|
||||
return@withLongRunningApi
|
||||
}
|
||||
val text = decodedText(bytes)
|
||||
val lines = text.lines()
|
||||
val formatted = if (lines.all { it.length <= MAX_MARKDOWN_LINE_LENGTH }) formattedWithinLimits(text) else null
|
||||
val document = MarkdownDocument(
|
||||
lines.flatMap { line -> line.chunked(MAX_MARKDOWN_LINE_LENGTH).ifEmpty { listOf("") } },
|
||||
formatted,
|
||||
bidiControlChar.containsMatchIn(text)
|
||||
)
|
||||
val document = markdownDocument(bytes)
|
||||
withContext(Dispatchers.Main) {
|
||||
if (appPlatform.isDesktop && ModalManager.center.isTopModalOpen(ModalViewId.MARKDOWN_FILE)) ModalManager.center.closeModal()
|
||||
ModalManager.center.showModal(id = ModalViewId.MARKDOWN_FILE, endButtons = {
|
||||
if (formatted != null) MarkdownViewSwitch()
|
||||
MarkdownFileSaveButton(file, bytes)
|
||||
}) {
|
||||
ModalManager.center.showModal(id = ModalViewId.MARKDOWN_FILE, endButtons = { MarkdownFileButtons(file, bytes, document) }) {
|
||||
key(this) { MarkdownFileView(file.fileName, document) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun markdownDocument(bytes: ByteArray): MarkdownDocument {
|
||||
val text = decodedText(bytes)
|
||||
val lines = text.lines()
|
||||
val formatted = if (lines.all { it.length <= MAX_MARKDOWN_LINE_LENGTH }) formattedWithinLimits(text) else null
|
||||
return MarkdownDocument(
|
||||
text,
|
||||
lines.flatMapIndexed { i, line ->
|
||||
val chunks = line.chunked(MAX_MARKDOWN_LINE_LENGTH).ifEmpty { listOf("") }
|
||||
chunks.mapIndexed { j, chunk -> MarkdownLine(chunk, lineBreak = i < lines.lastIndex && j == chunks.lastIndex) }
|
||||
},
|
||||
formatted,
|
||||
bidiControlChar.containsMatchIn(text)
|
||||
)
|
||||
}
|
||||
|
||||
private fun decodedText(bytes: ByteArray): String =
|
||||
Charsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPLACE)
|
||||
@@ -145,6 +160,39 @@ private fun MarkdownViewSwitch() {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MarkdownFileButtons(file: CIFile, bytes: ByteArray, document: MarkdownDocument) {
|
||||
MarkdownFileCopyButton(document.text, bytes.size, if (appPlatform.isAndroid) MAX_ANDROID_COPY_SIZE else null)
|
||||
if (document.formatted != null) MarkdownViewSwitch()
|
||||
MarkdownFileSaveButton(file, bytes)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun MarkdownFileCopyButton(text: String, fileSize: Int, maxSize: Int?) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
IconButton({
|
||||
val copy = {
|
||||
clipboard.setText(AnnotatedString(text))
|
||||
showToast(generalGetString(MR.strings.copied))
|
||||
}
|
||||
when {
|
||||
maxSize != null && fileSize > maxSize -> AlertManager.shared.showAlertMsg(
|
||||
generalGetString(MR.strings.markdown_file_too_large),
|
||||
String.format(generalGetString(MR.strings.markdown_file_copy_limit), formatBytes(maxSize.toLong()))
|
||||
)
|
||||
fileSize > MAX_MARKDOWN_COPY_SIZE -> AlertManager.shared.showAlertDialog(
|
||||
title = generalGetString(MR.strings.markdown_file_too_large),
|
||||
text = String.format(generalGetString(MR.strings.markdown_file_copy_large), formatBytes(fileSize.toLong())),
|
||||
confirmText = generalGetString(MR.strings.copy_verb),
|
||||
onConfirm = copy
|
||||
)
|
||||
else -> copy()
|
||||
}
|
||||
}) {
|
||||
Icon(painterResource(MR.images.ic_content_copy), stringResource(MR.strings.copy_verb), tint = MaterialTheme.colors.primary)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MarkdownFileSaveButton(file: CIFile, bytes: ByteArray) {
|
||||
val saveFileLauncher = rememberFileChooserLauncher(false, bytes) { to: URI? ->
|
||||
@@ -156,14 +204,17 @@ private fun MarkdownFileSaveButton(file: CIFile, bytes: ByteArray) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MarkdownFileView(fileName: String, document: MarkdownDocument) {
|
||||
internal fun MarkdownFileView(fileName: String, document: MarkdownDocument) {
|
||||
val textView = remember { appPrefs.markdownFileTextView.state }
|
||||
val formatted = document.formatted
|
||||
if (textView.value || formatted == null) {
|
||||
SelectionContainer {
|
||||
MarkdownFileColumn(fileName, document.hasBidiControls) {
|
||||
items(document.lines) { line ->
|
||||
Text(remember(line) { withInvisibleCharMarkers(line) }, Modifier.padding(horizontal = DEFAULT_PADDING), fontFamily = FontFamily.Monospace)
|
||||
Box(Modifier.padding(horizontal = DEFAULT_PADDING)) {
|
||||
Text(remember(line) { withInvisibleCharMarkers(line.text) }, fontFamily = FontFamily.Monospace)
|
||||
if (line.lineBreak) SelectableLineBreak()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,6 +223,11 @@ private fun MarkdownFileView(fileName: String, document: MarkdownDocument) {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BoxScope.SelectableLineBreak() {
|
||||
Text("\n", Modifier.align(Alignment.BottomEnd).height(1.dp).clearAndSetSemantics {})
|
||||
}
|
||||
|
||||
private fun withInvisibleCharMarkers(line: String): AnnotatedString = buildAnnotatedString {
|
||||
var start = 0
|
||||
invisibleChar.findAll(line).forEach {
|
||||
@@ -294,3 +350,15 @@ private fun hasImageSignature(base64: String): Boolean {
|
||||
val header = runCatching { Base64.getDecoder().decode(base64.take(12)) }.getOrNull() ?: return false
|
||||
return IMAGE_TYPES.any { it.matches(header) }
|
||||
}
|
||||
|
||||
@Preview
|
||||
@Composable
|
||||
fun PreviewMarkdownFileView() {
|
||||
val bytes = remember { "# Release notes\n\n- markdown files in chats\n- a button to copy the file\n".encodeToByteArray() }
|
||||
val document = remember { runBlocking { markdownDocument(bytes) } }
|
||||
SimpleXTheme {
|
||||
ModalView(close = {}, endButtons = { MarkdownFileButtons(CIFile.getSample(fileName = "notes.md"), bytes, document) }) {
|
||||
MarkdownFileView("notes.md", document)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -721,6 +721,9 @@
|
||||
<string name="markdown_formatted_view">Formatted view</string>
|
||||
<string name="markdown_text_view">Text view</string>
|
||||
<string name="markdown_file_bidi_warning">This file has text direction characters. The text can be shown in a different order than it is written.</string>
|
||||
<string name="markdown_file_too_large">File too large</string>
|
||||
<string name="markdown_file_copy_limit">Only files up to %s can be copied. Save the file to open it in another app.</string>
|
||||
<string name="markdown_file_copy_large">Your file is %s. Do you want to copy it?</string>
|
||||
<string name="loading_remote_file_title">Loading the file </string>
|
||||
<string name="loading_remote_file_desc">Please, wait while the file is being loaded from the linked mobile</string>
|
||||
<string name="file_error">File error</string>
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package chat.simplex.app
|
||||
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.platform.ClipEntry
|
||||
import androidx.compose.ui.platform.Clipboard
|
||||
import androidx.compose.ui.platform.ClipboardManager
|
||||
import androidx.compose.ui.platform.LocalClipboard
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.NativeClipboard
|
||||
import androidx.compose.ui.test.ExperimentalTestApi
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performKeyInput
|
||||
import androidx.compose.ui.test.performMouseInput
|
||||
import androidx.compose.ui.test.pressKey
|
||||
import androidx.compose.ui.test.runComposeUiTest
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import chat.simplex.common.model.ChatController.appPrefs
|
||||
import chat.simplex.common.simplexWindowState
|
||||
import chat.simplex.common.views.chat.item.MarkdownFileCopyButton
|
||||
import chat.simplex.common.views.chat.item.MarkdownFileView
|
||||
import chat.simplex.common.views.chat.item.markdownDocument
|
||||
import chat.simplex.common.views.helpers.AlertManager
|
||||
import chat.simplex.common.views.helpers.LocalAppBarHandler
|
||||
import chat.simplex.common.views.helpers.rememberAppBarHandler
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.awt.datatransfer.DataFlavor
|
||||
import java.awt.datatransfer.Transferable
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
|
||||
@OptIn(ExperimentalTestApi::class)
|
||||
class MarkdownFileViewTest {
|
||||
@Test
|
||||
fun copiedSelectionKeepsLineBreaks() = runComposeUiTest {
|
||||
val textView = appPrefs.markdownFileTextView.get()
|
||||
appPrefs.markdownFileTextView.set(true)
|
||||
try {
|
||||
val clipboard = RecordingClipboard()
|
||||
val document = runBlocking { markdownDocument("alpha\n\ngamma".toByteArray()) }
|
||||
setContent {
|
||||
CompositionLocalProvider(LocalClipboard provides clipboard, LocalAppBarHandler provides rememberAppBarHandler()) {
|
||||
MarkdownFileView("test.md", document)
|
||||
}
|
||||
}
|
||||
val first = onNodeWithText("alpha").fetchSemanticsNode().boundsInRoot
|
||||
val last = onNodeWithText("gamma").fetchSemanticsNode().boundsInRoot
|
||||
onRoot().performMouseInput {
|
||||
moveTo(Offset(first.left + 1f, first.center.y))
|
||||
press()
|
||||
moveTo(Offset(last.right + 10f, last.center.y))
|
||||
release()
|
||||
}
|
||||
onRoot().performKeyInput { pressKey(Key.Copy) }
|
||||
waitForIdle()
|
||||
assertEquals("alpha\n\ngamma", clipboard.text)
|
||||
} finally {
|
||||
appPrefs.markdownFileTextView.set(textView)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun copyButtonWarnsAbove128KB() = runComposeUiTest {
|
||||
var copied: String? = null
|
||||
val clipboard = object : ClipboardManager {
|
||||
override fun setText(annotatedString: AnnotatedString) { copied = annotatedString.text }
|
||||
override fun getText(): AnnotatedString? = null
|
||||
}
|
||||
val document = runBlocking { markdownDocument("alpha\n\ngamma".toByteArray()) }
|
||||
var fileSize by mutableStateOf(131_072)
|
||||
try {
|
||||
setContent {
|
||||
CompositionLocalProvider(LocalClipboardManager provides clipboard) {
|
||||
MarkdownFileCopyButton(document.text, fileSize, null)
|
||||
}
|
||||
AlertManager.shared.showInView()
|
||||
}
|
||||
onNodeWithContentDescription("Copy").performClick()
|
||||
assertEquals("alpha\n\ngamma", copied)
|
||||
copied = null
|
||||
fileSize = 131_073
|
||||
onNodeWithContentDescription("Copy").performClick()
|
||||
onNodeWithText("Your file is 128 KB. Do you want to copy it?").assertExists()
|
||||
assertNull(copied)
|
||||
onNodeWithText("Copy").performClick()
|
||||
assertEquals("alpha\n\ngamma", copied)
|
||||
} finally {
|
||||
AlertManager.shared.hideAllAlerts()
|
||||
simplexWindowState.toasts.clear()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun copyButtonRefusesAboveHardLimit() = runComposeUiTest {
|
||||
var copied: String? = null
|
||||
val clipboard = object : ClipboardManager {
|
||||
override fun setText(annotatedString: AnnotatedString) { copied = annotatedString.text }
|
||||
override fun getText(): AnnotatedString? = null
|
||||
}
|
||||
try {
|
||||
setContent {
|
||||
CompositionLocalProvider(LocalClipboardManager provides clipboard) {
|
||||
MarkdownFileCopyButton("alpha", 524_289, 524_288)
|
||||
}
|
||||
AlertManager.shared.showInView()
|
||||
}
|
||||
onNodeWithContentDescription("Copy").performClick()
|
||||
onNodeWithText("Only files up to 512 KB can be copied. Save the file to open it in another app.").assertExists()
|
||||
assertNull(copied)
|
||||
} finally {
|
||||
AlertManager.shared.hideAllAlerts()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class RecordingClipboard : Clipboard {
|
||||
var text: String? = null
|
||||
|
||||
override suspend fun getClipEntry(): ClipEntry? = null
|
||||
|
||||
override suspend fun setClipEntry(clipEntry: ClipEntry?) {
|
||||
text = (clipEntry?.nativeClipEntry as Transferable).getTransferData(DataFlavor.stringFlavor) as String
|
||||
}
|
||||
|
||||
override val nativeClipboard: NativeClipboard get() = this
|
||||
}
|
||||
@@ -99,6 +99,7 @@ private val previewScenes = listOf(
|
||||
SnapshotScene("DeletedItemView.PreviewDeletedItemView", chatItemFontScales) { PreviewDeletedItemView() },
|
||||
SnapshotScene("IntegrityErrorItemView.IntegrityErrorItemViewPreview", chatItemFontScales) { IntegrityErrorItemViewPreview() },
|
||||
SnapshotScene("MarkedDeletedItemView.PreviewMarkedDeletedItemView", chatItemFontScales) { PreviewMarkedDeletedItemView() },
|
||||
SnapshotScene("MarkdownFileView.PreviewMarkdownFileView") { PreviewMarkdownFileView() },
|
||||
SnapshotScene("ChatHelpView.PreviewChatHelpLayout") { PreviewChatHelpLayout() },
|
||||
SnapshotScene("ChatListNavLinkView.PreviewChatListNavLinkDirect") { PreviewChatListNavLinkDirect() },
|
||||
SnapshotScene("ChatListNavLinkView.PreviewChatListNavLinkGroup") { PreviewChatListNavLinkGroup() },
|
||||
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Reference in new issue
Block a user