Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 857 | Rev 862 | 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}
859 steven 229
        className="test"
230
        containerClassName="test-container"
1 www 231
        onHide={closeShareModal}
857 steven 232
        style={{ overflowY: "scroll", display: 'flex' }}
1 www 233
      >
234
        <Modal.Header closeButton>
235
          <Modal.Title>Compartir una publicación</Modal.Title>
236
        </Modal.Header>
237
        <form encType="multipart/form-data" onSubmit={handleSubmit(onSubmit)}>
238
          <Modal.Body>
239
            {SharedWithSelectRender()}
240
            <CKEditor
241
              data={watch("description")}
242
              onChange={(e) => {
243
                const text = e.editor.getData();
244
                setValue("description", text);
245
                if (errors.description && getValues(description)) {
246
                  clearErrors("description");
247
                }
248
              }}
249
              config={{
250
                startupFocus: "end",
766 steven 251
                allowedContent: false,
771 steven 252
                toolbarGroups: [
774 steven 253
                  // { name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
775 steven 254
                  // { name: 'clipboard',   groups: [ 'undo' ] },
773 steven 255
                  { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
256
                  { name: 'forms' },
257
                  { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
258
                  { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
259
                  { name: 'links' },
260
                  { name: 'insert' },
771 steven 261
                  { name: 'styles' },
262
                  { name: 'colors' },
263
                  { name: 'tools' },
264
                  { name: 'others' },
265
                ]
266
                // removeButtons: 'Clipboard,Paste',
267
                // removePlugins: 'Clipboard,Paste'
1 www 268
              }}
269
              name="description"
270
              onBeforeLoad={() => {
271
                setIsCKEditorLoading(false);
272
                 ("Ready");
273
              }}
274
            />
275
            {isCKEditorLoading && (
276
              <StyledSpinnerContainer>
277
                <Spinner />
278
              </StyledSpinnerContainer>
279
            )}
280
            {errors.description && (
281
              <FormErrorFeedback>
282
                {errors.description.message}
283
              </FormErrorFeedback>
284
            )}
285
 
286
            {dropZoneRender()}
287
            {errors.file && (
288
              <FormErrorFeedback>{errors.file.message}</FormErrorFeedback>
289
            )}
290
          </Modal.Body>
291
          <Modal.Footer>
292
            <Button size="sm" type="submit">Enviar</Button>
293
            <Button color="danger" size="sm" variant="danger" onClick={closeShareModal}>
294
              Cancelar
295
            </Button>
296
          </Modal.Footer>
297
        </form>
298
        {loading ? (
299
          <StyledSpinnerContainer>
300
            <Spinner />
301
          </StyledSpinnerContainer>
302
        ) : (
303
          ""
304
        )}
305
      </Modal>
306
      <ConfirmModal
307
        show={showConfirmModal}
308
        onClose={handleModalCancel}
309
        onAccept={handleModalAccept}
310
        acceptLabel="Aceptar"
311
        message="No se ha compartido tu publicación , desea descartarlo?"
312
      />
313
    </React.Fragment>
314
  );
315
};
316
 
317
const mapStateToProps = (state) => ({
318
  isOpen: state.shareModal.isOpen,
319
  postUrl: state.shareModal.postUrl,
320
  modalType: state.shareModal.modalType,
321
  lastModalType: state.shareModal.lastModalType,
322
  feedType: state.shareModal.feedType,
323
});
324
 
325
const mapDispatchToProps = {
326
  addNotification: (notification) => addNotification(notification),
327
  closeShareModal: () => closeShareModal(),
328
  openShareModal: (postUrl, modalType, feedType) =>
329
    openShareModal(postUrl, modalType, feedType),
330
  setModalType: (modalType) => setModalType(modalType),
331
  addFeed: (feed) => addFeed(feed),
332
};
333
 
334
export default connect(mapStateToProps, mapDispatchToProps)(ShareModal);