Improved iso 3166 searcher page performance (#79)

* 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
This commit is contained in:
Dark_Phoenix_ authored and ShareVB committed 2025-06-08 11:09:47 +02:00
1 parent 8decf33ec8
commit 226081db3a
4 files changed
+213 -103

No files matched your search

+2
View File
@@ -7,6 +7,7 @@ const props = defineProps<{
multiline?: boolean multiline?: boolean
rows?: number | string rows?: number | string
autosize?: boolean autosize?: boolean
readonly?: boolean
}>(); }>();
const emit = defineEmits(['update:value']); const emit = defineEmits(['update:value']);
@@ -21,6 +22,7 @@ const tooltipText = computed(() => isJustCopied.value ? 'Copied!' : 'Copy to cli
:multiline="multiline" :multiline="multiline"
:rows="rows" :rows="rows"
:autosize="autosize" :autosize="autosize"
:readonly="readonly"
> >
<template #suffix> <template #suffix>
<c-tooltip :tooltip="tooltipText"> <c-tooltip :tooltip="tooltipText">
+72 -50
View File
@@ -2,6 +2,9 @@ import { type MaybeRef, get } from '@vueuse/core';
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import FlexSearch from 'flexsearch'; import FlexSearch from 'flexsearch';
// Define key types to match Fuse.js format
type SearchKey = string | { name: string; weight?: number };
export function useFlexSearch<Data extends Record<string, any>>({ export function useFlexSearch<Data extends Record<string, any>>({
search, search,
data, data,
@@ -13,7 +16,7 @@ export function useFlexSearch<Data extends Record<string, any>>({
search: MaybeRef<string> search: MaybeRef<string>
data: Data[] data: Data[]
options?: { options?: {
keys: string[] keys: SearchKey[]
filterEmpty?: boolean filterEmpty?: boolean
tokenize?: 'strict' | 'forward' | 'reverse' | 'full' tokenize?: 'strict' | 'forward' | 'reverse' | 'full'
resolution?: number resolution?: number
@@ -23,96 +26,115 @@ export function useFlexSearch<Data extends Record<string, any>>({
limit?: MaybeRef<number> limit?: MaybeRef<number>
}) { }) {
// Extract options // Extract options
const { keys, filterEmpty = true, ...indexOptions } = options; const { keys, filterEmpty = true, tokenize = 'forward', ...indexOptions } = options;
// Create a map to store original data items // Normalize keys to include weights
const data_map = ref(new Map<number, Data>()); const normalizedKeys = keys.map((key) => {
if (typeof key === 'string') {
// Create separate indices for each key return { name: key, weight: 1 };
const indices = keys.map((key) => { }
return { return { name: key.name, weight: key.weight ?? 1 };
key,
index: new FlexSearch.Index({
tokenize: 'forward',
preset: 'performance',
resolution: 9,
optimize: true,
cache: 100,
fastupdate: true,
...indexOptions,
}),
};
}); });
// Helper to get unique key for each item (prefer 'id', fallback to index)
const getItemKey = (item: Data, idx: number) => (item.id !== undefined ? item.id : idx);
// Map to store original data items by unique key
const dataMap = ref(new Map<any, Data>());
// Create separate indices for each key with weight info
const indices = normalizedKeys.map(({ name, weight }) => ({
key: name,
weight,
index: new FlexSearch.Index({
tokenize,
preset: 'performance',
resolution: 9,
optimize: true,
cache: 100,
fastupdate: true,
...indexOptions,
}),
}));
// Initialize indices with data // Initialize indices with data
const initialize_indices = () => { const initializeIndices = () => {
data_map.value.clear(); dataMap.value.clear();
indices.forEach(({ index }) => index.clear());
data.forEach((item, idx) => { data.forEach((item, idx) => {
// Store original item const itemKey = getItemKey(item, idx);
data_map.value.set(idx, item); dataMap.value.set(itemKey, item);
// Add to each field index
indices.forEach(({ key, index }) => { indices.forEach(({ key, index }) => {
// Get the value for this key, potentially from nested paths // Support nested keys (e.g., 'foo.bar')
const value = key.split('.').reduce((obj, path) => obj?.[path], item); const value = key.split('.').reduce((obj, path) => obj?.[path], item);
if (value) { if (value) {
index.add(idx, String(value)); index.add(itemKey, String(value));
} }
}); });
}); });
}; };
// Initialize on creation // Initialize on creation
initialize_indices(); initializeIndices();
// Function to search across all indices // Watch for data changes (deep watch for array content)
const search_all_indices = (query: string, search_limit: number) => { watch(
() => data,
initializeIndices,
{ deep: true },
);
// Function to search across all indices with weight consideration
const searchAllIndices = (query: string, searchLimit: number) => {
if (!query) { if (!query) {
return []; return [];
} }
// Use a higher individual limit for each index to ensure we don't miss potential matches // Use a higher individual limit for each index to ensure we don't miss potential matches
const individual_limit = search_limit > 0 ? search_limit * 2 : undefined; const individualLimit = searchLimit > 0 ? searchLimit * 2 : undefined;
// Search each index // Search each index and collect results with weights
const result_sets = indices.map(({ index }) => const weightedResults = new Map<any, number>();
index.search(query, individual_limit ? { limit: individual_limit } : undefined),
);
// Combine and deduplicate results indices.forEach(({ index, weight }) => {
const unique_ids = new Set<number>(); const results = index.search(query, individualLimit ? { limit: individualLimit } : undefined);
result_sets.forEach((results) => {
results.forEach(id => unique_ids.add(id as number)); results.forEach((id) => {
const currentScore = weightedResults.get(id) || 0;
weightedResults.set(id, currentScore + weight);
});
}); });
// Convert back to array of original items // Sort by weight (higher weight = better match) and convert to array
const result_array = Array.from(unique_ids) const sortedIds = Array.from(weightedResults.entries())
.map(id => data_map.value.get(id)) .sort((a, b) => b[1] - a[1])
.map(([id]) => id);
// 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[]; .filter(Boolean) as Data[];
// Apply the limit to the final combined results
return search_limit > 0 ? result_array.slice(0, search_limit) : result_array;
}; };
// Watch for data changes to rebuild indices
watch(() => data.length, initialize_indices);
// Computed results // Computed results
const searchResult = computed<Data[]>(() => { const searchResult = computed<Data[]>(() => {
const query = get(search); const query = get(search);
const search_limit: number = get(limit); const searchLimit: number = get(limit);
// Handle empty query case // Handle empty query case
if (!query && !filterEmpty) { if (!query && !filterEmpty) {
return search_limit > 0 ? data.slice(0, search_limit) : data; return searchLimit > 0 ? data.slice(0, searchLimit) : data;
} }
if (!query) { if (!query) {
return []; return [];
} }
return search_all_indices(query, search_limit); return searchAllIndices(query, searchLimit);
}); });
return { searchResult }; return { searchResult };
+132 -46
View File
@@ -1,30 +1,19 @@
<script setup lang="ts"> <script setup lang="ts">
import CountriesDB from 'countries-db'; import CountriesDB from 'countries-db';
import ISO6391 from 'iso-639-1'; import ISO6391 from 'iso-639-1';
import { useFuzzySearch } from '@/composable/fuzzySearch';
import useDebouncedRef from '@/composable/debouncedref'; import useDebouncedRef from '@/composable/debouncedref';
import { useFlexSearch } from '@/composable/flexSearch';
const searchQuery = useDebouncedRef('', 500); const searchQuery = useDebouncedRef('', 250);
const countriesSearchData = Object.entries(CountriesDB.getAllCountries()).map(([_, info]) => { const countriesSearchData = Object.values(CountriesDB.getAllCountries());
return { const limit = ref(20);
iso2: info.iso2, const { searchResult } = useFlexSearch({
iso3: info.iso3,
domain: info.domain,
name: `${info.name} ${info.officialName}`,
info,
};
});
const limit = ref(100);
const { searchResult } = useFuzzySearch({
search: searchQuery, search: searchQuery,
data: countriesSearchData, data: countriesSearchData,
options: { options: {
keys: ['name', { name: 'iso3', weight: 3 }, { name: 'iso2', weight: 2 }, 'domain'], keys: ['name', { name: 'iso3', weight: 3 }, { name: 'iso2', weight: 2 }, 'domain'],
threshold: 0.3,
isCaseSensitive: false,
useExtendedSearch: true,
}, },
limit: limit.value, limit,
}); });
function langToName(code: string) { function langToName(code: string) {
@@ -39,10 +28,7 @@ function langToName(code: string) {
<template> <template>
<div mx-auto max-w-2400px important:flex-1> <div mx-auto max-w-2400px important:flex-1>
<div mx-auto max-w-600px flex justify-center gap-3> <div mx-auto max-w-600px flex justify-center gap-3>
<c-input-text <c-input-text v-model:value="searchQuery" placeholder="Search Countries by name, iso2, iso3...">
v-model:value="searchQuery"
placeholder="Search Countries by name, iso2, iso3..."
>
<template #prefix> <template #prefix>
<icon-mdi-search mr-6px color-black op-70 dark:color-white /> <icon-mdi-search mr-6px color-black op-70 dark:color-white />
</template> </template>
@@ -53,12 +39,7 @@ function langToName(code: string) {
</div> </div>
<div v-if="searchQuery.trim().length > 0"> <div v-if="searchQuery.trim().length > 0">
<div <div v-if="searchResult.length === 0" mt-4 text-20px font-bold>
v-if="searchResult.length === 0"
mt-4
text-20px
font-bold
>
No results No results
</div> </div>
@@ -75,27 +56,132 @@ function langToName(code: string) {
<tbody> <tbody>
<tr v-for="(result, ix) in searchResult" :key="ix"> <tr v-for="(result, ix) in searchResult" :key="ix">
<td style="vertical-align: top"> <td style="vertical-align: top">
<input-copyable :value="result.iso2" /> <input-copyable :value="result.iso2" :readonly="true" />
<input-copyable :value="result.iso3" /> <input-copyable :value="result.iso3" :readonly="true" />
</td> </td>
<td> <td>
<input-copyable label-width="150px" label="Name" label-position="left" :value="result.name" mb-1 /> <input-copyable label-width="150px" label="Name" label-position="left" :value="result.name" :readonly="true" mb-1 />
<input-copyable label-width="150px" label="Official Name" label-position="left" :value="result.info.officialName" mb-1 /> <input-copyable
<input-copyable label-width="150px" label="Domain" label-position="left" :value="result.info.domain" mb-1 /> label-width="150px"
<input-copyable label-width="150px" label="Emoji" label-position="left" :value="`${result.info.emoji} (${result.info.emojiUnicode})`" mb-1 /> label="Official Name"
<input-copyable label-width="150px" label="ISO Num" label-position="left" :value="result.info.isoNumeric" mb-1 /> label-position="left"
<input-copyable label-width="150px" label="Continent" label-position="left" :value="result.info.continentId" mb-1 /> :value="result.officialName"
<input-copyable label-width="150px" label="Elevation (m)" label-position="left" :value="result.info.elevation" mb-1 /> :readonly="true"
<input-copyable label-width="150px" label="Population" label-position="left" :value="result.info.population" mb-1 /> mb-1
<input-copyable label-width="150px" label="Area (km²)" label-position="left" :value="result.info.areaSqKm" mb-1 /> />
<input-copyable label-width="150px" label="Timezones" label-position="left" :value="result.info.timezones.join('\n')" mb-1 /> <input-copyable label-width="150px" label="Domain" label-position="left" :value="result.domain" :readonly="true" mb-1 />
<input-copyable label-width="150px" label="Currency" label-position="left" :value="`${result.info.currencyCode} / ${result.info.currencyName}`" mb-1 /> <input-copyable
<input-copyable label-width="150px" label="Postal Code" label-position="left" :value="`${result.info.postalCodeFormat} / ${result.info.postalCodeRegex}`" mb-1 /> label-width="150px"
<input-copyable label-width="150px" label="Phone Code" label-position="left" :value="result.info.phoneCode" mb-1 /> label="Emoji"
<input-copyable label-width="150px" label="Neighbor Countries" label-position="left" :value="result.info.neighborCountryIds.map(id => CountriesDB.getCountry(id, 'name')?.toString() || id).join(', ')" mb-1 /> label-position="left"
<input-copyable label-width="150px" label="Languages" label-position="left" :value="result.info.languages.map(langToName).join(', ')" mb-1 /> :value="`${result.emoji} (${result.emojiUnicode})`"
<input-copyable label-width="150px" label="Locales" label-position="left" :value="result.info.locales.map(langToName).join(', ')" mb-1 /> :readonly="true"
<!-- //NOSONAR --><n-a :href="`https://www.openstreetmap.org/#map=5/${result.info.coordinates.latitude}/${result.info.coordinates.longitude}`" target="_blank"> mb-1
/>
<input-copyable
label-width="150px"
label="ISO Num"
label-position="left"
:value="result.isoNumeric"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Continent"
label-position="left"
:value="result.continentId"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Elevation (m)"
label-position="left"
:value="result.elevation"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Population"
label-position="left"
:value="result.population"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Area (km²)"
label-position="left"
:value="result.areaSqKm"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Timezones"
label-position="left"
:value="result.timezones.join('\n')"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Currency"
label-position="left"
:value="`${result.currencyCode} / ${result.currencyName}`"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Postal Code"
label-position="left"
:value="`${result.postalCodeFormat} / ${result.postalCodeRegex}`"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Phone Code"
label-position="left"
:value="result.phoneCode"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Neighbor Countries"
label-position="left"
:value="
result.neighborCountryIds
.map((id) => CountriesDB.getCountry(id, 'name')?.toString() || id)
.join(', ')
"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Languages"
label-position="left"
:value="result.languages.map(langToName).join(', ')"
:readonly="true"
mb-1
/>
<input-copyable
label-width="150px"
label="Locales"
label-position="left"
:value="result.locales.map(langToName).join(', ')"
:readonly="true"
mb-1
/>
<!-- //NOSONAR --><n-a
:href="`https://www.openstreetmap.org/#map=5/${result.coordinates.latitude}/${result.coordinates.longitude}`"
target="_blank"
>
&gt; See on OpenStreetMap &gt; See on OpenStreetMap
</n-a> </n-a>
</td> </td>
+7 -7
View File
@@ -97,7 +97,7 @@ const { searchResult } = useFlexSearch({
<tbody> <tbody>
<tr v-for="(result, ix) in searchResult" :key="ix"> <tr v-for="(result, ix) in searchResult" :key="ix">
<td> <td>
<input-copyable :value="`U+${toPaddedHex(result.codePoint)}`" mb-1 /> <input-copyable :value="`U+${toPaddedHex(result.codePoint)}`" :readonly="true" mb-1 />
<!-- //NOSONAR --><n-a <!-- //NOSONAR --><n-a
:href="`https://unicodeplus.com/U+${toPaddedHex(result.codePoint)}`" :href="`https://unicodeplus.com/U+${toPaddedHex(result.codePoint)}`"
target="_blank" target="_blank"
@@ -106,17 +106,17 @@ const { searchResult } = useFlexSearch({
</n-a> </n-a>
</td> </td>
<td> <td>
<input-copyable :value="String.fromCodePoint(result.codePoint)" mb-1 /> <input-copyable :value="String.fromCodePoint(result.codePoint)" :readonly="true" mb-1 />
<input-copyable :value="toUTF8(result.codePoint)" /> <input-copyable :value="toUTF8(result.codePoint)" :readonly="true" />
</td> </td>
<td> <td>
<input-copyable :value="unicodeCategories.get(result.codePoint)" /> <input-copyable :value="unicodeCategories.get(result.codePoint)" :readonly="true" />
</td> </td>
<td> <td>
<input-copyable :value="`\&\#x${toPaddedHex(result.codePoint)};`" mb-1 /> <input-copyable :value="`\&\#x${toPaddedHex(result.codePoint)};`" :readonly="true" mb-1 />
<input-copyable :value="`\&\#${result.codePoint};`" /> <input-copyable :value="`\&\#${result.codePoint};`" :readonly="true" />
</td> </td>
<td><input-copyable :value="result.characterName" /></td> <td><input-copyable :value="result.characterName" :readonly="true" /></td>
</tr> </tr>
</tbody> </tbody>
</n-table> </n-table>