From 8f896d387c4bb7ce85425637efefd40bde15b437 Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Wed, 3 Jan 2024 00:42:47 +0530 Subject: [PATCH] move escape regexp to shared --- .../theme-default/components/VPLocalSearchBox.vue | 11 ++++------- src/node/build/bundle.ts | 6 +----- src/shared/shared.ts | 5 +++++ 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/client/theme-default/components/VPLocalSearchBox.vue b/src/client/theme-default/components/VPLocalSearchBox.vue index 2f49250c..965ab1df 100644 --- a/src/client/theme-default/components/VPLocalSearchBox.vue +++ b/src/client/theme-default/components/VPLocalSearchBox.vue @@ -28,6 +28,7 @@ import { } from 'vue' import type { ModalTranslations } from '../../../../types/local-search' import { pathToFile } from '../../app/utils' +import { escapeRegExp } from '../../shared' import { useData } from '../composables/data' import { LRUCache } from '../support/lru' import { createSearchTranslate } from '../support/translation' @@ -146,8 +147,8 @@ const cache = new LRUCache>(16) // 16 files debouncedWatch( () => [searchIndex.value, filterText.value, showDetailedList.value] as const, async ([index, filterTextValue, showDetailedListValue], old, onCleanup) => { - - if (old?.[0] !== index) { // in case of hmr + if (old?.[0] !== index) { + // in case of hmr cache.clear() } @@ -396,11 +397,7 @@ function formMarkRegex(terms: Set) { return new RegExp( [...terms] .sort((a, b) => b.length - a.length) - .map((term) => { - return `(${term - .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') - .replace(/-/g, '\\x2d')})` - }) + .map((term) => `(${escapeRegExp(term)})`) .join('|'), 'gi' ) diff --git a/src/node/build/bundle.ts b/src/node/build/bundle.ts index 3a7a983c..aabfe3e4 100644 --- a/src/node/build/bundle.ts +++ b/src/node/build/bundle.ts @@ -11,7 +11,7 @@ import { import { APP_PATH } from '../alias' import type { SiteConfig } from '../config' import { createVitePressPlugin } from '../plugin' -import { sanitizeFileName, slash } from '../shared' +import { escapeRegExp, sanitizeFileName, slash } from '../shared' import { task } from '../utils/task' import { buildMPAClient } from './buildMPAClient' @@ -257,7 +257,3 @@ function staticImportedByEntry( cache.set(id, someImporterIs) return someImporterIs } - -function escapeRegExp(str: string) { - return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d') -} diff --git a/src/shared/shared.ts b/src/shared/shared.ts index 44f562a9..8c8e4884 100644 --- a/src/shared/shared.ts +++ b/src/shared/shared.ts @@ -195,3 +195,8 @@ export function treatAsHtml(filename: string): boolean { return ext == null || !KNOWN_EXTENSIONS.has(ext.toLowerCase()) } + +// https://github.com/sindresorhus/escape-string-regexp/blob/ba9a4473850cb367936417e97f1f2191b7cc67dd/index.js +export function escapeRegExp(str: string) { + return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d') +}