Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 868 | Rev 943 | 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]);
868 steven 109
  const hideDuplicatedModal = () => {
110
    setTimeout(() => {
111
      const modals = document.getElementsByClassName('modal');
870 steven 112
      if(modals.length > 0 && modals[0].style.display !== 'none'){
113
        const currentModal = modals[0];
114
        currentModal.style.display = 'none';
115
      }
868 steven 116
    }, 3000);
117
  }
1 www 118
  useEffect(() => {
119
    clearErrors();
868 steven 120
    hideDuplicatedModal();
1 www 121
  }, [isOpen]);
122
 
123
  const handleShowConfirmModal = () => {
124
    setShowConfirmModal(!showConfirmModal);
125
  };
126
 
127
  const handleModalAccept = () => {
128
    setShowConfirmModal(false);
129
    setValue("description", "");
130
    setValue("file", "");
131
    openShareModal(postUrl, modalType, feedType);
132
    clearErrors();
133
  };
134
 
135
  const handleModalCancel = () => {
136
    setShowConfirmModal(false);
137
    closeShareModal();
138
    setModalType(lastModalType);
139
    openShareModal(postUrl, lastModalType, feedType);
140
  };
141
 
142
  const onSubmit = async (data, e) => {
143
    setLoading(true);
144
    const currentFormData = new FormData();
145
    for (let input in data) {
146
      currentFormData.append(input, data[input]);
147
       (`${input}:${data[input]}`);
148
    }
149
    await axios.post(postUrl, currentFormData).then((response) => {
150
      const data = response.data;
151
      const newFeed = data.data;
152
       (data);
153
      if (data.success) {
154
        closeShareModal();
155
        // reset data
156
        e.target.reset();
157
        setValue("description", "");
158
        setValue("file", "");
159
        clearErrors();
160
        addNotification({
161
          style: "success",
162
          msg: "La publicación ha sido compartida",
163
        });
164
        // if (modalType !== shareModalTypes.SHARE) {
165
          addFeed(newFeed);
166
        // }
167
      } else {
168
        if (data.data.description || data.data.file || data.data.share_width) {
169
          Object.entries(data.data).map(([key, value]) => {
170
            setError(key, { type: "required", message: value });
171
          });
172
        } else {
173
          addNotification({
174
            style: "danger",
175
            msg: "Ha ocurrido un error",
176
          });
177
        }
178
      }
179
    });
180
 
181
    setLoading(false);
182
  };
183
 
184
  const onUploadedHandler = (files) => {
185
    setValue("file", files);
186
    clearErrors("file");
187
  };
188
 
189
  const dropZoneRender = () => {
190
    if (
191
      modalType !== shareModalTypes.POST &&
192
      modalType !== shareModalTypes.SHARE
193
    ) {
194
      return (
195
        <DropzoneComponent
196
          modalType={modalType}
197
          onUploaded={onUploadedHandler}
198
          settedFile={getValues("file")}
199
          recomendationText={recomendationText()}
200
        />
201
      );
202
    }
203
  };
204
 
205
  const SharedWithSelectRender = () => {
206
    if (feedType === feedTypes.DASHBOARD) {
207
      return (
208
        <React.Fragment>
209
          <select
210
            // value={formData.shared_with}
211
            name="shared_with"
212
            id="shared_with"
213
            className="form-control"
214
            // onChange={(e) => onInputChangeHandler(e)}
215
            ref={register({
216
              required: "El campo es requerido",
217
            })}
218
            defaultValue="p"
219
          >
220
            <option disabled="disabled" value="" style={{ display: "none" }}>
221
              Compartir con
222
            </option>
223
            <option value="p">Público</option>
224
            <option value="c">Conexiones</option>
225
          </select>
226
          {errors.shared_with && (
227
            <FormErrorFeedback>{errors.shared_with.message}</FormErrorFeedback>
228
          )}
229
        </React.Fragment>
230
      );
231
    }
232
  };
233
 
234
  return (
235
    <React.Fragment>
236
      <Modal
237
        show={isOpen}
238
        onHide={closeShareModal}
239
      >
240
        <Modal.Header closeButton>
241
          <Modal.Title>Compartir una publicación</Modal.Title>
242
        </Modal.Header>
243
        <form encType="multipart/form-data" onSubmit={handleSubmit(onSubmit)}>
244
          <Modal.Body>
245
            {SharedWithSelectRender()}
246
            <CKEditor
247
              data={watch("description")}
248
              onChange={(e) => {
249
                const text = e.editor.getData();
250
                setValue("description", text);
251
                if (errors.description && getValues(description)) {
252
                  clearErrors("description");
253
                }
254
              }}
255
              config={{
256
                startupFocus: "end",
766 steven 257
                allowedContent: false,
771 steven 258
                toolbarGroups: [
774 steven 259
                  // { name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
775 steven 260
                  // { name: 'clipboard',   groups: [ 'undo' ] },
773 steven 261
                  { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
262
                  { name: 'forms' },
263
                  { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
264
                  { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
265
                  { name: 'links' },
266
                  { name: 'insert' },
771 steven 267
                  { name: 'styles' },
268
                  { name: 'colors' },
269
                  { name: 'tools' },
270
                  { name: 'others' },
271
                ]
272
                // removeButtons: 'Clipboard,Paste',
273
                // removePlugins: 'Clipboard,Paste'
1 www 274
              }}
275
              name="description"
276
              onBeforeLoad={() => {
277
                setIsCKEditorLoading(false);
278
                 ("Ready");
279
              }}
280
            />
281
            {isCKEditorLoading && (
282
              <StyledSpinnerContainer>
283
                <Spinner />
284
              </StyledSpinnerContainer>
285
            )}
286
            {errors.description && (
287
              <FormErrorFeedback>
288
                {errors.description.message}
289
              </FormErrorFeedback>
290
            )}
291
 
292
            {dropZoneRender()}
293
            {errors.file && (
294
              <FormErrorFeedback>{errors.file.message}</FormErrorFeedback>
295
            )}
296
          </Modal.Body>
297
          <Modal.Footer>
298
            <Button size="sm" type="submit">Enviar</Button>
299
            <Button color="danger" size="sm" variant="danger" onClick={closeShareModal}>
300
              Cancelar
301
            </Button>
302
          </Modal.Footer>
303
        </form>
304
        {loading ? (
305
          <StyledSpinnerContainer>
306
            <Spinner />
307
          </StyledSpinnerContainer>
308
        ) : (
309
          ""
310
        )}
311
      </Modal>
312
      <ConfirmModal
313
        show={showConfirmModal}
314
        onClose={handleModalCancel}
315
        onAccept={handleModalAccept}
316
        acceptLabel="Aceptar"
317
        message="No se ha compartido tu publicación , desea descartarlo?"
318
      />
319
    </React.Fragment>
320
  );
321
};
322
 
323
const mapStateToProps = (state) => ({
324
  isOpen: state.shareModal.isOpen,
325
  postUrl: state.shareModal.postUrl,
326
  modalType: state.shareModal.modalType,
327
  lastModalType: state.shareModal.lastModalType,
328
  feedType: state.shareModal.feedType,
329
});
330
 
331
const mapDispatchToProps = {
332
  addNotification: (notification) => addNotification(notification),
333
  closeShareModal: () => closeShareModal(),
334
  openShareModal: (postUrl, modalType, feedType) =>
335
    openShareModal(postUrl, modalType, feedType),
336
  setModalType: (modalType) => setModalType(modalType),
337
  addFeed: (feed) => addFeed(feed),
338
};
339
 
340
export default connect(mapStateToProps, mapDispatchToProps)(ShareModal);