Skip to content
Open
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
13 changes: 8 additions & 5 deletions src/lib/searchHistory.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,22 @@ class SearchHistory {
/**
* Add item to history
* @param {string} item Item to add
* @param {object} [options]
* @param {boolean} [options.preserveWhitespace=false] Keep leading and trailing whitespace
*/
addToHistory(item) {
if (!item || typeof item !== "string" || item.trim().length === 0) {
addToHistory(item, { preserveWhitespace = false } = {}) {
if (typeof item !== "string") {
return;
}

const trimmedItem = item.trim();
const historyItem = preserveWhitespace ? item : item.trim();
if (!historyItem.length) return;

// Remove existing item if present
this.history = this.history.filter((h) => h !== trimmedItem);
this.history = this.history.filter((h) => h !== historyItem);

// Add to beginning
this.history.unshift(trimmedItem);
this.history.unshift(historyItem);

// Limit history size
this.history = this.history.slice(0, MAX_HISTORY_ITEMS);
Expand Down
146 changes: 144 additions & 2 deletions src/sidebarApps/searchInFiles/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import autosize from "autosize";
import { getDocText } from "cm/editorUtils";
import Checkbox from "components/checkbox";
import Sidebar, { preventSlide } from "components/sidebar";
import select from "dialogs/select";
import escapeStringRegexp from "escape-string-regexp";
import Reactive from "html-tag-js/reactive";
import Ref from "html-tag-js/ref";
import fileIndex from "lib/fileIndex";
import files, { Tree, whenReady as waitForFileList } from "lib/fileList";
import openFile from "lib/openFile";
import { addedFolder } from "lib/openFolder";
import searchHistory from "lib/searchHistory";
import settings from "lib/settings";
import helpers from "utils/helpers";
import { createSearchResultView } from "./cmResultView";
Expand All @@ -35,6 +37,8 @@ const $include = Ref();
const $wholeWord = Ref();
const $caseSensitive = Ref();
const $useIndex = Ref();
const $btnSearchHistory = Ref();
const $btnReplaceHistory = Ref();
const $btnReplaceAll = Ref();
const $resultOverview = Ref();
const $resultHeader = Ref();
Expand Down Expand Up @@ -128,6 +132,7 @@ let pendingNativeSearchFinishVersion = null;
let nativeSearchId = null;
let activeSearchTasks = 0;
let activeReplaceTasks = 0;
let applyingHistoryPattern = false;

addEventListener($regExp, "change", onInput);
addEventListener($wholeWord, "change", onInput);
Expand All @@ -136,6 +141,12 @@ addEventListener($useIndex, "change", onInput);
addEventListener($search, "input", onInput);
addEventListener($include, "input", onInput);
addEventListener($exclude, "input", onInput);
addEventListener($btnSearchHistory, "click", () =>
openPatternHistory($search, strings["search"]),
);
addEventListener($btnReplaceHistory, "click", () =>
openPatternHistory($replace, strings["replace"]),
);
addEventListener($btnReplaceAll, "click", replaceAll);

files.on("push-file", () => {
Expand Down Expand Up @@ -257,7 +268,16 @@ export default [
type="search"
name="search"
placeholder={strings["search"]}
onchange={rememberSearchPattern}
oninput={onSearchPatternInput}
onkeydown={onSearchHistoryKeydown}
/>
<button
ref={$btnSearchHistory}
type="button"
className="icon historyrestore history-button"
title={strings["search"]}
></button>
</div>

<div className="replace-row">
Expand All @@ -266,7 +286,16 @@ export default [
type="search"
name="replace"
placeholder={strings["replace"]}
onchange={rememberReplacePattern}
oninput={onReplacePatternInput}
onkeydown={onReplaceHistoryKeydown}
/>
<button
ref={$btnReplaceHistory}
type="button"
className="icon historyrestore history-button"
title={strings["replace"]}
></button>
<button
ref={$btnReplaceAll}
className="icon replace_all"
Expand Down Expand Up @@ -309,6 +338,107 @@ export default [
() => {},
];

function rememberSearchPattern() {
searchHistory.addToHistory($search.value, { preserveWhitespace: true });
searchHistory.resetSearchNavigation();
}

function rememberReplacePattern() {
searchHistory.addToHistory($replace.value, { preserveWhitespace: true });
searchHistory.resetReplaceNavigation();
}

function onSearchPatternInput() {
if (!applyingHistoryPattern) searchHistory.resetSearchNavigation();
}

function onReplacePatternInput() {
if (!applyingHistoryPattern) searchHistory.resetReplaceNavigation();
}

function setPatternFromHistory(ref, value) {
if (value === undefined) return;
ref.el.value = value;
applyingHistoryPattern = true;
try {
ref.el.dispatchEvent(new Event("input", { bubbles: true }));
} finally {
applyingHistoryPattern = false;
}
ref.el.focus();
}

function escapePatternHtml(pattern) {
return pattern
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}

async function openPatternHistory(ref, title) {
const history = searchHistory.getHistory();
if (!history.length) return;

try {
const items = history.map((pattern) => ({
value: pattern,
text: escapePatternHtml(pattern),
}));
const value = await select(title, items, true);
setPatternFromHistory(ref, value);
} catch (_) {
// The history picker was dismissed.
}
}

function onSearchHistoryKeydown(event) {
if (event.key === "ArrowUp" && !$search.value.includes("\n")) {
event.preventDefault();
setPatternFromHistory(
$search,
searchHistory.navigateSearchUp($search.value),
);
} else if (event.key === "ArrowDown" && !$search.value.includes("\n")) {
event.preventDefault();
setPatternFromHistory(
$search,
searchHistory.navigateSearchDown($search.value),
);
} else if (event.key === "Escape") {
searchHistory.resetSearchNavigation();
} else if (
event.key.length === 1 ||
["Backspace", "Delete"].includes(event.key)
) {
searchHistory.resetSearchNavigation();
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}
}

function onReplaceHistoryKeydown(event) {
if (event.key === "ArrowUp" && !$replace.value.includes("\n")) {
event.preventDefault();
setPatternFromHistory(
$replace,
searchHistory.navigateReplaceUp($replace.value),
);
} else if (event.key === "ArrowDown" && !$replace.value.includes("\n")) {
event.preventDefault();
setPatternFromHistory(
$replace,
searchHistory.navigateReplaceDown($replace.value),
);
} else if (event.key === "Escape") {
searchHistory.resetReplaceNavigation();
} else if (
event.key.length === 1 ||
["Backspace", "Delete"].includes(event.key)
) {
searchHistory.resetReplaceNavigation();
}
}

/**
* Worker message handler
* @param {Event} e
Expand Down Expand Up @@ -939,6 +1069,8 @@ async function replaceAll() {
if (!search) return;
const regex = toRegex(search, options);
if (!regex) return;
searchHistory.addToHistory(search, { preserveWhitespace: true });
searchHistory.addToHistory(replace, { preserveWhitespace: true });

replacing = true;
activeReplaceTasks = 0;
Expand Down Expand Up @@ -1120,11 +1252,21 @@ function searchResultText(files, matches) {
* @param {string} param0.name
* @param {string} param0.placeholder
* @param {Ref} param0.ref
* @param {Function} [param0.onchange]
* @param {Function} [param0.oninput]
* @param {Function} [param0.onkeydown]
* @returns {HTMLTextAreaElement}
*/
function Textarea({ name, placeholder, ref }) {
function Textarea({ name, placeholder, ref, onchange, oninput, onkeydown }) {
return autosize(
<textarea ref={ref} name={name} placeholder={placeholder}></textarea>,
<textarea
ref={ref}
name={name}
placeholder={placeholder}
onchange={onchange}
oninput={oninput}
onkeydown={onkeydown}
></textarea>,
);
}

Expand Down
15 changes: 15 additions & 0 deletions src/sidebarApps/searchInFiles/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,21 @@
overflow-x: auto !important;
font-size: 0.85rem;
}

.history-button {
flex: 0 0 auto;
border: 0;
background: transparent;
color: var(--primary-text-color);
cursor: pointer;
padding: 4px;
border-radius: 4px;
font-size: 1.1rem;

&:hover {
background-color: var(--secondary-color);
}
}
}

.replace-row {
Expand Down
44 changes: 44 additions & 0 deletions tests/unit/searchHistory.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { readFileSync } from "node:fs";
import vm from "node:vm";
import { describe, expect, it, vi } from "vitest";

const source = readFileSync(
`${process.cwd()}/src/lib/searchHistory.js`,
"utf8",
);

function createHistory() {
const localStorage = {
getItem: vi.fn(() => null),
setItem: vi.fn(),
};
const context = vm.createContext({ console, localStorage });
vm.runInContext(source.slice(0, source.indexOf("export default")), context);
return {
context,
localStorage,
history: vm.runInContext("new SearchHistory()", context),
};
}

describe("search history", () => {
it("preserves exact patterns when requested", () => {
const { history, localStorage } = createHistory();

history.addToHistory(" foo\nbar ", { preserveWhitespace: true });

expect(history.getHistory()).toEqual([" foo\nbar "]);
expect(localStorage.setItem).toHaveBeenCalledWith(
"acode.searchreplace.history",
JSON.stringify([" foo\nbar "]),
);
});

it("retains trimmed history as the default behavior", () => {
const { history } = createHistory();

history.addToHistory(" foo ");

expect(history.getHistory()).toEqual(["foo"]);
});
});
Loading
Loading