vectory 0.13.2 → 0.13.4
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.
- checksums.yaml +4 -4
- data/.github/workflows/rake.yml +25 -1
- data/.github/workflows/release.yml +1 -0
- data/Gemfile +3 -1
- data/README.adoc +228 -4
- data/docs/Gemfile +3 -0
- data/docs/lychee.toml +3 -12
- data/docs/reference/api.adoc +194 -0
- data/lib/vectory/cli.rb +42 -4
- data/lib/vectory/configuration.rb +3 -2
- data/lib/vectory/emf.rb +4 -0
- data/lib/vectory/eps.rb +4 -0
- data/lib/vectory/errors.rb +11 -0
- data/lib/vectory/file_magic.rb +7 -2
- data/lib/vectory/image.rb +32 -3
- data/lib/vectory/png.rb +40 -0
- data/lib/vectory/png_options.rb +69 -0
- data/lib/vectory/png_renderer.rb +74 -0
- data/lib/vectory/ps.rb +4 -0
- data/lib/vectory/svg.rb +6 -0
- data/lib/vectory/svg_class_suffixer.rb +205 -0
- data/lib/vectory/svg_input_policy.rb +50 -0
- data/lib/vectory/svg_mapping.rb +59 -0
- data/lib/vectory/svg_namespace_binding.rb +228 -0
- data/lib/vectory/svg_subtree_graft.rb +97 -0
- data/lib/vectory/svg_transform.rb +82 -0
- data/lib/vectory/svg_transform_pipeline.rb +97 -0
- data/lib/vectory/vector.rb +0 -45
- data/lib/vectory/version.rb +1 -1
- data/lib/vectory.rb +12 -8
- data/script/check_png_shell +235 -0
- data/vectory.gemspec +9 -3
- metadata +74 -12
data/lib/vectory/cli.rb
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
require "thor"
|
|
2
2
|
require "vectory"
|
|
3
|
+
require_relative "png_options"
|
|
3
4
|
|
|
4
5
|
module Vectory
|
|
5
6
|
class CLI < Thor
|
|
@@ -32,6 +33,7 @@ module Vectory
|
|
|
32
33
|
PS = "ps".freeze
|
|
33
34
|
SVG = "svg".freeze
|
|
34
35
|
EMF = "emf".freeze
|
|
36
|
+
PNG = "png".freeze
|
|
35
37
|
|
|
36
38
|
def self.all
|
|
37
39
|
constants.map { |x| const_get(x) }
|
|
@@ -44,16 +46,25 @@ module Vectory
|
|
|
44
46
|
|
|
45
47
|
desc "convert INPUT_FILE_NAME",
|
|
46
48
|
"Perform pairwise vector image conversions for common vector image " \
|
|
47
|
-
"formats (EPS, PS, EMF, SVG)"
|
|
49
|
+
"formats (EPS, PS, EMF, SVG) and PNG output"
|
|
48
50
|
option :format,
|
|
49
51
|
aliases: :f,
|
|
50
52
|
required: true,
|
|
51
|
-
desc: "the desired output format (one of: svg, eps, ps, emf)"
|
|
53
|
+
desc: "the desired output format (one of: svg, eps, ps, emf, png)"
|
|
52
54
|
|
|
53
55
|
option :output,
|
|
54
56
|
aliases: :o,
|
|
55
57
|
desc: "file path to the desired output file (with the file " \
|
|
56
58
|
"extension)"
|
|
59
|
+
option :font, type: :string, repeatable: true,
|
|
60
|
+
desc: "explicit font face FAMILY=PATH (repeatable)"
|
|
61
|
+
option :fallback_font, type: :string, repeatable: true,
|
|
62
|
+
desc: "ordered fallback face FAMILY=PATH (repeatable)"
|
|
63
|
+
option :width, type: :string, desc: "PNG width in pixels"
|
|
64
|
+
option :height, type: :string, desc: "PNG height in pixels"
|
|
65
|
+
option :scale, type: :string, desc: "PNG scale factor"
|
|
66
|
+
option :background, type: :string,
|
|
67
|
+
desc: "PNG background: transparent, #RRGGBB or #RRGGBBAA"
|
|
57
68
|
def convert(file)
|
|
58
69
|
unless supported_format?(options[:format])
|
|
59
70
|
return unsupported_format_error(options[:format])
|
|
@@ -68,9 +79,16 @@ module Vectory
|
|
|
68
79
|
return unsupported_input_format_error
|
|
69
80
|
end
|
|
70
81
|
|
|
82
|
+
PngOptions.validate_format!(options)
|
|
71
83
|
object = source_object(file, input_format)
|
|
72
84
|
|
|
73
85
|
convert_to_format(object, options)
|
|
86
|
+
rescue Vectory::Error => e
|
|
87
|
+
handle_vectory_error(e)
|
|
88
|
+
rescue ::SystemCallError, IOError => e
|
|
89
|
+
# A missing input file or an unwritable output path.
|
|
90
|
+
Vectory.ui.error(e.message)
|
|
91
|
+
STATUS_SYSTEM_CALL_ERROR
|
|
74
92
|
end
|
|
75
93
|
default_task :convert
|
|
76
94
|
|
|
@@ -126,7 +144,9 @@ module Vectory
|
|
|
126
144
|
def convert_to_format(object, options)
|
|
127
145
|
path = options[:output] || current_dir_path(object.initial_path,
|
|
128
146
|
options[:format])
|
|
129
|
-
to_format(object, options[:format])
|
|
147
|
+
result = to_format(object, options[:format])
|
|
148
|
+
result.write(path)
|
|
149
|
+
print_png_warnings(result.warnings) if options[:format] == "png"
|
|
130
150
|
Vectory.ui.info("Output file was written to #{path}")
|
|
131
151
|
|
|
132
152
|
STATUS_SUCCESS
|
|
@@ -137,15 +157,33 @@ module Vectory
|
|
|
137
157
|
def handle_vectory_error(exception)
|
|
138
158
|
Vectory.ui.error(exception.message)
|
|
139
159
|
|
|
140
|
-
MAP_ERROR_TO_STATUS
|
|
160
|
+
match = MAP_ERROR_TO_STATUS.find { |type, _status| exception.is_a?(type) }
|
|
161
|
+
match ? match.last : raise(exception)
|
|
141
162
|
end
|
|
142
163
|
|
|
143
164
|
def current_dir_path(input_path, output_format)
|
|
144
165
|
File.join(Dir.pwd, "#{File.basename(input_path, '.*')}.#{output_format}")
|
|
145
166
|
end
|
|
146
167
|
|
|
168
|
+
def print_png_warnings(warnings)
|
|
169
|
+
seen = {}
|
|
170
|
+
warnings.each do |warning|
|
|
171
|
+
key = [warning.requested_family, warning.selected_family,
|
|
172
|
+
warning.style, warning.weight, warning.stretch, warning.scalars]
|
|
173
|
+
next if seen[key]
|
|
174
|
+
|
|
175
|
+
seen[key] = true
|
|
176
|
+
warn("Font substitution: #{warning.requested_family} -> " \
|
|
177
|
+
"#{warning.selected_family}; style=#{warning.style}; " \
|
|
178
|
+
"weight=#{warning.weight}; stretch=#{warning.stretch}; " \
|
|
179
|
+
"scalars=#{warning.scalars.map { |scalar| format('U+%04X', scalar) }.join(',')}")
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
|
|
147
183
|
def to_format(object, format)
|
|
148
184
|
method_name = "to_#{format}"
|
|
185
|
+
return object.public_send(method_name, **PngOptions.new(options).keywords) if format == "png"
|
|
186
|
+
|
|
149
187
|
object.public_send(method_name)
|
|
150
188
|
end
|
|
151
189
|
end
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "yeptris/psych"
|
|
4
|
+
|
|
3
5
|
module Vectory
|
|
4
6
|
# Configuration for Vectory
|
|
5
7
|
#
|
|
@@ -72,8 +74,7 @@ module Vectory
|
|
|
72
74
|
# @return [self] the configuration instance
|
|
73
75
|
# @raise [Errno::ENOENT] if the file doesn't exist
|
|
74
76
|
def self.load_from_file(path)
|
|
75
|
-
|
|
76
|
-
config_data = YAML.load_file(path)
|
|
77
|
+
config_data = Yeptris::Psych.load_file(path)
|
|
77
78
|
|
|
78
79
|
config = instance
|
|
79
80
|
config.timeout = config_data["timeout"] || config.timeout
|
data/lib/vectory/emf.rb
CHANGED
data/lib/vectory/eps.rb
CHANGED
data/lib/vectory/errors.rb
CHANGED
|
@@ -3,6 +3,17 @@
|
|
|
3
3
|
module Vectory
|
|
4
4
|
class ConversionError < Error; end
|
|
5
5
|
|
|
6
|
+
class RenderProfileError < ConversionError; end
|
|
7
|
+
class MalformedSvgError < ConversionError; end
|
|
8
|
+
class FontError < ConversionError; end
|
|
9
|
+
class ForbiddenExternalReferenceError < ConversionError; end
|
|
10
|
+
class RenderLimitError < ConversionError; end
|
|
11
|
+
|
|
12
|
+
class UnsupportedPlatformError < SystemCallError; end
|
|
13
|
+
class RendererLoadError < SystemCallError; end
|
|
14
|
+
class NativeRenderError < SystemCallError; end
|
|
15
|
+
class PngEncodingError < SystemCallError; end
|
|
16
|
+
|
|
6
17
|
class InvalidFormatError < Error
|
|
7
18
|
def initialize(format, supported_formats)
|
|
8
19
|
super("Invalid format '#{format}'. Supported formats: #{supported_formats.join(', ')}")
|
data/lib/vectory/file_magic.rb
CHANGED
|
@@ -22,7 +22,7 @@ module Vectory
|
|
|
22
22
|
end
|
|
23
23
|
|
|
24
24
|
def detect
|
|
25
|
-
beginning =
|
|
25
|
+
beginning = header
|
|
26
26
|
|
|
27
27
|
eps_slice = beginning.byteslice(0, EPS_30_MAGIC.size)
|
|
28
28
|
Vectory.ui.debug("File magic is '#{to_bytes(beginning)}' of '#{@path}'.")
|
|
@@ -40,12 +40,17 @@ module Vectory
|
|
|
40
40
|
|
|
41
41
|
private
|
|
42
42
|
|
|
43
|
+
# File.read returns nil, not "", for an empty file.
|
|
44
|
+
def header
|
|
45
|
+
File.read(@path, 100, mode: "rb") || "".b
|
|
46
|
+
end
|
|
47
|
+
|
|
43
48
|
def to_bytes(str)
|
|
44
49
|
str.unpack("c*").map { |e| "\\x#{e.to_s(16).rjust(2, '0')}" }.join
|
|
45
50
|
end
|
|
46
51
|
|
|
47
52
|
def contain_svg_tag?
|
|
48
|
-
content = File.read(@path, 4096)
|
|
53
|
+
content = File.read(@path, 4096).to_s
|
|
49
54
|
|
|
50
55
|
:svg if content.include?("<svg")
|
|
51
56
|
end
|
data/lib/vectory/image.rb
CHANGED
|
@@ -6,7 +6,7 @@ module Vectory
|
|
|
6
6
|
class Image
|
|
7
7
|
class << self
|
|
8
8
|
def from_path(path)
|
|
9
|
-
new(File.read(path, mode: "rb"))
|
|
9
|
+
new(File.read(path, mode: "rb"), path)
|
|
10
10
|
end
|
|
11
11
|
|
|
12
12
|
def from_content(content)
|
|
@@ -14,14 +14,43 @@ module Vectory
|
|
|
14
14
|
end
|
|
15
15
|
end
|
|
16
16
|
|
|
17
|
-
attr_reader :content
|
|
17
|
+
attr_reader :content, :initial_path
|
|
18
18
|
|
|
19
|
-
def initialize(content)
|
|
19
|
+
def initialize(content = nil, initial_path = nil)
|
|
20
20
|
@content = content
|
|
21
|
+
@initial_path = initial_path
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def size
|
|
25
|
+
content.bytesize
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def file_size
|
|
29
|
+
raise(NotWrittenToDiskError) unless @path
|
|
30
|
+
|
|
31
|
+
File.size(@path)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def write(path = nil)
|
|
35
|
+
target_path = path || @path || tmp_path
|
|
36
|
+
File.binwrite(target_path, content)
|
|
37
|
+
@path = File.expand_path(target_path)
|
|
38
|
+
|
|
39
|
+
self
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def path
|
|
43
|
+
@path || raise(NotWrittenToDiskError)
|
|
21
44
|
end
|
|
22
45
|
|
|
23
46
|
private
|
|
24
47
|
|
|
25
48
|
attr_writer :content
|
|
49
|
+
|
|
50
|
+
def tmp_path
|
|
51
|
+
dir = Dir.mktmpdir
|
|
52
|
+
filename = "image.#{self.class.default_extension}"
|
|
53
|
+
File.join(dir, filename)
|
|
54
|
+
end
|
|
26
55
|
end
|
|
27
56
|
end
|
data/lib/vectory/png.rb
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "image_size"
|
|
4
|
+
|
|
5
|
+
module Vectory
|
|
6
|
+
class Png < Image
|
|
7
|
+
def self.default_extension
|
|
8
|
+
"png"
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def self.mimetype
|
|
12
|
+
"image/png"
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
attr_reader :warnings
|
|
16
|
+
|
|
17
|
+
def initialize(content, initial_path = nil, warnings: [])
|
|
18
|
+
super(content.b, initial_path)
|
|
19
|
+
@warnings = warnings.dup.freeze
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def mime
|
|
23
|
+
self.class.mimetype
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def width
|
|
27
|
+
dimensions.width
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def height
|
|
31
|
+
dimensions.height
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
private
|
|
35
|
+
|
|
36
|
+
def dimensions
|
|
37
|
+
@dimensions ||= ImageSize.new(content)
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Vectory
|
|
4
|
+
# Converts command-line PNG options into the renderer's public values.
|
|
5
|
+
class PngOptions
|
|
6
|
+
NAMES = %w[font fallback_font width height scale background].freeze
|
|
7
|
+
|
|
8
|
+
def self.validate_format!(options)
|
|
9
|
+
return if options[:format] == "png"
|
|
10
|
+
return unless NAMES.any? { |name| options.key?(name) }
|
|
11
|
+
|
|
12
|
+
raise ConversionError, "Font and render-profile options require PNG output"
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def initialize(options)
|
|
16
|
+
@options = options
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def keywords
|
|
20
|
+
PngRenderer.with_errors do
|
|
21
|
+
{ profile: profile, fonts: fonts, fallback_fonts: fallback_fonts }
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
private
|
|
26
|
+
|
|
27
|
+
def profile
|
|
28
|
+
%w[width height scale background].each_with_object({}) do |name, values|
|
|
29
|
+
next unless @options.key?(name)
|
|
30
|
+
|
|
31
|
+
values[name.to_sym] = profile_value(name, @options[name])
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def profile_value(name, value)
|
|
36
|
+
case name
|
|
37
|
+
when "width", "height" then Integer(value, 10)
|
|
38
|
+
else value
|
|
39
|
+
end
|
|
40
|
+
rescue ArgumentError, TypeError
|
|
41
|
+
raise RenderProfileError, "Invalid PNG #{name}: #{value}"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def fonts
|
|
45
|
+
Array(@options[:font]).each_with_object({}) do |assignment, families|
|
|
46
|
+
family, face = font_face(assignment)
|
|
47
|
+
(families[family] ||= []) << face
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def fallback_fonts
|
|
52
|
+
Array(@options[:fallback_font]).map do |assignment|
|
|
53
|
+
_family, face = font_face(assignment)
|
|
54
|
+
face
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def font_face(assignment)
|
|
59
|
+
family, path = assignment.split("=", 2)
|
|
60
|
+
if family.nil? || family.strip.empty? || path.nil? || path.empty?
|
|
61
|
+
raise FontError, "Font option must be FAMILY=PATH"
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
[family, Svgpng::FontFace.new(bytes: File.binread(path), source_id: path, family: family)]
|
|
65
|
+
rescue ::SystemCallError, IOError => e
|
|
66
|
+
raise Vectory::SystemCallError, "Cannot read font: #{e.message}"
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Vectory
|
|
4
|
+
# Keep the optional native dependency behind the PNG projection boundary.
|
|
5
|
+
module PngRenderer
|
|
6
|
+
def self.render(content, profile:, fonts:, fallback_fonts:)
|
|
7
|
+
with_errors do
|
|
8
|
+
result = Svgpng.render(content, profile: profile, fonts: fonts,
|
|
9
|
+
fallback_fonts: fallback_fonts)
|
|
10
|
+
Png.new(result.png_bytes, warnings: result.warnings)
|
|
11
|
+
end
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def self.with_errors
|
|
15
|
+
require "svgpng"
|
|
16
|
+
yield
|
|
17
|
+
rescue LoadError => e
|
|
18
|
+
raise RendererLoadError, e.message
|
|
19
|
+
rescue Svgpng::Error => e
|
|
20
|
+
raise mapped_error(e), describe(e)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# The native layer reports only a status number; its typed details say why.
|
|
24
|
+
def self.describe(error)
|
|
25
|
+
return error.message unless error.message.match?(/\(status \d+\)\z/)
|
|
26
|
+
|
|
27
|
+
explain = status_messages.find { |type, _message| error.is_a?(type) }&.last
|
|
28
|
+
explain ? explain.call(error) : error.message
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def self.status_messages
|
|
32
|
+
{
|
|
33
|
+
Svgpng::FontMetadataError => lambda { |_error|
|
|
34
|
+
"Font face is unreadable, or its own family name differs from the family it was given"
|
|
35
|
+
},
|
|
36
|
+
Svgpng::DuplicateFontError => ->(_error) { "Two font faces share one family, style, weight and stretch" },
|
|
37
|
+
Svgpng::MissingFamilyError => ->(error) { "No font face was given for #{family(error)}" },
|
|
38
|
+
Svgpng::MissingGlyphError => lambda { |error|
|
|
39
|
+
"#{family(error).sub(/\A./, &:upcase)} has no glyph for #{scalars(error)}"
|
|
40
|
+
},
|
|
41
|
+
Svgpng::ForbiddenReferenceError => ->(error) { "External reference forbidden: #{reference(error)}" },
|
|
42
|
+
}
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def self.family(error)
|
|
46
|
+
error.requested_family ? "font family #{error.requested_family.inspect}" : "a font family in the SVG"
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def self.scalars(error)
|
|
50
|
+
values = Array(error.scalars).map { |scalar| format("U+%04X", scalar) }
|
|
51
|
+
values.empty? ? "some characters" : values.join(", ")
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def self.reference(error)
|
|
55
|
+
[error.reference_class, error.location].compact.join(" at ").then { |text| text.empty? ? "unknown" : text }
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# An ordered list preserves specific subclasses before their parent category.
|
|
59
|
+
def self.mapped_error(error)
|
|
60
|
+
mappings = {
|
|
61
|
+
Svgpng::ProfileError => RenderProfileError,
|
|
62
|
+
Svgpng::FontError => FontError,
|
|
63
|
+
Svgpng::ForbiddenReferenceError => ForbiddenExternalReferenceError,
|
|
64
|
+
Svgpng::LimitError => RenderLimitError,
|
|
65
|
+
Svgpng::InputError => MalformedSvgError,
|
|
66
|
+
Svgpng::UnsupportedPlatformError => UnsupportedPlatformError,
|
|
67
|
+
Svgpng::EncodingError => PngEncodingError,
|
|
68
|
+
Svgpng::NativeError => NativeRenderError,
|
|
69
|
+
}
|
|
70
|
+
mappings.find { |type, _target| error.is_a?(type) }&.last || NativeRenderError
|
|
71
|
+
end
|
|
72
|
+
private_class_method :mapped_error, :describe, :status_messages, :family, :scalars, :reference
|
|
73
|
+
end
|
|
74
|
+
end
|
data/lib/vectory/ps.rb
CHANGED
data/lib/vectory/svg.rb
CHANGED
|
@@ -32,6 +32,11 @@ module Vectory
|
|
|
32
32
|
self.content = content
|
|
33
33
|
end
|
|
34
34
|
|
|
35
|
+
def to_png(fonts:, fallback_fonts:, profile: {})
|
|
36
|
+
PngRenderer.render(content, profile: profile, fonts: fonts,
|
|
37
|
+
fallback_fonts: fallback_fonts)
|
|
38
|
+
end
|
|
39
|
+
|
|
35
40
|
def to_emf
|
|
36
41
|
Emf.from_content(Emfsvg.from_svg(content))
|
|
37
42
|
end
|
|
@@ -75,6 +80,7 @@ module Vectory
|
|
|
75
80
|
end
|
|
76
81
|
|
|
77
82
|
def content=(content)
|
|
83
|
+
SvgInputPolicy.validate!(content)
|
|
78
84
|
# non-root node inserts the xml tag which breaks markup when placed in
|
|
79
85
|
# another xml document
|
|
80
86
|
document = begin
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "crass"
|
|
4
|
+
require "leptris"
|
|
5
|
+
|
|
6
|
+
module Vectory
|
|
7
|
+
# Suffixes SVG class lists and CSS class selectors without normalizing CSS.
|
|
8
|
+
class SvgClassSuffixer
|
|
9
|
+
RULE_AT_RULES = %w[media supports layer container document -moz-document
|
|
10
|
+
scope starting-style keyframes -webkit-keyframes].freeze
|
|
11
|
+
SELECTOR_FUNCTIONS = %w[is where not has nth-child nth-last-child host
|
|
12
|
+
host-context slotted].freeze
|
|
13
|
+
private_constant :RULE_AT_RULES, :SELECTOR_FUNCTIONS
|
|
14
|
+
|
|
15
|
+
class << self
|
|
16
|
+
# @param content [String] SVG XML, or a host document containing SVGs
|
|
17
|
+
# @param suffix [String] a CSS identifier suffix, e.g. "_inject_0"
|
|
18
|
+
# @return [String] rewritten XML
|
|
19
|
+
def rewrite(content, suffix)
|
|
20
|
+
doc = parse(content)
|
|
21
|
+
doc.xpath("//*[local-name()='svg']").each do |svg|
|
|
22
|
+
([svg] + svg.xpath(".//*")).each do |element|
|
|
23
|
+
rewrite_element(element, suffix)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
doc.to_xml
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def parse(content)
|
|
32
|
+
doc = Leptris::XML.parse(content)
|
|
33
|
+
# Recent Leptris versions recover malformed XML by default.
|
|
34
|
+
raise Leptris::XML::ParseError, doc.errors.first.message if doc.respond_to?(:errors) && !doc.errors.empty?
|
|
35
|
+
|
|
36
|
+
doc
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def rewrite_element(element, suffix)
|
|
40
|
+
rewrite_classes(element, suffix)
|
|
41
|
+
return unless element.name == "style"
|
|
42
|
+
|
|
43
|
+
rewrite_style(element, suffix)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def rewrite_style(element, suffix)
|
|
47
|
+
# Parse the complete CSS stream, even when an XML comment or CDATA
|
|
48
|
+
# boundary splits a token. Apply insertions to the original text nodes
|
|
49
|
+
# so comments, processing instructions and CDATA remain in place.
|
|
50
|
+
nodes = element.xpath(".//text()")
|
|
51
|
+
changes = css_insertions(nodes.map(&:text).join, suffix)
|
|
52
|
+
offset = 0
|
|
53
|
+
nodes.each do |node|
|
|
54
|
+
text = node.text
|
|
55
|
+
rewrite_style_node(node, text, offset, changes)
|
|
56
|
+
offset += text.length
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def rewrite_style_node(node, text, offset, changes)
|
|
61
|
+
rewritten = text.dup
|
|
62
|
+
changes.each do |position, insertion|
|
|
63
|
+
next unless position > offset && position <= offset + text.length
|
|
64
|
+
|
|
65
|
+
rewritten.insert(position - offset, insertion)
|
|
66
|
+
end
|
|
67
|
+
node.content = rewritten unless rewritten == text
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def rewrite_classes(element, suffix)
|
|
71
|
+
# Keep attribute reads and writes on Leptris's native attribute layer.
|
|
72
|
+
attribute = element.attribute_nodes.find { |node| node.name == "class" }
|
|
73
|
+
if attribute
|
|
74
|
+
attribute.value = attribute.value.gsub(/[^\t\n\f\r ]+/) do |name|
|
|
75
|
+
name.end_with?(suffix) ? name : "#{name}#{suffix}"
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def css_insertions(css, suffix)
|
|
81
|
+
changes = {}
|
|
82
|
+
rules = Crass::Parser.new(css, preserve_comments: true).consume_rules(top_level: true)
|
|
83
|
+
rewrite_rules(rules, suffix, changes)
|
|
84
|
+
# Crass tolerates malformed CSS but stringify may repair or drop it.
|
|
85
|
+
# Token positions use CSS-normalized newlines; map them to the source.
|
|
86
|
+
offsets = source_offsets(css)
|
|
87
|
+
changes.sort.reverse.map { |position, insertion| [offsets[position], insertion] }
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def source_offsets(css)
|
|
91
|
+
offsets = [0]
|
|
92
|
+
css.scan(/\r\n|./m) { |character| offsets << (offsets.last + character.length) }
|
|
93
|
+
offsets
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def rewrite_rules(rules, suffix, changes)
|
|
97
|
+
rules.each do |rule|
|
|
98
|
+
case rule[:node]
|
|
99
|
+
when :qualified_rule
|
|
100
|
+
rewrite_selector(rule[:prelude], suffix, changes)
|
|
101
|
+
rewrite_nested_rules(rule[:block], suffix, changes)
|
|
102
|
+
when :at_rule
|
|
103
|
+
rewrite_at_rule(rule, suffix, changes)
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def rewrite_nested_rules(tokens, suffix, changes)
|
|
109
|
+
# Crass's declaration parser predates CSS nesting and discards nested
|
|
110
|
+
# rules. Walk its component values, keeping declaration values opaque.
|
|
111
|
+
parser = Crass::Parser.new(tokens)
|
|
112
|
+
prelude = []
|
|
113
|
+
while (token = parser.tokens.consume)
|
|
114
|
+
case token[:node]
|
|
115
|
+
when :semicolon
|
|
116
|
+
prelude.clear
|
|
117
|
+
when :at_keyword
|
|
118
|
+
rewrite_nested_at_rule(parser, prelude, suffix, changes)
|
|
119
|
+
when :simple_block
|
|
120
|
+
rewrite_nested_block(token, prelude, suffix, changes)
|
|
121
|
+
else
|
|
122
|
+
prelude << token
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def rewrite_nested_at_rule(parser, prelude, suffix, changes)
|
|
128
|
+
if prelude.all? { |token| trivia?(token) }
|
|
129
|
+
parser.tokens.reconsume
|
|
130
|
+
rewrite_at_rule(parser.consume_at_rule, suffix, changes)
|
|
131
|
+
prelude.clear
|
|
132
|
+
else
|
|
133
|
+
prelude << parser.tokens.current
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def rewrite_nested_block(token, prelude, suffix, changes)
|
|
138
|
+
if token[:start] == "{" && !custom_property?(prelude)
|
|
139
|
+
rewrite_selector(prelude, suffix, changes)
|
|
140
|
+
rewrite_nested_rules(token[:value], suffix, changes)
|
|
141
|
+
prelude.clear
|
|
142
|
+
else
|
|
143
|
+
prelude << token
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def trivia?(token)
|
|
148
|
+
[:comment, :whitespace].include?(token[:node])
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def custom_property?(tokens)
|
|
152
|
+
significant = tokens.reject { |token| trivia?(token) }
|
|
153
|
+
significant.first&.dig(:node) == :ident && significant.first[:value].start_with?("--") &&
|
|
154
|
+
significant[1]&.dig(:node) == :colon
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def rewrite_at_rule(rule, suffix, changes)
|
|
158
|
+
return unless rule[:block] && RULE_AT_RULES.include?(rule[:name].downcase)
|
|
159
|
+
|
|
160
|
+
rewrite_scope(rule[:prelude], suffix, changes) if rule[:name].downcase == "scope"
|
|
161
|
+
rewrite_nested_rules(rule[:block], suffix, changes)
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def rewrite_scope(tokens, suffix, changes)
|
|
165
|
+
tokens.each do |token|
|
|
166
|
+
next unless token[:node] == :simple_block && token[:start] == "("
|
|
167
|
+
|
|
168
|
+
rewrite_selector(token[:value], suffix, changes)
|
|
169
|
+
end
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
def rewrite_selector(tokens, suffix, changes)
|
|
173
|
+
previous = nil
|
|
174
|
+
tokens.each do |token|
|
|
175
|
+
next if token[:node] == :comment
|
|
176
|
+
|
|
177
|
+
if class_identifier?(token, previous)
|
|
178
|
+
suffix_identifier(token, suffix, changes)
|
|
179
|
+
elsif selector_function?(token)
|
|
180
|
+
rewrite_selector(token[:value], suffix, changes)
|
|
181
|
+
end
|
|
182
|
+
previous = token
|
|
183
|
+
end
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
def class_identifier?(token, previous)
|
|
187
|
+
token[:node] == :ident && previous&.dig(:node) == :delim && previous[:value] == "."
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def selector_function?(token)
|
|
191
|
+
token[:node] == :function && SELECTOR_FUNCTIONS.include?(token[:name].downcase)
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
def suffix_identifier(token, suffix, changes)
|
|
195
|
+
return if token[:value].end_with?(suffix)
|
|
196
|
+
|
|
197
|
+
# A trailing short hex escape can absorb the first suffix character.
|
|
198
|
+
# Add its optional terminator only when concatenation changes meaning.
|
|
199
|
+
combined = Crass::Tokenizer.tokenize(token[:raw] + suffix).first
|
|
200
|
+
insertion = combined[:value] == token[:value] + suffix ? suffix : " #{suffix}"
|
|
201
|
+
changes[token[:pos] + token[:raw].length] = insertion
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
end
|
|
205
|
+
end
|