1 /// crmUi: Sundry UI helpers
2 (function (angular
, $, _
) {
6 documentTitle
= 'CiviCRM';
8 angular
.module('crmUi', CRM
.angRequires('crmUi'))
10 // example <div crm-ui-accordion crm-title="ts('My Title')" crm-collapsed="true">...content...</div>
11 // WISHLIST: crmCollapsed should support two-way/continuous binding
12 .directive('crmUiAccordion', function() {
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>',
19 link: function (scope
, element
, attrs
) {
21 'crm-accordion-wrapper': true,
22 collapsed
: scope
.crmUiAccordion
.collapsed
25 scope
.$watch('crmUiAccordion', function(crmUiAccordion
) {
26 if (crmUiAccordion
&& crmUiAccordion
.help
) {
27 scope
.help
= crmUiAccordion
.help
.clone({}, {
28 title
: crmUiAccordion
.title
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()});
41 .service('crmUiAlert', function($compile
, $rootScope
, $templateRequest
, $q
) {
43 return function crmUiAlert(params
) {
44 var id
= 'crmUiAlert_' + (++count
);
46 if (params
.templateUrl
) {
47 tpl
= $templateRequest(params
.templateUrl
);
49 else if (params
.template
) {
50 tpl
= params
.template
;
53 params
.text
= '<div id="' + id
+ '"></div>'; // temporary stub
55 var result
= CRM
.alert(params
.text
, params
.title
, params
.type
, params
.options
);
57 $q
.when(tpl
, function(html
) {
58 var scope
= params
.scope
|| $rootScope
.$new();
59 var linker
= $compile(html
);
60 $('#' + id
).append($(linker(scope
)));
67 // Simple wrapper around $.crmDatepicker.
68 // example with no time input: <input crm-ui-datepicker="{time: false}" ng-model="myobj.datefield"/>
69 // example with custom date format: <input crm-ui-datepicker="{date: 'm/d/y'}" ng-model="myobj.datefield"/>
70 .directive('crmUiDatepicker', function () {
77 link: function (scope
, element
, attrs
, ngModel
) {
78 ngModel
.$render = function () {
79 element
.val(ngModel
.$viewValue
).change();
83 .crmDatepicker(scope
.crmUiDatepicker
)
84 .on('change', function() {
85 var requiredLength
= 19;
86 if (scope
.crmUiDatepicker
&& scope
.crmUiDatepicker
.time
=== false) {
89 if (scope
.crmUiDatepicker
&& scope
.crmUiDatepicker
.date
=== false) {
92 ngModel
.$setValidity('incompleteDateTime', !($(this).val().length
&& $(this).val().length
!== requiredLength
));
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
) {
107 template: function() {
108 var args
= $location
.search();
109 return (args
&& args
.angularDebug
) ? '<div crm-ui-accordion=\'{title: ts("Debug (%1)", {1: crmUiDebug}), collapsed: true}\'><pre>{{data|json}}</pre></div>' : '';
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
) {
123 // Display a field/row in a field list
124 // example: <div crm-ui-field="{title: ts('My Field')}"> {{mydata}} </div>
125 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field')}"> <input crm-ui-id="subform.myfield" name="myfield" /> </div>
126 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field')}"> <input crm-ui-id="subform.myfield" name="myfield" required /> </div>
127 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field'), help: hs('help_field_name'), required: true}"> {{mydata}} </div>
128 .directive('crmUiField', function() {
129 // Note: When writing new templates, the "label" position is particular. See/patch "var label" below.
131 default: '~/crmUi/field.html',
132 checkbox
: '~/crmUi/field-cb.html'
136 require
: '^crmUiIdScope',
139 // {title, name, help, helpFile}
142 templateUrl: function(tElement
, tAttrs
){
143 var layout
= tAttrs
.crmLayout
? tAttrs
.crmLayout
: 'default';
144 return templateUrls
[layout
];
147 link: function (scope
, element
, attrs
, crmUiIdCtrl
) {
148 $(element
).addClass('crm-section');
150 scope
.$watch('crmUiField', function(crmUiField
) {
151 if (crmUiField
&& crmUiField
.help
) {
152 scope
.help
= crmUiField
.help
.clone({}, {
153 title
: crmUiField
.title
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 () {
164 require
: '^crmUiIdScope',
167 pre: function (scope
, element
, attrs
, crmUiIdCtrl
) {
168 var id
= crmUiIdCtrl
.get(attrs
.crmUiId
);
169 element
.attr('id', id
);
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
;
181 angular
.extend(FieldHelp
.prototype, {
183 return this.options
[n
];
185 open
: function open() {
186 CRM
.help(this.options
.title
, {id
: this.options
.id
, file
: this.options
.file
});
188 clone
: function clone(options
, defaults
) {
189 return new FieldHelp(angular
.extend({}, defaults
, this.options
, options
));
193 // example: var hs = crmUiHelp({file: 'CRM/Foo/Bar'});
194 return function(defaults
){
195 // example: hs('myfield')
196 // example: hs({id: 'myfield', title: 'Foo Bar', file: 'Whiz/Bang'})
197 return function(options
) {
198 if (_
.isString(options
)) {
199 options
= {id
: options
};
201 return new FieldHelp(angular
.extend({}, defaults
, options
));
206 // Display a help icon
207 // Example: Use a default *.hlp file
208 // scope.hs = crmUiHelp({file: 'Path/To/Help/File'});
209 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field'})">
210 // Example: Use an explicit *.hlp file
211 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field', file:'CRM/Foo/Bar'})">
212 .directive('crmUiHelp', function() {
215 link: function(scope
, element
, attrs
) {
216 setTimeout(function() {
217 var crmUiHelp
= scope
.$eval(attrs
.crmUiHelp
);
218 var title
= crmUiHelp
&& crmUiHelp
.get('title') ? ts('%1 Help', {1: crmUiHelp
.get('title')}) : ts('Help');
219 element
.attr('title', title
);
223 .addClass('helpicon')
225 .on('click', function(e
) {
227 scope
.$eval(attrs
.crmUiHelp
).open();
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
) {
236 require
: '^crmUiIdScope',
238 template
: '<span ng-class="cssClasses"><span ng-transclude/><span crm-ui-visible="crmIsRequired" class="crm-marker" title="This field is required.">*</span></span>',
240 link: function (scope
, element
, attrs
, crmUiIdCtrl
) {
241 scope
.crmIsRequired
= false;
242 scope
.cssClasses
= {};
244 if (!attrs
.crmUiFor
) return;
246 var id
= crmUiIdCtrl
.get(attrs
.crmUiFor
);
247 element
.attr('for', id
);
250 var updateCss = function () {
251 scope
.cssClasses
['crm-error'] = !ngModel
.$valid
&& !ngModel
.$pristine
;
254 // Note: if target element is dynamically generated (eg via ngInclude), then it may not be available
255 // immediately for initialization. Use retries/retryDelay to initialize such elements.
256 var init = function (retries
, retryDelay
) {
257 var input
= $('#' + id
);
258 if (input
.length
=== 0 && !attrs
.crmUiForceRequired
) {
261 init(retries
-1, retryDelay
);
267 if (attrs
.crmUiForceRequired
) {
268 scope
.crmIsRequired
= true;
272 var tgtScope
= scope
;//.$parent;
273 if (attrs
.crmDepth
) {
274 for (var i
= attrs
.crmDepth
; i
> 0; i
--) {
275 tgtScope
= tgtScope
.$parent
;
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
;
286 scope
.crmIsRequired
= input
.prop('required');
289 ngModel
= $parse(attrs
.crmUiFor
)(tgtScope
);
291 ngModel
.$viewChangeListeners
.push(updateCss
);
302 // Define a scope in which a name like "subform.foo" maps to a unique ID.
303 // example: <div ng-form="subform" crm-ui-id-scope><label crm-ui-for="subform.foo">Foo:</label><input crm-ui-id="subform.foo" name="foo"/></div>
304 .directive('crmUiIdScope', function () {
308 controllerAs
: 'crmUiIdCtrl',
309 controller: function($scope
) {
311 this.get = function(name
) {
313 ids
[name
] = "crmUiId_" + (++uidCount
);
318 link: function (scope
, element
, attrs
) {}
322 // Display an HTML blurb inside an IFRAME.
323 // example: <iframe crm-ui-iframe="getHtmlContent()"></iframe>
324 // example: <iframe crm-ui-iframe crm-ui-iframe-src="getUrl()"></iframe>
325 .directive('crmUiIframe', function ($parse
) {
328 crmUiIframeSrc
: '@', // expression which evaluates to a URL
329 crmUiIframe
: '@' // expression which evaluates to HTML content
331 link: function (scope
, elm
, attrs
) {
332 var iframe
= $(elm
)[0];
333 iframe
.setAttribute('width', '100%');
334 iframe
.setAttribute('height', '250px');
335 iframe
.setAttribute('frameborder', '0');
337 var refresh = function () {
338 if (attrs
.crmUiIframeSrc
) {
339 iframe
.setAttribute('src', scope
.$parent
.$eval(attrs
.crmUiIframeSrc
));
342 var iframeHtml
= scope
.$parent
.$eval(attrs
.crmUiIframe
);
344 var doc
= iframe
.document
;
345 if (iframe
.contentDocument
) {
346 doc
= iframe
.contentDocument
;
348 else if (iframe
.contentWindow
) {
349 doc
= iframe
.contentWindow
.document
;
353 doc
.writeln(iframeHtml
);
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');
364 $(elm
).parent().on('dialogresize', function(e
, ui
) {
365 iframe
.setAttribute('class', 'resized');
368 scope
.$parent
.$watch(attrs
.crmUiIframe
, refresh
);
374 // <a ng-click="$broadcast('my-insert-target', 'some new text')>Insert</a>
375 // <textarea crm-ui-insert-rx='my-insert-target'></textarea>
376 .directive('crmUiInsertRx', function() {
378 link: function(scope
, element
, attrs
) {
379 scope
.$on(attrs
.crmUiInsertRx
, function(e
, tokenName
) {
380 CRM
.wysiwyg
.insert(element
, tokenName
);
381 $(element
).select2('close').select2('val', '');
382 CRM
.wysiwyg
.focus(element
);
388 // Define a rich text editor.
389 // example: <textarea crm-ui-id="myForm.body_html" crm-ui-richtext name="body_html" ng-model="mailing.body_html"></textarea>
390 .directive('crmUiRichtext', function ($timeout
) {
393 link: function (scope
, elm
, attr
, ngModel
) {
395 var editor
= CRM
.wysiwyg
.create(elm
);
401 $(elm
).on('blur', function() {
402 $timeout(function() {
403 scope
.$eval(attr
.ngBlur
);
408 ngModel
.$render = function(value
) {
409 editor
.done(function() {
410 CRM
.wysiwyg
.setVal(elm
, ngModel
.$viewValue
|| '');
417 // Display a lock icon (based on a boolean).
418 // example: <a crm-ui-lock binding="mymodel.boolfield"></a>
419 // example: <a crm-ui-lock
420 // binding="mymodel.boolfield"
421 // title-locked="ts('Boolfield is locked')"
422 // title-unlocked="ts('Boolfield is unlocked')"></a>
423 .directive('crmUiLock', function ($parse
, $rootScope
) {
424 var defaultVal = function (defaultValue
) {
425 var f = function (scope
) {
428 f
.assign = function (scope
, value
) {
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
);
441 link: function (scope
, element
, attrs
) {
442 var binding
= parse(attrs
.binding
, true);
443 var titleLocked
= parse(attrs
.titleLocked
, ts('Locked'));
444 var titleUnlocked
= parse(attrs
.titleUnlocked
, ts('Unlocked'));
446 $(element
).addClass('crm-i lock-button');
447 var refresh = function () {
448 var locked
= binding(scope
);
451 .removeClass('fa-unlock')
453 .prop('title', titleLocked(scope
))
458 .removeClass('fa-lock')
459 .addClass('fa-unlock')
460 .prop('title', titleUnlocked(scope
))
465 $(element
).click(function () {
466 binding
.assign(scope
, !binding(scope
));
468 $rootScope
.$digest();
471 scope
.$watch(attrs
.binding
, refresh
);
472 scope
.$watch(attrs
.titleLocked
, refresh
);
473 scope
.$watch(attrs
.titleUnlocked
, refresh
);
480 // CrmUiOrderCtrl is a controller class which manages sort orderings.
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(){
488 function CrmUiOrderCtrl(defaults
){
489 this.values
= defaults
;
491 angular
.extend(CrmUiOrderCtrl
.prototype, {
492 get: function get() {
495 getDir
: function getDir(name
) {
496 if (this.values
.indexOf(name
) >= 0 || this.values
.indexOf('+' + name
) >= 0) {
499 if (this.values
.indexOf('-' + name
) >= 0) {
504 // @return bool TRUE if something is removed
505 remove
: function remove(name
) {
506 var idx
= this.values
.indexOf(name
);
508 this.values
.splice(idx
, 1);
515 setDir
: function setDir(name
, dir
) {
516 return this.toggle(name
, dir
);
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
!== '') {
523 if (this.remove(name
) || this.remove('+' + name
)) {
526 if (this.remove('-' + name
)) {
532 this.values
.unshift('+' + name
);
534 else if (next
== '-') {
535 this.values
.unshift('-' + name
);
539 return CrmUiOrderCtrl
;
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.
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
) {
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
);
558 // For usage, see crmUiOrder (above)
559 .directive('crmUiOrderBy', function() {
561 link: function(scope
, element
, attrs
) {
562 function updateClass(crmUiOrderCtrl
, name
) {
563 var dir
= crmUiOrderCtrl
.getDir(name
);
565 .toggleClass('sorting_asc', dir
=== '+')
566 .toggleClass('sorting_desc', dir
=== '-')
567 .toggleClass('sorting', dir
=== '');
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]);
578 var tgt
= scope
.$eval(attrs
.crmUiOrderBy
);
579 updateClass(tgt
[0], tgt
[1]);
584 // Display a fancy SELECT (based on select2).
585 // usage: <select crm-ui-select="{placeholder:'Something',allowClear:true,...}" ng-model="myobj.field"><option...></select>
586 .directive('crmUiSelect', function ($parse
, $timeout
) {
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.
598 ngModel
.$render = function () {
599 $timeout(function () {
600 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
601 // new item is added before selection is made
602 var newVal
= _
.cloneDeep(ngModel
.$modelValue
);
603 // Fix possible data-type mismatch
604 if (typeof newVal
=== 'string' && element
.select2('container').hasClass('select2-container-multi')) {
605 newVal
= newVal
.length
? newVal
.split(',') : [];
607 element
.select2('val', newVal
);
611 function refreshModel() {
612 var oldValue
= ngModel
.$viewValue
, newValue
= element
.select2('val');
613 if (oldValue
!= newValue
) {
614 scope
.$parent
.$apply(function () {
615 ngModel
.$setViewValue(newValue
);
621 // TODO watch select2-options
622 element
.crmSelect2(scope
.crmUiSelect
|| {});
624 element
.on('change', refreshModel
);
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
) {
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.
645 ngModel
.$render = function () {
646 $timeout(function () {
647 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
648 // new item is added before selection is made
649 var newVal
= _
.cloneDeep(ngModel
.$modelValue
);
650 // Fix possible data-type mismatch
651 if (typeof newVal
=== 'string' && element
.select2('container').hasClass('select2-container-multi')) {
652 newVal
= newVal
.length
? newVal
.split(',') : [];
654 element
.select2('val', newVal
);
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
);
667 // TODO can we infer "entity" from model?
668 element
.crmEntityRef(scope
.crmEntityref
|| {});
669 element
.on('change', refreshModel
);
670 $timeout(ngModel
.$render
);
678 // validate multiple email text
679 // usage: <input crm-multiple-email type="text" ng-model="myobj.field" />
680 .directive('crmMultipleEmail', function ($parse
, $timeout
) {
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);
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+/;
696 var validityArr
= emails
.map(function(str
){
697 return emailRegex
.test(str
.trim());
700 if ($.inArray(false, validityArr
) > -1) {
701 ctrl
.$setValidity('crmMultipleEmail', false);
703 ctrl
.$setValidity('crmMultipleEmail', true);
710 // example <div crm-ui-tab id="tab-1" crm-title="ts('My Title')" count="3">...content...</div>
711 // WISHLIST: use a full Angular component instead of an incomplete jQuery wrapper
712 .directive('crmUiTab', function($parse
) {
714 require
: '^crmUiTabSet',
722 template
: '<div ng-transclude></div>',
724 link: function (scope
, element
, attrs
, crmUiTabSetCtrl
) {
725 crmUiTabSetCtrl
.add(scope
);
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() {
738 templateUrl
: '~/crmUi/tabset.html',
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'";
748 link: function (scope
, element
, attrs
) {}
752 // Generic, field-independent form validator.
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" />
755 .directive('crmUiValidate', function() {
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
);
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
) {
776 link: function (scope
, element
, attrs
) {
777 var model
= $parse(attrs
.crmUiVisible
);
778 function updatecChildren() {
779 element
.css('visibility', model(scope
.$parent
) ? 'inherit' : 'hidden');
782 scope
.$parent
.$watch(attrs
.crmUiVisible
, updatecChildren
);
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>
788 // example with custom nav classes: <div crm-ui-wizard crm-ui-wizard-nav-class="ng-animate-out ...">...</div>
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
792 .directive('crmUiWizard', function() {
797 crmUiWizardNavClass
: '@' // string, A list of classes that will be added to the nav items
799 templateUrl
: '~/crmUi/wizard.html',
801 controllerAs
: 'crmUiWizardCtrl',
802 controller: function($scope
, $parse
) {
803 var steps
= $scope
.steps
= []; // array<$scope>
804 var crmUiWizardCtrl
= this;
806 var selectedIndex
= null;
808 var findIndex = function() {
810 angular
.forEach(steps
, function(step
, stepKey
) {
811 if (step
.selected
) found
= stepKey
;
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; };
822 this.$maxVisit = function() { return maxVisited
; };
823 this.$validStep = function() {
824 return steps
[selectedIndex
] && steps
[selectedIndex
].isStepValid();
826 this.iconFor = function(index
) {
827 if (index
< this.$index()) return '√';
828 if (index
=== this.$index()) return '»';
831 this.isSelectable = function(step
) {
832 if (step
.selected
) return false;
833 return this.$validStep();
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
;
842 selectedIndex
= findIndex();
844 /*** @param Object step the $scope of the step */
845 this.add = function(step
) {
846 if (steps
.length
=== 0) {
847 step
.selected
= true;
851 steps
.sort(function(a
,b
){
852 return a
.crmUiWizardStep
- b
.crmUiWizardStep
;
854 selectedIndex
= findIndex();
856 this.remove = function(step
) {
858 angular
.forEach(steps
, function(otherStep
, otherKey
) {
859 if (otherStep
=== step
) key
= otherKey
;
862 steps
.splice(key
, 1);
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
]);
870 this.previous = function() { this.goto(this.$index()-1); };
871 this.next = function() { this.goto(this.$index()+1); };
872 if ($scope
.crmUiWizard
) {
873 $parse($scope
.crmUiWizard
).assign($scope
.$parent
, this);
876 link: function (scope
, element
, attrs
) {
877 scope
.ts
= CRM
.ts(null);
882 // Use this to add extra markup to wizard
883 .directive('crmUiWizardButtons', function() {
885 require
: '^crmUiWizard',
888 template
: '<span ng-transclude></span>',
890 link: function (scope
, element
, attrs
, crmUiWizardCtrl
) {
891 var realButtonsEl
= $(element
).closest('.crm-wizard').find('.crm-wizard-buttons');
892 $(element
).appendTo(realButtonsEl
);
897 // Example for Font Awesome: <button crm-icon="fa-check">Save</button>
898 // Example for jQuery UI (deprecated): <button crm-icon="check">Save</button>
899 .directive('crmIcon', function() {
902 link: function (scope
, element
, attrs
) {
903 if (element
.is('[crm-ui-tab]')) {
904 // handled in crmUiTab ctrl
907 if (attrs
.crmIcon
.substring(0,3) == 'fa-') {
908 $(element
).prepend('<i class="crm-i ' + attrs
.crmIcon
+ '"></i> ');
911 $(element
).prepend('<span class="icon ui-icon-' + attrs
.crmIcon
+ '"></span> ');
913 if ($(element
).is('button')) {
914 $(element
).addClass('crm-button');
920 // example: <div crm-ui-wizard-step crm-title="ts('My Title')" ng-form="mySubForm">...content...</div>
921 // If there are any conditional steps, then be sure to set a weight explicitly on *all* steps to maintain ordering.
922 // example: <div crm-ui-wizard-step="100" crm-title="..." ng-if="...">...content...</div>
923 // example with custom classes: <div crm-ui-wizard-step="100" crm-ui-wizard-step-class="ng-animate-out ...">...content...</div>
924 .directive('crmUiWizardStep', function() {
927 require
: ['^crmUiWizard', 'form'],
930 crmTitle
: '@', // expression, evaluates to a printable string
931 crmUiWizardStep
: '@', // int, a weight which determines the ordering of the steps
932 crmUiWizardStepClass
: '@' // string, A list of classes that will be added to the template
934 template
: '<div class="crm-wizard-step {{crmUiWizardStepClass}}" ng-show="selected" ng-transclude/></div>',
936 link: function (scope
, element
, attrs
, ctrls
) {
937 var crmUiWizardCtrl
= ctrls
[0], form
= ctrls
[1];
938 if (scope
.crmUiWizardStep
) {
939 scope
.crmUiWizardStep
= parseInt(scope
.crmUiWizardStep
);
941 scope
.crmUiWizardStep
= nextWeight
++;
943 scope
.isStepValid = function() {
946 crmUiWizardCtrl
.add(scope
);
947 scope
.$on('$destroy', function(){
948 crmUiWizardCtrl
.remove(scope
);
954 // Example: <button crm-confirm="{message: ts('Are you sure you want to continue?')}" on-yes="frobnicate(123)">Frobincate</button>
955 // Example: <button crm-confirm="{type: 'disable', obj: myObject}" on-yes="myObject.is_active=0; myObject.save()">Disable</button>
956 // Example: <button crm-confirm="{templateUrl: '~/path/to/view.html', export: {foo: bar}}" on-yes="frobnicate(123)">Frobincate</button>
957 .directive('crmConfirm', function ($compile
, $rootScope
, $templateRequest
, $q
) {
958 // Helpers to calculate default options for CRM.confirm()
960 'disable': function (options
) {
962 message
: ts('Are you sure you want to disable this?'),
963 options
: {no
: ts('Cancel'), yes
: ts('Disable')},
965 title
: ts('Disable %1?', {
966 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
970 'revert': function (options
) {
972 message
: ts('Are you sure you want to revert this?'),
973 options
: {no
: ts('Cancel'), yes
: ts('Revert')},
975 title
: ts('Revert %1?', {
976 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
980 'delete': function (options
) {
982 message
: ts('Are you sure you want to delete this?'),
983 options
: {no
: ts('Cancel'), yes
: ts('Delete')},
985 title
: ts('Delete %1?', {
986 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
991 var confirmCount
= 0;
993 link: function (scope
, element
, attrs
) {
994 $(element
).click(function () {
995 var options
= scope
.$eval(attrs
.crmConfirm
);
996 if (attrs
.title
&& !options
.title
) {
997 options
.title
= attrs
.title
;
999 var defaults
= (options
.type
) ? defaultFuncs
[options
.type
](options
) : {};
1001 var tpl
= null, stubId
= null;
1002 if (!options
.message
) {
1003 if (options
.templateUrl
) {
1004 tpl
= $templateRequest(options
.templateUrl
);
1006 else if (options
.template
) {
1007 tpl
= options
.template
;
1010 stubId
= 'crmUiConfirm_' + (++confirmCount
);
1011 options
.message
= '<div id="' + stubId
+ '"></div>';
1015 CRM
.confirm(_
.extend(defaults
, options
))
1016 .on('crmConfirm:yes', function() { scope
.$apply(attrs
.onYes
); })
1017 .on('crmConfirm:no', function() { scope
.$apply(attrs
.onNo
); });
1019 if (tpl
&& stubId
) {
1020 $q
.when(tpl
, function(html
) {
1021 var scope
= options
.scope
|| $rootScope
.$new();
1022 if (options
.export) {
1023 angular
.extend(scope
, options
.export);
1025 var linker
= $compile(html
);
1026 $('#' + stubId
).append($(linker(scope
)));
1034 // Sets document title & page title; attempts to override CMS title markup for the latter
1035 // WARNING: Use only once per route!
1036 // Example (same title for both): <h1 crm-page-title>{{ts('Hello')}}</h1>
1037 // Example (separate document title): <h1 crm-document-title="ts('Hello')" crm-page-title><i class="crm-i fa-flag"></i>{{ts('Hello')}}</h1>
1038 .directive('crmPageTitle', function($timeout
) {
1041 crmDocumentTitle
: '='
1043 link: function(scope
, $el
, attrs
) {
1045 $timeout(function() {
1046 var newPageTitle
= _
.trim($el
.html()),
1047 newDocumentTitle
= scope
.crmDocumentTitle
|| $el
.text();
1048 document
.title
= $('title').text().replace(documentTitle
, newDocumentTitle
);
1049 // If the CMS has already added title markup to the page, use it
1050 $('h1').not('.crm-container h1').each(function() {
1051 if (_
.trim($(this).html()) === pageTitle
) {
1052 $(this).addClass('crm-page-title').html(newPageTitle
);
1056 pageTitle
= newPageTitle
;
1057 documentTitle
= newDocumentTitle
;
1061 scope
.$watch(function() {return scope
.crmDocumentTitle
+ $el
.html();}, update
);
1066 .run(function($rootScope
, $location
) {
1067 /// Example: <button ng-click="goto('home')">Go home!</button>
1068 $rootScope
.goto = function(path
) {
1069 $location
.path(path
);
1071 // useful for debugging: $rootScope.log = console.log || function() {};
1075 })(angular
, CRM
.$, CRM
._
);