Merge branch 'feature/in-file-search'
This commit is contained in:
@@ -43,3 +43,7 @@ Obsidian works best with a well-organized vault, but most of my notes are unrela
|
|||||||
I want (_need_) a fast and easy way to search my notes, something that _**just works**_. That's what Omnisearch is.
|
I want (_need_) a fast and easy way to search my notes, something that _**just works**_. That's what Omnisearch is.
|
||||||
|
|
||||||
Since I like to favor "search over organization", I wanted to make a search interface that would be useful for me.
|
Since I like to favor "search over organization", I wanted to make a search interface that would be useful for me.
|
||||||
|
|
||||||
|
## LICENSE
|
||||||
|
|
||||||
|
Omnisearch is licensed under [GPL-3](https://tldrlegal.com/license/gnu-general-public-license-v3-(gpl-3)).
|
||||||
@@ -24,3 +24,6 @@
|
|||||||
|
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.omnisearch-highlight {
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"id": "scambier.obsidian-omnisearch",
|
"id": "scambier.obsidian-omnisearch",
|
||||||
"name": "Omnisearch",
|
"name": "Omnisearch",
|
||||||
"version": "0.1.8",
|
"version": "0.2.0",
|
||||||
"minAppVersion": "0.14.2",
|
"minAppVersion": "0.14.2",
|
||||||
"description": "Search over organization",
|
"description": "Search over organization",
|
||||||
"author": "Simon Cambier",
|
"author": "Simon Cambier",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "scambier.obsidian-search",
|
"name": "scambier.obsidian-search",
|
||||||
"version": "0.1.8",
|
"version": "0.2.0",
|
||||||
"description": "Search over organization",
|
"description": "Search over organization",
|
||||||
"main": "dist/main.js",
|
"main": "dist/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -13,7 +13,6 @@
|
|||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tsconfig/svelte": "^3.0.0",
|
"@tsconfig/svelte": "^3.0.0",
|
||||||
"@types/lodash-es": "^4.17.6",
|
|
||||||
"@types/node": "^16.11.6",
|
"@types/node": "^16.11.6",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.18.0",
|
"@typescript-eslint/eslint-plugin": "^5.18.0",
|
||||||
"@typescript-eslint/parser": "^5.18.0",
|
"@typescript-eslint/parser": "^5.18.0",
|
||||||
@@ -36,7 +35,6 @@
|
|||||||
"typescript": "^4.6.3"
|
"typescript": "^4.6.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"lodash-es": "^4.17.21",
|
|
||||||
"minisearch": "^5.0.0-beta1"
|
"minisearch": "^5.0.0-beta1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
18
pnpm-lock.yaml
generated
18
pnpm-lock.yaml
generated
@@ -2,7 +2,6 @@ lockfileVersion: 5.3
|
|||||||
|
|
||||||
specifiers:
|
specifiers:
|
||||||
'@tsconfig/svelte': ^3.0.0
|
'@tsconfig/svelte': ^3.0.0
|
||||||
'@types/lodash-es': ^4.17.6
|
|
||||||
'@types/node': ^16.11.6
|
'@types/node': ^16.11.6
|
||||||
'@typescript-eslint/eslint-plugin': ^5.18.0
|
'@typescript-eslint/eslint-plugin': ^5.18.0
|
||||||
'@typescript-eslint/parser': ^5.18.0
|
'@typescript-eslint/parser': ^5.18.0
|
||||||
@@ -16,7 +15,6 @@ specifiers:
|
|||||||
eslint-plugin-node: 11.1.0
|
eslint-plugin-node: 11.1.0
|
||||||
eslint-plugin-promise: 5.0.0
|
eslint-plugin-promise: 5.0.0
|
||||||
eslint-plugin-svelte3: ^3.4.1
|
eslint-plugin-svelte3: ^3.4.1
|
||||||
lodash-es: ^4.17.21
|
|
||||||
minisearch: ^5.0.0-beta1
|
minisearch: ^5.0.0-beta1
|
||||||
obsidian: latest
|
obsidian: latest
|
||||||
prettier: ^2.6.2
|
prettier: ^2.6.2
|
||||||
@@ -27,12 +25,10 @@ specifiers:
|
|||||||
typescript: ^4.6.3
|
typescript: ^4.6.3
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
lodash-es: 4.17.21
|
|
||||||
minisearch: 5.0.0-beta1
|
minisearch: 5.0.0-beta1
|
||||||
|
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@tsconfig/svelte': 3.0.0
|
'@tsconfig/svelte': 3.0.0
|
||||||
'@types/lodash-es': 4.17.6
|
|
||||||
'@types/node': 16.11.26
|
'@types/node': 16.11.26
|
||||||
'@typescript-eslint/eslint-plugin': 5.18.0_2e93aa916703472007e9b5dfec98785b
|
'@typescript-eslint/eslint-plugin': 5.18.0_2e93aa916703472007e9b5dfec98785b
|
||||||
'@typescript-eslint/parser': 5.18.0_eslint@7.12.1+typescript@4.6.3
|
'@typescript-eslint/parser': 5.18.0_eslint@7.12.1+typescript@4.6.3
|
||||||
@@ -168,16 +164,6 @@ packages:
|
|||||||
resolution: {integrity: sha1-7ihweulOEdK4J7y+UnC86n8+ce4=}
|
resolution: {integrity: sha1-7ihweulOEdK4J7y+UnC86n8+ce4=}
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/@types/lodash-es/4.17.6:
|
|
||||||
resolution: {integrity: sha512-R+zTeVUKDdfoRxpAryaQNRKk3105Rrgx2CFRClIgRGaqDTdjsm8h6IYA8ir584W3ePzkZfst5xIgDwYrlh9HLg==}
|
|
||||||
dependencies:
|
|
||||||
'@types/lodash': 4.14.181
|
|
||||||
dev: true
|
|
||||||
|
|
||||||
/@types/lodash/4.14.181:
|
|
||||||
resolution: {integrity: sha512-n3tyKthHJbkiWhDZs3DkhkCzt2MexYHXlX0td5iMplyfwketaOeKboEVBqzceH7juqvEg3q5oUoBFxSLu7zFag==}
|
|
||||||
dev: true
|
|
||||||
|
|
||||||
/@types/node/16.11.26:
|
/@types/node/16.11.26:
|
||||||
resolution: {integrity: sha512-GZ7bu5A6+4DtG7q9GsoHXy3ALcgeIHP4NnL0Vv2wu0uUB/yQex26v0tf6/na1mm0+bS9Uw+0DFex7aaKr2qawQ==}
|
resolution: {integrity: sha512-GZ7bu5A6+4DtG7q9GsoHXy3ALcgeIHP4NnL0Vv2wu0uUB/yQex26v0tf6/na1mm0+bS9Uw+0DFex7aaKr2qawQ==}
|
||||||
dev: true
|
dev: true
|
||||||
@@ -1561,10 +1547,6 @@ packages:
|
|||||||
path-exists: 3.0.0
|
path-exists: 3.0.0
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/lodash-es/4.17.21:
|
|
||||||
resolution: {integrity: sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==}
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/lodash.merge/4.6.2:
|
/lodash.merge/4.6.2:
|
||||||
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
|
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
|
||||||
dev: true
|
dev: true
|
||||||
|
|||||||
@@ -1,66 +1,57 @@
|
|||||||
<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"
|
|
||||||
|
|
||||||
let input: HTMLInputElement
|
export let value = ''
|
||||||
let inputValue: string
|
|
||||||
const dispatch = createEventDispatcher()
|
const dispatch = createEventDispatcher()
|
||||||
|
|
||||||
|
let elInput: HTMLInputElement
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
await tick()
|
await tick()
|
||||||
input.focus()
|
elInput.focus()
|
||||||
input.select()
|
// elInput.value = $searchQuery
|
||||||
|
elInput.select()
|
||||||
})
|
})
|
||||||
|
|
||||||
const debouncedOnInput = debounce(() => $searchQuery = inputValue, 100)
|
const debouncedOnInput = debounce(() => {
|
||||||
|
dispatch("input", value)
|
||||||
|
}, 100)
|
||||||
|
|
||||||
// const throttledMoveNoteSelection = throttle(moveNoteSelection, 75)
|
|
||||||
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) {
|
||||||
|
// Expand in-note results
|
||||||
|
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>
|
||||||
|
|
||||||
<input
|
<input
|
||||||
bind:this={input}
|
bind:value
|
||||||
bind:value={inputValue}
|
bind:this={elInput}
|
||||||
on:input={debouncedOnInput}
|
on:input={debouncedOnInput}
|
||||||
on:keydown={moveNoteSelection}
|
on:keydown={moveNoteSelection}
|
||||||
type="text"
|
type="text"
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { tick } from "svelte"
|
|
||||||
import CmpInput from "./CmpInput.svelte"
|
|
||||||
import CmpNoteResult from "./CmpNoteResult.svelte"
|
|
||||||
import type { ResultNote } from "./globals"
|
|
||||||
import { openNote } from "./notes"
|
|
||||||
import { getSuggestions } from "./search"
|
|
||||||
import {
|
|
||||||
modal,
|
|
||||||
plugin,
|
|
||||||
resultNotes,
|
|
||||||
searchQuery,
|
|
||||||
selectedNote,
|
|
||||||
} from "./stores"
|
|
||||||
|
|
||||||
searchQuery.subscribe(async (q) => {
|
|
||||||
const results = getSuggestions(q)
|
|
||||||
resultNotes.set(results)
|
|
||||||
const firstResult = results[0]
|
|
||||||
if (firstResult) {
|
|
||||||
await tick()
|
|
||||||
selectedNote.set(firstResult)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
async function createOrOpenNote(item: ResultNote): Promise<void> {
|
|
||||||
try {
|
|
||||||
const file = await $plugin.app.vault.create(
|
|
||||||
$searchQuery + ".md",
|
|
||||||
"# " + $searchQuery
|
|
||||||
)
|
|
||||||
await $plugin.app.workspace.openLinkText(file.path, "")
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof Error && e.message === "File already exists.") {
|
|
||||||
// Open the existing file instead of creating it
|
|
||||||
await openNote(item)
|
|
||||||
} else {
|
|
||||||
console.error(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function onInputEnter(event: CustomEvent<ResultNote>): void {
|
|
||||||
// console.log(event.detail)
|
|
||||||
openNote(event.detail)
|
|
||||||
$modal.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
function onInputCtrlEnter(event: CustomEvent<ResultNote>): void {
|
|
||||||
openNote(event.detail, true)
|
|
||||||
$modal.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
function onInputShiftEnter(event: CustomEvent<ResultNote>): void {
|
|
||||||
createOrOpenNote(event.detail)
|
|
||||||
$modal.close()
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<CmpInput
|
|
||||||
on:enter={onInputEnter}
|
|
||||||
on:shift-enter={onInputShiftEnter}
|
|
||||||
on:ctrl-enter={onInputCtrlEnter}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div class="prompt-results">
|
|
||||||
{#each $resultNotes as result}
|
|
||||||
<CmpNoteResult selected={result === $selectedNote} note={result} />
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
<div class="prompt-instructions">
|
|
||||||
<div class="prompt-instruction">
|
|
||||||
<span class="prompt-instruction-command">↑↓</span><span>to navigate</span>
|
|
||||||
</div>
|
|
||||||
<div class="prompt-instruction">
|
|
||||||
<span class="prompt-instruction-command">↵</span><span>to open</span>
|
|
||||||
</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">
|
|
||||||
<span class="prompt-instruction-command">esc</span><span>to dismiss</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
154
src/CmpModalInFile.svelte
Normal file
154
src/CmpModalInFile.svelte
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
<script lang="ts" context="module">
|
||||||
|
let lastSearch = ""
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script lang="ts">
|
||||||
|
import CmpInput from "./CmpInput.svelte"
|
||||||
|
import CmpResultInFile from "./CmpResultInFile.svelte"
|
||||||
|
import { excerptAfter, type ResultNote, type SearchMatch } from "./globals"
|
||||||
|
import { plugin } from "./stores"
|
||||||
|
import { loopIndex } from "./utils"
|
||||||
|
import { onMount, tick } from "svelte"
|
||||||
|
import { MarkdownView } from "obsidian"
|
||||||
|
import { getSuggestions } from "./search"
|
||||||
|
import type { ModalInFile, ModalVault } from "./modal"
|
||||||
|
|
||||||
|
export let modal: ModalInFile
|
||||||
|
export let parent: ModalVault | null = null
|
||||||
|
export let singleFilePath = ""
|
||||||
|
export let searchQuery: string
|
||||||
|
|
||||||
|
let groupedOffsets: number[] = []
|
||||||
|
let selectedIndex = 0
|
||||||
|
let note: ResultNote | null = null
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
searchQuery = lastSearch
|
||||||
|
})
|
||||||
|
|
||||||
|
$: {
|
||||||
|
if (searchQuery) {
|
||||||
|
note = getSuggestions(searchQuery, { singleFilePath })[0] ?? null
|
||||||
|
lastSearch = searchQuery
|
||||||
|
}
|
||||||
|
selectedIndex = 0
|
||||||
|
scrollIntoView()
|
||||||
|
}
|
||||||
|
|
||||||
|
$: {
|
||||||
|
if (note) {
|
||||||
|
const groups = getGroups(note.matches)
|
||||||
|
groupedOffsets = groups.map((group) =>
|
||||||
|
Math.round((group.first()!.offset + group.last()!.offset) / 2)
|
||||||
|
)
|
||||||
|
// console.log(groups)
|
||||||
|
// console.log(groupedOffsets)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Group together close
|
||||||
|
*/
|
||||||
|
function getGroups(matches: SearchMatch[]): SearchMatch[][] {
|
||||||
|
const groups: SearchMatch[][] = []
|
||||||
|
let lastOffset = -1
|
||||||
|
while (true) {
|
||||||
|
const group = getGroupedMatches(matches, lastOffset, excerptAfter)
|
||||||
|
if (!group.length) break
|
||||||
|
lastOffset = group.last()!.offset
|
||||||
|
groups.push(group)
|
||||||
|
}
|
||||||
|
return groups
|
||||||
|
}
|
||||||
|
|
||||||
|
function getGroupedMatches(
|
||||||
|
matches: SearchMatch[],
|
||||||
|
offsetFrom: number,
|
||||||
|
maxLen: number
|
||||||
|
): SearchMatch[] {
|
||||||
|
const first = matches.find((m) => m.offset > offsetFrom)
|
||||||
|
if (!first) return []
|
||||||
|
return matches.filter(
|
||||||
|
(m) => m.offset > offsetFrom && m.offset <= first.offset + maxLen
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveIndex(dir: 1 | -1): void {
|
||||||
|
selectedIndex = loopIndex(selectedIndex + dir, groupedOffsets.length)
|
||||||
|
scrollIntoView()
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrollIntoView(): void {
|
||||||
|
tick().then(() => {
|
||||||
|
const elem = document.querySelector(`[data-item-id="${selectedIndex}"]`)
|
||||||
|
elem?.scrollIntoView({ behavior: "auto", block: "nearest" })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openSelection(): Promise<void> {
|
||||||
|
// TODO: clean me, merge with notes.openNote()
|
||||||
|
if (note) {
|
||||||
|
modal.close()
|
||||||
|
if (parent) parent.close()
|
||||||
|
|
||||||
|
await $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 },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="modal-title">Omnisearch - File</div>
|
||||||
|
<CmpInput
|
||||||
|
value={searchQuery}
|
||||||
|
on:input={(e) => (searchQuery = e.detail)}
|
||||||
|
on:enter={openSelection}
|
||||||
|
on:arrow-up={() => moveIndex(-1)}
|
||||||
|
on:arrow-down={() => moveIndex(1)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="prompt-results">
|
||||||
|
{#if groupedOffsets.length && note}
|
||||||
|
{#each groupedOffsets as offset, i}
|
||||||
|
<CmpResultInFile
|
||||||
|
{offset}
|
||||||
|
{note}
|
||||||
|
index={i}
|
||||||
|
selected={i === selectedIndex}
|
||||||
|
on:hover={(e) => (selectedIndex = i)}
|
||||||
|
on:click={openSelection}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
{:else}
|
||||||
|
<center> We found 0 result for your search here. </center>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="prompt-instructions">
|
||||||
|
<div class="prompt-instruction">
|
||||||
|
<span class="prompt-instruction-command">↑↓</span><span>to navigate</span>
|
||||||
|
</div>
|
||||||
|
<div class="prompt-instruction">
|
||||||
|
<span class="prompt-instruction-command">↵</span><span>to open</span>
|
||||||
|
</div>
|
||||||
|
<div class="prompt-instruction">
|
||||||
|
<span class="prompt-instruction-command">esc</span>
|
||||||
|
{#if !!parent}
|
||||||
|
<span>to go back to Vault Search</span>
|
||||||
|
{:else}
|
||||||
|
<span>to dismiss</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
155
src/CmpModalVault.svelte
Normal file
155
src/CmpModalVault.svelte
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
<script lang="ts" context="module">
|
||||||
|
let lastSearch = ""
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script lang="ts">
|
||||||
|
import { TFile } from "obsidian"
|
||||||
|
import { onMount, tick } from "svelte"
|
||||||
|
import CmpInput from "./CmpInput.svelte"
|
||||||
|
import CmpResultNote from "./CmpResultNote.svelte"
|
||||||
|
import type { ResultNote } from "./globals"
|
||||||
|
import { ModalInFile, type ModalVault } from "./modal"
|
||||||
|
import { openNote } from "./notes"
|
||||||
|
import { getSuggestions } from "./search"
|
||||||
|
import { plugin } from "./stores"
|
||||||
|
import { loopIndex } from "./utils"
|
||||||
|
|
||||||
|
export let modal: ModalVault
|
||||||
|
let selectedIndex = 0
|
||||||
|
let searchQuery: string
|
||||||
|
let resultNotes: ResultNote[] = []
|
||||||
|
$: selectedNote = resultNotes[selectedIndex]
|
||||||
|
|
||||||
|
$: {
|
||||||
|
if (searchQuery) {
|
||||||
|
resultNotes = getSuggestions(searchQuery)
|
||||||
|
lastSearch = searchQuery
|
||||||
|
}
|
||||||
|
selectedIndex = 0
|
||||||
|
scrollIntoView()
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
searchQuery = lastSearch
|
||||||
|
})
|
||||||
|
|
||||||
|
async function createOrOpenNote(item: ResultNote): Promise<void> {
|
||||||
|
try {
|
||||||
|
const file = await $plugin.app.vault.create(
|
||||||
|
searchQuery + ".md",
|
||||||
|
"# " + searchQuery
|
||||||
|
)
|
||||||
|
await $plugin.app.workspace.openLinkText(file.path, "")
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof Error && e.message === "File already exists.") {
|
||||||
|
// Open the existing file instead of creating it
|
||||||
|
await openNote(item)
|
||||||
|
} else {
|
||||||
|
console.error(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onClick() {
|
||||||
|
if (!selectedNote) return
|
||||||
|
openNote(selectedNote)
|
||||||
|
modal.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onInputEnter(): void {
|
||||||
|
// console.log(event.detail)
|
||||||
|
if (!selectedNote) return
|
||||||
|
openNote(selectedNote)
|
||||||
|
modal.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onInputCtrlEnter(): void {
|
||||||
|
if (!selectedNote) return
|
||||||
|
openNote(selectedNote, true)
|
||||||
|
modal.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onInputShiftEnter(): void {
|
||||||
|
if (!selectedNote) return
|
||||||
|
createOrOpenNote(selectedNote)
|
||||||
|
modal.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onInputAltEnter(): void {
|
||||||
|
if (selectedNote) {
|
||||||
|
const file = $plugin.app.vault.getAbstractFileByPath(selectedNote.path)
|
||||||
|
if (file && file instanceof TFile) {
|
||||||
|
// modal.close()
|
||||||
|
new ModalInFile($plugin, file, searchQuery, modal).open()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveIndex(dir: 1 | -1): void {
|
||||||
|
selectedIndex = loopIndex(selectedIndex + dir, resultNotes.length)
|
||||||
|
scrollIntoView()
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrollIntoView(): void {
|
||||||
|
tick().then(() => {
|
||||||
|
if (selectedNote) {
|
||||||
|
const elem = document.querySelector(
|
||||||
|
`[data-note-id="${selectedNote.path}"]`
|
||||||
|
)
|
||||||
|
elem?.scrollIntoView({ behavior: "auto", block: "nearest" })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="modal-title">Omnisearch - Vault</div>
|
||||||
|
<CmpInput
|
||||||
|
value={lastSearch}
|
||||||
|
on:input={(e) => (searchQuery = e.detail)}
|
||||||
|
on:enter={onInputEnter}
|
||||||
|
on:shift-enter={onInputShiftEnter}
|
||||||
|
on:ctrl-enter={onInputCtrlEnter}
|
||||||
|
on:alt-enter={onInputAltEnter}
|
||||||
|
on:arrow-up={() => moveIndex(-1)}
|
||||||
|
on:arrow-down={() => moveIndex(1)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="prompt-results">
|
||||||
|
{#each resultNotes as result, i}
|
||||||
|
<CmpResultNote
|
||||||
|
selected={i === selectedIndex}
|
||||||
|
note={result}
|
||||||
|
on:hover={(e) => (selectedIndex = i)}
|
||||||
|
on:click={onClick}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
{#if !resultNotes.length && searchQuery}
|
||||||
|
<center> We found 0 result for your search here. </center>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="prompt-instructions">
|
||||||
|
<div class="prompt-instruction">
|
||||||
|
<span class="prompt-instruction-command">↑↓</span><span>to navigate</span>
|
||||||
|
</div>
|
||||||
|
<div class="prompt-instruction">
|
||||||
|
<span class="prompt-instruction-command">alt ↵</span>
|
||||||
|
<span>to expand in-note results</span>
|
||||||
|
</div>
|
||||||
|
<br />
|
||||||
|
<div class="prompt-instruction">
|
||||||
|
<span class="prompt-instruction-command">↵</span><span>to open</span>
|
||||||
|
</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">
|
||||||
|
<span class="prompt-instruction-command">esc</span><span>to dismiss</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
38
src/CmpResultInFile.svelte
Normal file
38
src/CmpResultInFile.svelte
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { createEventDispatcher } from "svelte"
|
||||||
|
import { excerptAfter, excerptBefore, type ResultNote } from "./globals"
|
||||||
|
import { escapeHTML, highlighter, stringsToRegex } from "./utils"
|
||||||
|
|
||||||
|
const dispatch = createEventDispatcher()
|
||||||
|
export let offset: number
|
||||||
|
export let note: ResultNote
|
||||||
|
export let index = 0
|
||||||
|
export let selected = false
|
||||||
|
|
||||||
|
$: reg = stringsToRegex(note.foundWords)
|
||||||
|
|
||||||
|
function cleanContent(content: string): string {
|
||||||
|
const pos = offset ?? -1
|
||||||
|
if (pos > -1) {
|
||||||
|
const from = Math.max(0, pos - excerptBefore)
|
||||||
|
const to = Math.min(content.length - 1, pos + excerptAfter)
|
||||||
|
content =
|
||||||
|
(from > 0 ? "…" : "") +
|
||||||
|
content.slice(from, to).trim() +
|
||||||
|
(to < content.length - 1 ? "…" : "")
|
||||||
|
}
|
||||||
|
return escapeHTML(content)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<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">
|
||||||
|
{@html cleanContent(note?.content ?? "").replace(reg, highlighter)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -1,28 +1,22 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { ResultNote } from "./globals"
|
import { createEventDispatcher } from "svelte"
|
||||||
import { openNote } from "./notes"
|
import { excerptAfter, excerptBefore, type ResultNote } from "./globals"
|
||||||
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
|
||||||
if (pos > -1) {
|
if (pos > -1) {
|
||||||
const surroundLen = 180
|
const from = Math.max(0, pos - excerptBefore)
|
||||||
const from = Math.max(0, pos - surroundLen)
|
const to = Math.min(content.length - 1, pos + excerptAfter)
|
||||||
const to = Math.min(content.length - 1, pos + surroundLen)
|
|
||||||
content =
|
content =
|
||||||
(from > 0 ? "…" : "") +
|
(from > 0 ? "…" : "") +
|
||||||
content.slice(from, to).trim() +
|
content.slice(from, to).trim() +
|
||||||
@@ -30,30 +24,16 @@ 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}
|
{@html note.basename}
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
import type { SearchResult } from 'minisearch'
|
|
||||||
|
|
||||||
// Matches a wikiling that begins a string
|
// Matches a wikiling that begins a string
|
||||||
export const regexWikilink = /^!?\[\[(?<name>.+?)(\|(?<alias>.+?))?\]\]/
|
export const regexWikilink = /^!?\[\[(?<name>.+?)(\|(?<alias>.+?))?\]\]/
|
||||||
export const regexLineSplit = /\r?\n|\r|((\.|\?|!)( |\r?\n|\r))/g
|
export const regexLineSplit = /\r?\n|\r|((\.|\?|!)( |\r?\n|\r))/g
|
||||||
export const regexYaml = /^---\s*\n(.*?)\n?^---\s?/ms
|
export const regexYaml = /^---\s*\n(.*?)\n?^---\s?/ms
|
||||||
|
|
||||||
|
export const excerptBefore = 100
|
||||||
|
export const excerptAfter = 180
|
||||||
|
|
||||||
|
export const highlightClass = 'suggestion-highlight omnisearch-highlight'
|
||||||
|
|
||||||
export type SearchNote = {
|
export type SearchNote = {
|
||||||
path: string
|
path: string
|
||||||
basename: string
|
basename: string
|
||||||
@@ -29,11 +32,13 @@ export const isSearchMatch = (o: { offset?: number }): o is SearchMatch => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type ResultNote = {
|
export type ResultNote = {
|
||||||
// searchResult: SearchResult
|
score: number
|
||||||
path: string
|
path: string
|
||||||
basename: string
|
basename: string
|
||||||
content: string
|
content: string
|
||||||
foundWords: string[]
|
foundWords: string[]
|
||||||
matches: SearchMatch[]
|
matches: SearchMatch[]
|
||||||
occurence: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const SPACE_OR_PUNCTUATION =
|
||||||
|
/[|\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u
|
||||||
|
|||||||
32
src/main.ts
32
src/main.ts
@@ -1,26 +1,38 @@
|
|||||||
import { Plugin, TFile } from 'obsidian'
|
import { MarkdownView, Plugin, TFile } from 'obsidian'
|
||||||
import { OmnisearchModal } from './modal'
|
|
||||||
import { plugin } from './stores'
|
import { plugin } from './stores'
|
||||||
import {
|
import {
|
||||||
addToIndex,
|
addToIndex,
|
||||||
instantiateMinisearch,
|
initGlobalSearchIndex,
|
||||||
removeFromIndex,
|
removeFromIndex,
|
||||||
removeFromIndexByPath,
|
removeFromIndexByPath,
|
||||||
} from './search'
|
} from './search'
|
||||||
|
import { ModalInFile, ModalVault } from './modal'
|
||||||
|
|
||||||
export default class OmnisearchPlugin extends Plugin {
|
export default class OmnisearchPlugin extends Plugin {
|
||||||
async onload(): Promise<void> {
|
async onload(): Promise<void> {
|
||||||
plugin.set(this)
|
plugin.set(this)
|
||||||
|
|
||||||
await instantiateMinisearch()
|
// Commands to display Omnisearch modals
|
||||||
|
|
||||||
// Commands to display Omnisearch modal
|
|
||||||
this.addCommand({
|
this.addCommand({
|
||||||
id: 'show-modal',
|
id: 'show-modal',
|
||||||
name: 'Open Omnisearch',
|
name: 'Vault search',
|
||||||
// hotkeys: [{ modifiers: ['Mod'], key: 'o' }],
|
|
||||||
callback: () => {
|
callback: () => {
|
||||||
new OmnisearchModal(this).open()
|
new ModalVault(this).open()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
this.addCommand({
|
||||||
|
id: 'show-modal-infile',
|
||||||
|
name: 'In-file search',
|
||||||
|
checkCallback: (checking: boolean) => {
|
||||||
|
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
|
||||||
|
if (view) {
|
||||||
|
if (!checking) {
|
||||||
|
new ModalInFile(this, view.file).open()
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -49,5 +61,7 @@ export default class OmnisearchPlugin extends Plugin {
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
initGlobalSearchIndex()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
55
src/modal.ts
55
src/modal.ts
@@ -1,18 +1,59 @@
|
|||||||
import { Modal } from 'obsidian'
|
import { Modal, TFile } from 'obsidian'
|
||||||
import type OmnisearchPlugin from './main'
|
import type OmnisearchPlugin from './main'
|
||||||
import CmpModal from './CmpModal.svelte'
|
import CmpModalVault from './CmpModalVault.svelte'
|
||||||
import { modal } from './stores'
|
import CmpModalInFile from './CmpModalInFile.svelte'
|
||||||
|
|
||||||
export class OmnisearchModal extends Modal {
|
abstract class ModalOmnisearch extends Modal {
|
||||||
constructor(plugin: OmnisearchPlugin) {
|
constructor(plugin: OmnisearchPlugin) {
|
||||||
super(plugin.app)
|
super(plugin.app)
|
||||||
|
|
||||||
|
// Remove all the default modal's children (except the close button)
|
||||||
|
// so that we can more easily customize it
|
||||||
|
const closeEl = this.containerEl.find('.modal-close-button')
|
||||||
|
this.modalEl.replaceChildren()
|
||||||
|
this.modalEl.append(closeEl)
|
||||||
this.modalEl.addClass('omnisearch-modal', 'prompt')
|
this.modalEl.addClass('omnisearch-modal', 'prompt')
|
||||||
this.modalEl.replaceChildren() // Remove all the default Modal's children
|
}
|
||||||
|
}
|
||||||
|
|
||||||
modal.set(this)
|
export class ModalVault extends ModalOmnisearch {
|
||||||
|
constructor(plugin: OmnisearchPlugin) {
|
||||||
|
super(plugin)
|
||||||
|
|
||||||
new CmpModal({
|
new CmpModalVault({
|
||||||
target: this.modalEl,
|
target: this.modalEl,
|
||||||
|
props: {
|
||||||
|
modal: this,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ModalInFile extends ModalOmnisearch {
|
||||||
|
constructor(
|
||||||
|
plugin: OmnisearchPlugin,
|
||||||
|
file: TFile,
|
||||||
|
searchQuery: string = '',
|
||||||
|
parent?: ModalOmnisearch,
|
||||||
|
) {
|
||||||
|
super(plugin)
|
||||||
|
|
||||||
|
if (parent) {
|
||||||
|
// Hide the parent modal
|
||||||
|
parent.containerEl.toggleVisibility(false)
|
||||||
|
this.onClose = () => {
|
||||||
|
parent.containerEl.toggleVisibility(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new CmpModalInFile({
|
||||||
|
target: this.modalEl,
|
||||||
|
props: {
|
||||||
|
modal: this,
|
||||||
|
singleFilePath: file.path,
|
||||||
|
parent: parent,
|
||||||
|
searchQuery,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
148
src/search.ts
148
src/search.ts
@@ -1,21 +1,27 @@
|
|||||||
import { Notice, TFile, type TAbstractFile } from 'obsidian'
|
import { Notice, TFile, type TAbstractFile } from 'obsidian'
|
||||||
import MiniSearch from 'minisearch'
|
import MiniSearch, { type SearchResult } from 'minisearch'
|
||||||
import type { IndexedNote, ResultNote, SearchMatch } from './globals'
|
|
||||||
import { indexedNotes, plugin } from './stores'
|
|
||||||
import { get } from 'svelte/store'
|
|
||||||
import {
|
import {
|
||||||
escapeRegex,
|
SPACE_OR_PUNCTUATION,
|
||||||
extractHeadingsFromCache,
|
type IndexedNote,
|
||||||
getAllIndices,
|
type ResultNote,
|
||||||
stringsToRegex,
|
type SearchMatch,
|
||||||
wait,
|
} from './globals'
|
||||||
} from './utils'
|
import { plugin } from './stores'
|
||||||
|
import { get } from 'svelte/store'
|
||||||
|
import { extractHeadingsFromCache, stringsToRegex, wait } from './utils'
|
||||||
|
|
||||||
let minisearch: MiniSearch<IndexedNote>
|
let minisearchInstance: MiniSearch<IndexedNote>
|
||||||
|
|
||||||
export async function instantiateMinisearch(): Promise<void> {
|
let indexedNotes: Record<string, IndexedNote> = {}
|
||||||
indexedNotes.set({})
|
|
||||||
minisearch = new MiniSearch({
|
/**
|
||||||
|
* Initializes the MiniSearch instance,
|
||||||
|
* and adds all the notes to the index
|
||||||
|
*/
|
||||||
|
export async function initGlobalSearchIndex(): Promise<void> {
|
||||||
|
indexedNotes = {}
|
||||||
|
minisearchInstance = new MiniSearch({
|
||||||
|
tokenize: text => text.split(SPACE_OR_PUNCTUATION),
|
||||||
idField: 'path',
|
idField: 'path',
|
||||||
fields: ['basename', 'content', 'headings1', 'headings2', 'headings3'],
|
fields: ['basename', 'content', 'headings1', 'headings2', 'headings3'],
|
||||||
})
|
})
|
||||||
@@ -42,21 +48,20 @@ export async function instantiateMinisearch(): Promise<void> {
|
|||||||
}ms`,
|
}ms`,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Listen to the query input to trigger a search
|
||||||
|
// subscribeToQuery()
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getMatches(text: string, reg: RegExp): SearchMatch[] {
|
/**
|
||||||
let match: RegExpExecArray | null = null
|
* Searches the index for the given query,
|
||||||
const matches: SearchMatch[] = []
|
* and returns an array of raw results
|
||||||
while ((match = reg.exec(text)) !== null) {
|
* @param query
|
||||||
const m = match[0]
|
* @returns
|
||||||
if (m) matches.push({ match: m, offset: match.index })
|
*/
|
||||||
}
|
function search(query: string): SearchResult[] {
|
||||||
return matches
|
if (!query) return []
|
||||||
}
|
return minisearchInstance.search(query, {
|
||||||
|
|
||||||
export function getSuggestions(query: string): ResultNote[] {
|
|
||||||
const results = minisearch
|
|
||||||
.search(query, {
|
|
||||||
prefix: true,
|
prefix: true,
|
||||||
fuzzy: term => (term.length > 4 ? 0.2 : false),
|
fuzzy: term => (term.length > 4 ? 0.2 : false),
|
||||||
combineWith: 'AND',
|
combineWith: 'AND',
|
||||||
@@ -67,45 +72,87 @@ export function getSuggestions(query: string): ResultNote[] {
|
|||||||
headings3: 1.1,
|
headings3: 1.1,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.sort((a, b) => b.score - a.score)
|
}
|
||||||
.slice(0, 50)
|
|
||||||
// console.log(`Omnisearch - Results for "${query}"`)
|
|
||||||
// console.log(results)
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a text against a regex, and returns the { string, offset } matches
|
||||||
|
* @param text
|
||||||
|
* @param reg
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export function getMatches(text: string, reg: RegExp): SearchMatch[] {
|
||||||
|
let match: RegExpExecArray | null = null
|
||||||
|
const matches: SearchMatch[] = []
|
||||||
|
while ((match = reg.exec(text)) !== null) {
|
||||||
|
const m = match[0]
|
||||||
|
if (m) matches.push({ match: m, offset: match.index })
|
||||||
|
}
|
||||||
|
return matches
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Searches the index, and returns an array of ResultNote objects.
|
||||||
|
* If we have the singleFile option set,
|
||||||
|
* the array contains a single result from that file
|
||||||
|
* @param query
|
||||||
|
* @param options
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export function getSuggestions(
|
||||||
|
query: string,
|
||||||
|
options?: Partial<{ singleFilePath: string | null }>,
|
||||||
|
): ResultNote[] {
|
||||||
|
// Get the raw results
|
||||||
|
let results = search(query)
|
||||||
|
if (!results.length) return []
|
||||||
|
|
||||||
|
// Either keep the 50 first results,
|
||||||
|
// or the one corresponding to `singleFile`
|
||||||
|
if (options?.singleFilePath) {
|
||||||
|
const result = results.find(r => r.id === options.singleFilePath)
|
||||||
|
if (result) results = [result]
|
||||||
|
else results = []
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
results = results.sort((a, b) => b.score - a.score).slice(0, 50)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map the raw results to get usable suggestions
|
||||||
const suggestions = results.map(result => {
|
const suggestions = results.map(result => {
|
||||||
const note = indexedNotes.get(result.id)
|
const note = indexedNotes[result.id]
|
||||||
if (!note) {
|
if (!note) {
|
||||||
throw new Error(`Note "${result.id}" not indexed`)
|
throw new Error(`Note "${result.id}" not indexed`)
|
||||||
}
|
}
|
||||||
const words = Object.keys(result.match)
|
const words = Object.keys(result.match)
|
||||||
const matches = getMatches(note.content, stringsToRegex(words))
|
const matches = getMatches(note.content, stringsToRegex(words))
|
||||||
const resultNote: ResultNote = {
|
const resultNote: ResultNote = {
|
||||||
// searchResult: result,
|
score: result.score,
|
||||||
foundWords: words,
|
foundWords: words,
|
||||||
occurence: 0,
|
|
||||||
matches,
|
matches,
|
||||||
...note,
|
...note,
|
||||||
}
|
}
|
||||||
// if (note.basename === 'Search') {
|
|
||||||
// console.log('=======')
|
|
||||||
// console.log(result)
|
|
||||||
// console.log(resultNote)
|
|
||||||
// }
|
|
||||||
return resultNote
|
return resultNote
|
||||||
})
|
})
|
||||||
|
|
||||||
return suggestions
|
return suggestions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a file to the index
|
||||||
|
* @param file
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
export async function addToIndex(file: TAbstractFile): Promise<void> {
|
export async function addToIndex(file: TAbstractFile): Promise<void> {
|
||||||
if (!(file instanceof TFile) || file.extension !== 'md') return
|
if (!(file instanceof TFile) || file.extension !== 'md') {
|
||||||
|
return
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const app = get(plugin).app
|
const app = get(plugin).app
|
||||||
// console.log(`Omnisearch - adding ${file.path} to index`)
|
// console.log(`Omnisearch - adding ${file.path} to index`)
|
||||||
const fileCache = app.metadataCache.getFileCache(file)
|
const fileCache = app.metadataCache.getFileCache(file)
|
||||||
// console.log(fileCache)
|
// console.log(fileCache)
|
||||||
|
|
||||||
if (indexedNotes.get(file.path)) {
|
if (indexedNotes[file.path]) {
|
||||||
throw new Error(`${file.basename} is already indexed`)
|
throw new Error(`${file.basename} is already indexed`)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,8 +174,8 @@ export async function addToIndex(file: TAbstractFile): Promise<void> {
|
|||||||
? extractHeadingsFromCache(fileCache, 3).join(' ')
|
? extractHeadingsFromCache(fileCache, 3).join(' ')
|
||||||
: '',
|
: '',
|
||||||
}
|
}
|
||||||
minisearch.add(note)
|
minisearchInstance.add(note)
|
||||||
indexedNotes.add(note)
|
indexedNotes[note.path] = note
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (e) {
|
||||||
console.trace('Error while indexing ' + file.basename)
|
console.trace('Error while indexing ' + file.basename)
|
||||||
@@ -136,6 +183,11 @@ export async function addToIndex(file: TAbstractFile): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes a file from the index
|
||||||
|
* @param file
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
export function removeFromIndex(file: TAbstractFile): void {
|
export function removeFromIndex(file: TAbstractFile): void {
|
||||||
if (file instanceof TFile && file.path.endsWith('.md')) {
|
if (file instanceof TFile && file.path.endsWith('.md')) {
|
||||||
// console.log(`Omnisearch - removing ${file.path} from index`)
|
// console.log(`Omnisearch - removing ${file.path} from index`)
|
||||||
@@ -143,10 +195,14 @@ export function removeFromIndex(file: TAbstractFile): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes a file from the index, by its path
|
||||||
|
* @param path
|
||||||
|
*/
|
||||||
export function removeFromIndexByPath(path: string): void {
|
export function removeFromIndexByPath(path: string): void {
|
||||||
const note = indexedNotes.get(path)
|
const note = indexedNotes[path]
|
||||||
if (note) {
|
if (note) {
|
||||||
minisearch.remove(note)
|
minisearchInstance.remove(note)
|
||||||
indexedNotes.remove(path)
|
delete indexedNotes[path]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,60 +1,7 @@
|
|||||||
import { get, writable } from 'svelte/store'
|
import { writable } from 'svelte/store'
|
||||||
import type { IndexedNote, ResultNote } from './globals'
|
|
||||||
import type OmnisearchPlugin from './main'
|
import type OmnisearchPlugin from './main'
|
||||||
import type { OmnisearchModal } from './modal'
|
|
||||||
|
|
||||||
function createIndexedNotes() {
|
/**
|
||||||
const { subscribe, set, update } = writable<Record<string, IndexedNote>>({})
|
* A reference to the plugin instance
|
||||||
return {
|
*/
|
||||||
subscribe,
|
|
||||||
set,
|
|
||||||
add(note: IndexedNote) {
|
|
||||||
update(notes => {
|
|
||||||
notes[note.path] = note
|
|
||||||
return notes
|
|
||||||
})
|
|
||||||
},
|
|
||||||
remove(path: string) {
|
|
||||||
update(notes => {
|
|
||||||
delete notes[path]
|
|
||||||
return notes
|
|
||||||
})
|
|
||||||
},
|
|
||||||
get(path: string): IndexedNote | undefined {
|
|
||||||
return get(indexedNotes)[path]
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const searchQuery = writable<string>('')
|
|
||||||
export const resultNotes = writable<ResultNote[]>([])
|
|
||||||
export const plugin = writable<OmnisearchPlugin>()
|
export const plugin = writable<OmnisearchPlugin>()
|
||||||
export const modal = writable<OmnisearchModal>()
|
|
||||||
export const selectedNote = createSelectedNote()
|
|
||||||
export const indexedNotes = createIndexedNotes()
|
|
||||||
|
|||||||
23
src/utils.ts
23
src/utils.ts
@@ -1,14 +1,14 @@
|
|||||||
import type { CachedMetadata } from 'obsidian'
|
import type { CachedMetadata } from 'obsidian'
|
||||||
import {
|
import {
|
||||||
|
highlightClass,
|
||||||
isSearchMatch,
|
isSearchMatch,
|
||||||
regexLineSplit,
|
regexLineSplit,
|
||||||
regexYaml,
|
regexYaml,
|
||||||
} from './globals'
|
} from './globals'
|
||||||
import type { SearchMatch } from './globals'
|
import type { SearchMatch } from './globals'
|
||||||
import { uniqBy } from 'lodash-es'
|
|
||||||
|
|
||||||
export function highlighter(str: string): string {
|
export function highlighter(str: string): string {
|
||||||
return '<span class="search-result-file-matched-text">' + str + '</span>'
|
return `<span class="${highlightClass}">${str}</span>`
|
||||||
}
|
}
|
||||||
|
|
||||||
export function escapeHTML(html: string): string {
|
export function escapeHTML(html: string): string {
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,5 +7,6 @@
|
|||||||
"0.1.5": "0.14.2",
|
"0.1.5": "0.14.2",
|
||||||
"0.1.6": "0.14.2",
|
"0.1.6": "0.14.2",
|
||||||
"0.1.7": "0.14.2",
|
"0.1.7": "0.14.2",
|
||||||
"0.1.8": "0.14.2"
|
"0.1.8": "0.14.2",
|
||||||
|
"0.2.0": "0.14.2"
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user