Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .config/eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,20 @@ export default tseslint.config(
"@typescript-eslint/no-unsafe-member-access": "off",
},
},
// Enforce new members automatically via linting rather than tests
// An optional prop this package adds to a React Native interface takes `| undefined`, as React Native's own do, so it accepts an explicit undefined under exactOptionalPropertyTypes
{
files: ["types.d.ts"],
rules: {
"no-restricted-syntax": [
"error",
{
selector:
"TSModuleDeclaration TSInterfaceBody > TSPropertySignature[optional=true] > TSTypeAnnotation > :not(TSUnionType:has(> TSUndefinedKeyword))",
message:
"Write `?: T | undefined`: under exactOptionalPropertyTypes a bare `?: T` rejects the explicit undefined React Native's own props accept.",
},
],
},
},
);
19 changes: 19 additions & 0 deletions src/__tests__/native/styled.test.ios.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,25 @@ test.each(["nativeStyleMapping", "nativeStyleToProp"] as const)(
},
);

test("a mapping entry set to undefined maps nothing", () => {
registerCSS(`.subject { color: blue; background-color: red; }`);
const StyledView = styled(View, {
className: {
target: "style",
nativeStyleMapping: {
color: "accessibilityLabel",
backgroundColor: undefined,
},
},
});

render(<StyledView testID={testID} className="subject" />);

const props = screen.getByTestId(testID).props;
expect(props.accessibilityLabel).toBe("#00f");
expect(props.style).toEqual({ backgroundColor: "#f00" });
});

test.each([false, true])(
"current mapping wins over deprecated alias (empty: %s)",
(empty) => {
Expand Down
133 changes: 133 additions & 0 deletions src/__tests__/types/exact-optional.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { join } from "node:path";

import ts from "typescript";

const root = join(__dirname, "../../..").replaceAll("\\", "/");
const fixtureName = `${root}/src/__tests__/types/exact-optional.fixture.tsx`;

// Writes an explicit undefined to each optional member a consumer writes
const fixture = `
import createDebug from "debug";
import type { MetroConfig } from "metro-config";
import {
Button,
FlatList,
Image,
ImageBackground,
KeyboardAvoidingView,
ScrollView,
Switch,
Text,
TouchableWithoutFeedback,
View,
} from "react-native";
import { styled } from "react-native-css";
import { compile } from "react-native-css/compiler";
import { compileWithAutoDebug, registerCSS } from "react-native-css/jest";
import { withReactNativeCSS } from "react-native-css/metro";
import type { Config } from "react-native-css/native/react/useNativeCss";
import type { Effect } from "react-native-css/native/reactivity";

declare const maybe: string | undefined;
declare const metroConfig: MetroConfig;

const StyledView = styled(View);
const MappedView = styled(
View,
{
className: {
target: "style",
nativeStyleMapping: { color: "accessibilityLabel", backgroundColor: undefined },
},
contentClassName: { target: "style", nativeStyleMapping: undefined },
},
{ passThrough: undefined },
);

export const elements = [
<View className={maybe} />,
<Text className={maybe} />,
<Image source={{}} className={maybe} />,
<ImageBackground source={{}} imageClassName={maybe} />,
<Switch className={maybe} />,
<Button title="" className={maybe} />,
<TouchableWithoutFeedback className={maybe} />,
<ScrollView contentContainerClassName={maybe} />,
<KeyboardAvoidingView contentContainerClassName={maybe} />,
<FlatList
data={[]}
renderItem={() => null}
columnWrapperClassName={maybe}
ListHeaderComponentClassName={maybe}
ListFooterComponentClassName={maybe}
/>,
<StyledView className={maybe} />,
<MappedView className={maybe} contentClassName={maybe} />,
];

compile("", {
filename: undefined,
projectRoot: undefined,
inlineRem: undefined,
inlineVariables: { exclude: undefined },
selectorPrefix: undefined,
stylesheetOrder: undefined,
features: undefined,
logger: undefined,
hexColors: undefined,
colorPrecision: undefined,
});
compile("", { logger: createDebug("test") });
compile("", { logger: (message: string) => void message });

registerCSS("", { debug: undefined });
compileWithAutoDebug("", { debug: undefined });

withReactNativeCSS(metroConfig, {
typescriptEnvPath: undefined,
disableTypeScriptGeneration: undefined,
globalClassNamePolyfill: undefined,
hexColors: undefined,
warnings: undefined,
});

export const config: Config = { source: "a", target: "a", nativeStyleMapping: undefined };
export const effect: Effect = {
observers: new Set(),
run() {},
dependencies: undefined,
snapshots: undefined,
};
`;

test("each optional member a consumer writes accepts an explicit undefined under exactOptionalPropertyTypes", () => {
const { config } = ts.readConfigFile(`${root}/tsconfig.json`, (path) =>
ts.sys.readFile(path),
);
const { options } = ts.parseJsonConfigFileContent(config, ts.sys, root);
const compilerOptions = { ...options, exactOptionalPropertyTypes: true };

const host = ts.createCompilerHost(compilerOptions, true);
const program = ts.createProgram(
[`${root}/types.d.ts`, fixtureName],
compilerOptions,
{
...host,
fileExists: (name) => name === fixtureName || host.fileExists(name),
getSourceFile: (name, languageVersion, ...rest) =>
name === fixtureName
? ts.createSourceFile(name, fixture, languageVersion, true)
: host.getSourceFile(name, languageVersion, ...rest),
},
);

const errors = ts
.getPreEmitDiagnostics(program, program.getSourceFile(fixtureName))
.map(({ file, start = 0, messageText }) => {
const line = file?.getLineAndCharacterOfPosition(start).line ?? -1;
const message = ts.flattenDiagnosticMessageText(messageText, "\n");
return `${line + 1}: ${message.split("\n")[0]}`;
});

expect(errors).toStrictEqual([]);
});
22 changes: 11 additions & 11 deletions src/compiler/compiler.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@ import type {
import { VAR_SYMBOL } from "../native/reactivity";

export interface CompilerOptions {
filename?: string;
projectRoot?: string;
inlineRem?: number | false;
inlineVariables?: false | InlineVariableOptions;
selectorPrefix?: string;
stylesheetOrder?: number;
features?: FeatureFlagRecord;
logger?: (message: string) => void | Debugger;
hexColors?: boolean;
colorPrecision?: number;
filename?: string | undefined;
projectRoot?: string | undefined;
inlineRem?: number | false | undefined;
inlineVariables?: false | InlineVariableOptions | undefined;
selectorPrefix?: string | undefined;
stylesheetOrder?: number | undefined;
features?: FeatureFlagRecord | undefined;
logger?: ((message: string) => void) | Debugger | undefined;
hexColors?: boolean | undefined;
colorPrecision?: number | undefined;
}

export interface InlineVariableOptions {
exclude?: `--${string}`[];
exclude?: `--${string}`[] | undefined;
}

// A channel is absent when the compile recorded nothing on it
Expand Down
4 changes: 2 additions & 2 deletions src/jest/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const debugDefault = Boolean(

export function registerCSS(
css: string,
options: CompilerOptions & { debug?: boolean } = {},
options: CompilerOptions & { debug?: boolean | undefined } = {},
) {
const { debug = debugDefault } = options;
const compiled = compileWithAutoDebug(css, options);
Expand All @@ -62,7 +62,7 @@ export function compileWithAutoDebug(
{
debug = debugDefault,
...options
}: CompilerOptions & { debug?: boolean | "verbose" } = {},
}: CompilerOptions & { debug?: boolean | "verbose" | undefined } = {},
) {
const logger = debug
? (text: string) => {
Expand Down
10 changes: 5 additions & 5 deletions src/metro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ import type { WarningLevel } from "./warnings";

export interface WithReactNativeCSSOptions extends CompilerOptions {
/* Specify the path to the TypeScript environment file. Defaults types-env.d.ts */
typescriptEnvPath?: string;
typescriptEnvPath?: string | undefined;
/* Disable generation of the types-env.d.ts file. Defaults false */
disableTypeScriptGeneration?: boolean;
disableTypeScriptGeneration?: boolean | undefined;
/** Add className to all React Native primitives. Defaults false */
globalClassNamePolyfill?: boolean;
hexColors?: boolean;
globalClassNamePolyfill?: boolean | undefined;
hexColors?: boolean | undefined;
/** How native builds print the compiler's warnings. Defaults "summary" */
warnings?: WarningLevel;
warnings?: WarningLevel | undefined;
}

export type { WarningLevel } from "./warnings";
Expand Down
8 changes: 6 additions & 2 deletions src/native/react/useNativeCss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { updateRules } from "./rules";
export type Config = {
source: string;
target: string[] | string | false;
nativeStyleMapping?: Record<string, string>;
nativeStyleMapping?: Record<string, string> | undefined;
};

export type ComponentState = {
Expand Down Expand Up @@ -226,7 +226,11 @@ const configForMapping = weakFamily(function (
const mapping = value.nativeStyleMapping ?? value.nativeStyleToProp;
const nativeStyleMapping = mapping
? Object.fromEntries(
Object.entries(mapping).map(([k, v]) => [k, v === true ? k : v]),
Object.entries(mapping).flatMap(([property, path]) =>
path === undefined
? []
: [[property, path === true ? property : path] as const],
),
)
: undefined;

Expand Down
4 changes: 2 additions & 2 deletions src/native/reactivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export type Effect = {
observers: Set<Observable<any, any>>;
run(): void;
/** Dependencies recorded by the last cleanupEffect() */
dependencies?: Observable<any, any>[];
dependencies?: Observable<any, any>[] | undefined;
/** Dependency values recorded by the last cleanupEffect() */
snapshots?: [Observable<any, any>, unknown][];
snapshots?: [Observable<any, any>, unknown][] | undefined;
};

export type Observable<Value, Arg = Value> = {
Expand Down
37 changes: 22 additions & 15 deletions src/runtime.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export type StyledReactElement<
: M[K] extends true | string | object
? K
: never
: never]?: string;
: never]?: string | undefined;
}
>;

Expand All @@ -42,15 +42,17 @@ export type StyledProps<P, M extends StyledConfiguration<any>> = P & {
: M[K] extends true | string | object
? K
: never
: never]?: string;
: never]?: string | undefined;
};

export interface Styled {
<const C extends ReactComponent>(
component: C,
mapping?: undefined,
options?: StyledOptions,
): ComponentType<ComponentPropsWithRef<C> & { className?: string }>;
): ComponentType<
ComponentPropsWithRef<C> & { className?: string | undefined }
>;
<const C extends ReactComponent, const M extends StyledConfiguration<C>>(
component: C,
mapping: M & StyledConfiguration<C>,
Expand All @@ -69,7 +71,7 @@ type StyledComponent<
: M[K] extends true | string | object
? K
: never
: never]?: string;
: never]?: string | undefined;
}
>;

Expand All @@ -88,27 +90,32 @@ interface StyledConfigurationObject<
T extends ComponentPropsDotNotation<C> | false,
> {
target: T;
nativeStyleMapping?: T extends false
? NativeStyleMapping<string, ComponentProps<C>>
: NativeStyleMapping<
ResolveDotPath<T, ComponentProps<C>>,
ComponentProps<C>
>;
nativeStyleMapping?:
| (T extends false
? NativeStyleMapping<string, ComponentProps<C>>
: NativeStyleMapping<
ResolveDotPath<T, ComponentProps<C>>,
ComponentProps<C>
>)
| undefined;
/** @deprecated Please use nativeStyleMapping */
nativeStyleToProp?: StyledConfigurationObject<C, T>["nativeStyleMapping"];
}

type NativeStyleMapping<T, S> = T extends object
? {
[K in keyof T as K extends string ? K : never]: true | DotNotation<S>;
[K in keyof T as K extends string ? K : never]:
| true
| DotNotation<S>
| undefined;
} & {
fill?: true | DotNotation<S>;
stroke?: true | DotNotation<S>;
fill?: true | DotNotation<S> | undefined;
stroke?: true | DotNotation<S> | undefined;
}
: Record<string, true | DotNotation<S>>;
: Record<string, true | DotNotation<S> | undefined>;

export interface StyledOptions {
passThrough?: boolean;
passThrough?: boolean | undefined;
}

/*************************** React Helpers ***************************/
Expand Down
Loading
Loading