Kotlin UI DSL: strict validation for LABEL_FOR and tests

GitOrigin-RevId: c72e012696aab5fc8ff834a140d9c0bf89d55d2c
This commit is contained in:
Pavel Porvatov
2022-09-07 13:25:49 +00:00
committed by intellij-monorepo-bot
parent 06da957994
commit 6aa8ca39ee
2 changed files with 68 additions and 3 deletions
@@ -155,8 +155,15 @@ private fun getLabelComponentFor(cell: CellBaseImpl<*>?): JComponent? {
}
private fun getLabelComponentFor(component: JComponent): JComponent? {
val delegate = component.getClientProperty(DslComponentProperty.LABEL_FOR) as? JComponent
if (delegate != null && delegate !== component) return getLabelComponentFor(delegate)
val labelFor = component.getClientProperty(DslComponentProperty.LABEL_FOR)
if (labelFor != null) {
if (labelFor is JComponent) {
return labelFor
}
else {
throw UiDslException("LABEL_FOR must be a JComponent: ${labelFor::class.java.name}")
}
}
if (ALLOWED_LABEL_COMPONENTS.any { clazz -> clazz.isInstance(component) }) {
return component
@@ -164,7 +171,6 @@ private fun getLabelComponentFor(component: JComponent): JComponent? {
return null
}
internal fun warn(message: String) {
if (FAIL_ON_WARN) {
throw UiDslException(message)
@@ -0,0 +1,59 @@
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.builder
import com.intellij.ui.dsl.UiDslException
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import java.awt.TextArea
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JTextField
import kotlin.test.assertEquals
class LabelTest {
@Test
fun testLabelFor() {
val label = JLabel("Label:")
lateinit var component: JTextField
panel {
row(label) {
component = textField().component
}
}
assertEquals(label.labelFor, component)
}
@Test
fun testLabelForProperty() {
val label = JLabel("Label:")
val panel = JPanel()
val textField = JTextField()
panel.add(textField)
panel.putClientProperty(DslComponentProperty.LABEL_FOR, textField)
panel {
row(label) {
cell(panel)
}
}
assertEquals(label.labelFor, textField)
}
@Test
fun testInvalidLabelForProperty() {
val label = JLabel("Label:")
val panel = JPanel()
val component = TextArea()
panel.add(component)
panel.putClientProperty(DslComponentProperty.LABEL_FOR, component)
assertThrows<UiDslException> {
panel {
row(label) {
cell(panel)
}
}
}
}
}