Skip to content
This repository has been archived by the owner on Nov 15, 2022. It is now read-only.

Commit

Permalink
feat(pkg): move some logic to javascript to improve page load
Browse files Browse the repository at this point in the history
  • Loading branch information
KaiSchwarz-cnic committed Mar 26, 2019
1 parent 8641552 commit 2fd9b9d
Show file tree
Hide file tree
Showing 11 changed files with 218 additions and 84 deletions.
52 changes: 52 additions & 0 deletions modules/addons/ispapidomainimport/assets/form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const ta = $("#domains");
const showNumber = (num) => {
const eL = $("#labeldomains");
eL.text(eL.text().replace(/ \([0-9]+\)$/, ''));
eL.text(eL.text() + `(${num})`);
};
const listDomains = (d) => {
$("div.listdomains").css('display', '');
$(".resultmsg").css('display', 'none');
ta.css('display', '').val("");
showNumber(0);
if (d.success) {
if (d.domains && d.domains.length) {
$(".resultmsg:last").css('display', '');
showNumber(d.domains.length);
ta.css('display', '').val(d.domains.join("\n"));
return;
}
}
$(".resultmsg:first").css('display', '');
};
const updateTextarea = () => {
const val = ta.val();
if (val !== "") {
listDomains({
success: true,
domains: val.split("\n")
});
}
};
$('button[class*="actionBttn"').click(function () {
$('#importform input[name="action"]').val(this.id);
if (this.id === "pull") {
$.ajax({
type: "POST",
data: $(this.form).serialize(),
dataType: 'json'
}).then((d) => {
//successful http communication, use returned result for output
listDomains(d);
}, (d) => {
//failed http communication, show error
listDomains({
success: false,
msg: `${d.status} ${d.statusText}`
});
});
} else {
this.form.submit();
}
});
updateTextarea();
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
<script type="text/javascript">
<!--
const url = "{$modulelink}";
const gateway = {$smarty.request.gateway|json_encode nofilter};
const currency = {$smarty.request.currency|json_encode nofilter};
const registrar = {$registrar|json_encode nofilter};
let domains = {$smarty.request.domains|json_encode nofilter}.replace(/\r\n/g, "\n").split("\n");
const lang = {$_lang|json_encode nofilter};
{literal}
let lenOrginal;
let data = {gateway, currency, registrar, action:'importsingle'};
$(document).ready(() => {
let lenOrginal;
let form = $('#backform');
let domains = form.find('input[name="domains"]').val().split("\n");
let data = {
gateway: form.find('input[name="gateway"]').val(),
currency: form.find('input[name="currency"]').val(),
registrar: form.find('input[name="registrar"]').val(),
action: 'importsingle'
};
// Adjust the width of thead cells with width of tbody cells when window resizes
$(window).resize(function() {
$(window).resize(function () {
const $table = $('table.scrollable');
const $bodyCells = $table.find('tbody tr:first').children();
const colWidth = $bodyCells.map(function() {
const colWidth = $bodyCells.map(function () {
return $(this).width();
}).get();
if (colWidth.length){
$table.find('thead tr').children().each(function(i, v) {
if (colWidth.length) {
$table.find('thead tr').children().each(function (i, v) {
$(v).width(colWidth[i]);
});
}
Expand All @@ -41,25 +37,24 @@ $(document).ready(() => {
// continue importing domains
importDomain();
};

const importDomain = () => {
if (!domains.length){
$("#inprogress").html(`${lang["status.importdone"]}.`);
if (!domains.length) {
$("#inprogress").html(`${translate("status.importdone")}.`);
return;
}
const domain = domains.shift();
data.domain = domain;
$.ajax(url, {
data.domain = domains.shift();
$.ajax({
data,
dataType: 'json',
type: 'POST',
beforeSend: () => {
//create line with spinner icon before import request will be sent
$("#inprogress").html(`${lang["status.importing"]} <b>${domain}</b> ...`);
$("#importresults").append(`<tr><td>${domain}</td><td class="result"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span></td></tr>`);
$("#inprogress").html(`${translate("status.importing")} <b>${data.domain}</b> ...`);
$("#importresults").append(`<tr><td>${data.domain}</td><td class="result"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span></td></tr>`);
$(window).resize();
}
})
.then((d) => {
}).then((d) => {
//successful http communication, use returned result for output
showResultContinue(d);
}, (d) => {
Expand All @@ -70,27 +65,33 @@ $(document).ready(() => {
});
});
};

const translate = (translationkey) => {
const lang = ISPAPI.lang;
if (lang.hasOwnProperty(translationkey)) {
return lang[translationkey];
}
return translationkey;
};

domains = domains.filter((domain, idx) => {
domain = domain.replace(/\s/g, "");
if (!domain.length){
if (!domain.length) {
return false;
}
if (!/^[a-zA-Z0-9\-\.]+\.[a-zA-Z0-9\-\.]+$/.test(domain)){
$("#importresults").append(`<tr><td>${domain}</td><td class="result"><span class="label label-danger" role="alert">${lang.domainnameinvaliderror}</span></td></tr>`);
if (!/^[a-zA-Z0-9\-\.]+\.[a-zA-Z0-9\-\.]+$/.test(domain)) {
$("#importresults").append(`<tr><td>${domain}</td><td class="result"><span class="label label-danger" role="alert">${translate('domainnameinvaliderror')}</span></td></tr>`);
$(window).resize();
return false;
}
return true;
});
if (!domains.length){
$("#importresults").append(`<tr><td colspan="2"><span class="label label-danger" role="alert">${lang.nothingtoimporterror}</span></td></tr>`);
$(window).resize();
return;
}
if (!domains.length) {
$("#importresults").append(`<tr><td colspan="2"><span class="label label-danger" role="alert">${translate('nothingtoimporterror')}</span></td></tr>`);
$(window).resize();
return;
}
lenOrginal = domains.length;
$('#counterleft').attr('aria-valuemax', lenOrginal);
importDomain();
});
{/literal}
//-->
</script>
});
25 changes: 25 additions & 0 deletions modules/addons/ispapidomainimport/assets/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
.glyphicon-refresh-animate {
-animation: spin .7s infinite linear;
-webkit-animation: spin .7s infinite linear;
animation: spin .7s infinite linear;
}
@-webkit-keyframes spin {
from { -webkit-transform: rotate(0deg);}
to { -webkit-transform: rotate(360deg);}
}
@keyframes spin {
from { transform: scale(1) rotate(0deg);}
to { transform: scale(1) rotate(360deg);}
}
table.scrollable {
width: auto;
}
table.scrollable thead {
display: block;
}
table.scrollable tbody {
display: block;
height: 400px;
overflow-y: auto;
overflow-x: hidden;
}
37 changes: 37 additions & 0 deletions modules/addons/ispapidomainimport/assets/translations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// access /admin/addonmodules.php?module=ispapidomainimport&action=getlang
// ... and save it as this file
// we could automate this in CI
if (typeof ISPAPI === "undefined") {
ISPAPI = {};
}
ISPAPI.lang = {
"ok": "OK",
"registrarerror": "The ispapi registrar authentication failed! Please verify your registrar credentials and try again.",
"actionerror": "Invalid action requested. Please go back and try again.",
"domaincreateerror": "Unable to create domain.",
"tldrenewalpriceerror": "Unable to determinate domain renewal price.",
"registrantcreateerror": "Unable to create client.",
"registrantcreateerrornophone": "Unable to create client (no phone number).",
"registrantfetcherror": "Unable to load registrant data.",
"registrantmissingerror": "Missing Registrant in domain configuration.",
"alreadyexistingerror": "Domain name already exists.",
"domainnameinvaliderror": "Invalid domain name.",
"nogatewayerror": "No Payment Gateway configured.",
"domainlistfetcherror": "Failed to load list of domains.",
"nodomainsfounderror": "The query did not return any domains names.",
"domainsfound": "The query returned the below domain names.",
"nothingtoimporterror": "Nothing to import.",
"label.domain": "Domain",
"label.domains": "Domains",
"label.gateway": "Payment Method",
"label.currency": "Currency",
"ph.domainfilter": "Enter Domain Name Filter",
"bttn.pulldomainlist": "Pull Domain list",
"bttn.importdomainlist": "Import Domains",
"bttn.back": "Back",
"col.domain": "Domain",
"col.importresult": "Import Result",
"col.left": "Left",
"status.importing": "Importing",
"status.importdone": "Import done"
};
41 changes: 29 additions & 12 deletions modules/addons/ispapidomainimport/lib/Admin/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,27 +42,28 @@ public function index($vars, $smarty)
*
* @return string html code
*/
public function pull($vars, $smarty)
public function pull()
{
$_REQUEST["domains"] = "";
$registrar = $smarty->getTemplateVars('registrar');
header('Cache-Control: no-cache, must-revalidate'); // HTTP/1.1
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Content-type: application/json; charset=utf-8');

// fetch list of domains from API
$r = Helper::APICall($registrar, array(
$r = Helper::APICall($_REQUEST['registrar'], array(
"COMMAND" => "QueryDomainList",
"USERDEPTH" => "SELF",
"ORDERBY" => "DOMAIN",
"LIMIT" => 10000,
"DOMAIN" => $_REQUEST["domain"],
));
if (!($r["CODE"] == 200)) {
$smarty->assign('error', $r["DESCRIPTION"]);
return $smarty->fetch('list_error.tpl');
}
foreach ($r["PROPERTY"]["DOMAIN"] as $domain) {
$_REQUEST["domains"] .= "$domain\n";
$json = array(
"success" => ($r["CODE"] == 200),
"msg" => $r["DESCRIPTION"]
);
if ($json["success"]) {
$json["domains"] = $r["PROPERTY"]["DOMAIN"];
}
$smarty->assign('count', $r["PROPERTY"]["COUNT"][0]);
return $this->index($vars, $smarty);
die(json_encode($json));
}

/**
Expand Down Expand Up @@ -107,4 +108,20 @@ public function importsingle($vars, $smarty)
}
die(json_encode($result));
}

/**
* getlang action. return translation texts in javascript source file format.
* save this as asset under assets/translations.js
*
* @param array $vars Module configuration parameters
* @param Smarty $smarty Smarty template instance
*
* @return string json response
*/
public function getlang($vars, $smarty)
{
header('Content-Type: application/javascript');
echo $smarty->fetch('getlang.tpl');
die();
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<br/><br/>
<form method="POST">
<input type="hidden" name="search" value="{$smarty.request.search}" />
<input type="hidden" name="gateway" value="{$smarty.request.gateway}" />
<input type="hidden" name="currency" value="{$smarty.request.currency}" />
<input type="hidden" name="domain" value="{$smarty.request.domain}" />
<input type="hidden" name="domains" value="{$smarty.request.domains}" />
<input type="hidden" name="clientpassword" value="{$smarty.request.clientpassword}" />
<input type="hidden" name="action" value="index" />
<input type="submit" value="{$_lang["bttn.back"]}" class="btn btn-default" />
</form>
Original file line number Diff line number Diff line change
@@ -1 +1 @@
<span class="label label-danger">{$error}</span>
<span class="label label-danger resultmsg">{$error}</span>
6 changes: 6 additions & 0 deletions modules/addons/ispapidomainimport/templates/admin/getlang.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{literal}
if (typeof ISPAPI === "undefined") {
ISPAPI = {};
}
{/literal}
ISPAPI.lang = {$_lang|json_encode nofilter};
16 changes: 13 additions & 3 deletions modules/addons/ispapidomainimport/templates/admin/import.tpl
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<link rel="stylesheet" type="text/css" href="/modules/addons/ispapidomainimport/assets/styles.css"/>
<table class="table table-condensed small scrollable">
<thead>
<tr>
Expand All @@ -16,6 +17,15 @@
<div id="inprogress"></div>
</div>
</div>
{include file='bttn_back.tpl'}
{include file='css.tpl'}
{include file='import.js.tpl'}
<br/><br/>
<form method="POST" id="backform">
<input type="hidden" name="gateway" value="{$smarty.request.gateway}" />
<input type="hidden" name="registrar" value="{$smarty.request.registrar}" />
<input type="hidden" name="currency" value="{$smarty.request.currency}" />
<input type="hidden" name="domain" value="{$smarty.request.domain}" />
<input type="hidden" name="domains" value="{$smarty.request.domains}" />
<input type="hidden" name="action" value="index" />
<input type="submit" value="{$_lang["bttn.back"]}" class="btn btn-default" />
</form>
<script type="text/javascript" src="/modules/addons/ispapidomainimport/assets/translations.js?{mktime()}"></script>
<script type="text/javascript" src="/modules/addons/ispapidomainimport/assets/import.js"></script>
Loading

0 comments on commit 2fd9b9d

Please sign in to comment.