Skip to content

Commit

Permalink
Add logic to render webp in articles
Browse files Browse the repository at this point in the history
  • Loading branch information
rossta committed Dec 14, 2024
1 parent 7606674 commit 15518be
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion app/views/components/markdown/article.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,29 @@ def code_block(source, metadata = "", **attributes)
render ::CodeBlock::Article.new(source, language: language, **json_attributes, **attributes)
end

def image_src_attrs(src)
image_file = ImageFile.new(src)
unless %w[.jpg .jpeg .png .webp].include?(image_file.ext)
return {src: helpers.asset_path(image_file.to_s)}
end

srcset = [
"400w",
"800w",
"1200w"
].map { |size| "#{helpers.asset_path(image_file.as_webp(size))} #{size}" }

{
src: helpers.asset_path(image_file.as_webp),
srcset:,
sizes: "(max-width: 767px) 100vw, (max-width: 1023px) 50vw, (min-width: 1280px) 33vw"
}
end

def image(src, alt: "", title: "")
title, json_attributes = parse_text_and_metadata(title, separator: "|")
figure(**json_attributes) do
image_tag(src, alt: alt, title: title, loading: "lazy")
img(**image_src_attrs(src), alt:)
figcaption { title }
end
end
Expand Down Expand Up @@ -71,4 +90,28 @@ def call(template, content)
end
end
end

class ImageFile
def exists?
File.exist?(file)
end

attr_reader :file
def initialize(file)
@file = file
end

def to_s = file

def as_webp(*suffixes)
suffixes = [] if suffixes == ["1200w"]
ImageFile.new("#{dirname}/#{([basename] + suffixes).join("-")}.webp")
end

def ext = File.extname(file)

def basename = File.basename(file, ".*")

def dirname = File.dirname(file)
end
end

0 comments on commit 15518be

Please sign in to comment.