Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 766 | Rev 769 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 www 1
import React, { useState, useEffect } from "react";
2
import { connect } from "react-redux";
3
import { Button, Modal } from "react-bootstrap";
4
import { useForm } from "react-hook-form";
5
import styled from "styled-components";
6
import FormErrorFeedback from "../../../shared/form-error-feedback/FormErrorFeedback";
7
import Spinner from "../../../shared/loading-spinner/Spinner";
8
import { addNotification } from "../../../redux/notification/notification.actions";
9
import {
10
  closeShareModal,
11
  openShareModal,
12
  setModalType,
13
} from "../../../redux/share-modal/shareModal.actions";
14
import { addFeed } from "../../../redux/feed/feed.actions";
15
import DropzoneComponent from "../../../shared/dropzone/DropzoneComponent";
16
import { shareModalTypes } from "../../../redux/share-modal/shareModal.types";
17
import { feedTypes } from "../../../redux/feed/feed.types";
198 steven 18
import {CKEditor} from "ckeditor4-react";
1 www 19
import {axios} from "../../../utils";
20
import ConfirmModal from "../../../shared/confirm-modal/ConfirmModal";
21
 
22
const StyledSpinnerContainer = styled.div`
23
  position: absolute;
24
  left: 0;
25
  top: 0;
26
  width: 100%;
27
  height: 100%;
28
  background: rgba(255, 255, 255, 0.4);
29
  display: flex;
30
  justify-content: center;
31
  align-items: center;
32
  z-index: 300;
33
`;
34
 
35
const ShareModal = (props) => {
36
  // Redux State Destructuring
37
  const {
38
    postUrl,
39
    isOpen,
40
    modalType,
41
    lastModalType,
42
    setModalType,
43
    feedType,
44
  } = props;
45
  // Redux dispatch Destructuring
46
  const { closeShareModal, addNotification, addFeed, openShareModal } = props;
47
  // states
48
  const [loading, setLoading] = useState(false);
49
  const [isCKEditorLoading, setIsCKEditorLoading] = useState(true);
50
  const [showConfirmModal, setShowConfirmModal] = useState(false);
51
 
52
  const {
53
    register,
54
    unregister,
55
    errors,
56
    handleSubmit,
57
    setValue,
58
    watch,
59
    getValues,
60
    clearErrors,
61
    setError,
62
  } = useForm({
63
    defaultValues: {
64
      description: "",
65
      share_width: "",
66
    },
67
  });
68
 
69
  useEffect(() => {
70
    register("description", {
71
      required: { value: "true", message: "El campo es requerido" },
72
    });
73
    register("posted_or_shared");
74
    if (
75
      modalType !== shareModalTypes.POST &&
76
      modalType !== shareModalTypes.SHARE
77
    ) {
78
      register("file", {
79
        required: { value: "true", message: "El campo es requerido" },
80
      });
81
    } else {
82
      if (!getValues("file")) unregister("file");
83
    }
84
  }, [modalType]);
85
 
86
  const recomendationText = () => {
87
    switch (modalType) {
88
      case shareModalTypes.IMAGE:
89
        return "Tamaño recomendado: 720x720";
90
      case shareModalTypes.FILE:
91
        return "solo documentos PDF";
92
      case shareModalTypes.VIDEO:
93
        return "Video de extensión mp4, mpeg, webm";
94
      default:
95
        return "";
96
    }
97
  };
98
 
99
  useEffect(() => {
100
    const postedOrShared = modalType === shareModalTypes.SHARE ? "s" : "p";
101
    setValue("posted_or_shared", postedOrShared);
102
    if (getValues("file") || getValues("description")) {
103
      if (modalType !== lastModalType) {
104
        closeShareModal();
105
        handleShowConfirmModal();
106
      }
107
    }
108
  }, [modalType]);
109
 
110
  useEffect(() => {
111
    clearErrors();
112
  }, [isOpen]);
113
 
114
  const handleShowConfirmModal = () => {
115
    setShowConfirmModal(!showConfirmModal);
116
  };
117
 
118
  const handleModalAccept = () => {
119
    setShowConfirmModal(false);
120
    setValue("description", "");
121
    setValue("file", "");
122
    openShareModal(postUrl, modalType, feedType);
123
    clearErrors();
124
  };
125
 
126
  const handleModalCancel = () => {
127
    setShowConfirmModal(false);
128
    closeShareModal();
129
    setModalType(lastModalType);
130
    openShareModal(postUrl, lastModalType, feedType);
131
  };
132
 
133
  const onSubmit = async (data, e) => {
134
    setLoading(true);
135
    const currentFormData = new FormData();
136
    for (let input in data) {
137
      currentFormData.append(input, data[input]);
138
       (`${input}:${data[input]}`);
139
    }
140
    await axios.post(postUrl, currentFormData).then((response) => {
141
      const data = response.data;
142
      const newFeed = data.data;
143
       (data);
144
      if (data.success) {
145
        closeShareModal();
146
        // reset data
147
        e.target.reset();
148
        setValue("description", "");
149
        setValue("file", "");
150
        clearErrors();
151
        addNotification({
152
          style: "success",
153
          msg: "La publicación ha sido compartida",
154
        });
155
        // if (modalType !== shareModalTypes.SHARE) {
156
          addFeed(newFeed);
157
        // }
158
      } else {
159
        if (data.data.description || data.data.file || data.data.share_width) {
160
          Object.entries(data.data).map(([key, value]) => {
161
            setError(key, { type: "required", message: value });
162
          });
163
        } else {
164
          addNotification({
165
            style: "danger",
166
            msg: "Ha ocurrido un error",
167
          });
168
        }
169
      }
170
    });
171
 
172
    setLoading(false);
173
  };
174
 
175
  const onUploadedHandler = (files) => {
176
    setValue("file", files);
177
    clearErrors("file");
178
  };
179
 
180
  const dropZoneRender = () => {
181
    if (
182
      modalType !== shareModalTypes.POST &&
183
      modalType !== shareModalTypes.SHARE
184
    ) {
185
      return (
186
        <DropzoneComponent
187
          modalType={modalType}
188
          onUploaded={onUploadedHandler}
189
          settedFile={getValues("file")}
190
          recomendationText={recomendationText()}
191
        />
192
      );
193
    }
194
  };
195
 
196
  const SharedWithSelectRender = () => {
197
    if (feedType === feedTypes.DASHBOARD) {
198
      return (
199
        <React.Fragment>
200
          <select
201
            // value={formData.shared_with}
202
            name="shared_with"
203
            id="shared_with"
204
            className="form-control"
205
            // onChange={(e) => onInputChangeHandler(e)}
206
            ref={register({
207
              required: "El campo es requerido",
208
            })}
209
            defaultValue="p"
210
          >
211
            <option disabled="disabled" value="" style={{ display: "none" }}>
212
              Compartir con
213
            </option>
214
            <option value="p">Público</option>
215
            <option value="c">Conexiones</option>
216
          </select>
217
          {errors.shared_with && (
218
            <FormErrorFeedback>{errors.shared_with.message}</FormErrorFeedback>
219
          )}
220
        </React.Fragment>
221
      );
222
    }
223
  };
224
 
225
  return (
226
    <React.Fragment>
227
      <Modal
228
        show={isOpen}
229
        onHide={closeShareModal}
230
        style={{ overflowY: "scroll" }}
231
      >
232
        <Modal.Header closeButton>
233
          <Modal.Title>Compartir una publicación</Modal.Title>
234
        </Modal.Header>
235
        <form encType="multipart/form-data" onSubmit={handleSubmit(onSubmit)}>
236
          <Modal.Body>
237
            {SharedWithSelectRender()}
238
            <CKEditor
239
              data={watch("description")}
240
              onChange={(e) => {
241
                const text = e.editor.getData();
242
                setValue("description", text);
243
                if (errors.description && getValues(description)) {
244
                  clearErrors("description");
245
                }
246
              }}
247
              config={{
248
                startupFocus: "end",
766 steven 249
                allowedContent: false,
767 steven 250
                removeButtons: 'clipboard,paste',
251
                removePlugins: 'clipboard,paste'
1 www 252
              }}
253
              name="description"
254
              onBeforeLoad={() => {
255
                setIsCKEditorLoading(false);
256
                 ("Ready");
257
              }}
258
            />
259
            {isCKEditorLoading && (
260
              <StyledSpinnerContainer>
261
                <Spinner />
262
              </StyledSpinnerContainer>
263
            )}
264
            {errors.description && (
265
              <FormErrorFeedback>
266
                {errors.description.message}
267
              </FormErrorFeedback>
268
            )}
269
 
270
            {dropZoneRender()}
271
            {errors.file && (
272
              <FormErrorFeedback>{errors.file.message}</FormErrorFeedback>
273
            )}
274
          </Modal.Body>
275
          <Modal.Footer>
276
            <Button size="sm" type="submit">Enviar</Button>
277
            <Button color="danger" size="sm" variant="danger" onClick={closeShareModal}>
278
              Cancelar
279
            </Button>
280
          </Modal.Footer>
281
        </form>
282
        {loading ? (
283
          <StyledSpinnerContainer>
284
            <Spinner />
285
          </StyledSpinnerContainer>
286
        ) : (
287
          ""
288
        )}
289
      </Modal>
290
      <ConfirmModal
291
        show={showConfirmModal}
292
        onClose={handleModalCancel}
293
        onAccept={handleModalAccept}
294
        acceptLabel="Aceptar"
295
        message="No se ha compartido tu publicación , desea descartarlo?"
296
      />
297
    </React.Fragment>
298
  );
299
};
300
 
301
const mapStateToProps = (state) => ({
302
  isOpen: state.shareModal.isOpen,
303
  postUrl: state.shareModal.postUrl,
304
  modalType: state.shareModal.modalType,
305
  lastModalType: state.shareModal.lastModalType,
306
  feedType: state.shareModal.feedType,
307
});
308
 
309
const mapDispatchToProps = {
310
  addNotification: (notification) => addNotification(notification),
311
  closeShareModal: () => closeShareModal(),
312
  openShareModal: (postUrl, modalType, feedType) =>
313
    openShareModal(postUrl, modalType, feedType),
314
  setModalType: (modalType) => setModalType(modalType),
315
  addFeed: (feed) => addFeed(feed),
316
};
317
 
318
export default connect(mapStateToProps, mapDispatchToProps)(ShareModal);