/* * 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.core import com.github.snabbdom.VNode import com.github.snabbdom.VNodeData import com.github.snabbdom.h import org.w3c.dom.CustomEventInit import org.w3c.dom.DragEvent import org.w3c.dom.Node import org.w3c.dom.events.MouseEvent import pl.treksoft.jquery.JQuery import pl.treksoft.jquery.jQuery import pl.treksoft.kvision.KVManager import pl.treksoft.kvision.i18n.I18n import pl.treksoft.kvision.i18n.I18n.trans import pl.treksoft.kvision.panel.Root import pl.treksoft.kvision.state.ObservableState import pl.treksoft.kvision.utils.* import kotlin.reflect.KProperty enum class Easing(internal val easing: String) { SWING("swing"), LINEAR("linear") } /** * Base widget class. The parent of all component classes. * * A simple widget is rendered as HTML DIV element. * * @constructor Creates basic Widget with given CSS class names. * @param classes Set of CSS class names */ @Suppress("TooManyFunctions", "LargeClass") open class Widget(classes: Set = setOf()) : StyledComponent(), Component { private val propertyValues: MutableMap = mutableMapOf() internal val classes = classes.toMutableSet() internal val surroundingClasses: MutableSet = mutableSetOf() internal val attributes: MutableMap = mutableMapOf() internal val internalListenersMap = mutableMapOf.() -> Unit>>() internal val listenersMap = mutableMapOf.() -> Unit>>() internal var listenerCounter: Int = 0 override var parent: Container? = null override var visible: Boolean = true set(value) { val oldField = field field = value if (oldField != field) refresh() } /** * A title attribute of generated HTML element. */ var title: String? by refreshOnUpdate() /** * An ID attribute of generated HTML element. */ var id: String? by refreshOnUpdate() /** * A role attribute of generated HTML element. */ var role: String? by refreshOnUpdate() /** * A tabindex attribute of generated HTML element. */ var tabindex: Int? by refreshOnUpdate() /** * Determines if the current widget is draggable. */ var draggable: Boolean? by refreshOnUpdate() protected var surroundingSpan by refreshOnUpdate(false) private var tooltipSiblings: JQuery? = null private var popoverSiblings: JQuery? = null protected var tooltipOptions: TooltipOptions? = null protected var popoverOptions: PopoverOptions? = null var eventTarget: Widget? = null private var vnkey = "kv_widget_${counter++}" protected var vnode: VNode? = null private var snAttrsCache: List? = null private var snClassCache: List? = null private var snOnCache: com.github.snabbdom.On? = null private var snHooksCache: com.github.snabbdom.Hooks? = null protected var lastLanguage: String? = null /** * A function called after the widget is inserted to the DOM. */ var afterInsertHook: ((VNode) -> Unit)? = null /** * A function called after the widget is removed from the DOM. */ var afterDestroyHook: (() -> Unit)? = null /** * A function called after the widget is disposed. */ var afterDisposeHook: (() -> Unit)? = null protected fun singleRender(block: () -> T): T { getRoot()?.renderDisabled = true val t = block() getRoot()?.renderDisabled = false getRoot()?.reRender() return t } override fun renderVNode(): VNode { return if (surroundingClasses.isEmpty()) { if (surroundingSpan) { h("span", arrayOf(render())) } else { render() } } else { val opt = snOpt { `class` = snClasses(surroundingClasses.map { c -> c to true }) } if (surroundingSpan) { h("div", opt, arrayOf(h("span", arrayOf(render())))) } else { h("div", opt, arrayOf(render())) } } } /** * Translates given text with I18n trans function and sets lastLanguage marker. * @param text a text marked for a dynamic translation * @return translated text */ protected fun translate(text: String): String { lastLanguage = I18n.language return trans(text) } protected fun translate(text: String?): String? { return text?.let { translate(it) } } /** * Renders current component as a Snabbdom vnode. * @return Snabbdom vnode */ protected open fun render(): VNode { return render("div") } /** * Renders current component as a Snabbdom vnode. * @param elementName HTML element name * @return Snabbdom vnode */ protected open fun render(elementName: String): VNode { return h(elementName, getSnOpt()) } /** * Renders current component as a Snabbdom vnode. * @param elementName HTML element name * @param children array of children nodes * @return Snabbdom vnode */ protected open fun render(elementName: String, children: Array): VNode { return h(elementName, getSnOpt(), children) } /** * Generates VNodeData to creating Snabbdom VNode. * * Optimizes creating process by keeping configuration attributes in a cache. */ private fun getSnOpt(): VNodeData { return snOpt { key = vnkey attrs = snAttrs(getSnAttrsInternal()) style = snStyle(getSnStyleInternal()) `class` = snClasses(getSnClassInternal()) on = getSnOn() hook = getSnHooksInternal() } } private fun getSnAttrsInternal(): List { if (lastLanguage != null && lastLanguage != I18n.language) snAttrsCache = null return snAttrsCache ?: { val s = getSnAttrs() snAttrsCache = s s }() } private fun getSnClassInternal(): List { return snClassCache ?: { val s = getSnClass() snClassCache = s s }() } private fun getSnHooksInternal(): com.github.snabbdom.Hooks? { return snHooksCache ?: { val s = getSnHooks() snHooksCache = s s }() } /** * Returns list of CSS class names for current widget in the form of a List. * @return list of CSS class names */ protected open fun getSnClass(): List { return classes.map { c -> c to true } + if (visible) listOf() else listOf("hidden" to true) } /** * Returns list of element attributes in the form of a List. * @return list of element attributes */ protected open fun getSnAttrs(): List { val snattrs = mutableListOf() id?.let { snattrs.add("id" to it) } title?.let { snattrs.add("title" to translate(it)) } role?.let { snattrs.add("role" to it) } tabindex?.let { snattrs.add("tabindex" to it.toString()) } if (draggable == true) { snattrs.add("draggable" to "true") } if (attributes.isNotEmpty()) { snattrs += attributes.toList() } return snattrs } /** * Returns list of event handlers in the form of a Snabbdom *On* object. * @return list of event handlers */ protected open fun getSnOn(): com.github.snabbdom.On? { val map = internalListenersMap.filter { it.key != "self" && it.value.isNotEmpty() }.map { val internalListeners = mutableMapOf.() -> Unit>() internalListeners.putAll(it.value) it.key to internalListeners }.toMap().toMutableMap() listenersMap.filter { it.key != "self" && it.value.isNotEmpty() } .forEach { (event, listeners) -> val internalListeners = map[event] if (internalListeners != null) { internalListeners.putAll(listeners) } else { map[event] = listeners } } return if (map.isNotEmpty()) { val handlers = emptyOn() map.forEach { (event, listeners) -> handlers.asDynamic()[event] = if (listeners.size == 1) { listeners.values.first() } else { listeners.map { arrayOf(it.value) }.toTypedArray() } } handlers } else { null } } /** * Returns list of hooks in the form of a Snabbdom *Hooks* object. * @return list of hooks */ protected open fun getSnHooks(): com.github.snabbdom.Hooks? { val hooks = hooks() hooks.apply { create = { _, v -> vnode = v afterCreate(v) } insert = { v -> vnode = v afterInsertInternal(v) afterInsert(v) afterInsertHook?.invoke(v) } destroy = { afterDestroyInternal() afterDestroy() afterDestroyHook?.invoke() vnode = null vnode } } return hooks } /** * @suppress * Internal function */ @Suppress("UNCHECKED_CAST", "UnsafeCastFromDynamic") protected fun setInternalEventListener(block: SnOn.() -> Unit): Int { val handlerCounter = listenerCounter++ val blockAsWidget = block as SnOn.() -> Unit val handlers = on(this) (handlers::apply)(blockAsWidget) for (key: String in js("Object").keys(handlers)) { val handler = handlers.asDynamic()[key] val map = internalListenersMap[key] if (map != null) { map[handlerCounter] = handler } else { internalListenersMap[key] = mutableMapOf(handlerCounter to handler) } } refresh() return handlerCounter } /** * Sets an event listener for current widget, keeping the actual type of component. * @param T widget type * @param block event handler * @return id of the handler * * Example: * * button.setEventListener