@billdog.io/react-native 1.0.0-beta.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.
- package/BillDogReactNative.podspec +30 -0
- package/LICENSE +21 -0
- package/README.md +330 -0
- package/android/build.gradle +99 -0
- package/android/src/main/AndroidManifest.xml +1 -0
- package/android/src/main/kotlin/io/billdog/reactnative/BillDogABTestModule.kt +317 -0
- package/android/src/main/kotlin/io/billdog/reactnative/BillDogAnalyticsModule.kt +389 -0
- package/android/src/main/kotlin/io/billdog/reactnative/BillDogModule.kt +817 -0
- package/android/src/main/kotlin/io/billdog/reactnative/BillDogPaywallViewManager.kt +383 -0
- package/android/src/main/kotlin/io/billdog/reactnative/BillDogSurveyModule.kt +427 -0
- package/android/src/main/kotlin/io/billdog/reactnative/BillDogVirtualCurrencyModule.kt +407 -0
- package/android/src/main/kotlin/io/billdog/virtualcurrency/BillDogVirtualCurrencyPackage.kt +44 -0
- package/dist/AdvancedPaywallCache.d.ts +70 -0
- package/dist/AdvancedPaywallCache.js +344 -0
- package/dist/BillDog.d.ts +255 -0
- package/dist/BillDog.js +918 -0
- package/dist/BillDogConfiguration.d.ts +145 -0
- package/dist/BillDogConfiguration.js +229 -0
- package/dist/ComponentRenderer.d.ts +17 -0
- package/dist/ComponentRenderer.js +886 -0
- package/dist/LayoutEngine.d.ts +101 -0
- package/dist/LayoutEngine.js +394 -0
- package/dist/LocalizationResolver.d.ts +99 -0
- package/dist/LocalizationResolver.js +266 -0
- package/dist/NativePaywallView.d.ts +36 -0
- package/dist/NativePaywallView.js +59 -0
- package/dist/PaywallCache.d.ts +74 -0
- package/dist/PaywallCache.js +293 -0
- package/dist/PaywallStateManager.d.ts +62 -0
- package/dist/PaywallStateManager.js +147 -0
- package/dist/PaywallView.d.ts +42 -0
- package/dist/PaywallView.js +275 -0
- package/dist/ProductVariableProvider.d.ts +60 -0
- package/dist/ProductVariableProvider.js +239 -0
- package/dist/VariableResolver.d.ts +120 -0
- package/dist/VariableResolver.js +379 -0
- package/dist/WebViewPaywall.d.ts +75 -0
- package/dist/WebViewPaywall.js +360 -0
- package/dist/animations/presets.d.ts +49 -0
- package/dist/animations/presets.js +367 -0
- package/dist/components/AccoladeCpsComponent.d.ts +13 -0
- package/dist/components/AccoladeCpsComponent.js +248 -0
- package/dist/components/AccordionComponent.d.ts +10 -0
- package/dist/components/AccordionComponent.js +187 -0
- package/dist/components/AnimatedWrapper.d.ts +35 -0
- package/dist/components/AnimatedWrapper.js +277 -0
- package/dist/components/CarouselComponent.d.ts +23 -0
- package/dist/components/CarouselComponent.js +484 -0
- package/dist/components/ChartCurveComponent.d.ts +13 -0
- package/dist/components/ChartCurveComponent.js +333 -0
- package/dist/components/CheckboxComponent.d.ts +9 -0
- package/dist/components/CheckboxComponent.js +172 -0
- package/dist/components/ConfettiComponent.d.ts +9 -0
- package/dist/components/ConfettiComponent.js +172 -0
- package/dist/components/CountdownComponent.d.ts +16 -0
- package/dist/components/CountdownComponent.js +414 -0
- package/dist/components/DelayedXComponent.d.ts +12 -0
- package/dist/components/DelayedXComponent.js +240 -0
- package/dist/components/DrawerModalComponent.d.ts +20 -0
- package/dist/components/DrawerModalComponent.js +286 -0
- package/dist/components/GradientView.d.ts +38 -0
- package/dist/components/GradientView.js +126 -0
- package/dist/components/HapticFeedbackComponent.d.ts +16 -0
- package/dist/components/HapticFeedbackComponent.js +64 -0
- package/dist/components/HorizontalProductsComponent.d.ts +17 -0
- package/dist/components/HorizontalProductsComponent.js +284 -0
- package/dist/components/MultiChoiceGridComponent.d.ts +13 -0
- package/dist/components/MultiChoiceGridComponent.js +234 -0
- package/dist/components/NPSScaleComponent.d.ts +16 -0
- package/dist/components/NPSScaleComponent.js +260 -0
- package/dist/components/NavigationComponent.d.ts +26 -0
- package/dist/components/NavigationComponent.js +302 -0
- package/dist/components/OAuthButtonComponent.d.ts +20 -0
- package/dist/components/OAuthButtonComponent.js +237 -0
- package/dist/components/ProgressLoaderComponent.d.ts +13 -0
- package/dist/components/ProgressLoaderComponent.js +308 -0
- package/dist/components/ProgressStepperComponent.d.ts +18 -0
- package/dist/components/ProgressStepperComponent.js +228 -0
- package/dist/components/SegmentedPickerComponent.d.ts +10 -0
- package/dist/components/SegmentedPickerComponent.js +221 -0
- package/dist/components/ShareButtonsComponent.d.ts +21 -0
- package/dist/components/ShareButtonsComponent.js +265 -0
- package/dist/components/ShareCodeComponent.d.ts +16 -0
- package/dist/components/ShareCodeComponent.js +274 -0
- package/dist/components/SingleChoiceGridComponent.d.ts +13 -0
- package/dist/components/SingleChoiceGridComponent.js +210 -0
- package/dist/components/SliderComponent.d.ts +9 -0
- package/dist/components/SliderComponent.js +263 -0
- package/dist/components/StarRatingInputComponent.d.ts +20 -0
- package/dist/components/StarRatingInputComponent.js +198 -0
- package/dist/components/StickerCompositeComponent.d.ts +13 -0
- package/dist/components/StickerCompositeComponent.js +136 -0
- package/dist/components/TabsComponent.d.ts +19 -0
- package/dist/components/TabsComponent.js +431 -0
- package/dist/components/TextInputComponent.d.ts +18 -0
- package/dist/components/TextInputComponent.js +227 -0
- package/dist/components/TimelineComponent.d.ts +19 -0
- package/dist/components/TimelineComponent.js +104 -0
- package/dist/components/ToggleComponent.d.ts +14 -0
- package/dist/components/ToggleComponent.js +132 -0
- package/dist/components/VerticalProductsComponent.d.ts +17 -0
- package/dist/components/VerticalProductsComponent.js +311 -0
- package/dist/dynamicValues.d.ts +36 -0
- package/dist/dynamicValues.js +142 -0
- package/dist/filters/dateFilters.d.ts +50 -0
- package/dist/filters/dateFilters.js +390 -0
- package/dist/filters/index.d.ts +18 -0
- package/dist/filters/index.js +253 -0
- package/dist/hooks/useOfferings.d.ts +76 -0
- package/dist/hooks/useOfferings.js +99 -0
- package/dist/hooks/usePaywall.d.ts +27 -0
- package/dist/hooks/usePaywall.js +114 -0
- package/dist/hooks/usePlacement.d.ts +34 -0
- package/dist/hooks/usePlacement.js +89 -0
- package/dist/hooks/useSubscription.d.ts +40 -0
- package/dist/hooks/useSubscription.js +97 -0
- package/dist/index.d.ts +98 -0
- package/dist/index.js +198 -0
- package/dist/models/BillDogError.d.ts +40 -0
- package/dist/models/BillDogError.js +11 -0
- package/dist/models/CacheFetchPolicy.d.ts +8 -0
- package/dist/models/CacheFetchPolicy.js +4 -0
- package/dist/models/CustomProduct.d.ts +32 -0
- package/dist/models/CustomProduct.js +15 -0
- package/dist/models/CustomerInfo.d.ts +17 -0
- package/dist/models/CustomerInfo.js +11 -0
- package/dist/models/Delegate.d.ts +20 -0
- package/dist/models/Delegate.js +11 -0
- package/dist/models/EntitlementInfo.d.ts +19 -0
- package/dist/models/EntitlementInfo.js +2 -0
- package/dist/models/Placement.d.ts +54 -0
- package/dist/models/Placement.js +15 -0
- package/dist/models/PurchaseParams.d.ts +39 -0
- package/dist/models/PurchaseParams.js +60 -0
- package/dist/models/PurchaseResult.d.ts +30 -0
- package/dist/models/PurchaseResult.js +15 -0
- package/dist/models/RestoreResult.d.ts +30 -0
- package/dist/models/RestoreResult.js +22 -0
- package/dist/models/RestoredItem.d.ts +26 -0
- package/dist/models/RestoredItem.js +13 -0
- package/dist/modules/ABTest.d.ts +65 -0
- package/dist/modules/ABTest.js +113 -0
- package/dist/modules/Analytics.d.ts +91 -0
- package/dist/modules/Analytics.js +182 -0
- package/dist/modules/Survey.d.ts +65 -0
- package/dist/modules/Survey.js +82 -0
- package/dist/modules/VirtualCurrency.d.ts +63 -0
- package/dist/modules/VirtualCurrency.js +147 -0
- package/dist/murmur.d.ts +23 -0
- package/dist/murmur.js +104 -0
- package/dist/notifications/LiveActivitiesManager.d.ts +47 -0
- package/dist/notifications/LiveActivitiesManager.js +106 -0
- package/dist/notifications/NotificationScheduler.d.ts +55 -0
- package/dist/notifications/NotificationScheduler.js +199 -0
- package/dist/notifications/PurchaseNotificationHandler.d.ts +24 -0
- package/dist/notifications/PurchaseNotificationHandler.js +55 -0
- package/dist/notifications/useDeviceToken.d.ts +36 -0
- package/dist/notifications/useDeviceToken.js +97 -0
- package/dist/notifications/useLiveActivity.d.ts +39 -0
- package/dist/notifications/useLiveActivity.js +104 -0
- package/dist/review/ReviewAnalytics.d.ts +34 -0
- package/dist/review/ReviewAnalytics.js +73 -0
- package/dist/review/ReviewManager.d.ts +83 -0
- package/dist/review/ReviewManager.js +339 -0
- package/dist/review/ReviewTimingManager.d.ts +82 -0
- package/dist/review/ReviewTimingManager.js +224 -0
- package/dist/survey-core/types.d.ts +215 -0
- package/dist/survey-core/types.js +8 -0
- package/dist/types.d.ts +438 -0
- package/dist/types.js +158 -0
- package/dist/utils/ApiClient.d.ts +65 -0
- package/dist/utils/ApiClient.js +132 -0
- package/dist/utils/CSSConverter.d.ts +49 -0
- package/dist/utils/CSSConverter.js +470 -0
- package/dist/utils/animations.d.ts +41 -0
- package/dist/utils/animations.js +194 -0
- package/dist/utils/calendarIntegration.d.ts +36 -0
- package/dist/utils/calendarIntegration.js +89 -0
- package/dist/utils/configurationResolver.d.ts +23 -0
- package/dist/utils/configurationResolver.js +78 -0
- package/dist/utils/deviceDetection.d.ts +38 -0
- package/dist/utils/deviceDetection.js +59 -0
- package/dist/utils/hapticFeedback.d.ts +17 -0
- package/dist/utils/hapticFeedback.js +53 -0
- package/dist/utils/iconMapper.d.ts +26 -0
- package/dist/utils/iconMapper.js +113 -0
- package/dist/utils/notificationPermissions.d.ts +13 -0
- package/dist/utils/notificationPermissions.js +51 -0
- package/dist/utils/priceFormatting.d.ts +19 -0
- package/dist/utils/priceFormatting.js +99 -0
- package/dist/utils/shareSheet.d.ts +17 -0
- package/dist/utils/shareSheet.js +42 -0
- package/dist/utils/subscriptionUpgrade.d.ts +84 -0
- package/dist/utils/subscriptionUpgrade.js +100 -0
- package/dist/valueUtils.d.ts +48 -0
- package/dist/valueUtils.js +129 -0
- package/dist/xFlowTags.d.ts +18 -0
- package/dist/xFlowTags.js +385 -0
- package/ios/BillDogABTest.m +50 -0
- package/ios/BillDogABTest.swift +188 -0
- package/ios/BillDogAnalytics.m +105 -0
- package/ios/BillDogAnalytics.swift +324 -0
- package/ios/BillDogBridge.m +222 -0
- package/ios/BillDogBridge.swift +715 -0
- package/ios/BillDogLiveActivities.m +41 -0
- package/ios/BillDogLiveActivities.swift +104 -0
- package/ios/BillDogPaywallViewManager.m +39 -0
- package/ios/BillDogPaywallViewManager.swift +361 -0
- package/ios/BillDogSurvey.m +34 -0
- package/ios/BillDogSurvey.swift +257 -0
- package/ios/BillDogVirtualCurrencyBridge.m +63 -0
- package/ios/BillDogVirtualCurrencyBridge.swift +511 -0
- package/junit.xml +25 -0
- package/package.json +61 -0
- package/react-native.config.js +13 -0
- package/src/AdvancedPaywallCache.ts +433 -0
- package/src/BillDog.ts +983 -0
- package/src/BillDogConfiguration.ts +318 -0
- package/src/ComponentRenderer.tsx +1325 -0
- package/src/LayoutEngine.ts +459 -0
- package/src/LocalizationResolver.ts +311 -0
- package/src/NativePaywallView.tsx +132 -0
- package/src/PaywallCache.ts +358 -0
- package/src/PaywallStateManager.ts +154 -0
- package/src/PaywallView.tsx +328 -0
- package/src/ProductVariableProvider.ts +282 -0
- package/src/VariableResolver.ts +516 -0
- package/src/WebViewPaywall.tsx +454 -0
- package/src/animations/presets.ts +421 -0
- package/src/components/AccoladeCpsComponent.tsx +259 -0
- package/src/components/AccordionComponent.tsx +213 -0
- package/src/components/AnimatedWrapper.tsx +316 -0
- package/src/components/CarouselComponent.tsx +615 -0
- package/src/components/ChartCurveComponent.tsx +452 -0
- package/src/components/CheckboxComponent.tsx +185 -0
- package/src/components/ConfettiComponent.tsx +178 -0
- package/src/components/CountdownComponent.tsx +454 -0
- package/src/components/DelayedXComponent.tsx +266 -0
- package/src/components/DrawerModalComponent.tsx +324 -0
- package/src/components/GradientView.tsx +129 -0
- package/src/components/HapticFeedbackComponent.tsx +39 -0
- package/src/components/HorizontalProductsComponent.tsx +329 -0
- package/src/components/MultiChoiceGridComponent.tsx +265 -0
- package/src/components/NPSScaleComponent.tsx +294 -0
- package/src/components/NavigationComponent.tsx +329 -0
- package/src/components/OAuthButtonComponent.tsx +266 -0
- package/src/components/ProgressLoaderComponent.tsx +366 -0
- package/src/components/ProgressStepperComponent.tsx +250 -0
- package/src/components/SegmentedPickerComponent.tsx +245 -0
- package/src/components/ShareButtonsComponent.tsx +299 -0
- package/src/components/ShareCodeComponent.tsx +303 -0
- package/src/components/SingleChoiceGridComponent.tsx +229 -0
- package/src/components/SliderComponent.tsx +280 -0
- package/src/components/StarRatingInputComponent.tsx +223 -0
- package/src/components/StickerCompositeComponent.tsx +168 -0
- package/src/components/TabsComponent.tsx +496 -0
- package/src/components/TextInputComponent.tsx +258 -0
- package/src/components/TimelineComponent.tsx +129 -0
- package/src/components/ToggleComponent.tsx +142 -0
- package/src/components/VerticalProductsComponent.tsx +357 -0
- package/src/dynamicValues.ts +180 -0
- package/src/filters/dateFilters.ts +411 -0
- package/src/filters/index.ts +281 -0
- package/src/hooks/useOfferings.ts +192 -0
- package/src/hooks/usePaywall.ts +154 -0
- package/src/hooks/usePlacement.ts +143 -0
- package/src/hooks/useSubscription.ts +154 -0
- package/src/index.ts +245 -0
- package/src/models/BillDogError.ts +24 -0
- package/src/models/CacheFetchPolicy.ts +13 -0
- package/src/models/CustomProduct.ts +33 -0
- package/src/models/CustomerInfo.ts +26 -0
- package/src/models/Delegate.ts +22 -0
- package/src/models/EntitlementInfo.ts +27 -0
- package/src/models/Placement.ts +50 -0
- package/src/models/PurchaseParams.ts +81 -0
- package/src/models/PurchaseResult.ts +32 -0
- package/src/models/RestoreResult.ts +27 -0
- package/src/models/RestoredItem.ts +25 -0
- package/src/modules/ABTest.ts +131 -0
- package/src/modules/Analytics.ts +227 -0
- package/src/modules/Survey.ts +126 -0
- package/src/modules/VirtualCurrency.ts +223 -0
- package/src/murmur.ts +102 -0
- package/src/notifications/LiveActivitiesManager.ts +140 -0
- package/src/notifications/NotificationScheduler.ts +292 -0
- package/src/notifications/PurchaseNotificationHandler.ts +67 -0
- package/src/notifications/useDeviceToken.ts +116 -0
- package/src/notifications/useLiveActivity.ts +125 -0
- package/src/review/ReviewAnalytics.ts +89 -0
- package/src/review/ReviewManager.ts +355 -0
- package/src/review/ReviewTimingManager.ts +265 -0
- package/src/survey-core/types.ts +244 -0
- package/src/types/ambient.d.ts +9 -0
- package/src/types.ts +680 -0
- package/src/utils/ApiClient.ts +163 -0
- package/src/utils/CSSConverter.ts +552 -0
- package/src/utils/animations.ts +232 -0
- package/src/utils/calendarIntegration.ts +113 -0
- package/src/utils/configurationResolver.ts +106 -0
- package/src/utils/deviceDetection.ts +83 -0
- package/src/utils/hapticFeedback.ts +55 -0
- package/src/utils/iconMapper.ts +102 -0
- package/src/utils/notificationPermissions.ts +48 -0
- package/src/utils/priceFormatting.ts +119 -0
- package/src/utils/shareSheet.ts +55 -0
- package/src/utils/subscriptionUpgrade.ts +183 -0
- package/src/valueUtils.ts +108 -0
- package/src/xFlowTags.ts +463 -0
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xFlow Date/Time Filters — React Native SDK.
|
|
3
|
+
*
|
|
4
|
+
* Verbatim mirror of src/lib/filters/dateFilters.ts (pure TypeScript, only
|
|
5
|
+
* Date + Intl — no web dependencies). Kept in lockstep with the web file;
|
|
6
|
+
* the shared conformance corpus (tests/parity/xflow-corpus/) enforces parity.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
// ============= Date Format Tokens (strftime-like) =============
|
|
10
|
+
|
|
11
|
+
const FORMAT_TOKENS: Record<string, (date: Date, locale?: string) => string> = {
|
|
12
|
+
'%Y': (d) => d.getFullYear().toString(),
|
|
13
|
+
'%y': (d) => d.getFullYear().toString().slice(-2),
|
|
14
|
+
'%m': (d) => String(d.getMonth() + 1).padStart(2, '0'),
|
|
15
|
+
'%B': (d, locale = 'en-US') => d.toLocaleDateString(locale, { month: 'long' }),
|
|
16
|
+
'%b': (d, locale = 'en-US') => d.toLocaleDateString(locale, { month: 'short' }),
|
|
17
|
+
'%d': (d) => String(d.getDate()).padStart(2, '0'),
|
|
18
|
+
'%e': (d) => String(d.getDate()),
|
|
19
|
+
'%j': (d) => {
|
|
20
|
+
const start = new Date(d.getFullYear(), 0, 0);
|
|
21
|
+
const diff = d.getTime() - start.getTime();
|
|
22
|
+
return String(Math.floor(diff / (1000 * 60 * 60 * 24))).padStart(3, '0');
|
|
23
|
+
},
|
|
24
|
+
'%A': (d, locale = 'en-US') => d.toLocaleDateString(locale, { weekday: 'long' }),
|
|
25
|
+
'%a': (d, locale = 'en-US') => d.toLocaleDateString(locale, { weekday: 'short' }),
|
|
26
|
+
'%w': (d) => d.getDay().toString(),
|
|
27
|
+
'%u': (d) => (d.getDay() || 7).toString(),
|
|
28
|
+
'%H': (d) => String(d.getHours()).padStart(2, '0'),
|
|
29
|
+
'%I': (d) => String(d.getHours() % 12 || 12).padStart(2, '0'),
|
|
30
|
+
'%k': (d) => String(d.getHours()),
|
|
31
|
+
'%l': (d) => String(d.getHours() % 12 || 12),
|
|
32
|
+
'%M': (d) => String(d.getMinutes()).padStart(2, '0'),
|
|
33
|
+
'%S': (d) => String(d.getSeconds()).padStart(2, '0'),
|
|
34
|
+
'%p': (d) => (d.getHours() >= 12 ? 'PM' : 'AM'),
|
|
35
|
+
'%P': (d) => (d.getHours() >= 12 ? 'pm' : 'am'),
|
|
36
|
+
'%z': (d) => {
|
|
37
|
+
const offset = d.getTimezoneOffset();
|
|
38
|
+
const sign = offset <= 0 ? '+' : '-';
|
|
39
|
+
const hours = String(Math.floor(Math.abs(offset) / 60)).padStart(2, '0');
|
|
40
|
+
const mins = String(Math.abs(offset) % 60).padStart(2, '0');
|
|
41
|
+
return `${sign}${hours}${mins}`;
|
|
42
|
+
},
|
|
43
|
+
'%Z': () => Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
44
|
+
'%F': (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`,
|
|
45
|
+
'%T': (d) => `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`,
|
|
46
|
+
'%R': (d) => `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`,
|
|
47
|
+
'%%': () => '%',
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// ============= Countdown Format Types =============
|
|
51
|
+
|
|
52
|
+
export type MaxUnit = 'days' | 'hours' | 'minutes' | 'seconds';
|
|
53
|
+
|
|
54
|
+
export type CountdownFormat =
|
|
55
|
+
| 'digital'
|
|
56
|
+
| 'digital_full'
|
|
57
|
+
| 'long'
|
|
58
|
+
| 'long_most_significant'
|
|
59
|
+
| 'short'
|
|
60
|
+
| 'short_most_significant'
|
|
61
|
+
| 'narrow'
|
|
62
|
+
| 'narrow_most_significant'
|
|
63
|
+
| 'wide'
|
|
64
|
+
| 'wide_most_significant'
|
|
65
|
+
| 'column'
|
|
66
|
+
| 'days_only'
|
|
67
|
+
| 'hours_only'
|
|
68
|
+
| 'minutes_only'
|
|
69
|
+
| 'seconds_only'
|
|
70
|
+
| 'compact';
|
|
71
|
+
|
|
72
|
+
export interface TimeRemaining {
|
|
73
|
+
days: number;
|
|
74
|
+
hours: number;
|
|
75
|
+
minutes: number;
|
|
76
|
+
seconds: number;
|
|
77
|
+
totalSeconds: number;
|
|
78
|
+
isExpired: boolean;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ============= Core Date Parsing =============
|
|
82
|
+
|
|
83
|
+
export function parseDate(value: string | number | Date): Date {
|
|
84
|
+
if (value instanceof Date) return value;
|
|
85
|
+
if (typeof value === 'number') return new Date(value);
|
|
86
|
+
|
|
87
|
+
const trimmed = String(value).trim();
|
|
88
|
+
|
|
89
|
+
const relativeMatch = trimmed.match(/^([+-])(\d+)([smhdwMy])$/);
|
|
90
|
+
if (relativeMatch) {
|
|
91
|
+
const [, sign, amount, unit] = relativeMatch;
|
|
92
|
+
const multiplier = sign === '+' ? 1 : -1;
|
|
93
|
+
const unitMs = getUnitMilliseconds(unit);
|
|
94
|
+
return new Date(Date.now() + multiplier * parseInt(amount) * unitMs);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const parsed = new Date(trimmed);
|
|
98
|
+
if (!isNaN(parsed.getTime())) return parsed;
|
|
99
|
+
|
|
100
|
+
console.warn('[parseDate] Could not parse date value:', value, '- defaulting to 5 minutes');
|
|
101
|
+
return new Date(Date.now() + 5 * 60 * 1000);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function getUnitMilliseconds(unit: string): number {
|
|
105
|
+
const units: Record<string, number> = {
|
|
106
|
+
s: 1000,
|
|
107
|
+
m: 60 * 1000,
|
|
108
|
+
h: 60 * 60 * 1000,
|
|
109
|
+
d: 24 * 60 * 60 * 1000,
|
|
110
|
+
w: 7 * 24 * 60 * 60 * 1000,
|
|
111
|
+
M: 30 * 24 * 60 * 60 * 1000,
|
|
112
|
+
y: 365 * 24 * 60 * 60 * 1000,
|
|
113
|
+
};
|
|
114
|
+
return units[unit] || units.d;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ============= Date Formatting =============
|
|
118
|
+
|
|
119
|
+
export function formatDate(date: Date | string | number, format: string, locale?: string): string {
|
|
120
|
+
const d = parseDate(date);
|
|
121
|
+
|
|
122
|
+
const presetFormats: Record<string, string> = {
|
|
123
|
+
iso: '%Y-%m-%dT%H:%M:%S',
|
|
124
|
+
date: '%Y-%m-%d',
|
|
125
|
+
time: '%H:%M:%S',
|
|
126
|
+
datetime: '%Y-%m-%d %H:%M:%S',
|
|
127
|
+
short: '%m/%d/%Y',
|
|
128
|
+
long: '%B %e, %Y',
|
|
129
|
+
full: '%A, %B %e, %Y',
|
|
130
|
+
time12: '%I:%M %p',
|
|
131
|
+
time24: '%H:%M',
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const formatString = presetFormats[format] || format;
|
|
135
|
+
|
|
136
|
+
return formatString.replace(/%[A-Za-z%]/g, (token) => {
|
|
137
|
+
const formatter = FORMAT_TOKENS[token];
|
|
138
|
+
return formatter ? formatter(d, locale) : token;
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ============= ms-string Parser =============
|
|
143
|
+
|
|
144
|
+
const MS_STRING_UNITS: Record<string, 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'months' | 'years'> = {
|
|
145
|
+
s: 'seconds',
|
|
146
|
+
m: 'minutes',
|
|
147
|
+
h: 'hours',
|
|
148
|
+
d: 'days',
|
|
149
|
+
w: 'weeks',
|
|
150
|
+
M: 'months',
|
|
151
|
+
y: 'years',
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
export function parseMsString(
|
|
155
|
+
value: string,
|
|
156
|
+
): { amount: number; unit: 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'months' | 'years' } | null {
|
|
157
|
+
const match = String(value).match(/^(-?\d+(?:\.\d+)?)\s*([smhdwMy])$/);
|
|
158
|
+
if (!match) return null;
|
|
159
|
+
const unit = MS_STRING_UNITS[match[2]];
|
|
160
|
+
if (!unit) return null;
|
|
161
|
+
return { amount: parseFloat(match[1]), unit };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ============= Date Arithmetic =============
|
|
165
|
+
|
|
166
|
+
export function dateAdd(
|
|
167
|
+
date: Date | string | number,
|
|
168
|
+
amount: number | string,
|
|
169
|
+
unit?: 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'months' | 'years',
|
|
170
|
+
): Date {
|
|
171
|
+
if (typeof amount === 'string') {
|
|
172
|
+
const parsed = parseMsString(amount);
|
|
173
|
+
if (parsed) {
|
|
174
|
+
amount = parsed.amount;
|
|
175
|
+
unit = parsed.unit;
|
|
176
|
+
} else {
|
|
177
|
+
amount = parseFloat(amount) || 0;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (!unit) unit = 'days';
|
|
181
|
+
const d = parseDate(date);
|
|
182
|
+
const result = new Date(d);
|
|
183
|
+
|
|
184
|
+
switch (unit) {
|
|
185
|
+
case 'seconds': result.setSeconds(result.getSeconds() + amount); break;
|
|
186
|
+
case 'minutes': result.setMinutes(result.getMinutes() + amount); break;
|
|
187
|
+
case 'hours': result.setHours(result.getHours() + amount); break;
|
|
188
|
+
case 'days': result.setDate(result.getDate() + amount); break;
|
|
189
|
+
case 'weeks': result.setDate(result.getDate() + amount * 7); break;
|
|
190
|
+
case 'months': result.setMonth(result.getMonth() + amount); break;
|
|
191
|
+
case 'years': result.setFullYear(result.getFullYear() + amount); break;
|
|
192
|
+
}
|
|
193
|
+
return result;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function dateSubtract(
|
|
197
|
+
date: Date | string | number,
|
|
198
|
+
amount: number | string,
|
|
199
|
+
unit?: 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'months' | 'years',
|
|
200
|
+
): Date {
|
|
201
|
+
if (typeof amount === 'string') {
|
|
202
|
+
const parsed = parseMsString(amount);
|
|
203
|
+
if (parsed) return dateAdd(date, -parsed.amount, parsed.unit);
|
|
204
|
+
}
|
|
205
|
+
return dateAdd(date, -(typeof amount === 'number' ? amount : parseFloat(amount) || 0), unit);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ============= Countdown Calculations =============
|
|
209
|
+
|
|
210
|
+
export function calculateTimeRemaining(
|
|
211
|
+
endDate: Date | string | number,
|
|
212
|
+
startDate: Date | string | number = new Date(),
|
|
213
|
+
): TimeRemaining {
|
|
214
|
+
const end = parseDate(endDate);
|
|
215
|
+
const start = parseDate(startDate);
|
|
216
|
+
|
|
217
|
+
const totalSeconds = Math.max(0, Math.floor((end.getTime() - start.getTime()) / 1000));
|
|
218
|
+
|
|
219
|
+
const days = Math.floor(totalSeconds / 86400);
|
|
220
|
+
const hours = Math.floor((totalSeconds % 86400) / 3600);
|
|
221
|
+
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
222
|
+
const seconds = totalSeconds % 60;
|
|
223
|
+
|
|
224
|
+
return { days, hours, minutes, seconds, totalSeconds, isExpired: totalSeconds <= 0 };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function applyMaxUnit(time: TimeRemaining, maxUnit: MaxUnit): TimeRemaining {
|
|
228
|
+
const { totalSeconds, isExpired } = time;
|
|
229
|
+
switch (maxUnit) {
|
|
230
|
+
case 'hours':
|
|
231
|
+
return { days: 0, hours: Math.floor(totalSeconds / 3600), minutes: Math.floor((totalSeconds % 3600) / 60), seconds: totalSeconds % 60, totalSeconds, isExpired };
|
|
232
|
+
case 'minutes':
|
|
233
|
+
return { days: 0, hours: 0, minutes: Math.floor(totalSeconds / 60), seconds: totalSeconds % 60, totalSeconds, isExpired };
|
|
234
|
+
case 'seconds':
|
|
235
|
+
return { days: 0, hours: 0, minutes: 0, seconds: totalSeconds, totalSeconds, isExpired };
|
|
236
|
+
case 'days':
|
|
237
|
+
default:
|
|
238
|
+
return time;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function resolveFormatAlias(format: CountdownFormat): CountdownFormat {
|
|
243
|
+
switch (format) {
|
|
244
|
+
case 'narrow': return 'short';
|
|
245
|
+
case 'narrow_most_significant': return 'short_most_significant';
|
|
246
|
+
case 'wide': return 'long';
|
|
247
|
+
case 'wide_most_significant': return 'long_most_significant';
|
|
248
|
+
default: return format;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function formatCountdown(
|
|
253
|
+
timeRemaining: TimeRemaining,
|
|
254
|
+
format: CountdownFormat = 'digital',
|
|
255
|
+
maxUnit?: MaxUnit,
|
|
256
|
+
): string {
|
|
257
|
+
const resolved = resolveFormatAlias(format);
|
|
258
|
+
const capped = maxUnit ? applyMaxUnit(timeRemaining, maxUnit) : timeRemaining;
|
|
259
|
+
const { days, hours, minutes, seconds, totalSeconds } = capped;
|
|
260
|
+
|
|
261
|
+
if (resolved === 'column') {
|
|
262
|
+
const colParts: string[] = [];
|
|
263
|
+
if (days > 0) colParts.push(`${days}d`);
|
|
264
|
+
if (hours > 0 || days > 0) colParts.push(`${hours}h`);
|
|
265
|
+
if (minutes > 0 || hours > 0 || days > 0) colParts.push(`${minutes}m`);
|
|
266
|
+
colParts.push(`${seconds}s`);
|
|
267
|
+
return colParts.join('\n');
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
switch (resolved) {
|
|
271
|
+
case 'digital':
|
|
272
|
+
return [
|
|
273
|
+
String(hours + days * 24).padStart(2, '0'),
|
|
274
|
+
String(minutes).padStart(2, '0'),
|
|
275
|
+
String(seconds).padStart(2, '0'),
|
|
276
|
+
].join(':');
|
|
277
|
+
case 'digital_full':
|
|
278
|
+
return [
|
|
279
|
+
String(days).padStart(2, '0'),
|
|
280
|
+
String(hours).padStart(2, '0'),
|
|
281
|
+
String(minutes).padStart(2, '0'),
|
|
282
|
+
String(seconds).padStart(2, '0'),
|
|
283
|
+
].join(':');
|
|
284
|
+
case 'long': {
|
|
285
|
+
const parts: string[] = [];
|
|
286
|
+
if (days > 0) parts.push(`${days} day${days !== 1 ? 's' : ''}`);
|
|
287
|
+
if (hours > 0) parts.push(`${hours} hour${hours !== 1 ? 's' : ''}`);
|
|
288
|
+
if (minutes > 0) parts.push(`${minutes} minute${minutes !== 1 ? 's' : ''}`);
|
|
289
|
+
if (seconds > 0 || parts.length === 0) parts.push(`${seconds} second${seconds !== 1 ? 's' : ''}`);
|
|
290
|
+
return parts.join(', ');
|
|
291
|
+
}
|
|
292
|
+
case 'long_most_significant':
|
|
293
|
+
if (days > 0) return `${days} day${days !== 1 ? 's' : ''}`;
|
|
294
|
+
if (hours > 0) return `${hours} hour${hours !== 1 ? 's' : ''}`;
|
|
295
|
+
if (minutes > 0) return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
|
|
296
|
+
return `${seconds} second${seconds !== 1 ? 's' : ''}`;
|
|
297
|
+
case 'short': {
|
|
298
|
+
const shortParts: string[] = [];
|
|
299
|
+
if (days > 0) shortParts.push(`${days}d`);
|
|
300
|
+
if (hours > 0) shortParts.push(`${hours}h`);
|
|
301
|
+
if (minutes > 0) shortParts.push(`${minutes}m`);
|
|
302
|
+
if (seconds > 0 || shortParts.length === 0) shortParts.push(`${seconds}s`);
|
|
303
|
+
return shortParts.join(' ');
|
|
304
|
+
}
|
|
305
|
+
case 'short_most_significant':
|
|
306
|
+
if (days > 0) return `${days}d`;
|
|
307
|
+
if (hours > 0) return `${hours}h`;
|
|
308
|
+
if (minutes > 0) return `${minutes}m`;
|
|
309
|
+
return `${seconds}s`;
|
|
310
|
+
case 'days_only':
|
|
311
|
+
return `${days} day${days !== 1 ? 's' : ''}`;
|
|
312
|
+
case 'hours_only': {
|
|
313
|
+
const totalHours = days * 24 + hours;
|
|
314
|
+
return `${totalHours} hour${totalHours !== 1 ? 's' : ''}`;
|
|
315
|
+
}
|
|
316
|
+
case 'minutes_only': {
|
|
317
|
+
const totalMinutes = Math.floor(totalSeconds / 60);
|
|
318
|
+
return `${totalMinutes} minute${totalMinutes !== 1 ? 's' : ''}`;
|
|
319
|
+
}
|
|
320
|
+
case 'seconds_only':
|
|
321
|
+
return `${totalSeconds} second${totalSeconds !== 1 ? 's' : ''}`;
|
|
322
|
+
case 'compact':
|
|
323
|
+
return `${days}:${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
|
|
324
|
+
default:
|
|
325
|
+
return formatCountdown(timeRemaining, 'digital', maxUnit);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ============= Helper Filters =============
|
|
330
|
+
|
|
331
|
+
export function toOrdinal(num: number): string {
|
|
332
|
+
const suffixes = ['th', 'st', 'nd', 'rd'];
|
|
333
|
+
const v = num % 100;
|
|
334
|
+
return num + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export function toMonthName(month: number, format: 'short' | 'long' = 'long', locale = 'en-US'): string {
|
|
338
|
+
const date = new Date(2000, month - 1, 1);
|
|
339
|
+
return date.toLocaleDateString(locale, { month: format });
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function toDayName(day: number, format: 'short' | 'long' = 'long', locale = 'en-US'): string {
|
|
343
|
+
const date = new Date(2000, 0, 2 + day);
|
|
344
|
+
return date.toLocaleDateString(locale, { weekday: format });
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function relativeTime(date: Date | string | number, locale = 'en-US'): string {
|
|
348
|
+
const d = parseDate(date);
|
|
349
|
+
const now = new Date();
|
|
350
|
+
const diffMs = d.getTime() - now.getTime();
|
|
351
|
+
const diffSeconds = Math.abs(Math.floor(diffMs / 1000));
|
|
352
|
+
const isPast = diffMs < 0;
|
|
353
|
+
|
|
354
|
+
let value: number;
|
|
355
|
+
let unit: Intl.RelativeTimeFormatUnit;
|
|
356
|
+
|
|
357
|
+
if (diffSeconds < 60) { value = diffSeconds; unit = 'second'; }
|
|
358
|
+
else if (diffSeconds < 3600) { value = Math.floor(diffSeconds / 60); unit = 'minute'; }
|
|
359
|
+
else if (diffSeconds < 86400) { value = Math.floor(diffSeconds / 3600); unit = 'hour'; }
|
|
360
|
+
else if (diffSeconds < 604800) { value = Math.floor(diffSeconds / 86400); unit = 'day'; }
|
|
361
|
+
else if (diffSeconds < 2592000) { value = Math.floor(diffSeconds / 604800); unit = 'week'; }
|
|
362
|
+
else if (diffSeconds < 31536000) { value = Math.floor(diffSeconds / 2592000); unit = 'month'; }
|
|
363
|
+
else { value = Math.floor(diffSeconds / 31536000); unit = 'year'; }
|
|
364
|
+
|
|
365
|
+
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
|
|
366
|
+
return rtf.format(isPast ? -value : value, unit);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ============= Countdown Specific Filters =============
|
|
370
|
+
|
|
371
|
+
export function countdownDaysTotal(startDate: Date | string | number, endDate: Date | string | number): number {
|
|
372
|
+
return Math.floor(calculateTimeRemaining(endDate, startDate).totalSeconds / 86400);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export function countdownHoursTotal(startDate: Date | string | number, endDate: Date | string | number): number {
|
|
376
|
+
return Math.floor(calculateTimeRemaining(endDate, startDate).totalSeconds / 3600);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function countdownMinutesTotal(startDate: Date | string | number, endDate: Date | string | number): number {
|
|
380
|
+
return Math.floor(calculateTimeRemaining(endDate, startDate).totalSeconds / 60);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export function countdownSecondsTotal(startDate: Date | string | number, endDate: Date | string | number): number {
|
|
384
|
+
return calculateTimeRemaining(endDate, startDate).totalSeconds;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export function countdownFrom(
|
|
388
|
+
endDate: Date | string | number,
|
|
389
|
+
startDate: Date | string | number = new Date(),
|
|
390
|
+
format: CountdownFormat = 'digital',
|
|
391
|
+
maxUnit?: MaxUnit,
|
|
392
|
+
): string {
|
|
393
|
+
return formatCountdown(calculateTimeRemaining(endDate, startDate), format, maxUnit);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// ============= Export All Filters =============
|
|
397
|
+
|
|
398
|
+
export const DATE_FILTERS = {
|
|
399
|
+
date: formatDate,
|
|
400
|
+
date_add: dateAdd,
|
|
401
|
+
date_subtract: dateSubtract,
|
|
402
|
+
countdown_from: countdownFrom,
|
|
403
|
+
countdown_days_total: countdownDaysTotal,
|
|
404
|
+
countdown_hours_total: countdownHoursTotal,
|
|
405
|
+
countdown_minutes_total: countdownMinutesTotal,
|
|
406
|
+
countdown_seconds_total: countdownSecondsTotal,
|
|
407
|
+
to_ordinal: toOrdinal,
|
|
408
|
+
to_month_name: toMonthName,
|
|
409
|
+
to_day_name: toDayName,
|
|
410
|
+
relative_time: relativeTime,
|
|
411
|
+
};
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Filter Registry and Chain Processor — React Native SDK.
|
|
3
|
+
*
|
|
4
|
+
* Verbatim mirror of src/lib/filters/index.ts (pure TypeScript, no web
|
|
5
|
+
* dependencies). Handles xFlow filter syntax: {{ variable | filter: arg }}
|
|
6
|
+
* and {% assign x = value | filter %}. Kept in lockstep with the web file;
|
|
7
|
+
* the shared conformance corpus enforces parity.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
formatDate,
|
|
12
|
+
dateAdd,
|
|
13
|
+
dateSubtract,
|
|
14
|
+
countdownFrom,
|
|
15
|
+
countdownDaysTotal,
|
|
16
|
+
countdownHoursTotal,
|
|
17
|
+
countdownMinutesTotal,
|
|
18
|
+
countdownSecondsTotal,
|
|
19
|
+
toOrdinal,
|
|
20
|
+
toMonthName,
|
|
21
|
+
toDayName,
|
|
22
|
+
relativeTime,
|
|
23
|
+
CountdownFormat,
|
|
24
|
+
} from './dateFilters';
|
|
25
|
+
|
|
26
|
+
// ============= String Filters =============
|
|
27
|
+
|
|
28
|
+
const STRING_FILTERS = {
|
|
29
|
+
upcase: (value: string) => String(value).toUpperCase(),
|
|
30
|
+
downcase: (value: string) => String(value).toLowerCase(),
|
|
31
|
+
capitalize: (value: string) => {
|
|
32
|
+
const str = String(value);
|
|
33
|
+
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
|
|
34
|
+
},
|
|
35
|
+
titlecase: (value: string) =>
|
|
36
|
+
String(value).replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.slice(1).toLowerCase()),
|
|
37
|
+
strip: (value: string) => String(value).trim(),
|
|
38
|
+
lstrip: (value: string) => String(value).trimStart(),
|
|
39
|
+
rstrip: (value: string) => String(value).trimEnd(),
|
|
40
|
+
truncate: (value: string, length: number = 50, ellipsis: string = '...') => {
|
|
41
|
+
const str = String(value);
|
|
42
|
+
if (str.length <= length) return str;
|
|
43
|
+
return str.slice(0, length - ellipsis.length) + ellipsis;
|
|
44
|
+
},
|
|
45
|
+
truncatewords: (value: string, words: number = 15, ellipsis: string = '...') => {
|
|
46
|
+
const wordArray = String(value).split(/\s+/);
|
|
47
|
+
if (wordArray.length <= words) return value;
|
|
48
|
+
return wordArray.slice(0, words).join(' ') + ellipsis;
|
|
49
|
+
},
|
|
50
|
+
append: (value: string, suffix: string) => String(value) + suffix,
|
|
51
|
+
prepend: (value: string, prefix: string) => prefix + String(value),
|
|
52
|
+
replace: (value: string, search: string, replacement: string = '') =>
|
|
53
|
+
String(value).replace(new RegExp(search, 'g'), replacement),
|
|
54
|
+
replace_first: (value: string, search: string, replacement: string = '') =>
|
|
55
|
+
String(value).replace(search, replacement),
|
|
56
|
+
remove: (value: string, toRemove: string) => String(value).replace(new RegExp(toRemove, 'g'), ''),
|
|
57
|
+
remove_first: (value: string, toRemove: string) => String(value).replace(toRemove, ''),
|
|
58
|
+
size: (value: string | any[]) => (Array.isArray(value) ? value.length : String(value).length),
|
|
59
|
+
escape: (value: string) =>
|
|
60
|
+
String(value)
|
|
61
|
+
.replace(/&/g, '&')
|
|
62
|
+
.replace(/</g, '<')
|
|
63
|
+
.replace(/>/g, '>')
|
|
64
|
+
.replace(/"/g, '"')
|
|
65
|
+
.replace(/'/g, '''),
|
|
66
|
+
url_encode: (value: string) => encodeURIComponent(String(value)),
|
|
67
|
+
url_decode: (value: string) => decodeURIComponent(String(value)),
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// ============= Number Filters =============
|
|
71
|
+
|
|
72
|
+
const NUMBER_FILTERS = {
|
|
73
|
+
plus: (value: number, addend: number) => Number(value) + Number(addend),
|
|
74
|
+
minus: (value: number, subtrahend: number) => Number(value) - Number(subtrahend),
|
|
75
|
+
times: (value: number, multiplier: number) => Number(value) * Number(multiplier),
|
|
76
|
+
divided_by: (value: number, divisor: number) => Number(value) / Number(divisor),
|
|
77
|
+
modulo: (value: number, divisor: number) => Number(value) % Number(divisor),
|
|
78
|
+
round: (value: number, decimals: number = 0) => {
|
|
79
|
+
const factor = Math.pow(10, decimals);
|
|
80
|
+
return Math.round(Number(value) * factor) / factor;
|
|
81
|
+
},
|
|
82
|
+
floor: (value: number) => Math.floor(Number(value)),
|
|
83
|
+
ceil: (value: number) => Math.ceil(Number(value)),
|
|
84
|
+
abs: (value: number) => Math.abs(Number(value)),
|
|
85
|
+
number_with_delimiter: (value: number, delimiter: string = ',') =>
|
|
86
|
+
Number(value).toLocaleString('en-US').replace(/,/g, delimiter),
|
|
87
|
+
currency: (value: number, symbol: string = '$', decimals: number = 2) =>
|
|
88
|
+
`${symbol}${Number(value).toFixed(decimals)}`,
|
|
89
|
+
percentage: (value: number, decimals: number = 0) => `${(Number(value) * 100).toFixed(decimals)}%`,
|
|
90
|
+
at_least: (value: number, min: number) => Math.max(Number(value), Number(min)),
|
|
91
|
+
at_most: (value: number, max: number) => Math.min(Number(value), Number(max)),
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// ============= Array Filters =============
|
|
95
|
+
|
|
96
|
+
const ARRAY_FILTERS = {
|
|
97
|
+
first: (value: any[]) => (Array.isArray(value) ? value[0] : value),
|
|
98
|
+
last: (value: any[]) => (Array.isArray(value) ? value[value.length - 1] : value),
|
|
99
|
+
join: (value: any[], separator: string = ', ') =>
|
|
100
|
+
Array.isArray(value) ? value.join(separator) : String(value),
|
|
101
|
+
reverse: (value: any[]) => (Array.isArray(value) ? [...value].reverse() : value),
|
|
102
|
+
sort: (value: any[]) => (Array.isArray(value) ? [...value].sort() : value),
|
|
103
|
+
uniq: (value: any[]) => (Array.isArray(value) ? [...new Set(value)] : value),
|
|
104
|
+
compact: (value: any[]) => (Array.isArray(value) ? value.filter((v) => v != null) : value),
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// ============= Default/Fallback Filters =============
|
|
108
|
+
|
|
109
|
+
const UTILITY_FILTERS = {
|
|
110
|
+
default: (value: any, defaultValue: any) =>
|
|
111
|
+
value == null || value === '' || value === false ? defaultValue : value,
|
|
112
|
+
default_if_none: (value: any, defaultValue: any) => (value == null ? defaultValue : value),
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// ============= All Filters Combined =============
|
|
116
|
+
|
|
117
|
+
export const ALL_FILTERS: Record<string, (...args: any[]) => any> = {
|
|
118
|
+
...STRING_FILTERS,
|
|
119
|
+
...NUMBER_FILTERS,
|
|
120
|
+
...ARRAY_FILTERS,
|
|
121
|
+
...UTILITY_FILTERS,
|
|
122
|
+
date: (value: any, format: string, locale?: string) => formatDate(value, format, locale),
|
|
123
|
+
date_add: (value: any, amount: number | string, unit?: any) => dateAdd(value, amount, unit),
|
|
124
|
+
date_subtract: (value: any, amount: number | string, unit?: any) => dateSubtract(value, amount, unit),
|
|
125
|
+
countdown_from: (endDate: any, startDate?: any, format?: CountdownFormat, maxUnit?: string) =>
|
|
126
|
+
countdownFrom(endDate, startDate, format, maxUnit as any),
|
|
127
|
+
countdown_days_total: (start: any, end: any) => countdownDaysTotal(start, end),
|
|
128
|
+
countdown_hours_total: (start: any, end: any) => countdownHoursTotal(start, end),
|
|
129
|
+
countdown_minutes_total: (start: any, end: any) => countdownMinutesTotal(start, end),
|
|
130
|
+
countdown_seconds_total: (start: any, end: any) => countdownSecondsTotal(start, end),
|
|
131
|
+
to_ordinal: (value: number) => toOrdinal(value),
|
|
132
|
+
to_month_name: (value: number, format?: 'short' | 'long', locale?: string) =>
|
|
133
|
+
toMonthName(value, format, locale),
|
|
134
|
+
to_day_name: (value: number, format?: 'short' | 'long', locale?: string) =>
|
|
135
|
+
toDayName(value, format, locale),
|
|
136
|
+
relative_time: (value: any, locale?: string) => relativeTime(value, locale),
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// ============= Filter Argument Parser =============
|
|
140
|
+
|
|
141
|
+
function parseFilterArgs(argsString: string): any[] {
|
|
142
|
+
if (!argsString?.trim()) return [];
|
|
143
|
+
|
|
144
|
+
const args: any[] = [];
|
|
145
|
+
let current = '';
|
|
146
|
+
let inQuote = false;
|
|
147
|
+
let quoteChar = '';
|
|
148
|
+
let depth = 0;
|
|
149
|
+
|
|
150
|
+
for (let i = 0; i < argsString.length; i++) {
|
|
151
|
+
const char = argsString[i];
|
|
152
|
+
if ((char === '"' || char === "'") && argsString[i - 1] !== '\\') {
|
|
153
|
+
if (!inQuote) { inQuote = true; quoteChar = char; }
|
|
154
|
+
else if (char === quoteChar) { inQuote = false; }
|
|
155
|
+
current += char;
|
|
156
|
+
} else if (char === '[' || char === '{') {
|
|
157
|
+
depth++;
|
|
158
|
+
current += char;
|
|
159
|
+
} else if (char === ']' || char === '}') {
|
|
160
|
+
depth--;
|
|
161
|
+
current += char;
|
|
162
|
+
} else if (char === ',' && !inQuote && depth === 0) {
|
|
163
|
+
args.push(parseArgValue(current.trim()));
|
|
164
|
+
current = '';
|
|
165
|
+
} else {
|
|
166
|
+
current += char;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (current.trim()) args.push(parseArgValue(current.trim()));
|
|
171
|
+
return args;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function parseArgValue(value: string): any {
|
|
175
|
+
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
176
|
+
(value.startsWith("'") && value.endsWith("'"))) {
|
|
177
|
+
return value.slice(1, -1);
|
|
178
|
+
}
|
|
179
|
+
if (value === 'true') return true;
|
|
180
|
+
if (value === 'false') return false;
|
|
181
|
+
if (value === 'null' || value === 'nil') return null;
|
|
182
|
+
const num = Number(value);
|
|
183
|
+
if (!isNaN(num) && value !== '') return num;
|
|
184
|
+
try {
|
|
185
|
+
return JSON.parse(value);
|
|
186
|
+
} catch {
|
|
187
|
+
return value;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ============= Filter Chain Processor =============
|
|
192
|
+
|
|
193
|
+
interface ParsedFilter {
|
|
194
|
+
name: string;
|
|
195
|
+
args: any[];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function parseFilterChain(filterChain: string): ParsedFilter[] {
|
|
199
|
+
const filters: ParsedFilter[] = [];
|
|
200
|
+
const parts: string[] = [];
|
|
201
|
+
let current = '';
|
|
202
|
+
let inQuote = false;
|
|
203
|
+
let quoteChar = '';
|
|
204
|
+
|
|
205
|
+
for (let i = 0; i < filterChain.length; i++) {
|
|
206
|
+
const char = filterChain[i];
|
|
207
|
+
if ((char === '"' || char === "'") && filterChain[i - 1] !== '\\') {
|
|
208
|
+
if (!inQuote) { inQuote = true; quoteChar = char; }
|
|
209
|
+
else if (char === quoteChar) { inQuote = false; }
|
|
210
|
+
current += char;
|
|
211
|
+
} else if (char === '|' && !inQuote) {
|
|
212
|
+
if (current.trim()) parts.push(current.trim());
|
|
213
|
+
current = '';
|
|
214
|
+
} else {
|
|
215
|
+
current += char;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (current.trim()) parts.push(current.trim());
|
|
219
|
+
|
|
220
|
+
for (const part of parts) {
|
|
221
|
+
const colonIndex = part.indexOf(':');
|
|
222
|
+
if (colonIndex === -1) {
|
|
223
|
+
filters.push({ name: part.trim(), args: [] });
|
|
224
|
+
} else {
|
|
225
|
+
const name = part.slice(0, colonIndex).trim();
|
|
226
|
+
const argsString = part.slice(colonIndex + 1).trim();
|
|
227
|
+
filters.push({ name, args: parseFilterArgs(argsString) });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return filters;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function applyFilterChain(value: any, filterChain: string): any {
|
|
234
|
+
const filters = parseFilterChain(filterChain);
|
|
235
|
+
let result = value;
|
|
236
|
+
for (const filter of filters) {
|
|
237
|
+
const filterFn = ALL_FILTERS[filter.name];
|
|
238
|
+
if (filterFn) {
|
|
239
|
+
try {
|
|
240
|
+
result = filterFn(result, ...filter.args);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
console.warn(`Filter "${filter.name}" failed:`, error);
|
|
243
|
+
}
|
|
244
|
+
} else {
|
|
245
|
+
console.warn(`Unknown filter: "${filter.name}"`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return result;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Replace {{ variable }} and {{ variable | filter: arg }} occurrences in text.
|
|
253
|
+
* Mirror of the web replaceVariablesWithFilters — unresolved variables are
|
|
254
|
+
* left untouched.
|
|
255
|
+
*/
|
|
256
|
+
export function replaceVariablesWithFilters(
|
|
257
|
+
text: string,
|
|
258
|
+
variables: Record<string, any>,
|
|
259
|
+
): string {
|
|
260
|
+
if (!text) return text;
|
|
261
|
+
|
|
262
|
+
return text.replace(
|
|
263
|
+
/\{\{\s*([\w.]+)(?:\s*\|\s*(.+?))?\s*\}\}/g,
|
|
264
|
+
(match, varPath, filterChain) => {
|
|
265
|
+
let value = varPath
|
|
266
|
+
.split('.')
|
|
267
|
+
.reduce((obj: any, key: string) => obj?.[key], variables);
|
|
268
|
+
|
|
269
|
+
if (value === undefined) return match;
|
|
270
|
+
|
|
271
|
+
if (filterChain) {
|
|
272
|
+
value = applyFilterChain(value, filterChain);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return value !== undefined ? String(value) : match;
|
|
276
|
+
},
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export { DATE_FILTERS } from './dateFilters';
|
|
281
|
+
export type { CountdownFormat, TimeRemaining, MaxUnit } from './dateFilters';
|