use parens for arrow funcs always

This commit is contained in:
Pavel Mineev
2021-01-29 03:17:10 -06:00
committed by Umputun
parent be2f6d0a20
commit e1e8da4b2a
40 changed files with 121 additions and 126 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
const getPresetEnv = options => ['@babel/preset-env', options];
const getPresetEnv = (options) => ['@babel/preset-env', options];
const preactPreset = [
'@babel/preset-react',
{
-1
View File
@@ -6,7 +6,6 @@ module.exports = {
singleQuote: true,
trailingComma: 'es5',
bracketSpacing: true,
arrowParens: 'avoid',
overrides: [
{
files: ['*.html'],
+2 -2
View File
@@ -53,7 +53,7 @@ export const logIn = (provider: AuthProvider): Promise<User | null> => {
clearInterval(checkInterval);
getUser()
.then(user => {
.then((user) => {
resolve(user);
})
.catch(() => {
@@ -263,7 +263,7 @@ export const uploadImage = (image: File): Promise<Image> => {
contentType: 'multipart/form-data',
body: data,
})
.then(resp => ({
.then((resp) => ({
name: image.name,
size: image.size,
type: image.type,
+6 -6
View File
@@ -17,10 +17,10 @@ describe('fetcher', () => {
return fetcher
.get('/api/some')
.then(data => {
.then((data) => {
throw new Error('Request should be failed');
})
.catch(e => {
.catch((e) => {
expect(e.code).toBe(2);
expect(e.error).toBe('you just cant');
expect(e.details).toBe('you just cant at all');
@@ -39,10 +39,10 @@ describe('fetcher', () => {
return fetcher
.get('/api/some')
.then(data => {
.then((data) => {
throw new Error('Request should be failed');
})
.catch(e => {
.catch((e) => {
expect(e.code).toBe(401);
expect(e.error).toBe('Not authorized.');
});
@@ -61,10 +61,10 @@ describe('fetcher', () => {
return fetcher
.get({ url: '/api/some', logError: false })
.then(data => {
.then((data) => {
throw new Error('Request should be failed');
})
.catch(e => {
.catch((e) => {
expect(e.code).toBe(0);
expect(e.error).toBe('Something went wrong.');
});
+3 -3
View File
@@ -83,7 +83,7 @@ const fetcher = methods.reduce<Partial<FetcherObject>>((acc, method) => {
}
return fetch(rurl, parameters)
.then(res => {
.then((res) => {
const date = (res.headers.has('date') && res.headers.get('date')) || '';
const timestamp = isNaN(Date.parse(date)) ? 0 : Date.parse(date);
const timeDiff = (new Date().getTime() - timestamp) / 1000;
@@ -104,7 +104,7 @@ const fetcher = methods.reduce<Partial<FetcherObject>>((acc, method) => {
throw new RequestError(descriptor.defaultMessage, res.status);
}
return res.text().then(text => {
return res.text().then((text) => {
let err;
try {
err = JSON.parse(text);
@@ -125,7 +125,7 @@ const fetcher = methods.reduce<Partial<FetcherObject>>((acc, method) => {
return res.text();
})
.catch(e => {
.catch((e) => {
if (isFailedFetch(e)) {
throw new RequestError(e.message, -2);
}
@@ -193,7 +193,7 @@ export class AuthPanel extends Component<Props, State> {
<FormattedMessage id="commentSort.sort-by" defaultMessage="Sort by" />{' '}
<span className="auth-panel__select-label">
<span className={b('auth-panel__select-label-value', {}, { focused: sortSelectFocused })}>
{sortArray.find(x => 'selected' in x && x.selected!)!.label}
{sortArray.find((x) => 'selected' in x && x.selected!)!.label}
</span>
<select
className="auth-panel__select"
@@ -201,7 +201,7 @@ export class AuthPanel extends Component<Props, State> {
onFocus={this.onSortFocus}
onBlur={this.onSortBlur}
>
{sortArray.map(sort => (
{sortArray.map((sort) => (
<option value={sort.value} selected={sort.selected}>
{sort.label}
</option>
@@ -315,7 +315,7 @@ function getSortArray(currentSort: Sorting, intl: IntlShape) {
},
];
return sortArray.map(sort => {
return sortArray.map((sort) => {
if (sort.value === currentSort) {
sort.selected = true;
}
@@ -327,8 +327,8 @@ function getSortArray(currentSort: Sorting, intl: IntlShape) {
export default function AuthPanelConnected(props: OwnProps) {
const intl = useIntl();
const theme = useTheme();
const provider = useSelector<StoreState, ProviderState>(state => state.provider);
const sort = useSelector<StoreState, Sorting>(state => state.comments.sort);
const provider = useSelector<StoreState, ProviderState>((state) => state.provider);
const sort = useSelector<StoreState, Sorting>((state) => state.comments.sort);
return (
<AuthPanel
+3 -3
View File
@@ -78,7 +78,7 @@ class Auth extends Component<Props, State> {
return (
<Dropdown title={other} theme={this.props.theme} onTitleClick={this.onEmailTitleClick}>
{providers.map(provider => (
{providers.map((provider) => (
<DropdownItem>{this.renderProvider(provider)}</DropdownItem>
))}
</Dropdown>
@@ -187,8 +187,8 @@ const authPanelMessages = defineMessages({
export default function AuthWrapper() {
const dispatch = useDispatch();
const provider = useSelector<StoreState, ProviderState>(store => store.provider);
const user = useSelector<StoreState, User | null>(store => store.user);
const provider = useSelector<StoreState, ProviderState>((store) => store.provider);
const user = useSelector<StoreState, User | null>((store) => store.user);
const theme = useTheme();
const intl = useIntl();
const handleSignin = useCallback((provider: AuthProvider) => dispatch(logIn(provider)), [dispatch]);
@@ -4,7 +4,7 @@ import { shallow } from 'enzyme';
import { SubscribeByRSS, createSubscribeUrl } from '.';
jest.mock('react-redux', () => ({
useSelector: jest.fn(fn => fn({ theme: 'light' })),
useSelector: jest.fn((fn) => fn({ theme: 'light' })),
}));
jest.mock('react-intl', () => {
@@ -214,7 +214,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
this.setState({ isDisabled: true, isErrorShown: false, text });
try {
await this.props.onSubmit(text, pageTitle || document.title);
updateJsonItem<Record<string, string>>(LS_SAVED_COMMENT_VALUE, data => {
updateJsonItem<Record<string, string>>(LS_SAVED_COMMENT_VALUE, (data) => {
delete data[this.props.id];
return data;
@@ -239,7 +239,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
this.props
.getPreview(text)
.then(preview => this.setState({ preview }))
.then((preview) => this.setState({ preview }))
.catch(() => {
this.setState({ isErrorShown: true, errorMessage: null });
});
@@ -267,7 +267,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
if (!this.textAreaRef) return;
if (!e.dataTransfer) return;
const items = Array.from(e.dataTransfer.items);
if (Array.from(items).filter(i => i.kind === 'file' && ImageMimeRegex.test(i.type)).length === 0) return;
if (Array.from(items).filter((i) => i.kind === 'file' && ImageMimeRegex.test(i.type)).length === 0) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
}
@@ -287,7 +287,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
if (StaticStore.config.max_image_size === 0) return;
if (!e.dataTransfer) return;
const data = Array.from(e.dataTransfer.files).filter(f => ImageMimeRegex.test(f.type));
const data = Array.from(e.dataTransfer.files).filter((f) => ImageMimeRegex.test(f.type));
if (data.length === 0) return;
e.preventDefault();
@@ -497,7 +497,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
</div>
{(isErrorShown || !!errorMessage) &&
(errorMessage || intl.formatMessage(messages.unexpectedError)).split('\n').map(e => (
(errorMessage || intl.formatMessage(messages.unexpectedError)).split('\n').map((e) => (
<p className="comment-form__error" role="alert" key={e}>
{e}
</p>
@@ -34,7 +34,7 @@ function SuggestionList({ items, theme }: { items: Array<Emoji>; theme: Theme })
function searchEmoji(key: string, text: string, theme: Theme) {
return import(/* webpackChunkName: "node-emoji" */ `node-emoji`)
.then(nodeEmoji => {
.then((nodeEmoji) => {
if (key === ':') {
const emojiList = nodeEmoji.search(text);
if (emojiList.length === 0) {
@@ -58,7 +58,7 @@ describe('<Comment />', () => {
expect(voteButtons.length).toEqual(2);
voteButtons.forEach(button => {
voteButtons.forEach((button) => {
expect(button.prop('aria-disabled')).toEqual('true');
expect(button.prop('title')).toEqual("Anonymous users can't vote");
});
@@ -73,7 +73,7 @@ describe('<Comment />', () => {
expect(voteButtons.length).toEqual(2);
voteButtons.forEach(button => {
voteButtons.forEach((button) => {
expect(button.prop('aria-disabled')).toEqual('false');
});
});
@@ -84,7 +84,7 @@ describe('<Comment />', () => {
const voteButtons = element.find('.comment__vote');
expect(voteButtons.length).toStrictEqual(2);
voteButtons.forEach(b => {
voteButtons.forEach((b) => {
expect(b.getDOMNode().getAttribute('aria-disabled')).toStrictEqual('true');
expect(b.getDOMNode().getAttribute('title')).toStrictEqual("Voting allowed only on post's page");
});
@@ -100,7 +100,7 @@ describe('<Comment />', () => {
const voteButtons = element.find('.comment__vote');
expect(voteButtons.length).toStrictEqual(2);
voteButtons.forEach(b => {
voteButtons.forEach((b) => {
expect(b.getDOMNode().getAttribute('aria-disabled')).toStrictEqual('true');
expect(b.getDOMNode().getAttribute('title')).toStrictEqual("Can't vote on read-only topics");
});
@@ -115,7 +115,7 @@ describe('<Comment />', () => {
const voteButtons = element.find('.comment__vote');
expect(voteButtons.length).toStrictEqual(2);
voteButtons.forEach(b => {
voteButtons.forEach((b) => {
expect(b.getDOMNode().getAttribute('aria-disabled')).toStrictEqual('true');
expect(b.getDOMNode().getAttribute('title')).toStrictEqual("Can't vote for deleted comment");
});
@@ -137,7 +137,7 @@ describe('<Comment />', () => {
const voteButtons = element.find('.comment__vote');
expect(voteButtons.length).toStrictEqual(2);
voteButtons.forEach(b => {
voteButtons.forEach((b) => {
expect(b.getDOMNode().getAttribute('aria-disabled')).toStrictEqual('true');
expect(b.getDOMNode().getAttribute('title')).toStrictEqual("Can't vote for your own comment");
});
@@ -149,7 +149,7 @@ describe('<Comment />', () => {
const voteButtons = element.find('.comment__vote');
expect(voteButtons.length).toStrictEqual(2);
voteButtons.forEach(b => {
voteButtons.forEach((b) => {
expect(b.getDOMNode().getAttribute('aria-disabled')).toStrictEqual('true');
expect(b.getDOMNode().getAttribute('title')).toStrictEqual('Sign in to vote');
});
+5 -5
View File
@@ -257,7 +257,7 @@ class Comment extends Component<CommentProps, State> {
blockUser = debounce((ttl: BlockTTL): void => {
const { user } = this.props.data;
const blockingDurations = getBlockingDurations(this.props.intl);
const blockDuration = blockingDurations.find(el => el.value === ttl);
const blockDuration = blockingDurations.find((el) => el.value === ttl);
// blocking duration may be undefined if user hasn't selected anything
// and ttl equals "Blocking period"
if (!blockDuration) return;
@@ -310,7 +310,7 @@ class Comment extends Component<CommentProps, State> {
sendVotingRequest = (votingValue: number, originalScore: number, originalDelta: number) => {
this.votingPromise = this.votingPromise
.then(() => this.props.putCommentVote!(this.props.data.id, votingValue))
.catch(e => this.handleVoteError(e, originalScore, originalDelta));
.catch((e) => this.handleVoteError(e, originalScore, originalDelta));
};
increaseScore = () => {
@@ -506,7 +506,7 @@ class Comment extends Component<CommentProps, State> {
<option disabled selected value={undefined}>
<FormattedMessage id="comment.blocking-period" defaultMessage="Blocking period" />
</option>
{blockingDurations.map(block => (
{blockingDurations.map((block) => (
<option value={block.value}>{block.label}</option>
))}
</select>
@@ -562,7 +562,7 @@ class Comment extends Component<CommentProps, State> {
time: new Date(props.data.time),
orig: isEditing
? props.data.orig &&
props.data.orig.replace(/&[#A-Za-z0-9]+;/gi, entity => {
props.data.orig.replace(/&[#A-Za-z0-9]+;/gi, (entity) => {
const span = document.createElement('span');
span.innerHTML = entity;
return span.innerText;
@@ -702,7 +702,7 @@ class Comment extends Component<CommentProps, State> {
href={`${o.locator.url}#${COMMENT_NODE_CLASSNAME_PREFIX}${o.pid}`}
aria-label={goToParentMessage}
title={goToParentMessage}
onClick={e => this.scrollToParent(e)}
onClick={(e) => this.scrollToParent(e)}
>
{' '}
</a>
@@ -40,7 +40,7 @@ const mapStateToProps = (state: StoreState, cprops: { data: CommentType }) => {
const props: ProvidedProps = {
editMode: getCommentMode(cprops.data.id)(state),
user: state.user,
isUserBanned: cprops.data.user.block || state.bannedUsers.find(u => u.id === cprops.data.user.id) !== undefined,
isUserBanned: cprops.data.user.block || state.bannedUsers.find((u) => u.id === cprops.data.user.id) !== undefined,
post_info: state.info,
isCommentsDisabled: state.info.read_only || false,
theme: state.theme,
@@ -64,9 +64,9 @@ export const boundActions = bindActions({
setVerifiedStatus,
});
export const ConnectedComment: FunctionComponent<
Omit<CommentProps, keyof (ProvidedProps & typeof bindActions)>
> = props => {
export const ConnectedComment: FunctionComponent<Omit<CommentProps, keyof (ProvidedProps & typeof bindActions)>> = (
props
) => {
const providedProps = mapStateToProps(useStore().getState(), props);
const actions = useActions(boundActions);
const intl = useIntl();
@@ -91,7 +91,7 @@ export class Dropdown extends Component<Props, State> {
const windowHeight = window.innerHeight;
const dcBottom = (() => {
// TODO: use ref
const dc = Array.from(this.rootNode.current.children).find(c => c.classList.contains('dropdown__content'));
const dc = Array.from(this.rootNode.current.children).find((c) => c.classList.contains('dropdown__content'));
if (!dc) return 0;
const rect = dc.getBoundingClientRect();
return window.scrollY + Math.abs(rect.top) + dc.scrollHeight + 10;
@@ -16,7 +16,7 @@ const ListComments: FunctionComponent<ListCommentsProps> = ({ comments = [] }) =
return (
<div className={classnames('comments-list', styles.root)}>
{comments.map(comment => (
{comments.map((comment) => (
<Comment
intl={intl}
key={comment.id}
@@ -10,8 +10,8 @@ function getObserver(): { observer: IntersectionObserver; instanceMap: WeakMap<E
}
instanceMap = new WeakMap<Element, (inView: boolean) => void>();
observer = new window.IntersectionObserver(
entries => {
entries.forEach(e => {
(entries) => {
entries.forEach((e) => {
const setInView = instanceMap.get(e.target);
if (!setInView) return;
setInView(e.isIntersecting);
+5 -5
View File
@@ -49,14 +49,14 @@ const mapStateToProps = (state: StoreState) => ({
user: state.user,
childToParentComments: Object.entries(state.comments.childComments).reduce(
(accumulator: Record<string, string>, [key, children]) => {
children.forEach(child => (accumulator[child] = key));
children.forEach((child) => (accumulator[child] = key));
return accumulator;
},
{}
),
collapsedThreads: state.collapsedThreads,
topComments: state.comments.topComments,
pinnedComments: state.comments.pinnedComments.map(id => state.comments.allComments[id]).filter(c => !c.hidden),
pinnedComments: state.comments.pinnedComments.map((id) => state.comments.allComments[id]).filter((c) => !c.hidden),
theme: state.theme,
info: state.info,
hiddenUsers: state.hiddenUsers,
@@ -166,7 +166,7 @@ export class Root extends Component<Props, State> {
if (!document.querySelector(hash)) {
const ids = getCollapsedParents(hash, this.props.childToParentComments, this.props.collapsedThreads);
ids.forEach(id => this.props.setCollapse(id, false));
ids.forEach((id) => this.props.setCollapse(id, false));
}
setTimeout(() => {
@@ -284,7 +284,7 @@ export class Root extends Component<Props, State> {
role="region"
aria-label={this.props.intl.formatMessage(messages.pinnedComments)}
>
{this.props.pinnedComments.map(comment => (
{this.props.pinnedComments.map((comment) => (
<Comment
CommentForm={CommentForm}
intl={this.props.intl}
@@ -304,7 +304,7 @@ export class Root extends Component<Props, State> {
{(IS_MOBILE && commentsShown < this.props.topComments.length
? this.props.topComments.slice(0, commentsShown)
: this.props.topComments
).map(id => (
).map((id) => (
<Thread
key={`thread-${id}`}
id={id}
@@ -64,7 +64,7 @@ export default class Settings extends Component<Props, State> {
block = (user: BlockedUser) => {
if (!window.confirm(this.props.intl.formatMessage(messages.blockUser, { userName: user.name }))) return;
this.setState({
unblockedUsers: this.state.unblockedUsers.filter(x => x !== user.id),
unblockedUsers: this.state.unblockedUsers.filter((x) => x !== user.id),
});
this.props.blockUser(user.id, user.name, 'permanently');
};
@@ -78,7 +78,7 @@ export default class Settings extends Component<Props, State> {
hide = (user: User) => {
this.setState({
unhiddenUsers: this.state.unhiddenUsers.filter(x => x !== user.id),
unhiddenUsers: this.state.unhiddenUsers.filter((x) => x !== user.id),
});
this.props.hideUser(user);
};
@@ -114,7 +114,7 @@ export default class Settings extends Component<Props, State> {
)}
{!!hiddenUsersList.length && (
<ul className="settings__list">
{hiddenUsersList.map(user => {
{hiddenUsersList.map((user) => {
const isUserUnhidden = unhiddenUsers.includes(user.id);
return (
@@ -163,7 +163,7 @@ export default class Settings extends Component<Props, State> {
{!!blockedUsers.length && (
<ul className="settings__list settings__blocked-users-list">
{blockedUsers.map(user => {
{blockedUsers.map((user) => {
const isUserUnblocked = unblockedUsers.includes(user.id);
return (
+2 -2
View File
@@ -52,7 +52,7 @@ export const Thread: FunctionComponent<Props> = ({ id, level, mix, getPreview })
aria-expanded={!collapsed}
>
<InView>
{inviewProps => (
{(inviewProps) => (
<Comment
CommentForm={CommentForm}
ref={inviewProps.ref}
@@ -70,7 +70,7 @@ export const Thread: FunctionComponent<Props> = ({ id, level, mix, getPreview })
{!collapsed &&
childs &&
!!childs.length &&
childs.map(currentId => (
childs.map((currentId) => (
<Thread key={`thread-${currentId}`} id={currentId} level={Math.min(level + 1, 6)} getPreview={getPreview} />
))}
{level < 6 && (
@@ -15,7 +15,7 @@ const LastCommentsList = ({ comments, isLoading }: { comments: CommentType[]; is
return (
<>
{comments.map(comment => (
{comments.map((comment) => (
<Comment
CommentForm={null}
intl={intl}
+1 -1
View File
@@ -9,7 +9,7 @@ const themeSelector = (state: StoreState) => state.theme;
* Connects redux theme property to component's
*/
function withTheme<P extends { theme: Theme }>(PlainComponent: ComponentType<P>) {
const C: FunctionComponent<Omit<P, 'theme'>> = props => {
const C: FunctionComponent<Omit<P, 'theme'>> = (props) => {
const theme = useSelector(themeSelector);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return <PlainComponent theme={theme} {...(props as any)} />;
+1 -1
View File
@@ -33,7 +33,7 @@ function init(): void {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
try {
const res = JSON.parse(this.responseText) as { url: string; count: number }[];
res.forEach(item => map[item.url].map(n => (n.innerHTML = item.count.toString(10))));
res.forEach((item) => map[item.url].map((n) => (n.innerHTML = item.count.toString(10))));
} catch (e) {}
}
};
+2 -2
View File
@@ -20,14 +20,14 @@ async function init(): Promise<void> {
return;
}
getUser().then(user => {
getUser().then((user) => {
if (!user || !user.admin) {
handleNotAuthorizedError(node);
return;
}
approveDeleteMe(token).then(
data => {
(data) => {
node.innerHTML = `
<h3>User deleted successfully</h3>
<pre>${JSON.stringify(data, null, 4)}</pre>
+6 -6
View File
@@ -76,9 +76,9 @@ function createInstance(config: typeof window.remark_config) {
config.url = (config.url || `${window.location.origin}${window.location.pathname}`).split('#')[0];
const query = Object.keys(config)
.filter(key => key !== '__colors__')
.filter((key) => key !== '__colors__')
.map(
key =>
(key) =>
`${encodeURIComponent(key)}=${encodeURIComponent(
config[key as keyof Omit<typeof window.remark_config, '__colors__'>] as string | number | boolean
)}`
@@ -97,7 +97,7 @@ function createInstance(config: typeof window.remark_config) {
const titleElement = document.querySelector('title');
if (titleElement) {
titleObserver = new MutationObserver(mutations => postTitleToIframe(mutations[0].target.textContent!));
titleObserver = new MutationObserver((mutations) => postTitleToIframe(mutations[0].target.textContent!));
titleObserver.observe(titleElement, {
subtree: true,
characterData: true,
@@ -228,14 +228,14 @@ function createInstance(config: typeof window.remark_config) {
document.removeEventListener('keydown', this.onKeyDown);
},
delay: null,
events: ['', 'webkit', 'moz', 'MS', 'o'].map(prefix => (prefix ? `${prefix}TransitionEnd` : 'transitionend')),
events: ['', 'webkit', 'moz', 'MS', 'o'].map((prefix) => (prefix ? `${prefix}TransitionEnd` : 'transitionend')),
onAnimationClose() {
const el = this.node!;
if (!this.node) {
return;
}
this.delay = window.setTimeout(this.animationStop, 1000);
this.events.forEach(event => el.addEventListener(event, this.animationStop, false));
this.events.forEach((event) => el.addEventListener(event, this.animationStop, false));
},
onKeyDown(e) {
// ESCAPE key pressed
@@ -252,7 +252,7 @@ function createInstance(config: typeof window.remark_config) {
clearTimeout(t.delay);
t.delay = null;
}
t.events.forEach(event => t.node!.removeEventListener(event, t.animationStop, false));
t.events.forEach((event) => t.node!.removeEventListener(event, t.animationStop, false));
return t.remove();
},
remove() {
+1 -1
View File
@@ -35,7 +35,7 @@ async function init(): Promise<void> {
throw new Error('Remark42: Site ID is undefined.');
}
(Array.from(nodes) as HTMLElement[]).forEach(node => {
(Array.from(nodes) as HTMLElement[]).forEach((node) => {
const max = (node.dataset.max && parseInt(node.dataset.max, 10)) || max_last_comments || DEFAULT_LAST_COMMENTS_MAX;
const locale = getLocale(window.remark_config);
+8 -10
View File
@@ -18,7 +18,7 @@ import { setItem } from 'common/local-storage';
import { LS_SORT_KEY } from 'common/constants';
/** sets comments, and put pinned comments in cache */
export const setComments = (comments: Node[]): StoreAction<void> => dispatch => {
export const setComments = (comments: Node[]): StoreAction<void> => (dispatch) => {
dispatch({
type: COMMENTS_SET,
comments,
@@ -26,23 +26,21 @@ export const setComments = (comments: Node[]): StoreAction<void> => dispatch =>
};
/** appends comment to tree */
export const addComment = (
text: string,
title: string,
pid?: Comment['id']
): StoreAction<Promise<void>> => async dispatch => {
export const addComment = (text: string, title: string, pid?: Comment['id']): StoreAction<Promise<void>> => async (
dispatch
) => {
const comment = await api.addComment({ text, title, pid });
dispatch({ type: COMMENTS_APPEND, pid: pid || null, comment });
};
/** edits comment in tree */
export const updateComment = (id: Comment['id'], text: string): StoreAction<Promise<void>> => async dispatch => {
export const updateComment = (id: Comment['id'], text: string): StoreAction<Promise<void>> => async (dispatch) => {
const comment = await api.updateComment({ id, text });
dispatch({ type: COMMENTS_EDIT, comment });
};
/** edits comment in tree */
export const putVote = (id: Comment['id'], value: number): StoreAction<Promise<void>> => async dispatch => {
export const putVote = (id: Comment['id'], value: number): StoreAction<Promise<void>> => async (dispatch) => {
await api.putCommentVote({ id, value });
const comment = await api.getComment(id);
dispatch({ type: COMMENTS_EDIT, comment });
@@ -85,7 +83,7 @@ export const fetchComments = (sort?: Sorting): StoreAction<Promise<Tree>> => asy
const data = await api.getPostComments(sort || comments.sort);
dispatch({ type: COMMENTS_REQUEST_SUCCESS });
if (hiddenUsersIds.length > 0) {
data.comments = filterTree(data.comments, node => hiddenUsersIds.indexOf(node.comment.user.id) === -1);
data.comments = filterTree(data.comments, (node) => hiddenUsersIds.indexOf(node.comment.user.id) === -1);
}
dispatch(setComments(data.comments));
@@ -95,7 +93,7 @@ export const fetchComments = (sort?: Sorting): StoreAction<Promise<Tree>> => asy
};
/** sets mode for comment, either reply or edit */
export const setCommentMode = (mode: StoreState['comments']['activeComment']): StoreAction<void> => dispatch => {
export const setCommentMode = (mode: StoreState['comments']['activeComment']): StoreAction<void> => (dispatch) => {
if (mode !== null && mode.state === CommentMode.None) {
mode = null;
}
+3 -3
View File
@@ -30,7 +30,7 @@ export const topComments = (
case COMMENTS_SET: {
return cmpRef(
state,
action.comments.map(x => x.comment.id)
action.comments.map((x) => x.comment.id)
);
}
case COMMENTS_APPEND: {
@@ -146,7 +146,7 @@ export const pinnedComments = (
): Comment['id'][] => {
switch (action.type) {
case COMMENTS_SET: {
return getPinnedComments(action.comments).map(x => x.id);
return getPinnedComments(action.comments).map((x) => x.id);
}
case COMMENTS_EDIT: {
const index = state.indexOf(action.comment.id);
@@ -162,7 +162,7 @@ export const pinnedComments = (
case COMMENTS_PATCH: {
if (!Object.prototype.hasOwnProperty.call(action.patch, 'pin')) return state;
if (!action.patch.pin) {
return state.filter(x => action.ids.indexOf(x) === -1);
return state.filter((x) => action.ids.indexOf(x) === -1);
}
return [...state, ...action.ids].reduce<Comment['id'][]>((c, x) => {
if (c.indexOf(x) === -1) {
+2 -2
View File
@@ -6,7 +6,7 @@ const PROVIDER_LOCALSTORAGE_KEY = '__remarkProvider';
/** saves last login provider from localstorage and put to store */
export function updateProvider(payload: PROVIDER_UPDATE_ACTION['payload']): StoreAction<void, PROVIDER_UPDATE_ACTION> {
return dispatch => {
return (dispatch) => {
setItem(PROVIDER_LOCALSTORAGE_KEY, JSON.stringify(payload));
dispatch({
type: PROVIDER_UPDATE,
@@ -17,7 +17,7 @@ export function updateProvider(payload: PROVIDER_UPDATE_ACTION['payload']): Stor
/** restores last login provider from localstorage and put to store */
export function restoreProvider(): StoreAction<void, PROVIDER_UPDATE_ACTION> {
return dispatch => {
return (dispatch) => {
const payloadString = getItem(PROVIDER_LOCALSTORAGE_KEY);
if (!payloadString) return;
try {
+1 -1
View File
@@ -3,7 +3,7 @@ import { Theme } from 'common/types';
import { StoreAction } from '../';
import { THEME_SET } from './types';
export const setTheme = (theme: Theme): StoreAction<void> => dispatch =>
export const setTheme = (theme: Theme): StoreAction<void> => (dispatch) =>
dispatch({
type: THEME_SET,
theme,
+2 -2
View File
@@ -23,8 +23,8 @@ export const getCollapsedComments = (): string[] =>
* @param info list of string of type "site-id_url_comment-id
*/
export const saveCollapsedComments = (siteId: string, url: string, info: Comment['id'][]): void => {
const data = info.map(i => `${siteId}_${url}_${i}`);
const notForThisPost = getFromLocalStorage().filter(entry => entry.indexOf(`${siteId}_${url}`) === -1);
const data = info.map((i) => `${siteId}_${url}_${i}`);
const notForThisPost = getFromLocalStorage().filter((entry) => entry.indexOf(`${siteId}_${url}`) === -1);
const all = new Set([...notForThisPost, ...data]);
localStorageSetItem(LS_COLLAPSE_KEY, JSON.stringify([...all]));
};
+1 -1
View File
@@ -5,7 +5,7 @@ import { userInfo } from 'common/user-info-settings';
import { StoreAction } from '../index';
import { USER_INFO_SET } from './types';
export const fetchInfo = (): StoreAction<Promise<Comment[] | null>> => async dispatch => {
export const fetchInfo = (): StoreAction<Promise<Comment[] | null>> => async (dispatch) => {
if (!userInfo.id) {
return null;
}
+14 -16
View File
@@ -28,13 +28,13 @@ function setUser(user: User | null = null): USER_SET_ACTION {
};
}
export const fetchUser = (): StoreAction<Promise<User | null>> => async dispatch => {
export const fetchUser = (): StoreAction<Promise<User | null>> => async (dispatch) => {
const user = await api.getUser();
dispatch(setUser(user));
return user;
};
export const logIn = (provider: AuthProvider): StoreAction<Promise<User | null>> => async dispatch => {
export const logIn = (provider: AuthProvider): StoreAction<Promise<User | null>> => async (dispatch) => {
const user = await api.logIn(provider);
dispatch(updateProvider({ name: provider.name }));
@@ -44,13 +44,13 @@ export const logIn = (provider: AuthProvider): StoreAction<Promise<User | null>>
return user;
};
export const logout = (): StoreAction<Promise<void>> => async dispatch => {
export const logout = (): StoreAction<Promise<void>> => async (dispatch) => {
await api.logOut();
dispatch(unsetCommentMode());
dispatch(setUser());
};
export const fetchBlockedUsers = (): StoreAction<Promise<BlockedUser[]>> => async dispatch => {
export const fetchBlockedUsers = (): StoreAction<Promise<BlockedUser[]>> => async (dispatch) => {
const list = (await api.getBlocked()) || [];
dispatch({ type: USER_BANLIST_SET, list });
@@ -58,11 +58,9 @@ export const fetchBlockedUsers = (): StoreAction<Promise<BlockedUser[]>> => asyn
return list;
};
export const blockUser = (
id: User['id'],
name: string,
ttl: BlockTTL
): StoreAction<Promise<void>> => async dispatch => {
export const blockUser = (id: User['id'], name: string, ttl: BlockTTL): StoreAction<Promise<void>> => async (
dispatch
) => {
await api.blockUser(id, ttl);
dispatch({
type: USER_BAN,
@@ -78,19 +76,19 @@ export const unblockUser = (id: User['id']): StoreAction<Promise<void>> => async
await api.unblockUser(id);
dispatch({ type: USER_UNBAN, id });
const comments = Object.values(getState().comments.allComments);
const userComments = comments.filter(comment => comment.user.id === id);
const userComments = comments.filter((comment) => comment.user.id === id);
if (!userComments.length) return;
const user = comments[0].user;
dispatch({
type: COMMENTS_PATCH,
ids: userComments.map(c => c.id),
ids: userComments.map((c) => c.id),
patch: { user: { ...user, block: false } },
});
};
export const fetchHiddenUsers = (): StoreAction<void> => dispatch => {
export const fetchHiddenUsers = (): StoreAction<void> => (dispatch) => {
const hiddenUsers = getHiddenUsers();
dispatch({ type: USER_HIDELIST_SET, payload: hiddenUsers });
@@ -103,8 +101,8 @@ export const hideUser = (user: User): StoreAction<void> => (dispatch, getState)
setItem(LS_HIDDEN_USERS_KEY, JSON.stringify(hiddenUsers));
const ids = Object.values(getState().comments.allComments)
.filter(c => c.user.id === user.id)
.map(c => c.id);
.filter((c) => c.user.id === user.id)
.map((c) => c.id);
dispatch({ type: USER_HIDE, user });
dispatch({ type: COMMENTS_PATCH, ids, patch: { hidden: true } });
@@ -133,14 +131,14 @@ export const setVerifiedStatus = (id: User['id'], status: boolean): StoreAction<
await api.removeVerifiedStatus(id);
}
const comments = Object.values(getState().comments.allComments);
const userComments = comments.filter(c => c.user.id === id);
const userComments = comments.filter((c) => c.user.id === id);
if (!userComments.length) return;
const user = userComments[0].user;
dispatch({
type: COMMENTS_PATCH,
ids: userComments.map(c => c.id),
ids: userComments.map((c) => c.id),
patch: { user: { ...user, verified: status } },
});
};
+2 -2
View File
@@ -38,13 +38,13 @@ export const bannedUsers = (state: BlockedUser[] = [], action: USER_ACTIONS): Bl
return action.list;
}
case USER_BAN: {
if (state.find(u => u.id === action.user.id) !== undefined) {
if (state.find((u) => u.id === action.user.id) !== undefined) {
return state;
}
return [action.user, ...state];
}
case USER_UNBAN: {
const index = state.findIndex(u => u.id === action.id);
const index = state.findIndex((u) => u.id === action.id);
if (index === -1) {
return state;
}
+1 -1
View File
@@ -4,7 +4,7 @@ export function parseJwt<T extends { exp: number; [key: string]: unknown }>(toke
const jsonPayload = decodeURIComponent(
atob(base64)
.split('')
.map(c => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`)
.map((c) => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`)
.join('')
);
+10 -10
View File
@@ -4,34 +4,34 @@ const enMessages = {};
export async function loadLocale(locale: string): Promise<Record<string, string>> {
if (locale === 'ru') {
return import(/* webpackChunkName: "ru" */ '../locales/ru.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "ru" */ '../locales/ru.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'de') {
return import(/* webpackChunkName: "de" */ '../locales/de.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "de" */ '../locales/de.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'fi') {
return import(/* webpackChunkName: "fi" */ '../locales/fi.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "fi" */ '../locales/fi.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'es') {
return import(/* webpackChunkName: "es" */ '../locales/es.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "es" */ '../locales/es.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'zh') {
return import(/* webpackChunkName: "zh" */ '../locales/zh.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "zh" */ '../locales/zh.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'tr') {
return import(/* webpackChunkName: "tr" */ '../locales/tr.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "tr" */ '../locales/tr.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'bg') {
return import(/* webpackChunkName: "bg" */ '../locales/bg.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "bg" */ '../locales/bg.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'ua') {
return import(/* webpackChunkName: "ua" */ '../locales/ua.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "ua" */ '../locales/ua.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'pl') {
return import(/* webpackChunkName: "pl" */ '../locales/pl.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "pl" */ '../locales/pl.json').then((res) => res.default).catch(() => enMessages);
}
if (locale === 'vi') {
return import(/* webpackChunkName: "vi" */ '../locales/vi.json').then(res => res.default).catch(() => enMessages);
return import(/* webpackChunkName: "vi" */ '../locales/vi.json').then((res) => res.default).catch(() => enMessages);
}
return enMessages;
+1 -1
View File
@@ -1,3 +1,3 @@
export function sleep(ms = 1000): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
return new Promise((resolve) => setTimeout(resolve, ms));
}
+2 -2
View File
@@ -5,10 +5,10 @@ const { keys } = require('./getTranslationKeys');
const errors = [];
locales.forEach(locale => {
locales.forEach((locale) => {
const dict = require(getLocalePath({ locale }));
const keysFromDict = Object.keys(dict);
keysFromDict.forEach(key => {
keysFromDict.forEach((key) => {
if (!keys.includes(key)) {
errors.push(
`"${key}" key not found in "${locale}" locale dict. Please run "npm run translation:generate" and commit changes.`
+2 -2
View File
@@ -19,7 +19,7 @@ function sortDict(dict) {
);
}
locales.forEach(locale => {
locales.forEach((locale) => {
let currentDict = {};
const pathToDict = getLocalePath({ locale });
if (fs.existsSync(pathToDict)) {
@@ -35,6 +35,6 @@ locales.forEach(locale => {
fs.writeFileSync(pathToDict, `${JSON.stringify(currentDict, null, 2)}\n`);
fs.writeFileSync(
path.resolve(__dirname, `../app/utils/loadLocale.ts`),
renderLoadLocale(locales.filter(locale => locale !== 'en'))
renderLoadLocale(locales.filter((locale) => locale !== 'en'))
);
});
+1 -1
View File
@@ -6,7 +6,7 @@ const enMessages = {};
export async function loadLocale(locale: string): Promise<Record<string, string>> {
${locales
.map(
locale => ` if (locale === '${locale}') {
(locale) => ` if (locale === '${locale}') {
return import(/* webpackChunkName: "${locale}" */ '../locales/${locale}.json').then((res) => res.default).catch(() => enMessages);
}
`
+1 -1
View File
@@ -32,7 +32,7 @@ const exclude = [
'react-intl',
'intl-messageformat',
'intl-messageformat-parser',
].map(m => path.resolve(__dirname, 'node_modules', m));
].map((m) => path.resolve(__dirname, 'node_modules', m));
const htmlMinifyOptions = {
minifyCSS: true,