hot_module 1.0.0.alpha1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 945191f12e89ec2f10631dd0cbf2292a6f01084f6eb111a2ba3692f2f847314e
4
+ data.tar.gz: b3cc68afcc453e60cda43d5eed8dfedda5bc0b33a5a6618a4f999a55a05e3e49
5
+ SHA512:
6
+ metadata.gz: cc78a6dab31349eaf65ce29644701766d1a8bfce8ae4cc8e196830068e4df43c78a19db85907d91b265c50abe64555e3d77968450fe8a99941314852dea820bb
7
+ data.tar.gz: 8f58833d468c5ad03fdf9e81a020bb36b1ac8c9b7f937bca1e9625302b408477e0e17f8ecbf0792aed5097fda1177bd7fa40b4805c84982beb8e82c0ae59d44a
data/.rubocop.yml ADDED
@@ -0,0 +1,36 @@
1
+ require:
2
+ - rubocop-minitest
3
+ - rubocop-rake
4
+
5
+ AllCops:
6
+ TargetRubyVersion: 3.0
7
+ NewCops: enable
8
+
9
+ Metrics/MethodLength:
10
+ Max: 20
11
+
12
+ Metrics/ModuleLength:
13
+ Enabled: false
14
+
15
+ Style/Documentation:
16
+ Enabled: false
17
+
18
+ Style/LambdaCall:
19
+ Enabled: false
20
+
21
+ Style/ParallelAssignment:
22
+ Enabled: false
23
+
24
+ Style/RegexpLiteral:
25
+ Enabled: false
26
+
27
+ Style/StringLiterals:
28
+ Enabled: true
29
+ EnforcedStyle: double_quotes
30
+
31
+ Style/StringLiteralsInInterpolation:
32
+ Enabled: true
33
+ EnforcedStyle: double_quotes
34
+
35
+ Layout/LineLength:
36
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-09-21
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at jared@jaredwhite.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in html_module.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "rubocop", "~> 1.21"
13
+
14
+ gem "rubocop-minitest", "~> 0.22.1"
15
+ gem "rubocop-rake", "~> 0.6.0"
16
+
17
+ gem "solargraph", "~> 0.47.2", group: :development
data/Gemfile.lock ADDED
@@ -0,0 +1,102 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ hot_module (1.0.0.alpha1)
5
+ nokogiri (~> 1.13)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activesupport (7.0.4)
11
+ concurrent-ruby (~> 1.0, >= 1.0.2)
12
+ i18n (>= 1.6, < 2)
13
+ minitest (>= 5.1)
14
+ tzinfo (~> 2.0)
15
+ ast (2.4.2)
16
+ backport (1.2.0)
17
+ benchmark (0.2.0)
18
+ concurrent-ruby (1.1.10)
19
+ diff-lcs (1.5.0)
20
+ e2mmap (0.1.0)
21
+ hash_with_dot_access (1.2.0)
22
+ activesupport (>= 5.0.0, < 8.0)
23
+ i18n (1.12.0)
24
+ concurrent-ruby (~> 1.0)
25
+ jaro_winkler (1.5.4)
26
+ json (2.6.2)
27
+ kramdown (2.4.0)
28
+ rexml
29
+ kramdown-parser-gfm (1.1.0)
30
+ kramdown (~> 2.0)
31
+ minitest (5.16.3)
32
+ nokogiri (1.13.8-arm64-darwin)
33
+ racc (~> 1.4)
34
+ nokogiri (1.13.8-x86_64-linux)
35
+ racc (~> 1.4)
36
+ parallel (1.22.1)
37
+ parser (3.1.2.1)
38
+ ast (~> 2.4.1)
39
+ racc (1.6.0)
40
+ rainbow (3.1.1)
41
+ rake (13.0.6)
42
+ regexp_parser (2.5.0)
43
+ reverse_markdown (2.1.1)
44
+ nokogiri
45
+ rexml (3.2.5)
46
+ rubocop (1.36.0)
47
+ json (~> 2.3)
48
+ parallel (~> 1.10)
49
+ parser (>= 3.1.2.1)
50
+ rainbow (>= 2.2.2, < 4.0)
51
+ regexp_parser (>= 1.8, < 3.0)
52
+ rexml (>= 3.2.5, < 4.0)
53
+ rubocop-ast (>= 1.20.1, < 2.0)
54
+ ruby-progressbar (~> 1.7)
55
+ unicode-display_width (>= 1.4.0, < 3.0)
56
+ rubocop-ast (1.21.0)
57
+ parser (>= 3.1.1.0)
58
+ rubocop-minitest (0.22.1)
59
+ rubocop (>= 0.90, < 2.0)
60
+ rubocop-rake (0.6.0)
61
+ rubocop (~> 1.0)
62
+ ruby-progressbar (1.11.0)
63
+ solargraph (0.47.2)
64
+ backport (~> 1.2)
65
+ benchmark
66
+ bundler (>= 1.17.2)
67
+ diff-lcs (~> 1.4)
68
+ e2mmap
69
+ jaro_winkler (~> 1.5)
70
+ kramdown (~> 2.3)
71
+ kramdown-parser-gfm (~> 1.1)
72
+ parser (~> 3.0)
73
+ reverse_markdown (>= 1.0.5, < 3)
74
+ rubocop (>= 0.52)
75
+ thor (~> 1.0)
76
+ tilt (~> 2.0)
77
+ yard (~> 0.9, >= 0.9.24)
78
+ thor (1.2.1)
79
+ tilt (2.0.11)
80
+ tzinfo (2.0.5)
81
+ concurrent-ruby (~> 1.0)
82
+ unicode-display_width (2.3.0)
83
+ webrick (1.7.0)
84
+ yard (0.9.28)
85
+ webrick (~> 1.7.0)
86
+
87
+ PLATFORMS
88
+ arm64-darwin-21
89
+ x86_64-linux
90
+
91
+ DEPENDENCIES
92
+ hash_with_dot_access (~> 1.2)
93
+ hot_module!
94
+ minitest (~> 5.0)
95
+ rake (~> 13.0)
96
+ rubocop (~> 1.21)
97
+ rubocop-minitest (~> 0.22.1)
98
+ rubocop-rake (~> 0.6.0)
99
+ solargraph (~> 0.47.2)
100
+
101
+ BUNDLED WITH
102
+ 2.3.14
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Jared White
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,37 @@
1
+ # HoTModuLe (WIP)
2
+
3
+ Parse, mutate, and render custom elements in Ruby using [HTML Modules](https://github.com/WICG/webcomponents/blob/gh-pages/proposals/html-modules-explainer.md).
4
+
5
+ Great for pairing with [esbuild-plugin-html-modules](https://github.com/whitefusionhq/esbuild-plugin-html-modules) for a full-stack component rendering pipeline.
6
+
7
+ ## Installation
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ $ bundle add hot_module
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ $ gem install hot_module
16
+
17
+ ## Usage
18
+
19
+ TODO: Write usage instructions here
20
+
21
+ ## Development
22
+
23
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
24
+
25
+ To install this gem onto your local machine, run `bin/rake install`. To release a new version, update the version number in `version.rb`, and then run `bin/rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
26
+
27
+ ## Contributing
28
+
29
+ Bug reports and pull requests are welcome on GitHub at https://github.com/whitefusionhq/hot_module. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/whitefusionhq/hot_module/blob/main/CODE_OF_CONDUCT.md).
30
+
31
+ ## License
32
+
33
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
34
+
35
+ ## Code of Conduct
36
+
37
+ Everyone interacting in the HoTModuLe project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/whitefusionhq/hot_module/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/hot_module/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "hot_module"
7
+ spec.version = HoTModuLe::VERSION
8
+ spec.authors = ["Jared White"]
9
+ spec.email = ["jared@whitefusion.studio"]
10
+
11
+ spec.summary = "Parse, mutate, and render HTML Modules in Ruby."
12
+ spec.homepage = "https://github.com/whitefusionhq/hot_module#readme"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = ">= 3.0"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = "https://github.com/whitefusionhq/hot_module"
18
+ spec.metadata["changelog_uri"] = "https://github.com/whitefusionhq/hot_module/blob/main/CHANGELOG.md"
19
+ spec.metadata["rubygems_mfa_required"] = "true"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(__dir__) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
26
+ end
27
+ end
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_dependency "nokogiri", "~> 1.13"
31
+
32
+ spec.add_development_dependency "hash_with_dot_access", "~> 1.2"
33
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HoTModuLe
4
+ class Fragment
5
+ def initialize(fragment, attribute_bindings, html_module:)
6
+ @fragment = fragment
7
+ @attribute_bindings = attribute_bindings
8
+ @html_module = html_module
9
+ end
10
+
11
+ # NOTE: for some reason, the Nokogiri traverse method yields node children first, then the
12
+ # parent node. That doesn't work for our case. We want to go strictly in source order. So this
13
+ # is our own implementation of that.
14
+ def traverse(node, &block)
15
+ yield(node)
16
+ node.children.each { |child| traverse(child, &block) }
17
+ end
18
+
19
+ def process(fragment = @fragment)
20
+ traverse(fragment) do |node|
21
+ process_attribute_bindings(node)
22
+ end
23
+ end
24
+
25
+ def process_attribute_bindings(node)
26
+ node.attributes.each do |name, attr_node|
27
+ @attribute_bindings.each do |attribute_binding|
28
+ next unless attribute_binding.matcher.match?(name)
29
+
30
+ break unless attribute_binding.method.(attribute: attr_node, node: node)
31
+ end
32
+ rescue Exception => e # rubocop:disable Lint/RescueException
33
+ raise e.class, e.message.lines.first, ["#{@html_module}:#{attr_node.line}", *e.backtrace]
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "hot_module"
4
+
5
+ module JSStrings
6
+ refine Kernel do
7
+ def `(str)
8
+ str
9
+ end
10
+ end
11
+ refine String do
12
+ def underscore
13
+ gsub(/([A-Z]+)(?=[A-Z][a-z])|([a-z\d])(?=[A-Z])/) do
14
+ (::Regexp.last_match(1) || ::Regexp.last_match(2)) << "_"
15
+ end.tr("-", "_").downcase
16
+ end
17
+ end
18
+ end
19
+
20
+ module HoTModuLe
21
+ module Petite
22
+ using JSStrings
23
+
24
+ # @param klass [Class]
25
+ # @return [void]
26
+ def self.included(klass)
27
+ klass.attribute_binding "v-for", :_for_binding
28
+ klass.attribute_binding "v-text", :_text_binding
29
+ klass.attribute_binding "v-html", :_html_binding
30
+ klass.attribute_binding "v-bind", :_handle_bound_attribute
31
+ klass.attribute_binding %r{^:}, :_handle_bound_attribute
32
+ end
33
+
34
+ protected
35
+
36
+ def evaluate_attribute_expression(attribute, eval_code = attribute.value) # rubocop:disable Metrics/AbcSize
37
+ eval_code = eval_code.gsub(/\${(.*)}/, "\#{\\1}")
38
+ @_locals ||= {}
39
+ @_locals.keys.reverse_each do |name|
40
+ eval_code = "#{name} = @_locals[\"#{name}\"];" + eval_code
41
+ end
42
+ instance_eval(eval_code, self.class.html_module, attribute.line)
43
+ rescue NameError => e
44
+ bad_name = e.message.match(/`(.*?)'/)[1]
45
+ suggestion = bad_name.underscore
46
+ eval_code.gsub!(bad_name, suggestion)
47
+ instance_eval(eval_code, self.class.html_module, attribute.line)
48
+ end
49
+
50
+ def _locals_stack
51
+ @_locals_stack ||= []
52
+ end
53
+
54
+ def _check_stack(node) # rubocop:disable Metrics/AbcSize
55
+ node_and_ancestors = [node, *node.ancestors.to_a]
56
+ stack_misses = 0
57
+
58
+ stack_nodes = _locals_stack.map { _1[:node] }
59
+ stack_nodes.each do |stack_node|
60
+ if node_and_ancestors.none? { _1["v-if"] == "!hydrated" } && node_and_ancestors.none? { _1 == stack_node }
61
+ stack_misses += 1
62
+ end
63
+ end
64
+
65
+ stack_misses.times { _locals_stack.pop }
66
+
67
+ !((node_and_ancestors & _locals_stack.map { _1[:node] }).empty?) # rubocop:disable Style/RedundantParentheses
68
+ end
69
+
70
+ def _for_binding(attribute:, node:)
71
+ return unless node.name == "template"
72
+
73
+ return if _check_stack(node)
74
+
75
+ @_locals_stack.push({ node: node })
76
+ _process_list(attribute: attribute, node: node)
77
+ end
78
+
79
+ def _text_binding(attribute:, node:)
80
+ return if _check_stack(node)
81
+
82
+ node.content = evaluate_attribute_expression(attribute)
83
+ end
84
+
85
+ def _html_binding(attribute:, node:)
86
+ return if _check_stack(node)
87
+
88
+ node.content = evaluate_attribute_expression(attribute)
89
+ end
90
+
91
+ def _handle_bound_attribute(attribute:, node:) # rubocop:disable Metrics
92
+ return if _check_stack(node)
93
+
94
+ return if attribute.name == ":key"
95
+
96
+ real_attribute = if attribute.name.start_with?(":")
97
+ attribute.name.delete_prefix(":")
98
+ elsif attribute.name.start_with?("v-bind:")
99
+ attribute.name.delete_prefix("v-bind:")
100
+ end
101
+
102
+ obj = evaluate_attribute_expression(attribute)
103
+
104
+ if real_attribute == "class"
105
+ class_names = case obj
106
+ when Hash
107
+ obj.filter { |_k, v| v == true }.keys
108
+ when Array
109
+ # TODO: handle objects inside of an array
110
+ obj
111
+ else
112
+ Array[obj]
113
+ end
114
+ node[real_attribute] = class_names.join(" ")
115
+ elsif real_attribute != "style" # style bindings aren't SSRed
116
+ node[real_attribute] = obj if obj
117
+ end
118
+ end
119
+
120
+ def _process_list(attribute:, node:) # rubocop:disable Metrics
121
+ item_node = node.element_children.first
122
+
123
+ delimiter = node["v-for"].include?(" of ") ? " of " : " in "
124
+ expression = node["v-for"].split(delimiter)
125
+ lh = expression[0].strip.delete_prefix("(").delete_suffix(")").split(",").map!(&:strip)
126
+ rh = expression[1].strip
127
+
128
+ list_items = evaluate_attribute_expression(attribute, rh)
129
+
130
+ # TODO: handle object style
131
+ # https://vuejs.org/guide/essentials/list.html#v-for-with-an-object
132
+
133
+ return unless list_items
134
+
135
+ _in_locals_stack do
136
+ list_items.each_with_index do |list_item, index|
137
+ new_node = item_node.clone
138
+ node.parent << new_node
139
+ new_node["v-if"] = "!hydrated"
140
+
141
+ local_items = { **(prev_items || {}) }
142
+ local_items[lh[0]] = list_item
143
+ local_items[lh[1]] = index if lh[1]
144
+
145
+ @_locals = local_items
146
+
147
+ Fragment.new(
148
+ new_node, self.class.attribute_bindings,
149
+ html_module: self.class.html_module
150
+ ).process
151
+ end
152
+ end
153
+ end
154
+
155
+ def _in_locals_stack
156
+ prev_items = @_locals
157
+ yield
158
+ @_locals = prev_items
159
+ end
160
+ end
161
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HoTModuLe
4
+ # Add a couple familar DOM API features to Nokogiri
5
+ module QuerySelection
6
+ # @param selector [String]
7
+ # @return [Nokogiri::XML::Element]
8
+ def query_selector(selector) = at_css(selector)
9
+
10
+ # @param selector [String]
11
+ # @return [Nokogiri::XML::Element]
12
+ def query_selector_all(selector) = css(selector)
13
+ end
14
+
15
+ Nokogiri::XML::Node.include QuerySelection unless Nokogiri::XML::Node.instance_methods.include?(:query_selector)
16
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HoTModuLe
4
+ # @return [String]
5
+ VERSION = "1.0.0.alpha1"
6
+ end
data/lib/hot_module.rb ADDED
@@ -0,0 +1,197 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "hot_module/version"
4
+
5
+ require "nokogiri"
6
+
7
+ # Include this module into your own component class
8
+ module HoTModuLe
9
+ class Error < StandardError; end
10
+
11
+ AttributeBinding = Struct.new(:matcher, :method_name, :method, keyword_init: true) # rubocop:disable Lint/StructNewOverride
12
+
13
+ require_relative "hot_module/fragment"
14
+ require_relative "hot_module/query_selection"
15
+
16
+ # @param klass [Class]
17
+ # @return [void]
18
+ def self.included(klass)
19
+ klass.extend ClassMethods
20
+ # Don't stomp on a superclass's `content` method
21
+ return if klass.instance_methods.include?(:content)
22
+
23
+ klass.include ContentMethod
24
+ end
25
+
26
+ # Extends the component class
27
+ module ClassMethods
28
+ def html_file_extensions = %w[tmpl.html html].freeze
29
+ def processed_css_extension = "css-local"
30
+
31
+ # @param tag_name [String]
32
+ # @param html_module [String] if not provided, a class method called `source_location` must be
33
+ # available with the absolute path of the Ruby file
34
+ # @param shadow_root [Boolean] default is true
35
+ # @return [void]
36
+ def custom_element(tag_name, html_module = nil, shadow_root: true) # rubocop:disable Metrics/AbcSize
37
+ if html_module.nil? && !respond_to?(:source_location)
38
+ raise HoTModuLe::Error, "You must either supply a file path argument or respond to `source_location'"
39
+ end
40
+
41
+ @tag_name = tag_name
42
+
43
+ if html_module
44
+ @html_module = html_module
45
+ else
46
+ basepath = File.join(File.dirname(source_location), File.basename(source_location, ".*"))
47
+
48
+ @html_module = html_file_extensions.lazy.filter_map do |ext|
49
+ path = "#{basepath}.#{ext}"
50
+ File.exist?(path) ? path : nil
51
+ end.first
52
+
53
+ raise HoTModuLe::Error, "Cannot find sidecar HTML module for `#{self}'" unless @html_module
54
+ end
55
+
56
+ @shadow_root = shadow_root
57
+ end
58
+
59
+ # @param value [String]
60
+ # @return [String]
61
+ def tag_name(value = nil)
62
+ @tag_name ||= value
63
+ end
64
+
65
+ # @param value [String]
66
+ # @return [String]
67
+ def html_module(value = nil)
68
+ @html_module ||= value
69
+ end
70
+
71
+ # @param value [Boolean]
72
+ # @return [Boolean]
73
+ def shadow_root(value = nil)
74
+ @shadow_root ||= value
75
+ end
76
+
77
+ # @return [Nokogiri::XML::Element]
78
+ def doc
79
+ @doc ||= Nokogiri::HTML5.fragment(
80
+ "<#{tag_name}>#{File.read(html_module)}</#{tag_name}>"
81
+ ).first_element_child
82
+ end
83
+
84
+ def attribute_bindings
85
+ @attribute_bindings ||= []
86
+ end
87
+
88
+ def attribute_binding(matcher, method_name)
89
+ attribute_bindings << AttributeBinding.new(
90
+ matcher: Regexp.new(matcher),
91
+ method_name: method_name
92
+ )
93
+ end
94
+ end
95
+
96
+ module ContentMethod
97
+ # @return [String, Nokogiri::XML::Element]
98
+ def content; end
99
+ end
100
+
101
+ # Override in component
102
+ #
103
+ # @return [Hash]
104
+ def attributes
105
+ {}
106
+ end
107
+
108
+ # @param attributes [Hash]
109
+ # @param content [String, Nokogiri::XML::Element]
110
+ # @param return_node [Boolean]
111
+ def render_element(attributes: self.attributes, content: self.content, return_node: false) # rubocop:disable Metrics
112
+ doc = self.class.doc.clone
113
+ tmpl_el = doc.css("> template").find { _1.attributes.length.zero? }
114
+
115
+ unless tmpl_el
116
+ tmpl_el = doc.document.create_element("template")
117
+ immediate_children = doc.css("> :not(style):not(script)")
118
+ tmpl_el << immediate_children
119
+ doc.prepend_child(tmpl_el)
120
+ end
121
+
122
+ # Process all the template bits
123
+ process_fragment(tmpl_el)
124
+
125
+ # Set attributes on the custom element
126
+ attributes.each { |k, v| doc[k.to_s.tr("_", "-")] = v }
127
+
128
+ # Look for external and internal styles
129
+ output_styles = ""
130
+ external_styles = doc.css("link[rel=stylesheet]")
131
+ external_styles.each do |external_style|
132
+ next unless external_style["hmod:process"]
133
+
134
+ output_styles += File.read(File.expand_path(external_style["href"], File.dirname(self.class.html_module)))
135
+ external_style.remove
136
+ rescue StandardError => e
137
+ raise e.class, e.message.lines.first,
138
+ ["#{self.class.html_module}:#{external_style.line}", *e.backtrace]
139
+ end
140
+ sidecar_file = "#{File.join(
141
+ File.dirname(self.class.html_module), File.basename(self.class.html_module, ".*")
142
+ )}.#{self.class.processed_css_extension}"
143
+ output_styles += if File.exist?(sidecar_file)
144
+ File.read(sidecar_file)
145
+ else
146
+ doc.css("> style:not([scope])").map(&:content).join
147
+ end
148
+
149
+ # Now remove all nodes *except* the template
150
+ doc.children.each do |node|
151
+ node.remove unless node == tmpl_el
152
+ end
153
+
154
+ style_tag = nil
155
+ if output_styles.length.positive?
156
+ # We'll transfer everything over to a single style element
157
+ style_tag = tmpl_el.document.create_element("style")
158
+ style_tag.content = output_styles
159
+ end
160
+
161
+ if self.class.shadow_root
162
+ # Guess what? We can reuse the same template tag! =)
163
+ tmpl_el["shadowroot"] = "open"
164
+ tmpl_el << style_tag if style_tag
165
+ doc << content if content
166
+ else
167
+ tmpl_el << style_tag if style_tag
168
+ tmpl_el.at_css("slot:not([name])")&.swap(content) if content
169
+ tmpl_el.children.each do |node|
170
+ doc << node
171
+ end
172
+ tmpl_el.remove
173
+ end
174
+
175
+ # And that is that.
176
+ return_node ? doc : doc.to_html
177
+ end
178
+
179
+ def call(...)
180
+ render_element(...)
181
+ end
182
+
183
+ # Override in component if need be, otherwise we'll use the node walker/binding pipeline
184
+ #
185
+ # @param fragment [Nokogiri::XML::Element]
186
+ # @return [void]
187
+ def process_fragment(fragment)
188
+ Fragment.new(
189
+ fragment, self.class.attribute_bindings.each { _1.method = method(_1.method_name) },
190
+ html_module: self.class.html_module
191
+ ).process
192
+ end
193
+
194
+ def inspect
195
+ "#<#{self.class.name} #{attributes}>"
196
+ end
197
+ end
metadata ADDED
@@ -0,0 +1,89 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hot_module
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0.alpha1
5
+ platform: ruby
6
+ authors:
7
+ - Jared White
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-10-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: nokogiri
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.13'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.13'
27
+ - !ruby/object:Gem::Dependency
28
+ name: hash_with_dot_access
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.2'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.2'
41
+ description:
42
+ email:
43
+ - jared@whitefusion.studio
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".rubocop.yml"
49
+ - CHANGELOG.md
50
+ - CODE_OF_CONDUCT.md
51
+ - Gemfile
52
+ - Gemfile.lock
53
+ - LICENSE.txt
54
+ - README.md
55
+ - Rakefile
56
+ - hot_module.gemspec
57
+ - lib/hot_module.rb
58
+ - lib/hot_module/fragment.rb
59
+ - lib/hot_module/petite.rb
60
+ - lib/hot_module/query_selection.rb
61
+ - lib/hot_module/version.rb
62
+ homepage: https://github.com/whitefusionhq/hot_module#readme
63
+ licenses:
64
+ - MIT
65
+ metadata:
66
+ homepage_uri: https://github.com/whitefusionhq/hot_module#readme
67
+ source_code_uri: https://github.com/whitefusionhq/hot_module
68
+ changelog_uri: https://github.com/whitefusionhq/hot_module/blob/main/CHANGELOG.md
69
+ rubygems_mfa_required: 'true'
70
+ post_install_message:
71
+ rdoc_options: []
72
+ require_paths:
73
+ - lib
74
+ required_ruby_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '3.0'
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">"
82
+ - !ruby/object:Gem::Version
83
+ version: 1.3.1
84
+ requirements: []
85
+ rubygems_version: 3.3.3
86
+ signing_key:
87
+ specification_version: 4
88
+ summary: Parse, mutate, and render HTML Modules in Ruby.
89
+ test_files: []