All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.mvysny.karibudsl.v10.Details.kt Maven / Gradle / Ivy

The newest version!
package com.github.mvysny.karibudsl.v10

import com.github.mvysny.kaributools.VaadinVersion
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.HasComponents
import com.vaadin.flow.component.details.Details
import com.vaadin.flow.component.html.Div
import kotlin.streams.toList

internal fun Component.checkOneChildAndGet(producerName: String): Component {
    val count: Long = children.count()
    check(count == 1L) { "$producerName was expected to produce 1 component but it produced $count" }
    return children.findFirst().get()
}

/**
 * Creates a [Details](https://vaadin.com/components/vaadin-details). Code example:
 *
 * ```
 * details("Hello") {
 *   content { button("hi!") }
 * }
 * ```
 */
@VaadinDsl
public fun (@VaadinDsl HasComponents).details(summaryText: String? = null, block: (@VaadinDsl Details).() -> Unit = {}): Details {
    val details = Details()
    if (summaryText != null) {
        details.summaryText = summaryText
    }
    return init(details, block)
}

/**
 * Allows you to set the summary of this [Details] as a component:
 * ```
 * details {
 *   summary { button("learn more") }
 * }
 * ```
 */
@VaadinDsl
public fun (@VaadinDsl Details).summary(block: (@VaadinDsl HasComponents).() -> Unit = {}) {
    val div = Div() // throwaway div, will be used to grab components produced by block
    div.block()
    val child: Component = div.checkOneChildAndGet("block()")
    this.summary = child
}

/**
 * Removes all [content][Details.getContent] components from this [Details].
 */
public fun Details.clearContent() {
    if (VaadinVersion.get.isAtLeast(24, 2)) {
        Details::class.java.getMethod("removeAll").invoke(this)
    } else {
        @Suppress("DEPRECATION")  // no other way to do this for Vaadin 24.1 and lower
        setContent(null)
    }
}

/**
 * Clears previous contents and re-populates the content of this [Details].
 */
@VaadinDsl
public fun (@VaadinDsl Details).content(block: (@VaadinDsl HasComponents).() -> Unit = {}) {
    clearContent()
    val div = Div() // throwaway div, will be used to grab components produced by block
    div.block()
    if (VaadinVersion.get.isAtLeast(24, 2)) {
        add(div.children.toList())
    } else {
        @Suppress("DEPRECATION")  // no other way to do this for Vaadin 24.1 and lower
        addContent(*div.children.toList().toTypedArray())
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy