md-show 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1aad05182090cfd84687b2056b5b629361387870a05ba5ff23d94dc9e8b1aed8
4
+ data.tar.gz: f60bd9b8e50d252b9cd366b22ee97f41e85419323f96ee1a2c284b72c6e0192f
5
+ SHA512:
6
+ metadata.gz: 7c983d915a61a1194038d294675951ea722c9dfcac88e134d1baf12e2c1d3c19cc839b7212a6be52431cbb94c03edfcf734c80d64eacf2010c027eaa5635e523
7
+ data.tar.gz: 323db1b15d69e21035e2d1b8df4576b89bea1399fa06c9f0003ffbd3297775346808dd70137c77fe2edd106722c5f8ef8b868df722b059fbcae98b8787f0fd94
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.2.1
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-04-19
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at jonatasdp@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in md-show.gemspec
6
+ gemspec
7
+
8
+ gem "puma"
9
+
10
+ gem "rake", "~> 13.0"
11
+
12
+ gem "rspec", "~> 3.0"
13
+
14
+ gem "rubocop", "~> 1.21"
data/Gemfile.lock ADDED
@@ -0,0 +1,88 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ md-show (0.1.0)
5
+ dotenv
6
+ json
7
+ pg
8
+ redcarpet
9
+ sinatra
10
+
11
+ GEM
12
+ remote: https://rubygems.org/
13
+ specs:
14
+ ast (2.4.2)
15
+ coderay (1.1.3)
16
+ diff-lcs (1.5.0)
17
+ dotenv (2.8.1)
18
+ json (2.6.3)
19
+ method_source (1.0.0)
20
+ mustermann (3.0.0)
21
+ ruby2_keywords (~> 0.0.1)
22
+ nio4r (2.5.8)
23
+ parallel (1.22.1)
24
+ parser (3.1.3.0)
25
+ ast (~> 2.4.1)
26
+ pg (1.4.6)
27
+ pry (0.14.2)
28
+ coderay (~> 1.1)
29
+ method_source (~> 1.0)
30
+ puma (6.0.0)
31
+ nio4r (~> 2.0)
32
+ rack (2.2.6.2)
33
+ rack-protection (3.0.5)
34
+ rack
35
+ rainbow (3.1.1)
36
+ rake (13.0.6)
37
+ redcarpet (3.6.0)
38
+ regexp_parser (2.6.1)
39
+ rexml (3.2.5)
40
+ rspec (3.12.0)
41
+ rspec-core (~> 3.12.0)
42
+ rspec-expectations (~> 3.12.0)
43
+ rspec-mocks (~> 3.12.0)
44
+ rspec-core (3.12.1)
45
+ rspec-support (~> 3.12.0)
46
+ rspec-expectations (3.12.2)
47
+ diff-lcs (>= 1.2.0, < 2.0)
48
+ rspec-support (~> 3.12.0)
49
+ rspec-mocks (3.12.4)
50
+ diff-lcs (>= 1.2.0, < 2.0)
51
+ rspec-support (~> 3.12.0)
52
+ rspec-support (3.12.0)
53
+ rubocop (1.41.0)
54
+ json (~> 2.3)
55
+ parallel (~> 1.10)
56
+ parser (>= 3.1.2.1)
57
+ rainbow (>= 2.2.2, < 4.0)
58
+ regexp_parser (>= 1.8, < 3.0)
59
+ rexml (>= 3.2.5, < 4.0)
60
+ rubocop-ast (>= 1.23.0, < 2.0)
61
+ ruby-progressbar (~> 1.7)
62
+ unicode-display_width (>= 1.4.0, < 3.0)
63
+ rubocop-ast (1.24.0)
64
+ parser (>= 3.1.1.0)
65
+ ruby-progressbar (1.11.0)
66
+ ruby2_keywords (0.0.5)
67
+ sinatra (3.0.5)
68
+ mustermann (~> 3.0)
69
+ rack (~> 2.2, >= 2.2.4)
70
+ rack-protection (= 3.0.5)
71
+ tilt (~> 2.0)
72
+ tilt (2.0.11)
73
+ unicode-display_width (2.3.0)
74
+
75
+ PLATFORMS
76
+ x86_64-darwin-21
77
+ x86_64-darwin-22
78
+
79
+ DEPENDENCIES
80
+ md-show!
81
+ pry
82
+ puma
83
+ rake (~> 13.0)
84
+ rspec (~> 3.0)
85
+ rubocop (~> 1.21)
86
+
87
+ BUNDLED WITH
88
+ 2.3.24
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Jônatas Davi Paganini
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # Markdown Show
2
+
3
+ This gem was created to allow me to run my own presentations.
4
+
5
+ I'm a big fan of markdown and I'd like to turn my simplest markdown files into
6
+ interactive presentations.
7
+
8
+ Features:
9
+
10
+ * Presentation mode: Breaks down all H1 as new slides. Hides rest of content and support keyboard navigation.
11
+ * Run SQL: Any SQL snippet from your markdown can be run in a backend server.
12
+ Check for [demo-sql.md](./demo-sql.md) as an example.
13
+
14
+ ## Installation
15
+
16
+ $ gem install md-show
17
+
18
+ ## Usage
19
+
20
+ $ md-show your-md-file.md "your-postgresql-uri"
21
+
22
+ The interesting part of this lib is the column auto detection which allows us to
23
+ just plot data detecting columns named as `x` and `y`. I initially built this tool
24
+ for my [data science workshop](https://github.com/jonatas/sql-data-science-training)
25
+ and now I'm making it available to allow me to use it in different scenarios.
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ The [public](./public) directory contains the front end files. The server is a
34
+ sinatra app just allowing to run the presentation.
35
+
36
+ ## Contributing
37
+
38
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jonatas/md-show. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/jonatas/md-show/blob/main/CODE_OF_CONDUCT.md).
39
+
40
+ ## License
41
+
42
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
43
+
44
+ ## Code of Conduct
45
+
46
+ Everyone interacting in the Md::Show project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/jonatas/md-show/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "md/show"
6
+
7
+ require "pry"
8
+ Pry.start
9
+
data/bin/md-show ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "md/show"
6
+
7
+ if ENV['PG_URI'].nil? && ARGV.size < 2
8
+ require 'dotenv'
9
+ Dotenv.load!
10
+ end
11
+
12
+ Md::Show.start!
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/demo-sql.md ADDED
@@ -0,0 +1,89 @@
1
+ # Minimal query
2
+
3
+ Will return a table when it does not know the type.
4
+
5
+ Click in the query to run it.
6
+
7
+ ```sql
8
+ SELECT 1;
9
+ ```
10
+ # Naming columns
11
+
12
+ If you name a `x` and `y` columns it will start bringing more data.
13
+
14
+ ```sql
15
+ SELECT 1 as y, now() as x;
16
+ ```
17
+
18
+ # Multi axis
19
+
20
+ For now, it's focused in time series data, which will have a single x and
21
+ multiple y series. To use several series, just prefix your column with `y`.
22
+
23
+ ```sql
24
+ WITH candlesticks AS (
25
+ SELECT
26
+ time_bucket('1 day', time),
27
+ symbol,
28
+ candlestick_agg(time, price, day_volume) AS agg
29
+ FROM
30
+ crypto_ticks
31
+ WHERE
32
+ symbol = 'BTC/USD'
33
+ AND time between now() - interval '1 year' AND now()
34
+ GROUP BY 1,2
35
+ ),
36
+ sma AS (
37
+ SELECT
38
+ time_bucket,
39
+ symbol,
40
+ avg((agg).close) OVER (PARTITION BY symbol ORDER BY time_bucket ROWS BETWEEN 19 PRECEDING AND CURRENT ROW) AS sma
41
+ FROM
42
+ candlesticks
43
+ ),
44
+ std_dev AS (
45
+ SELECT
46
+ sma.time_bucket,
47
+ sma.symbol,
48
+ sqrt(avg(((agg).close - sma) * ((agg).close - sma)) OVER (PARTITION BY sma.symbol ORDER BY sma.time_bucket ROWS BETWEEN 19 PRECEDING AND CURRENT ROW)) AS stddev
49
+ FROM
50
+ candlesticks,
51
+ sma
52
+ WHERE
53
+ candlesticks.time_bucket = sma.time_bucket
54
+ AND candlesticks.symbol = sma.symbol
55
+ )
56
+ SELECT
57
+ std_dev.time_bucket as x,
58
+ sma as y,
59
+ sma + 2 * stddev AS y_upper_band,
60
+ sma - 2 * stddev AS y_lower_band
61
+ FROM
62
+ sma,
63
+ std_dev
64
+ WHERE
65
+ sma.time_bucket = std_dev.time_bucket
66
+ AND sma.symbol = std_dev.symbol
67
+ ORDER BY 1 ASC;
68
+ ```
69
+
70
+ # JSON
71
+
72
+ It can also accept plain data through the `data` alias and just send render it
73
+ using plot.ly.
74
+
75
+ ```sql
76
+ WITH pair as (
77
+ SELECT timevector(bucket, close)
78
+ FROM one_day_candle where symbol = 'ADA/USD'
79
+ )
80
+ SELECT
81
+ toolkit_experimental.to_text(
82
+ timevector->toolkit_experimental.sort(),
83
+ '{"x": {{ TIMES | json_encode() | safe }},
84
+ "y": {{ VALUES | json_encode() | safe }},
85
+ "type": "scatter",
86
+ "title": "ADA/USD Daily Close"
87
+ }')::json as data from pair;
88
+ ```
89
+
@@ -0,0 +1,108 @@
1
+ require 'sinatra/base'
2
+ require 'redcarpet'
3
+ require 'pg'
4
+
5
+ class Md::Show::App < Sinatra::Base
6
+ def pg_uri
7
+ ARGV.size == 1 ? ENV['PG_URI'] : ARGV.last
8
+ end
9
+ # Connect to the PostgreSQL database using the URI provided
10
+ def connect_to_db
11
+ conn = PG.connect(pg_uri)
12
+ yield conn
13
+ ensure
14
+ conn.close if conn
15
+ end
16
+
17
+ # Render the markdown file to HTML using Redcarpet
18
+ def render_markdown(file_path)
19
+ markdown = File.read(file_path)
20
+ renderer = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
21
+ renderer.render(markdown)
22
+ end
23
+
24
+
25
+ # Run the SQL code snippet and return the result
26
+ def run_query(conn, sql)
27
+ #return if sql !~ /^\s*SELECT\t/i
28
+ result = conn.exec(sql)
29
+ response = result.map(&:to_h)
30
+ puts({sql: sql, response: response})
31
+ response
32
+ end
33
+
34
+ set :public_folder, File.join(File.dirname(__FILE__),"../../../public")
35
+
36
+ get '/' do
37
+ # Render the markdown file
38
+ html = render_markdown(ARGV[0])
39
+
40
+ html.scan(%r{<code>sql\n(.*?)\n</code>}m).to_a.each do |match|
41
+ html.gsub!("<code>sql\n#{match[0]}\n</code>",
42
+ "<pre><code class=\"language-sql\">#{match[0].chomp}</code></pre>")
43
+ end
44
+
45
+ # Inject the presentation navigation script
46
+ html = <<-HTML + html
47
+ <head>
48
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.17.1/themes/prism-okaidia.min.css" />
49
+ <script src="https://cdn.jsdelivr.net/npm/prismjs@1.17.1/prism.min.js"></script>
50
+ <script src="https://cdn.jsdelivr.net/npm/prismjs@1.17.1/components/prism-sql.min.js"></script>
51
+ <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
52
+ <script src="/main.js"></script>
53
+ <link rel="stylesheet" href="/main.css">
54
+ </head>
55
+ <button id="first-slide">⏮</button>
56
+ <button id="previous-slide">⬅️</button>
57
+ <button id="start-presentation">▶️</button>
58
+ <button id="stop-presentation" style="display: none;">⏹</button>
59
+ <button id="next-slide">➡️</button>
60
+ <button id="last-slide">⏭</button>
61
+ HTML
62
+
63
+ html
64
+ end
65
+
66
+ def parse_aggregated_results(data)
67
+ data.map do |hash|
68
+ hash.transform_values{|e|JSON.parse(e) rescue cast_results(e)}
69
+ end
70
+ end
71
+
72
+ def cast_results(e)
73
+ return [] unless e
74
+ return e unless e.start_with?("{") && e.end_with?("}")
75
+ e[1..-2].split(",").map{|f|cast_result(f)}
76
+ end
77
+
78
+ def cast_result(element)
79
+ case element
80
+ when /^\d+\.\d+$/
81
+ element.to_f
82
+ when /^"\d{4}-\d{2}-\d{2}\s.+"$/
83
+ element[1..-2]
84
+ else
85
+ element
86
+ end
87
+ end
88
+
89
+ post '/query' do
90
+ request.body.rewind
91
+ query = JSON.parse(request.body.read)['query']
92
+
93
+ result = nil
94
+ connect_to_db do |conn|
95
+ begin
96
+ puts query
97
+ result = conn.exec(query)
98
+ rescue PG::Error => e
99
+ puts "Ops!", e.message
100
+ return [500, { message: e.message }.to_json]
101
+ end
102
+ end
103
+ data = parse_aggregated_results(result)
104
+
105
+ [200, data.to_json]
106
+ end
107
+ end
108
+
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Md
4
+ module Show
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
data/lib/md/show.rb ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/setup'
4
+
5
+ require_relative "show/version"
6
+ require_relative "show/app"
7
+
8
+ module Md
9
+ module Show
10
+ class Error < StandardError; end
11
+
12
+ module_function
13
+ def start!
14
+ App.run!
15
+ end
16
+ end
17
+ end
data/md-show.gemspec ADDED
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/md/show/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "md-show"
7
+ spec.version = Md::Show::VERSION
8
+ spec.authors = ["Jônatas Davi Paganini"]
9
+ spec.email = ["jonatasdp@gmail.com"]
10
+
11
+ spec.summary = "Markdown show AKA md-show."
12
+ spec.description = "Preview markdown in a web page with the possibility of running sql snippets."
13
+ spec.homepage = "https://github.com/jonatas/md-show."
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.6.0"
16
+
17
+ # spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = spec.homepage
21
+ spec.metadata["changelog_uri"] = "#{spec.homepage}/main/tree/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
28
+ end
29
+ end
30
+ spec.bindir = "bin"
31
+ spec.executables = "md-show"
32
+ spec.require_paths = ["lib"]
33
+ spec.add_dependency 'sinatra'
34
+ spec.add_dependency 'dotenv'
35
+ spec.add_dependency 'redcarpet'
36
+ spec.add_dependency 'pg'
37
+ spec.add_dependency 'json'
38
+
39
+ spec.add_development_dependency "pry"
40
+ end
data/public/main.css ADDED
@@ -0,0 +1,39 @@
1
+ table {
2
+ font-family: 'Open Sans', sans-serif;
3
+ border-collapse: collapse;
4
+ background-color: #f0f0f0;
5
+ border: 1px solid #ddd;
6
+ }
7
+
8
+ td, th {
9
+ padding: 10px;
10
+ border: 1px solid #ddd;
11
+ }
12
+
13
+ tr:hover {
14
+ background-color: #ddd;
15
+ }
16
+
17
+ pre {
18
+ font-family: monospace;
19
+ padding: 10px;
20
+ border: 1px solid #ccc;
21
+ white-space: pre-wrap;
22
+ }
23
+
24
+ button {
25
+ padding: 0px;
26
+ border: 0px;
27
+ }
28
+
29
+ body.presentation-mode{
30
+ font-family: "Open Sans", sans-serif;
31
+ }
32
+ blockquote > p {
33
+ font-size: 150%;
34
+ font-style: italic;
35
+ color: #555;
36
+ background-color: #f9f9f9;
37
+ border-left: 5px solid #ccc;
38
+ padding: 10px 20px;
39
+ }
data/public/main.js ADDED
@@ -0,0 +1,201 @@
1
+ function openTab(evt, tabName) {
2
+ var i, tabcontent, tablinks;
3
+ tabcontent = document.getElementsByClassName("tabcontent");
4
+ for (i = 0; i < tabcontent.length; i++) {
5
+ tabcontent[i].style.display = "none";
6
+ }
7
+
8
+ tablinks = document.getElementsByClassName("tablinks");
9
+ for (i = 0; i < tablinks.length; i++) {
10
+ tablinks[i].className = tablinks[i].className.replace(" active", "");
11
+ }
12
+
13
+ document.getElementById(tabName).style.display = "block";
14
+ evt.currentTarget.className += " active";
15
+ }
16
+ const on = (e) => document.querySelector(e);
17
+ const all = (e) => document.querySelectorAll(e);
18
+ const parent = (element, tagName) => {
19
+ let ancestor = element;
20
+ while (ancestor.tagName !== tagName.toUpperCase()) {
21
+ ancestor = ancestor.parentNode;
22
+ }
23
+ return ancestor;
24
+ };
25
+
26
+ function runSelectStatements(){
27
+ const sql_blocks = all("code[class*='language-sql']");
28
+
29
+ for (let i = 0; i < sql_blocks.length; i++) {
30
+ sql_blocks[i].addEventListener("click", fetchQuery);
31
+ }
32
+ }
33
+
34
+ function fetchQuery(event) {
35
+ element = parent(event.target, "code");
36
+ element.removeEventListener("click", fetchQuery);
37
+ query = element.innerText;
38
+ fetch("/query", {
39
+ method: "post",
40
+ headers: { "Content-Type": "application/json" },
41
+ body: JSON.stringify({ query })
42
+ })
43
+ .then(response => response.json())
44
+ .then(data => renderResult(data, element));
45
+ }
46
+
47
+ function plot(data, element){
48
+ title = data.title || data[0].title;
49
+ let layout = {title}
50
+ if (!Array.isArray(data[0].x)) {
51
+ let x, y;
52
+ y_axis = Object.keys(data[0]).filter(e => e.match("^y"));
53
+ x = data.map(row => row.x);
54
+ axis_y = (y) => data.map(row => row[y]);
55
+ type = data.type || data[0].type || "scatter";
56
+ // FIXME: why this syntax is not valid?
57
+ // data = y_axis.map(key => {x, "y": axis_y(key), type });
58
+ data = y_axis.map(function(key){return {x: x, y: axis_y(key), type: type };})
59
+ }
60
+ div = document.createElement("div");
61
+ element.appendChild(div);
62
+ console.log({data});
63
+ Plotly.newPlot(div, data, layout);
64
+ }
65
+
66
+ function table(data, element){
67
+ // Render the result as a table
68
+ let table = document.createElement("table");
69
+ let thead = document.createElement("thead");
70
+ let tbody = document.createElement("tbody");
71
+ let headerRow = document.createElement("tr");
72
+
73
+ table.style.border =
74
+ thead.style.border =
75
+ tbody.style.border = "0.4px dotted";
76
+
77
+ Object.keys(data[0]).forEach(key => {
78
+ let headerCell = document.createElement("th");
79
+ headerCell.textContent = key;
80
+ headerRow.appendChild(headerCell);
81
+ });
82
+
83
+ thead.appendChild(headerRow);
84
+
85
+ data.forEach(serie=> {
86
+ if (!Array.isArray(serie)){
87
+ serie = [serie];
88
+ }
89
+ serie.forEach(row => {
90
+ let dataRow = document.createElement("tr");
91
+ Object.values(row).forEach(value => {
92
+ let dataCell = document.createElement("td");
93
+ dataCell.textContent = value;
94
+ dataRow.appendChild(dataCell);
95
+ });
96
+ tbody.appendChild(dataRow);
97
+ });
98
+
99
+ table.appendChild(thead);
100
+ table.appendChild(tbody);
101
+ });
102
+
103
+ element.parentNode.nextElementSibling.appendChild(table);
104
+ }
105
+
106
+ function renderResult(res, element) {
107
+ let data = Array.isArray(res) ? res : [res];
108
+ if (data[0].hasOwnProperty("data")){
109
+ plot([data[0].data], element);
110
+ } else if (data[0].hasOwnProperty("x")){
111
+ plot(data, element);
112
+ } else {
113
+ table(data, element);
114
+ }
115
+ }
116
+
117
+ function bindPresentationMode(){
118
+ let sections = all("h1, h2");
119
+ for (let i = 0; i < sections.length; i++) {
120
+ let currentSection = sections[i];
121
+ let slide = document.createElement("div");
122
+ slide.className = "slide";
123
+ let nextSection = sections[i + 1] || null;
124
+ let nextSectionParent = nextSection ? nextSection.parentNode : null;
125
+ let currentSectionParent = currentSection.parentNode;
126
+ let nextSibling = currentSection.nextSibling;
127
+ while (nextSibling !== nextSection && nextSibling !== null) {
128
+ slide.appendChild(nextSibling);
129
+ nextSibling = currentSection.nextSibling;
130
+ }
131
+ currentSectionParent.replaceChild(slide, currentSection);
132
+ slide.insertBefore(currentSection, slide.firstChild);
133
+ }
134
+
135
+ let currentSlide = 0;
136
+ const slides = all(".slide");
137
+
138
+ const showSlide = function(slideNumber) {
139
+ slides[currentSlide].style.display = "none";
140
+ currentSlide = slideNumber;
141
+ slides[slideNumber].style.display = "block";
142
+ };
143
+
144
+ const previousSlide = function() {
145
+ showSlide((currentSlide - 1 + slides.length) % slides.length);
146
+ };
147
+
148
+ const nextSlide = function() {
149
+ showSlide((currentSlide + 1) % slides.length);
150
+ }
151
+
152
+ const keyboardShortcuts = function(event) {
153
+ if (event.keyCode === 27) {
154
+ htmlMode();
155
+ } else if (event.keyCode === 37) {
156
+ previousSlide();
157
+ } else if (event.keyCode === 39) {
158
+ nextSlide();
159
+ }
160
+ };
161
+
162
+ const presentationMode = function() {
163
+ slides.forEach(function(slide) {
164
+ slide.style.display = "none";
165
+ });
166
+ showSlide(currentSlide);
167
+
168
+ document.body.classList.add("presentation-mode");
169
+ on("#start-presentation").style.display = "none";
170
+ on("#stop-presentation").style.display = "inline";
171
+
172
+ document.addEventListener("keydown", keyboardShortcuts);
173
+ };
174
+
175
+ const htmlMode = function() {
176
+ slides.forEach(function(slide) {
177
+ slide.style.display = "block";
178
+ });
179
+
180
+ document.body.classList.remove("presentation-mode");
181
+ on("#start-presentation").style.display = "inline";
182
+ on("#stop-presentation").style.display = "none";
183
+
184
+ document.removeEventListener("keydown", keyboardShortcuts);
185
+ };
186
+
187
+ showSlide(0);
188
+
189
+ on("#start-presentation").addEventListener("click", presentationMode)
190
+ on("#stop-presentation").addEventListener("click", htmlMode)
191
+ on("#next-slide").addEventListener("click", nextSlide);
192
+ on("#previous-slide").addEventListener("click",previousSlide);
193
+
194
+ document.querySelector("#first-slide").addEventListener("click", event => showSlide(0));
195
+ document.querySelector("#last-slide").addEventListener("click", event => showSlide(slides.length - 1));
196
+ }
197
+
198
+ document.addEventListener("DOMContentLoaded", function() {
199
+ runSelectStatements();
200
+ bindPresentationMode();
201
+ });
data/sig/md/show.rbs ADDED
@@ -0,0 +1,6 @@
1
+ module Md
2
+ module Show
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,152 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: md-show
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jônatas Davi Paganini
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2023-04-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: sinatra
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: dotenv
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: redcarpet
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pg
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: json
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: pry
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description: Preview markdown in a web page with the possibility of running sql snippets.
98
+ email:
99
+ - jonatasdp@gmail.com
100
+ executables:
101
+ - md-show
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".rspec"
106
+ - ".rubocop.yml"
107
+ - ".ruby-version"
108
+ - CHANGELOG.md
109
+ - CODE_OF_CONDUCT.md
110
+ - Gemfile
111
+ - Gemfile.lock
112
+ - LICENSE.txt
113
+ - README.md
114
+ - Rakefile
115
+ - bin/console
116
+ - bin/md-show
117
+ - bin/setup
118
+ - demo-sql.md
119
+ - lib/md/show.rb
120
+ - lib/md/show/app.rb
121
+ - lib/md/show/version.rb
122
+ - md-show.gemspec
123
+ - public/main.css
124
+ - public/main.js
125
+ - sig/md/show.rbs
126
+ homepage: https://github.com/jonatas/md-show.
127
+ licenses:
128
+ - MIT
129
+ metadata:
130
+ homepage_uri: https://github.com/jonatas/md-show.
131
+ source_code_uri: https://github.com/jonatas/md-show.
132
+ changelog_uri: https://github.com/jonatas/md-show./main/tree/CHANGELOG.md
133
+ post_install_message:
134
+ rdoc_options: []
135
+ require_paths:
136
+ - lib
137
+ required_ruby_version: !ruby/object:Gem::Requirement
138
+ requirements:
139
+ - - ">="
140
+ - !ruby/object:Gem::Version
141
+ version: 2.6.0
142
+ required_rubygems_version: !ruby/object:Gem::Requirement
143
+ requirements:
144
+ - - ">="
145
+ - !ruby/object:Gem::Version
146
+ version: '0'
147
+ requirements: []
148
+ rubygems_version: 3.4.6
149
+ signing_key:
150
+ specification_version: 4
151
+ summary: Markdown show AKA md-show.
152
+ test_files: []