phlex icon indicating copy to clipboard operation
phlex copied to clipboard

Add a safe dynamic element method

Open willcosgrove opened this issue 1 year ago • 2 comments

It was brought up in the Discord that we should have a safe way to create dynamic elements. So instead of doing:

send(tag_name, **attributes)

which could potentially call any method, not just an element method, we could have something more like:

element(tag_name, **attributes)

Where tag_name could be a string or symbol that matches any registered element, and it would raise if it didn't match an element.

The name is up for debate. Some ideas:

  • element - nice and short, no current conflicts with HTML or SVG, but because it's not a compound name, it could possibly get used one day
  • safe_element - compound names gets us out of conflict territory with HTML or SVG spec
  • dynamic_element
  • safe_tag
  • dynamic_tag
  • tag - shortest, but will conflict with the rails helper... maybe this is a good conflict if we can shim the API in phlex-rails to match the helper (The main inconsistency is that the Rails tag helper can take content as the first positional argument)
    # phlex-rails override
    def tag(content=nil, **attributes, &block)
      raise ArgumentError, "Cannot pass content positionally and in a block" if content && block_given?
    
      if content
        super(**attributes) { content }
      else
        super(**attributes, &block)
      end
    end
    

willcosgrove avatar Apr 16 '24 21:04 willcosgrove

I like element or tag. We call these elements in the register_element method, and "tag" should include things like comments and doctypes, which this probably shouldn't include.

I don’t think we should use safe_element if we allow for :script, though maybe we should have a version that doesn’t allow for :script. 🤔

joeldrapper avatar Jun 11 '24 10:06 joeldrapper

My vote is tag for all elements apart from script and then unsafe_tag for all elements including script tags. We could also include comment and doctype.

joeldrapper avatar Aug 10 '24 16:08 joeldrapper

@willcosgrove looks like you added the label breaking, but I’m pretty sure this won't be a breaking change. Have I missed anything?

joeldrapper avatar Aug 30 '24 15:08 joeldrapper

I think I marked it as breaking because of this: https://github.com/phlex-ruby/phlex-rails/blob/main/lib/phlex/rails/helpers/tag.rb

willcosgrove avatar Aug 30 '24 15:08 willcosgrove