Improve IES Lighting guidelines performance (#83)

* Improved performance on the Unicode Search page:
- Created new flexSearch component (Faster than fuzzySearch). For more information, see https://github.com/nextapps-de/flexsearch
- Replaced fuzzySearch with the flexSearch component on the unicode search page
- Fixed a bug where the search limit counter didn't have any effect
- Reduced the default search limit from 100 to 40 to reduce lag from loading all the ui elements

* Added clarification to comment

* components.d.ts update

* - Replaced FuzzySearch with FlexSearch on the ISO 3166 Searcher page
- Reduced the debounce from 500ms to 250ms
- Reduced the default search limit from 100 to 20, and fixed a bug where the search limit wasn't applied when the value changed
- Added the `readonly` prop to the `input-copyable` field
- Added the `readonly` flag to all input copyable fields on the unicode search and iso 3166 searcher pages

* Fixed incorrect case usage for functions and variables

* - Replaced fuzzysearch with flexsearch on the IES Lighting Guidelines page
- Reduced the debounce from 500ms to 250ms
- Changed the search keys so all columns are now searchable

* - Added logic to sort the limited results using a similarity score created by calculating the Levenshtein distance
- Added the `shouldSort` boolean to control whether the results should be filtered by similarity. `true` by default

* Merged new changes to flexSearch

* - Added readonly flag to input copyable fields
This commit is contained in:
Dark_Phoenix_ authored and ShareVB committed 2025-06-02 16:49:00 +02:00
1 parent 8172562fe6
commit ba663a4fb1
3 files changed
+106 -18

No files matched your search

+86 -4
View File
@@ -17,7 +17,23 @@ export function useFlexSearch<Data extends Record<string, any>>({
data: Data[]
options?: {
keys: SearchKey[]
/**
* Whether to show or not show items with an empty search query. `true` won't show any items, `false` will show all items.
* @default true
*/
filterEmpty?: boolean
/**
* Whether the results should be sorted by similarity score using the Levenshtein distance.
* @default true
*/
shouldSort?: boolean
/**
* Type of tokenization logic to use (Determines how the search logic will behave).
* @default 'forward'
* @see {@link https://github.com/nextapps-de/flexsearch?tab=readme-ov-file#tokenizer-partial-match | FlexSearch Tokenizer Documentation}
*
* Note: The `'tolerant'` tokenizer option mentioned in the documentation doesn't exist anymore in the current version of FlexSearch.
*/
tokenize?: 'strict' | 'forward' | 'reverse' | 'full'
resolution?: number
optimize?: boolean
@@ -26,7 +42,7 @@ export function useFlexSearch<Data extends Record<string, any>>({
limit?: MaybeRef<number>
}) {
// Extract options
const { keys, filterEmpty = true, tokenize = 'forward', ...indexOptions } = options;
const { keys, filterEmpty = true, shouldSort = true, tokenize = 'forward', ...indexOptions } = options;
// Normalize keys to include weights
const normalizedKeys = keys.map((key) => {
@@ -115,9 +131,75 @@ export function useFlexSearch<Data extends Record<string, any>>({
// Apply limit and convert back to original items
const limitedIds = searchLimit > 0 ? sortedIds.slice(0, searchLimit) : sortedIds;
return limitedIds
.map(id => dataMap.value.get(id))
.filter(Boolean) as Data[];
// Return the limited results early if it shouldn't be sorted by similarity
if (!shouldSort) {
return limitedIds
.map(id => dataMap.value.get(id))
.filter(Boolean) as Data[];
}
// Calculate Levenshtein distance
const levenshteinDistance = (str1: string, str2: string): number => {
const matrix = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null));
for (let i = 0; i <= str1.length; i++) {
matrix[0][i] = i;
}
for (let j = 0; j <= str2.length; j++) {
matrix[j][0] = j;
}
for (let j = 1; j <= str2.length; j++) {
for (let i = 1; i <= str1.length; i++) {
const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
matrix[j][i] = Math.min(
matrix[j][i - 1] + 1, // deletion
matrix[j - 1][i] + 1, // insertion
matrix[j - 1][i - 1] + indicator, // substitution
);
}
}
return matrix[str2.length][str1.length];
};
// Calculate similarity score (0-1, where 1 is perfect match)
const calculateSimilarity = (str1: string, str2: string): number => {
const maxLength = Math.max(str1.length, str2.length);
if (maxLength === 0) {
return 1;
}
const distance = levenshteinDistance(str1.toLowerCase(), str2.toLowerCase());
return 1 - (distance / maxLength);
};
// Sort limited results by similarity score
const sortedResults = limitedIds
.map((id) => {
const item = dataMap.value.get(id);
if (!item) {
return null;
}
// Calculate best similarity score across all searchable fields
const similarities = normalizedKeys.map(({ name }) => {
const value = name.split('.').reduce((obj, path) => obj?.[path], item);
return value ? calculateSimilarity(query, String(value)) : 0;
});
const bestSimilarity = Math.max(...similarities);
return {
item,
similarity: bestSimilarity,
};
})
.filter(Boolean)
.sort((a, b) => b!.similarity - a!.similarity)
.map(result => result!.item);
return sortedResults as Data[];
};
// Computed results
@@ -1,20 +1,16 @@
<script setup lang="ts">
import iesData from './ies-lighting-data.json';
import { useFuzzySearch } from '@/composable/fuzzySearch';
import useDebouncedRef from '@/composable/debouncedref';
import { useFlexSearch } from '@/composable/flexSearch';
const data = iesData.map(i => ({ ...i, all: `${i.industryType} - ${i.industryApplication}` }));
const searchQuery = useDebouncedRef('', 500);
const data = iesData;
const searchQuery = useDebouncedRef('', 250);
const { searchResult } = useFuzzySearch({
const { searchResult } = useFlexSearch({
search: searchQuery,
data,
options: {
keys: ['all'],
threshold: 0.2,
isCaseSensitive: false,
minMatchCharLength: 3,
useExtendedSearch: true,
keys: ['industryType', 'industryApplication', 'footCandlesRange', 'recommendedLighting'],
filterEmpty: false,
},
});
@@ -25,7 +21,7 @@ const { searchResult } = useFuzzySearch({
<div flex items-center gap-3>
<c-input-text
v-model:value="searchQuery"
placeholder="Search IES recommandation by industry or application"
placeholder="Search IES recommendation by industry or application"
mx-auto max-w-600px
>
<template #prefix>
@@ -64,16 +60,16 @@ const { searchResult } = useFuzzySearch({
<tbody>
<tr v-for="(result, ix) in searchResult" :key="ix">
<td>
<input-copyable :value="result.industryType" />
<input-copyable :readonly="true" :value="result.industryType" />
</td>
<td>
<input-copyable :value="result.industryApplication" />
<input-copyable :readonly="true" :value="result.industryApplication" />
</td>
<td>
<input-copyable :value="result.footCandlesRange" />
<input-copyable :readonly="true" :value="result.footCandlesRange" />
</td>
<td>
<input-copyable :value="result.recommendedLighting" />
<input-copyable :readonly="true" :value="result.recommendedLighting" />
</td>
</tr>
</tbody>