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(editor): editor highlight for variant groups #1468

Merged
merged 4 commits into from
Aug 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/inspector/client/components/CodeMirror.vue
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ onMounted(async () => {
function highlight() {
// clear previous
decorations.forEach(i => i.clear())
getMatchedPositions(props.modelValue, Array.from(props.matched || []))
getMatchedPositions(props.modelValue, Array.from(props.matched || []), true)
.forEach(i => mark(i[0], i[1]))
}

Expand Down
50 changes: 45 additions & 5 deletions packages/shared-common/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { e, isAttributifySelector } from '@unocss/core'
import type { UnoGenerator } from '@unocss/core'
import { e, isAttributifySelector, regexClassGroup } from '@unocss/core'
import MagicString from 'magic-string'

// https://github.com/dsblv/string-replace-async/blob/main/index.js
export function replaceAsync(string: string, searchValue: RegExp, replacer: (...args: string[]) => Promise<string>) {
Expand Down Expand Up @@ -26,7 +28,7 @@ export function replaceAsync(string: string, searchValue: RegExp, replacer: (...
}
}

export function getMatchedPositions(code: string, matched: string[]) {
export function getMatchedPositions(code: string, matched: string[], hasVariantGroup = false) {
const result: [number, number, string][] = []
const attributify: RegExpMatchArray[] = []
const plain = new Set<string>()
Expand All @@ -44,13 +46,36 @@ export function getMatchedPositions(code: string, matched: string[]) {

// hightlight for plain classes
let start = 0
code.split(/[\s"'`;<>]/g).forEach((i) => {
code.split(/([\s"'`;<>]|:\(|\)"|\)\s)/g).forEach((i) => {
const end = start + i.length
if (plain.has(i))
result.push([start, end, i])
start = end + 1
start = end
})

// highlight for variant group
if (hasVariantGroup) {
Array.from(code.matchAll(regexClassGroup))
.forEach((match) => {
const [, pre, sep, body] = match
const index = match.index!
let start = index + pre.length + sep.length + 1
body.split(/([\s"'`;<>]|:\(|\)"|\)\s)/g).forEach((i) => {
const end = start + i.length
const full = pre + sep + i
if (plain.has(full)) {
// find existing plain class match and replace it
const index = result.findIndex(([s, e]) => s === start && e === end)
if (index < 0)
result.push([start, end, full])
else
result[index][2] = full
}
start = end
})
})
}

// attributify values
attributify.forEach(([, name, value]) => {
const regex = new RegExp(`(${e(name)}=)(['"])[^\\2]*?${e(value)}[^\\2]*?\\2`, 'g')
Expand All @@ -67,5 +92,20 @@ export function getMatchedPositions(code: string, matched: string[]) {
})
})

return result
return result.sort((a, b) => a[0] - b[0])
}

export async function getMatchedPositionsFromCode(uno: UnoGenerator, code: string, id = '') {
const s = new MagicString(code)
const tokens = new Set()
const ctx = { uno, tokens } as any
for (const i of uno.config.transformers?.filter(i => i.enforce === 'pre') || [])
await i.transform(s, id, ctx)
for (const i of uno.config.transformers?.filter(i => !i.enforce || i.enforce === 'default') || [])
await i.transform(s, id, ctx)
for (const i of uno.config.transformers?.filter(i => i.enforce === 'post') || [])
await i.transform(s, id, ctx)
const hasVariantGroup = !!uno.config.transformers?.find(i => i.name === 'variant-group')
const result = await uno.generate(s.toString(), { preflights: false })
return getMatchedPositions(code, [...result.matched], hasVariantGroup)
}
4 changes: 2 additions & 2 deletions packages/vscode/src/annotation.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path'
import type { DecorationOptions, ExtensionContext, StatusBarItem } from 'vscode'
import { DecorationRangeBehavior, MarkdownString, Range, window, workspace } from 'vscode'
import { INCLUDE_COMMENT_IDE, getMatchedPositions, isCssId } from './integration'
import { INCLUDE_COMMENT_IDE, getMatchedPositionsFromCode, isCssId } from './integration'
import { log } from './log'
import { getColorsMap, getPrettiedMarkdown, isSubdir, throttle } from './utils'
import type { ContextLoader } from './contextLoader'
Expand Down Expand Up @@ -101,7 +101,7 @@ export async function registerAnnotations(

const ranges: DecorationOptions[] = (
await Promise.all(
getMatchedPositions(code, Array.from(result.matched))
(await getMatchedPositionsFromCode(ctx.uno, code))
.map(async (i): Promise<DecorationOptions> => {
// side-effect: update colorRanges
if (colorPreview && colorsMap.has(i[2]) && !_colorPositionsCache.has(`${i[0]}:${i[1]}`)) {
Expand Down
105 changes: 85 additions & 20 deletions test/pos.test.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,100 @@
import { expect, it } from 'vitest'
import { describe, expect, test } from 'vitest'
import presetAttributify from '@unocss/preset-attributify'
import presetUno from '@unocss/preset-uno'
import { createGenerator } from '@unocss/core'
import { getMatchedPositions } from '@unocss/shared-common'
import { getMatchedPositionsFromCode as match } from '@unocss/shared-common'
import transformerVariantGroup from '@unocss/transformer-variant-group'

it('getMatchedPositions', async () => {
const uno = createGenerator({
presets: [
presetAttributify({ strict: true }),
presetUno({ attributifyPseudo: true }),
],
describe('matched-positions', async () => {
test('attributify', async () => {
const uno = createGenerator({
presets: [
presetAttributify({ strict: true }),
presetUno({ attributifyPseudo: true }),
],
})

expect(await match(uno, '<div border="b gray4"></div>'))
.toMatchInlineSnapshot(`
[
[
13,
14,
"[border=\\"b\\"]",
],
[
15,
20,
"[border=\\"gray4\\"]",
],
]
`)
})

async function match(code: string) {
const result = await uno.generate(code, { preflights: false })
return getMatchedPositions(code, [...result.matched])
}
test('class-based', async () => {
const uno = createGenerator({
presets: [
presetUno(),
],
})

expect(await match('<div border="b gray4"></div>'))
.toMatchInlineSnapshot(`
expect(await match(uno, '<div class="bg-gray-900 h-4 hover:scale-100"></div>'))
.toMatchInlineSnapshot(`
[
[
15,
20,
"[border=\\"gray4\\"]",
12,
23,
"bg-gray-900",
],
[
13,
14,
"[border=\\"b\\"]",
24,
27,
"h-4",
],
[
28,
43,
"hover:scale-100",
],
]
`)
})

test('variant-group', async () => {
const uno = createGenerator({
presets: [
presetUno(),
],
transformers: [
transformerVariantGroup(),
],
})

expect(await match(uno, '<div class="hover:(h-4 w-4 bg-green-300) disabled:opacity-50"></div>'))
.toMatchInlineSnapshot(`
[
[
19,
22,
"hover:h-4",
],
[
23,
26,
"hover:w-4",
],
[
27,
39,
"hover:bg-green-300",
],
[
41,
60,
"disabled:opacity-50",
],
]
`)
})
})