Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#import "../../ios/parser/ENRMMarkdownParser.h"
#import "../../ios/parser/MarkdownASTNode.h"
#import "../../ios/styles/StyleConfig.h"
#import "../../ios/utils/ENRMTextRenderer.h"
#import "../../ios/utils/HTMLGenerator.h"
#import "../../ios/utils/LastElementUtils.h"
#import "../../ios/utils/MarkdownASTSerializer.h"
#import <XCTest/XCTest.h>

@interface ENRMClipboardExportTests : XCTestCase
@end

@implementation ENRMClipboardExportTests

- (void)testTableLineBreaksAreExportedAsHTMLBreaks
{
for (NSString *separator in @[ @"\n", @"\r", @"\r\n", @"\u2028", @"\u2029" ]) {
NSAttributedString *text =
[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"first%@second", separator]];
NSString *html = generateTableHTML(@[ @[ @{@"attributedText" : text} ] ], [[StyleConfig alloc] init]);
XCTAssertTrue([html containsString:@"first<br>second"], @"%@", html);
XCTAssertFalse([html containsString:@"<br><br>"], @"%@", html);
}
}

- (void)testEscapedCharactersAndLineBreaksShareOneRun
{
NSAttributedString *text = [[NSAttributedString alloc] initWithString:@"a & b\nc <d>"];
NSString *html = generateTableHTML(@[ @[ @{@"attributedText" : text} ] ], [[StyleConfig alloc] init]);
XCTAssertTrue([html containsString:@"a &amp; b<br>c &lt;d&gt;"], @"%@", html);
}

- (NSString *)htmlForMarkdown:(NSString *)markdown
{
MarkdownASTNode *ast = [[[ENRMMarkdownParser alloc] init] parseMarkdown:markdown
flags:[ENRMMd4cFlags defaultFlags]
isGFM:YES];
StyleConfig *config = [[StyleConfig alloc] init];
ENRMRenderResult *result = ENRMRenderASTNodes(ast.children, config, NO, YES, 0, NSLineBreakStrategyStandard);
return generateHTML(result.attributedText, config);
}

- (void)testHardBreaksStayInsideTheirBlock
{
NSString *paragraph = [self htmlForMarkdown:@"line one \nline two\n\npara two"];
XCTAssertTrue([paragraph containsString:@"line one<br>line two</p>"], @"%@", paragraph);
XCTAssertFalse([paragraph containsString:@"<br></p>"], @"%@", paragraph);

NSString *list = [self htmlForMarkdown:@"- item one \n item two\n- item three"];
XCTAssertTrue([list containsString:@"item one<br>item two</li>"], @"%@", list);
XCTAssertEqual([list componentsSeparatedByString:@"<li"].count, 3u, @"%@", list);
}

- (void)testCodeBlockNewlinesRemainLiteral
{
NSAttributedString *text = [[NSAttributedString alloc] initWithString:@"first\nsecond"
attributes:@{CodeBlockAttributeName : @YES}];
NSString *html = generateHTML(text, [[StyleConfig alloc] init]);
XCTAssertFalse([html containsString:@"<br>"], @"%@", html);
XCTAssertTrue([html containsString:@"first\nsecond"], @"%@", html);
}

- (void)testSerializedTableFormulaKeepsInlineDelimiters
{
MarkdownASTNode *formula = [[MarkdownASTNode alloc] initWithType:MarkdownNodeTypeLatexMathInline];
MarkdownASTNode *text = [[MarkdownASTNode alloc] initWithType:MarkdownNodeTypeText];
text.content = @"x_1";
[formula addChild:text];
MarkdownASTNode *cell = [[MarkdownASTNode alloc] initWithType:MarkdownNodeTypeTableCell];
[cell addChild:formula];
XCTAssertEqualObjects(markdownFromASTNodeChildren(cell), @"$x_1$");

MarkdownASTNode *strong = [[MarkdownASTNode alloc] initWithType:MarkdownNodeTypeStrong];
[strong addChild:formula];
MarkdownASTNode *nestedCell = [[MarkdownASTNode alloc] initWithType:MarkdownNodeTypeTableCell];
[nestedCell addChild:strong];
XCTAssertEqualObjects(markdownFromASTNodeChildren(nestedCell), @"**$x_1$**");
}

@end
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,12 @@ object MarkdownASTSerializer {
buffer.append("==")
}

NodeType.LatexMathInline -> {
buffer.append("\$")
appendChildren(node, buffer)
buffer.append("\$")
}

NodeType.Code -> {
buffer.append("`")
appendChildren(node, buffer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -848,7 +848,7 @@ object HTMLGenerator {
}
}

escapeHTMLTo(html, content.trimEnd('\n'))
escapeHTMLTo(html, content.trimEnd('\n'), preserveLineBreaks = !isCodeBlock)

if (isUnderline && link == null) html.append("</u>")
if (isStrikethrough) html.append("</s>")
Expand Down Expand Up @@ -1001,7 +1001,7 @@ object HTMLGenerator {
if (cellText is Spannable) {
append(generateInlineHTML(cellText, 0, cellText.length, cachedStyles, false))
} else {
escapeHTMLTo(this, cellText.toString())
escapeHTMLTo(this, cellText.toString(), preserveLineBreaks = true)
}
}

Expand Down Expand Up @@ -1042,14 +1042,17 @@ object HTMLGenerator {
private fun escapeHTMLTo(
output: StringBuilder,
text: String,
preserveLineBreaks: Boolean = false,
) {
val len = text.length

// Fast path: skip if no escaping needed
var needsEscape = false
for (i in 0 until len) {
val c = text[i]
if (c == '&' || c == '<' || c == '>' || c == '"' || c == '\'') {
if (c == '&' || c == '<' || c == '>' || c == '"' || c == '\'' ||
(preserveLineBreaks && (c == '\r' || c == '\n' || c == '\u2028' || c == '\u2029'))
) {
needsEscape = true
break
}
Expand All @@ -1059,8 +1062,15 @@ object HTMLGenerator {
return
}

for (i in 0 until len) {
when (val c = text[i]) {
var index = 0
while (index < len) {
val c = text[index++]
if (preserveLineBreaks && (c == '\r' || c == '\n' || c == '\u2028' || c == '\u2029')) {
if (c == '\r' && index < len && text[index] == '\n') index++
output.append("<br>")
continue
}
when (c) {
'&' -> output.append("&amp;")
'<' -> output.append("&lt;")
'>' -> output.append("&gt;")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package com.swmansion.enriched.markdown

import android.graphics.Color
import android.text.Layout
import android.text.SpannableString
import com.facebook.react.bridge.JavaOnlyMap
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
import com.swmansion.enriched.markdown.renderer.Renderer
import com.swmansion.enriched.markdown.styles.StyleConfig
import com.swmansion.enriched.markdown.utils.common.serialization.MarkdownASTSerializer
import com.swmansion.enriched.markdown.utils.text.conversion.HTMLGenerator
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class ClipboardExportTest {
private val context = RuntimeEnvironment.getApplication()

@Test
fun tableLineBreaksAreExportedAsHtmlBreaks() {
for (separator in listOf("\n", "\r", "\r\n", "\u2028", "\u2029")) {
for (text in listOf<CharSequence>(SpannableString("first${separator}second"), "first${separator}second")) {
val rows = listOf(listOf(Triple(text, false, Layout.Alignment.ALIGN_NORMAL)))
val html = HTMLGenerator.generateTableHTML(rows, style())
assertTrue(html, html.contains("first<br>second"))
assertFalse(html, html.contains("<br><br>"))
}
}
}

@Test
fun escapedCharactersAndLineBreaksShareOneRun() {
val rows = listOf(listOf(Triple<CharSequence, Boolean, Layout.Alignment>("a & b\nc <d>", false, Layout.Alignment.ALIGN_NORMAL)))
val html = HTMLGenerator.generateTableHTML(rows, style())
assertTrue(html, html.contains("a &amp; b<br>c &lt;d&gt;"))
}

@Test
fun codeBlockNewlinesRemainLiteral() {
val style = style()
val codeBlock =
MarkdownASTNode(
MarkdownASTNode.NodeType.CodeBlock,
content = "first\nsecond",
children = listOf(MarkdownASTNode(MarkdownASTNode.NodeType.Text, "first\nsecond")),
)
val renderer = Renderer()
renderer.configure(style, context)
val html = HTMLGenerator.generateHTML(renderer.renderContent(listOf(codeBlock)), style)
assertFalse(html, html.contains("<br>"))
assertTrue(html, html.contains("first\nsecond"))
}

@Test
fun serializedTableFormulaKeepsItsInlineDelimiters() {
val formula =
MarkdownASTNode(MarkdownASTNode.NodeType.LatexMathInline, children = listOf(MarkdownASTNode(MarkdownASTNode.NodeType.Text, "x_1")))
val cell = MarkdownASTNode(MarkdownASTNode.NodeType.TableCell, children = listOf(formula))
assertEquals("\$x_1\$", MarkdownASTSerializer.serializeChildren(cell))

val strong = MarkdownASTNode(MarkdownASTNode.NodeType.Strong, children = listOf(formula))
val nestedCell = MarkdownASTNode(MarkdownASTNode.NodeType.TableCell, children = listOf(strong))
assertEquals("**\$x_1\$**", MarkdownASTSerializer.serializeChildren(nestedCell))
}

private fun style(): StyleConfig {
com.facebook.react.uimanager.DisplayMetricsHolder
.initDisplayMetricsIfNotInitialized(context)

fun element() =
JavaOnlyMap().apply {
listOf(
"aspectRatio",
"bulletSize",
"checkboxBorderRadius",
"checkboxSize",
"height",
"itemSpacing",
"markerMinWidth",
"maxHeight",
"cellPaddingHorizontal",
"cellPaddingVertical",
"horizontalOverflow",
"lineHeight",
"marginTop",
"marginBottom",
"padding",
"borderRadius",
"borderWidth",
"gapWidth",
"marginLeft",
).forEach {
putDouble(it, 0.0)
}
listOf(
"bulletColor",
"checkedColor",
"checkedTextColor",
"checkmarkColor",
"headerBackgroundColor",
"headerTextColor",
"markerColor",
"rowEvenBackgroundColor",
"rowOddBackgroundColor",
"color",
"borderColor",
).forEach {
putInt(it, Color.BLACK)
}
putString("resizeMode", "contain")
putString("fontFamily", "")
putString("fontWeight", "normal")
putDouble("fontSize", 16.0)
putDouble("fontScale", 0.8)
putDouble("baselineOffsetScale", 0.5)
putBoolean("underline", false)
putInt("backgroundColor", Color.TRANSPARENT)
}
val style = JavaOnlyMap()
listOf(
"table",
"paragraph",
"codeBlock",
"code",
"blockquote",
"list",
"link",
"strong",
"em",
"strikethrough",
"underline",
"highlight",
"image",
"superscript",
"subscript",
).forEach { style.putMap(it, element()) }
style.putMap(
"spoiler",
element().apply {
putMap("particles", JavaOnlyMap.of("density", 0.5, "speed", 1.0))
putMap("solid", JavaOnlyMap.of("borderRadius", 0.0))
},
)
for (level in 1..6) style.putMap("h$level", element())
style.putMap(
"taskList",
JavaOnlyMap.of(
"checkedColor",
Color.BLACK,
"borderColor",
Color.BLACK,
"checkmarkColor",
Color.BLACK,
"checkedTextColor",
Color.BLACK,
"checkboxSize",
16.0,
"checkboxBorderRadius",
0.0,
"checkedStrikethrough",
false,
),
)
return StyleConfig(style, context, false, 0f)
}
}
Loading
Loading