package com.platformcomponents import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.text.TextUtils import android.util.TypedValue import android.view.ContextThemeWrapper import android.view.View import android.widget.FrameLayout import android.widget.LinearLayout import com.facebook.react.bridge.WritableNativeMap import com.facebook.react.uimanager.PixelUtil import com.facebook.react.uimanager.ReactCompoundViewGroup import com.facebook.react.uimanager.StateWrapper import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper import com.facebook.react.views.scroll.ReactScrollViewHelper import com.facebook.react.views.text.ReactTypefaceUtils import com.google.android.material.badge.BadgeDrawable import com.google.android.material.badge.BadgeUtils import com.google.android.material.button.MaterialButton import com.google.android.material.button.MaterialButtonToggleGroup class PCSegmentedControlView(context: Context) : FrameLayout(context), ReactScrollViewHelper.HasStateWrapper, ReactCompoundViewGroup { data class Segment( val label: String, val value: String, val disabled: Boolean, /** "", "sfSymbol" (ignored on Android), "drawable" or "image" */ val iconType: String, val iconName: String, val iconUri: String, val iconScale: Float, val iconTinted: Boolean, val badge: String, val accessibilityLabel: String, val testID: String = "", val iconRequest: String = "" ) { val hasIcon: Boolean get() = iconType == "drawable" || iconType == "image" /** What TalkBack announces for the segment, badge included. */ val spokenLabel: String get() { val base = accessibilityLabel.ifEmpty { label } return if (badge.isEmpty()) base else "$base, $badge" } } companion object { private const val TAG = "PCSegmentedControl" } // --- State Wrapper for Fabric state updates --- override var stateWrapper: StateWrapper? = null private var lastReportedWidth: Float = 0f private var lastReportedHeight: Float = 0f // --- Props --- var segments: List = emptyList() var selectedValue: String = "" // sentinel for none var interactivity: String = "enabled" // "enabled" | "disabled" var labelVisibility: String = "auto" // "auto" | "labeled" | "unlabeled" // Matches iOS, where a UISegmentedControl selection cannot be cleared by tapping. var selectionRequired: Boolean = true // android.material: "expressive" (the Material 3 Expressive connected buttons) | "m3" var expressive: Boolean = true // --- Styling (null / empty = Material theme default) --- var selectedSegmentColor: Int? = null var activeTintColor: Int? = null var inactiveTintColor: Int? = null var rippleColor: Int? = null var strokeColor: Int? = null var labelFontFamily: String = "" var labelFontSize: Float = 0f var labelFontWeight: String = "" var labelFontStyle: String = "" var badgeBackgroundColor: Int? = null var badgeTextColor: Int? = null var maxFontSizeMultiplier: Float = 0f /** Smallest visible height of the buttons in dp; negative = Material's (40dp). */ var controlMinHeight: Float = -1f /** The `haptics` prop; the manager plays it with the user's action (see PCHaptics). */ var haptics: String = "" // --- Events --- /** index -1 with an empty value means the selection was cleared. */ var onSelect: ((index: Int, value: String) -> Unit)? = null // --- UI --- private var toggleGroup: MaterialButtonToggleGroup? = null private val buttonIdToSegment: MutableMap = mutableMapOf() private var suppressCallbacks = false /** Bumped on every rebuild so late image loads can't touch stale buttons. */ private var rebuildGeneration = 0 // A height below the buttons' own (see fitButtons). Declared above init, // which rebuilds the buttons. /** The buttons' own height in px, with all their insets and padding. */ private var naturalHeight = 0 /** Vertical px currently taken out of every button. */ private var squeezed = 0 /** Each button's insetTop, insetBottom, paddingTop, paddingBottom as built. */ private val buttonVerticalDefaults: MutableMap = mutableMapOf() // --- Native theme --- // Widgets read theme colors when they are created, so they are rebuilt when the // native theme changes (brand color, light/dark switch). private var builtThemeVersion = PCNativeTheme.version private val nativeThemeListener = PCNativeTheme.Listener { PCThemeSupport.clearColorStateListCaches(this) rebuildUI() } init { // Badges overhang the button corner clipChildren = false clipToPadding = false rebuildUI() } // ---- Public apply* (called by manager) ---- fun applySegments(newSegments: List) { if (segments == newSegments) return segments = newSegments rebuildUI() } fun applySelectedValue(value: String) { if (selectedValue == value) return selectedValue = value updateSelection() } fun applyInteractivity(value: String?) { val newValue = if (value == "disabled") "disabled" else "enabled" if (interactivity == newValue) return interactivity = newValue updateEnabled() } fun applyLabelVisibility(value: String?) { val newValue = when (value) { "labeled", "unlabeled" -> value else -> "auto" } if (labelVisibility == newValue) return labelVisibility = newValue rebuildUI() } fun applyAndroidProps(required: Boolean, expressiveStyle: Boolean) { if (selectionRequired != required || expressive != expressiveStyle) { selectionRequired = required expressive = expressiveStyle rebuildUI() } } fun applySelectedSegmentColor(color: Int?) { if (selectedSegmentColor == color) return selectedSegmentColor = color rebuildUI() } fun applyActiveTintColor(color: Int?) { if (activeTintColor == color) return activeTintColor = color rebuildUI() } fun applyInactiveTintColor(color: Int?) { if (inactiveTintColor == color) return inactiveTintColor = color rebuildUI() } fun applyRippleColor(color: Int?) { if (rippleColor == color) return rippleColor = color rebuildUI() } fun applyStrokeColor(color: Int?) { if (strokeColor == color) return strokeColor = color rebuildUI() } fun applyBadgeColors(background: Int?, text: Int?) { if (badgeBackgroundColor == background && badgeTextColor == text) return badgeBackgroundColor = background badgeTextColor = text rebuildUI() } fun applyMaxFontSizeMultiplier(value: Float) { if (maxFontSizeMultiplier == value) return maxFontSizeMultiplier = value rebuildUI() } fun applyControlMinHeight(value: Float) { if (controlMinHeight == value) return controlMinHeight = value rebuildUI() } fun applyLabelStyle(fontFamily: String, fontSize: Float, fontWeight: String, fontStyle: String) { if (labelFontFamily == fontFamily && labelFontSize == fontSize && labelFontWeight == fontWeight && labelFontStyle == fontStyle ) return labelFontFamily = fontFamily labelFontSize = fontSize labelFontWeight = fontWeight labelFontStyle = fontStyle rebuildUI() } // The buttons have generated view ids, which React Native's touch handling would // take for React tags and dispatch JS touch events to unrelated views. Claim the // touch for this view instead; the buttons still receive it natively. override fun interceptsTouchEvent(touchX: Float, touchY: Float): Boolean = true override fun reactTagForTouch(touchX: Float, touchY: Float): Int = id override fun onAttachedToWindow() { super.onAttachedToWindow() PCNativeTheme.addListener(nativeThemeListener) PCNativeTheme.attach(context) if (builtThemeVersion != PCNativeTheme.version) nativeThemeListener.onNativeThemeChanged() } override fun onDetachedFromWindow() { PCNativeTheme.removeListener(nativeThemeListener) super.onDetachedFromWindow() } // ---- UI Building ---- private fun rebuildUI() { builtThemeVersion = PCNativeTheme.version removeAllViews() buttonIdToSegment.clear() buttonVerticalDefaults.clear() naturalHeight = 0 squeezed = 0 rebuildGeneration += 1 val generation = rebuildGeneration // Material widgets need a Material theme; fall back to Material 3 defaults instead of crashing. val materialContext = PCThemeSupport.materialContext(context, "SegmentedControl") // Expressive: the connected button group styles (2dp gaps, small inner // corners, the selected segment a pill) in place of the classic segmented buttons. val themedContext = if (expressive) ContextThemeWrapper(materialContext, R.style.PCExpressiveOverlay) else materialContext // The group and its buttons fill the height Yoga gives this view (the // buttons' own height unless the app sets one) val group = MaterialButtonToggleGroup(themedContext).apply { layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) isSingleSelection = true isSelectionRequired = selectionRequired clipChildren = false clipToPadding = false } // Calculate if we need compact mode (many segments or long labels) val totalLabelLength = segments.sumOf { it.label.length } val useCompactMode = segments.size > 3 || totalLabelLength > 20 for ((index, segment) in segments.withIndex()) { // "unlabeled" hides the text of segments that have an icon; segments // without one keep their label. "auto" and "labeled" show icon + label. val iconOnly = labelVisibility == "unlabeled" && segment.hasIcon val button = MaterialButton(themedContext, null, com.google.android.material.R.attr.materialButtonOutlinedStyle).apply { id = View.generateViewId() text = if (iconOnly) "" else segment.label isAllCaps = false // Preserve original text casing // Screen readers (and Detox) always get the label, even when hidden contentDescription = segment.spokenLabel // Detox matches the view tag PCTestID.apply(this, segment.testID) isEnabled = !segment.disabled && interactivity == "enabled" // Enable text truncation with ellipsis when space is limited ellipsize = TextUtils.TruncateAt.END maxLines = 1 // Material 3 segmented buttons use 12dp horizontal padding and an 8dp // icon gap (the outlined button style defaults to 24dp); tighten // further when there are many segments or long labels. val density = resources.displayMetrics.density val horizontalPadding = ((if (useCompactMode) 8 else 12) * density).toInt() setPaddingRelative(horizontalPadding, paddingTop, horizontalPadding, paddingBottom) iconPadding = ((if (useCompactMode) 4 else 8) * density).toInt() if (controlMinHeight >= 0) { // The visible height; Material's touch target insets stay around it val height = (controlMinHeight * density).toInt() + insetTop + insetBottom minHeight = height minimumHeight = height } if (iconOnly) { // Centre the icon instead of leaving it at the start edge iconGravity = MaterialButton.ICON_GRAVITY_TEXT_START iconPadding = 0 } applyIcon(this, segment, generation) styleButton(this, segment) } buttonIdToSegment[button.id] = segment buttonVerticalDefaults[button.id] = intArrayOf(button.insetTop, button.insetBottom, button.paddingTop, button.paddingBottom) // Share the width equally (like UISegmentedControl) so trailing segments // never overflow the control; long labels ellipsize instead. group.addView(button, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)) attachBadge(button, segment) } group.addOnButtonCheckedListener { toggleGroup, checkedId, isChecked -> if (suppressCallbacks) return@addOnButtonCheckedListener // Material toggles immediately. Restore the latest controlled prop once // that update finishes, including when the parent rejects the selection. post { updateSelection() } if (!isChecked) { // In single-selection mode switching from A to B reports A as unchecked // before B is reported as checked; by then the group already knows B is // checked. Only a tap that leaves nothing checked is a real deselection. if (toggleGroup.checkedButtonId == View.NO_ID) { onSelect?.invoke(-1, "") } return@addOnButtonCheckedListener } val segment = buttonIdToSegment[checkedId] ?: return@addOnButtonCheckedListener val index = segments.indexOf(segment) if (index >= 0) { onSelect?.invoke(index, segment.value) } } addView(group) toggleGroup = group updateSelection() updateEnabled() requestLayout() } /** * Resolves a segment's icon. Drawable names and release-bundled assets (which * React Native ships as drawable resources) resolve synchronously; other * image URIs load in the background and are applied when they arrive. */ private fun applyIcon(button: MaterialButton, segment: Segment, generation: Int) { if (!segment.iconTinted) { button.iconTint = null } when (segment.iconType) { "drawable" -> { button.icon = ResourceDrawableIdHelper.instance.getResourceDrawable(context, segment.iconName) } "image" -> { val uri = segment.iconUri val isResourceName = !uri.contains(':') if (isResourceName) { button.icon = ResourceDrawableIdHelper.instance.getResourceDrawable(context, uri) } else { PCImageLoader.load(context, uri, segment.iconScale, segment.iconRequest) { bitmap -> if (bitmap == null || generation != rebuildGeneration) return@load button.icon = BitmapDrawable(resources, bitmap) requestLayout() } } } } } /** * Draws a Material badge over the button's top-end corner. The badge lives * in the button's overlay, so it needs the button's final bounds: attach * after the first layout and follow later size changes. */ private fun attachBadge(button: MaterialButton, segment: Segment) { if (segment.badge.isEmpty()) return val inset = (2 * resources.displayMetrics.density).toInt() val badge = BadgeDrawable.create(button.context).apply { text = segment.badge badgeGravity = BadgeDrawable.TOP_END badgeBackgroundColor?.let { backgroundColor = it } badgeTextColor?.let { setBadgeTextColor(it) } } var attached = false button.addOnLayoutChangeListener { view, _, _, _, _, _, _, _, _ -> if (!attached) { attached = true BadgeUtils.attachBadgeDrawable(badge, view) // The badge's size is only known once it has an anchor. Offset it by // half its size so it sits fully inside the button corner; a badge // that overhangs the last segment would be clipped by the control. badge.horizontalOffset = badge.intrinsicWidth / 2 + inset badge.verticalOffset = badge.intrinsicHeight / 2 + inset } badge.updateBadgeCoordinates(view) } } /** * Applies the color and font props on top of the Material theme defaults. * Buttons are rebuilt whenever a style prop changes, so the theme values * read here are always the untouched defaults. */ private fun styleButton(button: MaterialButton, segment: Segment) { val checkedState = intArrayOf(android.R.attr.state_checked) val disabledState = intArrayOf(-android.R.attr.state_enabled) if (activeTintColor != null || inactiveTintColor != null) { val theme = button.textColors val disabled = theme.getColorForState(disabledState, theme.defaultColor) val checked = activeTintColor ?: theme.getColorForState(checkedState, theme.defaultColor) val normal = inactiveTintColor ?: theme.defaultColor val tint = ColorStateList( arrayOf(disabledState, checkedState, intArrayOf()), intArrayOf(disabled, checked, normal) ) button.setTextColor(tint) if (segment.iconTinted) { button.iconTint = tint } } selectedSegmentColor?.let { color -> val theme = button.backgroundTintList val normal = theme?.defaultColor ?: Color.TRANSPARENT button.backgroundTintList = ColorStateList( arrayOf(checkedState, intArrayOf()), intArrayOf(color, normal) ) } rippleColor?.let { button.rippleColor = ColorStateList.valueOf(it) } strokeColor?.let { button.strokeColor = ColorStateList.valueOf(it) } if (labelFontSize > 0) { button.setTextSize(TypedValue.COMPLEX_UNIT_SP, labelFontSize) } if (labelFontFamily.isNotEmpty() || labelFontWeight.isNotEmpty() || labelFontStyle.isNotEmpty()) { button.typeface = ReactTypefaceUtils.applyStyles( button.typeface, ReactTypefaceUtils.parseFontStyle(labelFontStyle.ifEmpty { null }), ReactTypefaceUtils.parseFontWeight(labelFontWeight.ifEmpty { null }), labelFontFamily.ifEmpty { null }, context.assets ) } button.setTag(R.id.pc_capped_text_size, null) PCThemeSupport.capTextSize(button, maxFontSizeMultiplier) } private fun updateSelection() { val group = toggleGroup ?: return suppressCallbacks = true val selectedId = buttonIdToSegment.entries.firstOrNull { it.value.value == selectedValue }?.key if (selectedId == null) group.clearChecked() else group.check(selectedId) suppressCallbacks = false } private fun updateEnabled() { val enabled = interactivity == "enabled" alpha = if (enabled) 1f else 0.5f val group = toggleGroup ?: return for (i in 0 until group.childCount) { val button = group.getChildAt(i) as? MaterialButton ?: continue val segment = buttonIdToSegment[button.id] ?: continue button.isEnabled = enabled && !segment.disabled } } // ---- Layout ---- private var manualLayoutPending = false /** * React Native's root view ignores requestLayout after the initial pass, so * a native view that changes its own subtree later (rebuilding segments for * a prop change, an icon finishing loading) has to measure and lay itself * out. Coalesced to one pass per frame. */ override fun requestLayout() { super.requestLayout() if (!manualLayoutPending) { manualLayoutPending = true PCManualLayout.beforeNextDraw(this) { if (manualLayoutPending) runManualLayout() } } } private fun runManualLayout() { manualLayoutPending = false // Nothing to do until Yoga has placed us; the regular pass covers that. if (width == 0 || height == 0) return measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) ) layout(left, top, right, bottom) } // ---- Measurement ---- override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { // The buttons' own height, measured while nothing is taken out of them if (squeezed == 0 || naturalHeight == 0) { fitButtons(0) super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) naturalHeight = toggleGroup?.measuredHeight ?: 0 } // Then the height Yoga gave us (an app's style height included); the // buttons fill it. Fabric may measure with 0 before the state is // applied; keep the buttons' height then. val exact = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY val givenHeight = MeasureSpec.getSize(heightMeasureSpec) val height = if (exact && givenHeight > 0) givenHeight else naturalHeight fitButtons(maxOf(0, naturalHeight - height)) super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)) setMeasuredDimension(measuredWidth, height) } /** * Takes [amount] px out of every button's height, from Material's touch * target insets first. Past those, the vertical padding goes as well and * the button's center gravity places the label, so it stays whole and * centered when the control is shorter than its buttons. */ private fun fitButtons(amount: Int) { if (amount == squeezed) return squeezed = amount val group = toggleGroup ?: return for (i in 0 until group.childCount) { val button = group.getChildAt(i) as? MaterialButton ?: continue val (insetTop, insetBottom, padTop, padBottom) = buttonVerticalDefaults[button.id] ?: continue val insetCut = minOf(amount, insetTop + insetBottom) val padCut = if (amount > insetCut) padTop + padBottom else 0 button.insetTop = insetTop - insetCut / 2 button.insetBottom = insetBottom - (insetCut - insetCut / 2) button.setPaddingRelative( button.paddingStart, padTop - padCut / 2, button.paddingEnd, padBottom - (padCut - padCut / 2) ) } } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) updateFrameSizeState() } /** * Update Fabric state with the measured frame size. * This allows the shadow node to use actual measured dimensions for Yoga layout. */ private fun updateFrameSizeState() { val wrapper = stateWrapper ?: return val group = toggleGroup ?: return // Measure the toggle group with exact width and unspecified height val widthSpec = MeasureSpec.makeMeasureSpec(width.coerceAtLeast(1), MeasureSpec.EXACTLY) val heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) group.measure(widthSpec, heightSpec) val widthDp = PixelUtil.toDIPFromPixel(width.toFloat()) // The buttons' own height, even while they are squeezed into less val heightPx = if (squeezed > 0 && naturalHeight > 0) naturalHeight else group.measuredHeight val heightDp = PixelUtil.toDIPFromPixel(heightPx.toFloat()) // Measure the group again at the size it is laid out at if (group.width > 0 && group.height > 0) { group.measure( MeasureSpec.makeMeasureSpec(group.width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(group.height, MeasureSpec.EXACTLY) ) } // Only update if changed if (widthDp != lastReportedWidth || heightDp != lastReportedHeight) { lastReportedWidth = widthDp lastReportedHeight = heightDp val stateData = WritableNativeMap().apply { putDouble("width", widthDp.toDouble()) putDouble("height", heightDp.toDouble()) } wrapper.updateState(stateData) } } }