Personal tools
You are here: Home   Documentation (new section)   Tutorials   Simple KSS   Begin with KSS  
 
Document Actions

Begin with KSS

Teaches how to setup and use KSS through a simple example.

ree

The target audience is everyone who wants to start using KSS. Zero knowledge of Javascript is required for this. Both designers and programmers should complete these lessons.
Page 1 of 4.

Installation

KSS is included with Plone 3.0. (We also plan provide backports for earlier versions, at a later point.) This document is valid for this version: kss.core 1.2, plone.app.kss 1.2 (Plone 3.0)

It is also important for all the further work that you run Zope in debug mode and that you disable caching from your browser. You should install the Web Developer Toolbar for Firefox. Then you should disable caching: this can be achieved from the leftmost menu in the Web Developer Toolbar by ticking in the Disable Cache checkbox. Note that otherwise you need to force the browser to reload the page completely after each change you have made in your KSS resource files. In case you have made a change and yet nothing happens on reload, it is caching to be blamed.

Also you would need to familiarize yourself with reading Javascript exceptions that occur on your page. KSS will raise a Javascript error in case something is wrong and you would be able to see this from your browser, some browsers (IE?) may require some debug option to set up. In case you have no browser preference we suggest to use FireFox as it comes with the most friendly debugging facilities. You are also suggested to install the FireBug extension.

Note that apart from reading the error message, you do not need to be able to understand or debug Javascript at all. Also you will not touch any Javascript code during this tutorial.

Production and Development mode

There is an additional logging facility that provides you with useful debug and informational messages about what happens. Debug information is only shown in Development mode of KSS. Development mode can be activated if you enable Debug mode in portal_javascript tool found in the root of your Plone Site. After doing so, you must reload your page in the browser. If you want to switch back to Production mode, you will need to reload the page again. Production mode offers a slightly smaller Javascript to be loaded into your page, and slightly faster execution, for example, by not giving you logs and detailed error messages.

If you ever see the Javascript error message Unknown message (kss optimized for production mode), this means you are running in Production Mode and you need to switch to Development Mode in order to see what happens.

If you are in Development Mode, and are using FireFox with the FireBug extension, you need not do anything, logs will appear directly in the FireBug console. If you use Safari, logging also appears in the Safari console. If these possibilities are not available for you, you have two other choices: either use Firebug Lite (on IE). or MochiKit (all browsers).

Activating logging with Firebug Lite (IE)

To activate Firebug Lite, you need to manually add the javascript file ++resource++firebuglite.js into the set of resources. You need to set this script to Non-Merging, and set its compression level to None. You must also make sure that you move this file above the ++resource++kukit.js and ++resource++kukit-devel.js. (Don't miss to press Save after this!) When this is done, you need to reload the page. After this Firebug Lite can be activated by pressing F12.

Activating logging with MochiKit

You need to do this only if you are unable to use both FireBug or FireBug Lite for some reason, although this should not happen.

First you need to enable MochiKit's javascript in the portal_javascript tool. Find the line with the id ++resource++MochiKit.js, and enable it, then press Save. Following this, reload your original page.

Then enter the following url into your browser after your page has been loaded (you can bookmark this as a link to avoid typing it in each time):

javascript:kukit.showLog();

Remark:

This needs to be repeated each time the page gets reloaded, because each time a page is loaded, the browser starts in a clear state, as far as javascript is concerned.

See the result of logging

In your KSS debug console (depending on the debug method you use) some log messages will start on reloading a page. They will begin this way:

Loading KSS engine.
...

If this does not happen, check if you have succeeded with the steps described above, most notably, are you in Development Mode? You may also need to log in to the portal, as by default KSS is disabled in Plone for non-authenticated users.

The text following the first line may indicate that KSS installed more eventrules on its own. This would not be a problem, but to allow us starting from a clean situation, we will disable all existing rule files.

Disable KSS's default event rule (KSS) files

Plone has some KSS rules in effect by default, which produces a lot of log messages. So first we want to disable this. Go to the ZMI and in the portal root, click on the plone_kss tool and deselect the plone.kss and at.kss checkboxes. Then save this page.

Reload your original portal page. At this point the logging console should display some log messages:

Loading KSS engine.
Using original cssQuery.
KSS bootstrap set up in Plone DOMLoad event.
Plone legacy [initializeMenus] action registered.
Plone legacy [bindExternalLinks] action registered.
Plone legacy [initializeCollapsible] action registered.
Plone [createTableOfContents] action registered.
Initializing 3 menus.
KSS started by Plone DOMLoad event.
Engine instantiated in [DOMLoad].
Initializing rule sheets.
Count of KSS links: 0
Setup of events for document starts.
0 special rules bound in grand total.
0 nodes bound in grand total.

This means that KSS is active in the page, but there were no rule sheets to set up - so nothing happened.

If the Count of KSS links is not zero, you need to return to the previous steps and make any remaining KSS resources inactive.

Some more explanation about the messages: The lines before the Count of KSS links are messages from plugin components that initialize themselves. There is no need to worry about that now.

Having arrived at this point, we can now proceed to start our first usage example.

Attach an event rule (kss) file

First you need to attach a KSS resource file to your page. This is similar to a CSS file in purpose - even the syntax is almost valid CSS - but it has different semantics and it controls how KSS events are bound to your page elements.

To do it simplest, create a file named tutorial1.kss in your custom skins directory. To make the file bound to each page in the portal, we need to make it known by the Resource Registries. Go to the ZMI in the portal root, enter plone_kss, press Add and customize your new entry in the following way:

Setting up portal_kss

Notice that merging should be disabled. We also set Compression type to None, and disable caching, to make it work more debugging friendly during this tutorial.o

Note:

In a production environment, you would want to set Compression type to safe, and allow merging and caching of the resource. You can also do this right now, just then do not forget to enable Debugging Mode on the top of the same page. This will make the resource debuggable, even if the production settings are applied for compression, caching and merging.

After pressing Add, navigate back to your portal frontpage, and reload it. You should see the following messages:

Loading KSS engine.
...
Initializing rule sheets.
Count of KSS links: 1
Start loading and processing http://127.0.0.1:8080/demo11/portal_kss/Plone%20Default/tutorial1.kss of type kss
GET http://127.0.0.1:8080/demo11/portal_kss/Plone%20Default/tutorial1.kss (39ms)
Finished loading and processing http://127.0.0.1:8080/demo11/portal_kss/Plone%20Default/tutorial1.kss resource type kss in 64 + 0 ms.
Setup of events for document starts.
0 special rules bound in grand total.
0 nodes bound in grand total.
Setup of events for document finished in 4 ms.
...

This means that your kss file is active on the page, although it is yet not doing anything. At this point you can proceed to the next chapter.

(optional:) Doing it the zope3 way

In the zope3 style of development instead of putting files into skins, we prefer to use resources. From the point of view of KSS this is all the same but this leads to a cleaner development style, better supported in the future versions of Plone. Do not attempt to do this however if you do not know at least a little of Five, because in this tutorial we will not teach you Five itself, we only show the way to use it for KSS. Remember: zope3 development style is easy once you have learned it, but one might feel that it has a steep learning curve.

To do this, you have to create a new product for the tutorlal or use one of your existing products. In the product directory on the filesystem, create a browser subdirectory and save the kss file there with the name tutorial1.kss. Then in the product root create a configure.zcml file with the following content:

<configure xmlns="http://namespaces.zope.org/zope"
  xmlns:browser="http://namespaces.zope.org/browser">

  <!-- the kss resource -->
  
  <browser:resource
    file="browser/tutorial1.kss"
    name="tutorial1.kss"
    />

</configure>

After this you need to restart zope: if you have made an error in this file you see it immediately as zope will refuse to start at all. If zope has started up, then check that the url http://127.0.0.1:8080/++resource++tutorial1.kss returns the kss file correctly from the browser (replace the beginning with your portal root url).

Also to use this file you must use ++resource++tutorial1.kss as the name of the file in the portal_kss tool. After making this change you should reload your page from the browser, open the kss debug console and see the log messages like above.

In addition, since now you have a separate tutorial product, you could also make a GenericSetup profule that automatically registers the kss resource with the kss tool. To have an example of this, you may want to peek in to Products/CMFPlone, into the profiles directory, ald learn the usage pattern from there. - However this step is totally optional and you might want to skip it at this point.

Set up some sample content

We will need some sample content in our example. For example we will need a navtree portlet appear on our page. Since this is not appearing on the front page of a newly created portal, we advise to create the following basic structure, that consists of a folder and three pages in it:

portal root ----- folder1 ----- page1
                     |
                     ---------- page2
                     |
                     -----------page3

In this case, if we visit the url http://127.0.0.1:8080/folder1/page1, we will get to the view of our simple page, and we can see the navigation portlet appearing in the left portal column.

You also need to log in as an authenticated user, because in the standard setup of Plone, KSS is disabled for unauthenticated users. Since you just created the above structure, this should already be true.

Write a simple event rule

Now we will add a KSS event rule to the kss file we created. This is the base unit that controls the dynamic behaviour of your page. A KSS rule looks similarly to a CSS rule. There is a selector part that selects one or more html nodes just like in CSS, then there is an event descriptor that is attached to the CSS selector with the comma. We will use the click event that will trigger when the selected node or nodes are clicked with the mouse.

First we decide which nodes we bind to. This can be any selectable element in the page. Let us first bind the event to the active element of the navtree - that is, the element where we are at the moment. Inspecting the page with Firebug, we will see the html of the required line:

<a title="" href="http://127.0.0.1:8080" 
         class="navTreeCurrentItem visualIconPadding">
  Home
</a>

We can see that the selector of this node can be, for example, a.navTreeCurrentItem so this will be the selector we use. The full event rule that we enter into the kss file will be this:

a.navTreeCurrentItem:click {
    action-client: alert;
}

Notice that after the selector we put :click, this tells KSS what event to use and is always obligatory in the KSS rule. Between the braces we have various properties that control what actions are bound to the selected nodes, and also the parameters for this actions. This rule says that when the event gets triggered, we do not want to communicate with the server yet, but simply pop up an alert box. This is just a debugging aid that helps us see if we are on the right track. The line action-client: alert; says we have a client action with the name alert. Later we will learn to use server actions.

Now reload the page, and you should see the following in the KSS console log:

Loading KSS engine.
KSS bootstrap set up in Plone DOMLoad event.
Plone legacy [initializeMenus] action registered.
Plone legacy [bindExternalLinks] action registered.
Plone legacy [initializeCollapsible] action registered.
Plone [createTableOfContents] action registered.
Initializing 2 menus.
KSS started by Plone DOMLoad event.
Engine instantiated in [DOMLoad].
Initializing rule sheets.
Count of KSS links: 1
Start loading and processing http://127.0.0.1:8080/demo11/portal_kss/Plone%20Default/tutorial1.kss of type kss
GET http://127.0.0.1:8080/demo11/portal_kss/Plone%20Default/tutorial1.kss (52ms)++resource++kukit... (line 3342)
EventRule #0: a.navTreeCurrentItem EVENT=click++resource++kukit... (line 2094)
Finished loading and processing http://127.0.0.1:8080/demo11/portal_kss/Plone%20Default/tutorial1.kss resource type kss in 58 + 7 ms.
Setup of events for document starts.
Using original cssQuery.
EventRule [#0-@@0@@click] selected 1 nodes.++resource++kukit... (line 2133)
0 special rules bound in grand total.++resource++kukit... (line 2667)
Instantiating event id [@@0], className [0], namespace [null].++resource++kukit... (line 3868)
1 nodes bound in grand total.++resource++kukit... (line 2582)
Setup of events for document finished in 14 ms.

Important is to see that our newly created eventrule is in effect (EventRule [#0-@@0@@click]), and that it is bound to 1 node in the page. The rest of the log can be ignored right now.

REMARK:

If the new contents of the kss file does not come into effect, make sure that you enabled Debugging in the portal_kss tool. If this is not done, the resource is most likely got cached where it should not be.

If we click on the Home line in the navtree portlet (or to the item line which is current and highlighted), the following popup dialog appears:

Alert action dialog

This tells us that the event has triggered in order, and also gives some additional information, like the number of the event rule (#0), the merge id of the event which is an internal identifier of KSS (@@0@@click), and the html node that triggered the event (A).

After pressing the OK button, the page will be reloaded because the link will be followed as if we would have clicked it normally. We will deal with this soon.

We should however note an important principle right away. If the rule does not select to any nodes, simply nothing happens: no error message will be raised. This is the designated behaviour and it is in line with how css behaves too. This is what allows us to put a lot of rules into the same kss file. No need to set up conditions: if the selected nodes are not present in the current page, simple nothing happens.

This is also the time to see what happens if we have an error in the kss file. Let us change click to klick and reload the page. We will get a javascript error. In FireFox for example a javascript error appears and we can see the followings in the console log:

[Exception... "'Error parsing KSS at
http://127.0.0.1:8080/demo11/portal_kss/Plone%20Default/tutorial1.kss :
ParsingError: Undefined event : [null:klick].' when calling
method: [nsIDOMEventListener::handleEvent]" nsresult:
"0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)" location:
"<unknown>" data: no]

The important part of the message says that the klick global event does not exist, the rest is just FireFox cruft. If we just make a syntax error, we get a ParsingError that also give the position of the error in the file. As a consequence nothing will work and we are forced to fix the error immediately and reload the page afterwards.

Note:

The null in [null:klick] means that the event is in the global namespace. Foe events in a custom namespace, the namespace would be displayed instead of null.

Specify an event binding parameter

Sometimes it is necessary to customize the way the event is bound. This can be done with parameters with the event binding. In the previous example after we closed the alert, the page reloaded because the link was followed by default. The click event has a parameter preventdefault which can be used to override this. The modified rule will be:

a.navTreeCurrentItem:click {
    evt-click-preventdefault: True;
    action-client: alert;   
}

The full property name is evt-click-preventdefault where three segments are separated with dashes:

  • evt says this is an event binding parameter
  • click is just the name of the event. It is obligatory to show it here.
  • the last segment is the name of the parameter itself that we are setting.

Also note:

  • The order of action-client and evt-click-preventdefault is not important.
  • Both capitals and small capitals are allowed in the boolean values, e.g. True or true, False or false are equivalent.

It is entirely up to each event which parameters they take and which ones are obligatory, or which ones have a default value. At the moment the preventdefault event is only usable for the click event and it has a default value of False. Obviously it may only be necessary to set this parameter if there is otherwise something that the browser wanted to do on the click, before we started to modify its behaviour.

The order of the lines within the rule block otherwise does not matter.

If we reload the page, after clicking on the link the alert will pop up but afterwards the link will not be followed. Specify an action parameter

We can also specify parameters to the actions themselves. The main difference between the event binder and the action parameters is, that the previous ones are effective when the event is bound (i.e. when we load the page) while the latter ones come to effect when the event is triggered (i.e. when we clicked on the link). As was the case with the event parameters, it is entirely up to the given action to decide what parameters it accepts and handles. Now, the alert action just happens to accept a message parameter, so we extend our rule with one line:

a.navTreeCurrentItem:click {
    evt-click-preventdefault: True;
    action-client: alert;
    alert-message: "Hey, we are here";
}

The property name was alert-message, the semantics is that we must always use the name of the action (alert) followed by a dash and the name of the parameter. Notice also that we stringified the value on the right side: this is only necessary if the value is not a single word. Both single and double quotes can be used and the quotes can also be used backslashed inside the string.

Reload a page, click on the link and see the alert popup appearing with the text we specified, with debug information added to the end of it:

Alert action dialog 2

This may also be the right moment to experiment if caching is not keeping you away from seeing your changes immediately. Principally, during development, when you have modified and saved the kss file, after reloading the page you should have the new values in effect - if you assure this, you will save yourself from a lot of headache.

You have learned the basics of setting up kss rules so far, but nothing that would really do anything so far. It is now time to sit back and relax a bit before we get to the definition and usage of server actions.

Continue...

 
by Balazs Ree last modified 2008-03-27 14:08
Contributors: spanky