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

78 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-04-11 22:34:03 +00:00
import { TextDocument, Position } from 'vscode-languageserver'
2020-04-11 21:20:45 +00:00
export const HTML_LANGUAGES = [
2020-04-28 21:54:52 +00:00
'aspnetcorerazor',
2020-04-11 21:20:45 +00:00
'blade',
'django-html',
'edge',
'ejs',
'erb',
'haml',
'handlebars',
2020-04-28 21:54:52 +00:00
'hbs',
2020-04-11 21:20:45 +00:00
'html',
'HTML (Eex)',
2020-04-30 08:57:06 +00:00
'HTML (EEx)',
'html-eex',
2020-04-11 21:20:45 +00:00
'jade',
'leaf',
2020-04-28 21:54:52 +00:00
'liquid',
2020-04-11 21:20:45 +00:00
'markdown',
2020-04-29 10:05:02 +00:00
'mustache',
2020-04-11 21:20:45 +00:00
'njk',
'nunjucks',
'php',
'razor',
'slim',
'twig',
]
2020-04-16 21:39:16 +00:00
export function isHtmlDoc(doc: TextDocument): boolean {
2020-04-11 21:20:45 +00:00
return HTML_LANGUAGES.indexOf(doc.languageId) !== -1
}
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(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(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
}