Code Monkey home page Code Monkey logo

phlexing's Introduction

Phlexing

Tests Rubocop

A simple ERB to Phlex Converter.

Phlexing Screenshot

Website

A hosted version of the converter is running at https://phlexing.fun.

Using the gem

Installation

Install the gem and add to the application's Gemfile by executing:

$ bundle add phlexing

If bundler is not being used to manage dependencies, install the gem by executing:

$ gem install phlexing

Basic Usage

require "phlexing"

Phlexing::Converter.convert(%(<h1 class="title">Hello World</h1>))
Output
h1(class: "title") { "Hello World" }

Converter Options

Option Type Default Value Description
whitespace Boolean true Generate whitespace in and around HTML block elements.
component Boolean false Generate a Phlex class with a view_template method around your input.
component_name String "Component" The name of your Phlex class.
parent_component String "Phlex::HTML" The name of the parent class your Phlex class will inherit from.
svg_param String "s" The name of the block argument Phlex will use to generate SVG-specific elements.
template_name String "view_template" The name of the generated template method in your Phlex class.

Multi-line HTML

Phlexing::Converter.convert(<<~HTML)
  <% @articles.each do |article| %>
    <h1><%= article.title %></h1>
  <% end %>
HTML
Output
@articles.each { |article| h1 { article.title } }

Component class

Phlexing::Converter.convert(<<~HTML, component: true)
  <h1><%= @user.name %></h1>

  <p><%= posts.count %> Posts</p>
HTML
Output
class Component < Phlex::HTML
  attr_accessor :posts

  def initialize(posts:, user:)
    @posts = posts
    @user = user
  end

  def view_template
    h1 { @user.name }

    p do
      text posts.count
      text %( Posts)
    end
  end
end

Rails Helpers

Phlexing::Converter.convert(%(<%= link_to "Home", root_path %>), component: true)
Output
class Component < Phlex::HTML
  include Phlex::Rails::Helpers::LinkTo
  include Phlex::Rails::Helpers::Routes

  def view_template
    link_to "Home", root_path
  end
end

Private component methods

Phlexing::Converter.convert(%(<% if active? %>Active<% else %>Inactive<% end %>), component: true)
Output
class Component < Phlex::HTML
  def view_template
    if active?
      text "Active"
    else
      text "Inactive"
    end
  end

  private

  def active?(*args, **kwargs)
    # TODO: Implement me
  end
end

ERB Attribute interpolation

Phlexing::Converter.convert(%(<div style="background: <%= active? ? "green" : "gray" %>"></div>))
Output
div(style: %(background: #{active? ? "green" : "gray"}))

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec 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.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/marcoroth/phlexing. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Phlexing project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

phlexing's People

Contributors

dependabot[bot] avatar djfpaagman avatar fig avatar joeldrapper avatar marcoroth avatar stephannv avatar thomasklemm avatar willcosgrove avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

phlexing's Issues

Support case-sensitive HTML elements

Even while it's encouraged to use Kebab-case for HTML-tags there are some use-cases where we have case-sensitive HTML elements, like in SVG (see #139). This would also allow to cleanup the special-handling we have for handling SVG elements in:

subchild.name = SVG_ELEMENTS[subchild.name] if SVG_ELEMENTS.key?(subchild.name)

Since we are using Nokogiri::HTML4::DocumentFragment for parsing the source it automatically casts all tag names to lowercase. While Nokogiri::HTML5::DocumentFragment would support case-sensitive tags, it doesn't support other things like properly detecting boolean attributes (see #119 and #120).

ERB Input:

<customElement>
 <anotherElement/>
</customElement>

Output:

class CustomelementComponent < Phlex::HTML
  register_element :anotherelement
  register_element :customelement

  def template
    customelement { anotherelement }
  end
end

Expected output:

class CustomelementComponent < Phlex::HTML
  register_element :anotherElement
  register_element :customElement

  def template
    customElement { anotherElement }
  end
end

SVG tags are a special case

ERB Input:

<svg>
  <feSpecularLighting>
    <fePointLight/>
  </feSpecularLighting>    
</svg>

Output:

svg { fespecularlighting { fepointlight } }

Expected output:

# `el` is just a random name
svg { |el| el.feSpecularLighting { el.fePointLight } }
# or
svg do |el|
  el.feSpecularLighting do 
    el.fePointLight
  end
end

There are two problems:

  • Phlex uses yielded svg to build svg tags
  • SVG tag methods uses camelCase pattern, downcase method names results on NoMethodError

Style tags gets minified/transformed

ERB Input:

<style>
  body { background: black }
</style>

Output:

style { "body{background:#000}" }

Expected output:

style { "body { background: #000 }" }

or

style { "body { background: black }" }

Methods called within the ERB template are not generated in the component output

ERB Input:

<% if some_condition? %>
  <%= "Text" %>
<% end %>

Output:

class Component < Phlex::HTML
  def template
    if some_condition?
      text "Text"
    end
  end
end

Expected output:

class Component < Phlex::HTML
  def template
    if some_condition?
      text "Text"
    end
  end

  private 
  
  # TODO: Implement the `some_condition?` method
  def some_condition?
    super
  end
end

Rails `t` and `translate` helpers

Case 1

ERB Input:

<%= t(".some.string") %> Text

Output:

text t(".some.string")

text " Text"

Expected output:

t(".some.string")

text " Text"

Case 2

ERB Input:

<%= translate(".some.string") %> Text

Output:

text translate(".some.string")

text " Text"

Expected output:

translate(".some.string")

text " Text"

More than one ERB string interpolation in HTML attribute

ERB Input:

<div style="<%= "background: red;" %><%= "display: block;" %>"></div>

Output:

div(style: ("background: red;" %><%=), block: %(), erb: %(), display:: %()) { %(">)
 }

Expected output:

div(style: %(#{"background: red;"}#{"display: block"}))

ERB interpolation within `<style>` tag doesn't work

ERB Input:

<style type="text/css">
<%= Rouge::Themes::Monokai.render(scope: 'pre') %>
</style>

Output:

style(type: "text/css") do
  "<erb loud> Rouge::Themes::Monokai.render(scope: 'pre') </erb>"
end

Expected output:

style(type: "text/css") do
  Rouge::Themes::Monokai.render(scope: 'pre')
end

Using Rails tag helpers with blocks

ERB Input:

<%= tag.p do %>
  <div>Text</div>
<% end %>

Output:

text tag.p do
  div { "Text" }
end

Expected output:

tag.p do
  div { "Text" }
end

or ideally:

p do
  div { "Text" }
end

Unnecessary whitespace for some tags

I'm converting some Tailwind UI components with Phlexing and noticed that I get a lot of unnecessary whitespace rows in my code. I've narrowed it down a bit and it seems to happen only for certain tags. Here's an example:

<div>
  <label>Test</label>
</div>

converts into:

div do
  whitespace
  label { "Test" }
end

If you change label to div or h1 it does not add the whitespace.

I've narrowed the cause down to the call to HtmlPress here, which leaves a space between the tags:

HtmlPress.press(converted_erb)

irb(main):001:0" html = <<~HTML.strip
irb(main):002:0"   <div>
irb(main):003:0"     <label>Test</label>
irb(main):004:0"  </div>
irb(main):005:0> HTML
=> "<div>\n  <label>Test</label>\n</div>"
irb(main):006:0> HtmlPress.press(html)
=> "<div> <label>Test</label></div>"
         ^ extra space here
irb(main):007:0" html = <<~HTML.strip
irb(main):008:0"   <div>
irb(main):009:0"     <h1>Test</h1>
irb(main):010:0"   </div>
irb(main):011:0> HTML
=> "<div>\n  <h1>Test</h1>\n</div>"
irb(main):012:0> HtmlPress.press(html)
=> "<div><h1>Test</h1></div>"
         ^ no space here

It seems that HtmlPress is unmaintained and marked deprecated by the owner (stereobooster/html_press#21), so I don't really expect them to fix this or accept a fix.

Not sure what a good approach would be here, what are your thoughts? Happy to work on some kind of fix 👍

ERB in attributes always outputs parens

Input:

<div class="<%= classes_helper %>" id="<%= many? ? "posts" : "post" %>"></div>

Output:

div(class: (classes_helper), id: (many? ? "posts" : "post"))

Expected output:

div(class: classes_helper, id: (many? ? "posts" : "post"))

Automatically detect Rails helpers

Using Phlexing::Converter.idents we should be able to figure out if the HTML is depending on any Rails helper within the template. If that's the case we could automatically include the right module, delegate the call to the helpers object Phlex provides or we could rewrite the Ruby code that we output

Uppercase tag names

ERB Input:

<HTML>
  <HEAD></HEAD>
  <BODY></BODY>
</HTML>

Output:

body

Expected output:

html do
  head
  body
end

`form_with` short-circuits output

ERB Input:

<%= form_with(model: @test) do |form| %>
   <h3>Test</h3>
<% end %>

Output:

class Test < Phlex::HTML
  def view_template
  end
end

Expected output:

class Test < Phlex::HTML
  def view_template
     form_with(model: @test) do |form|
    h3 { "Test" }
  end
end

It seems the form_wth line is the issue.

Interpolating ERB in HTML attributes

ERB Input:

<div class="<%= classes_helper %>">Text</div>

Output:

div(class: "<erb interpolated=", true: "") { ' classes_helper ">Text' }

Expected output:

div(class: classes_helper) { "Text" }

Stray `text` calls on method calls that render or capture for `Phlex::DeferredRender

Is your feature request related to a problem? Please describe.
Phlexing can't tell when to leave out the text method call on methods that render

image

Expected:

render SomeComponent.new do |c|
  c.section { "hello world" }
end

Not sure what the solution might be. Phlexing obviously doesn't know if c.section is rendering, capturing for Phlex::DeferredRender or returning a String.

Enable Comments tests again

In #52 while moving the test suite over to the gem the test in comments_test.rb started to fail. I don't fully understand why, but html_press does remove the HTML comments while minifing in the gem context, it didn't do that in the context of the Rails app.

Since the html_press is deprecated we should anyway be looking for an alternative.

Transform Phlex code output through RuboCop or SyntaxTree

Let's say we have this:

<%= tag.div class: something? ? "class-1" : "class-2" do %>
  <%= content_tag :span, something.text %>
<% end %>

Which would generate this through phlexing today:

class SomethingComponent < Phlex::HTML
  include Phlex::Rails::Helpers::ContentTag
  include Phlex::Rails::Helpers::Tag

  attr_accessor :something

  def initialize(something:)
    @something = something
  end

  def template
    tag.div class: something? ? "class-1" : "class-2" do
      content_tag :span, something.text
    end
  end

  private

  def something?(*args, **kwargs)
    # TODO: Implement me
  end
end

But since this is a regular Ruby class now we could write any RuboCop rule (or maybe even a SyntaxTree mutation visitor) which statically analyses the code and auto-fixes it (we could even make the rules toggleable from the UI)

For example some rules could be:

  • rewrite tag.div as div { ... }
  • rewrite content_tag :span to span { ... }
  • rewrite all references of something inside def template to @something and remove the attr_accessor for it
  • rewrite class: something? ? "class-1" : "class-2" to **classes(something?: { then: "class-1", else: "class-2" })
  • ...

We could even release these rules standalone as rubocop-phlex which people could use in their project independent of phlexing

Copy to clipboard button copies old code, not what is in text box

Sorry, you don't have a bug template, so I'm freestyling.

Issue

When clicking the click->converter#copy button, what is copied to the clipboard is output from a previous ERB conversion, not the one that is currently in the box. This happens 100% of the time for me since it started previously.

I'm guessing it might have something to do with either not having a component name, or the text input not being valid but the output is still generated, and then it gets "stuck" or something in Turbo. Refreshing the page resolves the issue.

Potential Solution

I noticed in the source that it's copying from output-copy, a second buffer of the text in the pre#output field.

await navigator.clipboard.writeText(document.getElementById("output-copy").value)

You surely know better than me since you made it, but that seems like it might be unnecessary. The innerText of the pre element returns the literal text that is visible to the user, which would prevent any mismatch between what is seen and what is copied.

- await navigator.clipboard.writeText(document.getElementById("output-copy").value) 
+ await navigator.clipboard.writeText(document.getElementById("output").innerText) 

Using Rails tag helpers alongside other nodes

ERB Input:

<div><%= tag.div('Hello world!') %>Text</div>

Output:

div do
  text(tag.div("Hello world!"))
  text "Text"
end

Expected output:

div do
  tag.div("Hello world!")
  text "Text"
end

or ideally:

div do
  div { "Hello world!" }
  text "Text"
end

Methods that take a block shouldn't be called with `plain`

ERB Input:

<%= something do %>
  Content
<% end %>

Output:

plain something do
  plain " Content"
end

Expected output:

something do
  plain " Content"
end

@adamlogic experienced this in the GoRails Phlex episode: https://youtu.be/l4bQSfqZZfQ&t=1267

I'm not sure if this is actually solvable. Since the ERB is using <%= we expect to output the return value of the method call. If the ERB is just <% the output works as expected. Like:

<% something do %>
  Content
<% end %>

Outputs:

something { plain " Content" }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.