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