tailwind-ctp-intellisense/packages/tailwindcss-language-service/src/util/html.ts

57 lines
1.5 KiB
TypeScript
Raw Normal View History

import type { TextDocument, Position } from 'vscode-languageserver'
import { State } from './state'
import { htmlLanguages } from './languages'
2020-04-11 21:20:45 +00:00
export function isHtmlDoc(state: State, doc: TextDocument): boolean {
const userHtmlLanguages = Object.keys(state.editor.userLanguages).filter((lang) =>
htmlLanguages.includes(state.editor.userLanguages[lang])
)
return [...htmlLanguages, ...userHtmlLanguages].indexOf(doc.languageId) !== -1
2020-04-11 21:20:45 +00:00
}
2020-04-11 22:34:03 +00:00
2020-04-16 21:39:16 +00:00
export function isVueDoc(doc: TextDocument): boolean {
2020-04-11 22:34:03 +00:00
return doc.languageId === 'vue'
}
2020-04-16 21:39:16 +00:00
export function isSvelteDoc(doc: TextDocument): boolean {
2020-04-11 22:34:03 +00:00
return doc.languageId === 'svelte'
}
export function isHtmlContext(state: State, doc: TextDocument, position: Position): boolean {
2020-04-16 21:39:16 +00:00
let str = doc.getText({
start: { line: 0, character: 0 },
end: position,
})
if (isHtmlDoc(state, doc) && !isInsideTag(str, ['script', 'style'])) {
2020-04-11 22:34:03 +00:00
return true
}
2020-04-16 21:39:16 +00:00
if (isVueDoc(doc)) {
return isInsideTag(str, ['template'])
}
2020-04-11 22:34:03 +00:00
2020-04-16 21:39:16 +00:00
if (isSvelteDoc(doc)) {
return !isInsideTag(str, ['script', 'style'])
2020-04-11 22:34:03 +00:00
}
return false
}
export function isInsideTag(str: string, tag: string | string[]): boolean {
let open = 0
let close = 0
let match: RegExpExecArray
let tags = Array.isArray(tag) ? tag : [tag]
let regex = new RegExp(`<(?<slash>/?)(?:${tags.join('|')})\\b`, 'ig')
while ((match = regex.exec(str)) !== null) {
if (match.groups.slash) {
close += 1
} else {
open += 1
}
}
return open > 0 && open > close
}