Merge pull request #12484 from eileenmcnaughton/queryFields
[civicrm-core.git] / ang / crmUi.js
CommitLineData
685acae4 1/// crmUi: Sundry UI helpers
2(function (angular, $, _) {
3
835fcb5e 4 var uidCount = 0,
826f5ace
CW
5 pageTitle = 'CiviCRM',
6 documentTitle = 'CiviCRM';
f8601d61 7
0b199194 8 angular.module('crmUi', CRM.angRequires('crmUi'))
030dce01 9
0cbed02c 10 // example <div crm-ui-accordion crm-title="ts('My Title')" crm-collapsed="true">...content...</div>
e4f46be0 11 // WISHLIST: crmCollapsed should support two-way/continuous binding
030dce01
TO
12 .directive('crmUiAccordion', function() {
13 return {
14 scope: {
207819ec 15 crmUiAccordion: '='
030dce01 16 },
207819ec 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>',
030dce01 18 transclude: true,
0cbed02c
TO
19 link: function (scope, element, attrs) {
20 scope.cssClasses = {
207819ec
CW
21 'crm-accordion-wrapper': true,
22 collapsed: scope.crmUiAccordion.collapsed
0cbed02c 23 };
207819ec
CW
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 });
0cbed02c 32 }
030dce01
TO
33 };
34 })
35
69a65adc
TO
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
a42344f4
CW
67 // Simple wrapper around $.crmDatepicker.
68 // example with no time input: <input crm-ui-datepicker="{time: false}" ng-model="myobj.datefield"/>
70e7470f 69 // example with custom date format: <input crm-ui-datepicker="{date: 'm/d/y'}" ng-model="myobj.datefield"/>
a42344f4 70 .directive('crmUiDatepicker', function () {
510d515d
TO
71 return {
72 restrict: 'AE',
2f31bc16 73 require: 'ngModel',
510d515d 74 scope: {
a42344f4 75 crmUiDatepicker: '='
510d515d 76 },
2f31bc16 77 link: function (scope, element, attrs, ngModel) {
ac5009c1
CW
78 ngModel.$render = function () {
79 element.val(ngModel.$viewValue).change();
80 };
81
a42344f4
CW
82 element
83 .crmDatepicker(scope.crmUiDatepicker)
84 .on('change', function() {
ac5009c1 85 var requiredLength = 19;
a42344f4
CW
86 if (scope.crmUiDatepicker && scope.crmUiDatepicker.time === false) {
87 requiredLength = 10;
88 }
89 if (scope.crmUiDatepicker && scope.crmUiDatepicker.date === false) {
ac5009c1 90 requiredLength = 8;
a42344f4
CW
91 }
92 ngModel.$setValidity('incompleteDateTime', !($(this).val().length && $(this).val().length !== requiredLength));
510d515d 93 });
510d515d
TO
94 }
95 };
96 })
97
c4c69e7b
TO
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();
916f65c0 109 return (args && args.angularDebug) ? '<div crm-ui-accordion=\'{title: ts("Debug (%1)", {1: crmUiDebug}), collapsed: true}\'><pre>{{data|json}}</pre></div>' : '';
c4c69e7b
TO
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
489c2674 123 // Display a field/row in a field list
c4256f35
CW
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>
3ca16b89 127 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field'), help: hs('help_field_name'), required: true}"> {{mydata}} </div>
3cc9c048 128 .directive('crmUiField', function() {
489c2674
TO
129 // Note: When writing new templates, the "label" position is particular. See/patch "var label" below.
130 var templateUrls = {
ef5d18a1
TO
131 default: '~/crmUi/field.html',
132 checkbox: '~/crmUi/field-cb.html'
489c2674
TO
133 };
134
135 return {
f8601d61
TO
136 require: '^crmUiIdScope',
137 restrict: 'EA',
489c2674 138 scope: {
d8356d0b 139 // {title, name, help, helpFile}
c4256f35 140 crmUiField: '='
489c2674
TO
141 },
142 templateUrl: function(tElement, tAttrs){
143 var layout = tAttrs.crmLayout ? tAttrs.crmLayout : 'default';
144 return templateUrls[layout];
145 },
146 transclude: true,
f8601d61 147 link: function (scope, element, attrs, crmUiIdCtrl) {
489c2674 148 $(element).addClass('crm-section');
563ba527 149 scope.help = null;
dfc2a868
TO
150 scope.$watch('crmUiField', function(crmUiField) {
151 if (crmUiField && crmUiField.help) {
152 scope.help = crmUiField.help.clone({}, {
153 title: crmUiField.title
154 });
155 }
156 });
f8601d61
TO
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',
3cc9c048
TO
166 link: {
167 pre: function (scope, element, attrs, crmUiIdCtrl) {
168 var id = crmUiIdCtrl.get(attrs.crmUiId);
169 element.attr('id', id);
170 }
f8601d61
TO
171 }
172 };
173 })
489c2674 174
dfc2a868
TO
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() {
dfc2a868
TO
186 CRM.help(this.options.title, {id: this.options.id, file: this.options.file});
187 },
188 clone: function clone(options, defaults) {
dfc2a868
TO
189 return new FieldHelp(angular.extend({}, defaults, this.options, options));
190 }
191 });
192
563ba527 193 // example: var hs = crmUiHelp({file: 'CRM/Foo/Bar'});
dfc2a868 194 return function(defaults){
563ba527
TO
195 // example: hs('myfield')
196 // example: hs({id: 'myfield', title: 'Foo Bar', file: 'Whiz/Bang'})
dfc2a868
TO
197 return function(options) {
198 if (_.isString(options)) {
199 options = {id: options};
200 }
201 return new FieldHelp(angular.extend({}, defaults, options));
6dc9d4ca
TO
202 };
203 };
dfc2a868
TO
204 })
205
206 // Display a help icon
9a593827 207 // Example: Use a default *.hlp file
563ba527
TO
208 // scope.hs = crmUiHelp({file: 'Path/To/Help/File'});
209 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field'})">
9a593827 210 // Example: Use an explicit *.hlp file
563ba527 211 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field', file:'CRM/Foo/Bar'})">
a517b78a
CW
212 .directive('crmUiHelp', function() {
213 return {
214 restrict: 'EA',
563ba527
TO
215 link: function(scope, element, attrs) {
216 setTimeout(function() {
217 var crmUiHelp = scope.$eval(attrs.crmUiHelp);
dfc2a868
TO
218 var title = crmUiHelp && crmUiHelp.get('title') ? ts('%1 Help', {1: crmUiHelp.get('title')}) : ts('Help');
219 element.attr('title', title);
563ba527 220 }, 50);
dfc2a868 221
a517b78a
CW
222 element
223 .addClass('helpicon')
a517b78a
CW
224 .attr('href', '#')
225 .on('click', function(e) {
226 e.preventDefault();
563ba527 227 scope.$eval(attrs.crmUiHelp).open();
a517b78a
CW
228 });
229 }
230 };
231 })
232
f8601d61
TO
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 = {};
489c2674 243
f8601d61 244 if (!attrs.crmUiFor) return;
489c2674 245
f8601d61
TO
246 var id = crmUiIdCtrl.get(attrs.crmUiFor);
247 element.attr('for', id);
248 var ngModel = null;
489c2674 249
f8601d61
TO
250 var updateCss = function () {
251 scope.cssClasses['crm-error'] = !ngModel.$valid && !ngModel.$pristine;
252 };
489c2674 253
f8601d61
TO
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);
3ca16b89 258 if (input.length === 0 && !attrs.crmUiForceRequired) {
f8601d61
TO
259 if (retries) {
260 $timeout(function(){
261 init(retries-1, retryDelay);
262 }, retryDelay);
263 }
264 return;
265 }
489c2674 266
3ca16b89
TO
267 if (attrs.crmUiForceRequired) {
268 scope.crmIsRequired = true;
269 return;
270 }
271
f8601d61
TO
272 var tgtScope = scope;//.$parent;
273 if (attrs.crmDepth) {
274 for (var i = attrs.crmDepth; i > 0; i--) {
275 tgtScope = tgtScope.$parent;
276 }
277 }
489c2674 278
f8601d61
TO
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 {
f2bad133 286 scope.crmIsRequired = input.prop('required');
f8601d61 287 }
489c2674 288
f8601d61
TO
289 ngModel = $parse(attrs.crmUiFor)(tgtScope);
290 if (ngModel) {
291 ngModel.$viewChangeListeners.push(updateCss);
292 }
293 };
489c2674 294
f8601d61
TO
295 $timeout(function(){
296 init(3, 100);
489c2674
TO
297 });
298 }
299 };
300 })
301
d376f33e 302 // Define a scope in which a name like "subform.foo" maps to a unique ID.
f8601d61
TO
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];
f2bad133 316 };
f8601d61
TO
317 },
318 link: function (scope, element, attrs) {}
319 };
320 })
321
d376f33e 322 // Display an HTML blurb inside an IFRAME.
107c5cc7 323 // example: <iframe crm-ui-iframe="getHtmlContent()"></iframe>
79cf1116 324 // example: <iframe crm-ui-iframe crm-ui-iframe-src="getUrl()"></iframe>
107c5cc7
TO
325 .directive('crmUiIframe', function ($parse) {
326 return {
327 scope: {
79cf1116
TO
328 crmUiIframeSrc: '@', // expression which evaluates to a URL
329 crmUiIframe: '@' // expression which evaluates to HTML content
107c5cc7
TO
330 },
331 link: function (scope, elm, attrs) {
332 var iframe = $(elm)[0];
333 iframe.setAttribute('width', '100%');
910a6c11 334 iframe.setAttribute('height', '250px');
107c5cc7
TO
335 iframe.setAttribute('frameborder', '0');
336
337 var refresh = function () {
79cf1116
TO
338 if (attrs.crmUiIframeSrc) {
339 iframe.setAttribute('src', scope.$parent.$eval(attrs.crmUiIframeSrc));
107c5cc7 340 }
79cf1116
TO
341 else {
342 var iframeHtml = scope.$parent.$eval(attrs.crmUiIframe);
107c5cc7 343
79cf1116
TO
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 }
f2bad133 356 };
107c5cc7 357
02cd9764
CW
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
910a6c11
MR
364 $(elm).parent().on('dialogresize', function(e, ui) {
365 iframe.setAttribute('class', 'resized');
366 });
367
107c5cc7 368 scope.$parent.$watch(attrs.crmUiIframe, refresh);
107c5cc7
TO
369 }
370 };
371 })
372
f8f85764
TO
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>
f8f85764
TO
376 .directive('crmUiInsertRx', function() {
377 return {
378 link: function(scope, element, attrs) {
379 scope.$on(attrs.crmUiInsertRx, function(e, tokenName) {
c62731c3
TC
380 CRM.wysiwyg.insert(element, tokenName);
381 $(element).select2('close').select2('val', '');
f91b1c0c 382 CRM.wysiwyg.focus(element);
f8f85764
TO
383 });
384 }
385 };
386 })
387
d376f33e 388 // Define a rich text editor.
3cc9c048
TO
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) {
38737af8
TO
391 return {
392 require: '?ngModel',
393 link: function (scope, elm, attr, ngModel) {
65d3e04c 394
c62731c3 395 var editor = CRM.wysiwyg.create(elm);
38737af8
TO
396 if (!ngModel) {
397 return;
398 }
399
07996588 400 if (attr.ngBlur) {
f91b1c0c
CW
401 $(elm).on('blur', function() {
402 $timeout(function() {
07996588 403 scope.$eval(attr.ngBlur);
d03e0d13 404 });
07996588
TO
405 });
406 }
407
f91b1c0c 408 ngModel.$render = function(value) {
c63f9bfb 409 editor.done(function() {
495f94fb 410 CRM.wysiwyg.setVal(elm, ngModel.$viewValue || '');
c63f9bfb 411 });
38737af8
TO
412 };
413 }
414 };
415 })
416
d376f33e 417 // Display a lock icon (based on a boolean).
685acae4 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;
f2bad133 427 };
685acae4 428 f.assign = function (scope, value) {
429 // ignore changes
f2bad133 430 };
685acae4 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) {
f2bad133
TO
442 var binding = parse(attrs.binding, true);
443 var titleLocked = parse(attrs.titleLocked, ts('Locked'));
444 var titleUnlocked = parse(attrs.titleUnlocked, ts('Unlocked'));
685acae4 445
77ec5a8d 446 $(element).addClass('crm-i lock-button');
685acae4 447 var refresh = function () {
448 var locked = binding(scope);
449 if (locked) {
450 $(element)
77ec5a8d
AH
451 .removeClass('fa-unlock')
452 .addClass('fa-lock')
685acae4 453 .prop('title', titleLocked(scope))
454 ;
455 }
456 else {
457 $(element)
77ec5a8d
AH
458 .removeClass('fa-lock')
459 .addClass('fa-unlock')
685acae4 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 })
030dce01 479
b21c9cdc
TO
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
d376f33e 584 // Display a fancy SELECT (based on select2).
ebfe3efb
TO
585 // usage: <select crm-ui-select="{placeholder:'Something',allowClear:true,...}" ng-model="myobj.field"><option...></select>
586 .directive('crmUiSelect', function ($parse, $timeout) {
8c632f2b 587 return {
ebfe3efb 588 require: '?ngModel',
1d924612 589 priority: 1,
8c632f2b 590 scope: {
8674b5ac 591 crmUiSelect: '='
8c632f2b 592 },
ebfe3efb 593 link: function (scope, element, attrs, ngModel) {
8c632f2b
TO
594 // In cases where UI initiates update, there may be an extra
595 // call to refreshUI, but it doesn't create a cycle.
596
c81696a6
CW
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
9ed95c23
CW
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);
c81696a6
CW
608 });
609 };
610 }
8c632f2b 611 function refreshModel() {
50e25421 612 var oldValue = ngModel.$viewValue, newValue = element.select2('val');
8c632f2b 613 if (oldValue != newValue) {
ebfe3efb
TO
614 scope.$parent.$apply(function () {
615 ngModel.$setViewValue(newValue);
8c632f2b 616 });
8c632f2b
TO
617 }
618 }
ebfe3efb 619
8c632f2b
TO
620 function init() {
621 // TODO watch select2-options
8c3a97ed 622 element.crmSelect2(scope.crmUiSelect || {});
c81696a6
CW
623 if (ngModel) {
624 element.on('change', refreshModel);
c81696a6 625 }
8099bfee
CW
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
9ed95c23
CW
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);
8099bfee
CW
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() {
8099bfee
CW
667 // TODO can we infer "entity" from model?
668 element.crmEntityRef(scope.crmEntityref || {});
669 element.on('change', refreshModel);
670 $timeout(ngModel.$render);
8c632f2b 671 }
ebfe3efb 672
8c632f2b
TO
673 init();
674 }
675 };
676 })
677
b4fdf77a 678 // validate multiple email text
679 // usage: <input crm-multiple-email type="text" ng-model="myobj.field" />
680 .directive('crmMultipleEmail', function ($parse, $timeout) {
681 return {
682 require: 'ngModel',
683 link: function(scope, element, attrs, ctrl) {
684 ctrl.$parsers.unshift(function(viewValue) {
685 // if empty value provided simply bypass validation
686 if (_.isEmpty(viewValue)) {
687 ctrl.$setValidity('crmMultipleEmail', true);
688 return viewValue;
689 }
690
691 // split email string on basis of comma
692 var emails = viewValue.split(',');
693 // regex pattern for single email
694 var emailRegex = /\S+@\S+\.\S+/;
695
696 var validityArr = emails.map(function(str){
697 return emailRegex.test(str.trim());
698 });
699
700 if ($.inArray(false, validityArr) > -1) {
701 ctrl.$setValidity('crmMultipleEmail', false);
702 } else {
703 ctrl.$setValidity('crmMultipleEmail', true);
704 }
705 return viewValue;
706 });
707 }
708 };
709 })
b1f92f72 710 // example <div crm-ui-tab id="tab-1" crm-title="ts('My Title')" count="3">...content...</div>
5f3568fd 711 // WISHLIST: use a full Angular component instead of an incomplete jQuery wrapper
030dce01
TO
712 .directive('crmUiTab', function($parse) {
713 return {
5f3568fd
TO
714 require: '^crmUiTabSet',
715 restrict: 'EA',
030dce01 716 scope: {
5f3568fd 717 crmTitle: '@',
cf500087 718 crmIcon: '@',
b1f92f72 719 count: '@',
5f3568fd 720 id: '@'
030dce01 721 },
5f3568fd 722 template: '<div ng-transclude></div>',
030dce01 723 transclude: true,
5f3568fd
TO
724 link: function (scope, element, attrs, crmUiTabSetCtrl) {
725 crmUiTabSetCtrl.add(scope);
726 }
030dce01
TO
727 };
728 })
729
730 // 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>
731 .directive('crmUiTabSet', function() {
732 return {
5f3568fd
TO
733 restrict: 'EA',
734 scope: {
dcb79a31
AS
735 crmUiTabSet: '@',
736 tabSetOptions: '@'
5f3568fd 737 },
ef5d18a1 738 templateUrl: '~/crmUi/tabset.html',
030dce01 739 transclude: true,
5f3568fd
TO
740 controllerAs: 'crmUiTabSetCtrl',
741 controller: function($scope, $parse) {
742 var tabs = $scope.tabs = []; // array<$scope>
743 this.add = function(tab) {
744 if (!tab.id) throw "Tab is missing 'id'";
745 tabs.push(tab);
746 };
747 },
030dce01
TO
748 link: function (scope, element, attrs) {}
749 };
750 })
751
d376f33e 752 // Generic, field-independent form validator.
3afb86ef
TO
753 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" />
754 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" crm-ui-validate-name="myError" />
3afb86ef
TO
755 .directive('crmUiValidate', function() {
756 return {
757 restrict: 'EA',
758 require: 'ngModel',
759 link: function(scope, element, attrs, ngModel) {
760 var validationKey = attrs.crmUiValidateName ? attrs.crmUiValidateName : 'crmUiValidate';
761 scope.$watch(attrs.crmUiValidate, function(newValue){
762 ngModel.$setValidity(validationKey, !!newValue);
763 });
764 }
765 };
766 })
767
e84a11d8
TO
768 // like ng-show, but hides/displays elements using "visibility" which maintains positioning
769 // example <div crm-ui-visible="false">...content...</div>
770 .directive('crmUiVisible', function($parse) {
771 return {
772 restrict: 'EA',
773 scope: {
774 crmUiVisible: '@'
775 },
776 link: function (scope, element, attrs) {
777 var model = $parse(attrs.crmUiVisible);
778 function updatecChildren() {
779 element.css('visibility', model(scope.$parent) ? 'inherit' : 'hidden');
780 }
781 updatecChildren();
782 scope.$parent.$watch(attrs.crmUiVisible, updatecChildren);
783 }
784 };
785 })
786
6717e4b9 787 // 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>
e5df45d2 788 // example with custom nav classes: <div crm-ui-wizard crm-ui-wizard-nav-class="ng-animate-out ...">...</div>
6717e4b9
TO
789 // Note: "myWizardCtrl" has various actions/properties like next() and $first().
790 // WISHLIST: Allow each step to determine if it is "complete" / "valid" / "selectable"
791 // WISHLIST: Allow each step to enable/disable (show/hide) itself
030dce01
TO
792 .directive('crmUiWizard', function() {
793 return {
6717e4b9
TO
794 restrict: 'EA',
795 scope: {
e5df45d2 796 crmUiWizard: '@',
37f1d23b 797 crmUiWizardNavClass: '@' // string, A list of classes that will be added to the nav items
6717e4b9 798 },
ef5d18a1 799 templateUrl: '~/crmUi/wizard.html',
030dce01 800 transclude: true,
6717e4b9
TO
801 controllerAs: 'crmUiWizardCtrl',
802 controller: function($scope, $parse) {
803 var steps = $scope.steps = []; // array<$scope>
804 var crmUiWizardCtrl = this;
805 var maxVisited = 0;
806 var selectedIndex = null;
807
808 var findIndex = function() {
809 var found = null;
810 angular.forEach(steps, function(step, stepKey) {
811 if (step.selected) found = stepKey;
812 });
813 return found;
814 };
815
816 /// @return int the index of the current step
817 this.$index = function() { return selectedIndex; };
818 /// @return bool whether the currentstep is first
819 this.$first = function() { return this.$index() === 0; };
820 /// @return bool whether the current step is last
821 this.$last = function() { return this.$index() === steps.length -1; };
f2bad133 822 this.$maxVisit = function() { return maxVisited; };
3f0da451 823 this.$validStep = function() {
f8c05c87 824 return steps[selectedIndex] && steps[selectedIndex].isStepValid();
3f0da451 825 };
6717e4b9
TO
826 this.iconFor = function(index) {
827 if (index < this.$index()) return '√';
828 if (index === this.$index()) return '»';
829 return ' ';
f2bad133 830 };
6717e4b9
TO
831 this.isSelectable = function(step) {
832 if (step.selected) return false;
5919adff 833 return this.$validStep();
6717e4b9
TO
834 };
835
836 /*** @param Object step the $scope of the step */
837 this.select = function(step) {
838 angular.forEach(steps, function(otherStep, otherKey) {
839 otherStep.selected = (otherStep === step);
840 if (otherStep === step && maxVisited < otherKey) maxVisited = otherKey;
841 });
842 selectedIndex = findIndex();
843 };
844 /*** @param Object step the $scope of the step */
845 this.add = function(step) {
846 if (steps.length === 0) {
847 step.selected = true;
848 selectedIndex = 0;
849 }
850 steps.push(step);
8688b463
TO
851 steps.sort(function(a,b){
852 return a.crmUiWizardStep - b.crmUiWizardStep;
853 });
854 selectedIndex = findIndex();
855 };
856 this.remove = function(step) {
857 var key = null;
858 angular.forEach(steps, function(otherStep, otherKey) {
859 if (otherStep === step) key = otherKey;
860 });
4109d03e 861 if (key !== null) {
8688b463
TO
862 steps.splice(key, 1);
863 }
6717e4b9
TO
864 };
865 this.goto = function(index) {
866 if (index < 0) index = 0;
867 if (index >= steps.length) index = steps.length-1;
868 this.select(steps[index]);
869 };
870 this.previous = function() { this.goto(this.$index()-1); };
871 this.next = function() { this.goto(this.$index()+1); };
872 if ($scope.crmUiWizard) {
f2bad133 873 $parse($scope.crmUiWizard).assign($scope.$parent, this);
6717e4b9
TO
874 }
875 },
c4991710
TO
876 link: function (scope, element, attrs) {
877 scope.ts = CRM.ts(null);
510eb730
FG
878
879 element.find('.crm-wizard-buttons button').click(function () {
880 // These values are captured inside the click handler to ensure the
881 // positions/sizes of the elements are captured at the time of the
882 // click vs. at the time this directive is initialized.
883 var topOfWizard = element.offset().top;
884 var heightOfMenu = $('#civicrm-menu').height() || 0;
885
886 $('html')
887 // stop any other animations that might be happening...
888 .stop()
889 // gracefully slide the user to the top of the wizard
890 .animate({scrollTop: topOfWizard - heightOfMenu}, 1000);
891 });
c4991710 892 }
030dce01
TO
893 };
894 })
895
6717e4b9
TO
896 // Use this to add extra markup to wizard
897 .directive('crmUiWizardButtons', function() {
030dce01 898 return {
6717e4b9
TO
899 require: '^crmUiWizard',
900 restrict: 'EA',
901 scope: {},
902 template: '<span ng-transclude></span>',
030dce01 903 transclude: true,
6717e4b9
TO
904 link: function (scope, element, attrs, crmUiWizardCtrl) {
905 var realButtonsEl = $(element).closest('.crm-wizard').find('.crm-wizard-buttons');
906 $(element).appendTo(realButtonsEl);
907 }
030dce01
TO
908 };
909 })
910
77ec5a8d
AH
911 // Example for Font Awesome: <button crm-icon="fa-check">Save</button>
912 // Example for jQuery UI (deprecated): <button crm-icon="check">Save</button>
39f4f54f
CW
913 .directive('crmIcon', function() {
914 return {
915 restrict: 'EA',
39f4f54f 916 link: function (scope, element, attrs) {
cf500087
CW
917 if (element.is('[crm-ui-tab]')) {
918 // handled in crmUiTab ctrl
919 return;
920 }
aee84611
AH
921 if (attrs.crmIcon.substring(0,3) == 'fa-') {
922 $(element).prepend('<i class="crm-i ' + attrs.crmIcon + '"></i> ');
923 }
924 else {
925 $(element).prepend('<span class="icon ui-icon-' + attrs.crmIcon + '"></span> ');
926 }
39f4f54f
CW
927 if ($(element).is('button')) {
928 $(element).addClass('crm-button');
929 }
930 }
931 };
932 })
933
3f0da451 934 // example: <div crm-ui-wizard-step crm-title="ts('My Title')" ng-form="mySubForm">...content...</div>
8688b463
TO
935 // If there are any conditional steps, then be sure to set a weight explicitly on *all* steps to maintain ordering.
936 // example: <div crm-ui-wizard-step="100" crm-title="..." ng-if="...">...content...</div>
1302b0a0 937 // example with custom classes: <div crm-ui-wizard-step="100" crm-ui-wizard-step-class="ng-animate-out ...">...content...</div>
030dce01 938 .directive('crmUiWizardStep', function() {
8688b463 939 var nextWeight = 1;
030dce01 940 return {
3f0da451 941 require: ['^crmUiWizard', 'form'],
6717e4b9 942 restrict: 'EA',
030dce01 943 scope: {
8688b463 944 crmTitle: '@', // expression, evaluates to a printable string
37f1d23b
TL
945 crmUiWizardStep: '@', // int, a weight which determines the ordering of the steps
946 crmUiWizardStepClass: '@' // string, A list of classes that will be added to the template
030dce01 947 },
1302b0a0 948 template: '<div class="crm-wizard-step {{crmUiWizardStepClass}}" ng-show="selected" ng-transclude/></div>',
030dce01 949 transclude: true,
3f0da451
TO
950 link: function (scope, element, attrs, ctrls) {
951 var crmUiWizardCtrl = ctrls[0], form = ctrls[1];
8688b463
TO
952 if (scope.crmUiWizardStep) {
953 scope.crmUiWizardStep = parseInt(scope.crmUiWizardStep);
954 } else {
955 scope.crmUiWizardStep = nextWeight++;
956 }
3f0da451
TO
957 scope.isStepValid = function() {
958 return form.$valid;
959 };
6717e4b9 960 crmUiWizardCtrl.add(scope);
e72fdb99 961 scope.$on('$destroy', function(){
8688b463
TO
962 crmUiWizardCtrl.remove(scope);
963 });
6717e4b9 964 }
030dce01
TO
965 };
966 })
967
5fb5b3cf 968 // Example: <button crm-confirm="{message: ts('Are you sure you want to continue?')}" on-yes="frobnicate(123)">Frobincate</button>
4b8c8b42 969 // Example: <button crm-confirm="{type: 'disable', obj: myObject}" on-yes="myObject.is_active=0; myObject.save()">Disable</button>
6a6d0f41
TO
970 // Example: <button crm-confirm="{templateUrl: '~/path/to/view.html', export: {foo: bar}}" on-yes="frobnicate(123)">Frobincate</button>
971 .directive('crmConfirm', function ($compile, $rootScope, $templateRequest, $q) {
88fcc9f1 972 // Helpers to calculate default options for CRM.confirm()
4b8c8b42
TO
973 var defaultFuncs = {
974 'disable': function (options) {
975 return {
976 message: ts('Are you sure you want to disable this?'),
977 options: {no: ts('Cancel'), yes: ts('Disable')},
978 width: 300,
979 title: ts('Disable %1?', {
980 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
981 })
982 };
983 },
470a458e
TO
984 'revert': function (options) {
985 return {
986 message: ts('Are you sure you want to revert this?'),
987 options: {no: ts('Cancel'), yes: ts('Revert')},
988 width: 300,
989 title: ts('Revert %1?', {
990 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
991 })
992 };
993 },
4b8c8b42
TO
994 'delete': function (options) {
995 return {
996 message: ts('Are you sure you want to delete this?'),
997 options: {no: ts('Cancel'), yes: ts('Delete')},
998 width: 300,
999 title: ts('Delete %1?', {
1000 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
1001 })
1002 };
1003 }
1004 };
6a6d0f41 1005 var confirmCount = 0;
4b8c8b42 1006 return {
4b8c8b42
TO
1007 link: function (scope, element, attrs) {
1008 $(element).click(function () {
f2bad133 1009 var options = scope.$eval(attrs.crmConfirm);
b8603a6d
CW
1010 if (attrs.title && !options.title) {
1011 options.title = attrs.title;
1012 }
4b8c8b42 1013 var defaults = (options.type) ? defaultFuncs[options.type](options) : {};
6a6d0f41
TO
1014
1015 var tpl = null, stubId = null;
1016 if (!options.message) {
1017 if (options.templateUrl) {
1018 tpl = $templateRequest(options.templateUrl);
1019 }
1020 else if (options.template) {
1021 tpl = options.template;
1022 }
1023 if (tpl) {
1024 stubId = 'crmUiConfirm_' + (++confirmCount);
1025 options.message = '<div id="' + stubId + '"></div>';
1026 }
1027 }
1028
4b8c8b42 1029 CRM.confirm(_.extend(defaults, options))
6a6d0f41
TO
1030 .on('crmConfirm:yes', function() { scope.$apply(attrs.onYes); })
1031 .on('crmConfirm:no', function() { scope.$apply(attrs.onNo); });
1032
1033 if (tpl && stubId) {
1034 $q.when(tpl, function(html) {
1035 var scope = options.scope || $rootScope.$new();
1036 if (options.export) {
1037 angular.extend(scope, options.export);
1038 }
1039 var linker = $compile(html);
1040 $('#' + stubId).append($(linker(scope)));
1041 });
1042 }
4b8c8b42
TO
1043 });
1044 }
1045 };
1046 })
835fcb5e 1047
826f5ace 1048 // Sets document title & page title; attempts to override CMS title markup for the latter
835fcb5e 1049 // WARNING: Use only once per route!
826f5ace
CW
1050 // Example (same title for both): <h1 crm-page-title>{{ts('Hello')}}</h1>
1051 // Example (separate document title): <h1 crm-document-title="ts('Hello')" crm-page-title><i class="crm-i fa-flag"></i>{{ts('Hello')}}</h1>
1052 .directive('crmPageTitle', function($timeout) {
835fcb5e 1053 return {
826f5ace
CW
1054 scope: {
1055 crmDocumentTitle: '='
1056 },
835fcb5e
CW
1057 link: function(scope, $el, attrs) {
1058 function update() {
1059 $timeout(function() {
826f5ace 1060 var newPageTitle = _.trim($el.html()),
3a603b78 1061 newDocumentTitle = scope.crmDocumentTitle || $el.text();
826f5ace 1062 document.title = $('title').text().replace(documentTitle, newDocumentTitle);
835fcb5e
CW
1063 // If the CMS has already added title markup to the page, use it
1064 $('h1').not('.crm-container h1').each(function() {
826f5ace 1065 if (_.trim($(this).html()) === pageTitle) {
1d924612 1066 $(this).addClass('crm-page-title').html(newPageTitle);
835fcb5e
CW
1067 $el.hide();
1068 }
1069 });
826f5ace
CW
1070 pageTitle = newPageTitle;
1071 documentTitle = newDocumentTitle;
835fcb5e
CW
1072 });
1073 }
1074
826f5ace 1075 scope.$watch(function() {return scope.crmDocumentTitle + $el.html();}, update);
835fcb5e 1076 }
7565f24a 1077 };
835fcb5e
CW
1078 })
1079
02308c07
TO
1080 .run(function($rootScope, $location) {
1081 /// Example: <button ng-click="goto('home')">Go home!</button>
1082 $rootScope.goto = function(path) {
1083 $location.path(path);
1084 };
4b8c8b42 1085 // useful for debugging: $rootScope.log = console.log || function() {};
02308c07 1086 })
685acae4 1087 ;
1088
5fb5b3cf 1089})(angular, CRM.$, CRM._);