refactor(keyboard): optimize keyboard event handling and initialization

This commit is contained in:
pandadev 2025-03-05 17:45:01 +01:00
parent c3b31bdde6
commit a5fbea31a1
No known key found for this signature in database
GPG key ID: C39629DACB8E762F
3 changed files with 117 additions and 110 deletions

18
app.vue
View file

@ -6,18 +6,28 @@
<script setup lang="ts"> <script setup lang="ts">
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { app, window } from "@tauri-apps/api"; import { window } from "@tauri-apps/api";
import { disable, enable } from "@tauri-apps/plugin-autostart"; import { disable, enable } from "@tauri-apps/plugin-autostart";
import { onMounted } from "vue"; import { onMounted } from "vue";
import { keyboard } from "wrdu-keyboard";
const keyboard = useKeyboard();
const { $settings } = useNuxtApp(); const { $settings } = useNuxtApp();
const router = useRouter();
keyboard.init();
router.beforeEach((to, from) => {
if (to.path !== from.path) {
keyboard.init();
}
});
router.afterEach(() => {
keyboard.clear();
});
onMounted(async () => { onMounted(async () => {
await listen("settings", async () => { await listen("settings", async () => {
keyboard.clear();
await navigateTo("/settings"); await navigateTo("/settings");
await app.show();
await window.getCurrentWindow().show(); await window.getCurrentWindow().show();
}); });

View file

@ -157,7 +157,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick, shallowRef } from "vue"; import { ref, computed, onMounted, watch, nextTick, shallowRef, onBeforeMount } from "vue";
import { OverlayScrollbarsComponent } from "overlayscrollbars-vue"; import { OverlayScrollbarsComponent } from "overlayscrollbars-vue";
import "overlayscrollbars/overlayscrollbars.css"; import "overlayscrollbars/overlayscrollbars.css";
import { app, window } from "@tauri-apps/api"; import { app, window } from "@tauri-apps/api";
@ -174,7 +174,7 @@ import type {
InfoColor, InfoColor,
InfoCode, InfoCode,
} from "~/types/types"; } from "~/types/types";
import { Key } from "wrdu-keyboard/key"; import { Key, keyboard } from "wrdu-keyboard";
interface GroupedHistory { interface GroupedHistory {
label: string; label: string;
@ -207,8 +207,6 @@ const imageLoading = ref<boolean>(false);
const pageTitle = ref<string>(""); const pageTitle = ref<string>("");
const pageOgImage = ref<string>(""); const pageOgImage = ref<string>("");
const keyboard = useKeyboard();
const isSameDay = (date1: Date, date2: Date): boolean => { const isSameDay = (date1: Date, date2: Date): boolean => {
return ( return (
date1.getFullYear() === date2.getFullYear() && date1.getFullYear() === date2.getFullYear() &&
@ -287,7 +285,7 @@ const loadHistoryChunk = async (): Promise<void> => {
} }
const processedItems = await Promise.all( const processedItems = await Promise.all(
results.map(async (item) => { results.map(async (item: HistoryItem) => {
const historyItem = new HistoryItem( const historyItem = new HistoryItem(
item.source, item.source,
item.content_type, item.content_type,
@ -389,7 +387,7 @@ const isSelected = (groupIndex: number, itemIndex: number): boolean => {
const searchHistory = async (): Promise<void> => { const searchHistory = async (): Promise<void> => {
const results = await $history.searchHistory(searchQuery.value); const results = await $history.searchHistory(searchQuery.value);
history.value = results.map((item) => history.value = results.map((item: HistoryItem) =>
Object.assign( Object.assign(
new HistoryItem( new HistoryItem(
item.source, item.source,
@ -434,8 +432,8 @@ const pasteSelectedItem = async (): Promise<void> => {
if (!selectedItem.value) return; if (!selectedItem.value) return;
let content = selectedItem.value.content; let content = selectedItem.value.content;
let contentType: string = selectedItem.value.content_type; let contentType = selectedItem.value.content_type as ContentType;
if (contentType === "image") { if (contentType === ContentType.Image) {
try { try {
content = await $history.readImage({ filename: content }); content = await $history.readImage({ filename: content });
} catch (error) { } catch (error) {
@ -488,10 +486,12 @@ const updateHistory = async (resetScroll: boolean = false): Promise<void> => {
const results = await $history.loadHistoryChunk(0, CHUNK_SIZE); const results = await $history.loadHistoryChunk(0, CHUNK_SIZE);
if (results.length > 0) { if (results.length > 0) {
const existingIds = new Set(history.value.map((item) => item.id)); const existingIds = new Set(history.value.map((item) => item.id));
const uniqueNewItems = results.filter((item) => !existingIds.has(item.id)); const uniqueNewItems = results.filter(
(item: HistoryItem) => !existingIds.has(item.id)
);
const processedNewItems = await Promise.all( const processedNewItems = await Promise.all(
uniqueNewItems.map(async (item) => { uniqueNewItems.map(async (item: HistoryItem) => {
const historyItem = new HistoryItem( const historyItem = new HistoryItem(
item.source, item.source,
item.content_type, item.content_type,
@ -561,71 +561,21 @@ const handleSelection = (
if (shouldScroll) scrollToSelectedItem(); if (shouldScroll) scrollToSelectedItem();
}; };
const setupEventListeners = async (): Promise<void> => { const setupKeyboardShortcuts = () => {
await listen("clipboard-content-updated", async () => { keyboard.prevent.down([Key.ArrowDown], () => selectNext());
lastUpdateTime.value = Date.now(); keyboard.prevent.down([Key.ArrowUp], () => selectPrevious());
await updateHistory(true); keyboard.prevent.down([Key.Enter], () => pasteSelectedItem());
if (groupedHistory.value[0]?.items.length > 0) { keyboard.prevent.down([Key.Escape], () => hideApp());
handleSelection(0, 0, false);
}
});
await listen("tauri://focus", async () => {
const currentTime = Date.now();
if (currentTime - lastUpdateTime.value > 0) {
const previousState = {
groupIndex: selectedGroupIndex.value,
itemIndex: selectedItemIndex.value,
scroll:
resultsContainer.value?.osInstance()?.elements().viewport
?.scrollTop || 0,
};
await updateHistory();
lastUpdateTime.value = currentTime;
handleSelection(previousState.groupIndex, previousState.itemIndex, false);
if (resultsContainer.value?.osInstance()?.elements().viewport?.scrollTo) {
resultsContainer.value.osInstance()?.elements().viewport?.scrollTo({
top: previousState.scroll,
behavior: "instant",
});
}
}
focusSearchInput();
});
await listen("tauri://blur", () => {
searchInput.value?.blur();
});
keyboard.prevent.down([Key.DownArrow], (event) => {
selectNext();
});
keyboard.prevent.down([Key.UpArrow], (event) => {
selectPrevious();
});
keyboard.prevent.down([Key.Enter], (event) => {
pasteSelectedItem();
});
keyboard.prevent.down([Key.Escape], (event) => {
hideApp();
});
switch (os.value) { switch (os.value) {
case "macos": case "macos":
keyboard.prevent.down([Key.LeftMeta, Key.K], (event) => {}); keyboard.prevent.down([Key.MetaLeft, Key.K], () => {});
keyboard.prevent.down([Key.MetaRight, Key.K], () => {});
keyboard.prevent.down([Key.RightMeta, Key.K], (event) => {});
break; break;
case "linux":
case "linux" || "windows": case "windows":
keyboard.prevent.down([Key.LeftControl, Key.K], (event) => {}); keyboard.prevent.down([Key.ControlLeft, Key.K], () => {});
keyboard.prevent.down([Key.ControlRight, Key.K], () => {});
keyboard.prevent.down([Key.RightControl, Key.K], (event) => {});
break; break;
} }
}; };
@ -654,6 +604,11 @@ watch(searchQuery, () => {
searchHistory(); searchHistory();
}); });
onBeforeMount(() => {
keyboard.clear();
setupKeyboardShortcuts();
});
onMounted(async () => { onMounted(async () => {
try { try {
os.value = platform(); os.value = platform();
@ -664,7 +619,50 @@ onMounted(async () => {
?.elements() ?.elements()
?.viewport?.addEventListener("scroll", handleScroll); ?.viewport?.addEventListener("scroll", handleScroll);
await setupEventListeners(); await listen("clipboard-content-updated", async () => {
lastUpdateTime.value = Date.now();
await updateHistory(true);
if (groupedHistory.value[0]?.items.length > 0) {
handleSelection(0, 0, false);
}
});
await listen("tauri://focus", async () => {
console.log("focus");
setupKeyboardShortcuts();
const currentTime = Date.now();
if (currentTime - lastUpdateTime.value > 0) {
const previousState = {
groupIndex: selectedGroupIndex.value,
itemIndex: selectedItemIndex.value,
scroll:
resultsContainer.value?.osInstance()?.elements().viewport
?.scrollTop || 0,
};
await updateHistory();
lastUpdateTime.value = currentTime;
handleSelection(
previousState.groupIndex,
previousState.itemIndex,
false
);
if (
resultsContainer.value?.osInstance()?.elements().viewport?.scrollTo
) {
resultsContainer.value.osInstance()?.elements().viewport?.scrollTo({
top: previousState.scroll,
behavior: "instant",
});
}
}
focusSearchInput();
});
await listen("tauri://blur", () => {
searchInput.value?.blur();
});
} catch (error) { } catch (error) {
console.error("Error during onMounted:", error); console.error("Error during onMounted:", error);
} }

View file

@ -89,43 +89,40 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { platform } from "@tauri-apps/plugin-os"; import { platform } from "@tauri-apps/plugin-os";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import { Key } from "wrdu-keyboard/key";
import { KeyValues, KeyLabels } from "../types/keys";
import { disable, enable } from "@tauri-apps/plugin-autostart"; import { disable, enable } from "@tauri-apps/plugin-autostart";
import { Key, keyboard } from "wrdu-keyboard";
import { KeyLabels } from "~/types/keys";
const activeModifiers = reactive<Set<KeyValues>>(new Set()); const activeModifiers = reactive<Set<Key>>(new Set());
const isKeybindInputFocused = ref(false); const isKeybindInputFocused = ref(false);
const keybind = ref<KeyValues[]>([]); const keybind = ref<Key[]>([]);
const keybindInput = ref<HTMLElement | null>(null); const keybindInput = ref<HTMLElement | null>(null);
const lastBlurTime = ref(0); const lastBlurTime = ref(0);
const os = ref(""); const os = ref("");
const router = useRouter(); const router = useRouter();
const keyboard = useKeyboard();
const showEmptyKeybindError = ref(false); const showEmptyKeybindError = ref(false);
const autostart = ref(false); const autostart = ref(false);
const { $settings } = useNuxtApp(); const { $settings } = useNuxtApp();
const modifierKeySet = new Set([ const modifierKeySet = new Set([
KeyValues.AltLeft, Key.AltLeft,
KeyValues.AltRight, Key.AltRight,
KeyValues.ControlLeft, Key.ControlLeft,
KeyValues.ControlRight, Key.ControlRight,
KeyValues.MetaLeft, Key.MetaLeft,
KeyValues.MetaRight, Key.MetaRight,
KeyValues.ShiftLeft, Key.ShiftLeft,
KeyValues.ShiftRight, Key.ShiftRight,
]); ]);
const isModifier = (key: KeyValues): boolean => { const isModifier = (key: Key): boolean => {
return modifierKeySet.has(key); return modifierKeySet.has(key);
}; };
const keyToLabel = (key: KeyValues): string => { const keyToLabel = (key: Key): string => {
return KeyLabels[key] || key; return KeyLabels[key as keyof typeof KeyLabels] || key;
}; };
const updateKeybind = () => { const updateKeybind = () => {
@ -148,9 +145,9 @@ const onFocus = () => {
}; };
const onKeyDown = (event: KeyboardEvent) => { const onKeyDown = (event: KeyboardEvent) => {
const key = event.code as KeyValues; const key = event.code as Key;
if (key === KeyValues.Escape) { if (key === Key.Escape) {
if (keybindInput.value) { if (keybindInput.value) {
keybindInput.value.blur(); keybindInput.value.blur();
} }
@ -186,16 +183,14 @@ const toggleAutostart = async () => {
await $settings.saveSetting("autostart", autostart.value ? "true" : "false"); await $settings.saveSetting("autostart", autostart.value ? "true" : "false");
}; };
os.value = platform(); const setupKeyboardShortcuts = () => {
keyboard.prevent.down([Key.All], (event: KeyboardEvent) => {
onMounted(async () => {
keyboard.down([Key.All], (event) => {
if (isKeybindInputFocused.value) { if (isKeybindInputFocused.value) {
onKeyDown(event); onKeyDown(event);
} }
}); });
keyboard.down([Key.Escape], (event) => { keyboard.prevent.down([Key.Escape], () => {
if (isKeybindInputFocused.value) { if (isKeybindInputFocused.value) {
keybindInput.value?.blur(); keybindInput.value?.blur();
} else { } else {
@ -205,39 +200,43 @@ onMounted(async () => {
switch (os.value) { switch (os.value) {
case "macos": case "macos":
keyboard.down([Key.LeftMeta, Key.Enter], (event) => { keyboard.prevent.down([Key.MetaLeft, Key.Enter], () => {
if (!isKeybindInputFocused.value) { if (!isKeybindInputFocused.value) {
saveKeybind(); saveKeybind();
} }
}); });
keyboard.down([Key.RightMeta, Key.Enter], (event) => { keyboard.prevent.down([Key.MetaRight, Key.Enter], () => {
if (!isKeybindInputFocused.value) { if (!isKeybindInputFocused.value) {
saveKeybind(); saveKeybind();
} }
}); });
break; break;
case "linux":
case "linux" || "windows": case "windows":
keyboard.down([Key.LeftControl, Key.Enter], (event) => { keyboard.prevent.down([Key.ControlLeft, Key.Enter], () => {
if (!isKeybindInputFocused.value) { if (!isKeybindInputFocused.value) {
saveKeybind(); saveKeybind();
} }
}); });
keyboard.down([Key.RightControl, Key.Enter], (event) => { keyboard.prevent.down([Key.ControlRight, Key.Enter], () => {
if (!isKeybindInputFocused.value) { if (!isKeybindInputFocused.value) {
saveKeybind(); saveKeybind();
} }
}); });
break; break;
} }
};
autostart.value = (await $settings.getSetting("autostart")) === "true"; onBeforeMount(() => {
});
onUnmounted(() => {
keyboard.clear(); keyboard.clear();
setupKeyboardShortcuts();
});
onMounted(async () => {
os.value = platform();
autostart.value = (await $settings.getSetting("autostart")) === "true";
}); });
</script> </script>