aboutsummaryrefslogtreecommitdiff
path: root/kvision-modules/kvision-onsenui/src/main/kotlin/pl/treksoft/kvision/onsenui/carousel/Carousel.kt
blob: 5998eba5c35b9080123c872a9b50d72afc0e74e2 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
 * Copyright (c) 2017-present Robert Jaros
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package pl.treksoft.kvision.onsenui.carousel

import com.github.snabbdom.VNode
import pl.treksoft.kvision.core.Component
import pl.treksoft.kvision.core.Container
import pl.treksoft.kvision.core.CssSize
import pl.treksoft.kvision.core.StringPair
import pl.treksoft.kvision.panel.SimplePanel
import pl.treksoft.kvision.utils.asString
import pl.treksoft.kvision.utils.obj
import pl.treksoft.kvision.utils.set
import kotlin.js.Promise

enum class CarouselDirection(internal val type: String) {
    HORIZONTAL("horizontal"),
    VERTICAL("vertical")
}

/**
 * A carousel component.
 *
 * @constructor Creates a carousel component.
 * @param direction a carousel direction
 * @param fullscreen whether the carousel should fill the whole screen
 * @param overscrollable whether the carousel should scroll past first and last items
 * @param animation determines if the transitions are animated
 * @param swipeable determines if the carousel can be scrolled by drag or swipe
 * @param classes a set of CSS class names
 * @param init an initializer extension function
 */
open class Carousel(
    direction: CarouselDirection? = null,
    fullscreen: Boolean? = null,
    overscrollable: Boolean? = null,
    animation: Boolean? = null,
    swipeable: Boolean? = null,
    initialIndex: Int? = null,
    classes: Set<String> = setOf(),
    init: (Carousel.() -> Unit)? = null
) : SimplePanel(classes) {

    /**
     * A carousel direction.
     */
    var direction: CarouselDirection? by refreshOnUpdate(direction)

    /**
     * Whether the carousel should fill the whole screen.
     */
    var fullscreen: Boolean? by refreshOnUpdate(fullscreen)

    /**
     * Whether the carousel should scroll past first and last items.
     */
    var overscrollable: Boolean? by refreshOnUpdate(overscrollable)

    /**
     * Determines if the transitions are animated.
     */
    var animation: Boolean? by refreshOnUpdate(animation)

    /**
     * Determines if the carousel can be scrolled by drag or swipe.
     */
    var swipeable: Boolean? by refreshOnUpdate(swipeable)

    /**
     * The index of the item to show on start.
     */
    var initialIndex: Int? by refreshOnUpdate(initialIndex)

    /**
     * Whether the selected item will be in the center of the carousel instead of the beginning.
     */
    var centered: Boolean? by refreshOnUpdate()

    /**
     * The item width (only for horizontal direction).
     */
    var itemWidth: CssSize? by refreshOnUpdate()

    /**
     * The item height (only for vertical direction).
     */
    var itemHeight: CssSize? by refreshOnUpdate()

    /**
     * Whether the carousel will be automatically scrolled to the closest item border.
     */
    var autoScroll: Boolean? by refreshOnUpdate()

    /**
     * Specifies how much the user must drag the carousel in order for it to auto scroll to the next item.
     */
    var autoScrollRatio: Number? by refreshOnUpdate()

    /**
     * Whether the carousel is disabled.
     */
    var disabled: Boolean? by refreshOnUpdate()

    /**
     * Whether the carousel will automatically refresh when the number of child nodes change.
     */
    var autoRefresh: Boolean? by refreshOnUpdate()

    /**
     * The swiper inner container.
     */
    val swiperPanel = SimplePanel(setOf("ons-swiper-target"))

    init {
        swiperPanel.parent = this
        @Suppress("LeakingThis")
        init?.invoke(this)
    }

    /**
     * A dynamic property returning the number of carousel items.
     */
    val itemCount: dynamic
        get() = getElement()?.asDynamic()?.itemCount

    /**
     * Swipe event listener function.
     */
    protected var onSwipeCallback: ((Number) -> Unit)? = null

    override fun render(): VNode {
        return render("ons-carousel", arrayOf(swiperPanel.renderVNode()))
    }

    @Suppress("UnsafeCastFromDynamic")
    override fun afterInsert(node: VNode) {
        if (onSwipeCallback != null) {
            getElement()?.asDynamic()?.onSwipe = onSwipeCallback
        }
        this.getElementJQuery()?.on("postchange") { e, _ ->
            this.dispatchEvent("onsPostchange", obj { detail = e })
        }
        this.getElementJQuery()?.on("refresh") { e, _ ->
            this.dispatchEvent("onsRefresh", obj { detail = e })
        }
        this.getElementJQuery()?.on("overscroll") { e, _ ->
            this.dispatchEvent("onsOverscroll", obj { detail = e })
        }
    }

    override fun getSnAttrs(): List<StringPair> {
        val sn = super.getSnAttrs().toMutableList()
        direction?.let {
            sn.add("direction" to it.type)
        }
        if (fullscreen == true) {
            sn.add("fullscreen" to "fullscreen")
        }
        if (overscrollable == true) {
            sn.add("overscrollable" to "overscrollable")
        }
        if (animation == false) {
            sn.add("animation" to "none")
        }
        if (swipeable == true) {
            sn.add("swipeable" to "swipeable")
        }
        initialIndex?.let {
            sn.add("initial-index" to it.toString())
        }
        if (centered == true) {
            sn.add("centered" to "centered")
        }
        itemWidth?.let {
            sn.add("item-width" to it.asString())
        }
        itemHeight?.let {
            sn.add("item-height" to it.asString())
        }
        if (autoScroll == true) {
            sn.add("auto-scroll" to "auto-scroll")
        }
        autoScrollRatio?.let {
            sn.add("auto-scroll-ratio" to it.toString())
        }
        if (disabled == true) {
            sn.add("disabled" to "disabled")
        }
        if (autoRefresh == true) {
            sn.add("auto-refresh" to "auto-refresh")
        }
        return sn
    }

    override fun add(child: Component): SimplePanel {
        swiperPanel.add(child)
        return this
    }

    override fun addAll(children: List<Component>): SimplePanel {
        swiperPanel.addAll(children)
        return this
    }

    override fun remove(child: Component): SimplePanel {
        swiperPanel.remove(child)
        return this
    }

    override fun removeAll(): SimplePanel {
        swiperPanel.removeAll()
        return this
    }

    override fun getChildren(): List<Component> {
        return swiperPanel.getChildren()
    }

    /**
     * Shows specified carousel item.
     * @param index the carousel item index
     * @param options a parameter object
     */
    @Suppress("UnsafeCastFromDynamic")
    open fun setActiveIndex(index: Int, options: dynamic = undefined): Promise<Unit>? {
        return getElement()?.asDynamic()?.setActiveIndex(index, options)
    }

    /**
     * Gets the active item index.
     * @return active item index
     */
    @Suppress("UnsafeCastFromDynamic")
    open fun getActiveIndex(): Number {
        return getElement()?.asDynamic()?.getActiveIndex() ?: -1
    }

    /**
     * Shows next carousel item.
     * @param options a parameter object
     */
    @Suppress("UnsafeCastFromDynamic")
    open fun next(options: dynamic = undefined): Promise<Unit> {
        return getElement()?.asDynamic()?.next(options)
    }

    /**
     * Shows previous carousel item.
     * @param options a parameter object
     */
    @Suppress("UnsafeCastFromDynamic")
    open fun prev(options: dynamic = undefined): Promise<Unit> {
        return getElement()?.asDynamic()?.prev(options)
    }

    /**
     * Shows first carousel item.
     * @param options a parameter object
     */
    @Suppress("UnsafeCastFromDynamic")
    open fun first(options: dynamic = undefined): Promise<Unit> {
        return getElement()?.asDynamic()?.first(options)
    }

    /**
     * Shows last carousel item.
     * @param options a parameter object
     */
    @Suppress("UnsafeCastFromDynamic")
    open fun last(options: dynamic = undefined): Promise<Unit> {
        return getElement()?.asDynamic()?.last(options)
    }

    /**
     * Updates the layout of the carousel.
     */
    @Suppress("UnsafeCastFromDynamic")
    open fun refreshCarousel() {
        getElement()?.asDynamic()?.refresh()
    }

    /**
     * Sets swipe event listener.
     * @param callback an event listener
     */
    open fun onSwipe(callback: (ratio: Number) -> Unit) {
        onSwipeCallback = callback
        getElement()?.asDynamic()?.onSwipe = callback
    }

    /**
     * Clears swipe event listener.
     */
    open fun onSwipeClear() {
        onSwipeCallback = null
        getElement()?.asDynamic()?.onSwipe = undefined
    }
}

/**
 * DSL builder extension function.
 *
 * It takes the same parameters as the constructor of the built component.
 */
fun Container.carousel(
    direction: CarouselDirection? = null,
    fullscreen: Boolean? = null,
    overscrollable: Boolean? = null,
    animation: Boolean? = null,
    swipeable: Boolean? = null,
    initialIndex: Int? = null,
    classes: Set<String>? = null,
    className: String? = null,
    init: (Carousel.() -> Unit)? = null
): Carousel {
    val carousel = Carousel(
        direction,
        fullscreen,
        overscrollable,
        animation,
        swipeable,
        initialIndex,
        classes ?: className.set,
        init
    )
    this.add(carousel)
    return carousel
}