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 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. 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) <img src="./public/windows.png"> Windows (x64)
</a> </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) Windows (arm64)
</a> </a>
<br> <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) <img src="./public/linux.png"> Linux (deb)
</a> </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) Linux (rpm)
</a> </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) Linux (AppImage)
</a> </a>
<br> <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) <img src="./public/apple.png"> macOS (Silicon)
</a> </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) macOS (Intel)
</a> </a>
<br> <br>
@ -123,7 +123,7 @@ bun build
## 📝 License ## 📝 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-link]: https://codespaces.new/0pandadev/Qopy
[codespaces-shield]: https://github.com/codespaces/badge.svg [codespaces-shield]: https://github.com/codespaces/badge.svg

View file

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

View file

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

View file

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

View file

@ -1,27 +1,281 @@
import { Key, keyboard } from "wrdu-keyboard";
import { platform } from "@tauri-apps/plugin-os"; 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) => { export default defineNuxtPlugin(async (nuxtApp) => {
const keyboardInstance = useKeyboard();
let currentOS = "windows";
try { try {
const osName = await Promise.resolve(platform()); const osName = platform();
currentOS = osName.toLowerCase().includes("mac") ? "macos" : "windows"; currentOS = osName.toLowerCase().includes("mac") ? "macos" : "windows";
} catch (error) { } catch (error) {
console.error("Error detecting platform:", error); console.error("Error detecting platform:", error);
} }
// Defer initialization until the app is mounted initKeyboardHandlers();
nuxtApp.hook('app:mounted', () => {
keyboardInstance.init(); nuxtApp.hook("page:finish", () => {
initKeyboardHandlers();
}); });
nuxtApp.provide('keyboard', { return {
listen: keyboardInstance.listen.bind(keyboardInstance), provide: {
init: keyboardInstance.init.bind(keyboardInstance), keyboard: {
Key, ...useKeyboard,
currentOS, Key,
// 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'); } },
}); };
}); });

46
src-tauri/Cargo.lock generated
View file

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