All files / submodels/goTo update.ts

73.58% Statements 39/53
50% Branches 8/16
77.41% Functions 24/31
72% Lines 36/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170                    4x 4x       4x 10x 10x 4x     4x     6x   6x               4x           10x 10x 7x   3x       4x 6x 6x   6x 6x               4x 37x 10x   10x 10x       10x     7x     6x 5x               4x   2x           7x 7x                 4x 4x   4x                     4x                                                                                                        
import { Data, Duration, Effect, Option, Schema, String } from 'effect'
import { Command, type Update } from 'foldkit'
import { modifyFields } from 'foldkit/struct'
 
import { parseCoordinate } from '../../core/systems/registry'
import { Message, OutMessage } from './message'
import { type Model, Status } from './model'
 
type UpdateReturn = Update.ReturnWithOutMessage<Model, Message, OutMessage>
 
const searchFailureReason = (query: string): string =>
  String.isEmpty(query)
    ? 'Enter a coordinate'
    : `Could not recognise "${query}"`
 
const submitSearch = (model: Model): UpdateReturn => {
  const query = model.query.trim()
  return Option.match(parseCoordinate(query), {
    onNone: () => ({
      model: modifyFields(model, {
        status: () =>
          Status.SearchFailed({ reason: searchFailureReason(query) }),
      }),
    }),
    onSome: ({ kind, point, maybeBounds, maybeCaution }) => ({
      model: modifyFields(model, {
        status: () => Status.Found({ kind, maybeCaution }),
      }),
      outMessage: OutMessage.ChoseLocation({ point, maybeBox: maybeBounds }),
    }),
  })
}
 
/** A location result counts only for the request in flight; typing, a search or a newer request cancels it. */
const whenAnswering = (
  model: Model,
  requestId: number,
  toResult: () => UpdateReturn,
): UpdateReturn => {
  const isCurrentRequest =
    Status.guards.Locating(model.status) && model.status.requestId === requestId
  if (isCurrentRequest) {
    return toResult()
  } else {
    return { model }
  }
}
 
const startLocating = (model: Model): UpdateReturn => {
  const requestId = model.locateRequestCount + 1
  return {
    model: modifyFields(model, {
      status: () => Status.Locating({ requestId }),
      locateRequestCount: () => requestId,
    }),
    commands: [GetCurrentPosition({ requestId })],
  }
}
 
// UPDATE
 
export const update = (model: Model, message: Message) =>
  Message.match<UpdateReturn>(message, {
    UpdatedQuery: ({ value }) => ({
      model: modifyFields(model, {
        query: () => value,
        status: () => Status.Idle(),
      }),
    }),
 
    SubmittedSearch: () => submitSearch(model),
 
    ClickedFindMyLocation: () =>
      Status.guards.Locating(model.status) ? { model } : startLocating(model),
 
    SucceededGetCurrentPosition: ({ requestId, point }) =>
      whenAnswering(model, requestId, () => ({
        model: modifyFields(model, { status: () => Status.Idle() }),
        outMessage: OutMessage.ChoseLocation({
          point,
          maybeBox: Option.none(),
        }),
      })),
 
    FailedGetCurrentPosition: ({ requestId, reason }) =>
      whenAnswering(model, requestId, () => ({
        model: modifyFields(model, {
          status: () => Status.LocateFailed({ reason }),
        }),
      })),
  })
 
/** The cue moved some other way (a map click, or clearing it), so the last status no longer applies. */
export const clearStatus = (model: Model): Update.Return<Model, Message> => ({
  model: modifyFields(model, { status: () => Status.Idle() }),
})
 
// COMMAND
 
class GeolocationError extends Data.TaggedError('GeolocationError')<{
  readonly reason: string
}> {}
 
const LOCATION_TIMEOUT = Duration.seconds(10)
const LOCATION_MAX_AGE = Duration.seconds(30)
 
const locationErrorText = (error: GeolocationPositionError): string => {
  if (error.code === error.PERMISSION_DENIED) {
    return 'Location permission denied.'
  }
  if (error.code === error.TIMEOUT) {
    return 'Location timed out.'
  }
  return 'Location unavailable.'
}
 
/** Ask the browser for the device position. The browser asks the user for permission the first time. */
export const GetCurrentPosition = Command.define('GetCurrentPosition', {
  args: { requestId: Schema.Int },
  messages: [
    Message.SucceededGetCurrentPosition,
    Message.FailedGetCurrentPosition,
  ],
  execute: ({ requestId }) =>
    Effect.callback<GeolocationPosition, GeolocationError>(resume => {
      if (typeof navigator === 'undefined' || !navigator.geolocation) {
        resume(
          Effect.fail(
            new GeolocationError({
              reason: 'This browser cannot share its location.',
            }),
          ),
        )
        return
      }
      navigator.geolocation.getCurrentPosition(
        position => resume(Effect.succeed(position)),
        error =>
          resume(
            Effect.fail(
              new GeolocationError({ reason: locationErrorText(error) }),
            ),
          ),
        {
          enableHighAccuracy: true,
          timeout: Duration.toMillis(LOCATION_TIMEOUT),
          maximumAge: Duration.toMillis(LOCATION_MAX_AGE),
        },
      )
    }).pipe(
      Effect.map(position =>
        Message.SucceededGetCurrentPosition({
          requestId,
          point: {
            lat: position.coords.latitude,
            lon: position.coords.longitude,
          },
        }),
      ),
      Effect.catch(error =>
        Effect.succeed(
          Message.FailedGetCurrentPosition({
            requestId,
            reason: error.reason,
          }),
        ),
      ),
    ),
})