2020-10-08 15:20:54 +00:00
|
|
|
import type { TextDocument, Position } from 'vscode-languageserver'
|
2020-05-03 17:11:45 +00:00
|
|
|
import { State } from './state'
|
2021-06-01 11:37:15 +00:00
|
|
|
import { htmlLanguages } from './languages'
|
2020-04-11 21:20:45 +00:00
|
|
|
|
2020-05-03 17:11:45 +00:00
|
|
|
export function isHtmlDoc(state: State, doc: TextDocument): boolean {
|
2021-06-01 11:37:15 +00:00
|
|
|
const userHtmlLanguages = Object.keys(state.editor.userLanguages).filter((lang) =>
|
|
|
|
htmlLanguages.includes(state.editor.userLanguages[lang])
|
2020-05-03 17:11:45 +00:00
|
|
|
)
|
2021-06-01 11:37:15 +00:00
|
|
|
|
|
|
|
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'
|
|
|
|
}
|
|
|
|
|
2021-06-01 11:37:15 +00:00
|
|
|
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,
|
|
|
|
})
|
|
|
|
|
2020-05-03 17:11:45 +00:00
|
|
|
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
|
|
|
|
}
|