@washingtonpost/subs-de-inputs 0.2.0-canary.1 → 0.2.0
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/CHANGELOG.md +21 -0
- package/dist/interfaces/index.d.ts +2 -0
- package/dist/services/dataEnrichment.d.ts +2 -1
- package/dist/subs-de-inputs.esm.js +37 -23
- package/dist/subs-de-inputs.esm.js.map +1 -1
- package/package.json +3 -3
- package/dist/index.js +0 -8
- package/dist/subs-de-inputs.cjs.development.js +0 -237
- package/dist/subs-de-inputs.cjs.development.js.map +0 -1
- package/dist/subs-de-inputs.cjs.production.min.js +0 -2
- package/dist/subs-de-inputs.cjs.production.min.js.map +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Change Log
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file. See
|
|
4
|
+
[Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
|
+
|
|
6
|
+
**[0.2.0 - 2024-05-01]**:
|
|
7
|
+
* Adds `ingest()` function
|
|
8
|
+
* ESM build only
|
|
9
|
+
* Babel config to target recent browsers only
|
|
10
|
+
|
|
11
|
+
**[0.1.1 - 2024-04-30]**:
|
|
12
|
+
* Fix build by removing unused file
|
|
13
|
+
|
|
14
|
+
**[0.1.0 - 2024-04-25]**:
|
|
15
|
+
* Add initial `<DESelect />` component
|
|
16
|
+
|
|
17
|
+
**[0.0.2 - 2024-04-24]**:
|
|
18
|
+
* Fix build error
|
|
19
|
+
|
|
20
|
+
**[0.0.1 - 2024-04-09]**:
|
|
21
|
+
* Initial setup
|
|
@@ -8,8 +8,9 @@ export declare const ingest: IngestType;
|
|
|
8
8
|
declare type IngestType = ({ submitData: { fieldName, value }, source, }: {
|
|
9
9
|
submitData: {
|
|
10
10
|
fieldName: string;
|
|
11
|
-
value: string;
|
|
11
|
+
value: string[];
|
|
12
12
|
};
|
|
13
|
+
type: (typeof IngestType)[keyof typeof IngestType];
|
|
13
14
|
source: string;
|
|
14
15
|
}) => Promise<{
|
|
15
16
|
status: ResponseStatus;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getCookie, WPGeo, JSON_HEADERS, ResponseStatus, ENDPOINTS } from '@washingtonpost/subs-sdk';
|
|
2
2
|
import React, { useState, useEffect } from 'react';
|
|
3
3
|
import { Select, theme, styled } from '@washingtonpost/wpds-ui-kit';
|
|
4
|
+
import { useScript, ScriptStatus } from '@washingtonpost/subs-hooks';
|
|
4
5
|
|
|
5
6
|
const CollectionBehaviors = {
|
|
6
7
|
COLLECT: 'COLLECT',
|
|
@@ -22,7 +23,9 @@ const IngestResponseState = {
|
|
|
22
23
|
INVALID_ATTRIBUTE_DEFINITION: '105',
|
|
23
24
|
INVALID_META_DEFINITION: '106',
|
|
24
25
|
UNAUTHENTICATED: '107',
|
|
25
|
-
MISMATCHED_IDENTIFIER: '108'
|
|
26
|
+
MISMATCHED_IDENTIFIER: '108',
|
|
27
|
+
DISABLED_ATTRIBUTE_DEFINITION: '109',
|
|
28
|
+
DO_NOT_COLLECT: '110'
|
|
26
29
|
};
|
|
27
30
|
|
|
28
31
|
const hasRequiredPrivacyCookies = () => {
|
|
@@ -71,6 +74,7 @@ const ingest = async _ref2 => {
|
|
|
71
74
|
fieldName,
|
|
72
75
|
value
|
|
73
76
|
},
|
|
77
|
+
type,
|
|
74
78
|
source
|
|
75
79
|
} = _ref2;
|
|
76
80
|
const url = `${base}/ingest`;
|
|
@@ -92,7 +96,7 @@ const ingest = async _ref2 => {
|
|
|
92
96
|
const payload = {
|
|
93
97
|
jucid,
|
|
94
98
|
ga,
|
|
95
|
-
type
|
|
99
|
+
type,
|
|
96
100
|
wapo_login_id,
|
|
97
101
|
data: {
|
|
98
102
|
fieldName,
|
|
@@ -117,6 +121,7 @@ const ingest = async _ref2 => {
|
|
|
117
121
|
}
|
|
118
122
|
};
|
|
119
123
|
|
|
124
|
+
const scriptSrc = `${ENDPOINTS.staticAssets === 'https://subscribe.washingtonpost.com/static' ? 'https://www.washingtonpost.com/subscribe/static/' : ENDPOINTS.staticAssets}/de-utils/twpdeu.min.js`;
|
|
120
125
|
const DESelect = _ref => {
|
|
121
126
|
let {
|
|
122
127
|
source,
|
|
@@ -133,37 +138,38 @@ const DESelect = _ref => {
|
|
|
133
138
|
} = _ref;
|
|
134
139
|
const [config, setConfig] = useState(dataDictionaryConfig);
|
|
135
140
|
const [selected, setSelected] = useState('');
|
|
141
|
+
const scriptStatus = useScript(scriptSrc);
|
|
136
142
|
useEffect(() => {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
if (!config) {
|
|
144
|
-
(async () => {
|
|
145
|
-
// TODO: Switch to window.__twpdeu.getFieldConfigs
|
|
146
|
-
const config = await getAttributes({
|
|
143
|
+
const fetchConfig = async () => {
|
|
144
|
+
try {
|
|
145
|
+
var _window;
|
|
146
|
+
const config = await ((_window = window) === null || _window === void 0 || (_window = _window.__twpdeu) === null || _window === void 0 ? void 0 : _window.getFieldConfigs({
|
|
147
147
|
fieldName
|
|
148
|
-
});
|
|
149
|
-
if (
|
|
150
|
-
|
|
148
|
+
}));
|
|
149
|
+
if (config) {
|
|
150
|
+
setConfig(config[0]);
|
|
151
|
+
} else {
|
|
152
|
+
console.error('unable to get config', fieldName);
|
|
151
153
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
+
} catch (e) {
|
|
155
|
+
console.warn('unable to get config', fieldName, e);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
if (scriptStatus === ScriptStatus.READY && !(children || config)) {
|
|
159
|
+
fetchConfig();
|
|
154
160
|
}
|
|
155
|
-
}, []);
|
|
161
|
+
}, [scriptStatus]);
|
|
156
162
|
useEffect(() => {
|
|
157
|
-
|
|
158
|
-
|
|
163
|
+
const submitSelected = async () => {
|
|
164
|
+
try {
|
|
159
165
|
// TODO: Switch to window.__twpdeu.push
|
|
160
166
|
// TODO: Log to GA
|
|
161
|
-
// TODO: Differentiate between explicit and implicit inputs?
|
|
162
167
|
const result = await ingest({
|
|
163
168
|
submitData: {
|
|
164
169
|
fieldName,
|
|
165
|
-
value: selected
|
|
170
|
+
value: [selected]
|
|
166
171
|
},
|
|
172
|
+
type: config !== null && config !== void 0 && config.explicit ? IngestType.EXPLICIT : IngestType.IMPLICIT,
|
|
167
173
|
source
|
|
168
174
|
});
|
|
169
175
|
const isError = result ? result.status !== ResponseStatus.SUCCESS : true;
|
|
@@ -171,8 +177,16 @@ const DESelect = _ref => {
|
|
|
171
177
|
isFinished: true,
|
|
172
178
|
isError
|
|
173
179
|
});
|
|
180
|
+
} catch (e) {
|
|
181
|
+
onFinished({
|
|
182
|
+
isFinished: false,
|
|
183
|
+
isError: true
|
|
184
|
+
});
|
|
174
185
|
}
|
|
175
|
-
}
|
|
186
|
+
};
|
|
187
|
+
if (submit && selected) {
|
|
188
|
+
submitSelected();
|
|
189
|
+
}
|
|
176
190
|
}, [submit, selected]);
|
|
177
191
|
if (!(children || config)) {
|
|
178
192
|
return React.createElement("span", null, "loading");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subs-de-inputs.esm.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type: IngestType.EXPLICIT,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string;\n };\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue } from '../../interfaces';\nimport { getAttributes, ingest } from '../../services/dataEnrichment';\nimport { ResponseStatus } from '@washingtonpost/subs-sdk';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n useEffect(() => {\n if (children) {\n if (__DEV__) {\n console.debug('childen props', children);\n }\n return;\n }\n\n if (!config) {\n (async () => {\n // TODO: Switch to window.__twpdeu.getFieldConfigs\n const config = await getAttributes({ fieldName });\n if (__DEV__) {\n console.debug('config from API', config);\n }\n setConfig(config[0]);\n })();\n }\n }, []);\n\n useEffect(() => {\n (async () => {\n if (submit && selected) {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n // TODO: Differentiate between explicit and implicit inputs?\n const result = await ingest({\n submitData: { fieldName, value: selected },\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n }\n })();\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","AttributesState","SUCCESS","IngestType","EXPLICIT","IMPLICIT","IngestResponseState","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","_ref","fieldName","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","attributes","e","console","debug","ingest","_ref2","submitData","value","source","wapo_login_id","Error","attributeInfo","name","collection_behavior","jucid","localStorage","getItem","ga","payload","type","metadata","response","method","body","JSON","stringify","DESelect","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","useEffect","process","env","NODE_ENV","result","isError","isFinished","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","SelectWrapper","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","styled","boxSizing","display","marginBottom","flexDirection","padding"],"mappings":";;;;MAQaA,mBAAmB,GAAG;EACjCC,OAAO,EAAE,SAAS;EAClBC,cAAc,EAAE;;MAeLC,eAAe,GAAG;EAC7BC,OAAO,EAAE;;MAGEC,UAAU,GAAG;EACxBC,QAAQ,EAAE,UAAU;EACpBC,QAAQ,EAAE;;MAGCC,mBAAmB,GAAG;EACjCJ,OAAO,EAAE,KAAK;EACdK,YAAY,EAAE,KAAK;EACnBC,YAAY,EAAE,KAAK;EACnBC,kBAAkB,EAAE,KAAK;EACzBC,YAAY,EAAE,KAAK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BAACW,MAAM,CAACI,KAAK,QAAEpC,KAAK,IAAIS,MAAM,CAACxB,IAAI,CAAgB,EACnDoC,oBAACW,MAAM,CAACK,KAAK,OAAG,CACD,EACjBhB,oBAACW,MAAM,CAACM,OAAO;IACbC,GAAG,EAAE;MAAEC,MAAM,EAAEC,KAAK,CAACC,QAAQ,CAACC;KAAM;uBACnBlC,MAAM,CAACxB;KAEvBuC,MAAM,CAACoB,GAAG,CAAEhE,KAAK,IAChByC,oBAACW,MAAM,CAACa,IAAI;IAACjE,KAAK,EAAEA,KAAK,CAACK,IAAI;IAAE6D,GAAG,EAAElE,KAAK,CAACK;KACxCL,KAAK,CAACK,IAAI,CAEd,CAAC,CACa,CAEpB,CACW,CACA;AAEpB,CAAC;AAED,MAAM8C,aAAa,gBAAGgB,MAAM,CAAC,KAAK,EAAE;EAClCC,SAAS,EAAE,YAAY;EACvBC,OAAO,EAAE,MAAM;EACfC,YAAY,EAAE,MAAM;EACpBC,aAAa,EAAE,QAAQ;EACvB,UAAU,EAAE;IACVC,OAAO,EAAE;GACV;EACD,KAAK,EAAE;IAAEJ,SAAS,EAAE;;CACrB,CAAC;;;;"}
|
|
1
|
+
{"version":3,"file":"subs-de-inputs.esm.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n DISABLED_ATTRIBUTE_DEFINITION: '109',\n DO_NOT_COLLECT: '110',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n type,\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string[];\n };\n type: (typeof IngestType)[keyof typeof IngestType];\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue, IngestType } from '../../interfaces';\nimport { ingest } from '../../services/dataEnrichment';\nimport { ENDPOINTS, ResponseStatus } from '@washingtonpost/subs-sdk';\nimport { useScript, ScriptStatus } from '@washingtonpost/subs-hooks';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nconst scriptSrc = `${\n ENDPOINTS.staticAssets === 'https://subscribe.washingtonpost.com/static'\n ? 'https://www.washingtonpost.com/subscribe/static/'\n : ENDPOINTS.staticAssets\n}/de-utils/twpdeu.min.js`;\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n const scriptStatus = useScript(scriptSrc);\n\n useEffect(() => {\n const fetchConfig = async () => {\n try {\n const config = await window?.__twpdeu?.getFieldConfigs({ fieldName });\n if (config) {\n setConfig(config[0]);\n } else {\n console.error('unable to get config', fieldName);\n }\n } catch (e) {\n console.warn('unable to get config', fieldName, e);\n }\n };\n\n if (scriptStatus === ScriptStatus.READY && !(children || config)) {\n fetchConfig();\n }\n }, [scriptStatus]);\n\n useEffect(() => {\n const submitSelected = async () => {\n try {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n const result = await ingest({\n submitData: { fieldName, value: [selected] },\n type: config?.explicit ? IngestType.EXPLICIT : IngestType.IMPLICIT,\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n } catch (e) {\n onFinished({\n isFinished: false,\n isError: true,\n });\n }\n };\n\n if (submit && selected) {\n submitSelected();\n }\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","AttributesState","SUCCESS","IngestType","EXPLICIT","IMPLICIT","IngestResponseState","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","DISABLED_ATTRIBUTE_DEFINITION","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","_ref","fieldName","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","attributes","e","console","debug","ingest","_ref2","submitData","value","type","source","wapo_login_id","Error","attributeInfo","name","collection_behavior","jucid","localStorage","getItem","ga","payload","metadata","response","method","body","JSON","stringify","scriptSrc","staticAssets","DESelect","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","scriptStatus","useScript","useEffect","fetchConfig","_window","__twpdeu","getFieldConfigs","error","warn","ScriptStatus","READY","submitSelected","result","explicit","isError","isFinished","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","SelectWrapper","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","styled","boxSizing","display","marginBottom","flexDirection","padding"],"mappings":";;;;;MAQaA,mBAAmB,GAAG;EACjCC,OAAO,EAAE,SAAS;EAClBC,cAAc,EAAE;;MAeLC,eAAe,GAAG;EAC7BC,OAAO,EAAE;;MAGEC,UAAU,GAAG;EACxBC,QAAQ,EAAE,UAAU;EACpBC,QAAQ,EAAE;;MAGCC,mBAAmB,GAAG;EACjCJ,OAAO,EAAE,KAAK;EACdK,YAAY,EAAE,KAAK;EACnBC,YAAY,EAAE,KAAK;EACnBC,kBAAkB,EAAE,KAAK;EACzBC,YAAY,EAAE,KAAK;EACnBC,4BAA4B,EAAE,KAAK;EACnCC,uBAAuB,EAAE,KAAK;EAC9BC,eAAe,EAAE,KAAK;EACtBC,qBAAqB,EAAE,KAAK;EAC5BC,6BAA6B,EAAE,KAAK;EACpCf,cAAc,EAAE;;;MC3CLgB,yBAAyB,GAAGA;;EACvC,IAAI,OAAOC,MAAM,KAAK,WAAW,EAAE;IACjC,OAAO,KAAK;;EAGd,MAAMC,MAAM,GAAGC,SAAS,CAAC,QAAQ,CAAC;EAElC,MAAMC,WAAW,IAAAC,MAAA,GAAGC,KAAK,EAAE,cAAAD,MAAA,uBAAPA,MAAA,CAASE,YAAY;EAEzC,OAAO,CAAC,EAAEL,MAAM,IAAIE,WAAW,KAAK,IAAI,CAAC;AAC3C,CAAC;;ACED,MAAMI,IAAI,MAAMC,SAAS,CAACD,YAAY;AAEtC,MAAME,eAAe,GAAwB,EAAE;AAC/C,MAAaC,aAAa,GAAsB,MAAAC,IAAA;MAAO;IACrDC;GAGD,GAAAD,IAAA;EACC,IAAIF,eAAe,CAACG,SAAS,CAAC,EAAE;IAC9B,OAAOH,eAAe,CAACG,SAAS,CAAC;;EAGnC,MAAMC,U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AAK,IAAIS,MAAM,CAACzB,IAAI,CAAgB,EACnD8C,oBAACW,MAAM,CAACK,KAAK,OAAG,CACD,EACjBhB,oBAACW,MAAM,CAACM,OAAO;IACbC,GAAG,EAAE;MAAEC,MAAM,EAAEC,KAAK,CAACC,QAAQ,CAACC;KAAM;uBACnB3C,MAAM,CAACzB;KAEvBiD,MAAM,CAACoB,GAAG,CAAE3E,KAAK,IAChBoD,oBAACW,MAAM,CAACa,IAAI;IAAC5E,KAAK,EAAEA,KAAK,CAACM,IAAI;IAAEuE,GAAG,EAAE7E,KAAK,CAACM;KACxCN,KAAK,CAACM,IAAI,CAEd,CAAC,CACa,CAEpB,CACW,CACA;AAEpB,CAAC;AAED,MAAMwD,aAAa,gBAAGgB,MAAM,CAAC,KAAK,EAAE;EAClCC,SAAS,EAAE,YAAY;EACvBC,OAAO,EAAE,MAAM;EACfC,YAAY,EAAE,MAAM;EACpBC,aAAa,EAAE,QAAQ;EACvB,UAAU,EAAE;IACVC,OAAO,EAAE;GACV;EACD,KAAK,EAAE;IAAEJ,SAAS,EAAE;;CACrB,CAAC;;;;"}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.2.0
|
|
2
|
+
"version": "0.2.0",
|
|
3
3
|
"license": "UNLICENSED",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"typings": "dist/index.d.ts",
|
|
@@ -36,13 +36,13 @@
|
|
|
36
36
|
"name": "de-inputs: utils",
|
|
37
37
|
"path": "dist/subs-de-inputs.esm.js",
|
|
38
38
|
"import": "{ getAttributes, ingest }",
|
|
39
|
-
"limit": "
|
|
39
|
+
"limit": "1 KB"
|
|
40
40
|
},
|
|
41
41
|
{
|
|
42
42
|
"name": "de-inputs: DESelect",
|
|
43
43
|
"path": "dist/subs-de-inputs.esm.js",
|
|
44
44
|
"import": "{ DESelect }",
|
|
45
|
-
"limit": "
|
|
45
|
+
"limit": "2 KB"
|
|
46
46
|
}
|
|
47
47
|
],
|
|
48
48
|
"devDependencies": {
|
package/dist/index.js
DELETED
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
-
|
|
5
|
-
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
|
6
|
-
|
|
7
|
-
var subsSdk = require('@washingtonpost/subs-sdk');
|
|
8
|
-
var React = require('react');
|
|
9
|
-
var React__default = _interopDefault(React);
|
|
10
|
-
var wpdsUiKit = require('@washingtonpost/wpds-ui-kit');
|
|
11
|
-
|
|
12
|
-
const CollectionBehaviors = {
|
|
13
|
-
COLLECT: 'COLLECT',
|
|
14
|
-
DO_NOT_COLLECT: 'DO_NOT_COLLECT'
|
|
15
|
-
};
|
|
16
|
-
const AttributesState = {
|
|
17
|
-
SUCCESS: '100'
|
|
18
|
-
};
|
|
19
|
-
const IngestType = {
|
|
20
|
-
EXPLICIT: 'explicit',
|
|
21
|
-
IMPLICIT: 'implicit'
|
|
22
|
-
};
|
|
23
|
-
const IngestResponseState = {
|
|
24
|
-
SUCCESS: '100',
|
|
25
|
-
SYSTEM_ERROR: '101',
|
|
26
|
-
INVALID_TYPE: '102',
|
|
27
|
-
INVALID_IDENTIFIER: '103',
|
|
28
|
-
INVALID_DATA: '104',
|
|
29
|
-
INVALID_ATTRIBUTE_DEFINITION: '105',
|
|
30
|
-
INVALID_META_DEFINITION: '106',
|
|
31
|
-
UNAUTHENTICATED: '107',
|
|
32
|
-
MISMATCHED_IDENTIFIER: '108'
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
const hasRequiredPrivacyCookies = () => {
|
|
36
|
-
var _WPGeo;
|
|
37
|
-
if (typeof window === 'undefined') {
|
|
38
|
-
return false;
|
|
39
|
-
}
|
|
40
|
-
const wp_usp = subsSdk.getCookie('wp_usp');
|
|
41
|
-
const countryCode = (_WPGeo = subsSdk.WPGeo()) === null || _WPGeo === void 0 ? void 0 : _WPGeo.country_code;
|
|
42
|
-
return !!(wp_usp && countryCode === 'US');
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
const base = `${subsSdk.ENDPOINTS.base}/de/v1`;
|
|
46
|
-
const attributesCache = {};
|
|
47
|
-
const getAttributes = async _ref => {
|
|
48
|
-
let {
|
|
49
|
-
fieldName
|
|
50
|
-
} = _ref;
|
|
51
|
-
if (attributesCache[fieldName]) {
|
|
52
|
-
return attributesCache[fieldName];
|
|
53
|
-
}
|
|
54
|
-
const fieldNames = [fieldName];
|
|
55
|
-
try {
|
|
56
|
-
const url = new URL(`${base}/attributes`);
|
|
57
|
-
url.searchParams.set('attributes', fieldNames.join(','));
|
|
58
|
-
const data = await fetch(url.toString(), {
|
|
59
|
-
credentials: 'include',
|
|
60
|
-
headers: subsSdk.JSON_HEADERS
|
|
61
|
-
});
|
|
62
|
-
const json = await data.json();
|
|
63
|
-
if (data.ok && json.status === subsSdk.ResponseStatus.SUCCESS) {
|
|
64
|
-
const attributes = json.attributes || [];
|
|
65
|
-
attributesCache[fieldName] = attributes;
|
|
66
|
-
return attributes;
|
|
67
|
-
} else {
|
|
68
|
-
return [];
|
|
69
|
-
}
|
|
70
|
-
} catch (e) {
|
|
71
|
-
console.debug(e);
|
|
72
|
-
return [];
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
const ingest = async _ref2 => {
|
|
76
|
-
let {
|
|
77
|
-
submitData: {
|
|
78
|
-
fieldName,
|
|
79
|
-
value
|
|
80
|
-
},
|
|
81
|
-
source
|
|
82
|
-
} = _ref2;
|
|
83
|
-
const url = `${base}/ingest`;
|
|
84
|
-
const wapo_login_id = subsSdk.getCookie('wapo_login_id');
|
|
85
|
-
if (!hasRequiredPrivacyCookies()) {
|
|
86
|
-
throw new Error('does not satisfy cookie check');
|
|
87
|
-
}
|
|
88
|
-
let attributeInfo = attributesCache[fieldName];
|
|
89
|
-
if (!attributeInfo) {
|
|
90
|
-
attributeInfo = await getAttributes({
|
|
91
|
-
fieldName
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
if (attributeInfo[0] && attributeInfo[0].name === fieldName && attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT) {
|
|
95
|
-
throw new Error('do not collect');
|
|
96
|
-
}
|
|
97
|
-
const jucid = localStorage.getItem('uuid');
|
|
98
|
-
const ga = subsSdk.getCookie('_ga');
|
|
99
|
-
const payload = {
|
|
100
|
-
jucid,
|
|
101
|
-
ga,
|
|
102
|
-
type: IngestType.EXPLICIT,
|
|
103
|
-
wapo_login_id,
|
|
104
|
-
data: {
|
|
105
|
-
fieldName,
|
|
106
|
-
value
|
|
107
|
-
},
|
|
108
|
-
metadata: {
|
|
109
|
-
source
|
|
110
|
-
}
|
|
111
|
-
};
|
|
112
|
-
try {
|
|
113
|
-
const response = await fetch(url, {
|
|
114
|
-
method: 'POST',
|
|
115
|
-
credentials: 'include',
|
|
116
|
-
headers: subsSdk.JSON_HEADERS,
|
|
117
|
-
body: JSON.stringify(payload)
|
|
118
|
-
});
|
|
119
|
-
const json = await response.json();
|
|
120
|
-
return json;
|
|
121
|
-
} catch (e) {
|
|
122
|
-
console.debug(e);
|
|
123
|
-
return null;
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
|
|
127
|
-
const DESelect = _ref => {
|
|
128
|
-
let {
|
|
129
|
-
source,
|
|
130
|
-
fieldName,
|
|
131
|
-
label,
|
|
132
|
-
dataDictionaryConfig,
|
|
133
|
-
defaultValue,
|
|
134
|
-
disabled,
|
|
135
|
-
submit,
|
|
136
|
-
onChange = () => {},
|
|
137
|
-
onFinished = () => {},
|
|
138
|
-
valuesFilter = () => true,
|
|
139
|
-
children
|
|
140
|
-
} = _ref;
|
|
141
|
-
const [config, setConfig] = React.useState(dataDictionaryConfig);
|
|
142
|
-
const [selected, setSelected] = React.useState('');
|
|
143
|
-
React.useEffect(() => {
|
|
144
|
-
if (children) {
|
|
145
|
-
if (process.env.NODE_ENV !== "production") {
|
|
146
|
-
console.debug('childen props', children);
|
|
147
|
-
}
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
if (!config) {
|
|
151
|
-
(async () => {
|
|
152
|
-
// TODO: Switch to window.__twpdeu.getFieldConfigs
|
|
153
|
-
const config = await getAttributes({
|
|
154
|
-
fieldName
|
|
155
|
-
});
|
|
156
|
-
if (process.env.NODE_ENV !== "production") {
|
|
157
|
-
console.debug('config from API', config);
|
|
158
|
-
}
|
|
159
|
-
setConfig(config[0]);
|
|
160
|
-
})();
|
|
161
|
-
}
|
|
162
|
-
}, []);
|
|
163
|
-
React.useEffect(() => {
|
|
164
|
-
(async () => {
|
|
165
|
-
if (submit && selected) {
|
|
166
|
-
// TODO: Switch to window.__twpdeu.push
|
|
167
|
-
// TODO: Log to GA
|
|
168
|
-
// TODO: Differentiate between explicit and implicit inputs?
|
|
169
|
-
const result = await ingest({
|
|
170
|
-
submitData: {
|
|
171
|
-
fieldName,
|
|
172
|
-
value: selected
|
|
173
|
-
},
|
|
174
|
-
source
|
|
175
|
-
});
|
|
176
|
-
const isError = result ? result.status !== subsSdk.ResponseStatus.SUCCESS : true;
|
|
177
|
-
onFinished({
|
|
178
|
-
isFinished: true,
|
|
179
|
-
isError
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
})();
|
|
183
|
-
}, [submit, selected]);
|
|
184
|
-
if (!(children || config)) {
|
|
185
|
-
return React__default.createElement("span", null, "loading");
|
|
186
|
-
}
|
|
187
|
-
const defaultValueProp = defaultValue ? {
|
|
188
|
-
defaultValue
|
|
189
|
-
} : {};
|
|
190
|
-
const disabledProp = disabled ? {
|
|
191
|
-
disabled: true
|
|
192
|
-
} : {};
|
|
193
|
-
// sort and filter out archived values
|
|
194
|
-
const values = config ? config.values.sort((a, b) => a.order - b.order).filter(value => value.archived !== true).filter(valuesFilter) : [];
|
|
195
|
-
return React__default.createElement(SelectWrapper, null, React__default.createElement(wpdsUiKit.Select.Root, {
|
|
196
|
-
onValueChange: e => {
|
|
197
|
-
onChange({
|
|
198
|
-
value: e
|
|
199
|
-
});
|
|
200
|
-
setSelected(e);
|
|
201
|
-
},
|
|
202
|
-
...defaultValueProp,
|
|
203
|
-
...disabledProp
|
|
204
|
-
}, children ? children : null, !children && config && React__default.createElement(React__default.Fragment, null, React__default.createElement(wpdsUiKit.Select.Trigger, {
|
|
205
|
-
"data-test-id": `${config.name}-select-trigger`
|
|
206
|
-
}, React__default.createElement(wpdsUiKit.Select.Label, null, label || config.name), React__default.createElement(wpdsUiKit.Select.Value, null)), React__default.createElement(wpdsUiKit.Select.Content, {
|
|
207
|
-
css: {
|
|
208
|
-
zIndex: wpdsUiKit.theme.zIndices.page
|
|
209
|
-
},
|
|
210
|
-
"data-test-id": `${config.name}-select-content`
|
|
211
|
-
}, values.map(value => React__default.createElement(wpdsUiKit.Select.Item, {
|
|
212
|
-
value: value.name,
|
|
213
|
-
key: value.name
|
|
214
|
-
}, value.name))))));
|
|
215
|
-
};
|
|
216
|
-
const SelectWrapper = /*#__PURE__*/wpdsUiKit.styled('div', {
|
|
217
|
-
boxSizing: 'border-box',
|
|
218
|
-
display: 'flex',
|
|
219
|
-
marginBottom: '$100',
|
|
220
|
-
flexDirection: 'column',
|
|
221
|
-
'& button': {
|
|
222
|
-
padding: '1px 6px'
|
|
223
|
-
},
|
|
224
|
-
'& *': {
|
|
225
|
-
boxSizing: 'border-box'
|
|
226
|
-
}
|
|
227
|
-
});
|
|
228
|
-
|
|
229
|
-
exports.AttributesState = AttributesState;
|
|
230
|
-
exports.CollectionBehaviors = CollectionBehaviors;
|
|
231
|
-
exports.DESelect = DESelect;
|
|
232
|
-
exports.IngestResponseState = IngestResponseState;
|
|
233
|
-
exports.IngestType = IngestType;
|
|
234
|
-
exports.getAttributes = getAttributes;
|
|
235
|
-
exports.hasRequiredPrivacyCookies = hasRequiredPrivacyCookies;
|
|
236
|
-
exports.ingest = ingest;
|
|
237
|
-
//# sourceMappingURL=subs-de-inputs.cjs.development.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"subs-de-inputs.cjs.development.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type: IngestType.EXPLICIT,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string;\n };\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue } from '../../interfaces';\nimport { getAttributes, ingest } from '../../services/dataEnrichment';\nimport { ResponseStatus } from '@washingtonpost/subs-sdk';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n useEffect(() => {\n if (children) {\n if (__DEV__) {\n console.debug('childen props', children);\n }\n return;\n }\n\n if (!config) {\n (async () => {\n // TODO: Switch to window.__twpdeu.getFieldConfigs\n const config = await getAttributes({ fieldName });\n if (__DEV__) {\n console.debug('config from API', config);\n }\n setConfig(config[0]);\n })();\n }\n }, []);\n\n useEffect(() => {\n (async () => {\n if (submit && selected) {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n // TODO: Differentiate between explicit and implicit inputs?\n const result = await ingest({\n submitData: { fieldName, value: selected },\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n }\n })();\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","AttributesState","SUCCESS","IngestType","EXPLICIT","IMPLICIT","IngestResponseState","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","_ref","fieldName","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","attributes","e","console","debug","ingest","_ref2","submitData","value","source","wapo_login_id","Error","attributeInfo","name","collection_behavior","jucid","localStorage","getItem","ga","payload","type","metadata","response","method","body","JSON","stringify","DESelect","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","useEffect","process","env","NODE_ENV","result","isError","isFinished","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","SelectWrapper","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","styled","boxSizing","display","marginBottom","flexDirection","padding"],"mappings":";;;;;;;;;;;MAQaA,mBAAmB,GAAG;EACjCC,OAAO,EAAE,SAAS;EAClBC,cAAc,EAAE;;MAeLC,eAAe,GAAG;EAC7BC,OAAO,EAAE;;MAGEC,UAAU,GAAG;EACxBC,QAAQ,EAAE,UAAU;EACpBC,QAAQ,EAAE;;MAGCC,mBAAmB,GAAG;EACjCJ,OAAO,EAAE,KAAK;EACdK,YAAY,EAAE,KAAK;EACnBC,YAAY,EAAE,KAAK;EACnBC,kBAAkB,EAAE,KAAK;EACzBC,YAAY,EAAE,KAAK;EACnBC,4BAA4B,EAAE,KAAK;EACnCC,uBAAuB,EAAE,KAAK;EAC9BC,eAAe,EAAE,KAAK;EACtBC,qBAAqB,EAAE;;;MCzCZC,yBAAyB,GAAGA;;EACvC,IAAI,OAAOC,MAAM,KAAK,WAAW,EAAE;IACjC,OAAO,KAAK;;EAGd,MAAMC,MAAM,GAAGC,iBAAS,CAAC,QAAQ,CAAC;EAElC,MAAMC,WAAW,IAAAC,MAAA,GAAGC,aAAK,EAAE,cAAAD,MAAA,uBAAPA,MAAA,CAASE,YAAY;EAEzC,OAAO,CAAC,EAAEL,MAAM,IAAIE,WAAW,KAAK,IAAI,CAAC;AAC3C,CAAC;;ACED,MAAMI,IAAI,MAAMC,iBAAS,CAACD,YAAY;AAEtC,MAAME,eAAe,GAAwB,EAAE;AAC/C,MAAaC,aAAa,GAAsB,MAAAC,IAAA;MAAO;IACrDC;GAGD,GAAAD,IAAA;EACC,IAAIF,eAAe,CAACG,SAAS,CAAC,EAAE;IAC9B,OAAOH,eAAe,CAACG,SAAS,CAAC;;EAGnC,MAAMC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,EAAE;GACV;EACD,KAAK,EAAE;IAAEJ,SAAS,EAAE;;CACrB,CAAC;;;;;;;;;;;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("@washingtonpost/subs-sdk"),a=require("react"),o=(e=a)&&"object"==typeof e&&"default"in e?e.default:e,n=require("@washingtonpost/wpds-ui-kit");const s={COLLECT:"COLLECT",DO_NOT_COLLECT:"DO_NOT_COLLECT"},r={EXPLICIT:"explicit",IMPLICIT:"implicit"},i=()=>{var e;if("undefined"==typeof window)return!1;const a=t.getCookie("wp_usp"),o=null===(e=t.WPGeo())||void 0===e?void 0:e.country_code;return!(!a||"US"!==o)},l=t.ENDPOINTS.base+"/de/v1",c={},u=async e=>{let{fieldName:a}=e;if(c[a])return c[a];const o=[a];try{const e=new URL(l+"/attributes");e.searchParams.set("attributes",o.join(","));const n=await fetch(e.toString(),{credentials:"include",headers:t.JSON_HEADERS}),s=await n.json();if(n.ok&&s.status===t.ResponseStatus.SUCCESS){const e=s.attributes||[];return c[a]=e,e}return[]}catch(e){return console.debug(e),[]}},d=async e=>{let{submitData:{fieldName:a,value:o},source:n}=e;const d=l+"/ingest",E=t.getCookie("wapo_login_id");if(!i())throw new Error("does not satisfy cookie check");let I=c[a];if(I||(I=await u({fieldName:a})),I[0]&&I[0].name===a&&I[0].collection_behavior===s.DO_NOT_COLLECT)throw new Error("do not collect");const S={jucid:localStorage.getItem("uuid"),ga:t.getCookie("_ga"),type:r.EXPLICIT,wapo_login_id:E,data:{fieldName:a,value:o},metadata:{source:n}};try{const e=await fetch(d,{method:"POST",credentials:"include",headers:t.JSON_HEADERS,body:JSON.stringify(S)});return await e.json()}catch(e){return console.debug(e),null}},E=n.styled("div",{boxSizing:"border-box",display:"flex",marginBottom:"$100",flexDirection:"column","& button":{padding:"1px 6px"},"& *":{boxSizing:"border-box"}});exports.AttributesState={SUCCESS:"100"},exports.CollectionBehaviors=s,exports.DESelect=e=>{let{source:s,fieldName:r,label:i,dataDictionaryConfig:l,defaultValue:c,disabled:I,submit:S,onChange:m=(()=>{}),onFinished:p=(()=>{}),valuesFilter:f=(()=>!0),children:g}=e;const[C,N]=a.useState(l),[T,b]=a.useState("");if(a.useEffect(()=>{g?"production"!==process.env.NODE_ENV&&console.debug("childen props",g):C||(async()=>{const e=await u({fieldName:r});"production"!==process.env.NODE_ENV&&console.debug("config from API",e),N(e[0])})()},[]),a.useEffect(()=>{(async()=>{if(S&&T){const e=await d({submitData:{fieldName:r,value:T},source:s});p({isFinished:!0,isError:!e||e.status!==t.ResponseStatus.SUCCESS})}})()},[S,T]),!g&&!C)return o.createElement("span",null,"loading");const _=c?{defaultValue:c}:{},D=I?{disabled:!0}:{},h=C?C.values.sort((e,t)=>e.order-t.order).filter(e=>!0!==e.archived).filter(f):[];return o.createElement(E,null,o.createElement(n.Select.Root,{onValueChange:e=>{m({value:e}),b(e)},..._,...D},g||null,!g&&C&&o.createElement(o.Fragment,null,o.createElement(n.Select.Trigger,{"data-test-id":C.name+"-select-trigger"},o.createElement(n.Select.Label,null,i||C.name),o.createElement(n.Select.Value,null)),o.createElement(n.Select.Content,{css:{zIndex:n.theme.zIndices.page},"data-test-id":C.name+"-select-content"},h.map(e=>o.createElement(n.Select.Item,{value:e.name,key:e.name},e.name))))))},exports.IngestResponseState={SUCCESS:"100",SYSTEM_ERROR:"101",INVALID_TYPE:"102",INVALID_IDENTIFIER:"103",INVALID_DATA:"104",INVALID_ATTRIBUTE_DEFINITION:"105",INVALID_META_DEFINITION:"106",UNAUTHENTICATED:"107",MISMATCHED_IDENTIFIER:"108"},exports.IngestType=r,exports.getAttributes=u,exports.hasRequiredPrivacyCookies=i,exports.ingest=d;
|
|
2
|
-
//# sourceMappingURL=subs-de-inputs.cjs.production.min.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"subs-de-inputs.cjs.production.min.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type: IngestType.EXPLICIT,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string;\n };\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue } from '../../interfaces';\nimport { getAttributes, ingest } from '../../services/dataEnrichment';\nimport { ResponseStatus } from '@washingtonpost/subs-sdk';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n useEffect(() => {\n if (children) {\n if (__DEV__) {\n console.debug('childen props', children);\n }\n return;\n }\n\n if (!config) {\n (async () => {\n // TODO: Switch to window.__twpdeu.getFieldConfigs\n const config = await getAttributes({ fieldName });\n if (__DEV__) {\n console.debug('config from API', config);\n }\n setConfig(config[0]);\n })();\n }\n }, []);\n\n useEffect(() => {\n (async () => {\n if (submit && selected) {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n // TODO: Differentiate between explicit and implicit inputs?\n const result = await ingest({\n submitData: { fieldName, value: selected },\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n }\n })();\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","IngestType","EXPLICIT","IMPLICIT","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","async","fieldName","_ref","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","SUCCESS","attributes","e","console","debug","ingest","submitData","value","source","_ref2","wapo_login_id","Error","attributeInfo","name","collection_behavior","payload","jucid","localStorage","getItem","ga","type","metadata","response","method","body","JSON","stringify","SelectWrapper","styled","boxSizing","display","marginBottom","flexDirection","& button","padding","& *","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","useEffect","process","env","NODE_ENV","result","isFinished","isError","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INV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