@capillarytech/creatives-library 9.2.3 → 9.2.4-beta.sprint-cap-214027-tags-ux-changes.48

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 (95) hide show
  1. package/config/app.js +2 -0
  2. package/constants/unified.js +11 -0
  3. package/package.json +1 -1
  4. package/services/api.js +27 -8
  5. package/translations/en.json +1 -0
  6. package/translations/ja-JP.json +1 -0
  7. package/translations/zh.json +1 -0
  8. package/utils/common.js +7 -0
  9. package/utils/history.js +9 -3
  10. package/utils/mfeHistory.js +14 -0
  11. package/utils/mockGroupedTags.js +44 -0
  12. package/utils/tagValidations.js +37 -4
  13. package/utils/tests/mfeHistory.test.js +53 -0
  14. package/utils/tests/mockGroupedTags.test.js +59 -0
  15. package/utils/tests/tagValidations.test.js +63 -0
  16. package/v2Components/CapTagList/TagFallbackPanel.js +126 -0
  17. package/v2Components/CapTagList/constants.js +21 -0
  18. package/v2Components/CapTagList/index.js +238 -58
  19. package/v2Components/CapTagList/messages.js +68 -0
  20. package/v2Components/CapTagList/style.scss +263 -1
  21. package/v2Components/CapTagList/tests/TagDescription.test.js +268 -0
  22. package/v2Components/CapTagList/tests/TagFallback.test.js +255 -0
  23. package/v2Components/CapTagList/utils.js +74 -0
  24. package/v2Components/ErrorInfoNote/ErrorInfoNote.test.js +53 -0
  25. package/v2Components/ErrorInfoNote/index.js +33 -11
  26. package/v2Components/ErrorInfoNote/messages.js +4 -0
  27. package/v2Components/ErrorInfoNote/style.scss +4 -0
  28. package/v2Components/ErrorInfoNote/utils.js +3 -0
  29. package/v2Components/FormBuilder/Classic.js +29 -16
  30. package/v2Components/FormBuilder/Functional/channels/mobilepush/config.js +1 -0
  31. package/v2Components/FormBuilder/Functional/channels/mobilepush/getEditorErrorDescriptor.js +1 -1
  32. package/v2Components/FormBuilder/Functional/channels/mobilepush/tests/validate.test.js +69 -0
  33. package/v2Components/FormBuilder/Functional/channels/mobilepush/validate.js +4 -4
  34. package/v2Components/FormBuilder/Functional/channels/sms/getEditorErrorDescriptor.js +3 -0
  35. package/v2Components/FormBuilder/Functional/channels/sms/tests/getEditorErrorDescriptor.test.js +17 -0
  36. package/v2Components/FormBuilder/Functional/channels/sms/tests/validate.test.js +18 -0
  37. package/v2Components/FormBuilder/Functional/channels/sms/validate.js +3 -1
  38. package/v2Components/FormBuilder/Functional/renderers/mpushRenderers.js +3 -0
  39. package/v2Components/FormBuilder/Functional/renderers/smsRenderers.js +5 -2
  40. package/v2Components/FormBuilder/Functional/tests/mpushRenderers.test.js +22 -0
  41. package/v2Components/FormBuilder/Functional/tests/smsRenderers.test.js +1 -1
  42. package/v2Components/HighlightedTextArea/MessageTextArea.js +16 -0
  43. package/v2Components/HighlightedTextArea/constants.js +25 -0
  44. package/v2Components/HighlightedTextArea/index.js +148 -0
  45. package/v2Components/HighlightedTextArea/messages.js +18 -0
  46. package/v2Components/HighlightedTextArea/smsCounter.js +11 -0
  47. package/v2Components/HighlightedTextArea/style.scss +105 -0
  48. package/v2Components/HighlightedTextArea/tests/HighlightedTextArea.test.js +97 -0
  49. package/v2Components/HighlightedTextArea/utils.js +17 -0
  50. package/v2Components/HtmlEditor/components/ValidationTabs/__tests__/ValidationTabs.test.js +42 -0
  51. package/v2Components/HtmlEditor/components/ValidationTabs/_validationTabs.scss +4 -0
  52. package/v2Components/HtmlEditor/components/ValidationTabs/index.js +17 -3
  53. package/v2Components/HtmlEditor/components/ValidationTabs/messages.js +4 -0
  54. package/v2Components/HtmlEditor/utils/__tests__/renderIssueMessage.test.js +32 -40
  55. package/v2Components/HtmlEditor/utils/renderIssueMessage.js +31 -24
  56. package/v2Components/HtmlEditor/utils/renderLegacyIssueMessage.js +56 -0
  57. package/v2Components/HtmlEditor/utils/validationConstants.js +2 -0
  58. package/v2Components/LiquidGenerator/constants.js +5 -0
  59. package/v2Components/LiquidGenerator/index.js +154 -0
  60. package/v2Components/LiquidGenerator/messages.js +50 -0
  61. package/v2Components/LiquidGenerator/style.scss +160 -0
  62. package/v2Components/LiquidGenerator/tests/LiquidGenerator.test.js +107 -0
  63. package/v2Components/LiquidGenerator/utils.js +42 -0
  64. package/v2Components/NavigationBar/index.js +2 -2
  65. package/v2Components/NavigationBar/mfeModuleHeader.config.js +15 -0
  66. package/v2Components/NavigationBar/tests/mfeModuleHeader.config.test.js +19 -0
  67. package/v2Containers/Cap/index.js +14 -10
  68. package/v2Containers/Cap/messages.js +4 -0
  69. package/v2Containers/Cap/mockdata/groupedStandardTags.json +17386 -0
  70. package/v2Containers/Cap/tests/__snapshots__/index.test.js.snap +1 -0
  71. package/v2Containers/Facebook/Advertisement/index.js +2 -1
  72. package/v2Containers/InApp/index.js +4 -1
  73. package/v2Containers/Line/Container/ImageCarousel/tests/__snapshots__/content.test.js.snap +3 -0
  74. package/v2Containers/Line/Container/ImageCarousel/tests/__snapshots__/index.test.js.snap +2 -0
  75. package/v2Containers/Line/Container/Text/index.js +5 -2
  76. package/v2Containers/Line/Container/Wrapper/tests/__snapshots__/index.test.js.snap +177 -125
  77. package/v2Containers/Line/Container/tests/__snapshots__/index.test.js.snap +18 -0
  78. package/v2Containers/MobilePushNew/index.js +4 -1
  79. package/v2Containers/Rcs/index.js +10 -2
  80. package/v2Containers/Rcs/tests/__snapshots__/index.test.js.snap +1258 -1034
  81. package/v2Containers/Sms/Create/index.js +5 -1
  82. package/v2Containers/Sms/Edit/index.js +5 -1
  83. package/v2Containers/SmsTrai/Create/tests/__snapshots__/index.test.js.snap +4 -0
  84. package/v2Containers/SmsTrai/Edit/index.js +13 -5
  85. package/v2Containers/SmsTrai/Edit/tests/__snapshots__/index.test.js.snap +15 -0
  86. package/v2Containers/TagList/index.js +6 -0
  87. package/v2Containers/TagList/tests/TagList.test.js +10 -4
  88. package/v2Containers/Viber/index.js +5 -2
  89. package/v2Containers/WebPush/Create/tests/contentValidity.test.js +1 -0
  90. package/v2Containers/WebPush/Create/tests/stayOpenOnSave.test.js +1 -0
  91. package/v2Containers/WebPush/Create/utils/validation.js +6 -0
  92. package/v2Containers/WebPush/Create/utils/validation.test.js +50 -0
  93. package/v2Containers/Whatsapp/index.js +11 -6
  94. package/v2Containers/Whatsapp/tests/__snapshots__/index.test.js.snap +2 -2
  95. package/v2Containers/Zalo/index.js +4 -1
package/config/app.js CHANGED
@@ -17,10 +17,12 @@ const config = {
17
17
  dashboard_url_v2: '/v2',
18
18
  subscription_api_endpoint: '/arya/api/v1/org-settings/subscription',
19
19
  exports_api_endpoint: '/arya/api/v1/export/data',
20
+ gateways_api_endpoint: '/arya/api/v1/creatives/gateways',
20
21
  accountConfig: (strs, accountId) => `${window.location.origin}/org/config/AccountAdd?q=a&channelId=2&accountId=${accountId}&edit=1`,
21
22
  },
22
23
  development: {
23
24
  api_endpoint: 'https://crm-nightly-new.cc.capillarytech.com/arya/api/v1/creatives',
25
+ gateways_api_endpoint: 'https://crm-nightly-new.cc.capillarytech.com/arya/api/v1/creatives/gateways',
24
26
  campaigns_api_endpoint: 'https://crm-nightly-new.cc.capillarytech.com/iris/v2/campaigns',
25
27
  campaigns_api_org_endpoint: 'https://crm-nightly-new.cc.capillarytech.com/iris/v2/org/campaign',
26
28
  auth_endpoint: 'https://crm-nightly-new.cc.capillarytech.com/arya/api/v1/auth',
@@ -160,6 +160,9 @@ export const UNSUBSCRIBE_TAG = 'unsubscribe';
160
160
  export const UNSUBSCRIBE_TAG_REGEX = new RegExp(`\\{\\{\\s*${UNSUBSCRIBE_TAG}\\s*\\}\\}`);
161
161
  /** Matches {{ ... }} and captures the inner tag content (for scanning content for tags). */
162
162
  export const TAG_CONTENT_REGEX = /{{([^}]+)}}/g;
163
+ // `default:` filter inside a tag, and the same filter with a quoted value e.g. default: 'x'
164
+ export const DEFAULT_FILTER_REGEX = /^\s*default\s*:/;
165
+ export const QUOTED_DEFAULT_REGEX = /^\s*default\s*:\s*('[^']*'|"[^"]*")\s*$/;
163
166
  export const ENTRY_TRIGGER_TAG_REGEX = /\bentryTrigger\.\w+(?:\.\w+)?(?:\(\w+\))?/g;
164
167
  /** Strips characters not allowed in a downloaded file name, keeping alphanumerics, `-`, `_` and spaces. */
165
168
  export const SAFE_FILE_NAME_REGEX = /[^a-zA-Z0-9-_ ]/g;
@@ -239,3 +242,11 @@ export const HTTP_METHODS = Object.freeze({
239
242
  PATCH: 'PATCH',
240
243
  DELETE: 'DELETE',
241
244
  });
245
+
246
+ // Temporary org feature flag for the personalization tags revamp (CAP-214027); remove once the backend support is released.
247
+ export const ENABLE_TAGS_REVAMP = 'ENABLE_TAGS_REVAMP';
248
+
249
+ // Development-only: local storage key that turns on the mock of the regrouped standard tags (see utils/mockGroupedTags.js)
250
+ export const MOCK_GROUPED_TAGS_STORAGE_KEY = 'MOCK_GROUPED_TAGS';
251
+ export const TIMELINE_CONTEXT = 'timeline';
252
+ export const OUTBOUND_CONTEXT = 'outbound';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capillarytech/creatives-library",
3
3
  "author": "meharaj",
4
- "version": "9.2.3",
4
+ "version": "9.2.4-beta.sprint-cap-214027-tags-ux-changes.48",
5
5
  "description": "Capillary creatives ui",
6
6
  "main": "./index.js",
7
7
  "module": "./index.es.js",
package/services/api.js CHANGED
@@ -13,6 +13,7 @@ import * as API from '../utils/ApiCaller';
13
13
  import { addBaseToTemplate, transformCustomFieldsData } from '../utils/commonUtils';
14
14
  import { EMAIL, SMS, TRANSACTION } from '../v2Containers/CreativesContainer/constants';
15
15
  import { HTTP_METHODS } from '../constants/unified';
16
+ import { isMockGroupedTagsEnabled, getMockStandardTags, buildMockTagsResponse } from '../utils/mockGroupedTags';
16
17
  let API_ENDPOINT = config.development.api_endpoint;
17
18
  let EXPORT_API_ENDPOINT = config.development.exports_api_endpoint;
18
19
  let CAMPAIGNS_API_ENDPOINT = config.development.campaigns_api_endpoint;
@@ -462,6 +463,31 @@ export const getUserList = () => {
462
463
  return API.get(url);// request(url, getAPICallObject('GET'));
463
464
  };
464
465
 
466
+ const requestTagMeta = async (queryParams) => {
467
+ const url = `${API_ENDPOINT}/meta/${queryParams.type}?query=${JSON.stringify(queryParams)}`;
468
+ const useMockTags = queryParams.type === 'TAG' && isMockGroupedTagsEnabled();
469
+ let result;
470
+ try {
471
+ result = await request(url, getAPICallObject('GET'));// request(url, getAPICallObject('GET'));
472
+ } catch (error) {
473
+ if (!useMockTags) throw error;
474
+ }
475
+ if (useMockTags) {
476
+ // development only: the regrouped standard tags are not deployed yet (see utils/mockGroupedTags.js)
477
+ if (result?.response?.metaEntities) {
478
+ result.response.metaEntities.standard = await getMockStandardTags(queryParams);
479
+ } else {
480
+ result = await buildMockTagsResponse(queryParams);
481
+ }
482
+ }
483
+ const customFields = get(result, 'response.metaEntities.custom', {});
484
+ if (customFields && Object.keys(customFields)?.length > 0) {
485
+ const transformedData = transformCustomFieldsData(customFields);
486
+ result.response.metaEntities.custom = transformedData;
487
+ }
488
+ return result;
489
+ };
490
+
465
491
  export const fetchSchemaForEntity = async ({queryParams}) => {
466
492
  if (queryParams.version === "v2" && queryParams.type === "LAYOUT") {
467
493
  const schema = getSchema(queryParams.layout);
@@ -470,14 +496,7 @@ export const fetchSchemaForEntity = async ({queryParams}) => {
470
496
  console.error(err);
471
497
  });
472
498
  }
473
- const url = `${API_ENDPOINT}/meta/${queryParams.type}?query=${JSON.stringify(queryParams)}`;
474
- const result = await request(url, getAPICallObject('GET'));// request(url, getAPICallObject('GET'));
475
- const customFields = get(result, 'response.metaEntities.custom', {});
476
- if (customFields && Object.keys(customFields)?.length > 0) {
477
- const transformedData = transformCustomFieldsData(customFields);
478
- result.response.metaEntities.custom = transformedData;
479
- }
480
- return result;
499
+ return requestTagMeta(queryParams);
481
500
  };
482
501
 
483
502
  export const fetchWeCrmAccounts = (sourceName) => {
@@ -317,6 +317,7 @@
317
317
  "creatives.componentsV2.TopBar.profile": "Profile",
318
318
  "creatives.componentsV2.TopBar.settings": "Settings",
319
319
  "creatives.componentsV2.unbalanacedCurlyBraces": "Invalid label, please close all curly braces",
320
+ "creatives.componentsV2.unquotedTagDefaultValue": "Invalid label, default value must be within quotes",
320
321
  "creatives.componentsv2.MobilePushPreviewV2.header": "This is the MobilePushPreviewV2 component !",
321
322
  "creatives.containers.Assets.Gallery.alphabetically": "Alphabetically",
322
323
  "creatives.containers.Assets.Gallery.assetDeleteFailed": "Image deletion failed.",
@@ -316,6 +316,7 @@
316
316
  "creatives.componentsV2.TopBar.profile": "",
317
317
  "creatives.componentsV2.TopBar.settings": "",
318
318
  "creatives.componentsV2.unbalanacedCurlyBraces": "",
319
+ "creatives.componentsV2.unquotedTagDefaultValue": "",
319
320
  "creatives.componentsv2.MobilePushPreviewV2.header": "",
320
321
  "creatives.containers.Assets.Gallery.alphabetically": "",
321
322
  "creatives.containers.Assets.Gallery.assetDeleteFailed": "",
@@ -316,6 +316,7 @@
316
316
  "creatives.componentsV2.TopBar.profile": "",
317
317
  "creatives.componentsV2.TopBar.settings": "",
318
318
  "creatives.componentsV2.unbalanacedCurlyBraces": "",
319
+ "creatives.componentsV2.unquotedTagDefaultValue": "",
319
320
  "creatives.componentsv2.MobilePushPreviewV2.header": "",
320
321
  "creatives.containers.Assets.Gallery.alphabetically": "",
321
322
  "creatives.containers.Assets.Gallery.assetDeleteFailed": "",
package/utils/common.js CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  ENABLE_NEW_FORMBUILDER_SMS,
29
29
  ENABLE_NEW_FORMBUILDER_MPUSH,
30
30
  SUPPORT_ENGAGEMENT_MODULE,
31
+ ENABLE_TAGS_REVAMP,
31
32
  } from '../constants/unified';
32
33
  import { apiMessageFormatHandler } from './commonUtils';
33
34
 
@@ -114,6 +115,12 @@ export const hasJPLocaleHideFeatureEnabled = Auth.hasFeatureAccess.bind(
114
115
  JP_LOCALE_HIDE_FEATURE,
115
116
  );
116
117
 
118
+ export const hasTagsRevampEnabled = Auth.hasFeatureAccess.bind(
119
+ null,
120
+ ENABLE_TAGS_REVAMP,
121
+ );
122
+
123
+
117
124
  export const hasWechatFeatureEnabled = Auth.hasFeatureAccess.bind(
118
125
  null,
119
126
  ENABLE_WECHAT,
package/utils/history.js CHANGED
@@ -1,8 +1,14 @@
1
1
  import { createBrowserHistory } from 'history';
2
2
  import pathConfig from '../config/path';
3
+ import rebaseHistory from './mfeHistory';
3
4
 
4
- const history = createBrowserHistory({
5
- basename: pathConfig.publicPath,
6
- });
5
+ // Local development uses the same prefix handling as the MFE build, so addresses registered
6
+ // with registerOwnedPath (served outside the public path) work locally too. Production
7
+ // standalone is the v1 build, which keeps the plain basename history.
8
+ const history = process.env.NODE_ENV === 'development'
9
+ ? rebaseHistory(createBrowserHistory(), pathConfig.publicPath)
10
+ : createBrowserHistory({
11
+ basename: pathConfig.publicPath,
12
+ });
7
13
 
8
14
  export default history;
@@ -11,10 +11,24 @@
11
11
  * while delegating all actual navigation to the shared instance. Net effect: relative
12
12
  * routing keeps working unchanged, and navigation still flows through the single shared
13
13
  * history. Standalone (no host history) is unaffected; the remote keeps creating its own.
14
+ *
15
+ * Top-level addresses the app serves outside its prefix are registered with registerOwnedPath
16
+ * (by app-only code); they are left as they are both ways: never prefixed on navigation, and
17
+ * never stripped when read (stripBase only strips the prefix).
14
18
  */
19
+ const ownedPaths = new Set();
20
+
21
+ export const registerOwnedPath = (path) => {
22
+ ownedPaths.add(String(path || '').replace(/\/+$/, ''));
23
+ };
24
+
25
+ const isOwnedPath = (pathname = '') => [...ownedPaths]
26
+ .some((owned) => owned && (pathname === owned || pathname.startsWith(`${owned}/`)));
27
+
15
28
  const addBase = (base, to) => {
16
29
  if (typeof to === 'string') {
17
30
  if (!to.startsWith('/')) return to; // already relative to current location
31
+ if (isOwnedPath(to.split(/[?#]/)[0])) return to;
18
32
  return to === '/' ? base : `${base}${to}`;
19
33
  }
20
34
  if (to && typeof to === 'object') {
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Development-only mock of the regrouped standard tags (CAP-214027).
3
+ *
4
+ * The grouping lives in the cc-crm-bootstrap seed, which cannot be deployed to the shared environments yet.
5
+ * On the local dev server the standard tags of GET /meta/TAG are replaced by the tags of
6
+ * groupedStandardTags.json (generated from the seed by docs/personalization-tags-revamp/tools/make_mock_tags.py).
7
+ * Custom, extended and loyalty tags stay real when the API answers. If the API does not answer, the mock alone
8
+ * is used. `localStorage.setItem('MOCK_GROUPED_TAGS', 'false')` turns the mock off.
9
+ */
10
+ import { MOCK_GROUPED_TAGS_STORAGE_KEY, TIMELINE_CONTEXT, OUTBOUND_CONTEXT } from '../constants/unified';
11
+
12
+ export const isMockGroupedTagsEnabled = () => {
13
+ if (process.env.NODE_ENV !== 'development') return false;
14
+ try {
15
+ return window.localStorage.getItem(MOCK_GROUPED_TAGS_STORAGE_KEY) !== 'false';
16
+ } catch (error) {
17
+ return true;
18
+ }
19
+ };
20
+
21
+ // Same filter the tag API applies: the tag must support the requested context and layout
22
+ export const filterTagsBySupportedModules = (tags = [], context = '', layout = '') => {
23
+ const requestedContext = context.toLowerCase() === TIMELINE_CONTEXT ? OUTBOUND_CONTEXT : context.toLowerCase();
24
+ const requestedLayout = layout.toLowerCase();
25
+ return tags.filter((tag) => tag?.definition?.supportedModules?.some((moduleInfo) => (
26
+ moduleInfo?.context?.toLowerCase() === requestedContext && moduleInfo?.layout?.toLowerCase() === requestedLayout
27
+ )));
28
+ };
29
+
30
+ export const getMockStandardTags = async ({ context, layout }) => {
31
+ // loaded on demand so that the mock never ends up in the main bundle
32
+ const { default: mockTags } = await import(/* webpackChunkName: "mock-grouped-tags" */ '../v2Containers/Cap/mockdata/groupedStandardTags.json');
33
+ return filterTagsBySupportedModules(mockTags, context, layout);
34
+ };
35
+
36
+ // What the tag API returns when only the standard tags are available
37
+ export const buildMockTagsResponse = async (queryParams) => ({
38
+ success: true,
39
+ response: {
40
+ metaEntities: {
41
+ standard: await getMockStandardTags(queryParams), custom: {}, extended: {}, loyaltyTags: {},
42
+ },
43
+ },
44
+ });
@@ -8,7 +8,16 @@
8
8
 
9
9
  import lodashForEach from 'lodash/forEach';
10
10
  import lodashCloneDeep from 'lodash/cloneDeep';
11
- import { ENTRY_TRIGGER_TAG_REGEX, SKIP_TAGS_REGEX_GROUPS, TAG_CONTENT_REGEX, UNSUBSCRIBE_TAG, UNSUBSCRIBE_TAG_REGEX } from '../constants/unified';
11
+ import {
12
+ ENTRY_TRIGGER_TAG_REGEX,
13
+ SKIP_TAGS_REGEX_GROUPS,
14
+ TAG_CONTENT_REGEX,
15
+ UNSUBSCRIBE_TAG,
16
+ UNSUBSCRIBE_TAG_REGEX,
17
+ DEFAULT_FILTER_REGEX,
18
+ QUOTED_DEFAULT_REGEX,
19
+ } from '../constants/unified';
20
+ import { hasTagsRevampEnabled } from './common';
12
21
 
13
22
  const DEFAULT = 'default';
14
23
  const SUBTAGS = 'subtags';
@@ -89,9 +98,9 @@ export const validateTagsCore = ({
89
98
  }
90
99
 
91
100
  response.isBraceError = !validateIfTagClosed(contentForBraceCheck);
92
- if (response.isBraceError) {
93
- response.valid = false;
94
- } else if (response?.missingTags?.length > 0) {
101
+ // the `default:` filter check belongs to the tags revamp (fallback), so it is skipped when the revamp is off
102
+ response.isDefaultQuoteError = hasTagsRevampEnabled() && !response.isBraceError && hasUnquotedTagDefault(contentForBraceCheck);
103
+ if (response.isBraceError || response.isDefaultQuoteError || response?.missingTags?.length > 0) {
95
104
  response.valid = false;
96
105
  }
97
106
  return response;
@@ -203,6 +212,30 @@ export const validateIfTagClosed = (value) => {
203
212
  return (l1 == l2 && l2 == l3 && l1 == l3);
204
213
  };
205
214
 
215
+ // Splits a tag body into filters on `|` outside quotes (Liquid has no escaped quotes).
216
+ const splitTagFilters = (body) => {
217
+ const filters = [''];
218
+ let quote = null;
219
+ [...body].forEach((char) => {
220
+ if (quote) {
221
+ if (char === quote) quote = null;
222
+ } else if (char === "'" || char === '"') {
223
+ quote = char;
224
+ } else if (char === '|') {
225
+ filters.push('');
226
+ return;
227
+ }
228
+ filters[filters.length - 1] += char;
229
+ });
230
+ return filters;
231
+ };
232
+
233
+ // `default:` inside a {{ }} tag must be followed by a quoted value, e.g. {{tag | default: 'x'}}
234
+ export const hasUnquotedTagDefault = (value = '') =>
235
+ (String(value).match(/{{.*?}}/g) || []).some((tag) => splitTagFilters(tag.slice(2, -2))
236
+ .slice(1)
237
+ .some((filter) => DEFAULT_FILTER_REGEX.test(filter) && !QUOTED_DEFAULT_REGEX.test(filter)));
238
+
206
239
  //replaces encoded string with their respective characters
207
240
  export const preprocessHtml = (content) => {
208
241
  const replacements = {
@@ -0,0 +1,53 @@
1
+ import { createMemoryHistory } from 'history';
2
+ import rebaseHistory, { registerOwnedPath } from '../mfeHistory';
3
+
4
+ const OWNED = '/own-page/ui';
5
+
6
+ const setup = (initial = '/creatives/ui/v2') => {
7
+ const shared = createMemoryHistory({ initialEntries: [initial] });
8
+ return { shared, history: rebaseHistory(shared, '/creatives/ui') };
9
+ };
10
+
11
+ describe('rebaseHistory', () => {
12
+ it('strips the prefix when reading and adds it when navigating', () => {
13
+ const { shared, history } = setup();
14
+ expect(history.location.pathname).toBe('/v2');
15
+ history.push('/v2/loyalty');
16
+ expect(shared.location.pathname).toBe('/creatives/ui/v2/loyalty');
17
+ });
18
+
19
+ it('prefixes every path until an address is registered as owned', () => {
20
+ const { shared, history } = setup();
21
+ history.push('/other-page/ui');
22
+ expect(shared.location.pathname).toBe('/creatives/ui/other-page/ui');
23
+ });
24
+
25
+ it('leaves a registered address outside the prefix as it is, both ways', () => {
26
+ registerOwnedPath(`${OWNED}/`);
27
+ const { shared, history } = setup(`${OWNED}/vendors/g-1`);
28
+ expect(history.location.pathname).toBe(`${OWNED}/vendors/g-1`);
29
+ history.push(`${OWNED}?channel=WHATSAPP`);
30
+ expect(shared.location.pathname).toBe(OWNED);
31
+ expect(shared.location.search).toBe('?channel=WHATSAPP');
32
+ history.replace({ pathname: `${OWNED}/vendors/new`, search: '?channel=SMS' });
33
+ expect(shared.location.pathname).toBe(`${OWNED}/vendors/new`);
34
+ expect(history.createHref({ pathname: OWNED })).toBe(OWNED);
35
+ });
36
+
37
+ it('still prefixes paths that only look like an owned address', () => {
38
+ registerOwnedPath(OWNED);
39
+ const { shared, history } = setup();
40
+ history.push(`${OWNED}x`);
41
+ expect(shared.location.pathname).toBe(`/creatives/ui${OWNED}x`);
42
+ });
43
+
44
+ it('tells listeners the location without the prefix', () => {
45
+ registerOwnedPath(OWNED);
46
+ const { history } = setup();
47
+ const listener = jest.fn();
48
+ history.listen(listener);
49
+ history.push('/v2');
50
+ history.push(OWNED);
51
+ expect(listener.mock.calls.map(([location]) => location.pathname)).toEqual(['/v2', OWNED]);
52
+ });
53
+ });
@@ -0,0 +1,59 @@
1
+ import { filterTagsBySupportedModules, isMockGroupedTagsEnabled, buildMockTagsResponse } from '../mockGroupedTags';
2
+ import mockTags from '../../v2Containers/Cap/mockdata/groupedStandardTags.json';
3
+
4
+ const tag = (value, modules) => ({ definition: { value, supportedModules: modules } });
5
+
6
+ describe('filterTagsBySupportedModules', () => {
7
+ const tags = [
8
+ tag('sms_outbound', [{ context: 'outbound', layout: 'sms' }]),
9
+ tag('email_outbound', [{ context: 'outbound', layout: 'email' }]),
10
+ tag('sms_journey', [{ context: 'journey', layout: 'sms' }]),
11
+ tag('no_modules'),
12
+ ];
13
+
14
+ it('keeps the tags that support both the context and the layout', () => {
15
+ expect(filterTagsBySupportedModules(tags, 'outbound', 'sms').map((t) => t.definition.value)).toEqual(['sms_outbound']);
16
+ });
17
+
18
+ it('is case insensitive and treats the timeline context as outbound', () => {
19
+ expect(filterTagsBySupportedModules(tags, 'Timeline', 'SMS').map((t) => t.definition.value)).toEqual(['sms_outbound']);
20
+ });
21
+ });
22
+
23
+ describe('isMockGroupedTagsEnabled', () => {
24
+ afterEach(() => window.localStorage.clear());
25
+
26
+ it('stays off outside the development build', () => {
27
+ // jest runs with NODE_ENV=test
28
+ expect(isMockGroupedTagsEnabled()).toBe(false);
29
+ });
30
+
31
+ it('is on in the development build unless the key is "false"', () => {
32
+ const original = process.env.NODE_ENV;
33
+ process.env.NODE_ENV = 'development';
34
+ try {
35
+ expect(isMockGroupedTagsEnabled()).toBe(true);
36
+ window.localStorage.setItem('MOCK_GROUPED_TAGS', 'false');
37
+ expect(isMockGroupedTagsEnabled()).toBe(false);
38
+ } finally {
39
+ process.env.NODE_ENV = original;
40
+ }
41
+ });
42
+ });
43
+
44
+ describe('groupedStandardTags mock', () => {
45
+ it('only holds active tag documents that carry a definition value', () => {
46
+ expect(mockTags.length).toBeGreaterThan(0);
47
+ expect(mockTags.every((doc) => doc.type === 'TAG' && doc.isActive && doc.definition?.value)).toBe(true);
48
+ });
49
+ });
50
+
51
+ describe('buildMockTagsResponse', () => {
52
+ it('answers like the tag API with only the standard tags filled', async () => {
53
+ const response = await buildMockTagsResponse({ context: 'outbound', layout: 'sms' });
54
+ expect(response.success).toBe(true);
55
+ const { standard, custom, extended, loyaltyTags } = response.response.metaEntities;
56
+ expect(standard.length).toBeGreaterThan(0);
57
+ expect([custom, extended, loyaltyTags]).toEqual([{}, {}, {}]);
58
+ });
59
+ });
@@ -1,4 +1,14 @@
1
1
  import '@testing-library/jest-dom';
2
+ import { hasTagsRevampEnabled } from '../common';
3
+
4
+ jest.mock('../common', () => ({
5
+ ...jest.requireActual('../common'),
6
+ hasTagsRevampEnabled: jest.fn(),
7
+ }));
8
+
9
+ beforeEach(() => {
10
+ hasTagsRevampEnabled.mockReturnValue(true);
11
+ });
2
12
  import {
3
13
  hasUnsubscribeTag,
4
14
  validateTagsCore,
@@ -11,6 +21,7 @@ import {
11
21
  skipTags,
12
22
  checkIfSupportedTag,
13
23
  transformInjectedTags,
24
+ hasUnquotedTagDefault,
14
25
  } from '../tagValidations';
15
26
  import { containsBase64Images } from '../content';
16
27
 
@@ -193,6 +204,58 @@ describe("check if curly brackets are balanced", () => {
193
204
  })
194
205
  })
195
206
 
207
+ describe('hasUnquotedTagDefault', () => {
208
+ it('allows tags without default and defaults within quotes', () => {
209
+ expect(hasUnquotedTagDefault('{{badge_description}}')).toBe(false);
210
+ expect(hasUnquotedTagDefault("{{badge_description | default: ''}}")).toBe(false);
211
+ expect(hasUnquotedTagDefault("{{badge_description | default: 'Rafeeq'}}")).toBe(false);
212
+ expect(hasUnquotedTagDefault('{{badge_description | default: "Rafeeq\'s"}}')).toBe(false);
213
+ expect(hasUnquotedTagDefault("Hi {{a|default:' '}} {{b}} plain text")).toBe(false);
214
+ });
215
+
216
+ it('flags default with missing or unquoted value', () => {
217
+ expect(hasUnquotedTagDefault('{{badge_description | default: }}')).toBe(true);
218
+ expect(hasUnquotedTagDefault('{{badge_description | default: Rafeeq}}')).toBe(true);
219
+ expect(hasUnquotedTagDefault("{{badge_description | default: 'Rafeeq}}")).toBe(true);
220
+ expect(hasUnquotedTagDefault("{{a}} {{b | default: 'x' y}}")).toBe(true);
221
+ });
222
+
223
+ it('ignores pipes inside quotes and allows chained filters', () => {
224
+ expect(hasUnquotedTagDefault("{{name | replace: '| default:', 'x'}}")).toBe(false);
225
+ expect(hasUnquotedTagDefault("{{name | default: 'a | default: b'}}")).toBe(false);
226
+ expect(hasUnquotedTagDefault("{{name | default: 'a|b'}}")).toBe(false);
227
+ expect(hasUnquotedTagDefault("{{name | default: 'x' | append: '!'}}")).toBe(false);
228
+ expect(hasUnquotedTagDefault("{{name | append: 'x' | default: 'y'}}")).toBe(false);
229
+ });
230
+
231
+ it('rejects backslash-escaped quotes since Liquid has no escapes', () => {
232
+ expect(hasUnquotedTagDefault("{{name | default: 'it\\'s'}}")).toBe(true);
233
+ });
234
+ });
235
+
236
+ describe('validateTagsCore default quote check', () => {
237
+ const run = (content) => validateTagsCore({
238
+ contentForBraceCheck: content, contentForUnsubscribeScan: content, tags: null, currentModule: 'default', isFullMode: true,
239
+ });
240
+
241
+ it('marks unquoted default as invalid with isDefaultQuoteError', () => {
242
+ expect(run('{{name | default: Rafeeq}}')).toEqual(expect.objectContaining({ valid: false, isBraceError: false, isDefaultQuoteError: true }));
243
+ });
244
+
245
+ it('skips the default quote check when the tags revamp is disabled', () => {
246
+ hasTagsRevampEnabled.mockReturnValueOnce(false);
247
+ expect(run('{{name | default: Rafeeq}}')).toEqual(expect.objectContaining({ valid: true, isDefaultQuoteError: false }));
248
+ });
249
+
250
+ it('keeps quoted default valid', () => {
251
+ expect(run("{{name | default: 'Rafeeq'}}")).toEqual(expect.objectContaining({ valid: true, isDefaultQuoteError: false }));
252
+ });
253
+
254
+ it('reports only brace error when braces are not closed', () => {
255
+ expect(run('{{name | default: Rafeeq}')).toEqual(expect.objectContaining({ isBraceError: true, isDefaultQuoteError: false }));
256
+ });
257
+ });
258
+
196
259
  describe("validateTags", () => {
197
260
  const tagsParam = [
198
261
  {
@@ -0,0 +1,126 @@
1
+ /**
2
+ * TagFallbackPanel
3
+ *
4
+ * Shown in the tag list after a tag is clicked, to choose what is sent when the tag has no value.
5
+ */
6
+ import PropTypes from 'prop-types';
7
+ import React from 'react';
8
+ import CapButton from '@capillarytech/cap-ui-library/CapButton';
9
+ import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
10
+ import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
11
+ import CapInput from '@capillarytech/cap-ui-library/CapInput';
12
+ import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
13
+ import CapRadio from '@capillarytech/cap-ui-library/CapRadio';
14
+ import CapRadioGroup from '@capillarytech/cap-ui-library/CapRadioGroup';
15
+ import CapRow from '@capillarytech/cap-ui-library/CapRow';
16
+ import { injectIntl, intlShape } from 'react-intl';
17
+ import messages from './messages';
18
+ import { FALLBACK_OPTIONS } from './constants';
19
+ import { buildTagWithFallback, isValidFallbackValue } from './utils';
20
+
21
+ export class TagFallbackPanel extends React.Component {
22
+ constructor(props) {
23
+ super(props);
24
+ this.state = {
25
+ option: FALLBACK_OPTIONS.NONE,
26
+ fallbackValue: '',
27
+ };
28
+ }
29
+
30
+ onOptionChange = (e) => {
31
+ this.setState({ option: e.target.value });
32
+ };
33
+
34
+ onFallbackValueChange = (e) => {
35
+ this.setState({ fallbackValue: e.target.value });
36
+ };
37
+
38
+ getTagValue = () => {
39
+ const { option, fallbackValue } = this.state;
40
+ return buildTagWithFallback(this.props.tagKey, option, fallbackValue);
41
+ };
42
+
43
+ copyTag = () => {
44
+ navigator?.clipboard?.writeText(`{{${this.getTagValue()}}}`);
45
+ };
46
+
47
+ onInsert = () => {
48
+ this.props.onInsert(this.getTagValue());
49
+ };
50
+
51
+ render() {
52
+ const {
53
+ intl: { formatMessage }, tagName, parentName, description, onBack,
54
+ } = this.props;
55
+ const { option, fallbackValue } = this.state;
56
+ const isCustomValue = option === FALLBACK_OPTIONS.CUSTOM_VALUE;
57
+ const isFallbackValueInvalid = isCustomValue && !isValidFallbackValue(fallbackValue);
58
+ const isInsertDisabled = isCustomValue && (!fallbackValue.trim() || isFallbackValueInvalid);
59
+
60
+ return (
61
+ <CapRow className="tag-fallback-panel">
62
+ <CapRow className="tag-fallback-header">
63
+ <CapRow type="flex" align="middle" noWrap className="tag-fallback-title-row">
64
+ <CapIcon
65
+ type="back"
66
+ size="m"
67
+ className="tag-fallback-back"
68
+ aria-label={formatMessage(messages.back)}
69
+ onClick={onBack}
70
+ />
71
+ <CapHeading type="h4" className="tag-fallback-tag-name">{tagName}</CapHeading>
72
+ </CapRow>
73
+ {parentName ? <CapLabel type="label2" className="tag-fallback-group-name">{parentName}</CapLabel> : null}
74
+ </CapRow>
75
+ <CapRow className="tag-fallback-body">
76
+ {description ? <CapLabel type="label2" className="tag-fallback-description">{description}</CapLabel> : null}
77
+ <CapHeading type="h4" className="tag-fallback-heading">{formatMessage(messages.fallbackBehaviour)}</CapHeading>
78
+ <CapLabel type="label2" className="tag-fallback-subtext">{formatMessage(messages.fallbackBehaviourDesc)}</CapLabel>
79
+ <CapRadioGroup className="tag-fallback-options" value={option} onChange={this.onOptionChange}>
80
+ <CapRadio value={FALLBACK_OPTIONS.NONE}>{formatMessage(messages.dontSendMessage)}</CapRadio>
81
+ <CapRadio value={FALLBACK_OPTIONS.NULL_VALUE}>{formatMessage(messages.sendWithNullValue)}</CapRadio>
82
+ <CapRadio value={FALLBACK_OPTIONS.CUSTOM_VALUE}>{formatMessage(messages.fallbackValue)}</CapRadio>
83
+ </CapRadioGroup>
84
+ {isCustomValue && (
85
+ <CapInput
86
+ className="tag-fallback-input"
87
+ value={fallbackValue}
88
+ onChange={this.onFallbackValueChange}
89
+ placeholder={formatMessage(messages.fallbackValuePlaceholder)}
90
+ errorMessage={isFallbackValueInvalid ? formatMessage(messages.fallbackValueInvalid) : ''}
91
+ size="default"
92
+ />
93
+ )}
94
+ <CapLabel type="label2" className="tag-fallback-preview-label">{formatMessage(messages.addsToMessageAs)}</CapLabel>
95
+ <CapRow type="flex" align="middle" noWrap className="tag-fallback-preview-row">
96
+ <CapLabel className="tag-fallback-preview">{`{{${this.getTagValue()}}}`}</CapLabel>
97
+ <CapIcon
98
+ type="copy"
99
+ size="m"
100
+ className="tag-fallback-copy"
101
+ aria-label={formatMessage(messages.copy)}
102
+ onClick={this.copyTag}
103
+ />
104
+ </CapRow>
105
+ </CapRow>
106
+ <CapRow type="flex" justify="end" className="tag-fallback-footer">
107
+ <CapButton type="primary" disabled={isInsertDisabled} onClick={this.onInsert}>
108
+ {formatMessage(messages.insertTag)}
109
+ </CapButton>
110
+ </CapRow>
111
+ </CapRow>
112
+ );
113
+ }
114
+ }
115
+
116
+ TagFallbackPanel.propTypes = {
117
+ intl: intlShape.isRequired,
118
+ tagKey: PropTypes.string.isRequired,
119
+ tagName: PropTypes.node,
120
+ parentName: PropTypes.node,
121
+ description: PropTypes.string,
122
+ onBack: PropTypes.func.isRequired,
123
+ onInsert: PropTypes.func.isRequired,
124
+ };
125
+
126
+ export default injectIntl(TagFallbackPanel);
@@ -0,0 +1,21 @@
1
+ export const FALLBACK_OPTIONS = {
2
+ NONE: 'NONE',
3
+ NULL_VALUE: 'NULL_VALUE',
4
+ CUSTOM_VALUE: 'CUSTOM_VALUE',
5
+ };
6
+
7
+ // Tag descriptions are shown in a tooltip next to the tag, using the cap-ui-library info icon.
8
+ export const TAG_DESCRIPTION_ICON_TYPE = 'info';
9
+
10
+ // Separates the groups in the path shown under a tag in the search results, e.g. "Customer › Customer properties".
11
+ export const TAG_PATH_SEPARATOR = ' › ';
12
+
13
+ // Group arrows of the tag tree with the tags revamp
14
+ export const TREE_SWITCHER_ICON_TYPES = { EXPANDED: 'chevron-down', COLLAPSED: 'chevron-right' };
15
+
16
+ // Tabs of the Personalization list with the tags revamp
17
+ export const LIST_TABS = { TAGS: 'tags', LIQUID: 'liquid' };
18
+ export const LIQUID_TAB_ICON_TYPE = 'aira-nav';
19
+
20
+ // Width (px) of the tag list when it opens in a modal (Bee editor): the revamped list is wider than CapModal's default 324
21
+ export const TAG_LIST_MODAL_WIDTH = 460;