Skip to content

Instantly share code, notes, and snippets.

@vitobotta
Created February 19, 2020 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitobotta/614c76f9f02d607e430264eea5c2c74b to your computer and use it in GitHub Desktop.
Save vitobotta/614c76f9f02d607e430264eea5c2c74b to your computer and use it in GitHub Desktop.
import { Controller } from "stimulus"
import Tagify from '@yaireo/tagify'
import Rails from '@rails/ujs'
export default class extends Controller {
static targets = ["input"]
render() {
const tagify = new Tagify(this.inputTarget, {
whitelist: [],
})
window.tagify = tagify
var controller;
const that = this
tagify.on("input", (event) => {
var value = event.detail.value;
tagify.settings.whitelist.length = 0; // reset the whitelist
// https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort
controller && controller.abort();
controller = new AbortController();
// show loading animation and hide the suggestions dropdown
tagify.loading(true).dropdown.hide.call(tagify)
fetch(`${that.inputTarget.dataset.tagsPath}?value=` + value, {signal:controller.signal})
.then(RES => RES.json())
.then(function(whitelist){
// update inwhitelist Array in-place
tagify.settings.whitelist.splice(0, whitelist.length, ...whitelist)
tagify.loading(false).dropdown.show.call(tagify, value); // render the suggestions dropdown
})
})
tagify.on("add", (event) => {
that.submitForm(event)
})
tagify.on("remove", (event) => {
that.submitForm(event)
})
}
connect() {
this.render()
this.actionName = document.querySelector("#action_name")
this.reloadForm = document.querySelector("#reload_form")
this.form = document.querySelector("form")
}
submitForm(event) {
event.preventDefault()
if (window.ajax) {
return
}
this.reloadForm.value = "false"
this.actionName.value = this.inputTarget.closest(".panel-section").id
Rails.fire(this.form, 'submit')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment