Skip to content

Commit

Permalink
[core] Use readonly arrays where possible (#25746)
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon authored Apr 15, 2021
1 parent afc9a21 commit b3c85de
Show file tree
Hide file tree
Showing 55 changed files with 134 additions and 121 deletions.
22 changes: 16 additions & 6 deletions docs/scripts/buildApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ interface ReactApi extends ReactDocgenApi {
forwardsRefTo: string | undefined;
inheritance: { component: string; pathname: string } | null;
name: string;
pagesMarkdown: Array<{ components: string[]; filename: string; pathname: string }>;
pagesMarkdown: ReadonlyArray<{
components: readonly string[];
filename: string;
pathname: string;
}>;
spread: boolean | undefined;
src: string;
styles: {
Expand Down Expand Up @@ -245,7 +249,9 @@ function generatePropDescription(prop: DescribeablePropDescriptor, propName: str

// Split up the parsed tags into 'arguments' and 'returns' parsed objects. If there's no
// 'returns' parsed object (i.e., one with title being 'returns'), make one of type 'void'.
const parsedArgs: doctrine.Tag[] = annotation.tags.filter((tag) => tag.title === 'param');
const parsedArgs: readonly doctrine.Tag[] = annotation.tags.filter(
(tag) => tag.title === 'param',
);
let parsedReturns:
| { description?: string | null; type?: doctrine.Type | null }
| undefined = annotation.tags.find((tag) => tag.title === 'returns');
Expand Down Expand Up @@ -858,7 +864,11 @@ async function parseComponentSource(

async function buildDocs(options: {
component: { filename: string };
pagesMarkdown: Array<{ components: string[]; filename: string; pathname: string }>;
pagesMarkdown: ReadonlyArray<{
components: readonly string[];
filename: string;
pathname: string;
}>;
prettierConfigPath: string;
outputDirectory: string;
theme: object;
Expand Down Expand Up @@ -1257,7 +1267,7 @@ function generateApiPagesManifest(outputPath: string, prettierConfigPath: string
writePrettifiedFile(outputPath, source, prettierConfigPath);
}

async function removeOutdatedApiDocsTranslations(components: ReactApi[]): Promise<void> {
async function removeOutdatedApiDocsTranslations(components: readonly ReactApi[]): Promise<void> {
const componentDirectories = new Set<string>();
const files = await fse.readdir(apiDocsTranslationsDirectory);
await Promise.all(
Expand Down Expand Up @@ -1291,7 +1301,7 @@ async function removeOutdatedApiDocsTranslations(components: ReactApi[]): Promis

async function run(argv: {
apiPagesManifestPath?: string;
componentDirectories?: string[];
componentDirectories?: readonly string[];
grep?: string;
outputDirectory?: string;
}) {
Expand Down Expand Up @@ -1340,7 +1350,7 @@ async function run(argv: {
const components = componentDirectories
.reduce((directories, componentDirectory) => {
return directories.concat(findComponents(componentDirectory));
}, [] as Array<{ filename: string }>)
}, [] as ReadonlyArray<{ filename: string }>)
.filter((component) => {
if (component.filename.includes('ThemeProvider')) {
return false;
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export interface MuiPage {
title?: string;
}

const pages: MuiPage[] = [
const pages: readonly MuiPage[] = [
{
pathname: '/getting-started',
children: [
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/autocomplete/Asynchronous.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function sleep(delay = 0) {

export default function Asynchronous() {
const [open, setOpen] = React.useState(false);
const [options, setOptions] = React.useState<Film[]>([]);
const [options, setOptions] = React.useState<readonly Film[]>([]);
const loading = open && options.length === 0;

React.useEffect(() => {
Expand Down
5 changes: 3 additions & 2 deletions docs/src/pages/components/autocomplete/CountrySelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default function CountrySelect() {
<Autocomplete
id="country-select-demo"
style={{ width: 300 }}
options={countries as CountryType[]}
options={countries}
classes={{
option: classes.option,
}}
Expand Down Expand Up @@ -61,10 +61,11 @@ interface CountryType {
code: string;
label: string;
phone: string;
suggested?: boolean;
}

// From https://bitbucket.org/atlassian/atlaskit-mk-2/raw/4ad0e56649c3e6c973e226b7efaeb28cb240ccb0/packages/core/select/src/data/countries.js
const countries = [
const countries: readonly CountryType[] = [
{ code: 'AD', label: 'Andorra', phone: '376' },
{
code: 'AE',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ interface FilmOptionType {
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films: FilmOptionType[] = [
const top100Films: readonly FilmOptionType[] = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default function FreeSoloCreateOptionDialog() {
}
}}
filterOptions={(options, params) => {
const filtered = filter(options, params) as FilmOptionType[];
const filtered = filter(options, params);

if (params.inputValue !== '') {
filtered.push({
Expand Down Expand Up @@ -147,7 +147,7 @@ interface FilmOptionType {
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films: FilmOptionType[] = [
const top100Films: readonly FilmOptionType[] = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
Expand Down
13 changes: 8 additions & 5 deletions docs/src/pages/components/autocomplete/GoogleMaps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ interface MainTextMatchedSubstrings {
interface StructuredFormatting {
main_text: string;
secondary_text: string;
main_text_matched_substrings: MainTextMatchedSubstrings[];
main_text_matched_substrings: readonly MainTextMatchedSubstrings[];
}
interface PlaceType {
description: string;
Expand All @@ -47,7 +47,7 @@ export default function GoogleMaps() {
const classes = useStyles();
const [value, setValue] = React.useState<PlaceType | null>(null);
const [inputValue, setInputValue] = React.useState('');
const [options, setOptions] = React.useState<PlaceType[]>([]);
const [options, setOptions] = React.useState<readonly PlaceType[]>([]);
const loaded = React.useRef(false);

if (typeof window !== 'undefined' && !loaded.current) {
Expand All @@ -65,7 +65,10 @@ export default function GoogleMaps() {
const fetch = React.useMemo(
() =>
throttle(
(request: { input: string }, callback: (results?: PlaceType[]) => void) => {
(
request: { input: string },
callback: (results?: readonly PlaceType[]) => void,
) => {
(autocompleteService.current as any).getPlacePredictions(
request,
callback,
Expand All @@ -91,9 +94,9 @@ export default function GoogleMaps() {
return undefined;
}

fetch({ input: inputValue }, (results?: PlaceType[]) => {
fetch({ input: inputValue }, (results?: readonly PlaceType[]) => {
if (active) {
let newOptions = [] as PlaceType[];
let newOptions: readonly PlaceType[] = [];

if (value) {
newOptions = [value];
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/autocomplete/Tags.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export default function Tags() {
options={top100Films.map((option) => option.title)}
defaultValue={[top100Films[13].title]}
freeSolo
renderTags={(value: string[], getTagProps) =>
renderTags={(value: readonly string[], getTagProps) =>
value.map((option: string, index: number) => (
<Chip variant="outlined" label={option} {...getTagProps({ index })} />
))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ interface MessageExample {
person: string;
}

const messageExamples: MessageExample[] = [
const messageExamples: readonly MessageExample[] = [
{
primary: 'Brunch this week?',
secondary: "I'll be in the neighbourhood this week. Let's grab a bite to eat",
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/chips/ChipsArray.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const ListItem = styled('li')(({ theme }) => ({
}));

export default function ChipsArray() {
const [chipData, setChipData] = React.useState<ChipData[]>([
const [chipData, setChipData] = React.useState<readonly ChipData[]>([
{ key: 0, label: 'Angular' },
{ key: 1, label: 'jQuery' },
{ key: 2, label: 'Polymer' },
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/date-picker/CustomDay.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default function CustomDay() {
const classes = useStyles();
const [value, setValue] = React.useState(new Date());

const renderWeekPickerDay = (date, _selectedDates, pickersDayProps) => {
const renderWeekPickerDay = (date, selectedDates, pickersDayProps) => {
if (!value) {
return <PickersDay {...pickersDayProps} />;
}
Expand Down
4 changes: 2 additions & 2 deletions docs/src/pages/components/date-picker/CustomDay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default function CustomDay() {

const renderWeekPickerDay = (
date: Date,
_selectedDates: Date[],
selectedDates: Array<Date | null>,
pickersDayProps: PickersDayProps<Date>,
) => {
if (!value) {
Expand Down Expand Up @@ -71,7 +71,7 @@ export default function CustomDay() {
onChange={(newValue) => {
setValue(newValue);
}}
renderDay={renderWeekPickerDay as any}
renderDay={renderWeekPickerDay}
renderInput={(params) => <TextField {...params} />}
inputFormat="'Week of' MMM d"
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export default function SwipeableTemporaryDrawer() {

return (
<div>
{(['left', 'right', 'top', 'bottom'] as Anchor[]).map((anchor) => (
{(['left', 'right', 'top', 'bottom'] as const).map((anchor) => (
<React.Fragment key={anchor}>
<Button onClick={toggleDrawer(anchor, true)}>{anchor}</Button>
<SwipeableDrawer
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/drawers/TemporaryDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export default function TemporaryDrawer() {

return (
<div>
{(['left', 'right', 'top', 'bottom'] as Anchor[]).map((anchor) => (
{(['left', 'right', 'top', 'bottom'] as const).map((anchor) => (
<React.Fragment key={anchor}>
<Button onClick={toggleDrawer(anchor, true)}>{anchor}</Button>
<Drawer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export default function MultipleSelectCheckmarks() {
value={personName}
onChange={handleChange}
input={<Input />}
renderValue={(selected) => (selected as string[]).join(', ')}
renderValue={(selected) => selected.join(', ')}
MenuProps={MenuProps}
>
{names.map((name) => (
Expand Down
4 changes: 2 additions & 2 deletions docs/src/pages/components/selects/MultipleSelectChip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const names = [
'Kelly Snyder',
];

function getStyles(name: string, personName: string[], theme: Theme) {
function getStyles(name: string, personName: readonly string[], theme: Theme) {
return {
fontWeight:
personName.indexOf(name) === -1
Expand Down Expand Up @@ -79,7 +79,7 @@ export default function MultipleSelectChip() {
input={<Input id="select-multiple-chip" />}
renderValue={(selected) => (
<div className={classes.chips}>
{(selected as string[]).map((value) => (
{selected.map((value) => (
<Chip key={value} label={value} className={classes.chip} />
))}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const names = [
'Kelly Snyder',
];

function getStyles(name: string, personName: string[], theme: Theme) {
function getStyles(name: string, personName: readonly string[], theme: Theme) {
return {
fontWeight:
personName.indexOf(name) === -1
Expand Down Expand Up @@ -71,11 +71,11 @@ export default function MultipleSelectPlaceholder() {
onChange={handleChange}
input={<Input />}
renderValue={(selected) => {
if ((selected as string[]).length === 0) {
if (selected.length === 0) {
return <em>Placeholder</em>;
}

return (selected as string[]).join(', ');
return selected.join(', ');
}}
MenuProps={MenuProps}
inputProps={{ 'aria-label': 'Without label' }}
Expand Down
7 changes: 6 additions & 1 deletion docs/src/pages/components/skeleton/SkeletonTypography.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import Typography, { TypographyProps } from '@material-ui/core/Typography';
import Skeleton from '@material-ui/core/Skeleton';
import Grid from '@material-ui/core/Grid';

const variants = ['h1', 'h3', 'body1', 'caption'] as TypographyProps['variant'][];
const variants = [
'h1',
'h3',
'body1',
'caption',
] as readonly TypographyProps['variant'][];

function TypographyDemo(props: { loading?: boolean }) {
const { loading = false } = props;
Expand Down
4 changes: 2 additions & 2 deletions docs/src/pages/components/snackbars/ConsecutiveSnackbars.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ export interface SnackbarMessage {

export interface State {
open: boolean;
snackPack: SnackbarMessage[];
snackPack: readonly SnackbarMessage[];
messageInfo?: SnackbarMessage;
}

export default function ConsecutiveSnackbars() {
const [snackPack, setSnackPack] = React.useState<SnackbarMessage[]>([]);
const [snackPack, setSnackPack] = React.useState<readonly SnackbarMessage[]>([]);
const [open, setOpen] = React.useState(false);
const [messageInfo, setMessageInfo] = React.useState<SnackbarMessage | undefined>(
undefined,
Expand Down
8 changes: 4 additions & 4 deletions docs/src/pages/components/tables/EnhancedTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ function getComparator<Key extends keyof any>(
: (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort<T>(array: T[], comparator: (a: T, b: T) => number) {
function stableSort<T>(array: readonly T[], comparator: (a: T, b: T) => number) {
const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
stabilizedThis.sort((a, b) => {
const order = comparator(a[0], b[0]);
Expand All @@ -103,7 +103,7 @@ interface HeadCell {
numeric: boolean;
}

const headCells: HeadCell[] = [
const headCells: readonly HeadCell[] = [
{
id: 'name',
numeric: false,
Expand Down Expand Up @@ -291,7 +291,7 @@ export default function EnhancedTable() {
const classes = useStyles();
const [order, setOrder] = React.useState<Order>('asc');
const [orderBy, setOrderBy] = React.useState<keyof Data>('calories');
const [selected, setSelected] = React.useState<string[]>([]);
const [selected, setSelected] = React.useState<readonly string[]>([]);
const [page, setPage] = React.useState(0);
const [dense, setDense] = React.useState(false);
const [rowsPerPage, setRowsPerPage] = React.useState(5);
Expand All @@ -316,7 +316,7 @@ export default function EnhancedTable() {

const handleClick = (event: React.MouseEvent<unknown>, name: string) => {
const selectedIndex = selected.indexOf(name);
let newSelected: string[] = [];
let newSelected: readonly string[] = [];

if (selectedIndex === -1) {
newSelected = newSelected.concat(selected, name);
Expand Down
4 changes: 2 additions & 2 deletions docs/src/pages/components/tables/ReactVirtualizedTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ interface Row {
}

interface MuiVirtualizedTableProps extends WithStyles<typeof styles> {
columns: ColumnData[];
columns: readonly ColumnData[];
headerHeight?: number;
onRowClick?: () => void;
rowCount: number;
Expand Down Expand Up @@ -186,7 +186,7 @@ interface Data {
}
type Sample = [string, number, number, number, number];

const sample: Sample[] = [
const sample: readonly Sample[] = [
['Frozen yoghurt', 159, 6.0, 24, 4.0],
['Ice cream sandwich', 237, 9.0, 37, 4.3],
['Eclair', 262, 16.0, 24, 6.0],
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/tables/SpanningTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ interface Row {
price: number;
}

function subtotal(items: Row[]) {
function subtotal(items: readonly Row[]) {
return items.map(({ price }) => price).reduce((sum, i) => sum + i, 0);
}

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/tables/StickyHeadTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ interface Column {
format?: (value: number) => string;
}

const columns: Column[] = [
const columns: readonly Column[] = [
{ id: 'name', label: 'Name', minWidth: 170 },
{ id: 'code', label: 'ISO\u00a0Code', minWidth: 100 },
{
Expand Down
Loading

0 comments on commit b3c85de

Please sign in to comment.