Skip to content
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

feat(language-service): add language-service package (WIP) #2976

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
18 changes: 18 additions & 0 deletions packages/language-client/.vscode/launch.json
@@ -0,0 +1,18 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
],
"preLaunchTask": "npm: dev"
}
]
}
26 changes: 26 additions & 0 deletions packages/language-client/.vscode/tasks.json
@@ -0,0 +1,26 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "dev",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"problemMatcher": [
{
"base": "$ts-webpack-watch",
"background": {
"activeOnStart": true,
"beginsPattern": "Build start",
"endsPattern": "Build success"
}
}
],
"group": "build"
}
]
}
4 changes: 4 additions & 0 deletions packages/language-client/.vscodeignore
@@ -0,0 +1,4 @@
.github/**
.vscode/**
.vscode-test/**
scripts/**
21 changes: 21 additions & 0 deletions packages/language-client/LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021-PRESENT Anthony Fu <https://github.com/antfu>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
23 changes: 23 additions & 0 deletions packages/language-client/README.md
@@ -0,0 +1,23 @@
<br>

<p align="center">
<img src="https://raw.githubusercontent.com/unocss/unocss/main/packages/vscode/res/logo.png" style="width:100px;" height="128" />
</p>

<h1 align="center">UnoCSS for VS Code</h1>

<p align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=antfu.unocss" target="__blank"><img src="https://img.shields.io/visual-studio-marketplace/v/antfu.unocss.svg?color=eee&amp;label=VS%20Code%20Marketplace&logo=visual-studio-code" alt="Visual Studio Marketplace Version" /></a>
</p>

<br>

## Documentation

Please refer to the [documentation](https://unocss.dev/integrations/vscode).

## License

MIT License &copy; 2021-PRESENT [Anthony Fu](https://github.com/antfu)


120 changes: 120 additions & 0 deletions packages/language-client/package.json
@@ -0,0 +1,120 @@
{
"publisher": "antfu",
"name": "@unocss/language-client",
"displayName": "UnoCSS",
"version": "0.55.4",
"private": true,
"description": "UnoCSS for Language Client",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/unocss/unocss",
"directory": "packages/language-client"
},
"categories": [
"Other"
],
"main": "./dist/index.js",
"preview": true,
"icon": "res/logo.png",
"engines": {
"vscode": "^1.71.0"
},
"activationEvents": [
"onStartupFinished"
],
"contributes": {
"commands": [
{
"command": "unocss.reload",
"title": "Reload UnoCSS",
"category": "UnoCSS"
}
],
"configuration": {
"type": "object",
"title": "UnoCSS",
"properties": {
"unocss.disable": {
"type": "boolean",
"default": false,
"description": "Disable the UnoCSS extension"
},
"unocss.languageIds": {
"type": "array",
"items": {
"type": "string"
}
},
"unocss.root": {
"type": [
"array",
"string"
],
"items": {
"type": "string"
},
"description": "Project root that contains the UnoCSS configuration file"
},
"unocss.underline": {
"type": "boolean",
"default": true,
"description": "Enable/disable underline decoration for class names"
},
"unocss.colorPreview": {
"type": "boolean",
"default": true,
"description": "Enable/disable color preview decorations"
},
"unocss.remToPxPreview": {
"type": "boolean",
"default": false,
"description": "Enable/disable rem to px preview in hover"
},
"unocss.remToPxRatio": {
"type": "number",
"default": 16,
"description": "Ratio of rem to px"
},
"unocss.selectionStyle": {
"type": "boolean",
"default": true,
"description": "Enable/disable selection style decorations"
},
"unocss.autocomplete.matchType": {
"type": "string",
"default": "prefix",
"enum": [
"prefix",
"fuzzy"
],
"description": "The matching type for autocomplete"
},
"unocss.autocomplete.maxItems": {
"type": "number",
"default": 1000,
"description": "The maximum number of items to show in autocomplete"
}
}
}
},
"scripts": {
"build": "tsup",
"dev": "tsup --watch src",
"publish": "esno ./scripts/publish.ts"
},
"dependencies": {
"vscode-languageclient": "^8.1.0"
},
"devDependencies": {
"@types/vscode": "^1.71.0",
"@unocss/language-server": "workspace:*",
"@unocss/nuxt": "workspace:*",
"@unocss/preset-uno": "workspace:*",
"esno": "^0.17.0",
"jiti": "^1.19.1",
"prettier": "^2.8.8",
"tsup": "^7.2.0",
"unconfig": "^0.3.10"
}
}
Binary file added packages/language-client/res/logo.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
31 changes: 31 additions & 0 deletions packages/language-client/scripts/publish.ts
@@ -0,0 +1,31 @@
/* eslint-disable no-console */
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import process from 'node:process'
import fs from 'fs-extra'
import { execa } from 'execa'

const dir = typeof __dirname === 'string' ? __dirname : dirname(fileURLToPath(import.meta.url))
const root = dirname(dir)

async function publish() {
const pkgPath = join(root, 'package.json')
const rawJSON = await fs.readFile(pkgPath, 'utf-8')
const pkg = JSON.parse(rawJSON)
pkg.name = 'unocss'
await fs.writeJSON(pkgPath, pkg, { spaces: 2 })

await execa('npm', ['run', 'build'], { cwd: root, stdio: 'inherit' })

try {
console.log('\nPublish to VSCE...\n')
await execa('npx', ['@vscode/vsce', 'publish', '--no-dependencies', '-p', process.env.VSCE_TOKEN!], { cwd: root, stdio: 'inherit' })
// console.log('\nPublish to OVSE...\n')
// await execa('npx', ['ovsx', 'publish', '--no-dependencies', '-p', process.env.OVSX_TOKEN!], { cwd: root, stdio: 'inherit' })
}
finally {
await fs.writeFile(pkgPath, rawJSON, 'utf-8')
}
}

publish()
95 changes: 95 additions & 0 deletions packages/language-client/src/annotation.ts
@@ -0,0 +1,95 @@
import { fileURLToPath } from 'node:url'
import type { DecorationOptions } from 'vscode'
import { DecorationRangeBehavior, Range, window } from 'vscode'
import type { LanguageClient } from 'vscode-languageclient/node'
import type { AnnotationEventParams } from './types'
import { getMarkdown } from './utils'
import { log } from './log'

export function registerAnnotation(client: LanguageClient) {
const UnderlineDecoration = window.createTextEditorDecorationType({
textDecoration: 'none; border-bottom: 1px dashed currentColor',
rangeBehavior: DecorationRangeBehavior.ClosedClosed,
})

const NoneDecoration = window.createTextEditorDecorationType({
textDecoration: 'none',
rangeBehavior: DecorationRangeBehavior.ClosedClosed,
})

const colorDecoration = window.createTextEditorDecorationType({
before: {
width: '0.9em',
height: '0.9em',
contentText: ' ',
border: '1px solid',
margin: 'auto 0.2em auto 0;vertical-align: middle;border-radius:50%;',
},
dark: {
before: {
borderColor: '#eeeeee50',
},
},
light: {
before: {
borderColor: '#00000050',
},
},
})

const reset = () => {
const editor = window.activeTextEditor
if (editor) {
editor.setDecorations(UnderlineDecoration, [])
editor.setDecorations(NoneDecoration, [])
editor.setDecorations(colorDecoration, [])
}
}

const annotationUpdateHandler = (params: AnnotationEventParams) => {
const editor = window.activeTextEditor
if (!editor) {
log.appendLine(`⚠️ Editor not found for ${params.uri}`)
return
}
if (params.uri === null) {
reset()
log.appendLine(`⚠️ ${params.reason}`)
return
}
const fsPath = fileURLToPath(params.uri)
const doc = editor.document
if (doc.uri.fsPath !== fsPath) {
reset()
return
}
const colorRanges = params.annotations.map<DecorationOptions>((r) => {
const [start, end] = r.range
return {
range: new Range(doc.positionAt(start), doc.positionAt(end)),
get hoverMessage() {
return getMarkdown(r.css, 'css')
},
}
})
if (params.underline) {
editor.setDecorations(UnderlineDecoration, colorRanges)
editor.setDecorations(NoneDecoration, [])
}
else {
editor.setDecorations(UnderlineDecoration, [])
editor.setDecorations(NoneDecoration, colorRanges)
}
}

client.onNotification('unocss/annotation', annotationUpdateHandler)

window.onDidChangeActiveTextEditor((editor) => {
const uri = editor?.document.uri.toString() ?? null
if (uri) {
client.sendNotification('unocss/updateAnnotation', {
uri,
})
}
})
}
49 changes: 49 additions & 0 deletions packages/language-client/src/index.ts
@@ -0,0 +1,49 @@
import { LanguageClient, TransportKind } from 'vscode-languageclient/node'
import type { LanguageClientOptions, ServerOptions } from 'vscode-languageclient/node'
import type { ExtensionContext } from 'vscode'
import { version } from '../package.json'
import { log } from './log'
import { registerAnnotation } from './annotation'

let client: LanguageClient

export async function activate(ext: ExtensionContext) {
log.appendLine(`⚪️ UnoCSS for VS Code v${version}\n`)

const serverModule = ext.asAbsolutePath('dist/server.js')

const serverOptions: ServerOptions = {
run: {
module: serverModule,
transport: TransportKind.ipc,
},
debug: {
module: serverModule,
transport: TransportKind.ipc,
},
}

const clientOptions: LanguageClientOptions = {
documentSelector: [
{ scheme: 'file', language: 'css' },
{ scheme: 'file', language: 'postcss' },
{ scheme: 'file', language: 'html' },
{ scheme: 'file', language: 'vue' },
{ scheme: 'file', language: 'javascript' },
{ scheme: 'file', language: 'javascriptreact' },
],
outputChannel: log,
}

client = new LanguageClient('unocss-lsp', 'UnoCSS LanguageClient', serverOptions, clientOptions)

registerAnnotation(client)

client.registerProposedFeatures()
client.start()
}

export function deactivate() {
if (client)
client.stop()
}
3 changes: 3 additions & 0 deletions packages/language-client/src/log.ts
@@ -0,0 +1,3 @@
import { window } from 'vscode'

export const log = window.createOutputChannel('unocss-lsp')