TWNTY-2244 - ESLint rule: enforce usage of .getLoadable() + .getValue() to get atoms (#4143)

* ESLint rule: enforce usage of .getLoadable() + .getValue() to get atoms

Co-authored-by: Matheus <matheus_benini@hotmail.com>

* Merge main

Co-authored-by: v1b3m <vibenjamin6@gmail.com>
Co-authored-by: Matheus <matheus_benini@hotmail.com>

* Fix

* Refactor according to review

Co-authored-by: v1b3m <vibenjamin6@gmail.com>
Co-authored-by: Matheus <matheus_benini@hotmail.com>

* Fix linter issue

Co-authored-by: v1b3m <vibenjamin6@gmail.com>
Co-authored-by: Matheus <matheus_benini@hotmail.com>

* Fix linter

Co-authored-by: v1b3m <vibenjamin6@gmail.com>
Co-authored-by: Matheus <matheus_benini@hotmail.com>

---------

Co-authored-by: gitstart-twenty <gitstart-twenty@users.noreply.github.com>
Co-authored-by: Matheus <matheus_benini@hotmail.com>
Co-authored-by: v1b3m <vibenjamin6@gmail.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
This commit is contained in:
gitstart-app[bot] 2024-03-06 00:24:20 +01:00 committed by GitHub
parent 706b5d3cf1
commit b2210bd418
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 180 additions and 24 deletions

View File

@ -47,5 +47,6 @@
}, },
"search.exclude": { "search.exclude": {
"**/.yarn": true, "**/.yarn": true,
} },
"eslint.debug": true
} }

View File

@ -48,6 +48,7 @@ module.exports = {
'@nx/workspace-styled-components-prefixed-with-styled': 'error', '@nx/workspace-styled-components-prefixed-with-styled': 'error',
'@nx/workspace-no-state-useref': 'error', '@nx/workspace-no-state-useref': 'error',
'@nx/workspace-component-props-naming': 'error', '@nx/workspace-component-props-naming': 'error',
'@nx/workspace-use-getLoadable-and-getValue-to-get-atoms': 'error',
'react/no-unescaped-entities': 'off', 'react/no-unescaped-entities': 'off',
'react/prop-types': 'off', 'react/prop-types': 'off',

View File

@ -46,7 +46,7 @@ export const useGetRelationMetadata = () =>
objectNameType: 'singular', objectNameType: 'singular',
}), }),
) )
.valueOrThrow(); .getValue();
if (!relationObjectMetadataItem) return null; if (!relationObjectMetadataItem) return null;

View File

@ -35,7 +35,7 @@ export const useRecordBoardDeprecatedCardFieldsInternal = (
async ( async (
field: Omit<ColumnDefinition<FieldMetadata>, 'size' | 'position'>, field: Omit<ColumnDefinition<FieldMetadata>, 'size' | 'position'>,
) => { ) => {
const existingFields = await snapshot const existingFields = snapshot
.getLoadable(recordBoardCardFieldsScopedState({ scopeId })) .getLoadable(recordBoardCardFieldsScopedState({ scopeId }))
.getValue(); .getValue();

View File

@ -11,16 +11,14 @@ export const useRemoveRecordBoardDeprecatedCardIdsInternal = () => {
return useRecoilCallback( return useRecoilCallback(
({ snapshot, set }) => ({ snapshot, set }) =>
(cardIdToRemove: string[]) => { (cardIdToRemove: string[]) => {
const boardColumns = snapshot const boardColumns = snapshot.getLoadable(boardColumnsState).getValue();
.getLoadable(boardColumnsState)
.valueOrThrow();
boardColumns.forEach((boardColumn) => { boardColumns.forEach((boardColumn) => {
const columnCardIds = snapshot const columnCardIds = snapshot
.getLoadable( .getLoadable(
recordBoardCardIdsByColumnIdFamilyState(boardColumn.id), recordBoardCardIdsByColumnIdFamilyState(boardColumn.id),
) )
.valueOrThrow(); .getValue();
set( set(
recordBoardCardIdsByColumnIdFamilyState(boardColumn.id), recordBoardCardIdsByColumnIdFamilyState(boardColumn.id),
columnCardIds.filter((cardId) => !cardIdToRemove.includes(cardId)), columnCardIds.filter((cardId) => !cardIdToRemove.includes(cardId)),

View File

@ -19,7 +19,9 @@ export const useSetRecordBoardDeprecatedCardSelectedInternal = (props: any) => {
const setCardSelected = useRecoilCallback( const setCardSelected = useRecoilCallback(
({ set, snapshot }) => ({ set, snapshot }) =>
(cardId: string, selected: boolean) => { (cardId: string, selected: boolean) => {
const activeCardIds = snapshot.getLoadable(activeCardIdsState).contents; const activeCardIds = snapshot
.getLoadable(activeCardIdsState)
.getValue();
set(isRecordBoardDeprecatedCardSelectedFamilyState(cardId), selected); set(isRecordBoardDeprecatedCardSelectedFamilyState(cardId), selected);
set(actionBarOpenState, selected || activeCardIds.length > 0); set(actionBarOpenState, selected || activeCardIds.length > 0);
@ -39,7 +41,9 @@ export const useSetRecordBoardDeprecatedCardSelectedInternal = (props: any) => {
const unselectAllActiveCards = useRecoilCallback( const unselectAllActiveCards = useRecoilCallback(
({ set, snapshot }) => ({ set, snapshot }) =>
() => { () => {
const activeCardIds = snapshot.getLoadable(activeCardIdsState).contents; const activeCardIds = snapshot
.getLoadable(activeCardIdsState)
.getValue();
activeCardIds.forEach((cardId: string) => { activeCardIds.forEach((cardId: string) => {
set(isRecordBoardDeprecatedCardSelectedFamilyState(cardId), false); set(isRecordBoardDeprecatedCardSelectedFamilyState(cardId), false);

View File

@ -68,7 +68,7 @@ export const useUpdateCompanyBoardColumnsInternal = () => {
for (const [id, companyProgress] of Object.entries(companyBoardIndex)) { for (const [id, companyProgress] of Object.entries(companyBoardIndex)) {
const currentCompanyProgress = snapshot const currentCompanyProgress = snapshot
.getLoadable(companyProgressesFamilyState(id)) .getLoadable(companyProgressesFamilyState(id))
.valueOrThrow(); .getValue();
if (!isDeeplyEqual(currentCompanyProgress, companyProgress)) { if (!isDeeplyEqual(currentCompanyProgress, companyProgress)) {
set(companyProgressesFamilyState(id), companyProgress); set(companyProgressesFamilyState(id), companyProgress);
@ -78,11 +78,11 @@ export const useUpdateCompanyBoardColumnsInternal = () => {
const currentPipelineSteps = snapshot const currentPipelineSteps = snapshot
.getLoadable(currentPipelineStepsState) .getLoadable(currentPipelineStepsState)
.valueOrThrow(); .getValue();
const currentBoardColumns = snapshot const currentBoardColumns = snapshot
.getLoadable(boardColumnsState) .getLoadable(boardColumnsState)
.valueOrThrow(); .getValue();
if (!isDeeplyEqual(pipelineSteps, currentPipelineSteps)) { if (!isDeeplyEqual(pipelineSteps, currentPipelineSteps)) {
set(currentPipelineStepsState, pipelineSteps); set(currentPipelineStepsState, pipelineSteps);
@ -133,7 +133,7 @@ export const useUpdateCompanyBoardColumnsInternal = () => {
.getLoadable( .getLoadable(
recordBoardCardIdsByColumnIdFamilyState(boardColumn.id), recordBoardCardIdsByColumnIdFamilyState(boardColumn.id),
) )
.valueOrThrow(); .getValue();
if (!isDeeplyEqual(currentBoardCardIds, boardCardIds)) { if (!isDeeplyEqual(currentBoardCardIds, boardCardIds)) {
set( set(

View File

@ -10,7 +10,7 @@ export const useSetRecordInStore = () => {
records.forEach((record) => { records.forEach((record) => {
const currentRecord = snapshot const currentRecord = snapshot
.getLoadable(recordStoreFamilyState(record.id)) .getLoadable(recordStoreFamilyState(record.id))
.valueOrThrow(); .getValue();
if (JSON.stringify(currentRecord) !== JSON.stringify(record)) { if (JSON.stringify(currentRecord) !== JSON.stringify(record)) {
set(recordStoreFamilyState(record.id), record); set(recordStoreFamilyState(record.id), record);

View File

@ -26,7 +26,7 @@ export const useLeaveTableFocus = (recordTableId?: string) => {
const currentHotkeyScope = snapshot const currentHotkeyScope = snapshot
.getLoadable(currentHotkeyScopeState) .getLoadable(currentHotkeyScopeState)
.valueOrThrow(); .getValue();
if (!isSoftFocusActive) { if (!isSoftFocusActive) {
return; return;

View File

@ -24,7 +24,7 @@ export const useSetRecordTableData = ({
// TODO: refactor with scoped state later // TODO: refactor with scoped state later
const currentEntity = snapshot const currentEntity = snapshot
.getLoadable(recordStoreFamilyState(entity.id)) .getLoadable(recordStoreFamilyState(entity.id))
.valueOrThrow(); .getValue();
if (JSON.stringify(currentEntity) !== JSON.stringify(entity)) { if (JSON.stringify(currentEntity) !== JSON.stringify(entity)) {
set(recordStoreFamilyState(entity.id), entity); set(recordStoreFamilyState(entity.id), entity);

View File

@ -19,8 +19,10 @@ export const usePipelineSteps = () => {
const handlePipelineStepAdd = useRecoilCallback( const handlePipelineStepAdd = useRecoilCallback(
({ snapshot }) => ({ snapshot }) =>
async (boardColumn: BoardColumnDefinition) => { (boardColumn: BoardColumnDefinition) => {
const currentPipeline = await snapshot.getPromise(currentPipelineState); const currentPipeline = snapshot
.getLoadable(currentPipelineState)
.getValue();
if (!currentPipeline?.id) return; if (!currentPipeline?.id) return;
return createOnePipelineStep?.({ return createOnePipelineStep?.({
@ -35,8 +37,10 @@ export const usePipelineSteps = () => {
const handlePipelineStepDelete = useRecoilCallback( const handlePipelineStepDelete = useRecoilCallback(
({ snapshot }) => ({ snapshot }) =>
async (boardColumnId: string) => { (boardColumnId: string) => {
const currentPipeline = await snapshot.getPromise(currentPipelineState); const currentPipeline = snapshot
.getLoadable(currentPipelineState)
.getValue();
if (!currentPipeline?.id) return; if (!currentPipeline?.id) return;
return deleteOnePipelineStep?.(boardColumnId); return deleteOnePipelineStep?.(boardColumnId);

View File

@ -14,7 +14,7 @@ export const usePreviousHotkeyScope = () => {
() => { () => {
const previousHotkeyScope = snapshot const previousHotkeyScope = snapshot
.getLoadable(previousHotkeyScopeState) .getLoadable(previousHotkeyScopeState)
.valueOrThrow(); .getValue();
if (!previousHotkeyScope) { if (!previousHotkeyScope) {
return; return;
@ -35,7 +35,7 @@ export const usePreviousHotkeyScope = () => {
(scope: string, customScopes?: CustomHotkeyScopes) => { (scope: string, customScopes?: CustomHotkeyScopes) => {
const currentHotkeyScope = snapshot const currentHotkeyScope = snapshot
.getLoadable(currentHotkeyScopeState) .getLoadable(currentHotkeyScopeState)
.valueOrThrow(); .getValue();
setHotkeyScope(scope, customScopes); setHotkeyScope(scope, customScopes);
set(previousHotkeyScopeState, currentHotkeyScope); set(previousHotkeyScopeState, currentHotkeyScope);

View File

@ -25,7 +25,7 @@ export const useScopedHotkeyCallback = () =>
}) => { }) => {
const currentHotkeyScopes = snapshot const currentHotkeyScopes = snapshot
.getLoadable(internalHotkeysEnabledScopesState) .getLoadable(internalHotkeysEnabledScopesState)
.valueOrThrow(); .getValue();
if (!currentHotkeyScopes.includes(scope)) { if (!currentHotkeyScopes.includes(scope)) {
if (DEBUG_HOTKEY_SCOPE) { if (DEBUG_HOTKEY_SCOPE) {

View File

@ -27,7 +27,7 @@ export const useSetHotkeyScope = () =>
async (hotkeyScopeToSet: string, customScopes?: CustomHotkeyScopes) => { async (hotkeyScopeToSet: string, customScopes?: CustomHotkeyScopes) => {
const currentHotkeyScope = snapshot const currentHotkeyScope = snapshot
.getLoadable(currentHotkeyScopeState) .getLoadable(currentHotkeyScopeState)
.valueOrThrow(); .getValue();
if (currentHotkeyScope.scope === hotkeyScopeToSet) { if (currentHotkeyScope.scope === hotkeyScopeToSet) {
if (!isNonNullable(customScopes)) { if (!isNonNullable(customScopes)) {

View File

@ -30,6 +30,11 @@ import {
rule as styledComponentsPrefixedWithStyled, rule as styledComponentsPrefixedWithStyled,
RULE_NAME as styledComponentsPrefixedWithStyledName, RULE_NAME as styledComponentsPrefixedWithStyledName,
} from './rules/styled-components-prefixed-with-styled'; } from './rules/styled-components-prefixed-with-styled';
import {
rule as useGetLoadableAndGetValueToGetAtoms,
RULE_NAME as useGetLoadableAndGetValueToGetAtomsName,
} from './rules/use-getLoadable-and-getValue-to-get-atoms';
/** /**
* Import your custom workspace rules at the top of this file. * Import your custom workspace rules at the top of this file.
* *
@ -64,6 +69,8 @@ module.exports = {
[sortCssPropertiesAlphabeticallyName]: sortCssPropertiesAlphabetically, [sortCssPropertiesAlphabeticallyName]: sortCssPropertiesAlphabetically,
[styledComponentsPrefixedWithStyledName]: [styledComponentsPrefixedWithStyledName]:
styledComponentsPrefixedWithStyled, styledComponentsPrefixedWithStyled,
[useGetLoadableAndGetValueToGetAtomsName]:
useGetLoadableAndGetValueToGetAtoms,
[maxConstsPerFileName]: maxConstsPerFile, [maxConstsPerFileName]: maxConstsPerFile,
}, },
}; };

View File

@ -0,0 +1,53 @@
import { TSESLint } from '@typescript-eslint/utils';
import { rule, RULE_NAME } from './use-getLoadable-and-getValue-to-get-atoms';
const ruleTester = new TSESLint.RuleTester({
parser: require.resolve('@typescript-eslint/parser'),
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
});
ruleTester.run(RULE_NAME, rule, {
valid: [
{
code: 'const atoms = snapshot.getLoadable(someState).getValue();',
},
{
code: 'const atoms = snapshot.getLoadable(someState(viewId)).getValue();',
},
],
invalid: [
{
code: 'const atoms = await snapshot.getPromise(someState);',
errors: [
{
messageId: 'invalidWayToGetAtoms',
},
],
output: 'const atoms = snapshot.getLoadable(someState).getValue();',
},
{
code: 'const atoms = await snapshot.getPromise(someState(viewId));',
errors: [
{
messageId: 'invalidWayToGetAtoms',
},
],
output:
'const atoms = snapshot.getLoadable(someState(viewId)).getValue();',
},
{
code: 'const atoms = snapshot.getLoadable(someState).anotherMethod();',
errors: [
{
messageId: 'invalidWayToGetAtoms',
},
],
output: 'const atoms = snapshot.getLoadable(someState).getValue();',
},
],
});

View File

@ -0,0 +1,88 @@
import { ESLintUtils } from '@typescript-eslint/utils';
// NOTE: The rule will be available in ESLint configs as "@nx/workspace-usage-getLoadable-and-getValue-to-get-atoms"
export const RULE_NAME = 'use-getLoadable-and-getValue-to-get-atoms';
export const rule = ESLintUtils.RuleCreator(() => __filename)({
name: RULE_NAME,
meta: {
type: 'problem',
docs: {
description: 'Ensure you are using getLoadable and getValue',
recommended: 'recommended',
},
fixable: 'code',
schema: [],
messages: {
redundantAwait: 'Redundant await on non-promise',
invalidAccessorOnSnapshot:
"Expected to use method 'getLoadable()' on 'snapshot' but instead found '{{ propertyName }}'",
invalidWayToGetAtoms:
"Expected to use method 'getValue()' with 'getLoadable()' but instead found '{{ propertyName }}'",
},
},
defaultOptions: [],
create: (context) => ({
AwaitExpression: (node) => {
const { argument, range }: any = node;
if (
(argument.callee?.object?.callee?.object?.name === 'snapshot' &&
argument?.callee?.object?.callee?.property?.name === 'getLoadable') ||
(argument.callee?.object?.name === 'snapshot' &&
argument?.callee?.property?.name === 'getLoadable')
) {
// remove await
context.report({
node,
messageId: 'redundantAwait',
data: {
propertyName: argument.callee.property.name,
},
fix: (fixer) => fixer.removeRange([range[0], range[0] + 5]),
});
}
},
MemberExpression: (node) => {
const { object, property }: any = node;
if (
object.callee?.type === 'MemberExpression' &&
object.callee.object?.name === 'snapshot' &&
object.callee.property?.name === 'getLoadable'
) {
const propertyName = property.name;
if (propertyName !== 'getValue') {
context.report({
node: property,
messageId: 'invalidWayToGetAtoms',
data: {
propertyName,
},
// replace the property with `getValue`
fix: (fixer) => fixer.replaceText(property, 'getValue'),
});
}
}
},
CallExpression: (node) => {
const { callee }: any = node;
if (
callee.type === 'MemberExpression' &&
callee.object?.name === 'snapshot' &&
callee.property?.name === 'getPromise'
) {
context.report({
node: callee.property,
messageId: 'invalidAccessorOnSnapshot',
data: {
propertyName: callee.property.name,
},
// Replace `getPromise` with `getLoadable`
fix: (fixer) => fixer.replaceText(callee.property, 'getLoadable'),
});
}
},
}),
});