"use strict";

exports.__esModule = true;
exports.POLL_VIEW = exports.MAIN_VIEW = exports.LOCATION_VIEW = exports.AUDIENCE_VIEW = void 0;
exports.default = Composer;

var _react = _interopRequireWildcard(require("react"));

var _core = require("@selfcommunity/core");

var _reactIntl = require("react-intl");

var _Icon = _interopRequireDefault(require("@mui/material/Icon"));

var _material = require("@mui/material");

var _styles = require("@mui/material/styles");

var _Composer = require("../../constants/Composer");

var _Media = require("../../constants/Media");

var _LoadingButton = _interopRequireDefault(require("@mui/lab/LoadingButton"));

var _Audience = _interopRequireDefault(require("./Audience"));

var _Categories = _interopRequireDefault(require("./Categories"));

var _string = require("../../utils/string");

var _classnames = _interopRequireDefault(require("classnames"));

var _Poll = _interopRequireDefault(require("../FeedObject/Poll"));

var _Editor = _interopRequireDefault(require("../Editor"));

var _Media2 = require("../../shared/Media");

var _MediasPreview = _interopRequireDefault(require("../../shared/MediasPreview"));

var _Poll2 = _interopRequireDefault(require("./Poll"));

var _Location = _interopRequireDefault(require("./Location"));

var _TagChip = _interopRequireDefault(require("../../shared/TagChip"));

var _index = require("./index");

var _notistack = require("notistack");

var _useThemeProps = _interopRequireDefault(require("@mui/material/styles/useThemeProps"));

const _excluded = ["feedObjectId", "feedObjectType", "feedObject", "defaultValue", "view", "mediaObjectTypes", "onClose", "onSuccess"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

const DialogTransition = /*#__PURE__*/(0, _react.forwardRef)(function Transition(props, ref) {
  return /*#__PURE__*/_react.default.createElement(_material.Fade, _extends({
    ref: ref
  }, props));
});
const TypeInput = (0, _styles.styled)(_material.InputBase, {
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  '&.Mui-InputBase-root': {
    'label + &': {
      marginTop: theme.spacing(3)
    }
  },
  '& .Mui-InputBase-input': {
    position: 'relative',
    backgroundColor: theme.palette.background.paper,
    border: 0,
    padding: '10px 26px 10px 12px'
  }
}));
const PREFIX = 'SCComposer';
const classes = {
  root: `${PREFIX}-root`,
  title: `${PREFIX}-title`,
  types: `${PREFIX}-types`,
  avatar: `${PREFIX}-avatar`,
  content: `${PREFIX}-content`,
  mediaContent: `${PREFIX}-mediaContent`,
  audienceContent: `${PREFIX}-audienceContent`,
  locationContent: `${PREFIX}-locationContent`,
  block: `${PREFIX}-block`,
  editor: `${PREFIX}-editor`,
  divider: `${PREFIX}-divider`,
  medias: `${PREFIX}-medias`,
  location: `${PREFIX}-location`,
  audience: `${PREFIX}-audience`,
  mediasActions: `${PREFIX}-mediasActions`,
  sortableMedia: `${PREFIX}-sortableMedia`,
  sortableMediaCover: `${PREFIX}-sortableMediaCover`,
  links: `${PREFIX}-links`,
  actions: `${PREFIX}-actions`,
  actionInput: `${PREFIX}-actionInput`,
  badgeError: `${PREFIX}-badgeError`
};
const Root = (0, _styles.styled)(_material.Dialog, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => {
  let mediaActionBackground = theme.palette.getContrastText(theme.palette.primary.main);

  if (mediaActionBackground.startsWith('#')) {
    mediaActionBackground = (0, _material.hexToRgb)(mediaActionBackground).replace(')', ', .5)');
  }

  return {
    [`& .${classes.title}`]: {
      borderBottom: '1px solid #D1D1D1',
      padding: theme.spacing(),
      paddingLeft: theme.spacing(2),
      paddingRight: theme.spacing(2),
      display: 'flex',
      flexDirection: 'row',
      flexWrap: 'nowrap',
      justifyContent: 'space-between',
      alignItems: 'center',
      '& > div': {
        flex: 1,
        textAlign: 'center'
      },
      '& > div:first-of-type': {
        textAlign: 'left'
      },
      '& > div:last-of-type': {
        textAlign: 'right',
        display: 'block'
      }
    },
    [`& .${classes.types}`]: {
      flexDirection: 'row',
      alignItems: 'center'
    },
    [`& .${classes.avatar}`]: {
      width: theme.spacing(4),
      height: theme.spacing(4),
      display: 'inline-block'
    },
    [`& .${classes.content}`]: {
      paddingLeft: 0,
      paddingRight: 0,
      paddingBottom: 0,
      position: 'relative',
      overflowY: 'visible'
    },
    [`& .${classes.mediaContent}, & .${classes.audienceContent}, & .${classes.locationContent}`]: {
      minHeight: 300
    },
    [`& .${classes.block}`]: {
      padding: theme.spacing(2)
    },
    [`& .${classes.editor}`]: {
      minHeight: 200
    },
    [`& .${classes.divider}`]: {
      borderTop: '1px solid #D1D1D1'
    },
    [`& .${classes.medias}`]: {
      margin: '0 23px'
    },
    [`& .${classes.location}, & .${classes.audience}`]: {
      padding: theme.spacing(2),
      paddingBottom: 0
    },
    [`& .${classes.mediasActions}`]: {
      position: 'absolute',
      left: 0,
      right: 0,
      background: mediaActionBackground,
      padding: theme.spacing(),
      zIndex: 1,
      display: 'flex',
      flexWrap: 'nowrap',
      justifyContent: 'space-between'
    },
    [`& .${classes.sortableMedia}`]: {
      position: 'relative'
    },
    [`& .${classes.sortableMediaCover}`]: {
      backgroundSize: 'cover !important',
      backgroundPosition: 'center !important',
      backgroundRepeat: 'no-repeat !important',
      border: '2px solid white',
      borderRadius: 6,
      height: 300
    },
    [`& .${classes.links}`]: {
      padding: theme.spacing(2)
    },
    [`& .${classes.actions}`]: {
      margin: 0,
      borderTop: '1px solid #D1D1D1',
      padding: theme.spacing(1),
      display: 'flex',
      flexDirection: 'row',
      flexWrap: 'nowrap',
      justifyContent: 'space-between',
      alignItems: 'center'
    },
    [`& .${classes.actionInput}`]: {
      display: 'none !important'
    },
    [`& .${classes.badgeError} .MuiBadge-badge`]: {
      padding: 0
    }
  };
});
const MAIN_VIEW = 'main';
exports.MAIN_VIEW = MAIN_VIEW;
const AUDIENCE_VIEW = 'audience';
exports.AUDIENCE_VIEW = AUDIENCE_VIEW;
const POLL_VIEW = 'poll';
exports.POLL_VIEW = POLL_VIEW;
const LOCATION_VIEW = 'location';
exports.LOCATION_VIEW = LOCATION_VIEW;
const AUDIENCE_ALL = 'all';
const AUDIENCE_TAG = 'tag';
const PREFERENCES = [_core.SCPreferences.CONFIGURATIONS_POST_TYPE_ENABLED, _core.SCPreferences.CONFIGURATIONS_DISCUSSION_TYPE_ENABLED, _core.SCPreferences.ADDONS_POST_GEOLOCATION_ENABLED, _core.SCPreferences.ADDONS_POLLS_ENABLED, _core.SCPreferences.ADDONS_VIDEO_UPLOAD_ENABLED];
const COMPOSER_INITIAL_STATE = {
  id: null,
  type: null,
  title: '',
  titleError: null,
  text: '',
  textError: null,
  categories: [],
  categoriesError: null,
  audience: AUDIENCE_ALL,
  addressing: [],
  addressingError: null,
  medias: [],
  poll: null,
  location: null,
  error: null
};

const reducer = (state, action) => {
  switch (action.type) {
    case 'reset':
      return Object.assign({}, COMPOSER_INITIAL_STATE, {
        key: (0, _string.random)()
      });

    case 'multiple':
      return Object.assign({}, state, action.value);

    default:
      return Object.assign({}, state, {
        [action.type]: action.value
      });
  }
};
/**
 > API documentation for the Community-UI Composer component. Learn about the available props and the CSS API.
 > The Composer component contains the logic around the creation of [Post](https://developers.selfcommunity.com/docs/apireference/v2/post/create_a_post) and [Discussion](https://developers.selfcommunity.com/docs/apireference/v2/discussion/create_a_discussion) objects.
 *
 #### Import
 ```jsx
 import {Composer} from '@selfcommunity/ui';
 ```
 #### Component Name
 The name `SCComposer` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCComposer-root|Styles applied to the root element.|
 |title|.SCComposer-title|Styles applied to the title element.|
 |types|.SCComposer-types|Styles applied to the types element.|
 |avatar|.SCComposer-avatar|Styles applied to the avatar element.|
 |content|.SCComposer-content|Styles applied to the content.|
 |mediaContent|.SCComposer-mediaContent|Styles applied to the media content.|
 |audienceContent|.SCComposer-audienceContent|Styles applied to the audience content.|
 |locationContent|.SCComposer-locationContent|Styles applied to the location content.|
 |block|.SCComposer-block|Styles applied to the block element.|
 |editor|.SCComposer-editor|Styles applied to the editor element.|
 |divider|.SCComposer-divider|Styles applied to the divider element.|
 |medias|.SCComposer-medias|Styles applied to the medias.|
 |location|.SCComposer-location|Styles applied to the location element.|
 |audience|.SCComposer-audience|Styles applied to the audience element.|
 |mediasActions|.SCComposer-mediasActions|Styles applied to the medias actions section.|
 |sortableMedia|.SCComposer-sortableMedia|Styles applied to the sortable media element.|
 |sortableMediaCover|.SCComposer-sortableMediaCover|Styles applied to the sortable media cover element.|
 |links|.SCComposer-links|Styles applied to the links element.|
 |actions|.SCComposer-actions|Styles applied to the actions section.|
 |actionInput|.SCComposer-actionInput|Styles applied to the action input element.|
 |badgeError|.SCComposer-badgeError|Styles applied to the badge error element.|


 * @param inProps
 */


function Composer(inProps) {
  // PROPS
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });

  const {
    feedObjectId = null,
    feedObjectType = null,
    feedObject = null,
    defaultValue = {},
    view = MAIN_VIEW,
    mediaObjectTypes = [_Media2.Image, _Media2.Document, _Media2.Link, _Media2.Share],
    onClose = null,
    onSuccess = null
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // Context


  const scPrefernces = (0, _react.useContext)(_core.SCPreferencesContext);
  const scAuthContext = (0, _react.useContext)(_core.SCUserContext);
  const {
    enqueueSnackbar
  } = (0, _notistack.useSnackbar)(); // State variables

  const [fades, setFades] = (0, _react.useState)({});
  const [isSubmitting, setIsSubmitting] = (0, _react.useState)(false);
  const [_view, setView] = (0, _react.useState)(view);
  const [composerTypes, setComposerTypes] = (0, _react.useState)([]);
  const [mediaChunks, setMediaChunks] = (0, _react.useState)([]);
  const [state, dispatch] = (0, _react.useReducer)(reducer, Object.assign({}, COMPOSER_INITIAL_STATE, defaultValue, {
    view,
    key: (0, _string.random)()
  }));
  const {
    key,
    id,
    type,
    title,
    titleError,
    text,
    categories,
    addressing,
    audience,
    medias,
    poll,
    pollError,
    location,
    error
  } = state;

  const addMedia = media => {
    dispatch({
      type: 'medias',
      value: [...medias, media]
    });
  };

  const destructureFeedObject = _feedObject => {
    if (_feedObject.type === _Composer.COMPOSER_TYPE_POST) {
      _feedObject = _feedObject;
    } else if (_feedObject.type === _Composer.COMPOSER_TYPE_DISCUSSION) {
      _feedObject = _feedObject;
    } else {
      _feedObject = _feedObject;
    }

    if (feedObject.author.id === scAuthContext.user.id) {
      dispatch({
        type: 'multiple',
        value: {
          id: _feedObject.id,
          type: _feedObject.type,
          title: _feedObject.title,
          text: _feedObject.html,
          categories: _feedObject.categories,
          audience: _feedObject.addressing ? AUDIENCE_TAG : AUDIENCE_ALL,
          addressing: _feedObject.addressing,
          medias: _feedObject.medias,
          poll: _feedObject.poll,
          location: _feedObject.location
        }
      });
    } else {
      setLoadError(true);
    }
  }; // Edit state variables


  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [loadError, setLoadError] = (0, _react.useState)(false);
  const editMode = Boolean(feedObjectId && feedObjectType || feedObject); // REFS

  const unloadRef = _react.default.useRef(false); // Create a ref for medias becaouse of state update error on chunk upload


  const mediasRef = _react.default.useRef({
    medias,
    mediaChunks,
    addMedia,
    setMediaChunks
  });

  mediasRef.current = {
    medias,
    mediaChunks,
    addMedia,
    setMediaChunks
  };
  /*
   * Compute preferences
   */

  const preferences = (0, _react.useMemo)(() => {
    const _preferences = {};
    PREFERENCES.map(p => _preferences[p] = p in scPrefernces.preferences ? scPrefernces.preferences[p].value : null);
    return _preferences;
  }, [scPrefernces.preferences]);
  /*
   * Compose the enabled types of posts that can be created based on preferences
   */

  const setEnabledComposerTypes = () => {
    const types = [];

    if (preferences[_core.SCPreferences.CONFIGURATIONS_POST_TYPE_ENABLED]) {
      types.push(_Composer.COMPOSER_TYPE_POST);
    }

    if (preferences[_core.SCPreferences.CONFIGURATIONS_DISCUSSION_TYPE_ENABLED]) {
      types.push(_Composer.COMPOSER_TYPE_DISCUSSION);
    }

    if (!type) {
      dispatch({
        type: 'type',
        value: preferences[_core.SCPreferences.CONFIGURATIONS_POST_TYPE_ENABLED] ? _Composer.COMPOSER_TYPE_POST : _Composer.COMPOSER_TYPE_DISCUSSION
      });
    }

    if (JSON.stringify(composerTypes) !== JSON.stringify(types)) {
      setComposerTypes(types);
    }
  };

  setEnabledComposerTypes(); // Load feed object

  (0, _react.useEffect)(() => {
    if (!editMode) {
      return;
    } else if (feedObject !== null) {
      destructureFeedObject(feedObject);
      return;
    }

    setIsLoading(true);

    _core.http.request({
      url: _core.Endpoints.FeedObject.url({
        type: feedObjectType,
        id: feedObjectId
      }),
      method: _core.Endpoints.FeedObject.method
    }).then(res => {
      destructureFeedObject(res.data);
    }).catch(() => {
      setLoadError(true);
    }).then(() => setIsLoading(false));
  }, [editMode]); // Props update

  (0, _react.useEffect)(() => setView(view), [view]); // Prevent unload

  (0, _react.useEffect)(() => {
    if (!unloadRef.current && canSubmit()) {
      unloadRef.current = true;

      const onUnload = event => {
        event.preventDefault();
        return '';
      };

      window.onbeforeunload = onUnload;
    } else if (unloadRef.current && !canSubmit()) {
      unloadRef.current = false;
      window.onbeforeunload = null;
    }
  }, [state]); // CHECKS

  const hasPoll = () => {
    return poll && poll.title.length > 0 && poll.choices.length >= _Composer.COMPOSER_POLL_MIN_CHOICES;
  };

  const canSubmit = () => {
    return type === _Composer.COMPOSER_TYPE_DISCUSSION && title.length > 0 || type === _Composer.COMPOSER_TYPE_POST && ((0, _string.stripHtml)(text).length > 0 || medias.length > 0 || hasPoll());
  };
  /* Handlers */


  const handleChangeView = view => {
    return event => {
      setView(view);
    };
  };

  const handleChangeType = (event, child) => {
    const target = event.target;
    dispatch({
      type: 'type',
      value: target.value
    });
  };

  const handleChangeText = value => {
    dispatch({
      type: 'text',
      value
    });
  };

  const handleChangePoll = poll => {
    dispatch({
      type: 'poll',
      value: poll
    });
  };

  const handleChange = prop => (event, data) => {
    let target = null;

    switch (prop) {
      case 'title':
        target = event.target;
        dispatch({
          type: 'multiple',
          value: {
            title: target.value,
            titleError: target.value.length > _Composer.COMPOSER_TITLE_MAX_LENGTH ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
              id: "ui.composer.title.error.maxlength",
              defaultMessage: "ui.composer.title.error.maxlength"
            }) : null
          }
        });
        break;

      case 'categories':
      case 'addressing':
      case 'location':
        dispatch({
          type: prop,
          value: event
        });
        break;

      case 'audience':
        data !== null && dispatch({
          type: 'multiple',
          value: {
            audience: data,
            addressing: audience === AUDIENCE_ALL ? [] : audience
          }
        });
        break;

      default:
        target = event.target;
        dispatch({
          type: prop,
          value: target.value
        });
        break;
    }
  };

  const handleClose = event => {
    if (unloadRef.current) {
      window.onbeforeunload = null;
    }

    onClose && onClose(event);
  };

  const handleDeletePoll = event => {
    dispatch({
      type: 'poll',
      value: null
    });
    setView(MAIN_VIEW);
  };

  const handleDeleteLocation = event => {
    dispatch({
      type: 'location',
      value: null
    });
  };

  const handleDeleteTag = id => event => {
    const _addressing = addressing.filter(t => t.id !== id);

    dispatch({
      type: 'multiple',
      value: {
        audience: _addressing.length === 0 ? AUDIENCE_ALL : AUDIENCE_TAG,
        addressing: _addressing
      }
    });
  };

  const handleFadeIn = obj => {
    return event => setFades(Object.assign({}, fades, {
      [obj]: true
    }));
  };

  const handleFadeOut = obj => {
    return event => setFades(Object.assign({}, fades, {
      [obj]: false
    }));
  };

  const handleDeleteMedia = (id, mediaObjectType) => {
    return event => {
      if (id) {
        dispatch({
          type: 'medias',
          value: medias.filter(m => m.id != id)
        });
      } else if (mediaObjectType) {
        dispatch({
          type: 'medias',
          value: medias.filter(m => !mediaObjectType.filter(m))
        });
      }
    };
  };

  const handleMediaProgress = chunks => {
    mediasRef.current.setMediaChunks(chunks);
  };

  const handleAddMedia = media => {
    mediasRef.current.addMedia(media);
  };

  const handleSortMedia = newSort => {
    dispatch({
      type: 'medias',
      value: [...medias.filter(media => newSort.findIndex(m => m.id === media.id) === -1), ...newSort]
    });
  };

  const handleSubmit = event => {
    if (_core.UserUtils.isBlocked(scAuthContext.user)) {
      // deny submit action if authenticated user is blocked
      enqueueSnackbar( /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.common.userBlocked",
        defaultMessage: "ui.common.userBlocked"
      }), {
        variant: 'warning',
        autoHideDuration: 3000
      });
      return;
    }

    const data = {
      title,
      text,
      medias: medias.map(m => m.id),
      categories: categories.map(c => c.id)
    };

    if (preferences[_core.SCPreferences.ADDONS_POLLS_ENABLED] && hasPoll()) {
      data.poll = poll;
    }

    if (preferences[_core.SCPreferences.ADDONS_POST_GEOLOCATION_ENABLED] && location) {
      data.location = {
        location: location.full_address,
        lat: location.lat,
        lng: location.lng
      };
    }

    if (scPrefernces.features.includes(_core.SCFeatures.USER_TAGGING) && audience === AUDIENCE_TAG) {
      data.addressing = addressing.map(t => t.id);
    }

    setIsSubmitting(true); // Finding right url

    let url = _core.Endpoints.Composer.url({
      type
    });

    let method = _core.Endpoints.Composer.method;

    if (editMode) {
      url = _core.Endpoints.ComposerEdit.url({
        type,
        id
      });
      method = _core.Endpoints.ComposerEdit.method;
    } // Perform request


    _core.http.request({
      url,
      method,
      data
    }).then(res => {
      onSuccess(res.data);

      if (unloadRef.current) {
        window.onbeforeunload = null;
      }

      dispatch({
        type: 'reset'
      });
    }).catch(error => {
      dispatch({
        type: 'multiple',
        value: (0, _core.formatHttpError)(error)
      });
    }).then(() => setIsSubmitting(false));
  };
  /* Renderers */


  const hasMediaShare = (0, _react.useMemo)(() => medias.findIndex(m => m.type === _Media.MEDIA_TYPE_SHARE) !== -1, [medias]);

  const renderMediaAdornment = mediaObjectType => {
    return /*#__PURE__*/_react.default.createElement(_material.Box, {
      className: classes.mediasActions,
      onMouseEnter: handleFadeIn(mediaObjectType.name),
      onMouseLeave: handleFadeOut(mediaObjectType.name)
    }, /*#__PURE__*/_react.default.createElement(_material.Fade, {
      in: Boolean(fades[mediaObjectType.name])
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      align: "left"
    }, /*#__PURE__*/_react.default.createElement(_material.Button, {
      onClick: handleChangeView(mediaObjectType.name),
      variant: "text",
      size: "small"
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: `ui.composer.media.${mediaObjectType.name}.edit`,
      defaultMessage: `ui.composer.media.${mediaObjectType.name}.edit`
    })))), /*#__PURE__*/_react.default.createElement(_material.Typography, {
      align: "right"
    }, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      onClick: handleDeleteMedia(null, mediaObjectType),
      size: "small",
      color: "primary"
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "delete"))));
  };

  const renderAudienceView = () => {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.DialogTitle, {
      className: classes.title
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "div"
    }, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      onClick: handleChangeView(MAIN_VIEW),
      size: "small"
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "arrow_back")), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.audience.title",
      defaultMessage: "ui.composer.audience.title"
    })), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.Avatar, {
      className: classes.avatar,
      src: scAuthContext.user.avatar
    })), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.Button, {
      onClick: handleChangeView(MAIN_VIEW),
      variant: "text",
      color: "inherit"
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.done",
      defaultMessage: "ui.composer.done"
    })))), /*#__PURE__*/_react.default.createElement(_material.DialogContent, {
      className: classes.audienceContent
    }, /*#__PURE__*/_react.default.createElement(_material.Box, {
      sx: {
        textAlign: 'center'
      },
      className: classes.block
    }, /*#__PURE__*/_react.default.createElement(_material.ToggleButtonGroup, {
      value: audience,
      exclusive: true,
      onChange: handleChange('audience')
    }, /*#__PURE__*/_react.default.createElement(_material.ToggleButton, {
      value: AUDIENCE_ALL,
      size: "small"
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "public"), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.audience.all",
      defaultMessage: "ui.composer.audience.all"
    })), /*#__PURE__*/_react.default.createElement(_material.ToggleButton, {
      value: AUDIENCE_TAG,
      size: "small"
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "label"), " ", /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.audience.tag",
      defaultMessage: "ui.composer.audience.tag"
    })))), /*#__PURE__*/_react.default.createElement(_material.Typography, {
      align: "center",
      className: classes.block,
      gutterBottom: true
    }, audience === AUDIENCE_ALL && /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.audience.all.message",
      defaultMessage: "ui.composer.audience.all.message"
    }), audience === AUDIENCE_TAG && /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.audience.tag.message",
      defaultMessage: "ui.composer.audience.tag.message"
    })), audience === AUDIENCE_TAG && /*#__PURE__*/_react.default.createElement(_material.Box, {
      className: classes.divider
    }, /*#__PURE__*/_react.default.createElement(_material.Box, {
      className: classes.block,
      sx: {
        textAlign: 'center'
      }
    }, /*#__PURE__*/_react.default.createElement(_Audience.default, {
      onChange: handleChange('addressing'),
      defaultValue: addressing
    })))));
  };

  const renderMediaView = mediaObjectType => {
    return () => {
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.DialogTitle, {
        className: classes.title
      }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
        component: "div"
      }, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
        onClick: handleChangeView(MAIN_VIEW),
        size: "small",
        disabled: mediasRef.current.mediaChunks.length > 0
      }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "arrow_back")), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: `ui.composer.media.${mediaObjectType.name}.edit`,
        defaultMessage: `ui.composer.media.${mediaObjectType.name}.edit`
      })), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.Avatar, {
        className: classes.avatar,
        src: scAuthContext.user.avatar
      })), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.Button, {
        onClick: handleChangeView(MAIN_VIEW),
        variant: "text",
        color: "inherit",
        disabled: mediasRef.current.mediaChunks.length > 0
      }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.composer.done",
        defaultMessage: "ui.composer.done"
      })))), /*#__PURE__*/_react.default.createElement(_material.DialogContent, {
        className: (0, _classnames.default)(classes.content, classes.mediaContent)
      }, /*#__PURE__*/_react.default.createElement(mediaObjectType.editComponent, {
        medias: medias.filter(mediaObjectType.filter),
        onProgress: handleMediaProgress,
        onSuccess: handleAddMedia,
        onSort: handleSortMedia,
        onDelete: handleDeleteMedia
      })));
    };
  };

  const renderPollView = () => {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.DialogTitle, {
      className: classes.title
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "div"
    }, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      onClick: handleChangeView(MAIN_VIEW),
      size: "small",
      disabled: !hasPoll()
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "arrow_back")), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.poll.title",
      defaultMessage: "ui.composer.poll.title"
    })), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.Avatar, {
      className: classes.avatar,
      src: scAuthContext.user.avatar
    })), /*#__PURE__*/_react.default.createElement(_material.Stack, {
      spacing: 2,
      direction: "row"
    }, /*#__PURE__*/_react.default.createElement(_material.Button, {
      onClick: handleDeletePoll,
      variant: "text",
      color: "inherit"
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.delete",
      defaultMessage: "ui.composer.delete"
    })), /*#__PURE__*/_react.default.createElement(_material.Button, {
      onClick: handleChangeView(MAIN_VIEW),
      variant: "text",
      color: "inherit",
      disabled: !hasPoll()
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.done",
      defaultMessage: "ui.composer.done"
    })))), /*#__PURE__*/_react.default.createElement(_material.DialogContent, {
      className: classes.content
    }, /*#__PURE__*/_react.default.createElement(_Poll2.default, {
      onChange: handleChangePoll,
      value: poll,
      error: pollError
    })));
  };

  const renderLocationView = () => {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.DialogTitle, {
      className: classes.title
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "div"
    }, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      onClick: handleChangeView(MAIN_VIEW),
      size: "small"
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "arrow_back")), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.location.title",
      defaultMessage: "ui.composer.location.title"
    })), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.Avatar, {
      className: classes.avatar,
      src: scAuthContext.user.avatar
    })), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.Button, {
      onClick: handleChangeView(MAIN_VIEW),
      variant: "text",
      color: "inherit"
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.done",
      defaultMessage: "ui.composer.done"
    })))), /*#__PURE__*/_react.default.createElement(_material.DialogContent, {
      className: classes.locationContent
    }, /*#__PURE__*/_react.default.createElement(_Location.default, {
      onChange: handleChange('location'),
      defaultValue: location
    })));
  };

  const renderMainView = () => {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.DialogTitle, {
      className: classes.title
    }, /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.FormControl, {
      className: classes.types
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "create"), /*#__PURE__*/_react.default.createElement(_material.Select, {
      value: type,
      onChange: handleChangeType,
      input: /*#__PURE__*/_react.default.createElement(TypeInput, null),
      disabled: editMode
    }, composerTypes.map(t => /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      value: t,
      key: t
    }, t === 'post' ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: 'ui.composer.type.post',
      defaultMessage: 'ui.composer.type.post'
    }) : /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: 'ui.composer.type.discussion',
      defaultMessage: 'ui.composer.type.discussion'
    })))))), /*#__PURE__*/_react.default.createElement(_material.Box, null, !scAuthContext.user ? /*#__PURE__*/_react.default.createElement(_material.Avatar, {
      className: classes.avatar
    }) : /*#__PURE__*/_react.default.createElement(_material.Avatar, {
      className: classes.avatar,
      src: scAuthContext.user.avatar
    })), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      onClick: handleClose
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "highlight_off")))), /*#__PURE__*/_react.default.createElement(_material.DialogContent, {
      className: classes.content
    }, type === _Composer.COMPOSER_TYPE_DISCUSSION && /*#__PURE__*/_react.default.createElement("div", {
      className: classes.block
    }, /*#__PURE__*/_react.default.createElement(_material.TextField, {
      label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.composer.title.label",
        defaultMessage: "ui.composer.title.label"
      }),
      fullWidth: true,
      variant: "outlined",
      value: title,
      multiline: true,
      onChange: handleChange('title'),
      InputProps: {
        endAdornment: /*#__PURE__*/_react.default.createElement(_material.Typography, {
          variant: "body2"
        }, _Composer.COMPOSER_TITLE_MAX_LENGTH - title.length)
      },
      error: Boolean(titleError),
      helperText: titleError,
      disabled: isSubmitting
    })), /*#__PURE__*/_react.default.createElement(_Editor.default, {
      key: `${key}-editor`,
      className: (0, _classnames.default)(classes.block, classes.editor),
      onChange: handleChangeText,
      defaultValue: text,
      readOnly: isSubmitting
    }), /*#__PURE__*/_react.default.createElement(_material.Box, {
      className: classes.medias
    }, /*#__PURE__*/_react.default.createElement(_MediasPreview.default, {
      medias: medias,
      mediaObjectTypes: mediaObjectTypes.map(mediaObjectType => {
        return Object.assign({}, mediaObjectType, {
          previewProps: {
            adornment: mediaObjectType.editButton !== null ? renderMediaAdornment(mediaObjectType) : null,
            gallery: false
          }
        });
      })
    })), poll && /*#__PURE__*/_react.default.createElement(_Poll.default, {
      pollObject: poll
    }), /*#__PURE__*/_react.default.createElement(_material.Stack, {
      spacing: 2,
      className: classes.audience,
      direction: "row"
    }, location && /*#__PURE__*/_react.default.createElement(_material.Chip, {
      icon: /*#__PURE__*/_react.default.createElement(_Icon.default, null, "add_location_alt"),
      label: location.full_address,
      onDelete: handleDeleteLocation,
      onClick: handleChangeView(LOCATION_VIEW)
    }), audience === AUDIENCE_TAG && addressing && addressing.map(t => /*#__PURE__*/_react.default.createElement(_TagChip.default, {
      key: t.id,
      tag: t,
      onDelete: handleDeleteTag(t.id),
      icon: /*#__PURE__*/_react.default.createElement(_Icon.default, null, "label"),
      onClick: handleChangeView(AUDIENCE_VIEW)
    }))), /*#__PURE__*/_react.default.createElement("div", {
      className: classes.block
    }, /*#__PURE__*/_react.default.createElement(_Categories.default, {
      key: `${key}-categories`,
      onChange: handleChange('categories'),
      defaultValue: categories,
      disabled: isSubmitting
    })), error && /*#__PURE__*/_react.default.createElement(_material.Typography, {
      className: classes.block,
      color: "error"
    }, error)), /*#__PURE__*/_react.default.createElement(_material.DialogActions, {
      className: classes.actions
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      align: "left"
    }, mediaObjectTypes.filter(mediaObjectType => mediaObjectType.editButton !== null).map(mediaObjectType => /*#__PURE__*/_react.default.createElement(mediaObjectType.editButton, {
      key: mediaObjectType.name,
      onClick: handleChangeView(mediaObjectType.name),
      disabled: isSubmitting || hasMediaShare,
      color: medias.filter(mediaObjectType.filter).length > 0 ? 'primary' : 'default'
    })), preferences[_core.SCPreferences.ADDONS_POLLS_ENABLED] && /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      "aria-label": "add poll",
      color: poll ? 'primary' : 'default',
      disabled: isSubmitting,
      onClick: handleChangeView(POLL_VIEW)
    }, /*#__PURE__*/_react.default.createElement(_material.Badge, {
      className: classes.badgeError,
      badgeContent: pollError ? /*#__PURE__*/_react.default.createElement(_Icon.default, {
        fontSize: "small"
      }, "error_outline") : null,
      color: "error"
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "bar_chart")))), /*#__PURE__*/_react.default.createElement(_material.Typography, {
      align: "right"
    }, preferences[_core.SCPreferences.ADDONS_POST_GEOLOCATION_ENABLED] && /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      disabled: isSubmitting,
      onClick: handleChangeView(LOCATION_VIEW),
      color: location !== null ? 'primary' : 'default'
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "add_location_alt")), scPrefernces.features.includes(_core.SCFeatures.USER_TAGGING) && /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      disabled: isSubmitting,
      onClick: handleChangeView(AUDIENCE_VIEW)
    }, audience === AUDIENCE_TAG ? /*#__PURE__*/_react.default.createElement(_Icon.default, null, "label") : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "public")), /*#__PURE__*/_react.default.createElement(_LoadingButton.default, {
      onClick: handleSubmit,
      color: "primary",
      variant: "contained",
      disabled: !canSubmit(),
      loading: isSubmitting
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.submit",
      defaultMessage: "ui.composer.submit"
    })))));
  };

  let child = null;

  switch (_view) {
    case MAIN_VIEW:
      child = renderMainView;
      break;

    case POLL_VIEW:
      child = renderPollView;
      break;

    case AUDIENCE_VIEW:
      child = renderAudienceView;
      break;

    case LOCATION_VIEW:
      child = renderLocationView;
      break;

    default:
      const media = mediaObjectTypes.filter(mediaObjectType => mediaObjectType.editComponent !== null).find(mv => mv.name === _view);
      child = media ? renderMediaView(media) : renderMainView;
  }

  if (editMode && isLoading) {
    child = () => /*#__PURE__*/_react.default.createElement(_index.ComposerSkeleton, null);
  } else if (editMode && loadError) {
    child = () => /*#__PURE__*/_react.default.createElement(_material.Alert, {
      severity: "error",
      onClose: handleClose
    }, /*#__PURE__*/_react.default.createElement(_material.AlertTitle, null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.edit.error.title",
      defaultMessage: "ui.composer.edit.error.title"
    })), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.edit.error.content",
      defaultMessage: "ui.composer.edit.error.content"
    }));
  }

  const theme = (0, _styles.useTheme)();
  const fullScreen = (0, _material.useMediaQuery)(theme.breakpoints.down('md'));

  if (!scAuthContext.user) {
    return null;
  }

  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    TransitionComponent: DialogTransition,
    keepMounted: true,
    onClose: handleClose
  }, rest, {
    className: classes.root,
    fullScreen: fullScreen
  }), child());
}