doc-survey-widget.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. import clsx from "clsx";
  2. import React, { useState } from "react";
  3. import { useLocation } from "@docusaurus/router";
  4. import { AnimatePresence, motion } from "framer-motion";
  5. type Props = {
  6. className?: string;
  7. };
  8. // users can submit rating(numbers displaying as a emoji) feedback and besides that they can also submit optional text feedback
  9. // if they submit rating feedback, we show the text feedback input
  10. // after they submit text feedback, we show a thank you message
  11. export const DocSurveyWidget = ({ className }: Props) => {
  12. const refWidget = React.useRef<HTMLDivElement>(null);
  13. const location = useLocation();
  14. // users can change their rating feedback, so we need to keep track of the survey response
  15. const [survey, setSurvey] = useState<DocSurveyResponse | null>(null);
  16. // if the user submits rating feedback, we show the text feedback input
  17. const [isSurveyTextVisible, setIsSurveyTextVisible] = useState(false);
  18. // if the user submits text feedback, we show a thank you message
  19. const [isFinished, setIsFinished] = useState(false);
  20. // the user can change their rating feedback, so we need to keep track of the selected option
  21. const [selectedOption, setSelectedOption] = useState<SurveyOption | null>(
  22. null,
  23. );
  24. const handleSurveyOptionClick = async (option: SurveyOption) => {
  25. setSelectedOption(option);
  26. setIsSurveyTextVisible(true);
  27. // setTimeout is needed because the text view has a transition
  28. // we need to scroll to the bottom after the transition is finished so that the text input is visible
  29. setTimeout(() => {
  30. refWidget.current?.scrollIntoView({
  31. behavior: "smooth",
  32. });
  33. }, 150);
  34. if (survey) {
  35. const data = await updateSurvey({
  36. surveyId: survey.id,
  37. body: { response: option },
  38. });
  39. if (!data) return;
  40. setSurvey(data);
  41. } else {
  42. const data = await createSurvey({
  43. body: {
  44. response: option,
  45. entityId: location.pathname,
  46. },
  47. });
  48. if (!data) return;
  49. setSurvey(data);
  50. }
  51. };
  52. const handleSurveyTextSubmit = async (text: string) => {
  53. if (text.trim() === "") {
  54. return;
  55. }
  56. const data = await updateSurvey({
  57. surveyId: survey.id,
  58. body: { response: selectedOption, responseText: text },
  59. });
  60. if (!data) return;
  61. setSurvey(data);
  62. // when the user submits text feedback, we show a thank you message
  63. setIsFinished(true);
  64. // reset the survey after N seconds so that the user can submit another survey
  65. setTimeout(() => {
  66. setSelectedOption(null);
  67. setSurvey(null);
  68. setIsFinished(false);
  69. setIsSurveyTextVisible(false);
  70. }, 3000);
  71. };
  72. return (
  73. <div
  74. ref={refWidget}
  75. className={clsx(
  76. "w-full max-w-[416px]",
  77. "flex flex-col",
  78. "p-3",
  79. "bg-gray-100 dark:bg-gray-700",
  80. "border border-gray-300 dark:border-gray-700",
  81. "rounded-[28px]",
  82. (isSurveyTextVisible || isFinished) && "h-[286px] sm:h-[242px]",
  83. !isSurveyTextVisible && !isFinished && "h-[114px] sm:h-[58px]",
  84. "transition-all duration-200 ease-in-out",
  85. "overflow-hidden",
  86. className,
  87. )}
  88. >
  89. {isFinished ? (
  90. <AnimatePresence>
  91. <SurveyFinished selectedOption={selectedOption} />
  92. </AnimatePresence>
  93. ) : (
  94. <>
  95. <SurveyOptions
  96. options={surveyOptions}
  97. selectedOption={selectedOption}
  98. onOptionClick={handleSurveyOptionClick}
  99. />
  100. {isSurveyTextVisible && (
  101. <SurveyText
  102. className={clsx(
  103. "w-full",
  104. "mt-4",
  105. isSurveyTextVisible && "h-[128px] block",
  106. !isSurveyTextVisible && "h-[0px] hidden",
  107. "transition-all duration-200 ease-in-out",
  108. )}
  109. onSubmit={handleSurveyTextSubmit}
  110. />
  111. )}
  112. </>
  113. )}
  114. </div>
  115. );
  116. };
  117. const SurveyOptions = (props: {
  118. className?: string;
  119. options: {
  120. value: SurveyOption;
  121. img: string;
  122. }[];
  123. selectedOption: SurveyOption | null;
  124. onOptionClick: (option: SurveyOption) => void;
  125. }) => {
  126. const hasSelectedOption = !!props.selectedOption;
  127. return (
  128. <div
  129. className={clsx(
  130. "w-full",
  131. "flex flex-col sm:flex-row",
  132. "items-center justify-between",
  133. "gap-4 sm:gap-2",
  134. "sm:pl-4",
  135. props.className,
  136. )}
  137. >
  138. <div
  139. className={clsx(
  140. "dark:text-gray-100 text-gray-800",
  141. "text-base",
  142. )}
  143. >
  144. Was this helpful?
  145. </div>
  146. <div className={clsx("flex", "items-center", "gap-3 sm:gap-1")}>
  147. {props.options.map(({ value, img }) => {
  148. const isSelected = props.selectedOption === value;
  149. return (
  150. <button
  151. key={value}
  152. onClick={() => props.onOptionClick(value)}
  153. className="p-1.5 sm:p-1"
  154. >
  155. <img
  156. src={img}
  157. alt={img.split("/").pop()}
  158. loading="lazy"
  159. className={clsx(
  160. "block",
  161. "flex-shrink-0",
  162. "sm:w-6 sm:h-6",
  163. "w-9 h-9",
  164. isSelected && "mix-blend-normal",
  165. isSelected && "scale-[1.33]",
  166. !isSelected && "mix-blend-luminosity",
  167. !isSelected &&
  168. hasSelectedOption &&
  169. "opacity-50",
  170. "transition-all duration-200 ease-in-out",
  171. )}
  172. />
  173. </button>
  174. );
  175. })}
  176. </div>
  177. </div>
  178. );
  179. };
  180. const SurveyText = (props: {
  181. className?: string;
  182. onSubmit: (text: string) => void;
  183. }) => {
  184. const [text, setText] = useState("");
  185. return (
  186. <form
  187. className={clsx(
  188. "w-full",
  189. "h-full",
  190. "flex",
  191. "flex-col",
  192. props.className,
  193. )}
  194. onSubmit={(e) => {
  195. e.preventDefault();
  196. props.onSubmit(text);
  197. }}
  198. >
  199. <textarea
  200. name="survey-text"
  201. required
  202. className={clsx(
  203. "w-full",
  204. "h-32",
  205. "p-4",
  206. "text-sm",
  207. "dark:placeholder-gray-500 placeholder-gray-400",
  208. "dark:text-gray-500 text-gray-400",
  209. "dark:bg-gray-900 bg-white",
  210. "border",
  211. "dark:border-gray-700",
  212. "border-gray-300",
  213. "rounded-lg",
  214. "resize-none",
  215. )}
  216. placeholder="Your emoji tells us how you feel. If you have any additional thoughts or suggestions, we'd love to hear them!"
  217. value={text}
  218. onChange={(e) => {
  219. setText(e.currentTarget.value);
  220. }}
  221. />
  222. <div
  223. className={clsx("flex", "items-center", "justify-end", "mt-2")}
  224. >
  225. <button
  226. type="submit"
  227. className={clsx(
  228. "w-20 h-8",
  229. "text-xs",
  230. "text-white ",
  231. "bg-gray-600",
  232. "border",
  233. "border-transparent",
  234. "rounded-full",
  235. )}
  236. >
  237. Send
  238. </button>
  239. </div>
  240. </form>
  241. );
  242. };
  243. const SurveyFinished = (props: {
  244. className?: string;
  245. selectedOption: SurveyOption | null;
  246. }) => {
  247. const option = surveyOptions.find(
  248. (option) => option.value === props.selectedOption,
  249. );
  250. return (
  251. <div
  252. className={clsx(
  253. "flex",
  254. "flex-col",
  255. "items-center",
  256. "justify-center",
  257. "h-full",
  258. "dark:text-white text-gray-800",
  259. props.className,
  260. )}
  261. >
  262. <img
  263. src={option?.img}
  264. className={clsx("w-8 h-8", "block")}
  265. alt="emoji"
  266. />
  267. <motion.div
  268. initial={{ opacity: 0 }}
  269. animate={{ opacity: 1, transition: { delay: 0.1 } }}
  270. exit={{ opacity: 0 }}
  271. >
  272. <div className={clsx("mt-6")}>Thank you!</div>
  273. </motion.div>
  274. <motion.div
  275. initial={{ opacity: 0 }}
  276. animate={{ opacity: 1, transition: { delay: 0.2 } }}
  277. exit={{ opacity: 0 }}
  278. >
  279. <div className={clsx("mt-1")}>
  280. Your feedback has been recieved.
  281. </div>
  282. </motion.div>
  283. </div>
  284. );
  285. };
  286. const createSurvey = async ({ body }: { body: DocSurveyCreateDto }) => {
  287. const response = await fetch(`${DOC_SURVEY_URL}/responses`, {
  288. method: "POST",
  289. headers: {
  290. "Content-Type": "application/json",
  291. },
  292. body: JSON.stringify(body),
  293. });
  294. if (!response.ok) {
  295. return null;
  296. }
  297. const data: DocSurveyResponse = await response.json();
  298. return data;
  299. };
  300. const updateSurvey = async ({
  301. surveyId,
  302. body,
  303. }: {
  304. surveyId?: string;
  305. body: DocSurveyUpdateDto;
  306. }) => {
  307. const response = await fetch(`${DOC_SURVEY_URL}/responses/${surveyId}`, {
  308. method: "PATCH",
  309. headers: {
  310. "Content-Type": "application/json",
  311. },
  312. body: JSON.stringify(body),
  313. });
  314. if (!response.ok) {
  315. return null;
  316. }
  317. const data: DocSurveyResponse = await response.json();
  318. return data;
  319. };
  320. const surveyOptions: {
  321. value: SurveyOption;
  322. img: string;
  323. }[] = [
  324. {
  325. value: 1,
  326. img: "/icons/emoji/emoji-crying-face.png",
  327. },
  328. {
  329. value: 2,
  330. img: "/icons/emoji/emoji-sad-face.png",
  331. },
  332. {
  333. value: 3,
  334. img: "/icons/emoji/emoji-neutral-face.png",
  335. },
  336. {
  337. value: 4,
  338. img: "/icons/emoji/emoji-slightly-smiling-face.png",
  339. },
  340. {
  341. value: 5,
  342. img: "/icons/emoji/emoji-star-struct-face.png",
  343. },
  344. ];
  345. export type SurveyOption = 1 | 2 | 3 | 4 | 5;
  346. export type Survey = {
  347. id: string;
  348. name: string;
  349. slug: string;
  350. options: SurveyOption[];
  351. source: string;
  352. entityType: string;
  353. surveyType: string;
  354. createdAt: string;
  355. updatedAt: string;
  356. };
  357. export type IDocSurveyContext = {
  358. survey: Survey;
  359. };
  360. export type DocSurveyCreateDto = {
  361. response: number;
  362. entityId: string;
  363. responseText?: string;
  364. metaData?: SurveyMetaData;
  365. };
  366. export type DocSurveyUpdateDto = {
  367. response: number;
  368. responseText?: string;
  369. metaData?: SurveyMetaData;
  370. };
  371. export type DocSurveyResponse = {
  372. response: number;
  373. entityId: string;
  374. survey: Survey;
  375. responseText?: string | null;
  376. metaData: SurveyMetaData;
  377. id: string;
  378. createdAt: string;
  379. updatedAt: string;
  380. };
  381. export type SurveyMetaData = Record<string, any>;
  382. const DOC_SURVEY_URL = `https://api.openpanel.co/surveys/documentation-pages-survey.php`;