Compare commits

..

No commits in common. "aa928f709440a643a53fb59a3403c633ded243f6" and "ae5103e8007e628b0dbc6858e5307c369ead53fc" have entirely different histories.

8 changed files with 529 additions and 363 deletions

2
.github/FUNDING.yml vendored
View file

@ -1 +1,3 @@
github: 0pandadev
buy_me_a_coffee: pandadev_
ko_fi: pandadev_

View file

@ -5,31 +5,31 @@
The fixed and simple clipboard manager for both Windows and Linux.
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.3/Qopy-0.3.3_x64.msi">
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.1/Qopy-0.3.1_x64.msi">
<img src="./public/windows.png"> Windows (x64)
</a>
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.3/Qopy-0.3.3_arm64.msi">
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.1/Qopy-0.3.1_arm64.msi">
Windows (arm64)
</a>
<br>
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.3/Qopy-0.3.3.deb">
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.1/Qopy-0.3.1.deb">
<img src="./public/linux.png"> Linux (deb)
</a>
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.3/Qopy-0.3.3.rpm">
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.1/Qopy-0.3.1.rpm">
Linux (rpm)
</a>
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.3/Qopy-0.3.3.AppImage">
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.1/Qopy-0.3.1.AppImage">
Linux (AppImage)
</a>
<br>
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.3/Qopy-0.3.3_silicon.dmg">
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.1/Qopy-0.3.1_silicon.dmg">
<img src="./public/apple.png"> macOS (Silicon)
</a>
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.3/Qopy-0.3.3_intel.dmg">
<a href="https://github.com/0PandaDEV/Qopy/releases/download/v0.3.1/Qopy-0.3.1_intel.dmg">
macOS (Intel)
</a>
<br>
@ -123,7 +123,7 @@ bun build
## 📝 License
Qopy is licensed under AGPL-3. See the [LICENSE file](./LICENCE) for more information.
Qopy is licensed under GPL-3. See the [LICENSE file](./LICENCE) for more information.
[codespaces-link]: https://codespaces.new/0pandadev/Qopy
[codespaces-shield]: https://github.com/codespaces/badge.svg

View file

@ -20,7 +20,7 @@
"sass-embedded": "1.85.1",
"uuid": "11.1.0",
"vue": "3.5.13",
"@waradu/keyboard": "4.2.0"
"wrdu-keyboard": "github:0PandaDEV/keyboard"
},
"overrides": {
"chokidar": "^3.6.0"

View file

@ -1,68 +1,41 @@
<template>
<main>
<TopBar
ref="topBar"
@search="searchHistory"
@searchStarted="searchStarted" />
<TopBar ref="topBar" @search="searchHistory" @searchStarted="searchStarted" />
<div class="container">
<OverlayScrollbarsComponent
class="results"
ref="resultsContainer"
<OverlayScrollbarsComponent class="results" ref="resultsContainer"
:options="{ scrollbars: { autoHide: 'scroll' } }">
<div
v-for="(group, groupIndex) in groupedHistory"
:key="groupIndex"
class="group">
<div v-for="(group, groupIndex) in groupedHistory" :key="groupIndex" class="group">
<div class="time-separator">{{ group.label }}</div>
<div class="results-group">
<Result
v-for="(item, index) in group.items"
:key="item.id"
:item="item"
:selected="isSelected(groupIndex, index)"
:image-url="imageUrls[item.id]"
:dimensions="imageDimensions[item.id]"
@select="selectItem(groupIndex, index)"
@image-error="onImageError"
<Result v-for="(item, index) in group.items" :key="item.id" :item="item"
:selected="isSelected(groupIndex, index)" :image-url="imageUrls[item.id]"
:dimensions="imageDimensions[item.id]" @select="selectItem(groupIndex, index)" @image-error="onImageError"
@setRef="(el: HTMLElement | null) => (selectedElement = el)" />
</div>
</div>
</OverlayScrollbarsComponent>
<div class="right">
<div
class="content"
v-if="selectedItem?.content_type === ContentType.Image">
<div class="content" v-if="selectedItem?.content_type === ContentType.Image">
<img :src="imageUrls[selectedItem.id]" alt="Image" class="image" />
</div>
<div
v-else-if="selectedItem && isYoutubeWatchUrl(selectedItem.content)"
class="content">
<img
class="image"
:src="getYoutubeThumbnail(selectedItem.content)"
alt="YouTube Thumbnail" />
<div v-else-if="selectedItem && isYoutubeWatchUrl(selectedItem.content)" class="content">
<img class="image" :src="getYoutubeThumbnail(selectedItem.content)" alt="YouTube Thumbnail" />
</div>
<div
class="content"
v-else-if="
selectedItem?.content_type === ContentType.Link && pageOgImage
">
<div class="content" v-else-if="
selectedItem?.content_type === ContentType.Link && pageOgImage
">
<img :src="pageOgImage" alt="Image" class="image" />
</div>
<OverlayScrollbarsComponent v-else class="content">
<span class="content-text">{{ selectedItem?.content || "" }}</span>
</OverlayScrollbarsComponent>
<OverlayScrollbarsComponent
class="information"
:options="{ scrollbars: { autoHide: 'scroll' } }">
<OverlayScrollbarsComponent class="information" :options="{ scrollbars: { autoHide: 'scroll' } }">
<div class="title">Information</div>
<div class="info-content" v-if="selectedItem && getInfo">
<div class="info-row" v-for="(row, index) in infoRows" :key="index">
<p class="label">{{ row.label }}</p>
<span
:class="{ 'url-truncate': row.isUrl }"
:data-text="row.value">
<img v-if="row.icon" :src="row.icon" :alt="String(row.value)" />
<span :class="{ 'url-truncate': row.isUrl }" :data-text="row.value">
<img v-if="row.icon" :src="row.icon" :alt="String(row.value)">
{{ row.value }}
</span>
</div>
@ -70,39 +43,26 @@
</OverlayScrollbarsComponent>
</div>
</div>
<BottomBar
:primary-action="{
text: 'Paste',
icon: IconsEnter,
onClick: pasteSelectedItem,
}"
:secondary-action="{
text: 'Actions',
icon: IconsKey,
input: 'K',
showModifier: true,
onClick: toggleActionsMenu,
}" />
<ActionsMenu
:selected-item="selectedItem"
:is-visible="isActionsMenuVisible"
@close="closeActionsMenu"
@toggle="toggleActionsMenu" />
<BottomBar :primary-action="{
text: 'Paste',
icon: IconsEnter,
onClick: pasteSelectedItem,
}" :secondary-action="{
text: 'Actions',
icon: IconsKey,
input: 'K',
showModifier: true,
onClick: toggleActionsMenu,
}" />
<ActionsMenu :selected-item="selectedItem" :is-visible="isActionsMenuVisible" @close="closeActionsMenu" @toggle="toggleActionsMenu" />
</main>
</template>
<script setup lang="ts">
import {
ref,
computed,
onMounted,
onUnmounted,
watch,
nextTick,
shallowRef,
} from "vue";
import { ref, computed, onMounted, watch, nextTick, shallowRef } from "vue";
import { OverlayScrollbarsComponent } from "overlayscrollbars-vue";
import "overlayscrollbars/overlayscrollbars.css";
import { platform } from "@tauri-apps/plugin-os";
import { listen } from "@tauri-apps/api/event";
import { useNuxtApp } from "#app";
import { invoke } from "@tauri-apps/api/core";
@ -126,14 +86,7 @@ interface GroupedHistory {
}
const { $history, $keyboard, $selectedResult } = useNuxtApp();
const {
selectedGroupIndex,
selectedItemIndex,
selectedElement,
useSelectedResult,
} = $selectedResult;
const listeners: Array<() => void> = [];
const { selectedGroupIndex, selectedItemIndex, selectedElement, useSelectedResult } = $selectedResult;
const CHUNK_SIZE = 50;
const SCROLL_THRESHOLD = 100;
@ -149,6 +102,7 @@ const resultsContainer = shallowRef<InstanceType<
> | null>(null);
const searchQuery = ref("");
const searchInput = ref<HTMLInputElement | null>(null);
const os = ref<string>("");
const imageUrls = shallowRef<Record<string, string>>({});
const imageDimensions = shallowRef<Record<string, string>>({});
const imageSizes = shallowRef<Record<string, string>>({});
@ -163,9 +117,18 @@ const topBar = ref<{ searchInput: HTMLInputElement | null } | null>(null);
const toggleActionsMenu = () => {
isActionsMenuVisible.value = !isActionsMenuVisible.value;
if (isActionsMenuVisible.value) {
$keyboard.disableContext('main');
$keyboard.enableContext('actionsMenu');
} else {
$keyboard.disableContext('actionsMenu');
$keyboard.enableContext('main');
}
nextTick(() => {
if (isActionsMenuVisible.value) {
document.getElementById("actions-menu")?.focus();
document.getElementById('actions-menu')?.focus();
} else {
focusSearchInput();
}
@ -174,7 +137,8 @@ const toggleActionsMenu = () => {
const closeActionsMenu = () => {
isActionsMenuVisible.value = false;
focusSearchInput();
$keyboard.disableContext('actionsMenu');
$keyboard.enableContext('main');
};
const isSameDay = (date1: Date, date2: Date): boolean => {
@ -191,7 +155,7 @@ const getWeekNumber = (date: Date): number => {
((date.getTime() - firstDayOfYear.getTime()) / 86400000 +
firstDayOfYear.getDay() +
1) /
7
7
);
};
@ -212,8 +176,8 @@ const groupedHistory = computed<GroupedHistory[]>(() => {
const filteredItems = searchQuery.value
? history.value.filter((item) =>
item.content.toLowerCase().includes(searchQuery.value.toLowerCase())
)
item.content.toLowerCase().includes(searchQuery.value.toLowerCase())
)
: history.value;
const yesterday = new Date(today.getTime() - 86400000);
@ -279,16 +243,16 @@ const loadHistoryChunk = async (): Promise<void> => {
img.src = `data:image/png;base64,${base64}`;
imageUrls.value[historyItem.id] = img.src;
await new Promise<void>((resolveProm) => {
await new Promise<void>((resolve) => {
img.onload = () => {
imageDimensions.value[
historyItem.id
] = `${img.width}x${img.height}`;
resolveProm();
resolve();
};
img.onerror = () => {
imageDimensions.value[historyItem.id] = "Error";
resolveProm();
resolve();
};
});
} catch (error) {
@ -402,11 +366,7 @@ const processSearchQueue = async () => {
{ id: item.id, timestamp: new Date(item.timestamp) }
)
);
if (groupedHistory.value.length > 0) {
handleSelection(0, 0, true);
} else {
selectItem(-1, -1);
}
} catch (error) {
console.error("Search error:", error);
} finally {
@ -419,13 +379,13 @@ const processSearchQueue = async () => {
const searchHistory = async (query: string): Promise<void> => {
searchQuery.value = query;
if (searchController) {
searchController.abort();
}
searchController = new AbortController();
searchQueue.push(query);
if (!isProcessingSearch) {
processSearchQueue();
@ -434,14 +394,10 @@ const searchHistory = async (query: string): Promise<void> => {
watch(
() => groupedHistory.value,
(newGroupedHistory, oldGroupedHistory) => {
if (
newGroupedHistory.length > 0 &&
oldGroupedHistory &&
oldGroupedHistory.length === 0
) {
(newGroupedHistory) => {
if (newGroupedHistory.length > 0) {
handleSelection(0, 0, true);
} else if (newGroupedHistory.length === 0) {
} else {
selectItem(-1, -1);
}
},
@ -488,7 +444,7 @@ const getYoutubeThumbnail = (url: string): string => {
const updateHistory = async (resetScroll: boolean = false): Promise<void> => {
offset = 0;
history.value = [];
const results = await $history.loadHistoryChunk(offset, CHUNK_SIZE);
if (results.length > 0) {
const processedItems = await Promise.all(
@ -518,16 +474,16 @@ const updateHistory = async (resetScroll: boolean = false): Promise<void> => {
img.src = `data:image/png;base64,${base64}`;
imageUrls.value[historyItem.id] = img.src;
await new Promise<void>((resolveProm) => {
await new Promise<void>((resolve) => {
img.onload = () => {
imageDimensions.value[
historyItem.id
] = `${img.width}x${img.height}`;
resolveProm();
resolve();
};
img.onerror = () => {
imageDimensions.value[historyItem.id] = "Error";
resolveProm();
resolve();
};
});
} catch (error) {
@ -564,6 +520,72 @@ const handleSelection = (
if (shouldScroll) scrollToSelectedItem();
};
const setupEventListeners = async (): Promise<void> => {
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 () => {
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();
$keyboard.disableContext('actionsMenu');
$keyboard.disableContext('settings');
$keyboard.enableContext('main');
if (isActionsMenuVisible.value) {
$keyboard.enableContext('actionsMenu');
}
});
await listen("tauri://blur", () => {
searchInput.value?.blur();
$keyboard.disableContext('main');
$keyboard.disableContext('actionsMenu');
});
$keyboard.setupAppShortcuts({
onNavigateDown: selectNext,
onNavigateUp: selectPrevious,
onSelect: pasteSelectedItem,
onEscape: () => {
if (isActionsMenuVisible.value) {
closeActionsMenu();
} else {
hideApp();
}
},
onToggleActions: toggleActionsMenu,
contextName: 'main',
priority: $keyboard.PRIORITY.HIGH
});
$keyboard.disableContext('settings');
$keyboard.enableContext('main');
};
const { hideApp } = useAppControl();
const focusSearchInput = (): void => {
@ -587,147 +609,38 @@ watch(
onMounted(async () => {
try {
os.value = platform();
await loadHistoryChunk();
if (groupedHistory.value.length > 0 && !selectedItem.value) {
handleSelection(0, 0, true);
}
resultsContainer.value
?.osInstance()
?.elements()
?.viewport?.addEventListener("scroll", handleScroll);
listeners.push(
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 setupEventListeners();
listeners.push(
await listen("tauri://focus", async () => {
console.log("Tauri window focused");
// Attempt to re-initialize keyboard listeners
if ($keyboard && typeof $keyboard.init === "function") {
console.log("Re-initializing keyboard via $keyboard.init()");
$keyboard.init();
$keyboard.setupAppShortcuts({
onNavigateDown: selectNext,
onNavigateUp: selectPrevious,
onSelect: pasteSelectedItem,
onEscape: () => {
if (isActionsMenuVisible.value) {
closeActionsMenu();
} else {
console.warn("$keyboard.init is not available");
hideApp();
}
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();
})
);
listeners.push(
await listen("tauri://blur", () => {
searchInput.value?.blur();
})
);
listeners.push(
$keyboard.listen(
[$keyboard.Key.DownArrow],
() => {
console.log(
"Down Arrow pressed. Active element:",
document.activeElement
);
selectNext();
},
{ prevent: true }
)
);
listeners.push(
$keyboard.listen(
[$keyboard.Key.UpArrow],
() => {
console.log(
"Up Arrow pressed. Active element:",
document.activeElement
);
selectPrevious();
},
{ prevent: true }
)
);
listeners.push(
$keyboard.listen([$keyboard.Key.Enter], pasteSelectedItem, {
prevent: true,
})
);
listeners.push(
$keyboard.listen(
[$keyboard.Key.Escape],
() => {
if (isActionsMenuVisible.value) {
closeActionsMenu();
} else {
hideApp();
}
},
{ prevent: true }
)
);
const metaOrCtrlKey =
$keyboard.currentOS === "macos"
? $keyboard.Key.Meta
: $keyboard.Key.Control;
listeners.push(
$keyboard.listen([metaOrCtrlKey, $keyboard.Key.K], toggleActionsMenu, {
prevent: true,
ignoreIfEditable: true,
})
);
},
onToggleActions: toggleActionsMenu,
contextName: 'main',
priority: $keyboard.PRIORITY.HIGH
});
$keyboard.disableContext('settings');
$keyboard.enableContext('main');
} catch (error) {
console.error("Error during onMounted:", error);
}
});
onUnmounted(() => {
listeners.forEach((unlisten) => {
if (typeof unlisten === "function") {
unlisten();
}
});
listeners.length = 0;
const viewport = resultsContainer.value?.osInstance()?.elements()?.viewport;
if (viewport) {
viewport.removeEventListener("scroll", handleScroll);
}
});
const getFormattedDate = computed(() => {
if (!selectedItem.value?.timestamp) return "";
return new Intl.DateTimeFormat("en-US", {
@ -874,9 +787,7 @@ const infoRows = computed(() => {
label: "Source",
value: getInfo.value.source,
isUrl: false,
icon: selectedItem.value?.source_icon
? `data:image/png;base64,${selectedItem.value.source_icon}`
: undefined,
icon: selectedItem.value?.source_icon ? `data:image/png;base64,${selectedItem.value.source_icon}` : undefined
},
{
label: "Content Type",
@ -889,12 +800,7 @@ const infoRows = computed(() => {
const typeSpecificRows: Record<
ContentType,
Array<{
label: string;
value: string | number;
isUrl?: boolean;
icon?: string;
}>
Array<{ label: string; value: string | number; isUrl?: boolean; icon?: string }>
> = {
[ContentType.Text]: [
{ label: "Characters", value: (getInfo.value as InfoText).characters },
@ -912,7 +818,7 @@ const infoRows = computed(() => {
],
[ContentType.Link]: [
...((getInfo.value as InfoLink).title &&
(getInfo.value as InfoLink).title !== "Loading..."
(getInfo.value as InfoLink).title !== "Loading..."
? [{ label: "Title", value: (getInfo.value as InfoLink).title || "" }]
: []),
{ label: "URL", value: (getInfo.value as InfoLink).url, isUrl: true },

View file

@ -45,6 +45,7 @@
<div
@blur="onBlur"
@focus="onFocus"
@keydown="onKeyDown"
class="keybind-input"
ref="keybindInput"
tabindex="0"
@ -74,7 +75,7 @@
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref, watch } from "vue";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { platform } from "@tauri-apps/plugin-os";
import { useRouter } from "vue-router";
import { KeyValues, KeyLabels } from "../types/keys";
@ -87,14 +88,14 @@ const activeModifiers = reactive<Set<KeyValues>>(new Set());
const isKeybindInputFocused = ref(false);
const keybind = ref<KeyValues[]>([]);
const keybindInput = ref<HTMLElement | null>(null);
const lastBlurTime = ref(0);
const blurredByEscape = ref(false);
const os = ref("");
const router = useRouter();
const showEmptyKeybindError = ref(false);
const autostart = ref(false);
const { $settings, $keyboard } = useNuxtApp();
const listeners: Array<() => void> = [];
const modifierKeySet = new Set([
KeyValues.AltLeft,
KeyValues.AltRight,
@ -114,15 +115,15 @@ const keyToLabel = (key: KeyValues): string => {
return KeyLabels[key] || key;
};
const updateKeybindDisplay = () => {
const updateKeybind = () => {
const modifiers = Array.from(activeModifiers);
const nonModifiers = keybind.value.filter((key) => !isModifier(key));
const sortedModifiers = modifiers.sort();
keybind.value = [...sortedModifiers, ...nonModifiers];
keybind.value = [...modifiers, ...nonModifiers];
};
const onBlur = () => {
isKeybindInputFocused.value = false;
lastBlurTime.value = Date.now();
showEmptyKeybindError.value = false;
};
@ -132,39 +133,35 @@ const onFocus = () => {
activeModifiers.clear();
keybind.value = [];
showEmptyKeybindError.value = false;
};
const unlistenAll = $keyboard.listen([$keyboard.Key.All], (event: KeyboardEvent) => {
event.preventDefault();
event.stopPropagation();
const key = event.code as KeyValues;
const onKeyDown = (event: KeyboardEvent) => {
const key = event.code as KeyValues;
if (key === KeyValues.Escape) {
if (key === KeyValues.Escape) {
if (keybindInput.value) {
blurredByEscape.value = true;
keybindInput.value?.blur();
return;
keybindInput.value.blur();
event.preventDefault();
event.stopPropagation();
}
return;
}
if (isModifier(key)) {
activeModifiers.add(key);
} else {
const nonModifierKey = keybind.value.find(k => !isModifier(k));
if (!nonModifierKey || nonModifierKey === key) {
keybind.value = Array.from(activeModifiers);
if (nonModifierKey !== key) keybind.value.push(key);
} else {
keybind.value = [ ...Array.from(activeModifiers), key];
}
}
updateKeybindDisplay();
showEmptyKeybindError.value = false;
}, { prevent: true });
listeners.push(unlistenAll);
if (isModifier(key)) {
activeModifiers.add(key);
} else if (!keybind.value.includes(key)) {
keybind.value = keybind.value.filter((k) => isModifier(k));
keybind.value.push(key);
}
updateKeybind();
showEmptyKeybindError.value = false;
};
const saveKeybind = async () => {
const finalKeybind = keybind.value.filter(k => k);
if (finalKeybind.length > 0) {
await $settings.saveSetting("keybind", JSON.stringify(finalKeybind));
if (keybind.value.length > 0) {
await $settings.saveSetting("keybind", JSON.stringify(keybind.value));
router.push("/");
} else {
showEmptyKeybindError.value = true;
@ -180,27 +177,67 @@ const toggleAutostart = async () => {
await $settings.saveSetting("autostart", autostart.value ? "true" : "false");
};
os.value = platform();
onMounted(async () => {
autostart.value = (await $settings.getSetting("autostart")) === "true";
const metaOrCtrlKey = $keyboard.currentOS === "macos" ? $keyboard.Key.Meta : $keyboard.Key.Control;
listeners.push(
$keyboard.listen([metaOrCtrlKey, $keyboard.Key.Enter], saveKeybind, { prevent: true, ignoreIfEditable: true })
);
listeners.push(
$keyboard.listen([$keyboard.Key.Escape], () => {
if (!isKeybindInputFocused.value && !blurredByEscape.value) {
$keyboard.setupKeybindCapture({
onCapture: (key: string) => {
if (isKeybindInputFocused.value) {
const keyValue = key as KeyValues;
if (isModifier(keyValue)) {
activeModifiers.add(keyValue);
} else if (!keybind.value.includes(keyValue)) {
keybind.value = keybind.value.filter((k) => isModifier(k));
keybind.value.push(keyValue);
}
updateKeybind();
showEmptyKeybindError.value = false;
}
},
onComplete: () => {
if (isKeybindInputFocused.value) {
keybindInput.value?.blur();
} else {
router.push("/");
}
if(blurredByEscape.value) blurredByEscape.value = false;
}, { prevent: true })
);
}
});
if (os.value === "macos") {
$keyboard.on("settings", [$keyboard.Key.LeftMeta, $keyboard.Key.Enter], () => {
saveKeybind();
}, { priority: $keyboard.PRIORITY.HIGH });
$keyboard.on("settings", [$keyboard.Key.RightMeta, $keyboard.Key.Enter], () => {
saveKeybind();
}, { priority: $keyboard.PRIORITY.HIGH });
} else {
$keyboard.on("settings", [$keyboard.Key.LeftControl, $keyboard.Key.Enter], () => {
saveKeybind();
}, { priority: $keyboard.PRIORITY.HIGH });
$keyboard.on("settings", [$keyboard.Key.RightControl, $keyboard.Key.Enter], () => {
saveKeybind();
}, { priority: $keyboard.PRIORITY.HIGH });
}
$keyboard.on("settings", [$keyboard.Key.Escape], () => {
if (!isKeybindInputFocused.value && !blurredByEscape.value) {
router.push("/");
}
blurredByEscape.value = false;
}, { priority: $keyboard.PRIORITY.HIGH });
$keyboard.disableContext("main");
$keyboard.enableContext("settings");
autostart.value = (await $settings.getSetting("autostart")) === "true";
});
onUnmounted(() => {
listeners.forEach(unlisten => unlisten());
listeners.length = 0;
$keyboard.disableContext("settings");
});
</script>

View file

@ -1,27 +1,281 @@
import { Key, keyboard } from "wrdu-keyboard";
import { platform } from "@tauri-apps/plugin-os";
import { useKeyboard, Key } from "@waradu/keyboard";
type KeyboardHandler = (event: KeyboardEvent) => void;
const activeContexts = new Set<string>();
const handlersByContext: Record<
string,
Array<{
keys: Key[];
callback: KeyboardHandler;
prevent: boolean;
priority?: number;
}>
> = {};
const PRIORITY = {
HIGH: 100,
MEDIUM: 50,
LOW: 0,
};
let currentOS = "windows";
const useKeyboard = {
PRIORITY,
registerContext: (contextName: string) => {
if (!handlersByContext[contextName]) {
handlersByContext[contextName] = [];
}
},
enableContext: (contextName: string) => {
if (!handlersByContext[contextName]) {
useKeyboard.registerContext(contextName);
}
activeContexts.add(contextName);
initKeyboardHandlers();
},
disableContext: (contextName: string) => {
activeContexts.delete(contextName);
initKeyboardHandlers();
},
on: (
contextName: string,
keys: Key[],
callback: KeyboardHandler,
options: { prevent?: boolean; priority?: number } = {}
) => {
if (!handlersByContext[contextName]) {
useKeyboard.registerContext(contextName);
}
const existingHandlerIndex = handlersByContext[contextName].findIndex(
(handler) =>
handler.keys.length === keys.length &&
handler.keys.every((key, i) => key === keys[i]) &&
handler.callback.toString() === callback.toString()
);
if (existingHandlerIndex !== -1) {
handlersByContext[contextName][existingHandlerIndex] = {
keys,
callback,
prevent: options.prevent ?? true,
priority: options.priority ?? PRIORITY.LOW,
};
} else {
handlersByContext[contextName].push({
keys,
callback,
prevent: options.prevent ?? true,
priority: options.priority ?? PRIORITY.LOW,
});
}
if (activeContexts.has(contextName)) {
initKeyboardHandlers();
}
},
clearAll: () => {
keyboard.clear();
},
setupAppShortcuts: (options: {
onNavigateUp?: () => void;
onNavigateDown?: () => void;
onSelect?: () => void;
onEscape?: () => void;
onToggleActions?: () => void;
contextName?: string;
priority?: number;
}) => {
const {
onNavigateUp,
onNavigateDown,
onSelect,
onEscape,
onToggleActions,
contextName = "app",
priority = PRIORITY.LOW,
} = options;
if (!handlersByContext[contextName]) {
useKeyboard.registerContext(contextName);
}
if (onNavigateUp) {
useKeyboard.on(contextName, [Key.UpArrow], () => onNavigateUp(), {
priority,
});
}
if (onNavigateDown) {
useKeyboard.on(contextName, [Key.DownArrow], () => onNavigateDown(), {
priority,
});
}
if (onSelect) {
useKeyboard.on(contextName, [Key.Enter], () => onSelect(), { priority });
}
if (onEscape) {
useKeyboard.on(contextName, [Key.Escape], () => onEscape(), { priority });
}
if (onToggleActions) {
const togglePriority = Math.max(priority, PRIORITY.HIGH);
if (currentOS === "macos") {
useKeyboard.on(
contextName,
[Key.LeftMeta, Key.K],
() => onToggleActions(),
{ priority: togglePriority }
);
useKeyboard.on(
contextName,
[Key.RightMeta, Key.K],
() => onToggleActions(),
{ priority: togglePriority }
);
} else {
useKeyboard.on(
contextName,
[Key.LeftControl, Key.K],
() => onToggleActions(),
{ priority: togglePriority }
);
useKeyboard.on(
contextName,
[Key.RightControl, Key.K],
() => onToggleActions(),
{ priority: togglePriority }
);
}
}
},
setupKeybindCapture: (options: {
onCapture: (key: string) => void;
onComplete: () => void;
}) => {
const { onCapture, onComplete } = options;
keyboard.prevent.down([Key.All], (event: KeyboardEvent) => {
if (event.code === "Escape") {
onComplete();
return;
}
onCapture(event.code);
});
},
};
const initKeyboardHandlers = () => {
keyboard.clear();
let allHandlers: Array<{
keys: Key[];
callback: KeyboardHandler;
prevent: boolean;
priority: number;
contextName: string;
}> = [];
for (const contextName of activeContexts) {
const handlers = handlersByContext[contextName] || [];
allHandlers = [
...allHandlers,
...handlers.map((handler) => ({
...handler,
priority: handler.priority ?? PRIORITY.LOW,
contextName,
})),
];
}
allHandlers.sort((a, b) => b.priority - a.priority);
const handlersByKeyCombination: Record<
string,
Array<(typeof allHandlers)[0]>
> = {};
allHandlers.forEach((handler) => {
const keyCombo = handler.keys.sort().join("+");
if (!handlersByKeyCombination[keyCombo]) {
handlersByKeyCombination[keyCombo] = [];
}
handlersByKeyCombination[keyCombo].push(handler);
});
Object.entries(handlersByKeyCombination).forEach(([_keyCombo, handlers]) => {
handlers.sort((a, b) => b.priority - a.priority);
const handler = handlers[0];
const wrappedCallback: KeyboardHandler = (event) => {
const isMetaCombo =
handler.keys.length > 1 &&
(handler.keys.includes(Key.LeftMeta) ||
handler.keys.includes(Key.RightMeta) ||
handler.keys.includes(Key.LeftControl) ||
handler.keys.includes(Key.RightControl));
const isNavigationKey =
event.key === "ArrowUp" ||
event.key === "ArrowDown" ||
event.key === "Enter" ||
event.key === "Escape";
const isInInput =
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement;
if (
(isMetaCombo || isNavigationKey || !isInInput) &&
activeContexts.has(handler.contextName)
) {
handler.callback(event);
}
};
if (handler.prevent) {
keyboard.prevent.down(handler.keys, wrappedCallback);
} else {
keyboard.down(handler.keys, wrappedCallback);
}
});
};
export default defineNuxtPlugin(async (nuxtApp) => {
const keyboardInstance = useKeyboard();
let currentOS = "windows";
try {
const osName = await Promise.resolve(platform());
const osName = platform();
currentOS = osName.toLowerCase().includes("mac") ? "macos" : "windows";
} catch (error) {
console.error("Error detecting platform:", error);
}
// Defer initialization until the app is mounted
nuxtApp.hook('app:mounted', () => {
keyboardInstance.init();
initKeyboardHandlers();
nuxtApp.hook("page:finish", () => {
initKeyboardHandlers();
});
nuxtApp.provide('keyboard', {
listen: keyboardInstance.listen.bind(keyboardInstance),
init: keyboardInstance.init.bind(keyboardInstance),
Key,
currentOS,
// Provide a clear method if users need to manually clear all listeners from the instance
clearAll: keyboardInstance.clear ? keyboardInstance.clear.bind(keyboardInstance) : () => { console.warn('@waradu/keyboard instance does not have a clear method'); }
});
return {
provide: {
keyboard: {
...useKeyboard,
Key,
},
},
};
});

46
src-tauri/Cargo.lock generated
View file

@ -105,9 +105,9 @@ dependencies = [
[[package]]
name = "arbitrary"
version = "1.4.1"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dde20b3d026af13f561bdd0f15edf01fc734f0dafcedbaf42bba506a9517f223"
checksum = "7d5a26814d8dcb93b0e5a0ff3c6d80a8843bafb21b39e8e18a6f05471870e110"
dependencies = [
"derive_arbitrary",
]
@ -628,13 +628,12 @@ dependencies = [
[[package]]
name = "cc"
version = "1.2.16"
version = "1.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c"
checksum = "504bdec147f2cc13c8b57ed9401fd8a147cc66b67ad5cb241394244f2c947549"
dependencies = [
"jobserver",
"libc",
"shlex",
]
[[package]]
@ -999,9 +998,9 @@ dependencies = [
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
version = "0.8.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
[[package]]
name = "crunchy"
@ -1125,9 +1124,9 @@ dependencies = [
[[package]]
name = "derive_arbitrary"
version = "1.4.1"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30542c1ad912e0e3d22a1935c290e12e8a29d704a420177a31faad4a601a0800"
checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611"
dependencies = [
"proc-macro2",
"quote",
@ -2620,7 +2619,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9"
dependencies = [
"hermit-abi 0.5.0",
"libc",
"windows-sys 0.59.0",
"windows-sys 0.52.0",
]
[[package]]
@ -2842,7 +2841,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
dependencies = [
"cfg-if",
"windows-targets 0.48.5",
"windows-targets 0.52.6",
]
[[package]]
@ -3574,9 +3573,9 @@ checksum = "cde51589ab56b20a6f686b2c68f7a0bd6add753d697abf720d63f8db3ab7b1ad"
[[package]]
name = "openssl"
version = "0.10.71"
version = "0.10.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e14130c6a98cd258fdcb0fb6d744152343ff729cbfcb28c656a9d12b999fbcd"
checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1"
dependencies = [
"bitflags 2.8.0",
"cfg-if",
@ -3606,9 +3605,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-sys"
version = "0.9.106"
version = "0.9.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bb61ea9811cc39e3c2069f40b8b8e2e70d8569b361f879786cc7ed48b777cdd"
checksum = "7f9e8deee91df40a943c71b917e5874b951d32a802526c85721ce3b776c929d6"
dependencies = [
"cc",
"libc",
@ -4561,14 +4560,15 @@ checksum = "57397d16646700483b67d2dd6511d79318f9d057fdbd21a4066aeac8b41d310a"
[[package]]
name = "ring"
version = "0.17.14"
version = "0.17.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.15",
"libc",
"spin",
"untrusted",
"windows-sys 0.52.0",
]
@ -4971,12 +4971,6 @@ dependencies = [
"digest",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signal-hook-registry"
version = "1.4.2"
@ -7733,9 +7727,9 @@ dependencies = [
[[package]]
name = "zip"
version = "2.4.1"
version = "2.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "938cc23ac49778ac8340e366ddc422b2227ea176edb447e23fc0627608dddadd"
checksum = "40dd8c92efc296286ce1fbd16657c5dbefff44f1b4ca01cc5f517d8b7b3d3e2e"
dependencies = [
"arbitrary",
"crc32fast",
@ -7743,7 +7737,7 @@ dependencies = [
"displaydoc",
"indexmap 2.3.0",
"memchr",
"thiserror 2.0.3",
"thiserror 1.0.63",
]
[[package]]

27
types/keyboard.d.ts vendored
View file

@ -1,27 +0,0 @@
import type { Key as WaraduKey, useKeyboard } from '@waradu/keyboard';
declare module '#app' {
interface NuxtApp {
$keyboard: {
listen: ReturnType<typeof useKeyboard>['listen'];
init: ReturnType<typeof useKeyboard>['init'];
Key: typeof WaraduKey;
currentOS: string;
clearAll: () => void;
};
}
}
declare module 'vue' {
interface ComponentCustomProperties {
$keyboard: {
listen: ReturnType<typeof useKeyboard>['listen'];
init: ReturnType<typeof useKeyboard>['init'];
Key: typeof WaraduKey;
currentOS: string;
clearAll: () => void;
};
}
}
export {};