From a257d9b769f4dd86f6509110bebc16ae90877ea5 Mon Sep 17 00:00:00 2001 From: Konrad Pozniak Date: Mon, 14 Mar 2022 14:43:00 +0100 Subject: [PATCH] correctly render whitespace in posts (#2383) * correctly preserve whitespace in posts * use extension function to convert from Spanned to Html * improve comment --- .../tusky/json/SpannedTypeAdapter.kt | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/keylesspalace/tusky/json/SpannedTypeAdapter.kt b/app/src/main/java/com/keylesspalace/tusky/json/SpannedTypeAdapter.kt index ceb96f4a..60af6134 100644 --- a/app/src/main/java/com/keylesspalace/tusky/json/SpannedTypeAdapter.kt +++ b/app/src/main/java/com/keylesspalace/tusky/json/SpannedTypeAdapter.kt @@ -19,6 +19,7 @@ import android.text.Spanned import android.text.SpannedString import androidx.core.text.HtmlCompat import androidx.core.text.parseAsHtml +import androidx.core.text.toHtml import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement @@ -32,12 +33,22 @@ import java.lang.reflect.Type class SpannedTypeAdapter : JsonDeserializer, JsonSerializer { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Spanned { - /* Html.fromHtml returns trailing whitespace if the html ends in a

tag, which - * all status contents do, so it should be trimmed. */ - return json.asString?.parseAsHtml()?.trimTrailingWhitespace() ?: SpannedString("") + return json.asString + /* Mastodon uses 'white-space: pre-wrap;' so spaces are displayed as returned by the Api. + * We can't use CSS so we replace spaces with non-breaking-spaces to emulate the behavior. + */ + ?.replace("
", "
 ") + ?.replace("
", "
 ") + ?.replace("
", "
 ") + ?.replace(" ", "  ") + ?.parseAsHtml() + /* Html.fromHtml returns trailing whitespace if the html ends in a

tag, which + * most status contents do, so it should be trimmed. */ + ?.trimTrailingWhitespace() + ?: SpannedString("") } override fun serialize(src: Spanned?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { - return JsonPrimitive(HtmlCompat.toHtml(src!!, HtmlCompat.TO_HTML_PARAGRAPH_LINES_INDIVIDUAL)) + return JsonPrimitive(src!!.toHtml(HtmlCompat.TO_HTML_PARAGRAPH_LINES_INDIVIDUAL)) } }