display command which will be terminated
[mkws-moved-to-github.git] / doc / mkws-developer.markdown
1 % The MasterKey Widget Set developer's guide
2 % Mike Taylor
3 % November 2014
4
5
6 Introduction
7 ============
8
9 This manual is for people who want to build the widget set from
10 source, develop the widget set's core code, or (more likely) create
11 their own widgets as extensions to the main set.
12
13 Those who want to use existing widgets should read
14 [The MKWS manual: embedded metasearching with the MasterKey Widget
15 Set](mkws-manual.html) instead.
16
17
18 Required development tools
19 ==========================
20
21 If you are building the widget set, you will need the following Debian
22 packages (or their equivalents on your operating system):
23
24         $ sudo apt-get install curl git make unzip apache2 pandoc
25
26 You also need Node.js, but unfortunately the `node-js` package is not
27 available for Debian wheezy. You can either get it from
28 wheezy-backports or download the source from
29 http://nodejs.org/download/ and build it yourself. You need both Node
30 itself and its package manager NPM: `make install` puts them into
31 `/usr/local/bin`.
32
33
34 Concepts
35 ========
36
37 Code structure
38 --------------
39
40 The code of the widget set is in four main layers, described here from
41 the bottom up:
42
43 1. The core code, which manages the set of widget teams, default
44 options, authentication onto the Service Proxy, and the creation of
45 widgets from HTML elements.
46 This code is in `mkws-core.js`
47
48 2. The team code, which manages teams of widgets. This is responsible
49 for the collections of widgets that make up teams, event queues, and
50 handling search-and-retrieval events
51 This code is in `mkws-team.js`
52
53 3. The generic widget code, which handles the creation of widget
54 objects, parsing configuration attributes from their HTML elements,
55 and firing off automatic searches.
56
57 4. The code for individual widgets, which is specific to those
58 widgets. It often involves subscribing to events and responding to
59 them by setting the HTML of the widget element, but need not do
60 so. The code for many of the most important widgets is in
61 `mkws-widget-main.js`, but certain other widgets are defined in other
62 files beginning with the prefix `mkws-widget-`.
63
64 In addition to this code, there are several source files containing
65 support code:
66
67 * `mkws-filter.js` contains support routine implementing the
68 filter-set data structure, which contains information about which
69 filters (e.g. by target, or by facet) are in force.
70
71 * `mkws-handlebars.js` contains Handlebars helpers which can be used
72 by the HTML templates.
73
74 * `mkws-popup.js` defines a special widget for creating popup
75   windows. These may, but need not, contain other MKWS widgets,
76   forming a popup searching application.
77
78 The final component of the source code is the set of Handlebars
79 templates, in the `templates` directory, which are used to emit the
80 HTML of the various widgets' contents. These are compiled into the
81 file `mkws-templates.js`.
82
83
84
85 Event passing
86 -------------
87
88 The primary method of communication between components of the widget
89 set -- specifically, between teams and their widgets -- is event
90 passing. Widgets subscribe to named events; when something relevant
91 happens (such as the reception of a message from metasearch
92 middleware), the event is published, along with the relevant data. All
93 widgets that susbcribed to the event are then notified, and can take
94 appropriate action.
95
96 Different kinds of events have different data associated with
97 them. This data is passed when the event is published, and so is made
98 available to the subscribing code.
99
100 The possible events, and their associated data, are described
101 [below](#events).
102
103
104 Defining new types of widget
105 ----------------------------
106
107 Development with MKWS consists primarily of defining new types of
108 widgets. This is done using exactly the same API as the the widgets
109 that come as part of the set: they have no privileged access.
110
111 You create a new widget type by calling the `mkws.registerWidgetType`
112 function, passing in the widget name and a function. The name is used
113 to recognise HTML elements as being widgets of this type -- for
114 example, if you register a `foo` widget, elements like
115 `<div class="mkws-foo">` will become widgets of this type.
116
117 The function promotes a bare widget object (which is created by the
118 core widget code and passed in as `this`) into a
119 widget of the appropriate type. MKWS doesn't use classes or explicit
120 prototypes: it just makes objects that have the necessary
121 behaviours. There are _no_ behaviours that Widgets are obliged to
122 provide: you can make a doesn't-do-anything-at-all widget if you like:
123
124         mkws.registerWidgetType('sluggard', function() {});
125
126 More commonly, widgets will subscribe to one or more events, so that
127 they're notified when something interesting happens. For example, the
128 `log` widget asks to be notified when a `log` event happens, and
129 appends the logged message to its node, as follows:
130
131         mkws.registerWidgetType('log', function() {
132           var that = this;
133
134           this.team.queue("log").subscribe(function(teamName, timestamp, message) {
135             $(that.node).append(teamName + ": " + timestamp + message + "<br/>");
136           });
137         });
138
139 This simple widget illustrates several important points:
140
141 * The base widget object (`this`) has several baked-in properties and
142   methods that are available to individual widgets. These include
143   `this.team` (the team that this widget is a part of) and `this.node`
144   (the DOM element of the widget). See below for a full list.
145
146 * The team object (`this.team`) also has baked-in properties and
147   methods. These include the `queue` function, which takes an event-name
148   as its argument. See below for a full list.
149
150 * You can add functionality to a widget by subscribing it to an
151   event's queue using `this.team.queue("EVENT").subscribe`. The
152   argument is a function which is called whenever the event is
153   published.
154
155 * As with so much JavaScript programming, the value of the special
156   variable `this` is lost inside the `subscribe` callback function,
157   so it must be saved if it's to be used inside that callback
158   (typically as a local variable named `that`).
159
160
161 Widget specialisation (inheritance)
162 -----------------------------------
163
164 Many widgets are simple specialisations of existing widgets. For
165 example, the `images` widget is the same as the `records` widget
166 except that it defaults to using the `images` template for displaying
167 its result list. It's defined as follows:
168
169         mkws.registerWidgetType('images', function() {
170           mkws.promotionFunction('records').call(this);
171           if (!this.config.template) this.config.template = 'images';
172         });
173
174 Remember that when a promotion function is called, it's passed a base
175 widget object that's not specialised for any particular task. To make
176 a specialised widget, you first promote that base widget into the type
177 that you want to specialise from -- in this case, `Records` -- using
178 the promotion function that's been registered for that type.
179
180 Once this has been done, the specialisations can be introduced. In
181 this case, it's a very simple matter of changing the `template`
182 configuration setting to `'images'` unless it's already been given an
183 explicit value. (That would occur if the HTML used an element like
184 `<div class="mkws-images" template="my-images">` to use a customised
185 template.
186
187
188 Reference Guide
189 ===============
190
191
192 Widget properties and methods
193 -----------------------------
194
195 The following properties and methods exist in the bare widget object
196 that is passed into `registerWidgetType`'s callback function, and can
197 be used by the derived widget.
198
199 * `String this.type` --
200         A string containing the type of the widget (`search`,
201         `switch`, etc.)
202
203 * `Team this.team` --
204         The team object to which this widget belongs. The team has
205         several additional important properties and methods, described
206         below.
207
208 * `DOMElement this.node` --
209         The DOM element of the widget. Most often used for inserting
210         HTML into the widget element.
211
212 * `Hash this.config` --
213         A table of configuration values for the widget. This table
214         inherits missing values from the team's configuration, which
215         in turn inherits from the top-level MKWS configuration, which
216         inherits from the default configuration. Instances of widgets
217         in HTML can set configuration items as HTML attributes: for
218         example, the HTML element
219         `<div class="mkwsRecords" maxrecs="10">`
220         creates a widget for which `this.config.maxrecs` is set to 10.
221
222 * `String this.toString()` --
223         A function returning a string that briefly names this
224         widget. Can be useful in logging.
225
226 * `Void this.log(string)` --
227         A function to log a string for debugging purposes. The string
228         is written on the browser console, and also published to any
229         subcribers to the `log` event.
230
231 * `String this.value()` --
232         A function returning the value of the widget's HTML element.
233
234 * `VOID autosearch()` --
235         Registers that this kind of widget is one that requires an
236         automatic search to be run for it if an `autosearch` attribute
237         is provided on the HTML element. This is appropriate for
238         widgets such as `Records` and `Facet` that display some part
239         of a search result.
240
241 * `subwidget(type, overrides, defaults)` --
242         Returns the HTML of a subwidget of the specified type, which
243         can then be inserted into the widget using the
244         `this.node.html` function. The subwidget is given the same
245         attributes at the parent widget that invokes this function,
246         except where overrides are passed in. If defaults are also
247         provided, then these are used when the parent widget provides
248         no values. Both the `overrides` and `defaults` arguments are
249         hashes: the latter is optional. This can be used to assemble
250         compound widgets containing several subwidgets.
251
252 In addition to these properties and methods of the bare widget object,
253 some kinds of specific widget add other properties of their own. For
254 example, the `builder` widget uses a `callback` property as the
255 function that it use to publish the widget definition that it
256 constructs. This defaults to the builtin function `alert`, but can be
257 overridden by derived widgets such as `console-builder`.
258
259
260 Team methods
261 ------------
262
263 Since the team object is supposed to be opaque to widgets, all access
264 is via the following API methods rather than direct access to
265 properties.
266
267 * `String team.name()`
268 * `Bool team.submitted()`
269 * `Num team.perpage()`
270 * `Num team.totalRecordCount()`
271 * `Num team.currentPage();`
272 * `String team.currentRecordId()`
273 * `String team.currentRecordData()`
274
275 These are all simple accessor functions that provide the ability to
276 read properties of the team. `submitted` is initially false, then
277 becomes true when the first search is submitted (manually or
278 automatically).
279
280 * `Array team.filters()` --
281         Another accessor function, providing access to the array of
282         prevailing filters (which narrow the search results by means
283         of Pazpar2 filters and limits). This is really too complicated
284         an object for the widgets to be given access to, but it's
285         convenient to do it this way. If you have a reason for using
286         this, see the `Navi` widget, which is the only place it's used.
287
288 * `Bool team.targetFiltered(targetId)` --
289         Indicates whether the specified target has been filtered by
290         selection as a facet. This is used only by the `Facet` widget,
291         and there is probably no reason for you to use it.
292
293 * `Hash team.config()` --
294         Access to the team's configuration settings. There is
295         rarely a need to use this: the settings that haven't
296         been overridden are accessible via `this.config`.
297
298 * `Void team.set_sortOrder(string)`, `Void team.set_perpage(number)` --
299         "Setter" functions for the team's `sortOrder` and `perpage`
300         functions. Unlikely to be needed outside of the `Sort` and
301         `Perpage` widgets.
302
303 * `Queue team.queue(eventName)` --
304         Returns the queue associated with the named event: this can be
305         used to subscribe to the event (or more rarely to publish
306         it). See [the section on events, below](#events).
307
308 * `Void team.newSearch(query, sortOrder, maxrecs, perpage, limit, targets, targetfilter)` --
309         Starts a new search with the specified parameters. All but the
310         query may be omitted, in which case the prevailing defaults
311         are used. The meanings of the parameters are those of the
312         same-named [configuration
313         settings](mkws-manual.html#configuration-settings) described in
314         the user's manual.
315
316 * `Void team.reShow()` --
317         Using the existing search, re-shows the result records after a
318         change in sort-order, per-page count, etc.
319
320 * `String team.recordElementId(recordId)` --
321         Utility function for converting a record identifer (returned
322         from Pazpar2) into a version suitable for use as an HTML
323         element ID.
324
325 * `String team.renderDetails(recordData)` --
326         Utility function returns an HTML rendering of the record
327         represented by the specified data.
328
329 * `Template team.loadTemplate(templateName)` --
330         Loads (or retrieves from cache) the named Handlebars template,
331         and returns it in a form that can be invoked as a function,
332         passed a data-set.
333
334 Some of these methods are arguably too low-level and should not be
335 exposed; others should probably be widget-level methods. The present
336 infelicities should be fixed in future releases, but backwards
337 compatibility with the present API will be maintained for at least one
338 complete major-release cycle.
339
340
341 Events
342 ------
343
344 The following events are generated by the widget-set code:
345
346 * `authenticated` (authName, realm) --
347         When authentication is completed successfully, this event is
348         published to _all_ teams. Two parameters are passed: the
349         human-readable name of the library that has been authenticated
350         onto, and the correponding machine-readable library ID.
351
352 * `ready` --
353         Published to _all_ teams when they are ready to search. No
354         parameters are passed. This event is used to implement
355         automatic searching, and should probably not be used by
356         application code.
357
358 * `stat` (data) --
359         Published to a team when a `stat` response is reveived from
360         Pazpar2. The data from the response is passed as a parameter.
361
362 * `firstrecords` (hitcount) --
363         Published to a team when the first set of records is found by
364         a search. The number of records found (so far) is passed as
365         the parameter.
366
367 * `complete` (hitcount) --
368         Published to a team when a search is complete, and no more
369         records will be found (i.e. all targets have either responded
370         or failed with an error). The final number of records found is
371         passed as the parameter.
372
373 * `targets` (data) --
374         Published to a team when a `bytarget` response is reveived from
375         Pazpar2. The data from the response is passed as a parameter.
376
377 * `facets` (data) --
378         Published to a team when a `term` response is reveived from
379         Pazpar2. The data from the response is passed as a parameter.
380
381 * `pager` (data) --
382         Published to a team when a `show` response is reveived from
383         Pazpar2. The data from the response is passed as a
384         parameter. This event is used to update the pager, showing how
385         many records have been found, which page is being displayed,
386         etc.
387
388 * `records` (data) --
389         Also published to a team when a `show` response is reveived
390         from Pazpar2. The data from the response is passed as a
391         parameter. This event is used to update the displayed records.
392
393 * `record` (data) --
394         Published to a team when a `record` response is reveived from
395         Pazpar2 (i.e. the full data for a single record). The data
396         from the response is passed as a parameter.
397
398 * `navi` --
399         Published to a team when a new search is about to be
400         submitted. This is a signal that the navigation area, showing
401         which filters are in effect, should be updated. No parameter
402         is passed: the event handler should consult `team.filters` to
403         see what the prevailing set is.
404
405 * `log` (teamName, timestamp, message) --
406         Published to a team when a message is about to be logged to
407         the console for debugging. Three arguments are passed: the
408         name of the team that generated the log message, a timestamp
409         string, and the message itself. Note that this event is _not_
410         published when the widget-set core code generates a log
411         message -- only when a team or a widget does.
412
413 - - -
414
415 Copyright (C) 2013-2014 Index Data ApS. <http://indexdata.com>