Add search extension
[civicrm-core.git] / ext / search / ang / search / crmSearchClause.directive.js
1 (function(angular, $, _) {
2 "use strict";
3
4 angular.module('search').directive('crmSearchClause', function() {
5 return {
6 scope: {
7 data: '<crmSearchClause'
8 },
9 templateUrl: '~/search/crmSearchClause.html',
10 controller: function ($scope, $element, $timeout) {
11 var ts = $scope.ts = CRM.ts();
12 var ctrl = $scope.$ctrl = this;
13 this.conjunctions = {AND: ts('And'), OR: ts('Or'), NOT: ts('Not')};
14 this.operators = CRM.vars.search.operators;
15 this.sortOptions = {
16 axis: 'y',
17 connectWith: '.api4-clause-group-sortable',
18 containment: $element.closest('.api4-clause-fieldset'),
19 over: onSortOver,
20 start: onSort,
21 stop: onSort
22 };
23
24 this.addGroup = function(op) {
25 $scope.data.clauses.push([op, []]);
26 };
27
28 this.removeGroup = function() {
29 $scope.data.groupParent.splice($scope.data.groupIndex, 1);
30 };
31
32 function onSort(event, ui) {
33 $($element).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event.type === 'sortstart');
34 $('.api4-input.form-inline').css('margin-left', '');
35 }
36
37 // Indent clause while dragging between nested groups
38 function onSortOver(event, ui) {
39 var offset = 0;
40 if (ui.sender) {
41 offset = $(ui.placeholder).offset().left - $(ui.sender).offset().left;
42 }
43 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset + 'px');
44 }
45
46 this.addClause = function() {
47 $timeout(function() {
48 if (ctrl.newClause) {
49 $scope.data.clauses.push([ctrl.newClause, '=', '']);
50 ctrl.newClause = null;
51 }
52 });
53 };
54 $scope.$watch('data.clauses', function(values) {
55 // Iterate in reverse order so index doesn't get out-of-sync during splice
56 _.forEachRight(values, function(clause, index) {
57 // Remove empty values
58 if (index >= ($scope.data.skip || 0)) {
59 if (typeof clause !== 'undefined' && !clause[0]) {
60 values.splice(index, 1);
61 }
62 // Add/remove value if operator allows for one
63 else if (typeof clause[1] === 'string' && _.contains(clause[1], 'NULL')) {
64 clause.length = 2;
65 } else if (typeof clause[1] === 'string' && clause.length === 2) {
66 clause.push('');
67 }
68 }
69 });
70 }, true);
71 }
72 };
73 });
74
75 })(angular, CRM.$, CRM._);