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

92 lines
1.8 KiB
TypeScript
Raw Normal View History

import type { TextDocument, Position } from 'vscode-languageserver'
import { State } from './state'
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',
2020-05-25 18:37:45 +00:00
'gohtml',
'GoHTML',
2020-04-11 21:20:45 +00:00
'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-11-30 15:54:31 +00:00
'mdx',
2020-04-29 10:05:02 +00:00
'mustache',
2020-04-11 21:20:45 +00:00
'njk',
'nunjucks',
'php',
'razor',
'slim',
'twig',
]
export function isHtmlDoc(state: State, doc: TextDocument): boolean {
const userHtmlLanguages = Object.keys(
state.editor.userLanguages
).filter((lang) => HTML_LANGUAGES.includes(state.editor.userLanguages[lang]))
return (
[...HTML_LANGUAGES, ...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
}