Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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