Made trust adding widget resetable, corrected the unexpected empty field behavior and improved autocomplete's responsiveness

This commit is contained in:
Nicolas Margulies 2022-04-29 01:40:43 +02:00
parent 4fb0b7d736
commit 7afc583282
3 changed files with 11 additions and 9 deletions

View File

@ -266,11 +266,10 @@ class ProfileTrustView(ProtectQuerysetMixin, LoginRequiredMixin, DetailView):
))
context["widget"] = {
"name": "trusted",
"resetable": True,
"attrs": {
"model_pk": ContentType.objects.get_for_model(Alias).pk,
"class": "autocomplete form-control",
"id": "trusted",
"resetable": True,
"api_url": "/api/note/alias/?note__polymorphic_ctype__model=noteuser",
"name_field": "name",
"placeholder": ""

View File

@ -1,3 +1,5 @@
const keycodes = [32, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 106, 107, 109, 110, 111, 186, 187, 188, 189, 190, 191, 219, 220, 221, 222]
$(document).ready(function () {
$('.autocomplete').keyup(function (e) {
const target = $('#' + e.target.id)
@ -10,7 +12,6 @@ $(document).ready(function () {
const input = target.val()
target.addClass('is-invalid')
target.removeClass('is-valid')
$('#' + prefix + '_reset').removeClass('d-none')
$.getJSON(api_url + (api_url.includes('?') ? '&' : '?') + 'format=json&search=^' + input + api_url_suffix, function (objects) {
let html = '<ul class="list-group list-group-flush" id="' + prefix + '_list">'
@ -41,11 +42,14 @@ $(document).ready(function () {
if (typeof autocompleted !== 'undefined') { autocompleted(obj, prefix) }
})
if (input === obj[name_field]) { $('#' + prefix + '_pk').val(obj.id) }
})
if (objects.results.length === 1 && e.originalEvent.keyCode >= 32) {
if (objects.results.length >= 2) {
$('#' + prefix + '_pk').val(objects.results[0].id)
}
if (objects.results.length === 1 &&
(keycodes.includes(e.originalEvent.keyCode) ||
input === objects.results[0][name_field])) {
$('#' + prefix + '_' + objects.results[0].id).trigger('click')
}
})
@ -55,7 +59,6 @@ $(document).ready(function () {
const name = $(this).attr('id').replace('_reset', '')
$('#' + name + '_pk').val('')
$('#' + name).val('')
$('#' + name + '_list').html('')
$(this).addClass('d-none')
$('#' + name).tooltip('hide')
})
})

View File

@ -12,6 +12,6 @@ SPDX-License-Identifier: GPL-3.0-or-later
{% endfor %}
aria-describedby="{{widget.attrs.id}}_tooltip">
{% if widget.resetable %}
<a id="{{ widget.attrs.id }}_reset" class="btn btn-light autocomplete-reset{% if not widget.value %} d-none{% endif %}">{% trans "Reset" %}</a>
<a id="{{ widget.attrs.id }}_reset" class="btn btn-light autocomplete-reset">{% trans "Reset" %}</a>
{% endif %}