---
layout: base-with-heading
title: Search Transcripts
eleventyExcludeFromCollections: ["episode"]
override:tags: []
override:eleventyComputed: []
---

<script src="https://unpkg.com/lunr/lunr.js"></script>

<div>
  <form id="search-form">
    <input type="text" class="form-control mb-3" name="searchQuery" id="searchQuery">
    <button class="btn btn-primary mb-3" type="submit">Search</button>
  </form>
  <div id="results">
    <ol></ol>
  </div>
</div>
<script type="module">
  import {Duration} from 'https://cdn.jsdelivr.net/npm/luxon@3.5.0/+esm' ;
  let idx, docs
  let search_index_promise = fetch('../transcript-index')
  .then((res)=>res.json())
  .then((documents)=>{
    docs = documents.map(({title, episode, season, url, cues})=>cues.map(({startTime, text})=>({title, episode, season, url, startTime, text}))).flat()
    console.log(documents)
    idx = lunr(function(){
      this.ref('id')
      this.field('text')
      this.metadataWhitelist = ['position']
      docs.forEach(function (doc, idx) {
        doc.id = idx;
        this.add(doc);
        }, this)
    })
  })

  function handleSubmit(evt) {
    evt.preventDefault();
    const formData = new FormData(evt.target)
    const {searchQuery} = Object.fromEntries(formData)
    const results = idx.search(searchQuery)
    results.forEach(r => {
      r.title = docs[r.ref].title,
      r.url = docs[r.ref].url
    })
    console.log('Form submitted!', results)
    const results_ol = document.getElementById("results").querySelector('ol')
    results_ol.innerHTML = ""
    results.forEach(r => {
      const el = document.createElement('li')
      const {url, title, text, season, episode, startTime} = docs[r.ref]
      el.innerHTML = `<a href="${url}?startAt=${startTime}">${title} (Season ${season}, episode ${episode})</a><p>${Duration.fromObject({seconds:startTime}).toFormat("hh:mm:ss")}</p><p>${text}</p>`
      results_ol.appendChild(el)
    })
   }
   document.getElementById('search-form').addEventListener('submit', handleSubmit)
   
</script>