vexyl 1.4.0

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.
@@ -0,0 +1,81 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Naomi Persephone Amethyst <naomi@amethyst.name>
3
+
4
+ module Vexyl
5
+ # An element of a rendered SVG document, for code that wants to change or embed one.
6
+ #
7
+ # +name+ is its name, with any prefix, as it's written; +attrs+ its attributes, in order;
8
+ # +text+ what's inside a +title+ or +desc+, the only elements that hold any, or the empty
9
+ # string; +children+ its child elements, in order.
10
+ class Element
11
+ # An attribute of an element, as it's written in the document.
12
+ Attribute = Struct.new(:name, :value) do
13
+ def to_h
14
+ { "name" => name, "value" => value }
15
+ end
16
+ end
17
+
18
+ attr_reader :name, :attrs, :text, :children
19
+
20
+ def initialize(name, attrs, text, children)
21
+ @name = name.frozen? ? name : name.dup.freeze
22
+ @attrs = attrs.map { |a| a.frozen? ? a : a.dup.freeze }.freeze
23
+ @text = (text.nil? ? "" : text).dup.freeze
24
+ @children = children.dup.freeze
25
+ freeze
26
+ end
27
+
28
+ # The value of an attribute, or nil if it has none of that name.
29
+ def attr(name)
30
+ @attrs.each do |a|
31
+ return a.value if a.name == name
32
+ end
33
+ nil
34
+ end
35
+
36
+ # Writes the element out as XML, which draws the same as the flag's SVG.
37
+ def to_s
38
+ b = +""
39
+ write(b)
40
+ b
41
+ end
42
+
43
+ # The element as the CLI's +tree+ command writes it: name, attrs, children, then text only
44
+ # when there is some.
45
+ def to_h
46
+ h = {
47
+ "name" => @name,
48
+ "attrs" => @attrs.map(&:to_h),
49
+ "children" => @children.map(&:to_h)
50
+ }
51
+ h["text"] = @text unless @text.empty?
52
+ h
53
+ end
54
+
55
+ def ==(other)
56
+ other.is_a?(Element) && other.name == @name && other.attrs == @attrs && other.text == @text &&
57
+ other.children == @children
58
+ end
59
+ alias eql? ==
60
+
61
+ def hash
62
+ [@name, @attrs, @text, @children].hash
63
+ end
64
+
65
+ protected
66
+
67
+ def write(b)
68
+ b << "<" << @name
69
+ @attrs.each do |a|
70
+ b << " " << a.name << "=\"" << Xml.escape(a.value) << "\""
71
+ end
72
+ if @text.empty? && @children.empty?
73
+ b << "/>"
74
+ return
75
+ end
76
+ b << ">" << Xml.escape(@text)
77
+ @children.each { |c| c.write(b) }
78
+ b << "</" << @name << ">"
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,47 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Naomi Persephone Amethyst <naomi@amethyst.name>
3
+
4
+ module Vexyl
5
+ # A document, an option or a share link that Vexyl refuses.
6
+ class Error < StandardError; end
7
+
8
+ # One thing wrong with a document, as section 2 of the SDK describes it. +line+ and +column+
9
+ # are where it is, from 1, or 0 if it has no one place; a line ends at LF, once line endings are
10
+ # normalized, and a column counts code points. +node+ is the name of the KDL node it's about, or
11
+ # nil. +message+ is for a person to read, and programs mustn't depend on its wording.
12
+ Problem = Struct.new(:line, :column, :node, :message) do
13
+ # Whether it has a place in the document.
14
+ def line?
15
+ line.positive?
16
+ end
17
+
18
+ def to_s
19
+ s = +""
20
+ s << "#{line}:#{column}: " if line.positive?
21
+ s << "#{node}: " if node && !node.empty?
22
+ s << message
23
+ end
24
+
25
+ def to_h
26
+ h = {}
27
+ if line.positive?
28
+ h["line"] = line
29
+ h["column"] = column
30
+ end
31
+ h["node"] = node if node && !node.empty?
32
+ h["message"] = message
33
+ h
34
+ end
35
+ end
36
+
37
+ # A document that isn't valid, with every problem found in it, in no order that programs
38
+ # should depend on.
39
+ class ProblemsError < Error
40
+ attr_reader :problems
41
+
42
+ def initialize(problems)
43
+ @problems = problems.dup.freeze
44
+ super(@problems.map(&:to_s).join("\n"))
45
+ end
46
+ end
47
+ end
data/lib/vexyl/flag.rb ADDED
@@ -0,0 +1,66 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Naomi Persephone Amethyst <naomi@amethyst.name>
3
+
4
+ module Vexyl
5
+ # A parsed and valid Vexyl document. It never changes, rendering included, so one flag can be
6
+ # rendered with many options, from many threads at once.
7
+ class Flag
8
+ def initialize(doc)
9
+ @doc = doc
10
+ freeze
11
+ end
12
+
13
+ # The flag's name, from its +meta+.
14
+ def name
15
+ @doc.meta.name
16
+ end
17
+
18
+ # The flag's proportion, which is also its grid: its height.
19
+ def hoist
20
+ @doc.hoist
21
+ end
22
+
23
+ # The flag's proportion, which is also its grid: its width.
24
+ def fly
25
+ @doc.fly
26
+ end
27
+
28
+ # The names of the flag's variants, in document order.
29
+ def variants
30
+ @doc.variants.keys.freeze
31
+ end
32
+
33
+ # The names of the flag's folds, in document order.
34
+ def folds
35
+ @doc.folds.keys.freeze
36
+ end
37
+
38
+ # The flag as plain data, in the canonical form of section 4 of the SDK: hashes with string
39
+ # keys, arrays, strings, numbers and booleans, all frozen.
40
+ def model
41
+ Canonical.model(@doc)
42
+ end
43
+
44
+ # The canonical model as JSON, as the conformance suite compares it.
45
+ def model_json
46
+ Json.write(model)
47
+ end
48
+
49
+ # Renders the flag as an SVG document. Takes a RenderOptions, a hash of options, or the
50
+ # options as keywords, such as <tt>flag.svg(height: 300, variant: "vertical")</tt>. Raises
51
+ # Vexyl::Error if an option can't be used, or the flag can't be drawn as asked.
52
+ def svg(options = nil, **keywords)
53
+ Render.svg(@doc, RenderOptions.from(options, **keywords))
54
+ end
55
+
56
+ # Renders the flag as a tree of Vexyl::Element, which writes out as a document that draws
57
+ # the same as #svg. Only a +title+ or +desc+ holds any text.
58
+ def svg_tree(options = nil, **keywords)
59
+ Render.tree(svg(options, **keywords))
60
+ end
61
+
62
+ def inspect
63
+ "#<Vexyl::Flag #{name.inspect}>"
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,253 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Naomi Persephone Amethyst <naomi@amethyst.name>
3
+
4
+ module Vexyl
5
+ # Points, polygons and folds, which reading a document checks and rendering draws.
6
+ module Geometry
7
+ # Degrees to radians, as one constant, so that every conversion rounds the same way.
8
+ DEGREES_TO_RADIANS = 0.017453292519943295
9
+
10
+ # An immutable point or direction.
11
+ class Vec
12
+ attr_reader :x, :y
13
+
14
+ def initialize(x, y)
15
+ @x = x.to_f
16
+ @y = y.to_f
17
+ end
18
+
19
+ def add(b)
20
+ Vec.new(@x + b.x, @y + b.y)
21
+ end
22
+
23
+ def sub(b)
24
+ Vec.new(@x - b.x, @y - b.y)
25
+ end
26
+
27
+ def mul(k)
28
+ Vec.new(@x * k, @y * k)
29
+ end
30
+
31
+ def dot(b)
32
+ @x * b.x + @y * b.y
33
+ end
34
+
35
+ # Turns clockwise as seen by the viewer, since y points down.
36
+ def rotate(degrees)
37
+ r = degrees * DEGREES_TO_RADIANS
38
+ s = Math.sin(r)
39
+ c = Math.cos(r)
40
+ Vec.new(@x * c - @y * s, @x * s + @y * c)
41
+ end
42
+
43
+ def inspect
44
+ "#<Vec #{@x}, #{@y}>"
45
+ end
46
+ alias to_s inspect
47
+ end
48
+
49
+ module_function
50
+
51
+ def rect_poly(x0, y0, x1, y1)
52
+ [Vec.new(x0, y0), Vec.new(x1, y0), Vec.new(x1, y1), Vec.new(x0, y1)]
53
+ end
54
+
55
+ # An outline's corners on a flag w wide and h high, or nil if it's curved.
56
+ def outline_points(o, w, h)
57
+ w = w.to_f
58
+ h = h.to_f
59
+ case o.kind
60
+ when "polygon"
61
+ o.vertices.map { |p| Vec.new(p.fly, p.hoist) }
62
+ when "swallowtail"
63
+ [Vec.new(0.0, 0.0), Vec.new(w, o.taper), Vec.new(w - o.depth, h / 2), Vec.new(w, h - o.taper),
64
+ Vec.new(0.0, h)]
65
+ when "tongued"
66
+ a = (h - o.tongue) / 2
67
+ [Vec.new(0.0, 0.0), Vec.new(w, 0.0), Vec.new(w - o.depth, a), Vec.new(w, h / 2),
68
+ Vec.new(w - o.depth, h - a), Vec.new(w, h), Vec.new(0.0, h)]
69
+ when "pennant"
70
+ a = (h - o.tip) / 2
71
+ if o.tip == 0
72
+ return [Vec.new(0.0, 0.0), Vec.new(w, h / 2), Vec.new(0.0, h)]
73
+ end
74
+ [Vec.new(0.0, 0.0), Vec.new(w, a), Vec.new(w, h - a), Vec.new(0.0, h)]
75
+ end
76
+ end
77
+
78
+ # The flag's shape before any outside border, or nil for a curved outline.
79
+ def boundary(f)
80
+ return rect_poly(0.0, 0.0, f.fly, f.hoist) if f.outline.nil?
81
+ outline_points(f.outline, f.fly, f.hoist)
82
+ end
83
+
84
+ # Moves a polygon's edges outward by a distance, keeping its angles mitered. It fails on
85
+ # polygons with no area, repeated points or edges that fold back on themselves, where outward
86
+ # has no meaning.
87
+ def offset_polygon(poly, distance)
88
+ area = 0.0
89
+ n = poly.size
90
+ n.times do |i|
91
+ p = poly[i]
92
+ q = poly[(i + 1) % n]
93
+ area += p.x * q.y - q.x * p.y
94
+ end
95
+ raise Vexyl::Error, "shape has no area, so it can't have an outside border" if area == 0
96
+ side = area < 0 ? -1.0 : 1.0
97
+ out = []
98
+ n.times do |i|
99
+ p = poly[i]
100
+ n1 = normal(poly[(i + n - 1) % n], p, side)
101
+ n2 = normal(p, poly[(i + 1) % n], side)
102
+ if n1.nil? || n2.nil?
103
+ raise Vexyl::Error, "shape repeats a point, so it can't have an outside border"
104
+ end
105
+ turn = 1 + n1.dot(n2)
106
+ raise Vexyl::Error, "shape folds back on itself, so it can't have an outside border" if turn < 1e-9
107
+ out << p.add(n1.add(n2).mul(distance / turn))
108
+ end
109
+ out
110
+ end
111
+
112
+ def normal(a, b, side)
113
+ l = Math.hypot(b.x - a.x, b.y - a.y)
114
+ return nil if l == 0
115
+ Vec.new(side * (b.y - a.y) / l, -side * (b.x - a.x) / l)
116
+ end
117
+ private_class_method :normal
118
+
119
+ def poly_area(poly)
120
+ sum = 0.0
121
+ n = poly.size
122
+ n.times do |i|
123
+ p = poly[i]
124
+ q = poly[(i + 1) % n]
125
+ sum += p.x * q.y - q.x * p.y
126
+ end
127
+ sum.abs / 2
128
+ end
129
+
130
+ # Maps (x, y) to (a*x + c*y + e, b*x + d*y + f), as SVG writes it.
131
+ class Matrix
132
+ attr_reader :a, :b, :c, :d, :e, :f
133
+
134
+ def initialize(a, b, c, d, e, f)
135
+ @a = a.to_f
136
+ @b = b.to_f
137
+ @c = c.to_f
138
+ @d = d.to_f
139
+ @e = e.to_f
140
+ @f = f.to_f
141
+ end
142
+
143
+ IDENTITY = new(1, 0, 0, 1, 0, 0)
144
+
145
+ def apply(p)
146
+ Vec.new(@a * p.x + @c * p.y + @e, @b * p.x + @d * p.y + @f)
147
+ end
148
+
149
+ # The transform that applies this, followed by n.
150
+ def followed_by(n)
151
+ Matrix.new(
152
+ n.a * @a + n.c * @b, n.b * @a + n.d * @b,
153
+ n.a * @c + n.c * @d, n.b * @c + n.d * @d,
154
+ n.a * @e + n.c * @f + n.e, n.b * @e + n.d * @f + n.f
155
+ )
156
+ end
157
+
158
+ # Reflects across the line through p and q.
159
+ def self.reflection(p, q)
160
+ d = q.sub(p)
161
+ l = d.dot(d)
162
+ cos = (d.x * d.x - d.y * d.y) / l
163
+ sin = 2 * d.x * d.y / l
164
+ new(cos, sin, sin, -cos, p.x - cos * p.x - sin * p.y, p.y - sin * p.x + cos * p.y)
165
+ end
166
+ end
167
+
168
+ # A flat piece of the folded flag. Its polygon is where it now lies, and its transform takes
169
+ # the flag's coordinates there. Facets are kept from back to front, and flipped ones show the
170
+ # flag's other side.
171
+ class Facet
172
+ attr_reader :poly, :place, :flipped
173
+
174
+ def initialize(poly, place, flipped)
175
+ @poly = poly
176
+ @place = place
177
+ @flipped = flipped
178
+ end
179
+
180
+ alias flipped? flipped
181
+ end
182
+
183
+ # Keeps the part of a polygon on one side of a line.
184
+ def half_plane(poly, a, b, side)
185
+ d = b.sub(a)
186
+ out = []
187
+ n = poly.size
188
+ n.times do |i|
189
+ cur = poly[i]
190
+ prev = poly[(i + n - 1) % n]
191
+ vc = side * (d.x * (cur.y - a.y) - d.y * (cur.x - a.x))
192
+ vp = side * (d.x * (prev.y - a.y) - d.y * (prev.x - a.x))
193
+ out << prev.add(cur.sub(prev).mul(vp / (vp - vc))) if (vc >= 0) != (vp >= 0)
194
+ out << cur if vc >= 0
195
+ end
196
+ out
197
+ end
198
+
199
+ # Folds a flat shape through a number of steps, or all of them if steps is 0.
200
+ def fold_facets(shape, fold, steps)
201
+ stack = [Facet.new(shape, Matrix::IDENTITY, false)]
202
+ limit = poly_area(shape) * 1e-9
203
+ fold.steps.each_with_index do |step, i|
204
+ break if steps > 0 && i == steps
205
+ a = Vec.new(step.a.fly, step.a.hoist)
206
+ b = Vec.new(step.b.fly, step.b.hoist)
207
+ moving = Vec.new(step.moving.fly, step.moving.hoist)
208
+ d = b.sub(a)
209
+ side = d.x * (moving.y - a.y) - d.y * (moving.x - a.x)
210
+ if side == 0 || d.dot(d) == 0
211
+ raise Vexyl::Error, format("fold step %d: its point to move is on its crease", i + 1)
212
+ end
213
+ side = side < 0 ? -1.0 : 1.0
214
+ mirror = Matrix.reflection(a, b)
215
+ kept = []
216
+ moved = []
217
+ stack.each do |f|
218
+ part = half_plane(f.poly, a, b, -side)
219
+ kept << Facet.new(part, f.place, f.flipped) if poly_area(part) > limit
220
+ part = half_plane(f.poly, a, b, side)
221
+ if poly_area(part) > limit
222
+ reflected = part.map { |p| mirror.apply(p) }
223
+ moved << Facet.new(reflected, f.place.followed_by(mirror), !f.flipped)
224
+ end
225
+ end
226
+ raise Vexyl::Error, format("fold step %d: nothing is on the side it moves", i + 1) if moved.empty?
227
+ if kept.empty?
228
+ raise Vexyl::Error, format("fold step %d: nothing is left on the other side of its crease", i + 1)
229
+ end
230
+ if kept.size + moved.size > Limits::MAX_FACETS
231
+ raise Vexyl::Error, format("fold step %d: makes more than %d pieces", i + 1, Limits::MAX_FACETS)
232
+ end
233
+ # Whichever way it goes, the moving stack lands in reverse order.
234
+ moved.reverse!
235
+ stack = case step.kind
236
+ when "over" then kept.concat(moved)
237
+ when "under" then moved.concat(kept)
238
+ else kept # A tuck goes inside the fold, out of sight.
239
+ end
240
+ end
241
+ stack
242
+ end
243
+
244
+ # The flat shape a flag folds as, including an outside border.
245
+ def fold_shape(f)
246
+ shape = boundary(f)
247
+ # A curved outline folds as its rectangle, with the flag's own clip inside.
248
+ shape = rect_poly(0.0, 0.0, f.fly, f.hoist) if shape.nil?
249
+ return offset_polygon(shape, f.border.width) if !f.border.nil? && f.border_outside
250
+ shape
251
+ end
252
+ end
253
+ end
data/lib/vexyl/json.rb ADDED
@@ -0,0 +1,75 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Naomi Persephone Amethyst <naomi@amethyst.name>
3
+
4
+ module Vexyl
5
+ # Writes plain data as JSON: hashes, arrays, strings, numbers, booleans and nil. It's its own
6
+ # so that numbers are written the same way everywhere, and the command starts quickly.
7
+ module Json
8
+ module_function
9
+
10
+ def write(value, indent: true)
11
+ out = +""
12
+ put(out, value, indent ? 0 : -1)
13
+ out
14
+ end
15
+
16
+ # A number as its shortest decimal, without an exponent if it's of a usual size.
17
+ def number(v)
18
+ return v.to_s if v.is_a?(Integer)
19
+ raise ArgumentError, "JSON has no #{v}" if v.nan? || v.infinite?
20
+ return v.to_i.to_s if v == v.round && v.abs < 1e15
21
+ text = v.to_s
22
+ return text unless text.include?("e")
23
+ mantissa, exponent = text.split("e")
24
+ mantissa = mantissa.delete_suffix(".0")
25
+ "#{mantissa}e#{exponent.to_i}"
26
+ end
27
+
28
+ def newline(out, depth)
29
+ return if depth.negative?
30
+ out << "\n" << (" " * depth)
31
+ end
32
+
33
+ def put(out, value, depth)
34
+ inner = depth >= 0 ? depth + 1 : -1
35
+ case value
36
+ when nil then out << "null"
37
+ when String then string(out, value)
38
+ when true, false then out << value.to_s
39
+ when Numeric then out << number(value)
40
+ when Hash
41
+ return out << "{}" if value.empty?
42
+ out << "{"
43
+ value.each_with_index do |(k, v), i|
44
+ out << "," if i.positive?
45
+ newline(out, inner)
46
+ string(out, k.to_s)
47
+ out << (depth >= 0 ? ": " : ":")
48
+ put(out, v, inner)
49
+ end
50
+ newline(out, depth)
51
+ out << "}"
52
+ when Array
53
+ return out << "[]" if value.empty?
54
+ out << "["
55
+ value.each_with_index do |v, i|
56
+ out << "," if i.positive?
57
+ newline(out, inner)
58
+ put(out, v, inner)
59
+ end
60
+ newline(out, depth)
61
+ out << "]"
62
+ else
63
+ raise ArgumentError, "can't write #{value.class} as JSON"
64
+ end
65
+ end
66
+
67
+ ESCAPES = { '"' => '\\"', "\\" => "\\\\", "\n" => "\\n", "\r" => "\\r", "\t" => "\\t" }.freeze
68
+
69
+ def string(out, s)
70
+ out << '"'
71
+ out << s.gsub(/["\\\x00-\x1f

]/) { |c| ESCAPES[c] || format("\\u%04x", c.ord) }
72
+ out << '"'
73
+ end
74
+ end
75
+ end