raindown 0.18.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. checksums.yaml +4 -4
  2. data/lib/raindown/area.rb +88 -0
  3. data/lib/raindown/chart/chart.rb +5 -2
  4. data/lib/raindown/chart/drawing.rb +0 -2
  5. data/lib/raindown/chart/line.rb +1 -1
  6. data/lib/raindown/chart/points.rb +2 -1
  7. data/lib/raindown/cli.rb +2 -2
  8. data/lib/raindown/code.rb +37 -5
  9. data/lib/raindown/config.rb +11 -0
  10. data/lib/raindown/document.rb +8 -6
  11. data/lib/raindown/editing.rb +8 -4
  12. data/lib/raindown/endpoint/curl.rb +19 -14
  13. data/lib/raindown/endpoint/curl_request.rb +90 -0
  14. data/lib/raindown/endpoint/curl_response.rb +6 -3
  15. data/lib/raindown/grid.rb +154 -0
  16. data/lib/raindown/grid_directives.rb +43 -0
  17. data/lib/raindown/grid_wrapping.rb +46 -0
  18. data/lib/raindown/http_json.rb +45 -0
  19. data/lib/raindown/image.rb +44 -0
  20. data/lib/raindown/js/js_nodes.rb +85 -33
  21. data/lib/raindown/js/quickjs_host.rb +63 -0
  22. data/lib/raindown/js/quickjs_runtime.js +61 -0
  23. data/lib/raindown/js/services.js +31 -0
  24. data/lib/raindown/markdown_nodes.rb +2 -0
  25. data/lib/raindown/node_blocks.rb +22 -9
  26. data/lib/raindown/node_injector.rb +56 -15
  27. data/lib/raindown/nodes.rb +52 -15
  28. data/lib/raindown/outdent.rb +100 -0
  29. data/lib/raindown/pages/listings.rb +71 -0
  30. data/lib/raindown/{pages.rb → pages/pages.rb} +21 -34
  31. data/lib/raindown/problem.rb +12 -3
  32. data/lib/raindown/project/card.rb +54 -0
  33. data/lib/raindown/project/endpoint.rb +14 -0
  34. data/lib/raindown/project/project.rb +168 -0
  35. data/lib/raindown/project_nodes.rb +47 -0
  36. data/lib/raindown/projects.rb +1 -1
  37. data/lib/raindown/rasters.rb +98 -0
  38. data/lib/raindown/scene.rb +10 -0
  39. data/lib/raindown/services/connections.rb +65 -0
  40. data/lib/raindown/services/local.rb +139 -0
  41. data/lib/raindown/services.rb +72 -0
  42. data/lib/raindown/skeleton.rb +1 -1
  43. data/lib/raindown/table/table.rb +2 -2
  44. data/lib/raindown/table/table_column.rb +0 -2
  45. data/lib/raindown/table/table_file.rb +2 -2
  46. data/lib/raindown/table/written_table.rb +0 -2
  47. data/lib/raindown/toc/markdown_headings.rb +98 -0
  48. data/lib/raindown/{toc.rb → toc/toc.rb} +8 -5
  49. data/lib/raindown/tui/endpoints.rb +1 -1
  50. data/lib/raindown/tui/feelings/feelings_log.rb +2 -1
  51. data/lib/raindown/tui/navigator/navigator.rb +1 -1
  52. data/lib/raindown/watcher/project.rb +2 -2
  53. data/lib/raindown/weather/branch_tree.rb +129 -0
  54. data/lib/raindown/weather/forecast.rb +193 -0
  55. data/lib/raindown/weather/forecast_cache.rb +58 -0
  56. data/lib/raindown/weather/forecast_cards.rb +115 -0
  57. data/lib/raindown/weather/sky.rb +82 -0
  58. data/lib/raindown/weather/weather.rb +140 -0
  59. data/lib/raindown/wiki_links.rb +2 -6
  60. data/lib/raindown.rb +39 -14
  61. data/lib/version.rb +1 -1
  62. metadata +33 -9
  63. data/lib/raindown/js/host.mjs +0 -51
  64. data/lib/raindown/tui/card.rb +0 -56
  65. data/lib/raindown/tui/endpoint.rb +0 -16
  66. data/lib/raindown/tui/project.rb +0 -147
  67. /data/lib/raindown/{page.rb → pages/page.rb} +0 -0
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../front_matter'
4
+ require_relative '../variables'
5
+
6
+ module Raindown
7
+ # The headings of Markdown as it's written, without rendering it, so a table of contents can be written back while
8
+ # it's typed: # headings and underlined ones, outside front matter, code and HTML comments, with their text as it
9
+ # reads, without its links, code or emphasis marks, and ids made the way Commonmarker makes them, numbered when
10
+ # they repeat, like to-read and to-read-1. Variables in them, like {title}, are filled in from the variables given,
11
+ # but headings in if: and for: blocks are as they're written, and headings that components render aren't in it, as
12
+ # they're only in HTML.
13
+ module MarkdownHeadings
14
+ ATX = /\A {0,3}(\#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+\#+)?[ \t]*\z/
15
+ SETEXT = /\A {0,3}(=+|-+)[ \t]*\z/
16
+ FENCE = /\A {0,3}(`{3,}|~{3,})/
17
+ # A line that's a block of its own, rather than a paragraph's, which can't be underlined into a heading.
18
+ BLOCK = /\A {0,3}(?:[|>#<]|[-*+][ \t]|\d+[.)][ \t]|\z)/
19
+ COMMENT = /<!--.*?-->/m
20
+
21
+ module_function
22
+
23
+ def scan(markdown, variables: nil)
24
+ seen = Hash.new(0)
25
+ headings(lines(markdown)).map do |level, written|
26
+ written = filled(written, variables)
27
+ text = plain(written)
28
+ id = anchor(plain(written, images: true))
29
+ count = seen[id]
30
+ seen[id] += 1
31
+ { level:, text:, id: count.zero? ? id : "#{id}-#{count}" }
32
+ end
33
+ end
34
+
35
+ # A heading's id, the way Commonmarker makes it, like to-read for "To read".
36
+ def anchor(heading)
37
+ heading.downcase.gsub(/[^\p{Word}\- ]/, '').tr(' ', '-')
38
+ end
39
+
40
+ # Its lines after its front matter, with its HTML comments blanked out, keeping their lines.
41
+ def lines(markdown)
42
+ _, body = FrontMatter.parse(markdown)
43
+ body.to_s.gsub(COMMENT) { it.gsub(/[^\n]/, '') }.lines(chomp: true)
44
+ end
45
+
46
+ # Each heading's level and text, outside fenced code, in order.
47
+ def headings(lines)
48
+ fence = nil
49
+ lines.each_with_index.filter_map do |line, index|
50
+ marker = line[FENCE, 1]
51
+ if marker || fence
52
+ fence = fence_after(fence, marker)
53
+ next
54
+ end
55
+
56
+ heading(line, index.positive? ? lines[index - 1] : '')
57
+ end
58
+ end
59
+
60
+ # The fence still open after a line with the marker: closed by one like it, at least as long.
61
+ def fence_after(fence, marker)
62
+ return marker unless fence
63
+ return nil if marker&.start_with?(fence[0]) && marker.length >= fence.length
64
+
65
+ fence
66
+ end
67
+
68
+ def heading(line, above)
69
+ if (match = line.match(ATX))
70
+ [match[1].length, match[2].to_s]
71
+ elsif line.match?(SETEXT) && !above.match?(BLOCK) && !above.match?(SETEXT)
72
+ [line.strip.start_with?('=') ? 1 : 2, above]
73
+ end
74
+ end
75
+
76
+ # The heading with its variables filled in, like {title}.
77
+ def filled(text, variables)
78
+ return text unless variables
79
+
80
+ text.gsub(/\{([A-Za-z_][\w.]*)\}/) { Variables.value(variables, ::Regexp.last_match(1)).to_s }
81
+ end
82
+
83
+ # The heading's text as it reads: links as their text, images left out, or as their alt text, as in its id, code
84
+ # without its backticks, emphasis without its marks, but for underscores inside words, HTML without its tags, and
85
+ # escaped characters as themselves.
86
+ def plain(text, images: false)
87
+ text.strip
88
+ .gsub(/!\[([^\]]*)\]\([^)]*\)/) { images ? ::Regexp.last_match(1) : '' }
89
+ .gsub(/\[([^\]]*)\]\([^)]*\)/, '\1')
90
+ .gsub(/(`+)(.+?)\1/) { ::Regexp.last_match(2).strip }
91
+ .gsub(/(\*\*|\*)(?=\S)(.+?)(?<=\S)\1/, '\2')
92
+ .gsub(/(?<![[:alnum:]])(__|_)(?=\S)(.+?)(?<=\S)\1(?![[:alnum:]])/, '\2')
93
+ .gsub(/<[^>]*>/, '')
94
+ .gsub(/\\([[:punct:]])/, '\1')
95
+ .strip
96
+ end
97
+ end
98
+ end
@@ -2,7 +2,8 @@
2
2
 
3
3
  require 'cgi/escape'
4
4
 
5
- require_relative 'node'
5
+ require_relative 'markdown_headings'
6
+ require_relative '../node'
6
7
 
7
8
  module Raindown
8
9
  # The node behind toc: and :toc, a table of contents of the document's headings.
@@ -14,8 +15,10 @@ module Raindown
14
15
  IGNORED = %r{<!--.*?-->|<script\b.*?</script\s*>}mi
15
16
  TAG = /<[^>]*>/
16
17
 
18
+ # From the Markdown as it's written, without rendering it, so it's quick enough to write back as it's typed.
17
19
  def rewrite(document:, metadata: nil, bare: false)
18
- headings = headings_below_title(markdown: document, metadata:, bare:)
20
+ variables = Context.new(document:, metadata: metadata || NoMetadata, bare:).variables
21
+ headings = below_title(MarkdownHeadings.scan(document, variables:))
19
22
  return '' if headings.empty?
20
23
 
21
24
  min_level = headings.map { |heading| heading[:level] }.min
@@ -27,7 +30,7 @@ module Raindown
27
30
 
28
31
  # With the document's final HTML, the headings include ones its components render.
29
32
  def render(document:, html: nil, metadata: nil, bare: false)
30
- items = headings_below_title(markdown: document, html:, metadata:, bare:).map do |heading|
33
+ items = below_title(headings(markdown: document, html:, metadata:, bare:)).map do |heading|
31
34
  "<li class='h#{heading[:level]}'><a href='##{heading[:id]}'>#{CGI.escapeHTML(heading[:text])}</a></li>"
32
35
  end
33
36
 
@@ -44,8 +47,8 @@ module Raindown
44
47
  end
45
48
 
46
49
  # A lone top-level heading that starts the document is its title, so it's left out when there are headings below it.
47
- def headings_below_title(**)
48
- title, *below = headings = headings(**)
50
+ def below_title(headings)
51
+ title, *below = headings
49
52
  return headings if below.empty? || title[:level] != 1 || below.any? { it[:level] == 1 }
50
53
 
51
54
  below
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'endpoint'
3
+ require_relative '../project/endpoint'
4
4
  require_relative 'views/endpoint_view'
5
5
  require_relative 'row'
6
6
  require_relative '../workers/worker'
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'csv'
3
+ # Loaded when first used, as it loads strscan, a native extension, which slows a packed executable's start.
4
+ autoload :CSV, 'csv'
4
5
  require 'fileutils'
5
6
  require 'open3'
6
7
  require 'time'
@@ -11,7 +11,7 @@ require_relative '../views/list_view'
11
11
  require_relative 'project_menu'
12
12
  require_relative 'teleport'
13
13
  require_relative 'views'
14
- require_relative '../project'
14
+ require_relative '../../project/project'
15
15
 
16
16
  module Raindown
17
17
  module TUI
@@ -17,9 +17,9 @@ module Raindown
17
17
  @execute = execute
18
18
  end
19
19
 
20
- # Loads the project's nodes from its .raindown folder.
20
+ # Loads the project's nodes from its .raindown folder, saying why any couldn't be.
21
21
  def start
22
- Nodes.load(File.join(root, Nodes::FOLDER))
22
+ Nodes.load(File.join(root, Nodes::FOLDER)).each { warn "[#{name}] raindown: #{it}" }
23
23
  rescue StandardError, ScriptError => e
24
24
  raise if ENV['RAINDOWN_DEBUG']
25
25
 
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'open3'
4
+
5
+ module Raindown
6
+ # The branches of a git repository that aren't merged into its main branch, a line each, with how many commits it has
7
+ # that its parent doesn't, those made earlier first, each branch off main followed by the branches off it, indented
8
+ # under it after an arrow:
9
+ # login · 4 commits
10
+ # -> login-tests · 2 commits
11
+ # search · 6 commits
12
+ # -> search-filters · 3 commits
13
+ # -> search-sort · 1 commit
14
+ # A branch is off the branch it shares the most commits with, or main, and it was made when its first commit that
15
+ # its parent doesn't have was, or its last commit when it has none. Git doesn't keep when a branch was made.
16
+ class BranchTree
17
+ MAINS = %w[main master].freeze
18
+ ARROW = '-> '
19
+ # How much further right a branch off another starts than it.
20
+ INDENT = 4
21
+
22
+ Commit = Data.define(:time, :parents)
23
+
24
+ # A branch as it's written: its name, how deep it is off main, and its own commits.
25
+ Branch = Data.define(:name, :depth, :commits) do
26
+ def arrow = depth.zero? ? '' : ARROW
27
+ def indent = INDENT * depth
28
+ def count = "#{commits} #{commits == 1 ? 'commit' : 'commits'}"
29
+ def to_s = "#{' ' * indent}#{arrow}#{name} · #{count}"
30
+ end
31
+
32
+ def initialize(root)
33
+ @root = root
34
+ end
35
+
36
+ def lines
37
+ branches.map(&:to_s)
38
+ end
39
+
40
+ # Each branch in the order it's written: a branch off main, then the branches off it.
41
+ def branches
42
+ return [] unless main
43
+
44
+ @tips = unmerged_tips
45
+ return [] if @tips.empty?
46
+
47
+ @commits = commits_off_main
48
+ @reach = @tips.to_h { |name, tip| [name, reachable(tip)] }
49
+ @parents = @tips.keys.to_h { [it, parent_of(it)] }
50
+ children_of(nil).flat_map { branches_from(it, 0) }
51
+ end
52
+
53
+ private
54
+
55
+ def main
56
+ @main ||= MAINS.find { git('rev-parse', '--verify', '--quiet', "refs/heads/#{it}") }
57
+ end
58
+
59
+ # Each unmerged branch's name and the commit it's at.
60
+ def unmerged_tips
61
+ output = git('branch', '--no-merged', main, '--format=%(refname:short) %(objectname)').to_s
62
+ output.lines.to_h(&:split)
63
+ end
64
+
65
+ # The commits on the branches that main doesn't have, by their hashes.
66
+ def commits_off_main
67
+ output = git('log', '--format=%H %ct %P', *@tips.values, "^#{main}").to_s
68
+ output.lines.to_h do |line|
69
+ hash, time, *parents = line.split
70
+ [hash, Commit.new(time: time.to_i, parents:)]
71
+ end
72
+ end
73
+
74
+ # The commits from a tip that main doesn't have.
75
+ def reachable(tip)
76
+ found = Set.new
77
+ queue = [tip]
78
+ while (hash = queue.shift)
79
+ next if found.include?(hash) || !@commits.key?(hash)
80
+
81
+ found << hash
82
+ queue.concat(@commits[hash].parents)
83
+ end
84
+ found
85
+ end
86
+
87
+ # The branch it shares the most commits with that isn't off it, or main. Of two at the same commit, the one made
88
+ # first is the parent.
89
+ def parent_of(name)
90
+ candidates = @tips.keys.reject { it == name || off?(it, name) }
91
+ shared = candidates.to_h { [it, (@reach[name] & @reach[it]).size] }.select { |_, count| count.positive? }
92
+ shared.max_by { |other, count| [count, -created_at(other, by: nil)] }&.first
93
+ end
94
+
95
+ # Whether one branch is off another: its tip has the other's, but not the other way round, or they're at the same
96
+ # commit and it's later by name.
97
+ def off?(name, other)
98
+ has = @reach[name].include?(@tips[other])
99
+ return has unless has && @reach[other].include?(@tips[name])
100
+
101
+ name > other
102
+ end
103
+
104
+ # When its first commit that its parent doesn't have was made, or its last commit.
105
+ def created_at(name, by: @parents[name])
106
+ own = @reach[name] - (by ? @reach[by] : Set.new)
107
+ times = own.map { @commits[it].time }
108
+ times.min || @commits[@tips[name]]&.time || 0
109
+ end
110
+
111
+ def children_of(parent)
112
+ @tips.keys.select { @parents[it] == parent }.sort_by { [created_at(it), it] }
113
+ end
114
+
115
+ # Each branch off main starts a line further right than the one made before it, and its first branch carries on
116
+ # its line, while its other branches start lines below, their arrows under its first's.
117
+ # The branch and the branches off it, a level deeper, with its own commits, those its parent doesn't have.
118
+ def branches_from(name, depth)
119
+ parent = @parents[name]
120
+ commits = (@reach[name] - (parent ? @reach[parent] : Set.new)).size
121
+ [Branch.new(name:, depth:, commits:), *children_of(name).flat_map { branches_from(it, depth + 1) }]
122
+ end
123
+
124
+ def git(*args)
125
+ output, status = Open3.capture2('git', '-C', @root, *args, err: File::NULL)
126
+ output if status.success?
127
+ end
128
+ end
129
+ end
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+ require 'json'
5
+ require_relative '../http_json'
6
+ require_relative 'forecast_cache'
7
+ require_relative 'forecast_cards'
8
+ require_relative 'sky'
9
+
10
+ module Raindown
11
+ # The weather where you are, or in a place you name, from Open-Meteo, which needs no key: the weather now and the next
12
+ # few days', for weather:. Where you are is your time zone's city, like Melbourne for Australia/Melbourne, from where
13
+ # tzdata's zone.tab puts it, and a place you name is found by Open-Meteo's geocoding. It's kept for a while, and kept
14
+ # longer when Open-Meteo can't be reached, so it isn't lost while you're offline.
15
+ class Forecast
16
+ GEOCODING = 'https://geocoding-api.open-meteo.com/v1/search'
17
+ FORECAST = 'https://api.open-meteo.com/v1/forecast'
18
+ ZONE_TAB = '/usr/share/zoneinfo/zone.tab'
19
+ FRESH_FOR = 15 * 60
20
+ # How long after Open-Meteo couldn't be reached it's asked again, using what was kept meanwhile.
21
+ RETRY_AFTER = 60
22
+ DAYS = 7
23
+ # What it asks Open-Meteo for now, for its sky as well as its temperature and weather.
24
+ CURRENT = 'temperature_2m,weather_code,cloud_cover,cloud_cover_low,cloud_cover_mid,cloud_cover_high,rain,showers,' \
25
+ 'snowfall,wind_speed_10m,visibility,uv_index_clear_sky'
26
+ # The countries that measure in Fahrenheit.
27
+ FAHRENHEIT = %w[US LR MM].freeze
28
+ # What the WMO's weather codes, which Open-Meteo answers with, are in words.
29
+ WORDS = {
30
+ 0 => 'clear', 1 => 'mostly clear', 2 => 'partly cloudy', 3 => 'overcast', 45 => 'fog', 48 => 'freezing fog',
31
+ 51 => 'light drizzle', 53 => 'drizzle', 55 => 'heavy drizzle', 56 => 'freezing drizzle', 57 => 'freezing drizzle',
32
+ 61 => 'light rain', 63 => 'rain', 65 => 'heavy rain', 66 => 'freezing rain', 67 => 'freezing rain',
33
+ 71 => 'light snow', 73 => 'snow', 75 => 'heavy snow', 77 => 'snow grains', 80 => 'light showers', 81 => 'showers',
34
+ 82 => 'heavy showers', 85 => 'snow showers', 86 => 'heavy snow showers', 95 => 'thunderstorms',
35
+ 96 => 'thunderstorms with hail', 99 => 'thunderstorms with hail'
36
+ }.freeze
37
+
38
+ Error = HTTPJSON::Error
39
+ Place = Data.define(:name, :latitude, :longitude, :country)
40
+ # A day's weather, its high and low, its weather code, and how strong its sun's ultraviolet gets, its UV index.
41
+ Day = Data.define(:date, :high, :low, :code, :uv) do
42
+ def words = WORDS.fetch(code, 'unknown')
43
+ end
44
+ # The weather now and the week's, in a unit, like °C, with the conditions now, as Open-Meteo gives them, for its sky,
45
+ # and how far ahead of UTC the place's clocks are, in seconds.
46
+ Report = Data.define(:place, :temperature, :code, :unit, :days, :conditions, :utc_offset) do
47
+ def words = WORDS.fetch(code, 'unknown')
48
+
49
+ # How strong the sun's ultraviolet is now under a clear sky, its UV index, as the Bureau of Meteorology and NOAA give
50
+ # it, the most it could be, as sun protection goes by, or nil when it wasn't given, like in a forecast kept from
51
+ # before it was asked for. Its conditions' names are text as Open-Meteo gives them, and symbols as they're kept.
52
+ def uv = conditions.transform_keys(&:to_s)['uv_index_clear_sky']
53
+
54
+ # How strong the sun's ultraviolet gets today, at its strongest, under a clear sky, or nil.
55
+ def uv_peak = days.first&.uv
56
+
57
+ # Its lines, the days' cards, as ForecastCards draws them.
58
+ def lines = ForecastCards.lines(days)
59
+
60
+ # The characters of its lines for an app to dim, the cards' borders, as [line, from, to].
61
+ def quiet = ForecastCards.borders(lines)
62
+
63
+ # The characters of its lines for an app to embolden, the cards' days, as [line, from, to].
64
+ def bold = ForecastCards.headings(days)
65
+
66
+ # The characters of its lines for an app to draw as large as a line is tall, the cards' emoji, as [line, from, to].
67
+ def large = ForecastCards.emoji(days)
68
+
69
+ # The weather now as a sky for an app to paint, its temperature in °C.
70
+ def sky
71
+ celsius = temperature
72
+ celsius = (temperature - 32) * 5 / 9 if unit == '°F'
73
+ Sky.of(conditions.transform_keys(&:to_sym).merge(temperature_2m: celsius))
74
+ end
75
+ end
76
+
77
+ # The forecast for a place you name, or else where you are, or nil when there's nowhere to forecast for.
78
+ def self.for(place_name = nil, zone: TimeZone.name)
79
+ new(place_name, zone:).report
80
+ end
81
+
82
+ # The forecast last kept for a place you name, or else where you are, however old, or nil, without asking for it.
83
+ def self.cached(place_name = nil, zone: TimeZone.name)
84
+ new(place_name, zone:).cached
85
+ end
86
+
87
+ def initialize(place_name, zone:)
88
+ @place_name = place_name
89
+ @zone = zone
90
+ @cache = Cache.new(place_name || zone.to_s)
91
+ end
92
+
93
+ # The forecast, from the cache while it's fresh, or else asked for again, for the place it was kept for, so it's not
94
+ # looked up again, or from the cache however old it is when Open-Meteo can't be reached, which isn't asked again for
95
+ # RETRY_AFTER seconds, or nil when it never has been.
96
+ def report
97
+ cached, fresh = @cache.report
98
+ return cached if fresh
99
+
100
+ place = cached&.place || self.place
101
+ return unless place
102
+
103
+ fetched(place).tap { @cache.keep(it) }
104
+ rescue Error
105
+ raise unless cached
106
+
107
+ @cache.unreached
108
+ cached
109
+ end
110
+
111
+ # The forecast kept for this place, however old, or nil, without asking Open-Meteo.
112
+ def cached = @cache.report.first
113
+
114
+ # The place to forecast for, as its name, latitude, longitude and country.
115
+ def place
116
+ return TimeZone.place(@zone) unless @place_name
117
+
118
+ found = HTTPJSON.get("#{GEOCODING}?#{URI.encode_www_form(name: @place_name, count: 1, language: 'en')}")['results']&.first
119
+ raise Error, "Couldn't find #{@place_name}" unless found
120
+
121
+ Place.new(name: found['name'], latitude: found['latitude'], longitude: found['longitude'], country: found['country_code'])
122
+ end
123
+
124
+ private
125
+
126
+ def fetched(place)
127
+ query = { latitude: place.latitude, longitude: place.longitude, current: CURRENT,
128
+ daily: 'weather_code,temperature_2m_max,temperature_2m_min,uv_index_clear_sky_max', timezone: 'auto',
129
+ forecast_days: DAYS }
130
+ query[:temperature_unit] = 'fahrenheit' if fahrenheit?(place)
131
+ report_of(place, HTTPJSON.get("#{FORECAST}?#{URI.encode_www_form(query)}"), unit_of(place))
132
+ end
133
+
134
+ def fahrenheit?(place) = FAHRENHEIT.include?(place.country)
135
+
136
+ def unit_of(place)
137
+ return '°F' if fahrenheit?(place)
138
+
139
+ '°C'
140
+ end
141
+
142
+ def report_of(place, answer, unit)
143
+ now = answer.fetch('current')
144
+ Report.new(place:, temperature: now['temperature_2m'], code: now['weather_code'], unit:, days: days_of(answer),
145
+ conditions: now.except('time', 'interval'), utc_offset: answer['utc_offset_seconds'].to_i)
146
+ end
147
+
148
+ def days_of(answer)
149
+ daily = answer.fetch('daily')
150
+ daily.fetch('time').each_index.map do |index|
151
+ Day.new(date: daily['time'][index], high: daily['temperature_2m_max'][index], low: daily['temperature_2m_min'][index],
152
+ code: daily['weather_code'][index], uv: daily['uv_index_clear_sky_max']&.at(index))
153
+ end
154
+ end
155
+
156
+ # Your time zone, like Australia/Melbourne, and its city, from tzdata.
157
+ module TimeZone
158
+ module_function
159
+
160
+ # Your time zone's name, from TZ or else where /etc/localtime points, or nil.
161
+ def name
162
+ zone = ENV.fetch('TZ', nil)&.delete_prefix(':')
163
+ zone = File.readlink('/etc/localtime')[%r{zoneinfo/(.+)\z}, 1] if zone.nil? || zone.empty?
164
+ zone
165
+ rescue SystemCallError
166
+ nil
167
+ end
168
+
169
+ # The zone's city, where zone.tab puts it, its name from the zone's, like Melbourne, or nil for a zone without one.
170
+ def place(zone, zone_tab: ZONE_TAB)
171
+ line = File.foreach(zone_tab).find { !it.start_with?('#') && it.split("\t")[2] == zone }
172
+ return unless line
173
+
174
+ country, coordinates = line.split("\t")
175
+ latitude, longitude = coordinates.scan(/[+-]\d+/).map { degrees(it) }
176
+ Place.new(name: zone.split('/').last.tr('_', ' '), latitude:, longitude:, country:)
177
+ rescue SystemCallError
178
+ nil
179
+ end
180
+
181
+ # Degrees from ISO 6709's ±DDMM, ±DDDMM, ±DDMMSS or ±DDDMMSS.
182
+ def degrees(text)
183
+ digits = text[1..]
184
+ whole = 2 + (digits.length % 2)
185
+ parts = [digits[0, whole], digits[whole, 2], digits[whole + 2, 2]].map(&:to_i)
186
+ value = (parts[0] + (parts[1] / 60.0) + (parts[2] / 3600.0)).round(4)
187
+ return -value if text.start_with?('-')
188
+
189
+ value
190
+ end
191
+ end
192
+ end
193
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'json'
5
+
6
+ module Raindown
7
+ class Forecast
8
+ # Where a place's forecast is kept, in ~/.cache/raindown, with when it was kept, and when Open-Meteo last couldn't be
9
+ # reached, so it's fresh for FRESH_FOR seconds after it was kept, or RETRY_AFTER after Open-Meteo couldn't be.
10
+ class Cache
11
+ def initialize(key)
12
+ @key = key
13
+ end
14
+
15
+ # The forecast kept, and whether it's still fresh, which it isn't with fewer days than DAYS, or [nil, false].
16
+ def report
17
+ kept = read
18
+ report = Report.new(**kept[:report], place: Place.new(**kept[:report][:place]), days: kept[:report][:days].map { Day.new(**it) })
19
+ [report, fresh?(kept, report)]
20
+ rescue Errno::ENOENT, JSON::ParserError, ArgumentError, TypeError, NoMethodError
21
+ [nil, false]
22
+ end
23
+
24
+ def keep(report)
25
+ kept = report.to_h.merge(place: report.place.to_h, days: report.days.map(&:to_h))
26
+ write(at: Time.now.to_i, report: kept)
27
+ end
28
+
29
+ # Notes when Open-Meteo couldn't be reached, beside what was kept, keeping when it was kept.
30
+ def unreached
31
+ write(read.merge(unreached_at: Time.now.to_i))
32
+ rescue Errno::ENOENT, JSON::ParserError
33
+ nil
34
+ end
35
+
36
+ private
37
+
38
+ def fresh?(kept, report)
39
+ now = Time.now.to_i
40
+ return true if kept[:unreached_at] && now - kept[:unreached_at] < RETRY_AFTER
41
+
42
+ now - kept[:at] < FRESH_FOR && report.days.size >= DAYS
43
+ end
44
+
45
+ def read = JSON.parse(File.read(file), symbolize_names: true)
46
+
47
+ def write(kept)
48
+ FileUtils.mkdir_p(File.dirname(file))
49
+ File.write(file, JSON.generate(kept))
50
+ end
51
+
52
+ def file
53
+ name = Digest::SHA256.hexdigest(@key)[0, 12]
54
+ File.join(ENV.fetch('XDG_CACHE_HOME', File.join(Dir.home, '.cache')), 'raindown', "forecast-#{name}.json")
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+
5
+ module Raindown
6
+ # A forecast's days as little cards side by side, in text, each with an emoji for its weather in its padding at its
7
+ # top right, its day, its high and low, and its weather in words, on two lines, padded inside:
8
+ # ╭────────────╮╭────────────╮
9
+ # │ ☁️ ││ 🌧️ │
10
+ # │ Today ││ Fri │
11
+ # │ 20° 10° ││ 19° 14° │
12
+ # │ overcast ││ light │
13
+ # │ ││ rain │
14
+ # ╰────────────╯╰────────────╯
15
+ module ForecastCards
16
+ # How wide a card's padding is on each side, its text inside it, and the card inside its borders.
17
+ PADDING = 2
18
+ TEXT = 8
19
+ WIDTH = TEXT + (2 * PADDING)
20
+ BORDERS = '╭╮╰╯─│'
21
+ # An emoji for each of the WMO's weather codes, each two characters wide, as editors show them.
22
+ EMOJI = {
23
+ 0 => '☀️', 1 => '🌤️', 2 => '⛅', 3 => '☁️', 45 => '🌫️', 48 => '🌫️', 51 => '🌦️', 53 => '🌦️', 55 => '🌦️', 56 => '🌨️',
24
+ 57 => '🌨️', 61 => '🌧️', 63 => '🌧️', 65 => '🌧️', 66 => '🌨️', 67 => '🌨️', 71 => '❄️', 73 => '❄️', 75 => '❄️',
25
+ 77 => '❄️', 80 => '🌦️', 81 => '🌦️', 82 => '🌧️', 85 => '🌨️', 86 => '🌨️', 95 => '⛈️', 96 => '⛈️', 99 => '⛈️'
26
+ }.freeze
27
+ UNKNOWN = '❔'
28
+ # Shorter words for the weather where the WMO's don't fit a card's two lines, and how many lines they have.
29
+ SHORTER = { 86 => 'heavy snow', 95 => 'storms', 96 => 'storms, hail', 99 => 'storms, hail' }.freeze
30
+ WORD_LINES = 2
31
+ EMOJI_WIDTH = 2
32
+ EMOJI_GAP = 2
33
+
34
+ module_function
35
+
36
+ # The cards' lines, from the days, the first of them today.
37
+ def lines(days)
38
+ days.each_with_index.map { |day, index| card(day, index) }.transpose.map(&:join)
39
+ end
40
+
41
+ # A card's lines: its top border, its padding with its weather's emoji at its right, its day, temperatures, its
42
+ # weather in words on two lines, and its bottom.
43
+ def card(day, index)
44
+ texts = [label(day, index), temperatures(day), *words(day)]
45
+ pad = ' ' * PADDING
46
+ ["╭#{'─' * WIDTH}╮", "│#{top_padding(day)}│", *texts.map { "│#{pad}#{fit(it)}#{pad}│" }, "╰#{'─' * WIDTH}╯"]
47
+ end
48
+
49
+ # The card's top padding, with its weather's emoji at its right, in the padding's corner, a space from the border,
50
+ # as an app may draw it larger than its text, in line with the text's padding.
51
+ def top_padding(day)
52
+ emoji = EMOJI.fetch(day.code, UNKNOWN)
53
+ "#{' ' * (WIDTH - Unicode::DisplayWidth.of(emoji, emoji: :all) - EMOJI_GAP)}#{emoji}#{' ' * EMOJI_GAP}"
54
+ end
55
+
56
+ # Text padded, by how wide it shows, to the card's text's width.
57
+ def fit(text)
58
+ text + (' ' * [TEXT - Unicode::DisplayWidth.of(text, emoji: :all), 0].max)
59
+ end
60
+
61
+ # The day's weather in words, like partly cloudy, wrapped to the card's text's width, on WORD_LINES lines.
62
+ def words(day)
63
+ wrapped = SHORTER.fetch(day.code, day.words).split.each_with_object([]) do |word, lines|
64
+ next lines << word if lines.empty? || "#{lines.last} #{word}".length > TEXT
65
+
66
+ lines[-1] = "#{lines.last} #{word}"
67
+ end
68
+ (wrapped + ([''] * WORD_LINES)).first(WORD_LINES)
69
+ end
70
+
71
+ def label(day, index)
72
+ return 'Today' if index.zero?
73
+
74
+ Date.parse(day.date).strftime('%a')
75
+ end
76
+
77
+ # Its high and low, without their degrees when they're too long for a card, like -12 -20.
78
+ def temperatures(day)
79
+ text = "#{day.high.round}° #{day.low.round}°"
80
+ return text if text.length <= TEXT
81
+
82
+ text.delete('°')
83
+ end
84
+
85
+ # Where each card's emoji is, on the cards' second line, as [line, from, to], in columns, for an app to draw as large
86
+ # as a line is tall.
87
+ def emoji(days)
88
+ days.each_index.map do |index|
89
+ from = (index * (WIDTH + 2)) + 1 + WIDTH - EMOJI_WIDTH - EMOJI_GAP
90
+ [1, from, from + EMOJI_WIDTH]
91
+ end
92
+ end
93
+
94
+ # Where each card's day is, on the cards' third line, as [line, from, to], for an app to embolden.
95
+ def headings(days)
96
+ days.each_with_index.map do |day, index|
97
+ from = (index * (WIDTH + 2)) + 1 + PADDING
98
+ [2, from, from + label(day, index).length]
99
+ end
100
+ end
101
+
102
+ # The characters of a card's lines that are its borders, as [line, from, to], in columns, as an emoji takes two,
103
+ # for an app to dim.
104
+ def borders(lines)
105
+ lines.each_with_index.flat_map do |line, index|
106
+ column = 0
107
+ line.each_grapheme_cluster.filter_map do |character|
108
+ at = column
109
+ column += Unicode::DisplayWidth.of(character, emoji: :all)
110
+ [index, at, at + 1] if BORDERS.include?(character)
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end