Skip to content

Add "Sort Selection" command #851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add sortSelection command
  • Loading branch information
bradlc committed May 16, 2022
commit 1588613c40dad88174bae9518f4f426fec3663b0
73 changes: 72 additions & 1 deletion packages/tailwindcss-language-server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ import { getModuleDependencies } from './util/getModuleDependencies'
import assert from 'assert'
// import postcssLoadConfig from 'postcss-load-config'
import * as parcel from './watcher/index.js'
import { generateRules } from 'tailwindcss-language-service/src/util/jit'
import { bigSign } from 'tailwindcss-language-service/src/util/jit'
import { getColor } from 'tailwindcss-language-service/src/util/color'
import * as culori from 'culori'
import namedColors from 'color-name'
Expand Down Expand Up @@ -186,6 +186,7 @@ interface ProjectService {
onDocumentColor(params: DocumentColorParams): Promise<ColorInformation[]>
onColorPresentation(params: ColorPresentationParams): Promise<ColorPresentation[]>
onCodeAction(params: CodeActionParams): Promise<CodeAction[]>
sortClassLists(classLists: string[]): string[]
}

type ProjectConfig = { folder: string; configPath?: string; documentSelector?: string[] }
Expand Down Expand Up @@ -1052,9 +1053,66 @@ async function createProjectService(
.replace(/\d+\.\d+(%?)/g, (value, suffix) => `${Math.round(parseFloat(value))}${suffix}`),
].map((value) => ({ label: `${prefix}-[${value}]` }))
},
sortClassLists(classLists: string[]): string[] {
return classLists.map((classList) => {
let result = ''
let parts = classList.split(/(\s+)/)
let classes = parts.filter((_, i) => i % 2 === 0)
let whitespace = parts.filter((_, i) => i % 2 !== 0)

if (classes[classes.length - 1] === '') {
classes.pop()
}

let classNamesWithOrder = state.jitContext.getClassOrder
? state.jitContext.getClassOrder(classes)
: getClassOrderPolyfill(state, classes)

classes = classNamesWithOrder
.sort(([, a], [, z]) => {
if (a === z) return 0
if (a === null) return -1
if (z === null) return 1
return bigSign(a - z)
})
.map(([className]) => className)

for (let i = 0; i < classes.length; i++) {
result += `${classes[i]}${whitespace[i] ?? ''}`
}

return result
})
},
}
}

function prefixCandidate(state: State, selector: string) {
let prefix = state.config.prefix
return typeof prefix === 'function' ? prefix(selector) : prefix + selector
}

function getClassOrderPolyfill(state: State, classes: string[]): Array<[string, bigint]> {
let parasiteUtilities = new Set([prefixCandidate(state, 'group'), prefixCandidate(state, 'peer')])

let classNamesWithOrder = []

for (let className of classes) {
let order =
state.modules.jit.generateRules
.module(new Set([className]), state.jitContext)
.sort(([a], [z]) => bigSign(z - a))[0]?.[0] ?? null

if (order === null && parasiteUtilities.has(className)) {
order = state.jitContext.layerOrder.components
}

classNamesWithOrder.push([className, order])
}

return classNamesWithOrder
}

function isObject(value: unknown): boolean {
return Object.prototype.toString.call(value) === '[object Object]'
}
Expand Down Expand Up @@ -1449,6 +1507,19 @@ class TW {
this.connection.onDocumentColor(this.onDocumentColor.bind(this))
this.connection.onColorPresentation(this.onColorPresentation.bind(this))
this.connection.onCodeAction(this.onCodeAction.bind(this))
this.connection.onRequest((method, params: { uri: string; classLists: string[] }) => {
if (method === '@/tailwindCSS/sortSelection') {
let project = this.getProject({ uri: params.uri })
if (!project) {
return { error: 'no-project' }
}
try {
return { result: project.sortClassLists(params.classLists) }
} catch {
return { error: 'unknown' }
}
}
})
}

private updateCapabilities() {
Expand Down
5 changes: 5 additions & 0 deletions packages/vscode-tailwindcss/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@
"command": "tailwindCSS.showOutput",
"title": "Tailwind CSS: Show Output",
"enablement": "tailwindCSS.hasOutputChannel"
},
{
"command": "tailwindCSS.sortSelection",
"title": "Tailwind CSS: Sort Selection",
"enablement": "editorHasSelection && resourceScheme == file"
}
],
"grammars": [
Expand Down
52 changes: 52 additions & 0 deletions packages/vscode-tailwindcss/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,58 @@ export async function activate(context: ExtensionContext) {
})
)

async function sortSelection(): Promise<void> {
let { document, selections } = Window.activeTextEditor
if (selections.length === 0) {
return
}
let selectionsJson = JSON.stringify(selections)
let uri = document.uri
let folder = Workspace.getWorkspaceFolder(uri)
if (clients.size === 0 || !folder || isExcluded(uri.fsPath, folder)) {
throw Error(`No active Tailwind project found for file ${document.uri.fsPath}`)
}
folder = getOuterMostWorkspaceFolder(folder)
let client = clients.get(folder.uri.toString())
if (!client) {
throw Error(`No active Tailwind project found for file ${document.uri.fsPath}`)
}
let ranges = selections.map((selection) => new Range(selection.start, selection.end))
let { error, result } = await client.sendRequest('@/tailwindCSS/sortSelection', {
uri: uri.toString(),
classLists: ranges.map((range) => document.getText(range)),
})
if (
Window.activeTextEditor.document.uri.toString() !== uri.toString() ||
JSON.stringify(Window.activeTextEditor.selections) !== selectionsJson
) {
return
}
if (error) {
throw Error(
{
'no-project': `No active Tailwind project found for file ${document.uri.fsPath}`,
unknown: 'An unknown error occurred.',
}[error]
)
}
Window.activeTextEditor.edit((builder) => {
for (let i = 0; i < ranges.length; i++) {
builder.replace(ranges[i], result[i])
}
})
}

context.subscriptions.push(
commands.registerCommand('tailwindCSS.sortSelection', async () => {
try {
await sortSelection()
} catch (error) {
Window.showWarningMessage(`Couldn’t sort Tailwind classes: ${error.message}`)
}
})
)

let watcher = Workspace.createFileSystemWatcher(`**/${CONFIG_FILE_GLOB}`, false, true, true)

watcher.onDidCreate((uri) => {
Expand Down