DEV: Allow 3-digit HEX color code in single icon route

Followup to aee8e62
This commit is contained in:
Penar Musaraj 2020-05-14 16:37:45 -04:00
parent 1b7f23a1bc
commit 5ff2a235f6
3 changed files with 21 additions and 2 deletions

View File

@ -64,7 +64,7 @@ class SvgSpriteController < ApplicationController
doc = Nokogiri.XML(icon)
doc.at_xpath("symbol").name = "svg"
doc.at_xpath("svg")['xmlns'] = "http://www.w3.org/2000/svg"
doc.at_xpath("svg")['fill'] = "##{params[:color]}" if params[:color]
doc.at_xpath("svg")['fill'] = adjust_hex(params[:color]) if params[:color]
response.headers["Last-Modified"] = 1.years.ago.httpdate
response.headers["Content-Length"] = doc.to_s.bytesize.to_s
@ -74,4 +74,14 @@ class SvgSpriteController < ApplicationController
end
end
end
private
def adjust_hex(hex)
if hex.size == 3
chars = hex.scan(/\w/)
hex = chars.zip(chars).flatten.join
end
"##{hex}"
end
end

View File

@ -503,7 +503,7 @@ Discourse::Application.routes.draw do
get "svg-sprite/:hostname/svg-:theme_ids-:version.js" => "svg_sprite#show", constraints: { hostname: /[\w\.-]+/, version: /\h{40}/, theme_ids: /([0-9]+(,[0-9]+)*)?/, format: :js }
get "svg-sprite/search/:keyword" => "svg_sprite#search", format: false, constraints: { keyword: /[-a-z0-9\s\%]+/ }
get "svg-sprite/picker-search" => "svg_sprite#icon_picker_search", defaults: { format: :json }
get "svg-sprite/:hostname/icon(/:color)/:name.svg" => "svg_sprite#svg_icon", constraints: { hostname: /[\w\.-]+/, name: /[-a-z0-9\s\%]+/, color: /(\h{6})/, format: :svg }
get "svg-sprite/:hostname/icon(/:color)/:name.svg" => "svg_sprite#svg_icon", constraints: { hostname: /[\w\.-]+/, name: /[-a-z0-9\s\%]+/, color: /(\h{3}{1,2})/, format: :svg }
get "highlight-js/:hostname/:version.js" => "highlight_js#show", constraints: { hostname: /[\w\.-]+/, format: :js }

View File

@ -115,6 +115,15 @@ describe SvgSpriteController do
expect(response.headers["Cache-Control"]).to eq("max-age=86400, public, immutable")
end
it "returns SVG given an icon name and a 3-character HEX color" do
get "/svg-sprite/#{Discourse.current_hostname}/icon/C00/fab-github.svg"
expect(response.status).to eq(200)
expect(response.body).to include('fab-github')
expect(response.body).to include('fill="#CC0000"')
expect(response.headers["Cache-Control"]).to eq("max-age=86400, public, immutable")
end
it "ignores non-HEX colors" do
get "/svg-sprite/#{Discourse.current_hostname}/icon/orange/fab-github.svg"
expect(response.status).to eq(404)