Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/js enhance #189

Merged
merged 14 commits into from
Jul 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
},
"homepage": "https://github.com/krasimir/webpack-library-starter",
"dependencies": {
"jquery": "^3.1.1"
"jquery": "^3.1.1",
"semantic-ui-modal": "^2.2.10"
}
}
56 changes: 56 additions & 0 deletions js/src/atk4-semantic-ui.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Handle api server response.
*/

(function ($, window, document, undefined) {

$.fn.api.settings.onResponse = function (response) {
if (response.success) {
try {
if (response && response.html && response.id) {
var result = $('#'+response.id).replaceWith(response.html);
if (!result.length) {
throw({message:'Unable to replace element with id: '+ response.id});
}
}
if (response && response.eval) {
var result = function(){ eval(response.eval.replace(/<\/?script>/g, '')); }.call(this.obj);
}
return {success:true};
} catch (e) {
//send our eval or replaceWith error to successTest
return {success:false, error: 'Error in ajax replace or eval:\n' + e.message };
}
} else {
//catch application error and display them in a new modal window.
var m = $("<div>").appendTo("body").addClass("ui scrolling modal").html(response.message);
m.modal({duration: 100, onHide: function() { m.children().remove(); return true; }}).modal("show");
return {success:true};
}
}

$.fn.api.settings.successTest = function(response) {
if(response.success){
this.data = {};
return true;
} else if (response.error) {
alert(response.error);
return true;
} else {
return false;
}
}

$.fn.api.settings.onFailure = function(response) {
var w = window.open(null,'Error in JSON response','height=1000,width=1100,location=no,menubar=no,scrollbars=yes,status=no,titlebar=no,toolbar=no');
if(w){
w.document.write('<h5>Error in JSON response</h5>');
w.document.write(response);
w.document.write('<center><input type=button onclick="window.close()" value="Close"></center>');
}else{
alert("Error in ajaxec response"+response);
}
}

}) (jQuery, window, document);

17 changes: 4 additions & 13 deletions js/src/index.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
import $ from 'jquery';

import 'atk4-semantic-ui';
import registerPlugin from './plugin';

// Import our plugins
import spinner from 'plugins/spinner'
import reloadView from 'plugins/reloadView'
import ajaxec from 'plugins/ajaxec'
import addParams from 'plugins/addParams'
import createModal from 'plugins/createModal'

// Register our plugins
registerPlugin('spinner', spinner);
registerPlugin('reloadView', reloadView);
registerPlugin('ajaxec', ajaxec);
registerPlugin('addParams', addParams);

$.addParams = function ( url, data )
{
if ( ! $.isEmptyObject(data) )
{
url += ( url.indexOf('?') >= 0 ? '&' : '?' ) + $.param(data);
}

return url;
}
registerPlugin('addParams', addParams, true);
registerPlugin('createModal', createModal);
4 changes: 1 addition & 3 deletions js/src/plugin.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import $ from 'jquery';

/* https://gist.github.com/monkeymonk/c08cb040431f89f99928132ca221d647 */

/**
Expand Down Expand Up @@ -48,4 +46,4 @@ export default function plugin(pluginName, className, shortHand = false) {

// - No conflict
$.fn[pluginName].noConflict = () => $.fn[pluginName] = old;
}
}
1 change: 0 additions & 1 deletion js/src/plugins/addParams.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import $ from 'jquery';

export default class addParams {
constructor(element, options) {
Expand Down
2 changes: 0 additions & 2 deletions js/src/plugins/ajaxec.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import $ from 'jquery';

export default class ajaxec {
constructor(element, options) {
const $element = $(element);

// ask for user confirmation just before
// TODO: because this is constructor, button can't be clicked again :(
if (options.confirm) {
if (!confirm(options.confirm)) {
return ;
Expand Down
45 changes: 45 additions & 0 deletions js/src/plugins/createModal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@

export default class createModal {
constructor(element, options) {

let $m = $('<div class="atk-modal ui modal scrolling"/>').appendTo('body').html(this.getDialogHtml(options.title));

$m.modal($.extend({
onHide: function (el) {
return true;
},
onHidden: function () {
$m.remove();
},
onVisible: function () {
$.getJSON(options.uri, options.uri_options, function (resp) {
$m.find('.atk-dialog-content').html(resp.html);
const result = function(){ eval(resp.eval.replace(/<\/?script>/g, '')); }.call(this.obj);
}).fail(function(){
console.log('Error loading modal content.')
});
$m.on("close", '.atk-dialog-content', function () {
$m.modal('hide');
});
}}, options.modal)).modal('show');
}

getDialogHtml(title) {
return `<i class="close icon"></i>
<div class="header">${title}</div>
<div class="image content atk-dialog-content">
<div class="ui active inverted dimmer">
<div class="ui text loader">Loading</div>
</div>
</div>`;
}
}

createModal.DEFAULTS = {
title: '',
uri: null,
uri_options: {},
modal: {
duration: 100
}
};
11 changes: 7 additions & 4 deletions js/src/plugins/reloadView.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import $ from 'jquery';

export default class reloadView {
constructor(element, options) {
Expand All @@ -9,11 +8,15 @@ export default class reloadView {
'active': true,
'inline': true,
'centered': true,
'replace': true});
'replace': false});

if(options.uri) {
$.get(options.uri, options.uri_options, (data) => {
$element.replaceWith(data);
$element.api({
on: 'now',
url: options.uri,
data: options.uri_options,
method: 'GET',
obj: $element
});
}
}
Expand Down
3 changes: 1 addition & 2 deletions js/src/plugins/spinner.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import $ from 'jquery';

export default class spinner {
constructor(element, options) {
Expand Down Expand Up @@ -53,4 +52,4 @@ spinner.DEFAULTS = {
centered: false,
baseDimmerMarkup: '<div class="ui dimmer"></div>',
baseLoaderMarkup: '<div class="ui loader"></div>',
};
};
8 changes: 3 additions & 5 deletions js/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,20 @@ const config = {
test: /(\.jsx|\.js)$/,
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/
},
}//,
// {
// test: /(\.jsx|\.js)$/,
// loader: "eslint-loader",
// exclude: /node_modules/
// }
]
},
externals: {jquery: 'jQuery'},
resolve: {
modules: [path.resolve('./src'), path.join(__dirname, 'node_modules')],
extensions: ['.json', '.js'],
},
plugins: plugins,
externals: {
'jquery': 'jQuery'
}
plugins: plugins
};

module.exports = config;
2 changes: 1 addition & 1 deletion src/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ public function ajaxSubmit()
$this->add(new View(['element'=>'input']))
->setAttr('name', $cb->name)
->setAttr('value', 'submit')
->setAttr('type', 'hidden');
->setStyle(['display'=>'none']);

$cb->set(function () {
try {
Expand Down
3 changes: 1 addition & 2 deletions src/TableColumn/Delete.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ public function init()

$reload = $this->table->reload ?: $this->table;

$ajaxec = (new \atk4\ui\jQuery($reload))->replaceWith($reload->render())->jsRender();
$this->table->app->terminate(json_encode(['success'=>true, 'message'=>'Success', 'eval'=>$ajaxec]));
$this->table->app->terminate($reload->renderJSON());
});

$this->table->on('click', 'a.'.$this->short_name)->ajaxec([
Expand Down
35 changes: 35 additions & 0 deletions src/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,41 @@ public function render($force_echo = true)
$this->template->render();
}

/**
* Render View using json format.
*
* @param bool $force_echo
*
* @return string
*/
public function renderJSON($force_echo = true)
{
try {
$this->renderAll();

return json_encode(['success'=> true,
'message'=> 'Success',
'eval' => $this->getJS($force_echo),
'html' => $this->template->render(),
'id' => $this->name, ]);
} catch (\Exception $exception) {
$l = $this->add(new self());
if ($exception instanceof \atk4\core\Exception) {
$l->template->setHTML('Content', $exception->getHTML());
} elseif ($exception instanceof \Error) {
$l->add(new self(['ui'=> 'message', get_class($exception).': '.
$exception->getMessage().' (in '.$exception->getFile().':'.$exception->getLine().')',
'error', ]));
$l->add(new Text())->set(nl2br($exception->getTraceAsString()));
} else {
$l->add(new self(['ui'=>'message', get_class($exception).': '.$exception->getMessage(), 'error']));
}

return json_encode(['success' => false,
'message' => $l->getHTML(), ]);
}
}

/**
* Created for recursive rendering or when you want to only get HTML of
* this object (not javascript).
Expand Down
3 changes: 3 additions & 0 deletions src/VirtualPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ public function init()
}

if ($this->cb->triggered == 'cut') {
if (isset($_GET['json'])) {
$this->app->terminate($this->renderJSON());
}
$this->app->terminate($this->render());
}

Expand Down
26 changes: 2 additions & 24 deletions src/jsModal.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,7 @@ public function __construct($title, $url, $args = [])
if ($url instanceof VirtualPage) {
$url = $url->getURL('cut');
}

$content = '
<i class="close icon"></i>
<div class="header">
'.htmlspecialchars($title).'
</div>
<div class="image content atk-dialog-content">
<div class="ui active inverted dimmer">
<div class="ui text loader">Loading</div>
</div>


</div>
';

parent::__construct('
var m=$("<div>").appendTo("body").addClass("ui scrolling modal").html([content]);
m.modal({duration: 100, onHide: function() { m.children().remove(); return true; }}).modal("show").find(".content").load($.addParams([url], [arg]), function() { m.modal("refresh"); });
m.find(".atk-dialog-content").data("opener", this).on("close", function() {
m.modal("hide");
m.remove();
});
',
['content'=>$content, 'url'=>$url, 'arg'=>$args]);
$args = array_merge($args, ['json'=>true]);
parent::__construct('$(this).createModal([arg])', ['arg'=>['uri'=>$url, 'title'=>$title, 'uri_options'=>$args]]);
}
}
2 changes: 1 addition & 1 deletion src/jsReload.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function __construct($view, $args = [])

$this->cb = $this->view->_add(new CallbackLater());
$this->cb->set(function () {
$this->view->app->terminate($this->view->render());
$this->view->app->terminate($this->view->renderJSON());
});
}

Expand Down
23 changes: 0 additions & 23 deletions template/semantic-ui/html.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,6 @@
<head>
<title>{title}Agile UI - Untitled Project{/}</title>{$meta}
<meta charset="utf-8">{$HEAD}
<script>
$.fn.api.settings.successTest = function(response) {
if(response && response.eval) {
try {
var result = function(){ eval(response.eval); }.call(this.obj);
} catch (e) {
//alert(e);
}
}
return true;
}

$.fn.api.settings.onFailure = function(response) {
w=window.open(null,'Error in JSON response','height=1000,width=1100,location=no,menubar=no,scrollbars=yes,status=no,titlebar=no,toolbar=no');
if(w){
w.document.write('<h5>Error in JSON response</h5>');
w.document.write(response);
w.document.write('<center><input type=button onclick="window.close()" value="Close"></center>');
}else{
alert("Error in ajaxec response"+response);
}
}
</script>
<style type="text/css">{$style}</style>
</head>
<body class="{$class}">{$Content}</body>
Expand Down
Loading