-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefaultLayout.mjs
51 lines (46 loc) · 1.49 KB
/
defaultLayout.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { existsSync } from "fs";
import { join } from "path";
const pagesPath = "src/pages";
const layoutPath = "src/layouts";
const layoutAlias = "@layouts";
const defaultLayout = "Layout";
const pascalCache = {};
function toPascalCase(str) {
pascalCache[str] =
pascalCache[str] ||
(/^[\p{L}\d]+$/iu.test(str) &&
str.charAt(0).toUpperCase() + str.slice(1)) ||
str
.replace(
/([\p{L}\d])([\p{L}\d]*)/giu,
(g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
)
.replace(/[^\p{L}\d]/giu, "");
return pascalCache[str];
}
const knownLayouts = new Set();
const knownNotLayouts = new Set();
export default function defaultLayoutPlugin() {
return function (tree, file) {
const filePathFull = file.history[0].replace(/\/[^\/]+$/, "");
const pagesPathFull = join(file.cwd, pagesPath);
const nestedDirs = filePathFull.slice(pagesPathFull.length + 1);
const directories = nestedDirs ? nestedDirs.split("/").reverse() : [];
let layout = defaultLayout;
directories.some((directory) => {
const layoutName = toPascalCase(directory);
if (
knownLayouts.has(layoutName) ||
(!knownNotLayouts.has(layoutName) &&
existsSync(join(layoutPath, layoutName + ".astro")))
) {
knownLayouts.add(layoutName);
layout = layoutName;
return true;
} else {
knownNotLayouts.add(layoutName);
}
});
file.data.astro.frontmatter.layout = `${layoutAlias}/${layout}.astro`;
};
}