1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-06-16 23:00:51 +03:00

Кнопка добавления в друзья

This commit is contained in:
Denis Shakhov 2014-08-14 23:53:04 +07:00
parent ba35f40cfb
commit f379725ea9
11 changed files with 280 additions and 108 deletions

View file

@ -58,11 +58,15 @@ class ActionProfile extends Action {
*/
protected function RegisterEvent() {
$this->AddEvent('friendoffer','EventFriendOffer');
$this->AddEvent('ajaxfriendadd', 'EventAjaxFriendAdd');
$this->AddEvent('ajaxfrienddelete', 'EventAjaxFriendDelete');
$this->AddEvent('ajaxfriendaccept', 'EventAjaxFriendAccept');
$this->AddEvent('ajax-modal-add-friend', 'EventAjaxModalAddFriend');
$this->AddEvent('ajax-note-save', 'EventAjaxNoteSave');
$this->AddEvent('ajax-note-remove', 'EventAjaxNoteRemove');
$this->AddEvent('ajax-modal-complaint', 'EventAjaxModalComplaint');
$this->AddEvent('ajax-complaint-add', 'EventAjaxComplaintAdd');
@ -147,7 +151,7 @@ class ActionProfile extends Action {
*/
$oComplaint->setText(htmlspecialchars($oComplaint->getText()));
if ($this->User_AddComplaint($oComplaint)) {
$this->Message_AddNotice($this->Lang_Get('user_complaint_submit_result'),$this->Lang_Get('attention'));
$this->Message_AddNotice($this->Lang_Get('report.notices.success'),$this->Lang_Get('attention'));
/**
* Убиваем каптчу
*/
@ -730,11 +734,6 @@ class ActionProfile extends Action {
*/
$this->Stream_subscribeUser($oFriend->getUserFrom(), $oFriend->getUserTo());
$this->Stream_subscribeUser($oFriend->getUserTo(), $oFriend->getUserFrom());
$oViewerLocal=$this->GetViewerLocal();
$oViewerLocal->Assign('oUserFriend',$oFriend);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("components/user/friend_item.tpl"));
} else {
return $this->EventErrorDebug();
}
@ -868,11 +867,6 @@ class ActionProfile extends Action {
$this->Stream_write($oFriend->getUserFrom(), 'add_friend', $oFriend->getUserTo());
$this->Stream_write($oFriend->getUserTo(), 'add_friend', $oFriend->getUserFrom());
$this->Message_AddNoticeSingle($this->Lang_Get('user.friends.notices.add_success'),$this->Lang_Get('attention'));
$oViewerLocal=$this->GetViewerLocal();
$oViewerLocal->Assign('oUserFriend',$oFriend);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("components/user/friend_item.tpl"));
} else {
return $this->EventErrorDebug();
}
@ -985,10 +979,6 @@ class ActionProfile extends Action {
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
}
$oViewerLocal=$this->GetViewerLocal();
$oViewerLocal->Assign('oUserFriend',$oFriendNew);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("components/user/friend_item.tpl"));
}
/**
* Удаление пользователя из друзей
@ -1047,10 +1037,6 @@ class ActionProfile extends Action {
if( $this->User_DeleteFriend($oFriend) ) {
$this->Message_AddNoticeSingle($this->Lang_Get('user.friends.notices.remove_success'),$this->Lang_Get('attention'));
$oViewerLocal=$this->GetViewerLocal();
$oViewerLocal->Assign('oUserFriend',$oFriend);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("components/user/friend_item.tpl"));
/**
* Отправляем пользователю сообщение об удалении дружеской связи
*/
@ -1073,6 +1059,24 @@ class ActionProfile extends Action {
return $this->EventErrorDebug();
}
}
/**
* Показывает модальное окно
*/
protected function EventAjaxModalAddFriend() {
$this->Viewer_SetResponseAjax('json');
if ( ! $this->oUserCurrent ) {
return parent::EventNotFound();
}
$iTarget = (int) getRequest('target');
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('target', $iTarget, true);
$this->Viewer_AssignAjax('sText', $oViewer->Fetch("modals/modal.add_friend.tpl"));
}
/**
* Обработка подтверждения старого емайла при его смене
* TODO: Перенести в экшн Settings

View file

@ -535,6 +535,7 @@ $config['head']['default']['js'] = array(
"___path.application.web___/frontend/common/js/blog.js",
"___path.application.web___/frontend/common/js/user.js",
"___path.application.web___/frontend/common/js/user-follow.js",
"___path.application.web___/frontend/common/js/user-friend.js",
"___path.application.web___/frontend/common/js/feed.js",
"___path.application.web___/frontend/common/js/feed-blogs.js",
"___path.application.web___/frontend/common/js/activity.js",

View file

@ -48,9 +48,7 @@
* Подписаться
*/
follow: function() {
ls.ajax.load( this.option( 'urls.follow' ), { aUserList: [ this.element.data('login') ] }, function( response ) {
this.onFollow( response );
}.bind(this));
ls.ajax.load( this.option( 'urls.follow' ), { aUserList: [ this.element.data('login') ] }, this.onFollow.bind(this) );
},
/**
@ -64,9 +62,7 @@
* Отписаться
*/
unfollow: function() {
ls.ajax.load( this.option( 'urls.follow' ), { iUserId: [ this.element.data('id') ] }, function( response ) {
this.onUnfollow( response );
}.bind(this));
ls.ajax.load( this.option( 'urls.follow' ), { iUserId: [ this.element.data('id') ] }, this.onUnfollow.bind(this) );
},
/**

View file

@ -0,0 +1,175 @@
/**
* Add friend
*
* @module ls/user/friend
*
* @license GNU General Public License, version 2
* @copyright 2013 OOO "ЛС-СОФТ" {@link http://livestreetcms.com}
* @author Denis Shakhov <denis.shakhov@gmail.com>
*/
(function($) {
"use strict";
$.widget( "livestreet.lsUserFriend", {
/**
* Дефолтные опции
*/
options: {
// Ссылки
urls: {
// Добавить в друзья
add: null,
// Удалить из друзей
remove: null,
// Подтвердить
accept: null,
// Модальное окно с формой добавления
modal: null
},
selectors: {
form: '.js-user-friend-form',
text: '.js-user-friend-text'
}
},
/**
* Конструктор
*
* @constructor
* @private
*/
_create: function () {
this.target = this.element.data( 'target' );
this._on({ click: this.onClick });
},
/**
* Коллбэк вызываемый при клике на кнопку добавления в друзья
*/
onClick: function( event ) {
var status = this.getStatus();
if ( status == 'notfriends' ) {
this.showForm();
} else if ( status == 'pending' ) {
this.accept();
} else if ( status == 'added' ) {
this.remove();
} else if ( status == 'linked' ) {
this.addLinked();
}
event.stopPropagation();
event.preventDefault();
},
/**
* Получение статуса
*/
getStatus: function() {
return this.element.attr( 'data-status' );
},
/**
* Установка статуса
*/
setStatus: function( status ) {
var textElement = this.element.find( this.option( 'selectors.text' ) ),
textClass = this.option( 'selectors.text' ).slice( 1 );
if ( ~ [ 'sent', 'rejected' ].indexOf( status ) ) {
textElement.replaceWith( '<span class="' + textClass + '">' + ls.lang.get( 'user.friends.status.' + status ) + '</span>' );
} else {
textElement.replaceWith( '<a href="#" class="' + textClass + '">' + ls.lang.get( 'user.friends.status.' + status ) + '</a>' );
}
this.element.attr( 'data-status', status );
},
/**
* Показывает форму
*/
showForm: function() {
var _this = this;
ls.modal.load( this.option( 'urls.modal' ), { target: this.target }, {
aftershow: function( e, modal ) {
var form = modal.element.find( _this.option( 'selectors.form' ) ),
textarea = form.find( _this.option( 'selectors.text' ) );
textarea.focus();
form.on( 'submit', function ( event ) {
var text = textarea.val();
ls.utils.formLock( form );
ls.ajax.load( _this.option( 'urls.add' ), {
idUser: _this.target,
userText: text
}, function( response ) {
ls.utils.formUnlock( form );
if ( response.bStateError ) {
ls.msg.error( null, response.sMsg );
} else {
ls.msg.notice( null, response.sMsg );
modal.hide();
_this.setStatus( 'sent' );
}
});
event.preventDefault();
}.bind(this))
}
});
},
/**
* Повторное подтверждение
*/
addLinked: function() {
this.accept( this.option( 'urls.add' ) );
},
/**
* Подтверждение
*/
accept: function( url ) {
ls.ajax.load( url || this.option( 'urls.accept' ), {
idUser: this.target,
}, function( response ) {
if ( response.bStateError ) {
ls.msg.error( null, response.sMsg );
} else {
ls.msg.notice( null, response.sMsg );
this.setStatus( 'added' );
}
}.bind(this));
},
/**
* Удаление из друзей
*/
remove: function() {
ls.ajax.load( this.option( 'urls.remove' ), {
idUser: this.target
}, function( response ) {
if ( response.bStateError ) {
ls.msg.error(null,response.sMsg);
} else {
ls.msg.notice(null,response.sMsg);
this.setStatus( 'linked' );
}
}.bind(this));
}
});
})(jQuery);

View file

@ -90,6 +90,16 @@ ls.user = (function ($) {
}
})
// Добавление пользователя в свою активность
$('.js-user-friend').lsUserFriend({
urls: {
add: aRouter.profile + 'ajaxfriendadd/',
remove: aRouter.profile + 'ajaxfrienddelete/',
accept: aRouter.profile + 'ajaxfriendaccept/',
modal: aRouter.profile + 'ajax-modal-add-friend'
}
})
// Добавление выбранных пользователей
$(document).on('click', '.js-user-list-select-add', function (e) {
var aCheckboxes = $('.js-user-list-select').find('.js-user-list-small-checkbox:checked'),
@ -128,65 +138,6 @@ ls.user = (function ($) {
});
};
/**
* Добавление в друзья
*/
this.addFriend = function(obj, idUser, sAction){
if(sAction != 'link' && sAction != 'accept') {
var sText = $('#add_friend_text').val();
$('#add_friend_form').children().each(function(i, item){$(item).attr('disabled','disabled')});
} else {
var sText='';
}
if(sAction == 'accept') {
var url = aRouter.profile+'ajaxfriendaccept/';
} else {
var url = aRouter.profile+'ajaxfriendadd/';
}
var params = {idUser: idUser, userText: sText};
ls.hook.marker('addFriendBefore');
ls.ajax.load(url, params, function(result){
$('#add_friend_form').children().each(function(i, item){$(item).removeAttr('disabled')});
if (!result) {
ls.msg.error('Error','Please try again later');
}
if (result.bStateError) {
ls.msg.error(null,result.sMsg);
} else {
ls.msg.notice(null,result.sMsg);
$('#add_friend_form').jqmHide();
$('#add_friend_item').remove();
$('#profile_actions').prepend($($.trim(result.sToggleText)));
ls.hook.run('ls_user_add_friend_after', [idUser,sAction,result], obj);
}
});
return false;
};
/**
* Удаление из друзей
*/
this.removeFriend = function(obj,idUser,sAction) {
var url = aRouter.profile+'ajaxfrienddelete/';
var params = {idUser: idUser,sAction: sAction};
ls.hook.marker('removeFriendBefore');
ls.ajax.load(url, params, function(result) {
if (result.bStateError) {
ls.msg.error(null,result.sMsg);
} else {
ls.msg.notice(null,result.sMsg);
$('#delete_friend_item').remove();
$('#profile_actions').prepend($($.trim(result.sToggleText)));
ls.hook.run('ls_user_remove_friend_after', [idUser,sAction,result], obj);
}
});
return false;
};
/**
* Добавляет жалобу
*/

View file

@ -1248,6 +1248,16 @@ return array(
'rejected' => 'Заявка отклонена',
'sent' => 'Заявка отправлена',
// Статусы
'status' => array(
'notfriends' => '___user.friends.add___',
'added' => '___user.friends.remove___',
'pending' => '___user.friends.status.notfriends___',
'rejected' => '___user.friends.rejected___',
'sent' => '___user.friends.sent___',
'linked' => '___user.friends.status.notfriends___',
),
// Форма добавления в друзья
'form' => array(
'title' => '___user.friends.add___',

View file

@ -127,6 +127,7 @@
.block-type-profile-actions { border: none; }
.block-type-profile-actions .block-content { padding: 0; }
.block-type-profile-actions ul li { margin-bottom: 0; }
.block-type-profile-actions ul li span,
.block-type-profile-actions ul li a { display: block; padding: 10px 15px; }
.block-type-profile-actions ul li a:hover { background: #fafafa; }
.block-type-profile-actions ul li a.followed { color: #f00; }

View file

@ -6,7 +6,7 @@
<ul class="profile-actions" id="profile_actions">
{* Добавление в друзья *}
{include 'components/user/friend_item.tpl' oUserFriend=$user->getUserFriend()}
{include 'components/user/friend_item.tpl' friendship=$user->getUserFriend() userTarget=$oUserProfile classes='js-user-friend'}
{* Отправить сообщение *}
<li>
@ -18,11 +18,7 @@
{* Подписаться *}
<li>
<a href="#" class="js-user-follow {if $user->isFollow()}active{/if}" data-id="{$user->getId()}" data-login="{$user->getLogin()}">
{if $user->isFollow()}
{$aLang.user.actions.unfollow}
{else}
{$aLang.user.actions.follow}
{/if}
{lang name="user.actions.{( $user->isFollow() ) ? 'unfollow' : 'follow'}"}
</a>
</li>

View file

@ -2,20 +2,57 @@
* Добавление / удаление из друзей
*}
{if $oUserFriend and ($oUserFriend->getFriendStatus()==$USER_FRIEND_ACCEPT+$USER_FRIEND_OFFER or $oUserFriend->getFriendStatus()==$USER_FRIEND_ACCEPT+$USER_FRIEND_ACCEPT)}
<li id="delete_friend_item"><a href="#" title="{$aLang.user.friends.remove}" onclick="return ls.user.removeFriend(this,{$oUserProfile->getId()},'del');">{$aLang.user.friends.remove}</a></li>
{elseif $oUserFriend and $oUserFriend->getStatusTo()==$USER_FRIEND_REJECT and $oUserFriend->getStatusFrom()==$USER_FRIEND_OFFER and $oUserFriend->getUserTo()==$oUserCurrent->getId()}
<li id="add_friend_item"><a href="#" title="{$aLang.user.friends.add}" onclick="return ls.user.addFriend(this,{$oUserProfile->getId()},'accept');">{$aLang.user.friends.add}</a></li>
{elseif $oUserFriend and $oUserFriend->getFriendStatus()==$USER_FRIEND_OFFER+$USER_FRIEND_REJECT and $oUserFriend->getUserTo()!=$oUserCurrent->getId()}
<li>{$aLang.user.friends.rejected}</li>
{elseif $oUserFriend and $oUserFriend->getFriendStatus()==$USER_FRIEND_OFFER+$USER_FRIEND_NULL and $oUserFriend->getUserFrom()==$oUserCurrent->getId()}
<li>{$aLang.user.friends.sent}</li>
{elseif $oUserFriend and $oUserFriend->getFriendStatus()==$USER_FRIEND_OFFER+$USER_FRIEND_NULL and $oUserFriend->getUserTo()==$oUserCurrent->getId()}
<li id="add_friend_item"><a href="#" title="{$aLang.user.friends.add}" onclick="return ls.user.addFriend(this,{$oUserProfile->getId()},'accept');">{$aLang.user.friends.add}</a></li>
{elseif !$oUserFriend}
{include file='modals/modal.add_friend.tpl'}
{$component = 'user-friend'}
<li id="add_friend_item"><a href="#" title="{$aLang.user.friends.add}" data-type="modal-toggle" data-modal-target="modal-add-friend">{$aLang.user.friends.add}</a></li>
{else}
<li id="add_friend_item"><a href="#" title="{$aLang.user.friends.add}" onclick="return ls.user.addFriend(this,{$oUserProfile->getId()},'link');">{$aLang.user.friends.add}</a></li>
{/if}
{block 'user_friend_options'}
{$friendship = $smarty.local.friendship}
{$tag = $smarty.local.tag|default:'li'}
{$mods = $smarty.local.mods}
{$attributes = $smarty.local.attributes}
{$classes = $smarty.local.classes}
{$userTarget = $smarty.local.userTarget}
{if $friendship}
{$status = $friendship->getFriendStatus()}
{$userCurrentId = $oUserCurrent->getId()}
{$userToId = $friendship->getUserTo()}
{* Добавлен *}
{if $status == $USER_FRIEND_ACCEPT + $USER_FRIEND_OFFER || $status == $USER_FRIEND_ACCEPT + $USER_FRIEND_ACCEPT}
{$status = 'added'}
{* Ожидает подтверждения *}
{elseif ( $friendship->getStatusTo() == $USER_FRIEND_REJECT && $friendship->getStatusFrom() == $USER_FRIEND_OFFER && $userToId == $userCurrentId )
|| ( $status == $USER_FRIEND_OFFER + $USER_FRIEND_NULL && $userCurrentId == $userToId )}
{$status = 'pending'}
{* Приглашение отклонено *}
{elseif $status == $USER_FRIEND_OFFER + $USER_FRIEND_REJECT && $userToId != $userCurrentId}
{$status = 'rejected'}
{* Приглашение отправлено *}
{elseif $status == $USER_FRIEND_OFFER + $USER_FRIEND_NULL && $userCurrentId == $friendship->getUserFrom()}
{$status = 'sent'}
{* Текущий пользователь удалил из друзей target пользователя, *}
{* но предложение target пользователя еще в силе *}
{else}
{$status = 'linked'}
{/if}
{* Добавить в друзья *}
{else}
{$status = 'notfriends'}
{/if}
{/block}
<{$tag} class="{$component} {mod name=$component mods=$mods} {$smarty.local.classes}" {$smarty.local.attributes} data-status="{$status}" data-target="{$userTarget->getId()}">
{block 'user_friend'}
{if in_array( $status, [ 'sent', 'rejected' ] )}
<span class="{$component}-text js-user-friend-text">{lang name="user.friends.status.{$status}"}</span>
{else}
<a href="#" class="{$component}-text js-user-friend-text">{lang name="user.friends.status.{$status}"}</a>
{/if}
{/block}
</{$tag}>

View file

@ -11,7 +11,7 @@
{block 'layout_head' append}
<script>
ls.lang.load({json var = $aLangJs});
ls.lang.load({lang_load name="comments.comments_declension, comments.unsubscribe, comments.subscribe, comments.folding.unfold, comments.folding.fold, comments.folding.unfold_all, comments.folding.fold_all, poll.notices.error_answers_max, blog.blog, favourite.add, favourite.remove, geo_select_city, geo_select_region, blog.add.fields.type.note_open, blog.add.fields.type.note_close, common.success.add, common.success.remove, pagination.notices.first, pagination.notices.last, user.actions.unfollow, user.actions.follow"});
ls.lang.load({lang_load name="comments.comments_declension, comments.unsubscribe, comments.subscribe, comments.folding.unfold, comments.folding.fold, comments.folding.unfold_all, comments.folding.fold_all, poll.notices.error_answers_max, blog.blog, favourite.add, favourite.remove, geo_select_city, geo_select_region, blog.add.fields.type.note_open, blog.add.fields.type.note_close, common.success.add, common.success.remove, pagination.notices.first, pagination.notices.last, user.actions.unfollow, user.actions.follow, user.friends.status.added, user.friends.status.notfriends, user.friends.status.pending, user.friends.status.rejected, user.friends.status.sent, user.friends.status.linked"});
ls.registry.set({json var = $aVarsJs});
ls.registry.set('comment_max_tree', {json var=Config::Get('module.comment.max_tree')});

View file

@ -13,7 +13,8 @@
{/block}
{block 'modal_content'}
<form id="add_friend_form" onsubmit="return ls.user.addFriend(this,{$oUserProfile->getId()},'add');">
{* TODO: Form validation (front-end / back-end) *}
<form id="add_friend_form" class="js-user-friend-form">
{include 'components/field/field.textarea.tpl'
sName = 'add_friend_text'
aRules = [ 'required' => true, 'rangelength' => '[2,200]' ]