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

[Slider] Improve TS definition of unstyled #26642

Merged
merged 3 commits into from
Jun 9, 2021
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
4 changes: 3 additions & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,9 @@ jobs:
command: yarn typescript:ci
- run:
name: Test module augmenation
command: yarn workspace @material-ui/core typescript:module-augmentation
command: |
yarn workspace @material-ui/core typescript:module-augmentation
yarn workspace @material-ui/unstyled typescript:module-augmentation

- restore_cache:
name: Restore generated declaration files
Expand Down
3 changes: 2 additions & 1 deletion packages/material-ui-unstyled/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@
"prebuild": "rimraf build tsconfig.build.tsbuildinfo",
"release": "yarn build && npm publish build --tag next",
"test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/material-ui-unstyled/**/*.test.{js,ts,tsx}'",
"typescript": "tslint -p tsconfig.json \"{src,test}/**/*.{spec,d}.{ts,tsx}\" && tsc -p tsconfig.json"
"typescript": "tslint -p tsconfig.json \"{src,test}/**/*.{spec,d}.{ts,tsx}\" && tsc -p tsconfig.json",
"typescript:module-augmentation": "node scripts/testModuleAugmentation.js"
},
"peerDependencies": {
"@types/react": "^16.8.6 || ^17.0.0",
Expand Down
65 changes: 65 additions & 0 deletions packages/material-ui-unstyled/scripts/testModuleAugmentation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const childProcess = require('child_process');
const { chunk } = require('lodash');
const glob = require('fast-glob');
const path = require('path');
const { promisify } = require('util');

const exec = promisify(childProcess.exec);
const packageRoot = path.resolve(__dirname, '../');

async function test(tsconfigPath) {
try {
await exec(['yarn', 'tsc', '--project', tsconfigPath].join(' '), { cwd: packageRoot });
} catch (error) {
if (error.stdout !== undefined) {
// `exec` error
throw new Error(`exit code ${error.code}: ${error.stdout}`);
}
// Unknown error
throw error;
}
}

/**
* Tests various module augmentation scenarios.
* We can't run them with a single `tsc` run since these apply globally.
* Running them all would mean they're not isolated.
* Each test case represents a section in our docs.
*
* We're not using mocha since mocha is used for runtime tests.
* This script also allows us to test in parallel which we can't do with our mocha tests.
*/
async function main() {
const tsconfigPaths = await glob('test/typescript/moduleAugmentation/*.tsconfig.json', {
absolute: true,
cwd: packageRoot,
});
// Need to process in chunks or we might run out-of-memory
// approximate yarn lerna --concurrency 7
const tsconfigPathsChunks = chunk(tsconfigPaths, 7);

// eslint-disable-next-line no-restricted-syntax
for await (const tsconfigPathsChunk of tsconfigPathsChunks) {
await Promise.all(
tsconfigPathsChunk.map(async (tsconfigPath) => {
await test(tsconfigPath).then(
() => {
// eslint-disable-next-line no-console -- test runner feedback
console.log(`PASS ${path.relative(process.cwd(), tsconfigPath)}`);
},
(error) => {
// don't bail but log the error
console.error(`FAIL ${path.relative(process.cwd(), tsconfigPath)}\n ${error}`);
// and mark the test as failed
process.exitCode = 1;
},
);
}),
);
}
}

main().catch((error) => {
console.error(error);
process.exit(1);
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { OverridableComponent, OverridableTypeMap, OverrideProps } from '@material-ui/types';
import { SliderUnstyledClasses } from './sliderUnstyledClasses';

export interface SliderStylePropsOverrides {}

export interface Mark {
value: number;
label?: React.ReactNode;
Expand Down Expand Up @@ -51,38 +53,43 @@ export interface SliderUnstyledTypeMap<P = {}, D extends React.ElementType = 'sp
*/
componentsProps?: {
root?: {
as: React.ElementType;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'>;
as?: React.ElementType;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'> &
SliderStylePropsOverrides;
};
Comment on lines 55 to 59
Copy link
Member

@oliviertassinari oliviertassinari Jun 10, 2021

Choose a reason for hiding this comment

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

@mnajdova Are we sure about these types? I'm lost when I look at them. In MUI-X @dtassone has used any

Suggested change
root?: {
as: React.ElementType;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'>;
as?: React.ElementType;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'> &
SliderStylePropsOverrides;
};
root?: any;

which might be too loose, but seems still better.

I mean, for instance, if I want to add an extra data- attribute it fails:

import * as React from 'react';
import SliderUnstyled from '@material-ui/unstyled/SliderUnstyled';

export default function UnstyledSlider() {
  return (
    <SliderUnstyled componentsProps={{ root: { 'data-foo': 'bar' } }} defaultValue={10} />
  );
}

Capture d’écran 2021-06-10 à 22 15 23


On styleProps specifically, I also don't see why we use SliderUnstyledTypeMap. As far as I know, the correlation between the props and what's available in this prop is "light". For instance, in the slider, we have an extra marked property:

https://github.com/mui-org/material-ui/blob/d36858d36741bb57facb7f1e91d0d2d4d760b4bb/packages/material-ui-unstyled/src/SliderUnstyled/SliderUnstyled.js#L624

Copy link
Member

Choose a reason for hiding this comment

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

I'm in favor of using specific types instead of any whenever possible. This way developers get prop validation for free from Typescript (this can be especially important if a component with mandatory props is used in a slot).
The data-foo you mentioned is a bit of an edge case as data attributes are not specified in any HTMLAttributes. To use them in a type-safe way, module augmentation should be used. However, IMO this should be the only case where developers should resort to module augmentation when providing componentsProps.

Copy link
Member

@oliviertassinari oliviertassinari Jun 10, 2021

Choose a reason for hiding this comment

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

@michaldudak data-*, tabindex, aria-*, they all fail. We don't accept any other props than as and styleProps. The issue for me is that we don't have any easy way to know what are types accepted. A developer could use components to render something completely different.

Copy link
Member

@michaldudak michaldudak Jun 10, 2021

Choose a reason for hiding this comment

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

In this case yes, they'll fail without module augmentation. But we could use what I made in https://github.com/mui-org/material-ui/blob/d587b1eab467739a2a143f0cd49bfc10cc35ba74/packages/material-ui-unstyled/src/SwitchUnstyled/SwitchUnstyled.tsx - when you pass in a component/intrinsic element in components prop, the corresponding componentsProps expects props for this exact component/element. data-* attributes obviously aren't supported this way, but all the others are (including aria-*)

Copy link
Member

@oliviertassinari oliviertassinari Jun 13, 2021

Choose a reason for hiding this comment

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

when you pass in a component/intrinsic element in components prop, the corresponding componentsProps

@michaldudak This approach seems to have potential 👍 .

Should we open a new issue to keep track of this problem?

Copy link
Member

Choose a reason for hiding this comment

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

Sure thing: #26810

track?: {
as?: React.ElementType;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'>;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'> &
SliderStylePropsOverrides;
};
rail?: {
as?: React.ElementType;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'>;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'> &
SliderStylePropsOverrides;
};
thumb?: {
as?: React.ElementType;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'>;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'> &
SliderStylePropsOverrides;
};
mark?: {
as?: React.ElementType;
styleProps?: Omit<
SliderUnstyledTypeMap<P, D>['props'],
'components' | 'componentsProps'
> & { markActive?: boolean };
> & { markActive?: boolean } & SliderStylePropsOverrides;
};
markLabel?: {
as?: React.ElementType;
styleProps?: Omit<
SliderUnstyledTypeMap<P, D>['props'],
'components' | 'componentsProps'
> & { markLabelActive?: boolean };
> & { markLabelActive?: boolean } & SliderStylePropsOverrides;
};
valueLabel?: {
as?: React.ElementType;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'>;
styleProps?: Omit<SliderUnstyledTypeMap<P, D>['props'], 'components' | 'componentsProps'> &
SliderStylePropsOverrides;
};
};
/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import * as React from 'react';
import { SliderUnstyled } from '@material-ui/unstyled';

declare module '@material-ui/unstyled' {
interface SliderStylePropsOverrides {
color?: 'primary' | 'secondary';
}
}

<SliderUnstyled componentsProps={{ root: { styleProps: { color: 'primary' } } }} />;

// @ts-expect-error unknown color
<SliderUnstyled componentsProps={{ root: { styleProps: { color: 'inherit' } } }} />;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "../../../../../tsconfig",
"files": ["sliderStyleProps.spec.tsx"]
}