Significant refactor of index
* Moved YAML library import to index plug (so no async syscalls anymore) should speed things up * Merged task and item indexing * Merged tasks plug into index (questionable) * taskstate is now no longer a tag, but needs to be configured via configs
This commit is contained in:
@@ -13,7 +13,6 @@ import { LuaEnv, LuaStackFrame } from "./space_lua/runtime.ts";
|
||||
import { evalStatement } from "./space_lua/eval.ts";
|
||||
import { editorSyscalls } from "./plugos/syscalls/editor.ts";
|
||||
import { markdownSyscalls } from "./plugos/syscalls/markdown.ts";
|
||||
import { yamlSyscalls } from "./plugos/syscalls/yaml.ts";
|
||||
import { languageSyscalls } from "./plugos/syscalls/language.ts";
|
||||
import { jsonschemaSyscalls } from "./plugos/syscalls/jsonschema.ts";
|
||||
|
||||
@@ -61,7 +60,6 @@ export async function loadConfig(
|
||||
editorSyscalls(lateBoundClient),
|
||||
// And these, because: why not
|
||||
markdownSyscalls(lateBoundClient),
|
||||
yamlSyscalls(),
|
||||
languageSyscalls(),
|
||||
jsonschemaSyscalls(),
|
||||
);
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
} from "./plugos/syscalls/space.ts";
|
||||
import { syncSyscalls } from "./plugos/syscalls/sync.ts";
|
||||
import { systemSyscalls } from "./plugos/syscalls/system.ts";
|
||||
import { yamlSyscalls } from "./plugos/syscalls/yaml.ts";
|
||||
import type { Space } from "./space.ts";
|
||||
import { MQHook } from "./plugos/hooks/mq.ts";
|
||||
import { mqSyscalls } from "./plugos/syscalls/mq.ts";
|
||||
@@ -160,7 +159,6 @@ export class ClientSystem {
|
||||
systemSyscalls(client, this.readOnlyMode),
|
||||
markdownSyscalls(client),
|
||||
assetSyscalls(this.system),
|
||||
yamlSyscalls(),
|
||||
codeWidgetSyscalls(this.codeWidgetHook),
|
||||
clientCodeWidgetSyscalls(),
|
||||
languageSyscalls(),
|
||||
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
} from "@silverbulletmd/silverbullet/lib/ref";
|
||||
import { resolveASTReference } from "../space_lua.ts";
|
||||
import { LuaWidget } from "./lua_widget.ts";
|
||||
import YAML from "js-yaml";
|
||||
import type { PageMeta } from "@silverbulletmd/silverbullet/type/index";
|
||||
|
||||
export function luaDirectivePlugin(client: Client) {
|
||||
@@ -46,12 +45,8 @@ export function luaDirectivePlugin(client: Client) {
|
||||
if (node.name === "FrontMatterCode") {
|
||||
const text = state.sliceDoc(node.from, node.to);
|
||||
try {
|
||||
const parsedFrontmatter = YAML.load(text);
|
||||
let tags = parsedFrontmatter.tags || [];
|
||||
if (typeof tags === "string") {
|
||||
tags = tags.split(/\s+|,\s*/);
|
||||
}
|
||||
if (tags.find((tag: string) => tag.startsWith("meta/template"))) {
|
||||
// Very ad-hoc regex to detect if meta/template appears in the tag list
|
||||
if (/tags:.*meta\/template/s.exec(text)) {
|
||||
shouldRender = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -81,31 +81,33 @@ export function attachWidgetEventHandlers(
|
||||
// Implement task toggling
|
||||
div.querySelectorAll("span[data-external-task-ref]").forEach((el: any) => {
|
||||
const taskRef = el.dataset.externalTaskRef;
|
||||
const input = el.querySelector("input[type=checkbox]")!;
|
||||
input.addEventListener(
|
||||
"click",
|
||||
(e: any) => {
|
||||
// Avoid triggering the click on the parent
|
||||
e.stopPropagation();
|
||||
},
|
||||
);
|
||||
input.addEventListener(
|
||||
"change",
|
||||
(e: any) => {
|
||||
e.stopPropagation();
|
||||
const oldState = e.target.dataset.state;
|
||||
const newState = oldState === " " ? "x" : " ";
|
||||
// Update state in DOM as well for future toggles
|
||||
e.target.dataset.state = newState;
|
||||
console.log("Toggling task", taskRef);
|
||||
client.clientSystem.localSyscall(
|
||||
"system.invokeFunction",
|
||||
["tasks.updateTaskState", taskRef, oldState, newState],
|
||||
).catch(
|
||||
console.error,
|
||||
);
|
||||
},
|
||||
);
|
||||
const input = el.querySelector("input[type=checkbox]");
|
||||
if (input) {
|
||||
input.addEventListener(
|
||||
"click",
|
||||
(e: any) => {
|
||||
// Avoid triggering the click on the parent
|
||||
e.stopPropagation();
|
||||
},
|
||||
);
|
||||
input.addEventListener(
|
||||
"change",
|
||||
(e: any) => {
|
||||
e.stopPropagation();
|
||||
const oldState = e.target.dataset.state;
|
||||
const newState = oldState === " " ? "x" : " ";
|
||||
// Update state in DOM as well for future toggles
|
||||
e.target.dataset.state = newState;
|
||||
console.log("Toggling task", taskRef);
|
||||
client.clientSystem.localSyscall(
|
||||
"system.invokeFunction",
|
||||
["index.updateTaskState", taskRef, oldState, newState],
|
||||
).catch(
|
||||
console.error,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (events) {
|
||||
|
||||
@@ -5,7 +5,8 @@ import {
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import { assertEquals, assertNotEquals } from "@std/assert";
|
||||
import { parseMarkdown } from "./parser.ts";
|
||||
import { extractHashtag, renderHashtag } from "../../plug-api/lib/tags.ts";
|
||||
import { extractHashtag } from "../../plug-api/lib/tags.ts";
|
||||
import { renderHashtag } from "../../plugs/index/tags.ts";
|
||||
|
||||
const sample1 = `---
|
||||
type: page
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
#meta/api #maturity/beta
|
||||
|
||||
Implements APIs for defining custom task states. Currently extremely basic.
|
||||
|
||||
# API
|
||||
|
||||
## taskState.define(def)
|
||||
Defines a custom task state. Options:
|
||||
* `name`: name of the state
|
||||
* `done`: whether or not the state should be considered "done" or not, used by the `Task: Remove Completed` command
|
||||
|
||||
# Example
|
||||
```lua
|
||||
taskState.define {
|
||||
name = "TO DO"
|
||||
}
|
||||
taskState.define {
|
||||
name = "IN PROGRESS"
|
||||
}
|
||||
taskState.define {
|
||||
name = "DONE",
|
||||
done = true
|
||||
}
|
||||
```
|
||||
|
||||
# Implementation
|
||||
|
||||
```space-lua
|
||||
-- priority: 50
|
||||
taskState = taskState or {}
|
||||
|
||||
function taskState.define(spec)
|
||||
config.set({"taskStates", spec.name}, spec)
|
||||
end
|
||||
```
|
||||
@@ -295,6 +295,17 @@ config.define("mqSubscriptions", {
|
||||
},
|
||||
})
|
||||
|
||||
-- Task states
|
||||
config.define("taskStates", {
|
||||
type = "object",
|
||||
additionalProperties = {
|
||||
type = "object",
|
||||
properties = {
|
||||
-- for future use
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
-- Don't use directly, WIP
|
||||
config.define("tagDefinitions", {
|
||||
type = "object",
|
||||
@@ -348,6 +359,7 @@ config.set {
|
||||
item = { all = true },
|
||||
task = { all = true },
|
||||
},
|
||||
taskStates = {},
|
||||
actionButtons = {
|
||||
{
|
||||
icon = "home",
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import "./syscall_mock.ts";
|
||||
import { parse } from "../../client/markdown_parser/parse_tree.ts";
|
||||
import { extractAttributes } from "@silverbulletmd/silverbullet/lib/attribute";
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { renderToText } from "./tree.ts";
|
||||
import { extendedMarkdownLanguage } from "../../client/markdown_parser/parser.ts";
|
||||
|
||||
const inlineAttributeSample = `
|
||||
# My document
|
||||
Top level attributes: [name:: sup] [age:: 42] [children: [pete, "john", mary]]
|
||||
|
||||
* [ ] Attribute in a task [tag:: foo]
|
||||
* Regular item [tag:: bar]
|
||||
|
||||
1. Itemized list [tag:: baz]
|
||||
`;
|
||||
|
||||
Deno.test("Test attribute extraction", async () => {
|
||||
const tree = parse(extendedMarkdownLanguage, inlineAttributeSample);
|
||||
const toplevelAttributes = await extractAttributes(tree);
|
||||
// console.log("All attributes", toplevelAttributes);
|
||||
assertEquals(toplevelAttributes.name, "sup");
|
||||
assertEquals(toplevelAttributes.age, 42);
|
||||
assertEquals(toplevelAttributes.children, ["pete", "john", "mary"]);
|
||||
// Check if the attributes are still there
|
||||
assertEquals(renderToText(tree), inlineAttributeSample);
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
import { parse as parseYaml } from "@std/yaml";
|
||||
|
||||
// @ts-ignore: syscall is a global function
|
||||
globalThis.syscall = (name: string, ...args: readonly any[]) => {
|
||||
switch (name) {
|
||||
case "yaml.parse":
|
||||
return Promise.resolve(parseYaml(args[0]));
|
||||
case "system.applyAttributeExtractors":
|
||||
return Promise.resolve({});
|
||||
default:
|
||||
throw Error(`Not implemented in tests: ${name}`);
|
||||
}
|
||||
};
|
||||
@@ -1,42 +1,3 @@
|
||||
import type { FrontMatter } from "./frontmatter.ts";
|
||||
import {
|
||||
type ParseTree,
|
||||
traverseTree,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import { tagRegex } from "../../client/markdown_parser/constants.ts";
|
||||
import type { ObjectValue } from "@silverbulletmd/silverbullet/type/index";
|
||||
|
||||
export function updateITags<T>(obj: ObjectValue<T>, frontmatter: FrontMatter) {
|
||||
const itags = new Set<string>([obj.tag, ...frontmatter.tags || []]);
|
||||
for (const tag of obj.tags || []) {
|
||||
itags.add(tag);
|
||||
}
|
||||
for (const tag of obj.itags || []) {
|
||||
itags.add(tag);
|
||||
}
|
||||
obj.itags = [...itags];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a set of hashtags from a tree
|
||||
* @param n the tree to extract from
|
||||
* @returns
|
||||
*/
|
||||
export function extractHashTags(n: ParseTree): string[] {
|
||||
const tags = new Set<string>();
|
||||
traverseTree(n, (n) => {
|
||||
if (n.type === "Hashtag") {
|
||||
tags.add(extractHashtag(n.children![0].text!));
|
||||
return true;
|
||||
} else if (n.type === "OrderedList" || n.type === "BulletList") {
|
||||
// Don't traverse into sub-lists
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return [...tags];
|
||||
}
|
||||
|
||||
/** Extract the name from hashtag text, removing # prefix and <angle brackets> if necessary */
|
||||
export function extractHashtag(text: string): string {
|
||||
if (text[0] !== "#") { // you shouldn't call this function at all
|
||||
@@ -52,27 +13,3 @@ export function extractHashtag(text: string): string {
|
||||
return text.slice(1);
|
||||
}
|
||||
}
|
||||
|
||||
/** Get markup for a hashtag name with # prefix and angle brackets if necessary */
|
||||
export function renderHashtag(name: string): string {
|
||||
// detect with the same regex as the parser
|
||||
const simple: string = "#" + name;
|
||||
const match = simple.match(tagRegex);
|
||||
if (!match || match[0].length !== simple.length) {
|
||||
return `#<${name}>`;
|
||||
} else return simple;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans hashtags from a tree as a side effect
|
||||
* @param n
|
||||
*/
|
||||
export function cleanHashTags(n: ParseTree) {
|
||||
traverseTree(n, (n) => {
|
||||
if (n.type === "Hashtag") {
|
||||
n.children = [];
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ export * as codeWidget from "./syscalls/code_widget.ts";
|
||||
export * as asset from "./syscalls/asset.ts";
|
||||
export * as events from "./syscalls/event.ts";
|
||||
export * as shell from "./syscalls/shell.ts";
|
||||
export * as YAML from "./syscalls/yaml.ts";
|
||||
export * as mq from "./syscalls/mq.ts";
|
||||
export * as datastore from "./syscalls/datastore.ts";
|
||||
export * as jsonschema from "./syscalls/jsonschema.ts";
|
||||
|
||||
@@ -31,8 +31,9 @@ export function queryLuaObjects<T>(
|
||||
tag: string,
|
||||
query: LuaCollectionQuery,
|
||||
scopedVariables?: Record<string, any>,
|
||||
ttlSecs?: number,
|
||||
): Promise<ObjectValue<T>[]> {
|
||||
return syscall("index.queryLuaObjects", tag, query, scopedVariables);
|
||||
return syscall("index.queryLuaObjects", tag, query, scopedVariables, ttlSecs);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { syscall } from "../syscall.ts";
|
||||
|
||||
/**
|
||||
* YAML operations
|
||||
* YAML operations, exposed via `index` plug
|
||||
* @module
|
||||
*/
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
spaceWriteSyscalls,
|
||||
} from "../client/plugos/syscalls/space.ts";
|
||||
import { systemSyscalls } from "../client/plugos/syscalls/system.ts";
|
||||
import { yamlSyscalls } from "../client/plugos/syscalls/yaml.ts";
|
||||
import { System } from "../client/plugos/system.ts";
|
||||
import { Space } from "../client/space.ts";
|
||||
import { SpaceLuaEnvironment } from "../client/space_lua.ts";
|
||||
@@ -53,7 +52,6 @@ export function createMockSystem() {
|
||||
spaceReadSyscalls(clientMock),
|
||||
spaceWriteSyscalls(clientMock),
|
||||
markdownSyscalls(clientMock),
|
||||
yamlSyscalls(),
|
||||
languageSyscalls(),
|
||||
jsonschemaSyscalls(),
|
||||
indexSyscalls(clientMock),
|
||||
|
||||
@@ -6,7 +6,6 @@ export const builtinPlugNames = [
|
||||
"sync",
|
||||
"plug-manager",
|
||||
"emoji",
|
||||
"tasks",
|
||||
"image-viewer",
|
||||
];
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { folderName } from "@silverbulletmd/silverbullet/lib/resolve";
|
||||
import { queryLuaObjects } from "../index/api.ts";
|
||||
import { language, lua } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import type { DocumentMeta, PageMeta } from "../../plug-api/types/index.ts";
|
||||
import { index, language, lua } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import type {
|
||||
DocumentMeta,
|
||||
PageMeta,
|
||||
} from "@silverbulletmd/silverbullet/type/index";
|
||||
import type { CompleteEvent } from "@silverbulletmd/silverbullet/type/client";
|
||||
|
||||
// Page completion
|
||||
@@ -44,7 +46,12 @@ export async function pageComplete(completeEvent: CompleteEvent) {
|
||||
|
||||
if (prefix.startsWith("^")) {
|
||||
// A carrot prefix means we're looking for a meta page
|
||||
allPages = await queryLuaObjects<PageMeta>("page", isMetaPageQuery!, {}, 5);
|
||||
allPages = await index.queryLuaObjects<PageMeta>(
|
||||
"page",
|
||||
isMetaPageQuery!,
|
||||
{},
|
||||
5,
|
||||
);
|
||||
// Let's prefix the names with a caret to make them match
|
||||
allPages = allPages.map((page) => ({
|
||||
...page,
|
||||
@@ -54,11 +61,11 @@ export async function pageComplete(completeEvent: CompleteEvent) {
|
||||
// This is the most common case, we're combining three types of completions here:
|
||||
allPages = (await Promise.all([
|
||||
// All non-meta pages
|
||||
queryLuaObjects<PageMeta>("page", isntMetaPageQuery, {}, 5),
|
||||
index.queryLuaObjects<PageMeta>("page", isntMetaPageQuery, {}, 5),
|
||||
// All documents
|
||||
queryLuaObjects<DocumentMeta>("document", isDocumentQuery, {}, 5),
|
||||
index.queryLuaObjects<DocumentMeta>("document", isDocumentQuery, {}, 5),
|
||||
// And all links to non-existing pages (to augment the existing ones)
|
||||
queryLuaObjects<string>(
|
||||
index.queryLuaObjects<string>(
|
||||
"aspiring-page",
|
||||
{
|
||||
select: { type: "Variable", name: "name", ctx: {} as any },
|
||||
|
||||
@@ -2,8 +2,8 @@ import {
|
||||
clientStore,
|
||||
codeWidget,
|
||||
editor,
|
||||
index,
|
||||
} from "@silverbulletmd/silverbullet/syscalls";
|
||||
import { queryLuaObjects } from "../index/api.ts";
|
||||
import type { FilterOption } from "@silverbulletmd/silverbullet/type/client";
|
||||
|
||||
// Run on "editor:init"
|
||||
@@ -44,7 +44,7 @@ export async function openMetaNavigator() {
|
||||
|
||||
export async function openTagNavigator() {
|
||||
// Query all tags with a matching parent
|
||||
const allTags: FilterOption[] = (await queryLuaObjects<string>("tag", {
|
||||
const allTags: FilterOption[] = (await index.queryLuaObjects<string>("tag", {
|
||||
select: { type: "Variable", name: "name", ctx: {} as any },
|
||||
distinct: true,
|
||||
})).map((name) => ({ name }));
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { extractHashtag } from "../../plug-api/lib/tags.ts";
|
||||
import { editor, markdown } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import {
|
||||
addParentPointers,
|
||||
@@ -14,6 +13,7 @@ import {
|
||||
import { parseToRef } from "@silverbulletmd/silverbullet/lib/ref";
|
||||
import { tagPrefix } from "../index/constants.ts";
|
||||
import type { ClickEvent } from "@silverbulletmd/silverbullet/type/client";
|
||||
import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
|
||||
async function actionClickOrActionEnter(
|
||||
mdTree: ParseTree | null,
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import {
|
||||
extractFrontMatter as extractFrontmatterFromTree,
|
||||
type FrontMatter,
|
||||
type FrontMatterExtractOptions,
|
||||
} from "../../plug-api/lib/frontmatter.ts";
|
||||
} from "./frontmatter.ts";
|
||||
import {
|
||||
collectNodesOfType,
|
||||
renderToText,
|
||||
|
||||
@@ -2,23 +2,24 @@ import {
|
||||
findNodeOfType,
|
||||
type ParseTree,
|
||||
replaceNodesMatching,
|
||||
traverseTreeAsync,
|
||||
} from "./tree.ts";
|
||||
traverseTree,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
|
||||
import { cleanupJSON } from "@silverbulletmd/silverbullet/lib/json";
|
||||
|
||||
import { YAML } from "../syscalls.ts";
|
||||
import YAML from "js-yaml";
|
||||
|
||||
/**
|
||||
* Extracts attributes from a tree
|
||||
* @param tree tree to extract attributes from
|
||||
* @returns mapping from attribute name to attribute value
|
||||
* Collects all attributes from a parse tree
|
||||
* @param tree to clean attributes from
|
||||
* @return
|
||||
*/
|
||||
export async function extractAttributes(
|
||||
export function collectAttributes(
|
||||
tree: ParseTree,
|
||||
): Promise<Record<string, any>> {
|
||||
): Record<string, any> {
|
||||
const attributes: Record<string, any> = {};
|
||||
await traverseTreeAsync(tree, async (n) => {
|
||||
|
||||
traverseTree(tree, (n) => {
|
||||
if (tree !== n && n.type === "ListItem") {
|
||||
// Find top-level only, no nested lists
|
||||
return true;
|
||||
@@ -30,16 +31,16 @@ export async function extractAttributes(
|
||||
const name = nameNode.children![0].text!;
|
||||
const val = valueNode.children![0].text!;
|
||||
try {
|
||||
attributes[name] = cleanupJSON(await YAML.parse(val));
|
||||
attributes[name] = cleanupJSON(YAML.load(val));
|
||||
} catch (e: any) {
|
||||
console.error("Error parsing attribute value as YAML", val, e);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Go on...
|
||||
return false;
|
||||
});
|
||||
|
||||
return attributes;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { queryLuaObjects } from "../index/api.ts";
|
||||
import type { TaskStateObject } from "./task.ts";
|
||||
import { config } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import type { CompleteEvent } from "@silverbulletmd/silverbullet/type/client";
|
||||
|
||||
export async function completeTaskState(completeEvent: CompleteEvent) {
|
||||
@@ -9,17 +8,11 @@ export async function completeTaskState(completeEvent: CompleteEvent) {
|
||||
if (!taskMatch) {
|
||||
return null;
|
||||
}
|
||||
const allStates = await queryLuaObjects<TaskStateObject>(
|
||||
"taskstate",
|
||||
{},
|
||||
{},
|
||||
5,
|
||||
);
|
||||
const states = [...new Set(allStates.map((s) => s.state))];
|
||||
const allStates = Object.keys(await config.get("taskStates", {}));
|
||||
|
||||
return {
|
||||
from: completeEvent.pos - taskMatch[2].length,
|
||||
options: states.map((state) => ({
|
||||
options: allStates.map((state) => ({
|
||||
label: state,
|
||||
})),
|
||||
};
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
ObjectValue,
|
||||
PageMeta,
|
||||
} from "@silverbulletmd/silverbullet/type/index";
|
||||
import { extractFrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { extractFrontMatter } from "./frontmatter.ts";
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { indexData } from "./data.ts";
|
||||
|
||||
@@ -25,7 +25,7 @@ age: 101
|
||||
Deno.test("Test indexers", async () => {
|
||||
createMockSystem();
|
||||
const tree = parseMarkdown(testPage);
|
||||
const frontmatter = await extractFrontMatter(tree);
|
||||
const frontmatter = extractFrontMatter(tree);
|
||||
|
||||
const pageMeta: PageMeta = {
|
||||
ref: "test",
|
||||
|
||||
+51
-52
@@ -1,12 +1,12 @@
|
||||
import { YAML } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import YAML from "js-yaml";
|
||||
import {
|
||||
collectNodesOfType,
|
||||
findNodeOfType,
|
||||
type ParseTree,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import type { TagObject } from "./tags.ts";
|
||||
import type { FrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { updateITags } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import type { FrontMatter } from "./frontmatter.ts";
|
||||
import { updateITags } from "./tags.ts";
|
||||
import type {
|
||||
ObjectValue,
|
||||
PageMeta,
|
||||
@@ -19,7 +19,7 @@ type DataObject = ObjectValue<
|
||||
} & Record<string, any>
|
||||
>;
|
||||
|
||||
export async function indexData(
|
||||
export function indexData(
|
||||
pageMeta: PageMeta,
|
||||
frontmatter: FrontMatter,
|
||||
tree: ParseTree,
|
||||
@@ -27,55 +27,54 @@ export async function indexData(
|
||||
const dataObjects: ObjectValue<DataObject>[] = [];
|
||||
const tagObjects: Map<string, ObjectValue<TagObject>> = new Map();
|
||||
|
||||
await Promise.all(
|
||||
collectNodesOfType(tree, "FencedCode").map(async (t) => {
|
||||
const codeInfoNode = findNodeOfType(t, "CodeInfo");
|
||||
if (!codeInfoNode) {
|
||||
return;
|
||||
}
|
||||
const fenceType = codeInfoNode.children![0].text!;
|
||||
if (fenceType !== "data" && !fenceType.startsWith("#")) {
|
||||
return;
|
||||
}
|
||||
const codeTextNode = findNodeOfType(t, "CodeText");
|
||||
if (!codeTextNode) {
|
||||
// Honestly, this shouldn't happen
|
||||
return;
|
||||
}
|
||||
const codeText = codeTextNode.children![0].text!;
|
||||
const dataType = fenceType === "data" ? "data" : fenceType.substring(1);
|
||||
try {
|
||||
const docs = codeText.split("---");
|
||||
// We support multiple YAML documents in one block
|
||||
for (let i = 0; i < docs.length; i++) {
|
||||
const doc = await YAML.parse(docs[i]);
|
||||
if (!doc) {
|
||||
continue;
|
||||
}
|
||||
const pos = t.from! + i;
|
||||
const dataObj = {
|
||||
ref: `${pageMeta.name}@${pos}`,
|
||||
tag: dataType,
|
||||
itags: ["data"],
|
||||
...doc,
|
||||
pos,
|
||||
page: pageMeta.name,
|
||||
};
|
||||
updateITags(dataObj, frontmatter);
|
||||
dataObjects.push(dataObj);
|
||||
collectNodesOfType(tree, "FencedCode").map((t) => {
|
||||
const codeInfoNode = findNodeOfType(t, "CodeInfo");
|
||||
if (!codeInfoNode) {
|
||||
return;
|
||||
}
|
||||
const fenceType = codeInfoNode.children![0].text!;
|
||||
if (fenceType !== "data" && !fenceType.startsWith("#")) {
|
||||
return;
|
||||
}
|
||||
const codeTextNode = findNodeOfType(t, "CodeText");
|
||||
if (!codeTextNode) {
|
||||
// Honestly, this shouldn't happen
|
||||
return;
|
||||
}
|
||||
const codeText = codeTextNode.children![0].text!;
|
||||
const dataType = fenceType === "data" ? "data" : fenceType.substring(1);
|
||||
try {
|
||||
const docs = codeText.split("---");
|
||||
// We support multiple YAML documents in one block
|
||||
for (let i = 0; i < docs.length; i++) {
|
||||
const doc = YAML.load(docs[i]);
|
||||
if (!doc) {
|
||||
continue;
|
||||
}
|
||||
tagObjects.set(dataType, {
|
||||
ref: dataType,
|
||||
tag: "tag",
|
||||
name: dataType,
|
||||
const pos = t.from! + i;
|
||||
const dataObj = {
|
||||
ref: `${pageMeta.name}@${pos}`,
|
||||
tag: dataType,
|
||||
itags: ["data"],
|
||||
...doc,
|
||||
pos,
|
||||
page: pageMeta.name,
|
||||
parent: "data",
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Could not parse data", codeText, "error:", e);
|
||||
return;
|
||||
};
|
||||
updateITags(dataObj, frontmatter);
|
||||
dataObjects.push(dataObj);
|
||||
}
|
||||
}),
|
||||
);
|
||||
return [...dataObjects, ...tagObjects.values()];
|
||||
tagObjects.set(dataType, {
|
||||
ref: dataType,
|
||||
tag: "tag",
|
||||
name: dataType,
|
||||
page: pageMeta.name,
|
||||
parent: "data",
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Could not parse data", codeText, "error:", e);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
return Promise.resolve([...dataObjects, ...tagObjects.values()]);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { space, system } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import { indexObjects } from "./api.ts";
|
||||
import type { DocumentMeta } from "../../plug-api/types/index.ts";
|
||||
|
||||
// Note: clearFileIndex is not called but since this is the only attachmet:index listener, this should be fine (famous last words)
|
||||
// Note: clearFileIndex is not called but since this is the only document:index listener, this should be fine (famous last words)
|
||||
export async function indexDocument(name: string) {
|
||||
if (await system.getMode() === "ro") {
|
||||
return;
|
||||
|
||||
@@ -4,11 +4,11 @@ import {
|
||||
findParentMatching,
|
||||
type ParseTree,
|
||||
renderToText,
|
||||
replaceNodesMatchingAsync,
|
||||
} from "./tree.ts";
|
||||
import { cleanupJSON } from "./json.ts";
|
||||
import { YAML } from "../syscalls.ts";
|
||||
import { extractHashtag } from "./tags.ts";
|
||||
replaceNodesMatching,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import { cleanupJSON } from "@silverbulletmd/silverbullet/lib/json";
|
||||
import YAML from "js-yaml";
|
||||
import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
|
||||
export type FrontMatter = { tags?: string[] } & Record<string, any>;
|
||||
|
||||
@@ -23,17 +23,17 @@ export type FrontMatterExtractOptions = {
|
||||
* optionally removes certain keys from the front matter
|
||||
* Side effect: adds parent pointers to tree
|
||||
*/
|
||||
export async function extractFrontMatter(
|
||||
export function extractFrontMatter(
|
||||
tree: ParseTree,
|
||||
options: FrontMatterExtractOptions = {},
|
||||
): Promise<FrontMatter> {
|
||||
): FrontMatter {
|
||||
addParentPointers(tree);
|
||||
let data: FrontMatter = {
|
||||
tags: [],
|
||||
};
|
||||
const tags: string[] = [];
|
||||
|
||||
await replaceNodesMatchingAsync(tree, async (t) => {
|
||||
replaceNodesMatching(tree, (t) => {
|
||||
// Find tags in paragraphs directly nested under the document where the only content is tags
|
||||
if (t.type === "Paragraph" && t.parent?.type === "Document") {
|
||||
let onlyTags = true;
|
||||
@@ -74,7 +74,7 @@ export async function extractFrontMatter(
|
||||
const yamlNode = t.children![1].children![0];
|
||||
const yamlText = renderToText(yamlNode);
|
||||
try {
|
||||
const parsedData: any = cleanupJSON(await YAML.parse(yamlText));
|
||||
const parsedData: any = cleanupJSON(YAML.load(yamlText));
|
||||
// console.log("Parsed front matter", parsedData);
|
||||
const newData = { ...parsedData };
|
||||
data = { ...data, ...parsedData };
|
||||
@@ -101,7 +101,7 @@ export async function extractFrontMatter(
|
||||
}
|
||||
}
|
||||
if (removedOne) {
|
||||
yamlNode.text = await YAML.stringify(newData);
|
||||
yamlNode.text = YAML.stringify(newData);
|
||||
}
|
||||
}
|
||||
// If nothing is left, let's just delete this whole block
|
||||
@@ -124,7 +124,7 @@ export async function extractFrontMatter(
|
||||
const name = nameNode.children![0].text!;
|
||||
const val = valueNode.children![0].text!;
|
||||
try {
|
||||
data[name] = cleanupJSON(await YAML.parse(val));
|
||||
data[name] = cleanupJSON(YAML.load(val));
|
||||
} catch (e: any) {
|
||||
console.error("Error parsing attribute value as YAML", val, e);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { parseMarkdown } from "../../client/markdown_parser/parser.ts";
|
||||
import { createMockSystem } from "../../plug-api/system_mock.ts";
|
||||
import type { PageMeta } from "@silverbulletmd/silverbullet/type/index";
|
||||
import { extractFrontMatter } from "./frontmatter.ts";
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { indexHeaders } from "./header.ts";
|
||||
|
||||
const testPage = `
|
||||
# Header 1
|
||||
## Header 1.1
|
||||
# Header 2 [testAttr: 10]
|
||||
`.trim();
|
||||
|
||||
Deno.test("Test header indexing", async () => {
|
||||
createMockSystem();
|
||||
const tree = parseMarkdown(testPage);
|
||||
const frontmatter = await extractFrontMatter(tree);
|
||||
|
||||
const pageMeta: PageMeta = {
|
||||
ref: "test",
|
||||
name: "test",
|
||||
tag: "page",
|
||||
created: "",
|
||||
lastModified: "",
|
||||
perm: "rw",
|
||||
};
|
||||
|
||||
const headers = await indexHeaders(
|
||||
pageMeta,
|
||||
frontmatter,
|
||||
tree,
|
||||
);
|
||||
// 1 data 1 tag
|
||||
assertEquals(headers.length, 3);
|
||||
|
||||
assertEquals(headers[0].name, "Header 1");
|
||||
assertEquals(headers[0].level, 1);
|
||||
assertEquals(headers[1].name, "Header 1.1");
|
||||
assertEquals(headers[1].level, 2);
|
||||
});
|
||||
+26
-23
@@ -1,30 +1,38 @@
|
||||
import {
|
||||
collectNodesMatching,
|
||||
collectNodesOfType,
|
||||
type ParseTree,
|
||||
renderToText,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import type { IndexTreeEvent } from "@silverbulletmd/silverbullet/type/event";
|
||||
import { indexObjects, queryLuaObjects } from "./api.ts";
|
||||
import { queryLuaObjects } from "./api.ts";
|
||||
import {
|
||||
getNameFromPath,
|
||||
parseToRef,
|
||||
} from "@silverbulletmd/silverbullet/lib/ref";
|
||||
import { extractAttributes } from "@silverbulletmd/silverbullet/lib/attribute";
|
||||
import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import { lua } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import type { ObjectValue } from "@silverbulletmd/silverbullet/type/index";
|
||||
import type {
|
||||
ObjectValue,
|
||||
PageMeta,
|
||||
} from "@silverbulletmd/silverbullet/type/index";
|
||||
import type { CompleteEvent } from "@silverbulletmd/silverbullet/type/client";
|
||||
import type { FrontMatter } from "./frontmatter.ts";
|
||||
import { cleanAttributes, collectAttributes } from "./attribute.ts";
|
||||
import { cleanTags, collectTags } from "./tags.ts";
|
||||
|
||||
type HeaderObject = ObjectValue<
|
||||
{
|
||||
name: string;
|
||||
text: string;
|
||||
page: string;
|
||||
level: number;
|
||||
pos: number;
|
||||
} & Record<string, any>
|
||||
>;
|
||||
|
||||
export async function indexHeaders({ name: pageName, tree }: IndexTreeEvent) {
|
||||
export function indexHeaders(
|
||||
pageMeta: PageMeta,
|
||||
_frontmatter: FrontMatter,
|
||||
tree: ParseTree,
|
||||
): Promise<HeaderObject[]> {
|
||||
const headers: ObjectValue<HeaderObject>[] = [];
|
||||
|
||||
for (
|
||||
@@ -34,32 +42,27 @@ export async function indexHeaders({ name: pageName, tree }: IndexTreeEvent) {
|
||||
)
|
||||
) {
|
||||
const level = +n.type!.substring("ATXHeading".length);
|
||||
const tags = new Set<string>();
|
||||
|
||||
collectNodesOfType(n, "Hashtag").forEach((h) => {
|
||||
// Push tag to the list, removing the initial #
|
||||
tags.add(extractHashtag(h.children![0].text!));
|
||||
h.children = [];
|
||||
});
|
||||
|
||||
// Extract attributes and remove from tree
|
||||
const extractedAttributes = await extractAttributes(n);
|
||||
const name = n.children!.slice(1).map(renderToText).join("").trim();
|
||||
const name = renderToText(n).slice(level + 1);
|
||||
const tags = collectTags(n);
|
||||
const attributes = collectAttributes(n);
|
||||
cleanTags(n);
|
||||
cleanAttributes(n);
|
||||
const text = renderToText(n).slice(level + 1);
|
||||
|
||||
headers.push({
|
||||
ref: `${pageName}@${n.from}`,
|
||||
ref: `${pageMeta.name}@${n.from}`,
|
||||
tag: "header",
|
||||
tags: [...tags],
|
||||
level,
|
||||
name,
|
||||
page: pageName,
|
||||
text,
|
||||
page: pageMeta.name,
|
||||
pos: n.from!,
|
||||
...extractedAttributes,
|
||||
...attributes,
|
||||
});
|
||||
}
|
||||
|
||||
// console.log("Found", headers, "headers(s)");
|
||||
await indexObjects(pageName, headers);
|
||||
return Promise.resolve(headers);
|
||||
}
|
||||
|
||||
export async function headerComplete(completeEvent: CompleteEvent) {
|
||||
|
||||
@@ -15,15 +15,22 @@ functions:
|
||||
getObjectByRef:
|
||||
path: api.ts:getObjectByRef
|
||||
syscall: index.getObjectByRef
|
||||
|
||||
extractFrontmatter:
|
||||
path: api.ts:extractFrontmatter
|
||||
syscall: index.extractFrontmatter
|
||||
|
||||
patchFrontmatter:
|
||||
path: api.ts:patchFrontmatter
|
||||
syscall: index.patchFrontmatter
|
||||
|
||||
# YAML syscalls
|
||||
yamlParse:
|
||||
path: yaml.ts:parse
|
||||
syscall: yaml.parse
|
||||
|
||||
yamlStringify:
|
||||
path: yaml.ts:stringify
|
||||
syscall: yaml.stringify
|
||||
|
||||
# Index management
|
||||
clearIndex:
|
||||
path: api.ts:clearIndex
|
||||
@@ -78,10 +85,6 @@ functions:
|
||||
- page:index
|
||||
|
||||
# Headers
|
||||
indexHeaders:
|
||||
path: header.ts:indexHeaders
|
||||
events:
|
||||
- page:index
|
||||
headerComplete:
|
||||
path: header.ts:headerComplete
|
||||
events:
|
||||
@@ -161,6 +164,34 @@ functions:
|
||||
events:
|
||||
- editor:lint
|
||||
|
||||
# Tasks
|
||||
updateTaskState:
|
||||
path: task.ts:updateTaskState
|
||||
|
||||
taskToggle:
|
||||
path: "./task.ts:taskToggle"
|
||||
events:
|
||||
- page:click
|
||||
taskToggleCommand:
|
||||
path: ./task.ts:taskCycleCommand
|
||||
command:
|
||||
name: "Task: Cycle State"
|
||||
key: Alt-t
|
||||
requireMode: rw
|
||||
requireEditor: page
|
||||
|
||||
taskComplete:
|
||||
path: ./complete.ts:completeTaskState
|
||||
events:
|
||||
- editor:complete
|
||||
|
||||
removeCompletedTasksCommand:
|
||||
path: task.ts:removeCompletedTasksCommand
|
||||
command:
|
||||
name: "Task: Remove Completed"
|
||||
requireMode: rw
|
||||
requireEditor: page
|
||||
|
||||
config:
|
||||
# Schema for the built-in tags indexed by this plug
|
||||
schema.tag:
|
||||
@@ -513,3 +544,39 @@ config:
|
||||
type: string
|
||||
pos:
|
||||
type: number
|
||||
task:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
properties:
|
||||
ref:
|
||||
type: string
|
||||
readOnly: true
|
||||
tag:
|
||||
type: string
|
||||
tags:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
nullable: true
|
||||
itags:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
nullable: true
|
||||
name:
|
||||
type: string
|
||||
page:
|
||||
type: string
|
||||
parent:
|
||||
type: string
|
||||
pos:
|
||||
type: number
|
||||
text:
|
||||
type: string
|
||||
state:
|
||||
type: string
|
||||
done:
|
||||
type: boolean
|
||||
deadline:
|
||||
type: string
|
||||
nullable: true
|
||||
|
||||
@@ -2,10 +2,7 @@ import type {
|
||||
ObjectValue,
|
||||
PageMeta,
|
||||
} from "@silverbulletmd/silverbullet/type/index";
|
||||
import {
|
||||
extractFrontMatter,
|
||||
type FrontMatter,
|
||||
} from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { extractFrontMatter, type FrontMatter } from "./frontmatter.ts";
|
||||
import type { ParseTree } from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import type { IndexTreeEvent } from "@silverbulletmd/silverbullet/type/event";
|
||||
import { space } from "@silverbulletmd/silverbullet/syscalls";
|
||||
@@ -13,6 +10,7 @@ import { indexObjects } from "./api.ts";
|
||||
import { indexPage as pageIndexPage } from "./page.ts";
|
||||
import { indexData } from "./data.ts";
|
||||
import { indexItems } from "./item.ts";
|
||||
import { indexHeaders } from "./header.ts";
|
||||
|
||||
export type IndexerFunction = (
|
||||
pageMeta: PageMeta,
|
||||
@@ -20,11 +18,16 @@ export type IndexerFunction = (
|
||||
tree: ParseTree,
|
||||
) => Promise<ObjectValue<any>[]>;
|
||||
|
||||
const allIndexers: IndexerFunction[] = [pageIndexPage, indexData, indexItems];
|
||||
const allIndexers: IndexerFunction[] = [
|
||||
pageIndexPage,
|
||||
indexData,
|
||||
indexItems,
|
||||
indexHeaders,
|
||||
];
|
||||
|
||||
export async function indexPage({ name, tree }: IndexTreeEvent) {
|
||||
const pageMeta = await space.getPageMeta(name);
|
||||
const frontmatter = await extractFrontMatter(tree);
|
||||
const frontmatter = extractFrontMatter(tree);
|
||||
|
||||
console.log("Now going to index page", name);
|
||||
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
import "../../plug-api/lib/syscall_mock.ts";
|
||||
import { parseMarkdown } from "../../client/markdown_parser/parser.ts";
|
||||
import { indexItems } from "./item.ts";
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { createMockSystem } from "../../plug-api/system_mock.ts";
|
||||
import { extractFrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { extractFrontMatter } from "./frontmatter.ts";
|
||||
import type { PageMeta } from "@silverbulletmd/silverbullet/type/index";
|
||||
|
||||
const itemsMd = `
|
||||
* Item 1 #tag1 #tag2 [age: 100]
|
||||
* Item 1.1 #tag3 #tag1
|
||||
* Item 1.1.1
|
||||
* [ ] Task 1
|
||||
* [x] Task 2
|
||||
* Item 2 #tag4
|
||||
* [ ] Sub task
|
||||
`;
|
||||
|
||||
Deno.test("Test item extraction", async () => {
|
||||
createMockSystem();
|
||||
const tree = parseMarkdown(itemsMd);
|
||||
const frontmatter = await extractFrontMatter(tree);
|
||||
const frontmatter = extractFrontMatter(tree);
|
||||
const pageMeta: PageMeta = {
|
||||
ref: "test",
|
||||
name: "test",
|
||||
@@ -25,7 +28,7 @@ Deno.test("Test item extraction", async () => {
|
||||
perm: "rw",
|
||||
};
|
||||
const items = await indexItems(pageMeta, frontmatter, tree);
|
||||
|
||||
// Test regular items
|
||||
assertEquals(items[0].name, "Item 1");
|
||||
assertEquals(items[0].age, 100);
|
||||
assertEquals(items[0].page, "test");
|
||||
@@ -41,6 +44,22 @@ Deno.test("Test item extraction", async () => {
|
||||
new Set(["tag3", "tag2", "tag1", "item"]),
|
||||
);
|
||||
assertEquals(items[1].parent, items[0].ref);
|
||||
|
||||
assertEquals(items[2].parent, items[1].ref);
|
||||
|
||||
// Test tasks
|
||||
assertEquals(items[3].tag, "task");
|
||||
assertEquals(items[3].name, "Task 1");
|
||||
assertEquals(items[3].done, false);
|
||||
assertEquals(items[3].state, " ");
|
||||
|
||||
assertEquals(items[4].tag, "task");
|
||||
assertEquals(items[4].name, "Task 2");
|
||||
assertEquals(items[4].done, true);
|
||||
assertEquals(items[4].state, "x");
|
||||
|
||||
assertEquals(items[6].tag, "task");
|
||||
assertEquals(items[6].name, "Sub task");
|
||||
assertEquals(items[6].done, false);
|
||||
assertEquals(items[6].parent, items[5].ref);
|
||||
assertEquals(new Set(items[6].itags), new Set(["task", "tag4"]));
|
||||
});
|
||||
|
||||
+63
-55
@@ -2,24 +2,31 @@ import {
|
||||
findParentMatching,
|
||||
type ParseTree,
|
||||
renderToText,
|
||||
traverseTreeAsync,
|
||||
traverseTree,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import {
|
||||
cleanAttributes,
|
||||
extractAttributes,
|
||||
} from "@silverbulletmd/silverbullet/lib/attribute";
|
||||
import {
|
||||
cleanHashTags,
|
||||
extractHashTags,
|
||||
updateITags,
|
||||
} from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import type { FrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { deepClone } from "@silverbulletmd/silverbullet/lib/json";
|
||||
import { cleanTags, collectTags, updateITags } from "./tags.ts";
|
||||
import type { FrontMatter } from "./frontmatter.ts";
|
||||
import type {
|
||||
ObjectValue,
|
||||
PageMeta,
|
||||
} from "@silverbulletmd/silverbullet/type/index";
|
||||
import { system } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import { cleanAttributes, collectAttributes } from "./attribute.ts";
|
||||
import { deepClone } from "@silverbulletmd/silverbullet/lib/json";
|
||||
|
||||
export type TaskObject = ObjectValue<
|
||||
{
|
||||
page: string;
|
||||
pos: number;
|
||||
name: string;
|
||||
text: string;
|
||||
done: boolean;
|
||||
state: string;
|
||||
deadline?: string;
|
||||
} & Record<string, any>
|
||||
>;
|
||||
|
||||
const completeStates = ["x", "X"];
|
||||
|
||||
export type ItemObject = ObjectValue<
|
||||
{
|
||||
@@ -35,14 +42,18 @@ export async function indexItems(
|
||||
frontmatter: FrontMatter,
|
||||
tree: ParseTree,
|
||||
) {
|
||||
const shouldIndexAll = await system.getConfig(
|
||||
const shouldIndexAllItems = await system.getConfig(
|
||||
"index.item.all",
|
||||
true,
|
||||
);
|
||||
const shouldIndexAllTasks = await system.getConfig(
|
||||
"index.task.all",
|
||||
true,
|
||||
);
|
||||
|
||||
let items: ObjectValue<ItemObject>[] = [];
|
||||
let items: ObjectValue<ItemObject | TaskObject>[] = [];
|
||||
|
||||
await traverseTreeAsync(tree, async (n) => {
|
||||
traverseTree(tree, (n) => {
|
||||
if (n.type !== "ListItem") {
|
||||
return false;
|
||||
}
|
||||
@@ -52,87 +63,84 @@ export async function indexItems(
|
||||
return true;
|
||||
}
|
||||
|
||||
// Is this a task?
|
||||
if (n.children.find((n) => n.type === "Task")) {
|
||||
// Skip tasks
|
||||
return true;
|
||||
}
|
||||
|
||||
const item: ItemObject = await extractItemFromNode(
|
||||
items.push(extractItemFromNode(
|
||||
pageMeta.name,
|
||||
n,
|
||||
frontmatter,
|
||||
);
|
||||
|
||||
items.push(item);
|
||||
));
|
||||
|
||||
// Traversal continue into child items (potentially)
|
||||
return false;
|
||||
});
|
||||
|
||||
if (!shouldIndexAll) {
|
||||
items = items.filter((item) => item.tags?.length);
|
||||
if (!shouldIndexAllItems) {
|
||||
items = items.filter((item) => item.tag !== "item" || item.tags?.length);
|
||||
}
|
||||
if (!shouldIndexAllTasks) {
|
||||
items = items.filter((item) => item.tag !== "task" || item.tags?.length);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
export async function extractItemFromNode(
|
||||
export function extractItemFromNode(
|
||||
name: string,
|
||||
itemNode: ParseTree,
|
||||
frontmatter: FrontMatter,
|
||||
withParents = true,
|
||||
) {
|
||||
const item: ItemObject = {
|
||||
): ItemObject | TaskObject {
|
||||
const item: ItemObject | TaskObject = {
|
||||
ref: `${name}@${itemNode.from}`,
|
||||
tag: "item",
|
||||
name: "",
|
||||
text: "",
|
||||
name: "", // to be replaced
|
||||
text: "", // to be replaced
|
||||
page: name,
|
||||
pos: itemNode.from!,
|
||||
};
|
||||
|
||||
// This will only be valid for items, not task
|
||||
let nameNode = itemNode.children!.find((n) => n.type === "Paragraph");
|
||||
|
||||
// Is this a task?
|
||||
const taskNode = itemNode.children!.find((n) => n.type === "Task");
|
||||
if (taskNode) {
|
||||
item.tag = "task";
|
||||
item.state = taskNode.children![0].children![1].text!;
|
||||
item.done = completeStates.includes(item.state);
|
||||
// Fake a paragraph node for text rendering later
|
||||
nameNode = { type: "Paragraph", children: taskNode.children!.slice(1) };
|
||||
}
|
||||
|
||||
// Now let's extract tags and attributes
|
||||
const tags = extractHashTags(itemNode);
|
||||
const extractedAttributes = await extractAttributes(itemNode);
|
||||
|
||||
const clonedTextNodes: ParseTree[] = [];
|
||||
const tags = collectTags(itemNode);
|
||||
const attributes = collectAttributes(itemNode);
|
||||
|
||||
for (const child of itemNode.children!.slice(1)) {
|
||||
if (child.type === "OrderedList" || child.type === "BulletList") {
|
||||
break;
|
||||
}
|
||||
clonedTextNodes.push(deepClone(child, ["parent"]));
|
||||
}
|
||||
item.text = renderToText(nameNode).trim();
|
||||
|
||||
// Original text
|
||||
item.text = clonedTextNodes.map(renderToText).join("").trim();
|
||||
|
||||
// Clean out attribtus and tags and render a clean item name
|
||||
for (const clonedTextNode of clonedTextNodes) {
|
||||
cleanHashTags(clonedTextNode);
|
||||
cleanAttributes(clonedTextNode);
|
||||
}
|
||||
|
||||
item.name = clonedTextNodes.map(renderToText).join("").trim();
|
||||
const cleanNameNode = deepClone(nameNode, ["parent"])!;
|
||||
cleanTags(cleanNameNode);
|
||||
cleanAttributes(cleanNameNode);
|
||||
item.name = renderToText(cleanNameNode).trim();
|
||||
|
||||
if (tags.length > 0) {
|
||||
item.tags = tags;
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(extractedAttributes)) {
|
||||
for (const [key, value] of Object.entries(attributes)) {
|
||||
item[key] = value;
|
||||
}
|
||||
|
||||
updateITags(item, frontmatter);
|
||||
|
||||
if (withParents) {
|
||||
await enrichItemFromParents(itemNode, item, name, frontmatter);
|
||||
enrichItemFromParents(itemNode, item, name, frontmatter);
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function enrichItemFromParents(
|
||||
export function enrichItemFromParents(
|
||||
n: ParseTree,
|
||||
item: ObjectValue<any>,
|
||||
pageName: string,
|
||||
@@ -141,7 +149,7 @@ export async function enrichItemFromParents(
|
||||
let directParent = true;
|
||||
let parentItemNode = findParentMatching(n, (n) => n.type === "ListItem");
|
||||
while (parentItemNode) {
|
||||
const parentItem = await extractItemFromNode(
|
||||
const parentItem = extractItemFromNode(
|
||||
pageName,
|
||||
parentItemNode,
|
||||
frontmatter,
|
||||
|
||||
+12
-9
@@ -1,7 +1,8 @@
|
||||
import { lua, YAML } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import { lua } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import {
|
||||
findNodeOfType,
|
||||
renderToText,
|
||||
traverseTree,
|
||||
traverseTreeAsync,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import type {
|
||||
@@ -9,13 +10,15 @@ import type {
|
||||
LintEvent,
|
||||
} from "@silverbulletmd/silverbullet/type/client";
|
||||
|
||||
export async function lintYAML(
|
||||
import YAML from "js-yaml";
|
||||
|
||||
export function lintYAML(
|
||||
{ tree, name }: LintEvent,
|
||||
): Promise<LintDiagnostic[]> {
|
||||
): LintDiagnostic[] {
|
||||
const diagnostics: LintDiagnostic[] = [];
|
||||
await traverseTreeAsync(tree, async (node) => {
|
||||
traverseTree(tree, (node) => {
|
||||
if (node.type === "FrontMatterCode") {
|
||||
const lintResult = await lintYaml(
|
||||
const lintResult = lintYaml(
|
||||
renderToText(node),
|
||||
node.from!,
|
||||
name,
|
||||
@@ -40,7 +43,7 @@ export async function lintYAML(
|
||||
return true;
|
||||
}
|
||||
const yamlCode = renderToText(codeText);
|
||||
const lintResult = await lintYaml(
|
||||
const lintResult = lintYaml(
|
||||
yamlCode,
|
||||
codeText.from!,
|
||||
);
|
||||
@@ -57,13 +60,13 @@ export async function lintYAML(
|
||||
|
||||
const errorRegex = /\((\d+):(\d+)\)/;
|
||||
|
||||
async function lintYaml(
|
||||
function lintYaml(
|
||||
yamlText: string,
|
||||
startPos: number,
|
||||
pageName?: string,
|
||||
): Promise<LintDiagnostic | undefined> {
|
||||
): LintDiagnostic | undefined {
|
||||
try {
|
||||
const parsed = await YAML.parse(yamlText);
|
||||
const parsed = YAML.load(yamlText);
|
||||
if (pageName && parsed.name && parsed.name != pageName) {
|
||||
return {
|
||||
from: startPos,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { parseMarkdown } from "../../client/markdown_parser/parser.ts";
|
||||
import { createMockSystem } from "../../plug-api/system_mock.ts";
|
||||
import type { PageMeta } from "@silverbulletmd/silverbullet/type/index";
|
||||
import { indexPage } from "./page.ts";
|
||||
import { extractFrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { extractFrontMatter } from "./frontmatter.ts";
|
||||
import { assertEquals } from "@std/assert";
|
||||
|
||||
const testPage = `
|
||||
@@ -18,8 +18,7 @@ hello: attribute
|
||||
Deno.test("Test page indexer", async () => {
|
||||
createMockSystem();
|
||||
const tree = parseMarkdown(testPage);
|
||||
|
||||
const frontmatter = await extractFrontMatter(tree);
|
||||
const frontmatter = extractFrontMatter(tree);
|
||||
|
||||
const pageMeta: PageMeta = {
|
||||
ref: "test",
|
||||
|
||||
+6
-9
@@ -1,11 +1,6 @@
|
||||
import {
|
||||
editor,
|
||||
lua,
|
||||
markdown,
|
||||
YAML,
|
||||
} from "@silverbulletmd/silverbullet/syscalls";
|
||||
import { editor, lua, markdown } from "@silverbulletmd/silverbullet/syscalls";
|
||||
|
||||
import type { FrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import type { FrontMatter } from "./frontmatter.ts";
|
||||
import { deleteObject, getObjectByRef, queryLuaObjects } from "./api.ts";
|
||||
import {
|
||||
findNodeOfType,
|
||||
@@ -13,11 +8,13 @@ import {
|
||||
renderToText,
|
||||
traverseTreeAsync,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import { updateITags } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import { updateITags } from "./tags.ts";
|
||||
import type { AspiringPageObject } from "./page_links.ts";
|
||||
import type { PageMeta } from "@silverbulletmd/silverbullet/type/index";
|
||||
import type { LintDiagnostic } from "@silverbulletmd/silverbullet/type/client";
|
||||
|
||||
import YAML from "js-yaml";
|
||||
|
||||
export async function indexPage(
|
||||
pageMeta: PageMeta,
|
||||
frontmatter: FrontMatter,
|
||||
@@ -122,7 +119,7 @@ async function lintYaml(
|
||||
to: number,
|
||||
): Promise<LintDiagnostic | undefined> {
|
||||
try {
|
||||
await YAML.parse(yamlText);
|
||||
await YAML.load(yamlText);
|
||||
} catch (e: any) {
|
||||
const errorMatch = errorRegex.exec(e.message);
|
||||
if (errorMatch) {
|
||||
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
resolveMarkdownLink,
|
||||
} from "@silverbulletmd/silverbullet/lib/resolve";
|
||||
import { indexObjects, queryLuaObjects } from "./api.ts";
|
||||
import { extractFrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { updateITags } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import { extractFrontMatter } from "./frontmatter.ts";
|
||||
import { updateITags } from "./tags.ts";
|
||||
import {
|
||||
getNameFromPath,
|
||||
isMarkdownPath,
|
||||
|
||||
+16
-18
@@ -1,17 +1,15 @@
|
||||
import type { IndexTreeEvent } from "@silverbulletmd/silverbullet/type/event";
|
||||
import { indexObjects } from "./api.ts";
|
||||
import {
|
||||
collectNodesOfType,
|
||||
findParentMatching,
|
||||
renderToText,
|
||||
traverseTreeAsync,
|
||||
traverseTree,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import { extractAttributes } from "@silverbulletmd/silverbullet/lib/attribute";
|
||||
import { updateITags } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import { extractFrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import { cleanTags, collectTags, updateITags } from "./tags.ts";
|
||||
import { extractFrontMatter } from "./frontmatter.ts";
|
||||
import type { ObjectValue } from "@silverbulletmd/silverbullet/type/index";
|
||||
import { system } from "@silverbulletmd/silverbullet/syscalls";
|
||||
import { cleanAttributes, collectAttributes } from "./attribute.ts";
|
||||
|
||||
/** ParagraphObject An index object for the top level text nodes */
|
||||
export type ParagraphObject = ObjectValue<
|
||||
@@ -30,9 +28,9 @@ export async function indexParagraphs({ name: page, tree }: IndexTreeEvent) {
|
||||
|
||||
const objects: ParagraphObject[] = [];
|
||||
|
||||
const frontmatter = await extractFrontMatter(tree);
|
||||
const frontmatter = extractFrontMatter(tree);
|
||||
|
||||
await traverseTreeAsync(tree, async (p) => {
|
||||
traverseTree(tree, (p) => {
|
||||
if (p.type !== "Paragraph") {
|
||||
return false;
|
||||
}
|
||||
@@ -45,19 +43,19 @@ export async function indexParagraphs({ name: page, tree }: IndexTreeEvent) {
|
||||
const fullText = renderToText(p);
|
||||
|
||||
// Collect tags and remove from the tree
|
||||
const tags = new Set<string>();
|
||||
collectNodesOfType(p, "Hashtag").forEach((tagNode) => {
|
||||
tags.add(extractHashtag(tagNode.children![0].text!));
|
||||
// Hacky way to remove the hashtag
|
||||
tagNode.children = [];
|
||||
});
|
||||
if (tags.size === 0 && !shouldIndexAll) {
|
||||
const tags = collectTags(p);
|
||||
|
||||
if (tags.length === 0 && !shouldIndexAll) {
|
||||
// Don't index paragraphs without a hashtag
|
||||
return false;
|
||||
}
|
||||
|
||||
// Extract attributes and remove from tree
|
||||
const attrs = await extractAttributes(p);
|
||||
// Extract attributes
|
||||
const attrs = collectAttributes(p);
|
||||
|
||||
// Clean tree
|
||||
cleanTags(p);
|
||||
cleanAttributes(p);
|
||||
const text = renderToText(p);
|
||||
|
||||
if (!text.trim()) {
|
||||
@@ -74,7 +72,7 @@ export async function indexParagraphs({ name: page, tree }: IndexTreeEvent) {
|
||||
pos,
|
||||
...attrs,
|
||||
};
|
||||
if (tags.size > 0) {
|
||||
if (tags.length > 0) {
|
||||
paragraph.tags = [...tags];
|
||||
paragraph.itags = [...tags];
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
renderToText,
|
||||
replaceNodesMatching,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import {
|
||||
collectNodesMatching,
|
||||
collectNodesOfType,
|
||||
@@ -11,6 +10,7 @@ import {
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import { indexObjects } from "./api.ts";
|
||||
import type { ObjectValue } from "@silverbulletmd/silverbullet/type/index";
|
||||
import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
|
||||
type TableRowObject =
|
||||
& ObjectValue<{
|
||||
|
||||
+61
-6
@@ -1,17 +1,18 @@
|
||||
import type { IndexTreeEvent } from "@silverbulletmd/silverbullet/type/event";
|
||||
import { extractFrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import { extractFrontMatter, type FrontMatter } from "./frontmatter.ts";
|
||||
import { indexObjects, queryLuaObjects } from "./api.ts";
|
||||
import {
|
||||
addParentPointers,
|
||||
collectNodesOfType,
|
||||
findParentMatching,
|
||||
type ParseTree,
|
||||
replaceNodesMatching,
|
||||
traverseTree,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import {
|
||||
extractHashtag,
|
||||
renderHashtag,
|
||||
} from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import type { ObjectValue } from "@silverbulletmd/silverbullet/type/index";
|
||||
import type { CompleteEvent } from "@silverbulletmd/silverbullet/type/client";
|
||||
import { tagRegex } from "../../client/markdown_parser/constants.ts";
|
||||
import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags";
|
||||
|
||||
export type TagObject = ObjectValue<{
|
||||
name: string;
|
||||
@@ -22,7 +23,7 @@ export type TagObject = ObjectValue<{
|
||||
export async function indexTags({ name, tree }: IndexTreeEvent) {
|
||||
const tags = new Set<string>(); // name:parent
|
||||
addParentPointers(tree);
|
||||
const pageTags: string[] = (await extractFrontMatter(tree)).tags || [];
|
||||
const pageTags: string[] = extractFrontMatter(tree).tags || [];
|
||||
for (const pageTag of pageTags) {
|
||||
tags.add(`${pageTag}:page`);
|
||||
}
|
||||
@@ -87,3 +88,57 @@ export async function tagComplete(completeEvent: CompleteEvent) {
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function updateITags<T>(obj: ObjectValue<T>, frontmatter: FrontMatter) {
|
||||
const itags = new Set<string>([obj.tag, ...frontmatter.tags || []]);
|
||||
for (const tag of obj.tags || []) {
|
||||
itags.add(tag);
|
||||
}
|
||||
for (const tag of obj.itags || []) {
|
||||
itags.add(tag);
|
||||
}
|
||||
obj.itags = [...itags];
|
||||
}
|
||||
|
||||
/** Get markup for a hashtag name with # prefix and angle brackets if necessary */
|
||||
export function renderHashtag(name: string): string {
|
||||
// detect with the same regex as the parser
|
||||
const simple: string = "#" + name;
|
||||
const match = simple.match(tagRegex);
|
||||
if (!match || match[0].length !== simple.length) {
|
||||
return `#<${name}>`;
|
||||
} else return simple;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans hashtags from a tree as a side effect
|
||||
* @param n
|
||||
* @return found hashtags
|
||||
*/
|
||||
export function collectTags(n: ParseTree): string[] {
|
||||
const tags = new Set<string>();
|
||||
traverseTree(n, (n) => {
|
||||
if (n.type === "Hashtag") {
|
||||
tags.add(extractHashtag(n.children![0].text!));
|
||||
return true;
|
||||
} else if (n.type === "OrderedList" || n.type === "BulletList") {
|
||||
// Don't traverse into sub-lists
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return [...tags];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans hashtags from a tree as a side effect
|
||||
* @param n
|
||||
*/
|
||||
export function cleanTags(n: ParseTree) {
|
||||
return replaceNodesMatching(n, (n) => {
|
||||
if (n.type === "Hashtag") {
|
||||
return null;
|
||||
}
|
||||
return;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import type { IndexTreeEvent } from "@silverbulletmd/silverbullet/type/event";
|
||||
|
||||
import {
|
||||
config,
|
||||
editor,
|
||||
events,
|
||||
markdown,
|
||||
space,
|
||||
sync,
|
||||
system,
|
||||
} from "@silverbulletmd/silverbullet/syscalls";
|
||||
|
||||
import {
|
||||
@@ -18,159 +16,18 @@ import {
|
||||
nodeAtPos,
|
||||
type ParseTree,
|
||||
renderToText,
|
||||
replaceNodesMatching,
|
||||
traverseTreeAsync,
|
||||
} from "@silverbulletmd/silverbullet/lib/tree";
|
||||
import { niceDate } from "@silverbulletmd/silverbullet/lib/dates";
|
||||
import {
|
||||
cleanAttributes,
|
||||
extractAttributes,
|
||||
} from "@silverbulletmd/silverbullet/lib/attribute";
|
||||
import { indexObjects } from "../index/api.ts";
|
||||
import {
|
||||
cleanHashTags,
|
||||
extractHashTags,
|
||||
updateITags,
|
||||
} from "@silverbulletmd/silverbullet/lib/tags";
|
||||
import { extractFrontMatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
|
||||
import {
|
||||
getNameFromPath,
|
||||
getOffsetFromLineColumn,
|
||||
isMarkdownPath,
|
||||
parseToRef,
|
||||
} from "@silverbulletmd/silverbullet/lib/ref";
|
||||
import { enrichItemFromParents } from "../index/item.ts";
|
||||
import { deepClone } from "@silverbulletmd/silverbullet/lib/json";
|
||||
import { queryLuaObjects } from "../index/api.ts";
|
||||
import type { ObjectValue } from "@silverbulletmd/silverbullet/type/index";
|
||||
import type { ClickEvent } from "@silverbulletmd/silverbullet/type/client";
|
||||
|
||||
export type TaskObject = ObjectValue<
|
||||
{
|
||||
page: string;
|
||||
pos: number;
|
||||
name: string;
|
||||
text: string;
|
||||
done: boolean;
|
||||
state: string;
|
||||
deadline?: string;
|
||||
} & Record<string, any>
|
||||
>;
|
||||
export const completeStates = ["x", "X"];
|
||||
|
||||
export type TaskStateObject = ObjectValue<{
|
||||
state: string;
|
||||
count: number;
|
||||
page: string;
|
||||
}>;
|
||||
|
||||
function getDeadline(deadlineNode: ParseTree): string {
|
||||
return deadlineNode.children![0].text!.replace(/📅\s*/, "");
|
||||
}
|
||||
|
||||
const completeStates = ["x", "X"];
|
||||
const incompleteStates = [" "];
|
||||
|
||||
export async function extractTasks(
|
||||
name: string,
|
||||
tree: ParseTree,
|
||||
): Promise<TaskObject[]> {
|
||||
const tasks: ObjectValue<TaskObject>[] = [];
|
||||
const taskStates = new Map<string, { count: number; firstPos: number }>();
|
||||
const frontmatter = await extractFrontMatter(tree);
|
||||
|
||||
await traverseTreeAsync(tree, async (n) => {
|
||||
if (n.type !== "Task") {
|
||||
return false;
|
||||
}
|
||||
const listItemNode = n.parent!;
|
||||
const state = n.children![0].children![1].text!;
|
||||
if (!incompleteStates.includes(state) && !completeStates.includes(state)) {
|
||||
let currentState = taskStates.get(state);
|
||||
if (!currentState) {
|
||||
currentState = { count: 0, firstPos: n.from! };
|
||||
taskStates.set(state, currentState);
|
||||
}
|
||||
currentState.count++;
|
||||
}
|
||||
const complete = completeStates.includes(state);
|
||||
|
||||
const task: TaskObject = {
|
||||
ref: `${name}@${n.from}`,
|
||||
tag: "task",
|
||||
name: "",
|
||||
text: "",
|
||||
done: complete,
|
||||
page: name,
|
||||
pos: n.from!,
|
||||
state,
|
||||
};
|
||||
|
||||
// The task text is everything after the task marker
|
||||
task.text = n.children!.slice(1).map(renderToText).join("").trim();
|
||||
|
||||
// This finds the deadline and tags, and removes them from the tree
|
||||
replaceNodesMatching(n, (tree) => {
|
||||
if (tree.type === "DeadlineDate") {
|
||||
task.deadline = getDeadline(tree);
|
||||
// Remove this node from the tree
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
// Extract tags and attributes
|
||||
task.tags = extractHashTags(n);
|
||||
const extractedAttributes = await extractAttributes(n);
|
||||
|
||||
// Then clean them out
|
||||
const clonedNode = deepClone(n, ["parent"]);
|
||||
cleanHashTags(clonedNode);
|
||||
cleanAttributes(clonedNode);
|
||||
task.name = clonedNode.children!.slice(1).map(renderToText).join("").trim();
|
||||
|
||||
for (const [key, value] of Object.entries(extractedAttributes)) {
|
||||
task[key] = value;
|
||||
}
|
||||
|
||||
updateITags(task, frontmatter);
|
||||
await enrichItemFromParents(listItemNode, task, name, frontmatter);
|
||||
|
||||
tasks.push(task);
|
||||
return true;
|
||||
});
|
||||
|
||||
// Index task states
|
||||
if (taskStates.size > 0) {
|
||||
await indexObjects<TaskStateObject>(
|
||||
name,
|
||||
Array.from(taskStates.entries()).map(([state, { firstPos, count }]) => ({
|
||||
ref: `${name}@${firstPos}`,
|
||||
tag: "taskstate",
|
||||
state,
|
||||
count,
|
||||
page: name,
|
||||
})),
|
||||
);
|
||||
}
|
||||
return tasks;
|
||||
}
|
||||
|
||||
export async function indexTasks({ name, tree }: IndexTreeEvent) {
|
||||
const shouldIndexAll = await system.getConfig(
|
||||
"index.task.all",
|
||||
true,
|
||||
);
|
||||
|
||||
let extractedTasks = await extractTasks(name, tree);
|
||||
|
||||
if (!shouldIndexAll) {
|
||||
extractedTasks = extractedTasks.filter((task) => task.tags?.length);
|
||||
}
|
||||
|
||||
// Index tasks themselves
|
||||
if (extractTasks.length > 0) {
|
||||
await indexObjects(name, extractedTasks);
|
||||
}
|
||||
}
|
||||
export const incompleteStates = [" "];
|
||||
|
||||
export function taskToggle(event: ClickEvent) {
|
||||
if (event.altKey) {
|
||||
@@ -179,13 +36,6 @@ export function taskToggle(event: ClickEvent) {
|
||||
return taskCycleAtPos(event.pos);
|
||||
}
|
||||
|
||||
export function previewTaskToggle(eventString: string) {
|
||||
const [eventName, pos] = JSON.parse(eventString);
|
||||
if (eventName === "task") {
|
||||
return taskCycleAtPos(+pos);
|
||||
}
|
||||
}
|
||||
|
||||
async function convertListItemToTask(node: ParseTree) {
|
||||
const listMark = node.children![0];
|
||||
const originalMark = renderToText(listMark);
|
||||
@@ -254,23 +104,18 @@ async function cycleTaskState(
|
||||
changeTo = "x";
|
||||
} else {
|
||||
// Not a checkbox, but a custom state
|
||||
const allStates = await queryLuaObjects<TaskStateObject>(
|
||||
"taskstate",
|
||||
{},
|
||||
{},
|
||||
);
|
||||
const states = [...new Set(allStates.map((s) => s.state))];
|
||||
const allStates = await config.get("taskStates", {});
|
||||
const states = Object.keys(allStates);
|
||||
console.log("All states", states);
|
||||
states.sort();
|
||||
// Select a next state
|
||||
const currentStateIndex = states.indexOf(stateText);
|
||||
let currentStateIndex = states.indexOf(stateText);
|
||||
if (currentStateIndex === -1) {
|
||||
console.error("Unknown state", stateText);
|
||||
return;
|
||||
currentStateIndex = 0;
|
||||
}
|
||||
const nextStateIndex = (currentStateIndex + 1) % states.length;
|
||||
changeTo = states[nextStateIndex];
|
||||
// console.log("All possible states", states);
|
||||
// return;
|
||||
}
|
||||
await editor.dispatch({
|
||||
changes: {
|
||||
@@ -329,8 +174,8 @@ export async function updateTaskState(
|
||||
|
||||
// Check if the task state marker is still there
|
||||
const targetText = editorText.substring(
|
||||
targetPos + 1,
|
||||
targetPos + 1 + oldState.length,
|
||||
targetPos + 3, // 3 because: "* ["
|
||||
targetPos + 3 + oldState.length,
|
||||
);
|
||||
if (targetText !== oldState) {
|
||||
console.error(
|
||||
@@ -341,8 +186,8 @@ export async function updateTaskState(
|
||||
}
|
||||
await editor.dispatch({
|
||||
changes: {
|
||||
from: targetPos + 1,
|
||||
to: targetPos + 1 + oldState.length,
|
||||
from: targetPos + 3,
|
||||
to: targetPos + 3 + oldState.length,
|
||||
insert: newState,
|
||||
},
|
||||
});
|
||||
@@ -359,11 +204,18 @@ export async function updateTaskState(
|
||||
ref.details.column,
|
||||
);
|
||||
|
||||
// Adding +1 to immediately hit the task state node
|
||||
const taskStateNode = nodeAtPos(referenceMdTree, targetPos + 1);
|
||||
if (!taskStateNode || taskStateNode.type !== "TaskState") {
|
||||
const itemNode = nodeAtPos(referenceMdTree, targetPos + 1);
|
||||
if (!itemNode) {
|
||||
console.error(
|
||||
"Reference not a task marker, out of date?",
|
||||
"Reference not a valid item, out of date?",
|
||||
itemNode,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const taskStateNode = findNodeOfType(itemNode, "TaskState");
|
||||
if (!taskStateNode) {
|
||||
console.error(
|
||||
"Cannot find a task state",
|
||||
taskStateNode,
|
||||
);
|
||||
return;
|
||||
@@ -410,7 +262,6 @@ export async function taskCycleCommand() {
|
||||
await editor.flashNotification("No task at cursor");
|
||||
return;
|
||||
}
|
||||
console.log("Node", node);
|
||||
const taskNode = node.type === "Task"
|
||||
? node
|
||||
: findParentMatching(node!, (n) => n.type === "Task");
|
||||
@@ -444,66 +295,21 @@ export async function taskCycleCommand() {
|
||||
convertListItemToTask(listItem);
|
||||
}
|
||||
|
||||
export async function postponeCommand() {
|
||||
const text = await editor.getText();
|
||||
const pos = await editor.getCursor();
|
||||
const tree = await markdown.parseMarkdown(text);
|
||||
addParentPointers(tree);
|
||||
|
||||
const node = nodeAtPos(tree, pos)!;
|
||||
// We kwow node.type === DeadlineDate (due to the task context)
|
||||
const date = getDeadline(node);
|
||||
const option = await editor.filterBox(
|
||||
"Postpone for...",
|
||||
[
|
||||
{ name: "a day", orderId: 1 },
|
||||
{ name: "a week", orderId: 2 },
|
||||
{ name: "following Monday", orderId: 3 },
|
||||
],
|
||||
"Select the desired time span to delay this task",
|
||||
);
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
// Parse "naive" due date
|
||||
const [yyyy, mm, dd] = date.split("-").map(Number);
|
||||
// Create new naive Date object.
|
||||
// `monthIndex` parameter is zero-based, so subtract 1 from parsed month.
|
||||
const d = new Date(yyyy, mm - 1, dd);
|
||||
switch (option.name) {
|
||||
case "a day":
|
||||
d.setDate(d.getDate() + 1);
|
||||
break;
|
||||
case "a week":
|
||||
d.setDate(d.getDate() + 7);
|
||||
break;
|
||||
case "following Monday":
|
||||
d.setDate(d.getDate() + ((7 - d.getDay() + 1) % 7 || 7));
|
||||
break;
|
||||
}
|
||||
// console.log("New date", niceDate(d));
|
||||
await editor.dispatch({
|
||||
changes: {
|
||||
from: node.from,
|
||||
to: node.to,
|
||||
insert: `📅 ${niceDate(d)}`,
|
||||
},
|
||||
selection: {
|
||||
anchor: pos,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeCompletedTasksCommand() {
|
||||
const tree = await markdown.parseMarkdown(await editor.getText());
|
||||
addParentPointers(tree);
|
||||
|
||||
// Taking this ugly approach because the tree is modified in place
|
||||
// Just finding and removing one task at a time and then repeating until nothing changes
|
||||
const allCompletedStates = completeStates.concat(
|
||||
Object.values(await config.get("taskStates", {})).filter((ts: any) =>
|
||||
ts.done
|
||||
).map((ts: any) => ts.name),
|
||||
);
|
||||
while (true) {
|
||||
const completedTaskNode = findNodeMatching(tree, (node) => {
|
||||
return node.type === "Task" &&
|
||||
["x", "X"].includes(node.children![0].children![1].text!);
|
||||
allCompletedStates.includes(node.children![0].children![1].text!);
|
||||
});
|
||||
if (completedTaskNode) {
|
||||
// Ok got one, let's remove it
|
||||
@@ -1,8 +1,6 @@
|
||||
import type { SysCallMapping } from "../system.ts";
|
||||
import YAML from "js-yaml";
|
||||
import { applyPatches, type YamlPatch } from "../../../plug-api/lib/yaml.ts";
|
||||
|
||||
type YamlStringifyOptions = {
|
||||
export type YamlStringifyOptions = {
|
||||
/** indentation width to use (in spaces). */
|
||||
indent?: number;
|
||||
/** when true, will not add an indentation level to array elements */
|
||||
@@ -30,28 +28,17 @@ type YamlStringifyOptions = {
|
||||
forceQuotes?: boolean;
|
||||
};
|
||||
|
||||
export function yamlSyscalls(): SysCallMapping {
|
||||
return {
|
||||
"yaml.parse": (_ctx, text: string): any => {
|
||||
return YAML.load(text);
|
||||
},
|
||||
"yaml.stringify": (
|
||||
_ctx,
|
||||
obj: any,
|
||||
options: YamlStringifyOptions = {},
|
||||
): string => {
|
||||
return YAML.dump(obj, {
|
||||
quotingType: '"',
|
||||
noCompatMode: true,
|
||||
...options,
|
||||
});
|
||||
},
|
||||
"yaml.patch": (
|
||||
_ctx,
|
||||
yaml: string,
|
||||
patches: YamlPatch[],
|
||||
): string => {
|
||||
return applyPatches(yaml, patches);
|
||||
},
|
||||
};
|
||||
export function parse(text: string): any {
|
||||
return YAML.load(text);
|
||||
}
|
||||
|
||||
export function stringify(
|
||||
text: string,
|
||||
options: YamlStringifyOptions = {},
|
||||
): any {
|
||||
return YAML.dump(text, {
|
||||
quotingType: '"',
|
||||
noCompatMode: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import "../../plug-api/lib/syscall_mock.ts";
|
||||
import { parseMarkdown } from "../../client/markdown_parser/parser.ts";
|
||||
import { extractTasks } from "./task.ts";
|
||||
import { assertEquals } from "@std/assert";
|
||||
|
||||
const itemsMd = `
|
||||
* Item 1 #tag1 #tag2 [age: 100]
|
||||
* [ ] Task 1 [age: 200]
|
||||
* [ ] Task 2 #tag3 #tag1
|
||||
* [x] Task 2.1
|
||||
`;
|
||||
|
||||
Deno.test("Test task extraction", async () => {
|
||||
const t = parseMarkdown(itemsMd);
|
||||
const tasks = await extractTasks("test", t);
|
||||
|
||||
assertEquals(tasks.length, 3);
|
||||
assertEquals(tasks[0].name, "Task 1");
|
||||
assertEquals(tasks[0].age, 200);
|
||||
assertEquals(tasks[0].page, "test");
|
||||
assertEquals(tasks[0].text, "Task 1 [age: 200]");
|
||||
assertEquals(new Set(tasks[0].itags), new Set(["tag1", "tag2", "task"]));
|
||||
assertEquals(tasks[0].parent, "test@1");
|
||||
assertEquals(tasks[1].name, "Task 2");
|
||||
// Don't inherit attributes
|
||||
assertEquals(tasks[1].age, undefined);
|
||||
// But inherit tags through itags, not tags
|
||||
assertEquals(
|
||||
new Set(tasks[1].tags),
|
||||
new Set(["tag1", "tag3"]),
|
||||
);
|
||||
assertEquals(
|
||||
new Set(tasks[1].itags),
|
||||
new Set(["tag1", "tag3", "task", "tag2"]),
|
||||
);
|
||||
assertEquals(tasks[1].parent, "test@1");
|
||||
// Deeply
|
||||
assertEquals(tasks[2].name, "Task 2.1");
|
||||
assertEquals(tasks[2].tags, []);
|
||||
assertEquals(
|
||||
new Set(tasks[2].itags),
|
||||
new Set(["tag1", "tag3", "task", "tag2"]),
|
||||
);
|
||||
});
|
||||
@@ -1,107 +0,0 @@
|
||||
name: tasks
|
||||
functions:
|
||||
# API
|
||||
updateTaskState:
|
||||
path: task.ts:updateTaskState
|
||||
|
||||
indexTasks:
|
||||
path: "./task.ts:indexTasks"
|
||||
events:
|
||||
- page:index
|
||||
taskToggle:
|
||||
path: "./task.ts:taskToggle"
|
||||
events:
|
||||
- page:click
|
||||
taskToggleCommand:
|
||||
path: ./task.ts:taskCycleCommand
|
||||
command:
|
||||
name: "Task: Cycle State"
|
||||
key: Alt-t
|
||||
requireMode: rw
|
||||
requireEditor: page
|
||||
taskPostponeCommand:
|
||||
path: ./task.ts:postponeCommand
|
||||
command:
|
||||
name: "Task: Postpone"
|
||||
key: Alt-+
|
||||
requireMode: rw
|
||||
requireEditor: page
|
||||
contexts:
|
||||
- DeadlineDate
|
||||
previewTaskToggle:
|
||||
path: ./task.ts:previewTaskToggle
|
||||
events:
|
||||
- preview:click
|
||||
|
||||
taskComplete:
|
||||
path: ./complete.ts:completeTaskState
|
||||
events:
|
||||
- editor:complete
|
||||
|
||||
removeCompletedTasksCommand:
|
||||
path: task.ts:removeCompletedTasksCommand
|
||||
command:
|
||||
name: "Task: Remove Completed"
|
||||
requireMode: rw
|
||||
requireEditor: page
|
||||
|
||||
config:
|
||||
schema.tag:
|
||||
task:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
properties:
|
||||
ref:
|
||||
type: string
|
||||
readOnly: true
|
||||
tag:
|
||||
type: string
|
||||
tags:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
nullable: true
|
||||
itags:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
nullable: true
|
||||
name:
|
||||
type: string
|
||||
page:
|
||||
type: string
|
||||
parent:
|
||||
type: string
|
||||
pos:
|
||||
type: number
|
||||
text:
|
||||
type: string
|
||||
state:
|
||||
type: string
|
||||
done:
|
||||
type: boolean
|
||||
deadline:
|
||||
type: string
|
||||
nullable: true
|
||||
taskstate:
|
||||
type: object
|
||||
properties:
|
||||
ref:
|
||||
type: string
|
||||
readOnly: true
|
||||
tag:
|
||||
type: string
|
||||
tags:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
nullable: true
|
||||
itags:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
nullable: true
|
||||
state:
|
||||
type: string
|
||||
count:
|
||||
type: number
|
||||
@@ -3,7 +3,10 @@ An attempt at documenting the changes/new features introduced in each release.
|
||||
## Edge
|
||||
Whenever a commit is pushed to the `main` branch, within ~10 minutes, it will be released as a docker image with the `:v2` tag, and a binary in the [edge release](https://github.com/silverbulletmd/silverbullet/releases/tag/edge). If you want to live on the bleeding edge of SilverBullet goodness (or regression) this is where to do it.
|
||||
|
||||
* **Removed** full-text search plug from the main distribution, this has now been moved to [a separate repo](https://github.com/silverbulletmd/basic-search) (installable via the library manager). This dramatically improves indexing speed. But actually: install [Silversearch](https://github.com/MrMugame/silversearch) instead.
|
||||
* Removed full-text search plug from the main distribution, this has now been moved to [a separate repo](https://github.com/silverbulletmd/basic-search) (installable via the library manager). This dramatically improves indexing speed. But actually: install [Silversearch](https://github.com/MrMugame/silversearch) instead.
|
||||
* Indexer refactor:
|
||||
* For consistency with items, `task` `refs` now point to the item’s position resulting in a slight positional shift, if you have code relying on this, you may have to adjust it
|
||||
*
|
||||
* Disabled indexing all paragraph text (even those not tagged) by default, this caused significant indexing overhead. [See discussion](https://community.silverbullet.md/t/who-is-using-paragraph-for-queries/3686).
|
||||
* To re-enable: `config.set("index.paragraph.all", true)`
|
||||
* Production builds now include sourcemaps for easier debugging in browser DevTools. If you don't want to serve sourcemaps publicly, you can block `*.js.map` files at your reverse proxy level (see [[TLS#Blocking sourcemaps]]).
|
||||
@@ -73,7 +76,6 @@ This is a dot release primarily because due to changes in how IndexedDB database
|
||||
## 2.1.8
|
||||
* New [[^Library/Std/APIs/Virtual Page]] API, internally used by:
|
||||
* [[^Library/Std/Infrastructure/Tag Page]]
|
||||
* [[^Library/Std/Infrastructure/Search]]
|
||||
* Some fixes in `tonumber` handling
|
||||
* Default table renderer now renders `ref` attributes as links, so they’re clickable:
|
||||
${query[[from index.tag "page" limit 3 select {ref=ref, lastModified=lastModified}]]}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
> **warning** Warning
|
||||
> Client encryption is a beta feature, its implementation may still evolve.
|
||||
#maturity/beta
|
||||
|
||||
By default SilverBullet keeps a copy of all your files as well as the index, unencrypted in your browser’s IndexedDB. As long as you control your device and other people do not have access to it, this should be perfectly safe. Browsers do not allow access to these databases from other websites and domains.
|
||||
|
||||
@@ -24,4 +23,4 @@ On the client, all of SilverBullet’s local data storage is built on a small ke
|
||||
|
||||
A strong 256-bit cryptographic key is derived (using _PBKDF2_) on the client from your username/password combo entered upon login. This key is kept in the service worker for SilverBullet clients to obtain so that the user is not required to constant log in when refreshing a tab, or opening new SilverBullet tabs and windows.
|
||||
|
||||
Since we need deterministic and stable encryption for data store keys, we use _AES-CTR_ with a fixed counter. For values we use _AES-GCM_ with randomized ivs.
|
||||
Since we need deterministic and stable encryption for data store keys, we use _AES-CTR_ with a fixed counter. For values we use _AES-GCM_ with randomized ivs.
|
||||
|
||||
@@ -91,15 +91,6 @@ ${template.each(query[[from index.tag "upnext"]], templates.taskItem)}
|
||||
|
||||
Similar to [[#item]], `task` objects have a `parent` attribute when nested (pointing to their parent `item`), and inherit their ancestor’s tags in `itags`.
|
||||
|
||||
## taskstate
|
||||
[[Task]] support the default `x` and ` ` states (done and not done), but custom states as well. Custom states used across your space are kept in `taskstate`:
|
||||
|
||||
* [NOT STARTED] Task 1
|
||||
* [IN PROGRESS] Task 2
|
||||
|
||||
And can be queried as follows:
|
||||
${query[[from index.tag "taskstate" where page == _CTX.currentPage.name]]}
|
||||
|
||||
## paragraph
|
||||
Top-level paragraphs (that is: paragraphs not embedded in a list) are indexed using the `paragraph` tag, any additional tags can be added using [[Tags]].
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
tags: maturity/beta
|
||||
pageDecoration:
|
||||
prefix: "🎄 "
|
||||
disableTOC: true
|
||||
@@ -6,9 +7,6 @@ pageDecoration:
|
||||
- christmas-decoration
|
||||
---
|
||||
Page decorations allow you to “decorate” pages in various fun ways.
|
||||
|
||||
> **warning** Warning
|
||||
> This feature is still experimental and may change in the (near) future.
|
||||
|
||||
# Supported decorations
|
||||
* `prefix`: A (visual) string prefix (often an emoji) to add to all page names. This prefix will appear in the top bar as well as in (live preview) links to this page. For example, the name of this page is actually “Page Decorations”, but when you link to it, you’ll see it’s prefixed with a 🎄: [[Page Decorations]]
|
||||
|
||||
+3
-1
@@ -9,7 +9,7 @@ which renders as follows:
|
||||
* [ ] This is my first task
|
||||
|
||||
# Custom states
|
||||
Tasks support the default `x` and ` ` states (done and not done), but custom states as well. Custom states used across your space are kept in [[Object#taskstate]].
|
||||
Tasks support the default `x` and ` ` states (done and not done), but custom states as well. Support for this is still very basic, however.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -21,6 +21,8 @@ Restrictions:
|
||||
|
||||
* Task states cannot contain `:` to avoid ambiguity with [[Attribute]] syntax.
|
||||
|
||||
It is advisable to explicitly define custom task state using the [[Library/Std/APIs/Task State#taskState.define(def)]] API, this will enable cycling through the task states by clicking on them.
|
||||
|
||||
# Querying
|
||||
SilverBullet allows you to simply toggle the complete state of a task by clicking the checkbox. It also allows for querying tasks as [[Object#task]]. For instance:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user