This repository has been archived by the owner on Jan 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
116 lines (97 loc) · 2.64 KB
/
index.js
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import alfy from 'alfy';
import { read } from 'to-vfile';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkFrontmatter from 'remark-frontmatter';
import remarkStringify from 'remark-stringify';
import yaml from 'js-yaml';
import { readdirSync } from 'node:fs';
import Fuse from 'fuse.js';
const ROOT = process.env.ROOT;
class File {
constructor(filename) {
this.filename = filename;
}
get path() {
return ROOT + this.filename;
}
get name() {
return this.filename.replace('.md', '');
}
}
class Snippet {
constructor(args) {
const { name, path, frontmatter, value, lang } = args;
this.name = name;
this.path = path;
this.frontmatter = frontmatter;
this.value = value;
this.lang = lang;
}
get tags() {
return this.frontmatter.tags.map((tag) => `#${tag}`).join(' ');
}
}
const getFiles = () => {
return readdirSync(ROOT)
.filter((filename) => filename.match('.md'))
.map((filename) => new File(filename));
};
const findByType = (tree, type) => {
return tree.children.find((item) => item.type === type);
};
const getData = async (files) => {
const data = [];
await Promise.all(
files.map(async (file) => {
return await unified()
.use(remarkParse)
.use(remarkStringify)
.use(remarkFrontmatter, { type: 'yaml', marker: '-' })
.use(() => (tree) => {
const path = file.path;
const frontmatter = findByType(tree, 'yaml').value
? yaml.load(findByType(tree, 'yaml').value)
: [];
const name = frontmatter.name ? frontmatter.name : file.name;
const value = findByType(tree, 'code').value;
const lang = findByType(tree, 'code').lang;
data.push(new Snippet({ name, path, frontmatter, value, lang }));
})
.process(await read(file.path));
}),
);
return data;
};
const files = getFiles();
const data = await getData(files);
const matcher = (snippet, query) => {
const options = {
keys: ['name', 'frontmatter.tags', 'lang'],
};
const fuse = new Fuse(data, options);
return [...fuse.search(alfy.input).map((match) => match.item)];
};
const items = matcher().map((snippet) => {
const item = {
title: snippet.name,
uid: snippet.path,
arg: snippet.value,
mods: {
alt: {
valid: true,
arg: snippet.path,
subtitle: 'Open in Finder',
},
},
text: {
copy: snippet.value,
largetype: snippet.value,
},
};
snippet.lang
? (item.subtitle = `written in ${snippet.lang}`)
: (item.subtitle = 'written in plain text');
return item;
});
alfy.output(items);