Line data Source code
1 : import { onMounted, readonly, ref, watch } from 'vue'
2 : import type { Ref } from 'vue'
3 :
4 : import { isInChina } from './regionProbe'
5 :
6 : export type RegionGateStatus = 'pending' | 'blocked' | 'allowed'
7 :
8 : /**
9 : * Gates email sign-up on the client's region. Starts `pending` and always
10 : * leaves it. Do not race this against a timeout: that decides `allowed` while a
11 : * real `blocked` answer is still in flight. The probe runs when the
12 : * component has mounted and `enabled` is true, so a host that gates its
13 : * sign-up form behind a flag never probes for a page it does not show;
14 : * disabling returns to `pending` and re-enabling probes again.
15 : */
16 13 : export function useRegionGate(enabled: Readonly<Ref<boolean>> = ref(true)): {
17 : status: Readonly<Ref<RegionGateStatus>>
18 : } {
19 13 : const status = ref<RegionGateStatus>('pending')
20 : // Bumped on every enabled change; a probe publishes only for the
21 : // generation that started it, so a result landing after a disable (or
22 : // before a re-enable) cannot leave a stale answer behind.
23 13 : let generation = 0
24 :
25 13 : onMounted(() => {
26 13 : watch(
27 : enabled,
28 : async (on) => {
29 13 : const probeGeneration = ++generation
30 13 : if (!on) {
31 0 : status.value = 'pending'
32 0 : return
33 : }
34 13 : const blocked = await isInChina().catch(() => false)
35 12 : if (probeGeneration !== generation) return
36 13 : status.value = blocked ? 'blocked' : 'allowed'
37 : },
38 : { immediate: true }
39 : )
40 : })
41 :
42 13 : return { status: readonly(status) }
43 : }
|