Skip to content

Instantly share code, notes, and snippets.

@MatheusRich
Last active December 22, 2023 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatheusRich/82967d906057c734361a3dde2762b218 to your computer and use it in GitHub Desktop.
Save MatheusRich/82967d906057c734361a3dde2762b218 to your computer and use it in GitHub Desktop.
Code Picture MVP
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "prism"
gem "nokogiri"
end
require "prism"
require "nokogiri"
file = ARGV[0]
abort("Missing file") if file.nil? || !File.exist?(file)
result = Prism.lex_file(file)
if result.failure?
errors = result.errors.map { " - #{_1.message}" }
abort("Failed to parse file:\n#{errors.join("\n")}")
end
# nicer colors than just pure random
def rand_color
"hsl(#{rand(0..360)},#{rand(70..110)}%,#{rand(40..90)}%)"
end
random_colors = {}
RANDOM_COLORS_THEME = ->(token_type) { random_colors[token_type] ||= rand_color }
THEME = RANDOM_COLORS_THEME
Pixel = Data.define(:color, :token_type, :token_value)
pixels = result.value.filter_map do |(token, _)|
next if token.type == :WORDS_SEP
next if token.type == :IGNORED_NEWLINE
next if token.type == :NEWLINE
next if token.type == :EOF
next if token.type == :MISSING
next if token.type == :NOT_PROVIDED
Pixel.new(THEME[token.type], token.type, token.value)
end
row_size = Math.sqrt(pixels.size).ceil
builder = Nokogiri::HTML4::Builder.new do |doc|
doc.html do
doc.style do
doc.text(
<<~CSS
.pixel {
display: table-cell;
width: 15px;
height: 15px;
position: relative;
}
CSS
)
doc.text(
<<~CSS
.pixel:hover::after {
display: block;
content: attr(data-content);
position: absolute;
z-index: 100;
top: 30px;
background: white;
color: black;
padding: 5px;
min-width: 150px;
min-height: 30px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
CSS
)
doc.text(".row { display: table-row; }")
end
doc.body do
pixels.each_slice(row_size).each do |row|
doc.div(class: "row") do
row.each do |pixel|
doc.span(
class: "pixel",
style: "background-color: #{pixel.color}",
"data-content": "Type: #{pixel.token_type}\nValue: #{pixel.token_value.inspect}"
)
end
end
end
end
end
end
File.write("code-picture.html", builder.to_html)
`open code-picture.html`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment