Rimozione dipendenza UI Autocomplete

Rimozione della dipendenza UI Autocomplete in favore di una libreria indipendente, aggiornamento funzioni JS per la gestione degli allegati.
This commit is contained in:
Dasc3er 2021-07-20 15:23:39 +02:00
parent 67ad05b3a7
commit 10e1301eb7
11 changed files with 508 additions and 258 deletions

View File

@ -81,7 +81,8 @@ input[type=file] {
position: fixed;
}
.ui-autocomplete {
.autocomplete, .ui-autocomplete {
background: white;
z-index: 10000;
min-width: 160px;
padding: 10px;
@ -94,8 +95,23 @@ input[type=file] {
border-radius: 5px;
}
.ui-autocomplete-category {
font-size: 150%;
.autocomplete .group, .ui-autocomplete-category {
font-size: 1.5em;
background: inherit;
}
.autocomplete > div {
padding: 5px;
}
.highlight {
background: #FFFF66;
}
.autocomplete > div:hover:not(.group),
.autocomplete > div.selected {
background: #F5F5F5;
cursor: pointer;
}
.ui-autocomplete-scrollable {

View File

@ -138,7 +138,7 @@ $(document).ready(function () {
$(this).attr("data-id_records", "");
$(this).data("id_records", "");
} else {
swal(globals.translations.waiting, globals.translations.waiting_msg, "error");
swal(globals.translations.waiting, globals.translations.waitingMessage, "error");
}
});
});

View File

@ -17,88 +17,75 @@
*/
$(document).ready(function () {
$('#supersearch').keyup(function () {
$(document).ajaxStop();
const searchInput = $('#supersearch');
const searchButton = searchInput.parent().find('i');
const searches = [];
if ($(this).val() == '') {
$(this).removeClass('wait');
} else {
$(this).addClass('wait');
}
});
autocomplete({
minLength: 1,
input: searchInput[0],
emptyMsg: globals.translations.noResults,
debounceWaitMs: 500,
fetch: function(text, update) {
text = text.toLowerCase();
$.widget("custom.supersearch", $.ui.autocomplete, {
_create: function () {
this._super();
this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
},
_renderMenu: function (ul, items) {
if (items[0].value == undefined) {
$('#supersearch').removeClass('wait');
ul.html('');
} else {
var that = this,
currentCategory = "";
// Registrazione ricerca
searches.push(text);
searchButton
.removeClass('fa-search')
.addClass('fa-spinner fa-spin');
ul.addClass('ui-autocomplete-scrollable');
ul.css('z-index', '999');
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
},
_renderItem: function (ul, item) {
return $("<li>")
.append("<a href='" + item.link + "' title='Clicca per aprire'><b>" + item.value + "</b><br/>" + item.label + "</a>")
.appendTo(ul);
}
});
// Configurazione supersearch
var $super = $('#supersearch').supersearch({
minLength: 3,
select: function (event, ui) {
location.href = ui.item.link;
},
source: function (request, response) {
$.ajax({
url: globals.rootdir + '/ajax_search.php',
dataType: "json",
dataType: "JSON",
data: {
term: request.term
term: text,
},
complete: function (jqXHR) {
$('#supersearch').removeClass('wait');
},
success: function (data) {
if (data == null) {
response($.map(['a'], function (item) {
return false;
}));
} else {
response($.map(data, function (item) {
labels = (item.labels).toString();
labels = labels.replace('<br/>,', '<br/>');
// Fix per gestione risultati null
data = data ? data : [];
return {
label: labels,
category: item.category,
link: item.link,
value: item.title
}
}));
// Trasformazione risultati in formato leggibile
const results = data.map(function (result) {
return {
label: result.label ? result.label : '<h4>' + result.title + '</h4>' + result.labels
.join('').split('<br/>,').join('<br/>'),
group: result.category,
link: result.link,
value: result.title
}
});
// Rimozione ricerca in corso
searches.pop();
if (searches.length === 0) {
searchButton
.removeClass('fa-spinner fa-spin')
.addClass('fa-search');
}
update(results);
},
error: function (){
searchButton
.removeClass('fa-spinner fa-spin')
.addClass('fa-exclamation-triangle');
}
});
},
preventSubmit: true,
disableAutoSelect: true,
onSelect: function(item) {
window.location.href = item.link;
},
customize: function(input, inputRect, container, maxHeight) {
container.style.width = '600px';
},
render: function(item, currentValue){
const itemElement = document.createElement("div");
itemElement.innerHTML = item.label;
// <a href='" + item.link + "' title='Clicca per aprire'><b>" + item.value + "</b><br/>" + item.label + "</a>
return itemElement;
}
});
});

View File

@ -0,0 +1,308 @@
/*
* OpenSTAManager: il software gestionale open source per l'assistenza tecnica e la fatturazione
* Copyright (C) DevCode s.r.l.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
/**
* Restituisce filename ed estensione di un file indicato.
* @param path
* @returns [string, string]
*/
function getFilenameAndExtension(path) {
let filename_extension = path.replace(/^.*[\\\/]/, '');
let filename = filename_extension.substring(0, filename_extension.lastIndexOf('.'));
let ext = filename_extension.split('.').pop();
return [filename, ext];
}
/**
* Inizializza la gestione degli allegati.
* @param gestione
*/
function initGestioneAllegati(gestione) {
const dropzone_id = '#' + gestione.attr('id') + ' .dropzone';
const maxFilesize = gestione.data('max_filesize');
if ($(dropzone_id).length === 0) {
return;
}
let params = new URLSearchParams({
op: "aggiungi-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
}).toString();
let dragdrop = new Dropzone(dropzone_id, {
dictDefaultMessage: globals.translations.allegati.messaggio + ".<br>(" + globals.translations.allegati.maxFilesize.replace('_SIZE_', maxFilesize) + ")",
paramName: "file",
maxFilesize: maxFilesize, // MB
uploadMultiple: false,
parallelUploads: 2,
addRemoveLinks: false,
autoProcessQueue: true,
autoQueue: true,
url: globals.rootdir + "/actions.php?" + params,
init: function (file, xhr, formData) {
this.on("success", function (file) {
dragdrop.removeFile(file);
});
this.on("complete", function (file) {
// Ricarico solo quando ho finito
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
ricaricaAllegati(gestione);
}
});
}
});
}
/**
* Funzione per l'apertura della schermata di modifica per una categoria di allegati.
* @param gestione
* @param pulsanteModifica
*/
function modificaCategoriaAllegati(gestione, pulsanteModifica) {
const categoria = $(pulsanteModifica).parent().parent();
console.log(categoria)
const nome = categoria.find(".box-title");
nome.addClass('hidden');
$(pulsanteModifica).addClass('hidden');
const pulsanteSalva = categoria.find(".category-save");
const pulsanteAnnulla = categoria.find(".category-cancel");
const inputNome = categoria.find(".category-name");
pulsanteSalva.removeClass("hidden");
pulsanteAnnulla.removeClass("hidden");
inputNome.removeClass("hidden");
}
/**
* Funzione per salvare le modifiche effettuate su una categoria di allegati.
* @param gestione
* @param pulsanteSalva
*/
function salvaCategoriaAllegati(gestione, pulsanteSalva) {
const categoria = $(pulsanteSalva).parent().parent();
const nome = categoria.find(".box-title");
const inputNome = categoria.find(".category-name");
mostraCaricamentoAllegati(gestione);
$.ajax({
url: globals.rootdir + "/actions.php",
cache: false,
type: "POST",
data: {
op: "modifica-categoria-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
category: nome.text(),
name: inputNome.val(),
},
success: function (data) {
ricaricaAllegati(gestione);
},
error: function (gestione) {
ricaricaAllegati(gestione);
}
});
}
/**
* Funzione per caricare un nuovo allegato.
* @param gestione
*/
function aggiungiAllegato(gestione) {
const id = "#" + gestione.attr('id');
const form = $(id + " #upload-form");
form.ajaxSubmit({
url: globals.rootdir + "/actions.php",
data: data,
type: "post",
uploadProgress: function (event, position, total, percentComplete) {
$(id + " #upload").prop("disabled", true).html(percentComplete + "%").removeClass("btn-success").addClass("btn-info");
},
success: function (data) {
ricaricaAllegati(gestione);
},
error: function (data) {
alert(globals.translations.allegati.errore + ": " + data);
}
});
}
/**
* Funzione per mostrare il loader di caricamento per gli allegati.
* @param gestione
*/
function mostraCaricamentoAllegati(gestione) {
const id = "#" + gestione.attr('id');
localLoading($(id + " .panel-body"), true);
}
/**
* Funzione dedicata al caricamento dinamico degli allegati.
* @param gestione
*/
function ricaricaAllegati(gestione) {
const id = "#" + gestione.attr('id');
let params = new URLSearchParams({
op: "list_attachments",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
}).toString();
$(id).load(globals.rootdir + "/ajax.php?" + params, function () {
localLoading($(id + " .panel-body"), false);
const nuovoAllegato = $(id + " table tr").eq(-1).attr("id");
if (nuovoAllegato !== undefined) {
$("#" + nuovoAllegato).effect("highlight", {}, 1500);
}
});
}
/**
* Funzione per l'apertura della pagina di gestione dei dati dell'allegato.
* @param button
*/
function modificaAllegato(button) {
const gestione = $(button).closest(".gestione-allegati");
const allegato = $(button).closest("tr").data();
let params = new URLSearchParams({
op: "visualizza-modifica-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
id_allegato: allegato.id,
}).toString();
openModal(globals.translations.allegati.modifica, globals.rootdir + "/actions.php?" + params);
}
/**
* Funzione per gestire il download di un allegato.
* @param button
*/
function saggiungiAllegato(button) {
const gestione = $(button).closest(".gestione-allegati");
const allegato = $(button).closest("tr").data();
let params = new URLSearchParams({
op: "download-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
id: allegato.id,
filename: allegato.filename,
}).toString();
window.open(globals.rootdir + "/actions.php?" + params, "_blank")
}
/**
* Funzione per l'apertura dell'anteprima di visualizzazione allegato.
* @param button
*/
function visualizzaAllegato(button) {
const allegato = $(button).closest("tr").data();
let params = new URLSearchParams({
file_id: allegato.id,
}).toString();
openModal(allegato.nome + ' <small style="color:white"><i>(' + allegato.filename + ')</i></small>', globals.rootdir + "/view.php?" + params);
}
/**
* Funzione per la gestione della rimozione di un allegato specifico.
*
* @param button
*/
function rimuoviAllegato(button) {
const gestione = $(button).closest(".gestione-allegati");
const allegato = $(button).closest("tr").data();
swal({
title: globals.translations.allegati.elimina,
type: "warning",
showCancelButton: true,
confirmButtonText: globals.translations.allegati.procedi,
}).then(function () {
mostraCaricamentoAllegati(gestione);
// Parametri della richiesta AJAX
let params = new URLSearchParams({
op: "rimuovi-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
id_allegato: allegato.id,
filename: allegato.filename,
}).toString();
// Richiesta AJAX
$.ajax(globals.rootdir + "/actions.php?" + params)
.then(function () {
ricaricaAllegati(gestione);
});
}).catch(swal.noop);
}
function impostaCategorieAllegatiDisponibili(gestione, categorie) {
// Disabilitazione per rimozione input in aggiunta
return;
const id = "#" + gestione.attr('id');
const input = $("#modifica-allegato #categoria_allegato")[0];
autocomplete({
minLength: 0,
input: input,
emptyMsg: globals.translations.noResults,
fetch: function (text, update) {
text = text.toLowerCase();
const suggestions = categorie.filter(n => n.toLowerCase().startsWith(text));
// Trasformazione risultati in formato leggibile
const results = suggestions.map(function (result) {
return {
label: result,
value: result
}
});
update(results);
},
onSelect: function (item) {
input.value = item.label;
},
});
}

View File

@ -82,9 +82,11 @@ const JS = gulp.parallel(() => {
const vendor = [
'jquery/dist/jquery.js',
'autosize/dist/autosize.js',
'autocompleter/autocomplete.js',
'html5sortable/dist/html5sortable.js',
'bootstrap-colorpicker/dist/js/bootstrap-colorpicker.js',
'moment/moment.js',
'components-jqueryui/jquery-ui.js',
//'components-jqueryui/jquery-ui.js',
'datatables.net/js/jquery.dataTables.js',
'datatables.net-buttons/js/dataTables.buttons.js',
'datatables.net-buttons/js/buttons.colVis.js',

View File

@ -56,12 +56,34 @@ $source = array_clean(array_column($categories, 'category'));
echo '
<script>
var categorie = '.json_encode($source).';
// Auto-completamento categoria
$("#modifica-allegato #categoria_allegato").autocomplete({
source: '.json_encode($source).',
minLength: 0
}).focus(function() {
$(this).autocomplete("search", $(this).val())
$(document).ready(function () {
const input = $("#modifica-allegato #categoria_allegato")[0];
autocomplete({
minLength: 0,
input: input,
emptyMsg: globals.translations.noResults,
fetch: function (text, update) {
text = text.toLowerCase();
const suggestions = categorie.filter(n => n.toLowerCase().startsWith(text));
// Trasformazione risultati in formato leggibile
const results = suggestions.map(function (result) {
return {
label: result,
value: result
}
});
update(results);
},
onSelect: function (item) {
input.value = item.label;
},
});
});
</script>
<script>$(document).ready(init)</script>';

View File

@ -108,19 +108,28 @@ if (Auth::check()) {
'details' => tr('Dettagli'),
'loading' => tr('Caricamento'),
'waiting' => tr('Impossibile procedere'),
'waiting_msg' => tr('Prima di proseguire devi selezionare alcuni elementi!'),
'waitingMessage' => tr('Prima di proseguire devi selezionare alcuni elementi!'),
'hooksExecuting' => tr('Hooks in esecuzione'),
'hookExecuting' => tr('Hook "_NAME_" in esecuzione'),
'hookMultiple' => tr('Hai _NUM_ notifiche'),
'hookSingle' => tr('Hai 1 notifica'),
'hookNone' => tr('Nessuna notifica'),
'singleCalendar' => tr("E' presente un solo periodo!"),
'noResults' => tr("Nessun elemento trovato"),
];
foreach ($translations as $key => $value) {
echo '
'.$key.': "'.addslashes($value).'",';
}
echo '
allegati: {
messaggio: "'.tr("Clicca o trascina qui per caricare uno o più file").'",
maxFilesize: "'.tr('Max upload: _SIZE_ MB').'",
errore: "'.tr('Errore').'",
modifica: "'.tr('Modifica allegato').'",
elimina: "'.tr('Vuoi eliminare questo file?').'",
procedi: "'.tr('Procedi').'",
},
ajax: {
"missing": {
"title": "'.tr('Errore').'",
@ -292,7 +301,7 @@ if (Auth::check()) {
hotkeys("f1,f2,f3,f4", function(event, handler) {
switch (handler.key) {
case "f1":
case "f1":
event.preventDefault();
$("button[data-toggle]").first().trigger("click");
break;
@ -453,7 +462,8 @@ if (Auth::check()) {
<div class="input-group">
<input type="text" name="q" class="form-control" id="supersearch" placeholder="'.tr('Cerca').'..."/>
<span class="input-group-btn">
<button class="btn btn-flat" id="search-btn" name="search" type="submit" ><i class="fa fa-search"></i>
<button class="btn btn-flat" id="search-btn" name="search" type="submit">
<i class="fa fa-search"></i>
</button>
</span>

View File

@ -158,58 +158,58 @@ echo '
echo '
<script>
var emails = [];
var id_anagrafica = "'.$id_anagrafica.'";
var pec = "'.$smtp['pec']. '";
$(document).ready(function() {';
$(document).ready(function() {
// Auto-completamento destinatario
if (id_anagrafica) {
$(document).load(globals.rootdir + "/ajax_complete.php?module=Anagrafiche&op=get_email&id_anagrafica=" + id_anagrafica + (pec ? "&type=pec" : ""), function(response) {
emails = JSON.parse(response);
// Autocompletamento destinatario
if (!empty($id_anagrafica)) {
echo '
$(document).load(globals.rootdir + "/ajax_complete.php?module=Anagrafiche&op=get_email&id_anagrafica='.$id_anagrafica.(($smtp['pec']) ? '&type=pec' : '').'", function(response) {
emails = JSON.parse(response);
$(".destinatari").each(function(){
addAutoComplete(this);
});
$(".destinatari").each(function(){
addAutoComplete(this);
aggiungiDestinatario();
});
aggiungiDestinatario();
});';
}
echo '
});
function inviaEmail() {
if($("#email-form").parsley().validate() && confirm("Inviare e-mail?")) {
$("#email-form").submit();
const form = $("#email-form");
if (form.parsley().validate() && confirm("Inviare e-mail?")) {
form.submit();
}
}
function addAutoComplete(input){
$(input).autocomplete({
source: emails,
function addAutoComplete(input) {
autocomplete({
minLength: 0,
close: function() {
input: input,
emptyMsg: globals.translations.noResults,
fetch: function (text, update) {
text = text.toLowerCase();
const suggestions = emails.filter(n => n.value.toLowerCase().startsWith(text));
update(suggestions);
},
onSelect: function (item) {
input.value = item.value;
aggiungiDestinatario();
},
}).focus(function() {
$(this).autocomplete("search", $(this).val());
});
}
function aggiungiDestinatario() {
var last = $("#lista-destinatari input").last();
const last = $("#lista-destinatari input").last();
if (last.val()) {
cleanup_inputs();
const nuovaRiga = aggiungiContenuto("#lista-destinatari", "#template-destinatario", {"-id-": $("#lista-destinatari > div").length});
aggiungiContenuto("#lista-destinatari", "#template-destinatario", {"-id-": $("#lista-destinatari > div").length});
$(".destinatari").each(function(){
nuovaRiga.find(".destinatari").each(function(){
addAutoComplete(this);
});
restart_inputs();
}
}
</script>';

View File

@ -49,8 +49,8 @@ foreach ($rs as $r) {
$result['link'] = base_path().'/editor.php?id_module='.$link_id.'&id_record='.$r['id'];
$result['title'] = 'Preventivo '.$r['numero'];
if ($rs[$r]['data_accettazione'] == '0000-00-00') {
$result['title'] .= ' del '.Translator::dateToLocale($rs[$r]['data_accettazione']);
if ($r['data_accettazione'] == '0000-00-00') {
$result['title'] .= ' del '.Translator::dateToLocale($r['data_accettazione']);
}
$result['category'] = 'Preventivi';

View File

@ -3,6 +3,7 @@
"main": "gulpfile.js",
"dependencies": {
"admin-lte": "^2.4.0",
"autocompleter": "^6.1.1",
"autonumeric": "^4.6.0",
"autosize": "^3.0.21",
"bootstrap": "^3.3.7",
@ -22,6 +23,7 @@
"fullcalendar": "^3.4.0",
"geocomplete": "^1.7.0",
"hotkeys-js": "^3.8.5",
"html5sortable": "^0.13.2",
"inputmask": "^3.3.9",
"jquery": "^3.5.1",
"jquery-form": "^4.2.1",

View File

@ -21,6 +21,7 @@ namespace HTMLBuilder\Manager;
use Models\Setting;
use Models\Upload;
use Util\FileSystem;
/**
* Gestione allegati.
@ -47,11 +48,14 @@ class FileManager implements ManagerInterface
// ID del form
$attachment_id = 'attachments_'.$options['id_module'].'_'.$options['id_plugin'];
$upload_max_filesize = ini_get('upload_max_filesize');
$upload_max_filesize = substr($upload_max_filesize, 0, -1);
$dbo = database();
// Codice HTML
$result = '
<div id="'.$attachment_id.'" >';
<div class="gestione-allegati" id="'.$attachment_id.'" data-id_module="'.$options['id_module'].'" data-id_plugin="'.$options['id_plugin'].'" data-id_record="'.$options['id_record'].'" data-max_filesize="'.$upload_max_filesize.'">';
if (!empty($options['showpanel'])) {
$result .= '
@ -79,16 +83,20 @@ class FileManager implements ManagerInterface
<div class="box-header with-border">
<h3 class="box-title">'.(!empty($category) ? $category : tr('Generale')).'</h3>
{[ "type": "text", "class": "hide category-name", "value": "'.$category.'" ]}
{[ "type": "text", "class": "hidden category-name", "value": "'.$category.'" ]}
<div class="box-tools pull-right">';
if (!empty($category) && !in_array($category, ['Fattura Elettronica'])) {
$result .= '
<button type="button" class="btn btn-box-tool category-save hide">
<button type="button" class="btn btn-box-tool category-save hidden">
<i class="fa fa-check"></i>
</button>
<button type="button" class="btn btn-box-tool category-cancel hidden">
<i class="fa fa-close"></i>
</button>
<button type="button" class="btn btn-box-tool category-edit">
<i class="fa fa-edit"></i>
</button>';
@ -115,7 +123,7 @@ class FileManager implements ManagerInterface
$file = Upload::find($r['id']);
$result .= '
<tr id="row_'.$r['id'].'" >
<tr id="row_'.$r['id'].'" data-id="'.$r['id'].'" data-filename="'.$r['filename'].'">
<td align="left">';
if ($file->user && $file->user->photo) {
@ -133,38 +141,38 @@ class FileManager implements ManagerInterface
<i class="fa fa-external-link"></i> '.$r['name'].'
</a>
<small> ('.$file->extension.')'.((!empty($file->size)) ? ' ('.\Util\FileSystem::formatBytes($file->size).')' : '').' '.(((setting('Logo stampe') == $r['filename']) || (setting('Filigrana stampe') == $r['filename'])) ? '<i class="fa fa-file-text-o"></i>' : '').'</small>'.'
<small> ('.$file->extension.')'.((!empty($file->size)) ? ' ('. FileSystem::formatBytes($file->size).')' : '').' '.(((setting('Logo stampe') == $r['filename']) || (setting('Filigrana stampe') == $r['filename'])) ? '<i class="fa fa-file-text-o"></i>' : '').'</small>'.'
</td>
<td>'.\Translator::timestampToLocale($r['created_at']).'</td>
<td>'.timestampFormat($r['created_at']).'</td>
<td class="text-center">
<a class="btn btn-xs btn-primary" href="'.base_path().'/actions.php?id_module='.$options['id_module'].'&op=download-allegato&id='.$r['id'].'&filename='.$r['filename'].'" target="_blank">
<button type="button" class="btn btn-xs btn-primary" onclick="saggiungiAllegato(this)">
<i class="fa fa-download"></i>
</a>';
</button>';
// Anteprime supportate dal browser
if ($file->hasPreview()) {
$result .= '
<button class="btn btn-xs btn-info" type="button" data-title="'.prepareToField($r['name']).' <small style=\'color:white\'><i>('.$r['filename'].')</i></small>" data-href="'.base_path().'/view.php?file_id='.$r['id'].'">
<button type="button" class="btn btn-xs btn-info" onclick="visualizzaAllegato(this)">
<i class="fa fa-eye"></i>
</button>';
} else {
$result .= '
<button class="btn btn-xs btn-default disabled" title="'.tr('Anteprima file non disponibile').'" disabled>
<button type="button" class="btn btn-xs btn-default disabled" title="'.tr('Anteprima file non disponibile').'" disabled>
<i class="fa fa-eye"></i>
</button>';
}
if (!$options['readonly']) {
$result .= '
<button type="button" class="btn btn-xs btn-warning" data-href="'.base_path().'/actions.php?op=visualizza-modifica-allegato&id_module='.$options['id_module'].'&id_allegato='.$r['id'].'" data-title="'.tr('Modifica allegato').'">
<button type="button" class="btn btn-xs btn-warning" onclick="modificaAllegato(this)">
<i class="fa fa-edit"></i>
</button>
<a class="btn btn-xs btn-danger ask" data-backto="record-edit" data-msg="'.tr('Vuoi eliminare questo file?').'" data-op="rimuovi-allegato" data-filename="'.$r['filename'].'" data-id_record="'.$r['id_record'].'" data-id_plugin="'.$options['id_plugin'].'" data-before="show_'.$attachment_id.'" data-callback="reload_'.$attachment_id.'">
<button type="button" class="btn btn-xs btn-danger" onclick="rimuoviAllegato(this)">
<i class="fa fa-trash"></i>
</a>';
</button>';
}
$result .= '
@ -214,147 +222,42 @@ class FileManager implements ManagerInterface
$source = array_clean(array_column($categories, 'category'));
$upload_max_filesize = ini_get('upload_max_filesize');
$upload_max_filesize = substr($upload_max_filesize, 0, -1);
$result .= '
<script>$(document).ready(init)</script>
<script>
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
$(document).ready(function() {
let dropzone_id = "#'.$attachment_id.' .dropzone";
if ($(dropzone_id).length == 0) {
return;
}
const container = $("#'.$attachment_id.'");
let dragdrop = new Dropzone(dropzone_id, {
dictDefaultMessage: "'.tr('Clicca o trascina qui per caricare uno o più file').'.<br>('.tr('Max upload: _SIZE_', [
'_SIZE_' => $upload_max_filesize.' MB',
]).')",
paramName: "file",
maxFilesize: '.$upload_max_filesize.', // MB
uploadMultiple: false,
parallelUploads: 2,
addRemoveLinks: false,
autoProcessQueue: true,
autoQueue: true,
url: "'.base_path().'/actions.php?op=aggiungi-allegato&id_module='.$options['id_module'].'&id_record='.$options['id_record'].'&id_plugin='.$options['id_plugin'].'",
init: function (file, xhr, formData) {
this.on("success", function (file) {
dragdrop.removeFile(file);
});
this.on("complete", function (file) {
// Ricarico solo quando ho finito
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
reload_'.$attachment_id.'();
}
});
}
});
// Modifica categoria
$("#'.$attachment_id.' .category-edit").click(function() {
var nome = $(this).parent().parent().find(".box-title");
var save_button = $(this).parent().find(".category-save");
var input = $(this).parent().parent().find(".category-name");
nome.hide();
$(this).hide();
input.removeClass("hide");
save_button.removeClass("hide");
});
$("#'.$attachment_id.' .category-save").click(function() {
var nome = $(this).parent().parent().find(".box-title");
var input = $(this).parent().parent().find(".category-name");
show_'.$attachment_id.'();
$.ajax({
url: globals.rootdir + "/actions.php",
cache: false,
type: "POST",
data: {
id_module: "'.$options['id_module'].'",
id_plugin: "'.$options['id_plugin'].'",
id_record: "'.$options['id_record'].'",
op: "modifica-categoria-allegato",
category: nome.text(),
name: input.val(),
},
success: function(data) {
reload_'.$attachment_id.'();
},
error: function(data) {
reload_'.$attachment_id.'();
}
});
});
function getFilenameAndExtension(path) {
let filename_extension = path.replace(/^.*[\\\/]/, \'\');
let filename = filename_extension.substring(0, filename_extension.lastIndexOf(\'.\'));
let ext = filename_extension.split(\'.\').pop();
return [filename, ext];
}
// Auto-completamento categoria
$("#'.$attachment_id.' #categoria_allegato").autocomplete({
source: '.json_encode($source).',
minLength: 0
}).focus(function() {
$(this).autocomplete("search", $(this).val())
});
var data = {
op: "aggiungi-allegato",
id_module: "'.$options['id_module'].'",
id_plugin: "'.$options['id_plugin'].'",
id_record: "'.$options['id_record'].'",
};
// Upload
$("#'.$attachment_id.' #upload").click(function(){
$form = $("#'.$attachment_id.' #upload-form");
$form.ajaxSubmit({
url: globals.rootdir + "/actions.php",
data: data,
type: "post",
uploadProgress: function(event, position, total, percentComplete) {
$("#'.$attachment_id.' #upload").prop("disabled", true).html(percentComplete + "%").removeClass("btn-success").addClass("btn-info");
},
success: function(data){
reload_'.$attachment_id.'();
},
error: function(data) {
alert("'.tr('Errore').': " + data);
}
});
});
initGestioneAllegati(container);
impostaCategorieAllegatiDisponibili(container, '.json_encode($source).');
});
function show_'.$attachment_id.'() {
localLoading($("#'.$attachment_id.' .panel-body"), true);
}
// Modifica categoria
$("#'.$attachment_id.' .category-edit").click(function() {
const container = $(this).closest(".gestione-allegati");
function reload_'.$attachment_id.'() {
$("#'.$attachment_id.'").load(globals.rootdir + "/ajax.php?op=list_attachments&id_module='.$options['id_module'].'&id_record='.$options['id_record'].'&id_plugin='.$options['id_plugin'].'", function() {
localLoading($("#'.$attachment_id.' .panel-body"), false);
modificaCategoriaAllegati(container, this);
});
var id = $("#'.$attachment_id.' table tr").eq(-1).attr("id");
if (id !== undefined) {
$("#" + id).effect("highlight", {}, 1500);
}
});
}
$("#'.$attachment_id.' .category-save").click(function() {
const container = $(this).closest(".gestione-allegati");
salvaCategoriaAllegati(container, this);
});
$("#'.$attachment_id.' .category-cancel").click(function() {
const container = $(this).closest(".gestione-allegati");
ricaricaAllegati(gestione);
});
// Upload
$("#'.$attachment_id.' #upload").click(function(){
const container = $(this).closest(".gestione-allegati");
aggiungiAllegato(container);
});
</script>';
return $result;