@talxis/base-controls 1.2406.13 → 1.2406.15

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.
@@ -1,63 +1 @@
1
- import numeral from 'numeral';
2
-
3
- class Numeral {
4
- static decimal(formatting) {
5
- const locale = {
6
- ordinal: (num) => {
7
- return '.';
8
- },
9
- currency: {
10
- symbol: formatting.currencySymbol
11
- },
12
- abbreviations: {
13
- thousand: 'k',
14
- million: 'm',
15
- billion: 'b',
16
- trillion: 't'
17
- },
18
- delimiters: {
19
- decimal: formatting.numberDecimalSeparator,
20
- thousands: formatting.numberGroupSeparator,
21
- }
22
- };
23
- if (!this._locales.includes('__pcfcustomdecimal')) {
24
- numeral.register('locale', '__pcfcustomdecimal', locale);
25
- }
26
- else {
27
- numeral.locales['__pcfcustomdecimal'] = locale;
28
- }
29
- numeral.locale('__pcfcustomdecimal');
30
- }
31
- static currency(formatting) {
32
- const locale = {
33
- ordinal: (num) => {
34
- return '.';
35
- },
36
- currency: {
37
- symbol: formatting.currencySymbol
38
- },
39
- abbreviations: {
40
- thousand: 'k',
41
- million: 'm',
42
- billion: 'b',
43
- trillion: 't'
44
- },
45
- delimiters: {
46
- decimal: formatting.currencyDecimalSeparator,
47
- thousands: formatting.currencyGroupSeparator,
48
- }
49
- };
50
- if (!this._locales.includes('__pcfcustomcurrency')) {
51
- numeral.register('locale', '__pcfcustomcurrency', locale);
52
- }
53
- else {
54
- numeral.locales['__pcfcustomcurrency'] = locale;
55
- }
56
- numeral.locale('__pcfcustomcurrency');
57
- }
58
- static get _locales() {
59
- return Object.keys(numeral.locales);
60
- }
61
- }
62
-
63
- export { Numeral as N };
1
+ import c from"numeral";class Numeral{static decimal(e){const l={ordinal:c=>".",currency:{symbol:e.currencySymbol},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},delimiters:{decimal:e.numberDecimalSeparator,thousands:e.numberGroupSeparator}};this._locales.includes("__pcfcustomdecimal")?c.locales.__pcfcustomdecimal=l:c.register("locale","__pcfcustomdecimal",l),c.locale("__pcfcustomdecimal")}static currency(e){const l={ordinal:c=>".",currency:{symbol:e.currencySymbol},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},delimiters:{decimal:e.currencyDecimalSeparator,thousands:e.currencyGroupSeparator}};this._locales.includes("__pcfcustomcurrency")?c.locales.__pcfcustomcurrency=l:c.register("locale","__pcfcustomcurrency",l),c.locale("__pcfcustomcurrency")}static get _locales(){return Object.keys(c.locales)}}export{Numeral as N};
@@ -1,302 +1 @@
1
- import { jsxs, jsx } from 'react/jsx-runtime';
2
- import { mergeStyleSets, useTheme as useTheme$1 } from '@fluentui/react';
3
- import { useEffect, useRef, useState } from 'react';
4
- import { useInputBasedComponent } from '../../hooks/useInputBasedComponent.js';
5
- import dayjs from 'dayjs';
6
- import utc from 'dayjs/plugin/utc';
7
- import customParseFormat from 'dayjs/plugin/customParseFormat';
8
- import { useTheme } from '@fluentui/react/lib/utilities/ThemeProvider/useTheme';
9
- import { Calendar as Calendar$1 } from '@fluentui/react/lib/Calendar';
10
- import { TimePicker } from '@talxis/react-components/dist/components/TimePicker';
11
- import { Text } from '@fluentui/react/lib/Text';
12
- import { DatePicker } from '@talxis/react-components/dist/components/DatePicker';
13
- import { useComponentSizing } from '../../hooks/useComponentSizing.js';
14
- import '../../hooks/useComponent.js';
15
- import 'fast-deep-equal/es6';
16
- import 'merge-anything';
17
- import 'liquidjs';
18
-
19
- const getDateTimeStyles = (theme) => {
20
- return mergeStyleSets({
21
- datePicker: {
22
- '[class^="statusMessage"]': {
23
- display: 'none'
24
- }
25
- },
26
- calendarCallout: {
27
- '.TALXIS__timepicker__root': {
28
- padding: 12,
29
- 'label': {
30
- paddingTop: 0
31
- },
32
- 'i': {
33
- fontSize: 16
34
- }
35
- },
36
- 'hr': {
37
- margin: 0,
38
- border: 'none',
39
- height: 1,
40
- backgroundColor: theme.semanticColors.bodyDivider
41
- },
42
- '[class^="monthAndYear"], [class*="weekDayLabelCell"]': {
43
- animationDuration: '0s'
44
- },
45
- '[class^="dayCell"]:focus': {
46
- outline: `solid 1px !important`
47
- },
48
- '.ms-DatePicker': {
49
- animationDuration: '0s'
50
- }
51
- }
52
- });
53
- };
54
-
55
- const getDefaultDateTimeTranslations = (dateFormattingInfo) => {
56
- return {
57
- time: {
58
- 1029: 'Čas',
59
- 1033: 'Time'
60
- },
61
- goToToday: {
62
- 1029: 'Přejít na dnešek',
63
- 1033: 'Go to today'
64
- },
65
- invalidTimeInput: {
66
- 1029: 'Neplatný časový formát.',
67
- 1033: 'Invalid time format.'
68
- },
69
- days: dateFormattingInfo.dayNames,
70
- months: dateFormattingInfo.monthNames,
71
- shortDays: dateFormattingInfo.shortestDayNames,
72
- shortMonths: dateFormattingInfo.abbreviatedMonthNames,
73
- };
74
- };
75
-
76
- dayjs.extend(customParseFormat);
77
- dayjs.extend(utc);
78
- const useDateTime = (props, ref) => {
79
- const boundValue = props.parameters.value;
80
- const context = props.context;
81
- const behavior = boundValue.attributes.Behavior;
82
- const format = boundValue.attributes.Format;
83
- const dateFormattingInfo = context.userSettings.dateFormattingInfo;
84
- const isDateTime = (() => {
85
- switch (format) {
86
- case 'DateAndTime':
87
- case 'Date and Time':
88
- case 'DateAndTime.DateAndTime':
89
- case 'datetime': {
90
- return true;
91
- }
92
- default: {
93
- return false;
94
- }
95
- }
96
- })();
97
- //MS returns the pattern without correct separator and they do this during formatting
98
- const shortDatePattern = dateFormattingInfo.shortDatePattern.replace(/\//g, dateFormattingInfo.dateSeparator).toUpperCase();
99
- const shortTimePattern = dateFormattingInfo.shortTimePattern.replace(/:/g, dateFormattingInfo.timeSeparator).replace('tt', 'A');
100
- const formatting = (() => {
101
- if (isDateTime) {
102
- return `${shortDatePattern} ${shortTimePattern}`;
103
- }
104
- return shortDatePattern;
105
- })();
106
- const formatDate = (date) => {
107
- if (date == undefined) {
108
- return undefined;
109
- }
110
- if (typeof date === 'string') {
111
- const dayjsDate = dayjs(date, formatting);
112
- //error situation
113
- if (!dayjsDate.isValid()) {
114
- return date;
115
- }
116
- date = dayjsDate.toDate();
117
- }
118
- if (isDateTime) {
119
- //should handle the time zone conversion
120
- return context.formatting.formatTime(date, behavior);
121
- }
122
- return context.formatting.formatDateShort(date);
123
- };
124
- const { value, labels, setValue, onNotifyOutputChanged } = useInputBasedComponent('DateTime', props, {
125
- formatter: formatDate,
126
- defaultTranslations: getDefaultDateTimeTranslations(props.context.userSettings.dateFormattingInfo)
127
- });
128
- useEffect(() => {
129
- var _a;
130
- const onBlur = () => {
131
- if (formatDate(boundValue.raw) === value) {
132
- return;
133
- }
134
- onNotifyOutputChanged({
135
- value: dateExtractor(value)
136
- });
137
- };
138
- const input = (_a = ref.current) === null || _a === void 0 ? void 0 : _a.querySelector('input');
139
- input === null || input === void 0 ? void 0 : input.addEventListener('blur', onBlur);
140
- return () => {
141
- input === null || input === void 0 ? void 0 : input.removeEventListener('blur', onBlur);
142
- };
143
- }, [value]);
144
- const getDate = () => {
145
- if (boundValue.raw instanceof Date) {
146
- if (behavior === 3) {
147
- //the date in javascript gets automatically adjusted to local time zone
148
- //this will make it think that the date already came in local time, thus not adjusting the time
149
- const date = new Date(boundValue.raw.toISOString().replace('Z', ''));
150
- return date;
151
- }
152
- return boundValue.raw;
153
- }
154
- //this scenario should only happen in cases of error or null value
155
- return undefined;
156
- };
157
- const dateExtractor = (value) => {
158
- if (value instanceof Date) {
159
- return value;
160
- }
161
- const dayjsDate = dayjs(value, formatting);
162
- if (!dayjsDate.isValid()) {
163
- return value;
164
- }
165
- return dayjsDate.toDate();
166
- };
167
- const clearDate = () => {
168
- onNotifyOutputChanged({
169
- value: undefined
170
- });
171
- };
172
- const selectDate = (date, time) => {
173
- let dayjsDate = dayjs(date !== null && date !== void 0 ? date : getDate());
174
- let _time = time;
175
- //date selected from calendar, keep the original time
176
- if (!_time) {
177
- _time = dayjs(getDate()).format('HH:mm');
178
- }
179
- const [hours, minutes] = _time.split(':');
180
- dayjsDate = dayjsDate.hour(parseInt(hours));
181
- dayjsDate = dayjsDate.minute(parseInt(minutes));
182
- onNotifyOutputChanged({
183
- value: dayjsDate.toDate()
184
- });
185
- };
186
- return [getDate(), value, isDateTime, { shortDatePattern, shortTimePattern }, labels, setValue, selectDate, clearDate];
187
- };
188
-
189
- const Calendar = (props) => {
190
- const theme = useTheme();
191
- const styles = getDateTimeStyles(theme);
192
- const timePickerRef = useRef(null);
193
- const [isTimePickerControlled, setIsTimePickerControlled] = useState(true);
194
- useEffect(() => {
195
- var _a;
196
- //@ts-ignore - we need to use the internal method to display exact time, otherwise the shown value would always get rounded to the next 15 min
197
- (_a = timePickerRef.current) === null || _a === void 0 ? void 0 : _a._updateValue(getFormattedTime());
198
- setIsTimePickerControlled(false);
199
- }, [props.timePickerProps.defaultValue]);
200
- const getFormattedTime = () => {
201
- return dayjs(props.timePickerProps.defaultValue).format(props.timePickerProps.timeFormat);
202
- };
203
- useEffect(() => {
204
- //hack to focus the selected date for keyboard support
205
- const day = document.querySelector('.ms-CalendarDay-daySelected');
206
- day === null || day === void 0 ? void 0 : day.focus();
207
- }, [props]);
208
- return (jsxs("div", Object.assign({ className: styles.calendarCallout }, { children: [jsx(Calendar$1, Object.assign({}, props)), jsx("hr", {}), props.timePickerProps.visible &&
209
- jsx(TimePicker, Object.assign({}, props.timePickerProps, { onChange: (e, time) => {
210
- setIsTimePickerControlled(true);
211
- props.timePickerProps.onChange(e, time);
212
- }, defaultValue: dayjs(new Date()).startOf('day').toDate(), useComboBoxAsMenuWidth: true, styles: {
213
- callout: {
214
- maxHeight: '300px !important'
215
- }
216
- }, autofill: {
217
- componentRef: timePickerRef,
218
- //hack to prevent blinking on prop updates
219
- value: isTimePickerControlled ? getFormattedTime() : undefined
220
- }, buttonIconProps: {
221
- iconName: 'Clock'
222
- }, onRenderOption: (option) => {
223
- //the timepicker displays 24 instead of 00 during the option displaying for some reason
224
- return jsx(Text, { children: option === null || option === void 0 ? void 0 : option.text.replace('24', '00') });
225
- }, increments: 15, allowFreeform: true }))] })));
226
- };
227
-
228
- const DateTime = (componentProps) => {
229
- var _a, _b, _c;
230
- const ref = useRef(null);
231
- const datePickerRef = useRef(null);
232
- const theme = useTheme$1();
233
- const styles = getDateTimeStyles(theme);
234
- componentProps.context;
235
- const parameters = componentProps.parameters;
236
- const [date, stringDate, isDateTime, patterns, labels, setStringDate, selectDate, clearDate] = useDateTime(componentProps, ref);
237
- const { height, width } = useComponentSizing(componentProps.context.mode);
238
- useEffect(() => {
239
- var _a, _b;
240
- if (((_a = componentProps.parameters.AutoFocus) === null || _a === void 0 ? void 0 : _a.raw) === true) {
241
- (_b = datePickerRef.current) === null || _b === void 0 ? void 0 : _b.showDatePickerPopup();
242
- }
243
- }, []);
244
- return (jsx("div", Object.assign({ ref: ref }, { children: jsx(DatePicker, { className: styles.datePicker, componentRef: datePickerRef, keepCalendarOpenAfterDaySelect: isDateTime, allowTextInput: true, calendarProps: {
245
- //needs to be here as the internal picker does not call the function passed in calendarAs
246
- onSelectDate: (date) => selectDate(date),
247
- },
248
- // Lowest date supported by CDS: https://learn.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/dn996866(v=crm.8)?redirectedfrom=MSDN
249
- minDate: new Date('1753-01-01T00:00:00.000Z'), firstDayOfWeek: componentProps.context.userSettings.dateFormattingInfo.firstDayOfWeek, calendarAs: (props) => jsx(Calendar, Object.assign({}, props, { strings: {
250
- goToToday: labels.goToToday(),
251
- days: JSON.parse(labels.days()),
252
- months: JSON.parse(labels.months()),
253
- shortDays: JSON.parse(labels.shortDays()),
254
- shortMonths: JSON.parse(labels.shortMonths())
255
- }, timePickerProps: {
256
- autoComplete: "off",
257
- autoCapitalize: "off",
258
- timeFormat: patterns.shortTimePattern,
259
- label: labels.time(),
260
- visible: isDateTime && !parameters.value.errorMessage,
261
- useHour12: patterns.shortTimePattern.endsWith('A'),
262
- onChange: (e, date) => selectDate(undefined, dayjs(date).format('HH:mm')),
263
- defaultValue: date,
264
- strings: {
265
- invalidInputErrorMessage: labels.invalidTimeInput()
266
- }
267
- } })), textField: {
268
- value: stringDate !== null && stringDate !== void 0 ? stringDate : "",
269
- onChange: (e, value) => setStringDate(value),
270
- placeholder: '---',
271
- onNotifyValidationResult: () => null,
272
- noValidate: true,
273
- borderless: ((_a = parameters.EnableBorder) === null || _a === void 0 ? void 0 : _a.raw) === false,
274
- errorMessage: parameters.value.errorMessage,
275
- styles: {
276
- fieldGroup: {
277
- height: height,
278
- width: width
279
- }
280
- },
281
- //@ts-ignore - TODO: fix types in shared components
282
- deleteButtonProps: ((_b = parameters.EnableDeleteButton) === null || _b === void 0 ? void 0 : _b.raw) === true ? {
283
- key: 'Delete',
284
- onClick: clearDate,
285
- showOnlyOnHover: true,
286
- iconProps: {
287
- iconName: 'Cancel'
288
- }
289
- } : undefined,
290
- clickToCopyProps: ((_c = parameters.EnableCopyButton) === null || _c === void 0 ? void 0 : _c.raw) === true ? {
291
- key: 'copy',
292
- showOnlyOnHover: true,
293
- iconProps: {
294
- iconName: 'Copy'
295
- }
296
- } : undefined
297
- },
298
- //undefined will break the calendar => it wont reflect date change in it's UI
299
- value: date !== null && date !== void 0 ? date : new Date() }) })));
300
- };
301
-
302
- export { DateTime };
1
+ import{jsxs as e,jsx as t}from"react/jsx-runtime";import{mergeStyleSets as o,useTheme as a}from"@fluentui/react";import{useEffect as r,useRef as n,useState as i}from"react";import{useInputBasedComponent as s}from"../../hooks/useInputBasedComponent.js";import l from"dayjs";import m from"dayjs/plugin/utc";import u from"dayjs/plugin/customParseFormat";import{useTheme as d}from"@fluentui/react/lib/utilities/ThemeProvider/useTheme";import{Calendar as c}from"@fluentui/react/lib/Calendar";import{TimePicker as p}from"@talxis/react-components/dist/components/TimePicker";import{Text as f}from"@fluentui/react/lib/Text";import{DatePicker as h}from"@talxis/react-components/dist/components/DatePicker";import{useComponentSizing as v}from"../../hooks/useComponentSizing.js";import"../../hooks/useComponent.js";import"fast-deep-equal/es6";import"merge-anything";import"liquidjs";const g=e=>o({datePicker:{'[class^="statusMessage"]':{display:"none"}},calendarCallout:{".TALXIS__timepicker__root":{padding:12,label:{paddingTop:0},i:{fontSize:16}},hr:{margin:0,border:"none",height:1,backgroundColor:e.semanticColors.bodyDivider},'[class^="monthAndYear"], [class*="weekDayLabelCell"]':{animationDuration:"0s"},'[class^="dayCell"]:focus':{outline:"solid 1px !important"},".ms-DatePicker":{animationDuration:"0s"}}}),y=e=>({time:{1029:"Čas",1033:"Time"},goToToday:{1029:"Přejít na dnešek",1033:"Go to today"},invalidTimeInput:{1029:"Neplatný časový formát.",1033:"Invalid time format."},days:e.dayNames,months:e.monthNames,shortDays:e.shortestDayNames,shortMonths:e.abbreviatedMonthNames});l.extend(u),l.extend(m);const D=o=>{const a=d(),s=g(a),m=n(null),[u,h]=i(!0);r((()=>{var e;null===(e=m.current)||void 0===e||e._updateValue(v()),h(!1)}),[o.timePickerProps.defaultValue]);const v=()=>l(o.timePickerProps.defaultValue).format(o.timePickerProps.timeFormat);return r((()=>{const e=document.querySelector(".ms-CalendarDay-daySelected");null==e||e.focus()}),[o]),e("div",Object.assign({className:s.calendarCallout},{children:[t(c,Object.assign({},o)),t("hr",{}),o.timePickerProps.visible&&t(p,Object.assign({},o.timePickerProps,{onChange:(e,t)=>{h(!0),o.timePickerProps.onChange(e,t)},defaultValue:l(new Date).startOf("day").toDate(),useComboBoxAsMenuWidth:!0,styles:{callout:{maxHeight:"300px !important"}},autofill:{componentRef:m,value:u?v():void 0},buttonIconProps:{iconName:"Clock"},onRenderOption:e=>t(f,{children:null==e?void 0:e.text.replace("24","00")}),increments:15,allowFreeform:!0}))]}))},P=e=>{var o,i,m;const u=n(null),d=n(null),c=a(),p=g(c);e.context;const f=e.parameters,[P,T,b,k,C,w,O,S]=((e,t)=>{const o=e.parameters.value,a=e.context,n=o.attributes.Behavior,i=o.attributes.Format,m=a.userSettings.dateFormattingInfo,u=(()=>{switch(i){case"DateAndTime":case"Date and Time":case"DateAndTime.DateAndTime":case"datetime":return!0;default:return!1}})(),d=m.shortDatePattern.replace(/\//g,m.dateSeparator).toUpperCase(),c=m.shortTimePattern.replace(/:/g,m.timeSeparator).replace("tt","A"),p=u?`${d} ${c}`:d,f=e=>{if(null!=e){if("string"==typeof e){const t=l(e,p);if(!t.isValid())return e;e=t.toDate()}return u?a.formatting.formatTime(e,n):a.formatting.formatDateShort(e)}},{value:h,labels:v,setValue:g,onNotifyOutputChanged:D}=s("DateTime",e,{formatter:f,defaultTranslations:y(e.context.userSettings.dateFormattingInfo)});r((()=>{var e;const a=()=>{f(o.raw)!==h&&D({value:T(h)})},r=null===(e=t.current)||void 0===e?void 0:e.querySelector("input");return null==r||r.addEventListener("blur",a),()=>{null==r||r.removeEventListener("blur",a)}}),[h]);const P=()=>{if(o.raw instanceof Date)return 3===n?new Date(o.raw.toISOString().replace("Z","")):o.raw},T=e=>{if(e instanceof Date)return e;const t=l(e,p);return t.isValid()?t.toDate():e};return[P(),h,u,{shortDatePattern:d,shortTimePattern:c},v,g,(e,t)=>{let o=l(null!=e?e:P()),a=t;a||(a=l(P()).format("HH:mm"));const[r,n]=a.split(":");o=o.hour(parseInt(r)),o=o.minute(parseInt(n)),D({value:o.toDate()})},()=>{D({value:void 0})}]})(e,u),{height:x,width:N}=v(e.context.mode);return r((()=>{var t,o;!0===(null===(t=e.parameters.AutoFocus)||void 0===t?void 0:t.raw)&&(null===(o=d.current)||void 0===o||o.showDatePickerPopup())}),[]),t("div",Object.assign({ref:u},{children:t(h,{className:p.datePicker,componentRef:d,keepCalendarOpenAfterDaySelect:b,allowTextInput:!0,calendarProps:{onSelectDate:e=>O(e)},minDate:new Date("1753-01-01T00:00:00.000Z"),firstDayOfWeek:e.context.userSettings.dateFormattingInfo.firstDayOfWeek,calendarAs:e=>t(D,Object.assign({},e,{strings:{goToToday:C.goToToday(),days:JSON.parse(C.days()),months:JSON.parse(C.months()),shortDays:JSON.parse(C.shortDays()),shortMonths:JSON.parse(C.shortMonths())},timePickerProps:{autoComplete:"off",autoCapitalize:"off",timeFormat:k.shortTimePattern,label:C.time(),visible:b&&!f.value.errorMessage,useHour12:k.shortTimePattern.endsWith("A"),onChange:(e,t)=>O(void 0,l(t).format("HH:mm")),defaultValue:P,strings:{invalidInputErrorMessage:C.invalidTimeInput()}}})),textField:{value:null!=T?T:"",onChange:(e,t)=>w(t),placeholder:"---",onNotifyValidationResult:()=>null,noValidate:!0,borderless:!1===(null===(o=f.EnableBorder)||void 0===o?void 0:o.raw),errorMessage:f.value.errorMessage,styles:{fieldGroup:{height:x,width:N}},deleteButtonProps:!0===(null===(i=f.EnableDeleteButton)||void 0===i?void 0:i.raw)?{key:"Delete",onClick:S,showOnlyOnHover:!0,iconProps:{iconName:"Cancel"}}:void 0,clickToCopyProps:!0===(null===(m=f.EnableCopyButton)||void 0===m?void 0:m.raw)?{key:"copy",showOnlyOnHover:!0,iconProps:{iconName:"Copy"}}:void 0},value:null!=P?P:new Date})}))};export{P as DateTime};
@@ -1,167 +1 @@
1
- import { jsx } from 'react/jsx-runtime';
2
- import { TextField } from '@talxis/react-components/dist/components/TextField';
3
- import { useInputBasedComponent } from '../../hooks/useInputBasedComponent.js';
4
- import numeral from 'numeral';
5
- import { N as Numeral } from '../../Numeral-a0284afb.js';
6
- import 'react';
7
- import '../../hooks/useComponent.js';
8
- import 'fast-deep-equal/es6';
9
- import 'merge-anything';
10
- import 'liquidjs';
11
- import '../../hooks/useComponentSizing.js';
12
-
13
- const CURRENCY_POSITIVE_PATTERN = {
14
- 0: '$n',
15
- 1: 'n$',
16
- 2: '$ n',
17
- 3: 'n $',
18
- };
19
- const CURRENCY_NEGATIVE_PATTERN = {
20
- 0: '($n)',
21
- 1: '-$n',
22
- 2: '$-n',
23
- 3: '$n-',
24
- 4: '(n$)',
25
- 5: '-n$',
26
- 6: 'n-$',
27
- 7: 'n$-',
28
- 8: '-n $',
29
- 9: '-$ n',
30
- 10: 'n $-',
31
- 11: '$ n-',
32
- 12: '$ -n',
33
- 13: 'n- $',
34
- 14: '($ n)',
35
- 15: '(n $)',
36
- 16: '$- n'
37
- };
38
- const NUMBER_NEGATIVE_PATTERN = {
39
- 0: '(n)',
40
- 1: '-n',
41
- 2: '- n',
42
- 3: 'n-',
43
- 4: 'n -'
44
- };
45
-
46
- const Decimal = (props) => {
47
- var _a, _b, _c, _d;
48
- const context = props.context;
49
- const parameters = props.parameters;
50
- const boundValue = parameters.value;
51
- const numberFormatting = context.userSettings.numberFormattingInfo;
52
- const formatter = (value) => {
53
- var _a;
54
- if (value == null) {
55
- return undefined;
56
- }
57
- if (isNaN(value)) {
58
- return value;
59
- }
60
- if (props.parameters.value.type === 'Decimal') {
61
- return context.formatting.formatDecimal(parseFloat(value), (_a = boundValue.attributes) === null || _a === void 0 ? void 0 : _a.Precision);
62
- }
63
- if (props.parameters.value.type === 'Currency') {
64
- //the layer above has information about the symbol, so we can use the formatted string
65
- if (props.parameters.value.formatted) {
66
- return props.parameters.value.formatted;
67
- }
68
- if (typeof value === 'number') {
69
- return context.formatting.formatCurrency(value);
70
- }
71
- }
72
- return context.formatting.formatInteger(parseInt(value));
73
- };
74
- const createNumberPattern = (pattern, numberPattern) => {
75
- return new RegExp(`^${escapeRegExp(pattern).replace('n', numberPattern)}$`.replace(/\s/g, ''));
76
- };
77
- const createCurrencyPattern = (pattern, numberPattern) => {
78
- const escapedPattern = escapeRegExp(pattern);
79
- const escapedCurrencySymbolPattern = `(${escapeRegExp(numberFormatting.currencySymbol)})?`;
80
- const finalPattern = escapedPattern.replace('\\$', escapedCurrencySymbolPattern).replace('n', numberPattern);
81
- return new RegExp(`^${finalPattern.replace(/\s/g, '')}$`);
82
- };
83
- const escapeRegExp = (string) => {
84
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
85
- };
86
- const extractNumericPart = (str) => {
87
- var _a;
88
- // Currency control just sends the string up and lets the framework decide whether the value is correct
89
- // It only tries to parse the number based on the current user format
90
- // This means that the value will also pass if the user inputs his own currency even though
91
- // the currency is different on the field
92
- if (typeof str === 'number') {
93
- return str;
94
- }
95
- str = str === null || str === void 0 ? void 0 : str.replace(/\s/g, '');
96
- Numeral.decimal(numberFormatting);
97
- let positivePattern;
98
- let negativePattern;
99
- switch (props.parameters.value.type) {
100
- case 'Whole.None': {
101
- const numberPattern = `\\d{1,}(${numberFormatting.numberGroupSeparator}\\d{1,})*`;
102
- positivePattern = createNumberPattern('n', numberPattern);
103
- negativePattern = createNumberPattern(NUMBER_NEGATIVE_PATTERN[numberFormatting.numberNegativePattern], numberPattern);
104
- break;
105
- }
106
- case 'Decimal': {
107
- const numberPattern = `\\d{1,}(${numberFormatting.numberGroupSeparator}\\d{1,})*(\\${numberFormatting.numberDecimalSeparator}\\d+)?`;
108
- positivePattern = createNumberPattern('n', numberPattern);
109
- negativePattern = createNumberPattern(NUMBER_NEGATIVE_PATTERN[numberFormatting.numberNegativePattern], numberPattern);
110
- break;
111
- }
112
- case 'Currency': {
113
- Numeral.currency(numberFormatting);
114
- const numberPattern = `\\d{1,}(${numberFormatting.currencyGroupSeparator}\\d{1,})*(\\${numberFormatting.currencyDecimalSeparator}\\d+)?`;
115
- positivePattern = createCurrencyPattern(CURRENCY_POSITIVE_PATTERN[numberFormatting.currencyPositivePattern], numberPattern);
116
- negativePattern = createCurrencyPattern(CURRENCY_NEGATIVE_PATTERN[numberFormatting.currencyNegativePattern], numberPattern);
117
- break;
118
- }
119
- }
120
- if (positivePattern.test(str)) {
121
- return (_a = numeral(str).value()) !== null && _a !== void 0 ? _a : undefined;
122
- }
123
- if (negativePattern.test(str)) {
124
- const value = numeral(str).value();
125
- if (value > 0) {
126
- return value * -1;
127
- }
128
- return value;
129
- }
130
- return str; // Return undefined if no numeric part is extracted
131
- };
132
- const { value, sizing, setValue, onNotifyOutputChanged } = useInputBasedComponent('Decimal', props, {
133
- formatter: formatter,
134
- valueExtractor: extractNumericPart
135
- });
136
- return (jsx(TextField, { readOnly: context.mode.isControlDisabled, autoFocus: (_a = parameters.AutoFocus) === null || _a === void 0 ? void 0 : _a.raw, borderless: ((_b = parameters.EnableBorder) === null || _b === void 0 ? void 0 : _b.raw) === false, errorMessage: boundValue.errorMessage, styles: {
137
- fieldGroup: {
138
- height: sizing.height,
139
- width: sizing.width
140
- }
141
- }, deleteButtonProps: ((_c = parameters.EnableDeleteButton) === null || _c === void 0 ? void 0 : _c.raw) === true
142
- ? {
143
- key: "delete",
144
- showOnlyOnHover: true,
145
- iconProps: {
146
- iconName: "Delete",
147
- },
148
- onClick: () => setValue(undefined),
149
- }
150
- : undefined, clickToCopyProps: ((_d = parameters.EnableCopyButton) === null || _d === void 0 ? void 0 : _d.raw) === true
151
- ? {
152
- key: "copy",
153
- showOnlyOnHover: true,
154
- iconProps: {
155
- iconName: "Copy",
156
- },
157
- }
158
- : undefined, value: value !== null && value !== void 0 ? value : "", onBlur: (event) => {
159
- onNotifyOutputChanged({
160
- value: extractNumericPart(event.target.value)
161
- });
162
- }, onChange: (e, value) => {
163
- setValue(value);
164
- } }));
165
- };
166
-
167
- export { Decimal };
1
+ import{jsx as e}from"react/jsx-runtime";import{TextField as r}from"@talxis/react-components/dist/components/TextField";import{useInputBasedComponent as t}from"../../hooks/useInputBasedComponent.js";import n from"numeral";import{N as o}from"../../Numeral-a0284afb.js";import"react";import"../../hooks/useComponent.js";import"fast-deep-equal/es6";import"merge-anything";import"liquidjs";import"../../hooks/useComponentSizing.js";const a={0:"$n",1:"n$",2:"$ n",3:"n $"},i={0:"($n)",1:"-$n",2:"$-n",3:"$n-",4:"(n$)",5:"-n$",6:"n-$",7:"n$-",8:"-n $",9:"-$ n",10:"n $-",11:"$ n-",12:"$ -n",13:"n- $",14:"($ n)",15:"(n $)",16:"$- n"},l={0:"(n)",1:"-n",2:"- n",3:"n-",4:"n -"},u=u=>{var s,m,c,p;const d=u.context,v=u.parameters,$=v.value,f=d.userSettings.numberFormattingInfo,g=(e,r)=>new RegExp(`^${b(e).replace("n",r)}$`.replace(/\s/g,"")),y=(e,r)=>{const t=b(e),n=`(${b(f.currencySymbol)})?`,o=t.replace("\\$",n).replace("n",r);return new RegExp(`^${o.replace(/\s/g,"")}$`)},b=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=e=>{var r;if("number"==typeof e)return e;let t,s;switch(e=null==e?void 0:e.replace(/\s/g,""),o.decimal(f),u.parameters.value.type){case"Whole.None":{const e=`\\d{1,}(${f.numberGroupSeparator}\\d{1,})*`;t=g("n",e),s=g(l[f.numberNegativePattern],e);break}case"Decimal":{const e=`\\d{1,}(${f.numberGroupSeparator}\\d{1,})*(\\${f.numberDecimalSeparator}\\d+)?`;t=g("n",e),s=g(l[f.numberNegativePattern],e);break}case"Currency":{o.currency(f);const e=`\\d{1,}(${f.currencyGroupSeparator}\\d{1,})*(\\${f.currencyDecimalSeparator}\\d+)?`;t=y(a[f.currencyPositivePattern],e),s=y(i[f.currencyNegativePattern],e);break}}if(t.test(e))return null!==(r=n(e).value())&&void 0!==r?r:void 0;if(s.test(e)){const r=n(e).value();return r>0?-1*r:r}return e},{value:C,sizing:w,setValue:N,onNotifyOutputChanged:P}=t("Decimal",u,{formatter:e=>{var r,t;if(null!=e){if(isNaN(e))return e;if("Decimal"===u.parameters.value.type)return d.formatting.formatDecimal(parseFloat(e),null===(r=$.attributes)||void 0===r?void 0:r.Precision);if("Currency"===u.parameters.value.type){if(u.parameters.value.formatted)return u.parameters.value.formatted;if("number"==typeof e)return d.formatting.formatDecimal(e,null===(t=$.attributes)||void 0===t?void 0:t.Precision)}return d.formatting.formatInteger(parseInt(e))}},valueExtractor:h});return e(r,{readOnly:d.mode.isControlDisabled,autoFocus:null===(s=v.AutoFocus)||void 0===s?void 0:s.raw,borderless:!1===(null===(m=v.EnableBorder)||void 0===m?void 0:m.raw),errorMessage:$.errorMessage,styles:{fieldGroup:{height:w.height,width:w.width}},deleteButtonProps:!0===(null===(c=v.EnableDeleteButton)||void 0===c?void 0:c.raw)?{key:"delete",showOnlyOnHover:!0,iconProps:{iconName:"Delete"},onClick:()=>N(void 0)}:void 0,clickToCopyProps:!0===(null===(p=v.EnableCopyButton)||void 0===p?void 0:p.raw)?{key:"copy",showOnlyOnHover:!0,iconProps:{iconName:"Copy"}}:void 0,value:null!=C?C:"",onBlur:e=>{P({value:h(e.target.value)})},onChange:(e,r)=>{N(r)}})};export{u as Decimal};