Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 54 additions & 43 deletions src/volar/entries/sfc-typed-router.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { relative } from 'pathe'
import type { VueLanguagePlugin } from '@vue/language-core'
import { replaceAll, toString } from 'muggle-string'
import { replaceSourceRange, toString } from 'muggle-string'
import { augmentVlsCtx } from '../utils/augment-vls-ctx'
import type ts from 'typescript'

/*
Future ideas:
Expand All @@ -13,21 +14,11 @@ import { augmentVlsCtx } from '../utils/augment-vls-ctx'
- (low priority) Enhance typing of `to` route in `beforeEnter` route guards defined in `definePage`
*/

const plugin: VueLanguagePlugin = (ctx) => {
const plugin: VueLanguagePlugin = ({
compilerOptions,
modules: { typescript: ts },
}) => {
const RE = {
USE_ROUTE: {
/**
* Targets the spot between `useRoute` and `()`
*/
BEFORE_PARENTHESES: /(?<=useRoute)(\s*)(?=\(\))/g,
/**
* Targets the spot right before `useRoute()`
*/
BEFORE: /(?=useRoute(\s*)\(\))/g,
/** Targets the spot right after `useRoute()` */
AFTER: /(?<=useRoute(\s*)\(\))/g,
},

DOLLAR_ROUTE: {
/**
* When using `$route` in a template, it is referred
Expand All @@ -39,39 +30,62 @@ const plugin: VueLanguagePlugin = (ctx) => {

return {
version: 2.1,
resolveEmbeddedCode(fileName, _sfc, embeddedCode) {
resolveEmbeddedCode(fileName, sfc, embeddedCode) {
if (!embeddedCode.id.startsWith('script_')) {
return
}

// TODO: Do we want to apply this to EVERY .vue file or only to components that the user wrote themselves?

// NOTE: this might not work if different from the root passed to VueRouter unplugin
const relativeFilePath = ctx.compilerOptions.baseUrl
? relative(ctx.compilerOptions.baseUrl, fileName)
const relativeFilePath = compilerOptions.baseUrl
? relative(compilerOptions.baseUrl, fileName)
: fileName

const useRouteNameType = `import('vue-router/auto-routes')._RouteNamesForFilePath<'${relativeFilePath}'>`
const useRouteNameTypeParam = `<${useRouteNameType}>`
const typedCall = `useRoute${useRouteNameTypeParam}`

if (embeddedCode.id.startsWith('script_ts')) {
// Inserts type param into `useRoute()` calls.
// We only apply this mutation on <script setup> blocks with lang="ts".
replaceAll(
embeddedCode.content,
RE.USE_ROUTE.BEFORE_PARENTHESES,
useRouteNameTypeParam
)
} else if (embeddedCode.id.startsWith('script_js')) {
// Typecasts `useRoute()` calls.
// We only apply this mutation on plain JS <script setup> blocks.
replaceAll(embeddedCode.content, RE.USE_ROUTE.BEFORE, `(`)
replaceAll(
embeddedCode.content,
RE.USE_ROUTE.AFTER,
` as ReturnType<typeof ${typedCall}>)`
)
if (sfc.scriptSetup) {
visit(sfc.scriptSetup.ast)
}

function visit(node: ts.Node) {
if (
ts.isCallExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === 'useRoute' &&
!node.typeArguments &&
!node.arguments.length
) {
if (!sfc.scriptSetup!.lang.startsWith('js')) {
replaceSourceRange(
embeddedCode.content,
sfc.scriptSetup!.name,
node.expression.end,
node.expression.end,
useRouteNameTypeParam
)
} else {
const start = node.getStart(sfc.scriptSetup!.ast)
replaceSourceRange(
embeddedCode.content,
sfc.scriptSetup!.name,
start,
start,
`(`
)
replaceSourceRange(
embeddedCode.content,
sfc.scriptSetup!.name,
node.end,
node.end,
` as ReturnType<typeof ${typedCall}>)`
)
}
} else {
ts.forEachChild(node, visit)
}
}

const contentStr = toString(embeddedCode.content)
Expand All @@ -80,21 +94,18 @@ const plugin: VueLanguagePlugin = (ctx) => {

// Augment `__VLS_ctx.$route` to override the typings of `$route` in template blocks
if (contentStr.match(RE.DOLLAR_ROUTE.VLS_CTX)) {
vlsCtxAugmentations.push(`$route: ReturnType<typeof ${typedCall}>;`)
vlsCtxAugmentations.push(
`{} as { $route: ReturnType<typeof ${typedCall}> }`
)
}

// We can try augmenting the types for `RouterView` below.
// if (contentStr.includes(`__VLS_WithComponent<'RouterView', __VLS_LocalComponents`)) {
// vlsCtxAugmentations.push(`RouterView: 'test';`)
// }

if (vlsCtxAugmentations.length > 0) {
augmentVlsCtx(
embeddedCode.content,
() => ` & {
${vlsCtxAugmentations.join('\n ')}
}`
)
if (vlsCtxAugmentations.length) {
augmentVlsCtx(embeddedCode.content, vlsCtxAugmentations)
}
},
}
Expand Down
8 changes: 4 additions & 4 deletions src/volar/utils/augment-vls-ctx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import type { Code } from '@vue/language-core'
* Augments the VLS context (volar) with additianal type information.
*
* @param content - content retrieved from the volar pluign
* @param getCodes - function that computes the code to add to the VLS context.
* @param codes - codes to add to the VLS context
*/
export function augmentVlsCtx(content: Code[], getCodes: () => ` & ${string}`) {
export function augmentVlsCtx(content: Code[], codes: Code[]) {
let from = -1
let to = -1

Expand All @@ -19,7 +19,7 @@ export function augmentVlsCtx(content: Code[], getCodes: () => ` & ${string}`) {

if (from === -1 && code.startsWith(`const __VLS_ctx`)) {
from = i
} else if (from !== -1 && code === `;\n`) {
} else if (from !== -1 && code === `}`) {
to = i
break
}
Expand All @@ -30,5 +30,5 @@ export function augmentVlsCtx(content: Code[], getCodes: () => ` & ${string}`) {
}

// TODO: getCodes should return a Code[] type but unsure of how to build that
content.splice(to, 0, getCodes())
content.splice(to, 0, ...codes.map((code) => `...${code},\n`))
}
Loading