eslint-plugin-logical-properties
Version:
63 lines (62 loc) • 2.52 kB
JavaScript
import { MustDisablePropertyError } from '../utils/MustDisablePropertyError.js';
import { stringToTemplate, tokenizeString, } from '../utils/tokenizeString.js';
import { getValidPropertyName } from '../utils/getValidPropertyName.js';
export const generateDirectionalShorthandError = (source, targets) => (`${source} should be replaced with the following properties: \n${targets.map((it) => `- ${it}`).join('\n')}`);
export const expandShorthandOptions = (options, values, isTemplateString = false) => {
const results = [];
for (const [index, value] of Object.entries(values)) {
const localMappings = options[+index];
const localResult = localMappings.map((mapping) => {
const localValue = isTemplateString
? `\`${value}\``
: `${value}`;
return `"${mapping}":${localValue}`;
});
results.push(...localResult);
}
return results;
};
const getPropertyValues = (context, property) => {
const sourceCode = context.sourceCode.getText(property.value);
if (!/^["'`].*["'`]$/.test(sourceCode)) {
return {
isTemplateString: false,
values: [sourceCode],
replacements: [],
};
}
const stringToTokenize = stringToTemplate(sourceCode
.replace(/^["'`]/, '')
.replace(/["'`]$/, ''));
const { output, tokens } = tokenizeString(stringToTokenize);
const values = output.split(' ');
return {
isTemplateString: true,
values,
replacements: tokens,
};
};
export const directionalShorthandTransformerFactory = ({ node, context, config: { shorthands = {}, }, }) => (property) => {
const propertyName = getValidPropertyName(property);
const { values, replacements, isTemplateString, } = getPropertyValues(context, property);
const options = shorthands[propertyName][values.length - 1];
if (!options) {
throw new MustDisablePropertyError();
}
const sourceText = context.sourceCode.getText(property);
const results = expandShorthandOptions(options, values, isTemplateString)
.map((it) => {
let final = it;
for (const [target, value] of replacements) {
final = final.replace(target, value);
}
return final;
});
context.report({
node: node,
message: generateDirectionalShorthandError(sourceText, results),
fix(fixer) {
return fixer.replaceText(property, results.join(','));
},
});
};