Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 862 | Rev 868 | 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}
864 steven 229
        className="d-flex no-scroll-modal"
1 www 230
        onHide={closeShareModal}
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,
771 steven 250
                toolbarGroups: [
774 steven 251
                  // { name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
775 steven 252
                  // { name: 'clipboard',   groups: [ 'undo' ] },
773 steven 253
                  { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
254
                  { name: 'forms' },
255
                  { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
256
                  { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
257
                  { name: 'links' },
258
                  { name: 'insert' },
771 steven 259
                  { name: 'styles' },
260
                  { name: 'colors' },
261
                  { name: 'tools' },
262
                  { name: 'others' },
263
                ]
264
                // removeButtons: 'Clipboard,Paste',
265
                // removePlugins: 'Clipboard,Paste'
1 www 266
              }}
267
              name="description"
268
              onBeforeLoad={() => {
269
                setIsCKEditorLoading(false);
270
                 ("Ready");
271
              }}
272
            />
273
            {isCKEditorLoading && (
274
              <StyledSpinnerContainer>
275
                <Spinner />
276
              </StyledSpinnerContainer>
277
            )}
278
            {errors.description && (
279
              <FormErrorFeedback>
280
                {errors.description.message}
281
              </FormErrorFeedback>
282
            )}
283
 
284
            {dropZoneRender()}
285
            {errors.file && (
286
              <FormErrorFeedback>{errors.file.message}</FormErrorFeedback>
287
            )}
288
          </Modal.Body>
289
          <Modal.Footer>
290
            <Button size="sm" type="submit">Enviar</Button>
291
            <Button color="danger" size="sm" variant="danger" onClick={closeShareModal}>
292
              Cancelar
293
            </Button>
294
          </Modal.Footer>
295
        </form>
296
        {loading ? (
297
          <StyledSpinnerContainer>
298
            <Spinner />
299
          </StyledSpinnerContainer>
300
        ) : (
301
          ""
302
        )}
303
      </Modal>
304
      <ConfirmModal
305
        show={showConfirmModal}
306
        onClose={handleModalCancel}
307
        onAccept={handleModalAccept}
308
        acceptLabel="Aceptar"
309
        message="No se ha compartido tu publicación , desea descartarlo?"
310
      />
311
    </React.Fragment>
312
  );
313
};
314
 
315
const mapStateToProps = (state) => ({
316
  isOpen: state.shareModal.isOpen,
317
  postUrl: state.shareModal.postUrl,
318
  modalType: state.shareModal.modalType,
319
  lastModalType: state.shareModal.lastModalType,
320
  feedType: state.shareModal.feedType,
321
});
322
 
323
const mapDispatchToProps = {
324
  addNotification: (notification) => addNotification(notification),
325
  closeShareModal: () => closeShareModal(),
326
  openShareModal: (postUrl, modalType, feedType) =>
327
    openShareModal(postUrl, modalType, feedType),
328
  setModalType: (modalType) => setModalType(modalType),
329
  addFeed: (feed) => addFeed(feed),
330
};
331
 
332
export default connect(mapStateToProps, mapDispatchToProps)(ShareModal);