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
chore(ocr): fix type issues & integrate ReadOnlyTextRepresentation
Elian Doran0e7f7fa20802
diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex 83a36ac0e6..b8f0f50341 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -1,8 +1,9 @@-import { it, describe, expect } from "vitest";-import { buildNote } from "../../../test/easy-froca";-import { getBoardData } from "./data";+import { describe, expect,it } from "vitest";+import FBranch from "../../../entities/fbranch";import froca from "../../../services/froca";+import { buildNote } from "../../../test/easy-froca";+import { getBoardData } from "./data";describe("Board data", () => {it("deduplicates cloned notes", async () => {diff --git a/apps/client/src/widgets/mobile_widgets/TabSwitcher.tsx b/apps/client/src/widgets/mobile_widgets/TabSwitcher.tsxindex ff92b6512e..32f21b94ab 100644--- a/apps/client/src/widgets/mobile_widgets/TabSwitcher.tsx+++ b/apps/client/src/widgets/mobile_widgets/TabSwitcher.tsx@@ -27,6 +27,7 @@ const VIEW_MODE_ICON_MAPPINGS: Record<Exclude<ViewMode, "default">, string> = {"contextual-help": "bx bx-help-circle","note-map": "bx bxs-network-chart",attachments: "bx bx-paperclip",+ ocr: "bx bx-text"};export default function TabSwitcher() {diff --git a/apps/client/src/widgets/note_types.tsx b/apps/client/src/widgets/note_types.tsxindex 0e3de9d1f9..f2f17dd590 100644--- a/apps/client/src/widgets/note_types.tsx+++ b/apps/client/src/widgets/note_types.tsx@@ -79,7 +79,7 @@ export const TYPE_MAPPINGS: Record<ExtendedNoteType, NoteTypeMapping> = {printable: true},readOnlyOCRText: {- view: () => import("./type_widgets/read_only_ocr_text"),+ view: () => import("./type_widgets/ReadOnlyTextRepresentation"),className: "note-detail-ocr-text",printable: true},diff --git a/apps/client/src/widgets/type_widgets/ReadOnlyTextRepresentation.tsx b/apps/client/src/widgets/type_widgets/ReadOnlyTextRepresentation.tsxnew file mode 100644index 0000000000..39f71fedef--- /dev/null+++ b/apps/client/src/widgets/type_widgets/ReadOnlyTextRepresentation.tsx@@ -0,0 +1,146 @@+import { useEffect, useState } from "preact/hooks";++import server from "../../services/server";+import toast from "../../services/toast";+import { t } from "../../services/i18n";+import { TypeWidgetProps } from "./type_widget";++interface TextRepresentationResponse {+ success: boolean;+ text: string;+ hasOcr: boolean;+ extractedAt: string | null;+ error?: string;+}++type State =+ | { kind: "loading" }+ | { kind: "loaded"; text: string; extractedAt: string | null }+ | { kind: "empty" }+ | { kind: "error"; message: string };++export default function ReadOnlyTextRepresentation({ note }: TypeWidgetProps) {+ const [ state, setState ] = useState<State>({ kind: "loading" });+ const [ processing, setProcessing ] = useState(false);++ async function fetchText() {+ setState({ kind: "loading" });++ try {+ const response = await server.get<TextRepresentationResponse>(`ocr/notes/${note.noteId}/text`);++ if (!response.success) {+ setState({ kind: "error", message: response.error || t("ocr.failed_to_load") });+ return;+ }++ if (!response.hasOcr || !response.text) {+ setState({ kind: "empty" });+ return;+ }++ setState({ kind: "loaded", text: response.text, extractedAt: response.extractedAt });+ } catch (error: any) {+ console.error("Error loading text representation:", error);+ setState({ kind: "error", message: error.message || t("ocr.failed_to_load") });+ }+ }++ useEffect(() => { fetchText(); }, [ note.noteId ]);++ async function processOCR() {+ setProcessing(true);+ try {+ const response = await server.post<{ success: boolean; error?: string }>(`ocr/process-note/${note.noteId}`);+ if (response.success) {+ toast.showMessage(t("ocr.processing_started"));+ setTimeout(fetchText, 2000);+ } else {+ throw new Error(response.error || t("ocr.processing_failed"));+ }+ } catch (error: any) {+ console.error("Error processing OCR:", error);+ toast.showError(error.message || t("ocr.processing_failed"));+ } finally {+ setProcessing(false);+ }+ }++ return (+ <div className="note-detail-printable" style={{ padding: "10px" }}>+ <div style={{+ marginBottom: "10px",+ padding: "8px 12px",+ backgroundColor: "var(--main-background-color)",+ border: "1px solid var(--main-border-color)",+ borderRadius: "4px",+ fontWeight: 500+ }}>+ <span className="bx bx-text" />{" "}{t("ocr.extracted_text_title")}+ </div>++ {state.kind === "loading" && (+ <div style={{ textAlign: "center", padding: "30px", color: "var(--muted-text-color)" }}>+ <span className="bx bx-loader-alt bx-spin" />{" "}{t("ocr.loading_text")}+ </div>+ )}++ {state.kind === "loaded" && (+ <>+ <pre style={{+ whiteSpace: "pre-wrap",+ fontFamily: "var(--detail-text-font-family)",+ fontSize: "var(--detail-text-font-size)",+ lineHeight: 1.6,+ border: "1px solid var(--main-border-color)",+ borderRadius: "4px",+ padding: "15px",+ backgroundColor: "var(--accented-background-color)",+ minHeight: "100px"+ }}>+ {state.text}+ </pre>+ <div style={{ fontSize: "0.9em", color: "var(--muted-text-color)", marginTop: "10px", fontStyle: "italic" }}>+ {t("ocr.extracted_on", { date: state.extractedAt ? new Date(state.extractedAt).toLocaleString() : t("ocr.unknown_date") })}+ </div>+ </>+ )}++ {state.kind === "empty" && (+ <>+ <div style={{ color: "var(--muted-text-color)", fontStyle: "italic", textAlign: "center", padding: "30px" }}>+ <span className="bx bx-info-circle" />{" "}{t("ocr.no_text_available")}+ </div>+ <button+ type="button"+ className="btn btn-secondary"+ style={{ marginTop: "15px" }}+ disabled={processing}+ onClick={processOCR}+ >+ {processing+ ? <><span className="bx bx-loader-alt bx-spin" />{" "}{t("ocr.processing")}</>+ : <><span className="bx bx-play" />{" "}{t("ocr.process_now")}</>+ }+ </button>+ <div style={{ fontSize: "0.9em", color: "var(--muted-text-color)", marginTop: "10px", fontStyle: "italic" }}>+ {t("ocr.no_text_explanation")}+ </div>+ </>+ )}++ {state.kind === "error" && (+ <div style={{+ color: "var(--error-color)",+ backgroundColor: "var(--error-background-color)",+ border: "1px solid var(--error-border-color)",+ padding: "10px",+ borderRadius: "4px",+ marginTop: "10px"+ }}>+ <span className="bx bx-error" />{" "}{state.message}+ </div>+ )}+ </div>+ );+}diff --git a/apps/client/src/widgets/type_widgets/read_only_ocr_text.ts b/apps/client/src/widgets/type_widgets/read_only_ocr_text.tsdeleted file mode 100644index c94f896a5b..0000000000--- a/apps/client/src/widgets/type_widgets/read_only_ocr_text.ts+++ /dev/null@@ -1,215 +0,0 @@-import type { EventData } from "../../components/app_context.js";-import type FNote from "../../entities/fnote.js";-import server from "../../services/server.js";-import toastService from "../../services/toast.js";-import { t } from "../../services/i18n.js";-import TypeWidget from "./type_widget.js";--const TPL = /*html*/`-<div class="note-detail-ocr-text note-detail-printable">- <style>- .note-detail-ocr-text {- min-height: 50px;- position: relative;- padding: 10px;- }-- .ocr-text-content {- white-space: pre-wrap;- font-family: var(--detail-text-font-family);- font-size: var(--detail-text-font-size);- line-height: 1.6;- border: 1px solid var(--main-border-color);- border-radius: 4px;- padding: 15px;- background-color: var(--accented-background-color);- min-height: 100px;- }-- .ocr-text-header {- margin-bottom: 10px;- padding: 8px 12px;- background-color: var(--main-background-color);- border: 1px solid var(--main-border-color);- border-radius: 4px;- font-weight: 500;- color: var(--main-text-color);- }-- .ocr-text-meta {- font-size: 0.9em;- color: var(--muted-text-color);- margin-top: 10px;- font-style: italic;- }-- .ocr-text-empty {- color: var(--muted-text-color);- font-style: italic;- text-align: center;- padding: 30px;- }-- .ocr-text-loading {- text-align: center;- padding: 30px;- color: var(--muted-text-color);- }-- .ocr-text-error {- color: var(--error-color);- background-color: var(--error-background-color);- border: 1px solid var(--error-border-color);- padding: 10px;- border-radius: 4px;- margin-top: 10px;- }-- .ocr-process-button {- margin-top: 15px;- }- </style>-- <div class="ocr-text-header">- <span class="bx bx-text"></span> ${t("ocr.extracted_text_title")}- </div>-- <div class="ocr-text-content"></div>-- <div class="ocr-text-actions"></div>-- <div class="ocr-text-meta"></div>-</div>`;--interface OCRResponse {- success: boolean;- text: string;- hasOcr: boolean;- extractedAt: string | null;- error?: string;-}--export default class ReadOnlyOCRTextWidget extends TypeWidget {-- private $content!: JQuery<HTMLElement>;- private $actions!: JQuery<HTMLElement>;- private $meta!: JQuery<HTMLElement>;- private currentNote?: FNote;-- static getType() {- return "readOnlyOCRText";- }-- doRender() {- this.$widget = $(TPL);- this.contentSized();- this.$content = this.$widget.find(".ocr-text-content");- this.$actions = this.$widget.find(".ocr-text-actions");- this.$meta = this.$widget.find(".ocr-text-meta");-- super.doRender();- }-- async doRefresh(note: FNote) {- this.currentNote = note;-- // Show loading state- this.$content.html(`<div class="ocr-text-loading">- <span class="bx bx-loader-alt bx-spin"></span> ${t("ocr.loading_text")}- </div>`);- this.$actions.empty();- this.$meta.empty();-- try {- const response = await server.get<OCRResponse>(`ocr/notes/${note.noteId}/text`);-- if (!response.success) {- this.showError(response.error || t("ocr.failed_to_load"));- return;- }-- if (!response.hasOcr || !response.text) {- this.showNoOCRAvailable();- return;- }-- // Show the OCR text- this.$content.text(response.text);-- // Show metadata- const extractedAt = response.extractedAt ? new Date(response.extractedAt).toLocaleString() : t("ocr.unknown_date");- this.$meta.html(t("ocr.extracted_on", { date: extractedAt }));-- } catch (error: any) {- console.error("Error loading OCR text:", error);- this.showError(error.message || t("ocr.failed_to_load"));- }- }-- private showNoOCRAvailable() {- const $processButton = $(`<button class="btn btn-secondary ocr-process-button" type="button">- <span class="bx bx-play"></span> ${t("ocr.process_now")}- </button>`);-- $processButton.on("click", () => this.processOCR());-- this.$content.html(`<div class="ocr-text-empty">- <span class="bx bx-info-circle"></span> ${t("ocr.no_text_available")}- </div>`);-- this.$actions.append($processButton);- this.$meta.html(t("ocr.no_text_explanation"));- }-- private async processOCR() {- if (!this.currentNote) {- return;- }-- const $button = this.$actions.find(".ocr-process-button");-- // Disable button and show processing state- $button.prop("disabled", true);- $button.html(`<span class="bx bx-loader-alt bx-spin"></span> ${t("ocr.processing")}`);-- try {- const response = await server.post(`ocr/process-note/${this.currentNote.noteId}`);-- if (response.success) {- toastService.showMessage(t("ocr.processing_started"));- // Refresh the view after a short delay to allow processing to begin- setTimeout(() => {- if (this.currentNote) {- this.doRefresh(this.currentNote);- }- }, 2000);- } else {- throw new Error(response.error || t("ocr.processing_failed"));- }- } catch (error: any) {- console.error("Error processing OCR:", error);- toastService.showError(error.message || t("ocr.processing_failed"));-- // Re-enable button- $button.prop("disabled", false);- $button.html(`<span class="bx bx-play"></span> ${t("ocr.process_now")}`);- }- }-- private showError(message: string) {- this.$content.html(`<div class="ocr-text-error">- <span class="bx bx-error"></span> ${message}- </div>`);- this.$actions.empty();- this.$meta.empty();- }-- async executeWithContentElementEvent({ resolve, ntxId }: EventData<"executeWithContentElement">) {- if (!this.isNoteContext(ntxId)) {- return;- }-- await this.initialized;- resolve(this.$content);- }-}diff --git a/apps/server/src/routes/api/ocr.ts b/apps/server/src/routes/api/ocr.tsindex 25edb81814..f087506e34 100644--- a/apps/server/src/routes/api/ocr.ts+++ b/apps/server/src/routes/api/ocr.ts@@ -63,7 +63,7 @@ import sql from "../../services/sql.js";* - session: []* tags: ["ocr"]*/-async function processNoteOCR(req: Request, res: Response) {+async function processNoteOCR(req: Request<{ noteId: string }>, res: Response) {try {const { noteId } = req.params;const { language = 'eng', forceReprocess = false } = req.body || {};@@ -169,7 +169,7 @@ async function processNoteOCR(req: Request, res: Response) {* - session: []* tags: ["ocr"]*/-async function processAttachmentOCR(req: Request, res: Response) {+async function processAttachmentOCR(req: Request<{ attachmentId: string }>, res: Response) {try {const { attachmentId } = req.params;const { language = 'eng', forceReprocess = false } = req.body || {};@@ -481,7 +481,7 @@ async function getOCRStats(req: Request, res: Response) {* - session: []* tags: ["ocr"]*/-async function deleteOCRResults(req: Request, res: Response) {+async function deleteOCRResults(req: Request<{ blobId: string }>, res: Response) {try {const { blobId } = req.params;@@ -549,7 +549,7 @@ async function deleteOCRResults(req: Request, res: Response) {* description: Note not found* tags: ["ocr"]*/-async function getNoteOCRText(req: Request, res: Response) {+async function getNoteOCRText(req: Request<{ noteId: string }>, res: Response) {try {const { noteId } = req.params;