|
| 1 | +/** |
| 2 | + * Copyright (c) Meta Platforms, Inc. and 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 | + * @flow strict |
| 8 | + */ |
| 9 | + |
| 10 | +import type { CompiledStyles } from '@stylexjs/stylex/lib/StyleXTypes'; |
| 11 | +import type { ReactDOMStyleProps } from '../../types/renderer.web'; |
| 12 | +import type { StrictSvgProps } from '../../../dist/types/StrictSvgProps'; |
| 13 | + |
| 14 | +import * as React from 'react'; |
| 15 | +import * as stylex from '@stylexjs/stylex'; |
| 16 | +import { errorMsg } from '../../shared/logUtils'; |
| 17 | +import { isSvgPropAllowed } from '../../shared/isSvgPropAllowed'; |
| 18 | + |
| 19 | +// $FlowFixMe[unclear-type] |
| 20 | +function validateStrictProps(props: any) { |
| 21 | + Object.keys(props).forEach((key) => { |
| 22 | + const isValid = isSvgPropAllowed(key); |
| 23 | + if (!isValid) { |
| 24 | + errorMsg(`invalid prop "${key}"`); |
| 25 | + delete props[key]; |
| 26 | + } |
| 27 | + }); |
| 28 | +} |
| 29 | + |
| 30 | +export function createStrictDOMSvgComponent<T, P: StrictSvgProps>( |
| 31 | + TagName: string, |
| 32 | + defaultStyle: StrictSvgProps['style'] |
| 33 | +): component(ref?: React.RefSetter<T>, ...P) { |
| 34 | + // NOTE: `debug-style` is not generated by `stylex.create` |
| 35 | + // so it needs a type-cast |
| 36 | + const debugStyle: CompiledStyles = { |
| 37 | + $$css: true, |
| 38 | + 'debug::name': `svg-${TagName}` as $FlowFixMe |
| 39 | + }; |
| 40 | + |
| 41 | + const component: React.AbstractComponent<P, T> = React.forwardRef( |
| 42 | + function (props, forwardedRef) { |
| 43 | + /** |
| 44 | + * get host props |
| 45 | + */ |
| 46 | + const { style, ...hostProps } = props; |
| 47 | + validateStrictProps(hostProps); |
| 48 | + |
| 49 | + if (props.role != null) { |
| 50 | + // "presentation" synonym has wider browser support |
| 51 | + // $FlowFixMe |
| 52 | + hostProps.role = props.role === 'none' ? 'presentation' : props.role; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * get host style props |
| 57 | + */ |
| 58 | + // Waiting on a diff so we can remove this indirection. |
| 59 | + const hostStyleProps: ReactDOMStyleProps = stylex.props([ |
| 60 | + debugStyle, |
| 61 | + defaultStyle, |
| 62 | + style |
| 63 | + ]); |
| 64 | + |
| 65 | + /** |
| 66 | + * Construct tree |
| 67 | + * |
| 68 | + * Intentional flow error as we are asking for a more specific type |
| 69 | + * than React itself. |
| 70 | + */ |
| 71 | + const element = ( |
| 72 | + <TagName |
| 73 | + {...hostProps} |
| 74 | + {...hostStyleProps} |
| 75 | + ref={forwardedRef as $FlowFixMe} |
| 76 | + /> |
| 77 | + ); |
| 78 | + return element; |
| 79 | + } |
| 80 | + ); |
| 81 | + |
| 82 | + component.displayName = `svg.${TagName}`; |
| 83 | + return component; |
| 84 | +} |
0 commit comments