Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";

import { getTranscriptMatches, type SearchOptions } from "./matching";

const defaultOptions: SearchOptions = {
caseSensitive: false,
wholeWord: false,
};

describe("getTranscriptMatches", () => {
it("returns transcript word spans in match order", () => {
const spans = [
createSpan("word-1", "Hello"),
createSpan("word-2", "world"),
createSpan("word-3", "hello"),
];

expect(
getTranscriptMatches(spans, "hello", defaultOptions).map(
(match) => match.id,
),
).toEqual(["word-1", "word-3"]);
});

it("maps phrase matches to the first matching word", () => {
const spans = [
createSpan("word-1", "plan"),
createSpan("word-2", "the"),
createSpan("word-3", "launch"),
];

expect(
getTranscriptMatches(spans, "the launch", defaultOptions).map(
(match) => match.id,
),
).toEqual(["word-2"]);
});

it("keeps whole-word matching behavior", () => {
const spans = [
createSpan("word-1", "sync"),
createSpan("word-2", "async"),
createSpan("word-3", "syncing"),
];

expect(
getTranscriptMatches(spans, "sync", {
...defaultOptions,
wholeWord: true,
}).map((match) => match.id),
).toEqual(["word-1"]);
});
});

function createSpan(id: string, text: string) {
const span = document.createElement("span");
span.dataset.wordId = id;
span.textContent = text;
return span;
}
48 changes: 28 additions & 20 deletions apps/desktop/src/session/components/note-input/search/matching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,28 +94,36 @@ export function getTranscriptMatches(
const searchText = prepareText(fullText, opts.caseSensitive);
const indices = findOccurrences(searchText, prepared, opts.wholeWord);
const result: MatchResult[] = [];
let spanIndex = 0;

for (const idx of indices) {
for (let i = 0; i < spanPositions.length; i++) {
const { start, end } = spanPositions[i];
if (idx >= start && idx < end) {
result.push({
element: allSpans[i],
id: allSpans[i].dataset.wordId || null,
});
break;
}
if (
i < spanPositions.length - 1 &&
idx >= end &&
idx < spanPositions[i + 1].start
) {
result.push({
element: allSpans[i + 1],
id: allSpans[i + 1].dataset.wordId || null,
});
break;
}
while (
spanIndex < spanPositions.length - 1 &&
idx >= spanPositions[spanIndex].end &&
idx >= spanPositions[spanIndex + 1].start
) {
spanIndex += 1;
}

const { start, end } = spanPositions[spanIndex];
if (idx >= start && idx < end) {
result.push({
element: allSpans[spanIndex],
id: allSpans[spanIndex].dataset.wordId || null,
});
continue;
}

if (
spanIndex < spanPositions.length - 1 &&
idx >= end &&
idx < spanPositions[spanIndex + 1].start
) {
const nextSpan = allSpans[spanIndex + 1];
result.push({
element: nextSpan,
id: nextSpan.dataset.wordId || null,
});
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render, screen } from "@testing-library/react";
import { act, render, screen } from "@testing-library/react";
import { createRef } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";

Expand All @@ -7,13 +7,11 @@ import { Transcript } from "./index";
const {
useSliceRowIdsMock,
useStoreMock,
useTableMock,
useListenerMock,
useAudioPlayerMock,
} = vi.hoisted(() => ({
useSliceRowIdsMock: vi.fn(),
useStoreMock: vi.fn(),
useTableMock: vi.fn(),
useListenerMock: vi.fn(),
useAudioPlayerMock: vi.fn(),
}));
Expand All @@ -26,7 +24,6 @@ vi.mock("~/store/tinybase/store/main", () => ({
UI: {
useSliceRowIds: useSliceRowIdsMock,
useStore: useStoreMock,
useTable: useTableMock,
useCheckpoints: vi.fn(() => null),
useIndexes: vi.fn(() => null),
},
Expand Down Expand Up @@ -86,16 +83,12 @@ describe("Transcript", () => {
partialWordsByChannel: Record<number, unknown[]>;
partialHintsByChannel: Record<number, unknown[]>;
};
let transcriptRowListener: (() => void) | null;
let transcriptWordsJson: string;
let transcriptsTable: Record<string, { words: string }>;

beforeEach(() => {
transcriptRowListener = null;
transcriptWordsJson = "[]";
transcriptsTable = {
[transcriptId]: {
words: transcriptWordsJson,
},
};

listenerState = {
getSessionMode: () => "active",
Expand All @@ -112,6 +105,16 @@ describe("Transcript", () => {

useSliceRowIdsMock.mockReturnValue([transcriptId]);
useStoreMock.mockReturnValue({
addRowListener: vi.fn(
(tableId: string, rowId: string, listener: () => void) => {
if (tableId === "transcripts" && rowId === transcriptId) {
transcriptRowListener = listener;
}

return "listener-1";
},
),
delListener: vi.fn(),
getCell: vi.fn(
(tableId: string, rowId: string, cellId: "words" | "speaker_hints") => {
if (
Expand All @@ -126,7 +129,6 @@ describe("Transcript", () => {
},
),
});
useTableMock.mockImplementation(() => transcriptsTable);
useListenerMock.mockImplementation((selector) => selector(listenerState));
useAudioPlayerMock.mockReturnValue({ audioExists: false });
});
Expand All @@ -140,11 +142,9 @@ describe("Transcript", () => {
expect(screen.getByTestId("listening-state").textContent).toBe("listening");

transcriptWordsJson = '[{"id":"word-1","text":" Hello"}]';
transcriptsTable = {
[transcriptId]: {
words: transcriptWordsJson,
},
};
act(() => {
transcriptRowListener?.();
});

view.rerender(<Transcript sessionId={sessionId} scrollRef={scrollRef} />);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
import { useMemo } from "react";

import type {
RenderTranscriptHuman,
RenderTranscriptRequest,
} from "@hypr/plugin-transcription";

import { getUniqueRowIds, useStoreRowsRevision } from "~/store/tinybase/hooks";
import * as main from "~/store/tinybase/store/main";
import {
buildRenderTranscriptRequestFromRows,
Expand All @@ -14,7 +15,6 @@ import {
} from "~/stt/render-transcript";
import { parseTranscriptHints, parseTranscriptWords } from "~/stt/utils";

type RenderTableId = "transcripts" | "mapping_session_participant" | "humans";
type UiStore = NonNullable<ReturnType<typeof main.UI.useStore>>;

export type TranscriptRowWithId = {
Expand Down Expand Up @@ -146,41 +146,6 @@ function useRenderData(
return { request, transcriptRows };
}

function useStoreRowsRevision(
store: UiStore | undefined,
tableId: RenderTableId,
rowIds: readonly string[],
): number {
const revisionRef = useRef(0);
const rowIdsKey = getRowIdsKey(rowIds);
const subscribedRowIds = useMemo(() => getUniqueRowIds(rowIds), [rowIdsKey]);

const subscribe = useCallback(
(notify: () => void) => {
if (!store || subscribedRowIds.length === 0) {
return noop;
}

const listenerIds = subscribedRowIds.map((rowId) =>
store.addRowListener(tableId, rowId, () => {
revisionRef.current += 1;
notify();
}),
);

return () => {
for (const listenerId of listenerIds) {
store.delListener(listenerId);
}
};
},
[store, subscribedRowIds, tableId],
);
const getSnapshot = useCallback(() => revisionRef.current, []);

return useSyncExternalStore(subscribe, getSnapshot, getZero);
}

function getTranscriptRow(store: UiStore, transcriptId: string): TranscriptRow {
const startedAt = store.getCell("transcripts", transcriptId, "started_at");

Expand Down Expand Up @@ -238,26 +203,4 @@ function getRowIdsKey(rowIds: readonly string[]): string {
return getUniqueRowIds(rowIds).join("\u0000");
}

function getUniqueRowIds(rowIds: readonly string[]): string[] {
const uniqueRowIds: string[] = [];
const seen = new Set<string>();

for (const rowId of rowIds) {
if (!rowId || seen.has(rowId)) {
continue;
}

uniqueRowIds.push(rowId);
seen.add(rowId);
}

return uniqueRowIds;
}

function noop() {}

function getZero() {
return 0;
}

const emptyIds: string[] = [];
Loading
Loading