correctly render whitespace in posts (#2383)
* correctly preserve whitespace in posts * use extension function to convert from Spanned to Html * improve comment
This commit is contained in:
parent
991d261459
commit
a257d9b769
|
@ -19,6 +19,7 @@ import android.text.Spanned
|
||||||
import android.text.SpannedString
|
import android.text.SpannedString
|
||||||
import androidx.core.text.HtmlCompat
|
import androidx.core.text.HtmlCompat
|
||||||
import androidx.core.text.parseAsHtml
|
import androidx.core.text.parseAsHtml
|
||||||
|
import androidx.core.text.toHtml
|
||||||
import com.google.gson.JsonDeserializationContext
|
import com.google.gson.JsonDeserializationContext
|
||||||
import com.google.gson.JsonDeserializer
|
import com.google.gson.JsonDeserializer
|
||||||
import com.google.gson.JsonElement
|
import com.google.gson.JsonElement
|
||||||
|
@ -32,12 +33,22 @@ import java.lang.reflect.Type
|
||||||
class SpannedTypeAdapter : JsonDeserializer<Spanned>, JsonSerializer<Spanned?> {
|
class SpannedTypeAdapter : JsonDeserializer<Spanned>, JsonSerializer<Spanned?> {
|
||||||
@Throws(JsonParseException::class)
|
@Throws(JsonParseException::class)
|
||||||
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Spanned {
|
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Spanned {
|
||||||
|
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("<br> ", "<br> ")
|
||||||
|
?.replace("<br /> ", "<br /> ")
|
||||||
|
?.replace("<br/> ", "<br/> ")
|
||||||
|
?.replace(" ", " ")
|
||||||
|
?.parseAsHtml()
|
||||||
/* Html.fromHtml returns trailing whitespace if the html ends in a </p> tag, which
|
/* Html.fromHtml returns trailing whitespace if the html ends in a </p> tag, which
|
||||||
* all status contents do, so it should be trimmed. */
|
* most status contents do, so it should be trimmed. */
|
||||||
return json.asString?.parseAsHtml()?.trimTrailingWhitespace() ?: SpannedString("")
|
?.trimTrailingWhitespace()
|
||||||
|
?: SpannedString("")
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun serialize(src: Spanned?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
|
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))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue