Merge pull request #5559 from colemanw/CRM-16209
[civicrm-core.git] / js / angular-crm-ui.js
1 /// crmUi: Sundry UI helpers
2 (function (angular, $, _) {
3
4 var uidCount = 0;
5
6 angular.module('crmUi', [])
7
8 // example <div crm-ui-accordion crm-title="ts('My Title')" crm-collapsed="true">...content...</div>
9 // WISHLIST: crmCollapsed should support two-way/continous binding
10 .directive('crmUiAccordion', function() {
11 return {
12 scope: {
13 crmUiAccordion: '='
14 },
15 template: '<div ng-class="cssClasses"><div class="crm-accordion-header">{{crmUiAccordion.title}} <a crm-ui-help="help" ng-if="help"></a></div><div class="crm-accordion-body" ng-transclude></div></div>',
16 transclude: true,
17 link: function (scope, element, attrs) {
18 scope.cssClasses = {
19 'crm-accordion-wrapper': true,
20 collapsed: scope.crmUiAccordion.collapsed
21 };
22 scope.help = null;
23 scope.$watch('crmUiAccordion', function(crmUiAccordion) {
24 if (crmUiAccordion && crmUiAccordion.help) {
25 scope.help = crmUiAccordion.help.clone({}, {
26 title: crmUiAccordion.title
27 });
28 }
29 });
30 }
31 };
32 })
33
34 // Examples:
35 // crmUiAlert({text: 'My text', title: 'My title', type: 'error'});
36 // crmUiAlert({template: '<a ng-click="ok()">Hello</a>', scope: $scope.$new()});
37 // var h = crmUiAlert({templateUrl: '~/crmFoo/alert.html', scope: $scope.$new()});
38 // ... h.close(); ...
39 .service('crmUiAlert', function($compile, $rootScope, $templateRequest, $q) {
40 var count = 0;
41 return function crmUiAlert(params) {
42 var id = 'crmUiAlert_' + (++count);
43 var tpl = null;
44 if (params.templateUrl) {
45 tpl = $templateRequest(params.templateUrl);
46 }
47 else if (params.template) {
48 tpl = params.template;
49 }
50 if (tpl) {
51 params.text = '<div id="' + id + '"></div>'; // temporary stub
52 }
53 var result = CRM.alert(params.text, params.title, params.type, params.options);
54 if (tpl) {
55 $q.when(tpl, function(html) {
56 var scope = params.scope || $rootScope.$new();
57 var linker = $compile(html);
58 $('#' + id).append($(linker(scope)));
59 });
60 }
61 return result;
62 };
63 })
64
65 // Simple wrapper around $.crmDatepicker.
66 // example with no time input: <input crm-ui-datepicker="{time: false}" ng-model="myobj.datefield"/>
67 // example with custom date format: <input crm-ui-datepicker="{dateFormat: 'm/d/y'}" ng-model="myobj.datefield"/>
68 .directive('crmUiDatepicker', function () {
69 return {
70 restrict: 'AE',
71 require: 'ngModel',
72 scope: {
73 crmUiDatepicker: '='
74 },
75 link: function (scope, element, attrs, ngModel) {
76 ngModel.$render = function () {
77 element.val(ngModel.$viewValue).change();
78 };
79
80 element
81 .crmDatepicker(scope.crmUiDatepicker)
82 .on('change', function() {
83 var requiredLength = 19;
84 if (scope.crmUiDatepicker && scope.crmUiDatepicker.time === false) {
85 requiredLength = 10;
86 }
87 if (scope.crmUiDatepicker && scope.crmUiDatepicker.date === false) {
88 requiredLength = 8;
89 }
90 ngModel.$setValidity('incompleteDateTime', !($(this).val().length && $(this).val().length !== requiredLength));
91 });
92 }
93 };
94 })
95
96 // Display debug information (if available)
97 // For richer DX, checkout Batarang/ng-inspector (Chrome/Safari), or AngScope/ng-inspect (Firefox).
98 // example: <div crm-ui-debug="myobject" />
99 .directive('crmUiDebug', function ($location) {
100 return {
101 restrict: 'AE',
102 scope: {
103 crmUiDebug: '@'
104 },
105 template: function() {
106 var args = $location.search();
107 return (args && args.angularDebug) ? '<div crm-ui-accordion crm-title=\'ts("Debug (%1)", {1: crmUiDebug})\' crm-collapsed="true"><pre>{{data|json}}</pre></div>' : '';
108 },
109 link: function(scope, element, attrs) {
110 var args = $location.search();
111 if (args && args.angularDebug) {
112 scope.ts = CRM.ts(null);
113 scope.$parent.$watch(attrs.crmUiDebug, function(data) {
114 scope.data = data;
115 });
116 }
117 }
118 };
119 })
120
121 // Display a field/row in a field list
122 // example: <div crm-ui-field="{title: ts('My Field')}"> {{mydata}} </div>
123 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field')}"> <input crm-ui-id="subform.myfield" name="myfield" /> </div>
124 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field')}"> <input crm-ui-id="subform.myfield" name="myfield" required /> </div>
125 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field'), help: hs('help_field_name')}"> {{mydata}} </div>
126 .directive('crmUiField', function() {
127 // Note: When writing new templates, the "label" position is particular. See/patch "var label" below.
128 var templateUrls = {
129 default: '~/crmUi/field.html',
130 checkbox: '~/crmUi/field-cb.html'
131 };
132
133 return {
134 require: '^crmUiIdScope',
135 restrict: 'EA',
136 scope: {
137 // {title, name, help, helpFile}
138 crmUiField: '='
139 },
140 templateUrl: function(tElement, tAttrs){
141 var layout = tAttrs.crmLayout ? tAttrs.crmLayout : 'default';
142 return templateUrls[layout];
143 },
144 transclude: true,
145 link: function (scope, element, attrs, crmUiIdCtrl) {
146 $(element).addClass('crm-section');
147 scope.help = null;
148 scope.$watch('crmUiField', function(crmUiField) {
149 if (crmUiField && crmUiField.help) {
150 scope.help = crmUiField.help.clone({}, {
151 title: crmUiField.title
152 });
153 }
154 });
155 }
156 };
157 })
158
159 // example: <div ng-form="subform" crm-ui-id-scope><label crm-ui-for="subform.foo">Foo:</label><input crm-ui-id="subform.foo" name="foo"/></div>
160 .directive('crmUiId', function () {
161 return {
162 require: '^crmUiIdScope',
163 restrict: 'EA',
164 link: {
165 pre: function (scope, element, attrs, crmUiIdCtrl) {
166 var id = crmUiIdCtrl.get(attrs.crmUiId);
167 element.attr('id', id);
168 }
169 }
170 };
171 })
172
173 // for example, see crmUiHelp
174 .service('crmUiHelp', function(){
175 // example: var h = new FieldHelp({id: 'foo'}); h.open();
176 function FieldHelp(options) {
177 this.options = options;
178 }
179 angular.extend(FieldHelp.prototype, {
180 get: function(n) {
181 return this.options[n];
182 },
183 open: function open() {
184 CRM.help(this.options.title, {id: this.options.id, file: this.options.file});
185 },
186 clone: function clone(options, defaults) {
187 return new FieldHelp(angular.extend({}, defaults, this.options, options));
188 }
189 });
190
191 // example: var hs = crmUiHelp({file: 'CRM/Foo/Bar'});
192 return function(defaults){
193 // example: hs('myfield')
194 // example: hs({id: 'myfield', title: 'Foo Bar', file: 'Whiz/Bang'})
195 return function(options) {
196 if (_.isString(options)) {
197 options = {id: options};
198 }
199 return new FieldHelp(angular.extend({}, defaults, options));
200 };
201 };
202 })
203
204 // Display a help icon
205 // Example: Use a default *.hlp file
206 // scope.hs = crmUiHelp({file: 'Path/To/Help/File'});
207 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field'})">
208 // Example: Use an explicit *.hlp file
209 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field', file:'CRM/Foo/Bar'})">
210 .directive('crmUiHelp', function() {
211 return {
212 restrict: 'EA',
213 link: function(scope, element, attrs) {
214 setTimeout(function() {
215 var crmUiHelp = scope.$eval(attrs.crmUiHelp);
216 var title = crmUiHelp && crmUiHelp.get('title') ? ts('%1 Help', {1: crmUiHelp.get('title')}) : ts('Help');
217 element.attr('title', title);
218 }, 50);
219
220 element
221 .addClass('helpicon')
222 .attr('href', '#')
223 .on('click', function(e) {
224 e.preventDefault();
225 scope.$eval(attrs.crmUiHelp).open();
226 });
227 }
228 };
229 })
230
231 // example: <div ng-form="subform" crm-ui-id-scope><label crm-ui-for="subform.foo">Foo:</label><input crm-ui-id="subform.foo" name="foo"/></div>
232 .directive('crmUiFor', function ($parse, $timeout) {
233 return {
234 require: '^crmUiIdScope',
235 restrict: 'EA',
236 template: '<span ng-class="cssClasses"><span ng-transclude/><span crm-ui-visible="crmIsRequired" class="crm-marker" title="This field is required.">*</span></span>',
237 transclude: true,
238 link: function (scope, element, attrs, crmUiIdCtrl) {
239 scope.crmIsRequired = false;
240 scope.cssClasses = {};
241
242 if (!attrs.crmUiFor) return;
243
244 var id = crmUiIdCtrl.get(attrs.crmUiFor);
245 element.attr('for', id);
246 var ngModel = null;
247
248 var updateCss = function () {
249 scope.cssClasses['crm-error'] = !ngModel.$valid && !ngModel.$pristine;
250 };
251
252 // Note: if target element is dynamically generated (eg via ngInclude), then it may not be available
253 // immediately for initialization. Use retries/retryDelay to initialize such elements.
254 var init = function (retries, retryDelay) {
255 var input = $('#' + id);
256 if (input.length === 0) {
257 if (retries) {
258 $timeout(function(){
259 init(retries-1, retryDelay);
260 }, retryDelay);
261 }
262 return;
263 }
264
265 var tgtScope = scope;//.$parent;
266 if (attrs.crmDepth) {
267 for (var i = attrs.crmDepth; i > 0; i--) {
268 tgtScope = tgtScope.$parent;
269 }
270 }
271
272 if (input.attr('ng-required')) {
273 scope.crmIsRequired = scope.$parent.$eval(input.attr('ng-required'));
274 scope.$parent.$watch(input.attr('ng-required'), function (isRequired) {
275 scope.crmIsRequired = isRequired;
276 });
277 }
278 else {
279 scope.crmIsRequired = input.prop('required');
280 }
281
282 ngModel = $parse(attrs.crmUiFor)(tgtScope);
283 if (ngModel) {
284 ngModel.$viewChangeListeners.push(updateCss);
285 }
286 };
287
288 $timeout(function(){
289 init(3, 100);
290 });
291 }
292 };
293 })
294
295 // Define a scope in which a name like "subform.foo" maps to a unique ID.
296 // example: <div ng-form="subform" crm-ui-id-scope><label crm-ui-for="subform.foo">Foo:</label><input crm-ui-id="subform.foo" name="foo"/></div>
297 .directive('crmUiIdScope', function () {
298 return {
299 restrict: 'EA',
300 scope: {},
301 controllerAs: 'crmUiIdCtrl',
302 controller: function($scope) {
303 var ids = {};
304 this.get = function(name) {
305 if (!ids[name]) {
306 ids[name] = "crmUiId_" + (++uidCount);
307 }
308 return ids[name];
309 };
310 },
311 link: function (scope, element, attrs) {}
312 };
313 })
314
315 // Display an HTML blurb inside an IFRAME.
316 // example: <iframe crm-ui-iframe="getHtmlContent()"></iframe>
317 .directive('crmUiIframe', function ($parse) {
318 return {
319 scope: {
320 crmUiIframe: '@' // expression which evalutes to HTML content
321 },
322 link: function (scope, elm, attrs) {
323 var iframe = $(elm)[0];
324 iframe.setAttribute('width', '100%');
325 iframe.setAttribute('frameborder', '0');
326
327 var refresh = function () {
328 // var iframeHtml = '<html><head><base target="_blank"></head><body onload="parent.document.getElementById(\'' + iframe.id + '\').style.height=document.body.scrollHeight + \'px\'"><scr' + 'ipt type="text/javascript" src="https://gist.github.com/' + iframeId + '.js"></sc' + 'ript></body></html>';
329 var iframeHtml = scope.$parent.$eval(attrs.crmUiIframe);
330
331 var doc = iframe.document;
332 if (iframe.contentDocument) {
333 doc = iframe.contentDocument;
334 }
335 else if (iframe.contentWindow) {
336 doc = iframe.contentWindow.document;
337 }
338
339 doc.open();
340 doc.writeln(iframeHtml);
341 doc.close();
342 };
343
344 // If the iframe is in a dialog, respond to resize events
345 $(elm).parent().on('dialogresize dialogopen', function(e, ui) {
346 $(this).css({padding: '0', margin: '0', overflow: 'hidden'});
347 iframe.setAttribute('height', '' + $(this).innerHeight() + 'px');
348 });
349
350 scope.$parent.$watch(attrs.crmUiIframe, refresh);
351 }
352 };
353 })
354
355 // Example:
356 // <a ng-click="$broadcast('my-insert-target', 'some new text')>Insert</a>
357 // <textarea crm-ui-insert-rx='my-insert-target'></textarea>
358 // TODO Consider ways to separate the plain-text/rich-text implementations
359 .directive('crmUiInsertRx', function() {
360 return {
361 link: function(scope, element, attrs) {
362 scope.$on(attrs.crmUiInsertRx, function(e, tokenName) {
363 var id = element.attr('id');
364 if (CKEDITOR.instances[id]) {
365 CKEDITOR.instances[id].insertText(tokenName);
366 $(element).select2('close').select2('val', '');
367 CKEDITOR.instances[id].focus();
368 }
369 else {
370 var crmForEl = $('#' + id);
371 var origVal = crmForEl.val();
372 var origPos = crmForEl[0].selectionStart;
373 var newVal = origVal.substring(0, origPos) + tokenName + origVal.substring(origPos, origVal.length);
374 crmForEl.val(newVal);
375 var newPos = (origPos + tokenName.length);
376 crmForEl[0].selectionStart = newPos;
377 crmForEl[0].selectionEnd = newPos;
378
379 $(element).select2('close').select2('val', '');
380 crmForEl.triggerHandler('change');
381 crmForEl.focus();
382 }
383 });
384 }
385 };
386 })
387
388 // Define a rich text editor.
389 // example: <textarea crm-ui-id="myForm.body_html" crm-ui-richtext name="body_html" ng-model="mailing.body_html"></textarea>
390 .directive('crmUiRichtext', function ($timeout) {
391 return {
392 require: '?ngModel',
393 link: function (scope, elm, attr, ngModel) {
394 var ck = CKEDITOR.replace(elm[0]);
395
396 if (!ngModel) {
397 return;
398 }
399
400 if (attr.ngBlur) {
401 ck.on('blur', function(){
402 $timeout(function(){
403 scope.$eval(attr.ngBlur);
404 });
405 });
406 }
407
408 ck.on('pasteState', function () {
409 scope.$apply(function () {
410 ngModel.$setViewValue(ck.getData());
411 });
412 });
413
414 ck.on('insertText', function () {
415 $timeout(function () {
416 ngModel.$setViewValue(ck.getData());
417 });
418 });
419
420 ngModel.$render = function (value) {
421 ck.setData(ngModel.$viewValue);
422 };
423 }
424 };
425 })
426
427 // Display a lock icon (based on a boolean).
428 // example: <a crm-ui-lock binding="mymodel.boolfield"></a>
429 // example: <a crm-ui-lock
430 // binding="mymodel.boolfield"
431 // title-locked="ts('Boolfield is locked')"
432 // title-unlocked="ts('Boolfield is unlocked')"></a>
433 .directive('crmUiLock', function ($parse, $rootScope) {
434 var defaultVal = function (defaultValue) {
435 var f = function (scope) {
436 return defaultValue;
437 };
438 f.assign = function (scope, value) {
439 // ignore changes
440 };
441 return f;
442 };
443
444 // like $parse, but accepts a defaultValue in case expr is undefined
445 var parse = function (expr, defaultValue) {
446 return expr ? $parse(expr) : defaultVal(defaultValue);
447 };
448
449 return {
450 template: '',
451 link: function (scope, element, attrs) {
452 var binding = parse(attrs.binding, true);
453 var titleLocked = parse(attrs.titleLocked, ts('Locked'));
454 var titleUnlocked = parse(attrs.titleUnlocked, ts('Unlocked'));
455
456 $(element).addClass('ui-icon lock-button');
457 var refresh = function () {
458 var locked = binding(scope);
459 if (locked) {
460 $(element)
461 .removeClass('ui-icon-unlocked')
462 .addClass('ui-icon-locked')
463 .prop('title', titleLocked(scope))
464 ;
465 }
466 else {
467 $(element)
468 .removeClass('ui-icon-locked')
469 .addClass('ui-icon-unlocked')
470 .prop('title', titleUnlocked(scope))
471 ;
472 }
473 };
474
475 $(element).click(function () {
476 binding.assign(scope, !binding(scope));
477 //scope.$digest();
478 $rootScope.$digest();
479 });
480
481 scope.$watch(attrs.binding, refresh);
482 scope.$watch(attrs.titleLocked, refresh);
483 scope.$watch(attrs.titleUnlocked, refresh);
484
485 refresh();
486 }
487 };
488 })
489
490 // CrmUiOrderCtrl is a controller class which manages sort orderings.
491 // Ex:
492 // JS: $scope.myOrder = new CrmUiOrderCtrl(['+field1', '-field2]);
493 // $scope.myOrder.toggle('field1');
494 // $scope.myOrder.setDir('field2', '');
495 // HTML: <tr ng-repeat="... | order:myOrder.get()">...</tr>
496 .service('CrmUiOrderCtrl', function(){
497 //
498 function CrmUiOrderCtrl(defaults){
499 this.values = defaults;
500 }
501 angular.extend(CrmUiOrderCtrl.prototype, {
502 get: function get() {
503 return this.values;
504 },
505 getDir: function getDir(name) {
506 if (this.values.indexOf(name) >= 0 || this.values.indexOf('+' + name) >= 0) {
507 return '+';
508 }
509 if (this.values.indexOf('-' + name) >= 0) {
510 return '-';
511 }
512 return '';
513 },
514 // @return bool TRUE if something is removed
515 remove: function remove(name) {
516 var idx = this.values.indexOf(name);
517 if (idx >= 0) {
518 this.values.splice(idx, 1);
519 return true;
520 }
521 else {
522 return false;
523 }
524 },
525 setDir: function setDir(name, dir) {
526 return this.toggle(name, dir);
527 },
528 // Toggle sort order on a field.
529 // To set a specific order, pass optional parameter 'next' ('+', '-', or '').
530 toggle: function toggle(name, next) {
531 if (!next && next !== '') {
532 next = '+';
533 if (this.remove(name) || this.remove('+' + name)) {
534 next = '-';
535 }
536 if (this.remove('-' + name)) {
537 next = '';
538 }
539 }
540
541 if (next == '+') {
542 this.values.unshift('+' + name);
543 }
544 else if (next == '-') {
545 this.values.unshift('-' + name);
546 }
547 }
548 });
549 return CrmUiOrderCtrl;
550 })
551
552 // Define a controller which manages sort order. You may interact with the controller
553 // directly ("myOrder.toggle('fieldname')") order using the helper, crm-ui-order-by.
554 // example:
555 // <span crm-ui-order="{var: 'myOrder', defaults: {'-myField'}}"></span>
556 // <th><a crm-ui-order-by="[myOrder,'myField']">My Field</a></th>
557 // <tr ng-repeat="... | order:myOrder.get()">...</tr>
558 // <button ng-click="myOrder.toggle('myField')">
559 .directive('crmUiOrder', function(CrmUiOrderCtrl) {
560 return {
561 link: function(scope, element, attrs){
562 var options = angular.extend({var: 'crmUiOrderBy'}, scope.$eval(attrs.crmUiOrder));
563 scope[options.var] = new CrmUiOrderCtrl(options.defaults);
564 }
565 };
566 })
567
568 // For usage, see crmUiOrder (above)
569 .directive('crmUiOrderBy', function() {
570 return {
571 link: function(scope, element, attrs) {
572 function updateClass(crmUiOrderCtrl, name) {
573 var dir = crmUiOrderCtrl.getDir(name);
574 element
575 .toggleClass('sorting_asc', dir === '+')
576 .toggleClass('sorting_desc', dir === '-')
577 .toggleClass('sorting', dir === '');
578 }
579
580 element.on('click', function(e){
581 var tgt = scope.$eval(attrs.crmUiOrderBy);
582 tgt[0].toggle(tgt[1]);
583 updateClass(tgt[0], tgt[1]);
584 e.preventDefault();
585 scope.$digest();
586 });
587
588 var tgt = scope.$eval(attrs.crmUiOrderBy);
589 updateClass(tgt[0], tgt[1]);
590 }
591 };
592 })
593
594 // Display a fancy SELECT (based on select2).
595 // usage: <select crm-ui-select="{placeholder:'Something',allowClear:true,...}" ng-model="myobj.field"><option...></select>
596 .directive('crmUiSelect', function ($parse, $timeout) {
597 return {
598 require: '?ngModel',
599 scope: {
600 crmUiSelect: '='
601 },
602 link: function (scope, element, attrs, ngModel) {
603 // In cases where UI initiates update, there may be an extra
604 // call to refreshUI, but it doesn't create a cycle.
605
606 ngModel.$render = function () {
607 $timeout(function () {
608 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
609 // new item is added before selection is made
610 element.select2('val', ngModel.$viewValue);
611 });
612 };
613 function refreshModel() {
614 var oldValue = ngModel.$viewValue, newValue = element.select2('val');
615 if (oldValue != newValue) {
616 scope.$parent.$apply(function () {
617 ngModel.$setViewValue(newValue);
618 });
619 }
620 }
621
622 function init() {
623 // TODO watch select2-options
624 element.select2(scope.crmUiSelect || {});
625 element.on('change', refreshModel);
626 $timeout(ngModel.$render);
627 }
628
629 init();
630 }
631 };
632 })
633
634 // Render a crmEntityRef widget
635 // usage: <input crm-entityref="{entity: 'Contact', select: {allowClear:true}}" ng-model="myobj.field" />
636 .directive('crmEntityref', function ($parse, $timeout) {
637 return {
638 require: '?ngModel',
639 scope: {
640 crmEntityref: '='
641 },
642 link: function (scope, element, attrs, ngModel) {
643 // In cases where UI initiates update, there may be an extra
644 // call to refreshUI, but it doesn't create a cycle.
645
646 ngModel.$render = function () {
647 $timeout(function () {
648 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
649 // new item is added before selection is made
650 element.select2('val', ngModel.$viewValue);
651 });
652 };
653 function refreshModel() {
654 var oldValue = ngModel.$viewValue, newValue = element.select2('val');
655 if (oldValue != newValue) {
656 scope.$parent.$apply(function () {
657 ngModel.$setViewValue(newValue);
658 });
659 }
660 }
661
662 function init() {
663 // TODO watch options
664 // TODO can we infer "entity" from model?
665 element.crmEntityRef(scope.crmEntityref || {});
666 element.on('change', refreshModel);
667 $timeout(ngModel.$render);
668 }
669
670 init();
671 }
672 };
673 })
674
675 // example <div crm-ui-tab crm-title="ts('My Title')">...content...</div>
676 // WISHLIST: use a full Angular component instead of an incomplete jQuery wrapper
677 .directive('crmUiTab', function($parse) {
678 return {
679 require: '^crmUiTabSet',
680 restrict: 'EA',
681 scope: {
682 crmTitle: '@',
683 id: '@'
684 },
685 template: '<div ng-transclude></div>',
686 transclude: true,
687 link: function (scope, element, attrs, crmUiTabSetCtrl) {
688 crmUiTabSetCtrl.add(scope);
689 }
690 };
691 })
692
693 // example: <div crm-ui-tab-set><div crm-ui-tab crm-title="Tab 1">...</div><div crm-ui-tab crm-title="Tab 2">...</div></div>
694 .directive('crmUiTabSet', function() {
695 return {
696 restrict: 'EA',
697 scope: {
698 crmUiTabSet: '@'
699 },
700 templateUrl: '~/crmUi/tabset.html',
701 transclude: true,
702 controllerAs: 'crmUiTabSetCtrl',
703 controller: function($scope, $parse) {
704 var tabs = $scope.tabs = []; // array<$scope>
705 this.add = function(tab) {
706 if (!tab.id) throw "Tab is missing 'id'";
707 tabs.push(tab);
708 };
709 },
710 link: function (scope, element, attrs) {}
711 };
712 })
713
714 // Generic, field-independent form validator.
715 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" />
716 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" crm-ui-validate-name="myError" />
717 .directive('crmUiValidate', function() {
718 return {
719 restrict: 'EA',
720 require: 'ngModel',
721 link: function(scope, element, attrs, ngModel) {
722 var validationKey = attrs.crmUiValidateName ? attrs.crmUiValidateName : 'crmUiValidate';
723 scope.$watch(attrs.crmUiValidate, function(newValue){
724 ngModel.$setValidity(validationKey, !!newValue);
725 });
726 }
727 };
728 })
729
730 // like ng-show, but hides/displays elements using "visibility" which maintains positioning
731 // example <div crm-ui-visible="false">...content...</div>
732 .directive('crmUiVisible', function($parse) {
733 return {
734 restrict: 'EA',
735 scope: {
736 crmUiVisible: '@'
737 },
738 link: function (scope, element, attrs) {
739 var model = $parse(attrs.crmUiVisible);
740 function updatecChildren() {
741 element.css('visibility', model(scope.$parent) ? 'inherit' : 'hidden');
742 }
743 updatecChildren();
744 scope.$parent.$watch(attrs.crmUiVisible, updatecChildren);
745 }
746 };
747 })
748
749 // example: <div crm-ui-wizard="myWizardCtrl"><div crm-ui-wizard-step crm-title="ts('Step 1')">...</div><div crm-ui-wizard-step crm-title="ts('Step 2')">...</div></div>
750 // Note: "myWizardCtrl" has various actions/properties like next() and $first().
751 // WISHLIST: Allow each step to determine if it is "complete" / "valid" / "selectable"
752 // WISHLIST: Allow each step to enable/disable (show/hide) itself
753 .directive('crmUiWizard', function() {
754 return {
755 restrict: 'EA',
756 scope: {
757 crmUiWizard: '@'
758 },
759 templateUrl: '~/crmUi/wizard.html',
760 transclude: true,
761 controllerAs: 'crmUiWizardCtrl',
762 controller: function($scope, $parse) {
763 var steps = $scope.steps = []; // array<$scope>
764 var crmUiWizardCtrl = this;
765 var maxVisited = 0;
766 var selectedIndex = null;
767
768 var findIndex = function() {
769 var found = null;
770 angular.forEach(steps, function(step, stepKey) {
771 if (step.selected) found = stepKey;
772 });
773 return found;
774 };
775
776 /// @return int the index of the current step
777 this.$index = function() { return selectedIndex; };
778 /// @return bool whether the currentstep is first
779 this.$first = function() { return this.$index() === 0; };
780 /// @return bool whether the current step is last
781 this.$last = function() { return this.$index() === steps.length -1; };
782 this.$maxVisit = function() { return maxVisited; };
783 this.$validStep = function() {
784 return steps[selectedIndex] && steps[selectedIndex].isStepValid();
785 };
786 this.iconFor = function(index) {
787 if (index < this.$index()) return '√';
788 if (index === this.$index()) return '»';
789 return ' ';
790 };
791 this.isSelectable = function(step) {
792 if (step.selected) return false;
793 var result = false;
794 angular.forEach(steps, function(otherStep, otherKey) {
795 if (step === otherStep && otherKey <= maxVisited) result = true;
796 });
797 return result;
798 };
799
800 /*** @param Object step the $scope of the step */
801 this.select = function(step) {
802 angular.forEach(steps, function(otherStep, otherKey) {
803 otherStep.selected = (otherStep === step);
804 if (otherStep === step && maxVisited < otherKey) maxVisited = otherKey;
805 });
806 selectedIndex = findIndex();
807 };
808 /*** @param Object step the $scope of the step */
809 this.add = function(step) {
810 if (steps.length === 0) {
811 step.selected = true;
812 selectedIndex = 0;
813 }
814 steps.push(step);
815 steps.sort(function(a,b){
816 return a.crmUiWizardStep - b.crmUiWizardStep;
817 });
818 selectedIndex = findIndex();
819 };
820 this.remove = function(step) {
821 var key = null;
822 angular.forEach(steps, function(otherStep, otherKey) {
823 if (otherStep === step) key = otherKey;
824 });
825 if (key !== null) {
826 steps.splice(key, 1);
827 }
828 };
829 this.goto = function(index) {
830 if (index < 0) index = 0;
831 if (index >= steps.length) index = steps.length-1;
832 this.select(steps[index]);
833 };
834 this.previous = function() { this.goto(this.$index()-1); };
835 this.next = function() { this.goto(this.$index()+1); };
836 if ($scope.crmUiWizard) {
837 $parse($scope.crmUiWizard).assign($scope.$parent, this);
838 }
839 },
840 link: function (scope, element, attrs) {
841 scope.ts = CRM.ts(null);
842 }
843 };
844 })
845
846 // Use this to add extra markup to wizard
847 .directive('crmUiWizardButtons', function() {
848 return {
849 require: '^crmUiWizard',
850 restrict: 'EA',
851 scope: {},
852 template: '<span ng-transclude></span>',
853 transclude: true,
854 link: function (scope, element, attrs, crmUiWizardCtrl) {
855 var realButtonsEl = $(element).closest('.crm-wizard').find('.crm-wizard-buttons');
856 $(element).appendTo(realButtonsEl);
857 }
858 };
859 })
860
861 // Example: <button crm-icon="check">Save</button>
862 .directive('crmIcon', function() {
863 return {
864 restrict: 'EA',
865 scope: {},
866 link: function (scope, element, attrs) {
867 $(element).prepend('<span class="icon ui-icon-' + attrs.crmIcon + '"></span> ');
868 if ($(element).is('button')) {
869 $(element).addClass('crm-button');
870 }
871 }
872 };
873 })
874
875 // example: <div crm-ui-wizard-step crm-title="ts('My Title')" ng-form="mySubForm">...content...</div>
876 // If there are any conditional steps, then be sure to set a weight explicitly on *all* steps to maintain ordering.
877 // example: <div crm-ui-wizard-step="100" crm-title="..." ng-if="...">...content...</div>
878 .directive('crmUiWizardStep', function() {
879 var nextWeight = 1;
880 return {
881 require: ['^crmUiWizard', 'form'],
882 restrict: 'EA',
883 scope: {
884 crmTitle: '@', // expression, evaluates to a printable string
885 crmUiWizardStep: '@' // int, a weight which determines the ordering of the steps
886 },
887 template: '<div class="crm-wizard-step" ng-show="selected" ng-transclude/></div>',
888 transclude: true,
889 link: function (scope, element, attrs, ctrls) {
890 var crmUiWizardCtrl = ctrls[0], form = ctrls[1];
891 if (scope.crmUiWizardStep) {
892 scope.crmUiWizardStep = parseInt(scope.crmUiWizardStep);
893 } else {
894 scope.crmUiWizardStep = nextWeight++;
895 }
896 scope.isStepValid = function() {
897 return form.$valid;
898 };
899 crmUiWizardCtrl.add(scope);
900 element.on('$destroy', function(){
901 crmUiWizardCtrl.remove(scope);
902 });
903 }
904 };
905 })
906
907 // Example: <button crm-confirm="{message: ts('Are you sure you want to continue?')}" on-yes="frobnicate(123)">Frobincate</button>
908 // Example: <button crm-confirm="{type: 'disable', obj: myObject}" on-yes="myObject.is_active=0; myObject.save()">Disable</button>
909 .directive('crmConfirm', function () {
910 // Helpers to calculate default options for CRM.confirm()
911 var defaultFuncs = {
912 'disable': function (options) {
913 return {
914 message: ts('Are you sure you want to disable this?'),
915 options: {no: ts('Cancel'), yes: ts('Disable')},
916 width: 300,
917 title: ts('Disable %1?', {
918 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
919 })
920 };
921 },
922 'revert': function (options) {
923 return {
924 message: ts('Are you sure you want to revert this?'),
925 options: {no: ts('Cancel'), yes: ts('Revert')},
926 width: 300,
927 title: ts('Revert %1?', {
928 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
929 })
930 };
931 },
932 'delete': function (options) {
933 return {
934 message: ts('Are you sure you want to delete this?'),
935 options: {no: ts('Cancel'), yes: ts('Delete')},
936 width: 300,
937 title: ts('Delete %1?', {
938 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
939 })
940 };
941 }
942 };
943 return {
944 link: function (scope, element, attrs) {
945 $(element).click(function () {
946 var options = scope.$eval(attrs.crmConfirm);
947 if (attrs.title && !options.title) {
948 options.title = attrs.title;
949 }
950 var defaults = (options.type) ? defaultFuncs[options.type](options) : {};
951 CRM.confirm(_.extend(defaults, options))
952 .on('crmConfirm:yes', function () { scope.$apply(attrs.onYes); })
953 .on('crmConfirm:no', function () { scope.$apply(attrs.onNo); });
954 });
955 }
956 };
957 })
958 .run(function($rootScope, $location) {
959 /// Example: <button ng-click="goto('home')">Go home!</button>
960 $rootScope.goto = function(path) {
961 $location.path(path);
962 };
963 // useful for debugging: $rootScope.log = console.log || function() {};
964 })
965 ;
966
967 })(angular, CRM.$, CRM._);