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