@binarynoir/vite-plugin-blog 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,6 +15,8 @@ scripts, styles and `transformIndexHtml` plugins apply to posts like to every ot
15
15
  ## What this does
16
16
 
17
17
  - **Posts are HTML in the page source.** A post reads with no JavaScript.
18
+ - **An index and tag pages.** `/blog/` lists every post, newest first, and each tag
19
+ in use gets `/blog/tag/{tag}/`. All of them use your page shell.
18
20
  - **Works under a strict Content Security Policy.** Code is highlighted with
19
21
  [Shiki](https://shiki.style) at build time, and its colors are written as classes, not
20
22
  `style` attributes, so `style-src 'self'` holds.
@@ -122,27 +124,29 @@ theme switch picks one.
122
124
 
123
125
  ## Options
124
126
 
125
- | Option | Default | What it does |
126
- | ---------------- | ------------- | -------------------------------------------------------------------- |
127
- | `dir` | (required) | The content folder, relative to Vite's `root` or absolute |
128
- | `template` | (required) | The page shell, relative to Vite's `root` |
129
- | `base` | `/blog/` | Where the blog lives on the site |
130
- | `site` | | The site's origin, for canonical URLs and Open Graph tags |
131
- | `preview` | `false` | Also build drafts and scheduled posts, with `noindex` |
132
- | `now` | build time | What "now" is when deciding whether a post is scheduled |
133
- | `timeZone` | `UTC` | For dates without an offset, and for showing dates |
134
- | `locale` | `en-US` | For showing dates |
135
- | `wordsPerMinute` | `230` | For reading time |
136
- | `titleSuffix` | `''` | Added after the post title in `<title>` |
137
- | `limits` | | `{ title: 70, description: 160, minTags: 0, maxTags }` |
138
- | `tags` | `tags.yml` | The only tags allowed; without either, any tag is |
139
- | `authors` | `authors.yml` | Known authors, by id |
140
- | `directives` | | Your own `:::` directives (below) |
141
- | `highlight` | GitHub themes | `{ themes: { light, dark }, classPrefix }`, or `false` |
142
- | `markdown` | | `(md) => void`: add markdown-it plugins |
143
- | `isKnownPath` | | `(path) => boolean`: also check links to site pages outside the blog |
144
- | `validate` | | `(post) => string[]`: your own checks; messages fail the build |
145
- | `render` | | `{ head, article }`: replace the default markup (below) |
127
+ | Option | Default | What it does |
128
+ | ---------------- | ------------------- | ----------------------------------------------------------------------- |
129
+ | `dir` | (required) | The content folder, relative to Vite's `root` or absolute |
130
+ | `template` | (required) | The page shell, relative to Vite's `root` |
131
+ | `base` | `/blog/` | Where the blog lives on the site |
132
+ | `site` | | The site's origin, for canonical URLs and Open Graph tags |
133
+ | `preview` | `false` | Also build drafts and scheduled posts, with `noindex` |
134
+ | `now` | build time | What "now" is when deciding whether a post is scheduled |
135
+ | `timeZone` | `UTC` | For dates without an offset, and for showing dates |
136
+ | `locale` | `en-US` | For showing dates |
137
+ | `wordsPerMinute` | `230` | For reading time |
138
+ | `titleSuffix` | `''` | Added after the post title in `<title>` |
139
+ | `index` | `{ title: "Blog" }` | The index's heading and description: `{ title, description }` |
140
+ | `tagPages` | `true` | Write a page per tag in use at `{base}tag/{tag}/` |
141
+ | `limits` | | `{ title: 70, description: 160, minTags: 0, maxTags }` |
142
+ | `tags` | `tags.yml` | The only tags allowed; without either, any tag is |
143
+ | `authors` | `authors.yml` | Known authors, by id |
144
+ | `directives` | | Your own `:::` directives (below) |
145
+ | `highlight` | GitHub themes | `{ themes: { light, dark }, classPrefix }`, or `false` |
146
+ | `markdown` | | `(md) => void`: add markdown-it plugins |
147
+ | `isKnownPath` | | `(path) => boolean`: also check links to site pages outside the blog |
148
+ | `validate` | | `(post) => string[]`: your own checks; messages fail the build |
149
+ | `render` | | `{ head, article, listHead, list }`: replace the default markup (below) |
146
150
 
147
151
  ### Directives
148
152
 
@@ -177,7 +181,12 @@ Back up the zone file.
177
181
 
178
182
  `render.article` and `render.head` get the post and a set of helpers: `escapeHtml`,
179
183
  `formatDate`, `dateAttribute`, `renderToc`, `renderHead`, `renderArticle`, `tags` and
180
- `posts` (every published post, newest first, for related posts or series links).
184
+ `posts` (every published post, newest first, for related posts or series links), plus
185
+ `indexUrl`, `tagUrl(tag)` and `usedTags` (tags with a page).
186
+
187
+ `render.list` and `render.listHead` do the same for the index and tag pages. They get a
188
+ page with `kind` (`"index"` or `"tag"`), `url`, `canonical`, `title`, `description`,
189
+ `tag` and its `posts`, newest first; the defaults are `renderList` and `renderListHead`.
181
190
 
182
191
  ```ts
183
192
  render: {
@@ -189,7 +198,9 @@ render: {
189
198
 
190
199
  The default article uses these classes: `post`, `post-header`, `post-description`,
191
200
  `post-meta`, `post-tags`, `tag`, `toc`, `toc-title`, `toc-2`, `toc-3`, `prose`.
192
- Inside posts: `heading-anchor`, `code-block`, `callout`, `callout-note`, `callout-tip`,
201
+ The default index and tag pages use `post-list`, `post-list-description`,
202
+ `post-list-tags` (the current tag has `aria-current="page"`), `post-items`, `post-item`
203
+ and `post-list-empty`. Inside posts: `heading-anchor`, `code-block`, `callout`, `callout-note`, `callout-tip`,
193
204
  `callout-warning`, `callout-title`.
194
205
 
195
206
  ### `virtual:blog/posts`
package/dist/index.cjs CHANGED
@@ -803,15 +803,25 @@ function createLoader(options, assetUrl) {
803
803
  posts.push(post);
804
804
  }
805
805
  const published = new Set(posts.map((post) => post.slug));
806
+ const usedTags2 = new Set(posts.flatMap((post) => post.tags));
806
807
  for (const [post, links2] of linksByPost) {
807
808
  for (const { href, line } of links2) {
808
809
  const where = line ? `line ${line}: ` : "";
809
810
  const pathname = href.split(/[?#]/)[0];
810
811
  if (pathname.startsWith(options.base)) {
811
812
  const rest = pathname.slice(options.base.length).replace(/(?:\/index\.html|\/)$/, "");
812
- if (!rest || rest.includes("/")) {
813
- if (options.isKnownPath && !options.isKnownPath(pathname))
814
- issues.push({ file: post.file, message: `${where}link to ${href} goes nowhere` });
813
+ if (!rest) continue;
814
+ const tag = /^tag\/([^/]+)$/.exec(rest)?.[1];
815
+ if (tag) {
816
+ if (options.tagPages !== false && usedTags2.has(tag)) continue;
817
+ issues.push({
818
+ file: post.file,
819
+ message: `${where}link to ${href} goes nowhere: no published post has the tag "${tag}"`
820
+ });
821
+ continue;
822
+ }
823
+ if (rest.includes("/")) {
824
+ issues.push({ file: post.file, message: `${where}link to ${href} goes nowhere` });
815
825
  continue;
816
826
  }
817
827
  if (published.has(rest)) continue;
@@ -868,6 +878,43 @@ function renderToc(toc) {
868
878
  ).join("");
869
879
  return `<nav class="toc" aria-label="On this page"><p class="toc-title">On this page</p><ol>${items}</ol></nav>`;
870
880
  }
881
+ function usedTags(content) {
882
+ const used = new Set(content.posts.flatMap((post) => post.tags));
883
+ const known = Object.keys(content.tags).filter((tag) => used.has(tag));
884
+ const others = [...used].filter((tag) => !Object.hasOwn(content.tags, tag)).sort();
885
+ return [...known, ...others];
886
+ }
887
+ function listPath(options, tag) {
888
+ return tag ? `${options.base}tag/${tag}/` : options.base;
889
+ }
890
+ function listPages(options, content) {
891
+ const page = (sitePath) => ({
892
+ url: joinUrl(options.siteBase, sitePath),
893
+ canonical: options.site ? joinUrl(options.site, joinUrl(options.siteBase, sitePath)) : void 0
894
+ });
895
+ const pages = [
896
+ {
897
+ kind: "index",
898
+ ...page(listPath(options)),
899
+ title: options.index?.title ?? "Blog",
900
+ description: options.index?.description ?? "",
901
+ posts: content.posts
902
+ }
903
+ ];
904
+ if (options.tagPages === false) return pages;
905
+ for (const tag of usedTags(content)) {
906
+ const info = content.tags[tag];
907
+ pages.push({
908
+ kind: "tag",
909
+ ...page(listPath(options, tag)),
910
+ title: info?.name ?? tag,
911
+ description: info?.description ?? "",
912
+ tag,
913
+ posts: content.posts.filter((post) => post.tags.includes(tag))
914
+ });
915
+ }
916
+ return pages;
917
+ }
871
918
  function createHelpers(options, content) {
872
919
  const display = {
873
920
  locale: options.locale,
@@ -878,6 +925,13 @@ function createHelpers(options, content) {
878
925
  };
879
926
  const formatDate = (date, hasTime = false) => formatPostDate({ date, hasTime }, display);
880
927
  const dateAttribute = (date, hasTime = false) => toDateTimeAttribute({ date, hasTime }, options.timeZone);
928
+ const tags = usedTags(content);
929
+ const indexUrl = joinUrl(options.siteBase, listPath(options));
930
+ const tagUrl = (tag) => joinUrl(options.siteBase, listPath(options, tag));
931
+ const tagItem = (tag) => {
932
+ const name = escapeHtml(content.tags[tag]?.name ?? tag);
933
+ return options.tagPages === false ? `<li class="tag">${name}</li>` : `<li class="tag"><a href="${escapeHtml(tagUrl(tag))}">${name}</a></li>`;
934
+ };
881
935
  const renderHead = (post) => [
882
936
  `<title>${escapeHtml(post.title + options.titleSuffix)}</title>`,
883
937
  meta("name", "description", post.description),
@@ -892,7 +946,7 @@ function createHelpers(options, content) {
892
946
  ...post.tags.map((tag) => meta("property", "article:tag", content.tags[tag]?.name ?? tag))
893
947
  ].filter(Boolean).join("\n ");
894
948
  const renderArticle = (post) => {
895
- const tags = post.tags.map((tag) => `<li class="tag">${escapeHtml(content.tags[tag]?.name ?? tag)}</li>`).join("");
949
+ const tags2 = post.tags.map(tagItem).join("");
896
950
  const updated = post.updated ? ` \xB7 Updated <time datetime="${dateAttribute(post.updated)}">${formatDate(post.updated)}</time>` : "";
897
951
  return [
898
952
  '<article class="post">',
@@ -900,7 +954,7 @@ function createHelpers(options, content) {
900
954
  `<h1>${escapeHtml(post.title)}</h1>`,
901
955
  `<p class="post-description">${escapeHtml(post.description)}</p>`,
902
956
  `<p class="post-meta"><time datetime="${dateAttribute(post.date, post.dateHasTime)}">${formatDate(post.date, post.dateHasTime)}</time>${updated} \xB7 ${post.readingMinutes} min read</p>`,
903
- tags ? `<ul class="post-tags">${tags}</ul>` : "",
957
+ tags2 ? `<ul class="post-tags">${tags2}</ul>` : "",
904
958
  "</header>",
905
959
  renderToc(post.toc),
906
960
  `<div class="prose" data-pagefind-body>
@@ -908,7 +962,52 @@ ${post.html}</div>`,
908
962
  "</article>"
909
963
  ].filter(Boolean).join("\n");
910
964
  };
965
+ const indexTitle = options.index?.title ?? "Blog";
966
+ const renderListHead = (page) => {
967
+ const title = page.kind === "index" ? page.title : `${page.title} \xB7 ${indexTitle}`;
968
+ return [
969
+ `<title>${escapeHtml(title + options.titleSuffix)}</title>`,
970
+ meta("name", "description", page.description),
971
+ page.canonical ? `<link rel="canonical" href="${escapeHtml(page.canonical)}">` : "",
972
+ meta("property", "og:type", "website"),
973
+ meta("property", "og:title", title),
974
+ meta("property", "og:description", page.description),
975
+ meta("property", "og:url", page.canonical)
976
+ ].filter(Boolean).join("\n ");
977
+ };
978
+ const renderList = (page) => {
979
+ const items = page.posts.map((post) => {
980
+ const postTags = post.tags.map(tagItem).join("");
981
+ return [
982
+ '<li class="post-item">',
983
+ `<h2><a href="${escapeHtml(post.url)}">${escapeHtml(post.title)}</a></h2>`,
984
+ `<p class="post-meta"><time datetime="${dateAttribute(post.date, post.dateHasTime)}">${formatDate(post.date, post.dateHasTime)}</time> \xB7 ${post.readingMinutes} min read</p>`,
985
+ `<p class="post-description">${escapeHtml(post.description)}</p>`,
986
+ postTags ? `<ul class="post-tags">${postTags}</ul>` : "",
987
+ "</li>"
988
+ ].filter(Boolean).join("");
989
+ }).join("\n");
990
+ const tagLinks = options.tagPages === false ? "" : tags.map((tag) => {
991
+ const current = page.tag === tag ? ' aria-current="page"' : "";
992
+ return `<li><a href="${escapeHtml(tagUrl(tag))}"${current}>${escapeHtml(content.tags[tag]?.name ?? tag)}</a></li>`;
993
+ }).join("");
994
+ return [
995
+ `<section class="post-list" aria-labelledby="post-list-title">`,
996
+ `<h1 id="post-list-title">${escapeHtml(page.title)}</h1>`,
997
+ page.description ? `<p class="post-list-description">${escapeHtml(page.description)}</p>` : "",
998
+ tagLinks ? `<nav class="post-list-tags" aria-label="Tags"><ul>${tagLinks}</ul></nav>` : "",
999
+ items ? `<ul class="post-items">
1000
+ ${items}
1001
+ </ul>` : '<p class="post-list-empty">No posts yet.</p>',
1002
+ "</section>"
1003
+ ].filter(Boolean).join("\n");
1004
+ };
911
1005
  return {
1006
+ indexUrl,
1007
+ tagUrl,
1008
+ usedTags: tags,
1009
+ renderListHead,
1010
+ renderList,
912
1011
  escapeHtml,
913
1012
  formatDate,
914
1013
  dateAttribute,
@@ -929,6 +1028,11 @@ function renderPostPage(template, post, options, helpers) {
929
1028
  const article = options.render?.article?.(post, helpers) ?? helpers.renderArticle(post);
930
1029
  return fillTemplate(template, head, article);
931
1030
  }
1031
+ function renderListPage(template, page, options, helpers) {
1032
+ const head = options.render?.listHead?.(page, helpers) ?? helpers.renderListHead(page);
1033
+ const body = options.render?.list?.(page, helpers) ?? helpers.renderList(page);
1034
+ return fillTemplate(template, head, body);
1035
+ }
932
1036
  function postSummaries(posts) {
933
1037
  return posts.map((post) => ({
934
1038
  slug: post.slug,
@@ -966,7 +1070,17 @@ function blog(userOptions) {
966
1070
  let load;
967
1071
  let content;
968
1072
  const pageIds = /* @__PURE__ */ new Map();
969
- const pageFile = (slug) => import_node_path3.default.join(config.root, postPath(options, slug).slice(1), "index.html");
1073
+ const fileFor = (sitePath) => import_node_path3.default.join(config.root, sitePath.slice(1), "index.html");
1074
+ const pageFile = (slug) => fileFor(postPath(options, slug));
1075
+ const allPages = () => {
1076
+ const pages = /* @__PURE__ */ new Map();
1077
+ for (const page of listPages(options, content)) {
1078
+ pages.set(page.url.slice(options.siteBase.length - 1), { kind: "list", page });
1079
+ }
1080
+ for (const post of content.posts)
1081
+ pages.set(postPath(options, post.slug), { kind: "post", post });
1082
+ return pages;
1083
+ };
970
1084
  const assetUrl = (file, slug) => config.command === "serve" ? `/@fs/${toPosix(file).replace(/^\/+/, "")}` : toPosix(import_node_path3.default.relative(import_node_path3.default.dirname(pageFile(slug)), file));
971
1085
  const readTemplate = () => {
972
1086
  const template = (0, import_node_fs3.readFileSync)(options.template, "utf8");
@@ -976,7 +1090,10 @@ function blog(userOptions) {
976
1090
  );
977
1091
  return template;
978
1092
  };
979
- const renderPage = (post) => renderPostPage(readTemplate(), post, options, createHelpers(options, content));
1093
+ const renderPage = (page) => {
1094
+ const helpers = createHelpers(options, content);
1095
+ return page.kind === "post" ? renderPostPage(readTemplate(), page.post, options, helpers) : renderListPage(readTemplate(), page.page, options, helpers);
1096
+ };
980
1097
  return {
981
1098
  name: "vite-plugin-blog",
982
1099
  enforce: "pre",
@@ -996,10 +1113,11 @@ function blog(userOptions) {
996
1113
  if (config.command !== "build") return;
997
1114
  pageIds.clear();
998
1115
  const pages = {};
999
- for (const post of content.posts) {
1000
- const id = pageFile(post.slug);
1001
- pageIds.set(id, post);
1002
- pages[`blog-${post.slug}`] = id;
1116
+ for (const [sitePath, page] of allPages()) {
1117
+ const id = fileFor(sitePath);
1118
+ pageIds.set(id, page);
1119
+ const rest = sitePath.slice(options.base.length).replace(/\/$/, "");
1120
+ pages[rest ? `blog-${rest.replace(/^tag\//, "tag__")}` : "blog"] = id;
1003
1121
  }
1004
1122
  return { ...inputOptions, input: addInputs(inputOptions.input, pages) };
1005
1123
  },
@@ -1015,8 +1133,8 @@ function blog(userOptions) {
1015
1133
  export default posts;
1016
1134
  `;
1017
1135
  if (id === RESOLVED_CSS_ID) return content.css;
1018
- const post = pageIds.get(id);
1019
- if (post) return renderPage(post);
1136
+ const page = pageIds.get(id);
1137
+ if (page) return renderPage(page);
1020
1138
  return null;
1021
1139
  },
1022
1140
  configureServer(server) {
@@ -1042,19 +1160,23 @@ export default posts;
1042
1160
  server.middlewares.use(async (req, res, next) => {
1043
1161
  try {
1044
1162
  const url = new URL(req.url ?? "/", "http://localhost");
1045
- const prefix = `${options.siteBase.replace(/\/$/, "")}${options.base}`;
1046
- if (!url.pathname.startsWith(prefix)) return next();
1047
- const match = /^([a-z0-9-]+)(\/|\/index\.html)?$/.exec(url.pathname.slice(prefix.length));
1048
- const post = match && content.posts.find((candidate) => candidate.slug === match[1]);
1049
- if (!post) return next();
1050
- if (!match[2]) {
1051
- res.statusCode = 301;
1052
- res.setHeader("Location", `${post.url}${url.search}`);
1053
- return res.end();
1163
+ const siteBase = options.siteBase.replace(/\/$/, "");
1164
+ if (!url.pathname.startsWith(siteBase)) return next();
1165
+ const sitePath = url.pathname.slice(siteBase.length).replace(/\/index\.html$/, "/");
1166
+ if (!sitePath.startsWith(options.base.replace(/\/$/, ""))) return next();
1167
+ const pages = allPages();
1168
+ const page = pages.get(sitePath);
1169
+ if (!page) {
1170
+ if (!sitePath.endsWith("/") && pages.has(`${sitePath}/`)) {
1171
+ res.statusCode = 301;
1172
+ res.setHeader("Location", `${siteBase}${sitePath}/${url.search}`);
1173
+ return res.end();
1174
+ }
1175
+ return next();
1054
1176
  }
1055
1177
  const html = await server.transformIndexHtml(
1056
- `${postPath(options, post.slug)}index.html`,
1057
- renderPage(post),
1178
+ `${sitePath}index.html`,
1179
+ renderPage(page),
1058
1180
  req.originalUrl
1059
1181
  );
1060
1182
  res.setHeader("Content-Type", "text/html; charset=utf-8");