astroscrap 0.1.0 → 0.1.2

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.
@@ -0,0 +1,4 @@
1
+ <svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
2
+ <rect width="256" height="256" fill="white"/>
3
+ <path d="M91.049 51.5995C107.677 22.7999 149.245 22.8001 165.873 51.5995L224.072 152.4C240.699 181.2 219.914 217.2 186.658 217.2H70.2639C37.0088 217.2 16.2243 181.2 32.8518 152.4L91.049 51.5995ZM127.5 102C106.79 102 90.0003 118.789 90.0002 139.5C90.0002 160.211 106.79 177 127.5 177C148.211 177 165 160.211 165 139.5C165 118.789 148.211 102 127.5 102Z" fill="black"/>
4
+ </svg>
@@ -0,0 +1,3 @@
1
+ <svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
2
+ <path d="M91.049 51.5995C107.677 22.7999 149.245 22.8001 165.873 51.5995L224.072 152.4C240.699 181.2 219.914 217.2 186.658 217.2H70.2639C37.0088 217.2 16.2243 181.2 32.8518 152.4L91.049 51.5995ZM127.5 102C106.79 102 90.0003 118.789 90.0002 139.5C90.0002 160.211 106.79 177 127.5 177C148.211 177 165 160.211 165 139.5C165 118.789 148.211 102 127.5 102Z" fill="black"/>
3
+ </svg>
@@ -1,3 +1,4 @@
1
+ import { existsSync, readdirSync } from "node:fs";
1
2
  import { fileURLToPath } from "node:url";
2
3
  import { isUnifiedProcessor, unified } from "@astrojs/markdown-remark";
3
4
  import remarkMath from "remark-math";
@@ -10,7 +11,6 @@ import { lookup } from "node:dns/promises";
10
11
  import { request } from "node:http";
11
12
  import { request as request$1 } from "node:https";
12
13
  import { parse } from "parse5";
13
- import { readdirSync } from "node:fs";
14
14
  import { isAbsolute, resolve } from "node:path";
15
15
  import { CircleAlert, Info, Lightbulb, ShieldAlert, TriangleAlert, icons } from "lucide";
16
16
  import { glob } from "astro/loaders";
@@ -574,7 +574,7 @@ function resolveOptions(options = {}) {
574
574
  };
575
575
  }
576
576
  const RESOLVED_VIRTUAL_CONFIG_ID = `\0virtual:scrap-config`;
577
- function renderVirtualConfig(options, root) {
577
+ function renderVirtualConfig(options, root, hasPublicFavicon = false) {
578
578
  const imports = [];
579
579
  const title = options.titleComponent ? `import Title from ${JSON.stringify(resolveProjectPath(options.titleComponent, root))}; export { Title };` : "export const Title = null;";
580
580
  if (options.styles) imports.push(`import ${JSON.stringify(resolveProjectPath(options.styles, root))};`);
@@ -601,6 +601,7 @@ function renderVirtualConfig(options, root) {
601
601
  const site = {
602
602
  title: options.title,
603
603
  icon: options.icon,
604
+ hasPublicFavicon,
604
605
  author: options.author,
605
606
  lang: options.lang,
606
607
  search: { placeholder: options.search.placeholder },
@@ -608,14 +609,14 @@ function renderVirtualConfig(options, root) {
608
609
  };
609
610
  return `${title} ${imports.join(" ")} export const HeaderItems = [${headerItems.join(",")}]; export default ${JSON.stringify(site)}`;
610
611
  }
611
- function createVirtualConfigPlugin(options, root) {
612
+ function createVirtualConfigPlugin(options, root, hasPublicFavicon = false) {
612
613
  return {
613
614
  name: "scrap-config",
614
615
  resolveId(source) {
615
616
  return source === "virtual:scrap-config" ? RESOLVED_VIRTUAL_CONFIG_ID : void 0;
616
617
  },
617
618
  load(source) {
618
- return source === "\0virtual:scrap-config" ? renderVirtualConfig(options, root) : void 0;
619
+ return source === "\0virtual:scrap-config" ? renderVirtualConfig(options, root, hasPublicFavicon) : void 0;
619
620
  }
620
621
  };
621
622
  }
@@ -841,7 +842,8 @@ function scrapLoader({ baseDir = "./scraps", parsers: overrides = {} } = {}) {
841
842
  const PAGES = [
842
843
  ["/", "index.astro"],
843
844
  ["/[id]", "[id].astro"],
844
- ["/404", "404.astro"]
845
+ ["/404", "404.astro"],
846
+ ["/_astroscrap/search.json", "search.json.ts"]
845
847
  ];
846
848
  function scrap(options = {}) {
847
849
  const settings = resolveOptions(options);
@@ -850,7 +852,14 @@ function scrap(options = {}) {
850
852
  hooks: { "astro:config:setup": ({ config, injectRoute, updateConfig }) => {
851
853
  updateConfig({
852
854
  markdown: markdownConfig(config, settings.baseDir, noteSlug, (id) => noteUrl(id, config.base)),
853
- vite: { plugins: [createVirtualConfigPlugin(settings, config.root)] }
855
+ prefetch: config.prefetch ?? true,
856
+ vite: { plugins: [createVirtualConfigPlugin(settings, config.root, existsSync(new URL("favicon.svg", config.publicDir))), {
857
+ name: "astroscrap:katex-font-display",
858
+ enforce: "pre",
859
+ transform(css, id) {
860
+ if (id.endsWith("/katex/dist/katex.min.css")) return css.replaceAll("font-display:block", "font-display:swap");
861
+ }
862
+ }] }
854
863
  });
855
864
  for (const [pattern, page] of PAGES) injectRoute({
856
865
  pattern,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astroscrap",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "An Astro integration for building interconnected Markdown notes sites",
5
5
  "keywords": [
6
6
  "astro",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@astrojs/markdown-remark": "^7.3.9",
47
- "@astroscrap/cosense-parser": "workspace:*",
47
+ "@astroscrap/cosense-parser": "^0.1.1",
48
48
  "@types/mdast": "^4.0.4",
49
49
  "@types/node": "^24.19.2",
50
50
  "katex": "^0.19.1",
@@ -42,7 +42,7 @@ if (thumbnail && !/^(?:\/|https?:\/\/)/i.test(thumbnail)) {
42
42
  const excerpt = preview?.excerpt;
43
43
  ---
44
44
  <li class="note-card">
45
- <a href={noteUrl(note.id, base)}>
45
+ <a href={noteUrl(note.id, base)} data-astro-prefetch="hover">
46
46
  {index ? <div class="card-heading">{status && <span class="pin" aria-label={status.label}><Icon icon={status.icon} /></span>}<h2>{title}</h2></div> : <h3>{title}</h3>}
47
47
  {thumbnail && image ? (
48
48
  <img class="note-thumbnail" src={thumbnail} alt={image.alt} loading="lazy" decoding="async" />
@@ -58,6 +58,6 @@ const excerpt = preview?.excerpt;
58
58
  .card-heading { display: flex; align-items: baseline; gap: 4px; min-width: 0; }
59
59
  .pin { flex: none; align-self: flex-start; padding-top: .25em; color: var(--astroscrap-color-text-muted); }
60
60
  .note-card p { margin: 5px 0 0; color: var(--astroscrap-color-text-muted); font-size: var(--astroscrap-font-size-sm); line-height: 1.7; -webkit-line-clamp: 4; }
61
- .note-thumbnail { width: 100%; flex: 1; min-height: 0; object-fit: cover; margin-top: 12px; border-radius: var(--astroscrap-border-radius); }
61
+ .note-thumbnail { width: 100%; flex: 1; min-height: 0; object-fit: contain; margin-top: 12px; }
62
62
  @media (max-width: 640px) { .note-card > a { padding: 15px; } }
63
63
  </style>
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // oxlint-disable-next-line typescript/triple-slash-reference -- loads the virtual module declaration for consumers.
2
2
  /// <reference path="./lib/virtual-config.d.ts" />
3
3
 
4
+ import { existsSync } from "node:fs";
4
5
  import type { AstroIntegration } from "astro";
5
6
  import { markdownConfig } from "./lib/markdown";
6
7
  import { noteSlug, noteUrl } from "./lib/paths";
@@ -15,6 +16,7 @@ const PAGES = [
15
16
  ["/", "index.astro"],
16
17
  ["/[id]", "[id].astro"],
17
18
  ["/404", "404.astro"],
19
+ ["/_astroscrap/search.json", "search.json.ts"],
18
20
  ] as const;
19
21
 
20
22
  export default function scrap(options: ScrapOptions = {}): AstroIntegration {
@@ -28,7 +30,25 @@ export default function scrap(options: ScrapOptions = {}): AstroIntegration {
28
30
  markdown: markdownConfig(config, settings.baseDir, noteSlug, (id) =>
29
31
  noteUrl(id, config.base),
30
32
  ),
31
- vite: { plugins: [createVirtualConfigPlugin(settings, config.root)] },
33
+ prefetch: config.prefetch ?? true,
34
+ vite: {
35
+ plugins: [
36
+ createVirtualConfigPlugin(
37
+ settings,
38
+ config.root,
39
+ existsSync(new URL("favicon.svg", config.publicDir)),
40
+ ),
41
+ {
42
+ name: "astroscrap:katex-font-display",
43
+ enforce: "pre",
44
+ transform(css, id) {
45
+ if (id.endsWith("/katex/dist/katex.min.css")) {
46
+ return css.replaceAll("font-display:block", "font-display:swap");
47
+ }
48
+ },
49
+ },
50
+ ],
51
+ },
32
52
  });
33
53
 
34
54
  for (const [pattern, page] of PAGES) {
@@ -1,27 +1,35 @@
1
1
  ---
2
2
  import { Search, X } from 'lucide';
3
+ import defaultFavicon from '../../assets/favicon.svg?url';
4
+ import defaultIcon from '../../assets/icon.svg?url';
3
5
  import Icon from '../components/Icon.astro';
4
6
  import '../styles/global.css';
5
7
  import 'katex/dist/katex.min.css';
6
- import { getNotes } from '../lib/notes';
7
- import { normalizeBase, noteUrl } from '../lib/paths';
8
- import { isSearchableNote } from '../lib/visibility';
8
+ import { normalizeBase } from '../lib/paths';
9
9
  import site, { Footer, HeaderItems, Title } from 'virtual:scrap-config';
10
10
  interface Props {
11
11
  title?: string;
12
12
  }
13
13
  const { title } = Astro.props;
14
- const notes = (await getNotes()).filter((note) => isSearchableNote(note, import.meta.env.DEV));
15
14
  const base = normalizeBase(import.meta.env.BASE_URL);
16
- const icon = site.icon?.startsWith('/') ? `${base}${site.icon.slice(1)}` : site.icon;
15
+ const icon = site.icon?.startsWith('/') ? `${base}${site.icon.slice(1)}` : site.icon ?? defaultIcon;
16
+ const pageTitle = title ? `${title} | ${site.title}` : site.title;
17
+ const pageUrl = new URL(Astro.url.pathname, Astro.site ?? Astro.url);
18
+ const imageUrl = new URL(`${base}og-image.png`, Astro.site ?? Astro.url).href;
17
19
  ---
18
20
  <!doctype html>
19
21
  <html lang={site.lang}>
20
22
  <head>
21
23
  <meta charset="utf-8" />
22
- <link rel="icon" type="image/svg+xml" href={`${base}favicon.svg`} />
24
+ <link rel="icon" type="image/svg+xml" href={site.hasPublicFavicon ? `${base}favicon.svg` : defaultFavicon} />
23
25
  <meta name="viewport" content="width=device-width, initial-scale=1" />
24
- <title>{title ? `${title} | ${site.title}` : site.title}</title>
26
+ <title>{pageTitle}</title>
27
+ <meta property="og:type" content="website" />
28
+ <meta property="og:title" content={pageTitle} />
29
+ <meta property="og:site_name" content={site.title} />
30
+ <meta property="og:url" content={pageUrl.href} />
31
+ <meta property="og:image" content={imageUrl} />
32
+ <meta name="twitter:card" content="summary" />
25
33
  </head>
26
34
  <body>
27
35
  <a class="skip" href="#main">Skip to content</a>
@@ -33,9 +41,8 @@ const icon = site.icon?.startsWith('/') ? `${base}${site.icon.slice(1)}` : site.
33
41
  <Icon icon={Search} />
34
42
  <input id="note-search" name="q" type="search" placeholder={site.search.placeholder} role="combobox" aria-autocomplete="list" aria-expanded="false" aria-controls="search-suggestions" autocomplete="off" />
35
43
  <button type="reset" aria-label="Clear search"><Icon icon={X} /></button>
36
- <ul id="search-suggestions" class="search-suggestions" role="listbox" hidden>
37
- {notes.map((note, index) => <li id={`suggestion-${index}`} role="option" aria-selected="false" data-search={`${note.id} ${note.body ?? ''}`}><a href={noteUrl(note.id, base)} tabindex="-1">{note.id}</a></li>)}
38
- </ul>
44
+ <ul id="search-suggestions" class="search-suggestions" role="listbox" data-url={`${base}_astroscrap/search.json`} hidden></ul>
45
+ <span id="search-status" class="sr-only" role="status"></span>
39
46
  </form>
40
47
  {HeaderItems.length > 0 && (
41
48
  <div class="header-items">
@@ -1,16 +1,17 @@
1
1
  const input = document.querySelector<HTMLInputElement>("#note-search")!;
2
2
  const form = input.form!;
3
3
  const list = document.querySelector<HTMLElement>("#search-suggestions")!;
4
- const options = [...list.querySelectorAll<HTMLElement>('[role="option"]')];
4
+ const searchStatus = document.querySelector<HTMLElement>("#search-status")!;
5
+ let options: HTMLElement[] = [];
6
+ let loading: Promise<void> | undefined;
5
7
  const normalize = (text: string) => text.normalize("NFKC").toLowerCase();
6
8
  let matches: HTMLElement[] = [];
7
9
  let active = -1;
8
10
 
9
11
  function select(index: number) {
12
+ matches[active]?.setAttribute("aria-selected", "false");
10
13
  active = index;
11
- options.forEach((option) =>
12
- option.setAttribute("aria-selected", String(option === matches[active])),
13
- );
14
+ matches[active]?.setAttribute("aria-selected", "true");
14
15
  if (matches[active]) input.setAttribute("aria-activedescendant", matches[active].id);
15
16
  else input.removeAttribute("aria-activedescendant");
16
17
  }
@@ -24,21 +25,47 @@ function close() {
24
25
  function update() {
25
26
  const query = normalize(input.value).trim();
26
27
  const words = query.split(/\s+/);
27
- matches = query
28
- ? options.filter((option) =>
29
- words.every((word) => normalize(option.dataset.search ?? "").includes(word)),
30
- )
31
- : [];
32
- options.forEach((option) => {
33
- option.hidden = !matches.includes(option);
28
+ select(-1);
29
+ matches = options.filter((option) => {
30
+ const matched = Boolean(query) && words.every((word) => option.dataset.search!.includes(word));
31
+ option.hidden = !matched;
32
+ return matched;
34
33
  });
35
34
  list.hidden = matches.length === 0;
36
35
  input.setAttribute("aria-expanded", String(!list.hidden));
37
- select(-1);
38
36
  }
39
37
 
40
38
  input.addEventListener("input", update);
41
- input.addEventListener("focus", update);
39
+ input.addEventListener("focus", () => {
40
+ loading ??= fetch(list.dataset.url!)
41
+ .then((response) => {
42
+ if (!response.ok) throw new Error("Search index unavailable");
43
+ return response.json() as Promise<{ id: string; href: string; search: string }[]>;
44
+ })
45
+ .then((notes) => {
46
+ options = notes.map((note, index) => {
47
+ const option = document.createElement("li");
48
+ option.id = `suggestion-${index}`;
49
+ option.setAttribute("role", "option");
50
+ option.setAttribute("aria-selected", "false");
51
+ option.dataset.search = normalize(note.search);
52
+ const link = document.createElement("a");
53
+ link.href = note.href;
54
+ link.tabIndex = -1;
55
+ link.textContent = note.id;
56
+ option.append(link);
57
+ return option;
58
+ });
59
+ list.replaceChildren(...options);
60
+ searchStatus.textContent = "";
61
+ if (document.activeElement === input) update();
62
+ })
63
+ .catch(() => {
64
+ loading = undefined;
65
+ searchStatus.textContent = "Search could not be loaded. Focus the search field to try again.";
66
+ });
67
+ update();
68
+ });
42
69
  input.addEventListener("keydown", (event) => {
43
70
  if (event.key === "Escape") {
44
71
  close();
@@ -15,6 +15,7 @@ declare module "virtual:scrap-config" {
15
15
  const site: {
16
16
  title: string;
17
17
  icon?: string;
18
+ hasPublicFavicon: boolean;
18
19
  author: string;
19
20
  lang: string;
20
21
  search: { placeholder: string };
@@ -6,7 +6,11 @@ import { resolveProjectPath } from "./paths";
6
6
  export const VIRTUAL_CONFIG_ID = "virtual:scrap-config";
7
7
  export const RESOLVED_VIRTUAL_CONFIG_ID = `\0${VIRTUAL_CONFIG_ID}`;
8
8
 
9
- export function renderVirtualConfig(options: ResolvedScrapOptions, root: URL): string {
9
+ export function renderVirtualConfig(
10
+ options: ResolvedScrapOptions,
11
+ root: URL,
12
+ hasPublicFavicon = false,
13
+ ): string {
10
14
  const imports: string[] = [];
11
15
 
12
16
  const title = options.titleComponent
@@ -45,6 +49,7 @@ export function renderVirtualConfig(options: ResolvedScrapOptions, root: URL): s
45
49
  const site = {
46
50
  title: options.title,
47
51
  icon: options.icon,
52
+ hasPublicFavicon,
48
53
  author: options.author,
49
54
  lang: options.lang,
50
55
  search: { placeholder: options.search.placeholder },
@@ -54,14 +59,20 @@ export function renderVirtualConfig(options: ResolvedScrapOptions, root: URL): s
54
59
  return `${title} ${imports.join(" ")} export const HeaderItems = [${headerItems.join(",")}]; export default ${JSON.stringify(site)}`;
55
60
  }
56
61
 
57
- export function createVirtualConfigPlugin(options: ResolvedScrapOptions, root: URL) {
62
+ export function createVirtualConfigPlugin(
63
+ options: ResolvedScrapOptions,
64
+ root: URL,
65
+ hasPublicFavicon = false,
66
+ ) {
58
67
  return {
59
68
  name: "scrap-config",
60
69
  resolveId(source: string) {
61
70
  return source === VIRTUAL_CONFIG_ID ? RESOLVED_VIRTUAL_CONFIG_ID : undefined;
62
71
  },
63
72
  load(source: string) {
64
- return source === RESOLVED_VIRTUAL_CONFIG_ID ? renderVirtualConfig(options, root) : undefined;
73
+ return source === RESOLVED_VIRTUAL_CONFIG_ID
74
+ ? renderVirtualConfig(options, root, hasPublicFavicon)
75
+ : undefined;
65
76
  },
66
77
  };
67
78
  }
@@ -0,0 +1,14 @@
1
+ import { getNotes } from "../lib/notes";
2
+ import { noteUrl } from "../lib/paths";
3
+ import { isSearchableNote } from "../lib/visibility";
4
+
5
+ export async function GET() {
6
+ const notes = (await getNotes()).filter((note) => isSearchableNote(note, import.meta.env.DEV));
7
+ return Response.json(
8
+ notes.map((note) => ({
9
+ id: note.id,
10
+ href: noteUrl(note.id, import.meta.env.BASE_URL),
11
+ search: `${note.id} ${note.body ?? ""}`,
12
+ })),
13
+ );
14
+ }