Skip to content

Commit

Permalink
Chore: eslint unicorn
Browse files Browse the repository at this point in the history
  • Loading branch information
SBoudrias committed Apr 25, 2024
1 parent 1d94a35 commit 48c6e7b
Show file tree
Hide file tree
Showing 52 changed files with 169 additions and 162 deletions.
21 changes: 13 additions & 8 deletions eslint.config.js
Expand Up @@ -17,23 +17,28 @@ export default tseslint.config(
'packages/*/__snapshots__/**',
],
},
eslint.configs.recommended,
nodePlugin.configs['flat/recommended-module'],
eslintPluginUnicorn.configs['flat/recommended'],
{
languageOptions: {
globals: {
...globals.nodeBuiltin,
},
},
plugins: {
unicorn: eslintPluginUnicorn,
},
rules: {
'unicorn/no-abusive-eslint-disable': 'error',
'unicorn/prefer-module': 'error',
'unicorn/prefer-node-protocol': 'error',
'unicorn/consistent-function-scoping': 'off',
'unicorn/filename-case': 'off',
'unicorn/no-array-callback-reference': 'off',
'unicorn/no-array-for-each': 'off',
'unicorn/no-array-reduce': 'off',
'unicorn/no-null': 'off',
'unicorn/no-process-exit': 'off',
'unicorn/prefer-event-target': 'off',
'unicorn/prefer-top-level-await': 'off',
'unicorn/prevent-abbreviations': 'off',
},
},
eslint.configs.recommended,
nodePlugin.configs['flat/recommended-module'],
{
files: ['**/*.mts', '**/*.ts'],
extends: [...tseslint.configs.recommended],
Expand Down
8 changes: 3 additions & 5 deletions packages/checkbox/src/index.mts
Expand Up @@ -126,7 +126,7 @@ export default createPrompt(

const [active, setActive] = useState(bounds.first);
const [showHelpTip, setShowHelpTip] = useState(true);
const [errorMsg, setError] = useState<string | undefined>(undefined);
const [errorMsg, setError] = useState<string | undefined>();

useKeypress(async (key) => {
if (isEnterKey(key)) {
Expand Down Expand Up @@ -158,9 +158,7 @@ export default createPrompt(
setShowHelpTip(false);
setItems(items.map((choice, i) => (i === active ? toggle(choice) : choice)));
} else if (key.name === 'a') {
const selectAll = Boolean(
items.find((choice) => isSelectable(choice) && !choice.checked),
);
const selectAll = items.some((choice) => isSelectable(choice) && !choice.checked);
setItems(items.map(check(selectAll)));
} else if (key.name === 'i') {
setItems(items.map(toggle));
Expand Down Expand Up @@ -249,4 +247,4 @@ export default createPrompt(
},
);

export { Separator };
export { Separator } from '@inquirer/core';
2 changes: 1 addition & 1 deletion packages/core/src/lib/Separator.mts
Expand Up @@ -7,7 +7,7 @@ import figures from '@inquirer/figures';
*/

export class Separator {
readonly separator = chalk.dim(new Array(15).join(figures.line));
readonly separator = chalk.dim(Array.from({ length: 15 }).join(figures.line));
readonly type = 'separator';

constructor(separator?: string) {
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/lib/create-prompt.mts
Expand Up @@ -47,8 +47,8 @@ export function createPrompt<Value, Config>(view: ViewFunction<Value, Config>) {
store.hooksCleanup.forEach((cleanFn) => {
cleanFn?.();
});
} catch (err) {
reject(err);
} catch (error) {
reject(error);
}

if (context?.clearPromptOnDone) {
Expand Down Expand Up @@ -89,9 +89,9 @@ export function createPrompt<Value, Config>(view: ViewFunction<Value, Config>) {
screen.render(content, bottomContent);

effectScheduler.run();
} catch (err) {
} catch (error) {
onExit();
reject(err);
reject(error);
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/lib/pagination/lines.mts
Expand Up @@ -20,7 +20,7 @@ function split(content: string, width: number) {
function rotate<T>(count: number, items: readonly T[]): readonly T[] {
const max = items.length;
const offset = ((count % max) + max) % max;
return items.slice(offset).concat(items.slice(0, offset));
return [...items.slice(offset), ...items.slice(0, offset)];
}

/**
Expand Down Expand Up @@ -58,7 +58,7 @@ export function lines<T>({
const renderItemAt = (index: number) => split(renderItem(layoutsInPage[index]!), width);

// Create a blank array of lines for the page
const pageBuffer = new Array(pageSize);
const pageBuffer: string[] = Array.from({ length: pageSize });

// Render the active item to decide the position
const activeItem = renderItemAt(requested).slice(0, pageSize);
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/lib/pagination/lines.test.mts
Expand Up @@ -19,7 +19,7 @@ describe('lines(...)', () => {
isActive: boolean;
index: number;
}): string =>
new Array(itemHeight)
Array.from({ length: itemHeight })
.fill(0)
.map((_, i) => {
if (i === 0) {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/lib/screen-manager.mts
Expand Up @@ -30,7 +30,7 @@ export default class ScreenManager {
// rl.line (mainly because of the password prompt), so just rely on it's
// length.
let prompt = rawPromptLine;
if (this.rl.line.length) {
if (this.rl.line.length > 0) {
prompt = prompt.slice(0, -this.rl.line.length);
}

Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/lib/use-ref.mts
@@ -1,5 +1,7 @@
import { useState } from './use-state.mjs';

export function useRef<Value>(val: Value): { current: Value } {
export function useRef<Value>(val?: Value): { current: Value };
export function useRef<Value>(val: Value): { current: Value };
export function useRef<Value>(val: Value) {
return useState({ current: val })[0];
}
6 changes: 5 additions & 1 deletion packages/core/src/lib/use-state.mts
Expand Up @@ -3,9 +3,13 @@ import { withPointer, handleChange } from './hook-engine.mjs';
// eslint-disable-next-line @typescript-eslint/ban-types
type NotFunction<T> = T extends Function ? never : T;

export function useState<Value>(
defaultValue?: NotFunction<Value> | (() => Value),
): [Value, (newValue: Value) => void];
export function useState<Value>(
defaultValue: NotFunction<Value> | (() => Value),
): [Value, (newValue: Value) => void] {
): [Value, (newValue: Value) => void];
export function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)) {
return withPointer<Value, [Value, (newValue: Value) => void]>((pointer) => {
const setFn = (newValue: Value) => {
// Noop if the value is still the same.
Expand Down
2 changes: 1 addition & 1 deletion packages/demo/demos/input.mjs
Expand Up @@ -2,7 +2,7 @@ import * as url from 'node:url';
import chalk from 'chalk';
import { input } from '@inquirer/prompts';

const hexRegEx = /([0-9]|[a-f])/gim;
const hexRegEx = /(\d|[a-f])/gim;
const isHex = (value) =>
(value.match(hexRegEx) || []).length === value.length &&
(value.length === 3 || value.length === 6);
Expand Down
9 changes: 6 additions & 3 deletions packages/editor/editor.test.mts
Expand Up @@ -75,12 +75,15 @@ describe('editor prompt', () => {
message: 'Add a description',
validate(value) {
switch (value) {
case '1':
case '1': {
return true;
case '2':
}
case '2': {
return '"2" is not an allowed value';
default:
}
default: {
return false;
}
}
},
});
Expand Down
2 changes: 1 addition & 1 deletion packages/editor/src/index.mts
Expand Up @@ -28,7 +28,7 @@ export default createPrompt<string, EditorConfig>((config, done) => {

const [status, setStatus] = useState<string>('pending');
const [value, setValue] = useState<string>(config.default || '');
const [errorMsg, setError] = useState<string | undefined>(undefined);
const [errorMsg, setError] = useState<string | undefined>();

const isLoading = status === 'loading';
const prefix = usePrefix({ isLoading, theme });
Expand Down
2 changes: 1 addition & 1 deletion packages/expand/src/index.mts
Expand Up @@ -48,7 +48,7 @@ export default createPrompt<string, ExpandConfig>((config, done) => {
const [status, setStatus] = useState<string>('pending');
const [value, setValue] = useState<string>('');
const [expanded, setExpanded] = useState<boolean>(defaultExpandState);
const [errorMsg, setError] = useState<string | undefined>(undefined);
const [errorMsg, setError] = useState<string | undefined>();
const theme = makeTheme(config.theme);
const prefix = usePrefix({ theme });

Expand Down
2 changes: 1 addition & 1 deletion packages/input/src/index.mts
Expand Up @@ -25,7 +25,7 @@ export default createPrompt<string, InputConfig>((config, done) => {
const [defaultValue = '', setDefaultValue] = useState<string | undefined>(
config.default,
);
const [errorMsg, setError] = useState<string | undefined>(undefined);
const [errorMsg, setError] = useState<string | undefined>();
const [value, setValue] = useState<string>('');

const isLoading = status === 'loading';
Expand Down
2 changes: 1 addition & 1 deletion packages/inquirer/examples/checkbox.js
Expand Up @@ -55,7 +55,7 @@ inquirer
},
],
validate(answer) {
if (answer.length < 1) {
if (answer.length === 0) {
return 'You must choose at least one topping.';
}

Expand Down
4 changes: 2 additions & 2 deletions packages/inquirer/examples/input.js
Expand Up @@ -5,7 +5,7 @@
import chalk from 'chalk';
import inquirer from '../lib/inquirer.js';

const hexRegEx = /([0-9]|[a-f])/gim;
const hexRegEx = /(\d|[a-f])/gim;
const isHex = (value) =>
(value.match(hexRegEx) || []).length === value.length &&
(value.length === 3 || value.length === 6);
Expand Down Expand Up @@ -43,7 +43,7 @@ const questions = [
message: "What's your phone number",
validate(value) {
const pass = value.match(
/^([01]{1})?[-.\s]?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i,
/^([01])?[\s.-]?\(?(\d{3})\)?[\s.-]?(\d{3})[\s.-]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?)(?:\d+)?)?$/i,
);
if (pass) {
return true;
Expand Down
30 changes: 17 additions & 13 deletions packages/inquirer/examples/long-list.js
Expand Up @@ -4,19 +4,23 @@

import inquirer from '../lib/inquirer.js';

const choices = Array.apply(0, new Array(26)).map((x, y) => String.fromCharCode(y + 65));
choices.push('Multiline option 1\n super cool feature \n more lines');
choices.push('Multiline option 2\n super cool feature \n more lines');
choices.push('Multiline option 3\n super cool feature \n more lines');
choices.push('Multiline option 4\n super cool feature \n more lines');
choices.push('Multiline option 5\n super cool feature \n more lines');
choices.push(new inquirer.Separator());
choices.push('Multiline option \n super cool feature');
choices.push({
name: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.',
value: 'foo',
short: 'The long option',
});
const choices = Array.apply(0, Array.from({ length: 26 })).map((x, y) =>
String.fromCodePoint(y + 65),
);
choices.push(
'Multiline option 1\n super cool feature \n more lines',
'Multiline option 2\n super cool feature \n more lines',
'Multiline option 3\n super cool feature \n more lines',
'Multiline option 4\n super cool feature \n more lines',
'Multiline option 5\n super cool feature \n more lines',
new inquirer.Separator(),
'Multiline option \n super cool feature',
{
name: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.',
value: 'foo',
short: 'The long option',
},
);

inquirer
.prompt([
Expand Down
4 changes: 2 additions & 2 deletions packages/inquirer/examples/pizza.js
Expand Up @@ -21,7 +21,7 @@ const questions = [
message: "What's your phone number?",
validate(value) {
const pass = value.match(
/^([01]{1})?[-.\s]?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i,
/^([01])?[\s.-]?\(?(\d{3})\)?[\s.-]?(\d{3})[\s.-]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?)(?:\d+)?)?$/i,
);
if (pass) {
return true;
Expand All @@ -44,7 +44,7 @@ const questions = [
name: 'quantity',
message: 'How many do you need?',
validate(value) {
const valid = !isNaN(parseFloat(value));
const valid = !Number.isNaN(Number.parseFloat(value));
return valid || 'Please enter a number';
},
filter: Number,
Expand Down
4 changes: 2 additions & 2 deletions packages/inquirer/examples/regex-validate-input.js
Expand Up @@ -10,11 +10,11 @@ const questions = [
name: 'api_key',
message: 'Please enter a valid API key.',
validate(input) {
if (/([a-f0-9]{40})/g.test(input)) {
if (/([\da-f]{40})/g.test(input)) {
return true;
}

throw Error('Please provide a valid API key secret.');
throw new Error('Please provide a valid API key secret.');
},
},
];
Expand Down
6 changes: 3 additions & 3 deletions packages/inquirer/examples/rx-observable-array.js
Expand Up @@ -21,7 +21,7 @@ const questions = [
message: "What's your phone number",
validate(value) {
const pass = value.match(
/^([01]{1})?[-.\s]?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i,
/^([01])?[\s.-]?\(?(\d{3})\)?[\s.-]?(\d{3})[\s.-]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?)(?:\d+)?)?$/i,
);
if (pass) {
return true;
Expand All @@ -36,10 +36,10 @@ const observable = from(questions);

inquirer.prompt(observable).ui.process.subscribe(
(ans) => {
console.log('Answer is: ', ans);
console.log('Answer is:', ans);
},
(err) => {
console.log('Error: ', err);
console.log('Error:', err);
},
() => {
console.log('Completed');
Expand Down
2 changes: 1 addition & 1 deletion packages/inquirer/examples/rx-observable-create.js
Expand Up @@ -23,7 +23,7 @@ const observe = Observable.create((obs) => {
message: "What's your phone number",
validate(value) {
const pass = value.match(
/^([01]{1})?[-.\s]?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i,
/^([01])?[\s.-]?\(?(\d{3})\)?[\s.-]?(\d{3})[\s.-]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?)(?:\d+)?)?$/i,
);
if (pass) {
return true;
Expand Down
7 changes: 2 additions & 5 deletions packages/inquirer/lib/objects/choice.js
Expand Up @@ -25,10 +25,7 @@ export default class Choice {
});
}

if (typeof val.disabled === 'function') {
this.disabled = val.disabled(answers);
} else {
this.disabled = val.disabled;
}
this.disabled =
typeof val.disabled === 'function' ? val.disabled(answers) : val.disabled;
}
}
13 changes: 13 additions & 0 deletions packages/inquirer/lib/objects/choices.js
Expand Up @@ -47,6 +47,15 @@ export default class Choices {
});
}

[Symbol.iterator]() {
const data = this.choices;
let index = -1;

return {
next: () => ({ value: data[++index], done: !(index in data) }),
};
}

/**
* Get a valid choice from the collection
* @param {Number} selector The selected choice index
Expand Down Expand Up @@ -106,6 +115,10 @@ export default class Choices {
return this.choices.find(func);
}

some(func) {
return this.choices.some(func);
}

push(...args) {
const objs = args.map((val) => new Choice(val));
this.choices.push(...objs);
Expand Down
2 changes: 1 addition & 1 deletion packages/inquirer/lib/objects/separator.js
Expand Up @@ -11,7 +11,7 @@ import figures from '@inquirer/figures';
export default class Separator {
constructor(line) {
this.type = 'separator';
this.line = chalk.dim(line || new Array(15).join(figures.line));
this.line = chalk.dim(line || Array.from({ length: 15 }).join(figures.line));
}

/**
Expand Down

0 comments on commit 48c6e7b

Please sign in to comment.