How to restrict SlickGrid to make a API call, while clicking or changing compound filters? - slickgrid

I have a SlickGrid Table, in which there are compound filters, currently when i try to change the compound filter (lets say from Equal To to Less Than), then it makes an API call.
I don't want to make an API call, how do i achieve this?
I searched in slickgrid docs, but couldn't find any property(if it is available).
Image

Please note that I'm the author of Angular-Slickgrid
So I looked at the problem you're having and it seems like a valid problem to look into, I agree that for some filters like the Compound Date Filter Operator we shouldn't query right away, that is after changing a the operator dropdown without providing a date. So, for that reason I am adding a new grid option skipCompoundOperatorFilterWithNullInput which will avoid triggering a filter change (it will also avoid querying the backend when implemented) when we first change the operator dropdown without providing a date being entered.
Note that this new option will only be available with Angular-Slickgrid v5.1.0+ (via this PR, now supports this and it will only be enabled by default on the Compound Date Filter (any other filters will have to explicitly enable this new flag either via grid option or via a column definition).
What if I cannot upgrade to 5.1.0? Are there any other ways of dealing with this?
Yes, it's just a bit more involving dealing with this though, it however requires a lot more work from your side. The information you need to know is that nearly every piece of code from Angular-Slickgrid and Slickgrid-Universal are protected TypeScript classes and functions which mean that you can simply use TypeScript to extends any of them. Let's take for example the CompoundDateFilter class, we could extend it this way to skip the callback triggering without a date provided (this._currentDate)
import { CompoundDateFilter, OperatorString } from '#slickgrid-universal/common';
export class CustomCompoundDateFilter extends CompoundDateFilter {
protected onTriggerEvent(e: Event | undefined) {
if (this._clearFilterTriggered) {
this.callback(e, { columnDef: this.columnDef, clearFilterTriggered: this._clearFilterTriggered, shouldTriggerQuery: this._shouldTriggerQuery });
this._filterElm.classList.remove('filled');
} else {
const selectedOperator = this._selectOperatorElm.value as OperatorString;
(this._currentValue) ? this._filterElm.classList.add('filled') : this._filterElm.classList.remove('filled');
// -- NEW CODE BELOW -- (to skip triggering callback on undefined date)
// when changing compound operator, we don't want to trigger the filter callback unless the date input is also provided
if (this._currentDate !== undefined) {
this.callback(e, { columnDef: this.columnDef, searchTerms: (this._currentValue ? [this._currentValue] : null), operator: selectedOperator || '', shouldTriggerQuery: this._shouldTriggerQuery });
}
}
this._clearFilterTriggered = false;
this._shouldTriggerQuery = true;
}
}
then use this new custom filter class in your column definitions
import { CustomCompoundDateFilter } from './custom-compoundDateFilter';
initGrid() {
this.columnDefinitions = [{
id: 'start', name: 'Start', field: 'start',
filterable: true, filter: { model: CustomCompoundDateFilter },
}];
}
and there you have it, below is a proof that it is working since I changed the operator and as you can see below this action is no longer resulting in 0 row returned. However if I had done the inverse, which is to input the date but without an operator, it would have execute the filtering because "no operator" is defaulting to the "equal to" operator.

Related

Cypress: Is there a way to write a command that can check a checkbox using UI

Currently, I am following cypress's example below and it works perfectly for the type commands. However, I have too many commands and I am trying to condense whichever ones I can. In this case, I only need to be able to check a box in certain tests but not sure how I would go about it. Any hints/ tips/ advice would be greatly appreciated. :)
Cypress.Commands.add('typeLogin', (user) => {
cy.get('input[name=email]').type(user.email)
cy.get('input[name=password]').type(user.password)
cy.get('input[name=checkbox]').check(user.checkbox)?
})
In the test:
const user = { email: 'fake#email.com', password: 'Secret1' }';
cy.typeLogin(user ) => {...
You can provide the checkbox to use (or whether to check/not check the checkbox) in your data model. From there, you have a few different options, depending on how your application is set up. If you only have one checkbox that should either be checked or not checked, you can use a boolean (useCheckbox below). If there are several values to choose from, you could pass in a string to use (this could be either a selector, if there are different selectors, or a value, if it is the same selector with different values).
const user = { email: 'foo#foo.com', password: 'foo', useCheckbox: true, checkbox: 'bar' }
...
Cypress.Commands.add('typeLogin', (user) => {
cy.get('input[name=email]').type(user.email)
cy.get('input[name=password]').type(user.password)
// we could use either `useCheckbox` to evaluate a boolean
if (user.useCheckbox) {
cy.get('input[name=checkbox]').check()
}
// or we could use the the `checkbox` field if we always to to check, we're just unsure of the value.
// in the first case, `user.checkbox` is the selector to use
cy.get(user.checkbox).check()
// in this second case, `user.checkbox` is the value to select
cy.get('input[name=checkbox]').check(user.checkbox)
})

spfx - onpropertychange event

I have created cascading dropdown. I need to load dropdown based on parent dropdown selection. I am trying to use onpropertychange event. but I am getting error on super.onpropertychange saying {Property 'onPropertyChange' does not exist on type 'BaseClientSideWebPart'.}
please let us know what I havve missed.
protected onPropertyChange(propertyPath: string, newValue: any):void{
if(propertyPath === "listDropDown"){
// Change only when drop down changes
super.onPropertyChange(propertyPath,newValue);
// Clears the existing data
this.properties.ItemsDropDown = undefined;
this.onPropertyChange('ItemsDropDown', this.properties.ItemsDropDown);
// Get/Load new items data
this.GetItems();
}
else {
// Render the property field
super.onPropertyChange(propertyPath, newValue);
}
}
Instead of onPropertyChange, perhaps you mean onPropertyFieldChanged from the BaseWebPart class?
The error message is accurate - web parts don't have a method called onPropertyChange. The above sounds like the closest match for what you are trying to do. Note that it takes not two arguments, but three: propertyPath, oldValue, and newValue.

Passing parameters from Command to Converter

I defined a new type of model element as a plug-in; let's refer to it as Foo. A Foo node in the model should translate to a section element in the view. So far, so good. I managed to do that by defining simple conversion rules. I also managed to define a new FooCommand that transforms (renames) selected blocks to Foo.
I got stuck trying to have attributes on those Foo model nodes be translated to attributes on the view elements (and vice-versa). Suppose Foos have an attribute named fooClass which should map to the view element's class attribute.
<Foo fooClass="green-foo"> should map to/from <section class="green-foo">
I can successfully receive parameters in FooCommand, but I can't seem to set them on the blocks being processed by the command:
execute(options = {}) {
const document = this.editor.document;
const fooClass = options.fooClass;
document.enqueueChanges(() => {
const batch = options.batch || document.batch();
const blocks = (options.selection || document.selection).getSelectedBlocks();
for (const block of blocks) {
if (!block.is('foo')) {
batch.rename(block, 'foo');
batch.setAttribute(block, 'fooClass', fooClass);
}
}
});
}
Below is the code for the init function in the Foo plugin, including the model→view and view→model conversions:
init() {
const editor = this.editor;
const doc = editor.document;
const data = editor.data;
const editing = editor.editing;
editor.commands.add('foo', new FooCommand(editor));
doc.schema.registerItem('foo', '$block');
buildModelConverter().for(data.modelToView, editing.modelToView)
.fromElement('foo')
.toElement(modelElement => {
const fooClass = modelElement.item.getAttribute('fooClass'));
return new ContainerElement('section', {'class': fooClass});
});
buildViewConverter().for(data.viewToModel)
.fromElement('section')
.toElement(viewElement => {
let classes = Array.from(viewElement.getClassNames());
let modelElement = new ModelElement('foo', {'fooClass': classes[0]});
return modelElement;
});
}
When I try to run the command via
editor.execute('foo', { fooClass: 'green-foo' })
I can see that the green-foo value is available to FooCommand, but the modelElement in the model→view conversion, on the other hand, has no fooClass attribute.
I'm sure I'm missing the point here and misusing the APIs. I'd be really thankful if someone could shed some light on this issue. I can provide more details, as needed.
Follow-up after initial suggestions
Thanks to #Reinmar and #jodator for their suggestion regarding configuring the document schema to allow for the custom attribute. I really thought that would have taken care of it, but no. It may have been a necessary step anyway, but I'm still unable to get the attribute value from the model element during the model→view conversion.
First, let me add an important piece of information I had left out: the CKEditor5's version I'm working with is 1.0.0-alpha2. I am aware several of the APIs are bound to change, but I would still like to get things working with the present version.
Model→view conversion
If I understand it correctly, one can either pass a string or a function to the toElement call. A question about using the latter: what exactly are the parameters passed to the function? I assumed it would be the model element (node?) to be converted. Is that the case? If so, why is the attribute set on that node via batch.setAttribute (inside a document.enqueueChanges) not available when requested? Should it be?
A sequencing problem?
Additional testing seems to indicate there's some kind of order-of-execution issue happening. I've observed that, even though the attribute is not available when I first try to read it from the modelElement parameter, it will be so if I read it again later. Let me try to illustrate the situation below. First, I'll modify the conversion code to make it use some dummy value in case the attribute value is not available when read:
buildModelConverter().for(data.modelToView, editing.modelToView)
.fromElement('foo')
.toElement(modelElement => {
let fooClass = modelElement.item.getAttribute('fooClass') || 'naught';
let viewElement = new ContainerElement('section');
viewElement.setAttribute('class', fooClass);
return viewElement;
});
Now I reload the page and execute the following instructions on the console:
c = Array.from(editor.document.getRoot().getChildren());
c[1].is('paragraph'); // true
// Changing the node from 'paragraph' to 'foo' and adding an attribute
// 'fooClass' with value 'green-foo' to it.
editor.document.enqueueChanges(() => {
const batch = editor.document.batch();
batch.rename(c[1], 'foo');
batch.setAttribute(c[1], 'fooClass', 'green-foo');
return batch;
});
c[1].is('paragraph'); // false
c[1].is('foo'); // true
c[1].hasAttribute('fooClass'); // true
c[1].getAttribute('fooClass'); // 'green-foo'
Even though it looks like the expected output is being produced, a glance at the generated view element shows the problem:
<section class="naught"/>
Lastly, even if I try to reset the fooClass attribute on the model element, the change is not reflected on the view element. Why is that? Shouldn't changes made via enqueueChanges cause the view to update?
Sorry for the very long post, but I'm trying to convey as many details as I can. Here's hoping someone will spot my mistake or misunderstanding of how the CKEditor 5's API actually works.
View not updating?
I turned to Document's events and experimented with the changesDone event. It successfully addresses the "timing" issue, as it consistently triggers only after all changes have been processed. Still, the problem of the view not updating in response to a change in the model remains. To make it clear, the model does change, but the view does not reflect that. Here is the call:
editor.document.enqueueChanges(() => editor.document.batch().setAttribute(c[1], 'fooClass', 'red-foo'));
To be 100% sure I wrote the whole feature myself. I use the 1.0.0-beta.1 API which is completely different than what you had.
Basically – it works. It isn't 100% correct yet, but I'll get to that.
How to convert an element+attribute pair?
The thing when implementing a feature which needs to convert element + attribute is that it requires handling the element and attribute conversion separately as they are treated separately by CKEditor 5.
Therefore, in the code below you'll find that I used elementToElement():
editor.conversion.elementToElement( {
model: 'foo',
view: 'section'
} );
So a converter between model's <foo> element and view's <section> element. This is a two-way converter so it handles upcasting (view -> model) and downcasting (model -> view) conversion.
NOTE: It doesn't handle the attribute.
Theoretically, as the view property you could write a callback which would read the model element's attribute and create view element with this attribute set too. But that wouldn't work because such a configuration would only make sense in case of downcasting (model -> view). How could we use that callback to downcast a view structure?
NOTE: You can write converters for downcast and upcast pipelines separately (by using editor.conversion.for()), in which case you could really use callbacks. But it doesn't really make sense in this case.
The attribute may change independently!
The other problem is that let's say you wrote an element converter which sets the attribute at the same time. Tada, you load <section class=ohmy> and gets <foo class=ohmy> in your model.
But then... what if the attribute will change in the model?
In the downcast pipeline CKEditor 5 treats element changes separately from attribute changes. It fires them as separate events. So, when your FooCommand is executed on a heading it calls writer.rename() and we get the following events in DowncastDispatcher:
remove with <heading>
insert:section
But then the attribute is changed too (writer.setAttribute()), so we also get:
setAttibute:class:section
The elementToElement() conversion helper listens to insert:section event. So it's blind to setAttribute:class:selection.
Therefore, when you change the value of the attribute, you need the attributeToAttribute() conversion.
Sequencing
I didn't want to reply to your question before we released 1.0.0-beta.1 because 1.0.0-beta.1 brought the Differ.
Before 1.0.0-beta.1 all changes were converted immediately when they were applied. So, rename() would cause immediate remove and insert:section events. At this point, the element that you got in the latter one wouldn't have the class attribute set yet.
Thanks to the Differ we're able to start the conversion once all the changes are applied (after change() block is executed). This means that the insert:section event is fired once the model <foo> element has the class attribute set already. That's why you could write a callback-based converters... bur you shouldn't :D
The code
import { downcastAttributeToAttribute } from '#ckeditor/ckeditor5-engine/src/conversion/downcast-converters';
import { upcastAttributeToAttribute } from '#ckeditor/ckeditor5-engine/src/conversion/upcast-converters';
class FooCommand extends Command {
execute( options = {} ) {
const model = this.editor.model;
const fooClass = options.class;
model.change( writer => {
const blocks = model.document.selection.getSelectedBlocks();
for ( const block of blocks ) {
if ( !block.is( 'foo' ) ) {
writer.rename( block, 'foo' );
writer.setAttribute( 'class', fooClass, block );
}
}
} );
}
}
class FooPlugin extends Plugin {
init() {
const editor = this.editor;
editor.commands.add( 'foo', new FooCommand( editor ) );
editor.model.schema.register( 'foo', {
allowAttributes: 'class',
inheritAllFrom: '$block'
} );
editor.conversion.elementToElement( {
model: 'foo',
view: 'section'
} );
editor.conversion.for( 'upcast' ).add(
upcastAttributeToAttribute( {
model: 'class',
view: 'class'
} )
);
editor.conversion.for( 'downcast' ).add(
downcastAttributeToAttribute( {
model: 'class',
view: 'class'
} )
);
// This should work but it does not due to https://github.com/ckeditor/ckeditor5-engine/issues/1379 :(((
// EDIT: The above issue is fixed and will be released in 1.0.0-beta.2.
// editor.conversion.attributeToAttribute( {
// model: {
// name: 'foo',
// key: 'class'
// },
// view: {
// name: 'section',
// key: 'class'
// }
// } );
}
}
This code works quite well, except the fact that it converts the class attribute on any possible element that has it. That's because I had to use very generic downcastAttributeToAttribute() and upcastAttributeToAttribute() converters because of a bug that I found (EDIT: it's fixed and will be available in 1.0.0-beta.2). The commented out piece of code is how you it should be defined if everything worked fine and it will work in 1.0.0-beta.2.
It's sad that we missed such a simple case, but that's mainly due to the fact that all our features... are much more complicated than this.

Ember-validation how to implement lazy validation

I am using ember-cli:2.5.0 and ember-validations:v2.0.0-alpha.5
In my ember-component i have a validation which is running automatically for each change in a attribute but i want to run this validation only if i call "validate()" method in technical term call validation lazily.
Please find the below code samples,
import Ember from 'ember';
import EmberValidations, { validator } from 'ember-validations';
export default Ember.Component.extend(EmberValidations, {
didReceiveAttrs() {
this.set('newBook', this._bookModel().create());
},
_bookModel(data = {}) {
return Ember.Object.extend(EmberValidations, {
bookVersion: null,
isEditable: false,
validationActive: false,
validations: {
bookVersion: {
inline: validator(function() {
if(this.validationActive){ //Here this.validationActive always return undefined
var version = this.model.get('bookVersion') || "",
message = [];
if (Ember.isEmpty(bookVersion)) {
message.push("Book Version is mandatory!!!");
}
if (message.length > 0) {
return message.join(',');
}
}
})
}
}
}, data);
}
});
actions: {
this.get('newBook').set("validationActive",true);
this.get('newBook').validate().then(() => {
//Do the action
}
}
I want the above validation to run only calling "this.get('newBook').validate()". I am entirely new to ember so down-voter please put your comments before down-voting for others kindly let me know for any more code samples.
Your help should be appreciable.
The addon you are using for validations ("ember-validations") is a very popular one and its documentation is pretty well when compared to others. If you look at the documentation there is a part named "Conditional Validators" in documentation. You can use a boolean property to control when the validation is to be performed.
You can see an illustration of what I mean in the following twiddle. I have created a simple validation within the application controller for user's name. The name field must have a length of at least 5 and the validation is to be performed only if the condition validationActive is true. Initially; the condition is false; which means validator did not work and isValid property of Controller (which is inherited from EmberValidations Mixin) is true. If you toggle the property with the button provided; the validation will run (since the condition is now set to true; hence validation is triggered) and isValid will return to false. If you change the value; the validation result will change appropriately with respect to the value of user's name. If you toggle the condition once again to set it to false; then isValid will become true no matter what the valie of user's name is.
I hope this gives you an insight about how to control when your validations should work.
Here is what you should do after your edit: The field is undefined because you are trying to reach component's own validationActive field within inline validator. Please get validationActive as follows this.model.get('validationActive') and give a try. It should work.

Calling multiple views in CouchApp query

I need to search the CouchDB based on several criteria entered in a form. Name, an array of Tags and so on. I would then need various views to index on these fields. Ultimately, all the results will be collated in data.js and provided to mustache.html. Say there are 3 views - docsByName, docsByTags, docsById.
What I don't know is, how to query all these views in query.js. Can this be done and how ?
Or should the approach be of that to write one view that makes multiple emits for each search somehow ?
Thank you.
From what you say I assume you are using Evently, so I will quote from Evently primer:
The async function is the main star, which in this case makes an Ajax request (but it can do anything it wants). Another important thing to note is that the first argument to the async function is a callback which you use to tell Evently when you are done with your asynchronous action. [...] Whatever you pass to the callback function then becomes the first item passed to the data function.
In short: put your Ajax requests in async.js.
As a side note: Evently is only one of the possible choices to write a couchapp and it is not clear if it is maintained. However it works and it is easy to rearrange the code to not use it.
EDIT: here is a sample async function (cut&paste from an old program):
function(cb, e) {
var app = $$(this).app
;
app.db.openDoc('SOMEDOCID', {
error: function(code, error, reason) {
alert("Error("+code+" "+error+"): "+reason);
}
, success: function(doc) {
app.view('SOMEVIEWNAME', {
include_docs: true
, error: function(code, error, reason) {
alert("Error("+code+" "+error+"): "+reason);
}
, success: function(resp) {
resp.doc = doc;
cb(resp);
}
});
}
});
}

Resources