xref: /expo/docs/ui/components/Text/index.tsx (revision 7c3fd962)
1import { css, SerializedStyles } from '@emotion/react';
2import { theme, typography, spacing, borderRadius } from '@expo/styleguide';
3import * as React from 'react';
4
5import { LinkBase, LinkProps } from './Link';
6import { TextComponentProps, TextElement } from './types';
7
8import { AdditionalProps, HeadingType } from '~/common/headingManager';
9import Permalink from '~/components/Permalink';
10import { durations } from '~/ui/foundations/durations';
11
12export { LinkBase } from './Link';
13export { AnchorContext } from './withAnchor';
14
15const CRAWLABLE_HEADINGS = ['h1', 'h2', 'h3', 'h4', 'h5'];
16const CRAWLABLE_TEXT = ['span', 'p', 'li', 'blockquote', 'code', 'pre'];
17
18type PermalinkedComponentProps = React.PropsWithChildren<
19  { level?: number; id?: string } & AdditionalProps
20>;
21
22const isDev = process.env.NODE_ENV === 'development';
23
24export const createPermalinkedComponent = (
25  BaseComponent: React.ComponentType<React.PropsWithChildren<any>>,
26  options?: {
27    baseNestingLevel?: number;
28    sidebarType?: HeadingType;
29  }
30) => {
31  const { baseNestingLevel, sidebarType = HeadingType.Text } = options || {};
32  return ({ children, level, id, ...props }: PermalinkedComponentProps) => {
33    const cleanChildren = React.Children.map(children, child => {
34      if (React.isValidElement(child) && child?.props?.href) {
35        isDev &&
36          console.warn(
37            `It looks like the header on this page includes a link, this is an invalid pattern, nested link will be removed!`,
38            child?.props?.href
39          );
40        return (child as JSX.Element)?.props?.children;
41      }
42      return child;
43    });
44    const nestingLevel = baseNestingLevel != null ? (level ?? 0) + baseNestingLevel : undefined;
45    return (
46      <Permalink nestingLevel={nestingLevel} additionalProps={{ ...props, sidebarType }} id={id}>
47        <BaseComponent>{cleanChildren}</BaseComponent>
48      </Permalink>
49    );
50  };
51};
52
53export function createTextComponent(Element: TextElement, textStyle?: SerializedStyles) {
54  function TextComponent(props: TextComponentProps) {
55    const { testID, tag, weight: textWeight, theme: textTheme, ...rest } = props;
56    const TextElementTag = tag ?? Element;
57
58    return (
59      <TextElementTag
60        css={[
61          baseTextStyle,
62          textStyle,
63          textWeight && { fontWeight: typography.utility.weight[textWeight].fontWeight },
64          textTheme && { color: theme.text[textTheme] },
65        ]}
66        data-testid={testID}
67        data-heading={CRAWLABLE_HEADINGS.includes(TextElementTag) || undefined}
68        data-text={CRAWLABLE_TEXT.includes(TextElementTag) || undefined}
69        {...rest}
70      />
71    );
72  }
73  TextComponent.displayName = `Text(${Element})`;
74  return TextComponent;
75}
76
77const baseTextStyle = css({
78  ...{ ...typography.body.paragraph, fontFamily: undefined },
79  color: theme.text.default,
80});
81
82const link = css({
83  cursor: 'pointer',
84  textDecoration: 'none',
85
86  ':hover': {
87    transition: durations.hover,
88    opacity: 0.8,
89  },
90});
91
92const linkStyled = css({
93  ...typography.utility.anchor,
94
95  // note(Cedric): transform prevents a 1px shift on hover on Safari
96  transform: 'translate3d(0,0,0)',
97
98  ':hover': {
99    textDecoration: 'underline',
100
101    code: {
102      textDecoration: 'inherit',
103    },
104  },
105
106  'span, code, strong, em, b, i': {
107    color: theme.link.default,
108  },
109});
110
111const listStyle = css({
112  marginLeft: '1.5rem',
113});
114
115const codeStyle = css({
116  borderRadius: borderRadius.small,
117  verticalAlign: 'initial',
118});
119
120export const kbdStyle = css({
121  fontWeight: 500,
122  color: theme.text.secondary,
123  padding: `0 ${spacing[1]}px`,
124  boxShadow: `0 0.1rem 0 1px ${theme.border.default}`,
125  borderRadius: borderRadius.small,
126  position: 'relative',
127  display: 'inline-flex',
128  margin: 0,
129  minWidth: 22,
130  justifyContent: 'center',
131  top: -1,
132});
133
134const { h1, h2, h3, h4, h5 } = typography.headers.default;
135const skipFontFamily = { fontFamily: undefined };
136const codeInHeaderStyle = { '& code': { fontSize: 'inherit' } };
137
138const h1Style = {
139  ...h1,
140  ...skipFontFamily,
141  fontWeight: 600,
142  marginTop: spacing[2],
143  marginBottom: spacing[2],
144  ...codeInHeaderStyle,
145};
146
147const h2Style = {
148  ...h2,
149  ...skipFontFamily,
150  fontWeight: 600,
151  marginTop: spacing[8],
152  marginBottom: spacing[3],
153  ...codeInHeaderStyle,
154};
155
156const h3Style = {
157  ...h3,
158  ...skipFontFamily,
159  fontWeight: 600,
160  marginTop: spacing[6],
161  marginBottom: spacing[1.5],
162  ...codeInHeaderStyle,
163};
164
165const h4Style = {
166  ...h4,
167  ...skipFontFamily,
168  fontWeight: 600,
169  marginTop: spacing[6],
170  marginBottom: spacing[1],
171  ...codeInHeaderStyle,
172};
173
174const h5Style = {
175  ...h5,
176  ...skipFontFamily,
177  fontWeight: 600,
178  marginTop: spacing[4],
179  marginBottom: spacing[1],
180  ...codeInHeaderStyle,
181};
182
183export const H1 = createTextComponent(TextElement.H1, css(h1Style));
184export const RawH2 = createTextComponent(TextElement.H2, css(h2Style));
185export const H2 = createPermalinkedComponent(RawH2, { baseNestingLevel: 2 });
186export const RawH3 = createTextComponent(TextElement.H3, css(h3Style));
187export const H3 = createPermalinkedComponent(RawH3, { baseNestingLevel: 3 });
188export const RawH4 = createTextComponent(TextElement.H4, css(h4Style));
189export const H4 = createPermalinkedComponent(RawH4, { baseNestingLevel: 4 });
190export const RawH5 = createTextComponent(TextElement.H5, css(h5Style));
191export const H5 = createPermalinkedComponent(RawH5, { baseNestingLevel: 5 });
192
193export const P = createTextComponent(TextElement.P);
194export const CODE = createTextComponent(
195  TextElement.CODE,
196  css([{ ...typography.utility.inlineCode, ...skipFontFamily }, codeStyle])
197);
198export const LI = createTextComponent(
199  TextElement.LI,
200  css({ ...typography.body.li, ...skipFontFamily })
201);
202export const LABEL = createTextComponent(
203  TextElement.SPAN,
204  css({ ...typography.body.label, ...skipFontFamily })
205);
206export const HEADLINE = createTextComponent(
207  TextElement.P,
208  css({ ...typography.body.headline, ...skipFontFamily })
209);
210export const FOOTNOTE = createTextComponent(
211  TextElement.P,
212  css({ ...typography.body.footnote, ...skipFontFamily })
213);
214export const CALLOUT = createTextComponent(
215  TextElement.P,
216  css({ ...typography.body.callout, ...skipFontFamily })
217);
218export const BOLD = createTextComponent(TextElement.STRONG, css({ fontWeight: 600 }));
219export const DEMI = createTextComponent(TextElement.SPAN, css({ fontWeight: 500 }));
220export const UL = createTextComponent(TextElement.UL, css([typography.body.ul, listStyle]));
221export const OL = createTextComponent(TextElement.OL, css([typography.body.ol, listStyle]));
222export const PRE = createTextComponent(
223  TextElement.PRE,
224  css({ ...typography.utility.pre, ...skipFontFamily })
225);
226export const KBD = createTextComponent(
227  TextElement.KBD,
228  css([{ ...typography.utility.pre, ...skipFontFamily }, kbdStyle])
229);
230export const MONOSPACE = createTextComponent(TextElement.CODE, css({ fontWeight: 500 }));
231
232const isExternalLink = (href?: string) => href?.includes('://');
233
234export const A = (props: LinkProps & { isStyled?: boolean }) => {
235  const { isStyled, ...rest } = props;
236  return (
237    <LinkBase
238      css={[link, !isStyled && linkStyled]}
239      openInNewTab={isExternalLink(props.href)}
240      {...rest}
241    />
242  );
243};
244A.displayName = 'Text(a)';
245