on cd1b0fa help sign in
urbit.org/lib/lib.js
291 lines 8.5 kB history raw
1import remark from "remark";
2import html from "remark-html";
3import fs from "fs";
4import { join, parse } from "path";
5import matter from "gray-matter";
6import toml from "@iarna/toml";
7import { DateTime } from "luxon";
9const directories = (dir) => {
10 switch (dir) {
11 case "blog":
12 return join(process.cwd(), "content/blog");
13 case "events":
14 return join(process.cwd(), "content/events");
15 case "docs":
16 return join(process.cwd(), "content/docs");
17 case "grants":
18 return join(process.cwd(), "content/grants");
19 case "media":
20 return join(process.cwd(), "content/media");
21 case "updates":
22 return join(process.cwd(), "content/updates");
23 case "/":
24 return join(process.cwd(), "content");
25 default:
26 return join(process.cwd(), `content/${dir}`);
27 }
28};
30export function getPostSlugs(key) {
31 const dir = fs.existsSync(directories(key))
32 ? fs.readdirSync(directories(key), { withFileTypes: true })
33 : [];
34 return dir
35 .filter((f) => f.isFile() && f.name !== "_index.md")
36 .map((f) => f.name);
39// NB Gavin: This could be much simpler if we converted everything to a more common standard, like YAML
40const options = {
41 engines: {
42 toml: toml.parse.bind(toml),
43 },
44 language: "toml",
45 delimiters: "+++",
46};
48export function getPostBySlug(slug, fields = [], key) {
49 const realSlug = slug.replace(/\.md$/, "");
50 const fullPath = join(directories(key), `${realSlug}.md`);
51 const fileContents = fs.readFileSync(fullPath, "utf8");
52 const { data, content } = matter(fileContents, options);
53 const items = {};
55 // Ensure only the minimal needed data is exposed
56 fields.forEach((field) => {
57 if (field === "slug") {
58 items[field] = realSlug;
59 }
61 if (field === "content") {
62 items[field] = content;
63 }
65 if (data[field]) {
66 items[field] = data[field];
67 }
68 });
70 return items;
73export function getAllPosts(fields = [], key, sort = "") {
74 const slugs = getPostSlugs(key);
75 const posts = slugs
76 .map((slug) => getPostBySlug(slug, fields, key))
77 // sort posts by date in descending order
78 .sort((post1, post2) => {
79 if (sort === "date") {
80 return DateTime.fromISO(post1.date) > DateTime.fromISO(post2.date)
81 ? -1
82 : 1;
83 } else if (sort === "weight") {
84 return post1.weight > post2.weight ? -1 : 1;
85 }
86 });
87 return posts;
90export function getAllEvents(fields = [], key) {
91 const slugs = getPostSlugs(key);
92 const posts = slugs
93 .map((slug) => getPostBySlug(slug, fields, key))
94 // sort posts by date in descending order
95 .sort((post1, post2) =>
96 DateTime.fromISO(post1.starts) > DateTime.fromISO(post2.starts) ? -1 : 1
97 );
98 return posts;
101function getAllPaths(dirPath, arrayOfFiles) {
102 let files = fs.readdirSync(dirPath);
104 arrayOfFiles = arrayOfFiles || [];
106 files.forEach(function (file) {
107 if (fs.statSync(dirPath + "/" + file).isDirectory()) {
108 arrayOfFiles = getAllPaths(dirPath + "/" + file, arrayOfFiles);
109 } else {
110 arrayOfFiles.push(join(dirPath, "/", file));
111 }
112 });
114 return arrayOfFiles;
117export function getDocsPaths() {
118 return getAllPaths(directories("docs"), []);
121export function getNextPost(slug, fields = [], key, sort = "date") {
122 let resultPost = null;
124 getAllPosts(fields, key, sort).forEach((post, index, array) => {
125 if (post.slug === slug) {
126 if (typeof array[index - 1] !== "undefined") {
127 resultPost = array[index - 1];
128 }
129 }
130 });
131 return resultPost;
134export function getPreviousPost(slug, fields = [], key, sort = "date") {
135 let resultPost = null;
137 getAllPosts(fields, key, sort).forEach((post, index, array) => {
138 if (post.slug === slug) {
139 if (typeof array[index + 1] !== "undefined") {
140 resultPost = array[index + 1];
141 }
142 }
143 });
144 return resultPost;
147export function formatDateWithTime(d) {
148 const date = DateTime.fromISO(d, {
149 setZone: true,
150 }).toLocaleString(DateTime.DATETIME_FULL);
151 return date;
154export function capitalize(str) {
155 return str.charAt(0).toUpperCase() + str.slice(1);
158// Takes an ISO 8601 date string
159// Returns a time relative to the IANA timezone and iso8601 date
160export function generateDisplayDate(iso8601, zone = "America/Los_Angeles") {
161 return DateTime.fromISO(iso8601, { zone });
164// Takes an ISO 8601 date string
165// Returns a time relative to user's current timezone
166export function generateRealtimeDate(iso8601) {
167 return DateTime.fromISO(iso8601).setZone("system");
170// Formats a DateTime object to something like "July 15, 2021, 5:00 PM"
171export function formatDateAndTime(dateTimeObject) {
172 return dateTimeObject.toLocaleString(DateTime.DATETIME_HUGE);
175// Formats a DateTime object to something like "5:00 PM"
176export function formatTime(dateTimeObject) {
177 const dt = dateTimeObject.toLocaleString(DateTime.TIME_SIMPLE);
178 return dt.replace(/:00/g, "");
181export function formatTimeZone(dateTimeObject) {
182 return dateTimeObject.offsetNameShort;
185// Formats a DateTime object to something like "Jul 15, 2021"
186export function formatDate(dateTimeObject) {
187 return dateTimeObject.toLocaleString(DateTime.DATE_FULL);
190// export function generateCrumbs(path) {
191// const crumbs = path.split('/')
192// return crumbs
193// .filter(v => v !== '')
194// .map((crumb, index) => ({
195// name: capitalize(crumb),
196// key: crumb,
197// path: crumbs.slice(0, index+2).join('/'),
198// }))
199// }
201export const getPage = (path) => {
202 try {
203 let fileContents = fs.readFileSync(`${path}.md`, "utf8");
204 if (fileContents) {
205 const { data, content } = matter(fileContents, options);
206 return { data, content };
207 }
208 } catch {
209 try {
210 let fileContents = fs.readFileSync(`${path}/_index.md`, "utf8");
211 if (fileContents) {
212 const { data, content } = matter(fileContents, options);
213 return { data, content };
214 }
215 } catch {
216 console.error("no md file for slug");
217 }
218 }
219};
221// Returns an array of unique grants categories
222export function getGrantsCategories() {
223 const paths = fs.readdirSync(directories("grants"));
224 const uniqueCategories = paths
225 // Get only markdown files
226 .filter((path) => parse(path).ext === ".md")
227 // Parse frontmatter
228 .map((path) =>
229 matter(fs.readFileSync(join(directories("grants"), path)), options)
230 )
231 // Each markdown file has an array of categories. Collapse these arrays into one array.
232 .reduce((acc, metadata) => {
233 return [...acc, ...metadata.data.taxonomies.grant_category];
234 }, [])
235 // Deduplicate single array of categories such that the output is an array where each category is represented only once.
236 .reduce((acc, uniqueItem) => {
237 if (acc.includes(uniqueItem)) {
238 return acc;
239 }
240 return [...acc, uniqueItem];
241 }, []);
242 return uniqueCategories;
245// Returns an array of unique grants types
246export function getGrantsTypes() {
247 const paths = fs.readdirSync(directories("grants"));
248 const uniqueTypes = paths
249 // Get only markdown files
250 .filter((path) => parse(path).ext === ".md")
251 // Parse frontmatter to JSON
252 .map((path) =>
253 matter(fs.readFileSync(join(directories("grants"), path)), options)
254 )
255 // Each markdown file has an array of types. Collapse these arrays into one array.
256 .reduce((acc, metadata) => {
257 return [...acc, ...metadata.data.taxonomies.grant_type];
258 }, [])
259 // Deduplicate single array of types such that the output is an array where each type is represented only once.
260 .reduce((acc, uniqueItem) => {
261 if (acc.includes(uniqueItem)) {
262 return acc;
263 }
264 return [...acc, uniqueItem];
265 }, []);
266 return uniqueTypes;
269// Returns a number which represents how many grants are open, or uncompleted
270export function getOpenGrantsCount() {
271 const paths = fs.readdirSync(directories("grants"));
272 const count = paths
273 // Get only markdown files
274 .filter((path) => parse(path).ext === ".md")
275 // Parse frontmatter to JSON
276 .map((path) =>
277 matter(fs.readFileSync(join(directories("grants"), path)), options)
278 )
279 // Count grants which are both uncompleted and not assigned
280 .reduce((acc, metadata) => {
281 if (
282 !metadata.data.extra.completed &&
283 !metadata.data.extra.canceled &&
284 metadata.data.extra.assignee === ""
285 ) {
286 return acc + 1;
287 }
288 return acc;
289 }, 0);
290 return count;