Real-time Search with Phoenix LiveView and Tailwind

Hi @caspg , Following up on my previous reply:

Ok, the staging site is up. The search bar on this page:

I have only added the search to that page currently (turned out I needed to put it in templates other than app.html.heex, so just trying to get it working on /plays first.)

On a possibly related note, I keep wondering about this, so I should ask: Is this the only socket I need in my lib/mono_phoenix_v01_web/endpoint.ex?

socket("/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]])

Will that socket handle the search too, or do I need to add another for the search?

Anyway, thanks for helping me try to find the cause of the Parameters: :not_mounted_at_router and `unknown hook found for “SearchBar” issues!

Please let me know if I should post the contents of any other files.

Getting a 404 on /plays

Yeah, I’ve switched to working on a different solution for search. That’s just a staging site, I pushed that commit to check something not on that route. Thanks for the note though.

That route works on production, which is here if you’re curious: The Plays · Shakespeare's Monologues (search function not yet added there.)

No problem, I’m working on the same problem so was just curious as to how you solved it.

That is awesome, thanks for sharing! :heart_hands:

How did you implement the shortcut for the keyboard search ctrl+k?

This is the Hook I’ve used:

let keysPressed: { [key in string]: boolean } = {}

function handleMetaKeydown(event: KeyboardEvent) {
  if (event.key === 'Control') {
    keysPressed[event.key] = true
    return
  }

  if ((keysPressed['Control'] || event.metaKey) && event.key === 'k') {
    event.preventDefault()

    document.getElementById('searbar-open-button')?.click()
  }
}

function handleMetaKeyUp(event: KeyboardEvent) {
  if (event.key === 'Control' || event.key === 'Meta') {
    delete keysPressed[event.key]
    return
  }
}

export const SearchBar = {
  mounted() {
    document.addEventListener('keydown', handleMetaKeydown)
    document.addEventListener('keyup', handleMetaKeyUp)
  },
  destroyed() {
    document.removeEventListener('keydown', handleMetaKeydown)
    document.removeEventListener('keyup', handleMetaKeyUp)
  },
}
1 Like

Um, this is the most incredible thread. I needed all of this!

I’m going to add my addition as I’m caching my searches but couldn’t contain my appreciation for all of your examples!