Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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