cx 26.1.0 → 26.1.2

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 (540) hide show
  1. package/.mocharc.json +5 -5
  2. package/LICENSE-THIRD-PARTY.md +91 -91
  3. package/LICENSE.md +7 -7
  4. package/README.md +46 -46
  5. package/build/data/ArrayElementView.d.ts +4 -3
  6. package/build/ui/Widget.js +0 -5
  7. package/build/ui/adapter/ArrayAdapter.js +0 -2
  8. package/build/ui/adapter/DataAdapter.d.ts +3 -3
  9. package/build/util/Component.js +5 -0
  10. package/build/util/test/createTestRenderer.d.ts +3 -1
  11. package/build/util/test/createTestRenderer.js +8 -2
  12. package/build/widgets/icons/calendar.js +4 -3
  13. package/build/widgets/icons/check.js +2 -2
  14. package/build/widgets/icons/clear.js +2 -2
  15. package/build/widgets/icons/close.js +2 -2
  16. package/build/widgets/icons/cx.js +2 -2
  17. package/build/widgets/icons/drop-down.js +2 -2
  18. package/build/widgets/icons/file.js +2 -2
  19. package/build/widgets/icons/folder-open.js +2 -2
  20. package/build/widgets/icons/folder.js +2 -2
  21. package/build/widgets/icons/forward.js +2 -2
  22. package/build/widgets/icons/loading.js +2 -2
  23. package/build/widgets/icons/menu.js +2 -2
  24. package/build/widgets/icons/pixel-picker.js +2 -2
  25. package/build/widgets/icons/search.js +2 -2
  26. package/build/widgets/icons/sort-asc.js +2 -2
  27. package/build/widgets/icons/square.js +2 -2
  28. package/build.js +133 -133
  29. package/dist/manifest.js +863 -863
  30. package/dist/ui.js +1 -10
  31. package/dist/util.js +4 -0
  32. package/dist/widgets.js +377 -313
  33. package/package.json +100 -97
  34. package/src/charts/Bar.scss +28 -28
  35. package/src/charts/Bar.ts +114 -114
  36. package/src/charts/BarGraph.scss +28 -28
  37. package/src/charts/BarGraph.tsx +145 -145
  38. package/src/charts/BubbleGraph.scss +31 -31
  39. package/src/charts/BubbleGraph.tsx +165 -165
  40. package/src/charts/Chart.ts +108 -108
  41. package/src/charts/ColorMap.ts +150 -150
  42. package/src/charts/Column.scss +28 -28
  43. package/src/charts/Column.ts +124 -124
  44. package/src/charts/ColumnBarBase.tsx +284 -284
  45. package/src/charts/ColumnBarGraphBase.tsx +229 -229
  46. package/src/charts/ColumnGraph.scss +29 -29
  47. package/src/charts/ColumnGraph.tsx +153 -153
  48. package/src/charts/Grid.ts +5 -5
  49. package/src/charts/Gridlines.scss +24 -24
  50. package/src/charts/Gridlines.tsx +88 -88
  51. package/src/charts/Legend.scss +50 -50
  52. package/src/charts/Legend.tsx +270 -270
  53. package/src/charts/LegendEntry.scss +29 -29
  54. package/src/charts/LegendEntry.tsx +197 -197
  55. package/src/charts/LineGraph.scss +24 -24
  56. package/src/charts/LineGraph.tsx +455 -455
  57. package/src/charts/Marker.scss +43 -43
  58. package/src/charts/Marker.tsx +483 -483
  59. package/src/charts/MarkerLine.scss +19 -19
  60. package/src/charts/MarkerLine.tsx +214 -214
  61. package/src/charts/MouseTracker.tsx +112 -112
  62. package/src/charts/Pie.ts +8 -8
  63. package/src/charts/PieChart.scss +28 -28
  64. package/src/charts/PieChart.tsx +717 -717
  65. package/src/charts/PieLabel.tsx +106 -106
  66. package/src/charts/PieLabelsContainer.ts +68 -68
  67. package/src/charts/Range.scss +19 -19
  68. package/src/charts/Range.tsx +318 -318
  69. package/src/charts/RangeMarker.scss +17 -17
  70. package/src/charts/RangeMarker.tsx +233 -233
  71. package/src/charts/ScatterGraph.scss +23 -23
  72. package/src/charts/ScatterGraph.tsx +245 -245
  73. package/src/charts/Swimlane.scss +16 -16
  74. package/src/charts/Swimlane.tsx +195 -195
  75. package/src/charts/Swimlanes.scss +16 -16
  76. package/src/charts/Swimlanes.tsx +179 -179
  77. package/src/charts/axis/Axis.scss +22 -22
  78. package/src/charts/axis/Axis.tsx +444 -444
  79. package/src/charts/axis/CategoryAxis.scss +34 -34
  80. package/src/charts/axis/CategoryAxis.tsx +313 -313
  81. package/src/charts/axis/NumericAxis.scss +34 -34
  82. package/src/charts/axis/NumericAxis.tsx +437 -437
  83. package/src/charts/axis/Stack.ts +61 -61
  84. package/src/charts/axis/TimeAxis.scss +33 -33
  85. package/src/charts/axis/TimeAxis.tsx +718 -718
  86. package/src/charts/axis/index.scss +5 -5
  87. package/src/charts/axis/index.ts +3 -3
  88. package/src/charts/axis/variables.scss +2 -2
  89. package/src/charts/helpers/MinMaxFinder.ts +66 -66
  90. package/src/charts/helpers/PointReducer.ts +135 -135
  91. package/src/charts/helpers/SnapPointFinder.ts +136 -136
  92. package/src/charts/helpers/ValueAtFinder.ts +72 -72
  93. package/src/charts/helpers/index.ts +4 -4
  94. package/src/charts/index.scss +22 -22
  95. package/src/charts/index.ts +34 -34
  96. package/src/charts/palette.scss +97 -97
  97. package/src/charts/shapes.tsx +86 -86
  98. package/src/charts/variables.scss +22 -22
  99. package/src/data/AggregateFunction.ts +171 -171
  100. package/src/data/ArrayElementView.spec.ts +88 -88
  101. package/src/data/ArrayElementView.ts +4 -3
  102. package/src/data/ArrayRef.ts +34 -34
  103. package/src/data/Binding.spec.ts +69 -69
  104. package/src/data/Expression.spec.ts +229 -229
  105. package/src/data/Expression.ts +233 -233
  106. package/src/data/Grouper.ts +158 -158
  107. package/src/data/Ref.spec.ts +79 -79
  108. package/src/data/Selector.ts +10 -10
  109. package/src/data/Store.spec.ts +22 -22
  110. package/src/data/StoreRef.spec.ts +24 -24
  111. package/src/data/StringTemplate.spec.ts +132 -132
  112. package/src/data/StructuredSelector.ts +146 -146
  113. package/src/data/View.spec.ts +60 -60
  114. package/src/data/View.ts +289 -289
  115. package/src/data/ZoomIntoPropertyView.spec.ts +64 -64
  116. package/src/data/comparer.spec.ts +60 -60
  117. package/src/data/computable.spec.ts +87 -87
  118. package/src/data/computable.ts +69 -69
  119. package/src/data/createAccessorModelProxy.spec.tsx +145 -145
  120. package/src/data/createAccessorModelProxy.ts +66 -66
  121. package/src/data/createStructuredSelector.spec.ts +45 -45
  122. package/src/data/createStructuredSelector.ts +62 -62
  123. package/src/data/defaultCompare.ts +14 -14
  124. package/src/data/diff/diffArrays.ts +49 -49
  125. package/src/data/diff/diffs.spec.ts +49 -49
  126. package/src/data/diff/index.ts +1 -1
  127. package/src/data/enableFatArrowExpansion.ts +6 -6
  128. package/src/data/getAccessor.spec.ts +11 -11
  129. package/src/data/getAccessor.ts +74 -74
  130. package/src/data/getSelector.spec.ts +43 -43
  131. package/src/data/getSelector.ts +66 -66
  132. package/src/data/index.ts +30 -30
  133. package/src/data/isSelector.ts +26 -26
  134. package/src/data/ops/append.spec.ts +28 -28
  135. package/src/data/ops/append.ts +5 -5
  136. package/src/data/ops/filter.spec.ts +35 -35
  137. package/src/data/ops/filter.ts +9 -9
  138. package/src/data/ops/findTreeNode.spec.ts +23 -23
  139. package/src/data/ops/findTreeNode.ts +14 -14
  140. package/src/data/ops/findTreePath.ts +23 -23
  141. package/src/data/ops/index.ts +11 -11
  142. package/src/data/ops/insertElement.ts +3 -3
  143. package/src/data/ops/merge.spec.ts +27 -27
  144. package/src/data/ops/merge.ts +13 -13
  145. package/src/data/ops/moveElement.ts +21 -21
  146. package/src/data/ops/removeTreeNodes.spec.ts +37 -37
  147. package/src/data/ops/removeTreeNodes.ts +15 -15
  148. package/src/data/ops/updateArray.spec.ts +69 -69
  149. package/src/data/ops/updateTree.spec.ts +54 -54
  150. package/src/data/ops/updateTree.ts +23 -23
  151. package/src/data/test-types.ts +7 -7
  152. package/src/global.scss +13 -13
  153. package/src/hooks/createLocalStorageRef.ts +21 -21
  154. package/src/hooks/index.ts +8 -8
  155. package/src/hooks/invokeCallback.spec.tsx +59 -59
  156. package/src/hooks/invokeCallback.ts +8 -8
  157. package/src/hooks/resolveCallback.spec.tsx +71 -71
  158. package/src/hooks/resolveCallback.ts +16 -16
  159. package/src/hooks/store.spec.tsx +67 -67
  160. package/src/hooks/store.ts +46 -46
  161. package/src/hooks/useEffect.ts +14 -14
  162. package/src/hooks/useInterval.ts +8 -8
  163. package/src/hooks/useState.ts +20 -20
  164. package/src/hooks/useTrigger.spec.tsx +105 -99
  165. package/src/hooks/useTrigger.ts +26 -26
  166. package/src/index.ts +7 -7
  167. package/src/jsx-runtime.spec.tsx +431 -431
  168. package/src/locale/de-de.ts +76 -76
  169. package/src/locale/en-us.ts +75 -75
  170. package/src/locale/es-es.ts +76 -76
  171. package/src/locale/fr-fr.ts +76 -76
  172. package/src/locale/nl-nl.ts +76 -76
  173. package/src/locale/pt-pt.ts +76 -76
  174. package/src/locale/sr-latn-ba.ts +76 -76
  175. package/src/svg/BoundedObject.ts +101 -101
  176. package/src/svg/ClipRect.tsx +29 -29
  177. package/src/svg/Ellipse.tsx +68 -68
  178. package/src/svg/Line.tsx +58 -58
  179. package/src/svg/NonOverlappingRect.ts +26 -26
  180. package/src/svg/NonOverlappingRectGroup.ts +49 -49
  181. package/src/svg/Rectangle.tsx +90 -90
  182. package/src/svg/Svg.scss +27 -27
  183. package/src/svg/Svg.tsx +241 -241
  184. package/src/svg/Text.tsx +134 -134
  185. package/src/svg/TextualBoundedObject.ts +35 -35
  186. package/src/svg/index.scss +8 -8
  187. package/src/svg/index.ts +17 -17
  188. package/src/svg/util/Rect.ts +105 -105
  189. package/src/ui/CSSHelper.ts +17 -17
  190. package/src/ui/Container.tsx +216 -216
  191. package/src/ui/ContentResolver.spec.tsx +585 -583
  192. package/src/ui/ContentResolver.ts +132 -132
  193. package/src/ui/Controller.spec.tsx +574 -566
  194. package/src/ui/Controller.ts +202 -202
  195. package/src/ui/Culture.ts +159 -159
  196. package/src/ui/Cx.spec.tsx +210 -208
  197. package/src/ui/Cx.tsx +386 -386
  198. package/src/ui/DataProxy.spec.tsx +337 -337
  199. package/src/ui/DetachedScope.tsx +159 -159
  200. package/src/ui/Format.ts +108 -108
  201. package/src/ui/HoverSync.tsx +189 -189
  202. package/src/ui/Instance.ts +866 -866
  203. package/src/ui/IsolatedScope.spec.tsx +62 -55
  204. package/src/ui/IsolatedScope.ts +50 -50
  205. package/src/ui/Localization.ts +70 -70
  206. package/src/ui/Prop.ts +140 -140
  207. package/src/ui/PureContainer.spec.tsx +232 -230
  208. package/src/ui/PureContainer.tsx +19 -19
  209. package/src/ui/RenderingContext.ts +99 -99
  210. package/src/ui/Repeater.spec.tsx +143 -141
  211. package/src/ui/Repeater.ts +194 -194
  212. package/src/ui/Rescope.spec.tsx +199 -199
  213. package/src/ui/ResizeManager.ts +30 -30
  214. package/src/ui/Restate.spec.tsx +422 -418
  215. package/src/ui/Restate.tsx +217 -217
  216. package/src/ui/StaticText.ts +11 -11
  217. package/src/ui/StructuredInstanceDataAccessor.ts +32 -32
  218. package/src/ui/Text.ts +49 -49
  219. package/src/ui/Widget.spec.tsx +53 -53
  220. package/src/ui/Widget.tsx +301 -308
  221. package/src/ui/ZIndexManager.ts +11 -11
  222. package/src/ui/adapter/ArrayAdapter.ts +229 -229
  223. package/src/ui/adapter/DataAdapter.ts +52 -52
  224. package/src/ui/adapter/GroupAdapter.ts +235 -235
  225. package/src/ui/adapter/TreeAdapter.spec.ts +76 -76
  226. package/src/ui/adapter/TreeAdapter.ts +185 -185
  227. package/src/ui/adapter/index.ts +4 -4
  228. package/src/ui/app/History.ts +133 -133
  229. package/src/ui/app/Url.spec.ts +50 -50
  230. package/src/ui/app/Url.ts +102 -102
  231. package/src/ui/app/index.ts +5 -5
  232. package/src/ui/app/startAppLoop.tsx +71 -71
  233. package/src/ui/app/startHotAppLoop.ts +41 -41
  234. package/src/ui/batchUpdates.ts +77 -77
  235. package/src/ui/bind.ts +10 -10
  236. package/src/ui/createFunctionalComponent.spec.tsx +454 -452
  237. package/src/ui/createFunctionalComponent.ts +86 -86
  238. package/src/ui/expr.ts +47 -47
  239. package/src/ui/exprHelpers.spec.ts +379 -379
  240. package/src/ui/exprHelpers.ts +78 -78
  241. package/src/ui/flattenProps.ts +21 -21
  242. package/src/ui/index.scss +2 -2
  243. package/src/ui/index.ts +47 -47
  244. package/src/ui/keyboardShortcuts.ts +40 -40
  245. package/src/ui/layout/ContentPlaceholder.spec.tsx +599 -587
  246. package/src/ui/layout/ContentPlaceholder.ts +133 -133
  247. package/src/ui/layout/FirstVisibleChildLayout.spec.tsx +207 -195
  248. package/src/ui/layout/FirstVisibleChildLayout.ts +60 -60
  249. package/src/ui/layout/LabelsLeftLayout.scss +46 -46
  250. package/src/ui/layout/LabelsLeftLayout.tsx +76 -76
  251. package/src/ui/layout/LabelsTopLayout.scss +64 -64
  252. package/src/ui/layout/LabelsTopLayout.tsx +156 -156
  253. package/src/ui/layout/UseParentLayout.ts +8 -8
  254. package/src/ui/layout/exploreChildren.ts +38 -38
  255. package/src/ui/layout/index.scss +3 -3
  256. package/src/ui/layout/index.ts +10 -10
  257. package/src/ui/layout/variables.scss +2 -2
  258. package/src/ui/selection/KeySelection.ts +153 -153
  259. package/src/ui/selection/Selection.ts +128 -128
  260. package/src/ui/selection/index.ts +3 -3
  261. package/src/ui/tpl.ts +4 -4
  262. package/src/ui/variables.scss +1 -1
  263. package/src/util/Component.spec.ts +411 -381
  264. package/src/util/Component.ts +301 -296
  265. package/src/util/Console.ts +13 -13
  266. package/src/util/Debug.ts +71 -71
  267. package/src/util/GlobalCacheIdentifier.ts +11 -11
  268. package/src/util/KeyCode.ts +21 -21
  269. package/src/util/SubscriberList.ts +86 -86
  270. package/src/util/Timing.ts +58 -58
  271. package/src/util/TraversalStack.spec.ts +53 -53
  272. package/src/util/TraversalStack.ts +47 -47
  273. package/src/util/calculateNaturalElementHeight.ts +22 -22
  274. package/src/util/call-once.scss +6 -6
  275. package/src/util/capitalize.ts +4 -4
  276. package/src/util/coalesce.ts +6 -6
  277. package/src/util/color/hslToRgb.ts +34 -34
  278. package/src/util/color/index.ts +4 -4
  279. package/src/util/color/parseColor.ts +173 -173
  280. package/src/util/color/rgbToHex.ts +14 -14
  281. package/src/util/date/dateDiff.ts +9 -9
  282. package/src/util/date/diff.ts +13 -13
  283. package/src/util/date/encodeDate.ts +8 -8
  284. package/src/util/date/encodeDateWithTimezoneOffset.ts +18 -18
  285. package/src/util/date/index.ts +11 -11
  286. package/src/util/date/lowerBoundCheck.ts +13 -13
  287. package/src/util/date/maxDate.ts +14 -14
  288. package/src/util/date/minDate.ts +14 -14
  289. package/src/util/date/monthStart.ts +8 -8
  290. package/src/util/date/parseDateInvariant.ts +20 -20
  291. package/src/util/date/sameDate.ts +11 -11
  292. package/src/util/date/upperBoundCheck.spec.ts +30 -30
  293. package/src/util/date/upperBoundCheck.ts +13 -13
  294. package/src/util/date/zeroTime.ts +9 -9
  295. package/src/util/debounce.ts +26 -26
  296. package/src/util/dummyCallback.ts +1 -1
  297. package/src/util/escapeSpecialRegexCharacters.ts +8 -8
  298. package/src/util/eventCallbacks.ts +12 -12
  299. package/src/util/expandFatArrows.ts +118 -118
  300. package/src/util/findScrollableParent.ts +15 -15
  301. package/src/util/getParentFrameBoundingClientRect.ts +13 -13
  302. package/src/util/getScrollerBoundingClientRect.ts +12 -12
  303. package/src/util/getSearchQueryPredicate.spec.ts +40 -40
  304. package/src/util/getSearchQueryPredicate.ts +58 -58
  305. package/src/util/getTopLevelBoundingClientRect.ts +7 -7
  306. package/src/util/getVendorPrefix.ts +33 -33
  307. package/src/util/hasKey.ts +18 -18
  308. package/src/util/index.scss +10 -10
  309. package/src/util/index.ts +55 -55
  310. package/src/util/isArray.ts +3 -3
  311. package/src/util/isDefined.ts +3 -3
  312. package/src/util/isDigit.ts +8 -8
  313. package/src/util/isFunction.ts +3 -3
  314. package/src/util/isNonEmptyArray.ts +3 -3
  315. package/src/util/isNumber.ts +3 -3
  316. package/src/util/isObject.ts +3 -3
  317. package/src/util/isPromise.ts +6 -6
  318. package/src/util/isString.ts +3 -3
  319. package/src/util/isTextInputElement.ts +2 -2
  320. package/src/util/isTouchDevice.ts +7 -7
  321. package/src/util/isTouchEvent.ts +64 -64
  322. package/src/util/isUndefined.ts +3 -3
  323. package/src/util/isValidIdentifierName.spec.ts +33 -33
  324. package/src/util/isValidIdentifierName.ts +5 -5
  325. package/src/util/onIdleCallback.ts +10 -10
  326. package/src/util/parseStyle.ts +29 -29
  327. package/src/util/quote.ts +6 -6
  328. package/src/util/reverseSlice.ts +9 -9
  329. package/src/util/routeAppend.spec.ts +19 -19
  330. package/src/util/routeAppend.ts +15 -15
  331. package/src/util/scrollElementIntoView.ts +40 -40
  332. package/src/util/scss/add-rules.scss +40 -40
  333. package/src/util/scss/calc.scss +44 -44
  334. package/src/util/scss/call-once.scss +12 -12
  335. package/src/util/scss/clockwise.scss +49 -49
  336. package/src/util/scss/colors.scss +9 -9
  337. package/src/util/scss/deep-get.scss +11 -11
  338. package/src/util/scss/deep-merge.scss +21 -21
  339. package/src/util/scss/divide.scss +3 -3
  340. package/src/util/scss/include.scss +48 -48
  341. package/src/util/scss/index.scss +9 -9
  342. package/src/util/shallowEquals.ts +43 -43
  343. package/src/util/test/createTestRenderer.tsx +19 -12
  344. package/src/util/throttle.ts +21 -21
  345. package/src/util/validatedDebounce.ts +23 -23
  346. package/src/variables.scss +217 -217
  347. package/src/widgets/AccessorBindings.spec.tsx +90 -90
  348. package/src/widgets/Button.scss +119 -119
  349. package/src/widgets/Button.tsx +189 -189
  350. package/src/widgets/Button.variables.scss +117 -117
  351. package/src/widgets/CxCredit.scss +39 -39
  352. package/src/widgets/CxCredit.tsx +46 -46
  353. package/src/widgets/DocumentTitle.ts +95 -95
  354. package/src/widgets/FlexBox.scss +148 -148
  355. package/src/widgets/FlexBox.tsx +168 -168
  356. package/src/widgets/Heading.scss +40 -40
  357. package/src/widgets/Heading.ts +42 -42
  358. package/src/widgets/HighlightedSearchText.scss +20 -20
  359. package/src/widgets/HighlightedSearchText.tsx +54 -54
  360. package/src/widgets/HtmlElement.spec.helpers.tsx +108 -108
  361. package/src/widgets/HtmlElement.spec.tsx +89 -89
  362. package/src/widgets/HtmlElement.tsx +407 -407
  363. package/src/widgets/Icon.scss +22 -22
  364. package/src/widgets/Icon.ts +64 -64
  365. package/src/widgets/List.scss +93 -93
  366. package/src/widgets/List.tsx +793 -793
  367. package/src/widgets/ProgressBar.scss +50 -50
  368. package/src/widgets/ProgressBar.tsx +66 -66
  369. package/src/widgets/ReactElementWrapper.spec.tsx +452 -452
  370. package/src/widgets/ReactElementWrapper.tsx +108 -108
  371. package/src/widgets/Resizer.scss +43 -43
  372. package/src/widgets/Resizer.tsx +200 -200
  373. package/src/widgets/Section.scss +55 -55
  374. package/src/widgets/Section.tsx +187 -187
  375. package/src/widgets/animations.scss +10 -10
  376. package/src/widgets/autoFocus.ts +9 -9
  377. package/src/widgets/cx.ts +63 -63
  378. package/src/widgets/drag-drop/DragClone.scss +35 -35
  379. package/src/widgets/drag-drop/DragHandle.scss +18 -18
  380. package/src/widgets/drag-drop/DragHandle.tsx +47 -47
  381. package/src/widgets/drag-drop/DragSource.scss +26 -26
  382. package/src/widgets/drag-drop/DragSource.tsx +237 -237
  383. package/src/widgets/drag-drop/DropZone.scss +76 -76
  384. package/src/widgets/drag-drop/DropZone.tsx +353 -353
  385. package/src/widgets/drag-drop/index.scss +3 -3
  386. package/src/widgets/drag-drop/index.ts +4 -4
  387. package/src/widgets/drag-drop/ops.tsx +422 -422
  388. package/src/widgets/drag-drop/variables.scss +14 -14
  389. package/src/widgets/enableAllInternalDependencies.ts +11 -11
  390. package/src/widgets/form/Calendar.scss +199 -199
  391. package/src/widgets/form/Calendar.tsx +760 -760
  392. package/src/widgets/form/Calendar.variables.scss +63 -63
  393. package/src/widgets/form/Checkbox.scss +129 -129
  394. package/src/widgets/form/Checkbox.tsx +287 -287
  395. package/src/widgets/form/Checkbox.variables.scss +39 -39
  396. package/src/widgets/form/ColorField.scss +98 -98
  397. package/src/widgets/form/ColorField.tsx +497 -497
  398. package/src/widgets/form/ColorPicker.scss +285 -285
  399. package/src/widgets/form/ColorPicker.tsx +544 -544
  400. package/src/widgets/form/ColorPicker.variables.scss +22 -22
  401. package/src/widgets/form/DateField.ts +21 -21
  402. package/src/widgets/form/DateTimeField.scss +92 -92
  403. package/src/widgets/form/DateTimeField.tsx +726 -726
  404. package/src/widgets/form/DateTimePicker.scss +46 -46
  405. package/src/widgets/form/DateTimePicker.tsx +429 -429
  406. package/src/widgets/form/Field.scss +164 -164
  407. package/src/widgets/form/Field.tsx +608 -608
  408. package/src/widgets/form/FieldGroup.ts +10 -10
  409. package/src/widgets/form/FieldIcon.ts +61 -61
  410. package/src/widgets/form/HelpText.scss +24 -24
  411. package/src/widgets/form/HelpText.ts +15 -15
  412. package/src/widgets/form/Label.scss +37 -37
  413. package/src/widgets/form/Label.tsx +117 -117
  414. package/src/widgets/form/LabeledContainer.ts +77 -77
  415. package/src/widgets/form/LookupField.scss +221 -221
  416. package/src/widgets/form/LookupField.spec.tsx +93 -93
  417. package/src/widgets/form/LookupField.tsx +1421 -1421
  418. package/src/widgets/form/MonthField.scss +100 -100
  419. package/src/widgets/form/MonthField.tsx +670 -670
  420. package/src/widgets/form/MonthPicker.scss +125 -125
  421. package/src/widgets/form/MonthPicker.tsx +822 -822
  422. package/src/widgets/form/NumberField.scss +63 -63
  423. package/src/widgets/form/NumberField.tsx +543 -543
  424. package/src/widgets/form/Radio.scss +123 -123
  425. package/src/widgets/form/Radio.tsx +249 -249
  426. package/src/widgets/form/Radio.variables.scss +45 -45
  427. package/src/widgets/form/Select.scss +101 -101
  428. package/src/widgets/form/Select.tsx +327 -327
  429. package/src/widgets/form/Slider.scss +121 -121
  430. package/src/widgets/form/Slider.tsx +473 -473
  431. package/src/widgets/form/Switch.scss +142 -142
  432. package/src/widgets/form/Switch.tsx +176 -176
  433. package/src/widgets/form/TextArea.scss +45 -45
  434. package/src/widgets/form/TextArea.tsx +229 -229
  435. package/src/widgets/form/TextField.scss +57 -57
  436. package/src/widgets/form/TextField.tsx +407 -407
  437. package/src/widgets/form/TimeField.ts +10 -10
  438. package/src/widgets/form/TimeList.tsx +105 -105
  439. package/src/widgets/form/UploadButton.scss +49 -49
  440. package/src/widgets/form/UploadButton.tsx +307 -307
  441. package/src/widgets/form/ValidationError.scss +22 -22
  442. package/src/widgets/form/ValidationError.tsx +72 -72
  443. package/src/widgets/form/ValidationGroup.spec.tsx +147 -147
  444. package/src/widgets/form/ValidationGroup.ts +141 -141
  445. package/src/widgets/form/Validator.ts +60 -60
  446. package/src/widgets/form/Wheel.scss +152 -152
  447. package/src/widgets/form/Wheel.tsx +314 -314
  448. package/src/widgets/form/index.scss +24 -24
  449. package/src/widgets/form/index.ts +28 -28
  450. package/src/widgets/form/variables.scss +355 -355
  451. package/src/widgets/grid/Grid.scss +640 -640
  452. package/src/widgets/grid/Grid.tsx +4243 -4243
  453. package/src/widgets/grid/GridCellEditor.tsx +58 -58
  454. package/src/widgets/grid/GridRow.ts +302 -302
  455. package/src/widgets/grid/GridRowLine.ts +49 -49
  456. package/src/widgets/grid/Pagination.scss +115 -115
  457. package/src/widgets/grid/Pagination.tsx +126 -126
  458. package/src/widgets/grid/TreeNode.scss +90 -90
  459. package/src/widgets/grid/TreeNode.tsx +154 -154
  460. package/src/widgets/grid/createGridCellEditor.tsx +18 -18
  461. package/src/widgets/grid/index.scss +3 -3
  462. package/src/widgets/grid/index.ts +16 -16
  463. package/src/widgets/grid/variables.scss +137 -137
  464. package/src/widgets/icons/arrow-down.svg +3 -3
  465. package/src/widgets/icons/arrow-right.svg +2 -2
  466. package/src/widgets/icons/base.svg +104 -104
  467. package/src/widgets/icons/calendar-old.svg +169 -169
  468. package/src/widgets/icons/calendar.svg +187 -187
  469. package/src/widgets/icons/calendar.tsx +20 -15
  470. package/src/widgets/icons/check.tsx +2 -1
  471. package/src/widgets/icons/clear.svg +74 -74
  472. package/src/widgets/icons/clear.tsx +2 -1
  473. package/src/widgets/icons/close.svg +74 -74
  474. package/src/widgets/icons/close.tsx +2 -2
  475. package/src/widgets/icons/cx.tsx +2 -1
  476. package/src/widgets/icons/drop-down.tsx +2 -1
  477. package/src/widgets/icons/dropdown-arrow.svg +61 -61
  478. package/src/widgets/icons/file.svg +4 -4
  479. package/src/widgets/icons/file.tsx +2 -1
  480. package/src/widgets/icons/folder-open.svg +5 -5
  481. package/src/widgets/icons/folder-open.tsx +2 -1
  482. package/src/widgets/icons/folder.svg +58 -58
  483. package/src/widgets/icons/folder.tsx +2 -1
  484. package/src/widgets/icons/forward.svg +67 -67
  485. package/src/widgets/icons/forward.tsx +2 -1
  486. package/src/widgets/icons/index.ts +14 -14
  487. package/src/widgets/icons/loading.svg +4 -4
  488. package/src/widgets/icons/loading.tsx +2 -1
  489. package/src/widgets/icons/menu.tsx +2 -1
  490. package/src/widgets/icons/pixel-picker.tsx +2 -2
  491. package/src/widgets/icons/registry.ts +56 -56
  492. package/src/widgets/icons/search.svg +107 -107
  493. package/src/widgets/icons/search.tsx +2 -1
  494. package/src/widgets/icons/sort-asc.svg +3 -3
  495. package/src/widgets/icons/sort-asc.tsx +2 -1
  496. package/src/widgets/icons/square.tsx +2 -1
  497. package/src/widgets/index.d.ts +55 -55
  498. package/src/widgets/index.scss +16 -16
  499. package/src/widgets/index.ts +58 -58
  500. package/src/widgets/nav/Link.scss +20 -20
  501. package/src/widgets/nav/Link.ts +11 -11
  502. package/src/widgets/nav/LinkButton.ts +176 -176
  503. package/src/widgets/nav/Menu.scss +76 -76
  504. package/src/widgets/nav/Menu.tsx +489 -489
  505. package/src/widgets/nav/Menu.variables.scss +25 -25
  506. package/src/widgets/nav/MenuItem.scss +130 -130
  507. package/src/widgets/nav/MenuItem.tsx +525 -525
  508. package/src/widgets/nav/MenuSpacer.ts +18 -18
  509. package/src/widgets/nav/RedirectRoute.ts +49 -49
  510. package/src/widgets/nav/Route.spec.tsx +24 -24
  511. package/src/widgets/nav/Scroller.scss +148 -148
  512. package/src/widgets/nav/Scroller.tsx +252 -252
  513. package/src/widgets/nav/Submenu.ts +6 -6
  514. package/src/widgets/nav/Tab.scss +82 -82
  515. package/src/widgets/nav/Tab.ts +120 -120
  516. package/src/widgets/nav/Tab.variables.scss +84 -84
  517. package/src/widgets/nav/cover.scss +22 -22
  518. package/src/widgets/nav/index.scss +5 -5
  519. package/src/widgets/nav/index.ts +10 -10
  520. package/src/widgets/nav/variables.scss +27 -27
  521. package/src/widgets/overlay/ContextMenu.ts +42 -42
  522. package/src/widgets/overlay/Dropdown.scss +186 -186
  523. package/src/widgets/overlay/FlyweightTooltipTracker.ts +57 -57
  524. package/src/widgets/overlay/Overlay.scss +68 -68
  525. package/src/widgets/overlay/Overlay.tsx +947 -947
  526. package/src/widgets/overlay/Toast.scss +163 -163
  527. package/src/widgets/overlay/Tooltip.scss +177 -177
  528. package/src/widgets/overlay/Tooltip.tsx +393 -393
  529. package/src/widgets/overlay/Window.scss +129 -129
  530. package/src/widgets/overlay/Window.variables.scss +62 -62
  531. package/src/widgets/overlay/captureMouse.scss +13 -13
  532. package/src/widgets/overlay/captureMouse.ts +195 -195
  533. package/src/widgets/overlay/createHotPromiseWindowFactory.ts +71 -71
  534. package/src/widgets/overlay/index.scss +15 -15
  535. package/src/widgets/overlay/tooltip-ops.ts +173 -173
  536. package/src/widgets/overlay/variables.scss +85 -85
  537. package/src/widgets/variables.scss +146 -146
  538. package/tsconfig.compile.json +4 -4
  539. package/tsconfig.json +34 -34
  540. package/tsconfig.mocha.json +14 -14
@@ -1,1421 +1,1421 @@
1
- /**@jsxImportSource react */
2
- import { Widget, VDOM, getContent } from "../../ui/Widget";
3
- import { Cx } from "../../ui/Cx";
4
- import { Field, getFieldTooltip, FieldInstance } from "./Field";
5
- import { ReadOnlyDataView } from "../../data/ReadOnlyDataView";
6
- import { HtmlElement, HtmlElementInstance } from "../HtmlElement";
7
- import { Binding, BindingInput } from "../../data/Binding";
8
- import { debug } from "../../util/Debug";
9
- import { Dropdown, DropdownConfig } from "../overlay/Dropdown";
10
- import { FocusManager } from "../../ui/FocusManager";
11
- import { isFocused } from "../../util/DOM";
12
- import { isTouchDevice } from "../../util/isTouchDevice";
13
- import { isTouchEvent } from "../../util/isTouchEvent";
14
- import {
15
- tooltipParentWillReceiveProps,
16
- tooltipParentWillUnmount,
17
- tooltipMouseMove,
18
- tooltipMouseLeave,
19
- tooltipParentDidMount,
20
- } from "../overlay/tooltip-ops";
21
- import { stopPropagation, preventDefault } from "../../util/eventCallbacks";
22
- import ClearIcon from "../icons/clear";
23
- import DropdownIcon from "../icons/drop-down";
24
- import { getSearchQueryPredicate } from "../../util/getSearchQueryPredicate";
25
- import { KeyCode } from "../../util/KeyCode";
26
- import { Localization } from "../../ui/Localization";
27
- import { StringTemplate } from "../../data/StringTemplate";
28
- import { Icon } from "../Icon";
29
- import { isString } from "../../util/isString";
30
- import { isDefined } from "../../util/isDefined";
31
- import { isArray } from "../../util/isArray";
32
- import { isNonEmptyArray } from "../../util/isNonEmptyArray";
33
- import { addEventListenerWithOptions } from "../../util/addEventListenerWithOptions";
34
- import { List } from "../List";
35
- import { Selection } from "../../ui/selection/Selection";
36
- import { HighlightedSearchText } from "../HighlightedSearchText";
37
- import { autoFocus } from "../autoFocus";
38
- import { bind } from "../../ui";
39
- import { AccessorChain, isAccessorChain } from "../../data/createAccessorModelProxy";
40
- import type { CxChild, RenderingContext } from "../../ui/RenderingContext";
41
- import type { DropdownInstance, Instance } from "../../ui/Instance";
42
- import { FieldConfig } from "./Field";
43
- import { Prop, BooleanProp, StringProp, StructuredProp, DataRecord } from "../../ui/Prop";
44
-
45
- export interface LookupBinding {
46
- local: string;
47
- remote: string;
48
- key?: boolean;
49
- }
50
-
51
- export interface LookupFieldConfig<TOption = unknown, TRecord = unknown> extends FieldConfig {
52
- /** Defaults to `false`. Set to `true` to enable multiple selection. */
53
- multiple?: BooleanProp;
54
-
55
- /** Selected value. Used only if `multiple` is set to `false`. */
56
- value?: Prop<number | string>;
57
-
58
- /** A list of selected ids. Used only if `multiple` is set to `true`. */
59
- values?: Prop<(number | string)[]>;
60
-
61
- /** A list of selected records. Used only if `multiple` is set to `true`. */
62
- records?: Prop<TRecord[]>;
63
-
64
- /** Text associated with the selection. Used only if `multiple` is set to `false`. */
65
- text?: StringProp;
66
-
67
- /** The opposite of `disabled`. */
68
- enabled?: BooleanProp;
69
-
70
- /** Defaults to `false`. Used to make the field read-only. */
71
- readOnly?: BooleanProp;
72
-
73
- /** Default text displayed when the field is empty. */
74
- placeholder?: StringProp;
75
-
76
- /** A list of available options. */
77
- options?: Prop<TOption[]>;
78
-
79
- /** Set to `true` to hide the clear button. Default value is `false`. */
80
- hideClear?: boolean;
81
-
82
- /** Set to `false` to hide the clear button. Default value is `true`. */
83
- showClear?: boolean;
84
-
85
- /** Set to `true` to display the clear button even if `required` is set. Default is `false`. */
86
- alwaysShowClear?: boolean;
87
-
88
- /** Base CSS class to be applied to the field. Defaults to `lookupfield`. */
89
- baseClass?: string;
90
-
91
- /** Name or configuration of the icon to be put on the left side of the input. */
92
- icon?: StringProp | Record<string, any>;
93
-
94
- /** Additional config to be applied to all items. */
95
- itemConfig?: any;
96
-
97
- /** An array of objects describing the mapping of option data to store data. */
98
- bindings?: LookupBinding[];
99
-
100
- /** A delay in milliseconds between typing stop and query. Default is `150`. */
101
- queryDelay?: number;
102
-
103
- /** Minimal number of characters required before query is made. */
104
- minQueryLength?: number;
105
-
106
- /** Set to `true` to hide the search field. */
107
- hideSearchField?: boolean;
108
-
109
- /** Number of options required to show search field. Defaults to `7`. */
110
- minOptionsForSearchField?: number;
111
-
112
- /** Text to display while data is being loaded. */
113
- loadingText?: string;
114
-
115
- /** Error message displayed if server query throws an exception. */
116
- queryErrorText?: string;
117
-
118
- /** Message to be displayed if no entries match the user query. */
119
- noResultsText?: string;
120
-
121
- /** Name of the field which holds the id of the option. Default is `id`. */
122
- optionIdField?: string;
123
-
124
- /** Name of the field which holds the display text of the option. Default is `text`. */
125
- optionTextField?: string;
126
-
127
- /** Name of the field to store id of selected value in multiple mode. Default is `id`. */
128
- valueIdField?: string;
129
-
130
- /** Name of the field to store display text of selected value. Default is `text`. */
131
- valueTextField?: string;
132
-
133
- /** `onQuery` will be called once to fetch all options; filtering occurs client-side. */
134
- fetchAll?: boolean;
135
-
136
- /** When set with `fetchAll`, fetched options are cached for widget lifetime. */
137
- cacheAll?: boolean;
138
-
139
- /** Close the dropdown after selection. Default is `true`. */
140
- closeOnSelect?: boolean;
141
-
142
- /** Message displayed if the entered search query is too short. */
143
- minQueryLengthMessageText?: string;
144
-
145
- /** Query function called to fetch options. */
146
- onQuery?:
147
- | string
148
- | ((
149
- query: string | { query: string; page: number; pageSize: number },
150
- instance: Instance,
151
- ) => TOption[] | Promise<TOption[]>);
152
-
153
- /** Set to `true` to sort dropdown options. */
154
- sort?: boolean;
155
-
156
- /** Additional list options, such as grouping configuration, custom sorting, etc. */
157
- listOptions?: Record<string, any>;
158
-
159
- /** Show dropdown immediately after component mount; useful for cell editing. */
160
- autoOpen?: BooleanProp;
161
-
162
- /** Allow enter key events to propagate; useful for forms or grid cell editors. */
163
- submitOnEnterKey?: BooleanProp;
164
-
165
- /** Allow dropdown enter key events to propagate for form submission. */
166
- submitOnDropdownEnterKey?: BooleanProp;
167
-
168
- /** Number of additional items loaded in `infinite` mode. Default is `100`. */
169
- pageSize?: number;
170
-
171
- /** Set to `true` to enable loading additional options when scroll reaches end. */
172
- infinite?: boolean;
173
-
174
- /** Allow quick selection of all displayed items on `Ctrl + A` key combination. */
175
- quickSelectAll?: boolean;
176
-
177
- /** Parameters that affect filtering. */
178
- filterParams?: StructuredProp;
179
-
180
- /** Used in multiple selection lookups to construct display text from multiple fields. */
181
- onGetRecordDisplayText?: ((record: TRecord, instance: Instance) => string) | null;
182
-
183
- /** Callback to create a filter function for given filter params. */
184
- onCreateVisibleOptionsFilter?:
185
- | string
186
- | ((filterParams: unknown, instance: Instance) => (option: TOption) => boolean);
187
-
188
- /** Additional configuration to be passed to the dropdown, such as `style`, `positioning`, etc. */
189
- dropdownOptions?: Partial<DropdownConfig>;
190
-
191
- /** Custom validation function. */
192
- onValidate?:
193
- | string
194
- | ((value: number | string, instance: Instance, validationParams: Record<string, unknown>) => unknown);
195
- }
196
-
197
- export class LookupField<TOption = unknown, TRecord = unknown> extends Field<
198
- LookupFieldConfig<TOption, TRecord>
199
- > {
200
- declare public baseClass: string;
201
- declare public multiple: boolean;
202
- declare public hideClear?: boolean;
203
- declare public showClear: boolean;
204
- declare public alwaysShowClear: boolean;
205
- declare public hideSearchField: boolean;
206
- declare public minOptionsForSearchField: number;
207
- declare public loadingText: string;
208
- declare public queryErrorText: string;
209
- declare public noResultsText: string;
210
- declare public optionIdField: string;
211
- declare public optionTextField: string;
212
- declare public valueIdField: string;
213
- declare public valueTextField: string;
214
- declare public fetchAll: boolean;
215
- declare public cacheAll: boolean;
216
- declare public closeOnSelect: boolean;
217
- declare public minQueryLengthMessageText: string;
218
- declare public sort?: boolean;
219
- declare public listOptions?: Record<string, any> | null;
220
- declare public autoOpen?: boolean;
221
- declare public submitOnEnterKey?: boolean;
222
- declare public submitOnDropdownEnterKey?: boolean;
223
- declare public pageSize: number;
224
- declare public infinite?: boolean;
225
- declare public quickSelectAll?: boolean;
226
- declare public queryDelay: number;
227
- declare public minQueryLength: number;
228
- declare public onGetRecordDisplayText?: ((record: Record<string, any>, instance: Instance) => string) | null;
229
- declare public onQuery?:
230
- | string
231
- | ((
232
- params: string | { query: string; page: number; pageSize: number },
233
- instance: Instance,
234
- ) => Promise<Record<string, any>[]> | Record<string, any>[]);
235
- declare public onCreateVisibleOptionsFilter?:
236
- | string
237
- | ((filterParams: unknown, instance: Instance) => (option: Record<string, any>) => boolean);
238
- declare public value?: BindingInput;
239
- declare public text?: BindingInput<string>;
240
- declare public records?: Record<string, any>[];
241
- declare public values?: unknown[];
242
- declare public options?: Record<string, any>[];
243
-
244
- declare public enabled?: boolean;
245
- declare public placeholder?: string;
246
- declare public readOnly?: boolean;
247
- declare public dropdownOptions?: Partial<DropdownConfig>;
248
- declare public bindings?: BindingConfig[];
249
- declare public keyBindings?: BindingConfig[];
250
- declare public itemConfig?: CxChild;
251
-
252
- declareData(...args: Record<string, any>[]): void {
253
- let additionalAttributes = this.multiple
254
- ? { values: undefined, records: undefined }
255
- : { value: undefined, text: undefined };
256
-
257
- super.declareData(
258
- {
259
- disabled: undefined,
260
- enabled: undefined,
261
- placeholder: undefined,
262
- required: undefined,
263
- options: undefined,
264
- icon: undefined,
265
- autoOpen: undefined,
266
- readOnly: undefined,
267
- filterParams: { structured: true },
268
- },
269
- additionalAttributes,
270
- ...args,
271
- );
272
- }
273
-
274
- init(): void {
275
- if (isDefined(this.hideClear)) this.showClear = !this.hideClear;
276
-
277
- if (this.alwaysShowClear) this.showClear = true;
278
-
279
- if (!this.bindings) {
280
- let b: BindingConfig[] = [];
281
- if (this.value) {
282
- if (isAccessorChain(this.value)) this.value = bind(this.value);
283
- if ((this.value as any).bind)
284
- b.push({
285
- key: true,
286
- local: (this.value as any).bind,
287
- remote: `$option.${this.optionIdField}`,
288
- set: (this.value as any).set,
289
- });
290
- }
291
-
292
- if (this.text as string | AccessorChain<unknown>) {
293
- if (isAccessorChain(this.text)) this.text = bind(this.text);
294
- if ((this.text as any).bind)
295
- b.push({
296
- local: (this.text as any).bind,
297
- remote: `$option.${this.optionTextField}`,
298
- set: (this.text as any).set,
299
- });
300
- }
301
-
302
- this.bindings = b;
303
- }
304
-
305
- if (this.bindings.length == 0 && this.multiple)
306
- this.bindings = [
307
- {
308
- key: true,
309
- local: `$value.${this.valueIdField}`,
310
- remote: `$option.${this.optionIdField}`,
311
- },
312
- {
313
- local: `$value.${this.valueTextField}`,
314
- remote: `$option.${this.optionTextField}`,
315
- },
316
- ];
317
-
318
- this.keyBindings = this.bindings.filter((b) => b.key);
319
-
320
- if (!this.items && !this.children)
321
- this.items = {
322
- type: HighlightedSearchText,
323
- text: { bind: `$option.${this.optionTextField}` },
324
- query: { bind: "$query" },
325
- } as any;
326
-
327
- this.itemConfig = this.children || this.items;
328
-
329
- this.items = [];
330
- delete this.children;
331
-
332
- super.init();
333
- }
334
-
335
- prepareData(context: RenderingContext, instance: FieldInstance<LookupField>): void {
336
- let { data, store } = instance;
337
-
338
- data.stateMods = {
339
- multiple: this.multiple,
340
- single: !this.multiple,
341
- disabled: data.disabled,
342
- readonly: data.readOnly,
343
- };
344
-
345
- data.visibleOptions = data.options;
346
- if (this.onCreateVisibleOptionsFilter && isArray(data.options)) {
347
- let filterPredicate = instance.invoke("onCreateVisibleOptionsFilter", data.filterParams, instance);
348
- data.visibleOptions = data.options.filter(filterPredicate);
349
- }
350
-
351
- data.selectedKeys = [];
352
-
353
- if (this.multiple) {
354
- if (isArray(data.values) && isArray(data.options)) {
355
- data.selectedKeys = data.values.map((v) => (this.keyBindings!.length == 1 ? [v] : v));
356
- let map: Record<number, Record<string, any>> = {};
357
- data.options.filter(($option) => {
358
- let optionKey = getOptionKey(this.keyBindings!, { $option });
359
- for (let i = 0; i < data.selectedKeys.length; i++)
360
- if (areKeysEqual(optionKey, data.selectedKeys[i])) {
361
- map[i] = convertOption(this.bindings!, { $option });
362
- break;
363
- }
364
- });
365
- data.records = [];
366
- for (let i = 0; i < data.selectedKeys.length; i++) if (map[i]) data.records.push(map[i]);
367
- } else if (isArray(data.records))
368
- data.selectedKeys.push(
369
- ...data.records.map(($value) => this.keyBindings!.map((b) => Binding.get(b.local).value({ $value }))),
370
- );
371
- } else {
372
- let dataViewData = store.getData();
373
- data.selectedKeys.push(this.keyBindings!.map((b) => Binding.get(b.local).value(dataViewData)));
374
- if (!this.text && isArray(data.options)) {
375
- let option = data.options.find(($option) =>
376
- areKeysEqual(getOptionKey(this.keyBindings!, { $option }), data.selectedKeys[0]),
377
- );
378
- data.text = (option && (option as any)[this.optionTextField!]) || "";
379
- }
380
- }
381
-
382
- (instance as DropdownInstance).lastDropdown = context.lastDropdown;
383
-
384
- super.prepareData(context, instance);
385
- }
386
-
387
- renderInput(context: RenderingContext, instance: FieldInstance<LookupField>, key: string): React.ReactNode {
388
- return (
389
- <LookupComponent
390
- key={key}
391
- multiple={this.multiple!}
392
- instance={instance}
393
- itemConfig={this.itemConfig}
394
- bindings={this.bindings!}
395
- baseClass={this.baseClass!}
396
- label={this.labelPlacement && getContent(this.renderLabel(context, instance, "label"))}
397
- help={this.helpPlacement && getContent(this.renderHelp(context, instance, "help"))}
398
- forceUpdate={context.forceUpdate}
399
- icon={this.renderIcon(context, instance, "icon")}
400
- />
401
- );
402
- }
403
-
404
- filterOptions(instance: Instance, options: DataRecord[], query?: string): DataRecord[] {
405
- if (!query) return options;
406
- let textPredicate = getSearchQueryPredicate(query);
407
- return options.filter(
408
- (o) => isString(o[this.optionTextField!]) && textPredicate((o as any)[this.optionTextField!] as string),
409
- );
410
- }
411
-
412
- isEmpty(data: Record<string, any>): boolean {
413
- if (this.multiple) return !isNonEmptyArray(data.values) && !isNonEmptyArray(data.records);
414
- return super.isEmpty(data);
415
- }
416
-
417
- getValidationValue(data: Record<string, any>): unknown {
418
- if (this.multiple) return data.records ?? data.values;
419
- return super.getValidationValue(data);
420
- }
421
-
422
- formatValue(context: RenderingContext, instance: Instance): string | React.ReactNode {
423
- if (!this.multiple) return super.formatValue(context, instance);
424
-
425
- let { records, values, options } = instance.data;
426
- if (isArray(records)) {
427
- let valueTextFormatter =
428
- typeof this.onGetRecordDisplayText === "function"
429
- ? this.onGetRecordDisplayText
430
- : (record: Record<string, any>) =>
431
- (record as any)[this.valueTextField!] || (record as any)[this.valueIdField!];
432
- return records.map((record) => valueTextFormatter(record as any, instance));
433
- }
434
-
435
- if (isArray(values)) {
436
- if (isArray(options))
437
- return values
438
- .map((id) => {
439
- let option = options.find((o) => (o as any)[this.optionIdField!] == id);
440
- return option ? (option as any)[this.valueTextField!] : id;
441
- })
442
- .filter(Boolean)
443
- .join(", ");
444
-
445
- return values.join(", ");
446
- }
447
-
448
- return null;
449
- }
450
- }
451
-
452
- LookupField.prototype.baseClass = "lookupfield";
453
- //LookupField.prototype.memoize = false;
454
- LookupField.prototype.multiple = false;
455
- LookupField.prototype.queryDelay = 150;
456
- LookupField.prototype.minQueryLength = 0;
457
- LookupField.prototype.hideSearchField = false;
458
- LookupField.prototype.minOptionsForSearchField = 7;
459
- LookupField.prototype.loadingText = "Loading...";
460
- LookupField.prototype.queryErrorText = "Error occurred while querying for lookup data.";
461
- LookupField.prototype.noResultsText = "No results found.";
462
- LookupField.prototype.optionIdField = "id";
463
- LookupField.prototype.optionTextField = "text";
464
- LookupField.prototype.valueIdField = "id";
465
- LookupField.prototype.valueTextField = "text";
466
- LookupField.prototype.suppressErrorsUntilVisited = true;
467
- LookupField.prototype.fetchAll = false;
468
- LookupField.prototype.cacheAll = false;
469
- LookupField.prototype.showClear = true;
470
- LookupField.prototype.alwaysShowClear = false;
471
- LookupField.prototype.closeOnSelect = true;
472
- LookupField.prototype.minQueryLengthMessageText = "Type in at least {0} character(s).";
473
- LookupField.prototype.icon = null;
474
- LookupField.prototype.sort = false;
475
- LookupField.prototype.listOptions = null;
476
- LookupField.prototype.autoOpen = false;
477
- LookupField.prototype.submitOnEnterKey = false;
478
- LookupField.prototype.submitOnDropdownEnterKey = false;
479
- LookupField.prototype.pageSize = 100;
480
- LookupField.prototype.infinite = false;
481
- LookupField.prototype.quickSelectAll = false;
482
- LookupField.prototype.onGetRecordDisplayText = null;
483
-
484
- Localization.registerPrototype("cx/widgets/LookupField", LookupField);
485
-
486
- Widget.alias("lookupfield", LookupField);
487
-
488
- interface BindingConfig {
489
- local: string;
490
- remote: string;
491
- key?: boolean;
492
- set?: (value: unknown, instance: Instance) => void;
493
- }
494
-
495
- function getOptionKey(bindings: BindingConfig[], data: Record<string, any>): unknown[] {
496
- return bindings.filter((a) => a.key).map((b) => Binding.get(b.remote).value(data));
497
- }
498
-
499
- function areKeysEqual(key1: unknown[], key2: unknown[]): boolean {
500
- if (!key1 || !key2 || key1.length != key2.length) return false;
501
-
502
- for (let i = 0; i < key1.length; i++) if (key1[i] !== key2[i]) return false;
503
-
504
- return true;
505
- }
506
-
507
- function convertOption(bindings: BindingConfig[], data: Record<string, any>): Record<string, any> {
508
- let result: Record<string, any> = { $value: {} };
509
- bindings.forEach((b) => {
510
- let value = Binding.get(b.remote).value(data);
511
- result = Binding.get(b.local).set(result, value);
512
- });
513
- return result.$value as Record<string, any>;
514
- }
515
-
516
- class SelectionDelegate extends Selection {
517
- delegate: (record: Record<string, any>, index: number) => boolean;
518
-
519
- constructor({ delegate }: { delegate: (record: Record<string, any>, index: number) => boolean }) {
520
- super();
521
- this.delegate = delegate;
522
- }
523
-
524
- getIsSelectedDelegate(store: unknown): (record: Record<string, any>, index: number) => boolean {
525
- return (record: Record<string, any>, index: number) => this.delegate(record, index);
526
- }
527
-
528
- select(): boolean {
529
- return false;
530
- }
531
- }
532
-
533
- interface LookupComponentProps {
534
- instance: FieldInstance<LookupField>;
535
- multiple: boolean;
536
- itemConfig: unknown;
537
- bindings: BindingConfig[];
538
- baseClass: string;
539
- label?: React.ReactNode;
540
- help?: React.ReactNode;
541
- forceUpdate: () => void;
542
- icon?: React.ReactNode;
543
- }
544
-
545
- interface LookupComponentState {
546
- options: unknown[];
547
- formatted?: string;
548
- value?: string;
549
- dropdownOpen: boolean;
550
- focus: boolean;
551
- status?: string;
552
- message?: string;
553
- query?: string;
554
- page?: number;
555
- hover?: boolean;
556
- }
557
-
558
- class LookupComponent extends VDOM.Component<LookupComponentProps, LookupComponentState> {
559
- dom: {
560
- input?: HTMLDivElement | null;
561
- dropdown?: HTMLDivElement | null;
562
- list?: HTMLDivElement | null;
563
- query?: HTMLInputElement | null;
564
- } = {};
565
- itemStore: ReadOnlyDataView;
566
- dropdown?: Widget;
567
- list?: Widget;
568
- listKeyDown?: (e: React.KeyboardEvent) => void;
569
- queryTimeoutId?: ReturnType<typeof setTimeout>;
570
- cachedResult?: Record<string, any>[];
571
- tmpCachedResult?: Record<string, any>[];
572
- lastQueryId?: number;
573
- lastQuery?: string;
574
- extraPageLoadingBlocker?: string | false;
575
- unsubscribeListOnWheel?: (() => void) | null;
576
- unsubscribeListOnScroll?: (() => void) | null;
577
-
578
- constructor(props: LookupComponentProps) {
579
- super(props);
580
- let { data, store } = this.props.instance;
581
- this.dom = {};
582
- this.state = {
583
- options: [],
584
- formatted: data.formatted,
585
- value: data.formatted,
586
- dropdownOpen: false,
587
- focus: false,
588
- };
589
-
590
- this.itemStore = new ReadOnlyDataView({
591
- store: store,
592
- });
593
- }
594
-
595
- getOptionKey(data: Record<string, any>): unknown[] {
596
- return this.props.bindings.filter((a) => a.key).map((b) => Binding.get(b.remote).value(data));
597
- }
598
-
599
- getLocalKey(data: Record<string, any>): unknown[] {
600
- return this.props.bindings.filter((a) => a.key).map((b) => Binding.get(b.local).value(data));
601
- }
602
-
603
- findOption(options: Record<string, any>[], key: unknown[]): number {
604
- if (!key) return -1;
605
- for (let i = 0; i < options.length; i++) {
606
- let optionKey = this.getOptionKey({ $option: options[i] });
607
- if (areKeysEqual(key, optionKey)) return i;
608
- }
609
- return -1;
610
- }
611
-
612
- getDropdown(): Widget {
613
- if (this.dropdown) return this.dropdown;
614
-
615
- let { widget }: { widget: LookupField } = this.props.instance as unknown as { widget: LookupField };
616
- let { lastDropdown } = this.props.instance as DropdownInstance;
617
-
618
- this.list = Widget.create({
619
- type: List,
620
- sortField: widget.sort && widget.optionTextField,
621
- sortDirection: "ASC",
622
- mod: "dropdown",
623
- scrollSelectionIntoView: true,
624
- cached: widget.infinite,
625
- ...widget.listOptions,
626
- records: bind("$options"),
627
- recordName: "$option",
628
- onItemClick: (e: React.MouseEvent, inst: Instance) => this.onItemClick(e, inst),
629
- pipeKeyDown: (kd: (e: React.KeyboardEvent) => void) => {
630
- this.listKeyDown = kd;
631
- },
632
- selectOnTab: true,
633
- focusable: false,
634
- selection: {
635
- type: SelectionDelegate,
636
- delegate: (data: any) =>
637
- this.props.instance.data.selectedKeys.find((x: any) =>
638
- areKeysEqual(x, this.getOptionKey({ $option: data })),
639
- ) != null,
640
- },
641
- children: this.props.itemConfig,
642
- });
643
-
644
- let dropdown = {
645
- constrain: true,
646
- scrollTracking: true,
647
- inline: !isTouchDevice() || !!lastDropdown,
648
- placementOrder: "down-right down-left up-right up-left",
649
- ...widget.dropdownOptions,
650
- type: Dropdown,
651
- relatedElement: this.dom.input,
652
- renderChildren: () => this.renderDropdownContents(),
653
- onFocusOut: (e: React.MouseEvent) => this.closeDropdown(e),
654
- memoize: false,
655
- touchFriendly: isTouchDevice(),
656
- onMeasureNaturalContentSize: () => {
657
- if (this.dom.dropdown && this.dom.list) {
658
- return {
659
- height:
660
- this.dom.dropdown.offsetHeight -
661
- this.dom.list.offsetHeight +
662
- ((this.dom.list.firstElementChild as HTMLElement)?.offsetHeight || 0),
663
- };
664
- }
665
- },
666
- onDismissAfterScroll: () => {
667
- this.closeDropdown(null, true);
668
- return false;
669
- },
670
- };
671
-
672
- return (this.dropdown = Widget.create(dropdown));
673
- }
674
-
675
- renderDropdownContents(): React.ReactNode {
676
- let content;
677
- let { instance } = this.props;
678
- let { data, widget }: { data: Record<string, any>; widget: LookupField } = instance as unknown as {
679
- data: Record<string, any>;
680
- widget: LookupField;
681
- };
682
- let { CSS, baseClass } = widget;
683
-
684
- let searchVisible =
685
- !widget.hideSearchField &&
686
- (!isArray(data.visibleOptions) ||
687
- (widget.minOptionsForSearchField && data.visibleOptions.length >= widget.minOptionsForSearchField));
688
-
689
- if (this.state.status == "loading") {
690
- content = (
691
- <div key="msg" className={CSS.element(baseClass, "message", "loading")}>
692
- {widget.loadingText}
693
- </div>
694
- );
695
- } else if (this.state.status == "error") {
696
- content = (
697
- <div key="msg" className={CSS.element(baseClass, "message", "error")}>
698
- {widget.queryErrorText}
699
- </div>
700
- );
701
- } else if (this.state.status == "info") {
702
- content = (
703
- <div key="msg" className={CSS.element(baseClass, "message", "info")}>
704
- {this.state.message}
705
- </div>
706
- );
707
- } else if (this.state.options.length == 0) {
708
- content = (
709
- <div key="msg" className={CSS.element(baseClass, "message", "no-results")}>
710
- {widget.noResultsText}
711
- </div>
712
- );
713
- } else {
714
- content = (
715
- <div
716
- key="msg"
717
- ref={(el) => {
718
- this.dom.list = el;
719
- this.subscribeListOnWheel(el);
720
- this.subscribeListOnScroll(el);
721
- }}
722
- className={CSS.element(baseClass, "scroll-container")}
723
- >
724
- <Cx widget={this.list} store={this.itemStore} options={{ name: "lookupfield-list" }} />
725
- </div>
726
- );
727
- }
728
-
729
- return (
730
- <div
731
- key="dropdown"
732
- ref={(el) => {
733
- this.dom.dropdown = el as HTMLDivElement;
734
- }}
735
- className={CSS.element(baseClass, "dropdown")}
736
- tabIndex={0}
737
- onFocus={(e) => this.onDropdownFocus(e)}
738
- onKeyDown={(e) => this.onDropdownKeyPress(e)}
739
- >
740
- {searchVisible && (
741
- <input
742
- key="query"
743
- ref={(el) => {
744
- this.dom.query = el as HTMLInputElement;
745
- }}
746
- type="text"
747
- className={CSS.element(baseClass, "query")}
748
- onClick={(e) => {
749
- e.preventDefault();
750
- e.stopPropagation();
751
- }}
752
- onChange={(e) => this.query(e.target.value)}
753
- onBlur={(e) => this.onQueryBlur(e)}
754
- />
755
- )}
756
- {content}
757
- </div>
758
- );
759
- }
760
-
761
- onListWheel(e: WheelEvent): void {
762
- let { list } = this.dom;
763
- if (
764
- list &&
765
- ((list.scrollTop + list.offsetHeight == list.scrollHeight && e.deltaY > 0) ||
766
- (list.scrollTop == 0 && e.deltaY < 0))
767
- ) {
768
- e.preventDefault();
769
- e.stopPropagation();
770
- }
771
- }
772
-
773
- onListScroll(): void {
774
- if (!this.dom.list) return;
775
- var el = this.dom.list;
776
- if (el.scrollTop > el.scrollHeight - 2 * el.offsetHeight) {
777
- this.loadAdditionalOptionPages();
778
- }
779
- }
780
-
781
- onDropdownFocus(e: React.FocusEvent): void {
782
- if (this.dom.query && !isFocused(this.dom.query) && !isTouchDevice()) FocusManager.focus(this.dom.query);
783
- }
784
-
785
- getPlaceholder(text?: string): React.ReactNode {
786
- let { CSS, baseClass } = this.props.instance.widget;
787
-
788
- if (text) return <span className={CSS.element(baseClass, "placeholder")}>{text}</span>;
789
-
790
- return <span className={CSS.element(baseClass, "placeholder")}>&nbsp;</span>;
791
- }
792
-
793
- render(): React.ReactNode {
794
- let { instance, label, help, icon: iconVDOM } = this.props;
795
- let { data, widget, state } = instance;
796
- let { CSS, baseClass, suppressErrorsUntilVisited } = widget as LookupField;
797
-
798
- let icon = iconVDOM && (
799
- <div
800
- key="icon"
801
- className={CSS.element(baseClass, "left-icon")}
802
- onMouseDown={preventDefault}
803
- onClick={(e) => {
804
- this.openDropdown(e);
805
- e.stopPropagation();
806
- e.preventDefault();
807
- }}
808
- >
809
- {iconVDOM}
810
- </div>
811
- );
812
-
813
- let dropdown;
814
- if (this.state.dropdownOpen) {
815
- this.itemStore.setData({
816
- $options: this.state.options,
817
- $query: this.lastQuery,
818
- });
819
- dropdown = (
820
- <Cx widget={this.getDropdown()} store={this.itemStore} options={{ name: "lookupfield-dropdown" }} />
821
- );
822
- }
823
-
824
- let insideButton = null;
825
- let multipleEntries = this.props.multiple && isArray(data.records) && data.records.length > 1;
826
-
827
- if (!data.readOnly) {
828
- if (
829
- widget.showClear &&
830
- !data.disabled &&
831
- !data.empty &&
832
- (widget.alwaysShowClear || (!data.required && !this.props.multiple) || multipleEntries)
833
- ) {
834
- insideButton = (
835
- <div
836
- key="ib"
837
- onMouseDown={preventDefault}
838
- onClick={(e) => (!this.props.multiple ? this.onClearClick(e) : this.onClearMultipleClick(e))}
839
- className={CSS.element(baseClass, "clear")}
840
- >
841
- <ClearIcon className={CSS.element(baseClass, "icon")} />
842
- </div>
843
- );
844
- } else {
845
- insideButton = (
846
- <div
847
- key="ib"
848
- className={CSS.element(baseClass, "tool")}
849
- onMouseDown={preventDefault}
850
- onClick={(e) => {
851
- this.toggleDropdown(e, true);
852
- e.stopPropagation();
853
- e.preventDefault();
854
- }}
855
- >
856
- <DropdownIcon className={CSS.element(baseClass, "icon")} />
857
- </div>
858
- );
859
- }
860
- }
861
-
862
- let text;
863
-
864
- if (this.props.multiple) {
865
- let readOnly = data.disabled || data.readOnly;
866
- if (isNonEmptyArray(data.records)) {
867
- let valueTextFormatter =
868
- widget.onGetRecordDisplayText ??
869
- ((record: Record<string, any>) => record[widget.valueTextField] as string);
870
- text = data.records.map((v, i) => (
871
- <div
872
- key={i}
873
- className={CSS.element(baseClass, "tag", {
874
- readonly: readOnly,
875
- })}
876
- >
877
- <span className={CSS.element(baseClass, "tag-value")}>{valueTextFormatter(v, instance)}</span>
878
- {!readOnly && (
879
- <div
880
- className={CSS.element(baseClass, "tag-clear")}
881
- onMouseDown={(e) => {
882
- e.preventDefault();
883
- e.stopPropagation();
884
- }}
885
- onClick={(e) => this.onClearClick(e, v)}
886
- >
887
- <ClearIcon className={CSS.element(baseClass, "icon")} />
888
- </div>
889
- )}
890
- </div>
891
- ));
892
- } else {
893
- text = this.getPlaceholder(data.placeholder);
894
- }
895
- } else {
896
- text = !data.empty ? data.text || this.getPlaceholder() : this.getPlaceholder(data.placeholder);
897
- }
898
-
899
- let states = {
900
- visited: state.visited,
901
- focus: this.state.focus || this.state.dropdownOpen,
902
- icon: !!iconVDOM,
903
- empty: !data.placeholder && data.empty,
904
- error: data.error && (state.visited || !suppressErrorsUntilVisited || !data.empty),
905
- };
906
-
907
- return (
908
- <div
909
- className={CSS.expand(data.classNames, CSS.state(states))}
910
- style={data.style}
911
- onMouseDown={stopPropagation}
912
- onTouchStart={stopPropagation}
913
- onKeyDown={(e) => this.onKeyDown(e)}
914
- >
915
- <div
916
- id={data.id}
917
- className={CSS.expand(CSS.element(widget.baseClass, "input"), data.inputClass)}
918
- style={data.inputStyle}
919
- tabIndex={data.disabled ? null : data.tabIndex || 0}
920
- ref={(el) => {
921
- this.dom.input = el;
922
- }}
923
- aria-labelledby={data.id + "-label"}
924
- onMouseMove={(e) => tooltipMouseMove(e, ...getFieldTooltip(this.props.instance))}
925
- onMouseLeave={(e) => tooltipMouseLeave(e, ...getFieldTooltip(this.props.instance))}
926
- onClick={(e) => this.onClick(e)}
927
- onKeyDown={(e) => this.onInputKeyDown(e)}
928
- onMouseDown={(e) => this.onMouseDown(e)}
929
- onBlur={(e) => this.onBlur(e)}
930
- onFocus={(e) => this.onFocus(e)}
931
- >
932
- {text}
933
- </div>
934
- {insideButton}
935
- {icon}
936
- {dropdown}
937
- {label}
938
- {help}
939
- </div>
940
- );
941
- }
942
-
943
- onMouseDown(e: React.MouseEvent): void {
944
- //skip touch start to allow touch scrolling
945
- if (isTouchEvent()) return;
946
- e.preventDefault();
947
- e.stopPropagation();
948
- this.toggleDropdown(e, true);
949
- }
950
-
951
- onClick(e: React.MouseEvent): void {
952
- //mouse down will handle it for non-touch events
953
- if (!isTouchEvent()) return;
954
- e.preventDefault();
955
- e.stopPropagation();
956
- this.toggleDropdown(e, true);
957
- }
958
-
959
- onItemClick(
960
- e: React.KeyboardEvent | React.MouseEvent,
961
- { store }: { store: { getData: () => Record<string, any> } },
962
- ): void {
963
- this.select(e, [store.getData()]);
964
- if (!this.props.instance.widget.submitOnEnterKey || e.type != "keydown") e.stopPropagation();
965
- if ((e as React.KeyboardEvent).keyCode != KeyCode.tab) e.preventDefault();
966
- }
967
-
968
- onClearClick(e: React.MouseEvent | React.KeyboardEvent, value?: Record<string, any>): void {
969
- let { instance } = this.props;
970
- let { data, store, widget } = instance;
971
- let { keyBindings } = widget;
972
- e.stopPropagation();
973
- e.preventDefault();
974
- if (widget.multiple) {
975
- if (isArray(data.records)) {
976
- let itemKey = this.getLocalKey({ $value: value });
977
- let newRecords = data.records.filter((v) => !areKeysEqual(this.getLocalKey({ $value: v }), itemKey));
978
-
979
- instance.set("records", newRecords);
980
-
981
- let newValues = newRecords
982
- .map((rec) => this.getLocalKey({ $value: rec }))
983
- .map((k) => (keyBindings!.length == 1 ? k[0] : k));
984
-
985
- instance.set("values", newValues);
986
- }
987
- } else {
988
- this.props.bindings.forEach((b) => {
989
- store.set(b.local, widget.emptyValue);
990
- });
991
- }
992
-
993
- if (!isTouchEvent()) this.dom.input!.focus();
994
- }
995
-
996
- onClearMultipleClick(e: React.MouseEvent): void {
997
- let { instance } = this.props;
998
- instance.set("records", []);
999
- instance.set("values", []);
1000
- }
1001
-
1002
- select(e: React.KeyboardEvent | React.MouseEvent, itemsData: Record<string, any>[], reset?: boolean): void {
1003
- let { instance } = this.props;
1004
- let { store, data, widget } = instance;
1005
- let { bindings, keyBindings } = widget;
1006
-
1007
- if (widget.multiple) {
1008
- let { selectedKeys, records } = data;
1009
-
1010
- let newRecords = reset ? [] : [...(records || [])];
1011
- let singleSelect = itemsData.length == 1;
1012
- let optionKey: unknown[] | null = null;
1013
- if (singleSelect) optionKey = this.getOptionKey(itemsData[0]);
1014
-
1015
- // deselect
1016
- if (singleSelect && selectedKeys.find((k: any) => areKeysEqual(optionKey!, k))) {
1017
- newRecords = records.filter((v: any) => !areKeysEqual(optionKey!, this.getLocalKey({ $value: v })));
1018
- } else {
1019
- itemsData.forEach((itemData) => {
1020
- let valueData: Record<string, any> = {
1021
- $value: {},
1022
- };
1023
- bindings!.forEach((b) => {
1024
- valueData = Binding.get(b.local).set(valueData, Binding.get(b.remote).value(itemData));
1025
- });
1026
- newRecords.push(valueData.$value as Record<string, any>);
1027
- });
1028
- }
1029
-
1030
- instance.set("records", newRecords);
1031
-
1032
- let newValues = newRecords
1033
- .map((rec) => this.getLocalKey({ $value: rec }))
1034
- .map((k) => (keyBindings!.length == 1 ? k[0] : k));
1035
-
1036
- instance.set("values", newValues);
1037
- } else {
1038
- bindings!.forEach((b) => {
1039
- let v = Binding.get(b.remote).value(itemsData[0]);
1040
- if (b.set) b.set(v, instance);
1041
- else store.set(b.local, v);
1042
- });
1043
- }
1044
-
1045
- if (widget.closeOnSelect) {
1046
- //Pressing Tab should work it's own thing. Focus will move elsewhere and the dropdown will close.
1047
- if ((e as React.KeyboardEvent).keyCode != KeyCode.tab) {
1048
- if (!isTouchEvent()) this.dom.input!.focus();
1049
- this.closeDropdown(e);
1050
- }
1051
- }
1052
-
1053
- if ((e as React.KeyboardEvent).keyCode == KeyCode.enter && widget.submitOnDropdownEnterKey) {
1054
- this.submitOnEnter(e as React.KeyboardEvent);
1055
- }
1056
- }
1057
-
1058
- onDropdownKeyPress(e: React.KeyboardEvent): void {
1059
- switch (e.keyCode) {
1060
- case KeyCode.esc:
1061
- this.closeDropdown(e);
1062
- this.dom.input!.focus();
1063
- break;
1064
-
1065
- case KeyCode.tab:
1066
- // if tab needs to do a list selection, we have to first call List's handleKeyDown
1067
- if (this.listKeyDown) this.listKeyDown(e);
1068
- // if next focusable element is disabled, recalculate and update the dom before switching focus
1069
- this.props.forceUpdate();
1070
- break;
1071
-
1072
- case KeyCode.a:
1073
- if (!e.ctrlKey) return;
1074
-
1075
- let { quickSelectAll, multiple } = this.props.instance.widget;
1076
- if (!quickSelectAll || !multiple) return;
1077
-
1078
- let optionsToSelect = this.state.options.map((o) => ({
1079
- $option: o,
1080
- }));
1081
- this.select(e, optionsToSelect, true);
1082
- e.stopPropagation();
1083
- e.preventDefault();
1084
- break;
1085
-
1086
- default:
1087
- if (this.listKeyDown) this.listKeyDown(e);
1088
- break;
1089
- }
1090
- }
1091
-
1092
- onKeyDown(e: React.KeyboardEvent): void {
1093
- switch (e.keyCode) {
1094
- case KeyCode.pageDown:
1095
- case KeyCode.pageUp:
1096
- if (this.state.dropdownOpen) e.preventDefault();
1097
- break;
1098
- }
1099
- }
1100
-
1101
- onInputKeyDown(e: React.KeyboardEvent): void {
1102
- let { instance } = this.props;
1103
- if (instance.widget.handleKeyDown(e, instance) === false) return;
1104
-
1105
- switch (e.keyCode) {
1106
- case KeyCode.delete:
1107
- this.onClearClick(e);
1108
- return;
1109
-
1110
- case KeyCode.shift:
1111
- case KeyCode.ctrl:
1112
- case KeyCode.tab:
1113
- case KeyCode.left:
1114
- case KeyCode.right:
1115
- case KeyCode.pageUp:
1116
- case KeyCode.pageDown:
1117
- case KeyCode.insert:
1118
- case KeyCode.esc:
1119
- break;
1120
-
1121
- case KeyCode.down:
1122
- this.openDropdown(e);
1123
- e.stopPropagation();
1124
- break;
1125
-
1126
- case KeyCode.enter:
1127
- if (this.props.instance.widget.submitOnEnterKey) {
1128
- this.submitOnEnter(e);
1129
- } else {
1130
- this.openDropdown(e);
1131
- }
1132
- break;
1133
-
1134
- default:
1135
- this.openDropdown(e);
1136
- break;
1137
- }
1138
- }
1139
-
1140
- onQueryBlur(e: React.FocusEvent): void {
1141
- FocusManager.nudge();
1142
- }
1143
-
1144
- onFocus(e: React.FocusEvent): void {
1145
- let { instance } = this.props;
1146
- let { widget } = instance;
1147
- if (widget.trackFocus) {
1148
- this.setState({
1149
- focus: true,
1150
- });
1151
- }
1152
-
1153
- if (this.props.instance.data.autoOpen) this.openDropdown(null);
1154
- }
1155
-
1156
- onBlur(e: React.FocusEvent): void {
1157
- if (!this.state.dropdownOpen) this.props.instance.setState({ visited: true });
1158
-
1159
- if (this.state.focus)
1160
- this.setState({
1161
- focus: false,
1162
- });
1163
- }
1164
-
1165
- toggleDropdown(e: React.KeyboardEvent | React.MouseEvent, keepFocus?: boolean): void {
1166
- if (this.state.dropdownOpen) this.closeDropdown(e, keepFocus);
1167
- else this.openDropdown(e);
1168
- }
1169
-
1170
- closeDropdown(e?: React.KeyboardEvent | React.MouseEvent | null, keepFocus?: boolean): void {
1171
- if (this.state.dropdownOpen) {
1172
- this.setState(
1173
- {
1174
- dropdownOpen: false,
1175
- },
1176
- () => keepFocus && this.dom.input?.focus(),
1177
- );
1178
-
1179
- this.props.instance.setState({
1180
- visited: true,
1181
- });
1182
- }
1183
-
1184
- //delete results valid only while the dropdown is open
1185
- delete this.tmpCachedResult;
1186
- }
1187
-
1188
- openDropdown(e: React.KeyboardEvent | React.MouseEvent | null): void {
1189
- let { instance } = this.props;
1190
- let { data } = instance;
1191
- if (!this.state.dropdownOpen && !data.disabled && !data.readOnly) {
1192
- this.query("");
1193
- this.setState(
1194
- {
1195
- dropdownOpen: true,
1196
- },
1197
- () => {
1198
- if (this.dom.dropdown) this.dom.dropdown.focus();
1199
- },
1200
- );
1201
- }
1202
- }
1203
-
1204
- query(q: string): void {
1205
- /*
1206
- In fetchAll mode onQuery should fetch all data and after
1207
- that everything is done filtering is done client-side.
1208
- If cacheAll is set results are cached for the lifetime of the
1209
- widget, otherwise cache is invalidated when dropdown closes.
1210
- */
1211
-
1212
- let { instance } = this.props;
1213
- let { widget, data } = instance;
1214
-
1215
- this.lastQuery = q;
1216
-
1217
- //do not make duplicate queries if fetchAll is enabled
1218
- if (widget.fetchAll && this.state.status == "loading") return;
1219
-
1220
- if (this.queryTimeoutId) clearTimeout(this.queryTimeoutId);
1221
-
1222
- if (q.length < widget.minQueryLength) {
1223
- this.setState({
1224
- status: "info",
1225
- message: StringTemplate.format(widget.minQueryLengthMessageText, widget.minQueryLength),
1226
- });
1227
- return;
1228
- }
1229
-
1230
- if (isArray(data.visibleOptions)) {
1231
- let results = widget.filterOptions(this.props.instance, data.visibleOptions as DataRecord[], q);
1232
- this.setState({
1233
- options: results,
1234
- status: "loaded",
1235
- });
1236
- }
1237
-
1238
- if (widget.onQuery) {
1239
- let { queryDelay, fetchAll, cacheAll, pageSize } = widget;
1240
-
1241
- if (fetchAll) queryDelay = 0;
1242
-
1243
- if (!this.cachedResult) {
1244
- this.setState({
1245
- status: "loading",
1246
- });
1247
- }
1248
-
1249
- this.queryTimeoutId = setTimeout(() => {
1250
- delete this.queryTimeoutId;
1251
-
1252
- let result = this.tmpCachedResult || this.cachedResult;
1253
- let query = fetchAll ? "" : q;
1254
- let params = !widget.infinite
1255
- ? query
1256
- : {
1257
- query,
1258
- page: 1,
1259
- pageSize,
1260
- };
1261
-
1262
- if (!result) result = instance.invoke("onQuery", params, instance);
1263
-
1264
- let queryId = (this.lastQueryId = Date.now());
1265
-
1266
- Promise.resolve(result)
1267
- .then((results) => {
1268
- //discard results which do not belong to the last query
1269
- if (queryId !== this.lastQueryId) return;
1270
-
1271
- if (!isArray(results)) results = [];
1272
-
1273
- if (fetchAll) {
1274
- if (cacheAll) this.cachedResult = results;
1275
- else this.tmpCachedResult = results;
1276
-
1277
- results = widget.filterOptions(this.props.instance, results, this.lastQuery);
1278
- }
1279
-
1280
- this.setState(
1281
- {
1282
- page: 1,
1283
- query,
1284
- options: results,
1285
- status: "loaded",
1286
- },
1287
- () => {
1288
- if (widget.infinite) this.onListScroll();
1289
- },
1290
- );
1291
- })
1292
- .catch((err) => {
1293
- this.setState({ status: "error" });
1294
- debug("Lookup query error:", err);
1295
- });
1296
- }, queryDelay);
1297
- }
1298
- }
1299
-
1300
- loadAdditionalOptionPages(): void {
1301
- let { instance } = this.props;
1302
- let { widget } = instance;
1303
- if (!widget.infinite) return;
1304
-
1305
- let { query, page, status, options } = this.state;
1306
- if (!page) page = 1;
1307
-
1308
- let blockerKey = query;
1309
-
1310
- if (status != "loaded") return;
1311
-
1312
- if (options.length < page * widget.pageSize) return; //some pages were not full which means we reached the end
1313
-
1314
- if (this.extraPageLoadingBlocker === blockerKey) return;
1315
-
1316
- this.extraPageLoadingBlocker = blockerKey;
1317
-
1318
- let params = {
1319
- page: page + 1,
1320
- query,
1321
- pageSize: widget.pageSize,
1322
- };
1323
-
1324
- var result = instance.invoke("onQuery", params, instance);
1325
-
1326
- Promise.resolve(result)
1327
- .then((results) => {
1328
- //discard results which do not belong to the last query
1329
- if (this.extraPageLoadingBlocker !== blockerKey) return;
1330
-
1331
- this.extraPageLoadingBlocker = false;
1332
-
1333
- if (!isArray(results)) return;
1334
-
1335
- this.setState(
1336
- {
1337
- page: params.page,
1338
- query,
1339
- options: [...options, ...results],
1340
- },
1341
- () => {
1342
- this.onListScroll();
1343
- },
1344
- );
1345
- })
1346
- .catch((err) => {
1347
- if (this.extraPageLoadingBlocker !== blockerKey) return;
1348
- this.extraPageLoadingBlocker = false;
1349
- this.setState({ status: "error" });
1350
- debug("Lookup query error:", err);
1351
- console.error(err);
1352
- });
1353
- }
1354
-
1355
- UNSAFE_componentWillReceiveProps(props: LookupComponentProps): void {
1356
- if (this.dom.input) {
1357
- tooltipParentWillReceiveProps(this.dom.input, ...getFieldTooltip(props.instance));
1358
- }
1359
- }
1360
-
1361
- componentDidMount(): void {
1362
- if (this.dom.input) {
1363
- tooltipParentDidMount(this.dom.input, ...getFieldTooltip(this.props.instance));
1364
- autoFocus(this.dom.input, this);
1365
- }
1366
- }
1367
-
1368
- componentDidUpdate(): void {
1369
- if (this.dom.input) {
1370
- autoFocus(this.dom.input, this);
1371
- }
1372
- }
1373
-
1374
- componentWillUnmount(): void {
1375
- if (this.queryTimeoutId) clearTimeout(this.queryTimeoutId);
1376
- tooltipParentWillUnmount(this.props.instance);
1377
- this.subscribeListOnWheel(null);
1378
- }
1379
-
1380
- subscribeListOnWheel(list: HTMLDivElement | null): void {
1381
- if (this.unsubscribeListOnWheel) {
1382
- this.unsubscribeListOnWheel();
1383
- this.unsubscribeListOnWheel = null;
1384
- }
1385
- if (list) {
1386
- this.unsubscribeListOnWheel = addEventListenerWithOptions(
1387
- list,
1388
- "wheel",
1389
- (e) => this.onListWheel(e as WheelEvent),
1390
- {
1391
- passive: false,
1392
- },
1393
- );
1394
- }
1395
- }
1396
-
1397
- subscribeListOnScroll(list: HTMLDivElement | null): void {
1398
- if (this.unsubscribeListOnScroll) {
1399
- this.unsubscribeListOnScroll();
1400
- this.unsubscribeListOnScroll = null;
1401
- }
1402
- if (list) {
1403
- this.unsubscribeListOnScroll = addEventListenerWithOptions(list, "scroll", () => this.onListScroll(), {
1404
- passive: false,
1405
- });
1406
- }
1407
- }
1408
-
1409
- submitOnEnter(e: React.KeyboardEvent): void {
1410
- let instance = this.props.instance.parent;
1411
- while (instance) {
1412
- let htmlInstance = instance as HtmlElementInstance;
1413
- if (htmlInstance.events && htmlInstance.events.onSubmit) {
1414
- htmlInstance.events.onSubmit(e, instance);
1415
- break;
1416
- } else {
1417
- instance = instance.parent;
1418
- }
1419
- }
1420
- }
1421
- }
1
+ /**@jsxImportSource react */
2
+ import { Widget, VDOM, getContent } from "../../ui/Widget";
3
+ import { Cx } from "../../ui/Cx";
4
+ import { Field, getFieldTooltip, FieldInstance } from "./Field";
5
+ import { ReadOnlyDataView } from "../../data/ReadOnlyDataView";
6
+ import { HtmlElement, HtmlElementInstance } from "../HtmlElement";
7
+ import { Binding, BindingInput } from "../../data/Binding";
8
+ import { debug } from "../../util/Debug";
9
+ import { Dropdown, DropdownConfig } from "../overlay/Dropdown";
10
+ import { FocusManager } from "../../ui/FocusManager";
11
+ import { isFocused } from "../../util/DOM";
12
+ import { isTouchDevice } from "../../util/isTouchDevice";
13
+ import { isTouchEvent } from "../../util/isTouchEvent";
14
+ import {
15
+ tooltipParentWillReceiveProps,
16
+ tooltipParentWillUnmount,
17
+ tooltipMouseMove,
18
+ tooltipMouseLeave,
19
+ tooltipParentDidMount,
20
+ } from "../overlay/tooltip-ops";
21
+ import { stopPropagation, preventDefault } from "../../util/eventCallbacks";
22
+ import ClearIcon from "../icons/clear";
23
+ import DropdownIcon from "../icons/drop-down";
24
+ import { getSearchQueryPredicate } from "../../util/getSearchQueryPredicate";
25
+ import { KeyCode } from "../../util/KeyCode";
26
+ import { Localization } from "../../ui/Localization";
27
+ import { StringTemplate } from "../../data/StringTemplate";
28
+ import { Icon } from "../Icon";
29
+ import { isString } from "../../util/isString";
30
+ import { isDefined } from "../../util/isDefined";
31
+ import { isArray } from "../../util/isArray";
32
+ import { isNonEmptyArray } from "../../util/isNonEmptyArray";
33
+ import { addEventListenerWithOptions } from "../../util/addEventListenerWithOptions";
34
+ import { List } from "../List";
35
+ import { Selection } from "../../ui/selection/Selection";
36
+ import { HighlightedSearchText } from "../HighlightedSearchText";
37
+ import { autoFocus } from "../autoFocus";
38
+ import { bind } from "../../ui";
39
+ import { AccessorChain, isAccessorChain } from "../../data/createAccessorModelProxy";
40
+ import type { CxChild, RenderingContext } from "../../ui/RenderingContext";
41
+ import type { DropdownInstance, Instance } from "../../ui/Instance";
42
+ import { FieldConfig } from "./Field";
43
+ import { Prop, BooleanProp, StringProp, StructuredProp, DataRecord } from "../../ui/Prop";
44
+
45
+ export interface LookupBinding {
46
+ local: string;
47
+ remote: string;
48
+ key?: boolean;
49
+ }
50
+
51
+ export interface LookupFieldConfig<TOption = unknown, TRecord = unknown> extends FieldConfig {
52
+ /** Defaults to `false`. Set to `true` to enable multiple selection. */
53
+ multiple?: BooleanProp;
54
+
55
+ /** Selected value. Used only if `multiple` is set to `false`. */
56
+ value?: Prop<number | string>;
57
+
58
+ /** A list of selected ids. Used only if `multiple` is set to `true`. */
59
+ values?: Prop<(number | string)[]>;
60
+
61
+ /** A list of selected records. Used only if `multiple` is set to `true`. */
62
+ records?: Prop<TRecord[]>;
63
+
64
+ /** Text associated with the selection. Used only if `multiple` is set to `false`. */
65
+ text?: StringProp;
66
+
67
+ /** The opposite of `disabled`. */
68
+ enabled?: BooleanProp;
69
+
70
+ /** Defaults to `false`. Used to make the field read-only. */
71
+ readOnly?: BooleanProp;
72
+
73
+ /** Default text displayed when the field is empty. */
74
+ placeholder?: StringProp;
75
+
76
+ /** A list of available options. */
77
+ options?: Prop<TOption[]>;
78
+
79
+ /** Set to `true` to hide the clear button. Default value is `false`. */
80
+ hideClear?: boolean;
81
+
82
+ /** Set to `false` to hide the clear button. Default value is `true`. */
83
+ showClear?: boolean;
84
+
85
+ /** Set to `true` to display the clear button even if `required` is set. Default is `false`. */
86
+ alwaysShowClear?: boolean;
87
+
88
+ /** Base CSS class to be applied to the field. Defaults to `lookupfield`. */
89
+ baseClass?: string;
90
+
91
+ /** Name or configuration of the icon to be put on the left side of the input. */
92
+ icon?: StringProp | Record<string, any>;
93
+
94
+ /** Additional config to be applied to all items. */
95
+ itemConfig?: any;
96
+
97
+ /** An array of objects describing the mapping of option data to store data. */
98
+ bindings?: LookupBinding[];
99
+
100
+ /** A delay in milliseconds between typing stop and query. Default is `150`. */
101
+ queryDelay?: number;
102
+
103
+ /** Minimal number of characters required before query is made. */
104
+ minQueryLength?: number;
105
+
106
+ /** Set to `true` to hide the search field. */
107
+ hideSearchField?: boolean;
108
+
109
+ /** Number of options required to show search field. Defaults to `7`. */
110
+ minOptionsForSearchField?: number;
111
+
112
+ /** Text to display while data is being loaded. */
113
+ loadingText?: string;
114
+
115
+ /** Error message displayed if server query throws an exception. */
116
+ queryErrorText?: string;
117
+
118
+ /** Message to be displayed if no entries match the user query. */
119
+ noResultsText?: string;
120
+
121
+ /** Name of the field which holds the id of the option. Default is `id`. */
122
+ optionIdField?: string;
123
+
124
+ /** Name of the field which holds the display text of the option. Default is `text`. */
125
+ optionTextField?: string;
126
+
127
+ /** Name of the field to store id of selected value in multiple mode. Default is `id`. */
128
+ valueIdField?: string;
129
+
130
+ /** Name of the field to store display text of selected value. Default is `text`. */
131
+ valueTextField?: string;
132
+
133
+ /** `onQuery` will be called once to fetch all options; filtering occurs client-side. */
134
+ fetchAll?: boolean;
135
+
136
+ /** When set with `fetchAll`, fetched options are cached for widget lifetime. */
137
+ cacheAll?: boolean;
138
+
139
+ /** Close the dropdown after selection. Default is `true`. */
140
+ closeOnSelect?: boolean;
141
+
142
+ /** Message displayed if the entered search query is too short. */
143
+ minQueryLengthMessageText?: string;
144
+
145
+ /** Query function called to fetch options. */
146
+ onQuery?:
147
+ | string
148
+ | ((
149
+ query: string | { query: string; page: number; pageSize: number },
150
+ instance: Instance,
151
+ ) => TOption[] | Promise<TOption[]>);
152
+
153
+ /** Set to `true` to sort dropdown options. */
154
+ sort?: boolean;
155
+
156
+ /** Additional list options, such as grouping configuration, custom sorting, etc. */
157
+ listOptions?: Record<string, any>;
158
+
159
+ /** Show dropdown immediately after component mount; useful for cell editing. */
160
+ autoOpen?: BooleanProp;
161
+
162
+ /** Allow enter key events to propagate; useful for forms or grid cell editors. */
163
+ submitOnEnterKey?: BooleanProp;
164
+
165
+ /** Allow dropdown enter key events to propagate for form submission. */
166
+ submitOnDropdownEnterKey?: BooleanProp;
167
+
168
+ /** Number of additional items loaded in `infinite` mode. Default is `100`. */
169
+ pageSize?: number;
170
+
171
+ /** Set to `true` to enable loading additional options when scroll reaches end. */
172
+ infinite?: boolean;
173
+
174
+ /** Allow quick selection of all displayed items on `Ctrl + A` key combination. */
175
+ quickSelectAll?: boolean;
176
+
177
+ /** Parameters that affect filtering. */
178
+ filterParams?: StructuredProp;
179
+
180
+ /** Used in multiple selection lookups to construct display text from multiple fields. */
181
+ onGetRecordDisplayText?: ((record: TRecord, instance: Instance) => string) | null;
182
+
183
+ /** Callback to create a filter function for given filter params. */
184
+ onCreateVisibleOptionsFilter?:
185
+ | string
186
+ | ((filterParams: unknown, instance: Instance) => (option: TOption) => boolean);
187
+
188
+ /** Additional configuration to be passed to the dropdown, such as `style`, `positioning`, etc. */
189
+ dropdownOptions?: Partial<DropdownConfig>;
190
+
191
+ /** Custom validation function. */
192
+ onValidate?:
193
+ | string
194
+ | ((value: number | string, instance: Instance, validationParams: Record<string, unknown>) => unknown);
195
+ }
196
+
197
+ export class LookupField<TOption = unknown, TRecord = unknown> extends Field<
198
+ LookupFieldConfig<TOption, TRecord>
199
+ > {
200
+ declare public baseClass: string;
201
+ declare public multiple: boolean;
202
+ declare public hideClear?: boolean;
203
+ declare public showClear: boolean;
204
+ declare public alwaysShowClear: boolean;
205
+ declare public hideSearchField: boolean;
206
+ declare public minOptionsForSearchField: number;
207
+ declare public loadingText: string;
208
+ declare public queryErrorText: string;
209
+ declare public noResultsText: string;
210
+ declare public optionIdField: string;
211
+ declare public optionTextField: string;
212
+ declare public valueIdField: string;
213
+ declare public valueTextField: string;
214
+ declare public fetchAll: boolean;
215
+ declare public cacheAll: boolean;
216
+ declare public closeOnSelect: boolean;
217
+ declare public minQueryLengthMessageText: string;
218
+ declare public sort?: boolean;
219
+ declare public listOptions?: Record<string, any> | null;
220
+ declare public autoOpen?: boolean;
221
+ declare public submitOnEnterKey?: boolean;
222
+ declare public submitOnDropdownEnterKey?: boolean;
223
+ declare public pageSize: number;
224
+ declare public infinite?: boolean;
225
+ declare public quickSelectAll?: boolean;
226
+ declare public queryDelay: number;
227
+ declare public minQueryLength: number;
228
+ declare public onGetRecordDisplayText?: ((record: Record<string, any>, instance: Instance) => string) | null;
229
+ declare public onQuery?:
230
+ | string
231
+ | ((
232
+ params: string | { query: string; page: number; pageSize: number },
233
+ instance: Instance,
234
+ ) => Promise<Record<string, any>[]> | Record<string, any>[]);
235
+ declare public onCreateVisibleOptionsFilter?:
236
+ | string
237
+ | ((filterParams: unknown, instance: Instance) => (option: Record<string, any>) => boolean);
238
+ declare public value?: BindingInput;
239
+ declare public text?: BindingInput<string>;
240
+ declare public records?: Record<string, any>[];
241
+ declare public values?: unknown[];
242
+ declare public options?: Record<string, any>[];
243
+
244
+ declare public enabled?: boolean;
245
+ declare public placeholder?: string;
246
+ declare public readOnly?: boolean;
247
+ declare public dropdownOptions?: Partial<DropdownConfig>;
248
+ declare public bindings?: BindingConfig[];
249
+ declare public keyBindings?: BindingConfig[];
250
+ declare public itemConfig?: CxChild;
251
+
252
+ declareData(...args: Record<string, any>[]): void {
253
+ let additionalAttributes = this.multiple
254
+ ? { values: undefined, records: undefined }
255
+ : { value: undefined, text: undefined };
256
+
257
+ super.declareData(
258
+ {
259
+ disabled: undefined,
260
+ enabled: undefined,
261
+ placeholder: undefined,
262
+ required: undefined,
263
+ options: undefined,
264
+ icon: undefined,
265
+ autoOpen: undefined,
266
+ readOnly: undefined,
267
+ filterParams: { structured: true },
268
+ },
269
+ additionalAttributes,
270
+ ...args,
271
+ );
272
+ }
273
+
274
+ init(): void {
275
+ if (isDefined(this.hideClear)) this.showClear = !this.hideClear;
276
+
277
+ if (this.alwaysShowClear) this.showClear = true;
278
+
279
+ if (!this.bindings) {
280
+ let b: BindingConfig[] = [];
281
+ if (this.value) {
282
+ if (isAccessorChain(this.value)) this.value = bind(this.value);
283
+ if ((this.value as any).bind)
284
+ b.push({
285
+ key: true,
286
+ local: (this.value as any).bind,
287
+ remote: `$option.${this.optionIdField}`,
288
+ set: (this.value as any).set,
289
+ });
290
+ }
291
+
292
+ if (this.text as string | AccessorChain<unknown>) {
293
+ if (isAccessorChain(this.text)) this.text = bind(this.text);
294
+ if ((this.text as any).bind)
295
+ b.push({
296
+ local: (this.text as any).bind,
297
+ remote: `$option.${this.optionTextField}`,
298
+ set: (this.text as any).set,
299
+ });
300
+ }
301
+
302
+ this.bindings = b;
303
+ }
304
+
305
+ if (this.bindings.length == 0 && this.multiple)
306
+ this.bindings = [
307
+ {
308
+ key: true,
309
+ local: `$value.${this.valueIdField}`,
310
+ remote: `$option.${this.optionIdField}`,
311
+ },
312
+ {
313
+ local: `$value.${this.valueTextField}`,
314
+ remote: `$option.${this.optionTextField}`,
315
+ },
316
+ ];
317
+
318
+ this.keyBindings = this.bindings.filter((b) => b.key);
319
+
320
+ if (!this.items && !this.children)
321
+ this.items = {
322
+ type: HighlightedSearchText,
323
+ text: { bind: `$option.${this.optionTextField}` },
324
+ query: { bind: "$query" },
325
+ } as any;
326
+
327
+ this.itemConfig = this.children || this.items;
328
+
329
+ this.items = [];
330
+ delete this.children;
331
+
332
+ super.init();
333
+ }
334
+
335
+ prepareData(context: RenderingContext, instance: FieldInstance<LookupField>): void {
336
+ let { data, store } = instance;
337
+
338
+ data.stateMods = {
339
+ multiple: this.multiple,
340
+ single: !this.multiple,
341
+ disabled: data.disabled,
342
+ readonly: data.readOnly,
343
+ };
344
+
345
+ data.visibleOptions = data.options;
346
+ if (this.onCreateVisibleOptionsFilter && isArray(data.options)) {
347
+ let filterPredicate = instance.invoke("onCreateVisibleOptionsFilter", data.filterParams, instance);
348
+ data.visibleOptions = data.options.filter(filterPredicate);
349
+ }
350
+
351
+ data.selectedKeys = [];
352
+
353
+ if (this.multiple) {
354
+ if (isArray(data.values) && isArray(data.options)) {
355
+ data.selectedKeys = data.values.map((v) => (this.keyBindings!.length == 1 ? [v] : v));
356
+ let map: Record<number, Record<string, any>> = {};
357
+ data.options.filter(($option) => {
358
+ let optionKey = getOptionKey(this.keyBindings!, { $option });
359
+ for (let i = 0; i < data.selectedKeys.length; i++)
360
+ if (areKeysEqual(optionKey, data.selectedKeys[i])) {
361
+ map[i] = convertOption(this.bindings!, { $option });
362
+ break;
363
+ }
364
+ });
365
+ data.records = [];
366
+ for (let i = 0; i < data.selectedKeys.length; i++) if (map[i]) data.records.push(map[i]);
367
+ } else if (isArray(data.records))
368
+ data.selectedKeys.push(
369
+ ...data.records.map(($value) => this.keyBindings!.map((b) => Binding.get(b.local).value({ $value }))),
370
+ );
371
+ } else {
372
+ let dataViewData = store.getData();
373
+ data.selectedKeys.push(this.keyBindings!.map((b) => Binding.get(b.local).value(dataViewData)));
374
+ if (!this.text && isArray(data.options)) {
375
+ let option = data.options.find(($option) =>
376
+ areKeysEqual(getOptionKey(this.keyBindings!, { $option }), data.selectedKeys[0]),
377
+ );
378
+ data.text = (option && (option as any)[this.optionTextField!]) || "";
379
+ }
380
+ }
381
+
382
+ (instance as DropdownInstance).lastDropdown = context.lastDropdown;
383
+
384
+ super.prepareData(context, instance);
385
+ }
386
+
387
+ renderInput(context: RenderingContext, instance: FieldInstance<LookupField>, key: string): React.ReactNode {
388
+ return (
389
+ <LookupComponent
390
+ key={key}
391
+ multiple={this.multiple!}
392
+ instance={instance}
393
+ itemConfig={this.itemConfig}
394
+ bindings={this.bindings!}
395
+ baseClass={this.baseClass!}
396
+ label={this.labelPlacement && getContent(this.renderLabel(context, instance, "label"))}
397
+ help={this.helpPlacement && getContent(this.renderHelp(context, instance, "help"))}
398
+ forceUpdate={context.forceUpdate}
399
+ icon={this.renderIcon(context, instance, "icon")}
400
+ />
401
+ );
402
+ }
403
+
404
+ filterOptions(instance: Instance, options: DataRecord[], query?: string): DataRecord[] {
405
+ if (!query) return options;
406
+ let textPredicate = getSearchQueryPredicate(query);
407
+ return options.filter(
408
+ (o) => isString(o[this.optionTextField!]) && textPredicate((o as any)[this.optionTextField!] as string),
409
+ );
410
+ }
411
+
412
+ isEmpty(data: Record<string, any>): boolean {
413
+ if (this.multiple) return !isNonEmptyArray(data.values) && !isNonEmptyArray(data.records);
414
+ return super.isEmpty(data);
415
+ }
416
+
417
+ getValidationValue(data: Record<string, any>): unknown {
418
+ if (this.multiple) return data.records ?? data.values;
419
+ return super.getValidationValue(data);
420
+ }
421
+
422
+ formatValue(context: RenderingContext, instance: Instance): string | React.ReactNode {
423
+ if (!this.multiple) return super.formatValue(context, instance);
424
+
425
+ let { records, values, options } = instance.data;
426
+ if (isArray(records)) {
427
+ let valueTextFormatter =
428
+ typeof this.onGetRecordDisplayText === "function"
429
+ ? this.onGetRecordDisplayText
430
+ : (record: Record<string, any>) =>
431
+ (record as any)[this.valueTextField!] || (record as any)[this.valueIdField!];
432
+ return records.map((record) => valueTextFormatter(record as any, instance));
433
+ }
434
+
435
+ if (isArray(values)) {
436
+ if (isArray(options))
437
+ return values
438
+ .map((id) => {
439
+ let option = options.find((o) => (o as any)[this.optionIdField!] == id);
440
+ return option ? (option as any)[this.valueTextField!] : id;
441
+ })
442
+ .filter(Boolean)
443
+ .join(", ");
444
+
445
+ return values.join(", ");
446
+ }
447
+
448
+ return null;
449
+ }
450
+ }
451
+
452
+ LookupField.prototype.baseClass = "lookupfield";
453
+ //LookupField.prototype.memoize = false;
454
+ LookupField.prototype.multiple = false;
455
+ LookupField.prototype.queryDelay = 150;
456
+ LookupField.prototype.minQueryLength = 0;
457
+ LookupField.prototype.hideSearchField = false;
458
+ LookupField.prototype.minOptionsForSearchField = 7;
459
+ LookupField.prototype.loadingText = "Loading...";
460
+ LookupField.prototype.queryErrorText = "Error occurred while querying for lookup data.";
461
+ LookupField.prototype.noResultsText = "No results found.";
462
+ LookupField.prototype.optionIdField = "id";
463
+ LookupField.prototype.optionTextField = "text";
464
+ LookupField.prototype.valueIdField = "id";
465
+ LookupField.prototype.valueTextField = "text";
466
+ LookupField.prototype.suppressErrorsUntilVisited = true;
467
+ LookupField.prototype.fetchAll = false;
468
+ LookupField.prototype.cacheAll = false;
469
+ LookupField.prototype.showClear = true;
470
+ LookupField.prototype.alwaysShowClear = false;
471
+ LookupField.prototype.closeOnSelect = true;
472
+ LookupField.prototype.minQueryLengthMessageText = "Type in at least {0} character(s).";
473
+ LookupField.prototype.icon = null;
474
+ LookupField.prototype.sort = false;
475
+ LookupField.prototype.listOptions = null;
476
+ LookupField.prototype.autoOpen = false;
477
+ LookupField.prototype.submitOnEnterKey = false;
478
+ LookupField.prototype.submitOnDropdownEnterKey = false;
479
+ LookupField.prototype.pageSize = 100;
480
+ LookupField.prototype.infinite = false;
481
+ LookupField.prototype.quickSelectAll = false;
482
+ LookupField.prototype.onGetRecordDisplayText = null;
483
+
484
+ Localization.registerPrototype("cx/widgets/LookupField", LookupField);
485
+
486
+ Widget.alias("lookupfield", LookupField);
487
+
488
+ interface BindingConfig {
489
+ local: string;
490
+ remote: string;
491
+ key?: boolean;
492
+ set?: (value: unknown, instance: Instance) => void;
493
+ }
494
+
495
+ function getOptionKey(bindings: BindingConfig[], data: Record<string, any>): unknown[] {
496
+ return bindings.filter((a) => a.key).map((b) => Binding.get(b.remote).value(data));
497
+ }
498
+
499
+ function areKeysEqual(key1: unknown[], key2: unknown[]): boolean {
500
+ if (!key1 || !key2 || key1.length != key2.length) return false;
501
+
502
+ for (let i = 0; i < key1.length; i++) if (key1[i] !== key2[i]) return false;
503
+
504
+ return true;
505
+ }
506
+
507
+ function convertOption(bindings: BindingConfig[], data: Record<string, any>): Record<string, any> {
508
+ let result: Record<string, any> = { $value: {} };
509
+ bindings.forEach((b) => {
510
+ let value = Binding.get(b.remote).value(data);
511
+ result = Binding.get(b.local).set(result, value);
512
+ });
513
+ return result.$value as Record<string, any>;
514
+ }
515
+
516
+ class SelectionDelegate extends Selection {
517
+ delegate: (record: Record<string, any>, index: number) => boolean;
518
+
519
+ constructor({ delegate }: { delegate: (record: Record<string, any>, index: number) => boolean }) {
520
+ super();
521
+ this.delegate = delegate;
522
+ }
523
+
524
+ getIsSelectedDelegate(store: unknown): (record: Record<string, any>, index: number) => boolean {
525
+ return (record: Record<string, any>, index: number) => this.delegate(record, index);
526
+ }
527
+
528
+ select(): boolean {
529
+ return false;
530
+ }
531
+ }
532
+
533
+ interface LookupComponentProps {
534
+ instance: FieldInstance<LookupField>;
535
+ multiple: boolean;
536
+ itemConfig: unknown;
537
+ bindings: BindingConfig[];
538
+ baseClass: string;
539
+ label?: React.ReactNode;
540
+ help?: React.ReactNode;
541
+ forceUpdate: () => void;
542
+ icon?: React.ReactNode;
543
+ }
544
+
545
+ interface LookupComponentState {
546
+ options: unknown[];
547
+ formatted?: string;
548
+ value?: string;
549
+ dropdownOpen: boolean;
550
+ focus: boolean;
551
+ status?: string;
552
+ message?: string;
553
+ query?: string;
554
+ page?: number;
555
+ hover?: boolean;
556
+ }
557
+
558
+ class LookupComponent extends VDOM.Component<LookupComponentProps, LookupComponentState> {
559
+ dom: {
560
+ input?: HTMLDivElement | null;
561
+ dropdown?: HTMLDivElement | null;
562
+ list?: HTMLDivElement | null;
563
+ query?: HTMLInputElement | null;
564
+ } = {};
565
+ itemStore: ReadOnlyDataView;
566
+ dropdown?: Widget;
567
+ list?: Widget;
568
+ listKeyDown?: (e: React.KeyboardEvent) => void;
569
+ queryTimeoutId?: ReturnType<typeof setTimeout>;
570
+ cachedResult?: Record<string, any>[];
571
+ tmpCachedResult?: Record<string, any>[];
572
+ lastQueryId?: number;
573
+ lastQuery?: string;
574
+ extraPageLoadingBlocker?: string | false;
575
+ unsubscribeListOnWheel?: (() => void) | null;
576
+ unsubscribeListOnScroll?: (() => void) | null;
577
+
578
+ constructor(props: LookupComponentProps) {
579
+ super(props);
580
+ let { data, store } = this.props.instance;
581
+ this.dom = {};
582
+ this.state = {
583
+ options: [],
584
+ formatted: data.formatted,
585
+ value: data.formatted,
586
+ dropdownOpen: false,
587
+ focus: false,
588
+ };
589
+
590
+ this.itemStore = new ReadOnlyDataView({
591
+ store: store,
592
+ });
593
+ }
594
+
595
+ getOptionKey(data: Record<string, any>): unknown[] {
596
+ return this.props.bindings.filter((a) => a.key).map((b) => Binding.get(b.remote).value(data));
597
+ }
598
+
599
+ getLocalKey(data: Record<string, any>): unknown[] {
600
+ return this.props.bindings.filter((a) => a.key).map((b) => Binding.get(b.local).value(data));
601
+ }
602
+
603
+ findOption(options: Record<string, any>[], key: unknown[]): number {
604
+ if (!key) return -1;
605
+ for (let i = 0; i < options.length; i++) {
606
+ let optionKey = this.getOptionKey({ $option: options[i] });
607
+ if (areKeysEqual(key, optionKey)) return i;
608
+ }
609
+ return -1;
610
+ }
611
+
612
+ getDropdown(): Widget {
613
+ if (this.dropdown) return this.dropdown;
614
+
615
+ let { widget }: { widget: LookupField } = this.props.instance as unknown as { widget: LookupField };
616
+ let { lastDropdown } = this.props.instance as DropdownInstance;
617
+
618
+ this.list = Widget.create({
619
+ type: List,
620
+ sortField: widget.sort && widget.optionTextField,
621
+ sortDirection: "ASC",
622
+ mod: "dropdown",
623
+ scrollSelectionIntoView: true,
624
+ cached: widget.infinite,
625
+ ...widget.listOptions,
626
+ records: bind("$options"),
627
+ recordName: "$option",
628
+ onItemClick: (e: React.MouseEvent, inst: Instance) => this.onItemClick(e, inst),
629
+ pipeKeyDown: (kd: (e: React.KeyboardEvent) => void) => {
630
+ this.listKeyDown = kd;
631
+ },
632
+ selectOnTab: true,
633
+ focusable: false,
634
+ selection: {
635
+ type: SelectionDelegate,
636
+ delegate: (data: any) =>
637
+ this.props.instance.data.selectedKeys.find((x: any) =>
638
+ areKeysEqual(x, this.getOptionKey({ $option: data })),
639
+ ) != null,
640
+ },
641
+ children: this.props.itemConfig,
642
+ });
643
+
644
+ let dropdown = {
645
+ constrain: true,
646
+ scrollTracking: true,
647
+ inline: !isTouchDevice() || !!lastDropdown,
648
+ placementOrder: "down-right down-left up-right up-left",
649
+ ...widget.dropdownOptions,
650
+ type: Dropdown,
651
+ relatedElement: this.dom.input,
652
+ renderChildren: () => this.renderDropdownContents(),
653
+ onFocusOut: (e: React.MouseEvent) => this.closeDropdown(e),
654
+ memoize: false,
655
+ touchFriendly: isTouchDevice(),
656
+ onMeasureNaturalContentSize: () => {
657
+ if (this.dom.dropdown && this.dom.list) {
658
+ return {
659
+ height:
660
+ this.dom.dropdown.offsetHeight -
661
+ this.dom.list.offsetHeight +
662
+ ((this.dom.list.firstElementChild as HTMLElement)?.offsetHeight || 0),
663
+ };
664
+ }
665
+ },
666
+ onDismissAfterScroll: () => {
667
+ this.closeDropdown(null, true);
668
+ return false;
669
+ },
670
+ };
671
+
672
+ return (this.dropdown = Widget.create(dropdown));
673
+ }
674
+
675
+ renderDropdownContents(): React.ReactNode {
676
+ let content;
677
+ let { instance } = this.props;
678
+ let { data, widget }: { data: Record<string, any>; widget: LookupField } = instance as unknown as {
679
+ data: Record<string, any>;
680
+ widget: LookupField;
681
+ };
682
+ let { CSS, baseClass } = widget;
683
+
684
+ let searchVisible =
685
+ !widget.hideSearchField &&
686
+ (!isArray(data.visibleOptions) ||
687
+ (widget.minOptionsForSearchField && data.visibleOptions.length >= widget.minOptionsForSearchField));
688
+
689
+ if (this.state.status == "loading") {
690
+ content = (
691
+ <div key="msg" className={CSS.element(baseClass, "message", "loading")}>
692
+ {widget.loadingText}
693
+ </div>
694
+ );
695
+ } else if (this.state.status == "error") {
696
+ content = (
697
+ <div key="msg" className={CSS.element(baseClass, "message", "error")}>
698
+ {widget.queryErrorText}
699
+ </div>
700
+ );
701
+ } else if (this.state.status == "info") {
702
+ content = (
703
+ <div key="msg" className={CSS.element(baseClass, "message", "info")}>
704
+ {this.state.message}
705
+ </div>
706
+ );
707
+ } else if (this.state.options.length == 0) {
708
+ content = (
709
+ <div key="msg" className={CSS.element(baseClass, "message", "no-results")}>
710
+ {widget.noResultsText}
711
+ </div>
712
+ );
713
+ } else {
714
+ content = (
715
+ <div
716
+ key="msg"
717
+ ref={(el) => {
718
+ this.dom.list = el;
719
+ this.subscribeListOnWheel(el);
720
+ this.subscribeListOnScroll(el);
721
+ }}
722
+ className={CSS.element(baseClass, "scroll-container")}
723
+ >
724
+ <Cx widget={this.list} store={this.itemStore} options={{ name: "lookupfield-list" }} />
725
+ </div>
726
+ );
727
+ }
728
+
729
+ return (
730
+ <div
731
+ key="dropdown"
732
+ ref={(el) => {
733
+ this.dom.dropdown = el as HTMLDivElement;
734
+ }}
735
+ className={CSS.element(baseClass, "dropdown")}
736
+ tabIndex={0}
737
+ onFocus={(e) => this.onDropdownFocus(e)}
738
+ onKeyDown={(e) => this.onDropdownKeyPress(e)}
739
+ >
740
+ {searchVisible && (
741
+ <input
742
+ key="query"
743
+ ref={(el) => {
744
+ this.dom.query = el as HTMLInputElement;
745
+ }}
746
+ type="text"
747
+ className={CSS.element(baseClass, "query")}
748
+ onClick={(e) => {
749
+ e.preventDefault();
750
+ e.stopPropagation();
751
+ }}
752
+ onChange={(e) => this.query(e.target.value)}
753
+ onBlur={(e) => this.onQueryBlur(e)}
754
+ />
755
+ )}
756
+ {content}
757
+ </div>
758
+ );
759
+ }
760
+
761
+ onListWheel(e: WheelEvent): void {
762
+ let { list } = this.dom;
763
+ if (
764
+ list &&
765
+ ((list.scrollTop + list.offsetHeight == list.scrollHeight && e.deltaY > 0) ||
766
+ (list.scrollTop == 0 && e.deltaY < 0))
767
+ ) {
768
+ e.preventDefault();
769
+ e.stopPropagation();
770
+ }
771
+ }
772
+
773
+ onListScroll(): void {
774
+ if (!this.dom.list) return;
775
+ var el = this.dom.list;
776
+ if (el.scrollTop > el.scrollHeight - 2 * el.offsetHeight) {
777
+ this.loadAdditionalOptionPages();
778
+ }
779
+ }
780
+
781
+ onDropdownFocus(e: React.FocusEvent): void {
782
+ if (this.dom.query && !isFocused(this.dom.query) && !isTouchDevice()) FocusManager.focus(this.dom.query);
783
+ }
784
+
785
+ getPlaceholder(text?: string): React.ReactNode {
786
+ let { CSS, baseClass } = this.props.instance.widget;
787
+
788
+ if (text) return <span className={CSS.element(baseClass, "placeholder")}>{text}</span>;
789
+
790
+ return <span className={CSS.element(baseClass, "placeholder")}>&nbsp;</span>;
791
+ }
792
+
793
+ render(): React.ReactNode {
794
+ let { instance, label, help, icon: iconVDOM } = this.props;
795
+ let { data, widget, state } = instance;
796
+ let { CSS, baseClass, suppressErrorsUntilVisited } = widget as LookupField;
797
+
798
+ let icon = iconVDOM && (
799
+ <div
800
+ key="icon"
801
+ className={CSS.element(baseClass, "left-icon")}
802
+ onMouseDown={preventDefault}
803
+ onClick={(e) => {
804
+ this.openDropdown(e);
805
+ e.stopPropagation();
806
+ e.preventDefault();
807
+ }}
808
+ >
809
+ {iconVDOM}
810
+ </div>
811
+ );
812
+
813
+ let dropdown;
814
+ if (this.state.dropdownOpen) {
815
+ this.itemStore.setData({
816
+ $options: this.state.options,
817
+ $query: this.lastQuery,
818
+ });
819
+ dropdown = (
820
+ <Cx widget={this.getDropdown()} store={this.itemStore} options={{ name: "lookupfield-dropdown" }} />
821
+ );
822
+ }
823
+
824
+ let insideButton = null;
825
+ let multipleEntries = this.props.multiple && isArray(data.records) && data.records.length > 1;
826
+
827
+ if (!data.readOnly) {
828
+ if (
829
+ widget.showClear &&
830
+ !data.disabled &&
831
+ !data.empty &&
832
+ (widget.alwaysShowClear || (!data.required && !this.props.multiple) || multipleEntries)
833
+ ) {
834
+ insideButton = (
835
+ <div
836
+ key="ib"
837
+ onMouseDown={preventDefault}
838
+ onClick={(e) => (!this.props.multiple ? this.onClearClick(e) : this.onClearMultipleClick(e))}
839
+ className={CSS.element(baseClass, "clear")}
840
+ >
841
+ <ClearIcon className={CSS.element(baseClass, "icon")} />
842
+ </div>
843
+ );
844
+ } else {
845
+ insideButton = (
846
+ <div
847
+ key="ib"
848
+ className={CSS.element(baseClass, "tool")}
849
+ onMouseDown={preventDefault}
850
+ onClick={(e) => {
851
+ this.toggleDropdown(e, true);
852
+ e.stopPropagation();
853
+ e.preventDefault();
854
+ }}
855
+ >
856
+ <DropdownIcon className={CSS.element(baseClass, "icon")} />
857
+ </div>
858
+ );
859
+ }
860
+ }
861
+
862
+ let text;
863
+
864
+ if (this.props.multiple) {
865
+ let readOnly = data.disabled || data.readOnly;
866
+ if (isNonEmptyArray(data.records)) {
867
+ let valueTextFormatter =
868
+ widget.onGetRecordDisplayText ??
869
+ ((record: Record<string, any>) => record[widget.valueTextField] as string);
870
+ text = data.records.map((v, i) => (
871
+ <div
872
+ key={i}
873
+ className={CSS.element(baseClass, "tag", {
874
+ readonly: readOnly,
875
+ })}
876
+ >
877
+ <span className={CSS.element(baseClass, "tag-value")}>{valueTextFormatter(v, instance)}</span>
878
+ {!readOnly && (
879
+ <div
880
+ className={CSS.element(baseClass, "tag-clear")}
881
+ onMouseDown={(e) => {
882
+ e.preventDefault();
883
+ e.stopPropagation();
884
+ }}
885
+ onClick={(e) => this.onClearClick(e, v)}
886
+ >
887
+ <ClearIcon className={CSS.element(baseClass, "icon")} />
888
+ </div>
889
+ )}
890
+ </div>
891
+ ));
892
+ } else {
893
+ text = this.getPlaceholder(data.placeholder);
894
+ }
895
+ } else {
896
+ text = !data.empty ? data.text || this.getPlaceholder() : this.getPlaceholder(data.placeholder);
897
+ }
898
+
899
+ let states = {
900
+ visited: state.visited,
901
+ focus: this.state.focus || this.state.dropdownOpen,
902
+ icon: !!iconVDOM,
903
+ empty: !data.placeholder && data.empty,
904
+ error: data.error && (state.visited || !suppressErrorsUntilVisited || !data.empty),
905
+ };
906
+
907
+ return (
908
+ <div
909
+ className={CSS.expand(data.classNames, CSS.state(states))}
910
+ style={data.style}
911
+ onMouseDown={stopPropagation}
912
+ onTouchStart={stopPropagation}
913
+ onKeyDown={(e) => this.onKeyDown(e)}
914
+ >
915
+ <div
916
+ id={data.id}
917
+ className={CSS.expand(CSS.element(widget.baseClass, "input"), data.inputClass)}
918
+ style={data.inputStyle}
919
+ tabIndex={data.disabled ? null : data.tabIndex || 0}
920
+ ref={(el) => {
921
+ this.dom.input = el;
922
+ }}
923
+ aria-labelledby={data.id + "-label"}
924
+ onMouseMove={(e) => tooltipMouseMove(e, ...getFieldTooltip(this.props.instance))}
925
+ onMouseLeave={(e) => tooltipMouseLeave(e, ...getFieldTooltip(this.props.instance))}
926
+ onClick={(e) => this.onClick(e)}
927
+ onKeyDown={(e) => this.onInputKeyDown(e)}
928
+ onMouseDown={(e) => this.onMouseDown(e)}
929
+ onBlur={(e) => this.onBlur(e)}
930
+ onFocus={(e) => this.onFocus(e)}
931
+ >
932
+ {text}
933
+ </div>
934
+ {insideButton}
935
+ {icon}
936
+ {dropdown}
937
+ {label}
938
+ {help}
939
+ </div>
940
+ );
941
+ }
942
+
943
+ onMouseDown(e: React.MouseEvent): void {
944
+ //skip touch start to allow touch scrolling
945
+ if (isTouchEvent()) return;
946
+ e.preventDefault();
947
+ e.stopPropagation();
948
+ this.toggleDropdown(e, true);
949
+ }
950
+
951
+ onClick(e: React.MouseEvent): void {
952
+ //mouse down will handle it for non-touch events
953
+ if (!isTouchEvent()) return;
954
+ e.preventDefault();
955
+ e.stopPropagation();
956
+ this.toggleDropdown(e, true);
957
+ }
958
+
959
+ onItemClick(
960
+ e: React.KeyboardEvent | React.MouseEvent,
961
+ { store }: { store: { getData: () => Record<string, any> } },
962
+ ): void {
963
+ this.select(e, [store.getData()]);
964
+ if (!this.props.instance.widget.submitOnEnterKey || e.type != "keydown") e.stopPropagation();
965
+ if ((e as React.KeyboardEvent).keyCode != KeyCode.tab) e.preventDefault();
966
+ }
967
+
968
+ onClearClick(e: React.MouseEvent | React.KeyboardEvent, value?: Record<string, any>): void {
969
+ let { instance } = this.props;
970
+ let { data, store, widget } = instance;
971
+ let { keyBindings } = widget;
972
+ e.stopPropagation();
973
+ e.preventDefault();
974
+ if (widget.multiple) {
975
+ if (isArray(data.records)) {
976
+ let itemKey = this.getLocalKey({ $value: value });
977
+ let newRecords = data.records.filter((v) => !areKeysEqual(this.getLocalKey({ $value: v }), itemKey));
978
+
979
+ instance.set("records", newRecords);
980
+
981
+ let newValues = newRecords
982
+ .map((rec) => this.getLocalKey({ $value: rec }))
983
+ .map((k) => (keyBindings!.length == 1 ? k[0] : k));
984
+
985
+ instance.set("values", newValues);
986
+ }
987
+ } else {
988
+ this.props.bindings.forEach((b) => {
989
+ store.set(b.local, widget.emptyValue);
990
+ });
991
+ }
992
+
993
+ if (!isTouchEvent()) this.dom.input!.focus();
994
+ }
995
+
996
+ onClearMultipleClick(e: React.MouseEvent): void {
997
+ let { instance } = this.props;
998
+ instance.set("records", []);
999
+ instance.set("values", []);
1000
+ }
1001
+
1002
+ select(e: React.KeyboardEvent | React.MouseEvent, itemsData: Record<string, any>[], reset?: boolean): void {
1003
+ let { instance } = this.props;
1004
+ let { store, data, widget } = instance;
1005
+ let { bindings, keyBindings } = widget;
1006
+
1007
+ if (widget.multiple) {
1008
+ let { selectedKeys, records } = data;
1009
+
1010
+ let newRecords = reset ? [] : [...(records || [])];
1011
+ let singleSelect = itemsData.length == 1;
1012
+ let optionKey: unknown[] | null = null;
1013
+ if (singleSelect) optionKey = this.getOptionKey(itemsData[0]);
1014
+
1015
+ // deselect
1016
+ if (singleSelect && selectedKeys.find((k: any) => areKeysEqual(optionKey!, k))) {
1017
+ newRecords = records.filter((v: any) => !areKeysEqual(optionKey!, this.getLocalKey({ $value: v })));
1018
+ } else {
1019
+ itemsData.forEach((itemData) => {
1020
+ let valueData: Record<string, any> = {
1021
+ $value: {},
1022
+ };
1023
+ bindings!.forEach((b) => {
1024
+ valueData = Binding.get(b.local).set(valueData, Binding.get(b.remote).value(itemData));
1025
+ });
1026
+ newRecords.push(valueData.$value as Record<string, any>);
1027
+ });
1028
+ }
1029
+
1030
+ instance.set("records", newRecords);
1031
+
1032
+ let newValues = newRecords
1033
+ .map((rec) => this.getLocalKey({ $value: rec }))
1034
+ .map((k) => (keyBindings!.length == 1 ? k[0] : k));
1035
+
1036
+ instance.set("values", newValues);
1037
+ } else {
1038
+ bindings!.forEach((b) => {
1039
+ let v = Binding.get(b.remote).value(itemsData[0]);
1040
+ if (b.set) b.set(v, instance);
1041
+ else store.set(b.local, v);
1042
+ });
1043
+ }
1044
+
1045
+ if (widget.closeOnSelect) {
1046
+ //Pressing Tab should work it's own thing. Focus will move elsewhere and the dropdown will close.
1047
+ if ((e as React.KeyboardEvent).keyCode != KeyCode.tab) {
1048
+ if (!isTouchEvent()) this.dom.input!.focus();
1049
+ this.closeDropdown(e);
1050
+ }
1051
+ }
1052
+
1053
+ if ((e as React.KeyboardEvent).keyCode == KeyCode.enter && widget.submitOnDropdownEnterKey) {
1054
+ this.submitOnEnter(e as React.KeyboardEvent);
1055
+ }
1056
+ }
1057
+
1058
+ onDropdownKeyPress(e: React.KeyboardEvent): void {
1059
+ switch (e.keyCode) {
1060
+ case KeyCode.esc:
1061
+ this.closeDropdown(e);
1062
+ this.dom.input!.focus();
1063
+ break;
1064
+
1065
+ case KeyCode.tab:
1066
+ // if tab needs to do a list selection, we have to first call List's handleKeyDown
1067
+ if (this.listKeyDown) this.listKeyDown(e);
1068
+ // if next focusable element is disabled, recalculate and update the dom before switching focus
1069
+ this.props.forceUpdate();
1070
+ break;
1071
+
1072
+ case KeyCode.a:
1073
+ if (!e.ctrlKey) return;
1074
+
1075
+ let { quickSelectAll, multiple } = this.props.instance.widget;
1076
+ if (!quickSelectAll || !multiple) return;
1077
+
1078
+ let optionsToSelect = this.state.options.map((o) => ({
1079
+ $option: o,
1080
+ }));
1081
+ this.select(e, optionsToSelect, true);
1082
+ e.stopPropagation();
1083
+ e.preventDefault();
1084
+ break;
1085
+
1086
+ default:
1087
+ if (this.listKeyDown) this.listKeyDown(e);
1088
+ break;
1089
+ }
1090
+ }
1091
+
1092
+ onKeyDown(e: React.KeyboardEvent): void {
1093
+ switch (e.keyCode) {
1094
+ case KeyCode.pageDown:
1095
+ case KeyCode.pageUp:
1096
+ if (this.state.dropdownOpen) e.preventDefault();
1097
+ break;
1098
+ }
1099
+ }
1100
+
1101
+ onInputKeyDown(e: React.KeyboardEvent): void {
1102
+ let { instance } = this.props;
1103
+ if (instance.widget.handleKeyDown(e, instance) === false) return;
1104
+
1105
+ switch (e.keyCode) {
1106
+ case KeyCode.delete:
1107
+ this.onClearClick(e);
1108
+ return;
1109
+
1110
+ case KeyCode.shift:
1111
+ case KeyCode.ctrl:
1112
+ case KeyCode.tab:
1113
+ case KeyCode.left:
1114
+ case KeyCode.right:
1115
+ case KeyCode.pageUp:
1116
+ case KeyCode.pageDown:
1117
+ case KeyCode.insert:
1118
+ case KeyCode.esc:
1119
+ break;
1120
+
1121
+ case KeyCode.down:
1122
+ this.openDropdown(e);
1123
+ e.stopPropagation();
1124
+ break;
1125
+
1126
+ case KeyCode.enter:
1127
+ if (this.props.instance.widget.submitOnEnterKey) {
1128
+ this.submitOnEnter(e);
1129
+ } else {
1130
+ this.openDropdown(e);
1131
+ }
1132
+ break;
1133
+
1134
+ default:
1135
+ this.openDropdown(e);
1136
+ break;
1137
+ }
1138
+ }
1139
+
1140
+ onQueryBlur(e: React.FocusEvent): void {
1141
+ FocusManager.nudge();
1142
+ }
1143
+
1144
+ onFocus(e: React.FocusEvent): void {
1145
+ let { instance } = this.props;
1146
+ let { widget } = instance;
1147
+ if (widget.trackFocus) {
1148
+ this.setState({
1149
+ focus: true,
1150
+ });
1151
+ }
1152
+
1153
+ if (this.props.instance.data.autoOpen) this.openDropdown(null);
1154
+ }
1155
+
1156
+ onBlur(e: React.FocusEvent): void {
1157
+ if (!this.state.dropdownOpen) this.props.instance.setState({ visited: true });
1158
+
1159
+ if (this.state.focus)
1160
+ this.setState({
1161
+ focus: false,
1162
+ });
1163
+ }
1164
+
1165
+ toggleDropdown(e: React.KeyboardEvent | React.MouseEvent, keepFocus?: boolean): void {
1166
+ if (this.state.dropdownOpen) this.closeDropdown(e, keepFocus);
1167
+ else this.openDropdown(e);
1168
+ }
1169
+
1170
+ closeDropdown(e?: React.KeyboardEvent | React.MouseEvent | null, keepFocus?: boolean): void {
1171
+ if (this.state.dropdownOpen) {
1172
+ this.setState(
1173
+ {
1174
+ dropdownOpen: false,
1175
+ },
1176
+ () => keepFocus && this.dom.input?.focus(),
1177
+ );
1178
+
1179
+ this.props.instance.setState({
1180
+ visited: true,
1181
+ });
1182
+ }
1183
+
1184
+ //delete results valid only while the dropdown is open
1185
+ delete this.tmpCachedResult;
1186
+ }
1187
+
1188
+ openDropdown(e: React.KeyboardEvent | React.MouseEvent | null): void {
1189
+ let { instance } = this.props;
1190
+ let { data } = instance;
1191
+ if (!this.state.dropdownOpen && !data.disabled && !data.readOnly) {
1192
+ this.query("");
1193
+ this.setState(
1194
+ {
1195
+ dropdownOpen: true,
1196
+ },
1197
+ () => {
1198
+ if (this.dom.dropdown) this.dom.dropdown.focus();
1199
+ },
1200
+ );
1201
+ }
1202
+ }
1203
+
1204
+ query(q: string): void {
1205
+ /*
1206
+ In fetchAll mode onQuery should fetch all data and after
1207
+ that everything is done filtering is done client-side.
1208
+ If cacheAll is set results are cached for the lifetime of the
1209
+ widget, otherwise cache is invalidated when dropdown closes.
1210
+ */
1211
+
1212
+ let { instance } = this.props;
1213
+ let { widget, data } = instance;
1214
+
1215
+ this.lastQuery = q;
1216
+
1217
+ //do not make duplicate queries if fetchAll is enabled
1218
+ if (widget.fetchAll && this.state.status == "loading") return;
1219
+
1220
+ if (this.queryTimeoutId) clearTimeout(this.queryTimeoutId);
1221
+
1222
+ if (q.length < widget.minQueryLength) {
1223
+ this.setState({
1224
+ status: "info",
1225
+ message: StringTemplate.format(widget.minQueryLengthMessageText, widget.minQueryLength),
1226
+ });
1227
+ return;
1228
+ }
1229
+
1230
+ if (isArray(data.visibleOptions)) {
1231
+ let results = widget.filterOptions(this.props.instance, data.visibleOptions as DataRecord[], q);
1232
+ this.setState({
1233
+ options: results,
1234
+ status: "loaded",
1235
+ });
1236
+ }
1237
+
1238
+ if (widget.onQuery) {
1239
+ let { queryDelay, fetchAll, cacheAll, pageSize } = widget;
1240
+
1241
+ if (fetchAll) queryDelay = 0;
1242
+
1243
+ if (!this.cachedResult) {
1244
+ this.setState({
1245
+ status: "loading",
1246
+ });
1247
+ }
1248
+
1249
+ this.queryTimeoutId = setTimeout(() => {
1250
+ delete this.queryTimeoutId;
1251
+
1252
+ let result = this.tmpCachedResult || this.cachedResult;
1253
+ let query = fetchAll ? "" : q;
1254
+ let params = !widget.infinite
1255
+ ? query
1256
+ : {
1257
+ query,
1258
+ page: 1,
1259
+ pageSize,
1260
+ };
1261
+
1262
+ if (!result) result = instance.invoke("onQuery", params, instance);
1263
+
1264
+ let queryId = (this.lastQueryId = Date.now());
1265
+
1266
+ Promise.resolve(result)
1267
+ .then((results) => {
1268
+ //discard results which do not belong to the last query
1269
+ if (queryId !== this.lastQueryId) return;
1270
+
1271
+ if (!isArray(results)) results = [];
1272
+
1273
+ if (fetchAll) {
1274
+ if (cacheAll) this.cachedResult = results;
1275
+ else this.tmpCachedResult = results;
1276
+
1277
+ results = widget.filterOptions(this.props.instance, results, this.lastQuery);
1278
+ }
1279
+
1280
+ this.setState(
1281
+ {
1282
+ page: 1,
1283
+ query,
1284
+ options: results,
1285
+ status: "loaded",
1286
+ },
1287
+ () => {
1288
+ if (widget.infinite) this.onListScroll();
1289
+ },
1290
+ );
1291
+ })
1292
+ .catch((err) => {
1293
+ this.setState({ status: "error" });
1294
+ debug("Lookup query error:", err);
1295
+ });
1296
+ }, queryDelay);
1297
+ }
1298
+ }
1299
+
1300
+ loadAdditionalOptionPages(): void {
1301
+ let { instance } = this.props;
1302
+ let { widget } = instance;
1303
+ if (!widget.infinite) return;
1304
+
1305
+ let { query, page, status, options } = this.state;
1306
+ if (!page) page = 1;
1307
+
1308
+ let blockerKey = query;
1309
+
1310
+ if (status != "loaded") return;
1311
+
1312
+ if (options.length < page * widget.pageSize) return; //some pages were not full which means we reached the end
1313
+
1314
+ if (this.extraPageLoadingBlocker === blockerKey) return;
1315
+
1316
+ this.extraPageLoadingBlocker = blockerKey;
1317
+
1318
+ let params = {
1319
+ page: page + 1,
1320
+ query,
1321
+ pageSize: widget.pageSize,
1322
+ };
1323
+
1324
+ var result = instance.invoke("onQuery", params, instance);
1325
+
1326
+ Promise.resolve(result)
1327
+ .then((results) => {
1328
+ //discard results which do not belong to the last query
1329
+ if (this.extraPageLoadingBlocker !== blockerKey) return;
1330
+
1331
+ this.extraPageLoadingBlocker = false;
1332
+
1333
+ if (!isArray(results)) return;
1334
+
1335
+ this.setState(
1336
+ {
1337
+ page: params.page,
1338
+ query,
1339
+ options: [...options, ...results],
1340
+ },
1341
+ () => {
1342
+ this.onListScroll();
1343
+ },
1344
+ );
1345
+ })
1346
+ .catch((err) => {
1347
+ if (this.extraPageLoadingBlocker !== blockerKey) return;
1348
+ this.extraPageLoadingBlocker = false;
1349
+ this.setState({ status: "error" });
1350
+ debug("Lookup query error:", err);
1351
+ console.error(err);
1352
+ });
1353
+ }
1354
+
1355
+ UNSAFE_componentWillReceiveProps(props: LookupComponentProps): void {
1356
+ if (this.dom.input) {
1357
+ tooltipParentWillReceiveProps(this.dom.input, ...getFieldTooltip(props.instance));
1358
+ }
1359
+ }
1360
+
1361
+ componentDidMount(): void {
1362
+ if (this.dom.input) {
1363
+ tooltipParentDidMount(this.dom.input, ...getFieldTooltip(this.props.instance));
1364
+ autoFocus(this.dom.input, this);
1365
+ }
1366
+ }
1367
+
1368
+ componentDidUpdate(): void {
1369
+ if (this.dom.input) {
1370
+ autoFocus(this.dom.input, this);
1371
+ }
1372
+ }
1373
+
1374
+ componentWillUnmount(): void {
1375
+ if (this.queryTimeoutId) clearTimeout(this.queryTimeoutId);
1376
+ tooltipParentWillUnmount(this.props.instance);
1377
+ this.subscribeListOnWheel(null);
1378
+ }
1379
+
1380
+ subscribeListOnWheel(list: HTMLDivElement | null): void {
1381
+ if (this.unsubscribeListOnWheel) {
1382
+ this.unsubscribeListOnWheel();
1383
+ this.unsubscribeListOnWheel = null;
1384
+ }
1385
+ if (list) {
1386
+ this.unsubscribeListOnWheel = addEventListenerWithOptions(
1387
+ list,
1388
+ "wheel",
1389
+ (e) => this.onListWheel(e as WheelEvent),
1390
+ {
1391
+ passive: false,
1392
+ },
1393
+ );
1394
+ }
1395
+ }
1396
+
1397
+ subscribeListOnScroll(list: HTMLDivElement | null): void {
1398
+ if (this.unsubscribeListOnScroll) {
1399
+ this.unsubscribeListOnScroll();
1400
+ this.unsubscribeListOnScroll = null;
1401
+ }
1402
+ if (list) {
1403
+ this.unsubscribeListOnScroll = addEventListenerWithOptions(list, "scroll", () => this.onListScroll(), {
1404
+ passive: false,
1405
+ });
1406
+ }
1407
+ }
1408
+
1409
+ submitOnEnter(e: React.KeyboardEvent): void {
1410
+ let instance = this.props.instance.parent;
1411
+ while (instance) {
1412
+ let htmlInstance = instance as HtmlElementInstance;
1413
+ if (htmlInstance.events && htmlInstance.events.onSubmit) {
1414
+ htmlInstance.events.onSubmit(e, instance);
1415
+ break;
1416
+ } else {
1417
+ instance = instance.parent;
1418
+ }
1419
+ }
1420
+ }
1421
+ }