fng-ui-select 0.12.0-beta.26 → 0.12.0-beta.260

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 +251 -114
  11. package/styles/fng-ui-select.css +16 -3
  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.26",
4
+ "version": "0.12.0-beta.260",
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"
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,44 @@
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('FngUISelectHelperService', ['$rootScope', '$q', 'RecordHandlerService', 'SubmissionsService', function ($rootScope, $q, RecordHandlerService, 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
+
43
+ // NB: the type defs for this service (IFngUISelectHelperService) are in the forms-angular's index.d.ts
9
44
  return {
10
45
  windowChanged: function (w, h) {
11
46
  var result = false;
@@ -19,53 +54,78 @@
19
54
  addClientLookup: function (lkpName, lkpData) {
20
55
  localLookups[lkpName] = lkpData;
21
56
  },
57
+ clearCache: function () {
58
+ valueCache = {};
59
+ },
22
60
  lookupFunc: function (value, formSchema, cb) {
23
61
  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));
30
- });
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}});
62
+ if (formSchema.fngUiSelect.deriveOptions) {
63
+ const results = value.map((value) => {
64
+ const obj = localLookups[formSchema.fngUiSelect.deriveOptions].find((test) => test.id === value);
65
+ return { id: value, text: obj ? obj.text : "" };
34
66
  });
35
67
  cb(formSchema, results);
36
- setTimeout(function () {
37
- $rootScope.$digest();
68
+ if (results.length > 0) {
69
+ setTimeout(function () {
70
+ $rootScope.$digest();
71
+ });
72
+ }
73
+ } else {
74
+ const promises = value.map((value) => {
75
+ const id = value.x ? (value.x.id || value.x) : value; // if it's already been converted, throw away the result of the previous conversion
76
+ if (!id) {
77
+ return $q.resolve({ data: { list: ""} }); // nothing to convert
78
+ } else if (valueCache[id]) {
79
+ return $q.resolve({ data: { list: valueCache[id] }}); // already cached
80
+ } else {
81
+ return SubmissionsService.getListAttributes(formSchema.ref, id); // need to look it up
82
+ }
38
83
  });
39
- });
40
- } 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
84
+ // TODO: no error handling here
85
+ // TODO: perform lookups of cache misses using a single round-trip
86
+ $q.all(promises).then((responses) => {
87
+ const results = responses.map((response) => {
88
+ let id = value.shift().x;
89
+ id = id.id || id; // in case it's already been converted
90
+ const text = response.data.list
91
+ valueCache[id] = text; // cache it for next time
92
+ return { id, text }
93
+ });
94
+ cb(formSchema, results);
95
+ setTimeout(function () {
96
+ $rootScope.$digest();
97
+ });
45
98
  });
46
- retVal = {id: value, text: obj ? obj.text : ''}
47
- } else {
48
- retVal = value;
49
99
  }
50
- cb(formSchema, retVal);
100
+ } else if (typeof value !== "string") {
101
+ cb(formSchema, value); // already converted
102
+ } else if (formSchema.fngUiSelect.deriveOptions) {
103
+ const obj = localLookups[formSchema.fngUiSelect.deriveOptions].find((test) => test.id === value);
104
+ cb(formSchema, { id: value, text: obj ? obj.text : "" });
51
105
  } else {
52
- SubmissionsService.getListAttributes({type:'lookup', collection:formSchema.ref.collection}, value).then(function (response) {
53
- cb(formSchema, {id: value, text: response.data.list});
54
- });
106
+ useCacheOrLookItUp(formSchema.ref, value, (text) => { cb(formSchema, { id: value, text }) });
107
+ }
108
+ },
109
+ doOwnConversion: function(scope, processedAttrs, ref) {
110
+ var id = RecordHandlerService.getData(scope.record, processedAttrs.info.name, scope.$index);
111
+ if (id) {
112
+ id = id.id || id; // in case it's already been converted
113
+ useCacheOrLookItUp(ref, id, (text) => { RecordHandlerService.setData(scope.record, processedAttrs.info.name, scope.$index, { id, text }) });
55
114
  }
56
115
  }
57
116
  };
58
117
  }]);
59
118
 
60
119
 
61
- uiSelectModule.controller('FngUISelectCtrl', ['$scope', '$window', '$timeout', '$http', 'uiSelectHelper', function ($scope, $window, $timeout, $http, uiSelectHelper) {
120
+ uiSelectModule.controller('FngUISelectCtrl', ['$scope', '$window', '$timeout', '$http', 'FngUISelectHelperService', function ($scope, $window, $timeout, $http, FngUISelectHelperService) {
62
121
 
63
122
  $scope.uiSelect = $scope.uiSelect || [];
64
123
 
65
124
  $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
125
+ // This is to stop the resize firing too often. Really horrible way of doing it caused by some very regrettable
126
+ // design choices which will be factored out later
67
127
  // Actually not choices - just not knowing any better
68
- if (!checkResize || uiSelectHelper.windowChanged($window.innerWidth, $window.innerHeight)) {
128
+ if (!checkResize || FngUISelectHelperService.windowChanged($window.innerWidth, $window.innerHeight)) {
69
129
  for (var i = 0; i < $scope.uiSelect.length; i++) {
70
130
  var selectId = $scope.uiSelect[i].selectId;
71
131
  var select = document.getElementById(selectId);
@@ -94,19 +154,28 @@
94
154
  $scope[id + '_options'] = [];
95
155
  } else {
96
156
  var promise;
97
- if (elem.filter && elem.filter[0] === '/') {
157
+ if (elem.filter && typeof elem.filter === "string" && elem.filter[0] === "/") {
158
+ if (elem.filter.startsWith("/api/")) {
159
+ console.log("WARNING! fng-ui-select is using an /api/ endpoint to refresh options - this is likely to cause security authorisation problems");
160
+ }
161
+ // 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
162
+ // 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).
163
+ // According to https://stackoverflow.com/questions/57431355/how-to-fix-431-request-header-fields-too-large-in-react-redux-app the limit is 8KB
164
+ // but I have seen it fail at about 5k...
165
+ var record = JSON.stringify($scope.record).length >= (4 * 1024) ? {_id: $scope.record._id} : $scope.record;
98
166
  // Custom URL
99
167
  promise = $http({
100
168
  method: 'GET',
101
169
  url: elem.filter,
102
170
  params: {
103
171
  q: searchString,
104
- e: $scope.record
172
+ e: record,
173
+ i: $scope.$index
105
174
  },
106
175
  cache: false
107
176
  });
108
177
  } else {
109
- promise = $http.get('/api/search/' + elem.ref.collection + '?q=' + searchString + (elem.filter ? ('&f=' + elem.filter) : ''));
178
+ promise = $http.get('/api/search/' + elem.ref + '?q=' + searchString + (elem.filter ? ('&f=' + elem.filter) : ''));
110
179
  }
111
180
  promise.then(function (response) {
112
181
  if (response.status >= 400) {
@@ -122,8 +191,14 @@
122
191
  }
123
192
  }
124
193
  })
125
- .catch(err => {
126
- $scope.showError(err.data);
194
+ .catch(function(err) {
195
+ var msg;
196
+ if (err && err.data && err.data.message) {
197
+ msg = err.data.message;
198
+ } else {
199
+ msg = 'Error ' + err.status + ': ' + err.statusText + ' - ' + err.data;
200
+ }
201
+ $scope.showError(msg);
127
202
  });
128
203
  }
129
204
  } else {
@@ -139,12 +214,12 @@
139
214
  $timeout($scope.windowResizeUiSelect);
140
215
  }]);
141
216
 
142
- uiSelectModule.directive('fngUiSelect', ['$compile', '$window', 'pluginHelper', 'cssFrameworkService', 'formMarkupHelper', 'uiSelectHelper',
143
- function ($compile, $window, pluginHelper, cssFrameworkService, formMarkupHelper, uiSelectHelper) {
217
+ uiSelectModule.directive('fngUiSelect', ['$compile', 'PluginHelperService', 'CssFrameworkService', 'FngUISelectHelperService', '$timeout',
218
+ function ($compile, PluginHelperService, CssFrameworkService, FngUISelectHelperService, $timeout) {
144
219
  return {
145
220
  restrict: 'E',
146
221
  controller: 'FngUISelectCtrl',
147
- link: function (scope, element, attr) {
222
+ link: function (scope, element, attrs) {
148
223
 
149
224
  function addToConversions(path, options) {
150
225
  if (Object.keys(options).length > 0) {
@@ -162,27 +237,40 @@
162
237
  }
163
238
  }
164
239
 
165
- var processedAttr = pluginHelper.extractFromAttr(attr, 'fngUiSelect');
166
- var elemScope = angular.extend({selectId: processedAttr.info.id}, processedAttr.directiveOptions);
167
- var multi = processedAttr.info.array;
168
- var elementHtml;
169
- var input = '';
240
+ const processedAttrs = PluginHelperService.extractFromAttr(attrs, 'fngUiSelect');
241
+ const id = processedAttrs.info.id;
242
+ const uniqueId = scope.$index !== undefined ? processedAttrs.info.id + "_" + scope.$index : id;
243
+ const elemScope = angular.extend({selectId: uniqueId}, processedAttrs.directiveOptions);
244
+ const multi = processedAttrs.info.array;
245
+ let elementHtml;
246
+ let input = '';
170
247
 
171
248
  scope.uiSelect.push(elemScope);
172
- addToConversions(processedAttr.info.name, processedAttr.directiveOptions);
249
+ addToConversions(processedAttrs.info.name, processedAttrs.directiveOptions);
173
250
 
174
251
  // Sort out the theme, defaulting to select2 (so old users won't see the change). Bootstrap theme only works with Bootstrap 3
175
- var theme = processedAttr.directiveOptions.theme || 'select2';
176
- if (processedAttr.info.theme === 'bootstrap' && cssFrameworkService.framework !== 'bs3') {
177
- theme = 'select2';
252
+ // and not with animate (see https://github.com/angular-ui/ui-select/issues/1731 and others)
253
+ var theme = processedAttrs.directiveOptions.theme || 'select2';
254
+ if (theme === 'bootstrap') {
255
+ if (CssFrameworkService.framework() !== 'bs3') {
256
+ theme = 'select2';
257
+ } else {
258
+ try {
259
+ if (angular.module('ngAnimate')) {
260
+ theme = 'select2';
261
+ }
262
+ } catch(e) {
263
+ ; // module not present, so bootstrap theme will work
264
+ }
265
+ }
178
266
  }
179
267
 
180
268
  var multiControl = false;
181
269
  var multiStr = '';
182
- if (multi && (processedAttr.directiveOptions.fngajax || processedAttr.directiveOptions.forcemultiple)) {
270
+ if (multi && (processedAttrs.directiveOptions.fngajax || processedAttrs.directiveOptions.forcemultiple)) {
183
271
  // We need the array to be an array of objects with a x property. This tells forms-angular to convert it by
184
272
  // adding an attribute to the schema.
185
- pluginHelper.findIdInSchemaAndFlagNeedX(scope.baseSchema(), processedAttr.info.id);
273
+ PluginHelperService.findIdInSchemaAndFlagNeedX(scope.baseSchema(), id);
186
274
  multiControl = true;
187
275
  } else {
188
276
  multiStr = multi ? 'multiple close-on-select reset-search-input ' : '';
@@ -190,36 +278,52 @@
190
278
 
191
279
  var requiredStr = '';
192
280
  var allowClearStr = '';
193
- if (processedAttr.info.required) {
281
+ if (processedAttrs.info.required) {
194
282
  requiredStr = ' ng-required="true"';
283
+ } else if (processedAttrs.directiveOptions.ngrequired) {
284
+ requiredStr = ` ng-required="${processedAttrs.directiveOptions.ngrequired}"`;
195
285
  } else {
196
286
  allowClearStr = ' allow-clear';
197
287
  }
288
+ let disabledStr = PluginHelperService.genIdAndDisabledStr(scope, processedAttrs, "", { forceNg: true });
198
289
 
199
290
  // First of all add a hidden input field which we will use to set the width of the select
200
- var hiddenInputInfo = {
201
- id: processedAttr.info.id + '_width-helper',
202
- name: processedAttr.info.name + '_width-helper',
203
- label: ''
204
- };
205
- if (processedAttr.info.size) {
206
- hiddenInputInfo.size = processedAttr.info.size;
291
+ if (!angular.element(`#${uniqueId}_width-helper`).length > 0) {
292
+ var hiddenInputInfo = {
293
+ id: `${uniqueId}_width-helper`,
294
+ name: processedAttrs.info.name + '_width-helper',
295
+ label: ''
296
+ };
297
+ if (processedAttrs.info.size) {
298
+ hiddenInputInfo.size = processedAttrs.info.size;
299
+ }
300
+ input = PluginHelperService.buildInputMarkup(
301
+ scope,
302
+ attrs,
303
+ {
304
+ processedAttrs,
305
+ fieldInfoOverrides: hiddenInputInfo,
306
+ ignoreFieldInfoFromAttrs: true,
307
+ needsX: multiControl
308
+ },
309
+ function () {
310
+ return '<input id="' + hiddenInputInfo.id + '" type="text" class="form-control" disabled="" aria-label="unused input" style="position: absolute; left: -4200px;">';
311
+ }
312
+ );
313
+ input = input.replace('class="row', 'class="hidden-row row')
207
314
  }
208
- input = pluginHelper.buildInputMarkup(scope, attr.model, hiddenInputInfo, processedAttr.options, false, multiControl, function (buildingBlocks) {
209
- return '<input id="' + hiddenInputInfo.id + '" type="text" class="form-control" disabled="" style="position: absolute; left: -4200px;">';
210
- });
211
315
 
212
316
  function optionsFromArray(multiControl, multi, array, arrayGetter) {
213
317
  var isObjects = scope[array] && (scope[array].isObjects || typeof scope[array][0] === "object");
214
318
  if (isObjects) {
215
- addToConversions(processedAttr.info.name, {fngajax: uiSelectHelper.lookupFunc});
216
- uiSelectHelper.addClientLookup(arrayGetter, scope[array]);
319
+ addToConversions(processedAttrs.info.name, {fngajax: FngUISelectHelperService.lookupFunc});
320
+ FngUISelectHelperService.addClientLookup(arrayGetter, scope[array]);
217
321
  }
218
322
  var select = '';
219
323
  if (multiControl) {
220
324
  select += '{{$select.selected' + (isObjects ? '.text' : '') + '}}';
221
325
  } else {
222
- select += multi ? '{{$item}}' : ('{{$select.selected' + (isObjects ? '.text' : '') + '}}');
326
+ select += multi ? '{{$item' + (isObjects ? '.text' : '') + '}}' : ('{{$select.selected' + (isObjects ? '.text' : '') + '}}');
223
327
  }
224
328
  select += '</ui-select-match>';
225
329
  select += '<ui-select-choices repeat="option in ' + array + ' | filter:$select.search">';
@@ -227,63 +331,96 @@
227
331
  return select;
228
332
  }
229
333
 
230
- elementHtml = pluginHelper.buildInputMarkup(scope, attr.model, processedAttr.info, processedAttr.options, multiControl, multiControl, function (buildingBlocks) {
231
- var defaultPlaceholder = 'Select an option...';
232
- if (processedAttr.directiveOptions.fngajax) {
233
- defaultPlaceholder = 'Start typing...'
234
- }
235
- // set up the ui-select directives
236
- var select = '<ui-select ' + multiStr + buildingBlocks.common + requiredStr + ' theme="' + theme + '" ng-disabled="disabled" style="width:300px;">';
237
- select += '<ui-select-match' + allowClearStr + ' placeholder="' + (processedAttr.info.placeholder || defaultPlaceholder) + '">';
238
-
239
-
240
- if (processedAttr.directiveOptions.fngajax) {
241
- // Stash any filters
242
- if (processedAttr.directiveOptions.fngajax !== true) {
243
- elemScope.filter = processedAttr.directiveOptions.fngajax;
334
+ elementHtml = PluginHelperService.buildInputMarkup(
335
+ scope,
336
+ attrs,
337
+ {
338
+ processedAttrs,
339
+ addButtons: multiControl,
340
+ needsX: multiControl,
341
+ },
342
+ function (buildingBlocks) {
343
+ var defaultPlaceholder = 'Select an option...';
344
+ if (processedAttrs.directiveOptions.fngajax) {
345
+ defaultPlaceholder = 'Start typing...'
244
346
  }
245
- // Set up lookup function
246
- addToConversions(processedAttr.info.name, {fngajax: uiSelectHelper.lookupFunc});
247
- // Use the forms-angular API to query the referenced collection
248
- elemScope.ref = processedAttr.info.ref;
249
- if (elemScope.ref) {
250
- if (elemScope.ref[0] === '{') {
251
- elemScope.ref = JSON.parse(elemScope.ref);
252
- } else {
253
- elemScope.ref = {type:'lookup', collection: elemScope.ref};
254
- console.warn('Support for string type "ref" property is deprecated - use ref:' + JSON.stringify(elemScope.ref));
347
+ // set up the ui-select directives
348
+ // hack here. buildingBlocks.common will almost certainly contain 'id="xxxx"', but we don't want this because the
349
+ // id will already be in disabledStr. remove it.
350
+ // the right solution here would be to include an option in the params that are passed to buildInputMarkup which
351
+ // specifies whether or not the buildingBlocks that it creates should include the id or not.
352
+ const idIdx = buildingBlocks.common.indexOf('id="');
353
+ if (idIdx > -1) {
354
+ const endIdIdx = buildingBlocks.common.indexOf('"', idIdx+4);
355
+ if (endIdIdx > -1) {
356
+ buildingBlocks.common = buildingBlocks.common.substring(0, idIdx) + buildingBlocks.common.substring(endIdIdx + 1);
255
357
  }
256
358
  }
257
- scope[processedAttr.info.id + '_options'] = [];
258
- if (multiControl) {
259
- select += '{{$select.selected.text}}';
260
- } else if (processedAttr.options.subschema) {
261
- select += '{{' + attr.model + '.' + processedAttr.info.name.replace(processedAttr.options.subschemaroot, processedAttr.options.subschemaroot + '[$index]') + '.text}}';
262
- } else {
263
- select += '{{' + buildingBlocks.modelString + '.text}}';
264
- }
265
- select += '</ui-select-match>';
266
- select += '<ui-select-choices repeat="option in (' + processedAttr.info.id + '_options) track by $index" ';
267
- select += 'refresh="refreshOptions($select.search, \'' + processedAttr.info.id + '\')" ';
268
- select += 'refresh-delay="100"> ';
269
- select += '<div ng-bind-html="option.text"></div>';
270
- } else if (processedAttr.directiveOptions.deriveoptions) {
271
- if (typeof scope[processedAttr.directiveOptions.deriveoptions] === "function") {
272
- select += optionsFromArray(multiControl, multi, scope[processedAttr.directiveOptions.deriveoptions](), processedAttr.directiveOptions.deriveoptions);
359
+ var select = '<ui-select ' + multiStr + buildingBlocks.common + requiredStr + disabledStr + ' theme="' + theme + '" style="min-width:18em;">'
360
+ select += '<ui-select-match' + allowClearStr + ' placeholder="' + (processedAttrs.info.placeholder || defaultPlaceholder) + '">';
361
+
362
+ if (processedAttrs.directiveOptions.fngajax) {
363
+ // Stash any filters
364
+ if (processedAttrs.directiveOptions.fngajax !== true) {
365
+ elemScope.filter = processedAttrs.directiveOptions.fngajax;
366
+ }
367
+ // if we have a hard-coded ref (processedAttrs.info.ref), forms-angular can perform the lookup conversion for us.
368
+ // where processedAttrs.directiveOptions.refprop is being used instead, the ref is 'variable' - it comes from a property of scope.record, and
369
+ // in this case, we'll need to handle the conversions ourselves.
370
+ addToConversions(processedAttrs.info.name, {fngajax: FngUISelectHelperService.lookupFunc, noconvert: !!processedAttrs.directiveOptions.refprop});
371
+ if (processedAttrs.directiveOptions.refprop) {
372
+ // the property that we'll be getting the ref from may not be populated yet, and might conceivably change at any time, so we
373
+ // need to $watch it. buildingBlocks.modelString will be something like "record.<array>[$index].<field>". replacing <field>
374
+ // with the value of refprop will give us a suitable watch expression.
375
+ const watchStr = buildingBlocks.modelString.substring(0, buildingBlocks.modelString.lastIndexOf(".") + 1) + processedAttrs.directiveOptions.refprop;
376
+ scope.$watch(watchStr, (newValue) => {
377
+ if (newValue && elemScope.ref !== newValue) {
378
+ elemScope.ref = newValue;
379
+ FngUISelectHelperService.doOwnConversion(scope, processedAttrs, elemScope.ref);
380
+ }
381
+ });
382
+ // we also need to re-do the conversion if the user cancels changes. this event does fire on more than just user cancellation,
383
+ // so this is slightly wasteful. but with the caching implemented by uiSelectHelper, this is no big deal.
384
+ scope.$on("fngCancel", () => {
385
+ $timeout(() => {
386
+ if (elemScope.ref) {
387
+ FngUISelectHelperService.doOwnConversion(scope, processedAttrs, elemScope.ref);
388
+ }
389
+ });
390
+ });
391
+ } else {
392
+ elemScope.ref = processedAttrs.info.ref;
393
+ }
394
+ scope[`${uniqueId}_options`] = [];
395
+ if (multiControl) {
396
+ select += '{{$select.selected.text}}';
397
+ } else if (processedAttrs.options.subschema) {
398
+ select += '{{' + attrs.model + '.' + processedAttrs.info.name.replace(processedAttrs.options.subschemaroot, processedAttrs.options.subschemaroot + '[$index]') + '.text}}';
399
+ } else {
400
+ select += '{{' + buildingBlocks.modelString + '.text}}';
401
+ }
402
+ select += '</ui-select-match>';
403
+ select += `<ui-select-choices repeat="option in (${uniqueId}_options) track by $index" `;
404
+ select += `refresh="refreshOptions($select.search, '${uniqueId}')" `;
405
+ select += 'refresh-delay="400"> ';
406
+ select += '<div ng-bind-html="option.text" ng-attr-title="{{ option.text }}"></div>';
407
+ } else if (processedAttrs.directiveOptions.deriveoptions) {
408
+ if (typeof scope[processedAttrs.directiveOptions.deriveoptions] === "function") {
409
+ select += optionsFromArray(multiControl, multi, scope[processedAttrs.directiveOptions.deriveoptions](), processedAttrs.directiveOptions.deriveoptions);
410
+ } else {
411
+ throw new Error("In fng-ui-select " + processedAttrs.directiveOptions.deriveoptions + " is not a function on the scope");
412
+ }
413
+ } else if (processedAttrs.info.options) {
414
+ // Simple case - enumerated options on the form scope
415
+ select += optionsFromArray(multiControl, multi, processedAttrs.info.options);
273
416
  } else {
274
- throw new Error("In fng-ui-select " + processedAttr.directiveOptions.deriveoptions + " is not a function on the scope");
417
+ throw new Error('fng-ui-select has no means of populating select');
275
418
  }
276
- } else if (processedAttr.info.options) {
277
- // Simple case - enumerated options on the form scope
278
- select += optionsFromArray(multiControl, multi, processedAttr.info.options);
279
- } else {
280
- throw new Error('fng-ui-select has no means of populating select');
419
+ select += '</ui-select-choices>';
420
+ select += '</ui-select>';
421
+ return select;
281
422
  }
282
- select += '</ui-select-choices>';
283
- select += '</ui-select>';
284
- return select;
285
- });
286
- scope.content = input + elementHtml;
423
+ );
287
424
  element.append($compile(input + elementHtml)(scope));
288
425
  }
289
426
  }
@@ -14,6 +14,19 @@
14
14
  background-color: rgba(255, 0, 0, 0.10);
15
15
  }
16
16
 
17
- .ui-select-container.ui-select-bootstrap {
18
- top: -4px;
19
- }
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
- };