refactor(react): add type safety for note relations

This commit is contained in:
Elian Doran 2025-09-14 10:22:20 +03:00
parent b8e4947adb
commit 3ac0dfb2ad
No known key found for this signature in database
2 changed files with 15 additions and 2 deletions

View File

@ -2,7 +2,7 @@ import { Inputs, MutableRef, useCallback, useContext, useDebugValue, useEffect,
import { CommandListenerData, EventData, EventNames } from "../../components/app_context";
import { ParentComponent } from "./react_utils";
import SpacedUpdate from "../../services/spaced_update";
import { FilterLabelsByType, KeyboardActionNames, OptionNames } from "@triliumnext/commons";
import { FilterLabelsByType, KeyboardActionNames, OptionNames, RelationNames } from "@triliumnext/commons";
import options, { type OptionValue } from "../../services/options";
import utils, { escapeRegExp, reloadFrontendApp } from "../../services/utils";
import NoteContext from "../../components/note_context";
@ -258,7 +258,7 @@ export function useNoteProperty<T extends keyof FNote>(note: FNote | null | unde
return note?.[property];
}
export function useNoteRelation(note: FNote | undefined | null, relationName: string): [string | null | undefined, (newValue: string) => void] {
export function useNoteRelation(note: FNote | undefined | null, relationName: RelationNames): [string | null | undefined, (newValue: string) => void] {
const [ relationValue, setRelationValue ] = useState<string | null | undefined>(note?.getRelationValue(relationName));
useEffect(() => setRelationValue(note?.getRelationValue(relationName) ?? null), [ note ]);

View File

@ -1,3 +1,6 @@
/**
* A listing of all the labels used by the system (i.e. not user-defined). Labels defined here have a data type which is not enforced, but offers type safety.
*/
type Labels = {
color: string;
iconClass: string;
@ -38,7 +41,17 @@ type Labels = {
includeArchived: boolean;
}
/**
* A listing of all relations used by the system (i.e. not user-defined). Unlike labels, relations
* always point to a note ID, so no specific data type is necessary.
*/
type Relations = [
"searchScript",
"ancestor"
];
export type LabelNames = keyof Labels;
export type RelationNames = Relations[number];
export type FilterLabelsByType<U> = {
[K in keyof Labels]: Labels[K] extends U ? K : never;