74 lines
1.9 KiB
TypeScript
74 lines
1.9 KiB
TypeScript
|
import { unified } from "npm:unified";
|
||
|
import remarkParse from "npm:remark-parse";
|
||
|
import remarkFrontmatter from "https://esm.sh/remark-frontmatter@4";
|
||
|
import { parse } from "https://deno.land/std@0.194.0/yaml/mod.ts";
|
||
|
|
||
|
export type Document = {
|
||
|
name: string;
|
||
|
lastModified: number;
|
||
|
contentType: string;
|
||
|
size: number;
|
||
|
perm: string;
|
||
|
};
|
||
|
|
||
|
export function parseFrontmatter(yaml: string) {
|
||
|
return parse(yaml);
|
||
|
}
|
||
|
|
||
|
export async function getDocuments(): Promise<Document[]> {
|
||
|
const headers = new Headers();
|
||
|
headers.append("Accept", "application/json");
|
||
|
|
||
|
const response = await fetch("http://192.168.178.56:3007/index.json", {
|
||
|
headers: headers,
|
||
|
});
|
||
|
|
||
|
return response.json();
|
||
|
}
|
||
|
|
||
|
export async function getDocument(name: string): Promise<string> {
|
||
|
const response = await fetch("http://192.168.178.56:3007/" + name);
|
||
|
return await response.text();
|
||
|
}
|
||
|
|
||
|
export function parseDocument(doc: string) {
|
||
|
return unified()
|
||
|
.use(remarkParse).use(remarkFrontmatter, ["yaml", "toml"])
|
||
|
.parse(doc);
|
||
|
}
|
||
|
|
||
|
export type ParsedDocument = ReturnType<typeof parseDocument>;
|
||
|
export type DocumentChild = ParsedDocument["children"][number];
|
||
|
|
||
|
export function findRangeOfChildren(children: DocumentChild[]) {
|
||
|
const firstChild = children[0];
|
||
|
const lastChild = children.length > 1
|
||
|
? children[children.length - 1]
|
||
|
: firstChild;
|
||
|
|
||
|
const start = firstChild.position?.start.offset;
|
||
|
const end = lastChild.position?.end.offset;
|
||
|
|
||
|
if (typeof start !== "number" || typeof end !== "number") return;
|
||
|
|
||
|
return [start, end];
|
||
|
}
|
||
|
|
||
|
export function getTextOfRange(children: DocumentChild[], text: string) {
|
||
|
if (!children || children.length === 0) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
const range = findRangeOfChildren(children);
|
||
|
if (!range) return;
|
||
|
return text.substring(range[0], range[1]);
|
||
|
}
|
||
|
|
||
|
export function getTextOfChild(child: DocumentChild): string | undefined {
|
||
|
if ("value" in child) return child.value;
|
||
|
if ("children" in child) {
|
||
|
return getTextOfChild(child.children[0]);
|
||
|
}
|
||
|
return;
|
||
|
}
|