<commit_before>read = (url) ->
  localStorage?.getItem?(url)

write = (url, html) ->
  localStorage?.setItem?(url, html)

swapItems = ($old, $new) ->
  $old.find('[data-anti-cache-item]').each ->
    $item = $(this)
    id = $item.data('anti-cache-item')
    replacement = $new.find("[data-anti-cache-item='#{id}']")
    $item.replaceWith(replacement)

  setTimeout (-> $old.addClass('folio-anti-cache--done')), 0

fetchFresh = ($el, url) ->
  $.get url, (res) -> swapItems($el, $(res))

performAntiCache = (e) ->
  $body = $(e.originalEvent.data.newBody || 'body')

  $body.find('[data-anti-cache]').each ->
    $el = $(this)
    url = $el.data('anti-cache')
    value = read(url)

    swapItems($el, $(value)) if value

    fetchFresh($el, url)

saveAntiCacheHtml = ->
  $('[data-anti-cache]').each ->
    $el = $(this)
    write $el.data('anti-cache'), $el.html()

$(document)
  .one 'turbolinks:load', performAntiCache
  .on 'turbolinks:before-render', performAntiCache
  .on 'turbolinks:before-cache', saveAntiCacheHtml
<commit_msg>improve anti-cache JS / turbolinks<commit_after>read = (url) ->
  localStorage?.getItem?(url)

write = (url, html) ->
  localStorage?.setItem?(url, html)

swapItems = ($old, $new, immediate) ->
  $old.find('[data-anti-cache-item]').each ->
    $item = $(this)
    id = $item.data('anti-cache-item')
    replacement = $new.find("[data-anti-cache-item='#{id}']")
    $item.replaceWith(replacement)

  if immediate
    $old.addClass('folio-anti-cache--done')
  else
    setTimeout (-> $old.addClass('folio-anti-cache--done')), 0

fetchFresh = ($el, url) ->
  $.get url, (res) -> swapItems($el, $(res), false)

performAntiCache = (e) ->
  $body = $(e.originalEvent.data.newBody || 'body')

  $body.find('[data-anti-cache]').each ->
    $el = $(this)
    url = $el.data('anti-cache')
    value = read(url)

    swapItems($el, $(value), true) if value

    fetchFresh($el, url)

saveAntiCacheHtml = ->
  $('[data-anti-cache]').each ->
    $el = $(this)
    write $el.data('anti-cache'), $el.html()

$(document)
  .one 'turbolinks:load', performAntiCache
  .on 'turbolinks:before-render', performAntiCache
  .on 'turbolinks:before-cache', saveAntiCacheHtml
{'fraction_non_alphanumeric': 0.21546203110704484, 'fraction_numerical': 0.0009149130832570906, 'mean_word_length': 3.6931330472103006, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3217222', 'n_tokens_mistral': 822, 'n_tokens_neox': 809, 'n_words': 140}