mirror of
https://github.com/CharaChorder/DeviceManager.git
synced 2026-01-20 08:52:59 +00:00
feat: periodically update os-layout in the background
fix: remove dead code in layout detection fixes #78 resolves #79
This commit is contained in:
@@ -1,40 +1,25 @@
|
||||
import {persistentWritable} from "$lib/storage"
|
||||
import {get} from "svelte/store"
|
||||
import {get, writable} from "svelte/store"
|
||||
|
||||
export const osLayout = persistentWritable<Record<string, string>>("os-layout", {})
|
||||
export const osLayout = writable<Map<string, string>>(new Map())
|
||||
|
||||
const keysCurrentlyDown = new Set<string>()
|
||||
|
||||
function keydown({code, key}: KeyboardEvent) {
|
||||
const keys = [...keysCurrentlyDown]
|
||||
keysCurrentlyDown.add(code)
|
||||
|
||||
const keyString = JSON.stringify([...keys.sort(), code])
|
||||
if (keyString in get(osLayout) || get(osLayout)[JSON.stringify([code])] === key) return
|
||||
|
||||
osLayout.update(layout => {
|
||||
layout[keyString] = key
|
||||
return layout
|
||||
})
|
||||
}
|
||||
|
||||
function keyup({code}: KeyboardEvent) {
|
||||
keysCurrentlyDown.delete(code)
|
||||
}
|
||||
|
||||
export function runLayoutDetection() {
|
||||
if ("keyboard" in navigator) {
|
||||
;(navigator.keyboard as any).getLayoutMap().then((layout: Map<string, string>) => {
|
||||
osLayout.update(osLayout => {
|
||||
Object.assign(
|
||||
osLayout,
|
||||
Object.fromEntries([...layout.entries()].map(([key, value]) => [JSON.stringify([key]), value])),
|
||||
)
|
||||
return osLayout
|
||||
})
|
||||
})
|
||||
async function updateLayout() {
|
||||
const layout: Map<string, string> = await (navigator as any).keyboard.getLayoutMap()
|
||||
const currentLayout = get(osLayout)
|
||||
if (
|
||||
layout.size !== currentLayout.size ||
|
||||
[...layout.keys()].some(key => layout.get(key) !== currentLayout.get(key))
|
||||
) {
|
||||
osLayout.set(layout)
|
||||
}
|
||||
}
|
||||
|
||||
export function runLayoutDetection(): () => void {
|
||||
if ("keyboard" in navigator) {
|
||||
updateLayout()
|
||||
const timer = setInterval(updateLayout, 5000)
|
||||
return () => clearInterval(timer)
|
||||
} else {
|
||||
console.warn("Keyboard API not supported")
|
||||
return () => {}
|
||||
}
|
||||
// TODO: do we want this?
|
||||
//window.addEventListener("keydown", keydown)
|
||||
//window.addEventListener("keyup", keyup)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user