Skip to content

Instantly share code, notes, and snippets.

@PolyDevil
Created September 28, 2021 12:23
Show Gist options
  • Select an option

  • Save PolyDevil/2e0f4e9f15cc3905ee747b449e6a0006 to your computer and use it in GitHub Desktop.

Select an option

Save PolyDevil/2e0f4e9f15cc3905ee747b449e6a0006 to your computer and use it in GitHub Desktop.

Revisions

  1. PolyDevil created this gist Sep 28, 2021.
    77 changes: 77 additions & 0 deletions machine.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,77 @@
    const fetchMachine = Machine({
    id: 'search',
    initial: 'idle',

    context: {
    search: '',
    isDropdownRendered: false,
    maxFocusedIndex: 0,
    focusedIndex: -1,
    },

    states: {
    idle: {
    entry: assign((_) => ({
    isDropdownRendered: false,
    focusedIndex: -1,
    })),
    on: {
    FOCUS: 'search',
    SYNC: {
    target: 'idle',
    actions: assign((context, { value }) => ({
    maxFocusedIndex: value,
    })),
    },
    },
    },

    search: {
    entry: assign((_) => ({
    isDropdownRendered: true,
    })),
    on: {
    TYPE: {
    target: 'search',
    actions: assign((context, { search }) => ({
    search,
    })),
    },
    SYNC: {
    target: 'search',
    actions: assign((context, { value }) => ({
    maxFocusedIndex: value,
    })),
    },
    BLUR: {
    target: 'idle',
    },
    INSPECT: {
    target: 'inspect',
    actions: assign((_) => ({
    focusedIndex: 0,
    })),
    },
    },
    },

    inspect: {
    on: {
    SEARCH: 'search',
    PREV: {
    target: 'inspect',
    actions: assign((context) => ({
    focusedIndex: Math.max(0, context.focusedIndex - 1),
    })),
    },
    NEXT: {
    target: 'inspect',
    actions: assign((context) => ({
    focusedIndex: Math.min(context.maxFocusedIndex - 1, context.focusedIndex + 1),
    })),
    },
    BLUR: 'idle',
    },
    },
    },
    });