2025-08-22 17:31:06 +03:00
|
|
|
import { ComponentChild, createContext, render, type JSX, type RefObject } from "preact";
|
2025-08-20 21:50:06 +03:00
|
|
|
import Component from "../../components/component";
|
2025-08-25 11:48:56 +03:00
|
|
|
import { type default as NoteContextType } from "../../components/note_context";
|
2025-08-20 21:50:06 +03:00
|
|
|
|
|
|
|
|
export const ParentComponent = createContext<Component | null>(null);
|
2025-08-25 11:48:56 +03:00
|
|
|
export const NoteContext = createContext<NoteContextType | null>(null);
|
|
|
|
|
|
|
|
|
|
interface ComponentContext {
|
|
|
|
|
parentComponent: Component | null;
|
|
|
|
|
noteContext: NoteContextType | null;
|
|
|
|
|
}
|
2025-08-20 21:50:06 +03:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Takes in a React ref and returns a corresponding JQuery selector.
|
|
|
|
|
*
|
|
|
|
|
* @param ref the React ref from which to obtain the jQuery selector.
|
|
|
|
|
* @returns the corresponding jQuery selector.
|
|
|
|
|
*/
|
|
|
|
|
export function refToJQuerySelector<T extends HTMLElement>(ref: RefObject<T> | null): JQuery<T> {
|
|
|
|
|
if (ref?.current) {
|
|
|
|
|
return $(ref.current);
|
|
|
|
|
} else {
|
|
|
|
|
return $();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Renders a React component and returns the corresponding DOM element wrapped in JQuery.
|
|
|
|
|
*
|
|
|
|
|
* @param parentComponent the parent Trilium component for the component to be able to handle events.
|
|
|
|
|
* @param el the JSX element to render.
|
|
|
|
|
* @returns the rendered wrapped DOM element.
|
|
|
|
|
*/
|
2025-08-25 11:48:56 +03:00
|
|
|
export function renderReactWidget(context: ComponentContext, el: JSX.Element) {
|
|
|
|
|
return renderReactWidgetAtElement(context, el, new DocumentFragment()).children();
|
2025-08-20 21:50:06 +03:00
|
|
|
}
|
|
|
|
|
|
2025-08-25 11:48:56 +03:00
|
|
|
export function renderReactWidgetAtElement({ parentComponent, noteContext }: ComponentContext, el: JSX.Element, container: Element | DocumentFragment) {
|
2025-08-20 21:50:06 +03:00
|
|
|
render((
|
|
|
|
|
<ParentComponent.Provider value={parentComponent}>
|
2025-08-25 11:48:56 +03:00
|
|
|
<NoteContext.Provider value={noteContext}>
|
|
|
|
|
{el}
|
|
|
|
|
</NoteContext.Provider>
|
2025-08-20 21:50:06 +03:00
|
|
|
</ParentComponent.Provider>
|
|
|
|
|
), container);
|
|
|
|
|
return $(container) as JQuery<HTMLElement>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function disposeReactWidget(container: Element) {
|
|
|
|
|
render(null, container);
|
2025-08-22 17:31:06 +03:00
|
|
|
}
|
|
|
|
|
|
2025-08-22 21:45:03 +03:00
|
|
|
export function joinElements(components: ComponentChild[], separator = ", ") {
|
2025-08-22 17:31:06 +03:00
|
|
|
return components.reduce<any>((acc, item) =>
|
2025-08-22 21:45:03 +03:00
|
|
|
(acc.length ? [...acc, separator, item] : [item]), []);
|
2025-08-22 21:04:04 +03:00
|
|
|
}
|