aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/utils/WebContextMenu.kt
blob: dc2d7549424ae63f0e8f512a83abc4a221108e21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.pitchedapps.frost.utils

import android.content.Context
import ca.allanwang.kau.utils.copyToClipboard
import ca.allanwang.kau.utils.shareText
import ca.allanwang.kau.utils.string
import ca.allanwang.kau.utils.toast
import com.pitchedapps.frost.R
import com.pitchedapps.frost.activities.MainActivity
import com.pitchedapps.frost.facebook.formattedFbUrl

/**
 * Created by Allan Wang on 2017-07-07.
 */
fun Context.showWebContextMenu(wc: WebContext) {

    var title = wc.url
    title = title.substring(title.indexOf("m/") + 1) //just so if defaults to 0 in case it's not .com/
    if (title.length > 100) title = title.substring(0, 100) + '\u2026'

    materialDialogThemed {
        title(title)
        items(WebContextType.values.map {
            if (it == WebContextType.COPY_TEXT && wc.text == null) return@map null
            this@showWebContextMenu.string(it.textId)
        }.filterNotNull())
        itemsCallback { _, _, position, _ ->
            WebContextType[position].onClick(this@showWebContextMenu, wc)
        }
        dismissListener {
            //showing the dialog interrupts the touch down event, so we must ensure that the viewpager's swipe is enabled
            (this@showWebContextMenu as? MainActivity)?.viewPager?.enableSwipe = true
        }
    }
}

class WebContext(val unformattedUrl: String, val text: String?) {
    val url = unformattedUrl.formattedFbUrl
}

enum class WebContextType(val textId: Int, val onClick: (c: Context, wc: WebContext) -> Unit) {
    OPEN_LINK(R.string.open_link, { c, wc -> c.launchWebOverlay(wc.unformattedUrl) }),
    COPY_LINK(R.string.copy_link, { c, wc -> c.copyToClipboard(wc.url) }),
    COPY_TEXT(R.string.copy_text, { c, wc -> if (wc.text != null) c.copyToClipboard(wc.text) else c.toast(R.string.no_text) }),
    SHARE_LINK(R.string.share_link, { c, wc -> c.shareText(wc.url) }),
    DEBUG_LINK(R.string.debug_link, { c, wc ->
        c.materialDialogThemed {
            title(R.string.debug_link)
            content(R.string.debug_link_desc)
            positiveText(R.string.kau_ok)
            onPositive { _, _ ->
                c.sendFrostEmail(R.string.debug_link_subject) {
                    message = c.string(R.string.debug_link_content)
                    addItem("Unformatted url", wc.unformattedUrl)
                    addItem("Formatted url", wc.url)
                }
            }
        }
    })
    ;

    companion object {
        val values = values()
        operator fun get(index: Int) = values[index]
    }
}