Skip to content

Commit e56b91a

Browse files
committed
RFC: Reduce API fragmentation across platforms
1 parent 5324ef5 commit e56b91a

File tree

1 file changed

+340
-0
lines changed

1 file changed

+340
-0
lines changed
Lines changed: 340 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,340 @@
1+
---
2+
title: Reduce API fragmentation across platforms
3+
author:
4+
- Nicolas Gallagher
5+
date: 2021-08-03
6+
---
7+
8+
# RFC: Reduce API fragmentation across platforms
9+
10+
## Summary
11+
12+
This is a proposal to incrementally reduce the API fragmentation faced by developers using React Native to target multiple platforms, and sharing code between native and web. Each proposed change is additive and can be tackled relatively independently. The aim is to avoid needing to migrate existing React Native code, and to make deprecations an optional and future part of this work.
13+
14+
## Motivation
15+
16+
React Native currently includes many APIs that are modelled on Web APIs but do not conform to the standards of those Web APIs. React Native also includes many APIs that achieve the same results on Android and iOS but are exposed as 2 different props. And React Native includes several APIs that have known performance (network and runtime) drawbacks on Web.
17+
18+
This proposal aims to allow developers to target more platforms with cross-platform APIs, and deliver better performance when targeting browsers. Features for Android, iOS, and Web are unified by aligning with the Web standard to a) minimize the overhead when running in browsers, and b) reduce developer education required to learn these features.
19+
20+
## Detailed design
21+
22+
Many of these additions are already in progress and have been proven in a user-space shim at Meta. The features that cannot be shimmed are explicitly called out below. Those features require core changes to React Native. Other features can be shimmed in user-space JavaScript if desired (with any associated performance cost of doing so).
23+
24+
### New common props
25+
26+
Certain props common to all core components have direct equivalents in React DOM. We should support those props where possible. For example, many of the existing `accessibility*` props in React Native are currently mapped to `aria-*` equivalents by React Native for Web. Supporting the ARIA interface would allow more ARIA-targeting React DOM libraries to work on React Native.
27+
28+
* ARIA props
29+
* `aria-busy` is the same as `accessibilityState.busy`.
30+
* `aria-checked` is the same as `accessibilityState.checked`.
31+
* `aria-disabled` is the same as `accessibilityState.disabled`.
32+
* `aria-expanded` is the same as `accessibilityState.expanded`.
33+
* `aria-hidden` is the same as `accessibilityElementsHidden` (iOS) / `importantforAccessibility` (Android).
34+
* `aria-label` is the same as `accessibilityLabel`.
35+
* `aria-live` is the same as `accessibilityLiveRegion` (with `'off'` value changed to `'none'`).
36+
* `aria-modal` is the same as `accessibilityViewIsModal`.
37+
* `aria-selected` is the same as `accessibilityState.selected`.
38+
* `aria-valuemax` is the same as `accessibilityValue.max`.
39+
* `aria-valuemin` is the same as `accessibilityValue.min`.
40+
* `aria-valuenow` is the same as `accessibilityValue.now`.
41+
* `aria-valuetext` is the same as `accessibilityValue.text`.
42+
* `role` is the same as `accessibilityRole` (with support for web values).
43+
* See prior work: [RFC Accessibility APIs](https://github.com/react-native-community/discussions-and-proposals/pull/410/files).
44+
* Add `dir` prop to configure element's layout / writing direction.
45+
* Make `id` the same as `nativeID`.
46+
* Make `onAuxClick` the same as React DOM `onAuxClick` PointerEvent (can't be shimmed).
47+
* Make `onClick` the same as React DOM `onClick` as PointerEvent (can't be shimmed).
48+
* Make `onPointer*` props that same as React DOM PointerEvent props (can't be shimmed).
49+
* The Android and iOS implementation is currently being developed by Meta.
50+
* Make `tabIndex` the same as React Native `focusable` prop.
51+
* Add support for `0` and `-1` values only.
52+
53+
Example:
54+
55+
```jsx
56+
<View
57+
aria-hidden={false}
58+
aria-label="Accessibility label"
59+
id="native-id"
60+
onClick={handleDOMClick}
61+
onPointerDown={handlePointerDown}
62+
role="button"
63+
tabIndex={0}
64+
>
65+
```
66+
67+
### New props for `<Image>`
68+
69+
Various React DOM `img` props also have direct equivalents in React Native. For example, `srcSet` is a subset of the `source` prop. Features like alternative text content are also required to target web.
70+
71+
* Add `alt` prop for alternative text support.
72+
* Add `crossOrigin` prop to declaratively configure cross-origin permissions for loaded images. Equivalent to setting the relevant `Header` in the `source` object.
73+
* Add `referrerPolicy` to declaratively configure referrer policy. Equivalent to setting the relevant `Header` in the `source` object.
74+
* Make `src` that same as setting `source.uri`.
75+
* Make `srcSet` the same as setting a `source` array with `uri` and `scale` properties defined.
76+
* Add `tintColor` prop.
77+
* Image currently sets `tintColor` via the inclusion of a non-standard style property.
78+
* Recommend adding `tintColor` prop to replace the React Native style property, to avoid the need to parse out `tintColor` from style for platforms like web.
79+
80+
`srcSet` to `source` mapping:
81+
82+
```js
83+
const { crossOrigin, referrerPolicy, srcSet } = props;
84+
const source = [];
85+
const srcList = srcSet.split(', ');
86+
srcList.forEach((src) => {
87+
const [uri, xscale] = src.split(' ');
88+
const scale = parseInt(xscale.split('x')[0], 10);
89+
const headers = {};
90+
if (crossOrigin === 'use-credentials') {
91+
headers['Access-Control-Allow-Credentials'] = true;
92+
}
93+
if (referrerPolicy != null) {
94+
headers['Referrer-Policy'] = referrerPolicy;
95+
}
96+
source.push({ headers, height, scale, uri, width });
97+
});
98+
```
99+
100+
Example:
101+
102+
```jsx
103+
<Image
104+
alt="Alternative text"
105+
crossOrigin="anonymous"
106+
srcSet="https://image.png 1x, https://image2.png 2x"
107+
tintColor="purple"
108+
>
109+
```
110+
111+
### New props for `<TextInput>`
112+
113+
* Redefine `autoComplete` prop.
114+
* Unify values for Android (`autoComplete`) and iOS (`textContentType`) with Web (`autoComplete`).
115+
* See below for example mapping
116+
* Add `enterKeyHint` prop and map to equivalent `returnKeyType` values.
117+
* Add `inputMode` prop and map to equivalent `keyboardType` values.
118+
* `inputMode === 'decimal'` is the same as `keyboardType = 'decimal-pad'`
119+
* `inputMode === 'email'` is the same as `keyboardType = 'email-address'`
120+
* `inputMode === 'numeric'` is the same as `keyboardType = 'numeric'`
121+
* `inputMode === 'search'` is the same as `keyboardType = 'search'`
122+
* `inputMode === 'tel'` is the same as `keyboardType = 'phone-pad'`
123+
* `inputMode === 'url'` is the same as `keyboardType = 'url'`
124+
* Make `readOnly` the same as `editable` (inverse).
125+
* Make `rows` the same as `numberOfLines`.
126+
* Support auto-expanding textarea on native platforms.
127+
128+
`autoComplete` mapping:
129+
130+
```js
131+
// https://reactnative.dev/docs/textinput#autocomplete-android
132+
const autoCompleteAndroid = {
133+
'address-line1': 'postal-address-region',
134+
'address-line2': 'postal-address-locality',
135+
bday: 'birthdate-full',
136+
'bday-day': 'birthdate-day',
137+
'bday-month': 'birthdate-month',
138+
'bday-year': 'birthdate-year',
139+
'cc-csc': 'cc-csc',
140+
'cc-exp': 'cc-exp',
141+
'cc-exp-month': 'cc-exp-month',
142+
'cc-exp-year': 'cc-exp-year',
143+
'cc-number': 'cc-number',
144+
country: 'postal-address-country',
145+
'current-password': 'password',
146+
email: 'email',
147+
name: 'name',
148+
'additional-name': 'name-middle',
149+
'family-name': 'name-family',
150+
'given-name': 'name-given',
151+
'honorific-prefix': 'namePrefix',
152+
'honorific-suffix': 'nameSuffix',
153+
'new-password': 'password-new',
154+
off: 'off',
155+
'one-time-code': 'sms-otp',
156+
'postal-code': 'postal-code',
157+
sex: 'gender',
158+
'street-address': 'street-address',
159+
tel: 'tel',
160+
'tel-country-code': 'tel-country-code',
161+
'tel-national': 'tel-national',
162+
username: 'username'
163+
};
164+
165+
// https://reactnative.dev/docs/textinput#textcontenttype-ios
166+
const autoCompleteIOS = {
167+
'address-line1': 'streetAddressLine1',
168+
'address-line2': 'streetAddressLine2',
169+
'cc-number': 'creditCardNumber',
170+
'current-password': 'password',
171+
country: 'countryName',
172+
email: 'emailAddress',
173+
name: 'name',
174+
'additional-name': 'middleName',
175+
'family-name': 'familyName',
176+
'given-name': 'givenName',
177+
nickname: 'nickname',
178+
'honorific-prefix': 'name-prefix',
179+
'honorific-suffix': 'name-suffix',
180+
'new-password': 'newPassword',
181+
off: 'none',
182+
'one-time-code': 'oneTimeCode',
183+
organization: 'organizationName',
184+
'organization-title': 'jobTitle',
185+
'postal-code': 'postalCode',
186+
'street-address': 'fullStreetAddress',
187+
tel: 'telephoneNumber',
188+
url: 'URL',
189+
username: 'username'
190+
};
191+
```
192+
193+
Example:
194+
195+
```jsx
196+
<TextArea
197+
autoComplete="email"
198+
inputMode="email"
199+
/>
200+
201+
<TextArea
202+
multiline
203+
readOnly
204+
rows={3}
205+
/>
206+
```
207+
208+
### New styles
209+
210+
* CSS Custom Properties
211+
* Support CSS custom property syntax `--variable-name`.
212+
* This can be shimmed in user-space on top of the existing `StyleSheet` API, with a React Context used to provide variables and values to a subtree.
213+
* CSS Lengths
214+
* Support `em`, `rem`, `v*`, `px` length units.
215+
* This can be shimmed in user-space on top of the existing `StyleSheet` API, with a React Context used to provide ancestral font-size information for `rem` values.
216+
* CSS Colors
217+
* Support CSS Colors using [Colorjs.io](https://colorjs.io/).
218+
* This can be shimmed in user-space.
219+
* CSS Media Queries
220+
* Support CSS Media Queries. Although Media Queries are not a preferred long-term solution, [Container Queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Container_Queries) are not yet widely supported by browsers.
221+
* This can be shimmed in user-space on top of the existing `StyleSheet` API.
222+
* CSS Logical Properties
223+
* Support CSS logical property names, i.e., `paddingInlineStart` rather than only non-standard `paddingStart`.
224+
* Support subtree-level logical properties, where setting the `dir` prop to `ltr` or `rtl` alters the way logical properties are resolved. Currently, React Native only supports global writing direction configuration for Android.
225+
* CSS Animations
226+
* Support declarative keyframes and animations that can be optimized on the native side and avoid the need for `Animated`.
227+
* See [animation](https://developer.mozilla.org/en-US/docs/Web/CSS/animation)).
228+
* CSS Transitions
229+
* Support declarative transitions that can be optimized on the native side and avoid the need for `Animated`.
230+
* Support `transitionProperty`, `transitionDuration`, `transitionTimingFunction`, and `transitionDelay` (see [transition](https://developer.mozilla.org/en-US/docs/Web/CSS/transition)).
231+
* `aspectRatio`
232+
* Support string values, i.e., `'16 / 9'`, to align with CSS.
233+
* `backgroundImage`
234+
* Support setting background images via `url()`.
235+
* Optional: support CSS gradients.
236+
* `boxShadow`
237+
* Add native support for CSS box shadows.
238+
* This would replace the very buggy iOS-specific `shadow*` styles and Android `elevation` style, allowing developers to unify shadows across native and web platforms.
239+
* `filter`
240+
* Support declarative filters per [filter](https://developer.mozilla.org/en-US/docs/Web/CSS/filter)
241+
* `fontVariant`
242+
* Support space-separated string values to align with CSS.
243+
* `fontWeight`
244+
* Support number values to align with React DOM / CSS.
245+
* `lineClamp`
246+
* Support CSS clamping text to a set number of lines via style.
247+
* This would be equivalent to using the `numberOfLines` prop on `<Text>` components.
248+
* `objectFit`
249+
* Support CSS `objectFit` property for `<Image>`.
250+
* This would be a subset (no "repeat" keyword) of functionality currently supported by the `resizeMode` prop and style for `<Image>`.
251+
* `objectFit === 'contain'` => `resizeMode = 'contain'`
252+
* `objectFit === 'cover'` => `resizeMode = 'cover'`
253+
* `objectFit === 'fill'` => `resizeMode = 'stretch'`
254+
* `objectFit === 'scale-down'` => `resizeMode = 'contain'`
255+
* `pointerEvents`
256+
* Support setting the `pointerEvents` values via style rather than a prop.
257+
* Retain the React Native specific `box-none` and `box-only` values.
258+
* `textShadow`
259+
* Add native support for CSS text shadows.
260+
* `transform`
261+
* Support using string values to set transforms.
262+
* This can be shimmed in user-space with a parser.
263+
* `verticalAlign`
264+
* Make `verticalAlign` the same as `textAlignVertical`.
265+
* `verticalAlign === 'middle'` is the same as `textAlignVertical = 'center'`;
266+
* `userSelect`
267+
* Support setting ability to select text via style.
268+
* Equivalent to using `selectable` prop on `<Text>`.
269+
270+
```jsx
271+
<View
272+
style={{
273+
boxShadow: '1px 1px 1px 1px #eee',
274+
backgroundColor: 'hsla(50,50,50,0.5)',
275+
pointerEvents: 'none',
276+
transform: 'scale(0.9)',
277+
width: '5rem'
278+
}}
279+
>
280+
281+
<Text
282+
style={{
283+
lineClamp: 3,
284+
userSelect: 'none',
285+
verticalAlign: 'middle'
286+
}}
287+
>
288+
289+
<Image
290+
style={{
291+
objectFit: 'cover'
292+
}}
293+
>
294+
```
295+
296+
### New imperative APIs
297+
298+
* `EventTarget` API
299+
* The `EventTarget` API is implemented in JS environments, and should be available on React Native host elements. This feature is commonly used on web, and could be used by React Native developers to support more complex features without first requiring further core API changes to support each use case.
300+
* Promote `node.unstable_addEventListener`, `node.unstable_removeEventListener` to stable APIs.
301+
* Add `node.dispatchEvent` support.
302+
* This cannot be shimmed in user-space.
303+
* `node.getBoundingClientRect`
304+
* Synchronous element measurement API. Current APIs like `node.measure` are async and return slightly different information to what you expect from `getBoundingClientRect` on web.
305+
* This cannot be shimmed in user-space.
306+
307+
### Other
308+
309+
* Revisit the type of all events modeled on W3C events. For example, `onTouchStart` should receive an event object that conforms to that received by the same prop in React DOM.
310+
* Aim to deprecate `StyleSheet.flatten()`.
311+
* This API encourages runtime introspection of styles in render calls. This pattern is a performance cost (flattening arrays of objects), and prevents us from supporting build-time optimizations for web (extracting styles to CSS files).
312+
* Aim to deprecate `StyleSheet.compose()`.
313+
* This API has no real value.
314+
* Aim to restore obfuscation of styles passed to `StyleSheet.create()`.
315+
* Returning the styles from create calls encourages introspection of those styles. On web, we need to be able to remove the JavaScript style objects from bundles to support build-time optimization like extraction to CSS files.
316+
* Aim to deprecate the `Touchable*` components.
317+
* The `Pressable` component was shipped as a replacement for `Touchable*`.
318+
* Aim to support more interaction states with `Pressable`.
319+
* Add ‘hovered’ and ‘focused’ to the state object, and replace ‘testOnly_pressed’ with an object of states.
320+
* Aim to move `Animated` out of core.
321+
* Move Animated out of core to separate package in monorepo, allow React Native for Web to import this package. Eventually could drop Animated from ‘react-native’ export.
322+
* Aim to move `VirtualizedList` and `FlatList` out of core.
323+
* Move `VirtualizedList`/`FlatList` out of core to separate package in monorepo, allow React Native for Web to import this package. Eventually could drop these components from `'react-native'` export.
324+
* Remove Flow types and JSX before publishing to npm (make this the default for the community). React Native and its community packages currently publish uncompiled, flow-typed JavaScript to npm. This causes common tools to crash on these packages.
325+
* Prevent libraries importing `'react-native'` package internals, by using the Node.js package exports API.
326+
327+
## Drawbacks
328+
329+
* Many of these features can be shimmed in user-space, at the cost of runtime overhead for native or web platforms. The runtime overhead for web is untenable. The runtime overhead of shifting shims into the JS targeting native has yet to be established.
330+
* It adds redundancy to the React Native API, as the proposal is to make additive changes and avoid requiring removal of existing APIs in the short term.
331+
332+
## Adoption strategy
333+
334+
To encourage library and product developers to proactively migrate to these new APIs, React Native for Web plans to only support these W3C standards-based APIs in future versions. This will allow us to incrementally add APIs to React Native without needing to commit to simultaneously deprecating APIs and migrating existing React Native code. Existing React Native developers will adopt these APIs if they wish to support web.
335+
336+
There are few, if any, breaking changes anticipated for React Native itself.
337+
338+
## How we teach this
339+
340+
Teaching these APIs is simplified by developer familiarity with existing DOM / React DOM APIs.

0 commit comments

Comments
 (0)