summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/TemplateFileSlug.js
blob: 03c9a29ef1faade089eb6eb43af860cbc53eec08 (plain)
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
52
53
54
55
56
57
import path from "node:path";
import { TemplatePath } from "@11ty/eleventy-utils";

class TemplateFileSlug {
	constructor(inputPath, extensionMap, eleventyConfig) {
		let inputDir = eleventyConfig.directories.input;
		if (inputDir) {
			inputPath = TemplatePath.stripLeadingSubPath(inputPath, inputDir);
		}

		this.inputPath = inputPath;
		this.cleanInputPath = inputPath.replace(/^.\//, "");

		let dirs = this.cleanInputPath.split("/");
		this.dirs = dirs;
		this.dirs.pop();

		this.parsed = path.parse(inputPath);
		this.filenameNoExt = extensionMap.removeTemplateExtension(this.parsed.base);
	}

	// `page.filePathStem` see https://v3.11ty.dev/docs/data-eleventy-supplied/#page-variable
	getFullPathWithoutExtension() {
		return "/" + TemplatePath.join(...this.dirs, this._getRawSlug());
	}

	_getRawSlug() {
		let slug = this.filenameNoExt;
		return this._stripDateFromSlug(slug);
	}

	/** Removes dates in the format of YYYY-MM-DD from a given slug string candidate. */
	_stripDateFromSlug(slug) {
		let reg = slug.match(/\d{4}-\d{2}-\d{2}-(.*)/);
		if (reg) {
			return reg[1];
		}
		return slug;
	}

	// `page.fileSlug` see https://v3.11ty.dev/docs/data-eleventy-supplied/#page-variable
	getSlug() {
		let rawSlug = this._getRawSlug();

		if (rawSlug === "index") {
			if (!this.dirs.length) {
				return "";
			}
			let lastDir = this.dirs[this.dirs.length - 1];
			return this._stripDateFromSlug(lastDir);
		}

		return rawSlug;
	}
}

export default TemplateFileSlug;