1 if (!dojo._hasResource["openils.widget.FlattenerGrid"]) {
2 dojo.provide("openils.widget.FlattenerGrid");
4 dojo.require("DojoSRF");
5 dojo.require("dojox.grid.DataGrid");
6 dojo.require("openils.FlattenerStore");
7 dojo.require("openils.PermaCrud");
8 dojo.require("openils.widget.GridColumnPicker");
9 dojo.require("openils.widget.EditDialog"); /* includes EditPane */
10 dojo.require("openils.widget._GridHelperColumns");
13 "openils.widget.FlattenerGrid",
14 [dojox.grid.DataGrid, openils.widget._GridHelperColumns], {
15 /* These potential constructor arguments are useful to
16 * FlattenerGrid in their own right */
17 "columnReordering": true,
18 "columnPersistKey": null,
19 "autoCoreFields": false,
20 "autoFieldFields": null,
21 "showLoadFilter": false, /* use FlattenerFilter(Dialog|Pane) */
22 "filterAlwaysInDiv": null, /* use FlattenerFilterPane and put its
23 content in this HTML element */
25 "filterInitializers": null,
26 "filterWidgetBuilders": null,
27 "filterSemaphore": null,
28 "filterSemaphoreCallback": null,
30 /* These potential constructor arguments may be useful to
31 * FlattenerGrid in their own right, and are passed to
36 "sortFieldReMap": null,
37 "defaultSort": null, /* whatever any part of the UI says will
39 "baseSort": null, /* will contains what the columnpicker
40 dictates, and precedes whatever the column
43 /* These potential constructor arguments are for functionality
44 * copied from AutoGrid */
45 "editOnEnter": false, /* also implies edit-on-dblclick */
46 "editStyle": "dialog", /* "dialog" or "pane" */
47 "requiredFields": null, /* affects create/edit dialogs */
48 "suppressEditFields": null, /* affects create/edit dialogs */
50 /* _generateMap() lives to interpret the attributes of the
51 * FlattenerGrid dijit itself plus those definined in
55 * <th field="foo" ...>
56 * to build the map to hand to the FlattenerStore, which in turn
57 * uses it to query the flattener service.
59 "_generateMap": function() {
60 var map = this.mapClause = {};
61 var fields = this.structure[0].cells[0];
63 /* These are the fields defined in thead -> tr -> [th,th,...].
64 * For purposes of building the map, where each field has
65 * three boolean attributes "display", "sort" and "filter",
66 * assume "display" is always true for these.
67 * That doesn't mean that at the UI level we can't hide a
70 * If you need extra fields in the map for which display
71 * should *not* be true, use mapExtras.
74 fields, function(field) {
75 if (field.field.match(/^\+/))
76 return; /* special fields e.g. checkbox/line # */
80 "filter": (field.ffilter || false),
82 "path": field.fpath || field.field
84 /* The following attribute is not for the flattener
85 * service's benefit, but for other uses. We capture
86 * the hardcoded <th> value (the header label) if any.*/
88 map[field.field]._label = field.name;
93 /* It's not particularly useful to add simple fields, i.e.
94 * circ_lib: "circ_lib.name"
95 * to mapExtras, because by convention used elsewhere in
96 * Flattener, that gives all attributes, including
97 * display, a true value. Still, be consistent to avoid
100 for (var key in this.mapExtras) {
101 if (typeof this.mapExtras[key] != "object") {
102 this.mapExtras[key] = {
103 "path": this.mapExtras[key],
110 dojo.mixin(map, this.mapExtras);
113 /* Do this now, since we don't want a silently added
114 * identifier attribute in the terminii list (see its uses). */
115 this._calculateMapTerminii();
116 this._supplementHeaderNames();
118 /* make sure we always have a field for fm identifier */
119 if (!map[this.fmIdentifier]) {
120 map[this.fmIdentifier] = {
121 "path": this.fmIdentifier,
122 "display": true, /* Flattener displays it to us,
123 but we don't display to user. */
132 "_cleanMapForStore": function(map) {
133 var clean = dojo.clone(map);
135 for (var column in clean) {
136 openils.Util.objectProperties(clean[column]).filter(
137 function(k) { return k.match(/^_/); }
139 function(k) { delete clean[column][k]; }
146 /* Given the hint of a class to start at, follow path to the end
147 * and return information on the last field. */
148 "_followPathToEnd": function(hint, path, allow_selector_backoff) {
149 function _fm_is_selector_for_class(h, field) {
150 var cl = fieldmapper.IDL.fmclasses[h];
151 return (cl.field_map[cl.pkey].selector == field);
154 var last_field, last_hint;
155 var orig_path = dojo.clone(path);
156 var field, field_def;
158 while (field = path.shift()) {
159 /* XXX this assumes we have the whole IDL loaded. I
160 * guess we could teach this to work by loading classes
161 * on demand when we don't have the whole IDL loaded. */
163 fieldmapper.IDL.fmclasses[hint].field_map[field];
166 /* This can be ok in some cases. Columns following
167 * IDL paths involving links with a nonempty "map"
168 * attribute can be used for display only (no
169 * sort, no filter). */
171 "Lost our way in IDL at hint " + hint +
172 ", field " + field + "; may be ok"
177 if (field_def["class"]) {
181 hint = field_def["class"];
182 } else if (path.length) {
183 /* There are more fields left but we can't follow
184 * the chain via IDL any further. */
186 "_calculateMapTerminii can't parse path " +
187 orig_path + " (at " + field + ")"
192 var datatype = field_def.datatype;
193 var indirect = false;
194 /* If allowed, back off the last field in the path if it's a
195 * selector for its class, because the preceding field will be
196 * a better thing to hand to AutoFieldWidget.
198 if (orig_path.length > 1 && allow_selector_backoff &&
199 _fm_is_selector_for_class(hint, field_def.name)) {
205 field = field_def.name;
211 "label": field_def.label,
212 "datatype": datatype,
217 /* The FlattenerStore doesn't need this, but it has at least two
218 * uses: 1) FlattenerFilterDialog, 2) setting column header labels
221 * To call these 'Terminii' can be misleading. In certain
222 * (actually probably common) cases, they won't really be the last
223 * field in a path, but the next-to-last. Read on. */
224 "_calculateMapTerminii": function() {
225 this.mapTerminii = [];
226 for (var column in this.mapClause) {
227 var end = this._followPathToEnd(
229 this.mapClause[column].path.split(/\./),
230 true /* allow selector backoff */
234 var terminus = dojo.mixin(
236 "simple_name": column,
237 "isfilter": this.mapClause[column].filter
240 if (this.mapClause[column]._label)
241 terminus.label = this.mapClause[column]._label;
243 this.mapTerminii.push(terminus);
247 "_supplementHeaderNames": function() {
248 /* If we didn't give a particular header cell
249 * (<th>) a display name (the innerHTML of that <th>), then
250 * use the IDL to provide the label of the terminus of the
251 * flattener path for that column. It may be better than using
252 * the raw field name. */
254 this.structure[0].cells[0].forEach(
257 header.name = self.mapTerminii.filter(
259 return t.simple_name == header.field;
267 "_columnOrderingAndLabels": function() {
271 this.views.views[0].structure.cells[0].forEach(
273 if (!c.field.match(/^\+/)) {
275 columns.push(c.field);
280 return {"labels": labels, "columns": columns};
283 "_getAutoFieldFields": function(fmclass) {
285 fieldmapper.IDL.fmclasses[fmclass].fields)
288 return !field.virtual && field.datatype != "link";
291 function(a, b) { return a.label > b.label ? 1 : -1; }
295 /* Take our core class (this.fmClass) and add table columns for
296 * any field we don't already have covered by actual hard-coded
298 "_addAutoCoreFields": function() {
299 var cell_list = this.structure[0].cells[0];
300 var fields = dojo.clone(
301 fieldmapper.IDL.fmclasses[this.fmClass].fields
303 function(a, b) { return a.label > b.label ? 1 : -1; }
307 fields, function(f) {
308 if (f.datatype == "link" || f.virtual)
311 if (cell_list.filter(
313 if (!c.fpath) return false;
314 return c.fpath.split(/\./)[0] == f.name;
329 "_addAutoFieldFields": function(paths) {
334 paths, function(path) {
335 /* The beginning is the end. */
336 var beginning = self._followPathToEnd(
337 self.fmClass, path.split(/\./), false
343 self._getAutoFieldFields(beginning.fmClass),
346 path + "." + field.name;
348 new RegExp("^" + would_be_path);
349 if (!self.structure[0].cells[0].filter(
352 c.fpath.match(wbp_re);
355 self.structure[0].cells[0].push({
356 "field": "AUTO_" + beginning.name +
358 "name": beginning.label + " - " +
361 "fpath": would_be_path,
372 "_addAutoFields": function() {
373 if (this.autoCoreFields)
374 this._addAutoCoreFields();
376 if (dojo.isArray(this.autoFieldFields))
377 this._addAutoFieldFields(this.autoFieldFields);
379 this.setStructure(this.structure);
382 "constructor": function(args) {
383 dojo.mixin(this, args);
385 this.fmIdentifier = this.fmIdentifier ||
386 fieldmapper.IDL.fmclasses[this.fmClass].pkey;
388 this.overrideEditWidgets = {};
389 this.overrideEditWidgetClass = {};
390 this.overrideWidgetArgs = {};
393 "startup": function() {
394 /* Save original query for further filtering later */
395 this._baseQuery = dojo.clone(this.query);
397 this._addAutoFields();
399 this._startupGridHelperColumns();
403 if (!this.columnPicker) {
405 new openils.widget.GridColumnPicker(
406 null, this.columnPersistKey, this);
407 this.columnPicker.onLoad = dojo.hitch(
408 this, function(opts) { this._finishStartup(opts.sortFields) });
410 this.columnPicker.onSortChange = dojo.hitch(this,
411 /* directly after, this.update() is called by the
412 column picker, causing a re-fetch */
414 this.store.baseSort = this._mapCPSortFields(fields)
418 this.columnPicker.load();
421 this.inherited(arguments);
424 "canSort": function(idx, skip_structure /* API abuse */) {
425 var initial = this.inherited(arguments);
427 /* idx is one-based instead of zero-based for a reason. */
428 var view_idx = Math.abs(idx) - 1;
431 this.views.views[0].structure.cells[0][view_idx].fsort
435 /* Maps ColumnPicker sort fields to the correct format.
436 If no sort fields specified, falls back to defaultSort */
437 "_mapCPSortFields": function(sortFields) {
438 var sort = this.defaultSort;
439 if (sortFields.length) {
440 sort = sortFields.map(function(f) {
442 a[f.field] = f.direction;
449 "_finishStartup": function(sortFields) {
451 this._setStore( /* Seriously, let's leave this as _setStore. */
452 new openils.FlattenerStore({
453 "fmClass": this.fmClass,
454 "fmIdentifier": this.fmIdentifier,
455 "mapClause": this._cleanMapForStore(this.mapClause),
456 "baseSort": this.baseSort,
457 "defaultSort": this._mapCPSortFields(sortFields),
458 "sortFieldReMap": this.sortFieldReMap
463 // pick up any column label changes
464 this.columnPicker.reloadStructure();
469 this._showing_create_pane = false;
471 if (this.editOnEnter)
472 this._applyEditOnEnter();
473 else if (this.singleEditStyle)
474 this._applySingleEditStyle();
476 /* Like AutoGrid's paginator, but we'll never have Back/Next
477 * links. Just a place to hold misc links */
482 "_setupLinks": function() {
483 this.linkHolder = new dijit.layout.ContentPane();
484 dojo.place(this.linkHolder.domNode, this.domNode, "before");
486 if (this.showLoadFilter) {
487 var which_filter_ui = this.filterAlwaysInDiv ?
488 "FlattenerFilterPane" : "FlattenerFilterDialog";
490 dojo.require("openils.widget." + which_filter_ui);
492 new openils.widget[which_filter_ui]({
493 "fmClass": this.fmClass,
494 "mapTerminii": this.mapTerminii,
495 "useDiv": this.filterAlwaysInDiv,
497 "initializers": this.filterInitializers,
498 "widgetBuilders": this.filterWidgetBuilders
501 this.filterUi.onApply = dojo.hitch(
502 this, function(filter) {
504 dojo.mixin(filter, this._baseQuery),
510 this.filterUi.startup();
512 if (this.filterSemaphore && this.filterSemaphore()) {
513 if (this.filterSemaphoreCallback)
514 this.filterSemaphoreCallback();
516 if (!this.filterAlwaysInDiv) {
519 "innerHTML": "Filter", /* XXX i18n */
520 "href": "javascript:void(0);",
521 "onclick": dojo.hitch(this, function() {
522 this.filterUi.show();
524 }, this.linkHolder.domNode
530 "refresh": function() {
531 this.fetchLock = false;
532 this._refresh(/* isRender */ true);
535 "_fetch": function() {
539 return this.inherited(arguments);
542 /* ******** below are methods mostly copied but
543 * slightly changed from AutoGrid ******** */
545 "_applySingleEditStyle": function() {
546 this.onMouseOverRow = function(e) {};
547 this.onMouseOutRow = function(e) {};
548 this.onCellFocus = function(cell, rowIndex) {
549 this.selection.deselectAll();
550 this.selection.select(this.focus.rowIndex);
554 /* capture keydown and launch edit dialog on enter */
555 "_applyEditOnEnter": function() {
556 this._applySingleEditStyle();
559 this, "onRowDblClick", function(e) {
560 if (this.editStyle == "pane")
562 this.selection.getFirstSelected(),
566 this._drawEditDialog(
567 this.selection.getFirstSelected(),
574 this, "onKeyDown", function(e) {
575 if (e.keyCode == dojo.keys.ENTER) {
576 this.selection.deselectAll();
577 this.selection.select(this.focus.rowIndex);
578 if (this.editStyle == "pane")
580 this.selection.getFirstSelected(),
584 this._drawEditDialog(
585 this.selection.getFirstSelected(),
593 "_makeEditPane": function(storeItem, rowIndex, onPostSubmit, onCancel) {
595 var fmObject = (new openils.PermaCrud()).retrieve(
597 this.store.getIdentity(storeItem)
600 var pane = new openils.widget.EditPane({
601 "fmObject": fmObject,
602 "hideSaveButton": this.editReadOnly,
603 "readOnly": this.editReadOnly,
604 "overrideWidgets": this.overrideEditWidgets,
605 "overrideWidgetClass": this.overrideEditWidgetClass,
606 "overrideWidgetArgs": this.overrideWidgetArgs,
607 "disableWidgetTest": this.disableWidgetTest,
608 "requiredFields": this.requiredFields,
609 "suppressFields": this.suppressEditFields,
610 "onPostSubmit": function() {
611 /* ask the store to call flattener specially to get
612 * the flat row related to only this fmobj */
613 grid.store.loadItem({"force": true, "item": storeItem});
615 if (grid.onPostUpdate)
616 grid.onPostUpdate(storeItem, rowIndex);
621 grid.views.views[0].getCellNode(
630 "onCancel": function() {
633 grid.views.views[0].getCellNode(
643 if (typeof this.editPaneOnSubmit == "function")
644 pane.onSubmit = this.editPaneOnSubmit;
646 pane.fieldOrder = this.fieldOrder;
647 pane.mode = "update";
651 "_makeCreatePane": function(onPostSubmit, onCancel) {
653 var pane = new openils.widget.EditPane({
654 "fmClass": this.fmClass,
655 "overrideWidgets": this.overrideEditWidgets,
656 "overrideWidgetClass": this.overrideEditWidgetClass,
657 "overrideWidgetArgs": this.overrideWidgetArgs,
658 "disableWidgetTest": this.disableWidgetTest,
659 "requiredFields": this.requiredFields,
660 "suppressFields": this.suppressEditFields,
661 "onPostSubmit": function(req, cudResults) {
662 var fmObject = cudResults[0];
663 if (grid.onPostCreate)
664 grid.onPostCreate(fmObject);
666 grid.store.fetchItemByIdentity({
667 "identity": fmObject[grid.fmIdentifier](),
668 "onItem": function(item) {
669 grid.store.onNew(item);
677 grid.selection.select(grid.rowCount - 1);
678 grid.views.views[0].getCellNode(
686 onPostSubmit(fmObject);
688 "onCancel": function() { if (onCancel) onCancel(); }
691 if (typeof this.createPaneOnSubmit == "function")
692 pane.onSubmit = this.createPaneOnSubmit;
693 pane.fieldOrder = this.fieldOrder;
694 pane.mode = "create";
699 * Creates an EditPane with a copy of the data from the provided store
700 * item for cloning said item
701 * @param {Object} storeItem Dojo data item
702 * @param {Number} rowIndex The Grid row index of the item to be cloned
703 * @param {Function} onPostSubmit Optional callback for post-submit behavior
704 * @param {Function} onCancel Optional callback for clone cancelation
705 * @return {Object} The clone EditPane
707 "_makeClonePane": function(storeItem,rowIndex,onPostSubmit,onCancel) {
708 var clonePane = this._makeCreatePane(onPostSubmit, onCancel);
709 var origPane = this._makeEditPane(storeItem, rowIndex);
713 origPane.fieldList, function(field) {
714 if (field.widget.widget.attr('disabled'))
717 var w = clonePane.fieldList.filter(
718 function(i) { return (i.name == field.name) }
722 w.widget.baseWidgetValue(field.widget.widget.attr('value'));
725 w.widget.onload = function() {
726 w.widget.baseWidgetValue(
727 field.widget.widget.attr('value')
737 "_drawEditDialog": function(storeItem, rowIndex) {
738 var done = dojo.hitch(this, function() { this.hideDialog(); });
739 var pane = this._makeEditPane(storeItem, rowIndex, done, done);
740 this.editDialog = new openils.widget.EditDialog({editPane:pane});
741 this.editDialog.startup();
742 this.editDialog.show();
746 * Generates an EditDialog for object creation and displays it to the user
748 "showCreateDialog": function() {
749 var done = dojo.hitch(this, function() { this.hideDialog(); });
750 var pane = this._makeCreatePane(done, done);
751 this.editDialog = new openils.widget.EditDialog({editPane:pane});
752 this.editDialog.startup();
753 this.editDialog.show();
756 "_drawEditPane": function(storeItem, rowIndex) {
757 var done = dojo.hitch(this, function() { this.hidePane(); });
759 dojo.style(this.domNode, "display", "none");
761 this.editPane = this._makeEditPane(storeItem, rowIndex, done, done);
762 this.editPane.startup();
763 dojo.place(this.editPane.domNode, this.domNode, "before");
766 this.onEditPane(this.editPane);
769 "showClonePane": function(onPostSubmit) {
770 var done = dojo.hitch(this, function() { this.hidePane(); });
771 var row = this.getFirstSelectedRow();
777 postSubmit = dojo.hitch(
778 this, function(result) {
779 onPostSubmit(this.getItem(row), result);
787 dojo.style(this.domNode, "display", "none");
788 this.editPane = this._makeClonePane(
789 this.getItem(row), row, postSubmit, done
791 dojo.place(this.editPane.domNode, this.domNode, "before");
793 this.onEditPane(this.editPane);
796 "showCreatePane": function() {
797 if (this._showing_create_pane)
799 this._showing_create_pane = true;
801 var done = dojo.hitch(
803 this._showing_create_pane = false;
808 dojo.style(this.domNode, "display", "none");
810 this.editPane = this._makeCreatePane(done, done);
811 this.editPane.startup();
813 dojo.place(this.editPane.domNode, this.domNode, "before");
816 this.onEditPane(this.editPane);
819 "hideDialog": function() {
820 this.editDialog.hide();
821 this.editDialog.destroy();
822 delete this.editDialog;
826 "hidePane": function() {
827 this.domNode.parentNode.removeChild(this.editPane.domNode);
828 this.editPane.destroy();
829 delete this.editPane;
830 dojo.style(this.domNode, "display", "block");
834 "deleteSelected": function() {
837 this.getSelectedItems().forEach(
839 var fmobj = new fieldmapper[self.fmClass]();
840 fmobj[self.fmIdentifier](
841 self.store.getIdentity(item)
843 (new openils.PermaCrud()).eliminate(
845 "oncomplete": function() {
846 self.store.deleteItem(item);
854 "getSelectedIDs": function() {
855 return this.getSelectedItems().map(
858 function(item) { return this.store.getIdentity(item); }
863 /* Print the same data that the Flattener is feeding to the
864 * grid, sorted the same way too. Remove limit and offset (i.e.,
865 * print it all) unless those are passed in to the print() method.
867 "print": function(limit, offset, query_mixin) {
868 var coal = this._columnOrderingAndLabels();
870 "query": dojo.mixin({}, this.query, query_mixin),
872 "columns": coal.columns,
873 "labels": coal.labels
875 "onComplete": function(text) {
876 openils.Util.printHtmlString(text);
882 req.start = offset || 0;
884 req.queryOptions.all = true;
887 this.store.fetchToPrint(req);
890 "printSelected": function() {
892 id_blob[this.store.getIdentityAttributes()[0]] =
893 this.getSelectedIDs();
895 this.print(null, null, id_blob);
900 /* monkey patch so we can get more attributes from each column in the
901 * markup that specifies grid columns (table->thead->tr->[td,...])
904 var b = dojox.grid.cells._Base;
905 var orig_mf = b.markupFactory;
907 b.markupFactory = function(node, cellDef) {
908 orig_mf(node, cellDef);
911 ["fpath", "ffilter"], function(a) {
912 var value = dojo.attr(node, a);
918 /* fsort and _visible are different. Assume true unless defined. */
920 ["fsort", "_visible"], function(a) {
921 var val = dojo.attr(node, a);
922 cellDef[a] = (typeof val == "undefined" || val === null) ?
923 true : dojo.fromJson(val);
929 /* the secret to successfully subclassing dojox.grid.DataGrid */
930 openils.widget.FlattenerGrid.markupFactory =
931 dojox.grid.DataGrid.markupFactory;