Files
docuseal/app/javascript/elements/submitter_autocomplete.js
T

74 lines
1.8 KiB
JavaScript
Raw Normal View History

2023-09-20 02:00:00 +03:00
import autocomplete from 'autocompleter'
export default class extends HTMLElement {
connectedCallback () {
autocomplete({
input: this.input,
preventSubmit: 1,
minLength: 1,
showOnFocus: true,
2024-02-28 14:13:23 +02:00
debounceWaitMs: 200,
2023-09-20 02:00:00 +03:00
onSelect: this.onSelect,
render: this.render,
fetch: this.fetch
})
}
onSelect = (item) => {
const fields = ['email', 'name', 'phone']
const submitterItemEl = this.closest('submitter-item')
fields.forEach((field) => {
const input = submitterItemEl.querySelector(`submitters-autocomplete[data-field="${field}"] input`)
2023-09-23 18:22:48 +03:00
const textarea = submitterItemEl.querySelector(`submitters-autocomplete[data-field="${field}"] textarea`)
2023-09-20 02:00:00 +03:00
if (input && item[field]) {
input.value = item[field]
2024-09-06 19:30:49 +03:00
input.dispatchEvent(new CustomEvent('linked-input.update', { bubbles: true }))
2023-09-20 02:00:00 +03:00
}
2023-09-23 18:22:48 +03:00
if (textarea && item[field]) {
textarea.value = textarea.value.replace(/[^;,\s]+$/, item[field] + ' ')
2024-03-16 22:18:43 +02:00
textarea.dispatchEvent(new Event('input', { bubbles: true }))
2023-09-23 18:22:48 +03:00
}
2023-09-20 02:00:00 +03:00
})
}
fetch = (text, resolve) => {
2023-09-23 18:22:48 +03:00
const q = text.split(/[;,\s]+/).pop().trim()
if (q) {
const queryParams = new URLSearchParams({ q, field: this.dataset.field })
2023-09-20 02:00:00 +03:00
2024-03-23 23:33:42 +02:00
this.currentFetch ||= fetch('/submitters_autocomplete?' + queryParams)
2024-02-27 15:20:34 +02:00
this.currentFetch.then(async (resp) => {
2023-09-20 02:00:00 +03:00
const items = await resp.json()
2024-05-30 23:38:38 +03:00
resolve(items)
2023-09-20 02:00:00 +03:00
}).catch(() => {
resolve([])
2024-02-27 15:20:34 +02:00
}).finally(() => {
this.currentFetch = null
2023-09-20 02:00:00 +03:00
})
} else {
resolve([])
}
}
render = (item) => {
const div = document.createElement('div')
2024-01-07 14:19:21 +02:00
div.setAttribute('dir', 'auto')
2023-09-20 02:00:00 +03:00
div.textContent = item[this.dataset.field]
return div
}
get input () {
2023-09-23 18:22:48 +03:00
return this.querySelector('input') || this.querySelector('textarea')
2023-09-20 02:00:00 +03:00
}
}