|
| 1 | +/* |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +package com.facebook.react.views.text; |
| 9 | + |
| 10 | +import android.text.TextPaint; |
| 11 | +import android.text.style.ClickableSpan; |
| 12 | +import android.view.View; |
| 13 | +import androidx.annotation.NonNull; |
| 14 | +import com.facebook.react.bridge.ReactContext; |
| 15 | +import com.facebook.react.uimanager.UIManagerHelper; |
| 16 | +import com.facebook.react.uimanager.events.EventDispatcher; |
| 17 | +import com.facebook.react.views.view.ViewGroupClickEvent; |
| 18 | + |
| 19 | +/** |
| 20 | + * This class is used in {@link TextLayoutManager} to linkify and style a span of text with |
| 21 | + * accessibilityRole="link". This is needed to make nested Text components accessible. |
| 22 | + * |
| 23 | + * <p>For example, if your React component looks like this: |
| 24 | + * |
| 25 | + * <pre>{@code |
| 26 | + * <Text> |
| 27 | + * Some text with |
| 28 | + * <Text onPress={onPress} accessible={true} accessibilityRole="link">a link</Text> |
| 29 | + * in the middle. |
| 30 | + * </Text> |
| 31 | + * }</pre> |
| 32 | + * |
| 33 | + * then only one {@link ReactTextView} will be created, for the parent. The child Text component |
| 34 | + * does not exist as a native view, and therefore has no accessibility properties. Instead, we have |
| 35 | + * to use spans on the parent's {@link ReactTextView} to properly style the child, and to make it |
| 36 | + * accessible (TalkBack announces that the text has links available, and the links are exposed in |
| 37 | + * the context menu). |
| 38 | + */ |
| 39 | +class ReactClickableSpan extends ClickableSpan implements ReactSpan { |
| 40 | + |
| 41 | + private final int mReactTag; |
| 42 | + private final int mForegroundColor; |
| 43 | + |
| 44 | + ReactClickableSpan(int reactTag, int foregroundColor) { |
| 45 | + mReactTag = reactTag; |
| 46 | + mForegroundColor = foregroundColor; |
| 47 | + } |
| 48 | + |
| 49 | + @Override |
| 50 | + public void onClick(@NonNull View view) { |
| 51 | + ReactContext context = (ReactContext) view.getContext(); |
| 52 | + EventDispatcher eventDispatcher = |
| 53 | + UIManagerHelper.getEventDispatcherForReactTag(context, mReactTag); |
| 54 | + if (eventDispatcher != null) { |
| 55 | + eventDispatcher.dispatchEvent(new ViewGroupClickEvent(mReactTag)); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public void updateDrawState(@NonNull TextPaint ds) { |
| 61 | + super.updateDrawState(ds); |
| 62 | + ds.setColor(mForegroundColor); |
| 63 | + ds.setUnderlineText(false); |
| 64 | + } |
| 65 | + |
| 66 | + public int getReactTag() { |
| 67 | + return mReactTag; |
| 68 | + } |
| 69 | +} |
0 commit comments