site

files for beauhilton.com
git clone https://git.beauhilton.com/site.git
Log | Files | Refs

reading-time.lua (1547B)


      1 -- Makes a reading time estimate based on word count.
      2 --
      3 -- Sample configuration:
      4 --
      5 -- [plugins.reading_time]
      6 --   file = "plugins/reading-time.lua"
      7 --
      8 -- [widgets.reading-time]
      9 --   widget = "reading_time"
     10 --   reading_speed = 350
     11 --
     12 --   # Where to insert the reading time estimate
     13 --   selector = "span#reading-time"
     14 --
     15 --   # Where to extract the text for word count
     16 --   content_selector = "main"
     17 --
     18 -- Minimum soupault version: 1.6
     19 -- Author: Daniil Baturin
     20 -- License: MIT
     21 
     22 reading_speed = config["reading_speed"]
     23 selector = config["selector"]
     24 content_selector = config["content_selector"]
     25 
     26 if (not reading_speed) then
     27   Log.warning("Missing option \"reading_speed\", using default (300 WPM)")
     28   reading_speed = 300
     29 end
     30 
     31 if (not selector) then
     32   Log.warning("Missing option \"selector\", using default (body)")
     33   selector = "body"
     34 end
     35 
     36 if (not content_selector) then
     37   Log.warning("Missing option \"content_selector\", using default (body)")
     38   content_selector = "body"
     39 end
     40 
     41 -- Extract the content
     42 content_element = HTML.select_one(page, content_selector)
     43 content = HTML.strip_tags(content_element)
     44 
     45 -- Calculate the word count
     46 words = Regex.split(content, "\\s+")
     47 word_count = size(words)
     48 
     49 -- Make a reading time text
     50 reading_time = floor(word_count / reading_speed)
     51 
     52 if (reading_time <= 1) then
     53   time_msg = "less than a minute"
     54 else
     55   time_msg = reading_time .. " minutes"
     56 end
     57 
     58 -- Insert the text in the target element
     59 target = HTML.select_one(page, selector)
     60 if target then
     61   HTML.prepend_child(target, HTML.create_text(time_msg))
     62 end