Skip to content

Commit

Permalink
replace tabs with two spaces
Browse files Browse the repository at this point in the history
  • Loading branch information
Trapfether committed Nov 29, 2023
1 parent e796696 commit 8364567
Show file tree
Hide file tree
Showing 4 changed files with 213 additions and 202 deletions.
19 changes: 8 additions & 11 deletions src/config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,11 @@ function loadTailwindConfig(baseDir, tailwindConfigPath) {
let resolveConfig = resolveConfigFallback
let loadConfig = loadConfigFallback
let tailwindConfig = {
// all html, css, and js files in the workspace
content: ['**/*.html', '**/*.css', '**/*.js'],
plugins: [
],
corePlugins: {
preflight: false,
},
}
// all html, css, and js files in the workspace
content: ['**/*.html', '**/*.css', '**/*.js'],
plugins: [
]
}

try {
let pkgDir = path.dirname(resolveFrom(baseDir, 'tailwindcss/package.json'))
Expand All @@ -113,7 +110,7 @@ function loadTailwindConfig(baseDir, tailwindConfigPath) {
// Prior to `[email protected]` this won't exist so we load it last
loadConfig = require(path.join(pkgDir, 'loadConfig'))
} catch {
}
}

if (tailwindConfigPath) {
clearModule(tailwindConfigPath)
Expand Down Expand Up @@ -146,8 +143,8 @@ function getConfigPath(options, baseDir) {

let configPath
try {
// This is a hack because typescript does not correctly resolve the type of the import
const useEscalade = /** @type {escalade.default} */(/** @type {unknown} */(escalade));
// This is a hack because typescript does not correctly resolve the type of the import
const useEscalade = /** @type {escalade.default} */(/** @type {unknown} */(escalade));
configPath = useEscalade(baseDir, (_dir, names) => {
if (names.includes('tailwind.config.js')) {
return 'tailwind.config.js'
Expand Down
262 changes: 138 additions & 124 deletions src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,133 +19,147 @@ import { sortClasses } from './sorting.mjs'
const config = workspace.getConfiguration();
/** @type {{ [key: string]: LangConfig | LangConfig[] }} */
const langConfig =
config.get('tailwind-raw-reorder.classRegex') || {};
config.get('tailwind-raw-reorder.classRegex') || {};

/**
* @param {ExtensionContext} context
*/
export function activate(context) {
let disposable = commands.registerTextEditorCommand(
'tailwind-raw-reorder.sortTailwindClasses',
function (editor, edit) {
const editorText = editor.document.getText();
const editorLangId = editor.document.languageId;
const editorFilePath = editor.document.fileName;

const matchers = buildMatchers(
langConfig[editorLangId] || langConfig['html']
);

const tailwindConfig = getTailwindConfig({
filepath: editorFilePath
});

for (const matcher of matchers) {
getTextMatch(matcher.regex, editorText, (text, startPosition) => {
const endPosition = startPosition + text.length;
const range = new Range(
editor.document.positionAt(startPosition),
editor.document.positionAt(endPosition)
);

const options = {
separator: matcher.separator,
replacement: matcher.replacement,
env: tailwindConfig
};

edit.replace(
range,
sortClasses(text, options)
);
});
}
}
);

let runOnProject = commands.registerCommand(
'tailwind-raw-reorder.sortTailwindClassesOnWorkspace',
() => {
let workspaceFolder = workspace.workspaceFolders || [];
if (workspaceFolder[0]) {
window.showInformationMessage(
`Running Tailwind Raw Reorder on: ${workspaceFolder[0].uri.fsPath}`
);

let rustyWindArgs = [
workspaceFolder[0].uri.fsPath,
'--write',
].filter((arg) => arg !== '');

let rustyWindProc = spawn(rustyWindPath, rustyWindArgs);

rustyWindProc.stdout.on(
'data',
(data) =>
data &&
data.toString() !== '' &&
console.log('rustywind stdout:\n', data.toString())
);

rustyWindProc.stderr.on('data', (data) => {
if (data && data.toString() !== '') {
console.log('rustywind stderr:\n', data.toString());
window.showErrorMessage(`Tailwind Raw Reorder error: ${data.toString()}`);
}
});
}
}
);

let runOnSelection = commands.registerCommand(
'tailwind-raw-reorder.sortTailwindClassesOnSelection',
() => {
let editor = window.activeTextEditor;
if (editor) {
let selection = editor.selection;
let editorText = editor.document.getText(selection);
let editorLangId = editor.document.languageId;
let editorFilePath = editor.document.fileName;

const matchers = buildMatchers(
langConfig[editorLangId] || langConfig['html']
);

const tailwindConfig = getTailwindConfig({
filepath: editorFilePath
});

for (const matcher of matchers) {
const seperator = matcher.separator;
const replacement = matcher.replacement;

//regex that matches a seperator seperated list of classes that may contain letters, numbers, dashes, underscores, square brackets, square brackets with single quotes inside, and forward slashes
const regexContent = `(?:[a-zA-Z][a-zA-Z\\/_\\-:]+(?:\\[[a-zA-Z\\/_\\-"'\\\\:\\.]\\])?(${(seperator || /\s/).source})*)+`;
const regex = new RegExp(regexContent);
if (regex.test(editorText)) {
const sortedText = sortClasses(editorText, {
seperator: seperator,
replacement,
env: tailwindConfig
});
editor.edit((editBuilder) => {
editBuilder.replace(selection, sortedText);
});
}
}
}
}
);

context.subscriptions.push(runOnProject);
context.subscriptions.push(disposable);

// if runOnSave is enabled organize tailwind classes before saving
if (config.get('tailwind-raw-reorder.runOnSave')) {
context.subscriptions.push(
workspace.onWillSaveTextDocument((_e) => {
commands.executeCommand('tailwind-raw-reorder.sortTailwindClasses');
})
);
}
let disposable = commands.registerTextEditorCommand(
'tailwind-raw-reorder.sortTailwindClasses',
function (editor, edit) {
const editorText = editor.document.getText();
const editorLangId = editor.document.languageId;
const editorFilePath = editor.document.fileName;

const matchers = buildMatchers(
langConfig[editorLangId] || langConfig['html']
);

const tailwindConfig = getTailwindConfig({
filepath: editorFilePath
});

if (!tailwindConfig) {
window.showErrorMessage(
'Tailwind Raw Reorder: Tailwind config not found'
);
return;
}

for (const matcher of matchers) {
getTextMatch(matcher.regex, editorText, (text, startPosition) => {
const endPosition = startPosition + text.length;
const range = new Range(
editor.document.positionAt(startPosition),
editor.document.positionAt(endPosition)
);

const options = {
separator: matcher.separator,
replacement: matcher.replacement,
env: tailwindConfig
};

edit.replace(
range,
sortClasses(text, options)
);
});
}
}
);

let runOnProject = commands.registerCommand(
'tailwind-raw-reorder.sortTailwindClassesOnWorkspace',
() => {
let workspaceFolder = workspace.workspaceFolders || [];
if (workspaceFolder[0]) {
window.showInformationMessage(
`Running Tailwind Raw Reorder on: ${workspaceFolder[0].uri.fsPath}`
);

let rustyWindArgs = [
workspaceFolder[0].uri.fsPath,
'--write',
].filter((arg) => arg !== '');

let rustyWindProc = spawn(rustyWindPath, rustyWindArgs);

rustyWindProc.stdout.on(
'data',
(data) =>
data &&
data.toString() !== '' &&
console.log('rustywind stdout:\n', data.toString())
);

rustyWindProc.stderr.on('data', (data) => {
if (data && data.toString() !== '') {
console.log('rustywind stderr:\n', data.toString());
window.showErrorMessage(`Tailwind Raw Reorder error: ${data.toString()}`);
}
});
}
}
);

let runOnSelection = commands.registerCommand(
'tailwind-raw-reorder.sortTailwindClassesOnSelection',
() => {
let editor = window.activeTextEditor;
if (editor) {
let selection = editor.selection;
let editorText = editor.document.getText(selection);
let editorLangId = editor.document.languageId;
let editorFilePath = editor.document.fileName;

const matchers = buildMatchers(
langConfig[editorLangId] || langConfig['html']
);

const tailwindConfig = getTailwindConfig({
filepath: editorFilePath
});

if (!tailwindConfig) {
window.showErrorMessage(
'Tailwind Raw Reorder: Tailwind config not found'
);
return;
}

for (const matcher of matchers) {
const seperator = matcher.separator;
const replacement = matcher.replacement;

//regex that matches a seperator seperated list of classes that may contain letters, numbers, dashes, underscores, square brackets, square brackets with single quotes inside, and forward slashes
const regexContent = `(?:[a-zA-Z][a-zA-Z\\/_\\-:]+(?:\\[[a-zA-Z\\/_\\-"'\\\\:\\.]\\])?(${(seperator || /\s/).source})*)+`;
const regex = new RegExp(regexContent);
if (regex.test(editorText)) {
const sortedText = sortClasses(editorText, {
seperator: seperator,
replacement,
env: tailwindConfig
});
editor.edit((editBuilder) => {
editBuilder.replace(selection, sortedText);
});
}
}
}
}
);

context.subscriptions.push(runOnProject);
context.subscriptions.push(disposable);

// if runOnSave is enabled organize tailwind classes before saving
if (config.get('tailwind-raw-reorder.runOnSave')) {
context.subscriptions.push(
workspace.onWillSaveTextDocument((_e) => {
commands.executeCommand('tailwind-raw-reorder.sortTailwindClasses');
})
);
}
}
10 changes: 5 additions & 5 deletions src/sorting.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
* @returns {number}
*/
export function bigSign(bigIntValue) {
const a = (bigIntValue > 0n) ? 1 : 0;
const b = (bigIntValue < 0n) ? 1 : 0;
const a = (bigIntValue > 0n) ? 1 : 0;
const b = (bigIntValue < 0n) ? 1 : 0;
return a - b;
}

Expand Down Expand Up @@ -46,12 +46,12 @@ function getClassOrderPolyfill(classes, { env }) {
prefixCandidate(env.context, 'peer'),
])

/** @type {[string, number][]} */
/** @type {[string, number][]} */
let classNamesWithOrder = [];

for (let className of classes) {
let rules = env
.generateRules(new Set([className]), env.context);
let rules = env
.generateRules(new Set([className]), env.context);
let order = rules.sort(([a], [z]) => bigSign(z - a))[0]?.[0] ?? null

if (order === null && parasiteUtilities.has(className)) {
Expand Down
Loading

0 comments on commit 8364567

Please sign in to comment.