1 /*
2  * Copyright 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.glance.text
18 
19 import androidx.annotation.RestrictTo
20 import androidx.compose.runtime.Composable
21 import androidx.compose.ui.graphics.Color
22 import androidx.glance.Emittable
23 import androidx.glance.EmittableWithText
24 import androidx.glance.GlanceModifier
25 import androidx.glance.GlanceNode
26 import androidx.glance.text.TextDefaults.defaultTextStyle
27 import androidx.glance.unit.ColorProvider
28 
29 /**
30  * Adds a text view to the glance view.
31  *
32  * @param text The text to be displayed.
33  * @param modifier [GlanceModifier] to apply to this layout node.
34  * @param style [TextStyle]] configuration for the text such as color, font, text align etc.
35  * @param maxLines An optional maximum number of lines for the text to span, wrapping if necessary.
36  *   If the text exceeds the given number of lines, it will be truncated.
37  */
38 @Composable
Textnull39 fun Text(
40     text: String,
41     modifier: GlanceModifier = GlanceModifier,
42     style: TextStyle = defaultTextStyle,
43     maxLines: Int = Int.MAX_VALUE,
44 ) {
45     GlanceNode(
46         factory = ::EmittableText,
47         update = {
48             this.set(text) { this.text = it }
49             this.set(modifier) { this.modifier = it }
50             this.set(style) { this.style = it }
51             this.set(maxLines) { this.maxLines = it }
52         }
53     )
54 }
55 
56 object TextDefaults {
57     val defaultTextColor = ColorProvider(Color.Black)
58     val defaultTextStyle: TextStyle = TextStyle(color = defaultTextColor)
59 }
60 
61 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
62 class EmittableText : EmittableWithText() {
63     override var modifier: GlanceModifier = GlanceModifier
64 
copynull65     override fun copy(): Emittable =
66         EmittableText().also {
67             it.modifier = modifier
68             it.text = text
69             it.style = style
70             it.maxLines = maxLines
71         }
72 
toStringnull73     override fun toString(): String =
74         "EmittableText($text, style=$style, modifier=$modifier, maxLines=$maxLines)"
75 }
76