Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: React DOM for Native (reduce API fragmentation) #496

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

necolas
Copy link

@necolas necolas commented Aug 5, 2022

Updated: September 2023

The contents of the RFC are reproduced below.

Also see RFC: DOM traversal and layout APIs in React Native


RFC: React DOM for Native

Summary

This is a proposal to incrementally reduce the API fragmentation faced by developers using React to target multiple platforms via code shared between native and web. The proposed cross-platform user interface APIs are a subset of existing web standards for DOM, CSS, and HTML - "Strict DOM". The proposed changes are overwhelmingly additive and do not require migration of existing React Native UI code (deprecations are optional / follow up work). Incremental progress can help to reduce the fragmentation between React Native and React DOM components, while the ability to run React DOM code (with minor modifications) on native is a longer-term goal.

Motivation

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.

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. Supporting standards helps to:

  • minimize the overhead when running in browsers;
  • reduce developer education required to learn features;
  • set clear and cohesive API end-state expectations for contributors to aim for;
  • accelerate the framework's development by avoiding API design costs;
  • support backwards compatibility;
  • develop universal codebases.

The existing solution for targeting web with React Native is to use React Native for Web. React Native for Web is a user-space library built on top of React DOM and native DOM APIs. It shims React Native components and APIs on the web. The tooling for an existing React DOM app simply maps the 'react-native' export to 'react-native-web'.

This is the most complete and widely used shim, but comes with considerable DX and UX costs on the web. The shim must implement a large surface area of fragmented APIs, and it needs to modify standard APIs and objects (e.g., events) to match React Native's non-standard implementations.

In contrast, implementing a "Strict DOM" subset in React Native shifts the weight of bridging native and web apps onto React Native, where it can be done most efficiently. Although React Native will not support all the features available on web, it will still support a greater expanded feature set relative to React Native today. On the web, we would only need to combine React DOM with a white-label CSS compiler like stylex.

Detailed design

The "complete" API involved is broken down into the following sections.

  • Environment API. Global APIs to add to the host environment.
  • Elements API. DOM APIs to add to host component instances.
  • Components API. React DOM components to add to React Native.
  • Props API. React DOM component props to add to new components, and existing React Native components as part of an incremental strategy.
  • Styling API. CSS APIs to add to the React Native environment.

A simplified example of the user-space code we'd aim to support is as follows:

import { html, css } from 'react-native/dom';

export function VStackPanel(props) {
  const connectedCallback = function (node) {
    const handler = () => {
      const { offsetWidth } = e.target;
      // ...
    };
    const options = { capture: true };
    node.addEventListener('pointerdown', handler, options);
    return function disconnected() {
      node.removeEventListener('pointerdown', handler, options)
    }
  };

  return (
    // Use HTML element
    <html.div
      children={props.children}
      // Synchronous click event that matches W3C event type
      on-click={props.click}
      // Use HTMLElement instance API
      ref={connectedCallback}
      // Use optimized styles
      style={css(
        { flexDirection: 'column', flex: 1 },
        props.style
      )}
    />
  )
}

But there are many incremental steps that can be taken along the way.

Implementation and adoption strategy

The proposal is to support both an incremental adoption strategy, as well as a separate "React DOM" bindings exports. The incremental strategy would find ways to align existing APIs in React Native with their React DOM equivalents, and gradually deprecate the non-standard APIs. Whereas the separate bindings export would be designed to provide most of what is needed for a direct compatibility layer with React DOM.

This would ensure a significant amount of overlap between the existing React Native components and the dedicated "React DOM" compatibility API, allowing for co-mingling of code and reduced developer education. There is no suggestion of deprecating the current React Native components and APIs at this stage.

Reduce API fragmentation across platforms

The initial step is to incrementally reduce existing API fragmenetation across platforms. This involves consolidating the different props, styles, and events for similar functionality across different platforms. The APIs that we consolidate upon are the W3C standards, as React Native is already fairly closely aligned with these standards.

Doing this will make it easier for web developers to work with React Native's existing components and related APIs. This is the path for developers to gradually migrate their existing React Native code into a form that is more aligned with the web. And it will allow React Native for Web to be smaller and faster, providing better results on web via the existing tools that developers use today.

One example of this kind of incremental change is to map props in the existing core components (i.e., View, Text, etc.) to the W3C equivalents: id to nativeID, aria-label to accessibilityLabel, and so on. React Native for Web currently "owns" this translation step, but we would instead move it into React Native to claw back performance on web. For developers familiar with React DOM, there will be less of a learning curve to applying that knowledge to React Native.

<View
  aria-hidden={false}
  aria-label="Accessibility label"
  id="native-id"
  on-click={handleDOMClick}
  on-pointerdown={handlePointerDown}
  role="button"
  tabIndex={0}
>
<Image
  alt="Alternative text"
  crossOrigin="anonymous"
  srcSet="https://image.png 1x, https://image2.png 2x"
  width={320}
>
<TextArea
  autoComplete="email"
  inputMode="email"
/>

<TextArea
  multiline
  readOnly
  rows={3}
/>

Example of how to map srcSet to source:

const { crossOrigin, referrerPolicy, srcSet } = props;
const source = [];
const srcList = srcSet.split(', ');
srcList.forEach((src) => {
  const [uri, xscale] = src.split(' ');
  const scale = parseInt(xscale.split('x')[0], 10);
  const headers = {};
  if (crossOrigin === 'use-credentials') {
    headers['Access-Control-Allow-Credentials'] = true;
  }
  if (referrerPolicy != null) {
    headers['Referrer-Policy'] = referrerPolicy;
  }
  source.push({ headers, height, scale, uri, width });
});

Example of how to map autoComplete to Android's autoComplete and iOS's textContentType:

// https://reactnative.dev/docs/textinput#autocomplete-android
const autoCompleteAndroid = {
  'address-line1': 'postal-address-region',
  'address-line2': 'postal-address-locality',
  bday: 'birthdate-full',
  'bday-day': 'birthdate-day',
  'bday-month': 'birthdate-month',
  'bday-year': 'birthdate-year',
  'cc-csc': 'cc-csc',
  'cc-exp': 'cc-exp',
  'cc-exp-month': 'cc-exp-month',
  'cc-exp-year': 'cc-exp-year',
  'cc-number': 'cc-number',
  country: 'postal-address-country',
  'current-password': 'password',
  email: 'email',
  name: 'name',
  'additional-name': 'name-middle',
  'family-name': 'name-family',
  'given-name': 'name-given',
  'honorific-prefix': 'namePrefix',
  'honorific-suffix': 'nameSuffix',
  'new-password': 'password-new',
  off: 'off',
  'one-time-code': 'sms-otp',
  'postal-code': 'postal-code',
  sex: 'gender',
  'street-address': 'street-address',
  tel: 'tel',
  'tel-country-code': 'tel-country-code',
  'tel-national': 'tel-national',
  username: 'username'
};

// https://reactnative.dev/docs/textinput#textcontenttype-ios
const autoCompleteIOS = {
  'address-line1': 'streetAddressLine1',
  'address-line2': 'streetAddressLine2',
  'cc-number': 'creditCardNumber',
  'current-password': 'password',
  country: 'countryName',
  email: 'emailAddress',
  name: 'name',
  'additional-name': 'middleName',
  'family-name': 'familyName',
  'given-name': 'givenName',
  nickname: 'nickname',
  'honorific-prefix': 'name-prefix',
  'honorific-suffix': 'name-suffix',
  'new-password': 'newPassword',
  off: 'none',
  'one-time-code': 'oneTimeCode',
  organization: 'organizationName',
  'organization-title': 'jobTitle',
  'postal-code': 'postalCode',
  'street-address': 'fullStreetAddress',
  tel: 'telephoneNumber',
  url: 'URL',
  username: 'username'
};

Where possible we should make these changes to the native code. However, we will prioritize user-space shims in JavaScript where they are faster to ship and allow us to gather feedback/support for this overall direction.

Beyond props, there is also the opportunity to reduce fragementation in styling APIs.

  • Don't hard crash on unknown or invalid style properties and values.
  • Deprecate StyleSheet.absoluteFill. Use position:'absolute';inset:0; instead.
  • Deprecate StyleSheet.absoluteFillObject.
  • Deprecate StyleSheet.compose(). Use existing [ a, b ] syntax instead.
  • Deprecate StyleSheet.flatten(). 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 (e.g., extracting styles to CSS files).
  • Deprecate or rename setStyleAttributePreprocessor (e.g., unstable_setStyleAttributePreprocessor).
  • StyleSheet.create() should obfuscate styles to prevent introspection (i.e., revert identify function change). 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.

To encourage React Native 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 must adopt these APIs if they wish to support web.

Create a separate package or export for DOM bindings

The next step would be to begin exporting separate React DOM bindings from React Native. This would aim to allow code originally written with React DOM to run on React Native with only minor modifications. There would be no need to use React Native for Web, and the web layer in this scenario would be a lot smaller, limited mostly to implementing the modern W3C events API and integrating a style API that allows for static extraction to optimized CSS.

Even this can be done in incremental fashion, with early (user-space) prototypes to get feedback. Most tags can be mapped to existing React Native components and props, in the reverse of the mapping used by React Native for Web.

Equivalent API for Web

In parallel, a user-space layer over React DOM would ensure equivalent APIs between native and web, by converging them both towards a desired the "end state" where the differences between React Native and React DOM are erased while landing on a "modern" flavor of React DOM.

The benefit of initially doing this in user-space is that it reduces the burden of complex migratations for React Native and React DOM (e.g., the changes to React DOM event types, the style prop, and explicit imports of component types), while allowing us to validate and iterate on the proposed end-state APIs with interested parties. This is currently blocked on OSS-ing of stylex.

How we teach this

Teaching these APIs is simplified by developer familiarity with existing DOM / React DOM APIs.

Drawbacks

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 React Native JS has yet to be established.

This 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.

We have to be very intentional about how much compatibility with open web standards we can promise. Some cross-platform limitations are rooted in significant differences in the host platforms APIs (e.g., accessibility) and the lack of 99% compat may frustrate users.

Aiming for a degree of React DOM compatibility shifts the burden of missing features onto React Native. Developers may not be used to an API that is complete on web but partially implemented on native platforms.


Environment APIs

window

Events

  • Receives all W3C events dispatched to components (capture and bubble phase). Resolves proposal #249.
  • Dispatches resize.

Properties

Methods

APIs

  • window.fetch
  • window.matchMedia. Resolves proposal #350.
  • IntersectionObserver API for observing the intersection of target elements. This can also be used as a building block for performance tooling.
  • MutationObserver API for watching changes to the host node tree. This can also be used as a building block for performance tooling.
  • ResizeObserver API for responding the changes in the size of elements. Note that this API no longer includes positional coordinates and is optimized for width/height information.

document

Support the document object for common patterns such as listening to visibility changes, and listening to capture or bubble phase events for the entire application (e.g., "outside click" pattern), etc.

The document object might not be exposed as a global, and would instead be accessed via node.getRootNode() to ensure code accounts for multi-window / multi-root scenarios that are more common for React Native apps than React DOM apps (rendering into sourceless iframes is a similar use case).

Events

Properties

Methods


Elements API (DOM subset)

Subset of cross-platform DOM APIs exposed on element instances. This would be an imperative API for working with the Shadow tree in React Native. Based on data from MDN Web API, please refer to the MDN links for complete DOM APIs and comment if you believe any should be included in the proposed subset.

In practice, this DOM API subset is generally limited to the “best practice” APIs that can safely be used with React DOM (i.e., read-only operations that don’t modify the DOM tree), and most React components should already be limited to this subset. One of the important details of this API are how it supports the different ways of determining the dimensions of elements.

EventTarget

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.

Methods

Event and CustomEvent

Event() and CustomEvent() represent events initialized by developers and that can be dispatched to elements using EventTarget.dispatchEvent().

Node

The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. All objects that implement Node functionality are based on one of its subclasses. Every kind of host node is represented by an interface based on Node.

In some cases, a particular feature of the base Node interface may not apply to one of its child interfaces; in that case, the inheriting node may return null or throw an exception, depending on circumstances.

Static properties

Node type constants

  • Node.ELEMENT_NODE (1)
  • Node.TEXT_NODE (3)
  • Node.DOCUMENT_NODE (9)

Document position constants

  • Node.DOCUMENT_POSITION_DISCONNECTED (1)
  • Node.DOCUMENT_POSITION_PRECEDING (2)
  • Node.DOCUMENT_POSITION_FOLLOWING (4)
  • Node.DOCUMENT_POSITION_CONTAINS (8)
  • Node.DOCUMENT_POSITION_CONTAINED_BY (16)

Instance properties

Instances methods

Node inherits methods from its parent, EventTarget.

Element

Element is the most general base class from which all element objects (i.e. objects that represent elements) in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element.

Instance properties

Element inherits properties from its parent interface, Node, and by extension that interface's parent, EventTarget.

Instance methods

Element inherits methods from its parents Node, and its own parent, EventTarget.

  • element.computedStyleMap(). Returns a StylePropertyMapReadOnly interface which provides a read-only representation of a CSS declaration block that is an alternative to CSSStyleDeclaration.
  • element.getAttribute(). Returns the value of a specified attribute on the element.
  • element.getBoundingClientRect(). Returns the size of an element and its position relative to the viewport.
  • element.getClientRects(). Returns a collection of DOMRect objects that indicate the bounding rectangles for each CSS border box in a client.
  • element.hasAttribute(). Returns a Boolean value indicating whether the specified element has the specified attribute or not.
  • element.hasPointerCapture(). Checks whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID.
  • element.scroll(). Scrolls to a particular set of coordinates inside a given element. (Note that this would be async in React Native.)
  • element.scrollBy(). Scrolls an element by the given amount. (Note that this would be async in React Native.)
  • element.scrollIntoView(). Scrolls the page until the element gets into the view. (Note that this would be async in React Native.)
  • element.scrollTo(). Alias for scroll().
  • element.setPointerCapture(). Used to designate a specific element as the capture target of future pointer events. Subsequent events for the pointer will be targeted at the capture element until capture is released.
  • element.releasePointerCapture(). Releases (stops) pointer capture that was previously set for a specific (PointerEvent) pointer.

Events

Listen to these events using addEventListener() or by assigning an event handler to the equivalent component prop.

  • error. Fired when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid. Also available via the on-error property.
  • scroll. Fired when the document view or an element has been scrolled. Also available via the on-scroll property.
  • select. Fired when some text has been selected. Also available via the on-select property.
  • wheel. Fired when the user rotates a wheel button on a pointing device (typically a mouse). Also available via the on-wheel property.

Clipboard events

  • copy. Fired when the user initiates a copy action through the browser's user interface. Also available via the on-copy property.
  • cut. Fired when the user initiates a cut action through the browser's user interface. Also available via the on-cut prop.
  • paste. Fired when the user initiates a paste action through the browser's user interface. Also available via the on-paste prop.

Focus events

  • blur. Fired when an element has lost focus. Also available via the on-blur prop.
  • focus. Fired when an element has gained focus. Also available via the on-focus prop.
  • focusin. Fired when an element is about to gain focus.
  • focusout. Fired when an element is about to lose focus.

Keyboard events

  • keydown. Fired when a key is pressed. Also available via the on-keydown prop.
  • keyup. Fired when a key is released. Also available via the on-keyup prop.

Pointer events

  • auxclick. Fired when a non-primary pointing device button (e.g., any mouse button other than the left button) has been pressed and released on an element. Also available via the onAuxClick prop.
  • click. Fired when a pointing device button (e.g., a mouse's primary button) is pressed and released on a single element. Also available via the onClick prop.
  • contextmenu. Fired when the user attempts to open a context menu. Also available via the oncontextmenu property.
  • gotpointercapture. Fired when an element captures a pointer using setPointerCapture(). Also available via the on-gotpointercapture prop.
  • lostpointercapture. Fired when a captured pointer is released. Also available via the on-lostpointercapture prop.
  • pointercancel. Fired when a pointer event is canceled. Also available via the on-pointercancel prop.
  • pointerdown. Fired when a pointer becomes active. Also available via the on-pointerdown prop.
  • pointerenter. Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants. Also available via the on-pointerenter prop.
  • pointerleave. Fired when a pointer is moved out of the hit test boundaries of an element. Also available via the on-pointerleave prop.
  • pointermove. Fired when a pointer changes coordinates. Also available via the on-pointermove prop.
  • pointerout. Fired when a pointer is moved out of the hit test boundaries of an element (among other reasons). Also available via the on-pointerout prop.
  • pointerover. Fired when a pointer is moved into an element's hit test boundaries. Also available via the on-pointerover prop.
  • pointerrawupdate. Fired when a pointer changes any properties that don't fire pointerdown or pointerup events.
  • pointerup. Fired when a pointer is no longer active. Also available via the on-pointerup prop.

HTMLElement

The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.

Properties

Inherits properties from its parent, Element, and implements those from DocumentAndElementEventHandlers, GlobalEventHandlers, and TouchEventHandlers.

  • HTMLElement.hidden [Read only]. A boolean value indicating if the element is hidden or not.
  • HTMLElement.offsetHeight [Read only]. Returns a double containing the height of an element, relative to the layout.
  • HTMLElement.offsetLeft [Read only]. Returns a double, the distance from this element's left border to its offsetParent's left border.
  • HTMLElement.offsetParent [Read only]. Returns a Element that is the element from which all offset calculations are currently computed.
  • HTMLElement.offsetTop [Read only]. Returns a double, the distance from this element's top border to its offsetParent's top border.
  • HTMLElement.offsetWidth [Read only]. Returns a double containing the width of an element, relative to the layout.

Methods

Inherits methods from its parent, Element, and implements those from DocumentAndElementEventHandlers, GlobalEventHandlers, and TouchEventHandlers.

Events

Listen to these events using addEventListener() or by assigning an event listener to the equivalent component prop.

  • beforeinput. Fired when the value of an <input>, <select>, or <textarea> element is about to be modified.
  • change. Fired when the value of an <input>, <select>, or <textarea> element has been changed and committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value. Also available via the on-change property.
  • input. Fired when the value of an <input>, <select>, or <textarea> element has been changed. Also available via the on-input property.

HTMLDialogElement

The HTMLDialogElement interface represents an HTML <dialog> element, providing the properties and methods used to manipulate image elements.

Properties

Inherits properties from its parent, HTMLElement.

  • HTMLDialogElement.open. A boolean value representing the state of the open HTML attribute. true means it is set, and therefore the dialog is shown. false means it not set, and therefore the dialog is not shown.
  • HTMLDialogElement.returnValue. A string representing the returnValue of the dialog.

Methods

Inherits properties from its parent, HTMLElement.

  • HTMLDialogElement.close(). Closes the dialog. An optional string may be passed as an argument, updating the returnValue of the dialog.
  • HTMLDialogElement.show().Displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog.
  • HTMLDialogElement.showModal(). Displays the dialog as a modal, over the top of any other dialogs that might be present. Everything outside the dialog are inert with interactions outside the dialog being blocked.

Events

  • cancel. Also available via the on-cancel prop.
  • close. Also available via the on-close prop.

HTMLImageElement

The HTMLImageElement interface represents an HTML <img> element, providing the properties and methods used to manipulate image elements.

Properties

Inherits properties from its parent, HTMLElement.

  • HTMLImageElement.complete [Read only]. Returns a boolean value that is true if the browser has finished fetching the image, whether successful or not. That means this value is also true if the image has no src value indicating an image to load.
  • HTMLImageElement.currentSrc [Read only]. Returns a USVString representing the URL from which the currently displayed image was loaded. This may change as the image is adjusted due to changing conditions, as directed by any media queries which are in place.
  • HTMLImageElement.naturalHeight [Read only]. Returns an integer value representing the intrinsic height of the image in CSS pixels, if it is available; else, it shows 0. This is the height the image would be if it were rendered at its natural full size.
  • HTMLImageElement.naturalWidth [Read only]. An integer value representing the intrinsic width of the image in CSS pixels, if it is available; otherwise, it will show 0. This is the width the image would be if it were rendered at its natural full size.

Events

  • error. Also available via the on-error prop.
  • load. Also available via the on-load prop.

HTMLInputElement

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.

Properties

Properties that apply only to visible elements containing text or numbers

  • disabled.
  • selectionEnd. unsigned long: Returns / Sets the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.
  • selectionStart. unsigned long: Returns / Sets the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the element. (Resolves issue #35616.)
  • selectionDirection. string: Returns / Sets the direction in which selection occurred. Possible values are: forward (the selection was performed in the start-to-end direction of the current locale), backward (the opposite direction) or none (the direction is unknown).
  • value. string: Returns / Sets the current value of the control. If the user enters a value different from the value expected, this may return an empty string.

Methods

  • select(). Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content.
  • setSelectionRange(). Selects a range of text in the input element (but does not focus it).
  • showPicker(). Shows a browser picker for date, time, color, and files.

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface:

  • invalid. Fired when an element does not satisfy its constraints during constraint validation. Also available via the on-invalid prop.
  • select event. Fired when some text has been selected.
  • selectionchange event. Fires when the text selection in a <input> element has been changed. Also available via the on-selectionchange prop.

HTMLTextAreaElement

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.

Properties

  • disabled.
  • selectionEnd. unsigned long: Returns / Sets the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.
  • selectionStart. unsigned long: Returns / Sets the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the <textarea> element.
  • selectionDirection. string: Returns / Sets the direction in which selection occurred. Possible values are: forward (the selection was performed in the start-to-end direction of the current locale), backward (the opposite direction) or none (the direction is unknown).
  • value. string: Returns / Sets the current value of the control. If the user enters a value different from the value expected, this may return an empty string.

Methods

  • select(). Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content.
  • setSelectionRange(). Selects a range of text in the input element (but does not focus it).

Events

Listen to these events using addEventListener() or using the equivalent prop name.

  • select event. Fired when some text has been selected.
  • selectionchange event. Fires when the text selection in a <input> element has been changed. Also available via the on-selectionchange prop.

Components API (React DOM subset)

Support a subset of React DOM components directly. Exported as an html object, i.e., html.div, html.a, etc.

This would provide a built-in declarative API for cross-platform elements in React Native. All unknown tags default to <span> layout. All known-but-unimplemented block-level tags default to <div> layout.

Sections

Content sectioning elements allow you to organize the document content into logical pieces. Use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify sections of content.

Text

Text content elements organize blocks or sections of content. Important for accessibility, these elements identify the purpose or structure of that content.

Inline text

Inline text semantics define the meaning, structure, or style of a word, line, or any arbitrary piece of text.

Media

  • img is similar to Image without advanced loader configuration.

Forms

Elements which can be used together to create forms which the user can fill out and submit. There's a great deal of further information about this available in the HTML forms guide.


Props API (React DOM subset)

Support a subset of React DOM props.

Common props

Props supported on all elements.

Supporting the ARIA 1.2 interface would allow more ARIA-targeting React DOM libraries to work on React Native, and would provide a well defined cross-platform target for equivalent native features (e.g., React Native for Windows needing heading levels, set size, etc.)

Common events

Events supported on all elements.

Each event handler should receive a W3C event object of the corresponding type, not a synthetic event. These props are merely conveniences and otherwise identical to using the EventTarget API mentioned later on. Note that no capture phase props are included, as listening to the capture phase (as well as custom events) can be handled with the EventTarget API. (Alternatively, we introduce oncapture-click, etc.)

To avoid breaking changes in React Native and React DOM, it may be preferrable to create new event prop names that receive events as specified by web standards, e.g., on-click, on-pointerup.

Resolves proposal #492.

  • on-auxclick is a PointerEvent for auxillary clicks.
  • on-blur.
  • on-click is a PointerEvent for primary clicks.
  • on-contextmenu is a PointerEvent for context clicks / long press.
  • on-copy.
  • on-cut.
  • on-focus.
  • on-gotpointercapture.
  • on-lostpointercapture.
  • on-paste.
  • on-pointercancel.
  • on-pointerdown.
  • on-pointerenter.
  • on-pointerleave.
  • on-pointermove.
  • on-pointerout.
  • on-pointerover.
  • on-pointerup.
  • on-keydown.
  • on-keyup.

<a> props

Additional props for <a>.

  • download.
  • href. Clicking will always attempt to open the URL in a browser, mail client, etc. Use of e.preventDefault() in an event handler will disable this behavior and allow custom routing logic to handle the interaction.
  • referredPolicy.
  • rel.
  • target.

<dailog> props

Additional props for <dialog>.

<img> props

Additional props for <img>.

  • alt prop for alternative text support.
  • crossOrigin is equivalent to setting the relevant Header in the source object. Declaratively configure cross-origin permissions for loaded images.
  • decoding.
  • draggable.
  • fetchPriority.
  • height is the same as source.height.
  • loading.
  • referrerPolicy is equivalent to setting the relevant Header in the source object. Declaratively configure referrer policy.
  • src is the same as source.uri.
  • srcSet is the same as setting a source array with uri and scale properties defined.
  • width is the same as source.width.

<img> events

Additional events for <img>.

<input> props

Additional props for <input>.

  • autoComplete is the same as mapped values for existing autoComplete (Android) and textContentType (iOS).
  • disabled.
  • enterKeyHint is the same as mapped values for returnKeyType.
  • inputMode is the same as mapped values for keyboardType.
    • inputMode === 'decimal' is the same as keyboardType = 'decimal-pad'.
    • inputMode === 'email' is the same as keyboardType = 'email-address'.
    • inputMode === 'none' is the same as showSoftInputOnFocus = false.
    • inputMode === 'numeric' is the same as keyboardType = 'numeric'.
    • inputMode === 'search' is the same as keyboardType = 'search'.
    • inputMode === 'tel' is the same as keyboardType = 'phone-pad'.
    • inputMode === 'url' is the same as keyboardType = 'url'.
  • max.
  • maxLength.
  • min.
  • minLength.
  • placeholder.
  • readOnly is the same as inverse editable.
  • required.
  • spellCheck.
  • type.
  • value.

<textarea> props

Additional props for <textarea>.

  • autoComplete is the same as mapped values for existing autoComplete (Android) and textContentType (iOS).
  • disabled.
  • enterKeyHint is the same as mapped values for returnKeyType.
  • inputMode is the same as mapped values for keyboardType.
    • inputMode === 'decimal' is the same as keyboardType = 'decimal-pad'.
    • inputMode === 'email' is the same as keyboardType = 'email-address'.
    • inputMode === 'none' is the same as showSoftInputOnFocus = false.
    • inputMode === 'numeric' is the same as keyboardType = 'numeric'.
    • inputMode === 'search' is the same as keyboardType = 'search'.
    • inputMode === 'tel' is the same as keyboardType = 'phone-pad'.
    • inputMode === 'url' is the same as keyboardType = 'url'.
  • max.
  • maxLength.
  • min.
  • minLength.
  • placeholder.
  • readOnly is the same as inverse editable.
  • required.
  • rows is the same as numberOfLines.
  • spellCheck.
  • value.

<input> and <textarea> events

Additional events for <input> and <textarea>.

  • on-beforeinput
  • on-change
  • on-input
  • on-invalid
  • on-select
  • on-selectionchange

Styles API (CSS subset)

Significantly expanded styling capabilities to cover more of the features that are heavily relied upon by web engineers. Styles are used with the css.create() function and are passed to the style prop on elements.

css() function

Styles must be wrapped in css().

const styles = css.create({
  foo: {
    width: 100
  },
  bar: (color) => ({
    color
  })
});

<div style={styles.foo} />
<div style={styles.bar(props.color)} />

CSS Compatibility

Existing properties that can be adjusted to align with the CSS spec.

  • aspectRatio. Support string values, i.e., '16 / 9', to align with CSS.
  • borderRadius. Support percentage values to align with CSS.
  • fontVariant support space-separated string values to align with CSS.
  • fontWeight support number values to align with React DOM / CSS.
  • objectFit is equivalent to resizeMode for <Image>.
  • pointerEvents is equivalent to pointerEvents prop.
  • position. Support for fixed and sticky values.
  • transform. Support using string values to set transforms.
  • verticalAlign is equivalent to textAlignVertical.
  • userSelect. Equivalent to using selectable prop on <Text>.

Existing logical properties that can be adjusted to adopt the CSS standard names. In addition, React Native will need to add native support for subtree-level writing direction controls. Setting the dir prop (or direction style) to ltr or rtl on an element should alter the way logical properties are resolved in the subtree.

  • (direction. But it is not recommended for most use cases on web.)
  • borderEndEndRadius is equivalent to borderBottomEndRadius.
  • borderEndStartRadius is equivalent to borderBottomStartRadius.
  • borderStartEndRadius is equivalent to borderTopEndRadius.
  • borderStartStartRadius is equivalent to borderTopStartRadius.
  • borderBlockColor is equivalent to borderTopColor & borderBottomColor.
  • borderBlockEndColor is equivalent to borderBottomColor.
  • borderBlockStartColor is equivalent to borderTopColor.
  • borderInlineColor is equivalent to borderEndColor & borderStartColor.
  • borderInlineEndColor is equivalent to borderEndColor.
  • borderInlineStartColor is equivalent to borderStartColor.
  • borderBlockStyle is equivalent to borderTopStyle & borderBottomStyle.
  • borderBlockEndStyle is equivalent to borderBottomStyle.
  • borderBlockStartStyle is equivalent to borderTopStyle.
  • borderInlineStyle is equivalent to borderEndStyle & borderStartStyle.
  • borderInlineEndStyle is equivalent to borderEndStyle.
  • borderInlineStartStyle is equivalent to borderStartStyle.
  • borderBlockWidth is equivalent to borderTopWidth & borderBottomWidth.
  • borderBlockEndWidth is equivalent to borderBottomWidth.
  • borderBlockStartWidth is equivalent to borderTopWidth.
  • borderInlineWidth is equivalent to borderEndWidth & borderStartWidth.
  • borderInlineEndWidth is equivalent to borderEndWidth.
  • borderInlineStartWidth is equivalent to borderStartWidth.
  • marginInlineStart is equivalent to marginStart.
  • marginInlineEnd is equivalent to marginEnd.
  • marginBlockStart is equivalent to marginTop.
  • marginBlockEnd is equivalent to marginBottom.
  • marginBlock is equivalent to marginVertical.
  • marginInline is equivalent to marginHorizontal.
  • paddingInlineStart is equivalent to paddingStart.
  • paddingInlineEnd is equivalent to paddingEnd.
  • paddingBlockStart is equivalent to paddingTop.
  • paddingBlockEnd is equivalent to paddingBottom.
  • paddingBlock is equivalent to paddingVertical.
  • paddingInline is equivalent to paddingHorizontal.
  • inset is equivalent to top & bottom & right & left.
  • insetBlock is equivalent to top & bottom.
  • insetBlockEnd is equivalent to bottom.
  • insetBlockStart is equivalent to top.
  • insetInline is equivalent to right & left.
  • insetInlineEnd is equivalent to right or left.
  • insetInlineStart is equivalent to right or left.
  • blockSize is equivalent to height.
  • minBlockSize is equivalent to minHeight.
  • maxBlockSize is equivalent to maxHeight.
  • inlineSize is equivalent to width.
  • minInlineSize is equivalent to minWidth.
  • maxInlineSize is equivalent to maxWidtht.

CSS Animations

Support declarative keyframes and animations that can be optimized on the native side and avoid the need for Animated. Consider dispatching the corresponding W3C animation events too. See animation).

TBD: the relationship between animationName (or equivalent) and the API used to define Animation keyframes.

CSS Colors

Support CSS 4 Colors, possibly by using Colorjs.io or implementing a native equivalent.

CSS Container Queries

Prepare for CSS Container Queries.

CSS Custom Properties

Support CSS custom property syntax --variable-name. This could 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.

CSS Filters

Support declarative filters as used by the CSS filter style.

CSS Functions

CSS Lengths

Support major units where supported by CSS.

  • em units.
  • rem units.
  • px units.
  • v* units.
  • % units.

CSS Media Queries

Support CSS Media Queries.

Although Media Queries are not a preferred long-term solution for responsive design, Container Queries are not yet widely supported by browsers. The dimensional Media Queries could be shimmed in user-space on top of the existing StyleSheet API.

Logical operators not, and, or, only.

Media features:

Proposed syntax:

// Either
css.create({
  position: 'absolute',
  '@media (max-width: 600px)': {
    position: 'sticky',
  }
});

// Or
css.create({
  position: {
    default: 'absolute',
    '@media (max-width: 600px)': 'sticky',
  }
});

The benefit of the latter is clearer expectations (and greater constraints) about when properties are overridden. For example, it's not as clear what the value for position would be in the following:

css.create(
  {
    position: 'absolute',
    '@media (max-width: 600px)': {
      position: 'sticky',
    }
  },
  {
    position: 'relative',
  }
);

// {
//   position: relative,
//   '@media (max-width: 600px)': {
//     position: 'sticky',
//   }
// }

Whereas in the next example we can set expectations that a property and any previous conditions are completed overridden by any declaration that later modifies the property in any way.

css.create(
  {
    position: {
      default: 'absolute',
      '@media (max-width: 600px)': 'sticky'
    }
  },
  {
    position: {
      default: 'relative',
    }
  }
);

// {
//   position: relative
// }

Consideration is also required to determine what the final value of a property is when Media Query conditions overlap, i.e., which media features and which conditions (e.g., multiple width conditions) take priority over others.

CSS Properties and Values

Miscellaneous CSS properties and values that should be supported on native.

CSS Transitions

Support declarative transitions that can be optimized on the native side and avoid the need for Animated. Consider dispatching the corresponding W3C transition events too.

@kelset kelset added the 💡 Proposal This label identifies a proposal label Aug 8, 2022
@javache
Copy link

javache commented Aug 9, 2022

I think this is a great overview of how we can incrementally move RN closer to web standards and reduce API fragmentation.

When it comes to implementing this though, let's look at how we can introduce a new RN abstraction to efficiently introduce aliases and mapping functions, so we can avoid overhead and breakages from doing this.

@necolas
Copy link
Author

necolas commented Aug 9, 2022

Recording feedback left on Twitter:

Expo

We at 𝝠 @expo ❤️ this!
Supporting standards means:
➜ Backwards compatibility
➜ Universal codebases
➜ Reliable updates

https://twitter.com/Baconbrix/status/1555953435576606720

NativeBase

This RFC is a giant leap in our efforts to create universal applications with a single codebase.
The API of React Native was created for mobile platforms. When used in web apps it created limitations and a lack of synergy.
The new RFC removes the old shackles

https://twitter.com/nativebase/status/1556961633859436545

@nickdima
Copy link

nickdima commented Aug 9, 2022

Glad to see this effort! When you're coming from React to React Native and wanting to build universal apps (web included) you feel like you're taking a step back from what you could do with React on the web. It shouldn't be.
This is also a step forward into making life easier for lib authors that want to support both React and React Native. There's a lot of progress made in building UI libs and design systems that focus on accessibility, customisation etc. but that's mostly React only for now. Would be awesome for RN to benefit more from this as well.

@giacomocerquone
Copy link

giacomocerquone commented Aug 9, 2022

This is really a great thing to see indeed, particularly needed too.
In detail, I feel that this discussion I opened over react-native-web necolas/react-native-web#2289 fits really well in the effort of reducing fragmentation between the web and the native platforms.

Now, it might also be "by design", but even having just some info about it would be awesome.

PS: I don't want this comment to grab the attention from the whole fragmentation thing as a mere issue/help request. But a discussion could be opened, imho, about the idea of making all the views with overflow: 'hidden' set by default, since it might be something that could reduce friction and fragmentation between the two plats.

@rickhanlonii
Copy link
Contributor

Awesome stuff, this is really exciting work, thanks for driving it @necolas!

@EvanBacon
Copy link

This proposal is really great and I think it'll make React Native feel a lot more fluid.

I am concerned that the styling changes will really struggle to be developed due to the lack of ownership on Yoga -- I get a lot of questions from the community about this, would love some more clarity on Meta's plan to unblock developers who are trying to contribute more styling functionality.

Apple and Google's versions of React Native offer a lot of built-in style properties, which feels really expressive and powerful to use. I would love to see React Native catch up and offer a wider variety of cross-platform styles in the core primitives.


Suggestion: In addition to the new feature additions, it would also be nice if Android failed more gracefully when invalid or unsupported style properties are used, currently Android runtimes tend to throw fatal errors when typos are used repeatedly.

I see users also perform generalized filtering in runtime code to ensure the upstream Android components don't fail. Here's an example of such code:

Example
const WEB_STYLES = [
  "backdropFilter",
  "animationDelay",
  "animationDirection",
  "animationDuration",
  "animationFillMode",
  "animationName",
  "animationIterationCount",
  "animationPlayState",
  "animationTimingFunction",
  "backgroundAttachment",
  "backgroundBlendMode",
  "backgroundClip",
  "backgroundImage",
  "backgroundOrigin",
  "backgroundPosition",
  "backgroundRepeat",
  "backgroundSize",
  "boxShadow",
  "boxSizing",
  "clip",
  "cursor",
  "filter",
  "gridAutoColumns",
  "gridAutoFlow",
  "gridAutoRows",
  "gridColumnEnd",
  "gridColumnGap",
  "gridColumnStart",
  "gridRowEnd",
  "gridRowGap",
  "gridRowStart",
  "gridTemplateColumns",
  "gridTemplateRows",
  "gridTemplateAreas",
  "outline",
  "outlineColor",
  "overflowX",
  "overflowY",
  "overscrollBehavior",
  "overscrollBehaviorX",
  "overscrollBehaviorY",
  "perspective",
  "perspectiveOrigin",
  "touchAction",
  "transformOrigin",
  "transitionDelay",
  "transitionDuration",
  "transitionProperty",
  "transitionTimingFunction",
  "userSelect",
  "visibility",
  "willChange",
];

function filterPlatformStyles(style) {
  if (Platform.OS !== "web") {
    return Object.fromEntries(
      Object.entries(style).filter(([k]) => !WEB_STYLES.includes(k))
    );
  }
  return style;
}

@necolas
Copy link
Author

necolas commented Aug 15, 2022

First 2 umbrella issues for the simpler tasks mentioned in this proposal:

facebook/react-native#34424
facebook/react-native#34425

@necolas
Copy link
Author

necolas commented Feb 24, 2023

Added traversal APIs. We'll publish a separate RFC that goes into more detail on the traversal API motivation and implementation.

Expo also expressed interest in RN supporting more of the APIs from the WinterCG: https://common-min-api.proposal.wintercg.org/#index

* [ ] [`boxShadow`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow). Add native support for CSS box shadows to replace buggy, iOS-specific `shadow*` styles. Resolves issue (#26110)[https://github.com/facebook/react-native/pull/26110] and [multiple other issues](https://github.com/facebook/react-native/search?q=ios+shadow&type=issues).
* [ ] [`caretColor`](https://developer.mozilla.org/en-US/docs/Web/CSS/caret-color).
* [ ] [`clipPath`](https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path).
* [ ] [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) values of `block`, `contents` (resolves proposal [#348](https://github.com/react-native-community/discussions-and-proposals/issues/348)), `inline`, `inline-block`, `inline-flex`.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the goal is "the best bits of the web" then I feel like display: grid really ought to be supported too.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The layout engine is Yoga, and it doesn't support grid (because grid is fairly complicated to build on top of the native platforms).

I feel like grid should be a part of "Make RN more like Web V2" to keep from holding anything else up.


Ohhh, I just noticed you were in that issue and promoting something called Taffy grid. 🎉

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@corysimmons It doesn't. But then Yoga also doesn't support block, inline or float layout, and they're all included in this proposal. Even Yoga's Flexbox implementation isn't web compatible and will need a rework if the aim is to support web layouts without modification.

Grid is complicated, but it's not really much more complicated than flexbox. I link to an existing native code implementation that could be either be used alongside Yoga or ported into Yoga in the issue you mention (facebook/yoga#867) (disclaimer: I wrote said implementation - but this is not me just shilling my own library - I wrote it in large part because I want to see it in React Native)

Is Grid just considered less essential? It's one of the most highly requested feature by React Native end users (me being one them!). Surely it at least ought to be considered higher priority than float, no?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, offline I had advocated for "grid" before "block" or "inline", and I do think it would be likely to come first (though I would also believe there is more web code using the latter if porting existing web code is the main draw).

It is exciting that Taffy has an implementation of Grid as well, though I want to set expectations that we are not planning to sequence work to port grid in the short term. I don't think we have solved safely innovating on Yoga yet, nor do I think we have really solved problems which would let us smoothly transition RN to any alternative layout engines. Both are at the scale of hundreds of thousand of surfaces, and billions of users, and even small changes in behavior of performance characteristics can effectively take out major portions of the industry.

To create better clarity there is a plan I am going to share out for concrete Yoga + RN work we are taking on over the next couple of months, as a more concrete articulation of the vision and accompanying discussion shared late last year. The majority of it is around shaping Yoga/RN to start letting us make conformance changes more confidently, along with getting a new OSS release of Yoga out.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@NickGerleman I guess I'm pretty skeptical of what appears to be the proposed approach. Which as I understand it is something like the following:

Incrementally evolve the existing algorithm towards standards compliance using fine-grained feature flags to alter behaviour in each place where the standards-compliant behaviour differs from the legacy behaviour while keeping a shared implementation for parts where the behaviour is the same.

It seems to me that by taking such an approach you end up with what is essentially two different algorithms sharing an implementation and that this is good nobody:

  • It's not good for users of React Native who's apps are in maintenance mode and need strict backwards compatibility, because it means that almost any change to Yoga, even if it aimed at the new "web compatible" version of the algorithm, is likely to touch codepaths that their app uses. This greatly increases the chance of a regression / backwards incompatible change being introduced.

  • It's not good for users of React Native who want web-compatible layout because it means development will be much slower (see point 3) Which means that either such an implementation will not be available at all for some time to come (years?), or that there will ongoing breaking changes once they adopt the algorithm. Which may well not tolerable even for people who willing to do a one-time pass over their code to switch to a new algorithm.

  • It's not good for maintainers of / contributors to Yoga as it will be much harder to make sense of each algorithm's flow when the implementations of each are intertwined with each other. And also because it meants that every change has to be checked for compatibility with the legacy algorithm (even if it is only intended to affect the new one), for which Yoga does not have a good test suite and testing is slow. This also effectively all-but-excludes OSS contributors from contributing algorithm changes to Yoga as they will not have access to the testing infrastructure that Meta employees are using the to test for compatibility with legacy apps.

I also think you might be underestimating the amount of changes that would be required to make Yoga's current implementation standards compliant. Based on my experience making similar changes to Taffy (which is derived from an earlier version of Yoga, and even after the changes made so far is still not entirely standards compliant), I would not be at all surprised if a shared implementation of RN's current algorthm and a standards-compliant flexbox algorithm ended up with more code feature flagged than shared. I would expect the tweaks to be small, but large in number and widespread throughout the algorithm.


My counter-proposal would be something like the following:

  1. Adapt the current implementation such that rather than recursively calling itself when it needs to size or layout a child node, it calls into a layout_child function that it takes as a function pointer parameter (or some such similar arrangement that allows the caller to provide a function to call to size child nodes). This will allow either Yoga itself or the embedder of Yoga to take back control flow between each node in the hierarchy and enables the possibility of switching between different algorithms/implementatons for each node.

  2. Freeze the current algorithm as it is. Aside from things like minor changes for compatibility with new compiler or similar, this code doesn't get touched from this point onwards.

  3. Implement a new standards-compliant algorithm. This could either be a copy of the current algorithm adapted to be more standards compliant (but free from the burden of backwards compatibility). Or it could be a port of an existing implementation that is already (more) standards compliant. Or it could be directly calling into an existing implementation that is already (more) standards compliant.

  4. In terms of releasing the new algorithm to RN users: it should be done in an opt-in manner on a per-node basis. I would suggest something like a new Div component (or Flex/Row/Column components), leaving View to continue using the legacy algorithm indefinitely, but there are a few different ways that you could handle this. I also think some effort should be put into tightening up the standards-compliance of the new implementation before release (perhaps porting the WPT test suite) so as to largely avoid the need for further breaking changes (although it could potentially be released as a preview version first, similarly to how to Hermes was introduced).

Step 1 would need to be done carefully in order to avoid breaking backwards compatibility, but no more carefully than every single change would need to be made if you go down the shared implementation route. But once you've made that changes then most algorithm changes to the new algorithm wouldn't need nearly as much scrutiny as legacy users simply wouldn't use that codepath at all. And as far as I can see, such a change would need to be made anyway if you want to support mutliple layout algorithms (even ones as simple as display: block).

Copy link

@nicoburns nicoburns Mar 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you saying you think that's relatively straight-forward to add to Yoga too?

Yes, I think so. I think we'd need to implement changes similar to DioxusLabs/taffy#246 which factors out child sizing so that it isn't assumed that a child is display: flex (note that's 500+ files changed but most of those are tests. The relevant changes are in src/compute)

The block layout algorithm itself is pretty simple (https://www.w3.org/TR/CSS22/visuren.html#block-formatting), although it should be noted that there is a decent amount of complexity introduced by margin collapsing (https://www.w3.org/TR/CSS22/box.html#collapsing-margins), in particular because margins can collapse between parents and children rather than just between siblings. Which I think means that the block algorithm may need to recurse arbitrarily far down the tree whereas the flexbox algorithm only need to look at the styles of direct children.

My interest in primarily in getting div rendering as you'd expect on the web; not in changing the default layout used by View in existing surfaces.

If you're happy with how Text works and don't need display: inline-block then that seems achievable to me :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well there's always room for improvement but I'm hopeful that this would be enough to motivate further changes in the future! Thanks for taking the time to help me learn a bit more about all this

Copy link

@nicoburns nicoburns May 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@necolas Taffy has just landed (DioxusLabs/taffy#474) block layout support. The implementation (https://github.com/DioxusLabs/taffy/blob/main/src/compute/block.rs) was actually surprisingly straightforward (sitting at ~650 LoC, with a couple of relatively minor tweaks to the interface we use to allow parents to measure the size of their children in order to accommodate margin collapsing). And we have just over 200 (yoga-compatible) test fixtures to go with it.

However, I have another question for you around supporting <div>s with default styles: would you consider box-sizing: content-box support necessary? Because Yoga and Taffy both only support box-sizing: border-box currently. I figure that most of the web is resetting box-sizing to border-box but technically it isn't the default.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think context-box is another "improvement" rather than blocker. For context, the way I've implemented this API is to create a new library that exports "strict" DOM components. A cross-platform component looks like this:

import { html } from 'react-strict-dom';
import { stylex } from '@stylexjs/stylex';

const styles = stylex.create({
  root: {}
});

function MyComponent(props) {
  return (
    <html.div style={styles.root} {...props} />
  );
}

The html components are as designed in this spec, where style is a special prop for all platforms - it's more like the React Native one that then React DOM one. The html components on web come with a built-in style reset that normalizes the layout across web and native, including setting box-sizing:border-box. There's no way around that to get this off the ground, so we'll probably be "stuck" with border-box as the default long-term (which I expect most web products will be ok with, including if they migrate from react-dom). But eventually there may be benefits to including support for content-box too.

At least, that's my thinking right now.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following up on my previous comment. Internally we've had engineers surface rendering issues that were traced back to elements being styled with context-box as the assumed box-sizing, and switching those elements to border-box was an unexpected event that required style modifications to avoid regressions. So I think in the short-term, it may be an acceptable cost for early adopters rendering existing React DOM UI on native to have to experience regressions like this and do manual adjustments. But if you're trying to "migrate" larger amounts of existing React DOM code to render on native, the native renderer will eventually need the default

/ layouts to be accurate. I think this is especially valuable for UI because you often only see visual regressions once they've already broken something in production, unless your application has extensive screenshot testing (which most don't/can't).

@LunatiqueCoder
Copy link

Really nice work! 🎉

I was curious about linear-gradient() CSS function? Would love to see that be part of React Native as well 🙈

@nandorojo
Copy link

We've been using React Native together with React Native Web for the past few years building beatgig.com. This RFC's completion would have an enormous impact.

I'm excited for so much of this, namely:

  • More CSS styles (gradients, filters, mask-image, clip-path, etc.)
  • IntersectionObserver
  • Synchronous e.preventDefault() on html.input, allowing formatting without flickers
  • boxShadow allowing multiple shadows
  • Generally using web APIs that are well-documented all over the internet

I came to RN from the web originally, and having React DOM for Native would have saved me so much time and effort. Hiring for RN would get far simpler too, as any web developer could jump right into the role.

Thanks for all the work here.

@nandorojo
Copy link

I think transformOrigin should be added here. There’s a new PR for that by @intergalacticspacehighway at facebook/react-native#37606 for reference

@henrymoulton
Copy link

henrymoulton commented Jun 8, 2023

For anyone who prefers video form, @nandorojo's talk "React Native in 2030" has a section on Modern CSS here that references this RFC: https://youtu.be/dKItY_2wFH0?t=775

"The Dream" of write once, run anywhere would become substantially easier with this change, and Fernando's talk makes a pretty compelling argument.

@Pranav-yadav
Copy link

If I'm not bad at searching, would love to see <dialog> 🙈, provided aria-modal is already included.

Ref:

@nandorojo
Copy link

Might be worth adding z-index here, as its behavior on Native doesn't always match up with Web.

@aliraza-noon
Copy link

what would be the impact of this in terms of performance ?

@necolas
Copy link
Author

necolas commented Sep 14, 2023

Updated to reflect that we've implemented a large chunk of the "Elements API" on the new architecture. Added display:grid and <dialog> as part of the API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
💡 Proposal This label identifies a proposal
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet