Hi. Is there a way to attach semantics to a custom...
# compose
s
Hi. Is there a way to attach semantics to a custom composable? This code adds the
testTag
to the
Text
node, but can i add it to
Greeting
instead?
Copy code
@Composable
fun Greeting(name: String) {
    Text(
        modifier = Modifier.semantics {
            testTag = "My testTag"
        },
        text = "Hello $name!"
    )
}
e
You just could add a Modifier param to your Greeting.
Copy code
@Composable
fun Greeting(…, modifier: Modifier = Modifier) {
    Text(modifier = modifier, text = "Hello world")
}
s
I've tried that, but the semantics are not attached to it in that case
e
Dont have much experience with semantics particularly. But from a kotlin perspective, maybe try passing in a higher order function on the modifier then
Copy code
@Composable
fun Greeting(…, block: Modifier.() -> Unit) {
    Text(modifier = Modifier.apply { block() }, text = "Hello world")
}
thus calling would be
Greeting(name = "Simon", block = { semantics { testTag = "tag" } } )
s
hmm, i'm not quite sure how this would apply them to
Greeting
. I tested it real quick anyways and it does not.
To be clear, this is what i am looking for in the layout inspector
m
My general assumption here is that because you are simply outputting a Text element, there's no node generated for the Greeting function itself. So there is no place to attach any semantics other than the Text node. Consider these two functions:
Copy code
@Composable
fun Greeting(modifier: Modifier = Modifier, name: String) {
    Text(
        modifier = modifier.testTag("My Test Tag"),
        text = "Hello $name!"
    )
}

@Composable
fun Greeting2(modifier: Modifier = Modifier, name: String) {
    Greeting(modifier, name)
}
They both output the EXACT SAME semantic tree, regardless of which one you call.
Copy code
Node #1 at (l=0.0, t=0.0, r=11.0, b=41.0)px
 |-Node #2 at (l=0.0, t=0.0, r=11.0, b=41.0)px, Tag: 'My Test Tag'
   Text = '[Hello Matt!]'
   Actions = [GetTextLayoutResult]
Node #1 is the root node, which you'll find on all trees. Node #2 is the text node.
Creating a Composable function IS NOT the same as creating a node in the tree.
s
Thanks @mattinger. That is pretty much what I thought, but I wanted to ask anyways because when you look at it in the layout inspector, you do see
Greeting
in the composable tree, but I guess that is not the same as the semantics tree that is build internally.