-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
AdaptiveCardRenderer.js
229 lines (183 loc) · 6.8 KB
/
AdaptiveCardRenderer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/* eslint no-magic-numbers: ["error", { "ignore": [0, 2] }] */
import PropTypes from 'prop-types';
import React, { useCallback, useLayoutEffect, useRef, useState } from 'react';
import { Components, getTabIndex, hooks } from 'botframework-webchat-component';
import useAdaptiveCardsHostConfig from '../hooks/useAdaptiveCardsHostConfig';
import useAdaptiveCardsPackage from '../hooks/useAdaptiveCardsPackage';
const { ErrorBox } = Components;
const { useDisabled, useLocalize, usePerformCardAction, useRenderMarkdownAsHTML, useStyleSet } = hooks;
function isPlainObject(obj) {
return Object.getPrototypeOf(obj) === Object.prototype;
}
function disableInputElements(element) {
const hyperlinks = element.querySelectorAll('a');
const inputs = element.querySelectorAll('button, input, select, textarea');
const disabledHandler = event => {
event.preventDefault();
event.stopImmediatePropagation();
event.stopPropagation();
};
[].forEach.call(inputs, input => {
input.disabled = true;
});
[].forEach.call(hyperlinks, hyperlink => {
hyperlink.addEventListener('click', disabledHandler);
});
}
function restoreInputValues(element, inputValues) {
const inputs = element.querySelectorAll('input, select, textarea');
[].forEach.call(inputs, (input, index) => {
const value = inputValues[index];
if (typeof value !== 'undefined') {
const { tagName, type } = input;
if (tagName === 'INPUT' && (type === 'checkbox' || type === 'radio')) {
input.checked = value;
} else {
input.value = value;
}
}
});
}
function saveInputValues(element) {
const inputs = element.querySelectorAll('input, select, textarea');
return [].map.call(inputs, ({ checked, tagName, type, value }) => {
if (tagName === 'INPUT' && (type === 'checkbox' || type === 'radio')) {
return checked;
}
return value;
});
}
const AdaptiveCardRenderer = ({ adaptiveCard, tapAction }) => {
const [{ adaptiveCardRenderer: adaptiveCardRendererStyleSet }] = useStyleSet();
const [{ HostConfig }] = useAdaptiveCardsPackage();
const [adaptiveCardsHostConfig] = useAdaptiveCardsHostConfig();
const [disabled] = useDisabled();
const errorMessage = useLocalize('Adaptive Card render error');
const performCardAction = usePerformCardAction();
const renderMarkdownAsHTML = useRenderMarkdownAsHTML();
const [error, setError] = useState();
const contentRef = useRef();
const inputValuesRef = useRef([]);
const handleClick = useCallback(
({ target }) => {
// Some items, e.g. tappable text, cannot be disabled thru DOM attributes
if (!disabled) {
const tabIndex = getTabIndex(target);
// If the user is clicking on something that is already clickable, do not allow them to click the card.
// E.g. a hero card can be tappable, and image and buttons inside the hero card can also be tappable.
if (typeof tabIndex !== 'number' || tabIndex < 0) {
tapAction && performCardAction(tapAction);
}
}
},
[disabled, performCardAction, tapAction]
);
const handleExecuteAction = useCallback(
action => {
// Some items, e.g. tappable image, cannot be disabled thru DOM attributes
if (disabled) {
return;
}
const actionTypeName = action.getJsonTypeName();
if (actionTypeName === 'Action.OpenUrl') {
performCardAction({
type: 'openUrl',
value: action.url
});
} else if (actionTypeName === 'Action.Submit') {
if (typeof action.data !== 'undefined') {
const { data: actionData } = action;
if (actionData && actionData.__isBotFrameworkCardAction) {
const { cardAction } = actionData;
const { displayText, type, value } = cardAction;
performCardAction({ displayText, type, value });
} else {
performCardAction({
type: typeof action.data === 'string' ? 'imBack' : 'postBack',
value: action.data
});
}
}
} else {
console.error(`Web Chat: received unknown action from Adaptive Cards`);
console.error(action);
}
},
[disabled, performCardAction]
);
useLayoutEffect(() => {
const { current } = contentRef;
if (current && adaptiveCard) {
// Currently, the only way to set the Markdown engine is to set it thru static member of AdaptiveCard class
// TODO: [P3] Checks if we could make the "renderMarkdownAsHTML" per card
// This could be limitations from Adaptive Cards package
// Because there could be timing difference between .parse and .render, we could be using wrong Markdown engine
adaptiveCard.constructor.onProcessMarkdown = (text, result) => {
if (renderMarkdownAsHTML) {
result.outputHtml = renderMarkdownAsHTML(text);
result.didProcess = true;
}
};
adaptiveCard.onExecuteAction = handleExecuteAction;
if (adaptiveCardsHostConfig) {
adaptiveCard.hostConfig = isPlainObject(adaptiveCardsHostConfig)
? new HostConfig(adaptiveCardsHostConfig)
: adaptiveCardsHostConfig;
}
const { failures } = adaptiveCard.validateProperties();
if (failures.length) {
// TODO: [P3] Since this can be called from `componentDidUpdate` and potentially error, we should fix a better way to propagate the error.
const errors = failures.reduce((items, { errors }) => [...items, ...errors], []);
return setError(errors);
}
let element;
try {
element = adaptiveCard.render();
} catch (error) {
return setError(error);
}
if (!element) {
return setError('Adaptive Card rendered as empty element');
}
error && setError(null);
disabled && disableInputElements(element);
restoreInputValues(element, inputValuesRef.current);
const [firstChild] = current.children;
if (firstChild) {
current.replaceChild(element, firstChild);
} else {
current.appendChild(element);
}
return () => {
inputValuesRef.current = saveInputValues(element);
};
}
}, [
adaptiveCard,
adaptiveCardsHostConfig,
contentRef,
disabled,
error,
handleExecuteAction,
HostConfig,
renderMarkdownAsHTML
]);
return error ? (
<ErrorBox message={errorMessage}>
<pre>{JSON.stringify(error, null, 2)}</pre>
</ErrorBox>
) : (
<div className={adaptiveCardRendererStyleSet} onClick={handleClick} ref={contentRef} />
);
};
AdaptiveCardRenderer.propTypes = {
adaptiveCard: PropTypes.any.isRequired,
tapAction: PropTypes.shape({
type: PropTypes.string.isRequired,
value: PropTypes.string
})
};
AdaptiveCardRenderer.defaultProps = {
tapAction: undefined
};
export default AdaptiveCardRenderer;