Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding spoiler tag support #990

Merged
merged 18 commits into from
Jul 11, 2023
Merged
Show file tree
Hide file tree
Changes from 14 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
Expand Up @@ -2,10 +2,7 @@ package com.jerboa.ui.components.common

import android.content.Context
import android.os.Build
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.URLSpan
import android.text.util.Linkify
import android.util.TypedValue
import android.view.View
Expand Down Expand Up @@ -36,15 +33,11 @@ import coil.ImageLoader
import com.jerboa.R
import com.jerboa.convertSpToPx
import com.jerboa.openLink
import com.jerboa.util.MarkwonLemmyLinkPlugin
import com.jerboa.util.MarkwonSpoilerPlugin
import io.noties.markwon.AbstractMarkwonPlugin
import io.noties.markwon.Markwon
import io.noties.markwon.MarkwonConfiguration
import io.noties.markwon.MarkwonPlugin
import io.noties.markwon.MarkwonVisitor
import io.noties.markwon.SpannableBuilder
import io.noties.markwon.core.CorePlugin
import io.noties.markwon.core.CorePlugin.OnTextAddedListener
import io.noties.markwon.core.CoreProps
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
import io.noties.markwon.ext.tables.TableAwareMovementMethod
import io.noties.markwon.ext.tables.TablePlugin
Expand All @@ -54,7 +47,6 @@ import io.noties.markwon.image.AsyncDrawableSpan
import io.noties.markwon.image.coil.CoilImagesPlugin
import io.noties.markwon.linkify.LinkifyPlugin
import io.noties.markwon.movement.MovementMethodPlugin
import org.commonmark.node.Link
import java.util.regex.Pattern

/**
Expand Down Expand Up @@ -85,52 +77,6 @@ val lemmyCommunityPattern: Pattern =
val lemmyUserPattern: Pattern =
Pattern.compile("(?<!\\S)@($userPatternFragment)(?:@($instancePatternFragment))?\\b")

/**
* Plugin to turn Lemmy-specific URIs into clickable links.
*/
class LemmyLinkPlugin : AbstractMarkwonPlugin() {
override fun configure(registry: MarkwonPlugin.Registry) {
registry.require(CorePlugin::class.java) { it.addOnTextAddedListener(LemmyTextAddedListener()) }
}

private class LemmyTextAddedListener : OnTextAddedListener {
override fun onTextAdded(visitor: MarkwonVisitor, text: String, start: Int) {
// we will be using the link that is used by markdown (instead of directly applying URLSpan)
val spanFactory = visitor.configuration().spansFactory().get(
Link::class.java,
) ?: return

// don't re-use builder (thread safety achieved for
// render calls from different threads and ... better performance)
val builder = SpannableStringBuilder(text)
if (addLinks(builder)) {
// target URL span specifically
val spans = builder.getSpans(0, builder.length, URLSpan::class.java)
if (!spans.isNullOrEmpty()) {
val renderProps = visitor.renderProps()
val spannableBuilder = visitor.builder()
for (span in spans) {
CoreProps.LINK_DESTINATION[renderProps] = span.url
SpannableBuilder.setSpans(
spannableBuilder,
spanFactory.getSpans(visitor.configuration(), renderProps),
start + builder.getSpanStart(span),
start + builder.getSpanEnd(span),
)
}
}
}
}

fun addLinks(text: Spannable): Boolean {
val communityLinkAdded = Linkify.addLinks(text, lemmyCommunityPattern, null)
val userLinkAdded = Linkify.addLinks(text, lemmyUserPattern, null)

return communityLinkAdded || userLinkAdded
}
}
}

object MarkdownHelper {
private var markwon: Markwon? = null
private var previewMarkwon: Markwon? = null
Expand All @@ -146,14 +92,15 @@ object MarkdownHelper {
markwon = Markwon.builder(context)
// email urls interfere with lemmy links
.usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
.usePlugin(LemmyLinkPlugin())
.usePlugin(MarkwonLemmyLinkPlugin())
.usePlugin(StrikethroughPlugin.create())
.usePlugin(TablePlugin.create(context))
.usePlugin(CoilImagesPlugin.create(context, loader))
.usePlugin(HtmlPlugin.create())
// use TableAwareLinkMovementMethod to handle clicks inside tables,
// wraps LinkMovementMethod internally
.usePlugin(MovementMethodPlugin.create(TableAwareMovementMethod.create()))
.usePlugin(MarkwonSpoilerPlugin(false))
.usePlugin(object : AbstractMarkwonPlugin() {
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
builder.linkResolver { _, link ->
Expand All @@ -167,7 +114,7 @@ object MarkdownHelper {
previewMarkwon = Markwon.builder(context)
// email urls interfere with lemmy links
.usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
.usePlugin(LemmyLinkPlugin())
.usePlugin(MarkwonLemmyLinkPlugin())
.usePlugin(StrikethroughPlugin.create())
.usePlugin(TablePlugin.create(context))
.usePlugin(HtmlPlugin.create { plugin -> plugin.addHandler(TagHandlerNoOp.create("img")) })
Expand All @@ -176,6 +123,7 @@ object MarkdownHelper {
builder.linkResolver { _, _ -> }
}
})
.usePlugin(MarkwonSpoilerPlugin(true))
.build()
}

Expand Down Expand Up @@ -254,7 +202,7 @@ object MarkdownHelper {
setTextColor(textColor.toArgb())
setTextSize(TypedValue.COMPLEX_UNIT_SP, mergedStyle.fontSize.value)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
setLineHeight(convertSpToPx(mergedStyle.lineHeight, context))
lineHeight = convertSpToPx(mergedStyle.lineHeight, context)
}
width = maxWidth

Expand Down
58 changes: 58 additions & 0 deletions app/src/main/java/com/jerboa/util/MarkwonLemmyLinkPlugin.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.jerboa.util

import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.URLSpan
import android.text.util.Linkify
import com.jerboa.ui.components.common.lemmyCommunityPattern
import com.jerboa.ui.components.common.lemmyUserPattern
import io.noties.markwon.*
import io.noties.markwon.core.CorePlugin
import io.noties.markwon.core.CoreProps
import org.commonmark.node.Link

/**
* Plugin to turn Lemmy-specific URIs into clickable links.
*/
class MarkwonLemmyLinkPlugin : AbstractMarkwonPlugin() {
override fun configure(registry: MarkwonPlugin.Registry) {
registry.require(CorePlugin::class.java) { it.addOnTextAddedListener(LemmyTextAddedListener()) }
}

private class LemmyTextAddedListener : CorePlugin.OnTextAddedListener {
override fun onTextAdded(visitor: MarkwonVisitor, text: String, start: Int) {
// we will be using the link that is used by markdown (instead of directly applying URLSpan)
val spanFactory = visitor.configuration().spansFactory().get(
Link::class.java,
) ?: return

// don't re-use builder (thread safety achieved for
// render calls from different threads and ... better performance)
val builder = SpannableStringBuilder(text)
if (addLinks(builder)) {
// target URL span specifically
val spans = builder.getSpans(0, builder.length, URLSpan::class.java)
if (!spans.isNullOrEmpty()) {
val renderProps = visitor.renderProps()
val spannableBuilder = visitor.builder()
for (span in spans) {
CoreProps.LINK_DESTINATION[renderProps] = span.url
SpannableBuilder.setSpans(
spannableBuilder,
spanFactory.getSpans(visitor.configuration(), renderProps),
start + builder.getSpanStart(span),
start + builder.getSpanEnd(span),
)
}
}
}
}

fun addLinks(text: Spannable): Boolean {
val communityLinkAdded = Linkify.addLinks(text, lemmyCommunityPattern, null)
val userLinkAdded = Linkify.addLinks(text, lemmyUserPattern, null)

return communityLinkAdded || userLinkAdded
}
}
}
140 changes: 140 additions & 0 deletions app/src/main/java/com/jerboa/util/MarkwonSpoilerPlugin.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package com.jerboa.util

import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import android.widget.TextView
import io.noties.markwon.AbstractMarkwonPlugin
import io.noties.markwon.MarkwonPlugin
import io.noties.markwon.MarkwonVisitor
import io.noties.markwon.core.CorePlugin
import io.noties.markwon.image.AsyncDrawableScheduler

data class SpoilerTitleSpan(val title: CharSequence)
class SpoilerCloseSpan

class MarkwonSpoilerPlugin(val preview: Boolean) : AbstractMarkwonPlugin() {
ZJouba marked this conversation as resolved.
Show resolved Hide resolved
override fun configure(registry: MarkwonPlugin.Registry) {
registry.require(CorePlugin::class.java) {
it.addOnTextAddedListener(
SpoilerTextAddedListener(),
)
}
}

private class SpoilerTextAddedListener : CorePlugin.OnTextAddedListener {
override fun onTextAdded(visitor: MarkwonVisitor, text: String, start: Int) {
val spoilerTitleRegex = Regex("(:::\\s*spoiler\\s*)(.*)")
// Find all spoiler "start" lines
val spoilerTitles = spoilerTitleRegex.findAll(text)

for (match in spoilerTitles) {
val spoilerTitle = match.groups[2]!!.value
visitor.builder().setSpan(
SpoilerTitleSpan(spoilerTitle),
start,
start + match.groups[2]!!.range.last,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
)
}

val spoilerCloseRegex = Regex("^(?!.*spoiler).*:::")
// Find all spoiler "end" lines
val spoilerCloses = spoilerCloseRegex.findAll(text)
for (match in spoilerCloses) {
visitor.builder()
.setSpan(SpoilerCloseSpan(), start, start + 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}

override fun afterSetText(textView: TextView) {
try {
val spanned = SpannableStringBuilder(textView.text)
val spoilerTitleSpans =
spanned.getSpans(0, spanned.length, SpoilerTitleSpan::class.java)
val spoilerCloseSpans =
spanned.getSpans(0, spanned.length, SpoilerCloseSpan::class.java)

spoilerTitleSpans.sortBy { spanned.getSpanStart(it) }
spoilerCloseSpans.sortBy { spanned.getSpanStart(it) }

spoilerTitleSpans.forEachIndexed { index, spoilerTitleSpan ->
val spoilerStart = spanned.getSpanStart(spoilerTitleSpan)

var spoilerEnd = spanned.length
if (index < spoilerCloseSpans.size) {
val spoilerCloseSpan = spoilerCloseSpans[index]
spoilerEnd = spanned.getSpanEnd(spoilerCloseSpan)
}

var open = false
val getSpoilerTitle = { openParam: Boolean ->
if (openParam) "▼ ${spoilerTitleSpan.title}" else "▶ ${spoilerTitleSpan.title}"
}

val spoilerTitle = getSpoilerTitle(false)

val spoilerContent = spanned.subSequence(
spanned.getSpanEnd(spoilerTitleSpan) + 1,
spoilerEnd - 3,
) as SpannableStringBuilder

// Remove spoiler content from span
spanned.replace(spoilerStart, spoilerEnd, spoilerTitle)
// Set span block title
spanned.setSpan(
spoilerTitle,
spoilerStart,
spoilerStart + spoilerTitle.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
)

val wrapper = object : ClickableSpan() {
override fun onClick(p0: View) {
if (!preview) {
textView.cancelPendingInputEvents()
open = !open

spanned.replace(
spoilerStart,
spoilerStart + spoilerTitle.length,
getSpoilerTitle(open),
)
if (open) {
spanned.insert(spoilerStart + spoilerTitle.length, spoilerContent)
} else {
spanned.replace(
spoilerStart + spoilerTitle.length,
spoilerStart + spoilerTitle.length + spoilerContent.length,
"",
)
}

textView.text = spanned
AsyncDrawableScheduler.schedule(textView)
}
}

override fun updateDrawState(ds: TextPaint) {
}
}

// Set spoiler block type as ClickableSpan
spanned.setSpan(
wrapper,
spoilerStart,
spoilerStart + spoilerTitle.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
)

textView.text = spanned
}
} catch (e: Exception) {
Log.w("jerboa", "Failed to parse spoiler tag. Format incorrect")
}
}
}