Vaadin: open calendar on field focus for datefield - vaadin

Vaadin widgets are simple and awesome! But they are also poorly configurable.
I need my DateField widget to open calendar on focus event. I didn't find that functionality in official Vaadin documentation. I found some 3rd party widget here, but it's compiled for Vaadin 7.7 and I use latest Vaadin (8.0.6). Also it has Joda-time 2.1 dependency which is highly undesirable in my project. So, is there any simple way to tune stock vaadin DateField widget to open it's calendar on field focus, or do I need to write my own component for that? Any help is appreciated.

As I was saying in my comment, as far as I know, currently the framework does not offer an implicit way to programmatically open the calendar popup. The same thing goes for some other components such as the grid editor, or the combo item list.
One quick workaround I can think of, is to add a javascript extension that registers focus listeners for all date fields, and clicks the button when a date field is focused. Please find below a sample.
P.S. If you only need to apply this to only some date fields, you can add IDs and pass them to the JS, where you'll do something like document.getElementById('myDateFieldId') instead of document.getElementsByClassName("v-datefield").
1) Layout with components
public class MyDateFieldComponent extends HorizontalLayout {
public MyDateFieldComponent() {
// basic setup
DateField fromDateField = new DateField("From", LocalDate.of(2011, Month.FEBRUARY, 6));
DateField toDateField = new DateField("To", LocalDate.of(2018, Month.FEBRUARY, 6));
setSpacing(true);
addComponents(fromDateField, toDateField);
// add the extension
addExtension(new CalendarFocusPopupOpenerExtension());
}
}
2) Extension - java/server side
import com.vaadin.annotations.JavaScript;
import com.vaadin.server.AbstractJavaScriptExtension;
#JavaScript("calendar-focus-popup-opener-extension.js")
public class CalendarFocusPopupOpenerExtension extends AbstractJavaScriptExtension {
public CalendarFocusPopupOpenerExtension() {
// call the bind function defined in the associated JS
callFunction("bind");
}
}
3) Extension - js/client side
window.com_example_calendar_CalendarFocusPopupOpenerExtension = function () {
this.bind = function () {
if (document.readyState === "complete") {
// if executed when document already loaded, just bind
console.log("Doc already loaded, binding");
bindToAllDateFields();
} else {
// otherwise, bind when finished loading
console.log("Doc nod loaded, binding later");
window.onload = function () {
console.log("Doc finally loaded, binding");
bindToAllDateFields();
}
}
};
function bindToAllDateFields() {
// get all the date fields to assign focus handlers to
var dateFields = document.getElementsByClassName("v-datefield");
for (var i = 0; i < dateFields.length; i++) {
addFocusListeners(dateFields[i]);
}
}
function addFocusListeners(dateField) {
// when focusing the date field, click the button
dateField.onfocus = function () {
dateField.getElementsByTagName("button")[0].click();
};
// or when focusing the date field input, click the button
dateField.getElementsByTagName("input")[0].onfocus = function () {
dateField.getElementsByTagName("button")[0].click();
};
}
};
4) Result
LATER UPDATE
A second approach could be to assign some IDs to your fields, and then check periodically to see when all are visible, and as soon as they are, bind the focus listeners.
1) Layout with components
public class MyDateFieldComponent extends HorizontalLayout {
public MyDateFieldComponent() {
// basic setup
DateField fromDateField = new DateField("From", LocalDate.of(2011, Month.FEBRUARY, 6));
fromDateField.setId("fromDateField"); // use id to bind
fromDateField.setVisible(false); // initially hide it
DateField toDateField = new DateField("To", LocalDate.of(2018, Month.FEBRUARY, 6));
toDateField.setId("toDateField"); // use id to bind
toDateField.setVisible(false); // initially hide it
// simulate a delay until the fields are available
Button showFieldsButton = new Button("Show fields", e -> {
fromDateField.setVisible(true);
toDateField.setVisible(true);
});
setSpacing(true);
addComponents(showFieldsButton, fromDateField, toDateField);
// add the extension
addExtension(new CalendarFocusPopupOpenerExtension(fromDateField.getId(), toDateField.getId()));
}
}
2) Extension - java/server side
#JavaScript("calendar-focus-popup-opener-extension.js")
public class CalendarFocusPopupOpenerExtension extends AbstractJavaScriptExtension {
public CalendarFocusPopupOpenerExtension(String... idsToBindTo) {
// send the arguments as an array of strings
JsonArray arguments = Json.createArray();
for (int i = 0; i < idsToBindTo.length; i++) {
arguments.set(i, idsToBindTo[i]);
}
// call the bind defined in the associated JS
callFunction("bind", arguments);
}
}
3) Extension - js/client side
window.com_example_calendar_CalendarFocusPopupOpenerExtension = function () {
var timer;
this.bind = function (idsToBindTo) {
// check every second to see if the fields are available. interval can be tweaked as required
timer = setInterval(function () {
bindWhenFieldsAreAvailable(idsToBindTo);
}, 1000);
};
function bindWhenFieldsAreAvailable(idsToBindTo) {
console.log("Looking for the following date field ids: [" + idsToBindTo + "]");
var dateFields = [];
for (var i = 0; i < idsToBindTo.length; i++) {
var dateFieldId = idsToBindTo[i];
var dateField = document.getElementById(dateFieldId);
if (!dateField) {
// field not present, wait
console.log("Date field with id [" + dateFieldId + "] not found, sleeping");
return;
} else {
// field present, add it to the list
console.log("Date field with id [" + dateFieldId + "] found, adding to binding list");
dateFields.push(dateField);
}
}
// all fields present and accounted for, bind the listeners!
clearInterval(timer);
console.log("All fields available, binding focus listeners");
bindTo(dateFields);
}
function bindTo(dateFields) {
// assign focus handlers to all date fields
for (var i = 0; i < dateFields.length; i++) {
addFocusListeners(dateFields[i]);
}
}
function addFocusListeners(dateField) {
// when focusing the date field, click the button
dateField.onfocus = function () {
dateField.getElementsByTagName("button")[0].click();
};
// or when focusing the date field input, click the button
dateField.getElementsByTagName("input")[0].onfocus = function () {
dateField.getElementsByTagName("button")[0].click();
};
}
};
4) Result

Related

Vaadin Grid ItemClickListener fails to register clicks on column with ImageRenderer

I have the following code which is supposed to show a clickable icon which opens a popup dialog reading out a lengthy note.
this.capacityCommentColumn = this.facilityGrid.addColumn(
p -> {
if (Strings.isNullOrEmpty(p.getCapacityComment())) {
return null;
} else {
return new ThemeResource("img/note.svg");
}
},
new ImageRenderer<>())
.setWidth(80)
.setCaption("Note");
this.facilityGrid.addItemClickListener(new ItemClickListener<MapQueryService.RowResult>() {
#Override
public void itemClick(Grid.ItemClick<MapQueryService.RowResult> event) {
if (event.getColumn() == capacityCommentColumn && !Strings.isNullOrEmpty(event.getItem().getCapacityComment())) {
final NoteWindow noteWindow = new NoteWindow();
noteWindow.txtDescription.setValue("test");
noteWindow.show();
}
}
});
The problem is the code does not respond to clicks on the actual image, only on the outside. You can see this below. Any idea if its possible to make the image clickable?
You need to add a click listener to the Renderer as well. For example:
Grid<Integer> grid = new Grid();
private void addIconColumn() {
ImageRenderer<Integer> renderer = new ImageRenderer<>();
renderer.addClickListener(e -> iconClicked(e.getItem())); // allow clicks on the image
Grid.Column<Integer, ThemeResource> iconColumn = grid.addColumn(i -> new ThemeResource("img/icon.svg"), renderer)
.setCaption("Icon");
grid.addItemClickListener(e -> { // allow clicks on the cell
if (iconColumn.equals(e.getColumn())) {
iconClicked(e.getItem());
}
});
}
private void iconClicked(Integer i) {
... your UI logic here ...
}
You can see a working example here: https://github.com/alejandro-du/community-answers/tree/master/click-image-in-grid

Distinguish between onClick and onDoubleClick on same element to perform different actions in Dart

I want to do the ill-advised and place both an onClick and onDoubleClick on the same element with each type of event resulting in a different action. Specifically on an image, click to advance to the next image, double-click to toggle fullscreen.
Naturally I get two clicks followed by a double-click (though I understand that some browsers only fire one click before the double-click).
I had thought to make it easy on myself and place each event into a buffer (List) - or rather to add the event.type string to a list, then, after a suitable elapse of time, say 250 or 300 milliseconds examine the last item in the buffer and if doubleclick then go fullscreen else advance the length of the list.
I have found that the list only ever has one item, and I have not worked out how to get the timer to work..
Amongst my attempts was this one:
void catchClickEvents(Event e) {
var eventTypes = new List<String>();
eventTypes.add(e.type);
Duration duration = const Duration(milliseconds: 300);
var timeout = new Timer(duration, () => processEvents(eventTypes));
}
void processEvents(List eTypes) {
// just to see what is going on...
print(eTypes);
}
this results in this output printed to the console:
[click]
[click]
[dblclick]
rather than
[click, click, dblclick]
If I slow it down there is a clear delay before those three event types are printed together
So...
The bigger question is
'What is the darty way to distiguish between single and double-click and perform a different action for each?'
The other questions are:
How do I fill a buffer with successive events (and later clear it down) - or even how do I use Dart's Stream of events as a buffer...
What is the real way timeout before examining the contents of the buffer?
(and I guess the final question is 'should I abandon the effort and settle for a conventional set of buttons with glyph-icons?'!)
I'm not sure if IE still has the event sequence explained here (no 2nd click event)
https://stackoverflow.com/a/5511527/217408
If yes you can use a slightly deviated variant of Roberts solution:
library app_element;
import 'dart:html' as dom;
import 'dart:async' as async;
Duration dblClickDelay = new Duration(milliseconds: 500);
async.Timer clickTimer;
void clickHandler(dom.MouseEvent e, [bool forReal = false]) {
if(clickTimer == null) {
clickTimer = new async.Timer(dblClickDelay, () {
clickHandler(e, true);
clickTimer = null;
});
} else if(forReal){
print('click');
}
}
void dblClickHandler(dom.MouseEvent e) {
if(clickTimer != null) {
clickTimer.cancel();
clickTimer = null;
}
print('doubleClick');
}
void main() {
dom.querySelector('button')
..onClick.listen(clickHandler)
..onDoubleClick.listen(dblClickHandler);
}
or just use Roberts solution with the mouseUp event instead of the click event.
The problem is that your variable is not global.
var eventTypes = new List<String>();
void catchClickEvents(Event e) {
eventTypes.add(e.type);
Duration duration = const Duration(milliseconds: 300);
var timeout = new Timer(duration, () => processEvents(eventTypes));
}
void processEvents(List eTypes) {
print(eTypes);
}
There also is e.detail that should return the number of the click. You can use that, if you don't need the Internet Explorer. The problem with your list is that it grows and never gets cleared.
Let's take into account what we know: You get click events and at somepoint you have doubleclicks.
You could use a click counter here. (Or use e.detail) to skip the second click event. So you only have click and dblclick.
Now when you get a click event, you create a new timer like you did before and run the click action. If you get the dblclick event you simply run you action. This could like this:
DivElement div = querySelector('#div');
Timer timeout = null;
div.onClick.listen((MouseEvent e) {
if(e.detail >= 2) {
e.preventDefault();
} else {
if(timeout != null) {
timeout.cancel();
}
timeout = new Timer(new Duration(milliseconds: 150), () => print('click'));
}
});
div.onDoubleClick.listen((MouseEvent e) {
if(timeout != null) {
timeout.cancel();
timeout = null;
}
print('dblclick');
});
This is the example code that works for me. If you can't rely on e.detail just us a counter and reset it after some ms after a click event.
I hope this helps you.
Regards, Robert
Your page should react on user inputs as fast as possible. If you wait to confirm double click - your onClick will become much less responsive. You can hide the problem by changing visual state of the element(for example, playing animation) after first click but it can confuse user. And it gets even worse with handheld. Also if element has to react only on onClick event, you can "cheat" and listen to onmousedown instead - it will make your UI much more responsive.
On top of all this, double click, from client to client, may have noticeably different trigger time interval and it isn't intuitive, for user, that you can double click something. You will have to bloat your interface with unnecessary hints.
edit: Added my solution. It should be fairly extensible and future proof.
import 'dart:html';
import 'dart:async';
import 'dart:math';
//enum. Kinda... https://code.google.com/p/dart/issues/detail?id=88
class UIAction {
static const NEXT = const UIAction._(0);
static const FULLSCREEN = const UIAction._(1);
static const ERROR = const UIAction._(2);
final int value;
const UIAction._(this.value);
}
/**
*[UIEventToUIAction] transforms UIEvents into corresponding UIActions.
*/
class UIEventToUIAction implements StreamTransformer<UIEvent, UIAction> {
/**
* I use "guesstimate" value for [doubleClickInterval] but you can calculate
* comfortable value for the user from his/her previous activity.
*/
final Duration doubleClickInterval = const Duration(milliseconds: 400);
final StreamController<UIAction> st = new StreamController();
Stream<UIAction> bind(Stream<UIEvent> originalStream) {
int t1 = 0,
t2 = 0;
bool isOdd = true;
Duration deltaTime;
originalStream.timeout(doubleClickInterval, onTimeout: (_) {
if ((deltaTime != null) && (deltaTime >= doubleClickInterval)) {
st.add(UIAction.NEXT);
}
}).forEach((UIEvent uiEvent) {
isOdd ? t1 = uiEvent.timeStamp : t2 = uiEvent.timeStamp;
deltaTime = new Duration(milliseconds: (t1 - t2).abs());
if (deltaTime < doubleClickInterval) st.add(UIAction.FULLSCREEN);
isOdd = !isOdd;
});
return st.stream;
}
}
void main() {
//Eagerly perform time consuming tasks to decrease the input latency.
Future NextImageLoaded;
Future LargeImageLoaded;
element.onMouseDown.forEach((_) {
NextImageLoaded = asyncActionStub(
"load next image. Returns completed future if already loaded");
LargeImageLoaded = asyncActionStub(
"load large version of active image to show in fullscreen mode."
"Returns completed future if already loaded");
});
Stream<UIEvent> userInputs = element.onClick as Stream<UIEvent>;
userInputs.transform(new UIEventToUIAction()).forEach((action) {
switch (action) {
case UIAction.FULLSCREEN:
LargeImageLoaded.then( (_) =>asyncActionStub("fullscreen mode") )
.then((_) => print("'full screen' finished"));
break;
case UIAction.NEXT:
NextImageLoaded.then( (_) =>asyncActionStub("next image") )
.then((_) => print("'next image' finished"));
break;
default:
asyncActionStub("???");
}
});
}
final DivElement element = querySelector("#element");
final Random rng = new Random();
final Set performed = new Set();
/**
*[asyncActionStub] Pretends to asynchronously do something usefull.
* Also pretends to use cache.
*/
Future asyncActionStub(String msg) {
if (performed.contains(msg)) {
return new Future.delayed(const Duration(milliseconds: 0));
}
print(msg);
return new Future.delayed(
new Duration(milliseconds: rng.nextInt(300)),
() => performed.add(msg));
}

Monotouch.Dialog Generate from db and retain values

I'm have a settings view where I'm using MT.D to build out my UI. I just got it to read elements from a database to populate the elements in a section.
What I don't know how to do is access each elements properties or values. I want to style the element with a different background color for each item based on it's value in the database. I also want to be able to get the selected value so that I can update it in the db. Here's the rendering of the code that does the UI stuff with MT.D. I can get the values to show up and slide out like their supposed to... but, styling or adding delegates to them to handle clicks I'm lost.
List<StyledStringElement> clientTypes = SettingsController.GetClientTypes ();
public SettingsiPhoneView () : base (new RootElement("Home"), true)
{
Root = new RootElement("Settings") {
new Section ("Types") {
new RootElement ("Types") {
new Section ("Client Types") {
from ct in clientTypes
select (Element) ct
}
},
new StringElement ("Other Types")
}
Here's how I handled it below. Basically you have to create the element in a foreach loop and then populate the delegate with whatever you want to do there. Like so:
public static List<StyledStringElement> GetClientTypesAsElement ()
{
List<ClientType> clientTypes = new List<ClientType> ();
List<StyledStringElement> ctStringElements = new List<StyledStringElement> ();
using (var db = new SQLite.SQLiteConnection(Database.db)) {
var query = db.Table<ClientType> ().Where (ct => ct.IsActive == true && ct.Description != "Default");
foreach (ClientType ct in query)
clientTypes.Add (ct);
}
foreach (ClientType ct in clientTypes) {
// Build RGB values from the hex stored in the db (Hex example : #0E40BF)
UIColor bgColor = UIColor.Clear.FromHexString(ct.Color, 1.0f);
var localRef = ct;
StyledStringElement element = new StyledStringElement(ct.Type, delegate {
ClientTypeView.EditClientTypeView(localRef.Type, localRef.ClientTypeId);
});
element.BackgroundColor = bgColor;
ctStringElements.Add (element);
}
return ctStringElements;
}

Check if textboxes have the same content

I want to check if the textboxes created like this:
(function(arr) {
for (var i = 0; i < arr.length; i++) {
app.add(app.createLabel(arr[i] + " mail"));
app.add(app.createTextBox().setName(arr[i]));
}
})(["first", "second", "third"]);
have the same contents? I was looking for something like getElementByTagname or or getTextboxes, but there are no such functions.
So how to iterate thvrough them and show a label if they are all equal?
To access any widget values you need to add them as a callback element (or a parent panel) to the server handler that will process them. The values of each widget are populated on a parameter passed to the handler function and can be referenced by the widget name (that you already set).
You don't need to setId as suggested on another answer. Unless you want to do something with the widget itself (and not its value). e.g. change its text or hide it, etc.
var textBoxes = ["first", "second", "third"];
function example() {
var app = UiApp.createApplication().setTitle('Test');
var panel = app.createVerticalPanel();
textBoxes.forEach(function(name){
panel.add(app.createLabel(name + " mail"));
panel.add(app.createTextBox().setName(name));
});
panel.add(app.createLabel('Example Label').setId('label').setVisible(false));
var handler = app.createServerHandler('btnHandler').addCallbackElement(panel);
panel.add(app.createButton('Click').addClickHandler(handler));
SpreadsheetApp.getActive().show(app.add(panel));
}
function btnHandler(e) {
var app = UiApp.getActiveApplication(),
allEqual = true;
for( var i = 1; i < textBoxes.length; ++i )
if( e.parameter[textBoxes[i-1]] !== e.parameter[textBoxes[i]] ) {
allEqual = false; break;
}
app.getElementById('label').setVisible(allEqual);
return app;
}
Notice that ServerHandlers do not run instantly, so it may take a few seconds for the label to show or hide after you click the button.
When you create the textboxes, assign each one an id using setId(id).
When you want to obtain their reference later, you can then use getElementById(id).
Here is an example:
function doGet() {
var app = UiApp.createApplication();
app.add(app.createTextBox().setId("tb1").setText("the original text"));
app.add(app.createButton().setText("Change textbox").addClickHandler(app.createServerHandler("myHandler")));
return app;
}
function myHandler() {
var app = UiApp.getActiveApplication();
app.getElementById("tb1").setText("new text: in handler");
return app;
}

AS2: Access class function from onRollOver

I am working on a class for building drop down buttons dynamically. Here is excerpt one of my code (located in the Class constructor):
_button.onRollOver = function()
{
this.gotoAndStop("over");
TweenLite.to(this.options,0.2 * optionCount,{_y:mask._y, ease:Strong.easeOut, onComplete:detectMouse, onCompleteParams:[button]});
function detectMouse(button:MovieClip)
{
button.options.onMouseMove = function()
{
for (var option:String in this._parent.children)
{
if (this._parent.children[option].hitTest(_root._xmouse, _root._ymouse, true))
{
if (!this._parent.children[option].active) {
this._parent.children[option].clear();
drawOption(this._parent.children[option], "hover");
this._parent.children[option].active = true;
}
}
}
};
}
};
I am attempting to call on the function drawOption() which is inside the same class and looks like so:
private function drawOption(option:MovieClip, state:String)
{
trace("yo");
switch (state)
{
case "hover" :
var backgroundColour:Number = _shadow;
var textColour:Number = 0xffffff;
break;
default :
var backgroundColour:Number = _background;
var textColour:Number = _shadow;
break;
}
option._x = edgePadding;
option._y = 1 + edgePadding + (optionPadding * (option.index)) + (optionHeight * option.index);
option.beginFill(backgroundColour,100);
option.lineStyle(1,_border,100,true);
option.moveTo(0,0);
option.lineTo(_optionWidth,0);
option.lineTo(_optionWidth,optionHeight);
option.lineTo(0,optionHeight);
option.endFill();
var textfield:TextField = option.createTextField("string", option.getNextHighestDepth(), 20, 2, _optionWidth, optionHeight);
var format:TextFormat = new TextFormat();
format.bold = true;
format.size = fontSize;
format.font = "Arial";
format.color = textColour;
textfield.text = option.string;
textfield.setTextFormat(format);
}
But because I am trying to call from inside an onRollOver it seems that it is unable to recognise the Class methods. How would I go about accessing the function without making a duplicate of it (very messy, do not want!).
In AS2 I prefer to use the Delegate class to add functions to event handlers whilst maintaining control over the scope.
You implement it like this:
import mx.utils.Delegate;
//create method allows you to set the active scope, and a handler function
_button.onRollOver = Delegate.create(this,rollOverHandler);
function rollOverHander() {
// since the scope has shifted you need to use
// the instance name of the button
_button.gotoAndStop("over");
TweenLite.to(_button.options,0.2 * optionCount,{_y:mask._y, ease:Strong.easeOut, onComplete:detectMouse, onCompleteParams:[button]});
}
everything in the onrollover relates to the button which is rolled over, to access the outer functions, you would have to navigate to the outer class before calling the function in exactly the same way that you are accessing the outer variables, eg:
if the parent of the button contains the function:
this._parent.drawOption(....)
ContainerMC class:
class ContainerMC extends MovieClip{
function ContainerMC() {
// constructor code
trace("Container => Constructor Called");
}
function Init(){
trace("Container => Init Called");
this["button_mc"].onRollOver = function(){
trace(this._parent.SayHello());
}
}
function SayHello():String{
trace("Container => SayHello Called");
return "Hellooooo World";
}
}
I then have a movieclip in the library with the Class ContainerMC and the identitfier Container_mc, which is added to the stage by this line in the main timeline:
var Container = attachMovie("Container_mc","Container_mc",_root.getNextHighestDepth());
Container.Init();
Edit: added working sample

Resources