2022-06-27 11:47:54 +00:00
|
|
|
import type { NuxtTemplate } from '@nuxt/schema'
|
|
|
|
import { join, parse, relative } from 'pathe'
|
|
|
|
import { kebabCase } from 'scule'
|
|
|
|
import { isNuxt2 } from './compatibility'
|
|
|
|
import { useNuxt } from './context'
|
|
|
|
import { logger } from './logger'
|
|
|
|
import { addTemplate } from './template'
|
|
|
|
|
2023-08-30 10:45:16 +00:00
|
|
|
export function addLayout (this: any, template: NuxtTemplate | string, name?: string) {
|
2022-06-27 11:47:54 +00:00
|
|
|
const nuxt = useNuxt()
|
2022-08-22 10:12:02 +00:00
|
|
|
const { filename, src } = addTemplate(template)
|
|
|
|
const layoutName = kebabCase(name || parse(filename).name).replace(/["']/g, '')
|
2022-06-27 11:47:54 +00:00
|
|
|
|
|
|
|
if (isNuxt2(nuxt)) {
|
|
|
|
// Nuxt 2 adds layouts in options
|
2022-10-27 10:36:37 +00:00
|
|
|
const layout = (nuxt.options as any).layouts[layoutName]
|
2022-06-27 11:47:54 +00:00
|
|
|
if (layout) {
|
|
|
|
return logger.warn(
|
2024-04-05 18:08:32 +00:00
|
|
|
`Not overriding \`${layoutName}\` (provided by \`${layout}\`) with \`${src || filename}\`.`,
|
2022-06-27 11:47:54 +00:00
|
|
|
)
|
|
|
|
}
|
2022-10-27 10:36:37 +00:00
|
|
|
(nuxt.options as any).layouts[layoutName] = `./${filename}`
|
2022-06-27 11:47:54 +00:00
|
|
|
if (name === 'error') {
|
|
|
|
this.addErrorLayout(filename)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Nuxt 3 adds layouts on app
|
|
|
|
nuxt.hook('app:templates', (app) => {
|
|
|
|
if (layoutName in app.layouts) {
|
2024-06-27 14:27:08 +00:00
|
|
|
const relativePath = relative(nuxt.options.srcDir, app.layouts[layoutName]!.file)
|
2022-06-27 11:47:54 +00:00
|
|
|
return logger.warn(
|
2024-04-05 18:08:32 +00:00
|
|
|
`Not overriding \`${layoutName}\` (provided by \`~/${relativePath}\`) with \`${src || filename}\`.`,
|
2022-06-27 11:47:54 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
app.layouts[layoutName] = {
|
|
|
|
file: join('#build', filename),
|
2024-04-05 18:08:32 +00:00
|
|
|
name: layoutName,
|
2022-06-27 11:47:54 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|