view app/javascript/src/main.coffee @ 485:6cac8fcf8164

Update to rails 7 (and ruby 3.1)
author nanaya <me@nanaya.pro>
date Sat, 15 Jan 2022 02:07:02 +0900
parents b493db1f40b0
children
line wrap: on
line source

import 'bootstrap'
import hljs from 'highlight.js'
import * as commonmark from 'commonmark'

#= require jquery
#= require bootstrap/transition
#= require bootstrap/collapse
#= require bootstrap/modal
#= require bootstrap/tab
#= require highlightjs
#= require commonmark

$(document).on "click", ".js-paste-clear", (e) ->
  e.preventDefault()
  $(".js-paste-paste")
    .val("")
    .focus()


loadLanguageItems = ->
  $languageSelectBox = $("#paste_language")
  return unless $languageSelectBox.length

  for language in hljs.listLanguages().sort()
    $languageSelectBox.append $("<option />", value: language, text: language)


markdownfy = (plaintext) ->
  reader = new commonmark.Parser
  writer = new commonmark.HtmlRenderer(safe: true)
  writer.render reader.parse(plaintext)


pasteText = ->
  $(".js-paste-paste").val() || $(".js-paste-pl").text()


highlightText = ->
  $hlBox = $(".js-paste-hl")
  return if $hlBox.attr("data-processed") == "1"

  $hlBox.text pasteText()

  highlight = -> hljs.highlightBlock($hlBox[0])
  setTimeout highlight, 0

  $hlBox.attr "data-processed", "1"


markdownText = ->
  $mdBox = $(".js-paste-md")
  return if $mdBox.attr("data-processed") == "1"

  $mdBox.html markdownfy(pasteText())
  $mdBox.find("a").attr("rel", "nofollow")
  $mdBox.attr "data-processed", "1"


setHash = (e) ->
  return unless history.replaceState

  newLocation = "##{e.currentTarget.getAttribute("data-mode")}"
  if newLocation == "#pl"
    newLocation = window.location.pathname

  history.replaceState null, "", newLocation


showPreview = (e) ->
  e.preventDefault()
  return if pasteText() == ""
  $(".js-paste-preview-md-box").html markdownfy(pasteText())
  $(".js-paste-preview-md-modal").modal "show"


switchToCurrentHash = ->
  return if $(".js-showing-paste").length == 0

  format = window.location.hash.slice(1)

  return unless format in ['pl', 'hl', 'md']

  $(".js-show-tab[data-mode=#{format}]").click()


$ loadLanguageItems
$ switchToCurrentHash
$(document).on "click", ".js-paste-preview-md", showPreview
$(document).on "click", ".js-show-tab[data-mode=hl]", highlightText
$(document).on "click", ".js-show-tab[data-mode=md]", markdownText
$(document).on "click", ".js-show-tab", setHash