game-village-politics-frontend/app/composables/useCardLayout.ts

91 lines
3.0 KiB
TypeScript

/** Where the player put the boxes of one dock: their order, which are folded, which float and where. */
export interface CardLayout {
order: string[]
collapsed: Record<string, boolean>
/** Viewport pixels of a floating box's top-left corner. */
floating: Record<string, { x: number; y: number }>
}
const empty = (): CardLayout => ({ order: [], collapsed: {}, floating: {} })
function load(key: string): CardLayout {
try {
const raw = localStorage.getItem(key)
return raw ? { ...empty(), ...JSON.parse(raw) } : empty()
} catch {
return empty()
}
}
/**
* The layout of one dock (`overview`, `map`), kept in this browser only: it is a
* per-viewer convenience, so the page works the same without storage.
*/
export function useCardLayout(scope: string) {
const key = `vp.layout.${scope}`
const layout = useState<CardLayout>(key, () => (import.meta.client ? load(key) : empty()))
watch(
layout,
(value) => {
try {
localStorage.setItem(key, JSON.stringify(value))
} catch {
// Storage off: the layout lasts until the page reloads.
}
},
{ deep: true },
)
/** Every key in the player's order; keys the player never moved keep their default place. */
function ordered(defaults: string[]): string[] {
const known = layout.value.order.filter((k) => defaults.includes(k))
for (const [i, k] of defaults.entries()) {
if (known.includes(k)) continue
// A new box goes after the default one before it.
const before = defaults.slice(0, i).reverse().find((d) => known.includes(d))
known.splice(before ? known.indexOf(before) + 1 : 0, 0, k)
}
return known
}
function toggle(card: string) {
layout.value.collapsed = { ...layout.value.collapsed, [card]: !layout.value.collapsed[card] }
}
/** Put a box back into the dock at a place among the docked ones. */
function dock(card: string, before: string | null, defaults: string[]) {
const order = ordered(defaults).filter((k) => k !== card)
const at = before ? order.indexOf(before) : -1
order.splice(at < 0 ? order.length : at, 0, card)
const { [card]: _, ...floating } = layout.value.floating
layout.value = { ...layout.value, order, floating }
}
function float(card: string, x: number, y: number) {
layout.value.floating = { ...layout.value.floating, [card]: { x: Math.round(x), y: Math.round(y) } }
}
return { layout, ordered, toggle, dock, float }
}
/** A window's offset from where its frame docks it, kept per browser; one place for every window. */
export function useWindowOffset(name = 'main') {
const key = `vp.window.${name}`
const offset = useState<{ x: number; y: number }>(key, () => {
if (!import.meta.client) return { x: 0, y: 0 }
try {
return { x: 0, y: 0, ...JSON.parse(localStorage.getItem(key) ?? '{}') }
} catch {
return { x: 0, y: 0 }
}
})
watch(offset, (value) => {
try {
localStorage.setItem(key, JSON.stringify(value))
} catch {
// Storage off: the window stays put until the page reloads.
}
})
return offset
}