fng-ui-select 0.12.0-beta.20 → 0.12.0-beta.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/cypress/integration/lists.spec.js +54 -0
  3. package/cypress/integration/lists.spec.ts +60 -0
  4. package/cypress/plugins/index.js +21 -0
  5. package/cypress/support/commands.js +25 -0
  6. package/cypress/support/index.js +20 -0
  7. package/cypress/tsconfig.json +14 -0
  8. package/cypress.json +4 -0
  9. package/package.json +7 -6
  10. package/src/fng-ui-select.js +245 -108
  11. package/styles/fng-ui-select.css +20 -4
  12. package/test/e2e/protractor/protractor-wip.conf.js +10 -0
  13. package/test/e2e/{single-within-array.spec.js → protractor/single-within-array.spec.js} +36 -36
  14. package/test/e2e/protractor-wip.conf.js +0 -11
  15. package/test/e2e/test/screen_tests/screenshots/firefox-Multi control-should convert multi ajax lookups into multiple controls.png +0 -0
  16. package/test/e2e/test/screen_tests/screenshots/firefox-Multi control-should handle inside cached lookups.png +0 -0
  17. package/test/e2e/test/screen_tests/screenshots/firefox-Multi control-should handle outside cached lookups.png +0 -0
  18. package/test/e2e/test/screen_tests/screenshots/firefox-Multi control-should handle simple enum.png +0 -0
  19. package/test/e2e/test/screen_tests/screenshots/firefox-Multiple controls array-should handle inside brackets ajax lookup.png +0 -0
  20. package/test/e2e/test/screen_tests/screenshots/firefox-Multiple controls array-should handle inside brackets cached table lookups.png +0 -0
  21. package/test/e2e/test/screen_tests/screenshots/firefox-Multiple controls array-should handle outside brackets ajax lookup.png +0 -0
  22. package/test/e2e/test/screen_tests/screenshots/firefox-Multiple controls array-should handle outside brackets cached table lookups.png +0 -0
  23. package/test/e2e/test/screen_tests/screenshots/firefox-Multiple controls array-should handle simple enums.png +0 -0
  24. package/test/e2e/test/screen_tests/screenshots/firefox-Single control-should handle Ajax lookup.png +0 -0
  25. package/test/e2e/test/screen_tests/screenshots/firefox-Single control-should handle cached table lookup.png +0 -0
  26. package/test/e2e/test/screen_tests/screenshots/firefox-Single control-should handle filtered Ajax lookup.png +0 -0
  27. package/test/e2e/test/screen_tests/screenshots/firefox-Single control-should handle simple enum.png +0 -0
  28. package/test/screen_tests/screenshots/firefox-Multi control-should convert multi ajax lookups into multiple controls.png +0 -0
  29. package/test/screen_tests/screenshots/firefox-Multi control-should handle inside cached lookups.png +0 -0
  30. package/test/screen_tests/screenshots/firefox-Multi control-should handle outside cached lookups.png +0 -0
  31. package/test/screen_tests/screenshots/firefox-Multi control-should handle simple enum.png +0 -0
  32. package/test/screen_tests/screenshots/firefox-Multiple controls array-should handle inside brackets ajax lookup.png +0 -0
  33. package/test/screen_tests/screenshots/firefox-Multiple controls array-should handle inside brackets cached table lookups.png +0 -0
  34. package/test/screen_tests/screenshots/firefox-Multiple controls array-should handle outside brackets ajax lookup.png +0 -0
  35. package/test/screen_tests/screenshots/firefox-Multiple controls array-should handle outside brackets cached table lookups.png +0 -0
  36. package/test/screen_tests/screenshots/firefox-Multiple controls array-should handle simple enums.png +0 -0
  37. package/test/screen_tests/screenshots/firefox-Single control-should handle Ajax lookup.png +0 -0
  38. package/test/screen_tests/screenshots/firefox-Single control-should handle cached table lookup.png +0 -0
  39. package/test/screen_tests/screenshots/firefox-Single control-should handle filtered Ajax lookup.png +0 -0
  40. package/test/screen_tests/screenshots/firefox-Single control-should handle simple enum.png +0 -0
  41. /package/test/e2e/{multi-control.spec.js → protractor/multi-control.spec.js} +0 -0
  42. /package/test/e2e/{multiple-control.spec.js → protractor/multiple-control.spec.js} +0 -0
  43. /package/test/e2e/{protractor-chrome.conf.js → protractor/protractor-chrome.conf.js} +0 -0
  44. /package/test/e2e/{protractor-firefox.conf.js → protractor/protractor-firefox.conf.js} +0 -0
  45. /package/test/e2e/{protractor-phantom.conf.js → protractor/protractor-phantom.conf.js} +0 -0
  46. /package/test/e2e/{single-control.spec.js → protractor/single-control.spec.js} +0 -0
package/README.md CHANGED
@@ -27,7 +27,7 @@ Options can be added to a fngUiSelect object within the form object as follows:
27
27
  back to _select2_.
28
28
  * _fngAjax_ creates a control that queries the back end after each keystroke (with 100ms of debounce) for matches.
29
29
  * Set to true to search the whole of the _ref_ collection (honouring any collection level filters)
30
- * Assign a string starting with '/' to do your own query on the backend. The search string will be in _req.query.q_ and the current value of the existing record in _req.query.e_.
30
+ * Assign a string starting with '/' to do your own query on the backend. The search string will be in _req.query.q_ and the current value of the existing record in _req.query.e_. The $index will be in _req.query.i_.
31
31
  * Use a mongo search object (converted to JSON and escaped) to apply a filter to the default search over _ref_ collection. For example to search
32
32
  only amongst records where the value of *accountSuspended* is false you might do
33
33
 
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ describe('Lists', function () {
3
+ var width = 1800;
4
+ var height = 1500;
5
+ var unique = new Date().valueOf();
6
+ beforeEach(function () {
7
+ cy.viewport(width, height);
8
+ });
9
+ it('Creates a new record with multiple shelves', function () {
10
+ cy.visit('/#/k_referencing_self_collection/new');
11
+ cy.get('#f_warehouse_name').type("m".concat(unique, " Warehouse"));
12
+ cy.get('#add_f_shelves_btn').click().click().click();
13
+ cy.get('#f_shelves_location_0').type('Top');
14
+ cy.get('#f_shelves_location_1').type('Middle');
15
+ cy.get('#f_shelves_location_2').type('Bottom');
16
+ cy.get('#add_f_items_btn').click();
17
+ cy.get('#f_items_description_0').type('Item 1');
18
+ cy.get('#f_items_shelf_0').select('Middle');
19
+ cy.get('#add_f_cleanedShelves').click().click();
20
+ cy.get('#f_cleanedShelves_0').select('Middle');
21
+ cy.get('#f_cleanedShelves_1').select('Top');
22
+ cy.get('#f_favouriteShelf').select('Bottom');
23
+ cy.get('#saveButton').click();
24
+ });
25
+ it('Creates a new record with a single shelf', function () {
26
+ cy.visit('/#/k_referencing_self_collection/new');
27
+ cy.get('#f_warehouse_name').type("s".concat(unique, " Warehouse"));
28
+ cy.get('#add_f_shelves_btn').click();
29
+ cy.get('#f_shelves_location_0').type('Only');
30
+ cy.get('#add_f_items_btn').click();
31
+ cy.get('#f_items_description_0').type('Item 1');
32
+ cy.get('#f_items_shelf_0').select('Only');
33
+ cy.get('#add_f_cleanedShelves').click();
34
+ cy.get('#f_cleanedShelves_0').select('Only');
35
+ cy.get('#f_favouriteShelf').select('Only');
36
+ cy.get('#saveButton').click();
37
+ });
38
+ it('Uses record with multiple shelves', function () {
39
+ cy.visit('/#/l_referencing_list_in_other_document/new');
40
+ cy.get('#f_description').type('An item in multi');
41
+ cy.get('.select2-arrow > b').click();
42
+ cy.get('.ui-select-search').type("m".concat(unique));
43
+ cy.get('.select2-result-label > .ng-binding').click();
44
+ cy.get('#f_shelf').select('Top');
45
+ });
46
+ it('Uses record with single shelf', function () {
47
+ cy.visit('/#/l_referencing_list_in_other_document/new');
48
+ cy.get('#f_description').type('An item in single');
49
+ cy.get('.select2-arrow > b').click();
50
+ cy.get('.ui-select-search').type("s".concat(unique));
51
+ cy.get('.select2-result-label > .ng-binding').click();
52
+ cy.get('#f_shelf').select('Only');
53
+ });
54
+ });
@@ -0,0 +1,60 @@
1
+ describe('Lists', function () {
2
+
3
+ var width = 1800;
4
+ var height = 1500;
5
+
6
+ let unique = new Date().valueOf();
7
+ beforeEach(() => {
8
+ cy.viewport(width, height);
9
+ })
10
+
11
+ it('Creates a new record with multiple shelves', function () {
12
+ cy.visit('/#/k_referencing_self_collection/new');
13
+ cy.get('#f_warehouse_name').type(`m${unique} Warehouse`);
14
+ cy.get('#add_f_shelves_btn').click().click().click();
15
+ cy.get('#f_shelves_location_0').type('Top');
16
+ cy.get('#f_shelves_location_1').type('Middle');
17
+ cy.get('#f_shelves_location_2').type('Bottom');
18
+ cy.get('#add_f_items_btn').click();
19
+ cy.get('#f_items_description_0').type('Item 1');
20
+ cy.get('#f_items_shelf_0').select('Middle');
21
+ cy.get('#add_f_cleanedShelves').click().click();
22
+ cy.get('#f_cleanedShelves_0').select('Middle');
23
+ cy.get('#f_cleanedShelves_1').select('Top');
24
+ cy.get('#f_favouriteShelf').select('Bottom');
25
+ cy.get('#saveButton').click();
26
+ });
27
+
28
+ it('Creates a new record with a single shelf', function () {
29
+ cy.visit('/#/k_referencing_self_collection/new');
30
+ cy.get('#f_warehouse_name').type(`s${unique} Warehouse`);
31
+ cy.get('#add_f_shelves_btn').click();
32
+ cy.get('#f_shelves_location_0').type('Only');
33
+ cy.get('#add_f_items_btn').click();
34
+ cy.get('#f_items_description_0').type('Item 1');
35
+ cy.get('#f_items_shelf_0').select('Only');
36
+ cy.get('#add_f_cleanedShelves').click();
37
+ cy.get('#f_cleanedShelves_0').select('Only');
38
+ cy.get('#f_favouriteShelf').select('Only');
39
+ cy.get('#saveButton').click();
40
+ });
41
+
42
+ it('Uses record with multiple shelves', function () {
43
+ cy.visit('/#/l_referencing_list_in_other_document/new');
44
+ cy.get('#f_description').type('An item in multi');
45
+ cy.get('.select2-arrow > b').click();
46
+ cy.get('.ui-select-search').type(`m${unique}`);
47
+ cy.get('.select2-result-label > .ng-binding').click();
48
+ cy.get('#f_shelf').select('Top');
49
+ });
50
+
51
+ it('Uses record with single shelf', function () {
52
+ cy.visit('/#/l_referencing_list_in_other_document/new');
53
+ cy.get('#f_description').type('An item in single');
54
+ cy.get('.select2-arrow > b').click();
55
+ cy.get('.ui-select-search').type(`s${unique}`);
56
+ cy.get('.select2-result-label > .ng-binding').click();
57
+ cy.get('#f_shelf').select('Only');
58
+ });
59
+
60
+ });
@@ -0,0 +1,21 @@
1
+ /// <reference types="cypress" />
2
+ // ***********************************************************
3
+ // This example plugins/index.js can be used to load plugins
4
+ //
5
+ // You can change the location of this file or turn off loading
6
+ // the plugins file with the 'pluginsFile' configuration option.
7
+ //
8
+ // You can read more here:
9
+ // https://on.cypress.io/plugins-guide
10
+ // ***********************************************************
11
+
12
+ // This function is called when a project is opened or re-opened (e.g. due to
13
+ // the project's config changing)
14
+
15
+ /**
16
+ * @type {Cypress.PluginConfig}
17
+ */
18
+ module.exports = (on, config) => {
19
+ // `on` is used to hook into various events Cypress emits
20
+ // `config` is the resolved Cypress config
21
+ }
@@ -0,0 +1,25 @@
1
+ // ***********************************************
2
+ // This example commands.js shows you how to
3
+ // create various custom commands and overwrite
4
+ // existing commands.
5
+ //
6
+ // For more comprehensive examples of custom
7
+ // commands please read more here:
8
+ // https://on.cypress.io/custom-commands
9
+ // ***********************************************
10
+ //
11
+ //
12
+ // -- This is a parent command --
13
+ // Cypress.Commands.add("login", (email, password) => { ... })
14
+ //
15
+ //
16
+ // -- This is a child command --
17
+ // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
18
+ //
19
+ //
20
+ // -- This is a dual command --
21
+ // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
22
+ //
23
+ //
24
+ // -- This will overwrite an existing command --
25
+ // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
@@ -0,0 +1,20 @@
1
+ // ***********************************************************
2
+ // This example support/index.js is processed and
3
+ // loaded automatically before your test files.
4
+ //
5
+ // This is a great place to put global configuration and
6
+ // behavior that modifies Cypress.
7
+ //
8
+ // You can change the location of this file or turn off
9
+ // automatically serving support files with the
10
+ // 'supportFile' configuration option.
11
+ //
12
+ // You can read more here:
13
+ // https://on.cypress.io/configuration
14
+ // ***********************************************************
15
+
16
+ // Import commands.js using ES2015 syntax:
17
+ import './commands'
18
+
19
+ // Alternatively you can use CommonJS syntax:
20
+ // require('./commands')
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "strict": true,
4
+ "target": "es5",
5
+ "lib": ["es5", "dom", "es2015.iterable"],
6
+ "types": ["cypress"]
7
+ },
8
+ "include": [
9
+ "**/*.ts"
10
+ ],
11
+ "exclude":[
12
+ "node_modules"
13
+ ]
14
+ }
package/cypress.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "baseUrl": "http://localhost:9000",
3
+ "defaultCommandTimeout": 9000
4
+ }
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "fng-ui-select",
3
3
  "author": "Mark Chapman <support@forms-angular.org>",
4
- "version": "0.12.0-beta.20",
4
+ "version": "0.12.0-beta.200",
5
5
  "description": "angular-ui-select plugin for forms-angular",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "https://github.com/forms-angular/fng-ui-select"
9
9
  },
10
10
  "dependencies": {
11
- "ui-select": "0.19.6",
12
- "select2": "3.4.3"
11
+ "select2": "3.5.1",
12
+ "ui-select": "0.19.8"
13
13
  },
14
14
  "devDependencies": {
15
- "protractor-screenshot-reporter": "0.0.4"
15
+ "cypress": "^9.5.4"
16
16
  },
17
17
  "engines": {
18
18
  "node": ">=0.10.0"
@@ -22,7 +22,8 @@
22
22
  ],
23
23
  "license": "MIT",
24
24
  "scripts": {
25
- "test": "NODE_ENV=test node ../website/server.js && protractor test/e2e/protractor-firefox.conf.js",
26
- "clear": "kill `ps -ef | grep '[0-9] node ../website/server.js' | egrep -o ' ([0-9]+) ' | head -1 | sed -e 's/ //'` -9"
25
+ "test": "npx cypress run --spec cypress/integration/lists.spec.js",
26
+ "old-test": "NODE_ENV=test node ../forms-angular/website/server.js & npx webdriver-manager update --versions.chrome=$(google-chrome --version | cut -d ' ' -f 3) && npx webdriver-manager start --versions.chrome=$(google-chrome --version | cut -d ' ' -f 3) & npx protractor test/e2e/protractor/protractor-chrome.conf.js",
27
+ "clear": "kill `ps -ef | grep '[0-9] node ../forms-angular/website/server.js' | egrep -o ' ([0-9]+) ' | head -1 | sed -e 's/ //'` -9"
27
28
  }
28
29
  }
@@ -3,9 +3,43 @@
3
3
 
4
4
  var uiSelectModule = angular.module('fng.uiSelect', ['ui.select']);
5
5
 
6
- uiSelectModule.factory('uiSelectHelper', ['$rootScope', '$q', 'SubmissionsService', function ($rootScope, $q, SubmissionsService) {
6
+ uiSelectModule.factory('uiSelectHelper', ['$rootScope', '$q', 'recordHandler', 'SubmissionsService', function ($rootScope, $q, recordHandler, SubmissionsService) {
7
7
  var lastW, lastH;
8
- var localLookups = {};
8
+ const localLookups = {};
9
+ // this ultra-simple cache stores { [id: string]: stringValue } as a means of avoiding unnecessary network round-trips, and the UI refresh
10
+ // lagging caused by the promises used to make them.
11
+ // there is no cache life-span because all we're storing here is the concatenation of records' list fields, and the chances of those
12
+ // changing while present in this cache is miniscule. even if they did change, displaying a stale record description in a picklist
13
+ // would surely not cause any great concern.
14
+ // there is no cache size limit because we're storing tiny amounts of data.
15
+ // NB: this cache assumes that record ids are unique across all resources (as is the case with a standard MongoDB back-end).
16
+ // TODO: provide an alternative implementation that includes the resourceName in the cache ids to avoid this limitation.
17
+ let valueCache = {};
18
+ // we're going to populate the select with this value whenever a SubmissionsService.getListAttributes(...) call is rejected. because we're
19
+ // only asking for list fields, permissions should not be the cause of failures, making "record not found" (where the foreign key
20
+ // reference has been broken) by far the most likely explanation.
21
+ // TODO: interpret the actual error condition and translate this into a user-friendly message
22
+ const RECORD_NOT_FOUND = "record not found";
23
+
24
+ function useCacheOrLookItUp(resourceName, id, cb) {
25
+ if (valueCache[id]) {
26
+ cb(valueCache[id]);
27
+ } else {
28
+ var text;
29
+ SubmissionsService.getListAttributes(resourceName, id)
30
+ .then((response) => {
31
+ text = response.data.list;
32
+ })
33
+ .catch(() => {
34
+ text = RECORD_NOT_FOUND; // cache this as well as there's no point in repeatedly performing a failing lookup
35
+ })
36
+ .finally(() => {
37
+ cb(text);
38
+ valueCache[id] = text;
39
+ })
40
+ }
41
+ }
42
+
9
43
  return {
10
44
  windowChanged: function (w, h) {
11
45
  var result = false;
@@ -19,39 +53,50 @@
19
53
  addClientLookup: function (lkpName, lkpData) {
20
54
  localLookups[lkpName] = lkpData;
21
55
  },
56
+ clearCache: function () {
57
+ valueCache = {};
58
+ },
22
59
  lookupFunc: function (value, formSchema, cb) {
23
60
  if (formSchema.array) {
24
- // TODO extend back end to do multiple lookups in one hit
25
-
26
- var promises = [];
27
- var results = [];
28
- angular.forEach(value, function (obj) {
29
- promises.push(SubmissionsService.getListAttributes(formSchema.ref, obj.x));
61
+ const promises = value.map((value) => {
62
+ const id = value.x ? (value.x.id || value.x) : undefined; // if it's already been converted, throw away the result of the previous conversion
63
+ if (!id) {
64
+ return $q.resolve({ data: { list: ""} }); // nothing to convert
65
+ } else if (valueCache[id]) {
66
+ return $q.resolve({ data: { list: valueCache[id] }}); // already cached
67
+ } else {
68
+ return SubmissionsService.getListAttributes(formSchema.ref, id); // need to look it up
69
+ }
30
70
  });
31
- $q.all(promises).then(function (responses) {
32
- angular.forEach(responses, function (response) {
33
- results.push({x: {id: value.shift().x, text: response.data.list}});
71
+ // TODO: no error handling here
72
+ // TODO: perform lookups of cache misses using a single round-trip
73
+ $q.all(promises).then((responses) => {
74
+ const results = responses.map((response) => {
75
+ let id = value.shift().x;
76
+ id = id.id || id; // in case it's already been converted
77
+ const text = response.data.list
78
+ valueCache[id] = text; // cache it for next time
79
+ return { id, text }
34
80
  });
35
81
  cb(formSchema, results);
36
82
  setTimeout(function () {
37
83
  $rootScope.$digest();
38
84
  });
39
85
  });
86
+ } else if (typeof value !== "string") {
87
+ cb(formSchema, value); // already converted
40
88
  } else if (formSchema.fngUiSelect.deriveOptions) {
41
- var retVal;
42
- if (typeof value === 'string') {
43
- var obj = localLookups[formSchema.fngUiSelect.deriveOptions].find(function (test) {
44
- return test.id === value
45
- });
46
- retVal = {id: value, text: obj ? obj.text : ''}
47
- } else {
48
- retVal = value;
49
- }
50
- cb(formSchema, retVal);
89
+ const obj = localLookups[formSchema.fngUiSelect.deriveOptions].find((test) => test.id === value);
90
+ cb(formSchema, { id: value, text: obj ? obj.text : "" });
51
91
  } else {
52
- SubmissionsService.getListAttributes({type:'lookup', collection:formSchema.ref.collection}, value).then(function (response) {
53
- cb(formSchema, {id: value, text: response.data.list});
54
- });
92
+ useCacheOrLookItUp(formSchema.ref, value, (text) => { cb(formSchema, { id: value, text }) });
93
+ }
94
+ },
95
+ doOwnConversion: function(scope, processedAttrs, ref) {
96
+ var id = recordHandler.getData(scope.record, processedAttrs.info.name, scope.$index);
97
+ if (id) {
98
+ id = id.id || id; // in case it's already been converted
99
+ useCacheOrLookItUp(ref, id, (text) => { recordHandler.setData(scope.record, processedAttrs.info.name, scope.$index, { id, text }) });
55
100
  }
56
101
  }
57
102
  };
@@ -63,7 +108,8 @@
63
108
  $scope.uiSelect = $scope.uiSelect || [];
64
109
 
65
110
  $scope.windowResizeUiSelect = function (checkResize) {
66
- // This is to stop the resize firing too often. Really horrible way of doing it caused by some very regrettable design choices which will be factored out later
111
+ // This is to stop the resize firing too often. Really horrible way of doing it caused by some very regrettable
112
+ // design choices which will be factored out later
67
113
  // Actually not choices - just not knowing any better
68
114
  if (!checkResize || uiSelectHelper.windowChanged($window.innerWidth, $window.innerHeight)) {
69
115
  for (var i = 0; i < $scope.uiSelect.length; i++) {
@@ -94,29 +140,51 @@
94
140
  $scope[id + '_options'] = [];
95
141
  } else {
96
142
  var promise;
97
- if (elem.filter && elem.filter[0] === '/') {
143
+ if (elem.filter && typeof elem.filter === "string" && elem.filter[0] === "/") {
144
+ if (elem.filter.startsWith("/api/")) {
145
+ console.log("WARNING! fng-ui-select is using an /api/ endpoint to refresh options - this is likely to cause security authorisation problems");
146
+ }
147
+ // HACK We want to pass the existing record in e, but we can fall foul of 431 errors if it is large, so we test for that
148
+ // using an arbitrary number and if so just send the _id (on the assumption that large records won't be new so will have an _id).
149
+ // According to https://stackoverflow.com/questions/57431355/how-to-fix-431-request-header-fields-too-large-in-react-redux-app the limit is 8KB
150
+ // but I have seen it fail at about 5k...
151
+ var record = JSON.stringify($scope.record).length >= (4 * 1024) ? {_id: $scope.record._id} : $scope.record;
98
152
  // Custom URL
99
153
  promise = $http({
100
154
  method: 'GET',
101
155
  url: elem.filter,
102
156
  params: {
103
157
  q: searchString,
104
- e: $scope.record
158
+ e: record,
159
+ i: $scope.$index
105
160
  },
106
161
  cache: false
107
162
  });
108
163
  } else {
109
- promise = $http.get('/api/search/' + elem.ref.collection + '?q=' + searchString + (elem.filter ? ('&f=' + elem.filter) : ''));
164
+ promise = $http.get('/api/search/' + elem.ref + '?q=' + searchString + (elem.filter ? ('&f=' + elem.filter) : ''));
110
165
  }
111
166
  promise.then(function (response) {
112
- if (elem.additional) {
113
- $scope[id + '_options'] = response.data.results.map(function (result) {
114
- result.text = result.text + (result.additional ? (', ' + result.additional) : '');
115
- return result;
116
- });
167
+ if (response.status >= 400) {
168
+ throw new Error(response.statusMessage)
169
+ } else {
170
+ if (elem.additional) {
171
+ $scope[id + '_options'] = response.data.results.map(function (result) {
172
+ result.text = result.text + (result.additional ? (', ' + result.additional) : '');
173
+ return result;
174
+ });
175
+ } else {
176
+ $scope[id + '_options'] = response.data.results;
177
+ }
178
+ }
179
+ })
180
+ .catch(function(err) {
181
+ var msg;
182
+ if (err && err.data && err.data.message) {
183
+ msg = err.data.message;
117
184
  } else {
118
- $scope[id + '_options'] = response.data.results;
185
+ msg = 'Error ' + err.status + ': ' + err.statusText + ' - ' + err.data;
119
186
  }
187
+ $scope.showError(msg);
120
188
  });
121
189
  }
122
190
  } else {
@@ -132,16 +200,19 @@
132
200
  $timeout($scope.windowResizeUiSelect);
133
201
  }]);
134
202
 
135
- uiSelectModule.directive('fngUiSelect', ['$compile', '$window', 'pluginHelper', 'cssFrameworkService', 'formMarkupHelper', 'uiSelectHelper',
136
- function ($compile, $window, pluginHelper, cssFrameworkService, formMarkupHelper, uiSelectHelper) {
203
+ uiSelectModule.directive('fngUiSelect', ['$compile', 'pluginHelper', 'cssFrameworkService', 'uiSelectHelper', '$timeout',
204
+ function ($compile, pluginHelper, cssFrameworkService, uiSelectHelper, $timeout) {
137
205
  return {
138
206
  restrict: 'E',
139
207
  controller: 'FngUISelectCtrl',
140
- link: function (scope, element, attr) {
208
+ link: function (scope, element, attrs) {
141
209
 
142
210
  function addToConversions(path, options) {
143
211
  if (Object.keys(options).length > 0) {
144
212
  var keys = path.split('.');
213
+ if (!scope.conversions) {
214
+ scope.conversions = {};
215
+ }
145
216
  var target = scope.conversions;
146
217
  for (var i = 0; i < keys.length; i++) {
147
218
  var thisKey = keys[i];
@@ -152,27 +223,40 @@
152
223
  }
153
224
  }
154
225
 
155
- var processedAttr = pluginHelper.extractFromAttr(attr, 'fngUiSelect');
156
- var elemScope = angular.extend({selectId: processedAttr.info.id}, processedAttr.directiveOptions);
157
- var multi = processedAttr.info.array;
158
- var elementHtml;
159
- var input = '';
226
+ const processedAttrs = pluginHelper.extractFromAttr(attrs, 'fngUiSelect');
227
+ const id = processedAttrs.info.id;
228
+ const uniqueId = scope.$index !== undefined ? processedAttrs.info.id + "_" + scope.$index : id;
229
+ const elemScope = angular.extend({selectId: uniqueId}, processedAttrs.directiveOptions);
230
+ const multi = processedAttrs.info.array;
231
+ let elementHtml;
232
+ let input = '';
160
233
 
161
234
  scope.uiSelect.push(elemScope);
162
- addToConversions(processedAttr.info.name, processedAttr.directiveOptions);
235
+ addToConversions(processedAttrs.info.name, processedAttrs.directiveOptions);
163
236
 
164
237
  // Sort out the theme, defaulting to select2 (so old users won't see the change). Bootstrap theme only works with Bootstrap 3
165
- var theme = processedAttr.directiveOptions.theme || 'select2';
166
- if (processedAttr.info.theme === 'bootstrap' && cssFrameworkService.framework !== 'bs3') {
167
- theme = 'select2';
238
+ // and not with animate (see https://github.com/angular-ui/ui-select/issues/1731 and others)
239
+ var theme = processedAttrs.directiveOptions.theme || 'select2';
240
+ if (theme === 'bootstrap') {
241
+ if (cssFrameworkService.framework() !== 'bs3') {
242
+ theme = 'select2';
243
+ } else {
244
+ try {
245
+ if (angular.module('ngAnimate')) {
246
+ theme = 'select2';
247
+ }
248
+ } catch(e) {
249
+ ; // module not present, so bootstrap theme will work
250
+ }
251
+ }
168
252
  }
169
253
 
170
254
  var multiControl = false;
171
255
  var multiStr = '';
172
- if (multi && (processedAttr.directiveOptions.fngajax || processedAttr.directiveOptions.forcemultiple)) {
256
+ if (multi && (processedAttrs.directiveOptions.fngajax || processedAttrs.directiveOptions.forcemultiple)) {
173
257
  // We need the array to be an array of objects with a x property. This tells forms-angular to convert it by
174
258
  // adding an attribute to the schema.
175
- pluginHelper.findIdInSchemaAndFlagNeedX(scope.baseSchema(), processedAttr.info.id);
259
+ pluginHelper.findIdInSchemaAndFlagNeedX(scope.baseSchema(), id);
176
260
  multiControl = true;
177
261
  } else {
178
262
  multiStr = multi ? 'multiple close-on-select reset-search-input ' : '';
@@ -180,29 +264,45 @@
180
264
 
181
265
  var requiredStr = '';
182
266
  var allowClearStr = '';
183
- if (processedAttr.info.required) {
267
+ if (processedAttrs.info.required) {
184
268
  requiredStr = ' ng-required="true"';
269
+ } else if (processedAttrs.directiveOptions.ngrequired) {
270
+ requiredStr = ` ng-required="${processedAttrs.directiveOptions.ngrequired}"`;
185
271
  } else {
186
272
  allowClearStr = ' allow-clear';
187
273
  }
274
+ let disabledStr = pluginHelper.genIdAndDisabledStr(scope, processedAttrs, "", { forceNg: true });
188
275
 
189
276
  // First of all add a hidden input field which we will use to set the width of the select
190
- var hiddenInputInfo = {
191
- id: processedAttr.info.id + '_width-helper',
192
- name: processedAttr.info.name + '_width-helper',
193
- label: ''
194
- };
195
- if (processedAttr.info.size) {
196
- hiddenInputInfo.size = processedAttr.info.size;
277
+ if (!angular.element(`#${uniqueId}_width-helper`).length > 0) {
278
+ var hiddenInputInfo = {
279
+ id: `${uniqueId}_width-helper`,
280
+ name: processedAttrs.info.name + '_width-helper',
281
+ label: ''
282
+ };
283
+ if (processedAttrs.info.size) {
284
+ hiddenInputInfo.size = processedAttrs.info.size;
285
+ }
286
+ input = pluginHelper.buildInputMarkup(
287
+ scope,
288
+ attrs,
289
+ {
290
+ processedAttrs,
291
+ fieldInfoOverrides: hiddenInputInfo,
292
+ ignoreFieldInfoFromAttrs: true,
293
+ needsX: multiControl
294
+ },
295
+ function () {
296
+ return '<input id="' + hiddenInputInfo.id + '" type="text" class="form-control" disabled="" aria-label="unused input" style="position: absolute; left: -4200px;">';
297
+ }
298
+ );
299
+ input = input.replace('class="row', 'class="hidden-row row')
197
300
  }
198
- input = pluginHelper.buildInputMarkup(scope, attr.model, hiddenInputInfo, processedAttr.options, false, multiControl, function (buildingBlocks) {
199
- return '<input id="' + hiddenInputInfo.id + '" type="text" class="form-control" disabled="" style="position: absolute; left: -4200px;">';
200
- });
201
301
 
202
302
  function optionsFromArray(multiControl, multi, array, arrayGetter) {
203
- var isObjects = (scope[array].isObjects || typeof scope[array][0] === "object");
303
+ var isObjects = scope[array] && (scope[array].isObjects || typeof scope[array][0] === "object");
204
304
  if (isObjects) {
205
- addToConversions(processedAttr.info.name, {fngajax: uiSelectHelper.lookupFunc});
305
+ addToConversions(processedAttrs.info.name, {fngajax: uiSelectHelper.lookupFunc});
206
306
  uiSelectHelper.addClientLookup(arrayGetter, scope[array]);
207
307
  }
208
308
  var select = '';
@@ -217,59 +317,96 @@
217
317
  return select;
218
318
  }
219
319
 
220
- elementHtml = pluginHelper.buildInputMarkup(scope, attr.model, processedAttr.info, processedAttr.options, multiControl, multiControl, function (buildingBlocks) {
221
- var defaultPlaceholder = 'Select an option...';
222
- if (processedAttr.directiveOptions.fngajax) {
223
- defaultPlaceholder = 'Start typing...'
224
- }
225
- // set up the ui-select directives
226
- var select = '<ui-select ' + multiStr + buildingBlocks.common + requiredStr + ' theme="' + theme + '" ng-disabled="disabled" style="width:300px;">';
227
- select += '<ui-select-match' + allowClearStr + ' placeholder="' + (processedAttr.info.placeholder || defaultPlaceholder) + '">';
228
-
229
-
230
- if (processedAttr.directiveOptions.fngajax) {
231
- // Stash any filters
232
- if (processedAttr.directiveOptions.fngajax !== true) {
233
- elemScope.filter = processedAttr.directiveOptions.fngajax;
320
+ elementHtml = pluginHelper.buildInputMarkup(
321
+ scope,
322
+ attrs,
323
+ {
324
+ processedAttrs,
325
+ addButtons: multiControl,
326
+ needsX: multiControl,
327
+ },
328
+ function (buildingBlocks) {
329
+ var defaultPlaceholder = 'Select an option...';
330
+ if (processedAttrs.directiveOptions.fngajax) {
331
+ defaultPlaceholder = 'Start typing...'
234
332
  }
235
- // Set up lookup function
236
- addToConversions(processedAttr.info.name, {fngajax: uiSelectHelper.lookupFunc});
237
- // Use the forms-angular API to query the referenced collection
238
- elemScope.ref = processedAttr.info.ref;
239
- if (elemScope.ref) {
240
- if (elemScope.ref[0] === '{') {
241
- elemScope.ref = JSON.parse(elemScope.ref);
242
- } else {
243
- elemScope.ref = {type:'lookup', collection: elemScope.ref};
244
- console.warn('Support for string type "ref" property is deprecated - use ref:' + JSON.stringify(elemScope.ref));
333
+ // set up the ui-select directives
334
+ // hack here. buildingBlocks.common will almost certainly contain 'id="xxxx"', but we don't want this because the
335
+ // id will already be in disabledStr. remove it.
336
+ // the right solution here would be to include an option in the params that are passed to buildInputMarkup which
337
+ // specifies whether or not the buildingBlocks that it creates should include the id or not.
338
+ const idIdx = buildingBlocks.common.indexOf('id="');
339
+ if (idIdx > -1) {
340
+ const endIdIdx = buildingBlocks.common.indexOf('"', idIdx+4);
341
+ if (endIdIdx > -1) {
342
+ buildingBlocks.common = buildingBlocks.common.substring(0, idIdx) + buildingBlocks.common.substring(endIdIdx + 1);
245
343
  }
246
344
  }
247
- scope[processedAttr.info.id + '_options'] = [];
248
- if (multiControl) {
249
- select += '{{$select.selected.text}}';
250
- } else if (processedAttr.options.subschema) {
251
- select += '{{' + attr.model + '.' + processedAttr.info.name.replace(processedAttr.options.subschemaroot, processedAttr.options.subschemaroot + '[$index]') + '.text}}';
345
+ var select = '<ui-select ' + multiStr + buildingBlocks.common + requiredStr + disabledStr + ' theme="' + theme + '" style="min-width:18em;">'
346
+ select += '<ui-select-match' + allowClearStr + ' placeholder="' + (processedAttrs.info.placeholder || defaultPlaceholder) + '">';
347
+
348
+ if (processedAttrs.directiveOptions.fngajax) {
349
+ // Stash any filters
350
+ if (processedAttrs.directiveOptions.fngajax !== true) {
351
+ elemScope.filter = processedAttrs.directiveOptions.fngajax;
352
+ }
353
+ // if we have a hard-coded ref (processedAttrs.info.ref), forms-angular can perform the lookup conversion for us.
354
+ // where processedAttrs.directiveOptions.refprop is being used instead, the ref is 'variable' - it comes from a property of scope.record, and
355
+ // in this case, we'll need to handle the conversions ourselves.
356
+ addToConversions(processedAttrs.info.name, {fngajax: uiSelectHelper.lookupFunc, noconvert: !!processedAttrs.directiveOptions.refprop});
357
+ if (processedAttrs.directiveOptions.refprop) {
358
+ // the property that we'll be getting the ref from may not be populated yet, and might conceivably change at any time, so we
359
+ // need to $watch it. buildingBlocks.modelString will be something like "record.<array>[$index].<field>". replacing <field>
360
+ // with the value of refprop will give us a suitable watch expression.
361
+ const watchStr = buildingBlocks.modelString.substring(0, buildingBlocks.modelString.lastIndexOf(".") + 1) + processedAttrs.directiveOptions.refprop;
362
+ scope.$watch(watchStr, (newValue) => {
363
+ if (newValue && elemScope.ref !== newValue) {
364
+ elemScope.ref = newValue;
365
+ uiSelectHelper.doOwnConversion(scope, processedAttrs, elemScope.ref);
366
+ }
367
+ });
368
+ // we also need to re-do the conversion if the user cancels changes. this event does fire on more than just user cancellation,
369
+ // so this is slightly wasteful. but with the caching implemented by uiSelectHelper, this is no big deal.
370
+ scope.$on("fngCancel", () => {
371
+ $timeout(() => {
372
+ if (elemScope.ref) {
373
+ uiSelectHelper.doOwnConversion(scope, processedAttrs, elemScope.ref);
374
+ }
375
+ });
376
+ });
377
+ } else {
378
+ elemScope.ref = processedAttrs.info.ref;
379
+ }
380
+ scope[`${uniqueId}_options`] = [];
381
+ if (multiControl) {
382
+ select += '{{$select.selected.text}}';
383
+ } else if (processedAttrs.options.subschema) {
384
+ select += '{{' + attrs.model + '.' + processedAttrs.info.name.replace(processedAttrs.options.subschemaroot, processedAttrs.options.subschemaroot + '[$index]') + '.text}}';
385
+ } else {
386
+ select += '{{' + buildingBlocks.modelString + '.text}}';
387
+ }
388
+ select += '</ui-select-match>';
389
+ select += `<ui-select-choices repeat="option in (${uniqueId}_options) track by $index" `;
390
+ select += `refresh="refreshOptions($select.search, '${uniqueId}')" `;
391
+ select += 'refresh-delay="400"> ';
392
+ select += '<div ng-bind-html="option.text" ng-attr-title="{{ option.text }}"></div>';
393
+ } else if (processedAttrs.directiveOptions.deriveoptions) {
394
+ if (typeof scope[processedAttrs.directiveOptions.deriveoptions] === "function") {
395
+ select += optionsFromArray(multiControl, multi, scope[processedAttrs.directiveOptions.deriveoptions](), processedAttrs.directiveOptions.deriveoptions);
396
+ } else {
397
+ throw new Error("In fng-ui-select " + processedAttrs.directiveOptions.deriveoptions + " is not a function on the scope");
398
+ }
399
+ } else if (processedAttrs.info.options) {
400
+ // Simple case - enumerated options on the form scope
401
+ select += optionsFromArray(multiControl, multi, processedAttrs.info.options);
252
402
  } else {
253
- select += '{{' + buildingBlocks.modelString + '.text}}';
403
+ throw new Error('fng-ui-select has no means of populating select');
254
404
  }
255
- select += '</ui-select-match>';
256
- select += '<ui-select-choices repeat="option in (' + processedAttr.info.id + '_options) track by $index" ';
257
- select += 'refresh="refreshOptions($select.search, \'' + processedAttr.info.id + '\')" ';
258
- select += 'refresh-delay="100"> ';
259
- select += '<div ng-bind-html="option.text"></div>';
260
- } else if (processedAttr.directiveOptions.deriveoptions) {
261
- select += optionsFromArray(multiControl, multi, scope[processedAttr.directiveOptions.deriveoptions](), processedAttr.directiveOptions.deriveoptions);
262
- } else if (processedAttr.info.options) {
263
- // Simple case - enumerated options on the form scope
264
- select += optionsFromArray(multiControl, multi, processedAttr.info.options);
265
- } else {
266
- throw new Error('fng-ui-select has no means of populating select');
405
+ select += '</ui-select-choices>';
406
+ select += '</ui-select>';
407
+ return select;
267
408
  }
268
- select += '</ui-select-choices>';
269
- select += '</ui-select>';
270
- return select;
271
- });
272
- scope.content = input + elementHtml;
409
+ );
273
410
  element.append($compile(input + elementHtml)(scope));
274
411
  }
275
412
  }
@@ -1,4 +1,7 @@
1
- .ng-invalid-required > a.select2-choice {
1
+ .ui-select-container.ng-invalid-required,
2
+ .ui-select-container.ng-invalid-required > a.select2-choice,
3
+ .ui-select-container.ng-invalid-required > a.select2-choice > .select2-chosen
4
+ {
2
5
  background-color: rgba(255, 0, 0, 0.10);
3
6
  }
4
7
 
@@ -11,6 +14,19 @@
11
14
  background-color: rgba(255, 0, 0, 0.10);
12
15
  }
13
16
 
14
- .ui-select-container.ui-select-bootstrap {
15
- top: -4px;
16
- }
17
+ fng-ui-select div[id$="width-helper"] {
18
+ margin-bottom: 0px!important;
19
+ }
20
+
21
+ fng-ui-select div[id$="width-helper"] div {
22
+ min-height: 0px;
23
+ }
24
+
25
+ fng-ui-select div[id$="width-helper"] label.control-label {
26
+ padding-top: 0px!important;
27
+ min-height: 0px!important;
28
+ }
29
+
30
+ .hidden-row {
31
+ display: none;
32
+ }
@@ -0,0 +1,10 @@
1
+ exports.config = {
2
+ specs: [
3
+ './single-within-array.spec.js'
4
+ ],
5
+ capabilities: {
6
+ browserName: 'chrome',
7
+ },
8
+ directConnect: true,
9
+ baseUrl: 'http://localhost:9000'
10
+ };
@@ -7,26 +7,26 @@ describe('Single control in array', function () {
7
7
  var height = 768;
8
8
  browser.driver.manage().window().setSize(width, height);
9
9
 
10
- it('should handle simple enum', function () {
11
- browser.get('/#/test_nested_select/new');
12
-
13
- var field = element(by.model('record.surname'));
14
- field.clear();
15
- field.sendKeys('Smith');
16
- field = element(by.model('record.forename'));
17
- field.clear();
18
- field.sendKeys('One');
19
- element(by.css('#add_f_nested_btn')).click();
20
- field = element(by.model('record.nested[$index].someText'));
21
- field.clear();
22
- field.sendKeys('Sometext One');
23
-
24
- $('#cg_f_nested_anEnum .select2-arrow').click();
25
- element.all(by.css('.select2-result-label.ui-select-choices-row-inner')).get(2).click();
26
- expect(element(by.css('#cg_f_nested_anEnum .select2-choice.ui-select-match')).getText()).toMatch('C Option');
27
- element(by.css('#saveButton')).click();
28
- expect(element(by.css('#cg_f_nested_anEnum .select2-choice.ui-select-match')).getText()).toMatch('C Option');
29
- });
10
+ // it('should handle simple enum', function () {
11
+ // browser.get('/#/test_nested_select/new');
12
+ //
13
+ // var field = element(by.model('record.surname'));
14
+ // field.clear();
15
+ // field.sendKeys('Smith');
16
+ // field = element(by.model('record.forename'));
17
+ // field.clear();
18
+ // field.sendKeys('One');
19
+ // element(by.css('#add_f_nested_btn')).click();
20
+ // field = element(by.model('record.nested[$index].someText'));
21
+ // field.clear();
22
+ // field.sendKeys('Sometext One');
23
+ //
24
+ // $('#cg_f_nested_anEnum .select2-arrow').click();
25
+ // element.all(by.css('.select2-result-label.ui-select-choices-row-inner')).get(2).click();
26
+ // expect(element(by.css('#cg_f_nested_anEnum .select2-choice.ui-select-match')).getText()).toMatch('C Option');
27
+ // element(by.css('#saveButton')).click();
28
+ // expect(element(by.css('#cg_f_nested_anEnum .select2-choice.ui-select-match')).getText()).toMatch('C Option');
29
+ // });
30
30
 
31
31
  it('should handle cached table lookup', function () {
32
32
  browser.get('/#/test_nested_select/new');
@@ -73,22 +73,22 @@ describe('Single control in array', function () {
73
73
  expect(element(by.css('#cg_f_nested_singleAjax .select2-choice.ui-select-match')).getText()).toMatch('IsAccepted John true 89');
74
74
  });
75
75
 
76
- it('should handle filtered Ajax lookup', function () {
77
- browser.get('/#/test_fng_ui_select/new');
78
- var match = $('#cg_f_filteredAjax a.select2-choice.ui-select-match');
79
- expect(match.getText()).toEqual('Start typing...');
80
- $('#cg_f_filteredAjax .select2-arrow').click();
81
- var field = $('#cg_f_filteredAjax input.select2-input');
82
- field.clear();
83
- field.sendKeys('J');
84
-
85
- expect(element.all(by.css('.select2-result-label.ui-select-choices-row-inner')).count()).toEqual(1);
86
- element.all(by.css('.select2-result-label.ui-select-choices-row-inner')).get(0).click();
87
- expect(match.getText()).toMatch('Jones Alan true 93');
88
- element(by.css('#saveButton')).click();
89
- match = $('#cg_f_filteredAjax a.select2-choice.ui-select-match');
90
- expect(match.getText()).toMatch('Jones Alan true 93');
91
- });
76
+ // it('should handle filtered Ajax lookup', function () {
77
+ // browser.get('/#/test_fng_ui_select/new');
78
+ // var match = $('#cg_f_filteredAjax a.select2-choice.ui-select-match');
79
+ // expect(match.getText()).toEqual('Start typing...');
80
+ // $('#cg_f_filteredAjax .select2-arrow').click();
81
+ // var field = $('#cg_f_filteredAjax input.select2-input');
82
+ // field.clear();
83
+ // field.sendKeys('J');
84
+ //
85
+ // expect(element.all(by.css('.select2-result-label.ui-select-choices-row-inner')).count()).toEqual(1);
86
+ // element.all(by.css('.select2-result-label.ui-select-choices-row-inner')).get(0).click();
87
+ // expect(match.getText()).toMatch('Jones Alan true 93');
88
+ // element(by.css('#saveButton')).click();
89
+ // match = $('#cg_f_filteredAjax a.select2-choice.ui-select-match');
90
+ // expect(match.getText()).toMatch('Jones Alan true 93');
91
+ // });
92
92
 
93
93
  });
94
94
 
@@ -1,11 +0,0 @@
1
- exports.config = {
2
- specs: [
3
- './single-within-array.spec.js'
4
- ],
5
- capabilities: {
6
- browserName: 'chrome'
7
- },
8
- directConnect: true,// broken with firefox 38 - see https://github.com/angular/protractor/issues/2134
9
- baseUrl: 'http://localhost:9000',
10
- framework: 'jasmine2',
11
- };