Przeglądaj źródła

added upload multiple files, fixed upload code

Piotr Labudda 8 lat temu
rodzic
commit
517b65deab
3 zmienionych plików z 609 dodań i 449 usunięć
  1. 46 449
      SE/se-lib/TableAjax.php
  2. 392 0
      SE/se-lib/TableAjax.php.files.js
  3. 171 0
      SE/se-lib/TableAjax.php.upload.js

+ 46 - 449
SE/se-lib/TableAjax.php

@@ -4119,137 +4119,9 @@ function <?php echo $jsToogleFiltrProcesuFunctionName; ?>(n) {
 }
 		</script>
 		<?php
-		echo UI::h('script', [], "
-			(function (global) {
-				var p5TA_dragOverChecker = function () {
-					var _node = null
-					var _pk = null
-					var _ns = null
-					var _overlayNode = null
-					var markNodeHoverOn = function (node, pk, ns) {
-						if (!_overlayNode) {
-							_overlayNode = document.createElement('div')
-							_overlayNode.style.backgroundColor = '#03a9f4'
-							_overlayNode.style.opacity = '0.2'
-							_overlayNode.style.position = 'absolute'
-							document.body.appendChild(_overlayNode)
-							_overlayNode.appendChild(document.createTextNode('drag file...'))
-						}
-						var bbox = node.getBoundingClientRect()
-						_overlayNode.style.top = ((window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0) + bbox.top) + 'px'
-						_overlayNode.style.left = '0px' // bbox.left + 'px'
-						_overlayNode.style.width = '100%' // bbox.width + 'px'
-						_overlayNode.style.height = bbox.height + 'px'
-						_overlayNode.setAttribute('ondrop', 'p5TA_onDrop(event, \''+pk+'\', \''+ns+'\')')
-						_overlayNode.setAttribute('ondragover', 'p5TA_overlay_onDragOver(event, this, \''+pk+'\', \''+ns+'\')')
-					}
-					var markNodeHoverOff = function () {
-						if (_overlayNode && _overlayNode.parentNode) _overlayNode.parentNode.removeChild(_overlayNode)
-						_overlayNode = null
-					}
-					var _removeOverlayTimeoutId = null
-					return {
-						update: function (node, pk, ns) {
-							_ns = ns
-							if (null !== _pk && _pk !== pk) {
-								markNodeHoverOff()
-							}
-							if (_pk !== pk) {
-								if (null !== node) markNodeHoverOn(node, pk, ns)
-							}
-							_pk = pk
-							if (null !== node) _node = node
-							if (_removeOverlayTimeoutId) clearTimeout(_removeOverlayTimeoutId)
-							_removeOverlayTimeoutId = setTimeout(markNodeHoverOff, 1000)
-						},
-						removeOverlay: function () {
-							markNodeHoverOff()
-						},
-					}
-				}
-				var this__dragOverChecker = p5TA_dragOverChecker()
-
-				function p5TA_uploadFiles(files, ns, pk) {
-					var formData = new FormData()
-					formData.append('namespace', ns)
-					formData.append('primaryKey', pk)
-					files.forEach(function (file, idx) {
-						formData.append('file' + idx, file)
-					})
-
-					window.fetch('index.php?_route=ViewTableAjax&_task=uploadFilesAjax', {
-						method: 'POST',
-						body: formData,
-						credentials: 'same-origin',
-					}).then(function checkStatus(response) {
-						if (response.status >= 200 && response.status < 300) {
-							return response
-						} else {
-							var error = new Error(response.statusText)
-							error.response = response
-							throw error
-						}
-					}).then(function (response) {
-						return response.json()
-					}).then(function (response) {
-						p5UI__notifyAjaxCallback(response)
-					}).catch(function(error) {
-						p5UI__notifyAjaxCallback({ type: 'error', msg: error })
-					})
-				}
-
-				function p5TA_onDrop(e, pk, ns) {
-					e.preventDefault();
-
-					// If dropped items aren't files, reject them
-					var dt = e.dataTransfer;
-					var files = []
-					if (dt.items) { // Use DataTransferItemList interface to access the file(s)
-						for (var i = 0; i < dt.items.length; i++) {
-							if (dt.items[i].kind == 'file') {
-								var file = dt.items[i].getAsFile();
-								files.push(file)
-							}
-						}
-					} else { // Use DataTransfer interface to access the file(s)
-						for (var i=0; i < dt.files.length; i++) {
-							files.push(dt.files[i])
-						}
-					}
-					if (!files) {
-						p5UI__notifyAjaxCallback({
-							type: 'info',
-							msg: 'brak plików',
-						})
-						return false
-					}
-					p5TA_uploadFiles(files, ns, pk);
-					this__dragOverChecker.removeOverlay()
-				}
-				function p5TA_onDragOver(e, n, pk, ns) {
-					e.preventDefault();
-					this__dragOverChecker.update(n, pk, ns)
-				}
-				function p5TA_overlay_onDragOver(e, n, pk, ns) {
-					e.preventDefault();
-					this__dragOverChecker.update(null, pk, ns)
-				}
-				function p5TA_onDragEnd(e, n, pk, ns) {
-					var dt = e.dataTransfer;
-					if (dt.items) { // Use DataTransferItemList interface to remove the drag data
-						for (var i = 0; i < dt.items.length; i++) {
-							dt.items.remove(i);
-						}
-					} else { // Use DataTransfer interface to remove the drag data
-						e.dataTransfer.clearData();
-					}
-				}
-				global.p5TA_onDrop = p5TA_onDrop
-				global.p5TA_onDragOver = p5TA_onDragOver
-				global.p5TA_onDragEnd = p5TA_onDragEnd
-				global.p5TA_overlay_onDragOver = p5TA_overlay_onDragOver
-			})(window);
-		");
+		UI::inlineJS(__FILE__ . '.upload.js', [
+			'URL_UPLOAD_FILES_AJAX' => "index.php?_route=ViewTableAjax&_task=uploadFilesAjax",
+		]);
 		UI::setTitle($this->_acl->getRawLabel(100) . " - " . UI::getTitle());
 		$out = ob_get_contents();
 		ob_end_clean();
@@ -5486,17 +5358,18 @@ jQuery(document).ready(function(){
 	private function sendAjaxFiles($id, $args) {
 		header("Content-type: text/plain");
 		$DBG = ('1' == V::get('DBG', '', $_REQUEST));
+		$acl = $this->_acl;
 
-		$dbID = $this->_acl->getDB();
+		$dbID = $acl->getDB();
 		$db = DB::getDB($dbID);
 		if (!$db) throw new HttpException("", 406);
 
-		$record = $this->_acl->buildQuery([])->getItem($id);
+		$record = $acl->buildQuery([])->getItem($id);
 		if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
 
-		if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
+		if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
 
-		$tblName = $this->_acl->getName();
+		$tblName = $acl->getName();
 		$confTblName = "{$tblName}_COLUMN";
 		$folderConfAll = FoldersConfig::getRawData();
 		if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych", 404);
@@ -5554,13 +5427,14 @@ jQuery(document).ready(function(){
 
 		$fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
 		$fileIndex = V::get($fileIndexField, $record['ID'], $record);
+		$namespace = $acl->getNamespace();
 		echo UI::h('div', [ 'class' => "container" ], [
 			UI::h('h4', [ 'style' => "margin:20px 0 3px 0;" ], [
 				"Pliki w katalogu ",
 				($sharePoint)
 					?	UI::h('a', [ 'href' => $sharePoint ], [
 							UI::h('span', [ 'class' => "glyphicon glyphicon-folder-open" ]),
-							UI::h('code', [], $mainFolder),
+							UI::h('code', [ 'style' => "margin-left:6px" ], $mainFolder),
 						])
 					:	UI::h('code', [], $mainFolder),
 				UI::h('span', [ 'class' => "pull-right valign-btns-bottom" ], [
@@ -5611,6 +5485,7 @@ jQuery(document).ready(function(){
 					UI::h('ul', [ 'id' => "FILES_TAB_{$this->_htmlID}", 'class' => "nav nav-tabs", 'style' => "margin:0;"], [
 						UI::h('li', [ 'class' => "active" ], [ UI::h('a', [ 'href' => "#local", 'data-toggle' => "local" ], "Wybierz plik lokalny"), ]),
 						UI::h('li', [], [ UI::h('a', [ 'href' => "#scan", 'data-toggle' => "scan" ], "Wybierz plik ze skanów" ), ]),
+						UI::h('li', [], [ UI::h('a', [ 'href' => "#multiple", 'data-toggle' => "multiple" ], "Wgraj wiele plików" ), ]),
 					]),
 					UI::h('div', [ 'id' => "myTabContent", 'class' => "tab-content" ], [
 						UI::h('div', [ 'class' => "tab-pane fade in active", 'id' => "local", 'style' => "text-align: center;" ], [
@@ -5621,6 +5496,19 @@ jQuery(document).ready(function(){
 								'ondragend' => "this.style.backgroundColor='#eee'",
 							]),
 						]),
+						UI::h('div', [ 'class' => "tab-pane fade", 'id' => "multiple" ], [
+							UI::h('div', [
+								'id' => "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
+								'style' => "width:86%; margin:10px auto; padding:40px 100px; background-color:#eee; border-radius:4px; text-align:center",
+								// 'ondrop' => "p5TA_onDrop(event, '{$id}', '{$namespace}')",
+								'ondrop' => "p5TAFiles_onDropMultiple(event, this, '{$id}', '{$namespace}')",
+								'ondragover' => "p5TAFiles_onDragOverMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#D9EDF7'",
+								'ondragleave' => "p5TAFiles_onDragLeaveMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#eee'",
+								'ondragend' => "p5TAFiles_onDragEndMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#eee'",
+							], [
+								"Upuść pliki tutaj",
+							]),
+						]),
 						UI::h('div', [ 'class' => "tab-pane fade", 'id' => "scan" ], [
 							(empty($skanyFiles))
 							?	UI::h('div', [ 'class' => "alert alert-info" ], [
@@ -5735,321 +5623,30 @@ jQuery(document).ready(function(){
 				]),
 		]);
 		$className = __CLASS__;
-		$jsArgs = [
-			'CAN_WRITE_RECORD' => (int)$this->_acl->canWriteRecord($record),
-			'SHARE_POINT' => $sharePoint,
+		UI::inlineJS(__FILE__ . '.files.js', [
+			'UNIQ_HASH' => $this->_htmlID,
+			'FUNCTION_FILE_LIST_UPDATE_AJAX' => "fileListUpdateAjax{$this->_htmlID}", // fileListUpdateAjax
+			'FUNCTION_FILE_LIST_UPDATE' => "fileListUpdate{$this->_htmlID}", // fileListUpdate
+			'FUNCTION_CONN_TBL_LIST_UPDATE_AJAX' => "connTblListUpdateAjax{$this->_htmlID}", // connTblListUpdateAjax
+			'FUNCTION_CONN_TBL_LIST_UPDATE' => "connTblListUpdate{$this->_htmlID}", // connTblListUpdate
+			'FUNCTION_FILE_LIST_ACTIONS' => "fileListActions{$this->_htmlID}", // fileListActions
+			'CONN_TABLES' => $this->getConnectedTables(),
+			'NODE_ID_FILES_FRM' => "FILES_FRM_{$this->_htmlID}",
+			'NODE_ID_FRM_UPLOAD_RESULTS' => "FRM_UPLOAD_RESULTS_{$this->_htmlID}",
+			'NODE_ID_FILES_TAB' => "FILES_TAB_{$this->_htmlID}",
+			'NODE_ID_FILES_LIST' => "FILES_LIST_{$this->_htmlID}",
+			'NODE_ID_FILES_CONN_TBLS' => "FILES_CONN_TBLS_{$this->_htmlID}",
+			'NODE_ID_FILES_LIST_ACTIONS' => "FILES_LIST_ACTIONS_{$this->_htmlID}",
+			'NODE_ID_FILES_MULTIPLE_UPLOAD' => "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
 			'URL_FILE_LIST_UPDATE_AJAX' => "index-ajax.php?_zasobID={$this->_zasobID};&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_LIST&ID={$record['ID']}",
-			'URL_CONNECTED_TABLE_LIST' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_CONN_TBL_LIST&ID={$record['ID']}",
-			// $urlFileRemoveAjax
 			'URL_FILE_REMOVE_AJAX' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILE_REMOVE&ID={$record['ID']}",
-		];
-		echo UI::h('script', [], "
-			function fileListUpdateAjax{$this->_htmlID}() {
-				var postData = {};
-				var URL_FILE_LIST_UPDATE_AJAX = '{$jsArgs['URL_FILE_LIST_UPDATE_AJAX']}';
-				jQuery.ajax({
-					url: URL_FILE_LIST_UPDATE_AJAX,
-					type: 'POST',
-					data: postData,
-					success: function(data) {
-						fileListUpdate{$this->_htmlID}(data);
-					},
-					error: function(jhr, textStatus, errorThrown) {
-						console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
-					}
-				});
-			}
-		");
-		echo UI::h('script', [], "
-			function fileListUpdate{$this->_htmlID}(fileListJson) {
-				var CAN_WRITE_RECORD = {$jsArgs['CAN_WRITE_RECORD']};
-				var SHARE_POINT = '{$jsArgs['SHARE_POINT']}';
-				var URL_FILE_REMOVE_AJAX = '{$jsArgs['URL_FILE_REMOVE_AJAX']}';
-				var fileListNode = jQuery('#FILES_LIST_{$this->_htmlID}');
-				fileListNode.empty();
-				fileListJson.map(function(file){
-					var node = $('<tr></tr>');
-					var fFun = CAN_WRITE_RECORD
-						? $('<i class=\"glyphicon glyphicon-remove\" style=\"cursor:pointer\" data-filename=\"' + file.name + '\"></i>')
-						: null
-					;
-					var fNameCell = $('<td style=\"overflow: hidden;\"></td>');
-					var fName = $('<div style=\"overflow:hidden; white-space:nowrap;\" title=\"' + file.name + '\"></div>');
-					if (fFun) fName.append(fFun);
-					fName.append(file.name);
-					fName.appendTo(fNameCell);
-					node.append(fNameCell);
-					node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:center;\">' + '<a href=\"' + file.web + '\" target=\"_blank\" class=\"glyphicon glyphicon-download-alt\"></a>' + '</td>');
-					if (SHARE_POINT) {
-						node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:center;\">' + '<a href=\"' + SHARE_POINT + '/' + file.name + '\" target=\"_blank\" class=\"glyphicon glyphicon-folder-open\"></a>' + '</td>');
-					}
-					node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:right;\">' + file.sizeStr + '</td>');
-					node.append('<td style=\"overflow:hidden; white-space:nowrap;\">' + file.created + '</td>');
-					node.appendTo(fileListNode);
-
-					if (fFun) {
-						$(fFun).click(function(e){
-							var n = $(e.target);
-							var fname= n.data('filename');
-							if (!fname) {
-								return false;
-							}
-							if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
-								var postData = {filename: fname};
-								jQuery.ajax({
-									url: URL_FILE_REMOVE_AJAX,
-									type: 'POST',
-									data: postData,
-									success: function(data) {
-										if (data && data.type) {
-											if (data.type == 'SUCCESS') {
-												n.parents('tr').remove();
-												//console.log('TODO: SUCCESS msg: ', data.msg);
-											}
-											else if (data.type == 'error') {
-												console.log('TODO: ERROR msg: ', data.msg);
-											}
-										} else {
-											console.log('TODO: ??? data: ', data);
-										}
-									},
-									error: function(jhr, textStatus, errorThrown) {
-										console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
-									}
-								});
-							}
-						});
-					}
-				});
-			}
-		");
-		echo UI::h('script', [], "
-			function connTblListUpdateAjax{$this->_htmlID}(connTblID) {
-				var postData = {};
-				var URL_CONNECTED_TABLE_LIST = '{$jsArgs['URL_CONNECTED_TABLE_LIST']}'
-
-				// clear current file list
-				jQuery('#FILES_CONN_TBLS_{$this->_htmlID}').find('.files-list').empty();
-
-				jQuery.ajax({
-					url: URL_CONNECTED_TABLE_LIST + '&connTblID=' + connTblID,
-					type: 'POST',
-					data: postData,
-					success: function(data) {
-						connTblListUpdate{$this->_htmlID}(data);
-					},
-					error: function(jqXHR, textStatus, errorThrown) {
-						var txt = jqXHR.responseText || 'Error';
-						jQuery('#FILES_CONN_TBLS_{$this->_htmlID}').find('.files-list').html('<tr><td colspan=\"6\"><div class=\"alert alert-danger\">' + txt + '</div></td></tr>');
-						if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
-					}
-				});
-			}
-		");
-		echo UI::h('script', [], "
-			function connTblListUpdate{$this->_htmlID}(fileListJson) {
-				var fileListNode = jQuery('#FILES_CONN_TBLS_{$this->_htmlID}').find('.files-list');
-				fileListNode.empty();
-				fileListJson.map(function(file){
-					var node = $('<tr></tr>');
-					var fNameCell = $('<td style=\"overflow: hidden;\"></td>');
-					var fName = $('<div style=\"overflow:hidden; white-space:nowrap;\" title=\"' + file.name + '\"></div>');
-					fName.append(file.name);
-					fName.appendTo(fNameCell);
-					node.append(fNameCell);
-					node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:center;\">' + '<a href=\"' + file.web + '\" target=\"_blank\" class=\"glyphicon glyphicon-download-alt\"></a>' + '</td>');
-					node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:right;\">' + file.sizeStr + '</td>');
-					node.append('<td style=\"overflow:hidden; white-space:nowrap;\">' + file.created + '</td>');
-					node.appendTo(fileListNode);
-				});
-			}
-		");
-		?>
-		<script>
-function fileListActions<?= $this->_htmlID; ?>() {
-	var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?= $this->_htmlID; ?>');
-	var btnReload = jQuery('<button class="btn-link btn-sm" title="odśwież uprawnienia do plików"><span class="glyphicon glyphicon-refresh"></span>Odśwież</button>');
-	btnReload.on('click', function(e) {
-		//console.log('TODO: click reload perms...');
-
-		function notifyAjaxCallback(data) {
-			var notify = {};
-			notify.type = (data && data.type)? data.type : '';
-			notify.msg = (data && data.msg)? data.msg : '';
-			switch (notify.type) {
-				case 'success':
-					if (!notify.msg) notify.msg = 'OK';
-					break;
-				case 'info':
-					if (!notify.msg) notify.msg = '';
-					break;
-				case 'error':
-					if (!notify.msg) notify.msg = 'Wystąpiły błędy';
-					break;
-				case 'warning':
-					notify.type = 'warn';
-					if (!notify.msg) notify.msg = 'Wystąpiły błędy';
-					break;
-				default:
-					notify.msg = 'Nieznany błąd';
-					if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
-					notify.type = '';
-			}
-			jQuery.notify(notify.msg, notify.type);
-		}
-
-		var reqData = {};
-		jQuery.ajax({
-			data: reqData,
-			dataType: 'json',
-			type: "GET",
-			url: 'index-ajax.php?_zasobID=<?= $this->_zasobID; ?>&_cls=<?= __CLASS__; ?>&_hash=<?= $this->_htmlID; ?>&_task=filePermsRefresh&ID=<?= $record['ID']; ?>',
-		})
-		.done(function(data, textStatus, jqXHR){
-			notifyAjaxCallback(data);
-			if (data && data.files) {
-				fileListUpdate<?= $this->_htmlID; ?>(data.files);
-			}
-		})
-		.fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
-			if (jqXHR.responseJSON) {
-				notifyAjaxCallback(jqXHR.responseJSON);
-			}
-			else {
-				var txt = jqXHR.responseText || 'Wystąpiły błędy';
-				if (jqXHR.status == 404) {
-					jQuery.notify(jqXHR.responseText, 'error');
-				} else {
-					jQuery.notify(jqXHR.responseText, 'warn');
-				}
-			}
-		});
-	});
-	filePermsReload.append(btnReload);
-}
-
-jQuery(document).ready(function(){
-	$('#FILES_TAB_<?= $this->_htmlID; ?> a').click(function(e) {
-		e.preventDefault();
-		$(this).tab('show');
-	})
-	.on('shown.bs.tab', function(e) {
-		var fileSource = $(e.target).data('toggle')
-			, frm = jQuery('#FILES_FRM_<?= $this->_htmlID; ?>').get(0);
-		if (frm['M_DIST_UPLOAD_SOURCE']) {
-			frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
-		}
-	})
-
-	jQuery('#FILES_FRM_<?= $this->_htmlID; ?>').ajaxForm({
-		url: 'index-ajax.php?_zasobID=<?= $this->_zasobID; ?>&_cls=<?= __CLASS__; ?>&_hash=<?= $this->_htmlID; ?>&_task=FILES_UPLOAD&ID=<?= $record['ID']; ?>',
-		beforeSubmit: function(args, $form, options) {
-			//console.log('#FILES_FRM_<?= $this->_htmlID; ?>.ajaxForm->beforeSubmit()...');
-			var argsMap = [];
-			args.map(function(v, k) {
-				argsMap[v.name] = v.value;
-			});
-			// validate
-			if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
-				if (!argsMap['M_DIST_FILES_NAME']) {
-					//console.log('#FILES_FRM_<?= $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
-					return false;
-				}
-			}
-			else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
-				if (!argsMap['SCANS_COLUMN_ADD']) {
-					//console.log('#FILES_FRM_<?= $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
-					return false;
-				}
-			}
-			else {
-				return false;
-			}
-
-			var $out = $('#FRM_UPLOAD_RESULTS_<?= $this->_htmlID; ?>');
-			$out.html('Wysyłanie...');
-		},
-		success: function(data) {
-			//console.log('#FILES_FRM_<?= $this->_htmlID; ?>.ajaxForm->success()...');
-			var $out = $('#FRM_UPLOAD_RESULTS_<?= $this->_htmlID; ?>');
-			var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
-			if (typeof data == 'object') {
-				if (data.type == 'error') {
-					$out.html('<div class="alert alert-danger">' + btnClose + data.msg + '</div>');
-				} else if (data.type == 'SUCCESS') {
-					$out.html('<div class="alert alert-success">' + btnClose + data.msg + '</div>');
-					fileListUpdateAjax<?= $this->_htmlID; ?>();
-					// TODO: scanFileListUpdateAjax...
-				}
-			} else {
-				if (data.substr(0, 7) == 'WARNING') {
-					data = data.substr(7);
-					$out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
-				} else if (data.substr(0, 5) == 'error') {
-					data = data.substr(5);
-					$out.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
-				} else if (data.substr(0, 7) == 'SUCCESS') {
-					data = data.substr(7);
-					$out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
-					fileListUpdateAjax<?= $this->_htmlID; ?>();
-					// TODO: scanFileListUpdateAjax...
-				} else if (data.substr(0, 4) == 'INFO') {
-					data = data.substr(4);
-					$out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
-				}
-			}
-		}
-	});
-
-	fileListActions<?= $this->_htmlID; ?>();
-
-	var fileList = <?= json_encode($jsonFiles); ?>;
-
-	fileListUpdate<?= $this->_htmlID; ?>(fileList);
-
-	var connTbls = <?= json_encode($this->getConnectedTables()); ?>;
-	if (connTbls) {
-		var connTblsOut = '';
-		for(var key in connTbls) {
-			connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
-		};
-
-		if (connTblsOut) {
-			connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
-			connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
-				'<table class="table table-bordered table-hover">' +
-					'<colgroup>' +
-						'<col style="">' +
-						'<col style="width:30px;">' +
-						<?php if ($sharePoint) : ?>
-							'<col style="width:30px;">' +
-						<?php endif; ?>
-						'<col style="width:80px;">' +
-						'<col style="width:140px;">' +
-					'</colgroup>' +
-					'<tbody class="files-list">' +
-					'</tbody>' +
-				'</table>' +
-				'</div>';
-
-			var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
-			_connTblsWrap.css('marginBottom', '26px');
-			_connTblsWrap.html(connTblsOut);
-			_connTblsWrap.find('.conn-tbl-load').each(function(){
-				jQuery(this).click(function(e){
-					var tblID = jQuery(e.target).data('zasobid');
-					if (tblID) {
-						connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
-					}// TODO: else show error
-				});
-			});
-		}
-	}
-
-	initDateTimePicker(jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>'));
-});
-		</script>
-		<?php
+			'URL_CONNECTED_TABLE_LIST' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_CONN_TBL_LIST&ID={$record['ID']}",
+			'URL_FILE_PERMS_REFRESH' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=filePermsRefresh&ID={$record['ID']}",
+			'URL_FILE_UPLOAD' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_UPLOAD&ID={$record['ID']}",
+			'CAN_WRITE_RECORD' => (int)$this->_acl->canWriteRecord($record),
+			'SHARE_POINT' => $sharePoint,
+			'JSON_FILES' => $jsonFiles,
+		]);
 		exit;
 	}
 

+ 392 - 0
SE/se-lib/TableAjax.php.files.js

@@ -0,0 +1,392 @@
+// @require variables:
+if ('undefined' === typeof UNIQ_HASH) throw "Missing UNIQ_HASH"; // $this->_htmlID,
+if ('undefined' === typeof FUNCTION_FILE_LIST_UPDATE_AJAX) throw "Missing FUNCTION_FILE_LIST_UPDATE_AJAX"; // "fileListUpdateAjax{$this->_htmlID}", // fileListUpdateAjax
+if ('undefined' === typeof FUNCTION_FILE_LIST_UPDATE) throw "Missing FUNCTION_FILE_LIST_UPDATE"; // "fileListUpdate{$this->_htmlID}", // fileListUpdate
+if ('undefined' === typeof FUNCTION_CONN_TBL_LIST_UPDATE_AJAX) throw "Missing FUNCTION_CONN_TBL_LIST_UPDATE_AJAX"; // "connTblListUpdateAjax{$this->_htmlID}", // connTblListUpdateAjax
+if ('undefined' === typeof FUNCTION_CONN_TBL_LIST_UPDATE) throw "Missing FUNCTION_CONN_TBL_LIST_UPDATE"; // "connTblListUpdate{$this->_htmlID}", // connTblListUpdate
+if ('undefined' === typeof FUNCTION_FILE_LIST_ACTIONS) throw "Missing FUNCTION_FILE_LIST_ACTIONS"; // "fileListActions{$this->_htmlID}", // fileListActions
+if ('undefined' === typeof CONN_TABLES) throw "Missing CONN_TABLES"; // $this->getConnectedTables(),
+if ('undefined' === typeof NODE_ID_FILES_FRM) throw "Missing NODE_ID_FILES_FRM"; // "FILES_FRM_{$this->_htmlID}",
+if ('undefined' === typeof NODE_ID_FRM_UPLOAD_RESULTS) throw "Missing NODE_ID_FRM_UPLOAD_RESULTS"; // "FRM_UPLOAD_RESULTS_{$this->_htmlID}",
+if ('undefined' === typeof NODE_ID_FILES_TAB) throw "Missing NODE_ID_FILES_TAB"; // "FILES_TAB_{$this->_htmlID}",
+if ('undefined' === typeof NODE_ID_FILES_LIST) throw "Missing NODE_ID_FILES_LIST"; // "FILES_LIST_{$this->_htmlID}",
+if ('undefined' === typeof NODE_ID_FILES_CONN_TBLS) throw "Missing NODE_ID_FILES_CONN_TBLS"; // "FILES_CONN_TBLS_{$this->_htmlID}",
+if ('undefined' === typeof NODE_ID_FILES_LIST_ACTIONS) throw "Missing NODE_ID_FILES_LIST_ACTIONS"; // "FILES_LIST_ACTIONS_{$this->_htmlID}",
+if ('undefined' === typeof NODE_ID_FILES_MULTIPLE_UPLOAD) throw "Missing NODE_ID_FILES_MULTIPLE_UPLOAD"; // "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
+if ('undefined' === typeof URL_FILE_LIST_UPDATE_AJAX) throw "Missing URL_FILE_LIST_UPDATE_AJAX";
+if ('undefined' === typeof URL_FILE_REMOVE_AJAX) throw "Missing URL_FILE_REMOVE_AJAX";
+if ('undefined' === typeof URL_CONNECTED_TABLE_LIST) throw "Missing URL_CONNECTED_TABLE_LIST";
+if ('undefined' === typeof URL_FILE_PERMS_REFRESH) throw "Missing URL_FILE_PERMS_REFRESH";
+if ('undefined' === typeof URL_FILE_UPLOAD) throw "Missing URL_FILE_UPLOAD";
+if ('undefined' === typeof CAN_WRITE_RECORD) throw "Missing CAN_WRITE_RECORD";
+if ('undefined' === typeof SHARE_POINT) throw "Missing SHARE_POINT";
+if ('undefined' === typeof JSON_FILES) throw "Missing JSON_FILES";
+
+function fileListUpdateAjax() { // FUNCTION_FILE_LIST_UPDATE_AJAX
+	var postData = {};
+	jQuery.ajax({
+		url: URL_FILE_LIST_UPDATE_AJAX,
+		type: 'POST',
+		data: postData,
+		success: function(data) {
+			fileListUpdate(data);
+		},
+		error: function(jhr, textStatus, errorThrown) {
+			console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
+		}
+	});
+}
+
+function fileListUpdate(fileListJson) { // FUNCTION_FILE_LIST_UPDATE
+	var fileListNode = jQuery('#' + NODE_ID_FILES_LIST);
+	fileListNode.empty();
+	fileListJson.map(function(file){
+		var node = jQuery('<tr></tr>');
+		var fFun = CAN_WRITE_RECORD
+			? jQuery('<i class=\"glyphicon glyphicon-remove\" style=\"cursor:pointer; margin-right:2px\" data-filename=\"' + file.name + '\"></i>')
+			: null
+		;
+		var fNameCell = jQuery('<td style=\"overflow: hidden;\"></td>');
+		var fName = jQuery('<div style=\"overflow:hidden; white-space:nowrap;\" title=\"' + file.name + '\"></div>');
+		if (fFun) fName.append(fFun);
+		fName.append(file.name);
+		fName.appendTo(fNameCell);
+		node.append(fNameCell);
+		node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:center;\">' + '<a href=\"' + file.web + '\" target=\"_blank\" class=\"glyphicon glyphicon-download-alt\"></a>' + '</td>');
+		if (SHARE_POINT) {
+			node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:center;\">' + '<a href=\"' + SHARE_POINT + '/' + file.name + '\" target=\"_blank\" class=\"glyphicon glyphicon-folder-open\"></a>' + '</td>');
+		}
+		node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:right;\">' + file.sizeStr + '</td>');
+		node.append('<td style=\"overflow:hidden; white-space:nowrap;\">' + file.created + '</td>');
+		node.appendTo(fileListNode);
+
+		if (fFun) {
+			jQuery(fFun).click(function(e){
+				var n = jQuery(e.target);
+				var fname= n.data('filename');
+				if (!fname) {
+					return false;
+				}
+				if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
+					var postData = {filename: fname};
+					jQuery.ajax({
+						url: URL_FILE_REMOVE_AJAX,
+						type: 'POST',
+						data: postData,
+						success: function(data) {
+							if (data && data.type) {
+								if (data.type == 'SUCCESS') {
+									n.parents('tr').remove();
+									//console.log('TODO: SUCCESS msg: ', data.msg);
+								}
+								else if (data.type == 'error') {
+									console.log('TODO: ERROR msg: ', data.msg);
+								}
+							} else {
+								console.log('TODO: ??? data: ', data);
+							}
+						},
+						error: function(jhr, textStatus, errorThrown) {
+							console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
+						}
+					});
+				}
+			});
+		}
+	});
+}
+
+function connTblListUpdateAjax(connTblID) { // FUNCTION_CONN_TBL_LIST_UPDATE_AJAX
+	var postData = {};
+
+	// clear current file list
+	jQuery('#' + NODE_ID_FILES_CONN_TBLS).find('.files-list').empty();
+
+	jQuery.ajax({
+		url: URL_CONNECTED_TABLE_LIST + '&connTblID=' + connTblID,
+		type: 'POST',
+		data: postData,
+		success: function(data) {
+			connTblListUpdate(data);
+		},
+		error: function(jqXHR, textStatus, errorThrown) {
+			var txt = jqXHR.responseText || 'Error';
+			jQuery('#' + NODE_ID_FILES_CONN_TBLS).find('.files-list').html('<tr><td colspan=\"6\"><div class=\"alert alert-danger\">' + txt + '</div></td></tr>');
+			if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
+		}
+	});
+}
+
+function connTblListUpdate(fileListJson) { // FUNCTION_CONN_TBL_LIST_UPDATE
+	var fileListNode = jQuery('#' + NODE_ID_FILES_CONN_TBLS).find('.files-list');
+	fileListNode.empty();
+	fileListJson.map(function(file){
+		var node = jQuery('<tr></tr>');
+		var fNameCell = jQuery('<td style=\"overflow: hidden;\"></td>');
+		var fName = jQuery('<div style=\"overflow:hidden; white-space:nowrap;\" title=\"' + file.name + '\"></div>');
+		fName.append(file.name);
+		fName.appendTo(fNameCell);
+		node.append(fNameCell);
+		node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:center;\">' + '<a href=\"' + file.web + '\" target=\"_blank\" class=\"glyphicon glyphicon-download-alt\"></a>' + '</td>');
+		node.append('<td style=\"overflow:hidden; white-space:nowrap; text-align:right;\">' + file.sizeStr + '</td>');
+		node.append('<td style=\"overflow:hidden; white-space:nowrap;\">' + file.created + '</td>');
+		node.appendTo(fileListNode);
+	});
+}
+
+function fileListActions() { // FUNCTION_FILE_LIST_ACTIONS
+	var filePermsReload = jQuery('#' + NODE_ID_FILES_LIST_ACTIONS);
+	var btnReload = jQuery('<button class="btn-link btn-sm" title="odśwież uprawnienia do plików"><span class="glyphicon glyphicon-refresh"></span>Odśwież</button>');
+	btnReload.on('click', function(e) {
+		//console.log('TODO: click reload perms...');
+
+		function notifyAjaxCallback(data) {
+			var notify = {};
+			notify.type = (data && data.type)? data.type : '';
+			notify.msg = (data && data.msg)? data.msg : '';
+			switch (notify.type) {
+				case 'success':
+					if (!notify.msg) notify.msg = 'OK';
+					break;
+				case 'info':
+					if (!notify.msg) notify.msg = '';
+					break;
+				case 'error':
+					if (!notify.msg) notify.msg = 'Wystąpiły błędy';
+					break;
+				case 'warning':
+					notify.type = 'warn';
+					if (!notify.msg) notify.msg = 'Wystąpiły błędy';
+					break;
+				default:
+					notify.msg = 'Nieznany błąd';
+					if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
+					notify.type = '';
+			}
+			jQuery.notify(notify.msg, notify.type);
+		}
+
+		var reqData = {};
+		jQuery.ajax({
+			data: reqData,
+			dataType: 'json',
+			type: "GET",
+			url: URL_FILE_PERMS_REFRESH,
+		})
+		.done(function(data, textStatus, jqXHR){
+			notifyAjaxCallback(data);
+			if (data && data.files) {
+				fileListUpdate(data.files);
+			}
+		})
+		.fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
+			if (jqXHR.responseJSON) {
+				notifyAjaxCallback(jqXHR.responseJSON);
+			}
+			else {
+				var txt = jqXHR.responseText || 'Wystąpiły błędy';
+				if (jqXHR.status == 404) {
+					jQuery.notify(jqXHR.responseText, 'error');
+				} else {
+					jQuery.notify(jqXHR.responseText, 'warn');
+				}
+			}
+		});
+	});
+	filePermsReload.append(btnReload);
+}
+
+jQuery(document).ready(function(){
+	jQuery('#' + NODE_ID_FILES_TAB + ' a').click(function(e) {
+		e.preventDefault();
+		jQuery(this).tab('show');
+	})
+	.on('shown.bs.tab', function(e) {
+		var fileSource = jQuery(e.target).data('toggle')
+			, frm = jQuery('#' + NODE_ID_FILES_FRM).get(0);
+		if (frm['M_DIST_UPLOAD_SOURCE']) {
+			frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
+		}
+	})
+
+	jQuery('#' + NODE_ID_FILES_FRM).ajaxForm({
+		url: URL_FILE_UPLOAD,
+		beforeSubmit: function(args, $form, options) {
+			//console.log('#' + NODE_ID_FILES_FRM + '.ajaxForm->beforeSubmit()...');
+			var argsMap = [];
+			args.map(function(v, k) {
+				argsMap[v.name] = v.value;
+			});
+			// validate
+			if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
+				if (!argsMap['M_DIST_FILES_NAME']) {
+					//console.log('#' + NODE_ID_FILES_FRM+'.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
+					return false;
+				}
+			}
+			else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
+				if (!argsMap['SCANS_COLUMN_ADD']) {
+					//console.log('#' + NODE_ID_FILES_FRM+'.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
+					return false;
+				}
+			}
+			else {
+				return false;
+			}
+
+			jQuery('#' + NODE_ID_FRM_UPLOAD_RESULTS).html('Wysyłanie...');
+		},
+		success: function(data) {
+			//console.log('#' + NODE_ID_FILES_FRM+'.ajaxForm->success()...');
+			var outJqNode = jQuery('#' + NODE_ID_FRM_UPLOAD_RESULTS);
+			var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
+			if (typeof data == 'object') {
+				if (data.type == 'error') {
+					outJqNode.html('<div class="alert alert-danger">' + btnClose + data.msg + '</div>');
+				} else if (data.type == 'SUCCESS') {
+					outJqNode.html('<div class="alert alert-success">' + btnClose + data.msg + '</div>');
+					fileListUpdateAjax();
+					// TODO: scanFileListUpdateAjax...
+				}
+			} else {
+				if (data.substr(0, 7) == 'WARNING') {
+					data = data.substr(7);
+					outJqNode.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
+				} else if (data.substr(0, 5) == 'error') {
+					data = data.substr(5);
+					outJqNode.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
+				} else if (data.substr(0, 7) == 'SUCCESS') {
+					data = data.substr(7);
+					outJqNode.html('<div class="alert alert-success">' + btnClose + data + '</div>');
+					fileListUpdateAjax();
+					// TODO: scanFileListUpdateAjax...
+				} else if (data.substr(0, 4) == 'INFO') {
+					data = data.substr(4);
+					outJqNode.html('<div class="alert alert-info">' + btnClose + data + '</div>');
+				}
+			}
+		}
+	})
+
+	fileListActions()
+
+	var fileList = JSON_FILES
+
+	fileListUpdate(fileList)
+
+	var connTbls = CONN_TABLES
+	if (connTbls) {
+		var connTblsOut = '';
+		for(var key in connTbls) {
+			connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
+		};
+
+		if (connTblsOut) {
+			connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
+			connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
+				'<table class="table table-bordered table-hover">' +
+					'<colgroup>' +
+						'<col style="">' +
+						'<col style="width:30px;">' +
+						( (SHARE_POINT) ? '<col style="width:30px;">' : '' ) +
+						'<col style="width:80px;">' +
+						'<col style="width:140px;">' +
+					'</colgroup>' +
+					'<tbody class="files-list">' +
+					'</tbody>' +
+				'</table>' +
+				'</div>';
+
+			var _connTblsWrap = jQuery('#' + NODE_ID_FILES_CONN_TBLS);
+			_connTblsWrap.css('marginBottom', '26px');
+			_connTblsWrap.html(connTblsOut);
+			_connTblsWrap.find('.conn-tbl-load').each(function(){
+				jQuery(this).click(function(e){
+					var tblID = jQuery(e.target).data('zasobid');
+					if (tblID) {
+						connTblListUpdateAjax(tblID);
+					}// TODO: else show error
+				});
+			});
+		}
+	}
+
+	initDateTimePicker(jQuery('#' + NODE_ID_FILES_FRM));
+});
+
+function p5TAFiles_onDropMultiple(event, targetNode, pk, ns) {
+	event.preventDefault()
+	targetNode.style.backgroundColor = '#eee'
+	var files = p5Utils__getFilesFromDropEvent(event)
+	if (!files) {
+		p5UI__notifyAjaxCallback({
+			type: 'info',
+			msg: 'brak plików',
+		})
+		return false
+	}
+	try {
+		var initialContent = (NODE_ID_FILES_MULTIPLE_UPLOAD)
+			? document.getElementById(NODE_ID_FILES_MULTIPLE_UPLOAD).innerHTML
+			: ''
+		;
+		p5TA_uploadWithProgress(files, ns, pk, {
+			onProgress: function (loadedPercent) {
+				var intPercent = Math.floor(loadedPercent)
+				if (NODE_ID_FILES_MULTIPLE_UPLOAD) {
+					document.getElementById(NODE_ID_FILES_MULTIPLE_UPLOAD).innerHTML = '<div class="progress">' +
+					  '<div class="progress-bar" role="progressbar" aria-valuenow="' + intPercent + '" aria-valuemin="0" aria-valuemax="100" style="width: ' + intPercent + '%;">' +
+					    intPercent + '%' +
+					  '</div>' +
+					'</div>'
+				} else {
+					p5UI__notifyAjaxCallback({ type: 'info', msg: 'wgrano ' + intPercent + '%' })
+				}
+			},
+			onLoad: function (response) {
+				if (NODE_ID_FILES_MULTIPLE_UPLOAD) {
+					document.getElementById(NODE_ID_FILES_MULTIPLE_UPLOAD).innerHTML = initialContent
+				}
+				try {
+					var respJson = JSON.parse(response)
+				} catch (e) {
+					p5UI__notifyAjaxCallback({ type: 'error', msg: 'Wystąpił błąd podczas wgrywania plików' })
+					return false
+				}
+				if (respJson && respJson.type && respJson.msg) {
+					p5UI__notifyAjaxCallback(respJson)
+				}
+				fileListUpdateAjax()
+			},
+			onError: function (e) {
+				p5UI__notifyAjaxCallback({ type: 'error', msg: e })
+				console.warn('error', e)
+			}
+		})
+	} catch (e) {
+		console.warn(e)
+	}
+}
+
+function p5TAFiles_onDragOverMultiple(event, targetNode) { // 'ondragover' => "p5TAFiles_onDragOverMultiple", // "event.preventDefault(); this.style.backgroundColor='#D9EDF7'",
+	event.preventDefault()
+	targetNode.style.backgroundColor = '#D9EDF7'
+}
+function p5TAFiles_onDragLeaveMultiple(event, targetNode) { // 'ondragleave' => "p5TAFiles_onDragLeaveMultiple", // "event.preventDefault(); this.style.backgroundColor='#eee'",
+	event.preventDefault()
+	targetNode.style.backgroundColor = '#eee'
+}
+function p5TAFiles_onDragEndMultiple(event, targetNode) { // 'ondragend' => "p5TAFiles_onDragEndMultiple", // "event.preventDefault(); this.style.backgroundColor='#eee'",
+	event.preventDefault()
+	targetNode.style.backgroundColor = '#eee'
+}
+
+global[FUNCTION_FILE_LIST_UPDATE_AJAX] = fileListUpdateAjax
+global[FUNCTION_FILE_LIST_UPDATE] = fileListUpdate
+global[FUNCTION_CONN_TBL_LIST_UPDATE_AJAX] = connTblListUpdateAjax
+global[FUNCTION_CONN_TBL_LIST_UPDATE] = connTblListUpdate
+global[FUNCTION_FILE_LIST_ACTIONS] = fileListActions
+global['p5TAFiles_onDropMultiple'] = p5TAFiles_onDropMultiple
+global['p5TAFiles_onDragOverMultiple'] = p5TAFiles_onDragOverMultiple
+global['p5TAFiles_onDragLeaveMultiple'] = p5TAFiles_onDragLeaveMultiple
+global['p5TAFiles_onDragEndMultiple'] = p5TAFiles_onDragEndMultiple

+ 171 - 0
SE/se-lib/TableAjax.php.upload.js

@@ -0,0 +1,171 @@
+// @require variables:
+if ('undefined' === typeof URL_UPLOAD_FILES_AJAX) throw "Missing URL_UPLOAD_FILES_AJAX";
+
+var this__dragOverChecker = (function () {
+	var _node = null
+	var _pk = null
+	var _ns = null
+	var _overlayNode = null
+	var markNodeHoverOn = function (node, pk, ns) {
+		if (!_overlayNode) {
+			_overlayNode = document.createElement('div')
+			_overlayNode.style.backgroundColor = '#03a9f4'
+			_overlayNode.style.opacity = '0.2'
+			_overlayNode.style.position = 'absolute'
+			document.body.appendChild(_overlayNode)
+			_overlayNode.appendChild(document.createTextNode('drag file...'))
+		}
+		var bbox = node.getBoundingClientRect()
+		_overlayNode.style.top = ((window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0) + bbox.top) + 'px'
+		_overlayNode.style.left = '0px' // bbox.left + 'px'
+		_overlayNode.style.width = '100%' // bbox.width + 'px'
+		_overlayNode.style.height = bbox.height + 'px'
+		_overlayNode.setAttribute('ondrop', 'p5TA_onDrop(event, \''+pk+'\', \''+ns+'\')')
+		_overlayNode.setAttribute('ondragover', 'p5TA_overlay_onDragOver(event, this, \''+pk+'\', \''+ns+'\')')
+	}
+	var markNodeHoverOff = function () {
+		if (_overlayNode && _overlayNode.parentNode) _overlayNode.parentNode.removeChild(_overlayNode)
+		_overlayNode = null
+	}
+	var _removeOverlayTimeoutId = null
+	return {
+		update: function (node, pk, ns) {
+			_ns = ns
+			if (null !== _pk && _pk !== pk) {
+				markNodeHoverOff()
+			}
+			if (_pk !== pk) {
+				if (null !== node) markNodeHoverOn(node, pk, ns)
+			}
+			_pk = pk
+			if (null !== node) _node = node
+			if (_removeOverlayTimeoutId) clearTimeout(_removeOverlayTimeoutId)
+			_removeOverlayTimeoutId = setTimeout(markNodeHoverOff, 1000)
+		},
+		removeOverlay: function () {
+			markNodeHoverOff()
+		},
+	}
+})();
+
+function p5Utils__getFilesFromDropEvent(event) {
+	var dt = event.dataTransfer
+	var files = []
+	if (dt.items) { // Use DataTransferItemList interface to access the file(s)
+		for (var i = 0; i < dt.items.length; i++) {
+			if (dt.items[i].kind == 'file') {
+				var file = dt.items[i].getAsFile();
+				files.push(file)
+			}
+		}
+	} else { // Use DataTransfer interface to access the file(s)
+		for (var i=0; i < dt.files.length; i++) {
+			files.push(dt.files[i])
+		}
+	}
+	return files
+}
+
+function p5TA_uploadWithProgress(files, ns, pk, callbacks) {
+	var formData = new FormData()
+	formData.append('namespace', ns)
+	formData.append('primaryKey', pk)
+	files.forEach(function (file, idx) {
+		formData.append('file' + idx, file)
+	})
+
+	var xhr = new XMLHttpRequest()
+	xhr.withCredentials = true
+	xhr.open('POST', URL_UPLOAD_FILES_AJAX)
+	xhr.onerror = function (e) {
+		if (callbacks && callbacks.onError) {
+			callbacks.onError(e)
+		} else {
+			console.log('error', e);
+		}
+	}
+	if (xhr.upload && callbacks && callbacks.onProgress) {
+		xhr.upload.onprogress = function __onProgress(event) {
+			// event.loaded / event.total * 100; // event.lengthComputable
+			callbacks.onProgress(event.loaded / event.total * 100)
+		};
+	}
+	xhr.onload = function (e) {
+		if (callbacks && callbacks.onLoad) {
+			callbacks.onLoad(e.target.responseText)
+		} else {
+			console.log('onload e.target.responseText:', e.target.responseText, 'event', e)
+		}
+	}
+	xhr.send(formData)
+}
+
+function p5TA_uploadFiles(files, ns, pk) {
+	var formData = new FormData()
+	formData.append('namespace', ns)
+	formData.append('primaryKey', pk)
+	files.forEach(function (file, idx) {
+		formData.append('file' + idx, file)
+	})
+
+	window.fetch(URL_UPLOAD_FILES_AJAX, {
+		method: 'POST',
+		body: formData,
+		credentials: 'same-origin',
+	}).then(function checkStatus(response) {
+		if (response.status >= 200 && response.status < 300) {
+			return response
+		} else {
+			var error = new Error(response.statusText)
+			error.response = response
+			throw error
+		}
+	}).then(function (response) {
+		return response.json()
+	}).then(function (response) {
+		p5UI__notifyAjaxCallback(response)
+	}).catch(function(error) {
+		p5UI__notifyAjaxCallback({ type: 'error', msg: error })
+	})
+}
+
+function p5TA_onDrop(event, pk, ns) {
+	event.preventDefault()
+	if (!files) {
+		p5UI__notifyAjaxCallback({
+			type: 'info',
+			msg: 'brak plików',
+		})
+		return false
+	}
+	p5TA_uploadFiles(files, ns, pk)
+	this__dragOverChecker.removeOverlay()
+}
+
+function p5TA_onDragOver(e, n, pk, ns) {
+	e.preventDefault();
+	this__dragOverChecker.update(n, pk, ns)
+}
+
+function p5TA_overlay_onDragOver(e, n, pk, ns) {
+	e.preventDefault();
+	this__dragOverChecker.update(null, pk, ns)
+}
+
+function p5TA_onDragEnd(e, n, pk, ns) {
+	var dt = e.dataTransfer;
+	if (dt.items) { // Use DataTransferItemList interface to remove the drag data
+		for (var i = 0; i < dt.items.length; i++) {
+			dt.items.remove(i);
+		}
+	} else { // Use DataTransfer interface to remove the drag data
+		e.dataTransfer.clearData();
+	}
+}
+
+global.p5TA_onDrop = p5TA_onDrop
+global.p5TA_onDragOver = p5TA_onDragOver
+global.p5TA_onDragEnd = p5TA_onDragEnd
+global.p5TA_overlay_onDragOver = p5TA_overlay_onDragOver
+global.p5Utils__getFilesFromDropEvent = p5Utils__getFilesFromDropEvent
+global.p5TA_uploadWithProgress = p5TA_uploadWithProgress