afcapel / stimulus-autocomplete

Stimulus autocomplete component
MIT License
478 stars 61 forks source link

Eval script tags returned from server #127

Closed cmer closed 1 year ago

cmer commented 1 year ago

This can be extremely useful to position the dropdown when just CSS won't do, for example.

I ran into such an issue, and returning a small bit of Javascript from the server saved me.

netlify[bot] commented 1 year ago

Deploy Preview for stimulus-autocomplete canceled.

Name Link
Latest commit 709a165dfefe1d08d93913f650da94851b697ada
Latest deploy log https://app.netlify.com/sites/stimulus-autocomplete/deploys/63c2393175aefc0009e3053f
glaszig commented 1 year ago

this will require a csp with unsafe-eval afaik.

how rails-ujs does it:

script = document.createElement('script')
script.setAttribute('nonce', cspNonce())
script.text = response
document.head.appendChild(script).parentNode.removeChild(script)
cmer commented 1 year ago

Makes sense. I updated the code. Let me know what you think!

cmer commented 1 year ago

I messed something up, still working on this...

cmer commented 1 year ago

I ended up solving my problem in a much better way. I just created a Stimulus controller instead. In case it's useful to anyone, I just added the controller on the element being returned. Here's my controller:

import { Controller } from "@hotwired/stimulus"

// Hack to position the dropdown outside of the parent div to allow it to overflow beyond the y axis
// See: https://stackoverflow.com/a/74749062
// and: https://codepen.io/tammibriggs/pen/gOKyWgG

export default class extends Controller {
  connect() {
    let dropdown = this.element;
    let parent = dropdown.parentElement;
    dropdown.style.left = parent.left + 'px';
    dropdown.style.position = 'fixed';
  }
}