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

179 lines
6.3 KiB
TypeScript
Raw Normal View History

import type { Cost, GameError, MarketOffers, MarketState, TradePlan, TradeResource, TradeSide, VillageUpdated } from '~/types/game'
import { toRaw } from 'vue'
import type { VillageContext } from './useVillage'
/**
* The market of the village in `v`: the last `market.show` snapshot and the market's
* intents. Every mutation answers with `market.show`; the village is refreshed after it
* for the stock. Sending, posting and accepting offers and creating routes commit
* resources, so they lock their forms (`busy`); cancelling, pausing, editing and deleting
* show their result at once and confirm in the background. Call it from a component's
* setup(): it listens for `village:updated` while mounted.
*/
export function useMarket(v: VillageContext) {
const state = ref<MarketState | null>(null)
const busy = ref(false)
const error = ref<string | null>(null)
const generic = useErrorText()
const { t, te } = useI18n()
/** Refusals in the market's words first (`market.errors.<code>`), then the game's. */
const errorText = (e: unknown) => {
const code = (e as Partial<GameError> | null)?.code
return code && te(`market.errors.${code}`) ? t(`market.errors.${code}`) : generic(e)
}
const villageId = computed(() => v.village.value?.id ?? null)
/** Server time of the snapshot shown: an older answer never replaces it. */
let shownAt = 0
let blocking = 0
function apply(s: MarketState) {
const at = Date.parse(s.server_time)
if (at < shownAt) return
shownAt = at
state.value = s
}
async function run(event: string, data: object = {}, opts: { block?: boolean; optimistic?: (s: MarketState) => void } = {}) {
const id = villageId.value
if (id === null) return false
const block = opts.block ?? !opts.optimistic
if (block) busy.value = ++blocking > 0
error.value = null
if (opts.optimistic && state.value) {
const copy = JSON.parse(JSON.stringify(toRaw(state.value))) as MarketState
opts.optimistic(copy)
state.value = copy
}
try {
apply(await ws.send<MarketState>(event, { village_id: id, ...data }))
v.refresh()
return true
} catch (e) {
if (opts.optimistic) load()
error.value = errorText(e)
return false
} finally {
if (block) busy.value = --blocking > 0
}
}
// Reloads run quietly, one at a time; a call while one runs asks for one more after it.
let loading: Promise<void> | null = null
let again = false
async function load(): Promise<void> {
const id = villageId.value
if (id === null) return
if (loading) {
again = true
return loading
}
loading = (async () => {
try {
apply(await ws.send<MarketState>('market.show', { village_id: id }))
} catch (e) {
error.value = errorText(e)
}
})()
try {
await loading
} finally {
loading = null
if (again) {
again = false
load()
}
}
}
watch(
villageId,
() => {
state.value = null
shownAt = 0
load()
},
{ immediate: true },
)
// Reload once when the next trade arrives or the next route runs.
const nextDue = computed(() => {
const s = state.value
if (!s) return null
const times = [...s.trades.map((t) => Date.parse(t.arrives_at)), ...s.routes.filter((r) => !r.paused).map((r) => Date.parse(r.next_at))]
return times.length ? Math.min(...times) : null
})
watch(
() => nextDue.value !== null && v.now.value >= nextDue.value,
(due) => {
if (due) load()
},
)
ws.listenWhileMounted<VillageUpdated>('village:updated', null, (data) => {
if (data.village_id === villageId.value) load()
})
return {
state,
busy,
error,
load,
/** Who lives on the field and how long merchants walk; the refusal's text when the server says no. */
preview: async (x: number, y: number): Promise<{ plan: TradePlan | null; refusal: string | null }> => {
try {
return { plan: await ws.send<TradePlan>('market.preview', { village_id: villageId.value, x, y }), refusal: null }
} catch (e) {
return { plan: null, refusal: errorText(e) }
}
},
send: (x: number, y: number, cargo: Cost) => run('market.send', { x, y, ...cargo }),
/** The world's open offers, nearest first; null after a refusal (shown in `error`). */
offers: async (give: TradeResource | null, want: TradeResource | null): Promise<MarketOffers | null> => {
try {
return await ws.send<MarketOffers>('market.offers', { village_id: villageId.value, ...(give ? { give } : {}), ...(want ? { want } : {}) })
} catch (e) {
error.value = errorText(e)
return null
}
},
offer: (give: TradeSide, want: TradeSide, count: number) => run('market.offer', { give, want, count }),
cancelOffer: (offerId: number) =>
run('market.cancelOffer', { offer_id: offerId }, {
optimistic: (s) => {
const o = s.offers.find((x) => x.id === offerId)
if (!o) return
s.offers = s.offers.filter((x) => x !== o)
if (s.market) {
s.market.free += o.count * o.merchants
s.market.busy -= o.count * o.merchants
}
},
}),
accept: (offerId: number, count: number) => run('market.accept', { offer_id: offerId, count }),
routeCreate: (x: number, y: number, resources: Cost, every: number) => run('market.routeCreate', { x, y, ...resources, every }),
routeUpdate: (routeId: number, change: Partial<Cost> & { every?: number; paused?: boolean }) =>
run('market.routeUpdate', { route_id: routeId, ...change }, {
optimistic: (s) => {
const r = s.routes.find((x) => x.id === routeId)
if (!r) return
for (const res of ['wood', 'clay', 'iron'] as const) if (change[res] !== undefined) r.resources[res] = change[res]
if (change.every !== undefined) r.every = change.every
// Pausing by hand or resuming clears the reason the route paused itself.
if (change.paused !== undefined) {
r.paused = change.paused
r.paused_reason = null
}
},
}),
routeDelete: (routeId: number) =>
run('market.routeDelete', { route_id: routeId }, {
optimistic: (s) => {
s.routes = s.routes.filter((x) => x.id !== routeId)
},
}),
}
}
export type MarketContext = ReturnType<typeof useMarket>