kouyou 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e9b64194573eeab63038eae58d45eac9a4dc849b9ebfd69b1749f8f03fc516f6
4
+ data.tar.gz: 43201fb1bb2f861db02f3d2c7d3594ecacd43fc003181349369b770d72103059
5
+ SHA512:
6
+ metadata.gz: 620170a0ea995f8ed91ad6de2a159a03966da089ed37799510bdf1434002a51ec3be85565fe7d115694cad89481fd686c695716544e1c241571a6c1722b6dd65
7
+ data.tar.gz: ce4cd71dc6adeda6e00f9b68d21cc3b3a1283818dc7188aa8475ef21165818062a07f5a89b9c62d5b3af9a6a9701a39bed289cdc59965ce0f10bea6b9c52c088
data/.yardopts ADDED
@@ -0,0 +1,5 @@
1
+ --markup markdown
2
+ lib/**/*.rb
3
+ -
4
+ CHANGELOG.md
5
+ LICENSE.txt
data/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 - 2026-12-03
4
+
5
+ Initial release: elements and components, component aliases, attribute
6
+ merging for wiring a child, and an HTML renderer.
@@ -0,0 +1,10 @@
1
+ # Code of Conduct
2
+
3
+ "kouyou" follows [The Ruby Community Conduct Guideline](https://www.ruby-lang.org/en/conduct) in all "collaborative space", which is defined as community communications channels (such as mailing lists, submitted patches, commit comments, etc.):
4
+
5
+ * Participants will be tolerant of opposing views.
6
+ * Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
7
+ * When interpreting the words and actions of others, participants should always assume good intentions.
8
+ * Behaviour which can be reasonably considered harassment will not be tolerated.
9
+
10
+ If you have any concerns about behaviour within this project, please contact us at [kouyou@micahfrost.com](mailto:kouyou@micahfrost.com).
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Micah Frost
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # Kouyou
2
+
3
+ Kouyou (紅葉, "autumn leaves") lets you write HTML views as plain Ruby
4
+ objects. A component's `children` is an expression that builds a tree of
5
+ elements and components. A renderer turns that tree into HTML.
6
+
7
+ ```ruby
8
+ class Card
9
+ include Kouyou::Component
10
+
11
+ def initialize(title:) = @title = title
12
+
13
+ def children
14
+ article(class: "card")[h2[@title], content]
15
+ end
16
+ end
17
+
18
+ Card.new(title: "Autumn")["Leaves <fall> & turn red"].to_html
19
+ # => <article class="card"><h2>Autumn</h2>Leaves &lt;fall&gt; &amp; turn red</article>
20
+ ```
21
+
22
+ Check out the [documentation](https://rubydoc.info/gems/kouyou) or see more [examples](examples/) here.
23
+
24
+ ## Object Oriented Components
25
+
26
+ Most view libraries are procedural, building a view buffer as they go. Building
27
+ a tree first allows:
28
+
29
+ - **A parent can send messages a child it was given** before anything is written.
30
+ A menu can add `id`, `aria-*` and `data-*` attributes to the trigger button
31
+ its caller passed in, and the button knows nothing about menus.
32
+ - **Renderers are separate from templates.** Nodes know nothing about HTML
33
+ output, so other renderers need no change to them.
34
+ - **Trees can be inspected and compared**: elements have structural `==`, as
35
+ the DOM's `isEqualNode`, and every element is an instance of its own class
36
+ (`Kouyou::HTML::Div`).
37
+
38
+ ## Contributing
39
+
40
+ Everyone interacting in the Kouyou project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).
41
+
42
+ ```bash
43
+ bin/setup
44
+ bundle exec rspec
45
+ bundle exec rubocop
46
+ bundle exec yard stats --list-undoc
47
+ ```
48
+
49
+ ## License
50
+
51
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,177 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb/escape"
4
+
5
+ module Kouyou
6
+ # One attribute, parsed from a name and a value when it's given, so a
7
+ # mistake raises in the template that made it:
8
+ #
9
+ # - The name is a String or Symbol, written as given: `"aria-label"`.
10
+ # - `true` and `false` become the attribute's own keywords where it has a
11
+ # pair: `draggable: false` is `draggable="false"`, `translate: true` is
12
+ # `translate="yes"`, and every `aria-*` takes "true" and "false". Other
13
+ # attributes are boolean, as in HTML: `true` is a bare attribute and
14
+ # `false` leaves it out. `nil` always leaves it out.
15
+ # - Arrays are token lists, joined with spaces; other values become text.
16
+ #
17
+ # The value is escaped like text when written, so the browser reads back
18
+ # exactly the Ruby value. That makes it safe as HTML, but not as script:
19
+ # the browser runs an event handler, a `srcdoc` document or a
20
+ # `javascript:` URL after reading the value back. So event handlers and
21
+ # `srcdoc` raise, and `javascript:` URLs are left out, unless the value is
22
+ # trusted: a {SafeString}, or a String whose `html_safe?` is true.
23
+ #
24
+ # @example
25
+ # Kouyou::Attribute.new(:draggable, false).to_html # => ' draggable="false"'
26
+ class Attribute
27
+ UNSAFE_NAME = %r{[<>&"'/=\s\x00]}
28
+ # SVG animation elements write `to`, `from`, `by` and `values` to the
29
+ # attribute their `attributeName` names, which can be `href`. `data` is
30
+ # the URL an <object> loads.
31
+ URLS = %w[href src action formaction lowsrc dynsrc background ping data to from by values].freeze
32
+ # Enumerated attributes whose keywords are a true/false pair. Leaving
33
+ # one out doesn't mean false: a missing draggable is "auto", a missing
34
+ # spellcheck inherits.
35
+ TRUE_FALSE = %w[true false].freeze
36
+ KEYWORDS = {
37
+ "contenteditable" => TRUE_FALSE,
38
+ "draggable" => TRUE_FALSE,
39
+ "spellcheck" => TRUE_FALSE,
40
+ "writingsuggestions" => TRUE_FALSE,
41
+ "translate" => %w[yes no].freeze,
42
+ "autocorrect" => %w[on off].freeze,
43
+ "autocomplete" => %w[on off].freeze
44
+ }.freeze
45
+ private_constant :UNSAFE_NAME, :URLS, :TRUE_FALSE, :KEYWORDS
46
+
47
+ # @return [String]
48
+ attr_reader :name
49
+
50
+ # @return [String, true, nil] the text, true for a bare attribute, or nil
51
+ # when the attribute is left out
52
+ attr_reader :value
53
+
54
+ # @param name [String, Symbol]
55
+ # @param value [Object]
56
+ # @raise [Kouyou::ArgumentError] for a name that isn't a String or
57
+ # Symbol, or that contains characters that would break the markup; for
58
+ # a Hash value; and for an untrusted value that would run as script
59
+ def initialize(name, value)
60
+ @name = parse_name(name)
61
+ @trusted = trusted_value?(value)
62
+ refuse_untrusted_script(value)
63
+ @value = parse_value(value)
64
+ freeze
65
+ end
66
+
67
+ # Equality ignores trust: trusted or not, the attribute renders the same.
68
+ #
69
+ # @return [Boolean] whether the value was trusted: a {SafeString}, or a
70
+ # String whose `html_safe?` is true
71
+ def trusted? = @trusted
72
+
73
+ # Matched more strictly than browsers, which only ignore ASCII case:
74
+ # anything but letters and `-` is dropped first, so `on_click` counts.
75
+ #
76
+ # @return [Boolean] whether the browser runs the value as script or
77
+ # markup: an event handler (`on*`) or `srcdoc`
78
+ def script?
79
+ key = name.downcase.delete("^a-z-")
80
+ key == "srcdoc" || (key.start_with?("on") && key.length > 2 && !key.include?("-"))
81
+ end
82
+
83
+ # Matched ignoring ASCII case and any namespace prefix: in SVG parsed as
84
+ # XML, any prefix can be bound to XLink, so `x:href` is a URL too.
85
+ #
86
+ # @return [Boolean] whether the value is a URL the browser loads or
87
+ # navigates to
88
+ def url? = URLS.include?(local_name)
89
+
90
+ # @return [Boolean] whether the attribute is left out: given nil, or
91
+ # false as a boolean attribute
92
+ def omitted? = value.nil?
93
+
94
+ # @return [String] such as ` id="x"` or ` hidden`; empty when omitted
95
+ def to_html
96
+ case value
97
+ when nil then ""
98
+ when true then " #{name}"
99
+ else %( #{name}="#{ERB::Escape.html_escape(value)}")
100
+ end
101
+ end
102
+
103
+ # Attributes are equal when they have the same name and value.
104
+ #
105
+ # @param other [Object]
106
+ # @return [Boolean]
107
+ def ==(other) = other.is_a?(Attribute) && name == other.name && value == other.value
108
+ alias eql? ==
109
+
110
+ # @return [Integer]
111
+ def hash = [Attribute, name, value].hash
112
+
113
+ # @return [String] such as `#<Kouyou::Attribute draggable="false">`
114
+ def inspect = "#<#{self.class.name}#{to_html}>"
115
+
116
+ private
117
+
118
+ def parse_name(name)
119
+ name = case name
120
+ when String then name
121
+ when Symbol then name.name
122
+ else raise Kouyou::ArgumentError, "attribute names must be Strings or Symbols, got #{name.inspect}"
123
+ end
124
+ raise Kouyou::ArgumentError, "unsafe attribute name: #{name.inspect}" if UNSAFE_NAME.match?(name)
125
+
126
+ name
127
+ end
128
+
129
+ def trusted_value?(value)
130
+ value.is_a?(SafeString) || (value.is_a?(String) && value.respond_to?(:html_safe?) && value.html_safe?)
131
+ end
132
+
133
+ def refuse_untrusted_script(value)
134
+ return if value.nil? || trusted? || !script?
135
+
136
+ raise Kouyou::ArgumentError, "unsafe attribute name: #{name.inspect} runs its value as script, " \
137
+ "so the value must be a Kouyou::SafeString"
138
+ end
139
+
140
+ def parse_value(value)
141
+ case value
142
+ when nil then nil
143
+ when true, false then keyword(value)
144
+ when Hash
145
+ raise Kouyou::ArgumentError,
146
+ "#{name} can't take a Hash: write each attribute's name in full, such as \"data-id\""
147
+ else
148
+ text = text(value)
149
+ text unless url? && !trusted? && javascript_url_in?(text)
150
+ end
151
+ end
152
+
153
+ def text(value) = value.is_a?(Array) ? value.flatten.select(&:itself).join(" ") : value.to_s
154
+
155
+ def local_name = name.downcase(:ascii).sub(/\A.*:/m, "")
156
+
157
+ # A `values` list is `;`-separated, and any entry can be used.
158
+ def javascript_url_in?(text)
159
+ urls = local_name == "values" ? text.split(";") : [text]
160
+ urls.any? { |url| javascript_url?(url) }
161
+ end
162
+
163
+ # As the URL parser reads a scheme: leading control characters and
164
+ # spaces stripped, tabs and newlines removed anywhere, ASCII case ignored.
165
+ def javascript_url?(url)
166
+ url.sub(/\A[\x00-\x20]+/, "").delete("\t\n\r").downcase(:ascii).start_with?("javascript:")
167
+ end
168
+
169
+ def keyword(value)
170
+ key = name.downcase(:ascii)
171
+ pair = KEYWORDS[key] || (TRUE_FALSE if key.start_with?("aria-"))
172
+ return value || nil unless pair
173
+
174
+ value ? pair.first : pair.last
175
+ end
176
+ end
177
+ end
@@ -0,0 +1,151 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kouyou
4
+ # An element's attributes: each name and value is parsed into an
5
+ # {Attribute} when they're given, and those left out (`nil`, or `false` on
6
+ # a boolean attribute) are dropped. Frozen; changed by replacement.
7
+ #
8
+ # @example
9
+ # Kouyou::Attributes.new(class: ["card", "open"], "data-id": 1).to_html
10
+ # # => ' class="card open" data-id="1"'
11
+ class Attributes
12
+ include Enumerable
13
+
14
+ # Attributes whose values are space-separated lists, which {#merge}
15
+ # combines: HTML's token lists, ARIA's lists of IDs, and Stimulus's
16
+ # controllers and actions. `for` isn't one: on <label> it's a single ID.
17
+ TOKEN_LISTS = %w[
18
+ class rel sandbox headers accesskey ping itemprop itemref itemtype blocking part
19
+ aria-controls aria-describedby aria-labelledby aria-owns aria-flowto
20
+ data-controller data-action
21
+ ].freeze
22
+ private_constant :TOKEN_LISTS
23
+
24
+ # @param attributes [Hash, Attributes] an Attributes as it is; a Hash parsed
25
+ # @return [Attributes]
26
+ def self.from(attributes) = attributes.is_a?(Attributes) ? attributes : new(attributes)
27
+
28
+ # @param attributes [Hash{String, Symbol => Object}] values are parsed
29
+ # into {Attribute}s; an Attribute is kept as it is
30
+ # @raise [Kouyou::ArgumentError] for anything but a Hash, and for an
31
+ # attribute {Attribute} refuses
32
+ def initialize(attributes)
33
+ raise Kouyou::ArgumentError, "attributes must be a Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
34
+
35
+ @attributes = {}
36
+ attributes.each do |name, value|
37
+ attribute = value.is_a?(Attribute) ? value : Attribute.new(name, value)
38
+ @attributes[attribute.name] = attribute unless attribute.omitted?
39
+ end
40
+ @attributes.freeze
41
+ freeze
42
+ end
43
+
44
+ # Adds attributes to these, for a parent wiring a child it was given.
45
+ # Merging the same attributes again changes nothing, which matters
46
+ # because templates run on every render.
47
+ #
48
+ # Where both set a name, token lists (`class`, `rel`, `aria-describedby`,
49
+ # `data-action`, ...) are combined without repeats, and anything else is
50
+ # replaced. A block overrides that, as with Hash#merge: it's given the
51
+ # name, both values and the value Kouyou would choose, and its result is
52
+ # parsed as the attribute's value (`nil` removes it).
53
+ #
54
+ # @example
55
+ # Kouyou::Attributes.new(class: "btn", id: "a").merge(class: "wide", id: "b")
56
+ # # => #<Kouyou::Attributes class="btn wide" id="b">
57
+ #
58
+ # @example Overriding the choice
59
+ # attributes.merge(other) { |name, old, new, kouyou| name == "data-action" ? new : kouyou }
60
+ #
61
+ # @param other [Hash, Attributes] in a Hash, `nil` or `false` on a
62
+ # boolean attribute removes it
63
+ # @yieldparam name [String]
64
+ # @yieldparam old [String, true] this value
65
+ # @yieldparam new [String, true] the other's value
66
+ # @yieldparam kouyou [String, true] the value without a block
67
+ # @yieldreturn [Object] the value to parse
68
+ # @return [Attributes] new attributes; these are unchanged
69
+ def merge(other, &)
70
+ merged = @attributes.dup
71
+ each_given(other) do |name, attribute|
72
+ next merged.delete(name) if attribute.omitted?
73
+
74
+ merged[name] = (old = merged[name]) ? choose(old, attribute, &) : attribute
75
+ end
76
+ Attributes.new(merged)
77
+ end
78
+
79
+ # @param name [String, Symbol]
80
+ # @return [Attribute, nil]
81
+ def [](name) = @attributes[name.to_s]
82
+
83
+ # @yieldparam attribute [Attribute] each, in the order given
84
+ # @return [Enumerator] without a block
85
+ def each(&)
86
+ return to_enum(:each) unless block_given?
87
+
88
+ @attributes.each_value(&)
89
+ self
90
+ end
91
+
92
+ # @return [Boolean] whether there are no attributes to write
93
+ def empty? = @attributes.empty?
94
+
95
+ # @return [Hash{String => String, true}] names to their values
96
+ def to_h = @attributes.transform_values(&:value)
97
+
98
+ # Attributes are equal when they have the same attributes, in any order,
99
+ # as the DOM's `isEqualNode` compares them. They're frozen, so they're
100
+ # safe as Hash keys.
101
+ #
102
+ # @param other [Object]
103
+ # @return [Boolean]
104
+ def ==(other) = other.is_a?(Attributes) && by_name == other.by_name
105
+ alias eql? ==
106
+
107
+ # @return [Integer]
108
+ def hash = [Attributes, @attributes].hash
109
+
110
+ # @return [String] such as `#<Kouyou::Attributes id="x" hidden>`
111
+ def inspect = "#<#{self.class.name}#{to_html}>"
112
+
113
+ # @return [String] each attribute after a space, such as ` id="x" hidden`
114
+ def to_html = each_with_object(+"") { |attribute, html| html << attribute.to_html }
115
+
116
+ protected
117
+
118
+ def by_name = @attributes
119
+
120
+ private
121
+
122
+ def each_given(other, &)
123
+ if other.is_a?(Attributes)
124
+ other.each { |attribute| yield attribute.name, attribute }
125
+ else
126
+ raise Kouyou::ArgumentError, "attributes must be a Hash, got #{other.inspect}" unless other.is_a?(Hash)
127
+
128
+ other.each do |name, value|
129
+ attribute = Attribute.new(name, value)
130
+ yield attribute.name, attribute
131
+ end
132
+ end
133
+ end
134
+
135
+ def choose(old, new)
136
+ kouyou = combined(old, new)
137
+ return kouyou unless block_given?
138
+
139
+ chosen = yield old.name, old.value, new.value, kouyou.value
140
+ [kouyou, new, old].find { |attribute| attribute.value.equal?(chosen) } || Attribute.new(old.name, chosen)
141
+ end
142
+
143
+ def combined(old, new)
144
+ return new unless token_list?(old.name) && old.value.is_a?(String) && new.value.is_a?(String)
145
+
146
+ Attribute.new(old.name, (old.value.split + new.value.split).uniq.join(" "))
147
+ end
148
+
149
+ def token_list?(name) = TOKEN_LISTS.include?(name.downcase(:ascii))
150
+ end
151
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kouyou
4
+ # What components include: the {Node} protocol and the {HTML::Elements}
5
+ # vocabulary, so `children` can be written as one expression. The class
6
+ # keeps its own superclass and constructor.
7
+ #
8
+ # A component can be given content with `[]`, as an element is given
9
+ # children, and places it among its children with `content`. One that
10
+ # defines no children of its own renders its content.
11
+ #
12
+ # @example
13
+ # class Card
14
+ # include Kouyou::Component
15
+ #
16
+ # def initialize(title) = @title = title
17
+ #
18
+ # def children = article[h2[@title], content]
19
+ # end
20
+ #
21
+ # Card.new("Kouyou")[Kouyou::HTML::P.new["Autumn leaves"]].to_html
22
+ # # => "<article><h2>Kouyou</h2><p>Autumn leaves</p></article>"
23
+ module Component
24
+ include Node
25
+ include HTML::Elements
26
+
27
+ # Gives the class {ComponentAliases#alias_component}.
28
+ def self.included(base)
29
+ super
30
+ base.extend(ComponentAliases)
31
+ end
32
+
33
+ # @return [Object, Array, nil] the component's content, unless it
34
+ # defines its own children
35
+ def children = content
36
+
37
+ # Gives the component content, which its children place with `content`.
38
+ # It can be given at any time; the next render uses it.
39
+ #
40
+ # @param content [Array] nodes; replaces any earlier content
41
+ # @return [self]
42
+ def [](*content)
43
+ # Named so it can't collide with the class's own instance variables.
44
+ @__content__ = content
45
+ self
46
+ end
47
+
48
+ private
49
+
50
+ # What the caller gave with `[]`, for `children` to place. The module
51
+ # has no constructor to set it in, so this is where the default lives.
52
+ #
53
+ # @return [Array]
54
+ def content = @__content__ || []
55
+ end
56
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kouyou
4
+ # Short names for components in templates. Every {Component} class has
5
+ # `alias_component`; a module can extend this to share a set of aliases
6
+ # with the classes that include it.
7
+ #
8
+ # @example
9
+ # class OrderPage
10
+ # include Kouyou::Component
11
+ #
12
+ # alias_component :card, UI::Card
13
+ #
14
+ # def children = card(title: "Order")[p["Total"]]
15
+ # end
16
+ #
17
+ # @example Sharing aliases
18
+ # module UI::Aliases
19
+ # extend Kouyou::ComponentAliases
20
+ #
21
+ # alias_component :card, UI::Card
22
+ # end
23
+ module ComponentAliases
24
+ # Defines a private method `name` that builds `component` with the
25
+ # arguments it's given: `card(title: "Hi")` is `UI::Card.new(title: "Hi")`.
26
+ # The method is this class's or module's own, so only its templates have
27
+ # it, and like any of its own methods it wins over an element of the same
28
+ # name (see {HTML::Elements}).
29
+ #
30
+ # @param name [Symbol, String]
31
+ # @param component [Class]
32
+ # @return [Symbol] the name
33
+ def alias_component(name, component)
34
+ define_method(name) { |*args, **options, &block| component.new(*args, **options, &block) }
35
+ private name
36
+ name.to_sym
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kouyou
4
+ # An HTML element in the tree. Each tag has its own subclass in
5
+ # {Kouyou::HTML}, which supplies the tag.
6
+ #
7
+ # An element is a {Node} whose children are whatever it was given, and it
8
+ # is its own root.
9
+ #
10
+ # @example
11
+ # Kouyou::HTML::Div.new(class: "card")[Kouyou::HTML::H1.new["Hi"]]
12
+ class Element
13
+ include Node
14
+
15
+ # @return [Attributes] the attributes written into the opening tag
16
+ attr_reader :attributes
17
+
18
+ # @return [Array] the nodes rendered inside the element
19
+ attr_reader :children
20
+
21
+ # @param attributes [Hash, Attributes] see {#attributes=}
22
+ # @param children [Array] see {#children=}
23
+ def initialize(attributes = {}, children = [])
24
+ self.attributes = attributes
25
+ self.children = children
26
+ end
27
+
28
+ # @param attributes [Hash, Attributes] replaces the attributes; a Hash is
29
+ # parsed into {Attributes}
30
+ # @raise [Kouyou::ArgumentError] for attributes {Attributes} refuses
31
+ def attributes=(attributes)
32
+ @attributes = Attributes.from(attributes)
33
+ end
34
+
35
+ # @param children [Array] nodes: elements, text, nil, or arrays of them;
36
+ # replaces any earlier children
37
+ # @raise [Kouyou::ArgumentError] for anything but an Array
38
+ def children=(children)
39
+ raise Kouyou::ArgumentError, "children must be an Array, got #{children.inspect}" unless children.is_a?(Array)
40
+
41
+ @children = children
42
+ end
43
+
44
+ # Sets the children and returns the element, so templates nest as one
45
+ # expression.
46
+ #
47
+ # @return [self]
48
+ def [](*children)
49
+ self.children = children
50
+ self
51
+ end
52
+
53
+ # @return [self]
54
+ def root = self
55
+
56
+ # Structural equality, as the DOM's `isEqualNode` has it: the same
57
+ # element class, with equal {Attributes} (in any order) and equal
58
+ # children, nested elements compared the same way and other nodes by
59
+ # identity. Children are compared as the tree they render, with nested
60
+ # Arrays flattened and nil dropped, so `div[[li["a"]], nil]` equals
61
+ # `div[li["a"]]`. A subclass such as `SubmitButton < HTML::Button` isn't
62
+ # equal to a plain HTML::Button.
63
+ #
64
+ # `eql?` and `hash` stay identity-based: elements change (`attributes=`,
65
+ # `children=`), and a structural hash would lose them as Hash keys.
66
+ #
67
+ # @param other [Object]
68
+ # @return [Boolean]
69
+ def ==(other)
70
+ equal?(other) || (other.instance_of?(self.class) && attributes == other.attributes && nodes == other.nodes)
71
+ end
72
+
73
+ protected
74
+
75
+ def nodes = children.flatten.compact
76
+ end
77
+
78
+ # An element that can't have children, such as <br> or <input>. Renderers
79
+ # write it without a closing tag.
80
+ class VoidElement < Element
81
+ # @raise [Kouyou::ArgumentError] unless `children` is an empty Array: a
82
+ # void element has no children
83
+ def children=(children)
84
+ unless children.is_a?(Array) && children.empty?
85
+ raise Kouyou::ArgumentError, "<#{tag}> is a void element and can't have children"
86
+ end
87
+
88
+ super
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kouyou
4
+ module HTML
5
+ # The template vocabulary for HTML: one private method per element, named
6
+ # after its tag, each returning a new element of its {Kouyou::HTML} class.
7
+ # Children are given with `[]`, so a template is one expression:
8
+ #
9
+ # @example
10
+ # div(class: "card")[
11
+ # h2["Title"],
12
+ # ul[items.map { |item| li[item] }]
13
+ # ]
14
+ #
15
+ # The methods are private so a component's public interface stays its
16
+ # own. In a template they hide Kernel's methods of the same name: `p` is
17
+ # the <p> element, and `select` is <select>. A class's own methods win
18
+ # over them, as Ruby's lookup has it: with `attr_reader :title`, `title`
19
+ # is the reader, and `tag(:title)` builds the element.
20
+ module Elements
21
+ DOCTYPE = SafeString.new("<!doctype html>")
22
+ private_constant :DOCTYPE
23
+
24
+ TAGS.each do |tag, element_class|
25
+ define_method(tag) { |attributes = {}| element_class.new(attributes) }
26
+ end
27
+ private(*TAGS.keys)
28
+
29
+ private
30
+
31
+ # Builds the element named `name`, for when the class's own method of
32
+ # that name shadows the element method.
33
+ #
34
+ # @example
35
+ # tag(:title)["Kouyou"]
36
+ #
37
+ # @param name [Symbol, String] an HTML element's tag
38
+ # @param attributes [Hash]
39
+ # @return [Element]
40
+ # @raise [Kouyou::ArgumentError] for a name that isn't an HTML element
41
+ def tag(name, attributes = {})
42
+ element_class = TAGS.fetch(name.to_s) { raise Kouyou::ArgumentError, "#{name.inspect} isn't an HTML element" }
43
+ element_class.new(attributes)
44
+ end
45
+
46
+ # @return [SafeString] the HTML5 doctype
47
+ def doctype = DOCTYPE
48
+
49
+ # @param string [#to_s] markup to render without escaping
50
+ # @return [SafeString]
51
+ def safe(string) = SafeString.new(string)
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kouyou
4
+ # One Element subclass per HTML tag (HTML::Div, HTML::H1, HTML::Template),
5
+ # so a tree can be matched by class and a tag subclassed with defaults.
6
+ #
7
+ # Tags such as object, data, time and map become HTML::Object, HTML::Data
8
+ # and so on, which shadow the top-level constants inside this namespace:
9
+ # refer to those with a leading `::` here.
10
+ module HTML
11
+ # @return [Array<String>] tags of elements that take children
12
+ STANDARD_TAGS = %w[
13
+ a abbr address article aside audio b bdi bdo blockquote body button
14
+ canvas caption cite code colgroup data datalist dd del details dfn
15
+ dialog div dl dt em fieldset figcaption figure footer form h1 h2 h3 h4
16
+ h5 h6 head header hgroup html i iframe ins kbd label legend li main map
17
+ mark menu meter nav noscript object ol optgroup option output p picture
18
+ pre progress q rp rt ruby s samp script search section select slot
19
+ small span strong style sub summary sup table tbody td template textarea
20
+ tfoot th thead time title tr u ul var video
21
+ ].freeze
22
+
23
+ # @return [Array<String>] tags of elements that can't have children
24
+ VOID_TAGS = %w[area base br col embed hr img input link meta source track wbr].freeze
25
+
26
+ # @return [Hash{String => Class}] element classes by tag name
27
+ TAGS = { Element => STANDARD_TAGS, VoidElement => VOID_TAGS }.flat_map do |superclass, tags|
28
+ tags.map do |tag|
29
+ element_class = ::Class.new(superclass)
30
+ # Evaluated source doesn't inherit this file's magic comment; with its
31
+ # own, `tag` returns one frozen literal instead of a new string per call.
32
+ element_class.class_eval <<~RUBY, __FILE__, __LINE__ + 1
33
+ # frozen_string_literal: true
34
+
35
+ def tag = #{tag.inspect} # def tag = "div"
36
+ RUBY
37
+ [tag, const_set(tag.capitalize, element_class)]
38
+ end
39
+ end.to_h.freeze
40
+ end
41
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kouyou
4
+ # The tree protocol, as in the DOM: a node has children, a root, and
5
+ # renders to HTML. An {Element}'s children are what it was given. A
6
+ # component is an ordinary object that includes Node and defines
7
+ # `children` to build its part of the tree from its own state; most
8
+ # include {Component}, which adds the HTML vocabulary.
9
+ #
10
+ # The subtree isn't kept. It's built whenever something reads it (once per
11
+ # render), so state changed through the component's own methods shows in
12
+ # the next render, and there is nothing to invalidate.
13
+ #
14
+ # @example
15
+ # class Greeting
16
+ # include Kouyou::Node
17
+ #
18
+ # def initialize(name) = @name = name
19
+ #
20
+ # def children = Kouyou::HTML::P.new["Hello, ", @name]
21
+ # end
22
+ #
23
+ # Greeting.new("Ada").to_html # => "<p>Hello, Ada</p>"
24
+ module Node
25
+ # Define this to build the node's children: an element, text, another
26
+ # node, nil, or an Array of them. The default builds nothing.
27
+ #
28
+ # @return [Object, Array, nil]
29
+ def children = []
30
+
31
+ # The single top-level element this node builds, found through nested
32
+ # nodes. Lets a parent reach the element a child component renders as.
33
+ #
34
+ # @return [Element]
35
+ # @raise [Kouyou::BuildError] if the node builds anything but one element
36
+ # (or one node with a root)
37
+ def root
38
+ node = children
39
+ node = node.first if node.is_a?(Array) && node.size == 1
40
+
41
+ case node
42
+ when Element then node
43
+ when Node then node.root
44
+ when Array, nil
45
+ raise BuildError,
46
+ "#{self.class.name} builds #{Array(node).size} top-level nodes, so it has no single root element"
47
+ else raise BuildError, "#{self.class.name} builds a #{node.class} at the top level, so it has no root element"
48
+ end
49
+ end
50
+
51
+ # `to_s` stays Ruby's default on purpose: if it rendered, interpolating a
52
+ # node would build it as a side effect, and the HTML would then be
53
+ # escaped as text.
54
+ #
55
+ # @return [String] the node as HTML, by {Renderer::HTML}
56
+ def to_html = Renderer::HTML.new.render(self)
57
+ end
58
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb/escape"
4
+
5
+ module Kouyou
6
+ # Renderers turn a tree into output:
7
+ # `Kouyou::Renderer::HTML.new.render(node)`.
8
+ module Renderer
9
+ # Turns a tree into an HTML string, reading it without changing it.
10
+ # nil renders nothing, so `(span["!"] if new?)` can sit in a list of
11
+ # children; Arrays render their items, so children can come from `map`.
12
+ #
13
+ # Strings are escaped, except a String subclass whose `html_safe?` is
14
+ # true, such as Rails' `ActiveSupport::SafeBuffer`: it was escaped when it
15
+ # was built, and escaping it again would show the entities as text.
16
+ class HTML
17
+ # @param node [Node, String, Symbol, Numeric, SafeString, Array, nil]
18
+ # @return [String] the HTML
19
+ # @raise [Kouyou::ArgumentError] for a node it can't render
20
+ #
21
+ # @example
22
+ # Kouyou::Renderer::HTML.new.render(Kouyou::HTML::P.new["a < b"]) # => "<p>a &lt; b</p>"
23
+ def render(node)
24
+ @html = +""
25
+ visit(node)
26
+ @html
27
+ end
28
+
29
+ private
30
+
31
+ def visit(node)
32
+ case node
33
+ when VoidElement then open_tag(node)
34
+ when Element
35
+ open_tag(node)
36
+ node.children.each { |child| visit(child) }
37
+ close_tag(node)
38
+ when String then @html << (html_safe?(node) ? node : ERB::Escape.html_escape(node))
39
+ when Symbol, Numeric then @html << ERB::Escape.html_escape(node)
40
+ when Array then node.each { |child| visit(child) }
41
+ when nil then nil
42
+ when SafeString then @html << node.to_s
43
+ # Last: Node is a module, so matching it walks the ancestors.
44
+ when Node then visit(node.children)
45
+ else raise Kouyou::ArgumentError, "can't render #{node.inspect}"
46
+ end
47
+ end
48
+
49
+ def open_tag(element) = @html << "<" << element.tag << element.attributes.to_html << ">"
50
+
51
+ def close_tag(element) = @html << "</" << element.tag << ">"
52
+
53
+ # Plain Strings skip the method check: they're most of the text.
54
+ def html_safe?(string)
55
+ !string.instance_of?(String) && string.respond_to?(:html_safe?) && string.html_safe?
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kouyou
4
+ VERSION = "0.1.0"
5
+ end
data/lib/kouyou.rb ADDED
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "kouyou/version"
4
+
5
+ # Ruby components that build an in-memory tree, rendered to HTML afterwards.
6
+ module Kouyou
7
+ # Included by every Kouyou error: `rescue Kouyou::Error` catches them all.
8
+ module Error; end
9
+
10
+ # Still an ::ArgumentError, so existing rescues keep working.
11
+ class ArgumentError < ::ArgumentError
12
+ include Error
13
+ end
14
+
15
+ # Raised when a component can't be built, such as when it has no single root.
16
+ class BuildError < StandardError
17
+ include Error
18
+ end
19
+
20
+ # Markup trusted as is: renderers emit it without escaping. It is a node
21
+ # like any other, so it can sit anywhere in the tree.
22
+ #
23
+ # It follows Rails' `html_safe?` convention, so Rails writes it unescaped
24
+ # too: `SafeBuffer` checks `html_safe?`, then appends it through `to_str`.
25
+ class SafeString
26
+ # @return [String] the markup, frozen
27
+ attr_reader :to_s
28
+
29
+ # @param string [#to_s] the markup; it is copied, so later changes to the
30
+ # original don't reach the tree
31
+ def initialize(string)
32
+ @to_s = string.to_s.dup.freeze
33
+ freeze
34
+ end
35
+
36
+ alias to_str to_s
37
+
38
+ # @return [true]
39
+ def html_safe? = true
40
+ end
41
+ end
42
+
43
+ require_relative "kouyou/attribute"
44
+ require_relative "kouyou/attributes"
45
+ require_relative "kouyou/node"
46
+ require_relative "kouyou/element"
47
+ require_relative "kouyou/html"
48
+ require_relative "kouyou/html/elements"
49
+ require_relative "kouyou/component_aliases"
50
+ require_relative "kouyou/component"
51
+ require_relative "kouyou/renderer/html"
data/sig/kouyou.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Kouyou
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kouyou
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Micah Frost
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: erb
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '5.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '5.0'
26
+ description: |
27
+ Kouyou (紅葉, autumn leaves) lets you write views as plain Ruby objects.
28
+ Most Ruby view libraries build HTML procedurally, writing it as a template
29
+ runs. Kouyou templates return a tree of objects instead, which can be
30
+ inspected and adjusted before a renderer turns it into HTML.
31
+ email:
32
+ - kouyou@micahfrost.com
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - ".yardopts"
38
+ - CHANGELOG.md
39
+ - CODE_OF_CONDUCT.md
40
+ - LICENSE.txt
41
+ - README.md
42
+ - Rakefile
43
+ - lib/kouyou.rb
44
+ - lib/kouyou/attribute.rb
45
+ - lib/kouyou/attributes.rb
46
+ - lib/kouyou/component.rb
47
+ - lib/kouyou/component_aliases.rb
48
+ - lib/kouyou/element.rb
49
+ - lib/kouyou/html.rb
50
+ - lib/kouyou/html/elements.rb
51
+ - lib/kouyou/node.rb
52
+ - lib/kouyou/renderer/html.rb
53
+ - lib/kouyou/version.rb
54
+ - sig/kouyou.rbs
55
+ homepage: https://github.com/mfrost/kouyou
56
+ licenses:
57
+ - MIT
58
+ metadata:
59
+ source_code_uri: https://github.com/mfrost/kouyou
60
+ changelog_uri: https://github.com/mfrost/kouyou/blob/main/CHANGELOG.md
61
+ documentation_uri: https://rubydoc.info/gems/kouyou
62
+ rubygems_mfa_required: 'true'
63
+ rdoc_options: []
64
+ require_paths:
65
+ - lib
66
+ required_ruby_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: 3.3.0
71
+ required_rubygems_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ requirements: []
77
+ rubygems_version: 4.0.20
78
+ specification_version: 4
79
+ summary: Object-oriented view components that render to HTML.
80
+ test_files: []