aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/pl/treksoft/kvision/panel/TabPanel.kt
blob: 4190dbae0e4c8a11d6f3d31dbdd04ab3d719a64e (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
67
68
69
70
71
72
73
74
75
76
package pl.treksoft.kvision.panel

import pl.treksoft.kvision.core.ResString
import pl.treksoft.kvision.core.Widget
import pl.treksoft.kvision.html.Link
import pl.treksoft.kvision.html.TAG
import pl.treksoft.kvision.html.Tag

open class TabPanel : SimplePanel(setOf()) {
    var activeIndex
        get() = content.activeIndex
        set(value) {
            content.activeIndex = value
            nav.children.forEach { it.removeCssClass("active") }
            if (content.activeIndex >= 0 && content.activeIndex <= nav.children.size) {
                nav.children[content.activeIndex].addCssClass("active")
            }
        }

    private var nav = Tag(TAG.UL, classes = setOf("nav", "nav-tabs"))
    private var content = StackPanel(false)

    init {
        this.addInternal(nav)
        this.addInternal(content)
    }

    open fun addTab(title: String, panel: Widget, icon: String? = null,
                    image: ResString? = null): TabPanel {
        val tag = Tag(TAG.LI)
        tag.role = "presentation"
        tag.add(Link(title, "#", icon, image))
        val index = nav.children.size
        tag.setEventListener {
            click = { e ->
                activeIndex = index
                e.preventDefault()
            }
        }
        nav.add(tag)
        if (nav.children.size == 1) {
            tag.addCssClass("active")
            activeIndex = 0
        }
        content.add(panel)
        return this
    }

    open fun removeTab(index: Int): TabPanel {
        nav.remove(nav.children[index])
        content.remove(content.children[index])
        activeIndex = content.activeIndex
        return this
    }

    override fun add(child: Widget): TabPanel {
        return addTab("", child)
    }

    override fun addAll(children: List<Widget>): TabPanel {
        children.forEach { add(it) }
        return this
    }

    override fun remove(child: Widget): TabPanel {
        val index = content.children.indexOf(child)
        return removeTab(index)
    }

    override fun removeAll(): TabPanel {
        content.removeAll()
        nav.removeAll()
        refresh()
        return this
    }
}