recoil#DefaultValue TypeScript Examples

The following examples show how to use recoil#DefaultValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: authContext.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
AuthContextHandler = selector<{ fade?: boolean, process?: Process, error?: string | null }>({
    key: 'AuthContextHandler',
    get: ({get}) => {
        const errors = get(AuthErrors);
        const error = get(AuthContextErrorAtom);
        let newError: string = '';

        if (errors.emailError)
            newError = 'enter a valid email address';

        else if (errors.passError)
            newError = 'Password must contain a number, a capital and a small letter';

        else if (errors.authError)
            newError = 'invalid auth key';

        return {
            fade: error ? false : get(AuthFade),
            process: get(AuthContextProcessAtom),
            error: newError === '' ? error : newError
        }
    }, set: ({set, get}, newValue) => {
        const auth = get(Authenticated);
        if (!(newValue instanceof DefaultValue)) {
            newValue.process && NProgress.start();
            if (newValue.process && auth)
                set(AuthContextProcessAtom, newValue.process);

            if (newValue.error !== undefined)
                set(AuthContextErrorAtom, newValue.error);

            if (newValue.fade !== undefined && auth) {
                set(AuthFade, newValue.fade);
                NProgress.done();
            }
        }
    }
})
Example #2
Source File: gridLibraryContext.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
GridSelector = selector<{ type: string, value: string } | null>({
    key: 'GridSelector',
    get: ({get}) => {
        const type = get(GridTypeAtom);
        const value = get(GridValueAtom);

        if (type === null || value === null)
            return null

        return {type, value}
    }, set: ({set}, newValue) => {
        if (!(newValue instanceof DefaultValue)) {
            if (newValue) {
                set(GridValueAtom, newValue.value);
                set(GridTypeAtom, newValue.type);
            }
        }
    }
})
Example #3
Source File: navigation.tsx    From frames with Mozilla Public License 2.0 6 votes vote down vote up
NavSectionAndOpacity = selector<NavSectionAndOpacity>({
    key: 'NavSectionAndOpacity',
    get: ({get}) => {
        let opacity = get(NavOpacityAtom);
        const section = get(NavConTextAtom);
        opacity = opacity === 0 ? opacity : 1 - opacity > 1 ? 1 : 1 - opacity;
        return {opacity, section}
    },
    set: ({get, set}, newValue) => {
        if (!(newValue instanceof DefaultValue)) {
            newValue.section && set(NavConTextAtom, newValue.section);
            newValue.opacity && set(NavOpacityAtom, newValue.opacity);
            return;
        }
    }
})
Example #4
Source File: authContext.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
AuthContextHandler = selector<{ fade?: boolean, process?: Process, error?: string | null }>({
    key: 'AuthContextHandler',
    get: ({get}) => {
        const errors = get(AuthErrors);
        const error = get(AuthContextErrorAtom);
        let newError: string = '';

        if (errors.emailError)
            newError = 'enter a valid email address';

        else if (errors.passError)
            newError = 'Password must contain a number, a capital and a small letter';

        else if (errors.authError)
            newError = 'invalid auth key';

        return {
            fade: error ? false : get(AuthFade),
            process: get(AuthContextProcessAtom),
            error: newError === '' ? error : newError
        }
    }, set: ({set, get}, newValue) => {
        const auth = get(Authenticated);
        if (!(newValue instanceof DefaultValue)) {
            newValue.process && NProgress.start();
            if (newValue.process && auth)
                set(AuthContextProcessAtom, newValue.process);

            if (newValue.error !== undefined)
                set(AuthContextErrorAtom, newValue.error);

            if (newValue.fade !== undefined && auth) {
                set(AuthFade, newValue.fade);
                NProgress.done();
            }
        }
    }
})
Example #5
Source File: gridLibraryContext.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
GridSelector = selector<{ type: string, value: string } | null>({
    key: 'GridSelector',
    get: ({get}) => {
        const type = get(GridTypeAtom);
        const value = get(GridValueAtom);

        if (type === null || value === null)
            return null

        return {type, value}
    }, set: ({set}, newValue) => {
        if (!(newValue instanceof DefaultValue)) {
            if (newValue) {
                set(GridValueAtom, newValue.value);
                set(GridTypeAtom, newValue.type);
            }
        }
    }
})
Example #6
Source File: navigation.tsx    From frames with Mozilla Public License 2.0 6 votes vote down vote up
NavSectionAndOpacity = selector<NavSectionAndOpacity>({
    key: 'NavSectionAndOpacity',
    get: ({get}) => {
        let opacity = get(NavOpacityAtom);
        const section = get(NavConTextAtom);
        opacity = opacity === 0 ? opacity : 1 - opacity > 1 ? 1 : 1 - opacity;
        return {opacity, section}
    },
    set: ({get, set}, newValue) => {
        if (!(newValue instanceof DefaultValue)) {
            newValue.section && set(NavConTextAtom, newValue.section);
            newValue.opacity && set(NavOpacityAtom, newValue.opacity);
            return;
        }
    }
})
Example #7
Source File: bindings.tsx    From arduino-web-oscilloscope with MIT License 6 votes vote down vote up
receiveFullState = selector<Data>({
  key: 'receiveFullState-this shouldnt be a selector',
  get: () => {
    throw new Error('write only selector')
  },
  set: ({ set }, data) => {
    if (data instanceof DefaultValue) return
    set(useTriggerPos.receive, data.triggerPos)
    set(useSecPerSample.receive, data.secPerSample)
    set(useSamplesPerBuffer.receive, data.samplesPerBuffer)
    set(useAmplifier.receive, data.amplifier)
    set(useTriggerVoltage.receive, data.triggerVoltage)
    set(useTriggerDirection.receive, data.triggerDir)
    set(useTriggerChannel.receive, data.triggerChannel)
    set(useTriggerMode.receive, data.triggerMode)
    set(useIsChannelOn.receive, data.isChannelOn)
  }
})
Example #8
Source File: dataset.state.ts    From nextclade with MIT License 6 votes vote down vote up
datasetCurrentNameAtom = selector<string | undefined>({
  key: 'datasetCurrentName',
  get({ get }) {
    return get(datasetCurrentNameStorageAtom)
  },
  set({ get, set, reset }, newDatasetCurrentName: string | undefined | DefaultValue) {
    const datasetCurrentName = get(datasetCurrentNameStorageAtom)
    if (isDefaultValue(newDatasetCurrentName) || isNil(newDatasetCurrentName)) {
      reset(datasetCurrentNameStorageAtom)
    } else if (datasetCurrentName !== newDatasetCurrentName) {
      const { datasets } = get(datasetsAtom)
      const dataset = datasets.find((dataset) => dataset.attributes.name.value === newDatasetCurrentName)
      if (dataset) {
        set(datasetCurrentNameStorageAtom, dataset.attributes.name.value)
        set(viewedGeneAtom, dataset.params?.defaultGene ?? GENE_OPTION_NUC_SEQUENCE)
        reset(inputResetAtom)
      }
    }
  },
})
Example #9
Source File: results.state.ts    From nextclade with MIT License 6 votes vote down vote up
analysisResultAtom = selectorFamily<NextcladeResult, string>({
  key: 'analysisResult',

  get:
    (seqName: string) =>
    ({ get }): NextcladeResult => {
      return get(analysisResultInternalAtom(seqName))
    },

  set:
    (seqName) =>
    ({ set, reset }, result: NextcladeResult | DefaultValue) => {
      if (isDefaultValue(result)) {
        reset(analysisResultInternalAtom(seqName))
        reset(seqNamesAtom)
      } else {
        set(analysisResultInternalAtom(seqName), result)
        set(seqNamesAtom, (prev) => {
          if (result && !prev.includes(result.seqName)) {
            return [...prev, result.seqName]
          }
          return prev
        })
      }
    },
})
Example #10
Source File: results.state.ts    From nextclade with MIT License 6 votes vote down vote up
sortAnalysisResultsAtom = selectorFamily<undefined, { category: SortCategory; direction: SortDirection }>({
  key: 'sortAnalysisResults',

  get: () => () => undefined,

  set:
    ({ category, direction }) =>
    ({ get, set }, def: undefined | DefaultValue) => {
      const results = get(analysisResultsAtom)

      let sortCategory = category
      if (isDefaultValue(def)) {
        sortCategory = SortCategory.index
      }

      const resultsSorted = sortResults(results, { category: sortCategory, direction })
      const seqNamesSorted = resultsSorted.map((result) => result.seqName)

      set(seqNamesAtom, seqNamesSorted)
    },
})
Example #11
Source File: results.state.ts    From nextclade with MIT License 6 votes vote down vote up
sortAnalysisResultsByKeyAtom = selectorFamily<undefined, { key: string; direction: SortDirection }>({
  key: 'sortAnalysisResultsByKey',

  get: () => () => undefined,

  set:
    ({ key, direction }) =>
    ({ get, set }, def: undefined | DefaultValue) => {
      const results = get(analysisResultsAtom)

      const resultsSorted = isDefaultValue(def)
        ? sortResults(results, { category: SortCategory.index, direction })
        : sortResultsByKey(results, { key, direction })

      const seqNamesSorted = resultsSorted.map((result) => result.seqName)
      set(seqNamesAtom, seqNamesSorted)
    },
})
Example #12
Source File: results.state.ts    From nextclade with MIT License 6 votes vote down vote up
analysisResultsAtom = selector<NextcladeResult[]>({
  key: 'analysisResults',

  get({ get }): NextcladeResult[] {
    const seqNames = get(seqNamesAtom)
    return seqNames.map((seqName) => get(analysisResultAtom(seqName)))
  },

  set({ get, set, reset }, results: NextcladeResult[] | DefaultValue) {
    const seqNames = get(seqNamesAtom)

    // Remove all results
    seqNames.forEach((seqName) => {
      reset(analysisResultAtom(seqName))
    })

    // If the operation is not 'reset', add the new items
    if (!isDefaultValue(results)) {
      results.forEach((result) => set(analysisResultAtom(result.seqName), result))
    }
  },
})
Example #13
Source File: bindings.tsx    From arduino-web-oscilloscope with MIT License 5 votes vote down vote up
allDataState = selector<number[]>({
  key: 'all-data-this shouldnt be a selector',
  get: () => [], // this is a write only selector
  set: ({ set, get }, newData) => {
    win.$recoilDebugStates = [] // TODO: fix memory leak in recoiljs beta
    if (newData instanceof DefaultValue) return
    if (newData.length === 0) return
    const data = parseSerial(newData)
    if (data.needData) set(sendFullState, null)
    if (data.forceUIUpdate) set(receiveFullState, data)

    let buffers = data.buffers

    set(freeMemoryState, data.freeMemory)
    set(didTriggerState, !!data.didTrigger)
    const shouldUpdate =
      // todo use isRunning state in board for this
      get(isRunningState) && buffers.some((buffer) => buffer.length > 0)
    if (shouldUpdate) {
      const oldBuffers = get(dataState)

      const oversamplingFactor = get(oversamplingFactorState)
      if (oversamplingFactor > 0) {
        const factor = 1 - 2 / (oversamplingFactor + 1)
        buffers = buffers.map((b, i) =>
          oversample(factor, buffers[i], oldBuffers[i])
        )
      }

      if (get(useTriggerMode.send) === TriggerMode.SLOW) {
        const oldLastT = Math.max(
          ...oldBuffers.map((b) => b[b.length - 1]?.t || 0)
        )

        buffers = buffers.map((b, i) => [
          ...oldBuffers[i],
          ...b.map(({ v, t }) => ({ v, t: t + oldLastT }))
        ])
        const totalSecs =
          get(useSecPerSample.send) * get(useSamplesPerBuffer.send)
        const lastT = Math.max(...buffers.map((b) => b[b.length - 1]?.t || 0))
        if (lastT > totalSecs) {
          buffers = buffers.map(() => [])
        }
      }
      const withFFT = [
        ...buffers,
        get(fftState0) ? getFFT(buffers[0]) : [],
        get(fftState1) ? getFFT(buffers[1]) : []
      ]

      set(dataState, withFFT)
      if (get(useTriggerMode.send) === TriggerMode.SINGLE) {
        set(isRunningState, false)
      }
    }
  }
})
Example #14
Source File: bindingsHelper.ts    From arduino-web-oscilloscope with MIT License 5 votes vote down vote up
export function makeIntercom<T>({
  key,
  ui2mcu,
  mcu2ui,
  default: defaultValue
}: {
  key: string
  ui2mcu: (v: T, get: GetRecoilValue | null) => number
  mcu2ui: (v: number, get: GetRecoilValue | null) => T
  default: T
}) {
  const remoteState = memoSelector(
    atom<number>({
      key,
      default: ui2mcu(defaultValue, null)
    })
  )

  // throttle to avoid filling the MCU serial buffer
  const serial_write = serial.write
  // const serial_write = throttle(serial.write, 40, {
  //   leading: false,
  //   trailing: true
  // })
  const send = selector<T>({
    key: key + '-selector',
    get: ({ get }) => mcu2ui(get(remoteState), get),
    set: ({ set, get, reset }, newValue) => {
      if (newValue instanceof DefaultValue) return reset(remoteState)
      set(remoteState, ui2mcu(newValue, get))
      serial_write(key + ui2mcu(newValue, get) + '>')
    }
  })
  const receive = selector<number>({
    key: key + '-receive-selector',
    get: () => {
      throw new Error('cant get here')
    },
    set: ({ set }, newValue) => {
      if (newValue instanceof DefaultValue) throw new Error('no reset allowed')
      set(remoteState, newValue)
    }
  })

  return { send, receive }
}
Example #15
Source File: results.state.ts    From nextclade with MIT License 5 votes vote down vote up
export function isDefaultValue(candidate: unknown): candidate is DefaultValue {
  return candidate instanceof DefaultValue
}