76 lines
1.5 KiB
JavaScript
76 lines
1.5 KiB
JavaScript
const estreePlugin = require('prettier/plugins/estree');
|
|
|
|
function hasSpecifierComments(node) {
|
|
return node.specifiers?.some((specifier) => specifier.comments?.length > 0) ?? false;
|
|
}
|
|
|
|
function flattenImportLines(doc) {
|
|
if (typeof doc === 'string') {
|
|
return doc;
|
|
}
|
|
|
|
if (Array.isArray(doc)) {
|
|
return doc.map(flattenImportLines);
|
|
}
|
|
|
|
if (!doc || typeof doc !== 'object') {
|
|
return doc;
|
|
}
|
|
|
|
if (doc.type === 'line') {
|
|
return ' ';
|
|
}
|
|
|
|
if ('contents' in doc) {
|
|
return {
|
|
...doc,
|
|
contents: flattenImportLines(doc.contents)
|
|
};
|
|
}
|
|
|
|
if (doc.type === 'fill' && 'parts' in doc) {
|
|
return {
|
|
...doc,
|
|
parts: flattenImportLines(doc.parts)
|
|
};
|
|
}
|
|
|
|
if (doc.type === 'if-break') {
|
|
return {
|
|
...doc,
|
|
breakContents: flattenImportLines(doc.breakContents),
|
|
flatContents: flattenImportLines(doc.flatContents)
|
|
};
|
|
}
|
|
|
|
if (doc.type === 'group' && 'expandedStates' in doc) {
|
|
return {
|
|
...doc,
|
|
expandedStates: flattenImportLines(doc.expandedStates)
|
|
};
|
|
}
|
|
|
|
return doc;
|
|
}
|
|
|
|
const estreePrinter = estreePlugin.printers.estree;
|
|
|
|
module.exports = {
|
|
printers: {
|
|
estree: {
|
|
...estreePrinter,
|
|
print(path, options, print, args) {
|
|
const printed = estreePrinter.print(path, options, print, args);
|
|
const node = path.getNode();
|
|
|
|
if (node?.type === 'ImportDeclaration' && !hasSpecifierComments(node)) {
|
|
return flattenImportLines(printed);
|
|
}
|
|
|
|
return printed;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|