Comparing JS Compression Methods in Sencha Cmd

Introduction

For years and years, web developers have been told that they must optimize their code for production environments. The conventional wisdom states that bandwidth usage will be reduced and applications will load much more quickly simply by compressing all of the JavaScript an application needs—and Sencha has helped to automate this process for years through Sencha Cmd.

However, as with many of our customers, you may not realize that you can squeeze even more performance out of this process by tweaking how Sencha Cmd compresses your code. Although Sencha Cmd defaults to using YUI Compressor for this task, you can optionally configure your build output to use Google Closure or UglifyJS instead — and as we’ll see in a moment, it often pays to test which compression tool offers the greatest savings.

Please note that this post should not be viewed as a recommendation for any specific tool. Many factors could influence your decision to choose one compression tool over another, and this post will attempt to provide some approaches to consider when making your own decision.

Why Would You Want to Change the Default Settings?

While the mechanics involved can be quite complicated, the general idea behind JavaScript compressors is rather simple: your code is tokenized and parsed into an abstract syntax tree (AST), then regenerated into a JavaScript program with modifications to compress the output.

The specifics of how these individual tools work (e.g. the algorithms used, etc) is beyond the scope of this article, but let’s quickly examine YUI Compressor, Closure and UglifyJS at a high level.

YUI Compressor

YUI Compressor is a command-line utility written in Java. It can perform both JavaScript and CSS compression, making it an ideal tool for most projects. YUI Compressor has been deprecated, although it still remains very popular.

As previously noted, Sencha Cmd uses YUI Compressor by default in the application build process.

Google Closure Compiler

Google Closure Compiler is also built with Java, but only performs JavaScript compression (no CSS). Closure can be run directly from the command-line, contains additional services (UI, API) and offers greater control over the compression process through code annotations and compilation flags.

UglifyJS

UglifyJS is the only one of these tools written with JavaScript, making it ideal for use in Node.js environments. Like Closure, UglifyJS only offers JavaScript compression (no CSS). UglifyJS is run as a command-line utility and allows detailed control over the compression process through a number of compilation flags.

Note: Sencha Cmd is built with Java, so UglifyJS is run using Rhino rather than Node.js.

Keep in mind that because each tool will produce slightly different compression output, it is hard to predict which will yield the most optimal results. To help illustrate this point, let’s dive into a sample application and test how each of these compression tools handles the code.

Case Study: Ext JS 5 Sample App

The easiest possible way to illustrate this concept is to generate a sample application using Sencha Cmd:

     sencha -sdk ~/path/to/ext generate app Foo ./foo

Because Sencha Cmd scaffolds a fully-functioning sample application, we don’t need to do anything else. Running the app in Firefox, our “development” app loads with the following stats:

There isn’t much of a surprise here. An Ext JS application in “development” mode relies on the Ext.Loader to synchronously load each JavaScript dependency — and although 0.29s isn’t much time spent waiting for 24 HTTP requests, it is easy to imagine how much longer an enterprise application might take.

After running sencha app build to get our sample app into “production”, the network statistics have changed quite a bit:

Clearly we have fewer JavaScript resources, and the overall load time has dropped to 0.02s! This is all thanks to the magic of JavaScript compression.

Obviously the use of JavaScript compression is important — but is it possible that tweaking the Sencha Cmd settings might yield even better results? To change which compression tool Sencha Cmd uses, let’s edit the app.json file:

{
    //...
 
    /**
     * override objects for setting build environment specific
     * settings.
     */
    "production": {
        "compressor" : {
            //"type" : "yui"    //the default...
            //"type" : "uglify" //or...
            "type" : "closure"
        }
    },
 
    //...
}

Now if we run sencha app build, the build process will use the configured compression tool. Next, let’s look at the results of using the various compression tools on our sample application:

 Compressor  File Size (Bytes)  % of Original
 (none)  5,166,339  100.0%
 YUI  1,109,534  21.48%
 Closure  1,081,242  20.93%
 UglifyJS  1,069,126  20.69%
 YUI (gzip)  343,696  6.65%
 Closure (gzip)  323,615  6.26%
 UglifyJS (gzip)  329,182  6.37%

In the table above, you can see the actual results of the compressed file sizes, in addition to a second step of gzipping the compressed output files (run via the gzip terminal command with default settings). It is interesting to note that while UglifyJS yielded the smallest output after our build process, Closure actually wins when we consider additional gzip compression.

It’s possible that we might have achieved even better results if we tweaked the gzip settings involved.

Considerations

So Closure wins… we should all just start using Closure. Right? Sadly it’s not so clear-cut.

If we take the additional step to measure the total time involved to run our build process (including generating our CSS theme and other steps), we will notice something important.

The sample app uses Ext JS 5.0.1.1255, and I ran the commands using Sencha Cmd 5.1.0.26 on my MacBook Pro (early 2011, OSX 10.10.1, 2GHz Intel i7, 8GB RAM). Results may vary on your machine. Note: I also modified the build settings to avoid theme slicing for older browsers.

     sencha -ti app build -c

The command above will provide us with the total time of execution (-ti flag), and it will also remove previous build output (-c flag) to guarantee our comparisons are clean. Running a build with each of the compression tools, we start to see why YUI Compressor is the default choice:

  • YUI: 0:00:33
  • Closure: 0:00:54
  • UglifyJS: 0:15:40

Closure takes nearly double the time to compress our build output—and UglifyJS takes roughly 31x longer! The takeaway here is that it’s worth deciding whether or not the significant increase in build time is worth a few saved kilobytes.

Ultimately, some companies may view a few kBs as insignificant when their primary objective is simply reducing the size of their JavaScript assets. But high-traffic applications will likely cause them to pay close attention to these minute details — where page speed and overall bandwidth can dramatically affect profits.

Finally, you might ask if any of the compressed JavaScript executed faster after compression. It’s nearly impossible to tell, and existing JSPerf tests indicate virtually no difference in speed of execution.

Customizing JS Compression

Sencha Cmd doesn’t currently allow us to configure the settings for YUI Compressor, but then again YUI Compressor doesn’t offer many settings to configure. Sencha Cmd does allow us to configure how Closure compiles our source code.

Opening app.json again, we can configure the Closure compilation options directly on the “compressor” object:

{
    //...
 
    "production": {
        "compressor" : {
            "type" : "closure",
 
            //all other keys are passed as options
            "ambiguateProperties" : true,
            "foldConstants"       : true
        }
    },
 
    //...
}

Sencha Cmd has not yet implemented the custom configurations for UglifyJS, but that feature is on the roadmap.

Conclusion

Compressing your JavaScript is a well-established best practice for increasing the performance of a web application. Sencha Cmd automates this process by default, but it may be worth playing with the advanced settings to squeeze additional optimizations out of your production build.

8 Comments   Read more

Meet the SenchaCon Speakers – Art Kay

For those of you who don’t already know me, my name is Art Kay and I work for Sencha as our Developer Relations Manager. I just celebrated my fourth anniversary here at Sencha, but I have been involved in our community since the early days of Ext JS 2.0.

SenchaCon 2015 is approaching in just a few short weeks, and I am super excited to see everyone for another great conference!

Everyone at Sencha has been working really hard on some brand-new, top-secret projects which we plan on announcing at SenchaCon 2015 — and you’ll certainly need to be there in person to hear about them first.

 

But this year’s conference will also feature a ton of awesome sessions led by the top developers in our community. We received so many fantastic sessions during our Call for Papers that nearly 50% of the presentations will be given by you, our amazing community!

I’ll be speaking at SenchaCon too — I actually have two sessions. Here’s a quick overview of my talks.

Debug Your Apps with Google Chrome and Sencha

Historically, debugging enterprise JavaScript applications has been a huge pain in the neck. Thankfully the developer tools in most modern browsers have matured and make inspecting application logic easier than ever. Google Chrome in particular has a rich set of debugging tools, which can be further complemented with Chrome Extensions.

I hope you’ll join me to discuss some advanced features of Chrome Developer Tools, and then hear how we built App Inspector for Sencha. We’ll also dive into how you can build your own debugging extensions for Google Chrome.

Advanced Techniques for Compressing your Applications

For years, developers have been told that they must optimize their production code in order to deliver prompt user experiences. The proliferation of mobile devices makes this advice even more critical, where sub-second delays in rendering can lead to user frustration and lost revenue. However, most developers don’t realize that they can squeeze even more performance out of their applications by tweaking how compression tools optimize their code.

Come to this session for a technical deep dive into how Sencha Cmd utilizes YUI Compressor, Google Closure and UglifyJS — and learn some advanced techniques for delivering the smallest possible applications.

Lots to Learn and People to Meet

This is definitely an event you don’t want to miss. You’ll walk away with tons of new information and ideas — and you’ll also get to meet the whole Sencha team, network with hundreds of your peers and enjoy some fun parties. Best of all, you might win tickets to the NFL’s biggest game in 2016!

If you haven’t already registered, you still have time. Email me and I’ll even send you a 20% discount code. Visit the SenchaCon website for more details on sessions and speakers — I hope I get to see you all there.

Senchacon Teaser No Comments   Read more

Ext JS Customer Spotlight: TriNet

eVestmentTriNet provides HR solutions to small and mid-sized businesses so companies can focus on developing their products, services and employees. Tailored by industry, TriNet bundled HR products provide critical core services of payroll, benefits, workers’ compensation and risk & compliance mitigation, as well as a dedicated HR team and a paperless cloud platform. TriNet handles many of the day-to-day responsibilities of being an employer and helps these companies contain HR costs, minimize employer-related risk and relieve the administrative burden of HR.

Why We Chose Ext JS

We used Ext JS to build a couple of applications, including TriNet Payroll. TriNet Payroll is an enhanced payroll solution that enables clients to preview estimated payroll costs before submitting payroll for processing.

Ext JS is an end-to-end solution, from a “single source of truth” in its data stores all the way to a set of industry-leading user interface components, including grids, charting, drawing and animation. We have used Ext JS grids extensively with our payroll and leave request applications. The Ext JS grid is extremely powerful and fast, with built-in column sorting and show/hide features. The TriNet dashboard application also utilizes various Ext JS chart components to provide a rich interactive user experience. With the depth and breadth of those features and its standardized API, we can deliver anything that our visual designers and product managers can imagine, with a faster time to market.

“We chose Ext JS 5 because it provides a number of dramatic advantages for building enterprise-class rich internet applications.

We looked at AngularJS, jQuery UI and YUI, but we chose Ext JS 5 because it provides a number of dramatic advantages for building enterprise-class rich internet applications. For instance, it has enabled us to deliver compelling user experiences for both desktop and tablet devices with the same code. The built-in support for both desktop and tablet interactions means there is very little custom coding required for the application to work in either environment. Sencha Cmd also is integrated with Cordova, so it’s simple to build a hybrid tablet application. The consistency of the API, its depth of components and tight integration translates to a very complete, expressive set of tools for rapidly building rich, intuitive interfaces.

Ext JS 5 also saves us time. The Ext JS framework ensures support for all popular browsers, and we do not need to expend engineering effort on browser compatibility issues.

Sencha Cmd is seamlessly integrated with Sass and Compass, which enables our team to write less CSS and gives us a mechanism to make our themes and styles well-organized and reusable. It also gives us a way to further customize our application styles, so we can more closely meet the specific needs of key customers and market segments.

Business Value of Using Ext JS

We received a lot of expert help from Sencha Support and Professional Services, and the Sencha support engineer has often made himself available to us on evenings and weekends. Not only does he have a tremendous amount of knowledge in all aspects of Ext JS development, but he also is a great mentor and source of creative solutions to difficult technical problems.

“As an object-oriented JavaScript framework with a robust, fully-functional class system, Ext JS provides familiar metaphors for software engineers coming from languages such as Java.

As an object-oriented JavaScript framework with a robust, fully-functional class system, Ext JS provides familiar metaphors for software engineers coming from languages such as Java, which we use on the back-end of our applications. The abstraction of the details of HTML and DOM manipulation into JavaScript also makes it possible to create custom, reusable components by using inheritance. This has substantially reduced the learning curve and training costs for our engineers who are new to web programming.

With the new Ext JS 5 Model-View-ViewModel (MVVM) architecture, we are writing even less custom code, which reduces the ‘bug surface’ of our applications. Taken together with Ext JS 5 Router/browser history capabilities, we are writing far less custom code and further accelerating the delivery of our products.

Sencha has a rigorous approach to JavaScript that provides a foundation on which to build well-organized, concise and testable applications that quickly load and respond to user input. Application footprints are made even smaller because we use Sencha Cmd as our build tool. Cmd not only minifies the code, but also inspects it and only includes framework and custom classes that are necessary for the application to run.

Our Advice to New Developers

  • Learn the framework: It’s critical to know the framework well if you’re developing applications for scalability and performance. We also recommend that you engage the Sencha Professional Services team to architect the application using best practices. This will reduce refactoring efforts later in the project.
  • Design for internationalization and 508 compliance: Ext JS provides support to internationalize your application and deliver 508 compliance. You should consider these features when you design the application.
  • Package common components: Ext JS provides many widgets out of the box. Consider packaging common components using Sencha command packages to reuse components across multiple applications.
  • Pay attention to performance: You’ll get optimal performance from your app if you follow Sencha best practices. You can use the Sencha knowledge base as well as the Professional Services and Support teams to design the application packages for performance and scalability. Pay attention to the memory footprint of the application components.

Final Thoughts

Sencha Ext JS is a robust framework for developing enterprise-class web applications, and its extensive set of tools makes development easier. The biggest advantage we see is the cross-browser and touch device support that enables us to build applications with a single code base. Support for 508 compliance is an added advantage to us. Overall, the Ext JS framework is well suited for data-intensive enterprise applications.

Ext JS 5 saves us time by ensuring support for all popular browsers, so we do not need to expend engineering effort on browser compatibility issues. No Comments   Read more

Announcing Ext JS 5.1 Beta

Introduction

We’re excited to announce the availability of Ext JS 5.1 Beta. Since Ext JS 5.0.1, we’ve been hard at work adding exciting new features and responding to all the great feedback from you, the Sencha Community. Ext JS 5.1 comes with an entirely new selection mode for our grids (the spreadsheet model), along with other new components and enhancements including: 3D column and bar charts, enhancements to the draw package, a color picker, and the rating widget. We would love for you to participate in the Ext JS 5.1 beta cycle via our forums, as we move towards the general availability of these exciting new features.

The Spreadsheet Selection Model

The Ext JS Grid has always been the centerpiece of the framework. With Ext JS 5.1, we’re adding a brand new selection model that mimics the experience of a spreadsheet, unsurprisingly called “spreadsheet”. Using this model, users can select cell ranges…

…as well as entire columns, rows or the entire data set.

You can even enable row checkboxes such that spreadsheet may be the only selection model you’ll ever need.

The Clipboard Plugin

When using the spreadsheet selection model, you can also add the new clipboard plugin to the grid to enable exchange with other applications running outside the browser. Users can select a range of data, then press CTRL+C (or Command+C on Mac) to copy those cells to the system clipboard, switch to an application such as Microsoft Excel and paste in their data.

Of course, the reverse also works. Users can copy data to the clipboard in an external application and then select the target cell in the grid and press CTRL+V (or Command+V on Mac) to paste.

All of this functionality can be added to a grid like so:

requires: [
        'Ext.grid.selection.SpreadsheetModel',
        'Ext.grid.plugin.Clipboard'
],
 
selModel: {
        type: 'spreadsheet',
        columnSelect: true  // replaces click-to-sort on header
},
 
plugins: 'clipboard'

By default, the clipboard plugin uses the system clipboard, but it can also use an internal buffer to exchange custom data formats between grids within your application.

Charts Get 3D Bars and Columns

With Ext JS 5.1, the sencha-charts package now provides a “bar3d” series and a “numeric3d” axis, which combine to produce some beautiful results like this stacked column chart:

By providing a custom renderer method, you can simply adjust the fillStyle of a column and still get all the proper gradients to maintain the 3D appearance:

And let’s not forget bar charts as well:

Stacked charts have two new configs in addition to 3D support: fullStack and fullStackTotal. These configs allow the chart to have any data in the store and instruct the series to dynamically scale the data at display time to fit a specified range (typically 0% to 100%).

To enable full stacking, just set fullStack on the series to true. By default, all y fields of the series are stacked with a total of 100, to represent percentages. Using fullStackTotal, you can, however, scale the axis to any range.

Chart Item Events

Finally, with charts, you can now wire up item-level events such as itemtap and itemmousemove by adding the new “chartitemevents” plugin to your chart.

Other New Components

Advanced Color Picker

You may recall the color picker component we introduced in a previous article:

Now, there are actually three color picker components. The above example shows the colorfield and colorselector. The colorfield component is the form field that displays the color value and a sample swatch. The colorselector is presented in the popup window.

The third color picker is the colorbutton which is just the color swatch that reacts to clicks to display a colorselector.

These components are part of the Ext.ux namespace and now live in the framework’s “ext-ux” package. More on “ext-ux” package below.

Rating Widget

The new rating widget (from this previous article) is now also part of the “ext-ux” package:

The rating widget is like a slider that allows the user to quickly pick a value in a limited range. Unlike a slider, a rating uses repeated glyphs (web fonts) to represent a selection and a single click adjusts the value.

The ext-ux Package

In previous versions of the framework, the Ext.ux namespace was developed in the “examples/ux” folder. This has always been a challenge for theme interaction, so with Ext JS 5.1 we have added an “ext-ux” package to contain these components. Over time, the existing members of Ext.ux will either be migrated to “ext-ux” or promoted to the framework proper.

To use “ext-ux” package in a Sencha Cmd application, you simple add it to your app.json file:

"requires": [
        "ext-ux"
]

As a standard package, the ext-ux build outputs are available to those not using Sencha Cmd as well. The “build” folder looks like this:

The JavaScript files “ext-ux.js” and “ext-ux-debug.js” are in the top-level build folder. Based on your application’s theme, you would then select from the three theme subfolders with compiled CSS and resources.

Draw Package Features

The Ext.draw package in “sencha-charts” also has some exciting new features for those going beyond simple charts.

Sprite Events

You can now process sprite events such as itemtap or itemmouseover by adding the “spriteevents” plugin to the Ext.draw.Container.

Hit Testing

We’ve added new APIs to allow you to hit test points against complex paths: pointInPath and pointOnPath. Also, here are a couple of examples to show the new APIs at work:

Path Intersection

You can also intersect two entire paths and process their intersection points. In another new example, you can drag paths around and see the intersections highlighted as you move.

The details of intersecting simple lines or complex shapes that consist of multiple bezier curve segments are hidden away, so you won’t need to worry about the content of paths.

Progress on Unifying The Core

As you may already know, with Ext JS 5.x, we’ve been working on a shared “sencha-core” package. In this release, we are moving Ext.app (our MVC and MVVM classes) to the core and finalizing the event system.

Ext.app.Profile

Originally found in Sencha Touch, Ext.app.Profile is now in sencha-core along with the rest of the Ext.app namespace. In other words, the unified MVC/MVVM feature set is now in the shared code arena. So now that Ext JS 5.1 applications have access to Ext.app.Profile, the logical questions are “how does it work” and “what does it provide”.

Activation

If you’ve never used Sencha Touch profiles before, they are basically like miniature applications. Applications then list the desired profiles in their profiles config. At launch time, the framework will create an instance of all of these profiles. It will then iterate the list in order and call the isActive method. The first profile instance to return true is considered the active (or current) profile.

The mainView Config

One obvious use for a profile (say for “tablet” or “desktop”) is to control the top-level view to present to the user. With Ext JS 5.1, there is a new mainView config that the application or profile can specify. This config supersedes the “autoCreateViewport” config for older Ext JS applications.

Profiles And Other Options

Prior to Ext.app.Profile, Ext JS 5.0 applications could use responsiveConfig (via a plugin or mixin) for run-time choices or Sencha Cmd build profiles to generate target-specific builds. Application profiles sit in the middle of these two options.

Application profiles are executed at load time and hence can do whatever is needed. They aren’t limited to setting config properties like a responsiveConfig. Because they must be included in the build, however, they will add to the size and space requirements of your application regardless of the device on which it is run. Using a build profile, however, you would be able to remove Android-specific content from an iOS-only build for the Apple App Store.

Event System (Observable and Element)

With Ext JS 5.0, we introduced the new multi-device, touch-enabled event system derived from Sencha Touch. This supported the momentum scroller and gesture recognition system and the delegated event model of Ext.Element. The entry point of the new event system was Ext.mixin.Observable. The original Ext JS event system, however, was provided by Ext.util.Observable. The APIs for these two classes were mostly the same, but they differed on some of the less common uses cases.

The unified event system in Ext JS 5.1 still provides these two classes (for compatibility reasons), but now the only difference between them is that Ext.mixin.Observable calls initConfig in its constructor whereas Ext.util.Observable uses the legacy Ext.apply approach to copy config object properties onto the instance.

In the process of completing the unification, we were able to optimize event listening and firing, thereby reducing overhead in these critical areas. Be sure to check the Upgrade Guide for the few compatibility issues.

Accessibility and Keyboard Navigation

Ext JS 5.1 continues to expand on the major accessibility support delivered in Ext JS 5.0.1. In particular, handling of various popup elements (from ComboBox to various menus) has been improved. The way cascades of such popups process focus and blur events has also been hardened.

Unified Scroller API

With many touch-enabled devices, special logic is needed to efficiently manage scrolling. To normalize all this device-specific behavior, Ext JS 5.1 adds Ext.scroll.Scroller. An instance of this class is created by the framework when using configs like autoScroll, overflowX and overflowY configs, but it can now be more fully controlled using the new scrollable config.

If you are familiar with Sencha Touch, you will likely recognize this config. With Ext JS 5.1, however, it can now be a config object for the Scroller. To retrieve the Scroller, you call getScrollable. This object provides useful APIs like scrollTo and scrollBy, so you no longer need to worry about how the scrolling is managed on the current device.

If you have configs like these in your application…

autoScroll: true
 
// or perhaps just horizontal:
overflowX: true
 
// or maybe just vertical:
overflowY: true

…they will continue to work, but in Ext JS 5.1, the following would be equivalent and prefered:

scrollable: true  // equivalent to autoScroll: true
 
scrollable: 'x'   // equivalent to overflowX: true
 
scrollable: 'y'   // equivalent to overflowY: true

Sencha Cmd 5.1

Last but not least, Sencha Cmd 5.1 is also now available. This release is focused on performance and introduces a new compiler optimization. The new optimization, called “cssPrefix”, optimizes framework code that supports using multiple versions of Ext JS on the same page. Called “sandboxing”, it requires code like this:

rowCls: Ext.baseCSSPrefix + 'grid-row',

The new optimization replaces the above with something like:

rowCls: 'x-grid-row',

This eliminates hundreds of such concatenations in a normal app (over a thousand for the entire framework). To take advantage of this optimization, you should see something like this in your app.json:

"output": {
        "js": {
                "optimize": true
        }
}

To expand all the optimizations available at present, you would have this:

"output": {
        "js": {
                "optimize": {
                        "callParent": true,
                        "cssPrefix": true,
                        "defines": true
                }
        }
}

If you use Sencha Cmd, you will need this version to work with Ext JS 5.1. As always, Sencha Cmd 5.1 supports all the previous framework versions from Ext JS 4.1.1a and Sencha Touch 2.1.

Conclusion

You can check out the examples here and download the beta here. If you are using Sencha Cmd, you will need Sencha Cmd 5.1.0 Beta.

We hope you try out the Ext JS 5.1 Beta. In addition to all the new features mentioned above, there are numerous bug fixes and other enhancements. Let us know what you think by submitting comments on the forums.

ext.jpg 15 Comments   Read more

Using GapDebug to Test Hybrid Web Apps Built with Sencha Frameworks

Introduction

Using GapDebug to Test Hybrid Web Apps Built with Sencha FrameworksDevelopers have been using PhoneGap (and subsequently Cordova) to deploy hybrid mobile applications since 2009, when it was first created. By allowing web applications to run on native devices, the HTML5 community fully embraced PhoneGap and thousands of apps have since been released on iOS, Android and a wide variety of other platforms. But while the wrapper itself is great, unfortunately the debugging tools have lagged far behind their browser counterparts — and debugging across multiple platforms has often been painful.

In this post, we’ll introduce you to the new Genuitec GapDebug tool and explain how it makes debugging hybrid applications deployed with PhoneGap far easier than ever before. We will also compare GapDebug to the popular Weinre debugger and highlight the key differences between them.

GapDebug LogoGapDebug

GapDebug is a free cross-platform mobile app debugger developed by Genuitec for use with Android and iOS PhoneGap (or Cordova) applications. It runs on both Windows and Mac OSX and is packed full of killer features for exploring every aspect of a hybrid app’s state and execution.

GapDebug is a free cross-platform mobile app debugger developed by Genuitec for use with Android and iOS PhoneGap (or Cordova) applications.

Many Sencha developers use Cordova or PhoneGap every day to deploy their hybrid applications — but debugging an HTML5 app directly from the device can be a very frustrating experience. GapDebug makes this process much easier, using a single interface for all apps and devices, and without requiring the developer to add special code.

How GapDebug Works – Plug and Debug

Before you can begin debugging, your iOS or Android devices require a simple 1-time configuration as outlined here. With your device configured, simply plug and debug by connecting your device to the GapDebug host computer using a USB cable. The device may prompt you to approve the connection. Once the connection is completed, the device info will appear on the left of the GapDebug user interface in the Device Panel.

On the mobile device, launch the app that you wish to debug. If the app is not already present or up to date on the device, use the app installation button GapDebug Download Image found next to the device info to select and install a new version of the app. Alternatively, you can drag and drop a binary app executable file on the device to install it. When the app is launched, the app’s ID and icon will appear just under the device in the GapDebug Device Panel.

Selecting the app in the Device Panel will start a debug Inspector in a new tab pane on the right side of GapDebug user interface. Two versions of the inspector are provided: for iOS apps a custom version of Apple’s Safari Webkit Inspector is presented, while Android apps get a custom version of the Chrome Developer Tools.

GapDebug (Windows version)
GapDebug (Windows version)

Before we dig in and start debugging, let’s first examine how GapDebug is different than the popular debugging tool Weinre.

GapDebug vs Weinre

Until GapDebug, Weinre was the go-to cross platform debugger for PhoneGap apps. Weinre was developed in early 2011 by Patrick Meuller as an open source solution for remote debugging of iOS and Android PhoneGap applications. It consists of a JavaScript library that is dynamically loaded by the app at startup, a debugger user interface that runs in your browser, and a server that handles communications between the application and the user interface.

Weinre is implemented in JavaScript and requires Node.js to install and execute locally, although you can avoid setting up a local installation by using one of several freely available online Weinre servers.

Weinre debugger user interface
Weinre debugger user interface

While Weinre remains an innovative tool, it is beginning to show its age. Let’s look at some of the pros and cons of using Weinre:

Pros

  • The debugger provides tools for DOM and CSS inspection, resource browsing and analysis, and a JavaScript console
  • Developers can simultaneously debug multiple apps across multiple devices
  • Mobile devices only require a network connection, no USB tether required
  • No special device configuration required
  • Weinre debugging works for a wider range of iOS and Android OS versions than GapDebug. (GapDebug supports Android v4.4 and above and iOS v5 and above)
  • Open source under Apache license

Cons

  • The Weinre user interface is a dated version of the WebKit Inspector
  • No JavaScript debugging and profiling
  • Not easy to reload the app for testing events such as deviceready
  • Requires modification of application code to include a special instrumentation script
  • Device must be online with a network connection, can’t debug offline scenarios
  • Requires processing time for communication with remote Weinre server
  • Server connection frequently times out, terminating your debug session unexpectedly

Using GapDebug to observe frequent Weinre network XHR activity in an application
Using GapDebug to observe frequent Weinre network XHR activity in an application

By contrast, GapDebug first debuted in June 2014 and is being rapidly enhanced with monthly updates by a small team at Genuitec.

Pros

  • Provides the most powerful hybrid app debugging features available through the use of special versions of Safari WebKit Inspector and Chrome Developer Tools
  • Professional Windows and Mac OSX installers, with automatic updates
  • Free for all users including commercial use
  • Simultaneously debug multiple apps across multiple devices
  • No requirement to modify application code with special instrumentation library
  • Device does not require a network connection, can debug offline apps
  • Easy app reloading to test events such as deviceready
  • Windows users can remotely debug iOS apps
  • Remotely view, control and debug Android apps over the internet

Cons

  • USB tethering may be considered a negative by some users
  • At this time, no common inspector UI (for cross-platform debugging, you must learn both the Safari WebKit Inspector tool and the Chrome Developer Tools — Genuitec is working towards a common UI in future release)
  • Currently only supports Android v4.4 and above and iOS 5 and above

Using GapDebug with Sencha

Because Sencha Cmd already has tight integration with Cordova and PhoneGap, Ext JS and Sencha Touch developers can immediately benefit from the superior tooling of GapDebug.

Using GapDebug, you can simultaneously debug multiple apps running on iOS and Android, and you can even debug iOS apps from Windows. Considering all of the HTML and CSS inspection, JavaScript debugging, and resource profiling capabilities, using GapDebug is a great choice when it comes to wrapping Sencha applications with PhoneGap or Cordova.

Summary

In most areas, GapDebug exceeds the capabilities of Weinre. While both GapDebug and Weinre applications require instrumenting to support debugging, GapDebug is not invasive and does not modify your application code. The GapDebug inspector tools are state of the art and function even when the device is offline. Lastly, GapDebug continues to be rapidly improved by the Genuitec team.

Download GapDebug for free and start debugging your Ext JS and Sencha Touch applications today.

analyzing-the-roi-of-javascript-in-enterprise-software-development-1.png No Comments   Read more

Optimizing The Development Process With Sencha Cmd 5

Optimizing The Development Process With Sencha Cmd 5Sencha Cmd provides a suite of tools for generating and building applications using Sencha frameworks (Ext JS and Sencha Touch). In addition to these bookends of the development process, Sencha Cmd also provides useful tools for your everyday development. From a built-in web server to package management, Sencha Cmd can help you automate many common tasks. In this article, we will explore how all this comes together and test it out with a new custom component.

In a previous article, we covered some of the basic commands in Sencha Cmd that you can use to create and build applications — demonstrating how you can smoothly integrate with your existing systems and deployment processes. In this article, we’ll take a look at updates specific to Ext JS 5 and Sencha Cmd 5.

Sencha Applications

The recommended practice for authoring Sencha applications is to create one source file for each class based on the Sencha Class System. Anyone familiar with Java development will recognize this convention. This is a proven method for organizing large bodies of code for readability and maintainability, and it is also easy to debug when using the dynamic loader because each file is loaded independently.

For small applications, combining this approach with the “ext-all.js” file (which contains the entire Ext JS framework) could be viable for production. For most real world applications, however, this same structure is not suitable for production because of the many HTTP requests required to load all of the classes. Further, these requests have to travel over a much slower network, which means the cost to load each file is much higher than one would experience during development.

Using Sencha Cmd, you can take your Sencha application from its ideal development form and create a minimized, optimized and compressed form that is ready for production.

  • Minimized – Only the classes you need will be included.
  • Optimized – High-level constructs in your code are replaced with equivalent and more efficient forms.
  • Compressed – Commonly called “minification” this is the rewriting of descriptive variable names to single letters and updating all references to match.

Getting Started

To make this process as simple as possible, Sencha Cmd provides a customizable build script as part of a “starter”application. Don’t worry if you already have an application, because you can generate the missing pieces you need on top of an existing application.

With Sencha Cmd installed, you can go to a suitable folder and run this command to get an Ext JS 5.0.1 application generated and ready to go:

        sencha generate app -ext MyApp myapp

In the “myapp” folder, you’ll find an Ext JS application named “MyApp”. The first time you run this command on a machine, Sencha Cmd will download the Ext JS 5.0.1 package. Once cached locally, Sencha Cmd will then extract the needed pieces and generate the application.

This new application can be immediately built and shipped to production (though with little fanfare) like so:

        cd myapp
        sencha app build
        scp -r build/production/* user@prod:/var/www

Development Workflow

As important as these two endpoints may be, developers spend only a small part of their day dealing with them. Most developers spend the majority of their time working on JavaScript or Sass (or CSS). The optimal process here is to make changes to these files and reload the page in the browser to see the results.

There are two primary things that a Sencha application needs in place to enable “development mode”: a build of the necessary Sass into CSS, and an appropriate configuration for the dynamic loader (called the ”bootstrap”).

Using App Watch

Prior to Sencha Cmd, these processes were handled manually using Compass and by making calls to Ext.Loader. In a Sencha Cmd application, these steps are included in the build process and can be fully automated using the following command:

        sencha app watch

The watch command starts by performing a special, trimmed down build (of the Sass and bootstrap), launches the web server and then monitors for changes in your application.

        C:Tempmyapp>sencha app watch
        ...
        [INF] Loading app json manifest...
        ...
        [INF] Mapping http://localhost:1841/ to C:Tempmyapp...
        [INF] ------------------------------------------------------------------
        [INF] Starting web server at : http://localhost:1841
        [INF] ------------------------------------------------------------------
        [INF] Waiting for changes...

As changes occur, Sencha Cmd will update the bootstrap and CSS to keep everything in sync. As soon as you save a file in your editor, you will see something like this:

        [INF] Starting web server at : http://localhost:1841
        [INF] ------------------------------------------------------------------
        [INF] Waiting for changes...
        [INF] -----------------------
        [INF] Writing content to C:Tempmyapp/bootstrap.js
        [INF] Writing content to C:Tempmyapp/bootstrap.json
        ...
        [INF] executing compass using system installed ruby runtime
        unchanged MyApp-all.scss
        [INF] Refresh complete in 3 sec. at 06:52:25 PM
        [INF] -----------------------
        [INF] Waiting for changes...

Once “Waiting for changes” appears, we know that the application is ready to reload in the browser.

The watch command is ideal when you are working with Sass because it ensures that your changes are reflected in CSS as quickly as possible. As covered in the Theme Guide, the ordering of Sass files is driven by the corresponding JavaScript file order. This means that as you refactor JavaScript, the order of Sass files can be affected. But not to worry — all of these details are managed by App Watch.

If you are using packages, you can also be sure that App Watch will pick up changes in your required packages as well. Whether you change JavaScript, Sass or simply add or modify resources, App Watch will ensure that all of these pieces are updated. Even changing the package requirements in your app.json will trigger the necessary updates.

Recent Improvements To Watch

If you have used watch in previous releases of Sencha Cmd, you should know that we have made several improvements in recent releases.

In particular, for Mac OS X users, we have revamped the internal filesystem monitor to greatly reduce CPU overhead. We have also improved the monitor’s tracking, so it ignores folders like “.git”.

Sencha App Watch In Action

To show how App Watch works, let’s see what happens when we add a requires for an awesome new package, ext-ux-colorpick, to the app.json of our generated application:

        "requires": [
                "ext-ux-colorpick"
        ]

We create an instance in the Main.js view:

        items: [{
                ...
        },{
                region: 'center',
                xtype: 'tabpanel',
                items:[{
                        title: 'Tab 1',
                        items: [{
                                xtype: 'colorfield',
                                fieldLabel: 'Color'
                        }]
                }]
        }]

Then hit “Save All” and observe the App Watch output:

        [INF] Waiting for changes...
        [INF] BuildEnvironment config change detected : C:Tempmyappapp.json
        [INF] Source File : http://cdn.sencha.com/.../ext-ux-colorpick.pkg
        [INF] Downloading : ....................
        [INF] Extracting  : ....................
        [INF] -----------------------
        [INF] Loading app json manifest...
        [INF] Writing content to C:Tempmyapp/bootstrap.js
        [INF] Writing content to C:Tempmyapp/bootstrap.json
        ...
        [INF] executing compass using system installed ruby runtime
        overwrite MyApp-all.css
        [INF] Refresh complete in 10 sec. at 08:49:37 PM
        [INF] -----------------------
        [INF] Waiting for changes...

We can now reload the page and see the color picker:

You don’t have to use App Watch to use ext-ux-colorpick, of course. To see how this Ext JS 5 component is put together, see the source code in the CmdPackages repository on GitHub. The Readme file will also explain what is included.

Manual Alternatives To App Watch

As handy as App Watch is, there are times when you need alternatives. Perhaps you seldom change the Sass, or you don’t have any RAM to spare. Or maybe the fact that App Watch requires Java 7 precludes you from using it in your environment. In any case, we need to peek into a couple of these high-level building blocks to see the commands that will be helpful and when to use them.

There are three commands that are commonly used when not using App Watch. These are:

        sencha app build development
        sencha app refresh
        sencha ant sass
        sencha ant resources

Let’s look at when each of these commands is needed.

Cover All Bases

Regardless of what is changed, a development build will ensure that all the necessary pieces are rebuilt:

        sencha app build development

This command includes all the others, so it will take longer than they do, but it will pick up any changes you might make. What is the difference between the new development build and the testing build that has been in Cmd since its first release? The testing build is intended to mimic the production build but with some ability to still debug the application. In a testing build, optimization and compression are disabled but otherwise the outcome is as close to production as possible. In a development build, only the pieces needed to reload from source are performed. In other words, a development build does things like skip JavaScript concatenation and generate a full CSS build (to minimize the need to rebuild the CSS).

NOTE: Sencha Cmd 5 has changed the list of build environments slightly to better manage Cordova and PhoneGap builds. Instead of “native” and “package” environments (which were unique to Sencha Touch), we have added “development” used above. This environment is the minimal build necessary for development purposes. The native and package operations are now handled by the “packager” config (see here for more details).

Changes in Theme or Package Requirements

If you change your package requirements or your theme in app.json, you should run a development build:

        sencha app build development

This ensures all of the Sass and resources are in sync with your package requirements as well as updates the bootstrap to describe the JavaScript sources from the new package.

Changes in Sass

When not using App Watch, changing Sass is the most common reason to fire up Cmd. If you are just changing the content of a .scss file, then the fastest way to rebuild just the Sass is:

        sencha ant sass

This will pick up changes in the Sass of required packages or themes as well. You don’t need to run “sencha app build development” in this case.

Changes in Resources

If you add a new image to your resources folder or to the resources folder of a required package (or theme), you can update the built resources using this:

        sencha ant resources

This places app and theme resources directly in the “resources” folder. Resources for a non-theme package “foo” would be placed in “resources/foo”.

Changes in JavaScript

Most changes in JavaScript do not require you to run any commands. If you follow the standard naming conventions for folders and files, so the Ext.Loader can properly convert class names into URLs, then you will rarely need to update the bootstrap. This is a good thing to be sure.

The command that updates the bootstrap is:

        sencha app refresh

Then, the question is: “what changes in JavaScript invalidate the bootstrap”?

To answer this question, it is best to sketch out the content of the bootstrap produced by refresh:

  • The relative paths to your “app” folder and “src” folders of all required packages (and themes).
  • The names of all classes (in your app and required packages).
  • The alternateClassNames for all classes.
  • The aliases for all classes.

This information enables these conventions in your application:

  • Require a class by its alias.
  • Require a class by an alternateClassName.
  • Require multiple classes using a wildcard (for example, “MyApp.model.*” ).
  • Require a class by name that does not conform to the file name conventions.
  • Create an instance using an alias, alternateClassName (or non-conforming file name) that is not listed in a “requires”.

If your application makes use of these features, then changes in JavaScript that affect the bootstrap content would require a refresh. Other changes do not require any commands at all.

Another way to look at the list above is to consider it as things to avoid if you are not using App Watch and don’t want to worry about refreshing your bootstrap.

In A Nutshell

If you are not using App Watch, you can typically avoid the need to run commands during everyday development by following the recommended conventions and listing “requires” for the classes you use. In this case, only changes in Sass or in the set of required packages require a build.

You can learn more about the Sencha Cmd build process here.

Conclusion

We think you’ll find App Watch a valuable tool in your daily workflow. When you need alternatives, understanding how Sencha Cmd manages these details can help streamline your daily process. Let us know what you think and enjoy the new color picker component.

P.S. You can test out the color picker here.

cmd.png 4 Comments   Read more

Top Support Tips

New Framework, New Doctype

by Greg Barry

In Ext JS 5, we support IE 8+, so we no longer encourage users to use the strict HTML 4 doctype. We now recommend using an HTML5 doctype. We also recommend the X-UA-Compatible meta tag to ensure Internet Explorer does not activate “Compatibility Mode” because this mode is not supported by Ext JS.

The following code snippet shows the ideal doctype and head for Ext JS 5.

<!DOCTYPE html>
<html>
<head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>

You can find more information about recent changes in Ext JS in our What’s New in Ext JS 5 guide.


Overhaul your Overrides

by Greg Barry

Overrides can be a very helpful tool to expand or change functionality on core classes without having to modify the framework’s source code. Ext JS 4.1 brought about a new way to create these overrides for the framework. This new declarative-based override works well within the foundational principles of Ext JS 4 and Ext JS 5. These overrides can then be placed in your Sencha Cmd generated overrides folder. The overrides folder allows Cmd to automatically include the overrides. For instance, if you use Ext.grid.Panel, you can create a file at overrides/grid/Panel.js. This should be automatically included after bootstrap is refreshed via sencha app build, sencha app watch, or sencha app refresh.

This method of overriding can be seen throughout the framework within our own internal code style. Examples of internal overrides in action include: theming, localization, RTL, and much more.

That said, we still see old overrides from Ext JS 3 being incorporated into applications using newer frameworks. This creates the potential for timing issues when applying them to your new application architecture.

The preferred method of generating an override is as follows:

Ext.define('MyApp.overrides.panel.Panel', {
        override: 'Ext.panel.Panel',
        close: function() {
                console.log('My Change to Close');
                this.callParent(); // call the original method
        },
        helloWorld: function(){
                console.log('Hello World');
        }
});

Let’s go over the syntax:

  1. First, define your override with an appropriate namespace for your application’s overrides folder.
  2. Add the override config and give it a value equivalent to the class you want to override. In this example, we’re overriding Ext.panel.Panel.
  3. Add the function you want to override. You’ll need to make sure you keep all of the relevant pieces. In this case, I’ve only changed the close function by adding a console log. If you were to create a panel and then do panel.close(), you will receive a console message saying, “My Change to Close”.


    Note: In your overridden method, you should execute this.callParent() if you need the overridden method to be called including the methods of any base classes.
  4. Add a new function altogether. As you may imagine, Ext.panel.Panel does not contain a “helloWorld” method. However, I’ve just added it via this override. Now, creating a panel and issuing panel.helloWorld() will result in logging the message “Hello World”.

As you can see, overrides are a powerful utility for customizing the framework for your application. If your overrides are still formatted in the Ext JS 3 manner, it may be time for an overhaul.

You can read more about the define mechanism here.


callParent(), a Little Bit Less

by Don Griffin

callParent is a method provided by the Sencha Class System (common to Ext JS and Sencha Touch) that is used to call methods in your base class. This is commonly done when you derive from a framework class and override a method it provides such as onRender. When you invoke callParent from a method that has parameters, you have two ways you can pass along those parameters to the base class method. You could use the shorthand arguments keyword like so:

Ext.define('App.view.MyPanel', {
        extend: 'Ext.panel.Panel',
        onRender: function (parentNode, index) {
                this.callParent(arguments);
        }
});

Or, you could explicitly pass these arguments in an array literal:

onRender: function (parentNode, index) {
        this.callParent([ parentNode, index ]);
}

The differences may seem minor, but when you use the Sencha Cmd 5 new optimizations for callParent, performance improvements can be profound. With the optimizer enabled, these two methods are optimized as follows:

onRender: function (parentNode, index) {
        Ext.panel.Panel.prototype.onRender.apply(this, arguments);
}
 
onRender: function (parentNode, index) {
        Ext.panel.Panel.prototype.onRender.call(this, parentNode, index);
}

In the second case, the optimizer is able to use the call method on the JavaScript Function instead of apply. We also avoid using arguments. Both of which are well-known high performance no-no’s. It turns out that we even avoid creating the array literal. Obviously, just enabling the optimization is helpful, but in code where performance is most critical, it is worth replacing arguments with the explicit array.

If you have questions, visit the forum.

20131111-top-support-tips.jpg 2 Comments   Read more

Announcing Sencha Architect 3.1

Sencha Architect 3.1On behalf of Sencha and the entire Architect team, I’m proud to announce the release of Sencha Architect 3.1. It comes with many new features, most notably Ext JS 5 support. Within the short period since the Ext JS 5 release, we have added support to bring Sencha Architect to parity with all the new features offered by Ext JS 5. We want to thank all the participants of the Sencha Architect 3.1 Early Access Program (EAP) for their invaluable input.


Ext JS 5 Support in Sencha Architect

The biggest update in Sencha Architect 3.1 is the addition of Ext JS 5 support. Ext JS 5 offers many new and exciting features: Touch support, architectural improvements (MVVM), responsive configs, and component upgrades, to name a few. All of these features are now supported by Sencha Architect.

MVVM Architecture Support

Ext JS 5 introduced support for MVVM architecture, with ViewControllers tied directly to the Views. To support this new approach, Sencha Architect 3.1 automatically generates a ViewController for every view that you create. Also with the new MVVM approach, a ViewModel coordinates changes between Model’s data and the View it represents, using a technique called “two-way data binding.” Sencha Architect 3.1 automatically generates a ViewModel as well for every view that you create. We encourage you to use ViewModels and ViewControllers. Note that if you are upgrading an existing Ext JS 4.2.x app, Sencha Architect 3.1 will continue to use the MVC structure you are accustomed to, but it will also allow you to leverage the MVVM functionality.

View Controllers

Routing Support

We have added support for the newly introduced routing feature in Ext JS 5, which allows you to implement “deep linking” within your applications by translating your application’s URL into controller actions and methods. Sencha Architect 3.1 offers a very simple interface to designate URLs on which to fire functions.

Routing Support

Touch-Optimized Charts Support

Ext JS 5 added a new high-performance and touch-optimized charting package (built on top of Sencha Touch charts) that offers support for interactions (pan, zoom, etc.) as well as some new chart types and enhancements to existing chart types.

Touch Charts Support

There are significant differences between this new charting package and the older Ext JS 4 legacy charts. Due to the differences, Sencha Architect 3.1 can’t auto-update your charts, instead it asks you to replace them using the new charts package. Note that Sencha Architect 3.1 does not support the use of the legacy charts, even though its available as a standalone package with the Ext JS 5 framework. That said, we have made every effort to provide helpful migration information for updating to the new charts package.


Migrating Ext JS 4.2.x Applications to Ext JS 5.0.x

One of our main goals with Sencha Architect 3.1 was to make the migration of Ext JS 4.2.x applications (built using the previous versions of Sencha Architect) as simple as possible. MigrationTo upgrade your application, simply open your Ext JS 4.2.x project in Sencha Architect 3.1, right-click on the Library node under Resources, and click Upgrade to Ext JS 5.0.x. Remember, Ext JS supports both the new MVVM and the previous MVC architectures, and it is not mandatory to switch to MVVM from MVC for your existing applications. Sencha Architect 3.1 will not automatically convert your MVC code to MVVM, but it will enable you to get started with the new MVVM architecture along with your existing MVC structure.


Sencha Cmd 5 in Sencha Architect 3.1

The latest Sencha Cmd 5.0.x integration with Sencha Architect 3.1 also offers a number of optimizations to make Sencha Architect and Cmd work faster and better, together.

Sencha Architect 3.1 leverages the Sencha Cmd ‘sencha app watch’ functionality to automatically digest and recompile the changes to your application by continuously monitoring for changes. With Sencha Cmd 5.0.x, Sencha Architect 3.1 can now deploy its own lightweight web server. This is especially helpful for users that are doing proof-of-concept projects or are just getting started and do not have a server environment set up. You can find the configurations for the web server under Preferences -> Web Server, where you can enable or disable it, and designate a port number.

Cmd Support


Other Improvements in Sencha Architect 3.1

Improved Project Inspector

We’ve greatly enhanced the project inspector in Sencha Architect 3.1 to make it easier to navigate, and to load large projects faster. The new project inspector even shows the namespaces as folders (a highly requested feature by our users), which is incredibly helpful when trying to organize your classes. The inspector now has two tree panels that sit side by side. The left pane shows every top level class and the right pane shows all details of the selected class.

Project Inspector

Visualization for Linked Instances

Sencha Architect has always allowed you to re-use existing views as building blocks to compose other views. We call this feature linked instances. When hand-coding this would be the same as writing a subclass and then re-using that class. Simple and DRY (http://en.wikipedia.org/wiki/Don’t_repeat_yourself).

When we expanded the single pane inspector to two panes it was obvious that we would need to change the way we visualized the relationships between classes. We are drawing bezier curves with SVG from each instance of the class in the detail inspector to where the class is defined.

Class Relationships

The reverse connection can also be shown by clicking the linked instance icon in the main panel. It will list every instance of where this class is being used.

Class Relationships

Helper Tool

We have added a “Helper” tool to provide common use cases that will support your development. The initial implementation of the ‘Helper” contains a data UI builder. We plan to enhance this feature in future releases of Sencha Architect.

Helper Tool

Theming Enhancements

Sencha Architect 3.1 provides a new feature for theming called “Quick Themes.” Quick Themes, which work just like custom themes, allow quick modifications to Neptune and Neptune Touch (default Ext JS themes) by simply modifying a few variables. Users save time by not having to customize every single component. A Quick Theme can always be converted to a regular custom theme, if you need more detailed customization. Other areas where Theming got some enhancements are: speed, autocomplete for SCSS variables, gradient selectors, and font selectors.

Theming

Editor Enhancements

The editor experience in Sencha Architect 3.1 has been enhanced to allow inline editing within classes. Users can now see the full context of their classes as they edit properties, create functions, and/or add comments.


Thank You

Adding Ext JS 5 support to Sencha Architect was a huge task, and we sincerely appreciate the comments and feedback from our Early Access Program (EAP) participants. We are very excited about this release and would like to hear about your experiences. Please give us your feedback in the Sencha Architect 3.x forum, so we can improve it further.

20140804-architect-3-1.jpg 19 Comments   Read more

What’s New in Ext JS 5.0.1

What's New in Ext JS 5.0.1Today, we are excited to announce the general availability of Ext JS 5.0.1! This maintenance release includes a number of improvements based on feedback from the Sencha community.

Lets take a tour of the changes.

Accessibility

With Ext JS 4.2.2, we released the “ext-aria” package to provide improved support for accessibility (as described in the WAI-ARIA 1.0 standard). While this was an important step to providing tools for you to make your applications accessible, we also learned a lot from the feedback we received both from our testing partners and early adopters.

With Ext JS 5, we wanted to incorporate that feedback and provide a better solution. I am delighted to say that with Ext JS 5.0.1, support for accessibility is much improved. In large part, this is because our support for focus and keyboard navigation has moved from “ext-aria” to the framework itself.

Focus

In Ext JS 5.0.1, we have greatly improved the internal handling of focus to better align with accessibility standards. The core components (such as buttons, tabs, form fields and grids) now all provide a clear, visual indication of focus. This is a key requirement for accessible applications. To give you control over these new visual aspects, we have added several new Sass variables and mixin parameters.

Keyboard Navigation

Previous releases of Ext JS provided the Ext.FocusManager to assist in managing focus. While this class remains, it is no longer the recommended approach. Instead, all components now have a “focusable” property that is used to manage the tabIndex DOM attribute. Any component with this property that is set to true will be able to receive focus either by clicking or via the keyboard.

When these focusable components are placed in certain containers (such as toolbars), the container provides arrow key navigation and manages which item will receive the focus on entry to the container.

There is lots of information about these accessibility, focus and keyboard navigation improvements. For more details, see the Accessibility Guide

ViewModels

It has been great seeing how quickly developers have picked up ViewModels and data binding. In addition to general bug fixing, there are some noteworthy improvements related to binding.

Selection Binding

Many developers have requested that we expand on the ability to use “selection” as a bindable property on those components that support the notion (such as ComboBox, Grids, Trees, Breadcrumbs, etc).

You can now use binding to keep the selections of these components in sync. For details, see the Kitchen Sink example.

Model & Field Validation

One key improvement with form fields is that two-way bindings now check that the value is valid before updating their bound properties. To support this when binding to Model fields, the form fields can now acquire the Model’s validators and include them in their own validation.

In Ext JS 5.0.0, these validators could only be consulted by first putting back the (potentially invalid) value. With Ext JS 5.0.1, you can be assured that invalid values will never be put back into your records.

Data

Ext.data also has some important fixes and improvements with this release.

TreeStore vs Node Events

With Ext JS 5.0.0, the TreeStore class was refactored to extend Ext.data.Store. In this process, however, one key problem existed: the way a TreeStore would relay events from the root node (Ext.data.NodeInterface).

For most events fired by tree nodes, everything worked as before. Unfortunately, certain node events collided with store events which created problems for listeners. One such example is the “remove” event.

The only safe and sure fix for this issue was to prefix all node events with “node” before firing them as TreeStore events. This means that the node’s “remove” event is now fired from the TreeStore as “noderemove”. While we always strive to avoid such changes in a maintenance release, there was really no way to resolve the issue without breaking either node listeners or store listeners. We apologize for the inconvenience this change may cause.

Associations

One limitation with associations in Ext JS 5.0.0 was that if you created a new record and then dropped that record, there was no cleanup logic to handle its potential child records. This could create a situation where a session would generate, create or update operations for these child records. These operations could not be processed by the server because the parent record was not saved.

With Ext JS 5.0.1, reference fields that declare parent/child ownership between Models are consulted when dropping records. When you indicate this type of association, dropped records will automatically handle deleting their child records.

For example:

        Ext.define('App.model.Order', {
                extend: 'Ext.data.Model',
                // ...
        });
 
        Ext.define('App.model.OrderItem', {
                extend: 'Ext.data.Model',
 
                fields: [{
                        name: 'orderId',
 
                        // Indicates that the referenced Model (Order) owns these
                        // records:
                        reference: { parent: 'Order' }
                }]
        });

In this way, when an Order is dropped (marked for deletion), its child OrderItems will likewise be dropped:

        order.drop();

Further, setting parent references to null (for example, by removing it from the parent’s association store) schedules that record for cleanup.

     order.orderItems().removeAt(0); // removed orderItem is dropped
 
     order.orderItems().getAt(0).setOrder(null); // also drops this item

The server is still ultimately responsible for a full cascade delete, but the above handling ensures that the client will never reference dropped records in save operations.

Responsive Configs

The new responsiveConfig provided by Ext.mixin.Responsive and Ext.plugin.Responsive provides lots of flexibility for managing dynamic conditions cleanly.

The new responsiveFormulas allows you to add properties for responsiveConfig rules to use. For example, your main controller could do something like this to publish new properties:

        Ext.define('MyApp.view.main.Main', {
                extend: 'Ext.container.Container',
 
                mixins: [
                        'Ext.mixin.Responsive'
                ],
 
                responsiveFormulas: {
                        small: 'width < 600',
                        medium: 'width >= 600 && width < 800',
                        large: 'width >= 800',
 
                        tuesday: function (context) {
                                return (new Date()).getDay() === 2;
                        }
                }
        });

In the above example, these new values (“small”, etc.) can be used in any of your responsiveConfigs. This can really help streamline your application’s responsiveConfigs as well as give you a single place to maintain these kinds of choices.

Charts

The “sencha-charts” package also contains several improvements, such as reusable markers like arrows, diamonds, etc. For starters, there is now a build of the sencha-charts package included in Ext JS 5.0.1 for those not using Sencha Cmd. The most significant change is that we’ve documented and exposed how to create custom chart themes.

Chart Themes

In Ext JS 5.0.0, charts shipped with several built-in themes that you could select for your charts, but building custom themes was not a documented process. With this release, we have provided this ability, so you can make your own color palettes and much more.

A theme for charts is a class derived from Ext.chart.theme.Base and given an alias that starts with “chart.theme.”. A basic theme could be as simple as this:

        Ext.define('App.chart.theme.Awesome', {
                extend: 'Ext.chart.theme.Base',
 
                singleton: true,
                alias: 'chart.theme.awesome',
 
                config: {
                        baseColor: '#4d7fe6'
                }
        });

From here, you can add any number of other configs to style your series, axes and markers. To see all the options, check out the API reference for the available configs. To use the new theme we’ve created, we simply set the “theme” config on the desired charts:

                theme: 'awesome'

Sencha Cmd

Last but not least, with Sencha Cmd 5.0.1 we have expanded the options in app.json to give you much more, fine-grained control to configure things to suit your needs without having to delve into the build scripts.

output

To give you a peek at the most useful of these new controls, let’s look at the “output” object. A common requirement for some environments is to maintain the “markup” file in a folder other than where the Sencha application resides. For example:

        foo.php
        foo/
                app.json
                app.js

The difference with this model is that the markup file (“foo.php” above, but it could be anything) is in a parent folder. In previous releases, this required setting several build properties. In Sencha Cmd 5.0.1, we can now do this in app.json:

        {
                ...
                "indexHtmlPath": "../foo.php",
 
                "output": {
                        "page": {
                                "path": "../foo.php",
                                "enable": false
                        }
                }
        }

The above ensures that all paths will be calculated relative to the parent folder while also disabling the build step that rewrites the markup file. The “output” object can control many other aspects of your build’s output, from enabling compiler optimizations to tuning the microloader.

packager

Cordova and PhoneGap are now much more flexible and easier to use with the new “packager” property. This new setting allows your build to specify its packager (either “cordova” or “phonegap”) directly in app.json. Combined with the “builds” object (added in Sencha Cmd 5.0.0), we can make an app that builds for the web, iOS and Android.

For example:

        {
                ...
                "builds": {
                        "web": {
                                "default": true  // picked by "sencha app build" 
                        },
                        "ios": {
                                "packager": "phonegap",
                                "phonegap": {
                                        "config": {
                                                "platform": "ios",
                                                "remote": true  // use PhoneGap Build
                                        }
                                }
                        },
                        "android": {
                                "packager": "phonegap"
                                "phonegap": {
                                        "config": {
                                                "platform": "android" // use Local Phonegap
                                        }
                                }
                        }
                }
        }

As before, we can run a build like so:

        sencha app build

The above will use the “web” build definition. But now we can also do these builds:

        sencha app build ios
        sencha app build android

Of course, you will need to have PhoneGap installed, and you will also need to configure your PhoneGap Build credentials. Alternatively, you could remove the above “remote” config and switch to the “cordova” packager (if you have Cordova and an iOS development environment installed).

Other than formalities, you can probably see how this property cleans up your build process. Using this approach also frees you up to add “testing” to any of these builds and get uncompressed JavaScript code for debugging (something that required manual tweaks in previous releases).

Conclusion

Ext JS 5.0.1 and Sencha Cmd 5.0.1 deliver many of the most important improvements that you’ve requested. On top of all the new capabilities in Ext JS 5, we are excited to see what amazing things you can do in your apps. Download it and try it out. Then, let us know in the forums what you think.

5.0.1.jpg 16 Comments   Read more

Reusing Code in Ext JS 5 and Sencha Touch Apps to Build a Sencha Space App

Guest Blog Post

With Ext JS 5&#44 reusing code between mobile &#40Sencha Touch&#41 and desktop/tablet apps &#40Ext JS&#41 is a dream come true. In the following exercise&#44 we will harness the power of Sencha Cmd 5 to build a Sencha Space application that&#39s capable of sharing code between Ext JS 5 and Sencha Touch 2.

Our goals are to&#58

  • Create Sencha Touch and Ext JS apps that reuse as much code as possible
  • Use packages to contain shared features
  • Learn how to tackle incompatibilities
  • Deploy apps in a Sencha Space environment

To reach our goal&#44 we will create an app that displays data for the most popular web browsers of 2012 in form of a grid and chart. The entire source code presented in this exercise is available for you to fork or download.

Preparation

Good preparation is the key to success. Workspace and packages are old pieces of a puzzle that provide a much clearer picture of multi&#45application environments now that Ext JS 5 is available.

Let&#39s start with creating a workspace. Make sure you have Sencha Cmd 5 installed.

gmac15:modus-presos grgur$ sencha generate workspace Ext5Tablet
Sencha Cmd v5.0.0.160
...

Now&#44 we have a workspace directory that will host our applications and the frameworks. Navigate to the workspace directory and run&#58

gmac15:Ext5Tablet grgur$ sencha -sdk /path/to/ext-5.0.0 generate app MyApp ./ExtSpace

We will refer to our app as MyApp. This Ext JS 5 application will serve our tablet users. To suppport our phone users&#44 we will create a separate Sencha Touch application&#58

gmac15:Ext5Tablet grgur$ sencha -sdk /path/to/touch-2.3.1-complete generate app MyApp ./TouchSpace

Finally&#44 it&#39s time to create our package that contains shared code. We will code a chart and a grid/list component in it&#44 so let&#39s call the package GridChart. From your workspace directory execute&#58

sencha generate package GridChart

This is what our file structure looks like now&#58

ExtSpace and TouchSpace are application folders&#44 packages/GridChart contains shared components&#44 while ext and touch reference framework SDKs. In the following sections&#44 we will take a deeper dive into each of these pieces.

Shared Chart Components

Ext JS 5 includes the amazing new charts from Sencha Touch 2. Best of all&#44 their configuration pattern is very similar&#44 so we can easily reuse them in our apps.

The Ext.chart.Chart widget is capable of intelligently instantiating the needed chart &#8212 and it does that for both frameworks.

Ext.define('GC.Chart', {
        extend : 'Ext.chart.Chart',
        xtype  : 'gcchart',
 
        config : {
                animate      : true,
                background   : 'white',
                insetPadding : 40,
                interactions : 'itemhighlight',
                legend       : {
                        docked : 'bottom'
                },
 
                colors: [...],
 
                series: [...],
                axes  : [...]
        }
});

Full source code is available here.

Note&#58 Charting in Sencha Touch is part of the Sencha Complete bundle.

Two patterns are visible in this example. First&#44 the code will be shared &#8212 meaning the entire class definition is compatible with both Sencha Touch 2 and Ext JS 5.

Second&#44 Ext JS 5 understands properties from config object and maps them to those outside of the block. That&#39s why this chart configuration looks like Sencha Touch but works just fine in Ext JS.

Now that we have a universal chart widget&#44 we can take a look at how we can create shared code that is slightly less common for the two frameworks.

Grid vs. List

We want to show plot data in a grid&#45like view. The Ext JS grid widget will perform the task for tablets and the Sencha Touch List will display data for phones. Nonetheless&#44 the code for both will exist in the same package.

The beauty of this approach is in a single line that belongs to the &#39package.json&#39 file of our GridChart package. From the workspace directory&#44 edit the ~/packages/GridChart/package.json file and add the following line&#58

"classpath": "${package.dir}/src,${package.dir}/src-${framework.name}"

The part that resembles &#39src&#45${framework.name}&#39 will allow us to have two folders&#44 each containing source code just for its respective framework. Those folders will be &#39src&#45touch&#39 (List) and &#39src&#45ext&#39 (Grid).

Both widgets will be very simple. For tablets&#44 our grid setup is as follows&#58

Ext.define('GC.Grid', {
        extend : 'Ext.grid.Panel',
        xtype  : 'gcgrid',
 
        title       : 'Browsers',
        split       : true,
        collapsible : true,
        columns     : [
                {
                        text      : 'Month',
                        flex      : 1,
                        dataIndex : 'month'
                },
                {
                        header    : 'IE',
                        xtype     : 'numbercolumn',
                        width     : 70,
                        dataIndex : 'data1',
                        format    : '0,0%'
                },
                {...},
                {...},
                {...}
        ]
});

Full source code is available here.

On the other hand&#44 the List is all about its template&#58

Ext.define('GC.Grid', {
        extend : 'Ext.List',
        xtype  : 'gcgrid',
 
        config : {
                cls     : 'browserlist',
                itemTpl : [
                        '&lt;h1&gt;{month}&lt;/h1&gt;',
                        '&lt;div class="browsers"&gt;',
                                '&lt;b&gt;IE&lt;/b&gt; {data1} ',
                                '&lt;b&gt;FF&lt;/b&gt; {data2} ',
                                '&lt;b&gt;Chrome&lt;/b&gt; {data3} ',
                                '&lt;b&gt;Safari&lt;/b&gt; {data4} ',
                         '&lt;/div>'
                ].join('')
        }
});

Full source code is available here.

We can wrap it up with our simple approach to displaying data. The following section is all about plugging this code into the platform&#45specific code of each application.

Tablet Layout

Shared code makes up a large part of our apps&#44 containing most of the business logic. Plugging it in is as easy as appending a single line into the &#39~/ExtSpace/app.json&#39 file of our Ext JS application.

         "requires": [
                "sencha-charts",
                "GridChart"
        ],

Full source code is available here.

Ext JS 5 comes with a modular approach to dependencies. You’ll also want to use the &#39sencha&#45charts&#39 package. Sencha Cmd 5 knows how to find each of these and will make the classes available to the application.

Note&#58 if you browse to the Ext JS 5 SDK directory&#44 the packages folder will have ext&#45charts and sencha&#45charts listed. Ext&#45charts refers to the older charting package&#44 whereas sencha&#45charts is the all new and improved code.

Before proceeding to editing the Main view&#44 you will learn a new trick with Cmd 5 &#8212 app watch. Make sure your terminal is in the directory of your application (e.g. ~/ExtSpace) and run&#58

gmac15:ExtSpace grgur$ sencha app watch
Sencha Cmd v5.0.0.160
[INF] Loading app json manifest...
...
create MyApp-all.css
[INF] Mapping http://localhost:1841/ to /Users/grgur/Projects/modus/modus-presos/Ext5Tablet...
[INF] ------------------------------------------------------------------
[INF] Starting web server at : http://localhost:1841
[INF] ------------------------------------------------------------------
[INF] Waiting for changes...

Many of the seasoned developers are already familiar with this command&#44 which sits in the background and watches for changes in SASS and JavaScript files. Any changes will automatically do the minimum amount of work to update the app &#8212 whether it&#39s CSS compilation or class metadata refresh.

Additionally&#44 the command will now instantiate the built&#45in Jetty web server to host your files hassle free.

With everything ready&#44 we can create the main view&#58

Ext.define('MyApp.view.main.Main', {
        extend : 'Ext.container.Container',
        xtype : 'app-main',
 
        requires: [
                'GC.Chart',                       //#1
                'GC.Grid',                        //#1
                'Ext.data.JsonStore',
                'Ext.chart.*'
        ],
 
        layout : {                          //#3
                type : 'border'
        },
 
        config : {                          //#2
                grid : 'west',
 
                chart : 'center',
 
                store : [                       
                        { month : 'Jan', data1 : 20, data2 : 37, data3 : 35, data4 : 4 },
                        //...
                        { month : 'Dec', data1 : 15, data2 : 31, data3 : 47, data4 : 4 }
                ]
        },
 
        /**
         * Instantiate a store based on data&#44 storeId or store instance
         */
        applyStore : function (data, store) {       // #5
                return Ext.isString(data) || data.isStore ? Ext.getStore(data) : Ext.factory({
                        fields : ['month', 'data1', 'data2', 'data3', 'data4' ],
                        data   : data
                }, 'Ext.data.JsonStore', store);
        },
 
        /**
         * Instantiate shared chart
         * @param region
         * @param chart
         * @returns {GC.Chart} Chart
         */
        applyChart : function (region, chart) { // #5
                return Ext.factory({
                        region : region,
                        width  : 400,
                        store  : this.getStore()            // #4
                }, 'GC.Chart', chart);
        },
 
        /**
         * Instantiate grid
         */
        applyGrid : function (region, grid) {       // #5
                return Ext.factory({
                        region : region,
                        width  : 400,
                        store  : this.getStore(),           // #4
                        title  : 'Browsers in 2012'
                }, 'GC.Grid', grid);
        },
 
        /**
         * Add items to the view
         */
        initComponent : function () {
                var me = this;
 
                me.items = [
                        me.getChart(),
                        me.getGrid()
                ];
 
                me.callParent();
        }
});

Full source code is available here.

Just by reviewing the code above you will notice a few gotchas&#58

  1. Previously we included the GridChart package in our app&#44 so Sencha Cmd could correctly map its location. In order to use any of the classes from that package&#44 we must still require them as per the Sencha convention.
  2. Unlike Sencha Touch 2&#44 Ext JS 4 configuration options are not members of the config object. For cross&#45framework compliance&#44 Ext JS 5 is now able to recognize most parameters from config objects that should otherwise belong to the constructor. In this example&#44 we are re&#45using the store property and adding two new: grid and chart. Both grid and chart are strings representing a location in the border layout.
  3. Layout is an exception for the point above. Due to differences in Ext.Component lifecycle between Sencha Touch 2 and Ext JS 5&#44 layout configuration has to be outside of the config block.
  4. Both grid and chart components reuse the same local data store.
  5. The Sencha Touch modular component instantiation&#44 which uses factory method and appliers&#44 is now Ext JS compliant. See applyStore&#44 applyChart&#44 and applyGrid methods.

Tip&#58 When creating shared components in packages&#44 we can override &#39constructor&#39&#58

constructor: function (config) {
        config.layout = 'border';
        this.callParent([config]);
}

Most of the hard work is now done. If you run the Ext JS 5 application in your browser&#44 you will see something like this&#58

Let&#39s replicate this view in Sencha Touch.

Phone Layout

Before adding any view code&#44 we will revisit this app&#39s app.json file in ~/TouchSpace/app.json&#58

"requires": [
        "GridChart"
],

Full source code is available here.

This time there is no need to reference sencha&#45charts because charts are not in the form of a package in Sencha Touch 2.3.

You can run sencha app watch for this app as well to help streamline updates.

Now&#44 let’s edit the Main view that was automatically generated for us and update it to match something like this&#58

Ext.define('MyApp.view.Main', {
        extend   : 'Ext.Container',
        xtype    : 'main',
        requires : [
                'GC.Chart',
                'GC.Grid',
                'Ext.data.JsonStore',
                'Ext.chart.*'
        ],
        config   : {
                layout: {
                        type: 'hbox',
                        align: 'stretch'
                },
 
                grid  : 1,
                chart : 2,
                store : [...]
        },
 
        applyStore : function (data, store) {...},
 
        applyChart : function (flex, chart) {
                return Ext.factory({
                        flex  : flex,
                        store : this.getStore()
                }, 'GC.Chart', chart);
        },
 
        applyGrid : function (flex, grid) {...},
 
        /**
         * Add items to the view
         */
        initialize : function () {
                var me = this,
                        grid = me.getGrid(),
                        chart = me.getChart();
 
                me.add([
                        grid,
                        chart
                ]);
 
                me.callParent();
        }
});

Full source code is available here.

Instead of border layout&#44 we used horizontal box. Everything else looks similar to the code we used in the Ext JS variation of the app.

The main difference is in the initialize and initComponent blocks where Ext JS needs to override this.items property&#44 and Sencha Touch makes use of the add method. This is simply because Sencha Touch creates DOM elements during instantiation&#44 while Ext JS does so during render phase&#44 which happens just before inserting the widget into the DOM.

With sharing so much of the code from the Ext JS application&#44 we developed a similar user interface in just a few minutes. If you haven’t run it in a browser yet&#44 this is what you will see&#58

Deploying in Sencha Space

Sencha Space is a secure&#44 cross&#45platform environment for mobile web and HTML5 apps that helps organizations deliver enterprise applications to end users. If you are new to Sencha Space&#44 you can watch the webinar Deep Exploration of Sencha Space.

Our new application will benefit from being part of this ecosystem and use its API to communicate with other apps.

Provided that you already have an account&#44 log in to your Sencha Space Management Console. From here&#44 add the apps and make sure they point to your local web server. No need to make the app publicly available quite yet&#44 which will help with the debugging process.

Make sure you set up invoke intent strings for both applications (see figure below). This demo uses *bpmobile* for phone (Sencha Touch) and *bprich* for tablet application (Ext JS).

We will revisit app.json files of both applications just to add paths to Sencha Space APIs. If you wish to debug&#44 you can also add a path to your local Weinre instance.

 "js": [
        {
                "path": "http://space.sencha.io/space.js",
                "remote": true
        },
//    ...
]

Full source code is available for the Ext JS 5 app and the Sencha Touch 2 app.

Finally&#44 one last gem. We want our apps to detect form factor and prompt the user to switch to the other app for a better experience. For example&#44 phone users accessing the Ext JS app should be told that a more applicable solution exists for their device.

Your Ext JS app&#39s ~/ExtSpace/app/Application.js file will have the following addition&#58

launch : function () {
        var me = this;
 
        Ext.onSpaceReady(function () {
                var width = Ext.getBody().getWidth();
                if (width < 1000) {
                        me.transferToMobile();
                }
        });
},
 
transferToMobile : function () {
        Ext.Msg.confirm('Phone detected', 'Do you want to see the phone site instead?', function (resp) {
                if (resp === 'yes') {
                        Ext.space.Invoke.get('bpmobile').then(function (connection) {
                                connection.send({}, true);
                        }, console.warn.bind(console));
                }
        });
}

Full source code is available here.

Ext.onSpaceReady fires when the Sencha Space ecosystem is ready to use&#44 which happens milliseconds after the document becomes available. Our handler will prompt the confirmation message first&#44 then use Invoke API to bring the Touch app to the foreground. Notice the bpmobile invoke string that identifies which app to communicate with.

There is no better reward than to sit back and enjoy the results of our coding session.

Ext 5 blog post from Modus Create on Vimeo.

Source

Full working source for this application is available here. All you need to do is load it in a browser or your Sencha Space instance.

Conclusion

Ext JS 5 offers many new features for enterprise apps&#44 one of which is support for integration and code sharing with Sencha Touch. However&#44 the integration capabilities extend much further with Sencha Cmd 5 and Sencha Space&#44 delivering the most feature rich frameworks to satisfy any enterprise environment. In this example&#44 we also demonstrated the power of the brand new Sencha Charts feature inherited from Sencha Touch 2. Ext JS 5 delivers an impeccable&#44 smooth user experience on both desktop and tablet devices.

reusing-code-teaser.jpg 5 Comments   Read more