Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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