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

Update eslint settings and fix errors #2383

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
26 changes: 23 additions & 3 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
{
"extends": ["react-app"],
"extends": [
"react-app",
"react-app/jest",
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:react/recommended",
"plugin:react-hooks/recommended"
],
"rules": {
"import/no-anonymous-default-export": "off"
}
"import/no-anonymous-default-export": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"no-prototype-builtins": "off",
"react/prop-types": "off",
"react/display-name": "off"
},
"ignorePatterns": [
"node_modules",
"build",
"coverage",
"src/test",
"*.js",
"*.spec.*"
]
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"scripts": {
"trust-localhost": "./script/trust-localhost.bash",
"lint": "npm run-script lint:bash && npm run-script lint:css && npm run-script lint:typescript",
"lint:typescript": "tslint -p ./tsconfig.json && tsc",
"lint:typescript": "eslint src && tslint -p ./tsconfig.json && tsc",
"lint:exports": "ts-unused-exports ./tsconfig.json",
"lint:css": "stylelint 'src/**/*.tsx'",
"lint:bash": "shellcheck $(find . -type f \\( -iname '*\\.sh' -or -iname '*\\.bash' \\) | grep -v 'node_modules' )",
Expand Down
1 change: 1 addition & 0 deletions src/app/components/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const applyColor = (color: ColorSet) => `
type Variant = 'primary' | 'secondary' | 'transparent' | 'default';
type Size = 'large' | 'medium' | 'small';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ComponentType = keyof JSX.IntrinsicElements | React.JSXElementConstructor<any>;

interface ButtonProps<T extends ComponentType | undefined> {
Expand Down
4 changes: 2 additions & 2 deletions src/app/components/DotMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ export const DotMenuIcon = styled(EllipsisV)`

// tslint:disable-next-line:variable-name
export const DotMenuToggle = styled(
React.forwardRef<HTMLDivElement, {isOpen: boolean}>(
({isOpen, ...props}, ref) => {
React.forwardRef(
({isOpen, ...props}: {isOpen: boolean}, ref) => {

return (
<PlainButton aria-label='Actions' aria-expanded={isOpen} {...props} ref={ref}>
Expand Down
1 change: 1 addition & 0 deletions src/app/components/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import theme, { defaultFocusOutline } from '../theme';
import { preventDefault } from '../utils';
import { textStyle } from './Typography/base';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ComponentWithRef = React.ComponentType<{ref: React.RefObject<any>}>;
interface ToggleProps<T extends ComponentWithRef = ComponentWithRef> {
className?: string;
Expand Down
2 changes: 1 addition & 1 deletion src/app/components/GoToTopButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const GoToTopIcon = styled(AngleUp)`
interface GoToTopButtonProps {
i18nAriaLabel: string;
onClick: () => void;
[key: string]: any;
[key: string]: unknown;
}

// tslint:disable-next-line: variable-name
Expand Down
2 changes: 1 addition & 1 deletion src/app/components/ScrollOffset.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export default class ScrollOffset extends React.Component<ScrollOffsetProps> {
}
};

private checkScroll = (maxChecks: number = 1) => {
private checkScroll = (maxChecks = 1) => {
let scrolls = 0;
const handler = () => {
scrolls++;
Expand Down
4 changes: 2 additions & 2 deletions src/app/components/htmlMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React, { ComponentType, HTMLAttributes } from 'react';
import { useIntl } from 'react-intl';

// tslint:disable-next-line:variable-name
type Type = <T extends any>(messageKey: string, Component: ComponentType<HTMLAttributes<T>>) =>
ComponentType<{values?: Record<string, any>} & HTMLAttributes<T>>;
type Type = <T extends object>(messageKey: string, Component: ComponentType<HTMLAttributes<T>>) =>
ComponentType<{values?: Record<string, Date | string | number | null>} & HTMLAttributes<T>>;

// tslint:disable-next-line:variable-name
export const htmlMessage: Type = (messageKey, Component) => ({values, ...props}) =>
Expand Down
3 changes: 2 additions & 1 deletion src/app/content/components/Assigned.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ const StyledButton = styled(Button)`
`;

// Override layout for Toast
const assignedMobileTop = (props: any) => getMobileSearchFailureTop(props) - bookBannerMobileMiniHeight;
const assignedMobileTop = (props: {mobileToolbarOpen: boolean}) =>
getMobileSearchFailureTop(props) - bookBannerMobileMiniHeight;
// tslint:disable-next-line: variable-name
const ToastOverride = styled(PageToasts)`
top: ${topbarDesktopHeight}rem;
Expand Down
2 changes: 1 addition & 1 deletion src/app/content/components/AssignedTopBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const useTextResizeIntegration = (handleChange: (value: TextResizerValue) => voi
const win = window;
const referrer = new URL(win.document.referrer);

const handler = (event: MessageEvent<any>) => {
const handler = (event: MessageEvent) => {
if (
event.data.type === 'TextSizeUpdate' &&
event.origin === referrer.origin &&
Expand Down
2 changes: 2 additions & 0 deletions src/app/content/components/Content.browserspec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ beforeAll(async() => {
});

describe('Content', () => {
const page = global.page;

for (const testCase of Object.keys(TEST_CASES)) {
describe(testCase, () => {
beforeEach(async() => {
Expand Down
2 changes: 1 addition & 1 deletion src/app/content/components/Page/connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export interface PagePropTypes {
systemQueryParams: SystemQueryParams;
textSize: TextResizerValue;
lockNavigation: boolean;
ToastOverride: StyledComponent<'div', any, {}, never>;
ToastOverride: StyledComponent<'div', object, {}, never>;
topHeadingLevel?: number;
}

Expand Down
3 changes: 2 additions & 1 deletion src/app/content/components/Topbar/TextResizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { FormattedMessage } from 'react-intl';
import decreaseTextSizeIcon from '../../../../assets/text-size-decrease.svg';
import increaseTextSizeIcon from '../../../../assets/text-size-increase.svg';
import textSizeIcon from '../../../../assets/text-size.svg';
import { HTMLInputElement } from '@openstax/types/lib.dom';
import {
textResizerDefaultValue,
textResizerMaxValue,
Expand All @@ -23,7 +24,7 @@ export interface TextResizerProps {
// tslint:disable-next-line:variable-name
export const TextResizer = (props: TextResizerProps) => {
const onChangeTextSize = (e: React.FormEvent<HTMLInputElement>) => {
const target = (e as any).currentTarget;
const target = e.currentTarget;
const value = parseInt(target.value, 10) as TextResizerValue;
if (!textResizerValues.includes(value)) { return; }
props.setTextSize(value);
Expand Down
6 changes: 4 additions & 2 deletions src/app/content/components/Topbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ interface Props {
bookTheme: string;
textSize: TextResizerValue | null;
setTextSize: (size: TextResizerValue) => void;
selectedResult: any;
selectedResult: unknown;
}

type CommonSearchInputParams = Pick<
Expand Down Expand Up @@ -217,7 +217,9 @@ function AltSCycler({hasSearchResults}: {hasSearchResults: boolean}) {
].map((q) => document?.querySelector<HTMLElement>(q));

// Determine which region we are in (if any)
const currentSectionIndex = targets.findIndex((el) => el?.contains(document?.activeElement!));
const currentSectionIndex = targets.findIndex((el) =>
document?.activeElement && el?.contains(document.activeElement)
);

// If not in any, go to search input
if (currentSectionIndex < 0) {
Expand Down
2 changes: 1 addition & 1 deletion src/app/content/components/popUp/ChapterFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const ChapterTitle = styled.span`
}
`;

const chunk = <T extends any>(sections: T[]) => {
const chunk = <T extends unknown>(sections: T[]) => {
const cutoff = Math.max(20, Math.ceil(sections.length / 2));
return [sections.slice(0, cutoff), sections.slice(cutoff)].filter((arr) => arr.length > 0);
};
Expand Down
8 changes: 4 additions & 4 deletions src/app/content/content.prerenderspec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ describe('content', () => {
await navigate(page, TEST_PAGE_WITHOUT_MATH);

const pendingEvents = await page.evaluate(() =>
window!.__APP_ANALYTICS.googleAnalyticsClient.getPendingCommands()
window?.__APP_ANALYTICS.googleAnalyticsClient.getPendingCommands()
);

expect(pendingEvents).toContainEqual({
Expand All @@ -132,18 +132,18 @@ describe('content', () => {
await navigate(page, TEST_PAGE_WITHOUT_MATH);

const initialEvents = await page.evaluate(() =>
window!.__APP_ANALYTICS.googleAnalyticsClient.getPendingCommands()
window?.__APP_ANALYTICS.googleAnalyticsClient.getPendingCommands()
);

await page.click('a[data-analytics-label="next"]');
await finishRender(page);

const pendingEvents = await page.evaluate(() =>
window!.__APP_ANALYTICS.googleAnalyticsClient.getPendingCommands()
window?.__APP_ANALYTICS.googleAnalyticsClient.getPendingCommands()
);

const newEvents = pendingEvents.filter(
(event: any) => !initialEvents.find(equals(event))
(event: Event) => !initialEvents.find(equals(event))
);

expect(newEvents).toMatchObject([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import Highlights from './Highlights';
import HighlightsToasts from './HighlightsToasts';
import * as Styled from './ShowMyHighlightsStyles';
import Filters from './SummaryPopup/Filters';
import { ServiceConsumer } from '../../../context/Services';

interface ShowMyHighlightsProps {
authenticated: User | undefined;
Expand Down Expand Up @@ -119,4 +120,5 @@ const connector = connect(
})
);

export default flow(withServices, connector)(ShowMyHighlights as React.ComponentType<any>);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default flow(withServices, connector)(ShowMyHighlights as unknown as React.ComponentType<ServiceConsumer>);
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ const HighlightListElement = ({ highlight, locationFilterId, pageId }: Highlight
}
</HighlightContentWrapper>
{isDeleting && <HighlightDeleteWrapper
deletingWhat={Boolean(highlight.annotation) ? 'both' : 'highlight'}
deletingWhat={highlight.annotation ? 'both' : 'highlight'}
onCancel={() => setIsDeleting(false)}
onDelete={confirmDelete}
/>}
Expand Down
5 changes: 3 additions & 2 deletions src/app/content/highlights/components/cardUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,11 @@ const updateStackedCardsPositions = (
const marginToAdd = index > 0 || addAditionalMarginForTheFirstCard ? remsToPx(cardMarginBottom) : 0;
const lastVisibleCardBottom = lastVisibleCardPosition + lastVisibleCardHeight;
const stackedTopOffset = Math.max(topOffset, lastVisibleCardBottom + marginToAdd);
const heightsForId = heights.get(highlight.id);

if (heights.get(highlight.id) && !checkIfHiddenByCollapsedAncestor(highlight)) {
if (heightsForId && !checkIfHiddenByCollapsedAncestor(highlight)) {
lastVisibleCardPosition = stackedTopOffset;
lastVisibleCardHeight = heights.get(highlight.id)!;
lastVisibleCardHeight = heightsForId;
}

positions.set(highlight.id, stackedTopOffset);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ export const useOnClickOutside = (

export default onClickOutside;

const isRefWithHtmlElement = (el: any): el is React.RefObject<HTMLElement> => {
const isRefWithHtmlElement = (el: {current?: unknown}): el is React.RefObject<HTMLElement> => {
return el instanceof Object && isHtmlElement(el.current);
};

export const isElementForOnClickOutside = (el: any): el is HTMLElement | React.RefObject<HTMLElement> => {
export const isElementForOnClickOutside = (el: object): el is HTMLElement | React.RefObject<HTMLElement> => {
return isHtmlElement(el) || isRefWithHtmlElement(el);
};
10 changes: 8 additions & 2 deletions src/app/content/highlights/utils/selectorsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ export const getLoadedCountsPerSource = (sources: SummaryHighlights | null) => f
mapValues(size)
)(sources);

export const checkIfHasMoreResults = (loaded: any, filteredCounts: any, pagination: SummaryHighlightsPagination) => {
return !!(pagination || Object.keys(omit(Object.keys(loaded), filteredCounts)).length);
export const checkIfHasMoreResults = (
loaded: object,
filteredCounts: object,
pagination: SummaryHighlightsPagination
) => {
return !!(
pagination || Object.keys(omit(Object.keys(loaded), filteredCounts)).length
);
};
8 changes: 6 additions & 2 deletions src/app/content/highlights/utils/summaryHighlightsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,16 @@ export const removeFromTotalCounts = (
totalCounts: CountsPerSource,
highlight: HighlightData
) => {
if (totalCounts[highlight.sourceId] && totalCounts[highlight.sourceId][highlight.color]) {
// Type issue: totalCounts does not allow members to be undefined,
// but in practice they are
const tc = totalCounts[highlight.sourceId]?.[highlight.color];

if (tc) {
const newTotal = {
...totalCounts,
[highlight.sourceId]: {
...totalCounts[highlight.sourceId],
[highlight.color]: totalCounts[highlight.sourceId][highlight.color]! - 1,
[highlight.color]: tc - 1,
},
};

Expand Down
3 changes: 2 additions & 1 deletion src/app/content/hooks/registerPageView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import googleAnalyticsClient from '../../../gateways/googleAnalyticsClient';
import * as selectNavigation from '../../navigation/selectors';
import { AnyRoute, RouteHookBody } from '../../navigation/types';
import { AppServices, MiddlewareAPI } from '../../types';
import { OutputParams } from 'query-string';

export const hookBody: RouteHookBody<AnyRoute> = (services: MiddlewareAPI & AppServices) => {
let lastTrackedLocation: any;
let lastTrackedLocation: { query: OutputParams; pathname: string; };

return async(action) => {
const state = services.getState();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import * as ksSelectors from '../selectors';
import ShowKeyboardShortcuts from './ShowKeyboardShortcuts';

// tslint:disable-next-line:variable-name
const StyledModal = styled<any /* there is a bug in the styled-components types when using forwardRef */>(Modal)`
const StyledModal = styled(Modal)`
max-width: 92.8rem;
`;

Expand Down
4 changes: 3 additions & 1 deletion src/app/content/launchToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ export const decodeToken = (launchToken: string | undefined) => {
// and into their own claims of the token. during transition try to decode
// sub and apply it to the token data so it works either way.
Object.assign(token, JSON.parse(token.sub));
} catch (e) { } // tslint:disable-line
} catch (e) {
// let it go
}

return token;
};
Expand Down
3 changes: 2 additions & 1 deletion src/app/content/practiceQuestions/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const reducer: Reducer<State, AnyAction> = (state = initialState, action): State
return {...state, currentQuestionIndex: state.currentQuestionIndex === null ? 0 : state.currentQuestionIndex + 1};
case getType(actions.setQuestions):
return {...state, loading: false, questions: action.payload};
case getType(actions.setAnswer):
case getType(actions.setAnswer): {
const { questionId, answer } = action.payload;
return {
...state,
Expand All @@ -49,6 +49,7 @@ const reducer: Reducer<State, AnyAction> = (state = initialState, action): State
[questionId]: answer,
},
};
}
case getType(actions.finishQuestions):
return {...state, currentQuestionIndex: null};
default:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import theme from '../../../../theme';
import { assertDocument } from '../../../../utils';
import * as TopbarStyled from '../../../components/Topbar/styled';
import { ResultsSidebarProps } from './SearchResultsBarWrapper';
import { HTMLInputElement } from '@openstax/types/lib.dom';
import * as Styled from './styled';

interface State {
Expand Down Expand Up @@ -59,7 +60,7 @@ export class SidebarSearchInput extends Component<ResultsSidebarProps> {
public newButtonEnabled = !!this.props.searchButtonColor;

public onSearchChange = (e: React.FormEvent<HTMLInputElement>) => {
this.setState({ query: (e.currentTarget as any).value, formSubmitted: false });
this.setState({ query: (e.currentTarget as HTMLInputElement).value, formSubmitted: false });
};

public onSearchSubmit = (e: React.FormEvent) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ interface SectionContentPreviewProps extends React.ComponentProps<typeof Content
// tslint:disable-next-line:variable-name
export const SectionContentPreview = styled(
React.forwardRef<HTMLAnchorElement, SectionContentPreviewProps>(
({selectedResult, ...props}, ref) => <ContentLinkComponent {...props} ref={ref} />
({selectedResult, ...props}: {selectedResult: unknown}, ref) => <ContentLinkComponent {...props} ref={ref} />
)
)`
${labelStyle}
Expand Down
2 changes: 1 addition & 1 deletion src/app/content/studyGuides/hooks/openStudyGuides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const hookBody: ActionHookBody<typeof openStudyGuides> = (services) => as

if (loggedOutAndQueryMissingFirstChapter || (!notLoggedIn && defaultFilter)) {
services.dispatch(replace(match as AnyMatch, {
search: getQueryForParam(summaryFilters as any as Record<string, string[]>, query),
search: getQueryForParam(summaryFilters as unknown as Record<string, string[]>, query),
}));
} else {
const studyGuides = select.summaryStudyGuides(state);
Expand Down
2 changes: 1 addition & 1 deletion src/app/content/studyGuides/hooks/printStudyGuides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const asyncHelper = async(services: MiddlewareAPI & AppServices) => {

try {
response = await loadMore(services);
} catch (error: any) {
} catch (error: unknown) {
services.dispatch(toggleStudyGuidesSummaryLoading(false));
throw ensureApplicationErrorType(error, new StudyGuidesPopupPrintError({ destination: 'studyGuides' }));
}
Expand Down
Loading
Loading