🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): Improve search highlighting in CodeMirrorEditor (#12961)
Ben Bachem07ee4ed96181
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e85b648544..57c7315f1f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -418,45 +418,48 @@ The background color of the following component will be `hsl(var(--primary))` an### Color Variables-| Variable | Description | Examples |-| ------------------------ | ------------------------------------------------------------------ | -------------------------------- |-| --background | Background color | Default background color of body |-| --foreground | Foreground color | Default text color of body |-| --muted | Muted background color | TabsList, Skeleton and Switch |-| --muted-foreground | Muted foreground color | |-| --popover | Popover background color | DropdownMenu, HoverCard, Popover |-| --popover-foreground | Popover foreground color | |-| --card | Card background color | Card |-| --card-foreground | Card foreground color | |-| --border | Border color | Default border color |-| --input | Input field border color | Input, Select, Textarea |-| --primary | Primary button background colors | Button variant="primary" |-| --primary-foreground | Primary button foreground color | |-| --secondary | Secondary button background color | Button variant="secondary" |-| --secondary-foreground | Secondary button foreground color | |-| --accent | Used for accents such as hover effects | DropdownMenuItem, SelectItem |-| --accent-foreground | Used for texts on hover effects | DropdownMenuItem, SelectItem |-| --destructive | Destructive action color for background | Button variant="destructive" |-| --destructive-foreground | Destructive action color for text | |-| --ring | Focus ring color | MultiSelect |-| --primary-accent | Primary accent color used for branding | Layout |-| --hover-primary-accent | Primary accent color used for hover effects for links | SignIn and AuthCloudRegionSwitch |-| --muted-green | Muted green for Event label | ObservationTree |-| --muted-magenta | Muted magenta for Generation label | ObservationTree |-| --muted-blue | Muted blue for Span label | ObservationTree |-| --muted-gray | Muted gray for disabled status badges | StatusBadge |-| --accent-light-green | Light green accent for background of output and assistant messages | IOPreview, Generations, Traces |-| --accent-dark-green | Dark green accent for border of output and assistant messages | CodeJsonViewer and IOPReview |-| --light-red | Light red for error background | level-color and StatusBadge |-| --dark-red | Dark red for error text and error badge dot color | level-color and ErrorPage |-| --light-yellow | Light yellow for warning background | LevelColor |-| --dark-yellow | Dark yellow for warning text | LevelColor |-| --light-green | Light green for success status badge background | StatusBadge |-| --dark-green | Dark green for success status badge text and dot | StatusBadge |-| --light-blue | Light blue for background of Staging label | LangfuseLogo |-| --dark-blue | Dark blue for text and border of Staging label | LangfuseLogo |-| --accent-light-blue | Light blue accent for table link hover effect | TableLink |-| --accent-dark-blue | Dark blue accent for table link text | TableLink |+| Variable | Description | Examples |+| -------------------------------- | ------------------------------------------------------------------ | -------------------------------- |+| --background | Background color | Default background color of body |+| --foreground | Foreground color | Default text color of body |+| --muted | Muted background color | TabsList, Skeleton and Switch |+| --muted-foreground | Muted foreground color | |+| --popover | Popover background color | DropdownMenu, HoverCard, Popover |+| --popover-foreground | Popover foreground color | |+| --card | Card background color | Card |+| --card-foreground | Card foreground color | |+| --border | Border color | Default border color |+| --input | Input field border color | Input, Select, Textarea |+| --primary | Primary button background colors | Button variant="primary" |+| --primary-foreground | Primary button foreground color | |+| --secondary | Secondary button background color | Button variant="secondary" |+| --secondary-foreground | Secondary button foreground color | |+| --accent | Used for accents such as hover effects | DropdownMenuItem, SelectItem |+| --accent-foreground | Used for texts on hover effects | DropdownMenuItem, SelectItem |+| --destructive | Destructive action color for background | Button variant="destructive" |+| --destructive-foreground | Destructive action color for text | |+| --ring | Focus ring color | MultiSelect |+| --primary-accent | Primary accent color used for branding | Layout |+| --hover-primary-accent | Primary accent color used for hover effects for links | SignIn and AuthCloudRegionSwitch |+| --muted-green | Muted green for Event label | ObservationTree |+| --muted-magenta | Muted magenta for Generation label | ObservationTree |+| --muted-blue | Muted blue for Span label | ObservationTree |+| --muted-gray | Muted gray for disabled status badges | StatusBadge |+| --accent-light-green | Light green accent for background of output and assistant messages | IOPreview, Generations, Traces |+| --accent-dark-green | Dark green accent for border of output and assistant messages | CodeJsonViewer and IOPReview |+| --light-red | Light red for error background | level-color and StatusBadge |+| --dark-red | Dark red for error text and error badge dot color | level-color and ErrorPage |+| --light-yellow | Light yellow for warning background | LevelColor |+| --dark-yellow | Dark yellow for warning text | LevelColor |+| --light-green | Light green for success status badge background | StatusBadge |+| --dark-green | Dark green for success status badge text and dot | StatusBadge |+| --light-blue | Light blue for background of Staging label | LangfuseLogo |+| --dark-blue | Dark blue for text and border of Staging label | LangfuseLogo |+| --accent-light-blue | Light blue accent for table link hover effect | TableLink |+| --accent-dark-blue | Dark blue accent for table link text | TableLink |+| --find-match-selected-background | Background color for selected search matches | CodeMirrorEditor |+| --find-match-selected-foreground | Foreground color for selected search matches | CodeMirrorEditor |+| --find-match-background | Background color for search matches | CodeMirrorEditor |### Adding New Colorsdiff --git a/web/src/components/ChatMessages/messageSearch/controller.ts b/web/src/components/ChatMessages/messageSearch/controller.tsindex 3511077340..906f2a9ada 100644--- a/web/src/components/ChatMessages/messageSearch/controller.ts+++ b/web/src/components/ChatMessages/messageSearch/controller.ts@@ -7,7 +7,8 @@ import { type RefObject } from "react";import {applyCodeMirrorSearchQuery,- selectCodeMirrorRange,+ unsetActiveSearchMarkCodeMirrorRange,+ setActiveSearchMarkCodeMirrorRange,} from "@/src/components/editor";export type MessageSearchMatch = {@@ -269,17 +270,33 @@ export function createMessageSearchController(inline: "center",});- const messageTarget = messageTargets.get(- getMessageTargetKey(activeMatch.pageId, activeMatch.messageId),+ let activeMessageTarget: MessageSearchMessageTarget | null = null;+ const inactiveMessageTargets: MessageSearchMessageTarget[] = [];++ const activeMessageTargetKey = getMessageTargetKey(+ activeMatch.pageId,+ activeMatch.messageId,);- messageTarget?.rowRef.current?.scrollIntoView({+ for (const [key, target] of messageTargets.entries()) {+ if (key === activeMessageTargetKey) {+ activeMessageTarget = target;+ } else {+ inactiveMessageTargets.push(target);+ }+ }++ for (const target of inactiveMessageTargets) {+ unsetActiveSearchMarkCodeMirrorRange(target?.editorRef);+ }++ activeMessageTarget?.rowRef.current?.scrollIntoView({behavior: "smooth",block: "center",inline: "nearest",});- selectCodeMirrorRange(messageTarget?.editorRef, {+ setActiveSearchMarkCodeMirrorRange(activeMessageTarget?.editorRef, {from: activeMatch.from,to: activeMatch.to,});@@ -318,7 +335,7 @@ export function createMessageSearchController(const refreshSearchResults = (shouldSyncEditors: boolean) => {const activeMatchChanged = recomputeMatches();- if (shouldSyncEditors) {+ if (shouldSyncEditors || activeMatchChanged) {syncEditorsToQuery();}diff --git a/web/src/components/ChatMessages/messageSearch/toolbar.tsx b/web/src/components/ChatMessages/messageSearch/toolbar.tsxindex 1c47470b44..3836533631 100644--- a/web/src/components/ChatMessages/messageSearch/toolbar.tsx+++ b/web/src/components/ChatMessages/messageSearch/toolbar.tsx@@ -21,7 +21,6 @@ export function MessageSearchToolbar({ className }: { className?: string }) {openRequestCount,queryInput,matches,- activeMatch,activeMatchIndex,openSearch,closeSearch,@@ -109,9 +108,6 @@ export function MessageSearchToolbar({ className }: { className?: string }) {onClick={nextMatch}disabled={matches.length === 0}/>- <div className="text-muted-foreground hidden max-w-48 truncate px-1 text-xs lg:block">- {activeMatch?.locationLabel ?? "No matches"}- </div><IconButton icon={X} label="Close search" onClick={closeSearch} /></div>);diff --git a/web/src/components/editor/CodeMirrorEditor.tsx b/web/src/components/editor/CodeMirrorEditor.tsxindex 269c165697..87b46a0cec 100644--- a/web/src/components/editor/CodeMirrorEditor.tsx+++ b/web/src/components/editor/CodeMirrorEditor.tsx@@ -6,7 +6,7 @@ import CodeMirror, {ViewPlugin,type ViewUpdate,} from "@uiw/react-codemirror";-import { RangeSetBuilder } from "@codemirror/state";+import { RangeSetBuilder, StateEffect, StateField } from "@codemirror/state";import { SearchQuery, search, setSearchQuery } from "@codemirror/search";import { json, jsonParseLinter } from "@codemirror/lang-json";import { linter, type Diagnostic } from "@codemirror/lint";@@ -165,6 +165,142 @@ const bidiSupport = [),];+// Add custom search highlight decoration using the same class names as the default search match decorations+// See: https://github.com/codemirror/search/blob/36e8f21e070d471fcbe2e2f338ef4e647b492ba8/src/search.ts#L396+const searchMatchMark = Decoration.mark({+ class: "cm-searchMatch",+});+const selectedSearchMatchMark = Decoration.mark({+ class: "cm-searchMatch cm-searchMatch-selected",+});++const setSearchHighlightMarks = StateEffect.define<+ {+ from: number;+ to: number;+ }[]+>({+ map: (ranges, change) =>+ ranges.map(({ from, to }) => ({+ from: change.mapPos(from),+ to: change.mapPos(to),+ })),+});++const setSelectedSearchHighlightMark = StateEffect.define<{+ from: number;+ to: number;+}>({+ map: ({ from, to }, change) => ({+ from: change.mapPos(from),+ to: change.mapPos(to),+ }),+});++const unsetSelectedSearchHighlightMark = StateEffect.define({});++const searchHighlightingSupport = StateField.define<DecorationSet>({+ create() {+ return Decoration.none;+ },+ update(decos, tr) {+ decos = decos.map(tr.changes);+ for (const effect of tr.effects) {+ if (effect.is(setSearchHighlightMarks)) {+ // Remove all existing search highlights+ decos = decos.update({+ filter: (from, to, decoration) => {+ return !decoration.spec.class?.includes("cm-searchMatch");+ },+ });++ decos = decos.update({+ add: effect.value.map(({ from, to }) =>+ searchMatchMark.range(from, to),+ ),+ });+ }++ if (effect.is(unsetSelectedSearchHighlightMark)) {+ let selectedRange: { from: number; to: number } | null = null;+ decos = decos.update({+ filter: (from, to, decoration) => {+ if (decoration.spec.class?.includes("cm-searchMatch-selected")) {+ selectedRange = { from, to };+ return false;+ }+ return true;+ },+ });++ // Reassign the value and cast it because typescript infers it to be always null,+ // not recognizing it to be assigned in the filter above.+ selectedRange = selectedRange as {+ from: number;+ to: number;+ } | null;++ if (selectedRange) {+ decos = decos.update({+ add: [searchMatchMark.range(selectedRange.from, selectedRange.to)],+ });+ }+ }++ if (effect.is(setSelectedSearchHighlightMark)) {+ // Remove normal search match mark from the selected range,+ // otherwise there will _both_ a normal and selected highlight on the active match.+ decos = decos.update({+ filter: (from, to, decoration) => {+ if (from === effect.value.from && to === effect.value.to) {+ return !decoration.spec.class?.includes("cm-searchMatch");+ }++ return true;+ },+ });++ let previousSelectedRange: { from: number; to: number } | null = null;++ // Make the existing selected search highlight a normal search highlight+ decos = decos.update({+ filter: (from, to, decoration) => {+ if (decoration.spec.class?.includes("cm-searchMatch-selected")) {+ previousSelectedRange = { from, to };+ return false;+ }++ return true;+ },+ });++ // Reassign the value and cast it because typescript infers it to be always null,+ // not recognizing it to be assigned in the filter above.+ previousSelectedRange = previousSelectedRange as {+ from: number;+ to: number;+ } | null;++ decos = decos.update({+ add: [+ ...(previousSelectedRange+ ? [+ searchMatchMark.range(+ previousSelectedRange.from,+ previousSelectedRange.to,+ ),+ ]+ : []),+ selectedSearchMatchMark.range(effect.value.from, effect.value.to),+ ].toSorted((a, b) => a.from - b.from),+ });+ }+ }+ return decos;+ },+ provide: (f) => EditorView.decorations.from(f),+});+export function applyCodeMirrorSearchQuery(editorRef: RefObject<ReactCodeMirrorRef | null> | undefined,searchValue: string,@@ -174,18 +310,30 @@ export function applyCodeMirrorSearchQuery(return;}+ const searchQuery = new SearchQuery({+ search: searchValue,+ caseSensitive: false,+ literal: true,+ });+view.dispatch({- effects: setSearchQuery.of(- new SearchQuery({- search: searchValue,- caseSensitive: false,- literal: true,- }),- ),+ effects: setSearchQuery.of(searchQuery),+ });++ const cursor = searchQuery.getCursor(view.state);+ const matchRanges: { from: number; to: number }[] = [];+ let current = cursor.next();+ while (!current.done) {+ matchRanges.push(current.value);+ current = cursor.next();+ }++ view.dispatch({+ effects: setSearchHighlightMarks.of(matchRanges),});}-export function selectCodeMirrorRange(+export function setActiveSearchMarkCodeMirrorRange(editorRef: RefObject<ReactCodeMirrorRef | null> | undefined,range: { from: number; to: number } | null,) {@@ -195,11 +343,23 @@ export function selectCodeMirrorRange(}view.dispatch({- selection: {- anchor: range.from,- head: range.to,- },- scrollIntoView: true,+ effects: [+ setSelectedSearchHighlightMark.of(range),+ EditorView.scrollIntoView(range.from),+ ],+ });+}++export function unsetActiveSearchMarkCodeMirrorRange(+ editorRef: RefObject<ReactCodeMirrorRef | null> | undefined,+) {+ const view = editorRef?.current?.view;+ if (!view) {+ return;+ }++ view.dispatch({+ effects: unsetSelectedSearchHighlightMark.of(null),});}@@ -268,6 +428,7 @@ export function CodeMirrorEditor({}}lang={mode === "json" ? "json" : undefined}extensions={[+ searchHighlightingSupport,search(),// RTL/bidi support - must be early for proper line decoration...bidiSupport,@@ -277,6 +438,16 @@ export function CodeMirrorEditor({outline: "none",},}),+ // Update search match highlight styles+ EditorView.theme({+ ".cm-searchMatch.cm-searchMatch": {+ backgroundColor: "hsl(var(--find-match-background))",+ },+ ".cm-searchMatch.cm-searchMatch-selected": {+ backgroundColor: "hsl(var(--find-match-selected-background))",+ color: "hsl(var(--find-match-selected-foreground))",+ },+ }),// Hide gutter when lineNumbers is false// Fix missing gutter border...(!lineNumbersdiff --git a/web/src/styles/globals.css b/web/src/styles/globals.cssindex 2f2198cf7e..976b64fe8b 100644--- a/web/src/styles/globals.css+++ b/web/src/styles/globals.css@@ -62,6 +62,14 @@--color-sidebar-border: hsl(var(--sidebar-border));--color-sidebar-ring: hsl(var(--sidebar-ring));+ --color-find-match-background: hsl(var(--find-match-background));+ --color-find-match-selected-background: hsl(+ var(--find-match-selected-background)+ );+ --color-find-match-selected-foreground: hsl(+ var(--find-match-selected-foreground)+ );+--radius-sm: calc(var(--radius) - 4px);--radius-md: calc(var(--radius) - 2px);--radius-lg: var(--radius);@@ -210,6 +218,10 @@--sidebar-border: 220 13% 91%;--sidebar-ring: 217.2 91.2% 59.8%;+ --find-match-background: 60 60% 85%;+ --find-match-selected-background: 60 100% 50%;+ --find-match-selected-foreground: 0 0% 0%;+--chart-1: 239 84% 58%;--chart-2: 188 94% 43%;--chart-3: 240 4% 46%;@@ -306,6 +318,10 @@--sidebar-border: 217.2 32.6% 26.5%;--sidebar-ring: 224.3 76.3% 46%;+ --find-match-background: 60 100% 20%;+ --find-match-selected-background: 60 100% 50%;+ --find-match-selected-foreground: 0 0% 0%;+--chart-1: 239 84% 58%;--chart-2: 188 94% 43%;--chart-3: 240 4% 46%;