1 /* 2 * Copyright 2023 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.compose.ui.focus 18 19 import androidx.compose.ui.Modifier 20 import androidx.compose.ui.internal.JvmDefaultWithCompatibility 21 import androidx.compose.ui.node.ModifierNodeElement 22 import androidx.compose.ui.platform.InspectorInfo 23 24 /** A [modifier][Modifier.Element] that can be used to observe focus state events. */ 25 @Deprecated("Use FocusEventModifierNode instead") 26 @JvmDefaultWithCompatibility 27 interface FocusEventModifier : Modifier.Element { 28 /** A callback that is called whenever the focus system raises events. */ onFocusEventnull29 fun onFocusEvent(focusState: FocusState) 30 } 31 32 /** Add this modifier to a component to observe focus state events. */ 33 fun Modifier.onFocusEvent(onFocusEvent: (FocusState) -> Unit): Modifier = 34 this then FocusEventElement(onFocusEvent) 35 36 private class FocusEventElement(val onFocusEvent: (FocusState) -> Unit) : 37 ModifierNodeElement<FocusEventNode>() { 38 override fun create() = FocusEventNode(onFocusEvent) 39 40 override fun update(node: FocusEventNode) { 41 node.onFocusEvent = onFocusEvent 42 } 43 44 override fun InspectorInfo.inspectableProperties() { 45 name = "onFocusEvent" 46 properties["onFocusEvent"] = onFocusEvent 47 } 48 49 override fun equals(other: Any?): Boolean { 50 if (this === other) return true 51 if (other !is FocusEventElement) return false 52 53 if (onFocusEvent !== other.onFocusEvent) return false 54 55 return true 56 } 57 58 override fun hashCode(): Int { 59 return onFocusEvent.hashCode() 60 } 61 } 62 63 private class FocusEventNode(var onFocusEvent: (FocusState) -> Unit) : 64 FocusEventModifierNode, Modifier.Node() { 65 onFocusEventnull66 override fun onFocusEvent(focusState: FocusState) { 67 this.onFocusEvent.invoke(focusState) 68 } 69 } 70