jquery.galleryManager.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. (function ($) {
  2. 'use strict';
  3. var galleryDefaults = {
  4. csrfToken: $('meta[name=csrf-token]').attr('content'),
  5. csrfTokenName: $('meta[name=csrf-param]').attr('content'),
  6. nameLabel: 'Name',
  7. descriptionLabel: 'Description',
  8. hasName: true,
  9. hasDesc: true,
  10. uploadUrl: '',
  11. deleteUrl: '',
  12. updateUrl: '',
  13. arrangeUrl: '',
  14. photos: []
  15. };
  16. function galleryManager(el, options) {
  17. //Extending options:
  18. var opts = $.extend({}, galleryDefaults, options);
  19. //code
  20. var csrfParams = opts.csrfToken ? '&' + opts.csrfTokenName + '=' + opts.csrfToken : '';
  21. var photos = {}; // photo elements by id
  22. var $gallery = $(el);
  23. if (!opts.hasName) {
  24. if (!opts.hasDesc) {
  25. $gallery.addClass('no-name-no-desc');
  26. $('.edit_selected', $gallery).hide();
  27. }
  28. else $gallery.addClass('no-name');
  29. } else if (!opts.hasDesc)
  30. $gallery.addClass('no-desc');
  31. var $sorter = $('.sorter', $gallery);
  32. var $images = $('.images', $sorter);
  33. var $editorModal = $('.editor-modal', $gallery);
  34. var $progressOverlay = $('.progress-overlay', $gallery);
  35. var $uploadProgress = $('.upload-progress', $progressOverlay);
  36. var $editorForm = $('.form', $editorModal);
  37. function htmlEscape(str) {
  38. return String(str)
  39. .replace(/&/g, '&')
  40. .replace(/"/g, '"')
  41. .replace(/'/g, ''')
  42. .replace(/</g, '&lt;')
  43. .replace(/>/g, '&gt;');
  44. }
  45. function createEditorElement(id, src, name, description) {
  46. var html = '<div class="photo-editor row">' +
  47. '<div class="col-xs-4">' +
  48. '<img src="' + htmlEscape(src) + '" style="max-width:100%;">' +
  49. '</div>' +
  50. '<div class="col-xs-8">' +
  51. (opts.hasName
  52. ?
  53. '<div class="form-group">' +
  54. '<label class="control-label" for="photo_name_' + id + '">' + opts.nameLabel + ':</label>' +
  55. '<input class="form-control" type="text" name="photo[' + id + '][name]" class="input-xlarge" value="' + htmlEscape(name) + '" id="photo_name_' + id + '"/>' +
  56. '</div>' : '') +
  57. (opts.hasDesc
  58. ?
  59. '<div class="form-group">' +
  60. '<label class="control-label" for="photo_description_' + id + '">' + opts.descriptionLabel + ':</label>' +
  61. '<textarea class="form-control" name="photo[' + id + '][description]" rows="3" cols="40" class="input-xlarge" id="photo_description_' + id + '">' + htmlEscape(description) + '</textarea>' +
  62. '</div>' : '') +
  63. '</div>' +
  64. '</div>';
  65. return $(html);
  66. }
  67. var photoTemplate = '<div class="photo">' + '<div class="image-preview"><img src=""/></div><div class="caption">';
  68. if (opts.hasName) {
  69. photoTemplate += '<h5></h5>';
  70. }
  71. if (opts.hasDesc) {
  72. photoTemplate += '<p></p>';
  73. }
  74. photoTemplate += '</div><div class="actions">';
  75. if (opts.hasName || opts.hasDesc) {
  76. photoTemplate += '<span class="editPhoto btn btn-primary btn-xs"><i class="fas fa-edit"></i></span> ';
  77. }
  78. photoTemplate += '<span class="deletePhoto btn btn-danger btn-xs"><i class="fas fa-trash"></i></span>' +
  79. '</div><input type="checkbox" class="photo-select"/></div>';
  80. function addPhoto(id, src, name, description, rank) {
  81. var photo = $(photoTemplate);
  82. photos[id] = photo;
  83. photo.data('id', id);
  84. photo.data('rank', rank);
  85. $('img', photo).attr('src', src);
  86. if (opts.hasName){
  87. // name = '';
  88. $('.caption h5', photo).text(name);
  89. }
  90. if (opts.hasDesc){
  91. $('.caption p', photo).text(description);
  92. }
  93. $images.append(photo);
  94. return photo;
  95. }
  96. function editPhotos(ids) {
  97. var l = ids.length;
  98. var form = $editorForm.empty();
  99. for (var i = 0; i < l; i++) {
  100. var id = ids[i];
  101. var photo = photos[id],
  102. src = $('img', photo).attr('src'),
  103. name = $('.caption h5', photo).text(),
  104. description = $('.caption p', photo).text();
  105. form.append(createEditorElement(id, src, name, description));
  106. }
  107. if (l > 0){
  108. $editorModal.modal('show');
  109. }
  110. }
  111. function removePhotos(ids) {
  112. $.ajax({
  113. type: 'POST',
  114. url: opts.deleteUrl,
  115. data: 'id[]=' + ids.join('&id[]=') + csrfParams,
  116. success: function (t) {
  117. if (t == 'OK') {
  118. for (var i = 0, l = ids.length; i < l; i++) {
  119. photos[ids[i]].remove();
  120. delete photos[ids[i]];
  121. }
  122. } else {
  123. alert(t);
  124. }
  125. }
  126. });
  127. }
  128. function deleteClick(e) {
  129. e.preventDefault();
  130. var photo = $(this).closest('.photo');
  131. var id = photo.data('id');
  132. // here can be question to confirm delete
  133. // if (!confirm(deleteConfirmation)) return false;
  134. removePhotos([id]);
  135. return false;
  136. }
  137. function editClick(e) {
  138. e.preventDefault();
  139. var photo = $(this).closest('.photo');
  140. var id = photo.data('id');
  141. editPhotos([id]);
  142. return false;
  143. }
  144. function updateButtons() {
  145. var selectedCount = $('.photo.selected', $sorter).length;
  146. $('.select_all', $gallery).prop('checked', $('.photo', $sorter).length == selectedCount);
  147. if (selectedCount == 0) {
  148. $('.edit_selected, .remove_selected', $gallery).addClass('disabled');
  149. } else {
  150. $('.edit_selected, .remove_selected', $gallery).removeClass('disabled');
  151. }
  152. }
  153. function selectChanged() {
  154. var $this = $(this);
  155. if ($this.is(':checked'))
  156. $this.closest('.photo').addClass('selected');
  157. else
  158. $this.closest('.photo').removeClass('selected');
  159. updateButtons();
  160. }
  161. function sending(xhr, fd, fixer){
  162. console.log(fixer);
  163. if( fixer.CurUploaded <= fixer.MaxUploaded ){
  164. xhr.send(fd);
  165. fixer.CurUploaded++;
  166. }else{
  167. setTimeout( sending,5000, xhr, fd, fixer);
  168. }
  169. }
  170. $images
  171. .on('click', '.photo .deletePhoto', deleteClick)
  172. .on('click', '.photo .editPhoto', editClick)
  173. .on('click', '.photo .photo-select', selectChanged);
  174. $('.images', $sorter).sortable({tolerance: "pointer"}).disableSelection().bind("sortstop", function () {
  175. var data = [];
  176. $('.photo', $sorter).each(function () {
  177. var t = $(this);
  178. data.push('order[' + t.data('id') + ']=' + t.data('rank'));
  179. });
  180. $.ajax({
  181. type: 'POST',
  182. url: opts.arrangeUrl,
  183. data: data.join('&') + csrfParams,
  184. dataType: "json"
  185. }).done(function (data) {
  186. for (var id in data[id]) {
  187. photos[id].data('rank', data[id]);
  188. }
  189. // order saved!
  190. // we can inform user that order saved
  191. });
  192. });
  193. if (window.FormData !== undefined) { // if XHR2 available
  194. var uploadFileName = $('.afile', $gallery).attr('name');
  195. var multiUpload = function (files) {
  196. if (files.length == 0) return;
  197. $progressOverlay.show();
  198. $uploadProgress.css('width', '5%');
  199. var filesCount = files.length;
  200. var uploadedCount = 0;
  201. var ids = [];
  202. var poper = new Map();
  203. var fixer = {MaxUploaded:3, CurUploaded:0, MaxScreen:12};
  204. for (var i = 0; i < filesCount; i++) {
  205. var fd = new FormData();
  206. fd.append(uploadFileName, files[i]);
  207. if (opts.csrfToken) {
  208. fd.append(opts.csrfTokenName, opts.csrfToken);
  209. }
  210. let xhr = new XMLHttpRequest();
  211. xhr.open('POST', opts.uploadUrl, true);
  212. xhr.onload = function () {
  213. uploadedCount++;
  214. fixer.CurUploaded--;
  215. if (this.status == 200) {
  216. var resp = JSON.parse(this.response);
  217. addPhoto(resp['id'], resp['preview'], '', resp['description'], resp['rank']);
  218. ids.push(resp['id']);
  219. var poperm = poper.get(resp['name']);
  220. poperm.toast('hide');
  221. setTimeout(() => {
  222. poperm.remove();
  223. },2000, poperm);
  224. } else {
  225. // exception !!!
  226. }
  227. $uploadProgress.css('width', '' + (5 + 95 * uploadedCount / filesCount) + '%');
  228. if (uploadedCount === filesCount) {
  229. $uploadProgress.css('width', '100%');
  230. $progressOverlay.hide();
  231. if (opts.hasName || opts.hasDesc) editPhotos(ids);
  232. }
  233. };
  234. var templ = $("#noty0").clone();
  235. var fname = files[i].name;
  236. xhr.nn = fname;
  237. $(xhr.upload).bind('progress', function (e) {
  238. // xhr.upload.addEventListener("progress", (event) => {
  239. let percent = Math.round(event.loaded *100/ event.total);
  240. // console.log(xhr.nn);
  241. // console.log(xhr);
  242. // console.log(percent);
  243. var el = poper.get(xhr.nn);
  244. el.find(".progress-bar").css("width", percent+"%");
  245. if( percent > 98 ){
  246. el.find(".text-muted").text("Обработка");
  247. }
  248. });
  249. templ.find(".toast-body").text(files[i].name);
  250. $("#notycont").prepend(templ);
  251. templ.toast('show');
  252. poper.set(files[i].name, templ);
  253. console.log(fixer);
  254. if( fixer.CurUploaded >= fixer.MaxUploaded ){
  255. console.log("pause");
  256. setTimeout( sending,5000, xhr, fd, fixer);
  257. }else{
  258. fixer.CurUploaded ++;
  259. xhr.send(fd);
  260. }
  261. }
  262. };
  263. (function () { // add drag and drop
  264. var el = $gallery[0];
  265. var isOver = false;
  266. var lastIsOver = false;
  267. setInterval(function () {
  268. if (isOver != lastIsOver) {
  269. if (isOver) el.classList.add('over');
  270. else el.classList.remove('over');
  271. lastIsOver = isOver
  272. }
  273. }, 30);
  274. function handleDragOver(e) {
  275. e.preventDefault();
  276. isOver = true;
  277. return false;
  278. }
  279. function handleDragLeave() {
  280. isOver = false;
  281. return false;
  282. }
  283. function handleDrop(e) {
  284. e.preventDefault();
  285. e.stopPropagation();
  286. var files = e.dataTransfer.files;
  287. multiUpload(files);
  288. isOver = false;
  289. return false;
  290. }
  291. function handleDragEnd() {
  292. isOver = false;
  293. }
  294. el.addEventListener('dragover', handleDragOver, false);
  295. el.addEventListener('dragleave', handleDragLeave, false);
  296. el.addEventListener('drop', handleDrop, false);
  297. el.addEventListener('dragend', handleDragEnd, false);
  298. })();
  299. $('.afile', $gallery).attr('multiple', 'true').on('change', function (e) {
  300. e.preventDefault();
  301. multiUpload(this.files);
  302. $(this).val(null);
  303. });
  304. } else {
  305. $('.afile', $gallery).on('change', function (e) {
  306. e.preventDefault();
  307. var ids = [];
  308. $progressOverlay.show();
  309. $uploadProgress.css('width', '5%');
  310. var data = {};
  311. if (opts.csrfToken)
  312. data[opts.csrfTokenName] = opts.csrfToken;
  313. $.ajax({
  314. type: 'POST',
  315. url: opts.uploadUrl,
  316. data: data,
  317. files: $(this),
  318. iframe: true,
  319. processData: false,
  320. dataType: "json"
  321. }).done(function (resp) {
  322. addPhoto(resp['id'], resp['preview'], '', resp['description'], resp['rank']);
  323. ids.push(resp['id']);
  324. $uploadProgress.css('width', '100%');
  325. $progressOverlay.hide();
  326. if (opts.hasName || opts.hasDesc) editPhotos(ids);
  327. });
  328. });
  329. }
  330. $('.save-changes', $editorModal).click(function (e) {
  331. e.preventDefault();
  332. $.post(opts.updateUrl, $('input, textarea', $editorForm).serialize() + csrfParams, function (data) {
  333. var count = data.length;
  334. for (var key = 0; key < count; key++) {
  335. var p = data[key];
  336. var photo = photos[p.id];
  337. $('img', photo).attr('src', p['src']);
  338. if (opts.hasName)
  339. $('.caption h5', photo).text(p['name']);
  340. if (opts.hasDesc)
  341. $('.caption p', photo).text(p['description']);
  342. }
  343. $editorModal.modal('hide');
  344. //deselect all items after editing
  345. $('.photo.selected', $sorter).each(function () {
  346. $('.photo-select', this).prop('checked', false)
  347. }).removeClass('selected');
  348. $('.select_all', $gallery).prop('checked', false);
  349. updateButtons();
  350. }, 'json');
  351. });
  352. $('.edit_selected', $gallery).click(function (e) {
  353. e.preventDefault();
  354. var ids = [];
  355. $('.photo.selected', $sorter).each(function () {
  356. ids.push($(this).data('id'));
  357. });
  358. editPhotos(ids);
  359. return false;
  360. });
  361. $('.remove_selected', $gallery).click(function (e) {
  362. e.preventDefault();
  363. var ids = [];
  364. $('.photo.selected', $sorter).each(function () {
  365. ids.push($(this).data('id'));
  366. });
  367. removePhotos(ids);
  368. });
  369. $('.select_all', $gallery).change(function () {
  370. if ($(this).prop('checked')) {
  371. $('.photo', $sorter).each(function () {
  372. $('.photo-select', this).prop('checked', true)
  373. }).addClass('selected');
  374. } else {
  375. $('.photo.selected', $sorter).each(function () {
  376. $('.photo-select', this).prop('checked', false)
  377. }).removeClass('selected');
  378. }
  379. updateButtons();
  380. });
  381. for (var i = 0, l = opts.photos.length; i < l; i++) {
  382. var resp = opts.photos[i];
  383. addPhoto(resp['id'], resp['preview'], resp['name'], resp['description'], resp['rank']);
  384. }
  385. }
  386. // The actual plugin
  387. $.fn.galleryManager = function (options) {
  388. if (this.length) {
  389. this.each(function () {
  390. galleryManager(this, options);
  391. });
  392. }
  393. };
  394. })(jQuery);