prettier / prettier-regression-testing

Automates the prettier/prettier regression checks with GitHub Actions.
11 stars 9 forks source link

New Ternary Formatting (WIP) #65

Open thorn0 opened 3 years ago

thorn0 commented 3 years ago

run rattrayalex/prettier#268

github-actions[bot] commented 3 years ago

[Error]

Error: Command failed with exit code 1: git checkout 268
error: pathspec '268' did not match any file(s) known to git
thorn0 commented 3 years ago

run rattrayalex/prettier#postfix-ternaries

github-actions[bot] commented 3 years ago

rattrayalex/prettier@postfix-ternaries VS prettier/prettier@main :: babel/babel@2ae19d01b132f5222e1d5bee2c83921e2f107d70

Diff (2322 lines) ```diff diff --git ORI/babel/eslint/babel-eslint-plugin-development-internal/src/rules/dry-error-messages.js ALT/babel/eslint/babel-eslint-plugin-development-internal/src/rules/dry-error-messages.js index d6e2226e..965d62ee 100644 --- ORI/babel/eslint/babel-eslint-plugin-development-internal/src/rules/dry-error-messages.js +++ ALT/babel/eslint/babel-eslint-plugin-development-internal/src/rules/dry-error-messages.js @@ -7,9 +7,11 @@ function isRelativePath(filePath) { } function resolveAbsolutePath(currentFilePath, moduleToResolve) { - return isRelativePath(moduleToResolve) - ? path.resolve(path.dirname(currentFilePath), moduleToResolve) - : moduleToResolve; + return ( + isRelativePath(moduleToResolve) ? + path.resolve(path.dirname(currentFilePath), moduleToResolve) + : moduleToResolve + ); } function isSourceErrorModule(currentFilePath, targetModulePath, src) { diff --git ORI/babel/packages/babel-cli/src/babel/dir.js ALT/babel/packages/babel-cli/src/babel/dir.js index 97e2f0e2..6429d05d 100644 --- ORI/babel/packages/babel-cli/src/babel/dir.js +++ ALT/babel/packages/babel-cli/src/babel/dir.js @@ -38,9 +38,8 @@ export default async function ({ relative = util.withExtension( relative, - cliOptions.keepFileExtension - ? path.extname(relative) - : cliOptions.outFileExtension, + cliOptions.keepFileExtension ? path.extname(relative) + : cliOptions.outFileExtension, ); const dest = getDest(relative, base); @@ -204,9 +203,8 @@ export default async function ({ try { await handleFile( filename, - filename === filenameOrDir - ? path.dirname(filenameOrDir) - : filenameOrDir, + filename === filenameOrDir ? path.dirname(filenameOrDir) + : filenameOrDir, ); compiledFiles++; diff --git ORI/babel/packages/babel-cli/src/babel/file.js ALT/babel/packages/babel-cli/src/babel/file.js index 71478faf..ca587f5b 100644 --- ORI/babel/packages/babel-cli/src/babel/file.js +++ ALT/babel/packages/babel-cli/src/babel/file.js @@ -49,12 +49,13 @@ export default async function ({ }, source: mapping.source, original: - mapping.source == null - ? null - : { - line: mapping.originalLine, - column: mapping.originalColumn, - }, + mapping.source == null ? null + : ( + { + line: mapping.originalLine, + column: mapping.originalColumn, + } + ), }); }); @@ -176,9 +177,8 @@ export default async function ({ // "inline" applies to the final output file, but not to the individual // files being concatenated. sourceMaps: - babelOptions.sourceMaps === "inline" - ? true - : babelOptions.sourceMaps, + babelOptions.sourceMaps === "inline" ? true + : babelOptions.sourceMaps, }); } catch (err) { if (!cliOptions.watch) { diff --git ORI/babel/packages/babel-cli/src/babel/util.js ALT/babel/packages/babel-cli/src/babel/util.js index 70d2c6b4..78cbc061 100644 --- ORI/babel/packages/babel-cli/src/babel/util.js +++ ALT/babel/packages/babel-cli/src/babel/util.js @@ -125,9 +125,10 @@ export function requireChokidar(): Object { try { // todo(babel 8): revert `@nicolo-ribaudo/chokidar-2` hack - return parseInt(process.versions.node) >= 8 - ? require("chokidar") - : require("@nicolo-ribaudo/chokidar-2"); + return ( + parseInt(process.versions.node) >= 8 ? require("chokidar") + : require("@nicolo-ribaudo/chokidar-2") + ); } catch (err) { console.error( "The optional dependency chokidar failed to install and is required for " + diff --git ORI/babel/packages/babel-core/src/config/config-chain.js ALT/babel/packages/babel-core/src/config/config-chain.js index 1d5a8d78..08bf7deb 100644 --- ORI/babel/packages/babel-core/src/config/config-chain.js +++ ALT/babel/packages/babel-core/src/config/config-chain.js @@ -200,9 +200,9 @@ export function* buildRootChain( } const pkgData = - typeof context.filename === "string" - ? yield* findPackageData(context.filename) - : null; + typeof context.filename === "string" ? + yield* findPackageData(context.filename) + : null; let ignoreFile, babelrcFile; let isIgnored = false; @@ -301,9 +301,9 @@ function babelrcLoadEnabled( let babelrcPatterns = babelrcRoots; if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns]; babelrcPatterns = babelrcPatterns.map(pat => { - return typeof pat === "string" - ? path.resolve(babelrcRootsDirectory, pat) - : pat; + return ( + typeof pat === "string" ? path.resolve(babelrcRootsDirectory, pat) : pat + ); }); // Fast path to avoid having to match patterns if the babelrc is just @@ -487,13 +487,15 @@ function buildOverrideEnvDescriptors( if (!override) throw new Error("Assertion failure - missing override"); const opts = override.env && override.env[envName]; - return opts - ? descriptors( + return ( + opts ? + descriptors( dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`, ) - : null; + : null + ); } function makeChainWalker({ diff --git ORI/babel/packages/babel-core/src/config/config-descriptors.js ALT/babel/packages/babel-core/src/config/config-descriptors.js index 59f9e462..c7176c28 100644 --- ORI/babel/packages/babel-core/src/config/config-descriptors.js +++ ALT/babel/packages/babel-core/src/config/config-descriptors.js @@ -84,11 +84,12 @@ export function createCachedDescriptors( const { plugins, presets, passPerPreset } = options; return { options, - plugins: plugins - ? () => createCachedPluginDescriptors(plugins, dirname)(alias) + plugins: + plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => handlerOf([]), - presets: presets - ? () => + presets: + presets ? + () => createCachedPresetDescriptors(presets, dirname)(alias)( !!passPerPreset, ) diff --git ORI/babel/packages/babel-core/src/config/files/configuration.js ALT/babel/packages/babel-core/src/config/files/configuration.js index fe3da459..119b79d6 100644 --- ORI/babel/packages/babel-core/src/config/files/configuration.js +++ ALT/babel/packages/babel-core/src/config/files/configuration.js @@ -74,10 +74,10 @@ export function* findRelativeConfig( loc, envName, caller, - packageData.pkg?.dirname === loc - ? // $FlowIgnore - packageData.pkg is not null - packageToBabelConfig((packageData.pkg: ConfigFile)) - : null, + packageData.pkg?.dirname === loc ? + // $FlowIgnore - packageData.pkg is not null + packageToBabelConfig((packageData.pkg: ConfigFile)) + : null, ); } @@ -156,9 +156,11 @@ export function* loadConfig( */ function readConfig(filepath, envName, caller): Handler { const ext = path.extname(filepath); - return ext === ".js" || ext === ".cjs" || ext === ".mjs" - ? readConfigJS(filepath, { envName, caller }) - : readConfigJSON5(filepath); + return ( + ext === ".js" || ext === ".cjs" || ext === ".mjs" ? + readConfigJS(filepath, { envName, caller }) + : readConfigJSON5(filepath) + ); } const LOADING_CONFIGS = new Set(); diff --git ORI/babel/packages/babel-core/src/config/files/module-types.js ALT/babel/packages/babel-core/src/config/files/module-types.js index de75ada4..5822b437 100644 --- ORI/babel/packages/babel-core/src/config/files/module-types.js +++ ALT/babel/packages/babel-core/src/config/files/module-types.js @@ -49,10 +49,12 @@ function guessJSModuleType(filename: string): "cjs" | "mjs" | "unknown" { function loadCjsDefault(filepath: string, fallbackToTranspiledModule: boolean) { const module = (require(filepath): mixed); - return module?.__esModule - ? // TODO (Babel 8): Remove "module" and "undefined" fallback + return ( + module?.__esModule ? + // TODO (Babel 8): Remove "module" and "undefined" fallback module.default || (fallbackToTranspiledModule ? module : undefined) - : module; + : module + ); } async function loadMjsDefault(filepath: string) { diff --git ORI/babel/packages/babel-core/src/config/full.js ALT/babel/packages/babel-core/src/config/full.js index f0a2632d..0f98dc4a 100644 --- ORI/babel/packages/babel-core/src/config/full.js +++ ALT/babel/packages/babel-core/src/config/full.js @@ -347,9 +347,8 @@ const validateIfOptionNeedsFilename = ( descriptor: UnloadedDescriptor, ): void => { if (options.test || options.include || options.exclude) { - const formattedPresetName = descriptor.name - ? `"${descriptor.name}"` - : "/* your preset */"; + const formattedPresetName = + descriptor.name ? `"${descriptor.name}"` : "/* your preset */"; throw new Error( [ `Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, diff --git ORI/babel/packages/babel-core/src/config/item.js ALT/babel/packages/babel-core/src/config/item.js index cf04f1bc..61833e6e 100644 --- ORI/babel/packages/babel-core/src/config/item.js +++ ALT/babel/packages/babel-core/src/config/item.js @@ -124,8 +124,9 @@ class ConfigItem { this.options = this._descriptor.options; this.dirname = this._descriptor.dirname; this.name = this._descriptor.name; - this.file = this._descriptor.file - ? { + this.file = + this._descriptor.file ? + { request: this._descriptor.file.request, resolved: this._descriptor.file.resolved, } diff --git ORI/babel/packages/babel-core/src/config/partial.js ALT/babel/packages/babel-core/src/config/partial.js index dc0a0e02..209b0158 100644 --- ORI/babel/packages/babel-core/src/config/partial.js +++ ALT/babel/packages/babel-core/src/config/partial.js @@ -99,9 +99,8 @@ export default function* loadPrivatePartialConfig( ); const filename = - typeof args.filename === "string" - ? path.resolve(cwd, args.filename) - : undefined; + typeof args.filename === "string" ? path.resolve(cwd, args.filename) + : undefined; const showConfigPath = yield* resolveShowConfigPath(absoluteCwd); diff --git ORI/babel/packages/babel-core/src/parser/util/missing-plugin-helper.js ALT/babel/packages/babel-core/src/parser/util/missing-plugin-helper.js index b1a94974..8ad15219 100644 --- ORI/babel/packages/babel-core/src/parser/util/missing-plugin-helper.js +++ ALT/babel/packages/babel-core/src/parser/util/missing-plugin-helper.js @@ -304,8 +304,8 @@ export default function generateMissingPluginMessage( const syntaxPluginInfo = getNameURLCombination(syntaxPlugin); if (transformPlugin) { const transformPluginInfo = getNameURLCombination(transformPlugin); - const sectionType = transformPlugin.name.startsWith("@babel/plugin") - ? "plugins" + const sectionType = + transformPlugin.name.startsWith("@babel/plugin") ? "plugins" : "presets"; helpMessage += `\n\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation. If you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`; diff --git ORI/babel/packages/babel-core/src/tools/build-external-helpers.js ALT/babel/packages/babel-core/src/tools/build-external-helpers.js index ef912022..9b01feef 100644 --- ORI/babel/packages/babel-core/src/tools/build-external-helpers.js +++ ALT/babel/packages/babel-core/src/tools/build-external-helpers.js @@ -126,9 +126,10 @@ function buildVar(allowlist) { function buildHelpers(body, namespace, allowlist) { const getHelperReference = name => { - return namespace - ? t.memberExpression(namespace, t.identifier(name)) - : t.identifier(`_${name}`); + return ( + namespace ? t.memberExpression(namespace, t.identifier(name)) + : t.identifier(`_${name}`) + ); }; const refs = {}; diff --git ORI/babel/packages/babel-core/src/transformation/file/file.js ALT/babel/packages/babel-core/src/transformation/file/file.js index fd5c1dad..d00f28b0 100644 --- ORI/babel/packages/babel-core/src/transformation/file/file.js +++ ALT/babel/packages/babel-core/src/transformation/file/file.js @@ -252,12 +252,12 @@ export default class File { column: loc.start.column + 1, }, end: - loc.end && loc.start.line === loc.end.line - ? { - line: loc.end.line, - column: loc.end.column + 1, - } - : undefined, + loc.end && loc.start.line === loc.end.line ? + { + line: loc.end.line, + column: loc.end.column + 1, + } + : undefined, }, { highlightCode }, ); diff --git ORI/babel/packages/babel-core/src/transformation/normalize-opts.js ALT/babel/packages/babel-core/src/transformation/normalize-opts.js index 4c53b7aa..abcef921 100644 --- ORI/babel/packages/babel-core/src/transformation/normalize-opts.js +++ ALT/babel/packages/babel-core/src/transformation/normalize-opts.js @@ -7,9 +7,9 @@ export default function normalizeOptions(config: ResolvedConfig): {} { const { filename, cwd, - filenameRelative = typeof filename === "string" - ? path.relative(cwd, filename) - : "unknown", + filenameRelative = typeof filename === "string" ? + path.relative(cwd, filename) + : "unknown", sourceType = "module", inputSourceMap, sourceMaps = !!inputSourceMap, diff --git ORI/babel/packages/babel-core/test/config-loading.js ALT/babel/packages/babel-core/test/config-loading.js index dcdf0ceb..8b4d0572 100644 --- ORI/babel/packages/babel-core/test/config-loading.js +++ ALT/babel/packages/babel-core/test/config-loading.js @@ -36,11 +36,11 @@ describe("@babel/core config loading", () => { return { cwd: path.dirname(FILEPATH), filename: FILEPATH, - presets: skipProgrammatic - ? null + presets: + skipProgrammatic ? null : [[require("./fixtures/config-loading/preset3"), {}]], - plugins: skipProgrammatic - ? null + plugins: + skipProgrammatic ? null : [[require("./fixtures/config-loading/plugin6"), {}]], }; } diff --git ORI/babel/packages/babel-core/test/resolution.js ALT/babel/packages/babel-core/test/resolution.js index 191e5436..8bc546fc 100644 --- ORI/babel/packages/babel-core/test/resolution.js +++ ALT/babel/packages/babel-core/test/resolution.js @@ -354,9 +354,11 @@ describe("addon resolution", function () { // because Jest 24 has an issue on setting the MODULE_NOT_FOUND error when the native // `require.resolve` is provided. // see https://github.com/babel/babel/pull/12439/files#r535996000 - process.versions.node.startsWith("8.") - ? /Cannot resolve module 'babel-preset-foo'/ - : /Cannot resolve module 'babel-preset-foo'.*\n- If you want to resolve "foo", use "module:foo"/, + process.versions.node.startsWith("8.") ? + /Cannot resolve module 'babel-preset-foo'/ + : ( + /Cannot resolve module 'babel-preset-foo'.*\n- If you want to resolve "foo", use "module:foo"/ + ), ); }); @@ -370,9 +372,11 @@ describe("addon resolution", function () { plugins: ["foo"], }); }).toThrow( - process.versions.node.startsWith("8.") - ? /Cannot resolve module 'babel-plugin-foo'/ - : /Cannot resolve module 'babel-plugin-foo'.*\n- If you want to resolve "foo", use "module:foo"/, + process.versions.node.startsWith("8.") ? + /Cannot resolve module 'babel-plugin-foo'/ + : ( + /Cannot resolve module 'babel-plugin-foo'.*\n- If you want to resolve "foo", use "module:foo"/ + ), ); }); @@ -386,9 +390,11 @@ describe("addon resolution", function () { presets: ["foo"], }); }).toThrow( - process.versions.node.startsWith("8.") - ? /Cannot resolve module 'babel-preset-foo'/ - : /Cannot resolve module 'babel-preset-foo'.*\n- Did you mean "@babel\/foo"\?/, + process.versions.node.startsWith("8.") ? + /Cannot resolve module 'babel-preset-foo'/ + : ( + /Cannot resolve module 'babel-preset-foo'.*\n- Did you mean "@babel\/foo"\?/ + ), ); }); @@ -402,9 +408,11 @@ describe("addon resolution", function () { plugins: ["foo"], }); }).toThrow( - process.versions.node.startsWith("8.") - ? /Cannot resolve module 'babel-plugin-foo'/ - : /Cannot resolve module 'babel-plugin-foo'.*\n- Did you mean "@babel\/foo"\?/, + process.versions.node.startsWith("8.") ? + /Cannot resolve module 'babel-plugin-foo'/ + : ( + /Cannot resolve module 'babel-plugin-foo'.*\n- Did you mean "@babel\/foo"\?/ + ), ); }); @@ -418,9 +426,11 @@ describe("addon resolution", function () { presets: ["testplugin"], }); }).toThrow( - process.versions.node.startsWith("8.") - ? /Cannot resolve module 'babel-preset-testplugin'/ - : /Cannot resolve module 'babel-preset-testplugin'.*\n- Did you accidentally pass a plugin as a preset\?/, + process.versions.node.startsWith("8.") ? + /Cannot resolve module 'babel-preset-testplugin'/ + : ( + /Cannot resolve module 'babel-preset-testplugin'.*\n- Did you accidentally pass a plugin as a preset\?/ + ), ); }); @@ -434,9 +444,11 @@ describe("addon resolution", function () { plugins: ["testpreset"], }); }).toThrow( - process.versions.node.startsWith("8.") - ? /Cannot resolve module 'babel-plugin-testpreset'/ - : /Cannot resolve module 'babel-plugin-testpreset'.*\n- Did you accidentally pass a preset as a plugin\?/, + process.versions.node.startsWith("8.") ? + /Cannot resolve module 'babel-plugin-testpreset'/ + : ( + /Cannot resolve module 'babel-plugin-testpreset'.*\n- Did you accidentally pass a preset as a plugin\?/ + ), ); }); diff --git ORI/babel/packages/babel-helper-builder-react-jsx/src/index.js ALT/babel/packages/babel-helper-builder-react-jsx/src/index.js index 5c6d478e..3460b0d7 100644 --- ORI/babel/packages/babel-helper-builder-react-jsx/src/index.js +++ ALT/babel/packages/babel-helper-builder-react-jsx/src/index.js @@ -232,8 +232,9 @@ You can set \`throwIfNamespace: false\` to bypass this warning.`, objs.unshift(t.objectExpression([])); } - const helper = useBuiltIns - ? t.memberExpression(t.identifier("Object"), t.identifier("assign")) + const helper = + useBuiltIns ? + t.memberExpression(t.identifier("Object"), t.identifier("assign")) : file.addHelper("extends"); // spread it diff --git ORI/babel/packages/babel-helper-compilation-targets/src/index.js ALT/babel/packages/babel-helper-compilation-targets/src/index.js index 9459e7f9..f1fa3cce 100644 --- ORI/babel/packages/babel-helper-compilation-targets/src/index.js +++ ALT/babel/packages/babel-helper-compilation-targets/src/index.js @@ -73,9 +73,8 @@ function getLowestVersions(browsers: Array): Targets { const isSplitUnreleased = isUnreleasedVersion(splitVersion, browserName); if (!all[normalizedBrowserName]) { - all[normalizedBrowserName] = isSplitUnreleased - ? splitVersion - : semverify(splitVersion); + all[normalizedBrowserName] = + isSplitUnreleased ? splitVersion : semverify(splitVersion); return all; } @@ -132,8 +131,8 @@ function semverifyTarget(target, value) { const targetParserMap = { __default(target, value) { - const version = isUnreleasedVersion(value, target) - ? value.toLowerCase() + const version = + isUnreleasedVersion(value, target) ? value.toLowerCase() : semverifyTarget(target, value); return [target, version]; }, @@ -141,9 +140,8 @@ const targetParserMap = { // Parse `node: true` and `node: "current"` to version node(target, value) { const parsed = - value === true || value === "current" - ? process.versions.node - : semverifyTarget(target, value); + value === true || value === "current" ? process.versions.node + : semverifyTarget(target, value); return [target, parsed]; }, }; diff --git ORI/babel/packages/babel-helper-create-class-features-plugin/src/fields.js ALT/babel/packages/babel-helper-create-class-features-plugin/src/fields.js index 185da71b..048b4a21 100644 --- ORI/babel/packages/babel-helper-create-class-features-plugin/src/fields.js +++ ALT/babel/packages/babel-helper-create-class-features-plugin/src/fields.js @@ -15,13 +15,15 @@ export function buildPrivateNamesMap(props) { const isInstance = !prop.node.static; if (isPrivate) { const { name } = prop.node.key.id; - const update = privateNamesMap.has(name) - ? privateNamesMap.get(name) - : { + const update = + privateNamesMap.has(name) ? privateNamesMap.get(name) + : ( + { id: prop.scope.generateUidIdentifier(name), static: !isInstance, method: isMethod, - }; + } + ); if (prop.node.kind === "get") { update.getId = prop.scope.generateUidIdentifier(`get_${name}`); } else if (prop.node.kind === "set") { @@ -217,9 +219,8 @@ const privateNameHandlerSpec = { if (isStatic) { const helperName = - isMethod && !isAccessor - ? "classStaticPrivateMethodGet" - : "classStaticPrivateFieldSpecGet"; + isMethod && !isAccessor ? "classStaticPrivateMethodGet" + : "classStaticPrivateFieldSpecGet"; return t.callExpression(file.addHelper(helperName), [ this.receiver(member), @@ -283,9 +284,8 @@ const privateNameHandlerSpec = { if (isStatic) { const helperName = - isMethod && !isAccessor - ? "classStaticPrivateMethodSet" - : "classStaticPrivateFieldSpecSet"; + isMethod && !isAccessor ? "classStaticPrivateMethodSet" + : "classStaticPrivateFieldSpecSet"; return t.callExpression(file.addHelper(helperName), [ this.receiver(member), @@ -412,8 +412,8 @@ export function transformPrivateNamesUsage( if (!privateNamesMap.size) return; const body = path.get("body"); - const handler = privateFieldsAsProperties - ? privateNameHandlerLoose + const handler = + privateFieldsAsProperties ? privateNameHandlerLoose : privateNameHandlerSpec; memberExpressionToFunctions(body, privateNameVisitor, { @@ -676,9 +676,10 @@ function replaceThisContext(path, ref, superRef, file, constantSuper) { refToPreserve: ref, getObjectRef() { state.needsClassRef = true; - return path.node.static - ? ref - : t.memberExpression(ref, t.identifier("prototype")); + return ( + path.node.static ? ref + : t.memberExpression(ref, t.identifier("prototype")) + ); }, }); replacer.replace(); diff --git ORI/babel/packages/babel-helper-module-transforms/src/index.js ALT/babel/packages/babel-helper-module-transforms/src/index.js index 53fb1851..ef38f937 100644 --- ORI/babel/packages/babel-helper-module-transforms/src/index.js +++ ALT/babel/packages/babel-helper-module-transforms/src/index.js @@ -158,8 +158,8 @@ export function buildNamespaceInitStatements( for (const exportName of sourceMetadata.reexportNamespace) { // Assign export to namespace object. statements.push( - (sourceMetadata.lazy - ? template.statement` + (sourceMetadata.lazy ? + template.statement` Object.defineProperty(EXPORTS, "NAME", { enumerable: true, get: function() { @@ -167,7 +167,7 @@ export function buildNamespaceInitStatements( } }); ` - : template.statement`EXPORTS.NAME = NAMESPACE;`)({ + : template.statement`EXPORTS.NAME = NAMESPACE;`)({ EXPORTS: metadata.exportName, NAME: exportName, NAMESPACE: t.cloneNode(srcNamespace), @@ -206,8 +206,8 @@ const buildReexportsFromMeta = ( metadata: SourceModuleMetadata, constantReexports: boolean, ) => { - const namespace = metadata.lazy - ? t.callExpression(t.identifier(metadata.name), []) + const namespace = + metadata.lazy ? t.callExpression(t.identifier(metadata.name), []) : t.identifier(metadata.name); const { stringSpecifiers } = meta; @@ -250,16 +250,17 @@ function buildESModuleHeader( enumerableModuleMeta: boolean = false, ) { return ( - enumerableModuleMeta - ? template.statement` + enumerableModuleMeta ? + template.statement` EXPORTS.__esModule = true; ` - : template.statement` + : ( + template.statement` Object.defineProperty(EXPORTS, "__esModule", { value: true, }); ` - )({ EXPORTS: metadata.exportName }); + ))({ EXPORTS: metadata.exportName }); } /** @@ -267,8 +268,8 @@ function buildESModuleHeader( */ function buildNamespaceReexport(metadata, namespace, constantReexports) { return ( - constantReexports - ? template.statement` + constantReexports ? + template.statement` Object.keys(NAMESPACE).forEach(function(key) { if (key === "default" || key === "__esModule") return; VERIFY_NAME_LIST; @@ -277,13 +278,14 @@ function buildNamespaceReexport(metadata, namespace, constantReexports) { EXPORTS[key] = NAMESPACE[key]; }); ` - : // Also skip already assigned bindings if they are strictly equal - // to be somewhat more spec-compliant when a file has multiple - // namespace re-exports that would cause a binding to be exported - // multiple times. However, multiple bindings of the same name that - // export the same primitive value are silently skipped - // (the spec requires an "ambigous bindings" early error here). - template.statement` + : ( + // Also skip already assigned bindings if they are strictly equal + // to be somewhat more spec-compliant when a file has multiple + // namespace re-exports that would cause a binding to be exported + // multiple times. However, multiple bindings of the same name that + // export the same primitive value are silently skipped + // (the spec requires an "ambigous bindings" early error here). + template.statement` Object.keys(NAMESPACE).forEach(function(key) { if (key === "default" || key === "__esModule") return; VERIFY_NAME_LIST; @@ -297,11 +299,12 @@ function buildNamespaceReexport(metadata, namespace, constantReexports) { }); }); ` - )({ + ))({ NAMESPACE: namespace, EXPORTS: metadata.exportName, - VERIFY_NAME_LIST: metadata.exportNameListName - ? template` + VERIFY_NAME_LIST: + metadata.exportNameListName ? + template` if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return; `({ EXPORTS_LIST: metadata.exportNameListName }) : null, diff --git ORI/babel/packages/babel-helper-optimise-call-expression/test/index.js ALT/babel/packages/babel-helper-optimise-call-expression/test/index.js index a98d91d0..1e2ac4ab 100644 --- ORI/babel/packages/babel-helper-optimise-call-expression/test/index.js +++ ALT/babel/packages/babel-helper-optimise-call-expression/test/index.js @@ -9,9 +9,8 @@ function transformInput(input, thisIdentifier) { return generator( optimizeCallExpression( callExpression.callee, - thisIdentifier - ? t.identifier(thisIdentifier) - : callExpression.callee.object, + thisIdentifier ? t.identifier(thisIdentifier) + : callExpression.callee.object, callExpression.arguments, callExpression.type === "OptionalCallExpression", ), diff --git ORI/babel/packages/babel-helper-remap-async-to-generator/src/index.js ALT/babel/packages/babel-helper-remap-async-to-generator/src/index.js index 282d3212..8ee41fa7 100644 --- ORI/babel/packages/babel-helper-remap-async-to-generator/src/index.js +++ ALT/babel/packages/babel-helper-remap-async-to-generator/src/index.js @@ -20,9 +20,8 @@ const awaitVisitor = { path.replaceWith( t.yieldExpression( - wrapAwait - ? t.callExpression(t.cloneNode(wrapAwait), [argument.node]) - : argument.node, + wrapAwait ? t.callExpression(t.cloneNode(wrapAwait), [argument.node]) + : argument.node, ), ); }, diff --git ORI/babel/packages/babel-helper-wrap-function/src/index.js ALT/babel/packages/babel-helper-wrap-function/src/index.js index 59f47780..2d2cb8fd 100644 --- ORI/babel/packages/babel-helper-wrap-function/src/index.js +++ ALT/babel/packages/babel-helper-wrap-function/src/index.js @@ -61,10 +61,9 @@ function plainFunction(path: NodePath, callId: Object, noNewArrows: boolean) { const node = path.node; const isDeclaration = path.isFunctionDeclaration(); const functionId = node.id; - const wrapper = isDeclaration - ? buildDeclarationWrapper - : functionId - ? buildNamedExpressionWrapper + const wrapper = + isDeclaration ? buildDeclarationWrapper + : functionId ? buildNamedExpressionWrapper : buildAnonymousExpressionWrapper; if (path.isArrowFunctionExpression()) { diff --git ORI/babel/packages/babel-parser/src/parser/expression.js ALT/babel/packages/babel-parser/src/parser/expression.js index e976098f..c999516e 100644 --- ORI/babel/packages/babel-parser/src/parser/expression.js +++ ALT/babel/packages/babel-parser/src/parser/expression.js @@ -558,15 +558,14 @@ export default class ExpressionParser extends LValParser { const expr = this.parseUpdate(node, update, refExpressionErrors); if (isAwait) { - const startsExpr = this.hasPlugin("v8intrinsic") - ? this.state.type.startsExpr + const startsExpr = + this.hasPlugin("v8intrinsic") ? this.state.type.startsExpr : this.state.type.startsExpr && !this.match(tt.modulo); if (startsExpr && !this.isAmbiguousAwait()) { this.raiseOverwrite( startPos, - this.hasPlugin("topLevelAwait") - ? Errors.AwaitNotInAsyncContext - : Errors.AwaitNotInAsyncFunction, + this.hasPlugin("topLevelAwait") ? Errors.AwaitNotInAsyncContext + : Errors.AwaitNotInAsyncFunction, ); return this.parseAwait(startPos, startLoc); } @@ -701,9 +700,8 @@ export default class ExpressionParser extends LValParser { const computed = this.eat(tt.bracketL); node.object = base; node.computed = computed; - const property = computed - ? this.parseExpression() - : this.parseMaybePrivateName(true); + const property = + computed ? this.parseExpression() : this.parseMaybePrivateName(true); if (this.isPrivateName(property)) { if (node.object.type === "Super") { @@ -861,10 +859,11 @@ export default class ExpressionParser extends LValParser { this.raise( node.start, Errors.ImportCallArity, - this.hasPlugin("importAssertions") || - this.hasPlugin("moduleAttributes") - ? "one or two arguments" - : "one argument", + ( + this.hasPlugin("importAssertions") || + this.hasPlugin("moduleAttributes") + ) ? "one or two arguments" + : "one argument", ); } else { for (const arg of node.arguments) { @@ -1878,8 +1877,9 @@ export default class ExpressionParser extends LValParser { prop.shorthand = false; if (this.eat(tt.colon)) { - prop.value = isPattern - ? this.parseMaybeDefault(this.state.start, this.state.startLoc) + prop.value = + isPattern ? + this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors); return this.finishNode(prop, "ObjectProperty"); @@ -1961,12 +1961,13 @@ export default class ExpressionParser extends LValParser { this.state.inPropertyName = true; // We check if it's valid for it to be a private name when we push it. (prop: $FlowFixMe).key = - this.match(tt.num) || - this.match(tt.string) || - this.match(tt.bigint) || - this.match(tt.decimal) - ? this.parseExprAtom() - : this.parseMaybePrivateName(isPrivateNameAllowed); + ( + this.match(tt.num) || + this.match(tt.string) || + this.match(tt.bigint) || + this.match(tt.decimal) + ) ? this.parseExprAtom() + : this.parseMaybePrivateName(isPrivateNameAllowed); if (!this.isPrivateName(prop.key)) { // ClassPrivateProperty is never computed, so we don't assign in that case. @@ -2130,11 +2131,12 @@ export default class ExpressionParser extends LValParser { // This logic is here to align the error location with the ESTree plugin. const errorPos = // $FlowIgnore - (node.kind === "method" || node.kind === "constructor") && - // $FlowIgnore - !!node.key - ? node.key.end - : node.start; + ( + (node.kind === "method" || node.kind === "constructor") && + // $FlowIgnore + !!node.key + ) ? node.key.end + : node.start; this.raise(errorPos, Errors.IllegalLanguageModeDirective); } @@ -2370,10 +2372,9 @@ export default class ExpressionParser extends LValParser { return; } - const reservedTest = !this.state.strict - ? isReservedWord - : isBinding - ? isStrictBindReservedWord + const reservedTest = + !this.state.strict ? isReservedWord + : isBinding ? isStrictBindReservedWord : isStrictReservedWord; if (reservedTest(word, this.inModule)) { diff --git ORI/babel/packages/babel-parser/src/parser/lval.js ALT/babel/packages/babel-parser/src/parser/lval.js index 4da763b1..62bcfc45 100644 --- ORI/babel/packages/babel-parser/src/parser/lval.js +++ ALT/babel/packages/babel-parser/src/parser/lval.js @@ -26,9 +26,11 @@ import { ExpressionErrors } from "./util"; import { Errors } from "./error"; const unwrapParenthesizedExpression = (node: Node): Node => { - return node.type === "ParenthesizedExpression" - ? unwrapParenthesizedExpression(node.expression) - : node; + return ( + node.type === "ParenthesizedExpression" ? + unwrapParenthesizedExpression(node.expression) + : node + ); }; export default class LValParser extends NodeUtils { @@ -170,9 +172,8 @@ export default class LValParser extends NodeUtils { ) { if (prop.type === "ObjectMethod") { const error = - prop.kind === "get" || prop.kind === "set" - ? Errors.PatternHasAccessor - : Errors.PatternHasMethod; + prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor + : Errors.PatternHasMethod; /* eslint-disable @babel/development-internal/dry-error-messages */ this.raise(prop.key.start, error); @@ -408,15 +409,13 @@ export default class LValParser extends NodeUtils { // "Global" reserved words have already been checked by parseIdentifier, // unless they have been found in the id or parameters of a strict-mode // function in a sloppy context. - (strictModeChanged - ? isStrictBindReservedWord(name, this.inModule) - : isStrictBindOnlyReservedWord(name)) + (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) + : isStrictBindOnlyReservedWord(name)) ) { this.raise( expr.start, - bindingType === BIND_NONE - ? Errors.StrictEvalArguments - : Errors.StrictEvalArgumentsBinding, + bindingType === BIND_NONE ? Errors.StrictEvalArguments + : Errors.StrictEvalArgumentsBinding, name, ); } @@ -505,9 +504,8 @@ export default class LValParser extends NodeUtils { default: { this.raise( expr.start, - bindingType === BIND_NONE - ? Errors.InvalidLhs - : Errors.InvalidLhsBinding, + bindingType === BIND_NONE ? Errors.InvalidLhs + : Errors.InvalidLhsBinding, contextDescription, ); } diff --git ORI/babel/packages/babel-parser/src/parser/statement.js ALT/babel/packages/babel-parser/src/parser/statement.js index e8473742..961dae05 100644 --- ORI/babel/packages/babel-parser/src/parser/statement.js +++ ALT/babel/packages/babel-parser/src/parser/statement.js @@ -533,9 +533,8 @@ export default class StatementParser extends ExpressionParser { const init = this.parseExpression(true, refExpressionErrors); if (this.match(tt._in) || this.isContextual("of")) { this.toAssignable(init, /* isLHS */ true); - const description = this.isContextual("of") - ? "for-of statement" - : "for-in statement"; + const description = + this.isContextual("of") ? "for-of statement" : "for-in statement"; this.checkLVal(init, description); return this.parseForIn(node, init, awaitAt); } else { @@ -762,10 +761,9 @@ export default class StatementParser extends ExpressionParser { } } - const kind = this.state.type.isLoop - ? "loop" - : this.match(tt._switch) - ? "switch" + const kind = + this.state.type.isLoop ? "loop" + : this.match(tt._switch) ? "switch" : null; for (let i = this.state.labels.length - 1; i >= 0; i--) { const label = this.state.labels[i]; @@ -783,11 +781,10 @@ export default class StatementParser extends ExpressionParser { statementStart: this.state.start, }); node.body = this.parseStatement( - context - ? context.indexOf("label") === -1 - ? context + "label" - : context - : "label", + context ? + context.indexOf("label") === -1 ? context + "label" + : context + : "label", ); this.state.labels.pop(); @@ -975,9 +972,8 @@ export default class StatementParser extends ExpressionParser { } node.left = init; - node.right = isForIn - ? this.parseExpression() - : this.parseMaybeAssignAllowIn(); + node.right = + isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); this.expect(tt.parenR); node.body = @@ -1009,8 +1005,8 @@ export default class StatementParser extends ExpressionParser { const decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(tt.eq)) { - decl.init = isFor - ? this.parseMaybeAssignDisallowIn() + decl.init = + isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); } else { if ( @@ -1140,11 +1136,10 @@ export default class StatementParser extends ExpressionParser { // treatFunctionsAsVar). this.scope.declareName( node.id.name, - this.state.strict || node.generator || node.async - ? this.scope.treatFunctionsAsVar - ? BIND_VAR - : BIND_LEXICAL - : BIND_FUNCTION, + this.state.strict || node.generator || node.async ? + this.scope.treatFunctionsAsVar ? BIND_VAR + : BIND_LEXICAL + : BIND_FUNCTION, node.id.start, ); } @@ -1605,15 +1600,13 @@ export default class StatementParser extends ExpressionParser { classBody.body.push(node); const kind = - node.kind === "get" - ? node.static - ? CLASS_ELEMENT_STATIC_GETTER - : CLASS_ELEMENT_INSTANCE_GETTER - : node.kind === "set" - ? node.static - ? CLASS_ELEMENT_STATIC_SETTER - : CLASS_ELEMENT_INSTANCE_SETTER - : CLASS_ELEMENT_OTHER; + node.kind === "get" ? + node.static ? CLASS_ELEMENT_STATIC_GETTER + : CLASS_ELEMENT_INSTANCE_GETTER + : node.kind === "set" ? + node.static ? CLASS_ELEMENT_STATIC_SETTER + : CLASS_ELEMENT_INSTANCE_SETTER + : CLASS_ELEMENT_OTHER; this.classScope.declarePrivateName( this.getPrivateNameSV(node.key), kind, @@ -2043,9 +2036,8 @@ export default class StatementParser extends ExpressionParser { if (this.state.exportedIdentifiers.indexOf(name) > -1) { this.raise( node.start, - name === "default" - ? Errors.DuplicateDefaultExport - : Errors.DuplicateExport, + name === "default" ? Errors.DuplicateDefaultExport + : Errors.DuplicateExport, name, ); } @@ -2071,8 +2063,8 @@ export default class StatementParser extends ExpressionParser { const node = this.startNode(); node.local = this.parseModuleExportName(); - node.exported = this.eatContextual("as") - ? this.parseModuleExportName() + node.exported = + this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone(); nodes.push(this.finishNode(node, "ExportSpecifier")); } diff --git ORI/babel/packages/babel-parser/src/plugins/flow/index.js ALT/babel/packages/babel-parser/src/plugins/flow/index.js index 9dfa320e..895bbaf5 100644 --- ORI/babel/packages/babel-parser/src/plugins/flow/index.js +++ ALT/babel/packages/babel-parser/src/plugins/flow/index.js @@ -660,9 +660,8 @@ export default (superClass: Class): Class => this.raise( startLoc, - declaration - ? FlowErrors.AssignReservedType - : FlowErrors.UnexpectedReservedType, + declaration ? FlowErrors.AssignReservedType + : FlowErrors.UnexpectedReservedType, word, ); } @@ -858,9 +857,10 @@ export default (superClass: Class): Class => } flowParseObjectPropertyKey(): N.Expression { - return this.match(tt.num) || this.match(tt.string) - ? this.parseExprAtom() - : this.parseIdentifier(true); + return ( + this.match(tt.num) || this.match(tt.string) ? this.parseExprAtom() + : this.parseIdentifier(true) + ); } flowParseObjectTypeIndexer( @@ -1224,9 +1224,8 @@ export default (superClass: Class): Class => if (property.value.this) { this.raise( property.value.this.start, - property.kind === "get" - ? FlowErrors.GetterMayNotHaveThisParam - : FlowErrors.SetterMayNotHaveThisParam, + property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam + : FlowErrors.SetterMayNotHaveThisParam, ); } @@ -1663,9 +1662,10 @@ export default (superClass: Class): Class => while (this.eat(tt.bitwiseAND)) { node.types.push(this.flowParseAnonFunctionWithoutParens()); } - return node.types.length === 1 - ? type - : this.finishNode(node, "IntersectionTypeAnnotation"); + return ( + node.types.length === 1 ? type + : this.finishNode(node, "IntersectionTypeAnnotation") + ); } flowParseUnionType(): N.FlowTypeAnnotation { @@ -1676,9 +1676,10 @@ export default (superClass: Class): Class => while (this.eat(tt.bitwiseOR)) { node.types.push(this.flowParseIntersectionType()); } - return node.types.length === 1 - ? type - : this.finishNode(node, "UnionTypeAnnotation"); + return ( + node.types.length === 1 ? type + : this.finishNode(node, "UnionTypeAnnotation") + ); } flowParseType(): N.FlowTypeAnnotation { @@ -1713,8 +1714,8 @@ export default (superClass: Class): Class => flowParseTypeAnnotatableIdentifier( allowPrimitiveOverride?: boolean, ): N.Identifier { - const ident = allowPrimitiveOverride - ? this.parseIdentifier() + const ident = + allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); if (this.match(tt.colon)) { ident.typeAnnotation = this.flowParseTypeAnnotation(); @@ -1783,8 +1784,8 @@ export default (superClass: Class): Class => node.predicate, ] = this.flowParseTypeAndPredicateInitialiser(); - node.returnType = typeNode.typeAnnotation - ? this.finishNode(typeNode, "TypeAnnotation") + node.returnType = + typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; } @@ -2586,8 +2587,9 @@ export default (superClass: Class): Class => type: string, contextDescription: string, ): void { - specifier.local = hasTypeImportKind(node) - ? this.flowParseRestrictedIdentifier( + specifier.local = + hasTypeImportKind(node) ? + this.flowParseRestrictedIdentifier( /* liberal */ true, /* declaration */ true, ) @@ -2951,8 +2953,9 @@ export default (superClass: Class): Class => if (result.error) this.state = result.failState; // assign after it is clear it is an arrow - node.returnType = result.node.typeAnnotation - ? this.finishNode(result.node, "TypeAnnotation") + node.returnType = + result.node.typeAnnotation ? + this.finishNode(result.node, "TypeAnnotation") : null; } @@ -3293,9 +3296,9 @@ export default (superClass: Class): Class => ) { return this.raise( pos, - suppliedType === null - ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied - : FlowErrors.EnumInvalidExplicitType, + suppliedType === null ? + FlowErrors.EnumInvalidExplicitTypeUnknownSupplied + : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType, ); @@ -3383,9 +3386,8 @@ export default (superClass: Class): Class => flowEnumMemberRaw(): { id: N.Node, init: EnumMemberInit } { const pos = this.state.start; const id = this.parseIdentifier(true); - const init = this.eat(tt.eq) - ? this.flowEnumMemberInit() - : { type: "none", pos }; + const init = + this.eat(tt.eq) ? this.flowEnumMemberInit() : { type: "none", pos }; return { id, init }; } diff --git ORI/babel/packages/babel-parser/src/plugins/jsx/index.js ALT/babel/packages/babel-parser/src/plugins/jsx/index.js index f8b6a3dd..b36325a7 100644 --- ORI/babel/packages/babel-parser/src/plugins/jsx/index.js +++ ALT/babel/packages/babel-parser/src/plugins/jsx/index.js @@ -63,10 +63,12 @@ tt.jsxTagEnd.updateContext = function (prevType) { }; function isFragment(object: ?N.JSXElement): boolean { - return object - ? object.type === "JSXOpeningFragment" || + return ( + object ? + object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" - : false; + : false + ); } // Transforms JSX element name to string. @@ -532,9 +534,10 @@ export default (superClass: Class): Class => ); } - return isFragment(openingElement) - ? this.finishNode(node, "JSXFragment") - : this.finishNode(node, "JSXElement"); + return ( + isFragment(openingElement) ? this.finishNode(node, "JSXFragment") + : this.finishNode(node, "JSXElement") + ); } // Parses entire JSX element from current position. diff --git ORI/babel/packages/babel-parser/src/plugins/typescript/index.js ALT/babel/packages/babel-parser/src/plugins/typescript/index.js index a562e8cb..bac0afc8 100644 --- ORI/babel/packages/babel-parser/src/plugins/typescript/index.js +++ ALT/babel/packages/babel-parser/src/plugins/typescript/index.js @@ -849,10 +849,9 @@ export default (superClass: Class): Class => case tt.name: case tt._void: case tt._null: { - const type = this.match(tt._void) - ? "TSVoidKeyword" - : this.match(tt._null) - ? "TSNullKeyword" + const type = + this.match(tt._void) ? "TSVoidKeyword" + : this.match(tt._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value); if ( type !== undefined && @@ -888,9 +887,11 @@ export default (superClass: Class): Class => case tt._import: return this.tsParseImportType(); case tt.braceL: - return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) - ? this.tsParseMappedType() - : this.tsParseTypeLiteral(); + return ( + this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? + this.tsParseMappedType() + : this.tsParseTypeLiteral() + ); case tt.bracketL: return this.tsParseTupleType(); case tt.parenL: @@ -971,11 +972,11 @@ export default (superClass: Class): Class => const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw), ); - return operator - ? this.tsParseTypeOperator(operator) - : this.isContextual("infer") - ? this.tsParseInferType() - : this.tsParseArrayTypeOrHigher(); + return ( + operator ? this.tsParseTypeOperator(operator) + : this.isContextual("infer") ? this.tsParseInferType() + : this.tsParseArrayTypeOrHigher() + ); } tsParseUnionOrIntersectionType( @@ -1151,9 +1152,11 @@ export default (superClass: Class): Class => } tsTryParseTypeOrTypePredicateAnnotation(): ?N.TsTypeAnnotation { - return this.match(tt.colon) - ? this.tsParseTypeOrTypePredicateAnnotation(tt.colon) - : undefined; + return ( + this.match(tt.colon) ? + this.tsParseTypeOrTypePredicateAnnotation(tt.colon) + : undefined + ); } tsTryParseTypeAnnotation(): ?N.TsTypeAnnotation { @@ -1377,8 +1380,8 @@ export default (superClass: Class): Class => tsParseEnumMember(): N.TsEnumMember { const node: N.TsEnumMember = this.startNode(); // Computed property names are grammar errors in an enum, so accept just string literal or identifier. - node.id = this.match(tt.string) - ? this.parseExprAtom() + node.id = + this.match(tt.string) ? this.parseExprAtom() : this.parseIdentifier(/* liberal */ true); if (this.eat(tt.eq)) { node.initializer = this.parseMaybeAssignAllowIn(); @@ -1503,9 +1506,11 @@ export default (superClass: Class): Class => } tsParseModuleReference(): N.TsModuleReference { - return this.tsIsExternalModuleReference() - ? this.tsParseExternalModuleReference() - : this.tsParseEntityName(/* allowReservedWords */ false); + return ( + this.tsIsExternalModuleReference() ? + this.tsParseExternalModuleReference() + : this.tsParseEntityName(/* allowReservedWords */ false) + ); } tsParseExternalModuleReference(): N.TsExternalModuleReference { @@ -1842,11 +1847,9 @@ export default (superClass: Class): Class => } const bodilessType = - type === "FunctionDeclaration" - ? "TSDeclareFunction" - : type === "ClassMethod" - ? "TSDeclareMethod" - : undefined; + type === "FunctionDeclaration" ? "TSDeclareFunction" + : type === "ClassMethod" ? "TSDeclareMethod" + : undefined; if (bodilessType && !this.match(tt.braceL) && this.isLineTerminator()) { this.finishNode(node, bodilessType); return; @@ -2276,9 +2279,8 @@ export default (superClass: Class): Class => expr: N.Expression, ): N.Statement { const decl = - expr.type === "Identifier" - ? this.tsParseExpressionStatement(node, expr) - : undefined; + expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) + : undefined; return decl || super.parseExpressionStatement(node, expr); } @@ -2971,17 +2973,15 @@ export default (superClass: Class): Class => parseMethod(...args: any[]) { const method = super.parseMethod(...args); if (method.abstract) { - const hasBody = this.hasPlugin("estree") - ? !!method.value.body - : !!method.body; + const hasBody = + this.hasPlugin("estree") ? !!method.value.body : !!method.body; if (hasBody) { const { key } = method; this.raise( method.start, TSErrors.AbstractMethodHasImplementation, - key.type === "Identifier" - ? key.name - : `[${this.input.slice(key.start, key.end)}]`, + key.type === "Identifier" ? key.name + : `[${this.input.slice(key.start, key.end)}]`, ); } } diff --git ORI/babel/packages/babel-parser/src/tokenizer/index.js ALT/babel/packages/babel-parser/src/tokenizer/index.js index 7c119c7d..e0f91a8d 100644 --- ORI/babel/packages/babel-parser/src/tokenizer/index.js +++ ALT/babel/packages/babel-parser/src/tokenizer/index.js @@ -424,9 +424,9 @@ export default class Tokenizer extends ParserErrors { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") { throw this.raise( this.state.pos, - next === charCodes.leftCurlyBrace - ? Errors.RecordExpressionHashIncorrectStartSyntaxType - : Errors.TupleExpressionHashIncorrectStartSyntaxType, + next === charCodes.leftCurlyBrace ? + Errors.RecordExpressionHashIncorrectStartSyntaxType + : Errors.TupleExpressionHashIncorrectStartSyntaxType, ); } @@ -631,10 +631,11 @@ export default class Tokenizer extends ParserErrors { if (next === code) { size = - code === charCodes.greaterThan && - this.input.charCodeAt(this.state.pos + 2) === charCodes.greaterThan - ? 3 - : 2; + ( + code === charCodes.greaterThan && + this.input.charCodeAt(this.state.pos + 2) === charCodes.greaterThan + ) ? 3 + : 2; if (this.input.charCodeAt(this.state.pos + size) === charCodes.equalsTo) { this.finishOp(tt.assign, size + 1); return; @@ -671,9 +672,8 @@ export default class Tokenizer extends ParserErrors { if (next === charCodes.equalsTo) { this.finishOp( tt.equality, - this.input.charCodeAt(this.state.pos + 2) === charCodes.equalsTo - ? 3 - : 2, + this.input.charCodeAt(this.state.pos + 2) === charCodes.equalsTo ? 3 + : 2, ); return; } @@ -994,17 +994,13 @@ export default class Tokenizer extends ParserErrors { ): number | null { const start = this.state.pos; const forbiddenSiblings = - radix === 16 - ? forbiddenNumericSeparatorSiblings.hex - : forbiddenNumericSeparatorSiblings.decBinOct; + radix === 16 ? forbiddenNumericSeparatorSiblings.hex + : forbiddenNumericSeparatorSiblings.decBinOct; const allowedSiblings = - radix === 16 - ? allowedNumericSeparatorSiblings.hex - : radix === 10 - ? allowedNumericSeparatorSiblings.dec - : radix === 8 - ? allowedNumericSeparatorSiblings.oct - : allowedNumericSeparatorSiblings.bin; + radix === 16 ? allowedNumericSeparatorSiblings.hex + : radix === 10 ? allowedNumericSeparatorSiblings.dec + : radix === 8 ? allowedNumericSeparatorSiblings.oct + : allowedNumericSeparatorSiblings.bin; let invalid = false; let total = 0; diff --git ORI/babel/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js ALT/babel/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js index e19a7755..dba53296 100644 --- ORI/babel/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js +++ ALT/babel/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js @@ -34,10 +34,11 @@ const WARNING_CALLS = new WeakSet(); function applyEnsureOrdering(path) { // TODO: This should probably also hoist computed properties. const decorators = ( - path.isClass() - ? [path].concat(path.get("body.body")) - : path.get("properties") - ).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []); + path.isClass() ? [path].concat(path.get("body.body")) + : path.get("properties")).reduce( + (acc, prop) => acc.concat(prop.node.decorators || []), + [], + ); const identDecorators = decorators.filter( decorator => !t.isIdentifier(decorator.expression), @@ -128,22 +129,22 @@ function applyTargetDecorators(path, state, decoratedProps) { ); } - const property = t.isLiteral(node.key) - ? node.key - : t.stringLiteral(node.key.name); + const property = + t.isLiteral(node.key) ? node.key : t.stringLiteral(node.key.name); const target = - path.isClass() && !node.static - ? buildClassPrototype({ - CLASS_REF: name, - }).expression - : name; + path.isClass() && !node.static ? + buildClassPrototype({ + CLASS_REF: name, + }).expression + : name; if (t.isClassProperty(node, { static: false })) { const descriptor = path.scope.generateDeclaredUidIdentifier("descriptor"); - const initializer = node.value - ? t.functionExpression( + const initializer = + node.value ? + t.functionExpression( null, [], t.blockStatement([t.returnStatement(node.value)]), @@ -191,16 +192,21 @@ function applyTargetDecorators(path, state, decoratedProps) { t.cloneNode(target), t.cloneNode(property), t.arrayExpression(decorators.map(dec => t.cloneNode(dec.expression))), - t.isObjectProperty(node) || t.isClassProperty(node, { static: true }) - ? buildGetObjectInitializer({ - TEMP: path.scope.generateDeclaredUidIdentifier("init"), - TARGET: t.cloneNode(target), - PROPERTY: t.cloneNode(property), - }).expression - : buildGetDescriptor({ - TARGET: t.cloneNode(target), - PROPERTY: t.cloneNode(property), - }).expression, + ( + t.isObjectProperty(node) || + t.isClassProperty(node, { static: true }) + ) ? + buildGetObjectInitializer({ + TEMP: path.scope.generateDeclaredUidIdentifier("init"), + TARGET: t.cloneNode(target), + PROPERTY: t.cloneNode(property), + }).expression + : ( + buildGetDescriptor({ + TARGET: t.cloneNode(target), + PROPERTY: t.cloneNode(property), + }).expression + ), t.cloneNode(target), ]), ); @@ -221,9 +227,8 @@ function decoratedClassToExpression({ node, scope }) { return; } - const ref = node.id - ? t.cloneNode(node.id) - : scope.generateUidIdentifier("class"); + const ref = + node.id ? t.cloneNode(node.id) : scope.generateUidIdentifier("class"); return t.variableDeclaration("let", [ t.variableDeclarator(ref, t.toExpression(node)), diff --git ORI/babel/packages/babel-plugin-proposal-nullish-coalescing-operator/src/index.js ALT/babel/packages/babel-plugin-proposal-nullish-coalescing-operator/src/index.js index ae948bad..76268d08 100644 --- ORI/babel/packages/babel-plugin-proposal-nullish-coalescing-operator/src/index.js +++ ALT/babel/packages/babel-plugin-proposal-nullish-coalescing-operator/src/index.js @@ -39,17 +39,19 @@ export default declare((api, { loose = false }) => { t.conditionalExpression( // We cannot use `!= null` in spec mode because // `document.all == null` and `document.all` is not "nullish". - noDocumentAll - ? t.binaryExpression("!=", assignment, t.nullLiteral()) - : t.logicalExpression( - "&&", - t.binaryExpression("!==", assignment, t.nullLiteral()), - t.binaryExpression( - "!==", - t.cloneNode(ref), - scope.buildUndefinedNode(), - ), + noDocumentAll ? + t.binaryExpression("!=", assignment, t.nullLiteral()) + : ( + t.logicalExpression( + "&&", + t.binaryExpression("!==", assignment, t.nullLiteral()), + t.binaryExpression( + "!==", + t.cloneNode(ref), + scope.buildUndefinedNode(), ), + ) + ), t.cloneNode(ref), node.right, ), diff --git ORI/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js ALT/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js index 2f353271..dc5c983c 100644 --- ORI/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js +++ ALT/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js @@ -36,9 +36,11 @@ export default declare((api, opts) => { const setSpreadProperties = api.assumption("setSpreadProperties") ?? loose; function getExtendsHelper(file) { - return useBuiltIns - ? t.memberExpression(t.identifier("Object"), t.identifier("assign")) - : file.addHelper("extends"); + return ( + useBuiltIns ? + t.memberExpression(t.identifier("Object"), t.identifier("assign")) + : file.addHelper("extends") + ); } function hasRestElement(path) { diff --git ORI/babel/packages/babel-plugin-proposal-optional-chaining/src/transform.js ALT/babel/packages/babel-plugin-proposal-optional-chaining/src/transform.js index 656b4ea0..14f47839 100644 --- ORI/babel/packages/babel-plugin-proposal-optional-chaining/src/transform.js +++ ALT/babel/packages/babel-plugin-proposal-optional-chaining/src/transform.js @@ -31,9 +31,8 @@ function needsMemoize(path) { optionalPath.isOptionalCallExpression() ) { const { node } = optionalPath; - const childKey = optionalPath.isOptionalMemberExpression() - ? "object" - : "callee"; + const childKey = + optionalPath.isOptionalMemberExpression() ? "object" : "callee"; const childPath = skipTransparentExprWrappers(optionalPath.get(childKey)); if (node.optional) { return !scope.isStatic(childPath.node); @@ -192,10 +191,12 @@ export function transform( // `if (a?.b) {}` transformed to `if (a != null && a.b) {}` // we don't need to return `void 0` because the returned value will // eveutally cast to boolean. - const nonNullishCheck = noDocumentAll - ? ast`${t.cloneNode(check)} != null` - : ast` - ${t.cloneNode(check)} !== null && ${t.cloneNode(ref)} !== void 0`; + const nonNullishCheck = + noDocumentAll ? ast`${t.cloneNode(check)} != null` + : ( + ast` + ${t.cloneNode(check)} !== null && ${t.cloneNode(ref)} !== void 0` + ); replacementPath.replaceWith( t.logicalExpression("&&", nonNullishCheck, replacement), ); @@ -203,10 +204,12 @@ export function transform( replacementPath.get("right"), ); } else { - const nullishCheck = noDocumentAll - ? ast`${t.cloneNode(check)} == null` - : ast` - ${t.cloneNode(check)} === null || ${t.cloneNode(ref)} === void 0`; + const nullishCheck = + noDocumentAll ? ast`${t.cloneNode(check)} == null` + : ( + ast` + ${t.cloneNode(check)} === null || ${t.cloneNode(ref)} === void 0` + ); const returnValue = isDeleteOperation ? ast`true` : ast`void 0`; replacementPath.replaceWith( diff --git ORI/babel/packages/babel-plugin-proposal-pipeline-operator/src/fsharpVisitor.js ALT/babel/packages/babel-plugin-proposal-pipeline-operator/src/fsharpVisitor.js index f32f8e33..378f91f0 100644 --- ORI/babel/packages/babel-plugin-proposal-pipeline-operator/src/fsharpVisitor.js +++ ALT/babel/packages/babel-plugin-proposal-pipeline-operator/src/fsharpVisitor.js @@ -10,9 +10,9 @@ const fsharpVisitor = { const placeholder = scope.generateUidIdentifierBasedOnNode(left); const call = - right.type === "AwaitExpression" - ? t.awaitExpression(t.cloneNode(placeholder)) - : t.callExpression(right, [t.cloneNode(placeholder)]); + right.type === "AwaitExpression" ? + t.awaitExpression(t.cloneNode(placeholder)) + : t.callExpression(right, [t.cloneNode(placeholder)]); const sequence = buildOptimizedSequenceExpression({ assign: t.assignmentExpression("=", t.cloneNode(placeholder), left), call, diff --git ORI/babel/packages/babel-plugin-syntax-decorators/src/index.js ALT/babel/packages/babel-plugin-syntax-decorators/src/index.js index a825adfd..3240ce7c 100644 --- ORI/babel/packages/babel-plugin-syntax-decorators/src/index.js +++ ALT/babel/packages/babel-plugin-syntax-decorators/src/index.js @@ -34,9 +34,8 @@ export default declare((api, options) => { manipulateOptions(opts, parserOpts) { parserOpts.plugins.push( - legacy - ? "decorators-legacy" - : ["decorators", { decoratorsBeforeExport }], + legacy ? "decorators-legacy" + : ["decorators", { decoratorsBeforeExport }], ); }, }; diff --git ORI/babel/packages/babel-plugin-transform-classes/src/transformClass.js ALT/babel/packages/babel-plugin-transform-classes/src/transformClass.js index ea57e999..c40e6d6a 100644 --- ORI/babel/packages/babel-plugin-transform-classes/src/transformClass.js +++ ALT/babel/packages/babel-plugin-transform-classes/src/transformClass.js @@ -377,9 +377,9 @@ export default function transformClass( classState.file.addHelper("assertThisInitialized"), [thisRef()], ); - return returnArg - ? t.logicalExpression("||", returnArg, thisExpr) - : thisExpr; + return ( + returnArg ? t.logicalExpression("||", returnArg, thisExpr) : thisExpr + ); }; } else { wrapReturn = returnArg => @@ -423,9 +423,9 @@ export default function transformClass( const descKey = node.kind === "method" ? "value" : node.kind; const key = - t.isNumericLiteral(node.key) || t.isBigIntLiteral(node.key) - ? t.stringLiteral(String(node.key.value)) - : t.toComputedKey(node); + t.isNumericLiteral(node.key) || t.isBigIntLiteral(node.key) ? + t.stringLiteral(String(node.key.value)) + : t.toComputedKey(node); let fn = t.toExpression(node); @@ -640,8 +640,8 @@ export default function transformClass( setState({ classId: classState.node.id, // this is the name of the binding that will **always** reference the class we've constructed - classRef: classState.node.id - ? t.identifier(classState.node.id.name) + classRef: + classState.node.id ? t.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"), superName: classState.node.superClass, isDerived: !!classState.node.superClass, diff --git ORI/babel/packages/babel-plugin-transform-computed-properties/src/index.js ALT/babel/packages/babel-plugin-transform-computed-properties/src/index.js index 9fa5c5c9..9968dae6 100644 --- ORI/babel/packages/babel-plugin-transform-computed-properties/src/index.js +++ ALT/babel/packages/babel-plugin-transform-computed-properties/src/index.js @@ -7,9 +7,8 @@ export default declare((api, options) => { const setComputedProperties = api.assumption("setComputedProperties") ?? options.loose; - const pushComputedProps = setComputedProperties - ? pushComputedPropsLoose - : pushComputedPropsSpec; + const pushComputedProps = + setComputedProperties ? pushComputedPropsLoose : pushComputedPropsSpec; const buildMutatorMapAssign = template(` MUTATOR_MAP_REF[KEY] = MUTATOR_MAP_REF[KEY] || {}; @@ -52,9 +51,9 @@ export default declare((api, options) => { function pushMutatorDefine({ body, getMutatorId, scope }, prop) { let key = - !prop.computed && t.isIdentifier(prop.key) - ? t.stringLiteral(prop.key.name) - : prop.key; + !prop.computed && t.isIdentifier(prop.key) ? + t.stringLiteral(prop.key.name) + : prop.key; const maybeMemoise = scope.maybeGenerateMemoised(key); if (maybeMemoise) { diff --git ORI/babel/packages/babel-plugin-transform-destructuring/src/index.js ALT/babel/packages/babel-plugin-transform-destructuring/src/index.js index d42c2bfc..7a000a5b 100644 --- ORI/babel/packages/babel-plugin-transform-destructuring/src/index.js +++ ALT/babel/packages/babel-plugin-transform-destructuring/src/index.js @@ -13,9 +13,11 @@ export default declare((api, options) => { api.assumption("objectRestNoSymbols") ?? options.loose; function getExtendsHelper(file) { - return useBuiltIns - ? t.memberExpression(t.identifier("Object"), t.identifier("assign")) - : file.addHelper("extends"); + return ( + useBuiltIns ? + t.memberExpression(t.identifier("Object"), t.identifier("assign")) + : file.addHelper("extends") + ); } /** diff --git ORI/babel/packages/babel-plugin-transform-flow-comments/src/index.js ALT/babel/packages/babel-plugin-transform-flow-comments/src/index.js index db926052..afa63b94 100644 --- ORI/babel/packages/babel-plugin-transform-flow-comments/src/index.js +++ ALT/babel/packages/babel-plugin-transform-flow-comments/src/index.js @@ -7,9 +7,10 @@ export default declare(api => { api.assertVersion(7); function commentFromString(comment) { - return typeof comment === "string" - ? { type: "CommentBlock", value: comment } - : comment; + return ( + typeof comment === "string" ? { type: "CommentBlock", value: comment } + : comment + ); } function attachComment({ diff --git ORI/babel/packages/babel-plugin-transform-for-of/src/index.js ALT/babel/packages/babel-plugin-transform-for-of/src/index.js index 882ff9b8..b98d663f 100644 --- ORI/babel/packages/babel-plugin-transform-for-of/src/index.js +++ ALT/babel/packages/babel-plugin-transform-for-of/src/index.js @@ -134,17 +134,20 @@ export default declare((api, options) => { } `; - const builder = skipteratorClosing - ? { + const builder = + skipteratorClosing ? + { build: buildForOfNoIteratorClosing, helper: "createForOfIteratorHelperLoose", getContainer: nodes => nodes, } - : { + : ( + { build: buildForOf, helper: "createForOfIteratorHelper", getContainer: nodes => nodes[1].block.body, - }; + } + ); function _ForOfStatementArray(path) { const { node, scope } = path; @@ -233,9 +236,8 @@ export default declare((api, options) => { const nodes = builder.build({ CREATE_ITERATOR_HELPER: state.addHelper(builder.helper), ITERATOR_HELPER: scope.generateUidIdentifier("iterator"), - ARRAY_LIKE_IS_ITERABLE: arrayLikeIsIterable - ? t.booleanLiteral(true) - : null, + ARRAY_LIKE_IS_ITERABLE: + arrayLikeIsIterable ? t.booleanLiteral(true) : null, STEP_KEY: t.identifier(stepKey), OBJECT: node.right, BODY: node.body, diff --git ORI/babel/packages/babel-plugin-transform-for-of/src/no-helper-implementation.js ALT/babel/packages/babel-plugin-transform-for-of/src/no-helper-implementation.js index 2624f0bc..3be26259 100644 --- ORI/babel/packages/babel-plugin-transform-for-of/src/no-helper-implementation.js +++ ALT/babel/packages/babel-plugin-transform-for-of/src/no-helper-implementation.js @@ -5,9 +5,8 @@ import { template, types as t } from "@babel/core"; // TODO (Babel 8): Remove this code. export default function transformWithoutHelper(loose, path, state) { - const pushComputedProps = loose - ? pushComputedPropsLoose - : pushComputedPropsSpec; + const pushComputedProps = + loose ? pushComputedPropsLoose : pushComputedPropsSpec; const { node } = path; const build = pushComputedProps(path, state); diff --git ORI/babel/packages/babel-plugin-transform-modules-commonjs/src/index.js ALT/babel/packages/babel-plugin-transform-modules-commonjs/src/index.js index 0004c3c7..336a9567 100644 --- ORI/babel/packages/babel-plugin-transform-modules-commonjs/src/index.js +++ ALT/babel/packages/babel-plugin-transform-modules-commonjs/src/index.js @@ -180,10 +180,11 @@ export default declare((api, options) => { noInterop, lazy, esNamespaceOnly: - typeof state.filename === "string" && - /\.mjs$/.test(state.filename) - ? mjsStrictNamespace - : strictNamespace, + ( + typeof state.filename === "string" && + /\.mjs$/.test(state.filename) + ) ? mjsStrictNamespace + : strictNamespace, }, ); diff --git ORI/babel/packages/babel-plugin-transform-modules-systemjs/src/index.js ALT/babel/packages/babel-plugin-transform-modules-systemjs/src/index.js index 4dd75d81..b0a85abd 100644 --- ORI/babel/packages/babel-plugin-transform-modules-systemjs/src/index.js +++ ALT/babel/packages/babel-plugin-transform-modules-systemjs/src/index.js @@ -97,9 +97,8 @@ function constructExportCall( const exportValue = exportValues[i]; objectProperties.push( t.objectProperty( - stringSpecifiers.has(exportName) - ? t.stringLiteral(exportName) - : t.identifier(exportName), + stringSpecifiers.has(exportName) ? t.stringLiteral(exportName) + : t.identifier(exportName), exportValue, ), ); diff --git ORI/babel/packages/babel-plugin-transform-modules-umd/src/index.js ALT/babel/packages/babel-plugin-transform-modules-umd/src/index.js index 4b1d69b6..94126592 100644 --- ORI/babel/packages/babel-plugin-transform-modules-umd/src/index.js +++ ALT/babel/packages/babel-plugin-transform-modules-umd/src/index.js @@ -64,9 +64,8 @@ export default declare((api, options) => { filename, moduleName, ) { - const moduleNameOrBasename = moduleName - ? moduleName.value - : basename(filename, extname(filename)); + const moduleNameOrBasename = + moduleName ? moduleName.value : basename(filename, extname(filename)); let globalToAssign = t.memberExpression( t.identifier("global"), t.identifier(t.toIdentifier(moduleNameOrBasename)), diff --git ORI/babel/packages/babel-plugin-transform-react-jsx-source/src/index.js ALT/babel/packages/babel-plugin-transform-react-jsx-source/src/index.js index 0f5bee8a..98bed9f8 100644 --- ORI/babel/packages/babel-plugin-transform-react-jsx-source/src/index.js +++ ALT/babel/packages/babel-plugin-transform-react-jsx-source/src/index.js @@ -25,9 +25,8 @@ export default declare(api => { const fileLineLiteral = lineNumber != null ? t.numericLiteral(lineNumber) : t.nullLiteral(); const fileColumnLiteral = - column0Based != null - ? t.numericLiteral(column0Based + 1) - : t.nullLiteral(); + column0Based != null ? t.numericLiteral(column0Based + 1) + : t.nullLiteral(); const fileNameProperty = t.objectProperty( t.identifier("fileName"), fileNameIdentifier, diff --git ORI/babel/packages/babel-plugin-transform-react-jsx/src/create-plugin.js ALT/babel/packages/babel-plugin-transform-react-jsx/src/create-plugin.js index e7d257b6..1e5ff088 100644 --- ORI/babel/packages/babel-plugin-transform-react-jsx/src/create-plugin.js +++ ALT/babel/packages/babel-plugin-transform-react-jsx/src/create-plugin.js @@ -30,11 +30,9 @@ export default function createPlugin({ name, development }) { // TODO (Babel 8): It should throw if this option is used with the automatic runtime filter, - runtime: RUNTIME_DEFAULT = process.env.BABEL_8_BREAKING - ? "automatic" - : development - ? "automatic" - : "classic", + runtime: RUNTIME_DEFAULT = process.env.BABEL_8_BREAKING ? "automatic" + : development ? "automatic" + : "classic", importSource: IMPORT_SOURCE_DEFAULT = DEFAULT.importSource, pragma: PRAGMA_DEFAULT = DEFAULT.pragma, @@ -354,9 +352,9 @@ You can set \`throwIfNamespace: false\` to bypass this warning.`, } const value = convertAttributeValue( - attribute.node.name.name !== "key" - ? attribute.node.value || t.booleanLiteral(true) - : attribute.node.value, + attribute.node.name.name !== "key" ? + attribute.node.value || t.booleanLiteral(true) + : attribute.node.value, ); if (attribute.node.name.name === "key" && value === null) { @@ -610,8 +608,9 @@ You can set \`throwIfNamespace: false\` to bypass this warning.`, objs.unshift(t.objectExpression([])); } - const helper = useBuiltIns - ? t.memberExpression(t.identifier("Object"), t.identifier("assign")) + const helper = + useBuiltIns ? + t.memberExpression(t.identifier("Object"), t.identifier("assign")) : file.addHelper("extends"); // spread it @@ -639,11 +638,11 @@ You can set \`throwIfNamespace: false\` to bypass this warning.`, accumulateAttribute(props, attr); } - return props.length === 1 && t.isSpreadElement(props[0]) - ? props[0].argument - : props.length > 0 - ? t.objectExpression(props) - : t.nullLiteral(); + return ( + props.length === 1 && t.isSpreadElement(props[0]) ? props[0].argument + : props.length > 0 ? t.objectExpression(props) + : t.nullLiteral() + ); } }); diff --git ORI/babel/packages/babel-plugin-transform-runtime/scripts/build-dist.js ALT/babel/packages/babel-plugin-transform-runtime/scripts/build-dist.js index db052f50..18288fba 100644 --- ORI/babel/packages/babel-plugin-transform-runtime/scripts/build-dist.js +++ ALT/babel/packages/babel-plugin-transform-runtime/scripts/build-dist.js @@ -117,8 +117,8 @@ function writeHelperFile( { esm, corejs } ) { const fileName = `${helperName}.js`; - const filePath = esm - ? path.join("helpers", "esm", fileName) + const filePath = + esm ? path.join("helpers", "esm", fileName) : path.join("helpers", fileName); const fullPath = path.join(pkgDirname, filePath); diff --git ORI/babel/packages/babel-plugin-transform-runtime/src/index.js ALT/babel/packages/babel-plugin-transform-runtime/src/index.js index 1893b9d4..04fbbcda 100644 --- ORI/babel/packages/babel-plugin-transform-runtime/src/index.js +++ ALT/babel/packages/babel-plugin-transform-runtime/src/index.js @@ -139,10 +139,9 @@ export default declare((api, options, dirname) => { const injectCoreJS2 = corejsVersion === 2; const injectCoreJS3 = corejsVersion === 3; - const moduleName = injectCoreJS3 - ? "@babel/runtime-corejs3" - : injectCoreJS2 - ? "@babel/runtime-corejs2" + const moduleName = + injectCoreJS3 ? "@babel/runtime-corejs3" + : injectCoreJS2 ? "@babel/runtime-corejs2" : "@babel/runtime"; const HEADER_HELPERS = ["interopRequireWildcard", "interopRequireDefault"]; @@ -170,8 +169,9 @@ export default declare((api, options, dirname) => { return { name: "transform-runtime", - inherits: injectCoreJS2 - ? createCorejsPlgin( + inherits: + injectCoreJS2 ? + createCorejsPlgin( pluginCorejs2, { method: "usage-pure", @@ -186,8 +186,8 @@ export default declare((api, options, dirname) => { [pluginsCompat]: { useBabelRuntime: modulePath }, }), ) - : injectCoreJS3 - ? createCorejsPlgin( + : injectCoreJS3 ? + createCorejsPlgin( pluginCorejs3, { method: "usage-pure", @@ -200,10 +200,12 @@ export default declare((api, options, dirname) => { [pluginsCompat]: { useBabelRuntime: modulePath }, }), ) - : createRegeneratorPlugin({ + : ( + createRegeneratorPlugin({ method: "usage-pure", [pluginsCompat]: { useBabelRuntime: modulePath }, - }), + }) + ), pre(file) { if (!useRuntimeHelpers) return; @@ -228,9 +230,8 @@ export default declare((api, options, dirname) => { isInteropHelper && !isModule(file.path) ? 4 : undefined; const helpersDir = - esModules && file.path.node.sourceType === "module" - ? "helpers/esm" - : "helpers"; + esModules && file.path.node.sourceType === "module" ? "helpers/esm" + : "helpers"; return addDefaultImport( `${modulePath}/${helpersDir}/${name}`, diff --git ORI/babel/packages/babel-plugin-transform-template-literals/src/index.js ALT/babel/packages/babel-plugin-transform-template-literals/src/index.js index 5b588900..58fb5678 100644 --- ORI/babel/packages/babel-plugin-transform-template-literals/src/index.js +++ ALT/babel/packages/babel-plugin-transform-template-literals/src/index.js @@ -64,9 +64,8 @@ export default declare((api, options) => { for (const elem of (quasi.quasis: Array)) { const { raw, cooked } = elem.value; const value = - cooked == null - ? path.scope.buildUndefinedNode() - : t.stringLiteral(cooked); + cooked == null ? path.scope.buildUndefinedNode() + : t.stringLiteral(cooked); strings.push(value); raws.push(t.stringLiteral(raw)); diff --git ORI/babel/packages/babel-preset-env/src/index.js ALT/babel/packages/babel-preset-env/src/index.js index 5e3a9e5e..906ba845 100644 --- ORI/babel/packages/babel-preset-env/src/index.js +++ ALT/babel/packages/babel-preset-env/src/index.js @@ -95,9 +95,8 @@ const getPlugin = (pluginName: string) => { export const transformIncludesAndExcludes = (opts: Array): Object => { return opts.reduce( (result, opt) => { - const target = opt.match(/^(es|es6|es7|esnext|web)\./) - ? "builtIns" - : "plugins"; + const target = + opt.match(/^(es|es6|es7|esnext|web)\./) ? "builtIns" : "plugins"; result[target].add(opt); return result; }, @@ -332,12 +331,12 @@ option \`forceAllTransforms: true\` instead. ); } - const transformTargets = ( - process.env.BABEL_8_BREAKING - ? forceAllTransforms - : forceAllTransforms || hasUglifyTarget - ) - ? {} + const transformTargets = + ( + ( + process.env.BABEL_8_BREAKING ? forceAllTransforms + : forceAllTransforms || hasUglifyTarget) + ) ? {} : targets; const include = transformIncludesAndExcludes(optionsInclude); @@ -400,9 +399,12 @@ option \`forceAllTransforms: true\` instead. return [ getPlugin(pluginName), { - loose: loose - ? "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error" - : "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error", + loose: + loose ? + "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error" + : ( + "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error" + ), }, ]; } diff --git ORI/babel/packages/babel-preset-env/src/normalize-options.js ALT/babel/packages/babel-preset-env/src/normalize-options.js index 51b265a9..43105ea6 100644 --- ORI/babel/packages/babel-preset-env/src/normalize-options.js +++ ALT/babel/packages/babel-preset-env/src/normalize-options.js @@ -41,11 +41,11 @@ const getValidIncludesAndExcludes = ( new Set([ ...allPluginsList, ...(type === "exclude" ? modulePlugins : []), - ...(corejs - ? corejs == 2 - ? [...Object.keys(corejs2Polyfills), ...corejs2DefaultWebIncludes] - : Object.keys(corejs3Polyfills) - : []), + ...(corejs ? + corejs == 2 ? + [...Object.keys(corejs2Polyfills), ...corejs2DefaultWebIncludes] + : Object.keys(corejs3Polyfills) + : []), ]); const pluginToRegExp = (plugin: PluginListItem) => { diff --git ORI/babel/packages/babel-preset-react/src/index.js ALT/babel/packages/babel-preset-react/src/index.js index 4a7e904f..080ba067 100644 --- ORI/babel/packages/babel-preset-react/src/index.js +++ ALT/babel/packages/babel-preset-react/src/index.js @@ -58,25 +58,27 @@ export default declare((api, opts) => { plugins: [ [ development ? transformReactJSXDevelopment : transformReactJSX, - process.env.BABEL_8_BREAKING - ? { - importSource, - pragma, - pragmaFrag, - runtime, - throwIfNamespace, - pure, - } - : { - importSource, - pragma, - pragmaFrag, - runtime, - throwIfNamespace, - pure, - useBuiltIns: !!opts.useBuiltIns, - useSpread: opts.useSpread, - }, + process.env.BABEL_8_BREAKING ? + { + importSource, + pragma, + pragmaFrag, + runtime, + throwIfNamespace, + pure, + } + : ( + { + importSource, + pragma, + pragmaFrag, + runtime, + throwIfNamespace, + pure, + useBuiltIns: !!opts.useBuiltIns, + useSpread: opts.useSpread, + } + ), ], transformReactDisplayName, pure !== false && transformReactPure, diff --git ORI/babel/packages/babel-preset-typescript/src/index.js ALT/babel/packages/babel-preset-typescript/src/index.js index 94534d04..b2ac3978 100644 --- ORI/babel/packages/babel-preset-typescript/src/index.js +++ ALT/babel/packages/babel-preset-typescript/src/index.js @@ -14,31 +14,36 @@ export default declare((api, opts) => { onlyRemoveTypeImports, } = normalizeOptions(opts); - const pluginOptions = process.env.BABEL_8_BREAKING - ? isTSX => ({ + const pluginOptions = + process.env.BABEL_8_BREAKING ? + isTSX => ({ allowNamespaces, isTSX, jsxPragma, jsxPragmaFrag, onlyRemoveTypeImports, }) - : isTSX => ({ + : ( + isTSX => ({ allowDeclareFields: opts.allowDeclareFields, allowNamespaces, isTSX, jsxPragma, jsxPragmaFrag, onlyRemoveTypeImports, - }); + }) + ); return { - overrides: allExtensions - ? [ + overrides: + allExtensions ? + [ { plugins: [[transformTypeScript, pluginOptions(isTSX)]], }, ] - : [ + : ( + [ { // Only set 'test' if explicitly requested, since it requires that // Babel is being called` @@ -51,6 +56,7 @@ export default declare((api, opts) => { test: /\.tsx$/, plugins: [[transformTypeScript, pluginOptions(true)]], }, - ], + ] + ), }; }); diff --git ORI/babel/packages/babel-types/scripts/generators/asserts.js ALT/babel/packages/babel-types/scripts/generators/asserts.js index bdfd9485..cf204d05 100644 --- ORI/babel/packages/babel-types/scripts/generators/asserts.js +++ ALT/babel/packages/babel-types/scripts/generators/asserts.js @@ -2,9 +2,9 @@ import definitions from "../../lib/definitions/index.js"; function addAssertHelper(type) { const result = - definitions.NODE_FIELDS[type] || definitions.FLIPPED_ALIAS_KEYS[type] - ? `node is t.${type}` - : "boolean"; + definitions.NODE_FIELDS[type] || definitions.FLIPPED_ALIAS_KEYS[type] ? + `node is t.${type}` + : "boolean"; return `export function assert${type}(node: object | null | undefined, opts?: object | null): asserts ${ result === "boolean" ? "node" : result diff --git ORI/babel/packages/babel-types/scripts/generators/builders.js ALT/babel/packages/babel-types/scripts/generators/builders.js index 3a30e605..cf477533 100644 --- ORI/babel/packages/babel-types/scripts/generators/builders.js +++ ALT/babel/packages/babel-types/scripts/generators/builders.js @@ -72,9 +72,10 @@ function generateBuilderArgs(type) { } export default function generateBuilders(kind) { - return kind === "uppercase.js" - ? generateUppercaseBuilders() - : generateLowercaseBuilders(); + return ( + kind === "uppercase.js" ? generateUppercaseBuilders() + : generateLowercaseBuilders() + ); } function generateLowercaseBuilders() { @@ -93,8 +94,8 @@ import type * as t from "../.."; Object.keys(definitions.BUILDER_KEYS).forEach(type => { const defArgs = generateBuilderArgs(type); const formatedBuilderName = formatBuilderName(type); - const formatedBuilderNameLocal = reservedNames.has(formatedBuilderName) - ? `_${formatedBuilderName}` + const formatedBuilderNameLocal = + reservedNames.has(formatedBuilderName) ? `_${formatedBuilderName}` : formatedBuilderName; output += `${ formatedBuilderNameLocal === formatedBuilderName ? "export " : "" diff --git ORI/babel/packages/babel-types/scripts/generators/typescript-legacy.js ALT/babel/packages/babel-types/scripts/generators/typescript-legacy.js index 40da48f4..23318891 100644 --- ORI/babel/packages/babel-types/scripts/generators/typescript-legacy.js +++ ALT/babel/packages/babel-types/scripts/generators/typescript-legacy.js @@ -123,9 +123,9 @@ for (const typeName of t.TYPES) { const realName = isDeprecated ? t.DEPRECATED_KEYS[typeName] : typeName; const result = - t.NODE_FIELDS[realName] || t.FLIPPED_ALIAS_KEYS[realName] - ? `node is ${realName}` - : "boolean"; + t.NODE_FIELDS[realName] || t.FLIPPED_ALIAS_KEYS[realName] ? + `node is ${realName}` + : "boolean"; if (isDeprecated) { lines.push(`/** @deprecated Use \`is${realName}\` */`); diff --git ORI/babel/packages/babel-types/scripts/generators/validators.js ALT/babel/packages/babel-types/scripts/generators/validators.js index acd6da65..1dd10da6 100644 --- ORI/babel/packages/babel-types/scripts/generators/validators.js +++ ALT/babel/packages/babel-types/scripts/generators/validators.js @@ -37,9 +37,9 @@ function addIsHelper(type, aliasKeys, deprecated) { } const result = - definitions.NODE_FIELDS[type] || definitions.FLIPPED_ALIAS_KEYS[type] - ? `node is t.${type}` - : "boolean"; + definitions.NODE_FIELDS[type] || definitions.FLIPPED_ALIAS_KEYS[type] ? + `node is t.${type}` + : "boolean"; return `export function is${type}(node: object | null | undefined, opts?: object | null): ${result} { ${deprecated || ""} ```
github-actions[bot] commented 3 years ago

rattrayalex/prettier@postfix-ternaries VS prettier/prettier@main :: vuejs/eslint-plugin-vue@62f577dcfcb859c24c6e0d4615ad880f5e1d4688

Diff (1836 lines) ```diff diff --git ORI/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js ALT/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js index 88cd9de..58a0950 100644 --- ORI/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js +++ ALT/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js @@ -127,9 +127,11 @@ function getRuleInfo(ast) { return currentExports }, {}) - return Object.prototype.hasOwnProperty.call(exportNodes, 'create') - ? Object.assign({ isNewStyle: !exportsIsFunction, meta: null }, exportNodes) + return ( + Object.prototype.hasOwnProperty.call(exportNodes, 'create') ? + Object.assign({ isNewStyle: !exportsIsFunction, meta: null }, exportNodes) : null + ) } // ----------------------------------------------------------------------------- @@ -167,9 +169,8 @@ module.exports = { const ruleName = filename === '' ? undefined : path.basename(filename, '.js') const expectedUrl = - !options.pattern || !ruleName - ? undefined - : options.pattern.replace(/{{\s*name\s*}}/g, ruleName) + !options.pattern || !ruleName ? undefined + : options.pattern.replace(/{{\s*name\s*}}/g, ruleName) /** * Check whether a given node is the expected URL. @@ -233,11 +234,12 @@ module.exports = { (metaNode && metaNode.loc) || node.loc.start, - message: !urlPropNode - ? 'Rules should export a `meta.docs.url` property.' - : !expectedUrl - ? '`meta.docs.url` property must be a string.' - : /* otherwise */ '`meta.docs.url` property must be `{{expectedUrl}}`.', + message: + !urlPropNode ? 'Rules should export a `meta.docs.url` property.' + : !expectedUrl ? '`meta.docs.url` property must be a string.' + : ( + /* otherwise */ '`meta.docs.url` property must be `{{expectedUrl}}`.' + ), data: { expectedUrl diff --git ORI/eslint-plugin-vue/lib/rules/attribute-hyphenation.js ALT/eslint-plugin-vue/lib/rules/attribute-hyphenation.js index cba9dc2..aeee490 100644 --- ORI/eslint-plugin-vue/lib/rules/attribute-hyphenation.js +++ ALT/eslint-plugin-vue/lib/rules/attribute-hyphenation.js @@ -71,8 +71,8 @@ module.exports = { context.report({ node: node.key, loc: node.loc, - message: useHyphenated - ? "Attribute '{{text}}' must be hyphenated." + message: + useHyphenated ? "Attribute '{{text}}' must be hyphenated." : "Attribute '{{text}}' can't be hyphenated.", data: { text @@ -105,10 +105,10 @@ module.exports = { VAttribute(node) { if (!utils.isCustomComponent(node.parent.parent)) return - const name = !node.directive - ? node.key.rawName - : node.key.name.name === 'bind' - ? node.key.argument && + const name = + !node.directive ? node.key.rawName + : node.key.name.name === 'bind' ? + node.key.argument && node.key.argument.type === 'VIdentifier' && node.key.argument.rawName : /* otherwise */ false diff --git ORI/eslint-plugin-vue/lib/rules/attributes-order.js ALT/eslint-plugin-vue/lib/rules/attributes-order.js index 5af387d..94bd873 100644 --- ORI/eslint-plugin-vue/lib/rules/attributes-order.js +++ ALT/eslint-plugin-vue/lib/rules/attributes-order.js @@ -69,9 +69,9 @@ function isVBindObject(node) { function getAttributeName(attribute, sourceCode) { if (attribute.directive) { if (isVBind(attribute)) { - return attribute.key.argument - ? sourceCode.getText(attribute.key.argument) - : '' + return ( + attribute.key.argument ? sourceCode.getText(attribute.key.argument) : '' + ) } else { return getDirectiveKeyName(attribute.key, sourceCode) } @@ -130,9 +130,9 @@ function getAttributeType(attribute) { } } propName = - attribute.key.argument && attribute.key.argument.type === 'VIdentifier' - ? attribute.key.argument.rawName - : '' + attribute.key.argument && attribute.key.argument.type === 'VIdentifier' ? + attribute.key.argument.rawName + : '' } else { propName = attribute.key.name } @@ -156,9 +156,10 @@ function getAttributeType(attribute) { */ function getPosition(attribute, attributePosition) { const attributeType = getAttributeType(attribute) - return attributePosition[attributeType] != null - ? attributePosition[attributeType] + return ( + attributePosition[attributeType] != null ? attributePosition[attributeType] : null + ) } /** diff --git ORI/eslint-plugin-vue/lib/rules/block-tag-newline.js ALT/eslint-plugin-vue/lib/rules/block-tag-newline.js index c88a36c..ae1a617 100644 --- ORI/eslint-plugin-vue/lib/rules/block-tag-newline.js +++ ALT/eslint-plugin-vue/lib/rules/block-tag-newline.js @@ -257,11 +257,9 @@ module.exports = { } const option = - options.multiline === options.singleline - ? options.singleline - : /[\n\r\u2028\u2029]/u.test(text.trim()) - ? options.multiline - : options.singleline + options.multiline === options.singleline ? options.singleline + : /[\n\r\u2028\u2029]/u.test(text.trim()) ? options.multiline + : options.singleline if (option === 'ignore') { return } @@ -336,9 +334,9 @@ module.exports = { singleline: elementsOptions.singleline || options.singleline, multiline: elementsOptions.multiline || options.multiline, maxEmptyLines: - elementsOptions.maxEmptyLines != null - ? elementsOptions.maxEmptyLines - : options.maxEmptyLines + elementsOptions.maxEmptyLines != null ? + elementsOptions.maxEmptyLines + : options.maxEmptyLines })(element) } } diff --git ORI/eslint-plugin-vue/lib/rules/comment-directive.js ALT/eslint-plugin-vue/lib/rules/comment-directive.js index 9ff9d2f..9f11fda 100644 --- ORI/eslint-plugin-vue/lib/rules/comment-directive.js +++ ALT/eslint-plugin-vue/lib/rules/comment-directive.js @@ -129,8 +129,9 @@ function processBlock(context, comment, reportUnusedDisableDirectives) { if (parsed != null) { if (parsed.type === 'eslint-disable') { if (parsed.rules.length) { - const rules = reportUnusedDisableDirectives - ? reportUnusedRules(context, comment, parsed.type, parsed.rules) + const rules = + reportUnusedDisableDirectives ? + reportUnusedRules(context, comment, parsed.type, parsed.rules) : parsed.rules for (const rule of rules) { disable( @@ -142,8 +143,9 @@ function processBlock(context, comment, reportUnusedDisableDirectives) { ) } } else { - const key = reportUnusedDisableDirectives - ? reportUnused(context, comment, parsed.type) + const key = + reportUnusedDisableDirectives ? + reportUnused(context, comment, parsed.type) : '' disable(context, comment.loc.start, 'block', null, key) } @@ -174,16 +176,18 @@ function processLine(context, comment, reportUnusedDisableDirectives) { comment.loc.start.line + (parsed.type === 'eslint-disable-line' ? 0 : 1) const column = -1 if (parsed.rules.length) { - const rules = reportUnusedDisableDirectives - ? reportUnusedRules(context, comment, parsed.type, parsed.rules) + const rules = + reportUnusedDisableDirectives ? + reportUnusedRules(context, comment, parsed.type, parsed.rules) : parsed.rules for (const rule of rules) { disable(context, { line, column }, 'line', rule.ruleId, rule.key || '') enable(context, { line: line + 1, column }, 'line', rule.ruleId) } } else { - const key = reportUnusedDisableDirectives - ? reportUnused(context, comment, parsed.type) + const key = + reportUnusedDisableDirectives ? + reportUnused(context, comment, parsed.type) : '' disable(context, { line, column }, 'line', null, key) enable(context, { line: line + 1, column }, 'line', null) diff --git ORI/eslint-plugin-vue/lib/rules/component-name-in-template-casing.js ALT/eslint-plugin-vue/lib/rules/component-name-in-template-casing.js index b2f60a6..a3d38fa 100644 --- ORI/eslint-plugin-vue/lib/rules/component-name-in-template-casing.js +++ ALT/eslint-plugin-vue/lib/rules/component-name-in-template-casing.js @@ -150,13 +150,13 @@ module.exports = { Program(node) { hasInvalidEOF = utils.hasInvalidEOF(node) }, - ...(registeredComponentsOnly - ? utils.executeOnVue(context, (obj) => { - registeredComponents.push( - ...utils.getRegisteredComponents(obj).map((n) => n.name) - ) - }) - : {}) + ...(registeredComponentsOnly ? + utils.executeOnVue(context, (obj) => { + registeredComponents.push( + ...utils.getRegisteredComponents(obj).map((n) => n.name) + ) + }) + : {}) } ) } diff --git ORI/eslint-plugin-vue/lib/rules/custom-event-name-casing.js ALT/eslint-plugin-vue/lib/rules/custom-event-name-casing.js index 39d9436..01a7c36 100644 --- ORI/eslint-plugin-vue/lib/rules/custom-event-name-casing.js +++ ALT/eslint-plugin-vue/lib/rules/custom-event-name-casing.js @@ -106,10 +106,10 @@ module.exports = { /** @type {Map,emitReferenceIds:Set}>} */ const setupContexts = new Map() const options = - context.options.length === 1 && typeof context.options[0] !== 'string' - ? // For backward compatibility - [undefined, context.options[0]] - : context.options + context.options.length === 1 && typeof context.options[0] !== 'string' ? + // For backward compatibility + [undefined, context.options[0]] + : context.options const caseType = options[0] || DEFAULT_CASE const objectOption = options[1] || {} const caseChecker = casing.getChecker(caseType) diff --git ORI/eslint-plugin-vue/lib/rules/html-closing-bracket-newline.js ALT/eslint-plugin-vue/lib/rules/html-closing-bracket-newline.js index 6963de8..d7564ff 100644 --- ORI/eslint-plugin-vue/lib/rules/html-closing-bracket-newline.js +++ ALT/eslint-plugin-vue/lib/rules/html-closing-bracket-newline.js @@ -81,9 +81,8 @@ module.exports = { const prevToken = template.getTokenBefore(closingBracketToken) const type = - node.loc.start.line === prevToken.loc.end.line - ? 'singleline' - : 'multiline' + node.loc.start.line === prevToken.loc.end.line ? 'singleline' + : 'multiline' const expectedLineBreaks = options[type] === 'always' ? 1 : 0 const actualLineBreaks = closingBracketToken.loc.start.line - prevToken.loc.end.line diff --git ORI/eslint-plugin-vue/lib/rules/html-comment-content-newline.js ALT/eslint-plugin-vue/lib/rules/html-comment-content-newline.js index 3985f7d..0b359de 100644 --- ORI/eslint-plugin-vue/lib/rules/html-comment-content-newline.js +++ ALT/eslint-plugin-vue/lib/rules/html-comment-content-newline.js @@ -102,12 +102,10 @@ module.exports = { return } - const startLine = openDecoration - ? openDecoration.loc.end.line - : value.loc.start.line - const endLine = closeDecoration - ? closeDecoration.loc.start.line - : value.loc.end.line + const startLine = + openDecoration ? openDecoration.loc.end.line : value.loc.start.line + const endLine = + closeDecoration ? closeDecoration.loc.start.line : value.loc.end.line const newlineType = startLine === endLine ? option.singleline : option.multiline if (newlineType === 'ignore') { @@ -141,11 +139,11 @@ module.exports = { start: beforeToken.loc.end, end: value.loc.start }, - messageId: openDecoration - ? 'expectedAfterExceptionBlock' + messageId: + openDecoration ? 'expectedAfterExceptionBlock' : 'expectedAfterHTMLCommentOpen', - fix: openDecoration - ? undefined + fix: + openDecoration ? undefined : (fixer) => fixer.insertTextAfter(beforeToken, '\n') }) } else { @@ -188,11 +186,11 @@ module.exports = { start: value.loc.end, end: afterToken.loc.start }, - messageId: closeDecoration - ? 'expectedBeforeExceptionBlock' + messageId: + closeDecoration ? 'expectedBeforeExceptionBlock' : 'expectedBeforeHTMLCommentOpen', - fix: closeDecoration - ? undefined + fix: + closeDecoration ? undefined : (fixer) => fixer.insertTextBefore(afterToken, '\n') }) } else { diff --git ORI/eslint-plugin-vue/lib/rules/html-comment-content-spacing.js ALT/eslint-plugin-vue/lib/rules/html-comment-content-spacing.js index b4f3167..bc1aa4b 100644 --- ORI/eslint-plugin-vue/lib/rules/html-comment-content-spacing.js +++ ALT/eslint-plugin-vue/lib/rules/html-comment-content-spacing.js @@ -94,11 +94,11 @@ module.exports = { start: beforeToken.loc.end, end: value.loc.start }, - messageId: openDecoration - ? 'expectedAfterExceptionBlock' + messageId: + openDecoration ? 'expectedAfterExceptionBlock' : 'expectedAfterHTMLCommentOpen', - fix: openDecoration - ? undefined + fix: + openDecoration ? undefined : (fixer) => fixer.insertTextAfter(beforeToken, ' ') }) } else { @@ -148,11 +148,11 @@ module.exports = { start: value.loc.end, end: afterToken.loc.start }, - messageId: closeDecoration - ? 'expectedBeforeExceptionBlock' + messageId: + closeDecoration ? 'expectedBeforeExceptionBlock' : 'expectedBeforeHTMLCommentOpen', - fix: closeDecoration - ? undefined + fix: + closeDecoration ? undefined : (fixer) => fixer.insertTextBefore(afterToken, ' ') }) } else { diff --git ORI/eslint-plugin-vue/lib/rules/html-comment-indent.js ALT/eslint-plugin-vue/lib/rules/html-comment-indent.js index d5992b5..019fc14 100644 --- ORI/eslint-plugin-vue/lib/rules/html-comment-indent.js +++ ALT/eslint-plugin-vue/lib/rules/html-comment-indent.js @@ -201,8 +201,8 @@ module.exports = { start: { line, column: 0 }, end: { line, column: actualIndentText.length } }, - messageId: actualIndentText - ? 'unexpectedBaseIndentation' + messageId: + actualIndentText ? 'unexpectedBaseIndentation' : 'missingBaseIndentation', data: { expected: toDisplay(baseIndentText), @@ -243,8 +243,8 @@ module.exports = { start: { line, column: baseIndentText.length }, end: { line, column: actualIndentText.length } }, - messageId: baseIndentText - ? 'unexpectedRelativeIndentation' + messageId: + baseIndentText ? 'unexpectedRelativeIndentation' : 'unexpectedIndentation', data: { expected: toDisplay(expectedOffsetIndentText, options.indentChar), diff --git ORI/eslint-plugin-vue/lib/rules/html-quotes.js ALT/eslint-plugin-vue/lib/rules/html-quotes.js index 9f741b2..5ebcf14 100644 --- ORI/eslint-plugin-vue/lib/rules/html-quotes.js +++ ALT/eslint-plugin-vue/lib/rules/html-quotes.js @@ -77,11 +77,10 @@ module.exports = { const contentText = quoted ? text.slice(1, -1) : text const fixToDouble = - avoidEscape && !quoted && contentText.includes(quoteChar) - ? double - ? contentText.includes("'") - : !contentText.includes('"') - : double + avoidEscape && !quoted && contentText.includes(quoteChar) ? + double ? contentText.includes("'") + : !contentText.includes('"') + : double const quotePattern = fixToDouble ? /"/g : /'/g const quoteEscaped = fixToDouble ? '"' : ''' diff --git ORI/eslint-plugin-vue/lib/rules/match-component-file-name.js ALT/eslint-plugin-vue/lib/rules/match-component-file-name.js index 8428516..966ae41 100644 --- ORI/eslint-plugin-vue/lib/rules/match-component-file-name.js +++ ALT/eslint-plugin-vue/lib/rules/match-component-file-name.js @@ -50,9 +50,8 @@ module.exports = { const options = context.options[0] const shouldMatchCase = (options && options.shouldMatchCase) || false const extensionsArray = options && options.extensions - const allowedExtensions = Array.isArray(extensionsArray) - ? extensionsArray - : ['jsx'] + const allowedExtensions = + Array.isArray(extensionsArray) ? extensionsArray : ['jsx'] const extension = path.extname(context.getFilename()) const filename = path.basename(context.getFilename(), extension) diff --git ORI/eslint-plugin-vue/lib/rules/max-len.js ALT/eslint-plugin-vue/lib/rules/max-len.js index 773b626..90e9e57 100644 --- ORI/eslint-plugin-vue/lib/rules/max-len.js +++ ALT/eslint-plugin-vue/lib/rules/max-len.js @@ -443,11 +443,9 @@ module.exports = { return } const maxLength = - inScript && inTemplate - ? Math.max(scriptMaxLength, templateMaxLength) - : inScript - ? scriptMaxLength - : templateMaxLength + inScript && inTemplate ? Math.max(scriptMaxLength, templateMaxLength) + : inScript ? scriptMaxLength + : templateMaxLength if ( (ignoreStrings && stringsByLine[lineNumber]) || diff --git ORI/eslint-plugin-vue/lib/rules/no-deprecated-events-api.js ALT/eslint-plugin-vue/lib/rules/no-deprecated-events-api.js index f393f59..ce7a838 100644 --- ORI/eslint-plugin-vue/lib/rules/no-deprecated-events-api.js +++ ALT/eslint-plugin-vue/lib/rules/no-deprecated-events-api.js @@ -37,9 +37,8 @@ module.exports = { node ) { const call = - node.parent.type === 'ChainExpression' - ? node.parent.parent - : node.parent + node.parent.type === 'ChainExpression' ? node.parent.parent + : node.parent if (call.optional) { // It is OK because checking whether it is deprecated. diff --git ORI/eslint-plugin-vue/lib/rules/no-dupe-v-else-if.js ALT/eslint-plugin-vue/lib/rules/no-dupe-v-else-if.js index 8e3a3de..10e5b41 100644 --- ORI/eslint-plugin-vue/lib/rules/no-dupe-v-else-if.js +++ ALT/eslint-plugin-vue/lib/rules/no-dupe-v-else-if.js @@ -147,9 +147,9 @@ module.exports = { } const test = node.value.expression const conditionsToCheck = - test.type === 'LogicalExpression' && test.operator === '&&' - ? [...splitByAnd(test), test] - : [test] + test.type === 'LogicalExpression' && test.operator === '&&' ? + [...splitByAnd(test), test] + : [test] const listToCheck = conditionsToCheck.map(buildOrOperands) /** @type {VElement | null} */ diff --git ORI/eslint-plugin-vue/lib/rules/no-extra-parens.js ALT/eslint-plugin-vue/lib/rules/no-extra-parens.js index 20c2593..461bd27 100644 --- ORI/eslint-plugin-vue/lib/rules/no-extra-parens.js +++ ALT/eslint-plugin-vue/lib/rules/no-extra-parens.js @@ -124,9 +124,9 @@ function createForVueSyntax(context) { } const expression = - node.expression.type === 'VFilterSequenceExpression' - ? node.expression.expression - : node.expression + node.expression.type === 'VFilterSequenceExpression' ? + node.expression.expression + : node.expression if (!isParenthesized(expression, tokenStore)) { return diff --git ORI/eslint-plugin-vue/lib/rules/no-irregular-whitespace.js ALT/eslint-plugin-vue/lib/rules/no-irregular-whitespace.js index 1cfbd61..a4f505d 100644 --- ORI/eslint-plugin-vue/lib/rules/no-irregular-whitespace.js +++ ALT/eslint-plugin-vue/lib/rules/no-irregular-whitespace.js @@ -195,28 +195,28 @@ module.exports = { return {} } const bodyVisitor = utils.defineTemplateBodyVisitor(context, { - ...(skipHTMLAttributeValues - ? { - 'VAttribute[directive=false] > VLiteral': - removeInvalidNodeErrorsInHTMLAttributeValue - } - : {}), - ...(skipHTMLTextContents - ? { VText: removeInvalidNodeErrorsInHTMLTextContent } - : {}), + ...(skipHTMLAttributeValues ? + { + 'VAttribute[directive=false] > VLiteral': + removeInvalidNodeErrorsInHTMLAttributeValue + } + : {}), + ...(skipHTMLTextContents ? + { VText: removeInvalidNodeErrorsInHTMLTextContent } + : {}), // inline scripts Literal: removeInvalidNodeErrorsInLiteral, - ...(skipTemplates - ? { TemplateElement: removeInvalidNodeErrorsInTemplateLiteral } - : {}) + ...(skipTemplates ? + { TemplateElement: removeInvalidNodeErrorsInTemplateLiteral } + : {}) }) return { ...bodyVisitor, Literal: removeInvalidNodeErrorsInLiteral, - ...(skipTemplates - ? { TemplateElement: removeInvalidNodeErrorsInTemplateLiteral } - : {}), + ...(skipTemplates ? + { TemplateElement: removeInvalidNodeErrorsInTemplateLiteral } + : {}), 'Program:exit'(node) { if (bodyVisitor['Program:exit']) { bodyVisitor['Program:exit'](node) @@ -232,9 +232,8 @@ module.exports = { // Removes errors that occur outside script and template const [scriptStart, scriptEnd] = node.range - const [templateStart, templateEnd] = templateBody - ? templateBody.range - : [0, 0] + const [templateStart, templateEnd] = + templateBody ? templateBody.range : [0, 0] errorIndexes = errorIndexes.filter( (errorIndex) => (scriptStart <= errorIndex && errorIndex < scriptEnd) || diff --git ORI/eslint-plugin-vue/lib/rules/no-parsing-error.js ALT/eslint-plugin-vue/lib/rules/no-parsing-error.js index 9a6b4f8..aec3593 100644 --- ORI/eslint-plugin-vue/lib/rules/no-parsing-error.js +++ ALT/eslint-plugin-vue/lib/rules/no-parsing-error.js @@ -99,8 +99,8 @@ module.exports = { loc: { line: error.lineNumber, column: error.column }, message: 'Parsing error: {{message}}.', data: { - message: error.message.endsWith('.') - ? error.message.slice(0, -1) + message: + error.message.endsWith('.') ? error.message.slice(0, -1) : error.message } }) diff --git ORI/eslint-plugin-vue/lib/rules/no-reserved-component-names.js ALT/eslint-plugin-vue/lib/rules/no-reserved-component-names.js index 890f1a3..08a51ce 100644 --- ORI/eslint-plugin-vue/lib/rules/no-reserved-component-names.js +++ ALT/eslint-plugin-vue/lib/rules/no-reserved-component-names.js @@ -146,12 +146,10 @@ module.exports = { function report(node, name) { context.report({ node, - messageId: RESERVED_NAMES_IN_HTML.has(name) - ? 'reservedInHtml' - : RESERVED_NAMES_IN_VUE.has(name) - ? 'reservedInVue' - : RESERVED_NAMES_IN_VUE3.has(name) - ? 'reservedInVue3' + messageId: + RESERVED_NAMES_IN_HTML.has(name) ? 'reservedInHtml' + : RESERVED_NAMES_IN_VUE.has(name) ? 'reservedInVue' + : RESERVED_NAMES_IN_VUE3.has(name) ? 'reservedInVue3' : 'reserved', data: { name diff --git ORI/eslint-plugin-vue/lib/rules/no-restricted-call-after-await.js ALT/eslint-plugin-vue/lib/rules/no-restricted-call-after-await.js index 6723d91..25870db 100644 --- ORI/eslint-plugin-vue/lib/rules/no-restricted-call-after-await.js +++ ALT/eslint-plugin-vue/lib/rules/no-restricted-call-after-await.js @@ -152,8 +152,8 @@ module.exports = { /** @type {TraceKind & TraceMap} */ const mod = traceMap[module] let local = mod - const paths = Array.isArray(option.path) - ? option.path + const paths = + Array.isArray(option.path) ? option.path : [option.path || 'default'] for (const path of paths) { local = local[path] || (local[path] = {}) diff --git ORI/eslint-plugin-vue/lib/rules/no-restricted-custom-event.js ALT/eslint-plugin-vue/lib/rules/no-restricted-custom-event.js index 19183e3..a031f95 100644 --- ORI/eslint-plugin-vue/lib/rules/no-restricted-custom-event.js +++ ALT/eslint-plugin-vue/lib/rules/no-restricted-custom-event.js @@ -146,8 +146,9 @@ module.exports = { node: nameLiteralNode, messageId: 'restrictedEvent', data: { message }, - suggest: option.suggest - ? [ + suggest: + option.suggest ? + [ { fix(fixer) { const sourceCode = context.getSourceCode() diff --git ORI/eslint-plugin-vue/lib/rules/no-restricted-props.js ALT/eslint-plugin-vue/lib/rules/no-restricted-props.js index 8a64913..61112be 100644 --- ORI/eslint-plugin-vue/lib/rules/no-restricted-props.js +++ ALT/eslint-plugin-vue/lib/rules/no-restricted-props.js @@ -130,8 +130,8 @@ function createSuggest(node, option) { if (node.type === 'Literal' || node.type === 'TemplateLiteral') { replaceText = JSON.stringify(option.suggest) } else if (node.type === 'Identifier') { - replaceText = /^[a-z]\w*$/iu.exec(option.suggest) - ? option.suggest + replaceText = + /^[a-z]\w*$/iu.exec(option.suggest) ? option.suggest : JSON.stringify(option.suggest) } else { return [] diff --git ORI/eslint-plugin-vue/lib/rules/no-restricted-static-attribute.js ALT/eslint-plugin-vue/lib/rules/no-restricted-static-attribute.js index 24cab62..27d72c2 100644 --- ORI/eslint-plugin-vue/lib/rules/no-restricted-static-attribute.js +++ ALT/eslint-plugin-vue/lib/rules/no-restricted-static-attribute.js @@ -148,10 +148,9 @@ module.exports = { */ function defaultMessage(node, option) { const key = node.key.rawName - const value = !option.useValue - ? '' - : node.value == null - ? '` set to `true' + const value = + !option.useValue ? '' + : node.value == null ? '` set to `true' : `="${node.value.value}"` let on = '' diff --git ORI/eslint-plugin-vue/lib/rules/no-restricted-v-bind.js ALT/eslint-plugin-vue/lib/rules/no-restricted-v-bind.js index d15bb4c..f7d62c8 100644 --- ORI/eslint-plugin-vue/lib/rules/no-restricted-v-bind.js +++ ALT/eslint-plugin-vue/lib/rules/no-restricted-v-bind.js @@ -138,8 +138,8 @@ module.exports = { create(context) { /** @type {ParsedOption[]} */ const options = ( - context.options.length === 0 ? DEFAULT_OPTIONS : context.options - ).map(parseOption) + context.options.length === 0 ? DEFAULT_OPTIONS + : context.options).map(parseOption) return utils.defineTemplateBodyVisitor(context, { /** @@ -167,12 +167,11 @@ module.exports = { function defaultMessage(key, option) { const vbind = key.name.rawName === ':' ? '' : 'v-bind' const arg = - key.argument != null && key.argument.type === 'VIdentifier' - ? `:${key.argument.rawName}` - : '' - const mod = option.modifiers.length - ? `.${option.modifiers.join('.')}` + key.argument != null && key.argument.type === 'VIdentifier' ? + `:${key.argument.rawName}` : '' + const mod = + option.modifiers.length ? `.${option.modifiers.join('.')}` : '' let on = '' if (option.useElement) { on = ` on \`<${key.parent.parent.parent.rawName}>\`` diff --git ORI/eslint-plugin-vue/lib/rules/no-template-shadow.js ALT/eslint-plugin-vue/lib/rules/no-template-shadow.js index 44f26cf..2d4997b 100644 --- ORI/eslint-plugin-vue/lib/rules/no-template-shadow.js +++ ALT/eslint-plugin-vue/lib/rules/no-template-shadow.js @@ -57,8 +57,9 @@ module.exports = { VElement(node) { scopeStack = { parent: scopeStack, - nodes: scopeStack - ? scopeStack.nodes.slice() // make copy + nodes: + scopeStack ? + scopeStack.nodes.slice() // make copy : [] } if (node.variables) { diff --git ORI/eslint-plugin-vue/lib/rules/no-unused-components.js ALT/eslint-plugin-vue/lib/rules/no-unused-components.js index e067e3e..15de5c8 100644 --- ORI/eslint-plugin-vue/lib/rules/no-unused-components.js +++ ALT/eslint-plugin-vue/lib/rules/no-unused-components.js @@ -41,9 +41,9 @@ module.exports = { create(context) { const options = context.options[0] || {} const ignoreWhenBindingPresent = - options.ignoreWhenBindingPresent !== undefined - ? options.ignoreWhenBindingPresent - : true + options.ignoreWhenBindingPresent !== undefined ? + options.ignoreWhenBindingPresent + : true const usedComponents = new Set() /** @type { { node: Property, name: string }[] } */ let registeredComponents = [] diff --git ORI/eslint-plugin-vue/lib/rules/no-unused-vars.js ALT/eslint-plugin-vue/lib/rules/no-unused-vars.js index a9939c1..9321e9e 100644 --- ORI/eslint-plugin-vue/lib/rules/no-unused-vars.js +++ ALT/eslint-plugin-vue/lib/rules/no-unused-vars.js @@ -125,19 +125,19 @@ module.exports = { name: variable.id.name }, suggest: - ignorePattern === '^_' - ? [ - { - desc: `Replace the ${variable.id.name} with _${variable.id.name}`, - fix(fixer) { - return fixer.replaceText( - variable.id, - `_${variable.id.name}` - ) - } + ignorePattern === '^_' ? + [ + { + desc: `Replace the ${variable.id.name} with _${variable.id.name}`, + fix(fixer) { + return fixer.replaceText( + variable.id, + `_${variable.id.name}` + ) } - ] - : [] + } + ] + : [] }) } } diff --git ORI/eslint-plugin-vue/lib/rules/no-use-v-if-with-v-for.js ALT/eslint-plugin-vue/lib/rules/no-use-v-if-with-v-for.js index 4790462..f2d6eea 100644 --- ORI/eslint-plugin-vue/lib/rules/no-use-v-if-with-v-for.js +++ ALT/eslint-plugin-vue/lib/rules/no-use-v-if-with-v-for.js @@ -96,13 +96,11 @@ module.exports = { "The '{{iteratorName}}' {{kind}} inside 'v-for' directive should be replaced with a computed property that returns filtered array instead. You should not mix 'v-for' with 'v-if'.", data: { iteratorName: - iteratorNode.type === 'Identifier' - ? iteratorNode.name - : context.getSourceCode().getText(iteratorNode), + iteratorNode.type === 'Identifier' ? iteratorNode.name + : context.getSourceCode().getText(iteratorNode), kind: - iteratorNode.type === 'Identifier' - ? 'variable' - : 'expression' + iteratorNode.type === 'Identifier' ? 'variable' + : 'expression' } }) } diff --git ORI/eslint-plugin-vue/lib/rules/order-in-components.js ALT/eslint-plugin-vue/lib/rules/order-in-components.js index 5f33734..a1fff31 100644 --- ORI/eslint-plugin-vue/lib/rules/order-in-components.js +++ ALT/eslint-plugin-vue/lib/rules/order-in-components.js @@ -311,13 +311,11 @@ module.exports = { const beforeComma = sourceCode.getTokenBefore(propertyNode) const codeStart = beforeComma.range[1] // to include comments - const codeEnd = hasAfterComma - ? afterComma.range[1] - : propertyNode.range[1] + const codeEnd = + hasAfterComma ? afterComma.range[1] : propertyNode.range[1] - const removeStart = hasAfterComma - ? codeStart - : beforeComma.range[0] + const removeStart = + hasAfterComma ? codeStart : beforeComma.range[0] yield fixer.removeRange([removeStart, codeEnd]) const propertyCode = diff --git ORI/eslint-plugin-vue/lib/rules/padding-line-between-blocks.js ALT/eslint-plugin-vue/lib/rules/padding-line-between-blocks.js index c1b6524..8932a2a 100644 --- ORI/eslint-plugin-vue/lib/rules/padding-line-between-blocks.js +++ ALT/eslint-plugin-vue/lib/rules/padding-line-between-blocks.js @@ -171,7 +171,9 @@ module.exports = { ), ...documentFragment.comments ].sort((a, b) => - a.range[0] > b.range[0] ? 1 : a.range[0] < b.range[0] ? -1 : 0 + a.range[0] > b.range[0] ? 1 + : a.range[0] < b.range[0] ? -1 + : 0 ) } diff --git ORI/eslint-plugin-vue/lib/rules/require-default-prop.js ALT/eslint-plugin-vue/lib/rules/require-default-prop.js index e0e29b6..e285601 100644 --- ORI/eslint-plugin-vue/lib/rules/require-default-prop.js +++ ALT/eslint-plugin-vue/lib/rules/require-default-prop.js @@ -173,9 +173,8 @@ module.exports = { for (const prop of propsToReport) { const propName = - prop.propName != null - ? prop.propName - : `[${context.getSourceCode().getText(prop.node.key)}]` + prop.propName != null ? prop.propName + : `[${context.getSourceCode().getText(prop.node.key)}]` context.report({ node: prop.node, diff --git ORI/eslint-plugin-vue/lib/rules/require-direct-export.js ALT/eslint-plugin-vue/lib/rules/require-direct-export.js index 18897eb..e5bd958 100644 --- ORI/eslint-plugin-vue/lib/rules/require-direct-export.js +++ ALT/eslint-plugin-vue/lib/rules/require-direct-export.js @@ -103,45 +103,46 @@ module.exports = { message: `Expected the component literal to be directly exported.` }) }, - ...(disallowFunctional - ? {} - : { - /** @param {BlockStatement} node */ - ':function > BlockStatement'(node) { - if (!maybeVue3Functional) { - return - } - scopeStack = { - upper: scopeStack, - withinVue3FunctionalBody: maybeVue3Functional.body === node - } - }, - /** @param {ReturnStatement} node */ - ReturnStatement(node) { - if ( - scopeStack && - scopeStack.withinVue3FunctionalBody && - node.argument - ) { - maybeVue3Functional.hasReturnArgument = true - } - }, - ':function > BlockStatement:exit'() { - scopeStack = scopeStack && scopeStack.upper - }, - /** @param {ExportDefaultDeclaration} node */ - 'ExportDefaultDeclaration:exit'(node) { - if (!maybeVue3Functional) { - return - } - if (!maybeVue3Functional.hasReturnArgument) { - context.report({ - node, - message: `Expected the component literal to be directly exported.` - }) - } + ...(disallowFunctional ? {} + : ( + { + /** @param {BlockStatement} node */ + ':function > BlockStatement'(node) { + if (!maybeVue3Functional) { + return + } + scopeStack = { + upper: scopeStack, + withinVue3FunctionalBody: maybeVue3Functional.body === node + } + }, + /** @param {ReturnStatement} node */ + ReturnStatement(node) { + if ( + scopeStack && + scopeStack.withinVue3FunctionalBody && + node.argument + ) { + maybeVue3Functional.hasReturnArgument = true } - }) + }, + ':function > BlockStatement:exit'() { + scopeStack = scopeStack && scopeStack.upper + }, + /** @param {ExportDefaultDeclaration} node */ + 'ExportDefaultDeclaration:exit'(node) { + if (!maybeVue3Functional) { + return + } + if (!maybeVue3Functional.hasReturnArgument) { + context.report({ + node, + message: `Expected the component literal to be directly exported.` + }) + } + } + } + )) } } } diff --git ORI/eslint-plugin-vue/lib/rules/require-explicit-emits.js ALT/eslint-plugin-vue/lib/rules/require-explicit-emits.js index 7974282..d57039d 100644 --- ORI/eslint-plugin-vue/lib/rules/require-explicit-emits.js +++ ALT/eslint-plugin-vue/lib/rules/require-explicit-emits.js @@ -221,9 +221,9 @@ module.exports = { const emitParam = emitProperty.value // `setup(props, {emit})` const variable = - emitParam.type === 'Identifier' - ? findVariable(context.getScope(), emitParam) - : null + emitParam.type === 'Identifier' ? + findVariable(context.getScope(), emitParam) + : null if (!variable) { return } @@ -458,9 +458,9 @@ function buildSuggest(object, emits, nameNode, context) { return fixer.insertTextAfter( objectLeftBrace, `\nemits: ['${nameNode.value}']${ - objectLeftBrace.loc.end.line < objectRightBrace.loc.start.line - ? '' - : '\n' + objectLeftBrace.loc.end.line < objectRightBrace.loc.start.line ? + '' + : '\n' }` ) } @@ -493,9 +493,9 @@ function buildSuggest(object, emits, nameNode, context) { return fixer.insertTextAfter( objectLeftBrace, `\nemits: {'${nameNode.value}': null}${ - objectLeftBrace.loc.end.line < objectRightBrace.loc.start.line - ? '' - : '\n' + objectLeftBrace.loc.end.line < objectRightBrace.loc.start.line ? + '' + : '\n' }` ) } diff --git ORI/eslint-plugin-vue/lib/rules/require-valid-default-prop.js ALT/eslint-plugin-vue/lib/rules/require-valid-default-prop.js index ef9453b..ca90dcd 100644 --- ORI/eslint-plugin-vue/lib/rules/require-valid-default-prop.js +++ ALT/eslint-plugin-vue/lib/rules/require-valid-default-prop.js @@ -198,9 +198,8 @@ module.exports = { */ function report(node, prop, expectedTypeNames) { const propName = - prop.propName != null - ? prop.propName - : `[${context.getSourceCode().getText(prop.node.key)}]` + prop.propName != null ? prop.propName + : `[${context.getSourceCode().getText(prop.node.key)}]` context.report({ node, message: diff --git ORI/eslint-plugin-vue/lib/rules/return-in-emits-validator.js ALT/eslint-plugin-vue/lib/rules/return-in-emits-validator.js index c4ced90..b558f92 100644 --- ORI/eslint-plugin-vue/lib/rules/return-in-emits-validator.js +++ ALT/eslint-plugin-vue/lib/rules/return-in-emits-validator.js @@ -123,9 +123,12 @@ module.exports = { if (emits) { context.report({ node, - message: scopeStack.hasReturnValue - ? 'Expected to return a true value in "{{name}}" emits validator.' - : 'Expected to return a boolean value in "{{name}}" emits validator.', + message: + scopeStack.hasReturnValue ? + 'Expected to return a true value in "{{name}}" emits validator.' + : ( + 'Expected to return a boolean value in "{{name}}" emits validator.' + ), data: { name: emits.emitName || 'Unknown' } diff --git ORI/eslint-plugin-vue/lib/rules/syntaxes/slot-attribute.js ALT/eslint-plugin-vue/lib/rules/syntaxes/slot-attribute.js index d5fa618..64d804d 100644 --- ORI/eslint-plugin-vue/lib/rules/syntaxes/slot-attribute.js +++ ALT/eslint-plugin-vue/lib/rules/syntaxes/slot-attribute.js @@ -68,15 +68,14 @@ module.exports = { (attr.key.name.name === 'slot-scope' || attr.key.name.name === 'scope') ) - const nameArgument = slotName - ? vBind - ? `:[${slotName}]` + const nameArgument = + slotName ? + vBind ? `:[${slotName}]` : `:${slotName}` : '' const scopeValue = - scopeAttr && scopeAttr.value - ? `=${sourceCode.getText(scopeAttr.value)}` - : '' + scopeAttr && scopeAttr.value ? `=${sourceCode.getText(scopeAttr.value)}` + : '' const replaceText = `v-slot${nameArgument}${scopeValue}` yield fixer.replaceText(slotAttr || scopeAttr, replaceText) diff --git ORI/eslint-plugin-vue/lib/rules/syntaxes/slot-scope-attribute.js ALT/eslint-plugin-vue/lib/rules/syntaxes/slot-scope-attribute.js index 902b5de..04fbff4 100644 --- ORI/eslint-plugin-vue/lib/rules/syntaxes/slot-scope-attribute.js +++ ALT/eslint-plugin-vue/lib/rules/syntaxes/slot-scope-attribute.js @@ -58,9 +58,8 @@ module.exports = { */ function fixSlotScopeToVSlot(fixer, scopeAttr) { const scopeValue = - scopeAttr && scopeAttr.value - ? `=${sourceCode.getText(scopeAttr.value)}` - : '' + scopeAttr && scopeAttr.value ? `=${sourceCode.getText(scopeAttr.value)}` + : '' const replaceText = `v-slot${scopeValue}` return fixer.replaceText(scopeAttr, replaceText) diff --git ORI/eslint-plugin-vue/lib/rules/this-in-template.js ALT/eslint-plugin-vue/lib/rules/this-in-template.js index 8ed4234..0e2ae75 100644 --- ORI/eslint-plugin-vue/lib/rules/this-in-template.js +++ ALT/eslint-plugin-vue/lib/rules/this-in-template.js @@ -53,8 +53,9 @@ module.exports = { VElement(node) { scopeStack = { parent: scopeStack, - nodes: scopeStack - ? scopeStack.nodes.slice() // make copy + nodes: + scopeStack ? + scopeStack.nodes.slice() // make copy : [] } if (node.variables) { @@ -71,58 +72,58 @@ module.exports = { 'VElement:exit'() { scopeStack = scopeStack && scopeStack.parent }, - ...(options === 'never' - ? { - /** @param { ThisExpression & { parent: MemberExpression } } node */ - 'VExpressionContainer MemberExpression > ThisExpression'(node) { - if (!scopeStack) { - return - } - const propertyName = utils.getStaticPropertyName(node.parent) - if ( - !propertyName || - scopeStack.nodes.some((el) => el.name === propertyName) || - RESERVED_NAMES.has(propertyName) || // this.class | this['class'] - /^[0-9].*$|[^a-zA-Z0-9_$]/.test(propertyName) // this['0aaaa'] | this['foo-bar bas'] - ) { - return - } - - context.report({ - node, - loc: node.loc, - message: "Unexpected usage of 'this'." - }) + ...(options === 'never' ? + { + /** @param { ThisExpression & { parent: MemberExpression } } node */ + 'VExpressionContainer MemberExpression > ThisExpression'(node) { + if (!scopeStack) { + return } + const propertyName = utils.getStaticPropertyName(node.parent) + if ( + !propertyName || + scopeStack.nodes.some((el) => el.name === propertyName) || + RESERVED_NAMES.has(propertyName) || // this.class | this['class'] + /^[0-9].*$|[^a-zA-Z0-9_$]/.test(propertyName) // this['0aaaa'] | this['foo-bar bas'] + ) { + return + } + + context.report({ + node, + loc: node.loc, + message: "Unexpected usage of 'this'." + }) } - : { - /** @param {VExpressionContainer} node */ - VExpressionContainer(node) { - if (!scopeStack) { - return - } - if (node.parent.type === 'VDirectiveKey') { - // We cannot use `.` in dynamic arguments because the right of the `.` becomes a modifier. - // For example, In `:[this.prop]` case, `:[this` is an argument and `prop]` is a modifier. - return - } - if (node.references) { - for (const reference of node.references) { - if ( - !scopeStack.nodes.some( - (el) => el.name === reference.id.name - ) - ) { - context.report({ - node: reference.id, - loc: reference.id.loc, - message: "Expected 'this'." - }) - } + } + : ( + { + /** @param {VExpressionContainer} node */ + VExpressionContainer(node) { + if (!scopeStack) { + return + } + if (node.parent.type === 'VDirectiveKey') { + // We cannot use `.` in dynamic arguments because the right of the `.` becomes a modifier. + // For example, In `:[this.prop]` case, `:[this` is an argument and `prop]` is a modifier. + return + } + if (node.references) { + for (const reference of node.references) { + if ( + !scopeStack.nodes.some((el) => el.name === reference.id.name) + ) { + context.report({ + node: reference.id, + loc: reference.id.loc, + message: "Expected 'this'." + }) } } } - }) + } + } + )) }) } } diff --git ORI/eslint-plugin-vue/lib/rules/use-v-on-exact.js ALT/eslint-plugin-vue/lib/rules/use-v-on-exact.js index 0a17906..2293865 100644 --- ORI/eslint-plugin-vue/lib/rules/use-v-on-exact.js +++ ALT/eslint-plugin-vue/lib/rules/use-v-on-exact.js @@ -38,9 +38,8 @@ const GLOBAL_MODIFIERS = new Set([ */ function getEventDirectives(startTag, sourceCode) { return utils.getDirectives(startTag, 'on').map((attribute) => ({ - name: attribute.key.argument - ? sourceCode.getText(attribute.key.argument) - : '', + name: + attribute.key.argument ? sourceCode.getText(attribute.key.argument) : '', node: attribute.key, modifiers: attribute.key.modifiers.map((modifier) => modifier.name) })) diff --git ORI/eslint-plugin-vue/lib/rules/v-bind-style.js ALT/eslint-plugin-vue/lib/rules/v-bind-style.js index e6878a3..e4c395e 100644 --- ORI/eslint-plugin-vue/lib/rules/v-bind-style.js +++ ALT/eslint-plugin-vue/lib/rules/v-bind-style.js @@ -44,10 +44,9 @@ module.exports = { context.report({ node, loc: node.loc, - message: preferShorthand - ? "Unexpected 'v-bind' before ':'." - : shorthandProp - ? "Expected 'v-bind:' instead of '.'." + message: + preferShorthand ? "Unexpected 'v-bind' before ':'." + : shorthandProp ? "Expected 'v-bind:' instead of '.'." : /* otherwise */ "Expected 'v-bind' before ':'.", *fix(fixer) { if (preferShorthand) { diff --git ORI/eslint-plugin-vue/lib/rules/v-for-delimiter-style.js ALT/eslint-plugin-vue/lib/rules/v-for-delimiter-style.js index a50b6a5..b5528b1 100644 --- ORI/eslint-plugin-vue/lib/rules/v-for-delimiter-style.js +++ ALT/eslint-plugin-vue/lib/rules/v-for-delimiter-style.js @@ -42,9 +42,8 @@ module.exports = { const delimiterToken = /** @type {Token} */ ( tokenStore.getTokenAfter( - node.left.length - ? node.left[node.left.length - 1] - : tokenStore.getFirstToken(node), + node.left.length ? node.left[node.left.length - 1] + : tokenStore.getFirstToken(node), (token) => token.type !== 'Punctuator' || token.value !== ')' ) ) diff --git ORI/eslint-plugin-vue/lib/rules/v-on-event-hyphenation.js ALT/eslint-plugin-vue/lib/rules/v-on-event-hyphenation.js index 60823e0..af5c056 100644 --- ORI/eslint-plugin-vue/lib/rules/v-on-event-hyphenation.js +++ ALT/eslint-plugin-vue/lib/rules/v-on-event-hyphenation.js @@ -65,14 +65,15 @@ module.exports = { context.report({ node: node.key, loc: node.loc, - message: useHyphenated - ? "v-on event '{{text}}' must be hyphenated." + message: + useHyphenated ? "v-on event '{{text}}' must be hyphenated." : "v-on event '{{text}}' can't be hyphenated.", data: { text }, - fix: autofix - ? (fixer) => + fix: + autofix ? + (fixer) => fixer.replaceText( node.key, text.replace(name, caseConverter(name)) diff --git ORI/eslint-plugin-vue/lib/rules/v-on-function-call.js ALT/eslint-plugin-vue/lib/rules/v-on-function-call.js index 90da5ed..f70a9cf 100644 --- ORI/eslint-plugin-vue/lib/rules/v-on-function-call.js +++ ALT/eslint-plugin-vue/lib/rules/v-on-function-call.js @@ -164,20 +164,23 @@ module.exports = { node: expression, message: "Method calls without arguments inside of 'v-on' directives must not have parentheses.", - fix: hasComment - ? null /* The comment is included and cannot be fixed. */ - : (fixer) => { + fix: + hasComment ? + null /* The comment is included and cannot be fixed. */ + : ( + (fixer) => { /** @type {Range} */ const range = - leftQuote && rightQuote - ? [leftQuote.range[1], rightQuote.range[0]] - : [tokens[0].range[0], tokens[tokens.length - 1].range[1]] + leftQuote && rightQuote ? + [leftQuote.range[1], rightQuote.range[0]] + : [tokens[0].range[0], tokens[tokens.length - 1].range[1]] return fixer.replaceTextRange( range, context.getSourceCode().getText(expression.callee) ) } + ) }) } }, diff --git ORI/eslint-plugin-vue/lib/rules/v-on-style.js ALT/eslint-plugin-vue/lib/rules/v-on-style.js index 4649aac..887b7a0 100644 --- ORI/eslint-plugin-vue/lib/rules/v-on-style.js +++ ALT/eslint-plugin-vue/lib/rules/v-on-style.js @@ -44,13 +44,12 @@ module.exports = { context.report({ node, loc: node.loc, - message: preferShorthand - ? "Expected '@' instead of 'v-on:'." + message: + preferShorthand ? "Expected '@' instead of 'v-on:'." : "Expected 'v-on:' instead of '@'.", fix: (fixer) => - preferShorthand - ? fixer.replaceTextRange([pos, pos + 5], '@') - : fixer.replaceTextRange([pos, pos + 1], 'v-on:') + preferShorthand ? fixer.replaceTextRange([pos, pos + 5], '@') + : fixer.replaceTextRange([pos, pos + 1], 'v-on:') }) } }) diff --git ORI/eslint-plugin-vue/lib/rules/valid-v-slot.js ALT/eslint-plugin-vue/lib/rules/valid-v-slot.js index 4914ede..dd383d2 100644 --- ORI/eslint-plugin-vue/lib/rules/valid-v-slot.js +++ ALT/eslint-plugin-vue/lib/rules/valid-v-slot.js @@ -69,9 +69,9 @@ function getSlotDirectivesOnChildren(node) { .groups.map((group) => group .map((childElement) => - childElement.name === 'template' - ? utils.getDirective(childElement, 'slot') - : null + childElement.name === 'template' ? + utils.getDirective(childElement, 'slot') + : null ) .filter(utils.isDef) ) @@ -88,9 +88,10 @@ function getNormalizedName(node, sourceCode) { if (node.key.argument == null) { return 'default' } - return node.key.modifiers.length === 0 - ? sourceCode.getText(node.key.argument) + return ( + node.key.modifiers.length === 0 ? sourceCode.getText(node.key.argument) : sourceCode.text.slice(node.key.argument.range[0], node.key.range[1]) + ) } /** @@ -266,9 +267,11 @@ function isUsingScopeVar(vSlot) { * @return {boolean} `true` if that argument node has invalid modifiers like `v-slot.foo`. */ function hasInvalidModifiers(vSlot, allowModifiers) { - return allowModifiers - ? vSlot.key.argument == null && vSlot.key.modifiers.length >= 1 + return ( + allowModifiers ? + vSlot.key.argument == null && vSlot.key.modifiers.length >= 1 : vSlot.key.modifiers.length >= 1 + ) } module.exports = { diff --git ORI/eslint-plugin-vue/lib/utils/html-comments.js ALT/eslint-plugin-vue/lib/utils/html-comments.js index aced46e..86cd966 100644 --- ORI/eslint-plugin-vue/lib/utils/html-comments.js +++ ALT/eslint-plugin-vue/lib/utils/html-comments.js @@ -180,18 +180,19 @@ function defineParser(sourceCode, config) { /** @type {HTMLCommentOpen} */ const open = createToken(TYPE_HTML_COMMENT_OPEN, '') diff --git ORI/eslint-plugin-vue/lib/utils/indent-common.js ALT/eslint-plugin-vue/lib/utils/indent-common.js index 5f1e236..8fd3ce4 100644 --- ORI/eslint-plugin-vue/lib/utils/indent-common.js +++ ALT/eslint-plugin-vue/lib/utils/indent-common.js @@ -1106,8 +1106,8 @@ module.exports.defineVisitor = function create( // Validate. for (const comment of comments) { const commentExpectedIndents = getExpectedIndents([comment]) - const commentExpectedIndent = commentExpectedIndents - ? commentExpectedIndents.expectedIndent + const commentExpectedIndent = + commentExpectedIndents ? commentExpectedIndents.expectedIndent : commentOptionalExpectedIndents[0] validateCore( @@ -1244,9 +1244,9 @@ module.exports.defineVisitor = function create( ) if (closeToken != null && closeToken.type.endsWith('TagClose')) { const offset = - closeToken.type !== 'HTMLSelfClosingTagClose' - ? options.closeBracket.startTag - : options.closeBracket.selfClosingTag + closeToken.type !== 'HTMLSelfClosingTagClose' ? + options.closeBracket.startTag + : options.closeBracket.selfClosingTag setOffset(closeToken, offset, openToken) } }, @@ -1422,8 +1422,8 @@ module.exports.defineVisitor = function create( const leftToken = tokenStore.getTokenAfter(whileToken) const testToken = tokenStore.getTokenAfter(leftToken) const lastToken = tokenStore.getLastToken(node) - const rightToken = isSemicolon(lastToken) - ? tokenStore.getTokenBefore(lastToken) + const rightToken = + isSemicolon(lastToken) ? tokenStore.getTokenBefore(lastToken) : lastToken processMaybeBlock(node.body, doToken) @@ -1564,12 +1564,10 @@ module.exports.defineVisitor = function create( setOffset(bodyToken, 0, tokenStore.getFirstToken(node.parent)) } else { // Normal functions. - const functionToken = node.async - ? tokenStore.getTokenAfter(firstToken) - : firstToken - const starToken = node.generator - ? tokenStore.getTokenAfter(functionToken) - : null + const functionToken = + node.async ? tokenStore.getTokenAfter(firstToken) : firstToken + const starToken = + node.generator ? tokenStore.getTokenAfter(functionToken) : null const idToken = node.id && tokenStore.getFirstToken(node.id) const leftToken = tokenStore.getTokenAfter( idToken || starToken || functionToken @@ -1800,8 +1798,9 @@ module.exports.defineVisitor = function create( const newToken = tokenStore.getFirstToken(node) const calleeToken = tokenStore.getTokenAfter(newToken) const rightToken = tokenStore.getLastToken(node) - const leftToken = isRightParen(rightToken) - ? tokenStore.getFirstTokenBetween(node.callee, rightToken, isLeftParen) + const leftToken = + isRightParen(rightToken) ? + tokenStore.getFirstTokenBetween(node.callee, rightToken, isLeftParen) : null setOffset(calleeToken, 1, newToken) @@ -2015,9 +2014,8 @@ module.exports.defineVisitor = function create( firstToken != null && firstToken.type === 'Punctuator' && firstToken.value === ' `, - parser: require.resolve('vue-eslint-parser'), - parserOptions: { - parser: require.resolve('@typescript-eslint/parser') - }, - errors: [ - { - message: - 'Boolean prop should not set a default (Vue defaults it to false).', - line: 7 - } - ] + parser: require.resolve('vue-eslint-parser'), + parserOptions: { + parser: require.resolve('@typescript-eslint/parser') }, - { - filename: 'test.vue', - code: ` + errors: [ + { + message: + 'Boolean prop should not set a default (Vue defaults it to false).', + line: 7 + } + ] + }, + { + filename: 'test.vue', + code: ` `, - parser: require.resolve('vue-eslint-parser'), - parserOptions: { - parser: require.resolve('@typescript-eslint/parser') - }, - options: ['default-false'], - errors: [ - { - message: 'Boolean prop should only be defaulted to false.', - line: 7 - } - ] - } - ]) + parser: require.resolve('vue-eslint-parser'), + parserOptions: { + parser: require.resolve('@typescript-eslint/parser') + }, + options: ['default-false'], + errors: [ + { + message: 'Boolean prop should only be defaulted to false.', + line: 7 + } + ] + } + ]) ] }) diff --git ORI/eslint-plugin-vue/tests/lib/rules/no-export-in-script-setup.js ALT/eslint-plugin-vue/tests/lib/rules/no-export-in-script-setup.js index 3ea9154..21fc268 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/no-export-in-script-setup.js +++ ALT/eslint-plugin-vue/tests/lib/rules/no-export-in-script-setup.js @@ -50,42 +50,44 @@ ruleTester.run('no-export-in-script-setup', rule, { ` }, - ...(semver.gte( - require('@typescript-eslint/parser/package.json').version, - '5.4.0' - ) && - semver.satisfies(require('typescript/package.json').version, '>=4.5.0-0') - ? [ - { - filename: 'test.vue', - code: ` + ...(( + semver.gte( + require('@typescript-eslint/parser/package.json').version, + '5.4.0' + ) && + semver.satisfies(require('typescript/package.json').version, '>=4.5.0-0') + ) ? + [ + { + filename: 'test.vue', + code: ` `, - parser: require.resolve('vue-eslint-parser'), - parserOptions: { - parser: require.resolve('@typescript-eslint/parser') - } + parser: require.resolve('vue-eslint-parser'), + parserOptions: { + parser: require.resolve('@typescript-eslint/parser') } - ] - : [ - { - filename: 'test.vue', - code: ` + } + ] + : [ + { + filename: 'test.vue', + code: ` `, - parser: require.resolve('vue-eslint-parser'), - parserOptions: { - parser: require.resolve('@typescript-eslint/parser') - } + parser: require.resolve('vue-eslint-parser'), + parserOptions: { + parser: require.resolve('@typescript-eslint/parser') } - ]) + } + ]) ], invalid: [ diff --git ORI/eslint-plugin-vue/tests/lib/rules/no-loss-of-precision.js ALT/eslint-plugin-vue/tests/lib/rules/no-loss-of-precision.js index 5608f8e..df409cd 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/no-loss-of-precision.js +++ ALT/eslint-plugin-vue/tests/lib/rules/no-loss-of-precision.js @@ -17,77 +17,77 @@ const tester = new RuleTester({ }) tester.run('no-loss-of-precision', rule, { valid: [ - ...(semver.gte(ESLint.version, '7.1.0') - ? [ - { - filename: 'test.vue', - code: ` + ...(semver.gte(ESLint.version, '7.1.0') ? + [ + { + filename: 'test.vue', + code: ` ` - }, - { - filename: 'test.vue', - code: ` + }, + { + filename: 'test.vue', + code: ` ` - } - ] - : []) + } + ] + : []) ], invalid: [ - ...(semver.gte(ESLint.version, '7.1.0') - ? [ - { - filename: 'test.vue', - code: ` + ...(semver.gte(ESLint.version, '7.1.0') ? + [ + { + filename: 'test.vue', + code: ` `, - errors: [ - { - message: 'This number literal will lose precision at runtime.', - line: 3 - }, - { - message: 'This number literal will lose precision at runtime.', - line: 4 - } - ] - }, - { - filename: 'test.vue', - code: ` + errors: [ + { + message: 'This number literal will lose precision at runtime.', + line: 3 + }, + { + message: 'This number literal will lose precision at runtime.', + line: 4 + } + ] + }, + { + filename: 'test.vue', + code: ` `, - errors: [ - { - message: 'This number literal will lose precision at runtime.', - line: 3 - } - ] - } - ] - : [ - { - filename: 'test.vue', - code: ` + errors: [ + { + message: 'This number literal will lose precision at runtime.', + line: 3 + } + ] + } + ] + : [ + { + filename: 'test.vue', + code: ` `, - errors: [ - 'Failed to extend ESLint core rule "no-loss-of-precision". You may be able to use this rule by upgrading the version of ESLint. If you cannot upgrade it, turn off this rule.' - ] - } - ]) + errors: [ + 'Failed to extend ESLint core rule "no-loss-of-precision". You may be able to use this rule by upgrading the version of ESLint. If you cannot upgrade it, turn off this rule.' + ] + } + ]) ] }) diff --git ORI/eslint-plugin-vue/tests/lib/rules/no-reserved-component-names.js ALT/eslint-plugin-vue/tests/lib/rules/no-reserved-component-names.js index cdb3ab7..5cb8b56 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/no-reserved-component-names.js +++ ALT/eslint-plugin-vue/tests/lib/rules/no-reserved-component-names.js @@ -586,8 +586,8 @@ ruleTester.run('no-reserved-component-names', rule, { parserOptions, errors: [ { - messageId: RESERVED_NAMES_IN_HTML.has(name) - ? 'reservedInHtml' + messageId: RESERVED_NAMES_IN_HTML.has(name) ? + 'reservedInHtml' : 'reserved', data: { name }, type: 'Literal', @@ -603,8 +603,8 @@ ruleTester.run('no-reserved-component-names', rule, { parserOptions, errors: [ { - messageId: RESERVED_NAMES_IN_HTML.has(name) - ? 'reservedInHtml' + messageId: RESERVED_NAMES_IN_HTML.has(name) ? + 'reservedInHtml' : 'reserved', data: { name }, type: 'Literal', @@ -620,8 +620,8 @@ ruleTester.run('no-reserved-component-names', rule, { parserOptions, errors: [ { - messageId: RESERVED_NAMES_IN_HTML.has(name) - ? 'reservedInHtml' + messageId: RESERVED_NAMES_IN_HTML.has(name) ? + 'reservedInHtml' : 'reserved', data: { name }, type: 'Literal', @@ -637,8 +637,8 @@ ruleTester.run('no-reserved-component-names', rule, { parserOptions, errors: [ { - messageId: RESERVED_NAMES_IN_HTML.has(name) - ? 'reservedInHtml' + messageId: RESERVED_NAMES_IN_HTML.has(name) ? + 'reservedInHtml' : 'reserved', data: { name }, type: 'TemplateLiteral', @@ -654,8 +654,8 @@ ruleTester.run('no-reserved-component-names', rule, { parserOptions, errors: [ { - messageId: RESERVED_NAMES_IN_HTML.has(name) - ? 'reservedInHtml' + messageId: RESERVED_NAMES_IN_HTML.has(name) ? + 'reservedInHtml' : 'reserved', data: { name }, type: 'TemplateLiteral', @@ -675,8 +675,8 @@ ruleTester.run('no-reserved-component-names', rule, { parserOptions, errors: [ { - messageId: RESERVED_NAMES_IN_HTML.has(name) - ? 'reservedInHtml' + messageId: RESERVED_NAMES_IN_HTML.has(name) ? + 'reservedInHtml' : 'reserved', data: { name }, type: 'Property', diff --git ORI/eslint-plugin-vue/tests/lib/rules/no-reserved-keys.js ALT/eslint-plugin-vue/tests/lib/rules/no-reserved-keys.js index b262ea4..abab93a 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/no-reserved-keys.js +++ ALT/eslint-plugin-vue/tests/lib/rules/no-reserved-keys.js @@ -300,15 +300,17 @@ ruleTester.run('no-reserved-keys', rule, { } ] }, - ...(semver.lt( - require('@typescript-eslint/parser/package.json').version, - '4.0.0' - ) - ? [] - : [ - { - filename: 'test.vue', - code: ` + ...(( + semver.lt( + require('@typescript-eslint/parser/package.json').version, + '4.0.0' + ) + ) ? + [] + : [ + { + filename: 'test.vue', + code: ` `, - parser: require.resolve('vue-eslint-parser'), - parserOptions: { - ecmaVersion: 6, - parser: require.resolve('@typescript-eslint/parser') - }, - errors: [ - { - message: "Key '$el' is reserved.", - line: 4 - } - ] + parser: require.resolve('vue-eslint-parser'), + parserOptions: { + ecmaVersion: 6, + parser: require.resolve('@typescript-eslint/parser') }, - { - filename: 'test.vue', - code: ` + errors: [ + { + message: "Key '$el' is reserved.", + line: 4 + } + ] + }, + { + filename: 'test.vue', + code: ` `, - parser: require.resolve('vue-eslint-parser'), - parserOptions: { - ecmaVersion: 6, - parser: require.resolve('@typescript-eslint/parser') - }, - errors: [ - { - message: "Key '$el' is reserved.", - line: 4 - } - ] - } - ]) + parser: require.resolve('vue-eslint-parser'), + parserOptions: { + ecmaVersion: 6, + parser: require.resolve('@typescript-eslint/parser') + }, + errors: [ + { + message: "Key '$el' is reserved.", + line: 4 + } + ] + } + ]) ] }) diff --git ORI/eslint-plugin-vue/tests/lib/rules/no-restricted-props.js ALT/eslint-plugin-vue/tests/lib/rules/no-restricted-props.js index 3348ca1..d691b22 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/no-restricted-props.js +++ ALT/eslint-plugin-vue/tests/lib/rules/no-restricted-props.js @@ -414,15 +414,17 @@ tester.run('no-restricted-props', rule, { } ] }, - ...(semver.lt( - require('@typescript-eslint/parser/package.json').version, - '4.0.0' - ) - ? [] - : [ - { - filename: 'test.vue', - code: ` + ...(( + semver.lt( + require('@typescript-eslint/parser/package.json').version, + '4.0.0' + ) + ) ? + [] + : [ + { + filename: 'test.vue', + code: ` `, - parserOptions: { - parser: require.resolve('@typescript-eslint/parser') - }, - options: [{ name: 'foo', suggest: 'Foo' }], - errors: [ - { - message: 'Using `foo` props is not allowed.', - line: 4, - suggestions: [ - { - desc: 'Instead, change to `Foo`.', - output: ` + parserOptions: { + parser: require.resolve('@typescript-eslint/parser') + }, + options: [{ name: 'foo', suggest: 'Foo' }], + errors: [ + { + message: 'Using `foo` props is not allowed.', + line: 4, + suggestions: [ + { + desc: 'Instead, change to `Foo`.', + output: ` ` - } - ] - } - ] - }, - { - filename: 'test.vue', - code: ` + } + ] + } + ] + }, + { + filename: 'test.vue', + code: ` `, - parserOptions: { - parser: require.resolve('@typescript-eslint/parser') - }, - options: [{ name: 'foo', suggest: 'Foo' }], - errors: [ - { - message: 'Using `foo` props is not allowed.', - line: 4, - suggestions: [ - { - desc: 'Instead, change to `Foo`.', - output: ` + parserOptions: { + parser: require.resolve('@typescript-eslint/parser') + }, + options: [{ name: 'foo', suggest: 'Foo' }], + errors: [ + { + message: 'Using `foo` props is not allowed.', + line: 4, + suggestions: [ + { + desc: 'Instead, change to `Foo`.', + output: ` ` - } - ] - } - ] - }, - { - filename: 'test.vue', - code: ` + } + ] + } + ] + }, + { + filename: 'test.vue', + code: ` @@ -513,18 +515,18 @@ tester.run('no-restricted-props', rule, { ) `, - parserOptions: { - parser: require.resolve('@typescript-eslint/parser') - }, - options: [{ name: 'foo', suggest: 'Foo' }], - errors: [ - { - message: 'Using `foo` props is not allowed.', - line: 7, - suggestions: [ - { - desc: 'Instead, change to `Foo`.', - output: ` + parserOptions: { + parser: require.resolve('@typescript-eslint/parser') + }, + options: [{ name: 'foo', suggest: 'Foo' }], + errors: [ + { + message: 'Using `foo` props is not allowed.', + line: 7, + suggestions: [ + { + desc: 'Instead, change to `Foo`.', + output: ` @@ -539,14 +541,14 @@ tester.run('no-restricted-props', rule, { ) ` - } - ] - } - ] - }, - { - filename: 'test.vue', - code: ` + } + ] + } + ] + }, + { + filename: 'test.vue', + code: ` `, - parserOptions: { - parser: require.resolve('@typescript-eslint/parser') - }, - options: [{ name: 'foo', suggest: 'Foo' }], - errors: [ - { - message: 'Using `foo` props is not allowed.', - line: 9, - suggestions: [ - { - desc: 'Instead, change to `Foo`.', - output: ` + parserOptions: { + parser: require.resolve('@typescript-eslint/parser') + }, + options: [{ name: 'foo', suggest: 'Foo' }], + errors: [ + { + message: 'Using `foo` props is not allowed.', + line: 9, + suggestions: [ + { + desc: 'Instead, change to `Foo`.', + output: ` ` - } - ] - } - ] - } - ]) + } + ] + } + ] + } + ]) ] }) diff --git ORI/eslint-plugin-vue/tests/lib/rules/prop-name-casing.js ALT/eslint-plugin-vue/tests/lib/rules/prop-name-casing.js index 4226e2d..dcf4877 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/prop-name-casing.js +++ ALT/eslint-plugin-vue/tests/lib/rules/prop-name-casing.js @@ -654,15 +654,17 @@ ruleTester.run('prop-name-casing', rule, { } ] }, - ...(semver.lt( - require('@typescript-eslint/parser/package.json').version, - '4.0.0' - ) - ? [] - : [ - { - filename: 'test.vue', - code: ` + ...(( + semver.lt( + require('@typescript-eslint/parser/package.json').version, + '4.0.0' + ) + ) ? + [] + : [ + { + filename: 'test.vue', + code: ` `, - parser: require.resolve('vue-eslint-parser'), - parserOptions: { - ...parserOptions, - parser: require.resolve('@typescript-eslint/parser') - }, - errors: [ - { - message: 'Prop "greeting_text" is not in camelCase.', - line: 4 - } - ] - } - ]) + parser: require.resolve('vue-eslint-parser'), + parserOptions: { + ...parserOptions, + parser: require.resolve('@typescript-eslint/parser') + }, + errors: [ + { + message: 'Prop "greeting_text" is not in camelCase.', + line: 4 + } + ] + } + ]) ] }) diff --git ORI/eslint-plugin-vue/tests/lib/rules/require-default-prop.js ALT/eslint-plugin-vue/tests/lib/rules/require-default-prop.js index e129ae8..2cf5250 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/require-default-prop.js +++ ALT/eslint-plugin-vue/tests/lib/rules/require-default-prop.js @@ -539,15 +539,17 @@ ruleTester.run('require-default-prop', rule, { } ] }, - ...(semver.lt( - require('@typescript-eslint/parser/package.json').version, - '4.0.0' - ) - ? [] - : [ - { - filename: 'test.vue', - code: ` + ...(( + semver.lt( + require('@typescript-eslint/parser/package.json').version, + '4.0.0' + ) + ) ? + [] + : [ + { + filename: 'test.vue', + code: ` `, - parser: require.resolve('vue-eslint-parser'), - parserOptions: { - ...parserOptions, - parser: require.resolve('@typescript-eslint/parser') - }, - errors: [ - { - message: "Prop 'foo' requires default value to be set.", - line: 4 - } - ] - } - ]) + parser: require.resolve('vue-eslint-parser'), + parserOptions: { + ...parserOptions, + parser: require.resolve('@typescript-eslint/parser') + }, + errors: [ + { + message: "Prop 'foo' requires default value to be set.", + line: 4 + } + ] + } + ]) ] }) diff --git ORI/eslint-plugin-vue/tests/lib/rules/script-indent.js ALT/eslint-plugin-vue/tests/lib/rules/script-indent.js index 229ea32..a1449df 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/script-indent.js +++ ALT/eslint-plugin-vue/tests/lib/rules/script-indent.js @@ -70,8 +70,8 @@ function loadPatterns(additionalValid, additionalInvalid) { }) const invalid = valid .map((pattern) => { - const kind = - (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space' + const kind = (pattern.options && pattern.options[0]) === 'tab' ? 'tab' + : 'space' const output = pattern.code const lines = output.split('\n').map((text, number) => ({ number, @@ -83,14 +83,13 @@ function loadPatterns(additionalValid, additionalInvalid) { .join('\n') const errors = lines .map((line) => - line.indentSize === 0 - ? null - : { - message: `Expected indentation of ${line.indentSize} ${kind}${ - line.indentSize === 1 ? '' : 's' - } but found 0 ${kind}s.`, - line: line.number + 1 - } + line.indentSize === 0 ? null + : { + message: `Expected indentation of ${line.indentSize} ${kind}${ + line.indentSize === 1 ? '' : 's' + } but found 0 ${kind}s.`, + line: line.number + 1 + } ) .filter(Boolean) diff --git ORI/eslint-plugin-vue/tests/lib/rules/space-in-parens.js ALT/eslint-plugin-vue/tests/lib/rules/space-in-parens.js index 8791652..ab5fbf6 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/space-in-parens.js +++ ALT/eslint-plugin-vue/tests/lib/rules/space-in-parens.js @@ -7,12 +7,12 @@ const { RuleTester, ESLint } = require('../../eslint-compat') const semver = require('semver') const rule = require('../../../lib/rules/space-in-parens') -const errorMessage = semver.lt(ESLint.version, '6.4.0') - ? (obj) => { +const errorMessage = semver.lt(ESLint.version, '6.4.0') ? + (obj) => { const messageId = obj.messageId delete obj.messageId - obj.message = messageId.startsWith('missing') - ? 'There must be a space inside this paren.' + obj.message = messageId.startsWith('missing') ? + 'There must be a space inside this paren.' : 'There should be no spaces inside this paren.' return obj } diff --git ORI/eslint-plugin-vue/tests/lib/rules/space-infix-ops.js ALT/eslint-plugin-vue/tests/lib/rules/space-infix-ops.js index b8a6797..d4d9d9d 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/space-infix-ops.js +++ ALT/eslint-plugin-vue/tests/lib/rules/space-infix-ops.js @@ -12,8 +12,8 @@ const tester = new RuleTester({ parserOptions: { ecmaVersion: 2015 } }) -const message = semver.lt(ESLint.version, '5.10.0') - ? () => 'Infix operators must be spaced.' +const message = semver.lt(ESLint.version, '5.10.0') ? + () => 'Infix operators must be spaced.' : (operator) => `Operator '${operator}' must be spaced.` tester.run('space-infix-ops', rule, { diff --git ORI/eslint-plugin-vue/tests/lib/rules/this-in-template.js ALT/eslint-plugin-vue/tests/lib/rules/this-in-template.js index 5d081f4..71821e4 100644 --- ORI/eslint-plugin-vue/tests/lib/rules/this-in-template.js +++ ALT/eslint-plugin-vue/tests/lib/rules/this-in-template.js @@ -199,22 +199,21 @@ function createInvalidTests(prefix, options, message, type) { // options // } ].concat( - options[0] === 'always' - ? [] - : [ - { - code: ``, - output: ``, - errors: [{ message, type }], - options - }, - { - code: ``, - output: ``, - errors: [{ message, type }], - options - } - ] + options[0] === 'always' ? [] + : [ + { + code: ``, + output: ``, + errors: [{ message, type }], + options + }, + { + code: ``, + output: ``, + errors: [{ message, type }], + options + } + ] ) } diff --git ORI/eslint-plugin-vue/tools/update-docs.js ALT/eslint-plugin-vue/tools/update-docs.js index 0985858..f6b0ec3 100644 --- ORI/eslint-plugin-vue/tools/update-docs.js +++ ALT/eslint-plugin-vue/tools/update-docs.js @@ -199,23 +199,23 @@ class DocFile { const { name, meta } = this.rule const footerPattern = /## (?::mag: Implementation|:rocket: Version).+$/s const footer = `${ - this.since - ? `## :rocket: Version + this.since ? + `## :rocket: Version This rule was introduced in eslint-plugin-vue ${this.since} ` - : '' + : '' }## :mag: Implementation - [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/${name}.js) - [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/${name}.js) ${ - meta.docs.extensionRule - ? ` + meta.docs.extensionRule ? + ` Taken with ❤️ [from ESLint core](${meta.docs.coreRuleUrl}) ` - : '' + : '' }` if (footerPattern.test(this.content)) { this.content = this.content.replace(footerPattern, footer) ```
github-actions[bot] commented 2 years ago

rattrayalex/prettier@postfix-ternaries VS prettier/prettier@main :: excalidraw/excalidraw@afa7932c9b25980534012b1ef85a6e9b5743b95c

Diff (3302 lines) ```diff diff --git ORI/excalidraw/src/actions/actionCanvas.tsx ALT/excalidraw/src/actions/actionCanvas.tsx index 7c3f9e2..19f2ebb 100644 --- ORI/excalidraw/src/actions/actionCanvas.tsx +++ ALT/excalidraw/src/actions/actionCanvas.tsx @@ -207,10 +207,9 @@ const zoomToFitElements = ( const nonDeletedElements = getNonDeletedElements(elements); const selectedElements = getSelectedElements(nonDeletedElements, appState); - const commonBounds = - zoomToSelection && selectedElements.length > 0 - ? getCommonBounds(selectedElements) - : getCommonBounds(nonDeletedElements); + const commonBounds = zoomToSelection && selectedElements.length > 0 ? + getCommonBounds(selectedElements) + : getCommonBounds(nonDeletedElements); const zoomValue = zoomValueToFitBoundsOnViewport(commonBounds, { width: appState.width, diff --git ORI/excalidraw/src/actions/actionClipboard.tsx ALT/excalidraw/src/actions/actionClipboard.tsx index aa0dbac..b20a384 100644 --- ORI/excalidraw/src/actions/actionClipboard.tsx +++ ALT/excalidraw/src/actions/actionClipboard.tsx @@ -46,9 +46,9 @@ export const actionCopyAsSvg = register({ try { await exportCanvas( "clipboard-svg", - selectedElements.length - ? selectedElements - : getNonDeletedElements(elements), + selectedElements.length ? + selectedElements + : getNonDeletedElements(elements), appState, app.files, appState, @@ -85,9 +85,9 @@ export const actionCopyAsPng = register({ try { await exportCanvas( "clipboard", - selectedElements.length - ? selectedElements - : getNonDeletedElements(elements), + selectedElements.length ? + selectedElements + : getNonDeletedElements(elements), appState, app.files, appState, @@ -96,11 +96,11 @@ export const actionCopyAsPng = register({ appState: { ...appState, toastMessage: t("toast.copyToClipboardAsPng", { - exportSelection: selectedElements.length - ? t("toast.selection") + exportSelection: selectedElements.length ? + t("toast.selection") : t("toast.canvas"), - exportColorScheme: appState.exportWithDarkMode - ? t("buttons.darkMode") + exportColorScheme: appState.exportWithDarkMode ? + t("buttons.darkMode") : t("buttons.lightMode"), }), }, diff --git ORI/excalidraw/src/actions/actionDeleteSelected.tsx ALT/excalidraw/src/actions/actionDeleteSelected.tsx index e38a4ed..33d4729 100644 --- ORI/excalidraw/src/actions/actionDeleteSelected.tsx +++ ALT/excalidraw/src/actions/actionDeleteSelected.tsx @@ -86,12 +86,10 @@ export const actionDeleteSelected = register({ // We cannot do this inside `movePoint` because it is also called // when deleting the uncommitted point (which hasn't caused any binding) const binding = { - startBindingElement: - activePointIndex === 0 ? null : startBindingElement, - endBindingElement: - activePointIndex === element.points.length - 1 - ? null - : endBindingElement, + startBindingElement: activePointIndex === 0 ? null + : startBindingElement, + endBindingElement: activePointIndex === element.points.length - 1 ? null + : endBindingElement, }; LinearElementEditor.movePoint(element, activePointIndex, "delete"); diff --git ORI/excalidraw/src/actions/actionDuplicateSelection.tsx ALT/excalidraw/src/actions/actionDuplicateSelection.tsx index 6d9cc5b..d4f3c35 100644 --- ORI/excalidraw/src/actions/actionDuplicateSelection.tsx +++ ALT/excalidraw/src/actions/actionDuplicateSelection.tsx @@ -35,12 +35,12 @@ export const actionDuplicateSelection = register({ mutateElement(element, { points: [ ...points.slice(0, activePointIndex + 1), - nextPoint - ? [ - (selectedPoint[0] + nextPoint[0]) / 2, - (selectedPoint[1] + nextPoint[1]) / 2, - ] - : [selectedPoint[0] + 30, selectedPoint[1] + 30], + nextPoint ? + [ + (selectedPoint[0] + nextPoint[0]) / 2, + (selectedPoint[1] + nextPoint[1]) / 2, + ] + : [selectedPoint[0] + 30, selectedPoint[1] + 30], ...points.slice(activePointIndex + 1), ], }); diff --git ORI/excalidraw/src/actions/actionExport.tsx ALT/excalidraw/src/actions/actionExport.tsx index 16f33f8..272a930 100644 --- ORI/excalidraw/src/actions/actionExport.tsx +++ ALT/excalidraw/src/actions/actionExport.tsx @@ -50,8 +50,8 @@ export const actionChangeExportScale = register({ PanelComponent: ({ elements: allElements, appState, updateData }) => { const elements = getNonDeletedElements(allElements); const exportSelected = isSomeElementSelected(elements, appState); - const exportedElements = exportSelected - ? getSelectedElements(elements, appState) + const exportedElements = exportSelected ? + getSelectedElements(elements, appState) : elements; return ( @@ -132,8 +132,8 @@ export const actionSaveToActiveFile = register({ const fileHandleExists = !!appState.fileHandle; try { - const { fileHandle } = isImageFileHandle(appState.fileHandle) - ? await resaveAsImageWithScene(elements, appState, app.files) + const { fileHandle } = isImageFileHandle(appState.fileHandle) ? + await resaveAsImageWithScene(elements, appState, app.files) : await saveAsJSON(elements, appState, app.files); return { @@ -141,9 +141,10 @@ export const actionSaveToActiveFile = register({ appState: { ...appState, fileHandle, - toastMessage: fileHandleExists - ? fileHandle?.name - ? t("toast.fileSavedToFilename").replace( + toastMessage: + fileHandleExists ? + fileHandle?.name ? + t("toast.fileSavedToFilename").replace( "{filename}", `"${fileHandle.name}"`, ) diff --git ORI/excalidraw/src/actions/actionFinalize.tsx ALT/excalidraw/src/actions/actionFinalize.tsx index e89112a..100f094 100644 --- ORI/excalidraw/src/actions/actionFinalize.tsx +++ ALT/excalidraw/src/actions/actionFinalize.tsx @@ -32,10 +32,11 @@ export const actionFinalize = register({ ); } return { - elements: - element.points.length < 2 || isInvisiblySmallElement(element) - ? elements.filter((el) => el.id !== element.id) - : undefined, + elements: ( + element.points.length < 2 || isInvisiblySmallElement(element) + ) ? + elements.filter((el) => el.id !== element.id) + : undefined, appState: { ...appState, editingLinearElement: null, @@ -55,10 +56,9 @@ export const actionFinalize = register({ focusContainer(); } - const multiPointElement = appState.multiElement - ? appState.multiElement - : appState.editingElement?.type === "freedraw" - ? appState.editingElement + const multiPointElement = + appState.multiElement ? appState.multiElement + : appState.editingElement?.type === "freedraw" ? appState.editingElement : null; if (multiPointElement) { @@ -94,9 +94,9 @@ export const actionFinalize = register({ const firstPoint = linePoints[0]; mutateElement(multiPointElement, { points: linePoints.map((point, index) => - index === linePoints.length - 1 - ? ([firstPoint[0], firstPoint[1]] as const) - : point, + index === linePoints.length - 1 ? + ([firstPoint[0], firstPoint[1]] as const) + : point, ), }); } @@ -135,25 +135,27 @@ export const actionFinalize = register({ elements: newElements, appState: { ...appState, - elementType: - (appState.elementLocked || appState.elementType === "freedraw") && - multiPointElement - ? appState.elementType - : "selection", + elementType: ( + (appState.elementLocked || appState.elementType === "freedraw") && + multiPointElement + ) ? + appState.elementType + : "selection", draggingElement: null, multiElement: null, editingElement: null, startBoundElement: null, suggestedBindings: [], - selectedElementIds: - multiPointElement && - !appState.elementLocked && - appState.elementType !== "freedraw" - ? { - ...appState.selectedElementIds, - [multiPointElement.id]: true, - } - : appState.selectedElementIds, + selectedElementIds: ( + multiPointElement && + !appState.elementLocked && + appState.elementType !== "freedraw" + ) ? + { + ...appState.selectedElementIds, + [multiPointElement.id]: true, + } + : appState.selectedElementIds, pendingImageElement: null, }, commitToHistory: appState.elementType === "freedraw", diff --git ORI/excalidraw/src/actions/actionProperties.tsx ALT/excalidraw/src/actions/actionProperties.tsx index cc3bbbd..ef04aeb 100644 --- ORI/excalidraw/src/actions/actionProperties.tsx +++ ALT/excalidraw/src/actions/actionProperties.tsx @@ -89,13 +89,13 @@ const getFormValue = function ( const nonDeletedElements = getNonDeletedElements(elements); return ( (editingElement && getAttribute(editingElement)) ?? - (isSomeElementSelected(nonDeletedElements, appState) - ? getCommonAttributeOfSelectedElements( - nonDeletedElements, - appState, - getAttribute, - ) - : defaultValue) ?? + (isSomeElementSelected(nonDeletedElements, appState) ? + getCommonAttributeOfSelectedElements( + nonDeletedElements, + appState, + getAttribute, + ) + : defaultValue) ?? null ); }; @@ -106,8 +106,8 @@ export const actionChangeStrokeColor = register({ return { ...(value.currentItemStrokeColor && { elements: changeProperty(elements, appState, (el) => { - return hasStrokeColor(el.type) - ? newElementWith(el, { + return hasStrokeColor(el.type) ? + newElementWith(el, { strokeColor: value.currentItemStrokeColor, }) : el; @@ -610,11 +610,11 @@ export const actionChangeSharpness = register({ getNonDeletedElements(elements), appState, ); - const shouldUpdateForNonLinearElements = targetElements.length - ? targetElements.every((el) => !isLinearElement(el)) + const shouldUpdateForNonLinearElements = targetElements.length ? + targetElements.every((el) => !isLinearElement(el)) : !isLinearElementType(appState.elementType); - const shouldUpdateForLinearElements = targetElements.length - ? targetElements.every(isLinearElement) + const shouldUpdateForLinearElements = targetElements.length ? + targetElements.every(isLinearElement) : isLinearElementType(appState.elementType); return { elements: changeProperty(elements, appState, (el) => @@ -624,11 +624,9 @@ export const actionChangeSharpness = register({ ), appState: { ...appState, - currentItemStrokeSharpness: shouldUpdateForNonLinearElements - ? value + currentItemStrokeSharpness: shouldUpdateForNonLinearElements ? value : appState.currentItemStrokeSharpness, - currentItemLinearStrokeSharpness: shouldUpdateForLinearElements - ? value + currentItemLinearStrokeSharpness: shouldUpdateForLinearElements ? value : appState.currentItemLinearStrokeSharpness, }, commitToHistory: true, @@ -656,9 +654,9 @@ export const actionChangeSharpness = register({ appState, (element) => element.strokeSharpness, (canChangeSharpness(appState.elementType) && - (isLinearElementType(appState.elementType) - ? appState.currentItemLinearStrokeSharpness - : appState.currentItemStrokeSharpness)) || + (isLinearElementType(appState.elementType) ? + appState.currentItemLinearStrokeSharpness + : appState.currentItemStrokeSharpness)) || null, )} onChange={(value) => updateData(value)} @@ -696,9 +694,9 @@ export const actionChangeArrowhead = register({ }), appState: { ...appState, - [value.position === "start" - ? "currentItemStartArrowhead" - : "currentItemEndArrowhead"]: value.type, + [value.position === "start" ? + "currentItemStartArrowhead" + : "currentItemEndArrowhead"]: value.type, }, commitToHistory: true, }; @@ -752,9 +750,9 @@ export const actionChangeArrowhead = register({ elements, appState, (element) => - isLinearElement(element) && canHaveArrowheads(element.type) - ? element.startArrowhead - : appState.currentItemStartArrowhead, + isLinearElement(element) && canHaveArrowheads(element.type) ? + element.startArrowhead + : appState.currentItemStartArrowhead, appState.currentItemStartArrowhead, )} onChange={(value) => updateData({ position: "start", type: value })} @@ -802,9 +800,9 @@ export const actionChangeArrowhead = register({ elements, appState, (element) => - isLinearElement(element) && canHaveArrowheads(element.type) - ? element.endArrowhead - : appState.currentItemEndArrowhead, + isLinearElement(element) && canHaveArrowheads(element.type) ? + element.endArrowhead + : appState.currentItemEndArrowhead, appState.currentItemEndArrowhead, )} onChange={(value) => updateData({ position: "end", type: value })} diff --git ORI/excalidraw/src/actions/actionZindex.tsx ALT/excalidraw/src/actions/actionZindex.tsx index f1cdcfe..1083518 100644 --- ORI/excalidraw/src/actions/actionZindex.tsx +++ ALT/excalidraw/src/actions/actionZindex.tsx @@ -81,22 +81,22 @@ export const actionSendToBack = register({ }, contextItemLabel: "labels.sendToBack", keyTest: (event) => - isDarwin - ? event[KEYS.CTRL_OR_CMD] && - event.altKey && - event.code === CODES.BRACKET_LEFT - : event[KEYS.CTRL_OR_CMD] && - event.shiftKey && - event.code === CODES.BRACKET_LEFT, + isDarwin ? + event[KEYS.CTRL_OR_CMD] && + event.altKey && + event.code === CODES.BRACKET_LEFT + : event[KEYS.CTRL_OR_CMD] && + event.shiftKey && + event.code === CODES.BRACKET_LEFT, PanelComponent: ({ updateData, appState }) => ( ); @@ -275,7 +273,7 @@ export const ColorPicker = ({ />
- {isActive ? ( + {isActive ? event.target !== pickerButton.current && setActive(false) @@ -296,7 +294,7 @@ export const ColorPicker = ({ type={type} /> - ) : null} + : null}
); diff --git ORI/excalidraw/src/components/ContextMenu.tsx ALT/excalidraw/src/components/ContextMenu.tsx index d64492f..0b3ffe5 100644 --- ORI/excalidraw/src/components/ContextMenu.tsx +++ ALT/excalidraw/src/components/ContextMenu.tsx @@ -48,8 +48,8 @@ const ContextMenu = ({ } const actionName = option.name; - const label = option.contextItemLabel - ? t(option.contextItemLabel) + const label = option.contextItemLabel ? + t(option.contextItemLabel) : ""; return (
  • @@ -62,9 +62,9 @@ const ContextMenu = ({ >
    {label}
    - {actionName - ? getShortcutFromShortcutName(actionName as ShortcutName) - : ""} + {actionName ? + getShortcutFromShortcutName(actionName as ShortcutName) + : ""}
  • diff --git ORI/excalidraw/src/components/HelpDialog.tsx ALT/excalidraw/src/components/HelpDialog.tsx index e84100c..0cbe616 100644 --- ORI/excalidraw/src/components/HelpDialog.tsx +++ ALT/excalidraw/src/components/HelpDialog.tsx @@ -299,17 +299,17 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => { void }) => { { if (isLinearElement(targetElement) && targetElement.points.length === 2) { return t("hints.lockAngle"); } - return isImageElement(targetElement) - ? t("hints.resizeImage") + return isImageElement(targetElement) ? + t("hints.resizeImage") : t("hints.resize"); } @@ -62,8 +62,8 @@ const getHints = ({ appState, elements, isMobile }: HintViewerProps) => { if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) { if (appState.editingLinearElement) { - return appState.editingLinearElement.activePointIndex - ? t("hints.lineEditor_pointSelected") + return appState.editingLinearElement.activePointIndex ? + t("hints.lineEditor_pointSelected") : t("hints.lineEditor_nothingSelected"); } return t("hints.lineEditor_info"); diff --git ORI/excalidraw/src/components/IconPicker.tsx ALT/excalidraw/src/components/IconPicker.tsx index 9b6d7ea..f165a63 100644 --- ORI/excalidraw/src/components/IconPicker.tsx +++ ALT/excalidraw/src/components/IconPicker.tsx @@ -161,7 +161,7 @@ export function IconPicker({ {options.find((option) => option.value === value)?.icon} - {isActive ? ( + {isActive ? <> @@ -182,7 +182,7 @@ export function IconPicker({
    - ) : null} + : null} ); diff --git ORI/excalidraw/src/components/ImageExportDialog.tsx ALT/excalidraw/src/components/ImageExportDialog.tsx index 213f384..e2fed34 100644 --- ORI/excalidraw/src/components/ImageExportDialog.tsx +++ ALT/excalidraw/src/components/ImageExportDialog.tsx @@ -101,8 +101,8 @@ const ImageExportModal = ({ const previewRef = useRef(null); const { exportBackground, viewBackgroundColor } = appState; - const exportedElements = exportSelected - ? getSelectedElements(elements, appState) + const exportedElements = exportSelected ? + getSelectedElements(elements, appState) : elements; useEffect(() => { diff --git ORI/excalidraw/src/components/LayerUI.tsx ALT/excalidraw/src/components/LayerUI.tsx index 9f65f97..43b3ddc 100644 --- ORI/excalidraw/src/components/LayerUI.tsx +++ ALT/excalidraw/src/components/LayerUI.tsx @@ -266,22 +266,22 @@ const LayerUI = ({ }); }, [setAppState]); - const libraryMenu = appState.isLibraryOpen ? ( - - ) : null; + const libraryMenu = appState.isLibraryOpen ? + + : null; const renderFixedSideContainer = () => { const shouldRenderSelectedShapeActions = showSelectedShapeActions( @@ -296,9 +296,9 @@ const LayerUI = ({ gap={4} className={clsx({ "disable-pointerEvents": zenModeEnabled })} > - {viewModeEnabled - ? renderViewModeCanvasActions() - : renderCanvasActions()} + {viewModeEnabled ? + renderViewModeCanvasActions() + : renderCanvasActions()} {shouldRenderSelectedShapeActions && renderSelectedShapeActions()} {!viewModeEnabled && ( @@ -476,54 +476,53 @@ const LayerUI = ({ ); - return isMobile ? ( - <> - {dialogs} - - - ) : ( -
    - {dialogs} - {renderFixedSideContainer()} - {renderBottomAppMenu()} - {appState.scrolledOutside && ( - - )} -
    - ); + return isMobile ? + <> + {dialogs} + + + :
    + {dialogs} + {renderFixedSideContainer()} + {renderBottomAppMenu()} + {appState.scrolledOutside && ( + + )} +
    ; }; const areEqual = (prev: LayerUIProps, next: LayerUIProps) => { diff --git ORI/excalidraw/src/components/LibraryMenu.tsx ALT/excalidraw/src/components/LibraryMenu.tsx index 763dfb8..ebbed64 100644 --- ORI/excalidraw/src/components/LibraryMenu.tsx +++ ALT/excalidraw/src/components/LibraryMenu.tsx @@ -241,86 +241,84 @@ export const LibraryMenu = ({ LibraryItem["id"] | null >(null); - return loadingState === "preloading" ? null : ( - - {showPublishLibraryDialog && ( - setShowPublishLibraryDialog(false)} - libraryItems={getSelectedItems(libraryItems, selectedItems)} - appState={appState} - onSuccess={onPublishLibSuccess} - onError={(error) => window.alert(error)} - updateItemsInStorage={() => library.saveLibrary(libraryItems)} - onRemove={(id: string) => - setSelectedItems(selectedItems.filter((_id) => _id !== id)) - } - /> - )} - {publishLibSuccess && renderPublishSuccess()} + return loadingState === "preloading" ? null + : + {showPublishLibraryDialog && ( + setShowPublishLibraryDialog(false)} + libraryItems={getSelectedItems(libraryItems, selectedItems)} + appState={appState} + onSuccess={onPublishLibSuccess} + onError={(error) => window.alert(error)} + updateItemsInStorage={() => library.saveLibrary(libraryItems)} + onRemove={(id: string) => + setSelectedItems(selectedItems.filter((_id) => _id !== id)) + } + /> + )} + {publishLibSuccess && renderPublishSuccess()} - {loadingState === "loading" ? ( -
    - {t("labels.libraryLoadingMessage")} -
    - ) : ( - { - const shouldSelect = !selectedItems.includes(id); + {loadingState === "loading" ? +
    + {t("labels.libraryLoadingMessage")} +
    + : { + const shouldSelect = !selectedItems.includes(id); - if (shouldSelect) { - if (event.shiftKey && lastSelectedItem) { - const rangeStart = libraryItems.findIndex( - (item) => item.id === lastSelectedItem, - ); - const rangeEnd = libraryItems.findIndex( - (item) => item.id === id, - ); + if (shouldSelect) { + if (event.shiftKey && lastSelectedItem) { + const rangeStart = libraryItems.findIndex( + (item) => item.id === lastSelectedItem, + ); + const rangeEnd = libraryItems.findIndex( + (item) => item.id === id, + ); - if (rangeStart === -1 || rangeEnd === -1) { - setSelectedItems([...selectedItems, id]); - return; - } + if (rangeStart === -1 || rangeEnd === -1) { + setSelectedItems([...selectedItems, id]); + return; + } - const selectedItemsMap = arrayToMap(selectedItems); - const nextSelectedIds = libraryItems.reduce( - (acc: LibraryItem["id"][], item, idx) => { - if ( - (idx >= rangeStart && idx <= rangeEnd) || - selectedItemsMap.has(item.id) - ) { - acc.push(item.id); - } - return acc; - }, - [], - ); + const selectedItemsMap = arrayToMap(selectedItems); + const nextSelectedIds = libraryItems.reduce( + (acc: LibraryItem["id"][], item, idx) => { + if ( + (idx >= rangeStart && idx <= rangeEnd) || + selectedItemsMap.has(item.id) + ) { + acc.push(item.id); + } + return acc; + }, + [], + ); - setSelectedItems(nextSelectedIds); + setSelectedItems(nextSelectedIds); + } else { + setSelectedItems([...selectedItems, id]); + } + setLastSelectedItem(id); } else { - setSelectedItems([...selectedItems, id]); + setLastSelectedItem(null); + setSelectedItems(selectedItems.filter((_id) => _id !== id)); } - setLastSelectedItem(id); - } else { - setLastSelectedItem(null); - setSelectedItems(selectedItems.filter((_id) => _id !== id)); - } - }} - onPublish={() => setShowPublishLibraryDialog(true)} - resetLibrary={resetLibrary} - /> - )} -
    - ); + }} + onPublish={() => setShowPublishLibraryDialog(true)} + resetLibrary={resetLibrary} + /> + } +
    ; }; diff --git ORI/excalidraw/src/components/LibraryMenuItems.tsx ALT/excalidraw/src/components/LibraryMenuItems.tsx index b2dd630..ec0d262 100644 --- ORI/excalidraw/src/components/LibraryMenuItems.tsx +++ ALT/excalidraw/src/components/LibraryMenuItems.tsx @@ -57,11 +57,11 @@ const LibraryMenuItems = ({ resetLibrary: () => void; }) => { const renderRemoveLibAlert = useCallback(() => { - const content = selectedItems.length - ? t("alerts.removeItemsFromsLibrary", { count: selectedItems.length }) + const content = selectedItems.length ? + t("alerts.removeItemsFromsLibrary", { count: selectedItems.length }) : t("alerts.resetLibrary"); - const title = selectedItems.length - ? t("confirmDialog.removeItemsFromLib") + const title = selectedItems.length ? + t("confirmDialog.removeItemsFromLib") : t("confirmDialog.resetLibrary"); return ( { const itemsSelected = !!selectedItems.length; - const items = itemsSelected - ? libraryItems.filter((item) => selectedItems.includes(item.id)) + const items = itemsSelected ? + libraryItems.filter((item) => selectedItems.includes(item.id)) : libraryItems; - const resetLabel = itemsSelected - ? t("buttons.remove") + const resetLabel = itemsSelected ? + t("buttons.remove") : t("buttons.resetLibrary"); return (
    @@ -128,8 +128,7 @@ const LibraryMenuItems = ({ aria-label={t("buttons.export")} icon={exportToFileIcon} onClick={async () => { - const libraryItems = itemsSelected - ? items + const libraryItems = itemsSelected ? items : await library.loadLibrary(); saveLibraryAsJSON(libraryItems) .catch(muteFSAbortError) @@ -278,9 +277,9 @@ const LibraryMenuItems = ({ ); const unpublishedItems = [ // append pending library item - ...(pendingElements.length - ? [{ id: null, elements: pendingElements }] - : []), + ...(pendingElements.length ? + [{ id: null, elements: pendingElements }] + : []), ...libraryItems.filter((item) => item.status !== "published"), ]; diff --git ORI/excalidraw/src/components/LibraryUnit.tsx ALT/excalidraw/src/components/LibraryUnit.tsx index 46b0e8d..b7d4630 100644 --- ORI/excalidraw/src/components/LibraryUnit.tsx +++ ALT/excalidraw/src/components/LibraryUnit.tsx @@ -88,15 +88,15 @@ export const LibraryUnit = ({ ref={ref} draggable={!!elements} onClick={ - !!elements || !!isPending - ? (event) => { - if (id && event.shiftKey) { - onToggle(id, event); - } else { - onClick(); - } + !!elements || !!isPending ? + (event) => { + if (id && event.shiftKey) { + onToggle(id, event); + } else { + onClick(); } - : undefined + } + : undefined } onDragStart={(event) => { setIsHovered(false); diff --git ORI/excalidraw/src/components/MobileMenu.tsx ALT/excalidraw/src/components/MobileMenu.tsx index cae2818..b3dde93 100644 --- ORI/excalidraw/src/components/MobileMenu.tsx +++ ALT/excalidraw/src/components/MobileMenu.tsx @@ -164,7 +164,7 @@ export const MobileMenu = ({ }} > - {appState.openMenu === "canvas" ? ( + {appState.openMenu === "canvas" ?
    @@ -192,9 +192,11 @@ export const MobileMenu = ({
    - ) : appState.openMenu === "shape" && + : ( + appState.openMenu === "shape" && !viewModeEnabled && - showSelectedShapeActions(appState, elements) ? ( + showSelectedShapeActions(appState, elements) + ) ?
    - ) : null} + : null}
    {renderAppToolbar()} {appState.scrolledOutside && !appState.openMenu && ( diff --git ORI/excalidraw/src/components/ProjectName.tsx ALT/excalidraw/src/components/ProjectName.tsx index db2b700..0308cf2 100644 --- ORI/excalidraw/src/components/ProjectName.tsx +++ ALT/excalidraw/src/components/ProjectName.tsx @@ -40,7 +40,7 @@ export const ProjectName = (props: Props) => { - {props.isNameEditable ? ( + {props.isNameEditable ? { value={fileName} onChange={(event) => setFileName(event.target.value)} /> - ) : ( - + : {props.value} - )} + }
    ); }; diff --git ORI/excalidraw/src/components/PublishLibrary.tsx ALT/excalidraw/src/components/PublishLibrary.tsx index adcc90a..fbed5e1 100644 --- ORI/excalidraw/src/components/PublishLibrary.tsx +++ ALT/excalidraw/src/components/PublishLibrary.tsx @@ -301,7 +301,7 @@ const PublishLibrary = ({ title={t("publishDialog.title")} className="publish-library" > - {shouldRenderForm ? ( + {shouldRenderForm ?
    {t("publishDialog.noteDescription.pre")} @@ -443,11 +443,10 @@ const PublishLibrary = ({ />
    - ) : ( -

    + :

    {t("publishDialog.atleastOneLibItem")}

    - )} + } ); }; diff --git ORI/excalidraw/src/components/Section.tsx ALT/excalidraw/src/components/Section.tsx index ebe00f8..c87a517 100644 --- ORI/excalidraw/src/components/Section.tsx +++ ALT/excalidraw/src/components/Section.tsx @@ -16,14 +16,13 @@ export const Section = ({ heading, children, ...props }: SectionProps) => { ); return (
    - {typeof children === "function" ? ( + {typeof children === "function" ? children(header) - ) : ( - <> + : <> {header} {children} - )} + }
    ); }; diff --git ORI/excalidraw/src/components/ToolButton.tsx ALT/excalidraw/src/components/ToolButton.tsx index 6361954..aa8165c 100644 --- ORI/excalidraw/src/components/ToolButton.tsx +++ ALT/excalidraw/src/components/ToolButton.tsx @@ -104,9 +104,9 @@ export const ToolButton = React.forwardRef((props: ToolButtonProps, ref) => { "ToolIcon_type_button", sizeCn, props.className, - props.visible && !props.hidden - ? "ToolIcon_type_button--show" - : "ToolIcon_type_button--hide", + props.visible && !props.hidden ? + "ToolIcon_type_button--show" + : "ToolIcon_type_button--hide", { ToolIcon: !props.hidden, "ToolIcon--selected": props.selected, diff --git ORI/excalidraw/src/components/Tooltip.tsx ALT/excalidraw/src/components/Tooltip.tsx index fc1c69c..5193bcd 100644 --- ORI/excalidraw/src/components/Tooltip.tsx +++ ALT/excalidraw/src/components/Tooltip.tsx @@ -43,14 +43,14 @@ const updateTooltip = ( const margin = 5; const left = itemX + itemWidth / 2 - labelWidth / 2; - const offsetLeft = - left + labelWidth >= viewportWidth ? left + labelWidth - viewportWidth : 0; + const offsetLeft = left + labelWidth >= viewportWidth ? + left + labelWidth - viewportWidth + : 0; const top = itemBottom + margin; - const offsetTop = - top + labelHeight >= viewportHeight - ? itemBottom - itemTop + labelHeight + margin * 2 - : 0; + const offsetTop = top + labelHeight >= viewportHeight ? + itemBottom - itemTop + labelHeight + margin * 2 + : 0; Object.assign(tooltip.style, { top: `${top - offsetTop}px`, diff --git ORI/excalidraw/src/components/icons.tsx ALT/excalidraw/src/components/icons.tsx index 62ed80a..29595d1 100644 --- ORI/excalidraw/src/components/icons.tsx +++ ALT/excalidraw/src/components/icons.tsx @@ -45,7 +45,9 @@ export const createIcon = ( className={clsx({ "rtl-mirror": mirror })} style={style} > - {typeof d === "string" ? : d} + {typeof d === "string" ? + + : d} ); }; diff --git ORI/excalidraw/src/data/blob.ts ALT/excalidraw/src/data/blob.ts index 2418f5a..ca0bd0d 100644 --- ORI/excalidraw/src/data/blob.ts +++ ALT/excalidraw/src/data/blob.ts @@ -146,9 +146,9 @@ export const loadFromBlob = async ( theme: localAppState?.theme, fileHandle: blob.handle || null, ...cleanAppStateForExport(data.appState || {}), - ...(localAppState - ? calculateScrollCenter(data.elements || [], localAppState, null) - : {}), + ...(localAppState ? + calculateScrollCenter(data.elements || [], localAppState, null) + : {}), }, files: data.files, }, diff --git ORI/excalidraw/src/data/encode.ts ALT/excalidraw/src/data/encode.ts index 1d5a595..0f81aa4 100644 --- ORI/excalidraw/src/data/encode.ts +++ ALT/excalidraw/src/data/encode.ts @@ -10,10 +10,9 @@ export const toByteString = ( data: string | Uint8Array | ArrayBuffer, ): Promise => { return new Promise((resolve, reject) => { - const blob = - typeof data === "string" - ? new Blob([new TextEncoder().encode(data)]) - : new Blob([data instanceof Uint8Array ? data : new Uint8Array(data)]); + const blob = typeof data === "string" ? + new Blob([new TextEncoder().encode(data)]) + : new Blob([data instanceof Uint8Array ? data : new Uint8Array(data)]); const reader = new FileReader(); reader.onload = (event) => { if (!event.target || typeof event.target.result !== "string") { @@ -52,8 +51,8 @@ export const stringToBase64 = async (str: string, isByteString = false) => { // async to align with stringToBase64 export const base64ToString = async (base64: string, isByteString = false) => { - return isByteString - ? window.atob(base64) + return isByteString ? + window.atob(base64) : byteStringToString(window.atob(base64)); }; @@ -103,8 +102,8 @@ export const decode = async (data: EncodedData): Promise => { switch (data.encoding) { case "bstring": // if compressed, do not double decode the bstring - decoded = data.compressed - ? data.encoded + decoded = data.compressed ? + data.encoded : await byteStringToString(data.encoded); break; default: @@ -300,13 +299,13 @@ export const compressData = async = never>( dataBuffer: Uint8Array, options: { encryptionKey: string; - } & ([T] extends [never] - ? { - metadata?: T; - } - : { - metadata: T; - }), + } & ([T] extends [never] ? + { + metadata?: T; + } + : { + metadata: T; + }), ): Promise => { const fileInfo: FileEncodingInfo = { version: 2, diff --git ORI/excalidraw/src/data/encryption.ts ALT/excalidraw/src/data/encryption.ts index 21d3b85..808fe7f 100644 --- ORI/excalidraw/src/data/encryption.ts +++ ALT/excalidraw/src/data/encryption.ts @@ -21,10 +21,9 @@ export const generateEncryptionKey = async < ["encrypt", "decrypt"], ); return ( - returnAs === "cryptoKey" - ? key - : (await window.crypto.subtle.exportKey("jwk", key)).k - ) as T extends "cryptoKey" ? CryptoKey : string; + returnAs === "cryptoKey" ? key + : (await window.crypto.subtle.exportKey("jwk", key)) + .k) as T extends "cryptoKey" ? CryptoKey : string; }; export const getCryptoKey = (key: string, usage: KeyUsage) => @@ -49,17 +48,15 @@ export const encryptData = async ( key: string | CryptoKey, data: Uint8Array | ArrayBuffer | Blob | File | string, ): Promise<{ encryptedBuffer: ArrayBuffer; iv: Uint8Array }> => { - const importedKey = - typeof key === "string" ? await getCryptoKey(key, "encrypt") : key; + const importedKey = typeof key === "string" ? + await getCryptoKey(key, "encrypt") + : key; const iv = createIV(); const buffer: ArrayBuffer | Uint8Array = - typeof data === "string" - ? new TextEncoder().encode(data) - : data instanceof Uint8Array - ? data - : data instanceof Blob - ? await data.arrayBuffer() - : data; + typeof data === "string" ? new TextEncoder().encode(data) + : data instanceof Uint8Array ? data + : data instanceof Blob ? await data.arrayBuffer() + : data; // We use symmetric encryption. AES-GCM is the recommended algorithm and // includes checks that the ciphertext has not been modified by an attacker. diff --git ORI/excalidraw/src/data/filesystem.ts ALT/excalidraw/src/data/filesystem.ts index 55f4117..516aa2b 100644 --- ORI/excalidraw/src/data/filesystem.ts +++ ALT/excalidraw/src/data/filesystem.ts @@ -28,9 +28,8 @@ export const fileOpen = (opts: { M extends false | undefined ? FileWithHandle : FileWithHandle[] > => { // an unsafe TS hack, alas not much we can do AFAIK - type RetType = M extends false | undefined - ? FileWithHandle - : FileWithHandle[]; + type RetType = + M extends false | undefined ? FileWithHandle : FileWithHandle[]; const mimeTypes = opts.extensions?.reduce((mimeTypes, type) => { mimeTypes.push(MIME_TYPES[type]); diff --git ORI/excalidraw/src/data/json.ts ALT/excalidraw/src/data/json.ts index e7ce527..4725a43 100644 --- ORI/excalidraw/src/data/json.ts +++ ALT/excalidraw/src/data/json.ts @@ -49,19 +49,16 @@ export const serializeAsJSON = ( type: EXPORT_DATA_TYPES.excalidraw, version: VERSIONS.excalidraw, source: EXPORT_SOURCE, - elements: - type === "local" - ? clearElementsForExport(elements) - : clearElementsForDatabase(elements), - appState: - type === "local" - ? cleanAppStateForExport(appState) - : clearAppStateForDatabase(appState), - files: - type === "local" - ? filterOutDeletedFiles(elements, files) - : // will be stripped from JSON - undefined, + elements: type === "local" ? + clearElementsForExport(elements) + : clearElementsForDatabase(elements), + appState: type === "local" ? + cleanAppStateForExport(appState) + : clearAppStateForDatabase(appState), + files: type === "local" ? + filterOutDeletedFiles(elements, files) + : // will be stripped from JSON + undefined, }; return JSON.stringify(data, null, 2); @@ -81,8 +78,7 @@ export const saveAsJSON = async ( name: appState.name, extension: "excalidraw", description: "Excalidraw file", - fileHandle: isImageFileHandle(appState.fileHandle) - ? null + fileHandle: isImageFileHandle(appState.fileHandle) ? null : appState.fileHandle, }); return { fileHandle }; diff --git ORI/excalidraw/src/data/restore.ts ALT/excalidraw/src/data/restore.ts index cb316b4..fe8389d 100644 --- ORI/excalidraw/src/data/restore.ts +++ ALT/excalidraw/src/data/restore.ts @@ -157,23 +157,21 @@ const restoreElement = ( let x = element.x; let y = element.y; - let points = // migrate old arrow model to new one - !Array.isArray(element.points) || element.points.length < 2 - ? [ - [0, 0], - [element.width, element.height], - ] - : element.points; + let points = !Array.isArray(element.points) || element.points.length < 2 ? // migrate old arrow model to new one + [ + [0, 0], + [element.width, element.height], + ] + : element.points; if (points[0][0] !== 0 || points[0][1] !== 0) { ({ points, x, y } = LinearElementEditor.getNormalizedPoints(element)); } return restoreElementWithProperties(element, { - type: - (element.type as ExcalidrawElement["type"] | "draw") === "draw" - ? "line" - : element.type, + type: (element.type as ExcalidrawElement["type"] | "draw") === "draw" ? + "line" + : element.type, startBinding: element.startBinding, endBinding: element.endBinding, lastCommittedPoint: null, @@ -237,26 +235,23 @@ export const restoreAppState = ( const suppliedValue = appState[key]; const localValue = localAppState ? localAppState[key] : undefined; (nextAppState as any)[key] = - suppliedValue !== undefined - ? suppliedValue - : localValue !== undefined - ? localValue - : defaultValue; + suppliedValue !== undefined ? suppliedValue + : localValue !== undefined ? localValue + : defaultValue; } return { ...nextAppState, - elementType: AllowedExcalidrawElementTypes[nextAppState.elementType] - ? nextAppState.elementType + elementType: AllowedExcalidrawElementTypes[nextAppState.elementType] ? + nextAppState.elementType : "selection", // Migrates from previous version where appState.zoom was a number - zoom: - typeof appState.zoom === "number" - ? { - value: appState.zoom as NormalizedZoomValue, - translation: defaultAppState.zoom.translation, - } - : appState.zoom || defaultAppState.zoom, + zoom: typeof appState.zoom === "number" ? + { + value: appState.zoom as NormalizedZoomValue, + translation: defaultAppState.zoom.translation, + } + : appState.zoom || defaultAppState.zoom, }; }; diff --git ORI/excalidraw/src/disitrubte.ts ALT/excalidraw/src/disitrubte.ts index 8335f5c..3e8459e 100644 --- ORI/excalidraw/src/disitrubte.ts +++ ALT/excalidraw/src/disitrubte.ts @@ -22,10 +22,9 @@ export const distributeElements = ( selectedElements: ExcalidrawElement[], distribution: Distribution, ): ExcalidrawElement[] => { - const [start, mid, end, extent] = - distribution.axis === "x" - ? (["minX", "midX", "maxX", "width"] as const) - : (["minY", "midY", "maxY", "height"] as const); + const [start, mid, end, extent] = distribution.axis === "x" ? + (["minX", "midX", "maxX", "width"] as const) + : (["minY", "midY", "maxY", "height"] as const); const bounds = getCommonBoundingBox(selectedElements); const groups = getMaximumGroups(selectedElements) @@ -108,10 +107,9 @@ export const getMaximumGroups = ( >(); elements.forEach((element: ExcalidrawElement) => { - const groupId = - element.groupIds.length === 0 - ? element.id - : element.groupIds[element.groupIds.length - 1]; + const groupId = element.groupIds.length === 0 ? + element.id + : element.groupIds[element.groupIds.length - 1]; const currentGroupMembers = groups.get(groupId) || []; diff --git ORI/excalidraw/src/element/binding.ts ALT/excalidraw/src/element/binding.ts index ec5895f..4337798 100644 --- ORI/excalidraw/src/element/binding.ts +++ ALT/excalidraw/src/element/binding.ts @@ -97,14 +97,14 @@ const bindOrUnbindLinearElementEdge = ( // element on the other edge already ("start" edge takes precedence). if ( otherEdgeBindableElement == null || - (otherEdgeBindableElement === "keep" - ? !isLinearElementSimpleAndAlreadyBoundOnOppositeEdge( - linearElement, - bindableElement, - startOrEnd, - ) - : startOrEnd === "start" || - otherEdgeBindableElement.id !== bindableElement.id) + (otherEdgeBindableElement === "keep" ? + !isLinearElementSimpleAndAlreadyBoundOnOppositeEdge( + linearElement, + bindableElement, + startOrEnd, + ) + : startOrEnd === "start" || + otherEdgeBindableElement.id !== bindableElement.id) ) { bindLinearElement(linearElement, bindableElement, startOrEnd); boundToElementIds.add(bindableElement.id); @@ -435,17 +435,17 @@ export const getEligibleElementsForBinding = ( ): SuggestedBinding[] => { const includedElementIds = new Set(elements.map(({ id }) => id)); return elements.flatMap((element) => - isBindingElement(element) - ? (getElligibleElementsForBindingElement( - element as NonDeleted, - ).filter( - (element) => !includedElementIds.has(element.id), - ) as SuggestedBinding[]) - : isBindableElement(element) - ? getElligibleElementsForBindableElementAndWhere(element).filter( - (binding) => !includedElementIds.has(binding[0].id), - ) - : [], + isBindingElement(element) ? + (getElligibleElementsForBindingElement( + element as NonDeleted, + ).filter( + (element) => !includedElementIds.has(element.id), + ) as SuggestedBinding[]) + : isBindableElement(element) ? + getElligibleElementsForBindableElementAndWhere(element).filter( + (binding) => !includedElementIds.has(binding[0].id), + ) + : [], ); }; @@ -505,7 +505,9 @@ const getElligibleElementsForBindableElementAndWhere = ( } return [ element, - canBindStart && canBindEnd ? "both" : canBindStart ? "start" : "end", + canBindStart && canBindEnd ? "both" + : canBindStart ? "start" + : "end", bindableElement, ]; }) diff --git ORI/excalidraw/src/element/bounds.ts ALT/excalidraw/src/element/bounds.ts index 59be00a..4b393df 100644 --- ORI/excalidraw/src/element/bounds.ts +++ ALT/excalidraw/src/element/bounds.ts @@ -267,10 +267,9 @@ export const getArrowheadPoints = ( if (arrowhead === "arrow") { // Length for -> arrows is based on the length of the last section const [cx, cy] = element.points[element.points.length - 1]; - const [px, py] = - element.points.length > 1 - ? element.points[element.points.length - 2] - : [0, 0]; + const [px, py] = element.points.length > 1 ? + element.points[element.points.length - 2] + : [0, 0]; length = Math.hypot(cx - px, cy - py); } else { @@ -444,16 +443,12 @@ export const getResizedElementAbsoluteCoords = ( } else { // Line const gen = rough.generator(); - const curve = - element.strokeSharpness === "sharp" - ? gen.linearPath( - points as [number, number][], - generateRoughOptions(element), - ) - : gen.curve( - points as [number, number][], - generateRoughOptions(element), - ); + const curve = element.strokeSharpness === "sharp" ? + gen.linearPath( + points as [number, number][], + generateRoughOptions(element), + ) + : gen.curve(points as [number, number][], generateRoughOptions(element)); const ops = getCurvePathOps(curve); bounds = getMinMaxXYFromCurvePathOps(ops); } @@ -474,13 +469,12 @@ export const getElementPointsCoords = ( ): [number, number, number, number] => { // This might be computationally heavey const gen = rough.generator(); - const curve = - sharpness === "sharp" - ? gen.linearPath( - points as [number, number][], - generateRoughOptions(element), - ) - : gen.curve(points as [number, number][], generateRoughOptions(element)); + const curve = sharpness === "sharp" ? + gen.linearPath( + points as [number, number][], + generateRoughOptions(element), + ) + : gen.curve(points as [number, number][], generateRoughOptions(element)); const ops = getCurvePathOps(curve); const [minX, minY, maxX, maxY] = getMinMaxXYFromCurvePathOps(ops); return [ diff --git ORI/excalidraw/src/element/collision.ts ALT/excalidraw/src/element/collision.ts index 3ac8b32..1c960e3 100644 --- ORI/excalidraw/src/element/collision.ts +++ ALT/excalidraw/src/element/collision.ts @@ -91,11 +91,9 @@ const isHittingElementNotConsideringBoundingBox = ( const threshold = 10 / appState.zoom.value; const check = - element.type === "text" - ? isStrictlyInside - : isElementDraggableFromInside(element) - ? isInsideCheck - : isNearCheck; + element.type === "text" ? isStrictlyInside + : isElementDraggableFromInside(element) ? isInsideCheck + : isNearCheck; return hitTestPointAgainstElement({ element, point, threshold, check }); }; @@ -352,7 +350,10 @@ const hitTestFreeDrawElement = ( const da = distance2d(P[0], P[1], A[0], A[1]); const db = distance2d(P[0], P[1], B[0], B[1]); - P = db < da && da > length ? B : da < db && db > length ? A : P; + P = + db < da && da > length ? B + : da < db && db > length ? A + : P; if (Math.hypot(y - P[1], x - P[0]) < threshold) { return true; diff --git ORI/excalidraw/src/element/index.ts ALT/excalidraw/src/element/index.ts index ef4059c..538774f 100644 --- ORI/excalidraw/src/element/index.ts +++ ALT/excalidraw/src/element/index.ts @@ -80,9 +80,9 @@ const _clearElements = ( elements: readonly ExcalidrawElement[], ): ExcalidrawElement[] => getNonDeletedElements(elements).map((element) => - isLinearElementType(element.type) - ? { ...element, lastCommittedPoint: null } - : element, + isLinearElementType(element.type) ? + { ...element, lastCommittedPoint: null } + : element, ); export const clearElementsForDatabase = ( diff --git ORI/excalidraw/src/element/linearElementEditor.ts ALT/excalidraw/src/element/linearElementEditor.ts index 1d07660..26e6aaa 100644 --- ORI/excalidraw/src/element/linearElementEditor.ts +++ ALT/excalidraw/src/element/linearElementEditor.ts @@ -133,13 +133,13 @@ export class LinearElementEditor { LinearElementEditor.movePoint( element, activePointIndex, - activePointIndex === 0 - ? element.points[element.points.length - 1] - : element.points[0], + activePointIndex === 0 ? + element.points[element.points.length - 1] + : element.points[0], ); } - const bindingElement = isBindingEnabled(appState) - ? getHoveredElementForBinding( + const bindingElement = isBindingEnabled(appState) ? + getHoveredElementForBinding( tupleToCoors( LinearElementEditor.getPointAtIndexGlobalCoordinates( element, @@ -263,8 +263,8 @@ export class LinearElementEditor { editingLinearElement: { ...appState.editingLinearElement, activePointIndex: clickedPointIndex > -1 ? clickedPointIndex : null, - pointerOffset: targetPoint - ? { + pointerOffset: targetPoint ? + { x: scenePointer.x - targetPoint[0], y: scenePointer.y - targetPoint[1], } @@ -337,10 +337,9 @@ export class LinearElementEditor { element: NonDeleted, indexMaybeFromEnd: number, // -1 for last element ): Point { - const index = - indexMaybeFromEnd < 0 - ? element.points.length + indexMaybeFromEnd - : indexMaybeFromEnd; + const index = indexMaybeFromEnd < 0 ? + element.points.length + indexMaybeFromEnd + : indexMaybeFromEnd; const [x1, y1, x2, y2] = getElementAbsoluteCoords(element); const cx = (x1 + x2) / 2; const cy = (y1 + y2) / 2; @@ -504,8 +503,8 @@ export class LinearElementEditor { return [point[0] + deltaX, point[1] + deltaY] as const; } - return offsetX || offsetY - ? ([point[0] - offsetX, point[1] - offsetY] as const) + return offsetX || offsetY ? + ([point[0] - offsetX, point[1] - offsetY] as const) : point; }); } diff --git ORI/excalidraw/src/element/newElement.ts ALT/excalidraw/src/element/newElement.ts index b7adb2b..b0e6f5a 100644 --- ORI/excalidraw/src/element/newElement.ts +++ ALT/excalidraw/src/element/newElement.ts @@ -98,11 +98,9 @@ const getTextElementPositionOffsets = ( ) => { return { x: - opts.textAlign === "center" - ? metrics.width / 2 - : opts.textAlign === "right" - ? metrics.width - : 0, + opts.textAlign === "center" ? metrics.width / 2 + : opts.textAlign === "right" ? metrics.width + : 0, y: opts.verticalAlign === "middle" ? metrics.height / 2 : 0, }; }; @@ -276,10 +274,9 @@ export const deepCopyElement = (val: any, depth: number = 0) => { } if (Object.prototype.toString.call(val) === "[object Object]") { - const tmp = - typeof val.constructor === "function" - ? Object.create(Object.getPrototypeOf(val)) - : {}; + const tmp = typeof val.constructor === "function" ? + Object.create(Object.getPrototypeOf(val)) + : {}; for (const key in val) { if (val.hasOwnProperty(key)) { // don't copy top-level shape property, which we want to regenerate diff --git ORI/excalidraw/src/element/resizeElements.ts ALT/excalidraw/src/element/resizeElements.ts index ac2106c..9a91860 100644 --- ORI/excalidraw/src/element/resizeElements.ts +++ ALT/excalidraw/src/element/resizeElements.ts @@ -205,13 +205,12 @@ export const reshapeSingleTwoPointElement = ( cy, -element.angle, ); - let [width, height] = - resizeArrowDirection === "end" - ? [rotatedX - element.x, rotatedY - element.y] - : [ - element.x + element.points[1][0] - rotatedX, - element.y + element.points[1][1] - rotatedY, - ]; + let [width, height] = resizeArrowDirection === "end" ? + [rotatedX - element.x, rotatedY - element.y] + : [ + element.x + element.points[1][0] - rotatedX, + element.y + element.points[1][1] - rotatedY, + ]; if (shouldRotateWithDiscreteAngle) { [width, height] = getPerfectElementSizeWithRotation( element.type, @@ -221,9 +220,9 @@ export const reshapeSingleTwoPointElement = ( ); } const [nextElementX, nextElementY] = adjustXYWithRotation( - resizeArrowDirection === "end" - ? { s: true, e: true } - : { n: true, w: true }, + resizeArrowDirection === "end" ? + { s: true, e: true } + : { n: true, w: true }, element.x, element.y, element.angle, @@ -247,15 +246,11 @@ const rescalePointsInElement = ( width: number, height: number, ) => - isLinearElement(element) || isFreeDrawElement(element) - ? { - points: rescalePoints( - 0, - width, - rescalePoints(1, height, element.points), - ), - } - : {}; + isLinearElement(element) || isFreeDrawElement(element) ? + { + points: rescalePoints(0, width, rescalePoints(1, height, element.points)), + } + : {}; const MIN_FONT_SIZE = 1; @@ -737,10 +732,9 @@ export const getResizeOffsetXY = ( x: number, y: number, ): [number, number] => { - const [x1, y1, x2, y2] = - selectedElements.length === 1 - ? getElementAbsoluteCoords(selectedElements[0]) - : getCommonBounds(selectedElements); + const [x1, y1, x2, y2] = selectedElements.length === 1 ? + getElementAbsoluteCoords(selectedElements[0]) + : getCommonBounds(selectedElements); const cx = (x1 + x2) / 2; const cy = (y1 + y2) / 2; const angle = selectedElements.length === 1 ? selectedElements[0].angle : 0; diff --git ORI/excalidraw/src/element/textWysiwyg.tsx ALT/excalidraw/src/element/textWysiwyg.tsx index 7fc8999..ad8e0a8 100644 --- ORI/excalidraw/src/element/textWysiwyg.tsx +++ ALT/excalidraw/src/element/textWysiwyg.tsx @@ -250,11 +250,11 @@ export const textWysiwyg = ({ .reduce( (startIndices, line, idx, lines) => startIndices.concat( - idx - ? // curr line index is prev line's start + prev line's length + \n - startIndices[idx - 1] + lines[idx - 1].length + 1 - : // first selected line - selectionStart, + idx ? + // curr line index is prev line's start + prev line's length + \n + startIndices[idx - 1] + lines[idx - 1].length + 1 + : // first selected line + selectionStart, ), [] as number[], ) diff --git ORI/excalidraw/src/element/transformHandles.ts ALT/excalidraw/src/element/transformHandles.ts index b259509..aa417d7 100644 --- ORI/excalidraw/src/element/transformHandles.ts +++ ALT/excalidraw/src/element/transformHandles.ts @@ -99,8 +99,7 @@ export const getTransformHandlesFromCoords = ( const centeringOffset = (size - 8) / (2 * zoom.value); const transformHandles: TransformHandles = { - nw: omitSides.nw - ? undefined + nw: omitSides.nw ? undefined : generateTransformHandle( x1 - dashedLineMargin - handleMarginX + centeringOffset, y1 - dashedLineMargin - handleMarginY + centeringOffset, @@ -110,8 +109,7 @@ export const getTransformHandlesFromCoords = ( cy, angle, ), - ne: omitSides.ne - ? undefined + ne: omitSides.ne ? undefined : generateTransformHandle( x2 + dashedLineMargin - centeringOffset, y1 - dashedLineMargin - handleMarginY + centeringOffset, @@ -121,8 +119,7 @@ export const getTransformHandlesFromCoords = ( cy, angle, ), - sw: omitSides.sw - ? undefined + sw: omitSides.sw ? undefined : generateTransformHandle( x1 - dashedLineMargin - handleMarginX + centeringOffset, y2 + dashedLineMargin - centeringOffset, @@ -132,8 +129,7 @@ export const getTransformHandlesFromCoords = ( cy, angle, ), - se: omitSides.se - ? undefined + se: omitSides.se ? undefined : generateTransformHandle( x2 + dashedLineMargin - centeringOffset, y2 + dashedLineMargin - centeringOffset, @@ -143,8 +139,7 @@ export const getTransformHandlesFromCoords = ( cy, angle, ), - rotation: omitSides.rotation - ? undefined + rotation: omitSides.rotation ? undefined : generateTransformHandle( x1 + width / 2 - handleWidth / 2, y1 - diff --git ORI/excalidraw/src/excalidraw-app/collab/RoomDialog.tsx ALT/excalidraw/src/excalidraw-app/collab/RoomDialog.tsx index ac3fc27..5f705a9 100644 --- ORI/excalidraw/src/excalidraw-app/collab/RoomDialog.tsx +++ ALT/excalidraw/src/excalidraw-app/collab/RoomDialog.tsx @@ -106,7 +106,7 @@ const RoomDialog = ({

    {t("roomDialog.desc_shareLink")}

    - {"share" in navigator ? ( + {"share" in navigator ? - ) : null} + : null} { exportedElements, { ...appState, - viewBackgroundColor: appState.exportBackground - ? appState.viewBackgroundColor + viewBackgroundColor: appState.exportBackground ? + appState.viewBackgroundColor : getDefaultAppState().viewBackgroundColor, }, files, diff --git ORI/excalidraw/src/excalidraw-app/sentry.ts ALT/excalidraw/src/excalidraw-app/sentry.ts index 04b3246..c54da7f 100644 --- ORI/excalidraw/src/excalidraw-app/sentry.ts +++ ALT/excalidraw/src/excalidraw-app/sentry.ts @@ -17,8 +17,8 @@ const onlineEnv = ); Sentry.init({ - dsn: onlineEnv - ? "https://7bfc596a5bf945eda6b660d3015a5460@sentry.io/5179260" + dsn: onlineEnv ? + "https://7bfc596a5bf945eda6b660d3015a5460@sentry.io/5179260" : undefined, environment: onlineEnv ? SentryEnvHostnameMap[onlineEnv] : undefined, release: process.env.REACT_APP_GIT_SHA, diff --git ORI/excalidraw/src/ga.ts ALT/excalidraw/src/ga.ts index f2e27e0..3a3432d 100644 --- ORI/excalidraw/src/ga.ts +++ ALT/excalidraw/src/ga.ts @@ -74,10 +74,10 @@ const STRING_EPSILON = 0.000001; export const toString = (nvector: NVector): string => { const result = nvector .map((value, index) => - Math.abs(value) > STRING_EPSILON - ? value.toFixed(7).replace(/(\.|0+)$/, "") + - (index > 0 ? NVECTOR_BASE[index] : "") - : null, + Math.abs(value) > STRING_EPSILON ? + value.toFixed(7).replace(/(\.|0+)$/, "") + + (index > 0 ? NVECTOR_BASE[index] : "") + : null, ) .filter((representation) => representation != null) .join(" + "); diff --git ORI/excalidraw/src/global.d.ts ALT/excalidraw/src/global.d.ts index 85e8d4c..04e790c 100644 --- ORI/excalidraw/src/global.d.ts +++ ALT/excalidraw/src/global.d.ts @@ -34,11 +34,8 @@ type Mutable = { -readonly [P in keyof T]: T[P]; }; -type ResolutionType any> = T extends ( - ...args: any -) => Promise - ? R - : any; +type ResolutionType any> = + T extends (...args: any) => Promise ? R : any; // https://github.com/krzkaczor/ts-essentials type MarkOptional = Omit & Partial>; diff --git ORI/excalidraw/src/groups.ts ALT/excalidraw/src/groups.ts index f374e81..283c2f1 100644 --- ORI/excalidraw/src/groups.ts +++ ALT/excalidraw/src/groups.ts @@ -126,11 +126,12 @@ export const getNewGroupIdsForDuplication = ( mapper: (groupId: GroupId) => GroupId, ) => { const copy = [...groupIds]; - const positionOfEditingGroupId = editingGroupId - ? groupIds.indexOf(editingGroupId) + const positionOfEditingGroupId = editingGroupId ? + groupIds.indexOf(editingGroupId) : -1; - const endIndex = - positionOfEditingGroupId > -1 ? positionOfEditingGroupId : groupIds.length; + const endIndex = positionOfEditingGroupId > -1 ? + positionOfEditingGroupId + : groupIds.length; for (let index = 0; index < endIndex; index++) { copy[index] = mapper(copy[index]); } @@ -145,11 +146,12 @@ export const addToGroup = ( ) => { // insert before the editingGroupId, or push to the end. const groupIds = [...prevGroupIds]; - const positionOfEditingGroupId = editingGroupId - ? groupIds.indexOf(editingGroupId) + const positionOfEditingGroupId = editingGroupId ? + groupIds.indexOf(editingGroupId) : -1; - const positionToInsert = - positionOfEditingGroupId > -1 ? positionOfEditingGroupId : groupIds.length; + const positionToInsert = positionOfEditingGroupId > -1 ? + positionOfEditingGroupId + : groupIds.length; groupIds.splice(positionToInsert, 0, newGroupId); return groupIds; }; diff --git ORI/excalidraw/src/history.ts ALT/excalidraw/src/history.ts index cc620ca..75c441a 100644 --- ORI/excalidraw/src/history.ts +++ ALT/excalidraw/src/history.ts @@ -121,11 +121,12 @@ class History { elements.push({ ...element, // don't store last point if not committed - points: - element.lastCommittedPoint !== - element.points[element.points.length - 1] - ? element.points.slice(0, -1) - : element.points, + points: ( + element.lastCommittedPoint !== + element.points[element.points.length - 1] + ) ? + element.points.slice(0, -1) + : element.points, }); } else { elements.push(element); diff --git ORI/excalidraw/src/i18n.ts ALT/excalidraw/src/i18n.ts index 8eaf129..10f3995 100644 --- ORI/excalidraw/src/i18n.ts +++ ALT/excalidraw/src/i18n.ts @@ -110,8 +110,8 @@ export const t = ( replacement?: { [key: string]: string | number }, ) => { if (currentLang.code.startsWith(TEST_LANG_CODE)) { - const name = replacement - ? `${path}(${JSON.stringify(replacement).slice(1, -1)})` + const name = replacement ? + `${path}(${JSON.stringify(replacement).slice(1, -1)})` : path; return `\u{202a}[[${name}]]\u{202c}`; } diff --git ORI/excalidraw/src/packages/utils.ts ALT/excalidraw/src/packages/utils.ts index c09d101..9f2c98f 100644 --- ORI/excalidraw/src/packages/utils.ts +++ ALT/excalidraw/src/packages/utils.ts @@ -103,7 +103,10 @@ export const exportToBlob = async ( const canvas = await exportToCanvas(opts); - quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8; + quality = + quality ? quality + : /image\/jpe?g/.test(mimeType) ? 0.92 + : 0.8; return new Promise((resolve) => { canvas.toBlob( diff --git ORI/excalidraw/src/points.ts ALT/excalidraw/src/points.ts index 7806203..d02cb23 100644 --- ORI/excalidraw/src/points.ts +++ ALT/excalidraw/src/points.ts @@ -19,8 +19,8 @@ export const rescalePoints = ( const prevMinDimension = Math.min(...prevDimValues); const prevDimensionSize = prevMaxDimension - prevMinDimension; - const dimensionScaleFactor = - prevDimensionSize === 0 ? 1 : nextDimensionSize / prevDimensionSize; + const dimensionScaleFactor = prevDimensionSize === 0 ? 1 + : nextDimensionSize / prevDimensionSize; let nextMinDimension = Infinity; diff --git ORI/excalidraw/src/renderer/renderElement.ts ALT/excalidraw/src/renderer/renderElement.ts index 6fa5431..ba564c9 100644 --- ORI/excalidraw/src/renderer/renderElement.ts +++ ALT/excalidraw/src/renderer/renderElement.ts @@ -101,19 +101,17 @@ const generateElementCanvas = ( distance(y1, y2) * window.devicePixelRatio * zoom.value + padding * zoom.value * 2; - canvasOffsetX = - element.x > x1 - ? Math.floor(distance(element.x, x1)) * - window.devicePixelRatio * - zoom.value - : 0; - - canvasOffsetY = - element.y > y1 - ? Math.floor(distance(element.y, y1)) * - window.devicePixelRatio * - zoom.value - : 0; + canvasOffsetX = element.x > x1 ? + Math.floor(distance(element.x, x1)) * + window.devicePixelRatio * + zoom.value + : 0; + + canvasOffsetY = element.y > y1 ? + Math.floor(distance(element.y, y1)) * + window.devicePixelRatio * + zoom.value + : 0; context.translate(canvasOffsetX, canvasOffsetY); } else { @@ -178,9 +176,9 @@ const drawImagePlaceholder = ( ); context.drawImage( - element.status === "error" - ? IMAGE_ERROR_PLACEHOLDER_IMG - : IMAGE_PLACEHOLDER_IMG, + element.status === "error" ? + IMAGE_ERROR_PLACEHOLDER_IMG + : IMAGE_PLACEHOLDER_IMG, element.width / 2 - size / 2, element.height / 2 - size / 2, size, @@ -228,8 +226,8 @@ const drawElementOnCanvas = ( break; } case "image": { - const img = isInitializedImageElement(element) - ? renderConfig.imageCache.get(element.fileId)?.image + const img = isInitializedImageElement(element) ? + renderConfig.imageCache.get(element.fileId)?.image : undefined; if (img != null && !(img instanceof Promise)) { context.drawImage( @@ -264,11 +262,9 @@ const drawElementOnCanvas = ( const lineHeight = element.height / lines.length; const verticalOffset = element.height - element.baseline; const horizontalOffset = - element.textAlign === "center" - ? element.width / 2 - : element.textAlign === "right" - ? element.width - : 0; + element.textAlign === "center" ? element.width / 2 + : element.textAlign === "right" ? element.width + : 0; for (let index = 0; index < lines.length; index++) { context.fillText( lines[index], @@ -311,20 +307,18 @@ export const generateRoughOptions = ( const options: Options = { seed: element.seed, strokeLineDash: - element.strokeStyle === "dashed" - ? getDashArrayDashed(element.strokeWidth) - : element.strokeStyle === "dotted" - ? getDashArrayDotted(element.strokeWidth) - : undefined, + element.strokeStyle === "dashed" ? getDashArrayDashed(element.strokeWidth) + : element.strokeStyle === "dotted" ? + getDashArrayDotted(element.strokeWidth) + : undefined, // for non-solid strokes, disable multiStroke because it tends to make // dashes/dots overlay each other disableMultiStroke: element.strokeStyle !== "solid", // for non-solid strokes, increase the width a bit to make it visually // similar to solid strokes, because we're also disabling multiStroke - strokeWidth: - element.strokeStyle !== "solid" - ? element.strokeWidth + 0.5 - : element.strokeWidth, + strokeWidth: element.strokeStyle !== "solid" ? + element.strokeWidth + 0.5 + : element.strokeWidth, // when increasing strokeWidth, we must explicitly set fillWeight and // hachureGap because if not specified, roughjs uses strokeWidth to // calculate them (and we don't want the fills to be modified) @@ -342,10 +336,8 @@ export const generateRoughOptions = ( case "diamond": case "ellipse": { options.fillStyle = element.fillStyle; - options.fill = - element.backgroundColor === "transparent" - ? undefined - : element.backgroundColor; + options.fill = element.backgroundColor === "transparent" ? undefined + : element.backgroundColor; if (element.type === "ellipse") { options.curveFitting = 1; } @@ -354,10 +346,8 @@ export const generateRoughOptions = ( case "line": { if (isPathALoop(element.points)) { options.fillStyle = element.fillStyle; - options.fill = - element.backgroundColor === "transparent" - ? undefined - : element.backgroundColor; + options.fill = element.backgroundColor === "transparent" ? undefined + : element.backgroundColor; } return options; } @@ -623,14 +613,16 @@ const drawElementFromCanvas = ( const _isPendingImageElement = isPendingImageElement(element, renderConfig); - const scaleXFactor = - "scale" in elementWithCanvas.element && !_isPendingImageElement - ? elementWithCanvas.element.scale[0] - : 1; - const scaleYFactor = - "scale" in elementWithCanvas.element && !_isPendingImageElement - ? elementWithCanvas.element.scale[1] - : 1; + const scaleXFactor = ( + "scale" in elementWithCanvas.element && !_isPendingImageElement + ) ? + elementWithCanvas.element.scale[0] + : 1; + const scaleYFactor = ( + "scale" in elementWithCanvas.element && !_isPendingImageElement + ) ? + elementWithCanvas.element.scale[1] + : 1; context.save(); context.scale( @@ -919,18 +911,14 @@ export const renderElementToSvg = ( const lineHeight = element.height / lines.length; const verticalOffset = element.height - element.baseline; const horizontalOffset = - element.textAlign === "center" - ? element.width / 2 - : element.textAlign === "right" - ? element.width - : 0; + element.textAlign === "center" ? element.width / 2 + : element.textAlign === "right" ? element.width + : 0; const direction = isRTL(element.text) ? "rtl" : "ltr"; const textAnchor = - element.textAlign === "center" - ? "middle" - : element.textAlign === "right" || direction === "rtl" - ? "end" - : "start"; + element.textAlign === "center" ? "middle" + : element.textAlign === "right" || direction === "rtl" ? "end" + : "start"; for (let i = 0; i < lines.length; i++) { const text = svgRoot.ownerDocument!.createElementNS(SVG_NS, "text"); text.textContent = lines[i]; @@ -968,10 +956,10 @@ export function getFreeDrawPath2D(element: ExcalidrawFreeDrawElement) { export function getFreeDrawSvgPath(element: ExcalidrawFreeDrawElement) { // If input points are empty (should they ever be?) return a dot - const inputPoints = element.simulatePressure - ? element.points - : element.points.length - ? element.points.map(([x, y], i) => [x, y, element.pressures[i]]) + const inputPoints = + element.simulatePressure ? element.points + : element.points.length ? + element.points.map(([x, y], i) => [x, y, element.pressures[i]]) : [[0, 0, 0.5]]; // Consider changing the options for simulated pressure vs real pressure diff --git ORI/excalidraw/src/renderer/renderScene.ts ALT/excalidraw/src/renderer/renderScene.ts index 9fddadd..4c0714f 100644 --- ORI/excalidraw/src/renderer/renderScene.ts +++ ALT/excalidraw/src/renderer/renderScene.ts @@ -157,10 +157,11 @@ const renderLinearPointHandles = ( (point, idx) => { context.strokeStyle = "red"; context.setLineDash([]); - context.fillStyle = - appState.editingLinearElement?.activePointIndex === idx - ? "rgba(255, 127, 127, 0.9)" - : "rgba(255, 255, 255, 0.9)"; + context.fillStyle = ( + appState.editingLinearElement?.activePointIndex === idx + ) ? + "rgba(255, 127, 127, 0.9)" + : "rgba(255, 255, 255, 0.9)"; const { POINT_HANDLE_SIZE } = LinearElementEditor; fillCircle( context, @@ -654,8 +655,8 @@ const renderBindingHighlight = ( renderConfig: RenderConfig, suggestedBinding: SuggestedBinding, ) => { - const renderHighlight = Array.isArray(suggestedBinding) - ? renderBindingHighlightForSuggestedPointBinding + const renderHighlight = Array.isArray(suggestedBinding) ? + renderBindingHighlightForSuggestedPointBinding : renderBindingHighlightForBindableElement; context.save(); @@ -736,7 +737,9 @@ const renderBindingHighlightForSuggestedPointBinding = ( context.fillStyle = "rgba(0,0,0,.05)"; const pointIndices = - startOrEnd === "both" ? [0, -1] : startOrEnd === "start" ? [0] : [-1]; + startOrEnd === "both" ? [0, -1] + : startOrEnd === "start" ? [0] + : [-1]; pointIndices.forEach((index) => { const [x, y] = LinearElementEditor.getPointAtIndexGlobalCoordinates( element, diff --git ORI/excalidraw/src/scene/scrollbars.ts ALT/excalidraw/src/scene/scrollbars.ts index c36acde..1caa1de 100644 --- ORI/excalidraw/src/scene/scrollbars.ts +++ ALT/excalidraw/src/scene/scrollbars.ts @@ -64,43 +64,39 @@ export const getScrollBars = ( // The scrollbar represents where the viewport is in relationship to the scene return { - horizontal: - viewportMinX === sceneMinX && viewportMaxX === sceneMaxX - ? null - : { - x: - Math.max(safeArea.left, SCROLLBAR_MARGIN) + - ((viewportMinX - sceneMinX) / (sceneMaxX - sceneMinX)) * - viewportWidth, - y: - viewportHeight - + horizontal: viewportMinX === sceneMinX && viewportMaxX === sceneMaxX ? null + : { + x: + Math.max(safeArea.left, SCROLLBAR_MARGIN) + + ((viewportMinX - sceneMinX) / (sceneMaxX - sceneMinX)) * + viewportWidth, + y: + viewportHeight - + SCROLLBAR_WIDTH - + Math.max(SCROLLBAR_MARGIN, safeArea.bottom), + width: + ((viewportMaxX - viewportMinX) / (sceneMaxX - sceneMinX)) * + viewportWidth - + Math.max(SCROLLBAR_MARGIN * 2, safeArea.left + safeArea.right), + height: SCROLLBAR_WIDTH, + }, + vertical: viewportMinY === sceneMinY && viewportMaxY === sceneMaxY ? null + : { + x: isRTL ? + Math.max(safeArea.left, SCROLLBAR_MARGIN) + : viewportWidth - SCROLLBAR_WIDTH - - Math.max(SCROLLBAR_MARGIN, safeArea.bottom), - width: - ((viewportMaxX - viewportMinX) / (sceneMaxX - sceneMinX)) * - viewportWidth - - Math.max(SCROLLBAR_MARGIN * 2, safeArea.left + safeArea.right), - height: SCROLLBAR_WIDTH, - }, - vertical: - viewportMinY === sceneMinY && viewportMaxY === sceneMaxY - ? null - : { - x: isRTL - ? Math.max(safeArea.left, SCROLLBAR_MARGIN) - : viewportWidth - - SCROLLBAR_WIDTH - - Math.max(safeArea.right, SCROLLBAR_MARGIN), - y: - ((viewportMinY - sceneMinY) / (sceneMaxY - sceneMinY)) * - viewportHeight + - Math.max(safeArea.top, SCROLLBAR_MARGIN), - width: SCROLLBAR_WIDTH, - height: - ((viewportMaxY - viewportMinY) / (sceneMaxY - sceneMinY)) * - viewportHeight - - Math.max(SCROLLBAR_MARGIN * 2, safeArea.top + safeArea.bottom), - }, + Math.max(safeArea.right, SCROLLBAR_MARGIN), + y: + ((viewportMinY - sceneMinY) / (sceneMaxY - sceneMinY)) * + viewportHeight + + Math.max(safeArea.top, SCROLLBAR_MARGIN), + width: SCROLLBAR_WIDTH, + height: + ((viewportMaxY - viewportMinY) / (sceneMaxY - sceneMinY)) * + viewportHeight - + Math.max(SCROLLBAR_MARGIN * 2, safeArea.top + safeArea.bottom), + }, }; }; diff --git ORI/excalidraw/src/scene/selection.ts ALT/excalidraw/src/scene/selection.ts index 3c883d8..04261c4 100644 --- ORI/excalidraw/src/scene/selection.ts +++ ALT/excalidraw/src/scene/selection.ts @@ -59,6 +59,6 @@ export const getTargetElements = ( elements: readonly NonDeletedExcalidrawElement[], appState: AppState, ) => - appState.editingElement - ? [appState.editingElement] - : getSelectedElements(elements, appState); + appState.editingElement ? + [appState.editingElement] + : getSelectedElements(elements, appState); diff --git ORI/excalidraw/src/shapes.tsx ALT/excalidraw/src/shapes.tsx index c4b98a8..2d3abf8 100644 --- ORI/excalidraw/src/shapes.tsx +++ ALT/excalidraw/src/shapes.tsx @@ -112,9 +112,9 @@ export const findShapeByKey = (key: string) => { return ( key === (index + 1).toString() || (shape.key && - (typeof shape.key === "string" - ? shape.key === key - : (shape.key as readonly string[]).includes(key))) + (typeof shape.key === "string" ? + shape.key === key + : (shape.key as readonly string[]).includes(key))) ); }); return shape?.value || null; diff --git ORI/excalidraw/src/tests/helpers/api.ts ALT/excalidraw/src/tests/helpers/api.ts index 557d9e8..0786065 100644 --- ORI/excalidraw/src/tests/helpers/api.ts +++ ALT/excalidraw/src/tests/helpers/api.ts @@ -91,16 +91,12 @@ export class API { fontSize?: T extends "text" ? ExcalidrawTextElement["fontSize"] : never; fontFamily?: T extends "text" ? ExcalidrawTextElement["fontFamily"] : never; textAlign?: T extends "text" ? ExcalidrawTextElement["textAlign"] : never; - verticalAlign?: T extends "text" - ? ExcalidrawTextElement["verticalAlign"] - : never; - }): T extends "arrow" | "line" - ? ExcalidrawLinearElement - : T extends "freedraw" - ? ExcalidrawFreeDrawElement - : T extends "text" - ? ExcalidrawTextElement - : ExcalidrawGenericElement => { + verticalAlign?: T extends "text" ? ExcalidrawTextElement["verticalAlign"] + : never; + }): T extends "arrow" | "line" ? ExcalidrawLinearElement + : T extends "freedraw" ? ExcalidrawFreeDrawElement + : T extends "text" ? ExcalidrawTextElement + : ExcalidrawGenericElement => { let element: Mutable = null!; const appState = h?.state || getDefaultAppState(); @@ -175,8 +171,7 @@ export class API { filepath: string, encoding?: T, ): Promise => { - filepath = path.isAbsolute(filepath) - ? filepath + filepath = path.isAbsolute(filepath) ? filepath : path.resolve(path.join(__dirname, "../", filepath)); return readFile(filepath, { encoding }) as any; }; diff --git ORI/excalidraw/src/tests/helpers/ui.ts ALT/excalidraw/src/tests/helpers/ui.ts index 8e70a8c..5156d1d 100644 --- ORI/excalidraw/src/tests/helpers/ui.ts +++ ALT/excalidraw/src/tests/helpers/ui.ts @@ -249,18 +249,14 @@ export class UI { height?: number; angle?: number; } = {}, - ): (T extends "arrow" | "line" | "freedraw" - ? ExcalidrawLinearElement - : T extends "text" - ? ExcalidrawTextElement - : ExcalidrawElement) & { + ): (T extends "arrow" | "line" | "freedraw" ? ExcalidrawLinearElement + : T extends "text" ? ExcalidrawTextElement + : ExcalidrawElement) & { /** Returns the actual, current element from the elements array, instead of the proxy */ - get(): T extends "arrow" | "line" | "freedraw" - ? ExcalidrawLinearElement - : T extends "text" - ? ExcalidrawTextElement - : ExcalidrawElement; + get(): T extends "arrow" | "line" | "freedraw" ? ExcalidrawLinearElement + : T extends "text" ? ExcalidrawTextElement + : ExcalidrawElement; } { UI.clickTool(type); mouse.reset(); diff --git ORI/excalidraw/src/zindex.ts ALT/excalidraw/src/zindex.ts index ac9cf7d..f865fe7 100644 --- ORI/excalidraw/src/zindex.ts +++ ALT/excalidraw/src/zindex.ts @@ -70,10 +70,9 @@ const getTargetIndex = ( return true; }; - const candidateIndex = - direction === "left" - ? findLastIndex(elements, indexFilter, Math.max(0, boundaryIndex - 1)) - : findIndex(elements, indexFilter, boundaryIndex + 1); + const candidateIndex = direction === "left" ? + findLastIndex(elements, indexFilter, Math.max(0, boundaryIndex - 1)) + : findIndex(elements, indexFilter, boundaryIndex + 1); const nextElement = elements[candidateIndex]; @@ -97,8 +96,8 @@ const getTargetIndex = ( return candidateIndex; } - const siblingGroupId = appState.editingGroupId - ? nextElement.groupIds[ + const siblingGroupId = appState.editingGroupId ? + nextElement.groupIds[ nextElement.groupIds.indexOf(appState.editingGroupId) - 1 ] : nextElement.groupIds[nextElement.groupIds.length - 1]; @@ -108,8 +107,8 @@ const getTargetIndex = ( if (elementsInSiblingGroup.length) { // assumes getElementsInGroup() returned elements are sorted // by zIndex (ascending) - return direction === "left" - ? elements.indexOf(elementsInSiblingGroup[0]) + return direction === "left" ? + elements.indexOf(elementsInSiblingGroup[0]) : elements.indexOf( elementsInSiblingGroup[elementsInSiblingGroup.length - 1], ); @@ -158,34 +157,30 @@ const shiftElements = ( return; } - const leadingElements = - direction === "left" - ? elements.slice(0, targetIndex) - : elements.slice(0, leadingIndex); + const leadingElements = direction === "left" ? + elements.slice(0, targetIndex) + : elements.slice(0, leadingIndex); const targetElements = elements.slice(leadingIndex, trailingIndex + 1); - const displacedElements = - direction === "left" - ? elements.slice(targetIndex, leadingIndex) - : elements.slice(trailingIndex + 1, targetIndex + 1); - const trailingElements = - direction === "left" - ? elements.slice(trailingIndex + 1) - : elements.slice(targetIndex + 1); - - elements = - direction === "left" - ? [ - ...leadingElements, - ...targetElements, - ...displacedElements, - ...trailingElements, - ] - : [ - ...leadingElements, - ...displacedElements, - ...targetElements, - ...trailingElements, - ]; + const displacedElements = direction === "left" ? + elements.slice(targetIndex, leadingIndex) + : elements.slice(trailingIndex + 1, targetIndex + 1); + const trailingElements = direction === "left" ? + elements.slice(trailingIndex + 1) + : elements.slice(targetIndex + 1); + + elements = direction === "left" ? + [ + ...leadingElements, + ...targetElements, + ...displacedElements, + ...trailingElements, + ] + : [ + ...leadingElements, + ...displacedElements, + ...targetElements, + ...trailingElements, + ]; }); return elements.map((element) => { @@ -252,8 +247,8 @@ const shiftElementsToEnd = ( const leadingElements = elements.slice(0, leadingIndex); const trailingElements = elements.slice(trailingIndex + 1); - return direction === "left" - ? [ + return direction === "left" ? + [ ...leadingElements, ...targetElements, ...displacedElements, ```
    github-actions[bot] commented 2 years ago

    [Error]

    HttpError: Validation Failed: {"resource":"IssueComment","code":"unprocessable","field":"data","message":"Body is too long (maximum is 65536 characters)"}
    rattrayalex commented 2 years ago

    Some examples that I think look really nice:

               return this.tsParseTupleType();
    @@ -1081,11 +1081,9 @@ export default (superClass: Class<Parser>): Class<Parser> =>
                 type === tt._null
               ) {
                 const nodeType =
    -              type === tt._void
    -                ? "TSVoidKeyword"
    -                : type === tt._null
    -                ? "TSNullKeyword"
    -                : keywordTypeFromName(this.state.value);
    +              type === tt._void ? "TSVoidKeyword"
    +              : type === tt._null ? "TSNullKeyword"
    +              : keywordTypeFromName(this.state.value);
                 if (
                   nodeType !== undefined &&
                   this.lookaheadCharCode() !== charCodes.dot
    @@ -1157,11 +1155,11 @@ export default (superClass: Class<Parser>): Class<Parser> =>
         tsParseTypeOperatorOrHigher(): N.TsType {
           const isTypeOperator =
             tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
    -      return isTypeOperator
    -        ? this.tsParseTypeOperator()
    -        : this.isContextual(tt._infer)
    -        ? this.tsParseInferType()
    -        : this.tsParseArrayTypeOrHigher();
    +      return (
    +        isTypeOperator ? this.tsParseTypeOperator()
    +        : this.isContextual(tt._infer) ? this.tsParseInferType()
    +        : this.tsParseArrayTypeOrHigher()
    +      );
         }

    One thing that looks like it might be a bug:

    --- ORI/babel/eslint/babel-eslint-tests/test/integration/config-files.js
    +++ ALT/babel/eslint/babel-eslint-tests/test/integration/config-files.js
    @@ -17,10 +17,11 @@ describe("Babel config files", () => {
         ).toMatchObject({ errorCount: 0 });
       });
    
    -  const babel7node12 =
    -    process.env.BABEL_8_BREAKING || parseInt(process.versions.node) < 12
    -      ? it.skip
    -      : it;
    +  const babel7node12 = (
    +      process.env.BABEL_8_BREAKING || parseInt(process.versions.node) < 12
    +    ) ?
    +      it.skip
    +    : it;

    And I see several examples where the short-consequent case-style looks weird, eg:

    -        this.input.charCodeAt(this.state.pos + 2) === charCodes.equalsTo
    -          ? 3
    -          : 2,
    +        this.input.charCodeAt(this.state.pos + 2) === charCodes.equalsTo ? 3
    +        : 2,