1 /// crmUi: Sundry UI helpers
2 (function (angular
, $, _
) {
6 angular
.module('crmUi', [])
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() {
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>',
18 link: function (scope
, element
, attrs
) {
20 collapsed
: scope
.$parent
.$eval(attrs
.crmCollapsed
)
26 // example: <input crm-ui-date="myobj.datefield" />
27 // example: <input crm-ui-date="myobj.datefield" crm-ui-date-format="yy-mm-dd" />
28 .directive('crmUiDate', function ($parse
, $timeout
) {
32 crmUiDate
: '@', // expression, model binding
33 crmUiDateFormat
: '@' // expression, date format (default: "yy-mm-dd")
35 link: function (scope
, element
, attrs
) {
36 var fmt
= attrs
.crmUiDateFormat
? $parse(attrs
.crmUiDateFormat
)() : "yy-mm-dd";
37 var model
= $parse(attrs
.crmUiDate
);
39 element
.addClass('dateplugin');
40 $(element
).datepicker({
44 var updateChildren
= (function() {
45 element
.off('change', updateParent
);
46 $(element
).datepicker('setDate', model(scope
.$parent
));
47 element
.on('change', updateParent
);
49 var updateParent
= (function() {
50 $timeout(function () {
51 model
.assign(scope
.$parent
, $(element
).val());
56 scope
.$parent
.$watch(attrs
.crmUiDate
, updateChildren
);
57 element
.on('change', updateParent
);
62 // example: <div crm-ui-date-time="myobj.mydatetimefield"></div>
63 .directive('crmUiDateTime', function ($parse
) {
69 template
: '<input crm-ui-date="dtparts.date" placeholder="{{dateLabel}}"/> <input crm-ui-time="dtparts.time" placeholder="{{timeLabel}}"/>',
70 link: function (scope
, element
, attrs
) {
71 var model
= $parse(attrs
.crmUiDateTime
);
72 scope
.dateLabel
= ts('Date');
73 scope
.timeLabel
= ts('Time');
75 var updateChildren
= (function () {
76 var value
= model(scope
.$parent
);
78 var dtparts
= value
.split(/ /);
79 scope
.dtparts
= {date
: dtparts
[0], time
: dtparts
[1]};
82 scope
.dtparts
= {date
: '', time
: ''};
85 var updateParent
= (function () {
86 model
.assign(scope
.$parent
, scope
.dtparts
.date
+ " " + scope
.dtparts
.time
);
90 scope
.$parent
.$watch(attrs
.crmUiDateTime
, updateChildren
);
91 scope
.$watch('dtparts.date', updateParent
);
92 scope
.$watch('dtparts.time', updateParent
);
97 // Display a field/row in a field list
98 // example: <div crm-ui-field crm-title="My Field"> {{mydata}} </div>
99 // example: <div crm-ui-field="subform.myfield" crm-title="'My Field'"> <input crm-ui-id="subform.myfield" name="myfield" /> </div>
100 // example: <div crm-ui-field="subform.myfield" crm-title="'My Field'"> <input crm-ui-id="subform.myfield" name="myfield" required /> </div>
101 .directive('crmUiField', function() {
102 // Note: When writing new templates, the "label" position is particular. See/patch "var label" below.
104 default: '~/crmUi/field.html',
105 checkbox
: '~/crmUi/field-cb.html'
109 require
: '^crmUiIdScope',
115 templateUrl: function(tElement
, tAttrs
){
116 var layout
= tAttrs
.crmLayout
? tAttrs
.crmLayout
: 'default';
117 return templateUrls
[layout
];
120 link: function (scope
, element
, attrs
, crmUiIdCtrl
) {
121 $(element
).addClass('crm-section');
122 scope
.crmUiField
= attrs
.crmUiField
;
123 scope
.crmTitle
= attrs
.crmTitle
;
128 // 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>
129 .directive('crmUiId', function () {
131 require
: '^crmUiIdScope',
134 pre: function (scope
, element
, attrs
, crmUiIdCtrl
) {
135 var id
= crmUiIdCtrl
.get(attrs
.crmUiId
);
136 element
.attr('id', id
);
142 // 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>
143 .directive('crmUiFor', function ($parse
, $timeout
) {
145 require
: '^crmUiIdScope',
147 template
: '<span ng-class="cssClasses"><span ng-transclude/><span crm-ui-visible="crmIsRequired" class="crm-marker" title="This field is required.">*</span></span>',
149 link: function (scope
, element
, attrs
, crmUiIdCtrl
) {
150 scope
.crmIsRequired
= false;
151 scope
.cssClasses
= {};
153 if (!attrs
.crmUiFor
) return;
155 var id
= crmUiIdCtrl
.get(attrs
.crmUiFor
);
156 element
.attr('for', id
);
159 var updateCss = function () {
160 scope
.cssClasses
['crm-error'] = !ngModel
.$valid
&& !ngModel
.$pristine
;
163 // Note: if target element is dynamically generated (eg via ngInclude), then it may not be available
164 // immediately for initialization. Use retries/retryDelay to initialize such elements.
165 var init = function (retries
, retryDelay
) {
166 var input
= $('#' + id
);
167 if (input
.length
=== 0) {
170 init(retries
-1, retryDelay
);
176 var tgtScope
= scope
;//.$parent;
177 if (attrs
.crmDepth
) {
178 for (var i
= attrs
.crmDepth
; i
> 0; i
--) {
179 tgtScope
= tgtScope
.$parent
;
183 if (input
.attr('ng-required')) {
184 scope
.crmIsRequired
= scope
.$parent
.$eval(input
.attr('ng-required'));
185 scope
.$parent
.$watch(input
.attr('ng-required'), function (isRequired
) {
186 scope
.crmIsRequired
= isRequired
;
190 scope
.crmIsRequired
= input
.prop('required');
193 ngModel
= $parse(attrs
.crmUiFor
)(tgtScope
);
195 ngModel
.$viewChangeListeners
.push(updateCss
);
206 // 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>
207 .directive('crmUiIdScope', function () {
211 controllerAs
: 'crmUiIdCtrl',
212 controller: function($scope
) {
214 this.get = function(name
) {
216 ids
[name
] = "crmUiId_" + (++uidCount
);
221 link: function (scope
, element
, attrs
) {}
225 // example: <iframe crm-ui-iframe="getHtmlContent()"></iframe>
226 .directive('crmUiIframe', function ($parse
) {
229 crmUiIframe
: '@' // expression which evalutes to HTML content
231 link: function (scope
, elm
, attrs
) {
232 var iframe
= $(elm
)[0];
233 iframe
.setAttribute('width', '100%');
234 iframe
.setAttribute('frameborder', '0');
236 var refresh = function () {
237 // 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>';
238 var iframeHtml
= scope
.$parent
.$eval(attrs
.crmUiIframe
);
240 var doc
= iframe
.document
;
241 if (iframe
.contentDocument
) {
242 doc
= iframe
.contentDocument
;
244 else if (iframe
.contentWindow
) {
245 doc
= iframe
.contentWindow
.document
;
249 doc
.writeln(iframeHtml
);
253 scope
.$parent
.$watch(attrs
.crmUiIframe
, refresh
);
254 //setTimeout(function () { refresh(); }, 50);
259 // example: <textarea crm-ui-id="myForm.body_html" crm-ui-richtext name="body_html" ng-model="mailing.body_html"></textarea>
260 .directive('crmUiRichtext', function ($timeout
) {
263 link: function (scope
, elm
, attr
, ngModel
) {
264 var ck
= CKEDITOR
.replace(elm
[0]);
270 ck
.on('pasteState', function () {
271 scope
.$apply(function () {
272 ngModel
.$setViewValue(ck
.getData());
276 ck
.on('insertText', function () {
277 $timeout(function () {
278 ngModel
.$setViewValue(ck
.getData());
282 ngModel
.$render = function (value
) {
283 ck
.setData(ngModel
.$viewValue
);
289 // example: <a crm-ui-lock binding="mymodel.boolfield"></a>
290 // example: <a crm-ui-lock
291 // binding="mymodel.boolfield"
292 // title-locked="ts('Boolfield is locked')"
293 // title-unlocked="ts('Boolfield is unlocked')"></a>
294 .directive('crmUiLock', function ($parse
, $rootScope
) {
295 var defaultVal = function (defaultValue
) {
296 var f = function (scope
) {
299 f
.assign = function (scope
, value
) {
305 // like $parse, but accepts a defaultValue in case expr is undefined
306 var parse = function (expr
, defaultValue
) {
307 return expr
? $parse(expr
) : defaultVal(defaultValue
);
312 link: function (scope
, element
, attrs
) {
313 var binding
= parse(attrs
.binding
, true);
314 var titleLocked
= parse(attrs
.titleLocked
, ts('Locked'));
315 var titleUnlocked
= parse(attrs
.titleUnlocked
, ts('Unlocked'));
317 $(element
).addClass('ui-icon lock-button');
318 var refresh = function () {
319 var locked
= binding(scope
);
322 .removeClass('ui-icon-unlocked')
323 .addClass('ui-icon-locked')
324 .prop('title', titleLocked(scope
))
329 .removeClass('ui-icon-locked')
330 .addClass('ui-icon-unlocked')
331 .prop('title', titleUnlocked(scope
))
336 $(element
).click(function () {
337 binding
.assign(scope
, !binding(scope
));
339 $rootScope
.$digest();
342 scope
.$watch(attrs
.binding
, refresh
);
343 scope
.$watch(attrs
.titleLocked
, refresh
);
344 scope
.$watch(attrs
.titleUnlocked
, refresh
);
351 // usage: <select crm-ui-select="{placeholder:'Something',allowClear:true,...}" ng-model="myobj.field"><option...></select>
352 .directive('crmUiSelect', function ($parse
, $timeout
) {
358 link: function (scope
, element
, attrs
, ngModel
) {
359 // In cases where UI initiates update, there may be an extra
360 // call to refreshUI, but it doesn't create a cycle.
362 ngModel
.$render = function () {
363 $timeout(function () {
364 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
365 // new item is added before selection is made
366 $(element
).select2('val', ngModel
.$viewValue
);
369 function refreshModel() {
370 var oldValue
= ngModel
.$viewValue
, newValue
= $(element
).select2('val');
371 if (oldValue
!= newValue
) {
372 scope
.$parent
.$apply(function () {
373 ngModel
.$setViewValue(newValue
);
379 // TODO watch select2-options
380 var options
= attrs
.crmUiSelect
? scope
.$parent
.$eval(attrs
.crmUiSelect
) : {};
381 $(element
).select2(options
);
382 $(element
).on('change', refreshModel
);
383 $timeout(ngModel
.$render
);
391 // example <div crm-ui-tab crm-title="ts('My Title')">...content...</div>
392 // WISHLIST: use a full Angular component instead of an incomplete jQuery wrapper
393 .directive('crmUiTab', function($parse
) {
395 require
: '^crmUiTabSet',
401 template
: '<div ng-transclude></div>',
403 link: function (scope
, element
, attrs
, crmUiTabSetCtrl
) {
404 crmUiTabSetCtrl
.add(scope
);
409 // 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>
410 .directive('crmUiTabSet', function() {
416 templateUrl
: '~/crmUi/tabset.html',
418 controllerAs
: 'crmUiTabSetCtrl',
419 controller: function($scope
, $parse
) {
420 var tabs
= $scope
.tabs
= []; // array<$scope>
421 this.add = function(tab
) {
422 if (!tab
.id
) throw "Tab is missing 'id'";
426 link: function (scope
, element
, attrs
) {}
430 // example: <input crm-ui-time="myobj.mytimefield" />
431 .directive('crmUiTime', function ($parse
, $timeout
) {
437 link: function (scope
, element
, attrs
) {
438 var model
= $parse(attrs
.crmUiTime
);
440 element
.addClass('crm-form-text six');
441 $(element
).timeEntry({show24Hours
: true});
443 var updateChildren
= (function() {
444 element
.off('change', updateParent
);
445 $(element
).timeEntry('setTime', model(scope
.$parent
));
446 element
.on('change', updateParent
);
448 var updateParent
= (function () {
449 $timeout(function () {
450 model
.assign(scope
.$parent
, element
.val());
455 scope
.$parent
.$watch(attrs
.crmUiTime
, updateChildren
);
456 element
.on('change', updateParent
);
461 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" />
462 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" crm-ui-validate-name="myError" />
463 // Generic, field-independent validator.
464 .directive('crmUiValidate', function() {
468 link: function(scope
, element
, attrs
, ngModel
) {
469 var validationKey
= attrs
.crmUiValidateName
? attrs
.crmUiValidateName
: 'crmUiValidate';
470 scope
.$watch(attrs
.crmUiValidate
, function(newValue
){
471 ngModel
.$setValidity(validationKey
, !!newValue
);
477 // like ng-show, but hides/displays elements using "visibility" which maintains positioning
478 // example <div crm-ui-visible="false">...content...</div>
479 .directive('crmUiVisible', function($parse
) {
485 link: function (scope
, element
, attrs
) {
486 var model
= $parse(attrs
.crmUiVisible
);
487 function updatecChildren() {
488 element
.css('visibility', model(scope
.$parent
) ? 'inherit' : 'hidden');
491 scope
.$parent
.$watch(attrs
.crmUiVisible
, updatecChildren
);
496 // 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>
497 // Note: "myWizardCtrl" has various actions/properties like next() and $first().
498 // WISHLIST: Allow each step to determine if it is "complete" / "valid" / "selectable"
499 // WISHLIST: Allow each step to enable/disable (show/hide) itself
500 .directive('crmUiWizard', function() {
506 templateUrl
: '~/crmUi/wizard.html',
508 controllerAs
: 'crmUiWizardCtrl',
509 controller: function($scope
, $parse
) {
510 var steps
= $scope
.steps
= []; // array<$scope>
511 var crmUiWizardCtrl
= this;
513 var selectedIndex
= null;
515 var findIndex = function() {
517 angular
.forEach(steps
, function(step
, stepKey
) {
518 if (step
.selected
) found
= stepKey
;
523 /// @return int the index of the current step
524 this.$index = function() { return selectedIndex
; };
525 /// @return bool whether the currentstep is first
526 this.$first = function() { return this.$index() === 0; };
527 /// @return bool whether the current step is last
528 this.$last = function() { return this.$index() === steps
.length
-1; };
529 this.$maxVisit = function() { return maxVisited
; };
530 this.$validStep = function() {
531 return steps
[selectedIndex
].isStepValid();
533 this.iconFor = function(index
) {
534 if (index
< this.$index()) return '√';
535 if (index
=== this.$index()) return '»';
538 this.isSelectable = function(step
) {
539 if (step
.selected
) return false;
541 angular
.forEach(steps
, function(otherStep
, otherKey
) {
542 if (step
=== otherStep
&& otherKey
<= maxVisited
) result
= true;
547 /*** @param Object step the $scope of the step */
548 this.select = function(step
) {
549 angular
.forEach(steps
, function(otherStep
, otherKey
) {
550 otherStep
.selected
= (otherStep
=== step
);
551 if (otherStep
=== step
&& maxVisited
< otherKey
) maxVisited
= otherKey
;
553 selectedIndex
= findIndex();
555 /*** @param Object step the $scope of the step */
556 this.add = function(step
) {
557 if (steps
.length
=== 0) {
558 step
.selected
= true;
562 steps
.sort(function(a
,b
){
563 return a
.crmUiWizardStep
- b
.crmUiWizardStep
;
565 selectedIndex
= findIndex();
567 this.remove = function(step
) {
569 angular
.forEach(steps
, function(otherStep
, otherKey
) {
570 if (otherStep
=== step
) key
= otherKey
;
573 steps
.splice(key
, 1);
576 this.goto = function(index
) {
577 if (index
< 0) index
= 0;
578 if (index
>= steps
.length
) index
= steps
.length
-1;
579 this.select(steps
[index
]);
581 this.previous = function() { this.goto(this.$index()-1); };
582 this.next = function() { this.goto(this.$index()+1); };
583 if ($scope
.crmUiWizard
) {
584 $parse($scope
.crmUiWizard
).assign($scope
.$parent
, this);
587 link: function (scope
, element
, attrs
) {}
591 // Use this to add extra markup to wizard
592 .directive('crmUiWizardButtons', function() {
594 require
: '^crmUiWizard',
597 template
: '<span ng-transclude></span>',
599 link: function (scope
, element
, attrs
, crmUiWizardCtrl
) {
600 var realButtonsEl
= $(element
).closest('.crm-wizard').find('.crm-wizard-buttons');
601 $(element
).appendTo(realButtonsEl
);
606 // example: <div crm-ui-wizard-step crm-title="ts('My Title')" ng-form="mySubForm">...content...</div>
607 // If there are any conditional steps, then be sure to set a weight explicitly on *all* steps to maintain ordering.
608 // example: <div crm-ui-wizard-step="100" crm-title="..." ng-if="...">...content...</div>
609 .directive('crmUiWizardStep', function() {
612 require
: ['^crmUiWizard', 'form'],
615 crmTitle
: '@', // expression, evaluates to a printable string
616 crmUiWizardStep
: '@' // int, a weight which determines the ordering of the steps
618 template
: '<div class="crm-wizard-step" ng-show="selected" ng-transclude/></div>',
620 link: function (scope
, element
, attrs
, ctrls
) {
621 var crmUiWizardCtrl
= ctrls
[0], form
= ctrls
[1];
622 if (scope
.crmUiWizardStep
) {
623 scope
.crmUiWizardStep
= parseInt(scope
.crmUiWizardStep
);
625 scope
.crmUiWizardStep
= nextWeight
++;
627 scope
.isStepValid = function() {
630 crmUiWizardCtrl
.add(scope
);
631 element
.on('$destroy', function(){
632 crmUiWizardCtrl
.remove(scope
);
638 // Example: <button crm-confirm="{message: ts('Are you sure you want to continue?')}" on-yes="frobnicate(123)">Frobincate</button>
639 // Example: <button crm-confirm="{type: 'disable', obj: myObject}" on-yes="myObject.is_active=0; myObject.save()">Disable</button>
640 .directive('crmConfirm', function () {
641 // Helpers to calculate default options for CRM.confirm()
643 'disable': function (options
) {
645 message
: ts('Are you sure you want to disable this?'),
646 options
: {no
: ts('Cancel'), yes
: ts('Disable')},
648 title
: ts('Disable %1?', {
649 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
653 'revert': function (options
) {
655 message
: ts('Are you sure you want to revert this?'),
656 options
: {no
: ts('Cancel'), yes
: ts('Revert')},
658 title
: ts('Revert %1?', {
659 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
663 'delete': function (options
) {
665 message
: ts('Are you sure you want to delete this?'),
666 options
: {no
: ts('Cancel'), yes
: ts('Delete')},
668 title
: ts('Delete %1?', {
669 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
676 link: function (scope
, element
, attrs
) {
677 $(element
).click(function () {
678 var options
= scope
.$eval(attrs
.crmConfirm
);
679 var defaults
= (options
.type
) ? defaultFuncs
[options
.type
](options
) : {};
680 CRM
.confirm(_
.extend(defaults
, options
))
681 .on('crmConfirm:yes', function () { scope
.$apply(attrs
.onYes
); })
682 .on('crmConfirm:no', function () { scope
.$apply(attrs
.onNo
); });
687 .run(function($rootScope
, $location
) {
688 /// Example: <button ng-click="goto('home')">Go home!</button>
689 $rootScope
.goto = function(path
) {
690 $location
.path(path
);
692 // useful for debugging: $rootScope.log = console.log || function() {};
696 })(angular
, CRM
.$, CRM
._
);