Merge pull request #17924 from MauricioFauth/import-js-upload-progress

Extract inline JS for import's upload progress logic
This commit is contained in:
Maurício Meneghini Fauth 2022-11-28 21:37:46 -03:00 committed by GitHub
commit f249289e09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 150 additions and 165 deletions

View File

@ -1,6 +1,10 @@
import $ from 'jquery';
import { AJAX } from './ajax.js';
import { Functions } from './functions.js';
import { Navigation } from './navigation.js';
import { CommonParams } from './common.js';
/* global themeImagePath */ // templates/javascript/variables.twig
/**
* Functions used in the import tab
@ -58,6 +62,7 @@ AJAX.registerTeardown('import.js', function () {
$('#input_import_file').off('change').off('focus');
$('#select_local_import_file').off('focus');
$('#text_csv_enclosed').add('#text_csv_escaped').off('keyup');
$('#importmain #buttonGo').off('click');
});
AJAX.registerOnload('import.js', function () {
@ -155,4 +160,133 @@ AJAX.registerOnload('import.js', function () {
}
return true;
});
$('#importmain #buttonGo').on('click', function () {
const uploadProgressInfo = document.getElementById('upload_progress_info');
const uploadId = uploadProgressInfo.dataset.uploadId;
const handler = uploadProgressInfo.dataset.handler;
$('#upload_form_form').css('display', 'none');
const clockImage = '<img src="' + themeImagePath + 'ajax_clock_small.gif" width="16" height="16" alt="ajax clock">';
if (handler !== 'PhpMyAdmin\\Plugins\\Import\\Upload\\UploadNoplugin') {
var finished = false;
var percent = 0.0;
var total = 0;
var complete = 0;
var originalTitle = parent && parent.document ? parent.document.title : false;
var importStart;
var performUpload = function () {
$.getJSON(
'index.php?route=/import-status',
{ 'id': uploadId, 'import_status': 1, 'server': CommonParams.get('server') },
function (response) {
finished = response.finished;
percent = response.percent;
total = response.total;
complete = response.complete;
if (total === 0 && complete === 0 && percent === 0) {
$('#upload_form_status_info').html(clockImage + ' ' + window.Messages.uploadProgressMaximumAllowedSize);
$('#upload_form_status').css('display', 'none');
} else {
var now = new Date();
now = Date.UTC(
now.getFullYear(),
now.getMonth(),
now.getDate(),
now.getHours(),
now.getMinutes(),
now.getSeconds()
) + now.getMilliseconds() - 1000;
var statusText = Functions.sprintf(
window.Messages.uploadProgressStatusText,
Functions.formatBytes(
complete, 1, window.Messages.strDecimalSeparator
),
Functions.formatBytes(
total, 1, window.Messages.strDecimalSeparator
)
);
if ($('#importmain').is(':visible')) {
// Show progress UI
$('#importmain').hide();
const uploadProgressDiv = '<div class="upload_progress">'
+ '<div class="upload_progress_bar_outer">'
+ '<div class="percentage"></div>'
+ '<div id="status" class="upload_progress_bar_inner">'
+ '<div class="percentage"></div></div></div>'
+ '<div>' + clockImage + ' ' + window.Messages.uploadProgressUploading + '</div>'
+ '<div id="statustext"></div></div>';
$('#import_form_status').html(uploadProgressDiv).show();
importStart = now;
} else if (percent > 9 || complete > 2000000) {
// Calculate estimated time
var usedTime = now - importStart;
var seconds = parseInt(((total - complete) / complete) * usedTime / 1000);
var speed = Functions.sprintf(
window.Messages.uploadProgressPerSecond,
Functions.formatBytes(complete / usedTime * 1000, 1, window.Messages.strDecimalSeparator)
);
var minutes = parseInt(seconds / 60);
seconds %= 60;
var estimatedTime;
if (minutes > 0) {
estimatedTime = window.Messages.uploadProgressRemainingMin
.replace('%MIN', minutes)
.replace('%SEC', seconds);
} else {
estimatedTime = window.Messages.uploadProgressRemainingSec
.replace('%SEC', seconds);
}
statusText += '<br>' + speed + '<br><br>' + estimatedTime;
}
var percentString = Math.round(percent) + '%';
$('#status').animate({ width: percentString }, 150);
$('.percentage').text(percentString);
// Show percent in window title
if (originalTitle !== false) {
parent.document.title
= percentString + ' - ' + originalTitle;
} else {
document.title
= percentString + ' - ' + originalTitle;
}
$('#statustext').html(statusText);
}
if (finished) {
if (originalTitle !== false) {
parent.document.title = originalTitle;
} else {
document.title = originalTitle;
}
$('#importmain').hide();
// Loads the message, either success or mysql error
$('#import_form_status')
.html(clockImage + ' ' + window.Messages.uploadProgressBeingProcessed)
.show();
$('#import_form_status').load(
'index.php?route=/import-status&message=1&import_status=1&server=' + CommonParams.get('server')
);
Navigation.reload();
} else {
setTimeout(performUpload, 1000);
}
});
};
setTimeout(performUpload, 1000);
} else {
// No plugin available
$('#upload_form_status_info').html(clockImage + ' ' + window.Messages.uploadProgressNoDetails);
$('#upload_form_status').css('display', 'none');
}
});
});

View File

@ -853,6 +853,19 @@ final class JavaScriptMessagesController
'These functions are meant to return a binary result; to avoid inconsistent results you should store'
. ' it in a BINARY, VARBINARY, or BLOB column.'
),
'uploadProgressMaximumAllowedSize' => __(
'The file being uploaded is probably larger than the maximum allowed size.'
),
'uploadProgressStatusText' => __('%s of %s'),
'uploadProgressPerSecond' => __('%s/sec.'),
'uploadProgressRemainingMin' => __('About %MIN min. %SEC sec. remaining.'),
'uploadProgressRemainingSec' => __('About %SEC sec. remaining.'),
'uploadProgressBeingProcessed' => __('The file is being processed, please be patient.'),
'uploadProgressUploading' => __('Uploading your import file…'),
'uploadProgressNoDetails' => __(
'Please be patient, the file is being uploaded. Details about the upload are not available.'
),
];
}
}

View File

@ -9,15 +9,12 @@
<iframe id="import_upload_iframe" name="import_upload_iframe" width="1" height="1" class="hide"></iframe>
<div id="import_form_status" class="hide"></div>
<div class="d-none" id="upload_progress_info" data-upload-id="{{ upload_id|e('html_attr') }}" data-handler="{{ handler|e('html_attr') }}"></div>
<div id="importmain">
<img src="{{ image('ajax_clock_small.gif') }}" width="16" height="16" alt="ajax clock" class="hide">
<script type="text/javascript">
//<![CDATA[
{% include 'import/javascript.twig' with {'upload_id': upload_id, 'handler': handler} only %}
//]]>
</script>
<form id="import_file_form" action="{{ url('/import') }}" method="post" enctype="multipart/form-data" name="import" class="ajax"
{%- if handler != 'PhpMyAdmin\\Plugins\\Import\\Upload\\UploadNoplugin' %} target="import_upload_iframe"{% endif %}>
{{ get_hidden_inputs(hidden_inputs) }}

View File

@ -1,159 +0,0 @@
$( function() {
{# Add event when user click on "Go" button #}
$("#buttonGo").on("click", function() {
{# Hide form #}
$("#upload_form_form").css("display", "none");
{% if handler != 'PhpMyAdmin\\Plugins\\Import\\Upload\\UploadNoplugin' %}
{# Some variable for javascript #}
{% set ajax_url = 'index.php?route=/import-status&id=' ~ upload_id ~ get_common_raw({
'import_status': 1
}, '&') %}
{% set promot_str = 'The file being uploaded is probably larger than the maximum allowed size or this is a known bug in webkit based (Safari, Google Chrome, Arora etc.) browsers.'|trans %}
{% set statustext_str = '%s of %s'|trans %}
{% set second_str = '%s/sec.'|trans %}
{% set remaining_min = 'About %MIN min. %SEC sec. remaining.'|trans %}
{% set remaining_second = 'About %SEC sec. remaining.'|trans %}
{% set processed_str = 'The file is being processed, please be patient.'|trans %}
{% set import_url = get_common_raw({'import_status': 1}, '&') %}
{% set upload_html %}
<div class="upload_progress">
<div class="upload_progress_bar_outer">
<div class="percentage"></div>
<div id="status" class="upload_progress_bar_inner">
<div class="percentage"></div>
</div>
</div>
<div>
<img src="{{ image('ajax_clock_small.gif') }}" width="16" height="16" alt="ajax clock"> {{ 'Uploading your import file…'|trans|escape('js') -}}
</div>
<div id="statustext"></div>
</div>
{% endset %}
{# Start output #}
var finished = false;
var percent = 0.0;
var total = 0;
var complete = 0;
var original_title = parent && parent.document ? parent.document.title : false;
var import_start;
var perform_upload = function () {
new $.getJSON(
"{{ ajax_url|raw }}",
{},
function(response) {
finished = response.finished;
percent = response.percent;
total = response.total;
complete = response.complete;
if (total==0 && complete==0 && percent==0) {
$("#upload_form_status_info").html('<img src="{{ image('ajax_clock_small.gif') }}" width="16" height="16" alt="ajax clock"> {{ promot_str|escape('js') }}');
$("#upload_form_status").css("display", "none");
} else {
var now = new Date();
now = Date.UTC(
now.getFullYear(),
now.getMonth(),
now.getDate(),
now.getHours(),
now.getMinutes(),
now.getSeconds())
+ now.getMilliseconds() - 1000;
var statustext = Functions.sprintf(
"{{ statustext_str|escape('js') }}",
Functions.formatBytes(
complete, 1, window.Messages.strDecimalSeparator
),
Functions.formatBytes(
total, 1, window.Messages.strDecimalSeparator
)
);
if ($("#importmain").is(":visible")) {
{# Show progress UI #}
$("#importmain").hide();
$("#import_form_status")
.html('{{ upload_html|spaceless|raw }}')
.show();
import_start = now;
}
else if (percent > 9 || complete > 2000000) {
{# Calculate estimated time #}
var used_time = now - import_start;
var seconds = parseInt(((total - complete) / complete) * used_time / 1000);
var speed = Functions.sprintf(
"{{ second_str|escape('js') }}",
Functions.formatBytes(complete / used_time * 1000, 1, window.Messages.strDecimalSeparator)
);
var minutes = parseInt(seconds / 60);
seconds %= 60;
var estimated_time;
if (minutes > 0) {
estimated_time = "{{ remaining_min|escape('js') }}"
.replace("%MIN", minutes)
.replace("%SEC", seconds);
}
else {
estimated_time = "{{ remaining_second|escape('js') }}"
.replace("%SEC", seconds);
}
statustext += "<br>" + speed + "<br><br>" + estimated_time;
}
var percent_str = Math.round(percent) + "%";
$("#status").animate({width: percent_str}, 150);
$(".percentage").text(percent_str);
{# Show percent in window title #}
if (original_title !== false) {
parent.document.title
= percent_str + " - " + original_title;
}
else {
document.title
= percent_str + " - " + original_title;
}
$("#statustext").html(statustext);
}
if (finished == true) {
if (original_title !== false) {
parent.document.title = original_title;
}
else {
document.title = original_title;
}
$("#importmain").hide();
{# Loads the message, either success or mysql error #}
$("#import_form_status")
.html('<img src="{{ image('ajax_clock_small.gif') }}" width="16" height="16" alt="ajax clock"> {{ processed_str|raw }}')
.show();
$("#import_form_status").load("index.php?route=/import-status&message=true&{{ import_url|raw }}");
Navigation.reload();
{# If finished #}
}
else {
setTimeout(perform_upload, 1000);
}
});
};
setTimeout(perform_upload, 1000);
{% else %}
{# No plugin available #}
{% set image_tag -%}
<img src="{{ image('ajax_clock_small.gif') }}" width="16" height="16" alt="ajax clock">
{{- 'Please be patient, the file is being uploaded. Details about the upload are not available.'|trans|escape('js') -}}
{{- show_docu('faq', 'faq2-9') -}}
{%- endset %}
$('#upload_form_status_info').html('{{ image_tag|raw }}');
$("#upload_form_status").css("display", "none");
{% endif %}
});
});