Merge pull request #10895 from seamuslee001/CRM-21100-rc
[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')}"> {{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) {
259 if (retries) {
260 $timeout(function(){
261 init(retries-1, retryDelay);
262 }, retryDelay);
263 }
264 return;
265 }
266
267 var tgtScope = scope;//.$parent;
268 if (attrs.crmDepth) {
269 for (var i = attrs.crmDepth; i > 0; i--) {
270 tgtScope = tgtScope.$parent;
271 }
272 }
273
274 if (input.attr('ng-required')) {
275 scope.crmIsRequired = scope.$parent.$eval(input.attr('ng-required'));
276 scope.$parent.$watch(input.attr('ng-required'), function (isRequired) {
277 scope.crmIsRequired = isRequired;
278 });
279 }
280 else {
281 scope.crmIsRequired = input.prop('required');
282 }
283
284 ngModel = $parse(attrs.crmUiFor)(tgtScope);
285 if (ngModel) {
286 ngModel.$viewChangeListeners.push(updateCss);
287 }
288 };
289
290 $timeout(function(){
291 init(3, 100);
292 });
293 }
294 };
295 })
296
297 // Define a scope in which a name like "subform.foo" maps to a unique ID.
298 // 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>
299 .directive('crmUiIdScope', function () {
300 return {
301 restrict: 'EA',
302 scope: {},
303 controllerAs: 'crmUiIdCtrl',
304 controller: function($scope) {
305 var ids = {};
306 this.get = function(name) {
307 if (!ids[name]) {
308 ids[name] = "crmUiId_" + (++uidCount);
309 }
310 return ids[name];
311 };
312 },
313 link: function (scope, element, attrs) {}
314 };
315 })
316
317 // Display an HTML blurb inside an IFRAME.
318 // example: <iframe crm-ui-iframe="getHtmlContent()"></iframe>
319 // example: <iframe crm-ui-iframe crm-ui-iframe-src="getUrl()"></iframe>
320 .directive('crmUiIframe', function ($parse) {
321 return {
322 scope: {
323 crmUiIframeSrc: '@', // expression which evaluates to a URL
324 crmUiIframe: '@' // expression which evaluates to HTML content
325 },
326 link: function (scope, elm, attrs) {
327 var iframe = $(elm)[0];
328 iframe.setAttribute('width', '100%');
329 iframe.setAttribute('frameborder', '0');
330
331 var refresh = function () {
332 if (attrs.crmUiIframeSrc) {
333 iframe.setAttribute('src', scope.$parent.$eval(attrs.crmUiIframeSrc));
334 }
335 else {
336 var iframeHtml = scope.$parent.$eval(attrs.crmUiIframe);
337
338 var doc = iframe.document;
339 if (iframe.contentDocument) {
340 doc = iframe.contentDocument;
341 }
342 else if (iframe.contentWindow) {
343 doc = iframe.contentWindow.document;
344 }
345
346 doc.open();
347 doc.writeln(iframeHtml);
348 doc.close();
349 }
350 };
351
352 // If the iframe is in a dialog, respond to resize events
353 $(elm).parent().on('dialogresize dialogopen', function(e, ui) {
354 $(this).css({padding: '0', margin: '0', overflow: 'hidden'});
355 iframe.setAttribute('height', '' + $(this).innerHeight() + 'px');
356 });
357
358 scope.$parent.$watch(attrs.crmUiIframe, refresh);
359 }
360 };
361 })
362
363 // Example:
364 // <a ng-click="$broadcast('my-insert-target', 'some new text')>Insert</a>
365 // <textarea crm-ui-insert-rx='my-insert-target'></textarea>
366 .directive('crmUiInsertRx', function() {
367 return {
368 link: function(scope, element, attrs) {
369 scope.$on(attrs.crmUiInsertRx, function(e, tokenName) {
370 CRM.wysiwyg.insert(element, tokenName);
371 $(element).select2('close').select2('val', '');
372 CRM.wysiwyg.focus(element);
373 });
374 }
375 };
376 })
377
378 // Define a rich text editor.
379 // example: <textarea crm-ui-id="myForm.body_html" crm-ui-richtext name="body_html" ng-model="mailing.body_html"></textarea>
380 .directive('crmUiRichtext', function ($timeout) {
381 return {
382 require: '?ngModel',
383 link: function (scope, elm, attr, ngModel) {
384
385 var editor = CRM.wysiwyg.create(elm);
386 if (!ngModel) {
387 return;
388 }
389
390 if (attr.ngBlur) {
391 $(elm).on('blur', function() {
392 $timeout(function() {
393 scope.$eval(attr.ngBlur);
394 });
395 });
396 }
397
398 ngModel.$render = function(value) {
399 editor.done(function() {
400 CRM.wysiwyg.setVal(elm, ngModel.$viewValue || '');
401 });
402 };
403 }
404 };
405 })
406
407 // Display a lock icon (based on a boolean).
408 // example: <a crm-ui-lock binding="mymodel.boolfield"></a>
409 // example: <a crm-ui-lock
410 // binding="mymodel.boolfield"
411 // title-locked="ts('Boolfield is locked')"
412 // title-unlocked="ts('Boolfield is unlocked')"></a>
413 .directive('crmUiLock', function ($parse, $rootScope) {
414 var defaultVal = function (defaultValue) {
415 var f = function (scope) {
416 return defaultValue;
417 };
418 f.assign = function (scope, value) {
419 // ignore changes
420 };
421 return f;
422 };
423
424 // like $parse, but accepts a defaultValue in case expr is undefined
425 var parse = function (expr, defaultValue) {
426 return expr ? $parse(expr) : defaultVal(defaultValue);
427 };
428
429 return {
430 template: '',
431 link: function (scope, element, attrs) {
432 var binding = parse(attrs.binding, true);
433 var titleLocked = parse(attrs.titleLocked, ts('Locked'));
434 var titleUnlocked = parse(attrs.titleUnlocked, ts('Unlocked'));
435
436 $(element).addClass('crm-i lock-button');
437 var refresh = function () {
438 var locked = binding(scope);
439 if (locked) {
440 $(element)
441 .removeClass('fa-unlock')
442 .addClass('fa-lock')
443 .prop('title', titleLocked(scope))
444 ;
445 }
446 else {
447 $(element)
448 .removeClass('fa-lock')
449 .addClass('fa-unlock')
450 .prop('title', titleUnlocked(scope))
451 ;
452 }
453 };
454
455 $(element).click(function () {
456 binding.assign(scope, !binding(scope));
457 //scope.$digest();
458 $rootScope.$digest();
459 });
460
461 scope.$watch(attrs.binding, refresh);
462 scope.$watch(attrs.titleLocked, refresh);
463 scope.$watch(attrs.titleUnlocked, refresh);
464
465 refresh();
466 }
467 };
468 })
469
470 // CrmUiOrderCtrl is a controller class which manages sort orderings.
471 // Ex:
472 // JS: $scope.myOrder = new CrmUiOrderCtrl(['+field1', '-field2]);
473 // $scope.myOrder.toggle('field1');
474 // $scope.myOrder.setDir('field2', '');
475 // HTML: <tr ng-repeat="... | order:myOrder.get()">...</tr>
476 .service('CrmUiOrderCtrl', function(){
477 //
478 function CrmUiOrderCtrl(defaults){
479 this.values = defaults;
480 }
481 angular.extend(CrmUiOrderCtrl.prototype, {
482 get: function get() {
483 return this.values;
484 },
485 getDir: function getDir(name) {
486 if (this.values.indexOf(name) >= 0 || this.values.indexOf('+' + name) >= 0) {
487 return '+';
488 }
489 if (this.values.indexOf('-' + name) >= 0) {
490 return '-';
491 }
492 return '';
493 },
494 // @return bool TRUE if something is removed
495 remove: function remove(name) {
496 var idx = this.values.indexOf(name);
497 if (idx >= 0) {
498 this.values.splice(idx, 1);
499 return true;
500 }
501 else {
502 return false;
503 }
504 },
505 setDir: function setDir(name, dir) {
506 return this.toggle(name, dir);
507 },
508 // Toggle sort order on a field.
509 // To set a specific order, pass optional parameter 'next' ('+', '-', or '').
510 toggle: function toggle(name, next) {
511 if (!next && next !== '') {
512 next = '+';
513 if (this.remove(name) || this.remove('+' + name)) {
514 next = '-';
515 }
516 if (this.remove('-' + name)) {
517 next = '';
518 }
519 }
520
521 if (next == '+') {
522 this.values.unshift('+' + name);
523 }
524 else if (next == '-') {
525 this.values.unshift('-' + name);
526 }
527 }
528 });
529 return CrmUiOrderCtrl;
530 })
531
532 // Define a controller which manages sort order. You may interact with the controller
533 // directly ("myOrder.toggle('fieldname')") order using the helper, crm-ui-order-by.
534 // example:
535 // <span crm-ui-order="{var: 'myOrder', defaults: {'-myField'}}"></span>
536 // <th><a crm-ui-order-by="[myOrder,'myField']">My Field</a></th>
537 // <tr ng-repeat="... | order:myOrder.get()">...</tr>
538 // <button ng-click="myOrder.toggle('myField')">
539 .directive('crmUiOrder', function(CrmUiOrderCtrl) {
540 return {
541 link: function(scope, element, attrs){
542 var options = angular.extend({var: 'crmUiOrderBy'}, scope.$eval(attrs.crmUiOrder));
543 scope[options.var] = new CrmUiOrderCtrl(options.defaults);
544 }
545 };
546 })
547
548 // For usage, see crmUiOrder (above)
549 .directive('crmUiOrderBy', function() {
550 return {
551 link: function(scope, element, attrs) {
552 function updateClass(crmUiOrderCtrl, name) {
553 var dir = crmUiOrderCtrl.getDir(name);
554 element
555 .toggleClass('sorting_asc', dir === '+')
556 .toggleClass('sorting_desc', dir === '-')
557 .toggleClass('sorting', dir === '');
558 }
559
560 element.on('click', function(e){
561 var tgt = scope.$eval(attrs.crmUiOrderBy);
562 tgt[0].toggle(tgt[1]);
563 updateClass(tgt[0], tgt[1]);
564 e.preventDefault();
565 scope.$digest();
566 });
567
568 var tgt = scope.$eval(attrs.crmUiOrderBy);
569 updateClass(tgt[0], tgt[1]);
570 }
571 };
572 })
573
574 // Display a fancy SELECT (based on select2).
575 // usage: <select crm-ui-select="{placeholder:'Something',allowClear:true,...}" ng-model="myobj.field"><option...></select>
576 .directive('crmUiSelect', function ($parse, $timeout) {
577 return {
578 require: '?ngModel',
579 priority: 1,
580 scope: {
581 crmUiSelect: '='
582 },
583 link: function (scope, element, attrs, ngModel) {
584 // In cases where UI initiates update, there may be an extra
585 // call to refreshUI, but it doesn't create a cycle.
586
587 if (ngModel) {
588 ngModel.$render = function () {
589 $timeout(function () {
590 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
591 // new item is added before selection is made
592 var newVal = _.cloneDeep(ngModel.$modelValue);
593 // Fix possible data-type mismatch
594 if (typeof newVal === 'string' && element.select2('container').hasClass('select2-container-multi')) {
595 newVal = newVal.length ? newVal.split(',') : [];
596 }
597 element.select2('val', newVal);
598 });
599 };
600 }
601 function refreshModel() {
602 var oldValue = ngModel.$viewValue, newValue = element.select2('val');
603 if (oldValue != newValue) {
604 scope.$parent.$apply(function () {
605 ngModel.$setViewValue(newValue);
606 });
607 }
608 }
609
610 function init() {
611 // TODO watch select2-options
612 element.crmSelect2(scope.crmUiSelect || {});
613 if (ngModel) {
614 element.on('change', refreshModel);
615 }
616 }
617
618 init();
619 }
620 };
621 })
622
623 // Render a crmEntityRef widget
624 // usage: <input crm-entityref="{entity: 'Contact', select: {allowClear:true}}" ng-model="myobj.field" />
625 .directive('crmEntityref', function ($parse, $timeout) {
626 return {
627 require: '?ngModel',
628 scope: {
629 crmEntityref: '='
630 },
631 link: function (scope, element, attrs, ngModel) {
632 // In cases where UI initiates update, there may be an extra
633 // call to refreshUI, but it doesn't create a cycle.
634
635 ngModel.$render = function () {
636 $timeout(function () {
637 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
638 // new item is added before selection is made
639 var newVal = _.cloneDeep(ngModel.$modelValue);
640 // Fix possible data-type mismatch
641 if (typeof newVal === 'string' && element.select2('container').hasClass('select2-container-multi')) {
642 newVal = newVal.length ? newVal.split(',') : [];
643 }
644 element.select2('val', newVal);
645 });
646 };
647 function refreshModel() {
648 var oldValue = ngModel.$viewValue, newValue = element.select2('val');
649 if (oldValue != newValue) {
650 scope.$parent.$apply(function () {
651 ngModel.$setViewValue(newValue);
652 });
653 }
654 }
655
656 function init() {
657 // TODO can we infer "entity" from model?
658 element.crmEntityRef(scope.crmEntityref || {});
659 element.on('change', refreshModel);
660 $timeout(ngModel.$render);
661 }
662
663 init();
664 }
665 };
666 })
667
668 // example <div crm-ui-tab id="tab-1" crm-title="ts('My Title')" count="3">...content...</div>
669 // WISHLIST: use a full Angular component instead of an incomplete jQuery wrapper
670 .directive('crmUiTab', function($parse) {
671 return {
672 require: '^crmUiTabSet',
673 restrict: 'EA',
674 scope: {
675 crmTitle: '@',
676 crmIcon: '@',
677 count: '@',
678 id: '@'
679 },
680 template: '<div ng-transclude></div>',
681 transclude: true,
682 link: function (scope, element, attrs, crmUiTabSetCtrl) {
683 crmUiTabSetCtrl.add(scope);
684 }
685 };
686 })
687
688 // 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>
689 .directive('crmUiTabSet', function() {
690 return {
691 restrict: 'EA',
692 scope: {
693 crmUiTabSet: '@',
694 tabSetOptions: '@'
695 },
696 templateUrl: '~/crmUi/tabset.html',
697 transclude: true,
698 controllerAs: 'crmUiTabSetCtrl',
699 controller: function($scope, $parse) {
700 var tabs = $scope.tabs = []; // array<$scope>
701 this.add = function(tab) {
702 if (!tab.id) throw "Tab is missing 'id'";
703 tabs.push(tab);
704 };
705 },
706 link: function (scope, element, attrs) {}
707 };
708 })
709
710 // Generic, field-independent form validator.
711 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" />
712 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" crm-ui-validate-name="myError" />
713 .directive('crmUiValidate', function() {
714 return {
715 restrict: 'EA',
716 require: 'ngModel',
717 link: function(scope, element, attrs, ngModel) {
718 var validationKey = attrs.crmUiValidateName ? attrs.crmUiValidateName : 'crmUiValidate';
719 scope.$watch(attrs.crmUiValidate, function(newValue){
720 ngModel.$setValidity(validationKey, !!newValue);
721 });
722 }
723 };
724 })
725
726 // like ng-show, but hides/displays elements using "visibility" which maintains positioning
727 // example <div crm-ui-visible="false">...content...</div>
728 .directive('crmUiVisible', function($parse) {
729 return {
730 restrict: 'EA',
731 scope: {
732 crmUiVisible: '@'
733 },
734 link: function (scope, element, attrs) {
735 var model = $parse(attrs.crmUiVisible);
736 function updatecChildren() {
737 element.css('visibility', model(scope.$parent) ? 'inherit' : 'hidden');
738 }
739 updatecChildren();
740 scope.$parent.$watch(attrs.crmUiVisible, updatecChildren);
741 }
742 };
743 })
744
745 // 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>
746 // example with custom nav classes: <div crm-ui-wizard crm-ui-wizard-nav-class="ng-animate-out ...">...</div>
747 // Note: "myWizardCtrl" has various actions/properties like next() and $first().
748 // WISHLIST: Allow each step to determine if it is "complete" / "valid" / "selectable"
749 // WISHLIST: Allow each step to enable/disable (show/hide) itself
750 .directive('crmUiWizard', function() {
751 return {
752 restrict: 'EA',
753 scope: {
754 crmUiWizard: '@',
755 crmUiWizardNavClass: '@' // string, A list of classes that will be added to the nav items
756 },
757 templateUrl: '~/crmUi/wizard.html',
758 transclude: true,
759 controllerAs: 'crmUiWizardCtrl',
760 controller: function($scope, $parse) {
761 var steps = $scope.steps = []; // array<$scope>
762 var crmUiWizardCtrl = this;
763 var maxVisited = 0;
764 var selectedIndex = null;
765
766 var findIndex = function() {
767 var found = null;
768 angular.forEach(steps, function(step, stepKey) {
769 if (step.selected) found = stepKey;
770 });
771 return found;
772 };
773
774 /// @return int the index of the current step
775 this.$index = function() { return selectedIndex; };
776 /// @return bool whether the currentstep is first
777 this.$first = function() { return this.$index() === 0; };
778 /// @return bool whether the current step is last
779 this.$last = function() { return this.$index() === steps.length -1; };
780 this.$maxVisit = function() { return maxVisited; };
781 this.$validStep = function() {
782 return steps[selectedIndex] && steps[selectedIndex].isStepValid();
783 };
784 this.iconFor = function(index) {
785 if (index < this.$index()) return '√';
786 if (index === this.$index()) return '»';
787 return ' ';
788 };
789 this.isSelectable = function(step) {
790 if (step.selected) return false;
791 var result = false;
792 angular.forEach(steps, function(otherStep, otherKey) {
793 if (step === otherStep && otherKey <= maxVisited) result = true;
794 });
795 return result;
796 };
797
798 /*** @param Object step the $scope of the step */
799 this.select = function(step) {
800 angular.forEach(steps, function(otherStep, otherKey) {
801 otherStep.selected = (otherStep === step);
802 if (otherStep === step && maxVisited < otherKey) maxVisited = otherKey;
803 });
804 selectedIndex = findIndex();
805 };
806 /*** @param Object step the $scope of the step */
807 this.add = function(step) {
808 if (steps.length === 0) {
809 step.selected = true;
810 selectedIndex = 0;
811 }
812 steps.push(step);
813 steps.sort(function(a,b){
814 return a.crmUiWizardStep - b.crmUiWizardStep;
815 });
816 selectedIndex = findIndex();
817 };
818 this.remove = function(step) {
819 var key = null;
820 angular.forEach(steps, function(otherStep, otherKey) {
821 if (otherStep === step) key = otherKey;
822 });
823 if (key !== null) {
824 steps.splice(key, 1);
825 }
826 };
827 this.goto = function(index) {
828 if (index < 0) index = 0;
829 if (index >= steps.length) index = steps.length-1;
830 this.select(steps[index]);
831 };
832 this.previous = function() { this.goto(this.$index()-1); };
833 this.next = function() { this.goto(this.$index()+1); };
834 if ($scope.crmUiWizard) {
835 $parse($scope.crmUiWizard).assign($scope.$parent, this);
836 }
837 },
838 link: function (scope, element, attrs) {
839 scope.ts = CRM.ts(null);
840 }
841 };
842 })
843
844 // Use this to add extra markup to wizard
845 .directive('crmUiWizardButtons', function() {
846 return {
847 require: '^crmUiWizard',
848 restrict: 'EA',
849 scope: {},
850 template: '<span ng-transclude></span>',
851 transclude: true,
852 link: function (scope, element, attrs, crmUiWizardCtrl) {
853 var realButtonsEl = $(element).closest('.crm-wizard').find('.crm-wizard-buttons');
854 $(element).appendTo(realButtonsEl);
855 }
856 };
857 })
858
859 // Example for Font Awesome: <button crm-icon="fa-check">Save</button>
860 // Example for jQuery UI (deprecated): <button crm-icon="check">Save</button>
861 .directive('crmIcon', function() {
862 return {
863 restrict: 'EA',
864 link: function (scope, element, attrs) {
865 if (element.is('[crm-ui-tab]')) {
866 // handled in crmUiTab ctrl
867 return;
868 }
869 if (attrs.crmIcon.substring(0,3) == 'fa-') {
870 $(element).prepend('<i class="crm-i ' + attrs.crmIcon + '"></i> ');
871 }
872 else {
873 $(element).prepend('<span class="icon ui-icon-' + attrs.crmIcon + '"></span> ');
874 }
875 if ($(element).is('button')) {
876 $(element).addClass('crm-button');
877 }
878 }
879 };
880 })
881
882 // example: <div crm-ui-wizard-step crm-title="ts('My Title')" ng-form="mySubForm">...content...</div>
883 // If there are any conditional steps, then be sure to set a weight explicitly on *all* steps to maintain ordering.
884 // example: <div crm-ui-wizard-step="100" crm-title="..." ng-if="...">...content...</div>
885 // example with custom classes: <div crm-ui-wizard-step="100" crm-ui-wizard-step-class="ng-animate-out ...">...content...</div>
886 .directive('crmUiWizardStep', function() {
887 var nextWeight = 1;
888 return {
889 require: ['^crmUiWizard', 'form'],
890 restrict: 'EA',
891 scope: {
892 crmTitle: '@', // expression, evaluates to a printable string
893 crmUiWizardStep: '@', // int, a weight which determines the ordering of the steps
894 crmUiWizardStepClass: '@' // string, A list of classes that will be added to the template
895 },
896 template: '<div class="crm-wizard-step {{crmUiWizardStepClass}}" ng-show="selected" ng-transclude/></div>',
897 transclude: true,
898 link: function (scope, element, attrs, ctrls) {
899 var crmUiWizardCtrl = ctrls[0], form = ctrls[1];
900 if (scope.crmUiWizardStep) {
901 scope.crmUiWizardStep = parseInt(scope.crmUiWizardStep);
902 } else {
903 scope.crmUiWizardStep = nextWeight++;
904 }
905 scope.isStepValid = function() {
906 return form.$valid;
907 };
908 crmUiWizardCtrl.add(scope);
909 scope.$on('$destroy', function(){
910 crmUiWizardCtrl.remove(scope);
911 });
912 }
913 };
914 })
915
916 // Example: <button crm-confirm="{message: ts('Are you sure you want to continue?')}" on-yes="frobnicate(123)">Frobincate</button>
917 // Example: <button crm-confirm="{type: 'disable', obj: myObject}" on-yes="myObject.is_active=0; myObject.save()">Disable</button>
918 // Example: <button crm-confirm="{templateUrl: '~/path/to/view.html', export: {foo: bar}}" on-yes="frobnicate(123)">Frobincate</button>
919 .directive('crmConfirm', function ($compile, $rootScope, $templateRequest, $q) {
920 // Helpers to calculate default options for CRM.confirm()
921 var defaultFuncs = {
922 'disable': function (options) {
923 return {
924 message: ts('Are you sure you want to disable this?'),
925 options: {no: ts('Cancel'), yes: ts('Disable')},
926 width: 300,
927 title: ts('Disable %1?', {
928 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
929 })
930 };
931 },
932 'revert': function (options) {
933 return {
934 message: ts('Are you sure you want to revert this?'),
935 options: {no: ts('Cancel'), yes: ts('Revert')},
936 width: 300,
937 title: ts('Revert %1?', {
938 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
939 })
940 };
941 },
942 'delete': function (options) {
943 return {
944 message: ts('Are you sure you want to delete this?'),
945 options: {no: ts('Cancel'), yes: ts('Delete')},
946 width: 300,
947 title: ts('Delete %1?', {
948 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
949 })
950 };
951 }
952 };
953 var confirmCount = 0;
954 return {
955 link: function (scope, element, attrs) {
956 $(element).click(function () {
957 var options = scope.$eval(attrs.crmConfirm);
958 if (attrs.title && !options.title) {
959 options.title = attrs.title;
960 }
961 var defaults = (options.type) ? defaultFuncs[options.type](options) : {};
962
963 var tpl = null, stubId = null;
964 if (!options.message) {
965 if (options.templateUrl) {
966 tpl = $templateRequest(options.templateUrl);
967 }
968 else if (options.template) {
969 tpl = options.template;
970 }
971 if (tpl) {
972 stubId = 'crmUiConfirm_' + (++confirmCount);
973 options.message = '<div id="' + stubId + '"></div>';
974 }
975 }
976
977 CRM.confirm(_.extend(defaults, options))
978 .on('crmConfirm:yes', function() { scope.$apply(attrs.onYes); })
979 .on('crmConfirm:no', function() { scope.$apply(attrs.onNo); });
980
981 if (tpl && stubId) {
982 $q.when(tpl, function(html) {
983 var scope = options.scope || $rootScope.$new();
984 if (options.export) {
985 angular.extend(scope, options.export);
986 }
987 var linker = $compile(html);
988 $('#' + stubId).append($(linker(scope)));
989 });
990 }
991 });
992 }
993 };
994 })
995
996 // Sets document title & page title; attempts to override CMS title markup for the latter
997 // WARNING: Use only once per route!
998 // Example (same title for both): <h1 crm-page-title>{{ts('Hello')}}</h1>
999 // Example (separate document title): <h1 crm-document-title="ts('Hello')" crm-page-title><i class="crm-i fa-flag"></i>{{ts('Hello')}}</h1>
1000 .directive('crmPageTitle', function($timeout) {
1001 return {
1002 scope: {
1003 crmDocumentTitle: '='
1004 },
1005 link: function(scope, $el, attrs) {
1006 function update() {
1007 $timeout(function() {
1008 var newPageTitle = _.trim($el.html()),
1009 newDocumentTitle = scope.crmDocumentTitle || $el.text();
1010 document.title = $('title').text().replace(documentTitle, newDocumentTitle);
1011 // If the CMS has already added title markup to the page, use it
1012 $('h1').not('.crm-container h1').each(function() {
1013 if (_.trim($(this).html()) === pageTitle) {
1014 $(this).addClass('crm-page-title').html(newPageTitle);
1015 $el.hide();
1016 }
1017 });
1018 pageTitle = newPageTitle;
1019 documentTitle = newDocumentTitle;
1020 });
1021 }
1022
1023 scope.$watch(function() {return scope.crmDocumentTitle + $el.html();}, update);
1024 }
1025 };
1026 })
1027
1028 .run(function($rootScope, $location) {
1029 /// Example: <button ng-click="goto('home')">Go home!</button>
1030 $rootScope.goto = function(path) {
1031 $location.path(path);
1032 };
1033 // useful for debugging: $rootScope.log = console.log || function() {};
1034 })
1035 ;
1036
1037 })(angular, CRM.$, CRM._);