Improve hompage performance (#85)

* 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

* Merged new changes to flexSearch

* chore: vercel optimisation tentative

* Emoji Picker:
- Replaced fuzzysearch with flexsearch
- Reduced debounce from 500ms to 250ms
- Increased search limit from 100 to 150
- Implemented a UI loading sequence where it will load an emoji group each 150ms instead of loading all groups at once. This eliminates the lag experienced when loading the page or when removing the search query
- Updated unicode-emoji-json from version 0.4.0 to 0.8.0

Emoji Card:
- Fixed an issue where the country flag emojis weren't being rendered
- Added row which displays the emoji keywords, and uses a tooltip to display all keywords when they are truncated to fit in the card
- Moved codepoints and unicode escape lines to seperate rows instead of occasionally being displayed on the same line

* - Added logic to use an emoji in the search query

* small change

* - Replaced fuzzysearch with flexsearch in the command pallette
- Improved the performance of the collapsible tool menu by rewriting the logic to prevent the DOM elements being destroyed and recreated each time a category is expanded or collapsed
- Added logic to load the home page tool cards in batches instead of all at once

* Fixed linter error

* Fixed an issue where the weight of a search key wasn't properly being applied

---------

Co-authored-by: ShareVB <sharevb@gmail.com>
This commit is contained in:
Dark_Phoenix_andShareVB authored and ShareVB committed 2025-06-08 11:11:17 +02:00
1 parent b77c57e08d
commit fd7691495b
5 files changed
+220 -76

No files matched your search

+21
View File
@@ -192,6 +192,7 @@ declare module '@vue/runtime-core' {
IcoConverter: typeof import('./src/tools/ico-converter/ico-converter.vue')['default']
'IconMdi:brushVariant': typeof import('~icons/mdi/brush-variant')['default']
'IconMdi:kettleSteamOutline': typeof import('~icons/mdi/kettle-steam-outline')['default']
IconMdiArrowDown: typeof import('~icons/mdi/arrow-down')['default']
IconMdiChevronDown: typeof import('~icons/mdi/chevron-down')['default']
IconMdiChevronRight: typeof import('~icons/mdi/chevron-right')['default']
IconMdiClose: typeof import('~icons/mdi/close')['default']
@@ -298,26 +299,46 @@ declare module '@vue/runtime-core' {
MorseConverter: typeof import('./src/tools/morse-converter/morse-converter.vue')['default']
MultiLinkDownloader: typeof import('./src/tools/multi-link-downloader/multi-link-downloader.vue')['default']
MyIp: typeof import('./src/tools/my-ip/my-ip.vue')['default']
NA: typeof import('naive-ui')['NA']
NAlert: typeof import('naive-ui')['NAlert']
NanoidGenerator: typeof import('./src/tools/nanoid-generator/nanoid-generator.vue')['default']
NanoMemo: typeof import('./src/tools/nano-memo/nano-memo.vue')['default']
'NanoMemo.content': typeof import('./src/tools/nano-memo/nano-memo.content.md')['default']
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
NButton: typeof import('naive-ui')['NButton']
NCard: typeof import('naive-ui')['NCard']
NCheckbox: typeof import('naive-ui')['NCheckbox']
NCode: typeof import('naive-ui')['NCode']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDivider: typeof import('naive-ui')['NDivider']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NFormItem: typeof import('naive-ui')['NFormItem']
NGi: typeof import('naive-ui')['NGi']
NginxFormatter: typeof import('./src/tools/nginx-formatter/nginx-formatter.vue')['default']
NginxMemo: typeof import('./src/tools/nginx-memo/nginx-memo.vue')['default']
'NginxMemo.content': typeof import('./src/tools/nginx-memo/nginx-memo.content.md')['default']
NGrid: typeof import('naive-ui')['NGrid']
NH1: typeof import('naive-ui')['NH1']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NInput: typeof import('naive-ui')['NInput']
NInputGroup: typeof import('naive-ui')['NInputGroup']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NP: typeof import('naive-ui')['NP']
NRadio: typeof import('naive-ui')['NRadio']
NRadioGroup: typeof import('naive-ui')['NRadioGroup']
NScrollbar: typeof import('naive-ui')['NScrollbar']
NSpace: typeof import('naive-ui')['NSpace']
NSpin: typeof import('naive-ui')['NSpin']
NStatistic: typeof import('naive-ui')['NStatistic']
NSwitch: typeof import('naive-ui')['NSwitch']
NSpin: typeof import('naive-ui')['NSpin']
NTable: typeof import('naive-ui')['NTable']
NTag: typeof import('naive-ui')['NTag']
NumberInput: typeof import('./src/tools/pomodoro-timer/app/components/NumberInput.vue')['default']
NumeronymGenerator: typeof import('./src/tools/numeronym-generator/numeronym-generator.vue')['default']
OcrImage: typeof import('./src/tools/ocr-image/ocr-image.vue')['default']
+89 -57
View File
@@ -25,37 +25,40 @@ const collapsedCategories = useStorage<Record<string, boolean>>(
},
);
const isToggling = ref(false);
function toggleCategoryCollapse({ name }: { name: string }) {
collapsedCategories.value[name] = !collapsedCategories.value[name];
}
/**
* areAllCollapsed (new)
* --------------------------------------------------------------------------
* A computed property that checks if all categories are collapsed.
* - If even one category is expanded (false), this becomes false.
* - If no categories are found or all are collapsed (true), it becomes true.
*/
const areAllCollapsed = computed(() => {
return toolsByCategory.value.every(({ name }) => collapsedCategories.value[name] !== false);
});
/**
* toggleAllCategories (new)
* --------------------------------------------------------------------------
* If all categories are collapsed, expand them all; otherwise, collapse them all.
*/
function toggleAllCategories() {
const nextState = !areAllCollapsed.value;
async function toggleAllCategories() {
if (isToggling.value) {
return;
}
isToggling.value = true;
const shouldCollapse = !areAllCollapsed.value;
const updates: Record<string, boolean> = {};
toolsByCategory.value.forEach(({ name }) => {
collapsedCategories.value[name] = nextState;
updates[name] = shouldCollapse;
});
};
Object.assign(collapsedCategories.value, updates);
await nextTick();
isToggling.value = false;
}
const menuOptions = computed(() =>
toolsByCategory.value.map(({ name, components }) => ({
name,
isCollapsed: collapsedCategories.value[name] === undefined ? true : collapsedCategories.value[name], // default to collapsed if not set
isCollapsed: collapsedCategories.value[name] === undefined ? true : collapsedCategories.value[name],
tools: components.map(tool => ({
label: makeLabel(tool),
icon: makeIcon(tool),
@@ -68,18 +71,18 @@ const themeVars = useThemeVars();
</script>
<template>
<!--
A button at the top to expand or collapse all categories at once.
- Uses areAllCollapsed to determine the label ("Expand All" vs. "Collapse All").
- Calls toggleAllCategories() on click.
-->
<div class="top-controls" ml-6px>
<c-button @click="toggleAllCategories">
{{ areAllCollapsed ? 'Expand All Tools' : 'Collapse All Tools' }}
<c-button :disabled="isToggling" @click="toggleAllCategories">
<span v-if="isToggling">
{{ areAllCollapsed ? 'Expanding...' : 'Collapsing...' }}
</span>
<span v-else>
{{ areAllCollapsed ? 'Expand All Tools' : 'Collapse All Tools' }}
</span>
</c-button>
</div>
<div v-for="{ name, tools, isCollapsed } of menuOptions" :key="name">
<div v-for="{ name, tools, isCollapsed } of menuOptions" :key="name" class="category-container">
<div ml-6px mt-12px flex cursor-pointer items-center op-60 @click="toggleCategoryCollapse({ name })">
<span :class="{ 'rotate-0': isCollapsed, 'rotate-90': !isCollapsed }" text-16px lh-1 op-50 transition-transform>
<icon-mdi-chevron-right />
@@ -90,7 +93,7 @@ const themeVars = useThemeVars();
</span>
</div>
<n-collapse-transition :show="!isCollapsed">
<div class="menu-container" :class="{ collapsed: isCollapsed }">
<div class="menu-wrapper">
<div class="toggle-bar" @click="toggleCategoryCollapse({ name })" />
@@ -104,44 +107,73 @@ const themeVars = useThemeVars();
:default-expand-all="true"
/>
</div>
</n-collapse-transition>
</div>
</div>
</template>
<style scoped lang="less">
.menu-wrapper {
display: flex;
flex-direction: row;
.menu {
flex: 1;
margin-bottom: 5px;
.category-container {
.menu-container {
overflow: hidden;
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
::v-deep(.n-menu-item-content::before) {
left: 0;
right: 13px;
}
}
.toggle-bar {
width: 24px;
opacity: 0.1;
transition: opacity ease 0.2s;
position: relative;
cursor: pointer;
&::before {
width: 2px;
height: 100%;
content: ' ';
background-color: v-bind('themeVars.textColor3');
border-radius: 2px;
position: absolute;
top: 0;
left: 14px;
&:not(.collapsed) {
max-height: 1000px;
opacity: 1;
transform: translateY(0);
}
&:hover {
opacity: 0.5;
&.collapsed {
max-height: 0;
opacity: 0;
transform: translateY(-10px);
}
.menu-wrapper {
display: flex;
flex-direction: row;
transition: transform 0.4s cubic-bezier(0.2, 0.9, 0.3, 1);
.menu-container:not(.collapsed) & {
transform: translateY(0);
}
.menu-container.collapsed & {
transform: translateY(-20px);
}
.menu {
flex: 1;
margin-bottom: 5px;
::v-deep(.n-menu-item-content::before) {
left: 0;
right: 13px;
}
}
.toggle-bar {
width: 24px;
opacity: 0.1;
transition: opacity ease 0.2s;
position: relative;
cursor: pointer;
&::before {
width: 2px;
height: 100%;
content: ' ';
background-color: v-bind('themeVars.textColor3');
border-radius: 2px;
position: absolute;
top: 0;
left: 14px;
}
&:hover {
opacity: 0.5;
}
}
}
}
}
+44 -14
View File
@@ -112,20 +112,34 @@ export function useFlexSearch<Data extends Record<string, any>>({
const individualLimit = searchLimit > 0 ? searchLimit * 2 : undefined;
// Search each index and collect results with weights
const weightedResults = new Map<any, number>();
const weightedResults = new Map<any, { score: number; maxWeight: number }>();
indices.forEach(({ index, weight }) => {
const results = index.search(query, individualLimit ? { limit: individualLimit } : undefined);
results.forEach((id) => {
const currentScore = weightedResults.get(id) || 0;
weightedResults.set(id, currentScore + weight);
const current = weightedResults.get(id) || { score: 0, maxWeight: 0 };
// Use the maximum weight among matching fields as the primary score
// Add a small bonus for additional field matches
const newScore = Math.max(current.score, weight * 100) + (weight * 10);
const newMaxWeight = Math.max(current.maxWeight, weight);
weightedResults.set(id, {
score: newScore,
maxWeight: newMaxWeight,
});
});
});
// Sort by weight (higher weight = better match) and convert to array
// Sort by score (higher score = better match) and convert to array
const sortedIds = Array.from(weightedResults.entries())
.sort((a, b) => b[1] - a[1])
.sort((a, b) => {
// First sort by max weight, then by total score
if (b[1].maxWeight !== a[1].maxWeight) {
return b[1].maxWeight - a[1].maxWeight;
}
return b[1].score - a[1].score;
})
.map(([id]) => id);
// Apply limit and convert back to original items
@@ -174,7 +188,7 @@ export function useFlexSearch<Data extends Record<string, any>>({
return 1 - (distance / maxLength);
};
// Sort limited results by similarity score
// Sort limited results by similarity score, but maintain weight priority
const sortedResults = limitedIds
.map((id) => {
const item = dataMap.value.get(id);
@@ -182,21 +196,37 @@ export function useFlexSearch<Data extends Record<string, any>>({
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;
});
// Calculate weighted similarity score across all searchable fields
let bestWeightedSimilarity = 0;
let maxFieldWeight = 0;
const bestSimilarity = Math.max(...similarities);
normalizedKeys.forEach(({ name, weight }) => {
const value = name.split('.').reduce((obj, path) => obj?.[path], item);
if (value) {
const similarity = calculateSimilarity(query, String(value));
const weightedSimilarity = similarity * weight;
if (weightedSimilarity > bestWeightedSimilarity) {
bestWeightedSimilarity = weightedSimilarity;
maxFieldWeight = weight;
}
}
});
return {
item,
similarity: bestSimilarity,
similarity: bestWeightedSimilarity,
maxWeight: maxFieldWeight,
};
})
.filter(Boolean)
.sort((a, b) => b!.similarity - a!.similarity)
.sort((a, b) => {
// First sort by max field weight, then by weighted similarity
if (b!.maxWeight !== a!.maxWeight) {
return b!.maxWeight - a!.maxWeight;
}
return b!.similarity - a!.similarity;
})
.map(result => result!.item);
return sortedResults as Data[];
@@ -2,7 +2,6 @@ import { defineStore } from 'pinia';
import _ from 'lodash';
import type { PaletteOption } from './command-palette.types';
import { useToolStore } from '@/tools/tools.store';
import { useFuzzySearch } from '@/composable/fuzzySearch';
import { useStyleStore } from '@/stores/style.store';
import SunIcon from '~icons/mdi/white-balance-sunny';
@@ -10,6 +9,7 @@ import GithubIcon from '~icons/mdi/github';
import BugIcon from '~icons/mdi/bug-outline';
import DiceIcon from '~icons/mdi/dice-5';
import InfoIcon from '~icons/mdi/information-outline';
import { useFlexSearch } from '@/composable/flexSearch';
const maxSearchResultsPerCategory = import.meta.env.VITE_MAX_SEARCH_RESULT || 25;
@@ -74,12 +74,11 @@ export const useCommandPaletteStore = defineStore('command-palette', () => {
},
];
const { searchResult } = useFuzzySearch({
const { searchResult } = useFlexSearch({
search: searchPrompt,
data: searchOptions,
options: {
keys: [{ name: 'name', weight: 2 }, 'description', 'keywords', 'category'],
threshold: 0.3,
},
});
+64 -2
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { IconDragDrop, IconFileDescription, IconHeart } from '@tabler/icons-vue';
import { useHead } from '@vueuse/head';
import { computed } from 'vue';
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';
import Draggable from 'vuedraggable';
import VueMarkdown from 'vue-markdown-render';
import ColoredCard from '../components/ColoredCard.vue';
@@ -32,6 +32,61 @@ const favoriteTools = computed(() => toolStore.favoriteTools);
function onUpdateFavoriteTools() {
toolStore.updateFavoriteTools(favoriteTools.value); // Update the store with the new order
}
// Batch loading logic for tool cards
const TOOLS_PER_ROW = 4; // Based on xl:grid-cols-4
const ROWS_PER_BATCH = 8;
const TOOLS_PER_BATCH = TOOLS_PER_ROW * ROWS_PER_BATCH; // 32 tools per batch
const visibleToolsCount = ref(TOOLS_PER_BATCH); // Start with first batch
let loadingInterval: NodeJS.Timeout | null = null;
// Computed property for visible tools
const visibleTools = computed(() => {
return toolStore.tools.slice(0, visibleToolsCount.value);
});
// Function to stop automated loading
function stopAutomatedLoading() {
if (loadingInterval) {
clearInterval(loadingInterval);
loadingInterval = null;
}
}
// Function to start automated loading
function startAutomatedLoading() {
// Clear any existing interval
if (loadingInterval) {
clearInterval(loadingInterval);
}
// Start loading batches every 150ms
loadingInterval = setInterval(() => {
if (visibleToolsCount.value < toolStore.tools.length) {
visibleToolsCount.value = Math.min(
visibleToolsCount.value + TOOLS_PER_BATCH,
toolStore.tools.length,
);
}
else {
// Stop loading when all tools are visible
stopAutomatedLoading();
}
}, 150);
}
// Start automated loading on component mount
onMounted(() => {
nextTick(() => {
startAutomatedLoading();
});
});
// Clean up on component unmount
onUnmounted(() => {
stopAutomatedLoading();
});
</script>
<template>
@@ -108,7 +163,14 @@ function onUpdateFavoriteTools() {
{{ $t('home.categories.allTools') }}
</h3>
<div class="grid grid-cols-1 gap-12px lg:grid-cols-3 md:grid-cols-3 sm:grid-cols-2 xl:grid-cols-4">
<ToolCard v-for="tool in toolStore.tools" :key="tool.name" :tool="tool" />
<ToolCard v-for="tool in visibleTools" :key="tool.name" :tool="tool" />
</div>
<!-- Loading indicator when more tools are coming -->
<div v-if="visibleToolsCount < toolStore.tools.length" mt-6 text-center>
<div text-14px op-70>
Loading more tools... ({{ visibleTools.length }}/{{ toolStore.tools.length }})
</div>
</div>
</div>
</div>