In-file search ok

This commit is contained in:
Simon Cambier
2022-04-18 22:01:15 +02:00
parent 47b30b5c62
commit f6c3f9b580
8 changed files with 133 additions and 138 deletions

View File

@@ -1,16 +1,17 @@
<script lang="ts"> <script lang="ts">
import { createEventDispatcher } from "svelte"
import { import {
excerptAfter, excerptAfter,
excerptBefore, excerptBefore,
type IndexedNote,
type ResultNote, type ResultNote,
type SearchMatch,
} from "./globals" } from "./globals"
import { indexedNotes, inFileSearch } from "./stores"
import { escapeHTML, highlighter, stringsToRegex } from "./utils" import { escapeHTML, highlighter, stringsToRegex } from "./utils"
const dispatch = createEventDispatcher()
export let offset: number export let offset: number
export let note: ResultNote export let note: ResultNote
export let index = 0
export let selected = false
$: reg = stringsToRegex(note.foundWords) $: reg = stringsToRegex(note.foundWords)
@@ -26,9 +27,16 @@ function cleanContent(content: string): string {
} }
return escapeHTML(content) return escapeHTML(content)
} }
</script> </script>
<div class="suggestion-item omnisearch-result"> <div
class="suggestion-item omnisearch-result"
data-item-id={index}
class:is-selected={selected}
on:mousemove={(e) => dispatch("hover")}
on:click={(e) => dispatch("click")}
>
<div class="omnisearch-result__body"> <div class="omnisearch-result__body">
{@html cleanContent(note?.content ?? "").replace(reg, highlighter)} {@html cleanContent(note?.content ?? "").replace(reg, highlighter)}
</div> </div>

View File

@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { debounce } from "obsidian"; import { debounce } from "obsidian"
import { createEventDispatcher, onMount, tick } from "svelte" import { createEventDispatcher, onMount, tick } from "svelte"
import { searchQuery, selectedNote } from "./stores" import { searchQuery } from "./stores"
let elInput: HTMLInputElement let elInput: HTMLInputElement
let inputValue: string let inputValue: string
@@ -14,50 +14,36 @@ onMount(async () => {
elInput.select() elInput.select()
}) })
const debouncedOnInput = debounce(() => $searchQuery = inputValue, 100) const debouncedOnInput = debounce(() => ($searchQuery = inputValue), 100)
function moveNoteSelection(ev: KeyboardEvent): void { function moveNoteSelection(ev: KeyboardEvent): void {
switch (ev.key) { switch (ev.key) {
case "ArrowDown": case "ArrowDown":
ev.preventDefault() ev.preventDefault()
selectedNote.next() dispatch("arrow-down")
break break
case "ArrowUp": case "ArrowUp":
ev.preventDefault() ev.preventDefault()
selectedNote.previous() dispatch("arrow-up")
break break
// case "ArrowLeft":
// ev.preventDefault()
// break
// case "ArrowRight":
// ev.preventDefault()
// break
case "Enter": case "Enter":
ev.preventDefault() ev.preventDefault()
if (ev.ctrlKey || ev.metaKey) { if (ev.ctrlKey || ev.metaKey) {
// Open in a new pane // Open in a new pane
dispatch("ctrl-enter", $selectedNote) dispatch("ctrl-enter")
} else if (ev.shiftKey) { } else if (ev.shiftKey) {
// Create a new note // Create a new note
dispatch("shift-enter", $selectedNote) dispatch("shift-enter")
} else if (ev.altKey) { } else if (ev.altKey) {
// Create a new note // Create a new note
dispatch("alt-enter", $selectedNote) dispatch("alt-enter")
} else { } else {
// Open in current pane // Open in current pane
dispatch("enter", $selectedNote) dispatch("enter")
} }
break break
} }
// Scroll selected note into view when selecting with keyboard
if ($selectedNote) {
const elem = document.querySelector(
`[data-note-id="${$selectedNote.path}"]`
)
elem?.scrollIntoView({ behavior: "auto", block: "nearest" })
}
} }
</script> </script>

View File

@@ -1,11 +1,15 @@
<script lang="ts"> <script lang="ts">
import CmpInput from "./CmpInput.svelte" import CmpInput from "./CmpInput.svelte"
import CmpNoteInternalResult from "./CmpInfileResult.svelte" import CmpInFileResult from "./CmpInfileResult.svelte"
import { excerptAfter, type ResultNote, type SearchMatch } from "./globals" import { excerptAfter, type SearchMatch } from "./globals"
import { resultNotes } from "./stores" import { modal, plugin, resultNotes } from "./stores"
import { loopIndex } from "./utils"
import { tick } from "svelte"
import { MarkdownView } from "obsidian"
let matches: SearchMatch[] = [] let matches: SearchMatch[] = []
let groupedOffsets: number[] = [] let groupedOffsets: number[] = []
let selectedIndex = 0
$: note = $resultNotes[0] $: note = $resultNotes[0]
$: { $: {
@@ -47,21 +51,58 @@ function getGroupedMatches(
) )
} }
function onInputEnter(event: CustomEvent<ResultNote>): void { function moveIndex(dir: 1 | -1): void {
// console.log(event.detail) selectedIndex = loopIndex(selectedIndex + dir, groupedOffsets.length)
// openNote(event.detail) scrollIntoView()
// $modal.close() }
function scrollIntoView(): void {
tick().then(() => {
const elem = document.querySelector(`[data-item-id="${selectedIndex}"]`)
elem?.scrollIntoView({ behavior: "auto", block: "nearest" })
})
}
function openSelection(): void {
// TODO: clean me, merge with notes.openNote()
if (note) {
$plugin.app.workspace.openLinkText(note.path, "")
const view = $plugin.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) {
throw new Error("OmniSearch - No active MarkdownView")
}
const offset = groupedOffsets[selectedIndex] ?? 0
const pos = view.editor.offsetToPos(offset)
pos.ch = 0
view.editor.setCursor(pos)
view.editor.scrollIntoView({
from: { line: pos.line - 10, ch: 0 },
to: { line: pos.line + 10, ch: 0 },
})
$modal.close()
}
} }
</script> </script>
<div class="modal-title">Omnisearch - File</div> <div class="modal-title">Omnisearch - File</div>
<CmpInput on:enter={onInputEnter} /> <CmpInput
on:enter={openSelection}
on:arrow-up={() => moveIndex(-1)}
on:arrow-down={() => moveIndex(1)}
/>
<div class="modal-content"> <div class="modal-content">
<div class="prompt-results"> <div class="prompt-results">
{#if groupedOffsets.length && note} {#if groupedOffsets.length && note}
{#each groupedOffsets as offset} {#each groupedOffsets as offset, i}
<CmpNoteInternalResult {offset} {note} /> <CmpInFileResult
{offset}
{note}
index={i}
selected={i === selectedIndex}
on:hover={(e) => (selectedIndex = i)}
on:click={openSelection}
/>
{/each} {/each}
{:else} {:else}
We found 0 result for your search here. We found 0 result for your search here.
@@ -75,14 +116,6 @@ function onInputEnter(event: CustomEvent<ResultNote>): void {
<div class="prompt-instruction"> <div class="prompt-instruction">
<span class="prompt-instruction-command"></span><span>to open</span> <span class="prompt-instruction-command"></span><span>to open</span>
</div> </div>
<!-- <div class="prompt-instruction">
<span class="prompt-instruction-command">ctrl ↵</span>
<span>to open in a new pane</span>
</div>
<div class="prompt-instruction">
<span class="prompt-instruction-command">shift ↵</span>
<span>to create</span>
</div> -->
<div class="prompt-instruction"> <div class="prompt-instruction">
<span class="prompt-instruction-command">esc</span><span>to dismiss</span> <span class="prompt-instruction-command">esc</span><span>to dismiss</span>
</div> </div>

View File

@@ -1,9 +1,18 @@
<script lang="ts"> <script lang="ts">
import { tick } from "svelte"
import CmpInput from "./CmpInput.svelte" import CmpInput from "./CmpInput.svelte"
import CmpNoteResult from "./CmpNoteResult.svelte" import CmpNoteResult from "./CmpNoteResult.svelte"
import type { ResultNote } from "./globals" import type { ResultNote } from "./globals"
import { openNote } from "./notes" import { openNote } from "./notes"
import { modal, plugin, resultNotes, searchQuery, selectedNote } from "./stores" import { modal, plugin, resultNotes, searchQuery } from "./stores"
import { loopIndex } from "./utils"
let selectedIndex = 0
$: selectedNote = $resultNotes[selectedIndex]!
searchQuery.subscribe((q) => {
selectedIndex = 0
})
async function createOrOpenNote(item: ResultNote): Promise<void> { async function createOrOpenNote(item: ResultNote): Promise<void> {
try { try {
@@ -22,21 +31,42 @@ async function createOrOpenNote(item: ResultNote): Promise<void> {
} }
} }
function onInputEnter(event: CustomEvent<ResultNote>): void { function onClick() {
openNote(selectedNote)
$modal.close()
}
function onInputEnter(event: CustomEvent<unknown>): void {
// console.log(event.detail) // console.log(event.detail)
openNote(event.detail) openNote(selectedNote)
$modal.close() $modal.close()
} }
function onInputCtrlEnter(event: CustomEvent<ResultNote>): void { function onInputCtrlEnter(event: CustomEvent<unknown>): void {
openNote(event.detail, true) openNote(selectedNote, true)
$modal.close() $modal.close()
} }
function onInputShiftEnter(event: CustomEvent<ResultNote>): void { function onInputShiftEnter(event: CustomEvent<unknown>): void {
createOrOpenNote(event.detail) createOrOpenNote(selectedNote)
$modal.close() $modal.close()
} }
function moveIndex(dir: 1 | -1): void {
selectedIndex = loopIndex(selectedIndex + dir, $resultNotes.length)
scrollIntoView()
}
function scrollIntoView(): void {
if (selectedNote) {
tick().then(() => {
const elem = document.querySelector(
`[data-note-id="${selectedNote.path}"]`
)
elem?.scrollIntoView({ behavior: "auto", block: "nearest" })
})
}
}
</script> </script>
<div class="modal-title">Omnisearch - Vault</div> <div class="modal-title">Omnisearch - Vault</div>
@@ -44,12 +74,19 @@ function onInputShiftEnter(event: CustomEvent<ResultNote>): void {
on:enter={onInputEnter} on:enter={onInputEnter}
on:shift-enter={onInputShiftEnter} on:shift-enter={onInputShiftEnter}
on:ctrl-enter={onInputCtrlEnter} on:ctrl-enter={onInputCtrlEnter}
on:arrow-up={() => moveIndex(-1)}
on:arrow-down={() => moveIndex(1)}
/> />
<div class="modal-content"> <div class="modal-content">
<div class="prompt-results"> <div class="prompt-results">
{#each $resultNotes as result} {#each $resultNotes as result, i}
<CmpNoteResult selected={result === $selectedNote} note={result} /> <CmpNoteResult
selected={i === selectedIndex}
note={result}
on:hover={(e) => (selectedIndex = i)}
on:click={onClick}
/>
{/each} {/each}
</div> </div>
</div> </div>

View File

@@ -1,21 +1,16 @@
<script lang="ts"> <script lang="ts">
import { createEventDispatcher } from "svelte"
import { excerptAfter, excerptBefore, type ResultNote } from "./globals" import { excerptAfter, excerptBefore, type ResultNote } from "./globals"
import { openNote } from "./notes" import { getMatches } from "./search"
import { getMatches } from "./search";
import { modal, selectedNote } from "./stores"
import { escapeHTML, highlighter, stringsToRegex } from "./utils" import { escapeHTML, highlighter, stringsToRegex } from "./utils"
const dispatch = createEventDispatcher()
export let selected = false export let selected = false
export let note: ResultNote export let note: ResultNote
// function getMatches(text: string) { $: reg = stringsToRegex(note.foundWords)
// let match: RegExpExecArray | null = null $: matches = getMatches(note.content, reg)
// const matches: { term: string; index: number }[] = [] $: cleanedContent = cleanContent(note.content)
// while (null !== (match = reg.exec(text))) {
// matches.push({ term: match[0], index: match.index })
// }
// return matches
// }
function cleanContent(content: string): string { function cleanContent(content: string): string {
const pos = note.matches[0]?.offset ?? -1 const pos = note.matches[0]?.offset ?? -1
@@ -29,27 +24,14 @@ function cleanContent(content: string): string {
} }
return escapeHTML(content) return escapeHTML(content)
} }
$: reg = stringsToRegex(note.foundWords)
$: matches = getMatches(note.content, reg)
$: cleanedContent = cleanContent(note.content)
function onHover() {
$selectedNote = note
}
function onClick() {
openNote(note)
$modal.close()
}
</script> </script>
<div <div
data-note-id={note.path} data-note-id={note.path}
class="suggestion-item omnisearch-result" class="suggestion-item omnisearch-result"
class:is-selected={selected} class:is-selected={selected}
on:mouseover={onHover} on:mousemove={(e) => dispatch("hover")}
on:focus={onHover} on:click={(e) => dispatch("click")}
on:click={onClick}
> >
<span class="omnisearch-result__title"> <span class="omnisearch-result__title">
<!-- {@html note.basename.replace(reg, highlighter)} --> <!-- {@html note.basename.replace(reg, highlighter)} -->

View File

@@ -7,11 +7,9 @@ import {
plugin, plugin,
resultNotes, resultNotes,
searchQuery, searchQuery,
selectedNote,
} from './stores' } from './stores'
import { get } from 'svelte/store' import { get } from 'svelte/store'
import { extractHeadingsFromCache, stringsToRegex, wait } from './utils' import { extractHeadingsFromCache, stringsToRegex, wait } from './utils'
import { tick } from 'svelte'
let minisearchInstance: MiniSearch<IndexedNote> let minisearchInstance: MiniSearch<IndexedNote>
@@ -96,13 +94,6 @@ function subscribeToQuery(): void {
// Save the results in the store // Save the results in the store
resultNotes.set(results) resultNotes.set(results)
// Automatically select the first result
const firstResult = results[0]
if (firstResult) {
await tick()
selectedNote.set(firstResult)
}
} }
} }

View File

@@ -27,32 +27,6 @@ function createIndexedNotes() {
} }
} }
function createSelectedNote() {
const { subscribe, set, update } = writable<ResultNote | null>(null)
return {
subscribe,
set,
next: () =>
update(v => {
const notes = get(resultNotes)
if (!notes.length) return null
let id = notes.findIndex(n => n.path === v?.path)
if (id === -1) return notes[0] ?? null
id = id < notes.length - 1 ? id + 1 : 0
return notes[id] ?? null
}),
previous: () =>
update(v => {
const notes = get(resultNotes)
if (!notes.length) return null
let id = notes.findIndex(n => n.path === v?.path)
if (id === -1) return notes[0] ?? null
id = id > 0 ? id - 1 : notes.length - 1
return notes[id] ?? null
}),
}
}
/** /**
* If this field is set, the search will be limited to the given file * If this field is set, the search will be limited to the given file
*/ */
@@ -68,11 +42,6 @@ export const searchQuery = writable<string>('')
*/ */
export const resultNotes = writable<ResultNote[]>([]) export const resultNotes = writable<ResultNote[]>([])
/**
* The currently selected/hovered note in the results list
*/
export const selectedNote = createSelectedNote()
/** /**
* A reference to the plugin instance * A reference to the plugin instance
*/ */

View File

@@ -53,21 +53,6 @@ export function getAllIndices(text: string, regex: RegExp): SearchMatch[] {
.filter(isSearchMatch) .filter(isSearchMatch)
} }
// export function getAllIndices(text: string, terms: string[]): SearchMatch[] {
// let matches: SearchMatch[] = []
// for (const term of terms) {
// matches = [
// ...matches,
// ...[...text.matchAll(new RegExp(escapeRegex(term), 'gi'))]
// .map(o => ({ match: o[0], index: o.index }))
// .filter(isSearchMatch),
// ]
// }
// return matches
// // matches.sort((a, b) => b.match.length - a.match.length)
// // return uniqBy(matches, 'index')
// }
export function stringsToRegex(strings: string[]): RegExp { export function stringsToRegex(strings: string[]): RegExp {
return new RegExp(strings.map(escapeRegex).join('|'), 'gi') return new RegExp(strings.map(escapeRegex).join('|'), 'gi')
} }
@@ -93,3 +78,7 @@ export function extractHeadingsFromCache(
cache.headings?.filter(h => h.level === level).map(h => h.heading) ?? [] cache.headings?.filter(h => h.level === level).map(h => h.heading) ?? []
) )
} }
export function loopIndex(index: number, nbItems: number): number {
return (index + nbItems) % nbItems
}