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