Showing posts with label ojInputText. Show all posts
Showing posts with label ojInputText. Show all posts

Wednesday, May 18, 2016

HTML5 Input Types for Oracle JET

I read an interesting question today, "Can you use HTML5 Input Types with Oracle JET's ojInputText?" Of course, the answer is "Yes" (the answer is always Yes). A better question is "How do you use HTML5 Input Types with Oracle JET's ojInputText?" OK, before we go there, let's answer the "Why" question: "Why would you use HTML5 Input Types with Oracle JET's ojInputText?" Oracle JET already includes number, text, and date input types, all styled according to the Oracle Alta specification. The reason for HTML5 Input Types? Device support. The idea behind HTML5 input types is to allow each device to display the most appropriate input method for a specific input type. This allows mobile web apps to maintain consistency with native mobile apps. For this reason, I am a HUGE fan of HTML5 input types. Note: desktop browsers don't have very good support for HTML5 Input Types.

Let's move onto the "How" question. Can you just set the type attribute of an ojInputText to "date" and get an HTML5 date input? No. Oracle JET will reset the type attribute to "text." The trick is to register a MutationObserver to listen for changes to the type attribute, and then reset it back to date (or whatever HTML5 input type you desire). Next question: How do I assign a MutationObserver to an instance of ojInputText? At this time, the best way I know to do this is with a knockout custom binding handler. You may remember that we used a custom binding handler last time we extended ojInputText (and then reused it a few more times). The reason for registering a ko.bindingHandler is to give us life cycle management events: we know when the DOM element is available and can enhance that element as we see fit. Here is an example of a custom component named html5DateInputText that extends ojInputText through ko.bindingHandlers. On initialization, the bindingHandler configures a MutationObserver that ensures the type attribute is always date. If you don't see a browser-specific date picker in the following example, then your browser might not support the date HTML5 input type. That doesn't mean the example is broken. It still works (depending on how you define the word "works") and falls back gracefully to a plain ojInputText.

Here is the custom binding handler:

var observerConfig = {
  attributes: true,
  childList: true,
  characterData: true
};
  
// Custom binding handler that wraps ojInputText and provides extra functionality
ko.bindingHandlers.html5DateInputText = {
    // setup extension to ojInputText as well as register event handlers
    init: function(element, valueAccessor, allBindingsAccessor, ctx) {
      var options = allBindingsAccessor().ojInputTextOptions || {};
      

      var observer = new MutationObserver(function(mutations) {
        ko.utils.arrayForEach(mutations, function(mutation) {
          if (mutation.type === 'attributes') {
            if (mutation.attributeName === 'type') {
              var $target = $(mutation.target);
              if ($target.attr('type') !== 'date') {
                $target.attr('type', 'date');
              }
            }
          }
        });   
      });
        
      observer.observe(element, observerConfig);
      
      $(element)
        .ojInputText(options)
        .on({
          'ojoptionchange': function (event, data) {
            //console.log(data)
            // use option === "value" for final value
            // use option === "rawValue" for each character
            if(data.option === "rawValue") {
              var val = data.value;
              var observable = valueAccessor();
              observable(val);
            }
          }
        })

      //handle disposal (if KO removes by the template binding)
      ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
        $(element).ojInputText("destroy");
        observer.disconnect();
        console.log("ojInputText destroyed");
      });
      
    },
    // This is how we update the UI based on observable changes
    update: function(element, valueAccessor) {
      var value = ko.utils.unwrapObservable(valueAccessor());
      $(element).ojInputText("option", "value", value);
    }
  };

If you want a different input type (tel, number, email and so on), then change lines 19 and 20 to match your target input type.

Note: The ojInputText Alta skin includes padding: 0 5px. The Chrome HTML5 Date spinners weren't centered using that padding so I added a line of CSS to reset padding to 5px on all sides.

Monday, May 9, 2016

rateLimit'ing ojInputText using a Read-only Observable (Debouncing the rawValue)

In my post Filtering Oracle JET ArrayTableDataSource I showed how to use an ojInputText to filter tabular data. In that post I mentioned using the knockout rateLimit extender, but shied away from it because rateLimit'ing an observable attached to an ojInputText rawValue throws the error, "rawValue option cannot be set" (even though rateLimit'ing in this manner works). It is true that rawValue is a read only field. For some reason, rateLimit'ing an observable causes a write to the component property bound to the observable. This makes sense because that is the point of an observable: update something after the observable value changes. The problem is that rawValue is read-only. I raised this issue with my colleagues and Jeanne Waldman shared this idea:

Create a pureComputed based off the rawValue observable and rateLimit the pureComputed.

Interesting. Jeanne's idea essentially creates a read-only observable that we can then rateLimit, effectively isolating rawValue from a write attempt. Here are the JavaScript changes necessary to implement Jeanne's idea:


// ... other code above here
ko.pureComputed(self.nameSearch)
  .extend({
    rateLimit: {
      timeout: 250,
      method: "notifyWhenChangesStop"
    }
  })
  .subscribe(function(newValue) {
    self.datasource.reset(
      filteredEmployees(newValue)
    );
  });

// ... other code below here

Notice that we are wrapping the previously used nameSearch observable in a ko.pureComputed, extending the ko.pureComputed, and then subscribing to the rate limited observable. Here is the jsFiddle:

Success! Our filter code now only runs 250 milliseconds after user input pauses. Considering our search algorithm, this will definitely perform better than invoking the algorithm for each key press. But is it as good as it could be? I'm not sure. We are now rate limiting a second observable rather than the primary observable. Will the primary observable continue to emit events with each key press? Did we trade an innocuous error message for some CPU/memory overhead? Does it matter? Normally, given two working solutions, I would choose performance, but I really don't want to see error messages cluttering my console.

Wednesday, April 27, 2016

Animated "Clear" button in ojInputText

Last week I posted Extending Oracle JET Components through Custom Bindings (Input Text with Buttons). About three quarters of the way through that post, I included a jsFiddle that shows how to add a delete button inside ojInputText. One of my readers asked if it was possible to hide the delete button if the ojInputText is empty. The answer, of course, is YES. The first thing we need to do is modify our ojoptionchange event handler to listen for the rawValue option instead of the value option. rawValue changes with each key press whereas value changes when the component loses focus.

.on({
  'ojoptionchange': function(event, data) {
    // use option === "value" for final value
    // use option === "rawValue" for each character
    if (data.option === "rawValue") {
      var observable = valueAccessor();
      //
      // ** show/hide icon code goes here
      //
      observable($(element).ojInputText("option", "value"));
    }
  }
})

If all we want to do is show/hide the "button" within the ojInputText, then we can toggle the oj-helper-hidden utility class on the i button element. That will result in the button instantly appearing or disappearing based on the length of the ojInputText element's value. I'm not a fan of jarring UX changes. If something is going to appear on the screen, I want it to fade in. The gradual appearance helps prepare my mind for the existence of a new user interface element while the movement draws my attention to this new element. Unfortunately, we can't animate the oj-helper-hidden class. The oj-helper-hidden class changes the display attribute and CSS does not support animating changes between the states of that attribute. We can, however, change the appearance of an element by animating the element's opacity. The following jsFiddle uses the opacity approach to toggle the appearance of the delete/clear button within ojInputText.

Extra credit: Compare these jsFiddles: http://jsfiddle.net/jmarion/tbr4k30n/ and http://jsfiddle.net/jmarion/5e10mx8z/. On line 62 of the first fiddle (my first post on this subject), I use jQuery to identify the value option of the ojInputText. In the second fiddle (this fiddle), lines 87 and 91 do the exact same thing, but without the jQuery method invocation. I got smarter the second time around. the ojOptionChange event actually includes the current value in the data object. I don't need to invoke a jQuery plugin method to retrieve the current value.

Note: I included CSS to change the cursor when the button becomes transparent, but the JavaScript click event will still trigger. Since the button is transparent when the ojInputText has no value, this should not be an issue. The net result of deleting nothing is... yep, you guessed it: nothing.

Tuesday, April 19, 2016

Extending Oracle JET Components through Custom Bindings (Input Text with Buttons)

The other day I saw an interesting question on an Oracle JET forum: "Can you add a clear button inside the end of an ojInputText?" Think of this like the magnifying glass at the end of a search field or an X that allows you to delete all of the text within an ojInputText. My first thought was to use a little CSS to add a FontAwesome icon to the end of the data entry field. If we were using a plain HTML input element, this would be no small task because it is impossible to use CSS alone to add an icon to the end of an input element (maybe someday HTML and CSS will support before and after selectors for input elements?). ojInputText, however, already wraps input elements in an outer div so we just need to add a little CSS to style that outer div. Here is an example that just uses CSS styling

You see a problem with this solution? I didn't at first. From a visual perspective, it meets all of the requirements—oh, except it isn't a button. If all you want is a visual indicator/icon within ojInputText, then this is a small, tidy solution will suffice. If you actually wanted a button, then keep reading.

My colleague Paul Thaden reworked my example for click events:

Notice this example replaces the :after pseudo selector with jQuery append. This allows us to handle the icon's click events. This is a great, simple solution if you need to handle click events AND know when elements will exist in the DOM (so you can wire up event handlers, enhance the markup, etc). But what about those times when elements are created and destroyed through iterators or View/Component changes? What we really need is a way to manage the component's lifecycle so we can enhance and wire up event handlers on creation. Knockout has a mechanism for this called Custom Binding Handlers.

Have you noticed the $(".selector").ojFoo syntax in a lot of the Oracle JET JSDocs? That looks a lot like the jQuery UI syntax (because it is—thank you JB for confirming, see this video). If Oracle JET components are a lot like jQuery UI widgets, then we are in luck. The internet is littered with examples of people creating custom binding handlers for jQuery UI components. Here is a great example that creates a custom binding handler for the jQuery UI datepicker. All we need to do is follow that example, replacing datepicker with ojInputText. In other words, we can extend any Oracle JET component binding by pretending it doesn't have bindings and treating it like a jQuery plugin. Here is a jsFiddle showing examples of two-way data binding and data model creation/destruction, etc:

Too much clutter? Just want to see the ojInputText extension? Here is the HTML

<input id="text-input" 
       type="text"
       data-bind="audioInputText: value,
                  ojInputTextOptions: {rootAttributes:
                                        {class: 'audio-ojInputText'}}"/>

And the JavaScript

ko.bindingHandlers.audioInputText = {
    // setup extension to ojInputText as well as register event handlers
    init: function(element, valueAccessor, allBindingsAccessor, ctx) {
      var options = allBindingsAccessor().ojInputTextOptions || {};
        
      $(element)
        .ojInputText(options)
        .on({
          'ojoptionchange': function (event, data) {
            // use option === "value" for final value
            // use option === "rawValue" for each character
            if(data.option === "value") {
              var observable = valueAccessor();
              observable($(element).ojInputText("option", "value"));
            }
          }
        })
        .closest(".audio-ojInputText")
          .append('')
          .find("i")
            .click(function() {
              var msg = "This could activate the microphone... but it doesn't. " +
                "Hey, I noticed you entered '" +
                ko.utils.unwrapObservable(valueAccessor()) + "'"
              alert(msg);
            });

      //handle disposal (if KO removes by the template binding)
      ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
        $(element).ojInputText("destroy");
        console.log("ojInputText destroyed");
      });
        
    },
    // This is how we update the UI based on observable changes
    update: function(element, valueAccessor) {
      var value = ko.utils.unwrapObservable(valueAccessor());
      $(element).ojInputText("option", "value", value);
    }
  };

Here is an example of an ojInputText with a delete button that deletes all of the text within the observable when clicked.

In each of the examples above, I hard coded the click handler and the icon. In prior examples, the click handler used model data, making it somewhat generic, but not generic enough to delegate clicks to the ViewModel. Let's create one final example that we'll call ojInputText Clear Buttons. This example is generic enough to use any icon library (glyphicons, fontawesome, oj icons, etc) and invokes a click handler within the ViewModel.

Thursday, March 24, 2016

Filtering Oracle JET ArrayTableDataSource

I recently wrote about Filtering Table Data with Knockout Computeds. I'm not sure I shared anything earth shattering as others have already written about that topic. My real motivation for writing that post was to provide a foundation to compare/contrast filtering a plain HTML table against an Oracle JET ojTable that is based on an oj.ArrayTableDataSource (not to be confused with oj.CollectionTableDataSource, which wraps an oj.Collection and has its own where method and cookbook example).

Let's jettify the Filtering Table Data with Knockout Computeds example. Instead of <input type="text">, we'll use ojInputText. Instead of a Bootstrap table, we'll use ojTable. Here is the jsFiddle:

As you can see, the code is fairly similar. A couple of key differences to note are the rawValue parameter and the lack of a computed. Instead of using the value and valueUpdate parameters, the ojInputText component uses value and rawValue. The ojInputText value parameter acts just like the standard knockout parameter, tracking the final updated value after losing focus. The rawValue parameter tracks changes as you type, which is similar to the standard input with the valueUpdate parameter. The other difference between these examples is that this example didn't use a computed observable, but rather the oj.ArrayTableDataSource.reset() method to replace the table's array when filtering.

As with the Knockout computed example, we can debounce this example so that the array filter code doesn't run with every key press, but only after a predetermined pause. I included the rate limiting extension in the JavaScript, but commented it out for example purposes. When filtering large data sets, it might make sense to switch from observing rawValue to observing the value parameter. Another option is to include a Search button that triggers the filter code on click. You can find an example of this here.

Note: Filtering arrays requires an ES6 compatible browser or some type of polyfill library. The examples include Lazy.js as a polyfill so you can run the jsFiddle example in a wider range of web browsers.

Thursday, March 17, 2016

Validating Oracle JET Input Before Submission Take II

For a blogger, I would say the best part about blogging is learning something new from a reader. My latest schooling comes from Oracle JET expert JB and involves Oracle JET's built-in validation. I learned a lot about the jQuery syntax for validating unvisited form fields and confirming validation before submission while writing the post Validating Oracle JET Input Before Submission. This is great... if you are using jQuery. If you are using knockout, however, there is another way: oj.InvalidComponentTracker. Scroll down the oj.editableValue document until you see the Binding Attributes section. Every oj.editableValue (which includes ojInputText, ojInputPassword, ojSelect, and just about every other input type) has an invalidComponentTracker attribute. Just set each validated input field's invalidComponentTracker attribute to the same observable and then you can test that one observable from your submit function. The App Level Validation: Dynamic Form Example cookbook recipe is a great example. Here are the basics: in your ViewModel, add:

self.tracker = ko.observable();

For each validated input in the view, add the invalidComponentTracker attribute like this:

<input id="password" required data-bind="ojComponent: {
    component: 'ojInputPassword', value: user.password,
    invalidComponentTracker: tracker}" type="password">

Oracle JET will will set the tracker observable to an instance of oj.InvalidComponentTracker. In your submit handler you can test for invalidHidden and invalidShown messages. If either of those fields return true, then you know the form contains invalid input. For visited fields, validation failure messages should be visible. For unvisited fields, you can make validation messages visible by invoking the oj.InvalidComponentTracker showMessages method.

Here is an example of the JavaScript I now use in my form submit routine to ensure validation was successful prior to submission:

var tracker = self.tracker();
if (tracker.invalidHidden || tracker.invalidShown) {
  tracker.showMessages();
  tracker.focusOnFirstInvalid();
  return;
}

Tip: Be sure to add 'ojs/ojknockout-validation' to your ViewModel's define/require block.

Thursday, March 3, 2016

Validating Oracle JET Input Before Submission

Oracle JET includes a very convenient validation module to validate user input. Even though it validates input immediately, it only displays validation warnings/errors after a user visits a validated component. This is as it should be. Can you imagine visiting a data entry page that immediately displayed all validation errors before you entered your first value? Oracle JET quietly maintains a list of validation messages in the collection messagesHidden. You can see this in action by navigating over to the Validation recipe in the Oracle JET cookbook and then pasting the following into the console:

$("#username").ojInputText("option", "messagesHidden");

The result will look something like the following:

Now enter some data into the username field and replay the last console command (hint: use the up arrow). Notice that the result collection is now empty.

Now, let's say you have a data entry form and you want to ensure validation occurs before a user submits data. What if a user skipped over a required field? Now that the username field has a value, enter the following into the console:

$("#username").ojInputText("isValid");

The console should return true. Now you can confirm validation and cancel submission if the form fails validation, but what about displaying that validation error message for fields that fail validation? Refresh the recipe page so that username has no value and validation warnings are hidden and then type the following into the JavaScript console:

$("#username").ojInputText("validate");

That highly valuable validation error message should reappear.

That is great, but do I need to check the isValid status of every field in my form? Do I need to invoke the validate method on every input field? In a word: YES (Note: if you are using knockout, there is an easier way. See Validating Oracle JET Input Before Submission Take II). But don't worry, you don't have to list every single field. We can let jQuery selectors handle this for us. Here is how:


var validateSelector = function(selector, componentName) {
  // Note: using multi-step selectors for two reasons:
  // #1: make it easier to pass in distinct part of selector
  // #2: sizzle selectors work in reverse, so we want to narrow selected
  // elements BEFORE testing data-bind.
  $(selector)
    .filter("[data-bind]")
    .filter("[data-bind*='" + componentName + "']")
    .each(function() {
      //console.log("Invoking validator on", this);
      $(this)[componentName]("validate");
    });
};

var isValidSelector = function(selector, componentName) {

  var $elements = $(selector)
    .filter("[data-bind]") // has a data-bind attribute
    .filter("[data-bind*='" + componentName + "']");

  // using a for loop to exit immediately if false
  for (var idx = 0, len = $elements.length; idx < len; idx++) {
    if (!$($elements[idx])[componentName]("isValid")) {
      return false;
    }
  }

  // fell through, so return true
  return true;
};


validateSelector("input[type='text']", "ojInputText");
validateSelector("input[type='password']", "ojInputPassword");
validateSelector("select", "ojSelect");

// first selector to fail will end the chain and return false
var formIsValid = isValidSelector("input[type='text']", "ojInputText") &&
  isValidSelector("input[type='password']", "ojInputPassword") &&
  isValidSelector("select", "ojSelect");

I certainly haven't covered every selector possible, but hopefully this is enough to communicate the idea. Of course, you don't want to paste this code into every single ViewModel. Instead, throw it into a RequireJS module and include it in ViewModels that require validation. In fact, why not display messages and check the validation status all at once by writing the module to just expose a single method that does both?

... Or, if you are using knockout, you could skip the whole jQuery selector thing by using an oj.invalidComponentTracker (Thank you JB for showing me this feature).