---
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, transcriptPageUrl, segments})=>segments.map(({start, text, id})=>({segment_id:id, title, episode, season, transcriptPageUrl, url, start, text}))).flat()
    console.log(docs)
    idx = lunr(function(){
      this.ref('index')
      this.field('text')
      this.metadataWhitelist = ['position']
      docs.forEach(function (doc, idx) {
        doc.index = 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
      r.id = docs[r.ref].id
    })
    console.log('Form submitted!', searchQuery, results)
    const results_ol = document.getElementById("results").querySelector('ol')
    results_ol.innerHTML = ""
    results.forEach(r => {
      const el = document.createElement('li')
      const {segment_id, url, title, text, season, episode, start, transcriptPageUrl} = docs[r.ref]
      el.innerHTML = `<a href="${transcriptPageUrl}#${segment_id}">${title} (Season ${season}, episode ${episode})</a><p>${Duration.fromObject({seconds:start/1000}).toFormat("hh:mm:ss")}</p><p>${text}</p>`
      results_ol.appendChild(el)
    })
   }
   document.getElementById('search-form').addEventListener('submit', handleSubmit)
   
</script>