EditSocialLinks.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. import React, { useState, useContext, useEffect } from 'react';
  2. import { Typography, Table, Button, Modal, Input } from 'antd';
  3. import { ColumnsType } from 'antd/lib/table';
  4. import dynamic from 'next/dynamic';
  5. import { SocialDropdown } from '../../SocialDropdown';
  6. import { fetchData, SOCIAL_PLATFORMS_LIST } from '../../../../utils/apis';
  7. import { ServerStatusContext } from '../../../../utils/server-status-context';
  8. import {
  9. API_SOCIAL_HANDLES,
  10. postConfigUpdateToAPI,
  11. RESET_TIMEOUT,
  12. DEFAULT_SOCIAL_HANDLE,
  13. OTHER_SOCIAL_HANDLE_OPTION,
  14. } from '../../../../utils/config-constants';
  15. import { SocialHandle, UpdateArgs } from '../../../../types/config-section';
  16. import {
  17. isValidMatrixAccount,
  18. isValidAccount,
  19. isValidUrl,
  20. DEFAULT_TEXTFIELD_URL_PATTERN,
  21. } from '../../../../utils/validators';
  22. import { TextField } from '../../TextField';
  23. import { createInputStatus, STATUS_ERROR, STATUS_SUCCESS } from '../../../../utils/input-statuses';
  24. import { FormStatusIndicator } from '../../FormStatusIndicator';
  25. const { Title } = Typography;
  26. // Lazy loaded components
  27. const CaretDownOutlined = dynamic(() => import('@ant-design/icons/CaretDownOutlined'), {
  28. ssr: false,
  29. });
  30. const CaretUpOutlined = dynamic(() => import('@ant-design/icons/CaretUpOutlined'), {
  31. ssr: false,
  32. });
  33. const DeleteOutlined = dynamic(() => import('@ant-design/icons/DeleteOutlined'), {
  34. ssr: false,
  35. });
  36. // eslint-disable-next-line react/function-component-definition
  37. export default function EditSocialLinks() {
  38. const [availableIconsList, setAvailableIconsList] = useState([]);
  39. const [currentSocialHandles, setCurrentSocialHandles] = useState([]);
  40. const [displayModal, setDisplayModal] = useState(false);
  41. const [displayOther, setDisplayOther] = useState(false);
  42. const [modalProcessing, setModalProcessing] = useState(false);
  43. const [editId, setEditId] = useState(-1);
  44. // current data inside modal
  45. const [modalDataState, setModalDataState] = useState(DEFAULT_SOCIAL_HANDLE);
  46. const [submitStatus, setSubmitStatus] = useState(null);
  47. const serverStatusData = useContext(ServerStatusContext);
  48. const { serverConfig, setFieldInConfigState } = serverStatusData || {};
  49. const { instanceDetails } = serverConfig;
  50. const { socialHandles: initialSocialHandles } = instanceDetails;
  51. let resetTimer = null;
  52. const PLACEHOLDERS = {
  53. mastodon: 'https://mastodon.social/@username',
  54. twitter: 'https://twitter.com/username',
  55. };
  56. const getAvailableIcons = async () => {
  57. try {
  58. const result = await fetchData(SOCIAL_PLATFORMS_LIST, { auth: false });
  59. const list = Object.keys(result).map(item => ({
  60. key: item,
  61. ...result[item],
  62. }));
  63. setAvailableIconsList(list);
  64. } catch (error) {
  65. console.log(error);
  66. // do nothing
  67. }
  68. };
  69. const isPredefinedSocial = (platform: string) =>
  70. availableIconsList.find(item => item.key === platform) || false;
  71. const selectedOther =
  72. modalDataState.platform !== '' &&
  73. !availableIconsList.find(item => item.key === modalDataState.platform);
  74. useEffect(() => {
  75. getAvailableIcons();
  76. }, []);
  77. useEffect(() => {
  78. if (instanceDetails.socialHandles) {
  79. setCurrentSocialHandles(initialSocialHandles);
  80. }
  81. }, [instanceDetails]);
  82. const resetStates = () => {
  83. setSubmitStatus(null);
  84. resetTimer = null;
  85. clearTimeout(resetTimer);
  86. };
  87. const resetModal = () => {
  88. setDisplayModal(false);
  89. setEditId(-1);
  90. setDisplayOther(false);
  91. setModalProcessing(false);
  92. setModalDataState({ ...DEFAULT_SOCIAL_HANDLE });
  93. };
  94. const handleModalCancel = () => {
  95. resetModal();
  96. };
  97. const updateModalState = (fieldName: string, value: string) => {
  98. setModalDataState({
  99. ...modalDataState,
  100. [fieldName]: value,
  101. });
  102. };
  103. const handleDropdownSelect = (value: string) => {
  104. if (value === OTHER_SOCIAL_HANDLE_OPTION) {
  105. setDisplayOther(true);
  106. updateModalState('platform', '');
  107. } else {
  108. setDisplayOther(false);
  109. updateModalState('platform', value);
  110. }
  111. };
  112. const handleOtherNameChange = event => {
  113. const { value } = event.target;
  114. updateModalState('platform', value);
  115. };
  116. const handleUrlChange = ({ value }: UpdateArgs) => {
  117. updateModalState('url', value);
  118. };
  119. // posts all the variants at once as an array obj
  120. const postUpdateToAPI = async (postValue: any) => {
  121. await postConfigUpdateToAPI({
  122. apiPath: API_SOCIAL_HANDLES,
  123. data: { value: postValue },
  124. onSuccess: () => {
  125. setFieldInConfigState({
  126. fieldName: 'socialHandles',
  127. value: postValue,
  128. path: 'instanceDetails',
  129. });
  130. // close modal
  131. setModalProcessing(false);
  132. handleModalCancel();
  133. setSubmitStatus(createInputStatus(STATUS_SUCCESS));
  134. resetTimer = setTimeout(resetStates, RESET_TIMEOUT);
  135. },
  136. onError: (message: string) => {
  137. setSubmitStatus(createInputStatus(STATUS_ERROR, `There was an error: ${message}`));
  138. setModalProcessing(false);
  139. resetTimer = setTimeout(resetStates, RESET_TIMEOUT);
  140. },
  141. });
  142. };
  143. // on Ok, send all of dataState to api
  144. // show loading
  145. // close modal when api is done
  146. const handleModalOk = () => {
  147. setModalProcessing(true);
  148. const postData = currentSocialHandles.length ? [...currentSocialHandles] : [];
  149. if (editId === -1) {
  150. postData.push(modalDataState);
  151. } else {
  152. postData.splice(editId, 1, modalDataState);
  153. }
  154. postUpdateToAPI(postData);
  155. };
  156. const handleDeleteItem = (index: number) => {
  157. const postData = [...currentSocialHandles];
  158. postData.splice(index, 1);
  159. postUpdateToAPI(postData);
  160. };
  161. const handleMoveItemUp = (index: number) => {
  162. if (index <= 0 || index >= currentSocialHandles.length) {
  163. return;
  164. }
  165. const postData = [...currentSocialHandles];
  166. const tmp = postData[index - 1];
  167. postData[index - 1] = postData[index];
  168. postData[index] = tmp;
  169. postUpdateToAPI(postData);
  170. };
  171. const handleMoveItemDown = (index: number) => {
  172. if (index < 0 || index >= currentSocialHandles.length - 1) {
  173. return;
  174. }
  175. const postData = [...currentSocialHandles];
  176. const tmp = postData[index + 1];
  177. postData[index + 1] = postData[index];
  178. postData[index] = tmp;
  179. postUpdateToAPI(postData);
  180. };
  181. const socialHandlesColumns: ColumnsType<SocialHandle> = [
  182. {
  183. title: 'Social Link',
  184. dataIndex: '',
  185. key: 'combo',
  186. render: (_, record) => {
  187. const { platform, url } = record;
  188. const platformInfo = isPredefinedSocial(platform);
  189. // custom platform case
  190. if (!platformInfo) {
  191. return (
  192. <div className="social-handle-cell">
  193. <p className="option-label">
  194. <strong>{platform}</strong>
  195. <span className="handle-url" title={url}>
  196. {url}
  197. </span>
  198. </p>
  199. </div>
  200. );
  201. }
  202. const { icon, platform: platformName } = platformInfo;
  203. return (
  204. <div className="social-handle-cell">
  205. <span className="option-icon">
  206. <img src={icon} alt="" className="option-icon" />
  207. </span>
  208. <p className="option-label">
  209. <strong>{platformName}</strong>
  210. <span className="handle-url" title={url}>
  211. {url}
  212. </span>
  213. </p>
  214. </div>
  215. );
  216. },
  217. },
  218. {
  219. title: '',
  220. dataIndex: '',
  221. key: 'edit',
  222. render: (_, _record, index) => (
  223. <div className="actions">
  224. <Button
  225. size="small"
  226. onClick={() => {
  227. const platformInfo = currentSocialHandles[index];
  228. setEditId(index);
  229. setModalDataState({ ...platformInfo });
  230. setDisplayModal(true);
  231. if (!isPredefinedSocial(platformInfo.platform)) {
  232. setDisplayOther(true);
  233. }
  234. }}
  235. >
  236. Edit
  237. </Button>
  238. <Button
  239. icon={<CaretUpOutlined />}
  240. size="small"
  241. hidden={index === 0}
  242. onClick={() => handleMoveItemUp(index)}
  243. />
  244. <Button
  245. icon={<CaretDownOutlined />}
  246. size="small"
  247. hidden={index === currentSocialHandles.length - 1}
  248. onClick={() => handleMoveItemDown(index)}
  249. />
  250. <Button
  251. className="delete-button"
  252. icon={<DeleteOutlined />}
  253. size="small"
  254. onClick={() => handleDeleteItem(index)}
  255. />
  256. </div>
  257. ),
  258. },
  259. ];
  260. const isValid = (url: string, platform: string) => {
  261. if (platform === 'xmpp') {
  262. return isValidAccount(url, 'xmpp');
  263. }
  264. if (platform === 'matrix') {
  265. return isValidMatrixAccount(url);
  266. }
  267. return isValidUrl(url);
  268. };
  269. const okButtonProps = {
  270. disabled: !isValid(modalDataState.url, modalDataState.platform),
  271. };
  272. const otherField = (
  273. <div className="other-field-container formfield-container">
  274. <div className="label-side" />
  275. <div className="input-side">
  276. <Input
  277. placeholder="Other platform name"
  278. defaultValue={modalDataState.platform}
  279. onChange={handleOtherNameChange}
  280. />
  281. </div>
  282. </div>
  283. );
  284. return (
  285. <div className="social-links-edit-container">
  286. <Title level={3} className="section-title">
  287. Your Social Handles
  288. </Title>
  289. <p className="description">
  290. Add all your social media handles and links to your other profiles here.
  291. </p>
  292. <FormStatusIndicator status={submitStatus} />
  293. <Table
  294. className="social-handles-table"
  295. pagination={false}
  296. size="small"
  297. rowKey={record => `${record.platform}-${record.url}`}
  298. columns={socialHandlesColumns}
  299. dataSource={currentSocialHandles}
  300. />
  301. <Modal
  302. title="Edit Social Handle"
  303. open={displayModal}
  304. onOk={handleModalOk}
  305. onCancel={handleModalCancel}
  306. confirmLoading={modalProcessing}
  307. okButtonProps={okButtonProps}
  308. >
  309. <div className="social-handle-modal-content">
  310. <SocialDropdown
  311. iconList={availableIconsList}
  312. selectedOption={selectedOther ? OTHER_SOCIAL_HANDLE_OPTION : modalDataState.platform}
  313. onSelected={handleDropdownSelect}
  314. />
  315. {displayOther && otherField}
  316. <br />
  317. <TextField
  318. fieldName="social-url"
  319. label="URL"
  320. placeholder={PLACEHOLDERS[modalDataState.platform] || 'Url to page'}
  321. value={modalDataState.url}
  322. onChange={handleUrlChange}
  323. useTrim
  324. type="url"
  325. pattern={DEFAULT_TEXTFIELD_URL_PATTERN}
  326. />
  327. <FormStatusIndicator status={submitStatus} />
  328. </div>
  329. </Modal>
  330. <br />
  331. <Button
  332. type="primary"
  333. onClick={() => {
  334. resetModal();
  335. setDisplayModal(true);
  336. }}
  337. >
  338. Add a new social link
  339. </Button>
  340. </div>
  341. );
  342. }