Перейти к контенту
  • 0

IPB 3.1.4 Быстрый ответ выделенного текста


ikamazini

Вопрос

в topicViewTemplate найти:

<li class='top hide'><a href='#top' class='top' title='{$this->lang->words['back_top']}'>{$this->lang->words['back_top']} of the page up there ^</a></li>

  			     <if test="replyButton:|:$displayData['reply_button']['image']">

добавить ниже:

<li><a href="javascript:void(0)" onclick="Quote_sel('{$post['author']['members_display_name']}',{$post['post'][
'pid']})">Цитировать</a></li>

 

далее fastquote.js надо подключить на загрузку в globalTemplate:

<script type="text/javascript" src="/public/js/fastquote.js"/></script>

 

сам fastquote.js:

function Quote_sel(author, pid){

var quote = '';
   	if (quote = window.getSelection)//забираем выделение, все браузеры делают это так
           	quote = window.getSelection().toString();
   	else
           	quote = document.selection.createRange().text;//а для IE
                   	if (quote.length > 0){}
                   	else {return false};

Quote_txt = '[quote name="'+author+'" post="'+pid+'"]'+quote+'[/quote]';//в цитату здесь вывел только имя и ссылку на пост,
//считаю информацию о времении не нужной, но подключить, если что, не сложно

$("fast-reply_textarea").value += Quote_txt; //вставляем в поле быстрого ответа

}

 

работает, но ...

 

http://s5.postimage.org/qn5377lif/Screen_Capture0020.jpg

 

как сделать чтоб после нажатие на "Цитировать" автоматически открылся "Fast Reply" и только после этого поставился там цитировани текст

 

-------

 

добавить?

onclick="getfocus()"

в:

<li><a href="javascript:void(0)" onclick="Quote_sel('{$post['author']['members_display_name']}',{$post['post'][
'pid']})">Цитировать</a></li>

 

 

а это код добавить js:

function getfocus()
{
document.getElementById('fast-reply_textarea').focus();
}

 

фокус работает, но цитировани текст не ставится ... :(

Ссылка на комментарий
Поделиться на других сайтах

Рекомендуемые сообщения

  • 0

iaroslav

 

с помощью хука: Ник и цитата в форму быстрого ответа для 3.1.x

в topicViewTemplate найти:

<li class='top hide'><a href='#top' class='top' title='{$this->lang->words['back_top']}'>{$this->lang->words['back_top']} of the page up there ^</a></li>

				<if test="replyButton:|:$displayData['reply_button']['image']">

 

добавить ниже:

<li><a href="#editor_fast-reply" class="frq_quote" onclick='frq_quote({$quote_args})'>Цитировать</a></li>

 

Нo в "editor_fast-reply" вставляется:

 

http://s5.postimage.org/hotq25inb/Screen_Capture0021.jpg

 

пытаюсь, нo не получается

Ссылка на комментарий
Поделиться на других сайтах

  • 0

Я имел в виду функции посмотреть. Вот так в лоб, просто прописав функцию, конечно же не получится. Ибо в topicViewTemplate переменная $quote_args пустая (я сам пытался, правда не создавая новую кнопку, а дописывая в имеющуюся цитату). Собственно в самом скрипте чуть повыше происхоит присваивание этой переменной значений но как-то хитро. Сейчас вот тоже разобраться пробую.

P.S. Кстати, я пытаюсь не новую кнопку создавать, а дописывать функционал в кнопку "цитата", благо на onclick там ничего нет и сама цитата вполе работает.

<a href="{parse url="module=post&section=post&do=reply_post&f={$this->request['f']}&t={$this->request['t']}&qpid={$post['post']['pid']}" base="publicWithApp"}" title="{$this->lang->words['quote_with_mq']}" onclick="что-нибудь-своё">{parse replacement="mq_post_icon"} {$this->lang->words['mq']}</a>

 

Кстати, искал альтернативные хуки и нашёл вот такой вот код для цитирования выделеного

/* ------------------------------ */
   	/**
	* Parsing ISO 8601 date by Daniel http://dansnetwork.com/2008/11/01/javascript-iso8601rfc3339-date-parser/
   	*/
   	parseIsoDate: function(s){
   	var re=new RegExp(/(\d\d\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d\D?(\d\d\.?(\d*))?)(Z|[+-]\d\d?(:\d\d)?)?/);
   	var a=re.exec(s).slice(1).map(function(x,i){
   	if (i==6 && x) x=parseInt(x,10)/Math.pow(10,x.length)*1000;
   	return parseInt(x,10)||0;
   	});
   	return new Date(
   	Date.UTC(a[0],a[1]-1,a[2],a[3]-(a[7]||0),a[4],a[5],a[6]));
   	},

   	/* ------------------------------ */
   	/**
	* (Pav30) Selective quoting 1.0 by Pavulon
   	*/
   	selective_quote: function()
   	{
                   	// looking for selection
                   	var sel;
                   	if (window.getSelection)
                   	{
                                   	sel = window.getSelection();
                   	}
                   	else if (document.getSelection)
                   	{
                                   	sel = document.getSelection();
                   	}
                   	else if (document.selection)
                   	{
                                   	//IE suxxx
                                   	sel = document.selection.createRange();
                   	}
                   	else
                                   	return alert(ipb.lang['no_selection']);

                   	if (sel.isCollapsed) { return alert(ipb.lang['no_selection']); }
                   	var post, name, timestamp, date, content;

                   	var parent = 0;

                   	// litle IE "fix"
                   	var parent1 = ( document.selection ) ? sel.parentElement() : sel.anchorNode.parentNode;
                   	var parent2 = ( document.selection ) ? sel.parentElement() : sel.focusNode.parentNode;

                   	// avoid infinite loop
                   	var num = 20;
                   	while ( ! parent && --num>0 )
                   	{
                                   	// check 4 correct object at the begining
                                   	if ( !parent1.id || (parent1.id && !parent1.id.match(/post_id_/ ) ) )
                                   	{
                                                   	if ( parent1.parentNode )
                                                   	{
                                                                   	parent1 = parent1.parentNode;
                                                   	}
                                                   	else
                                                   	{
                                                                   	break;
                                                   	}
                                   	}
                                   	// and the end of selection
                                   	if ( !parent2.id || (parent2.id && !parent2.id.match(/post_id_/ ) ) )
                                   	{
                                                   	if ( parent2.parentNode )
                                                   	{
                                                                   	parent2 = parent2.parentNode;
                                                   	}
                                                   	else
                                                   	{
                                                                   	break;
                                                   	}
                                   	}
                                   	if ( parent1 == parent2 && parent1.id && parent1.id.match(/post_id_/ ) )
                                   	{
                                                   	// we've got it =]
                                                   	parent = parent1;
                                   	} else if ( parent1.id && parent1.id.match(/post_id_/ ) &&  parent2.id && parent2.id.match(/post_id_/ ) )
                                   	{
                                                   	// starting post has another id than ending
                                                   	break;
                                   	}
                   	}

                   	if ( parent )
                   	{
                                   	post = parent.id.replace('post_id_', '');
                                   	if ( ! isNaN(post) )
                                   	{
                                                   	// we got post id and we look 4 another infos
                                                   	var childs = $('post_id_'+post).getElementsByTagName("a");
                                                   	for (i = 0; i < childs.length; i++)
                                                   	{
                                                                   	// poster name link should have correct class
                                                                   	if (childs[i].className == 'url fn')
                                                                   	{
                                                                                   	name = childs[i].innerHTML;
                                                                   	}
                                                   	}

                                                   	childs = $('post_id_'+post).getElementsByTagName("abbr");
                                                   	for (i = 0; i < childs.length; i++)
                                                   	{
                                                                   	if (childs[i].className == 'published')
                                                                   	{
                                                                                   	//convert ISO 8601 to timestamp
                                                                                   	var t = ipb.topic.parseIsoDate(childs[i].title)
                                                                                   	timestamp = t.getTime()/1000.0;
                                                                                   	date = childs[i].innerHTML;
                                                                                   	// another IE fix, cause "Internet Explorer for Windows does not support the <abbr> element"
                                                                                   	if ( !date )
                                                                                   	{
                                                                                           	var re=new RegExp(/<abbr([^>]*)>([^<]*)<\/abbr>/i);
                                                                                           	var b=re.exec($('post_id_'+post).innerHTML);
                                                                                           	date = b[b.length-1];
                                                                                   	}
                                                                   	}
                                                   	}
                                   	}
                                   	content = ( document.selection ) ? sel.text : sel.toString();
                   	} else {
                                   	return alert(ipb.lang['wrong_selection']);
                   	}
                   	// preparing content
                   	var quote = '[quote';
                   	if ( name ) { quote = quote + ' name=\'' + name + '\''; }
                   	if ( date ) { quote = quote + ' date=\'' + date + '\''; }
                   	if ( timestamp ) { quote = quote + ' timestamp=\'' + timestamp + '\''; }
                   	if ( post ) { quote = quote + ' post=\'' + post + '\''; }
                   	quote = quote + ']\n';
                   	quote = quote + content;
                   	quote = quote + '\n[/quote]'
                   	if ( $('fast-reply_textarea') )
                   	{
                                   	// load fast-reply editor if it is not created before
                                   	if( $('fast-reply_textarea').hasClassName('unloaded_editor') )
                                   	{
                                                   	if( !in_use )
                                                   	{
                                                                   	if( $('fast-reply_toolbar_1') ){
                                                                                   	$('fast-reply_toolbar_1').show();
                                                                   	}
                                                                   	if( $('fast-reply_toolbar_2') ){
                                                                                   	$('fast-reply_toolbar_2').show();
                                                                   	}

                                                                   	$('fast-reply_textarea').removeClassName('unloaded_editor').value = '';

                                                                   	// we're creating editor, so observing is no longer needed
                                                                   	Event.stopObserving( $('fast-reply_textarea'), 'focus' );
                                                                   	ipb.editors[ 'fast-reply' ] = new ipb.editor( 'fast-reply', USE_RTE );                                
                                                                   	$( ipb.editors['fast-reply'] ).resize_to( 250 );

                                                                   	try {
                                                                                   	ipb.editors[ 'fast-reply' ].editor_window.focus();
                                                                   	} catch(err) { }
                                                                   	in_use = 1;
                                                   	}
                                   	}
                                   	$('fast-reply_textarea').value = $('fast-reply_textarea').value + quote;
                                   	$('fast-reply_textarea').focus();
                   	}
   	},

Нашёл я его вот тут: http://forum.invisio...ective-quoting/

(не смотря на название, код явно для 3,1 или даже 3,0)

Изменено пользователем iaroslav
Ссылка на комментарий
Поделиться на других сайтах

  • 0

в скрипте добавляю:

        if( $('fast-reply_toolbar_1') ){ $('fast-reply_toolbar_1').show(); }
       if( $('fast-reply_toolbar_2') ){ $('fast-reply_toolbar_2').show(); }
       $('fast-reply_textarea').removeClassName('unloaded_editor').value = '';
       ipb.editors[ 'fast-reply' ] = new ipb.editor( 'fast-reply', USE_RTE );
       $( ipb.editors['fast-reply'] ).resize_to( 250 );
       in_use = 1;

 

после этого эдитор('fast-reply_textarea') открывается и цитата тоже вставляется, но если поставить две цитата тогда вторая заменяет первого и в эдитор('fast-reply_textarea') не ставится два цитата.

 

 

iaroslav щас потестирую

 

не работает для 3.1.4 :no:

 

Кстати, искал альтернативные хуки и нашёл вот такой вот код для цитирования выделеного

думаю будет работать, но не знаю как вызывать функции, к сожалению это не в пределах моего знания :(

Изменено пользователем ikamazini
Ссылка на комментарий
Поделиться на других сайтах

  • 0

А я таки сумел реализовать на основе хука и ваших советов для 3,14. Итого

Название файлика .js взято предложенное вами, содержимое файлика взято их хука и выглядит вот так

<script type='text/javascript'>
function frq_put_to_editor(string){
if( !in_use ) {
 if( $('fast-reply_toolbar_1') ){ $('fast-reply_toolbar_1').show(); }
 if( $('fast-reply_toolbar_2') ){ $('fast-reply_toolbar_2').show(); }
 $('fast-reply_textarea').removeClassName('unloaded_editor').value = '';
 ipb.editors[ 'fast-reply' ] = new ipb.editor( 'fast-reply', USE_RTE );
 $( ipb.editors['fast-reply'] ).resize_to( 250 );
 in_use = 1;
}
if(USE_RTE)
{
 var text = ipb.editors[ 'fast-reply' ].editor_get_contents();
 if(text == "\n<br\n")
 	ipb.editors[ 'fast-reply' ].editor_set_content(string);
 else
 	ipb.editors[ 'fast-reply' ].editor_set_content(text + '
' + string);
} else
 document.getElementById("fast-reply_textarea").value += string;
}
function frq_quote(nick, pid)
{
txt = '';
if  	(window.getSelection)   txt = window.getSelection().toString();    
else if (document.getSelection) txt = document.getSelection();              
else if (document.selection)	txt = document.selection.createRange().text;
if(txt == '')
{
 items = $$('#post_id_'+pid+' div');
 for (var i = 0; i < items.size(); i++) {
  if(items[i].hasClassName('entry-content'))
  {
if (window.getSelection) {
var range = document.createRange();
range.selectNode(items[i]);
window.getSelection().addRange(range);
txt = window.getSelection().toString();
} else if (document.getSelection) {
var range = document.createRange();
range.selectNode(items[i]);
document.getSelection().addRange(range);
txt = document.getSelection();
} else if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(items[i]);
range.select();
txt = document.getSelection();
}  
  }
 }
}
if(USE_RTE)
 code = "[quote name='"+nick+"' post='"+pid+"']
"+txt+"
[/quote]
";
else
 code = "[quote name='"+nick+"' post='"+pid+"']\n"+txt+"\n[/quote]\n";
frq_put_to_editor(code);
sel = false;
if (document.selection && document.selection.empty) document.selection.empty();
if (window.getSelection) sel = window.getSelection();
if (document.getSelection) sel = document.getSelection();
  	if(sel && sel.removeAllRanges) sel.removeAllRanges();
}
</script>

Изменение в globalTemplate те же, что и предложены вами.

В topicViewTemplate дописано заместо

<a href="{parse url="module=post&section=post&do=reply_post&f={$ this->request['f']}&t={$this->request[' t']}&qpid={$post['post']['pid'] }" base="publicWithApp"}" title="{$this->lang->words['quote_with_mq']}" >{parse replacement="mq_post_icon"} {$this->lang->words['mq']}</a>

вот это

<a href="{parse url="module=post&section=post&do=reply_post&f={$ this->request['f']}&t={$this->request[' t']}&qpid={$post['post']['pid'] }" base="publicWithApp"}" title="{$this->lang->words['quote_with_mq']}"  onclick="frq_quote('{$post['author']['members_display_name' ]}',{$post['post'][ 'pid']})">{parse replacement="mq_post_icon"} {$this->lang->words['mq']}</a>

 

Аналог для себя, думаю, сделаете без особого труда.

P.S. Спасибо большое вам и автору хука (Ritsuka) за функции и идеи.

Изменено пользователем iaroslav
Ссылка на комментарий
Поделиться на других сайтах

  • 0

iaroslav спасибо тебе :x: и автору хука

я сделал так, больше нравится :yes: :

<li><a href="#editor_fast-reply" class="frq_quote" onclick="frq_quote('{$post['author']['members_display_name' ]}',{$post['post'][ 'pid']})">FastQuote</a></li>

Изменено пользователем ikamazini
Ссылка на комментарий
Поделиться на других сайтах

Присоединиться к обсуждению

Вы можете ответить сейчас, а зарегистрироваться позже. Если у вас уже есть аккаунт, войдите, чтобы ответить от своего имени.

Гость
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Ответить на вопрос...

×   Вы вставили отформатированный текст.   Удалить форматирование

  Допустимо не более 75 смайлов.

×   Ваша ссылка была автоматически заменена на медиа-контент.   Отображать как ссылку

×   Ваши публикации восстановлены.   Очистить редактор

×   Вы не можете вставить изображения напрямую. Загрузите или вставьте изображения по ссылке.

Зарузка...
×
×
  • Создать...

Важная информация

Находясь на нашем сайте, вы соглашаетесь на использование файлов cookie, а также с нашим положением о конфиденциальности Политика конфиденциальности и пользовательским соглашением Условия использования.