Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
import "./AttributeEditor.css";
import type { AttributeEditor as CKEditorAttributeEditor, EditorConfig, ModelElement, ModelNode, ModelPosition, MentionHostedFeed } from "@triliumnext/ckeditor5";
import { AttributeType } from "@triliumnext/commons";
import clsx from "clsx";
import { createPortal, RefObject } from "preact";
import { useEffect, useImperativeHandle, useMemo, useRef, useState } from "preact/hooks";
import type { CommandData, FilteredCommandNames } from "../../components/app_context";
import FAttribute from "../../entities/fattribute";
import FNote from "../../entities/fnote";
import contextMenu from "../../menus/context_menu";
import { getPreprocessedData } from "../../services/attribute_clipboard";
import attribute_parser, { Attribute } from "../../services/attribute_parser";
import attribute_renderer from "../../services/attribute_renderer";
import attributes from "../../services/attributes";
import froca from "../../services/froca";
import { t } from "../../services/i18n";
import link from "../../services/link";
import server from "../../services/server";
import { isIMEComposing } from "../../services/shortcuts";
import { escapeQuotes, getErrorMessage } from "../../services/utils";
import ActionButton from "../react/ActionButton";
import CKEditor, { CKEditorApi } from "../react/CKEditor";
import { useLegacyWidget, useTriliumEvent } from "../react/hooks";
import { createAutocompleteMentionList, createNoteMentionList } from "../type_widgets/text/mention_list_view";
import AttributeDetailWidget, { AttributeNameSuggestion, fetchAttributeNames } from "./attribute_detail";
type AttributeCommandNames = FilteredCommandNames<CommandData>;
/**
* How long the post-save blink runs for. Matches the animation in the CSS, and only serves to take the
* class back off again — shortening it would cut the animation short.
*/
const BLINK_DURATION = 300;
interface AttributeEditorProps {
api: RefObject<AttributeEditorImperativeHandlers | null>;
note: FNote;
componentId: string;
notePath?: string | null;
ntxId?: string | null;
hidden?: boolean;
/** Runs once the editor is ready, for the shortcut that caused it to be mounted. */
initialCommand?: "addNewLabel" | "addNewRelation";
}
export interface AttributeEditorImperativeHandlers {
save(): Promise<void>;
refresh(): void;
focus(): void;
renderOwnedAttributes(ownedAttributes: FAttribute[]): Promise<void>;
}
export default function AttributeEditor({ api, note, componentId, notePath, ntxId, hidden, initialCommand }: AttributeEditorProps) {
const [ currentValue, setCurrentValue ] = useState("");
const [ error, setError ] = useState<unknown>();
const [ needsSaving, setNeedsSaving ] = useState(false);
const [ isBlinking, setIsBlinking ] = useState(false);
const [isMenuOpen, setIsMenuOpen] = useState(false);
const suppressNextOnHide = useRef(false);
const blinkTimeout = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const lastSavedContent = useRef<string | undefined>(undefined);
const currentValueRef = useRef(currentValue);
const wrapperRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<CKEditorApi | undefined>(undefined);
// The editor outlives a switch to another note, so its `@` list reads the path as it opens.
const notePathRef = useRef(notePath);
notePathRef.current = notePath;
const hostedMentions = useMemo(() => buildHostedMentions(() => notePathRef.current), []);
// The CKEditor bundle is heavy and this component mounts in always-visible containers
// (e.g. the status bar), so the editor class is loaded on demand to keep CKEditor out
// of the startup module graph.
const [ editorClass, setEditorClass ] = useState<typeof CKEditorAttributeEditor>();
useEffect(() => {
let active = true;
void import("@triliumnext/ckeditor5").then((ckeditor) => {
// Avoid a state update if the editor unmounted before the bundle finished loading.
if (active) {
setEditorClass(() => ckeditor.AttributeEditor);
}
});
return () => {
active = false;
};
}, []);
const [ attributeDetailWidgetEl, attributeDetailWidget ] = useLegacyWidget(() => new AttributeDetailWidget());
useEffect(() => () => clearTimeout(blinkTimeout.current), []);
async function renderOwnedAttributes(ownedAttributes: FAttribute[], saved: boolean) {
// attrs are not resorted if position changes after the initial load
ownedAttributes.sort((a, b) => a.position - b.position);
let htmlAttrs = (`<p>${(await attribute_renderer.renderAttributes(ownedAttributes, true)).html()}</p>`);
if (saved) {
lastSavedContent.current = htmlAttrs;
setNeedsSaving(false);
}
if (htmlAttrs.length > 0) {
htmlAttrs += " ";
}
editorRef.current?.setText(htmlAttrs);
setCurrentValue(htmlAttrs);
}
function parseAttributes() {
try {
return attribute_parser.lexAndParse(getPreprocessedData(currentValueRef.current));
} catch (e: unknown) {
setError(e);
}
}
async function save() {
const attributes = parseAttributes();
if (!attributes || !needsSaving) {
// An error occurred and will be reported to the user, or nothing to save.
return;
}
await server.put(`notes/${note.noteId}/attributes`, attributes, componentId);
setNeedsSaving(false);
// blink the attribute text to give a visual hint that save has been executed
setIsBlinking(true);
clearTimeout(blinkTimeout.current);
blinkTimeout.current = setTimeout(() => setIsBlinking(false), BLINK_DURATION);
}
async function handleAddNewAttributeCommand(command: AttributeCommandNames | undefined) {
// TODO: Not sure what the relation between FAttribute[] and Attribute[] is.
const attrs = parseAttributes() as FAttribute[];
if (!attrs) {
return;
}
let type: AttributeType;
let name;
let value;
if (command === "addNewLabel") {
type = "label";
name = "myLabel";
value = "";
} else if (command === "addNewRelation") {
type = "relation";
name = "myRelation";
value = "";
} else if (command === "addNewLabelDefinition") {
type = "label";
name = "label:myLabel";
value = "promoted,single,text";
} else if (command === "addNewRelationDefinition") {
type = "label";
name = "relation:myRelation";
value = "promoted,single";
} else {
return;
}
//@ts-expect-error TODO: Incomplete type
attrs.push({
type,
name,
value,
isInheritable: false
});
await renderOwnedAttributes(attrs, false);
// this.$editor.scrollTop(this.$editor[0].scrollHeight);
const rect = wrapperRef.current?.getBoundingClientRect();
attributeDetailWidget.showAttributeDetail({
allAttributes: attrs,
attribute: attrs[attrs.length - 1],
isOwned: true,
x: rect ? (rect.left + rect.right) / 2 : 0,
focus: "name",
parent: wrapperRef.current ?? undefined
});
}
// Refresh with note
function refresh() {
renderOwnedAttributes(note.getOwnedAttributes(), true);
}
useEffect(() => refresh(), [ note ]);
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
if (loadResults.getAttributeRows(componentId).find((attr) => attributes.isAffecting(attr, note))) {
refresh();
}
});
// Keyboard shortcuts
useTriliumEvent("addNewLabel", ({ ntxId: eventNtxId }) => {
if (eventNtxId !== ntxId) return;
handleAddNewAttributeCommand("addNewLabel");
});
useTriliumEvent("addNewRelation", ({ ntxId: eventNtxId }) => {
if (eventNtxId !== ntxId) return;
handleAddNewAttributeCommand("addNewRelation");
});
// Imperative API
useImperativeHandle(api, () => ({
save,
refresh,
renderOwnedAttributes: (attributes) => renderOwnedAttributes(attributes as FAttribute[], false),
focus: () => editorRef.current?.focus()
}), [ save, refresh, renderOwnedAttributes ]);
return (
<>
{!hidden && <div
className={clsx("attribute-list-editor-wrapper", isBlinking && "blink")}
ref={wrapperRef}
style="position: relative; padding-top: 10px; padding-bottom: 10px"
onKeyDown={(e) => {
// Skip processing during IME composition
if (isIMEComposing(e)) {
return;
}
if (e.key === "Enter") {
// allow autocomplete to fill the result textarea
setTimeout(() => save(), 100);
}
}}
> <div style="position: relative;">
{editorClass && <CKEditor
apiRef={editorRef}
className="attribute-list-editor"
tabIndex={200}
editor={editorClass}
currentValue={currentValue}
config={buildAttributeEditorConfig(hostedMentions)}
onChange={(currentValue) => {
currentValueRef.current = currentValue ?? "";
const oldValue = getPreprocessedData(lastSavedContent.current ?? "").trimEnd();
const newValue = getPreprocessedData(currentValue ?? "").trimEnd();
setNeedsSaving(oldValue !== newValue);
setError(undefined);
}}
onClick={(e, pos) => {
if (pos && pos.textNode && pos.textNode.data) {
const clickIndex = getClickIndex(pos);
let parsedAttrs: Attribute[];
try {
parsedAttrs = attribute_parser.lexAndParse(getPreprocessedData(currentValueRef.current), true);
} catch (e: unknown) {
// the input is incorrect because the user messed up with it and now needs to fix it manually
console.log(e);
return null;
}
let matchedAttr: Attribute | null = null;
for (const attr of parsedAttrs) {
if (attr.startIndex !== undefined && clickIndex > attr.startIndex &&
attr.endIndex !== undefined && clickIndex <= attr.endIndex) {
matchedAttr = attr;
break;
}
}
if (matchedAttr) {
attributeDetailWidget.showAttributeDetail({
allAttributes: parsedAttrs,
attribute: matchedAttr,
isOwned: true,
x: e.pageX,
parent: wrapperRef.current ?? undefined
});
} else {
// Presses inside the editor no longer dismiss the popup, so
// clicking next to an attribute has to close it explicitly.
attributeDetailWidget.hide();
}
} else {
attributeDetailWidget.hide();
}
}}
onKeyDown={() => attributeDetailWidget.hide()}
onBlur={() => save()}
onInitialized={() => {
editorRef.current?.focus();
if (initialCommand) {
void handleAddNewAttributeCommand(initialCommand);
}
}}
disableNewlines disableSpellcheck
/>}
<div className="attribute-editor-buttons">
{ needsSaving && <ActionButton
icon="bx bx-save"
className="save-attributes-button tn-tool-button"
text={escapeQuotes(t("attribute_editor.save_attributes"))}
onClick={save}
/> }
<ActionButton
icon="bx bx-plus"
className="add-new-attribute-button tn-tool-button"
text={escapeQuotes(t("attribute_editor.add_a_new_attribute"))}
onClick={(e) => {
// Prevent automatic hiding of the context menu due to the button being clicked.
e.stopPropagation();
if (isMenuOpen) {
// If we re-show the menu, ContextMenu.show() will call hide()
// and immediately trigger onHide. Suppress that transient hide.
suppressNextOnHide.current = true;
}
setIsMenuOpen(true);
contextMenu.show<AttributeCommandNames>({
x: e.pageX,
y: e.pageY,
orientation: "left",
items: [
{ title: t("attribute_editor.add_new_label"), command: "addNewLabel", uiIcon: "bx bx-hash" },
{ title: t("attribute_editor.add_new_relation"), command: "addNewRelation", uiIcon: "bx bx-transfer" },
{ kind: "separator" },
{ title: t("attribute_editor.add_new_label_definition"), command: "addNewLabelDefinition", uiIcon: "bx bx-empty" },
{ title: t("attribute_editor.add_new_relation_definition"), command: "addNewRelationDefinition", uiIcon: "bx bx-empty" }
],
selectMenuItemHandler: (item) => handleAddNewAttributeCommand(item.command),
onHide: () => {
if (suppressNextOnHide.current) {
suppressNextOnHide.current = false;
return;
}
setIsMenuOpen(false);
},
});
}}
/>
</div>
</div>
{ error && (
<div className="attribute-errors">
{getErrorMessage(error)}
</div>
)}
</div>}
{createPortal(attributeDetailWidgetEl, document.body)}
</>
);
}
/** The config of the attribute editor, which completes what is typed from `hostedMentions`. */
export function buildAttributeEditorConfig(hostedMentions: MentionHostedFeed[]): EditorConfig {
return {
toolbar: { items: [] },
placeholder: t("attribute_editor.placeholder"),
mention: { feeds: [], hostedFeeds: hostedMentions },
referenceLink: {
getTitle: link.getReferenceLinkTitle,
getTitleSync: link.getReferenceLinkTitleSync,
renderTitle: renderReferenceTitle
},
licenseKey: "GPL",
language: "en"
};
}
/** Fills `element` with the title of the note a relation's reference link points to. */
async function renderReferenceTitle(element: HTMLElement, href: string) {
const { noteId } = link.parseNavigationStateFromUrl(href);
const note = noteId ? await froca.getNote(noteId, true) : null;
element.textContent = note ? note.title : "[missing]";
}
/**
* Completes the name typed after `marker` as the attributes panel's name box completes it, from the
* same names drawn the same way, and inserts the name picked behind the marker.
*/
/**
* The lists for the markers typed in the editor. Every list opens with nothing highlighted: in this
* editor Enter means "save the attributes", so an open list must not swallow it into committing
* whichever suggestion happens to be first.
*/
function buildHostedMentions(getNotePath: () => string | null | undefined): MentionHostedFeed[] {
return [
attributeNameMention("#", "label"),
attributeNameMention("~", "relation"),
{
marker: "@",
minimumCharacters: 0,
// Relation targets are note titles, which contain spaces.
allowSpaces: true,
list: () => createNoteMentionList({ allowCreatingNotes: true, preselect: false, getParentNotePath: getNotePath })
}
];
}
function attributeNameMention(marker: "#" | "~", type: "label" | "relation"): MentionHostedFeed {
return {
marker,
minimumCharacters: 0,
list: () => createAutocompleteMentionList({
source: (query) => fetchAttributeNames(type, query),
renderItem: (name, query) => <AttributeNameSuggestion type={type} name={name} query={query} />,
toMention: (name) => ({ id: `${marker}${name}` })
})
};
}
/**
* Where the press landed in {@link getPreprocessedData}'s text, which is what the parsed attributes
* carry their offsets in: the editor's own offset counts a reference link as one node, so every
* sibling before the pressed one is measured as the text it stands for.
*/
export function getClickIndex(pos: ModelPosition) {
let clickIndex = pos.offset - (pos.textNode?.startOffset ?? 0);
let curNode: ModelNode | Text | ModelElement | null = pos.textNode;
while (curNode?.previousSibling) {
curNode = curNode.previousSibling;
if ((curNode as ModelElement).name === "reference") {
clickIndex += (curNode.getAttribute("href") as string).length + 1;
} else if ("data" in curNode) {
clickIndex += (curNode.data as string).length;
}
}
return clickIndex;
}