Does changing dojo.dnd.Source.checkAcceptance to true affect type checking? - dojo

I've got a working DnD implementation however I've run into a snag. It seems that if I set dojo.dnd.Source.checkAcceptance to true, the Source container I do that to stops checking the dndType, it accepts everything.
I'm checking if there is a node present in the dojo.dnd.Source container, if there is I want to disable dropping. I do this twice because if content is already present when the page loads, we want to disable dropping additional content there and only allow the Source container to contain 1 node. Likewise for the onDrop event.
If checkAcceptance = false, then that works and doesn't accept any drops, however if checkAcceptance = true then it accepts everything.
I'm using dojo version 1.4.2.
Here's the offending code:
var contentSourceA = new dojo.dnd.Source("ContentCol",{accept: ["contentItem"]});
if (dojo.query("#ContentCol")[0].children.length > 1) {
contentSourceA.checkAcceptance = function(){return false;}
}else{
contentSourceA.checkAcceptance = function(){return true;}
}
dojo.connect(contentSourceA,'onDrop',function(source,node,copy){
if (dojo.query("#ContentCol")[0].children.length > 1) {
contentSourceA.checkAcceptance = function(){return false;}
}else{
contentSourceA.checkAcceptance = function(){return true;}
}
});
So hence my question: Does changing dojo.dnd.Source.checkAcceptance affect the type checking functionality? If not, what have I done wrong here? Should I do this via one of the Topic events?

The type checking logic is encapsulated in the default implementation of dojo.dnd.Source.checkAcceptance function. If you override this function, the default logic is lost.
You can create your own DnD source class by inheriting dojo.dnd.Source:
dojo.declare("AcceptOneItemSource", dojo.dnd.Source, {
checkAcceptance : function(source, nodes) {
if (this.node.children.length > 1) {
return false;
}
return this.inherited(arguments);
}
});

Related

How to prevent closing of cell edit mode on validation errors with custom vue components in ag-grid

I have succesfully rendered my own component as the cellEditor and would like and on-leave I would like it to try to validate the value and prevent the closing if it fails.
If I look at this then https://www.ag-grid.com/javascript-grid-cell-editing/#editing-api there's cancelable callback functions for editing. But in this callback function is there a way to access the current instantiated component? I would think that would be the easiest way to handle this.
I'm using vee-validate so the validation function is async, just to keep in mind.
Use Full row editing.
Create a global variable like
var problemRow = -1;
Then Subscribe to this events:
onRowEditingStarted: function (event) {
if (problemRow!=-1 && event.rowIndex!=problemRow) {
gridOptions.api.stopEditing();
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
},
onRowEditingStopped: function (event) {
if (problemRow==-1) {
if (event.data.firstName != "your validation") {
problemRow = event.rowIndex
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
}
if (problemRow == event.rowIndex) {
if (event.data.firstName != "your validation") {
problemRow = event.rowIndex
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
else{
problemRow=-1;
}
}
},
I had a similar issue - albeit in AngularJS and the non-Angular mode for ag-grid - I needed to prevent the navigation when the cell editor didn't pass validation.
The documentation is not very detailed, so in the end I added a custom cell editor with a form wrapped around the input field (to handle the niceties such as red highlighting etc), and then used Angular JS validation. That got me so far, but the crucial part was trying to prevent the user tabbing out or away when the value was invalid so the user could at least fix the issue.
I did this by adding a value parser when adding the cell, and then within that if the value was invalid according to various rules, throw an exception. Not ideal, I know - but it does prevent ag-grid from trying to move away from the cell.
I tried loads of approaches to solving this - using the tabToNextCell events, suppressKeyboardEvent, navigateToNextCell, onCellEditingStopped - to name a few - this was the only thing that got it working correctly.
Here's my value parser, for what it's worth:
var codeParser = function (args) {
var cellEditor = _controller.currentCellEditor.children['codeValue'];
var paycodeId = +args.colDef.field;
var paycodeInfo = _controller.paycodes.filter(function (f) { return f.id === paycodeId; })[0];
// Check against any mask
if (paycodeInfo && paycodeInfo.mask) {
var reg = new RegExp("^" + paycodeInfo.mask + '$');
var match = args.newValue.match(reg);
if (!match) {
$mdToast.show($mdToast.simple().textContent('Invalid value - does not match paycode format.').position('top right').toastClass('errorToast'))
.then(function(r) {
_controller.currentCellEditor.children['codeValue'].focus();
});
throw 'Invalid value - does not match paycode format.';
}
}
return true;
};
The _controller.currentCellEditor value is set during the init of the cell editor component. I do this so I can then refocus the control after the error has been shown in the toast:
CodeValueEditor.prototype.init = function (params) {
var form = document.createElement('form');
form.setAttribute('id', 'mainForm');
form.setAttribute('name', 'mainForm');
var input = document.createElement('input');
input.classList.add('ag-cell-edit-input');
input.classList.add('paycode-editor');
input.setAttribute('name', 'codeValue');
input.setAttribute('id', 'codeValue');
input.tabIndex = "0";
input.value = params.value;
if (params.mask) {
input.setAttribute('data-mask', params.mask);
input.setAttribute('ng-pattern','/^' + params.mask + '$/');
input.setAttribute('ng-class',"{'pattern-error': mainForm.codeValue.$error.pattern}");
input.setAttribute('ng-model', 'ctl.currentValue');
}
form.appendChild(input);
this.container = form;
$compile(this.container)($scope);
_controller.currentValue = null;
// This is crucial - we can then reference the container in
// the parser later on to refocus the control
_controller.currentCellEditor = this.container;
$scope.$digest();
};
And then cleared in the grid options onCellEditingStopped event:
onCellEditingStopped: function (event) {
$scope.$apply(function() {
_controller.currentCellEditor = null;
});
},
I realise it's not specifically for your components (Vue.js) but hopefully it'll help someone else. If anyone has done it a better way, I'm all ears as I don't like throwing the unnecessary exception!

How does Selenium WebDriver's isDisplayed() method work

I currently have a large number of circumstances where I need to verify that a page (along with all of its elements) are displaying correctly. The isDisplayed() method of WebElement appears to be a logical way to do this, however I would like to understand precisely what this method is doing to determine whether or not an element "is displayed". The javadoc does not shed any light on the inner workings of the method and other information on the web appears to be sparse at best.
If anyone could provide a detailed description of how this method works, I would be very grateful.
I would trust in Selenium to work out if an element is displayed or not. If it doesn't work you can raise a bug and/or fix any issues you see and provide a patch.
This is what the method does (Taken from the current Selenium source code):
/**
* Determines whether an element is what a user would call "shown". This means
* that the element is shown in the viewport of the browser, and only has
* height and width greater than 0px, and that its visibility is not "hidden"
* and its display property is not "none".
* Options and Optgroup elements are treated as special cases: they are
* considered shown iff they have a enclosing select element that is shown.
*
* #param {!Element} elem The element to consider.
* #param {boolean=} opt_ignoreOpacity Whether to ignore the element's opacity
* when determining whether it is shown; defaults to false.
* #return {boolean} Whether or not the element is visible.
*/
bot.dom.isShown = function(elem, opt_ignoreOpacity) {
if (!bot.dom.isElement(elem)) {
throw new Error('Argument to isShown must be of type Element');
}
// Option or optgroup is shown iff enclosing select is shown (ignoring the
// select's opacity).
if (bot.dom.isElement(elem, goog.dom.TagName.OPTION) ||
bot.dom.isElement(elem, goog.dom.TagName.OPTGROUP)) {
var select = /**#type {Element}*/ (goog.dom.getAncestor(elem, function(e) {
return bot.dom.isElement(e, goog.dom.TagName.SELECT);
}));
return !!select && bot.dom.isShown(select, /*ignoreOpacity=*/true);
}
// Image map elements are shown if image that uses it is shown, and
// the area of the element is positive.
var imageMap = bot.dom.maybeFindImageMap_(elem);
if (imageMap) {
return !!imageMap.image &&
imageMap.rect.width > 0 && imageMap.rect.height > 0 &&
bot.dom.isShown(imageMap.image, opt_ignoreOpacity);
}
// Any hidden input is not shown.
if (bot.dom.isElement(elem, goog.dom.TagName.INPUT) &&
elem.type.toLowerCase() == 'hidden') {
return false;
}
// Any NOSCRIPT element is not shown.
if (bot.dom.isElement(elem, goog.dom.TagName.NOSCRIPT)) {
return false;
}
// Any element with hidden visibility is not shown.
if (bot.dom.getEffectiveStyle(elem, 'visibility') == 'hidden') {
return false;
}
// Any element with a display style equal to 'none' or that has an ancestor
// with display style equal to 'none' is not shown.
function displayed(e) {
if (bot.dom.getEffectiveStyle(e, 'display') == 'none') {
return false;
}
var parent = bot.dom.getParentElement(e);
return !parent || displayed(parent);
}
if (!displayed(elem)) {
return false;
}
// Any transparent element is not shown.
if (!opt_ignoreOpacity && bot.dom.getOpacity(elem) == 0) {
return false;
}
// Any element with the hidden attribute or has an ancestor with the hidden
// attribute is not shown
function isHidden(e) {
//IE does not support hidden attribute yet
if (goog.userAgent.IE) {
return true;
}
if (e.hasAttribute) {
if (e.hasAttribute('hidden')){
return false;
}
} else {
return true;
}
var parent = bot.dom.getParentElement(e);
return !parent || isHidden(parent);
}
if (!isHidden(elem)) {
return false;
}
// Any element without positive size dimensions is not shown.
function positiveSize(e) {
var rect = bot.dom.getClientRect(e);
if (rect.height > 0 && rect.width > 0) {
return true;
}
// A vertical or horizontal SVG Path element will report zero width or
// height but is "shown" if it has a positive stroke-width.
if (bot.dom.isElement(e, 'PATH') && (rect.height > 0 || rect.width > 0)) {
var strokeWidth = bot.dom.getEffectiveStyle(e, 'stroke-width');
return !!strokeWidth && (parseInt(strokeWidth, 10) > 0);
}
// Zero-sized elements should still be considered to have positive size
// if they have a child element or text node with positive size, unless
// the element has an 'overflow' style of 'hidden'.
return bot.dom.getEffectiveStyle(e, 'overflow') != 'hidden' &&
goog.array.some(e.childNodes, function(n) {
return n.nodeType == goog.dom.NodeType.TEXT ||
(bot.dom.isElement(n) && positiveSize(n));
});
}
if (!positiveSize(elem)) {
return false;
}
// Elements that are hidden by overflow are not shown.
if (bot.dom.getOverflowState(elem) == bot.dom.OverflowState.HIDDEN) {
return false;
}
Not sure it really needs any more explanation, the comments are quite clear. Let me know if you want any more info added.
WebDriver has its own W3C specification.
The section about determining visibility is what you are after.
I would warn that saying something "is displayed" is such a broad term, and thus there are many scenarios to it. Therefore, there may well be situations that WebDriver does not account for.
So it's important, vital in fact, to remember that something being "displayed" or "visible" has many meanings. (In the same way a page being fully loaded, also has many meanings.)
Also remember Selenium is entirely open source. There is nothing stopping you from getting a fresh checkout of the repository and inspecting it locally.
As per the documentation isDisplayed() method determines whether the WebElement is displayed or not and returns a boolean whether or not the element is displayed or not. This method avoids the problem of having to parse an element's style attribute.
This implementation is inline with the specification with in the WebDriver Level 2 W3C Working Draft which mentions:
Although WebDriver does not define a primitive to ascertain the
visibility of an
element in the
viewport,
we acknowledge that it is an important feature for many users. Here we
include a recommended approach which will give a simplified
approximation of an element’s visibility, but please note that it
relies only on tree-traversal, and only covers a subset of visibility
checks.
The visibility of an element is guided by what is perceptually visible
to the human eye. In this context, an element’s displayedness does not
relate to the
visibility or
display style
properties.
The approach recommended to implementors to ascertain an element’s
visibility was originally developed by the Selenium project, and is
based on crude approximations about an element's nature and
relationship in the tree. An element is in general to be considered
visible if any part of it is drawn on the canvas within the boundaries
of the viewport.
The element displayed algorithm is a boolean state where true
signifies that the element is displayed and false signifies that the
element is not displayed. To compute the state on element, invoke the
Call(bot.dom.isShown, null, element). If doing so does not produce an
error, return the return value from this function call. Otherwise
return an error with error code unknown error.
This function is typically exposed to GET requests with a URI Template of:
/session/{session id}/element/{element id}/displayed

OpenTok - How to publish/unpublish manually?

I looked at these links
http://www.tokbox.com/opentok/api/tools/js/documentation/overview/publish.html
http://www.tokbox.com/opentok/api/tools/js/tutorials/overview
but their are no examples for publishingunpublishing manually, that is, publishing/unpublishing without using 'streamCreated'/'streamDestroyed' event handler respectively.
The reason I want to do this is that I have a button to publish/unpublish so that the user can do it at will.
Is there a way to do this?
Yes and it is very simple. Check out the prepublish source code to see how. There are 2 functions, startPublishing() and stopPublishing() which achieve this.
Primarily they use session.publish(publisher);to publish and session.unpublish(publisher); to unpublish.
Here is code I have used to work off:
// Called by a button to start publishing to the session
function startPublishing() {
if (!publisher) {
var parentDiv = document.getElementById("myCamera");
var publisherDiv = document.createElement('div'); // Create a div for the publisher to replace
publisherDiv.setAttribute('id', 'opentok_publisher');
parentDiv.appendChild(publisherDiv);
var publisherProps = {
width : VIDEO_WIDTH,
height : VIDEO_HEIGHT
};
publisher = TB.initPublisher(apiKey, publisherDiv.id, publisherProps); // Pass the replacement div id and properties
session.publish(publisher);
show('unpublishLink');
hide('publishLink');
}
}
//Called by a button to stop publishing to the session
function stopPublishing() {
if (publisher) {
session.unpublish(publisher);
}
publisher = null;
show('publishLink');
hide('unpublishLink');
}

Yii renderpartial (proccessoutput = true) Avoid Duplicate js request

Im creating a site who works with ajaxRequest, when I click a link, it will load using ajaxRequest. When I load for example user/login UserController actionLogin, I renderPartial the view with processOUtput to true so the js needed inside that view will be generated, however if I have clientScriptRegister inside that view with events, how can I avoid to generate the scriptRegistered twice or multiple depending on the ajaxRequest? I have tried Yii::app()->clientScript->isSCriptRegistered('scriptId') to check if the script is already registered but it seems that if you used ajaxRequest, the result is always false because it will only be true after the render is finished.
Controller code
if (Yii::app()->request->isAjaxRequest)
{
$this->renderPartial('view',array('model'=>$model),false,true);
}
View Code
if (!Yii::app()->clientScript->isScriptregistered("view-script"))
Yii::app()->clientScript->registerScript("view-script","
$('.link').live('click',function(){
alert('test');
})
");
If I request for the controller for the first time, it works perfectly (alert 1 time) but if I request again for that same controller without refreshing my page and just using ajaxRequest, the alert will output twice if you click it (because it keeps on generating eventhough you already registered it once)
This is the same if you have CActiveForm inside the view with jquery functionality.. the corescript yiiactiveform will be called everytime you renderPartial.
To avoid including core scripts twice
If your scripts have already been included through an earlier request, use this to avoid including them again:
// For jQuery core, Yii switches between the human-readable and minified
// versions based on DEBUG status; so make sure to catch both of them
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
If you have views that are being rendered both independently and as HTML fragments to be included with AJAX, you can wrap this inside if (Yii::app()->request->isAjaxRequest) to cover all bases.
To avoid including jQuery scripts twice (JS solution)
There's also the possibility of preventing scripts from being included twice on the client side. This is not directly supported and slightly more cumbersome, but in practice it works fine and it does not require you to know on the server side what's going on at the client side (i.e. which scripts have been already included).
The idea is to get the HTML from the server and simply strip out the <script> tags with regular expression replace. The important point is you can detect if jQuery core scripts and plugins have already been loaded (because they create $ or properties on it) and do this conditionally:
function stripExistingScripts(html) {
var map = {
"jquery.js": "$",
"jquery.min.js": "$",
"jquery-ui.min.js": "$.ui",
"jquery.yiiactiveform.js": "$.fn.yiiactiveform",
"jquery.yiigridview.js": "$.fn.yiiGridView",
"jquery.ba-bbq.js": "$.bbq"
};
for (var scriptName in map) {
var target = map[scriptName];
if (isDefined(target)) {
var regexp = new RegExp('<script.*src=".*' +
scriptName.replace('.', '\\.') +
'".*</script>', 'i');
html = html.replace(regexp, '');
}
}
return html;
}
There's a map of filenames and objects that will have been defined if the corresponding script has already been included; pass your incoming HTML through this function and it will check for and remove <script> tags that correspond to previously loaded scripts.
The helper function isDefined is this:
function isDefined(path) {
var target = window;
var parts = path.split('.');
while(parts.length) {
var branch = parts.shift();
if (typeof target[branch] === 'undefined') {
return false;
}
target = target[branch];
}
return true;
}
To avoid attaching event handlers twice
You can simply use a Javascript object to remember if you have already attached the handler; if yes, do not attach it again. For example (view code):
Yii::app()->clientScript->registerScript("view-script","
window.myCustomState = window.myCustomState || {}; // initialize if not exists
if (!window.myCustomState.liveClickHandlerAttached) {
window.myCustomState.liveClickHandlerAttached = true;
$('.link').live('click',function(){
alert('test');
})
}
");
The cleanest way is to override beforeAction(), to avoid any duplicated core script:
class Controller extends CController {
protected function beforeAction($action) {
if( Yii::app()->request->isAjaxRequest ) {
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-2.0.0.js'] = false;
Yii::app()->clientScript->scriptMap['anything.js'] = false;
}
return parent::beforeAction($action);
}
}
Note that you have to put the exact js file name, without the path.
To avoid including script files twice, try this extension: http://www.yiiframework.com/extension/nlsclientscript/
To avoid attaching event handlers twice, see Jons answer: https://stackoverflow.com/a/10188538/729324

Dojo DnD Move Node Programmatically

I would like to know if there is a way to move the node programmatically in dojo Dnd? The reason is I would like to revert the changes to the drag and drop when the web service call triggered a failed save on the database. Here is what I have so far.
In my code, the node Id seems to be unrecognized by the dojo.dnd.Container.DelItem. I cannot just use the selected item on the target because this is a asynchronous webservice function callback. So the user may be selecting another node on the container when this is called.
function OnMoveWSComplete(strResult) {
var resultObj = eval('(' + strResult + ')');
var sourceContainer = eval('(' + objResult.sourceContainerId + ')');
var targetContainer = eval('(' + objResult.targetContainerId + ')');
var targetNodes = targetContainer.getAllNodes();
for (var iNode = 0; iNode < targetNodes.length; iNode++) {
var currId = getLastIdFromStr(targetNodes[iNode].id);
if (currId == resultObj.Id) {
var targetN = targetNodes[iNode];
var Name = targetNodes[iNode].childNodes[0].nodeValue;
targetContainer.delItem(targetNodes[iNode].id);
var origData = { Id: resultObj.Id, Name: Name };
sourceContainer.insertNodes(true, origData);
break;
}
}
}
EDIT: Solution (Thanks Eugene Lazutkin) [2009/11/30]:
/**
* Move one node from one container to the other
*/
function moveNode(nodeId, sourceContainer, targetContainer) {
var node = dojo.byId(nodeId);
// Save the data
var saveData = sourceContainer.map[nodeId].data;
// Do the move
sourceContainer.parent.removeChild(node);
targetContainer.parent.appendChild(node);
// Sync the DOM object → map
sourceContainer.sync();
targetContainer.sync();
// Restore data for recreation of data
targetContainer.map[nodeId].data = saveData;
}
It looks like you assume that delItem removes physical nodes. Take a look at the documentation — probably you want to move nodes between containers instead of deleting them from the map. One simple way to do that just to move DOM nodes between containers, and call sync() on both containers.
Addition: Here is a super-simple pseudocode-like example:
function move(node, source, target){
// normalize node and/or node id
node = dojo.byId(node);
// move it physically from one parent to another
// (from target to source) adding to the end
target.parent.appenChild(node);
// now it is moved from source to target
// let's synchronize both dojo.dnd.Source's
source.sync();
target.sync();
}
Or something along these lines should work. The important pieces:
Move node from one parent to another using any DOM operations you deem appropriate. I used appendChild(), but you can use insertBefore(), or anything else.
Synchronize both sources involved after the move.
Obviously it works if both sources use nodes of the same type and structure. If not, you should do something more complex, e.g., move everything you need emulating a real DnD move by publishing topics described in the documentation.
I have this function which moves selected nodes by button click:
source.forInItems(dojo.hitch(this, function(item, id, map) {
if (dojo.hasClass(id, "dojoDndItemAnchor")) {
target.onDrop(source, [ dojo.byId(id) ], false);
dojo.removeClass(id, "dojoDndItemAnchor");
}
}));
onDrop() is an overridable method, which is called upon item drop, and by default calls to method onDropExternal(source, nodes, copy).
I am doing the same thing right now. I was able to solve by doing the following.
Set the dnd/Source autoSync property to true
<div data-dojo-type="dojo.dnd.Source" accept="widget" class="source" data-dojo-props="autoSync: true">
After dragging it looses the dndtype so I had to re-add it using client side code. Also I remove the dojoDndItemAnchor class after drop.
$(node).removeClass('dojoDndItemAnchor').attr('dndtype', 'widget');