CRM-16445 - crmUiRichtext - Fix image insertion. Wait 50ms.
[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/continous 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 .directive('crmUiIframe', function ($parse) {
318 return {
319 scope: {
320 crmUiIframe: '@' // expression which evalutes to HTML content
321 },
322 link: function (scope, elm, attrs) {
323 var iframe = $(elm)[0];
324 iframe.setAttribute('width', '100%');
325 iframe.setAttribute('frameborder', '0');
326
327 var refresh = function () {
328 // 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>';
329 var iframeHtml = scope.$parent.$eval(attrs.crmUiIframe);
330
331 var doc = iframe.document;
332 if (iframe.contentDocument) {
333 doc = iframe.contentDocument;
334 }
335 else if (iframe.contentWindow) {
336 doc = iframe.contentWindow.document;
337 }
338
339 doc.open();
340 doc.writeln(iframeHtml);
341 doc.close();
342 };
343
344 // If the iframe is in a dialog, respond to resize events
345 $(elm).parent().on('dialogresize dialogopen', function(e, ui) {
346 $(this).css({padding: '0', margin: '0', overflow: 'hidden'});
347 iframe.setAttribute('height', '' + $(this).innerHeight() + 'px');
348 });
349
350 scope.$parent.$watch(attrs.crmUiIframe, refresh);
351 }
352 };
353 })
354
355 // Example:
356 // <a ng-click="$broadcast('my-insert-target', 'some new text')>Insert</a>
357 // <textarea crm-ui-insert-rx='my-insert-target'></textarea>
358 // TODO Consider ways to separate the plain-text/rich-text implementations
359 .directive('crmUiInsertRx', function() {
360 return {
361 link: function(scope, element, attrs) {
362 scope.$on(attrs.crmUiInsertRx, function(e, tokenName) {
363 var id = element.attr('id');
364 if (CKEDITOR.instances[id]) {
365 CKEDITOR.instances[id].insertText(tokenName);
366 $(element).select2('close').select2('val', '');
367 CKEDITOR.instances[id].focus();
368 }
369 else {
370 var crmForEl = $('#' + id);
371 var origVal = crmForEl.val();
372 var origPos = crmForEl[0].selectionStart;
373 var newVal = origVal.substring(0, origPos) + tokenName + origVal.substring(origPos, origVal.length);
374 crmForEl.val(newVal);
375 var newPos = (origPos + tokenName.length);
376 crmForEl[0].selectionStart = newPos;
377 crmForEl[0].selectionEnd = newPos;
378
379 $(element).select2('close').select2('val', '');
380 crmForEl.triggerHandler('change');
381 crmForEl.focus();
382 }
383 });
384 }
385 };
386 })
387
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) {
391 return {
392 require: '?ngModel',
393 link: function (scope, elm, attr, ngModel) {
394 var ck = CKEDITOR.replace(elm[0]);
395
396 if (ck) {
397 _.extend(ck.config, {
398 width: '94%',
399 height: '400',
400 filebrowserBrowseUrl: CRM.crmUi.browseUrl + '?cms=civicrm&type=files',
401 filebrowserImageBrowseUrl: CRM.crmUi.browseUrl + '?cms=civicrm&type=images',
402 filebrowserFlashBrowseUrl: CRM.crmUi.browseUrl + '?cms=civicrm&type=flash',
403 filebrowserUploadUrl: CRM.crmUi.uploadUrl + '?cms=civicrm&type=files',
404 filebrowserImageUploadUrl: CRM.crmUi.uploadUrl + '?cms=civicrm&type=images',
405 filebrowserFlashUploadUrl: CRM.crmUi.uploadUrl + '?cms=civicrm&type=flash',
406 });
407 }
408
409 if (!ngModel) {
410 return;
411 }
412
413 if (attr.ngBlur) {
414 ck.on('blur', function(){
415 $timeout(function(){
416 scope.$eval(attr.ngBlur);
417 });
418 });
419 }
420
421 // CRM-16445 - When one inserts an image, none of these events seem to fire at the right time:
422 // afterCommandExec, afterInsertHtml, afterPaste, afterSetData, change, insertElement,
423 // insertHtml, insertText, pasteState. It seems that 'pasteState' is the general equivalent of
424 // what 'change' should be, except (in the case of image insertion) it fires too soon.
425 ck.on('pasteState', function(evt) {
426 $timeout(function() {
427 ngModel.$setViewValue(ck.getData());
428 }, 50);
429 });
430
431 ngModel.$render = function (value) {
432 ck.setData(ngModel.$viewValue);
433 };
434 }
435 };
436 })
437
438 // Display a lock icon (based on a boolean).
439 // example: <a crm-ui-lock binding="mymodel.boolfield"></a>
440 // example: <a crm-ui-lock
441 // binding="mymodel.boolfield"
442 // title-locked="ts('Boolfield is locked')"
443 // title-unlocked="ts('Boolfield is unlocked')"></a>
444 .directive('crmUiLock', function ($parse, $rootScope) {
445 var defaultVal = function (defaultValue) {
446 var f = function (scope) {
447 return defaultValue;
448 };
449 f.assign = function (scope, value) {
450 // ignore changes
451 };
452 return f;
453 };
454
455 // like $parse, but accepts a defaultValue in case expr is undefined
456 var parse = function (expr, defaultValue) {
457 return expr ? $parse(expr) : defaultVal(defaultValue);
458 };
459
460 return {
461 template: '',
462 link: function (scope, element, attrs) {
463 var binding = parse(attrs.binding, true);
464 var titleLocked = parse(attrs.titleLocked, ts('Locked'));
465 var titleUnlocked = parse(attrs.titleUnlocked, ts('Unlocked'));
466
467 $(element).addClass('ui-icon lock-button');
468 var refresh = function () {
469 var locked = binding(scope);
470 if (locked) {
471 $(element)
472 .removeClass('ui-icon-unlocked')
473 .addClass('ui-icon-locked')
474 .prop('title', titleLocked(scope))
475 ;
476 }
477 else {
478 $(element)
479 .removeClass('ui-icon-locked')
480 .addClass('ui-icon-unlocked')
481 .prop('title', titleUnlocked(scope))
482 ;
483 }
484 };
485
486 $(element).click(function () {
487 binding.assign(scope, !binding(scope));
488 //scope.$digest();
489 $rootScope.$digest();
490 });
491
492 scope.$watch(attrs.binding, refresh);
493 scope.$watch(attrs.titleLocked, refresh);
494 scope.$watch(attrs.titleUnlocked, refresh);
495
496 refresh();
497 }
498 };
499 })
500
501 // CrmUiOrderCtrl is a controller class which manages sort orderings.
502 // Ex:
503 // JS: $scope.myOrder = new CrmUiOrderCtrl(['+field1', '-field2]);
504 // $scope.myOrder.toggle('field1');
505 // $scope.myOrder.setDir('field2', '');
506 // HTML: <tr ng-repeat="... | order:myOrder.get()">...</tr>
507 .service('CrmUiOrderCtrl', function(){
508 //
509 function CrmUiOrderCtrl(defaults){
510 this.values = defaults;
511 }
512 angular.extend(CrmUiOrderCtrl.prototype, {
513 get: function get() {
514 return this.values;
515 },
516 getDir: function getDir(name) {
517 if (this.values.indexOf(name) >= 0 || this.values.indexOf('+' + name) >= 0) {
518 return '+';
519 }
520 if (this.values.indexOf('-' + name) >= 0) {
521 return '-';
522 }
523 return '';
524 },
525 // @return bool TRUE if something is removed
526 remove: function remove(name) {
527 var idx = this.values.indexOf(name);
528 if (idx >= 0) {
529 this.values.splice(idx, 1);
530 return true;
531 }
532 else {
533 return false;
534 }
535 },
536 setDir: function setDir(name, dir) {
537 return this.toggle(name, dir);
538 },
539 // Toggle sort order on a field.
540 // To set a specific order, pass optional parameter 'next' ('+', '-', or '').
541 toggle: function toggle(name, next) {
542 if (!next && next !== '') {
543 next = '+';
544 if (this.remove(name) || this.remove('+' + name)) {
545 next = '-';
546 }
547 if (this.remove('-' + name)) {
548 next = '';
549 }
550 }
551
552 if (next == '+') {
553 this.values.unshift('+' + name);
554 }
555 else if (next == '-') {
556 this.values.unshift('-' + name);
557 }
558 }
559 });
560 return CrmUiOrderCtrl;
561 })
562
563 // Define a controller which manages sort order. You may interact with the controller
564 // directly ("myOrder.toggle('fieldname')") order using the helper, crm-ui-order-by.
565 // example:
566 // <span crm-ui-order="{var: 'myOrder', defaults: {'-myField'}}"></span>
567 // <th><a crm-ui-order-by="[myOrder,'myField']">My Field</a></th>
568 // <tr ng-repeat="... | order:myOrder.get()">...</tr>
569 // <button ng-click="myOrder.toggle('myField')">
570 .directive('crmUiOrder', function(CrmUiOrderCtrl) {
571 return {
572 link: function(scope, element, attrs){
573 var options = angular.extend({var: 'crmUiOrderBy'}, scope.$eval(attrs.crmUiOrder));
574 scope[options.var] = new CrmUiOrderCtrl(options.defaults);
575 }
576 };
577 })
578
579 // For usage, see crmUiOrder (above)
580 .directive('crmUiOrderBy', function() {
581 return {
582 link: function(scope, element, attrs) {
583 function updateClass(crmUiOrderCtrl, name) {
584 var dir = crmUiOrderCtrl.getDir(name);
585 element
586 .toggleClass('sorting_asc', dir === '+')
587 .toggleClass('sorting_desc', dir === '-')
588 .toggleClass('sorting', dir === '');
589 }
590
591 element.on('click', function(e){
592 var tgt = scope.$eval(attrs.crmUiOrderBy);
593 tgt[0].toggle(tgt[1]);
594 updateClass(tgt[0], tgt[1]);
595 e.preventDefault();
596 scope.$digest();
597 });
598
599 var tgt = scope.$eval(attrs.crmUiOrderBy);
600 updateClass(tgt[0], tgt[1]);
601 }
602 };
603 })
604
605 // Display a fancy SELECT (based on select2).
606 // usage: <select crm-ui-select="{placeholder:'Something',allowClear:true,...}" ng-model="myobj.field"><option...></select>
607 .directive('crmUiSelect', function ($parse, $timeout) {
608 return {
609 require: '?ngModel',
610 scope: {
611 crmUiSelect: '='
612 },
613 link: function (scope, element, attrs, ngModel) {
614 // In cases where UI initiates update, there may be an extra
615 // call to refreshUI, but it doesn't create a cycle.
616
617 if (ngModel) {
618 ngModel.$render = function () {
619 $timeout(function () {
620 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
621 // new item is added before selection is made
622 element.select2('val', ngModel.$viewValue);
623 });
624 };
625 }
626 function refreshModel() {
627 var oldValue = ngModel.$viewValue, newValue = element.select2('val');
628 if (oldValue != newValue) {
629 scope.$parent.$apply(function () {
630 ngModel.$setViewValue(newValue);
631 });
632 }
633 }
634
635 function init() {
636 // TODO watch select2-options
637 element.select2(scope.crmUiSelect || {});
638 if (ngModel) {
639 element.on('change', refreshModel);
640 $timeout(ngModel.$render);
641 }
642 }
643
644 init();
645 }
646 };
647 })
648
649 // Render a crmEntityRef widget
650 // usage: <input crm-entityref="{entity: 'Contact', select: {allowClear:true}}" ng-model="myobj.field" />
651 .directive('crmEntityref', function ($parse, $timeout) {
652 return {
653 require: '?ngModel',
654 scope: {
655 crmEntityref: '='
656 },
657 link: function (scope, element, attrs, ngModel) {
658 // In cases where UI initiates update, there may be an extra
659 // call to refreshUI, but it doesn't create a cycle.
660
661 ngModel.$render = function () {
662 $timeout(function () {
663 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
664 // new item is added before selection is made
665 element.select2('val', ngModel.$viewValue);
666 });
667 };
668 function refreshModel() {
669 var oldValue = ngModel.$viewValue, newValue = element.select2('val');
670 if (oldValue != newValue) {
671 scope.$parent.$apply(function () {
672 ngModel.$setViewValue(newValue);
673 });
674 }
675 }
676
677 function init() {
678 // TODO can we infer "entity" from model?
679 element.crmEntityRef(scope.crmEntityref || {});
680 element.on('change', refreshModel);
681 $timeout(ngModel.$render);
682 }
683
684 init();
685 }
686 };
687 })
688
689 // example <div crm-ui-tab crm-title="ts('My Title')">...content...</div>
690 // WISHLIST: use a full Angular component instead of an incomplete jQuery wrapper
691 .directive('crmUiTab', function($parse) {
692 return {
693 require: '^crmUiTabSet',
694 restrict: 'EA',
695 scope: {
696 crmTitle: '@',
697 id: '@'
698 },
699 template: '<div ng-transclude></div>',
700 transclude: true,
701 link: function (scope, element, attrs, crmUiTabSetCtrl) {
702 crmUiTabSetCtrl.add(scope);
703 }
704 };
705 })
706
707 // 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>
708 .directive('crmUiTabSet', function() {
709 return {
710 restrict: 'EA',
711 scope: {
712 crmUiTabSet: '@'
713 },
714 templateUrl: '~/crmUi/tabset.html',
715 transclude: true,
716 controllerAs: 'crmUiTabSetCtrl',
717 controller: function($scope, $parse) {
718 var tabs = $scope.tabs = []; // array<$scope>
719 this.add = function(tab) {
720 if (!tab.id) throw "Tab is missing 'id'";
721 tabs.push(tab);
722 };
723 },
724 link: function (scope, element, attrs) {}
725 };
726 })
727
728 // Generic, field-independent form validator.
729 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" />
730 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" crm-ui-validate-name="myError" />
731 .directive('crmUiValidate', function() {
732 return {
733 restrict: 'EA',
734 require: 'ngModel',
735 link: function(scope, element, attrs, ngModel) {
736 var validationKey = attrs.crmUiValidateName ? attrs.crmUiValidateName : 'crmUiValidate';
737 scope.$watch(attrs.crmUiValidate, function(newValue){
738 ngModel.$setValidity(validationKey, !!newValue);
739 });
740 }
741 };
742 })
743
744 // like ng-show, but hides/displays elements using "visibility" which maintains positioning
745 // example <div crm-ui-visible="false">...content...</div>
746 .directive('crmUiVisible', function($parse) {
747 return {
748 restrict: 'EA',
749 scope: {
750 crmUiVisible: '@'
751 },
752 link: function (scope, element, attrs) {
753 var model = $parse(attrs.crmUiVisible);
754 function updatecChildren() {
755 element.css('visibility', model(scope.$parent) ? 'inherit' : 'hidden');
756 }
757 updatecChildren();
758 scope.$parent.$watch(attrs.crmUiVisible, updatecChildren);
759 }
760 };
761 })
762
763 // 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>
764 // Note: "myWizardCtrl" has various actions/properties like next() and $first().
765 // WISHLIST: Allow each step to determine if it is "complete" / "valid" / "selectable"
766 // WISHLIST: Allow each step to enable/disable (show/hide) itself
767 .directive('crmUiWizard', function() {
768 return {
769 restrict: 'EA',
770 scope: {
771 crmUiWizard: '@'
772 },
773 templateUrl: '~/crmUi/wizard.html',
774 transclude: true,
775 controllerAs: 'crmUiWizardCtrl',
776 controller: function($scope, $parse) {
777 var steps = $scope.steps = []; // array<$scope>
778 var crmUiWizardCtrl = this;
779 var maxVisited = 0;
780 var selectedIndex = null;
781
782 var findIndex = function() {
783 var found = null;
784 angular.forEach(steps, function(step, stepKey) {
785 if (step.selected) found = stepKey;
786 });
787 return found;
788 };
789
790 /// @return int the index of the current step
791 this.$index = function() { return selectedIndex; };
792 /// @return bool whether the currentstep is first
793 this.$first = function() { return this.$index() === 0; };
794 /// @return bool whether the current step is last
795 this.$last = function() { return this.$index() === steps.length -1; };
796 this.$maxVisit = function() { return maxVisited; };
797 this.$validStep = function() {
798 return steps[selectedIndex] && steps[selectedIndex].isStepValid();
799 };
800 this.iconFor = function(index) {
801 if (index < this.$index()) return 'โˆš';
802 if (index === this.$index()) return 'ยป';
803 return ' ';
804 };
805 this.isSelectable = function(step) {
806 if (step.selected) return false;
807 var result = false;
808 angular.forEach(steps, function(otherStep, otherKey) {
809 if (step === otherStep && otherKey <= maxVisited) result = true;
810 });
811 return result;
812 };
813
814 /*** @param Object step the $scope of the step */
815 this.select = function(step) {
816 angular.forEach(steps, function(otherStep, otherKey) {
817 otherStep.selected = (otherStep === step);
818 if (otherStep === step && maxVisited < otherKey) maxVisited = otherKey;
819 });
820 selectedIndex = findIndex();
821 };
822 /*** @param Object step the $scope of the step */
823 this.add = function(step) {
824 if (steps.length === 0) {
825 step.selected = true;
826 selectedIndex = 0;
827 }
828 steps.push(step);
829 steps.sort(function(a,b){
830 return a.crmUiWizardStep - b.crmUiWizardStep;
831 });
832 selectedIndex = findIndex();
833 };
834 this.remove = function(step) {
835 var key = null;
836 angular.forEach(steps, function(otherStep, otherKey) {
837 if (otherStep === step) key = otherKey;
838 });
839 if (key !== null) {
840 steps.splice(key, 1);
841 }
842 };
843 this.goto = function(index) {
844 if (index < 0) index = 0;
845 if (index >= steps.length) index = steps.length-1;
846 this.select(steps[index]);
847 };
848 this.previous = function() { this.goto(this.$index()-1); };
849 this.next = function() { this.goto(this.$index()+1); };
850 if ($scope.crmUiWizard) {
851 $parse($scope.crmUiWizard).assign($scope.$parent, this);
852 }
853 },
854 link: function (scope, element, attrs) {
855 scope.ts = CRM.ts(null);
856 }
857 };
858 })
859
860 // Use this to add extra markup to wizard
861 .directive('crmUiWizardButtons', function() {
862 return {
863 require: '^crmUiWizard',
864 restrict: 'EA',
865 scope: {},
866 template: '<span ng-transclude></span>',
867 transclude: true,
868 link: function (scope, element, attrs, crmUiWizardCtrl) {
869 var realButtonsEl = $(element).closest('.crm-wizard').find('.crm-wizard-buttons');
870 $(element).appendTo(realButtonsEl);
871 }
872 };
873 })
874
875 // Example: <button crm-icon="check">Save</button>
876 .directive('crmIcon', function() {
877 return {
878 restrict: 'EA',
879 scope: {},
880 link: function (scope, element, attrs) {
881 $(element).prepend('<span class="icon ui-icon-' + attrs.crmIcon + '"></span> ');
882 if ($(element).is('button')) {
883 $(element).addClass('crm-button');
884 }
885 }
886 };
887 })
888
889 // example: <div crm-ui-wizard-step crm-title="ts('My Title')" ng-form="mySubForm">...content...</div>
890 // If there are any conditional steps, then be sure to set a weight explicitly on *all* steps to maintain ordering.
891 // example: <div crm-ui-wizard-step="100" crm-title="..." ng-if="...">...content...</div>
892 .directive('crmUiWizardStep', function() {
893 var nextWeight = 1;
894 return {
895 require: ['^crmUiWizard', 'form'],
896 restrict: 'EA',
897 scope: {
898 crmTitle: '@', // expression, evaluates to a printable string
899 crmUiWizardStep: '@' // int, a weight which determines the ordering of the steps
900 },
901 template: '<div class="crm-wizard-step" ng-show="selected" ng-transclude/></div>',
902 transclude: true,
903 link: function (scope, element, attrs, ctrls) {
904 var crmUiWizardCtrl = ctrls[0], form = ctrls[1];
905 if (scope.crmUiWizardStep) {
906 scope.crmUiWizardStep = parseInt(scope.crmUiWizardStep);
907 } else {
908 scope.crmUiWizardStep = nextWeight++;
909 }
910 scope.isStepValid = function() {
911 return form.$valid;
912 };
913 crmUiWizardCtrl.add(scope);
914 element.on('$destroy', function(){
915 crmUiWizardCtrl.remove(scope);
916 });
917 }
918 };
919 })
920
921 // Example: <button crm-confirm="{message: ts('Are you sure you want to continue?')}" on-yes="frobnicate(123)">Frobincate</button>
922 // Example: <button crm-confirm="{type: 'disable', obj: myObject}" on-yes="myObject.is_active=0; myObject.save()">Disable</button>
923 // Example: <button crm-confirm="{templateUrl: '~/path/to/view.html', export: {foo: bar}}" on-yes="frobnicate(123)">Frobincate</button>
924 .directive('crmConfirm', function ($compile, $rootScope, $templateRequest, $q) {
925 // Helpers to calculate default options for CRM.confirm()
926 var defaultFuncs = {
927 'disable': function (options) {
928 return {
929 message: ts('Are you sure you want to disable this?'),
930 options: {no: ts('Cancel'), yes: ts('Disable')},
931 width: 300,
932 title: ts('Disable %1?', {
933 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
934 })
935 };
936 },
937 'revert': function (options) {
938 return {
939 message: ts('Are you sure you want to revert this?'),
940 options: {no: ts('Cancel'), yes: ts('Revert')},
941 width: 300,
942 title: ts('Revert %1?', {
943 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
944 })
945 };
946 },
947 'delete': function (options) {
948 return {
949 message: ts('Are you sure you want to delete this?'),
950 options: {no: ts('Cancel'), yes: ts('Delete')},
951 width: 300,
952 title: ts('Delete %1?', {
953 1: options.obj.title || options.obj.label || options.obj.name || ts('the record')
954 })
955 };
956 }
957 };
958 var confirmCount = 0;
959 return {
960 link: function (scope, element, attrs) {
961 $(element).click(function () {
962 var options = scope.$eval(attrs.crmConfirm);
963 if (attrs.title && !options.title) {
964 options.title = attrs.title;
965 }
966 var defaults = (options.type) ? defaultFuncs[options.type](options) : {};
967
968 var tpl = null, stubId = null;
969 if (!options.message) {
970 if (options.templateUrl) {
971 tpl = $templateRequest(options.templateUrl);
972 }
973 else if (options.template) {
974 tpl = options.template;
975 }
976 if (tpl) {
977 stubId = 'crmUiConfirm_' + (++confirmCount);
978 options.message = '<div id="' + stubId + '"></div>';
979 }
980 }
981
982 CRM.confirm(_.extend(defaults, options))
983 .on('crmConfirm:yes', function() { scope.$apply(attrs.onYes); })
984 .on('crmConfirm:no', function() { scope.$apply(attrs.onNo); });
985
986 if (tpl && stubId) {
987 $q.when(tpl, function(html) {
988 var scope = options.scope || $rootScope.$new();
989 if (options.export) {
990 angular.extend(scope, options.export);
991 }
992 var linker = $compile(html);
993 $('#' + stubId).append($(linker(scope)));
994 });
995 }
996 });
997 }
998 };
999 })
1000 .run(function($rootScope, $location) {
1001 /// Example: <button ng-click="goto('home')">Go home!</button>
1002 $rootScope.goto = function(path) {
1003 $location.path(path);
1004 };
1005 // useful for debugging: $rootScope.log = console.log || function() {};
1006 })
1007 ;
1008
1009 })(angular, CRM.$, CRM._);