Robert Vogel has submitted this change and it was merged. Change subject: shoutbox mentions implementation ......................................................................
shoutbox mentions implementation * user can decide if he wants to get notifications via web and/or mail * typing @ in the shoutbox brings up a list of available usernames * doc added Change-Id: I18a7f4c01e7a1cc2f0dbf930967c072cf0e80eac (cherry picked from commit 3c9fa86f6d26103334cb9064635af4105868e458) --- M ShoutBox/ShoutBox.class.php M ShoutBox/ShoutBox.setup.php M ShoutBox/docs/Hooks.txt M ShoutBox/i18n/de-formal.json M ShoutBox/i18n/de.json M ShoutBox/i18n/en.json M ShoutBox/i18n/qqq.json A ShoutBox/resources/bluespice.shoutBox.mention.js A ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.css A ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.js A ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.min.js 11 files changed, 1,328 insertions(+), 7 deletions(-) Approvals: Robert Vogel: Verified; Looks good to me, approved diff --git a/ShoutBox/ShoutBox.class.php b/ShoutBox/ShoutBox.class.php index 5355c88..aa55513 100644 --- a/ShoutBox/ShoutBox.class.php +++ b/ShoutBox/ShoutBox.class.php @@ -103,6 +103,9 @@ $this->setHook( 'BeforePageDisplay' ); $this->setHook( 'BSInsertMagicAjaxGetData' ); $this->setHook( 'BSStateBarBeforeTopViewAdd', 'onStateBarBeforeTopViewAdd' ); + $this->setHook( 'BeforeCreateEchoEvent' ); + $this->setHook( 'EchoGetDefaultNotifiedUsers' ); + // Permissions $this->mCore->registerPermission( 'readshoutbox' ); @@ -217,6 +220,7 @@ $oOutputPage->addModuleStyles( 'ext.bluespice.shoutbox.styles' ); $oOutputPage->addModules( 'ext.bluespice.shoutbox' ); + $oOutputPage->addModules( 'ext.bluespice.shoutbox.mention' ); BsExtensionManager::setContext( 'MW::ShoutboxShow' ); return true; @@ -272,7 +276,7 @@ $sKey = BsCacheHelper::getCacheKey( 'BlueSpice', 'ShoutBox', $iArticleId, $iLimit ); $aData = BsCacheHelper::get( $sKey ); - +$aData = false; if ( $aData !== false ) { wfDebugLog( 'BsMemcached', __CLASS__ . ': Fetching shouts from cache' ); $sOutput = $aData; @@ -317,6 +321,7 @@ while ( $row = $dbr->fetchRow( $res ) ) { $oUser = User::newFromId( $row['sb_user_id'] ); $oProfile = BsCore::getInstance()->getUserMiniProfile( $oUser ); + $sMessage = preg_replace_callback("#@(\w*)#", "self::replaceUsernameInMessage", $row['sb_message']); $oShoutBoxMessageView = new ViewShoutBoxMessage(); if ( $bShowAge ) $oShoutBoxMessageView->setDate( BsFormatConverter::mwTimestampToAgeString( $row['sb_timestamp'], true ) ); @@ -324,7 +329,7 @@ $oShoutBoxMessageView->setUsername( $row['sb_user_name'] ); $oShoutBoxMessageView->setUser( $oUser ); $oShoutBoxMessageView->setMiniProfile( $oProfile ); - $oShoutBoxMessageView->setMessage( $row['sb_message'] ); + $oShoutBoxMessageView->setMessage( $sMessage ); $oShoutBoxMessageView->setShoutID( $row['sb_id'] ); $oShoutBoxMessageListView->addItem( $oShoutBoxMessageView ); // Since we have one more shout than iLimit, we need to count :) @@ -431,6 +436,7 @@ ); // TODO RBV (21.10.10 17:21): Send error / success to client. wfRunHooks( 'BSShoutBoxAfterInsertShout', array( $iArticleId, $iUserId, $sNick, $sMessage, $sTimestamp ) ); + self::notify("insert", $iArticleId, $iUserId, $sNick, $sMessage, $sTimestamp); self::invalidateShoutBoxCache( $iArticleId ); return FormatJson::encode( @@ -511,4 +517,133 @@ return true; } + /** + * Notifies a User for different actions + * @param String $sAction + * @param int $iArticleId + * @param int $iUserId + * @param String $sNick + * @param String $sMessage + * @param String $sTimestamp + */ + public static function notify( $sAction, $iArticleId, $iUserId, $sNick, $sMessage, $sTimestamp ) { + switch ( $sAction ) { + case "insert": + $aUsers = self::getUsersMentioned( $sMessage ); + if ( count( $aUsers ) < 1 ) + break; + self::notifyUser( "mention", $aUsers, $iArticleId, $iUserId ); + } + } + + /** + * Returns an array of users being mentioned in a shoutbox message + * @param String $sMessage + * @return array Array filled with users of type User + */ + public static function getUsersMentioned( $sMessage ) { + if ( empty( $sMessage ) ) + return array(); + $bResult = preg_match_all( "#@(\w*)#", $sMessage, $aMatches ); + if ( $bResult === false || $bResult < 1 ) + return array(); + $aReturn = array(); + foreach ( $aMatches[1] as $sUserName ) { + $aReturn [] = User::newFromName( $sUserName ); + } + return $aReturn; + } + + /** + * Notifies all Users specified in the array via Echo extension if it's turned on + * @param String $sAction + * @param array $aUsers + * @param int $iArticleId + * @param int $iUserId + */ + public static function notifyUser( $sAction, $aUsers, $iArticleId, $iUserId ) { + if ( class_exists( 'EchoEvent' ) ) { + foreach ( $aUsers as $oUser ) { + EchoEvent::create( array( + 'type' => 'bs-shoutbox-' . $sAction, + 'title' => Article::newFromID( $iArticleId )->getTitle(), + 'agent' => User::newFromId( $iUserId ), + 'extra' => array( + 'summary' => "", + 'titlelink' => true, + 'difflink' => array( 'diffparams' => array() ), + 'agentlink' => true, + 'mentioned-user-id' => $oUser->getId() + ), + ) ); + } + } else { + $sSubject = wfMessage( + 'bs-shoutbox-notifications-title-message-subject' + )->plain(); + $oUser = User::newFromId( $iUserId ); + $sMessage = wfMessage( + 'bs-shoutbox-notifications-title-message-text', BsCore::getUserDisplayName($oUser), Linker::link( Article::newFromID( $iArticleId )->getTitle() ), Linker::link( $oUser ) + )->plain(); + BsMailer::getInstance( 'MW' )->send( $aUsers, $sSubject, $sMessage ); + } + } + + /** + * Handler for EchoGetDefaultNotifiedUsers hook. + * @param array $event EchoEvent to get implicitly subscribed users for + * @param array &$users Array to append implicitly subscribed users to. + * @return bool true in all cases + */ + public static function onEchoGetDefaultNotifiedUsers( $event, &$users ) { + switch ( $event->getType() ) { + case 'bs-shoutbox-mention': + $extra = $event->getExtra(); + if ( !$extra || !isset( $extra['mentioned-user-id'] ) ) { + break; + } + $recipientId = $extra['mentioned-user-id']; + //really ugly, but newFromId appears to be broken... + $oDBr = wfGetDB( DB_SLAVE ); + $row = $oDBr->selectRow( 'user', '*', array( 'user_id' => (int) $recipientId ) ); + $recipient = User::newFromRow( $row ); + $users[$recipientId] = $recipient; + break; + } + return true; + } + + /** + * Adds the Shoutbox mentions notification option + * @param array $notifications + * @param array $notificationCategories + * @return boolean + */ + public function onBeforeCreateEchoEvent( &$notifications, &$notificationCategories ) { + $notificationCategories['bs-shoutbox-mention-cat'] = array( 'priority' => 3 ); + $notifications['bs-shoutbox-mention'] = array( // HINT: http://www.mediawiki.org/wiki/Echo_(Notifications)/Developer_guide#Defining_a_notification + 'category' => 'bs-shoutbox-mention-cat', + 'group' => 'neutral', + 'formatter-class' => 'BsNotificationsFormatter', + 'title-message' => 'bs-shoutbox-notifications-title-message-text', + 'title-params' => array( 'agentlink', 'titlelink' ), + 'flyout-message' => 'bs-shoutbox-notifications-title-message-text', + 'title-params' => array( 'agentlink', 'titlelink' ), + 'email-subject-message' => 'bs-shoutbox-notifications-title-message-subject', + 'email-body-message' => 'bs-shoutbox-notifications-title-message-text', + 'title-params' => array( 'agentlink', 'titlelink' ), + ); + return true; + } + + /** + * Callback from preg_replace, replaces the mention with a link to the user page + * @param array $sMatch + * @return String The link to the user page + */ + public static function replaceUsernameInMessage( $sMatch ) { + $oUser = User::newFromName( $sMatch[1] ); + return Linker::link( $oUser->getUserPage(), BsCore::getUserDisplayName( $oUser ) ); + } + } diff --git a/ShoutBox/ShoutBox.setup.php b/ShoutBox/ShoutBox.setup.php index d6cb639..0527c33 100644 --- a/ShoutBox/ShoutBox.setup.php +++ b/ShoutBox/ShoutBox.setup.php @@ -26,6 +26,21 @@ 'position' => 'bottom' ) + $aResourceModuleTemplate; +$wgResourceModules['ext.bluespice.shoutbox.mention'] = array( + 'scripts' => array( + 'jquery.textcomplete/jquery.textcomplete.min.js', + 'bluespice.shoutBox.mention.js', + ), + 'styles' => 'jquery.textcomplete/jquery.textcomplete.css', + 'dependencies' => array( + 'ext.bluespice', + 'ext.bluespice.shoutbox' + ), + 'position' => 'bottom' +) + $aResourceModuleTemplate; + +$wgDefaultUserOptions["echo-subscriptions-web-bs-shoutbox-mention-cat"] = true; + $wgResourceModules['ext.bluespice.shoutbox.styles'] = array( 'styles' => 'bluespice.shoutBox.css', ) + $aResourceModuleTemplate; diff --git a/ShoutBox/docs/Hooks.txt b/ShoutBox/docs/Hooks.txt index f11aadb..06c2ba7 100644 --- a/ShoutBox/docs/Hooks.txt +++ b/ShoutBox/docs/Hooks.txt @@ -12,4 +12,12 @@ &$sOutput: Html output. $iArticleId: The page_id of the article the shout belongs to. &$iLimit: The limit option. -return bool false to break the following query. \ No newline at end of file +return bool false to break the following query. + +'EchoGetDefaultNotifiedUsers' Handler for EchoGetDefaultNotifiedUsers hook. +$event: EchoEvent to get implicitly subscribed users for +&$users Array to append implicitly subscribed users to. + +'BeforeCreateEchoEvent' Adds the Shoutbox mentions notification option +&$notifications: The notifications options array +&$notificationCategories: The notifications categories array \ No newline at end of file diff --git a/ShoutBox/i18n/de-formal.json b/ShoutBox/i18n/de-formal.json index 7ab4914..2af7eae 100644 --- a/ShoutBox/i18n/de-formal.json +++ b/ShoutBox/i18n/de-formal.json @@ -8,5 +8,7 @@ "bs-shoutbox-archive-failure": "Beim Löschen des Eintrags ist ein Fehler aufgetreten, bitte versuchen Sie es erneut.", "bs-shoutbox-confirm-text": "Möchten Sie diesen Eintrag wirklich löschen?", "bs-shoutbox-entermessage": "Bitte geben Sie eine Nachricht ein.", - "bs-shoutbox-too-early": "Bitte warten Sie ein paar Sekunden, bevor Sie den nächsten Eintrag abschicken." + "bs-shoutbox-too-early": "Bitte warten Sie ein paar Sekunden, bevor Sie den nächsten Eintrag abschicken.", + "bs-shoutbox-notifications-title-message-subject": "Sie wurden in einer Nachricht in der Shoutbox erwähnt.", + "bs-shoutbox-notifications-title-message-text": "Sie wurden von $2 in einer Nachricht auf der Seite \"$3\" {{GENDER:$1|erwähnt}}." } diff --git a/ShoutBox/i18n/de.json b/ShoutBox/i18n/de.json index bf1070c..1844cc9 100644 --- a/ShoutBox/i18n/de.json +++ b/ShoutBox/i18n/de.json @@ -28,5 +28,8 @@ "bs-shoutbox-confirm-title": "Bestätigen", "bs-shoutbox-entermessage": "Bitte gib eine Nachricht ein.", "bs-shoutbox-too-early": "Bitte warte ein paar Sekunden, bevor du den nächsten Eintrag abschickst.", - "bs-shoutbox-n-shouts": "$1 {{PLURAL:$1|Shout|Shouts}}" + "bs-shoutbox-n-shouts": "$1 {{PLURAL:$1|Shout|Shouts}}", + "echo-category-title-bs-shoutbox-mention-cat": "Benachrichtigung bei Erwähnung in einer Nachricht in der Shoutbox", + "bs-shoutbox-notifications-title-message-subject": "Du wurdest in einer Nachricht in der Shoutbox erwähnt.", + "bs-shoutbox-notifications-title-message-text": "Du wurdest von $2 in einer Nachricht auf der Seite \"$3\" {{GENDER:$1|erwähnt}}." } diff --git a/ShoutBox/i18n/en.json b/ShoutBox/i18n/en.json index f21378c..f06d8f4 100644 --- a/ShoutBox/i18n/en.json +++ b/ShoutBox/i18n/en.json @@ -27,5 +27,8 @@ "bs-shoutbox-confirm-title": "Confirm", "bs-shoutbox-entermessage": "Please enter a message.", "bs-shoutbox-too-early": "Please wait a few seconds before submitting the next entry.", - "bs-shoutbox-n-shouts": "$1 {{PLURAL:$1|Shout|Shouts}}" + "bs-shoutbox-n-shouts": "$1 {{PLURAL:$1|Shout|Shouts}}", + "echo-category-title-bs-shoutbox-mention-cat": "Notification for mention in a shout", + "bs-shoutbox-notifications-title-message-subject": "You've been mentioned", + "bs-shoutbox-notifications-title-message-text": "You've been {{GENDER:$1|mentioned}} by $2 in a shout on the page \"$3.\"" } diff --git a/ShoutBox/i18n/qqq.json b/ShoutBox/i18n/qqq.json index 37e8966..f51879d 100644 --- a/ShoutBox/i18n/qqq.json +++ b/ShoutBox/i18n/qqq.json @@ -31,5 +31,8 @@ "bs-shoutbox-confirm-title": "Window title for confirm\n{{Identical|Confirm}}", "bs-shoutbox-entermessage": "Text for please enter a message.", "bs-shoutbox-too-early": "Please wait a few seconds before submitting the next entry.", - "bs-shoutbox-n-shouts": "Text for the number of shouts, used in StateBar\n*$1 is the number of shouts, also use this for PLURAL distinction\n{{Identical|Shout}}" + "bs-shoutbox-n-shouts": "Text for the number of shouts, used in StateBar\n*$1 is the number of shouts, also use this for PLURAL distinction\n{{Identical|Shout}}", + "echo-category-title-bs-shoutbox-mention-cat": "text found in notifications, let's the user decide if he wants to be notified about a mention in a message in the shoutbox via web, mail or both", + "bs-shoutbox-notifications-title-message-subject": "notifications text used for e-mail if the user was mentioned in a shoutbox entry", + "bs-shoutbox-notifications-title-message-text": "text used in notifications in the wiki and as the mail body if the user was mentioned in a shoutbox entry \n*$1 the user being mentioned \n*$2 is the link to the user page of the user that mentioned another user. \n*$3 is the link to the page where the shoutbox entry was made." } diff --git a/ShoutBox/resources/bluespice.shoutBox.mention.js b/ShoutBox/resources/bluespice.shoutBox.mention.js new file mode 100644 index 0000000..b52e731 --- /dev/null +++ b/ShoutBox/resources/bluespice.shoutBox.mention.js @@ -0,0 +1,38 @@ +$( document ).ready( function () { + var BSShoutboxMentions = { + mentions: [ ], + //matches whole words starting with @ + match: /\B@(\w*)$/, + search: function ( term, callback ) { + //if the mentions array is empty get a list of all users available + //first trigger with the @ in the shoutbox to not overload requests + if ( BSShoutboxMentions.mentions.length === 0 ) { + this.getUsers(); + } + callback( $.map( BSShoutboxMentions.mentions, function ( mention ) { + //returns matches for names containing the term + case insensitive + return mention.toLowerCase().indexOf( term.toLowerCase() ) !== -1 ? mention : null; + } ) ); + }, + index: 1, + replace: function ( mention ) { + //put the username in the shoutbox, not the displayname for better usage later + var username = mention.match( /\((.*?)\)/ ); + return '@' + username[1] + ' '; + }, + getUsers: function () { + $.getJSON( bs.util.getCAIUrl( 'getUserStoreData' ), function ( data ) { + var users = [ ]; + $.each( data.users, function ( i, v ) { + users.push( v.display_name + " (" + v.user_name + ")" ); + } ); + BSShoutboxMentions.mentions = users; + } ); + } + } + + var strategies = [ + BSShoutboxMentions + ]; + $( '#bs-sb-message' ).textcomplete( strategies ); +} ); \ No newline at end of file diff --git a/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.css b/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.css new file mode 100644 index 0000000..37a761b --- /dev/null +++ b/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.css @@ -0,0 +1,33 @@ +/* Sample */ + +.dropdown-menu { + border: 1px solid #ddd; + background-color: white; +} + +.dropdown-menu li { + border-top: 1px solid #ddd; + padding: 2px 5px; +} + +.dropdown-menu li:first-child { + border-top: none; +} + +.dropdown-menu li:hover, +.dropdown-menu .active { + background-color: rgb(110, 183, 219); +} + + +/* SHOULD not modify */ + +.dropdown-menu { + list-style: none; + padding: 0; + margin: 0; +} + +.dropdown-menu a:hover { + cursor: pointer; +} diff --git a/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.js b/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.js new file mode 100644 index 0000000..ce4df50 --- /dev/null +++ b/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.js @@ -0,0 +1,1077 @@ +/*! + * jQuery.textcomplete + * + * Repository: https://github.com/yuku-t/jquery-textcomplete + * License: MIT (https://github.com/yuku-t/jquery-textcomplete/blob/master/LICENSE) + * Author: Yuku Takahashi + */ + +if (typeof jQuery === 'undefined') { + throw new Error('jQuery.textcomplete requires jQuery'); +} + ++function ($) { + 'use strict'; + + var warn = function (message) { + if (console.warn) { console.warn(message); } + }; + + $.fn.textcomplete = function (strategies, option) { + var args = Array.prototype.slice.call(arguments); + return this.each(function () { + var $this = $(this); + var completer = $this.data('textComplete'); + if (!completer) { + completer = new $.fn.textcomplete.Completer(this, option || {}); + $this.data('textComplete', completer); + } + if (typeof strategies === 'string') { + if (!completer) return; + args.shift() + completer[strategies].apply(completer, args); + } else { + // For backward compatibility. + // TODO: Remove at v0.4 + $.each(strategies, function (obj) { + $.each(['header', 'footer', 'placement', 'maxCount'], function (name) { + if (obj[name]) { + completer.option[name] = obj[name]; + warn(name + 'as a strategy param is deplicated. Use option.'); + delete obj[name]; + } + }); + }); + completer.register($.fn.textcomplete.Strategy.parse(strategies)); + } + }); + }; + +}(jQuery); + ++function ($) { + 'use strict'; + + // Exclusive execution control utility. + // + // func - The function to be locked. It is executed with a function named + // `free` as the first argument. Once it is called, additional + // execution are ignored until the free is invoked. Then the last + // ignored execution will be replayed immediately. + // + // Examples + // + // var lockedFunc = lock(function (free) { + // setTimeout(function { free(); }, 1000); // It will be free in 1 sec. + // console.log('Hello, world'); + // }); + // lockedFunc(); // => 'Hello, world' + // lockedFunc(); // none + // lockedFunc(); // none + // // 1 sec past then + // // => 'Hello, world' + // lockedFunc(); // => 'Hello, world' + // lockedFunc(); // none + // + // Returns a wrapped function. + var lock = function (func) { + var locked, queuedArgsToReplay; + + return function () { + // Convert arguments into a real array. + var args = Array.prototype.slice.call(arguments); + if (locked) { + // Keep a copy of this argument list to replay later. + // OK to overwrite a previous value because we only replay + // the last one. + queuedArgsToReplay = args; + return; + } + locked = true; + var self = this; + args.unshift(function replayOrFree() { + if (queuedArgsToReplay) { + // Other request(s) arrived while we were locked. + // Now that the lock is becoming available, replay + // the latest such request, then call back here to + // unlock (or replay another request that arrived + // while this one was in flight). + var replayArgs = queuedArgsToReplay; + queuedArgsToReplay = undefined; + replayArgs.unshift(replayOrFree); + func.apply(self, replayArgs); + } else { + locked = false; + } + }); + func.apply(this, args); + }; + }; + + var isString = function (obj) { + return Object.prototype.toString.call(obj) === '[object String]'; + }; + + var uniqueId = 0; + + function Completer(element, option) { + this.$el = $(element); + this.id = 'textcomplete' + uniqueId++; + this.strategies = []; + this.views = []; + this.option = $.extend({}, Completer.DEFAULTS, option); + + if (!this.$el.is('textarea') && !element.isContentEditable) { + throw new Error('textcomplete must be called to a Textarea or a ContentEditable.'); + } + + if (element === document.activeElement) { + // element has already been focused. Initialize view objects immediately. + this.initialize() + } else { + // Initialize view objects lazily. + var self = this; + this.$el.one('focus.' + this.id, function () { self.initialize(); }); + } + } + + Completer.DEFAULTS = { + appendTo: $('body'), + zIndex: '100' + }; + + $.extend(Completer.prototype, { + // Public properties + // ----------------- + + id: null, + option: null, + strategies: null, + adapter: null, + dropdown: null, + $el: null, + + // Public methods + // -------------- + + initialize: function () { + var element = this.$el.get(0); + // Initialize view objects. + this.dropdown = new $.fn.textcomplete.Dropdown(element, this, this.option); + var Adapter, viewName; + if (this.option.adapter) { + Adapter = this.option.adapter; + } else { + if (this.$el.is('textarea')) { + viewName = typeof element.selectionEnd === 'number' ? 'Textarea' : 'IETextarea'; + } else { + viewName = 'ContentEditable'; + } + Adapter = $.fn.textcomplete[viewName]; + } + this.adapter = new Adapter(element, this, this.option); + }, + + destroy: function () { + this.$el.off('.' + this.id); + if (this.adapter) { + this.adapter.destroy(); + } + if (this.dropdown) { + this.dropdown.destroy(); + } + this.$el = this.adapter = this.dropdown = null; + }, + + // Invoke textcomplete. + trigger: function (text, skipUnchangedTerm) { + if (!this.dropdown) { this.initialize(); } + text != null || (text = this.adapter.getTextFromHeadToCaret()); + var searchQuery = this._extractSearchQuery(text); + if (searchQuery.length) { + var term = searchQuery[1]; + // Ignore shift-key, ctrl-key and so on. + if (skipUnchangedTerm && this._term === term) { return; } + this._term = term; + this._search.apply(this, searchQuery); + } else { + this._term = null; + this.dropdown.deactivate(); + } + }, + + fire: function (eventName) { + this.$el.trigger(eventName); + return this; + }, + + register: function (strategies) { + Array.prototype.push.apply(this.strategies, strategies); + }, + + // Insert the value into adapter view. It is called when the dropdown is clicked + // or selected. + // + // value - The selected element of the array callbacked from search func. + // strategy - The Strategy object. + select: function (value, strategy) { + this.adapter.select(value, strategy); + this.fire('change').fire('textComplete:select', value, strategy); + this.adapter.focus(); + }, + + // Private properties + // ------------------ + + _clearAtNext: true, + _term: null, + + // Private methods + // --------------- + + // Parse the given text and extract the first matching strategy. + // + // Returns an array including the strategy, the query term and the match + // object if the text matches an strategy; otherwise returns an empty array. + _extractSearchQuery: function (text) { + for (var i = 0; i < this.strategies.length; i++) { + var strategy = this.strategies[i]; + var context = strategy.context(text); + if (context || context === '') { + if (isString(context)) { text = context; } + var match = text.match(strategy.match); + if (match) { return [strategy, match[strategy.index], match]; } + } + } + return [] + }, + + // Call the search method of selected strategy.. + _search: lock(function (free, strategy, term, match) { + var self = this; + strategy.search(term, function (data, stillSearching) { + if (!self.dropdown.shown) { + self.dropdown.activate(); + self.dropdown.setPosition(self.adapter.getCaretPosition()); + } + if (self._clearAtNext) { + // The first callback in the current lock. + self.dropdown.clear(); + self._clearAtNext = false; + } + self.dropdown.render(self._zip(data, strategy)); + if (!stillSearching) { + // The last callback in the current lock. + free(); + self._clearAtNext = true; // Call dropdown.clear at the next time. + } + }, match); + }), + + // Build a parameter for Dropdown#render. + // + // Examples + // + // this._zip(['a', 'b'], 's'); + // //=> [{ value: 'a', strategy: 's' }, { value: 'b', strategy: 's' }] + _zip: function (data, strategy) { + return $.map(data, function (value) { + return { value: value, strategy: strategy }; + }); + } + }); + + $.fn.textcomplete.Completer = Completer; +}(jQuery); + ++function ($) { + 'use strict'; + + var include = function (zippedData, datum) { + var i, elem; + var idProperty = datum.strategy.idProperty + for (i = 0; i < zippedData.length; i++) { + elem = zippedData[i]; + if (elem.strategy !== datum.strategy) continue; + if (idProperty) { + if (elem.value[idProperty] === datum.value[idProperty]) return true; + } else { + if (elem.value === datum.value) return true; + } + } + return false; + }; + + var dropdownViews = {}; + $(document).on('click', function (e) { + var id = e.originalEvent && e.originalEvent.keepTextCompleteDropdown; + $.each(dropdownViews, function (key, view) { + if (key !== id) { view.deactivate(); } + }); + }); + + // Dropdown view + // ============= + + // Construct Dropdown object. + // + // element - Textarea or contenteditable element. + function Dropdown(element, completer, option) { + this.$el = Dropdown.findOrCreateElement(option); + this.completer = completer; + this.id = completer.id + 'dropdown'; + this._data = []; // zipped data. + this.$inputEl = $(element); + + // Override setPosition method. + if (option.listPosition) { this.setPosition = option.listPosition; } + if (option.height) { this.$el.height(option.height); } + var self = this; + $.each(['maxCount', 'placement', 'footer', 'header', 'className'], function (_i, name) { + if (option[name] != null) { self[name] = option[name]; } + }); + this._bindEvents(element); + dropdownViews[this.id] = this; + } + + $.extend(Dropdown, { + // Class methods + // ------------- + + findOrCreateElement: function (option) { + var $parent = option.appendTo; + if (!($parent instanceof $)) { $parent = $($parent); } + var $el = $parent.children('.dropdown-menu') + if (!$el.length) { + $el = $('<ul class="dropdown-menu"></ul>').css({ + display: 'none', + left: 0, + position: 'absolute', + zIndex: option.zIndex + }).appendTo($parent); + } + return $el; + } + }); + + $.extend(Dropdown.prototype, { + // Public properties + // ----------------- + + $el: null, // jQuery object of ul.dropdown-menu element. + $inputEl: null, // jQuery object of target textarea. + completer: null, + footer: null, + header: null, + id: null, + maxCount: 10, + placement: '', + shown: false, + data: [], // Shown zipped data. + className: '', + + // Public methods + // -------------- + + destroy: function () { + // Don't remove $el because it may be shared by several textcompletes. + this.deactivate(); + + this.$el.off('.' + this.id); + this.$inputEl.off('.' + this.id); + this.clear(); + this.$el = this.$inputEl = this.completer = null; + delete dropdownViews[this.id] + }, + + render: function (zippedData) { + var contentsHtml = this._buildContents(zippedData); + var unzippedData = $.map(this.data, function (d) { return d.value; }); + if (this.data.length) { + this._renderHeader(unzippedData); + this._renderFooter(unzippedData); + if (contentsHtml) { + this._renderContents(contentsHtml); + this._activateIndexedItem(); + } + this._setScroll(); + } else if (this.shown) { + this.deactivate(); + } + }, + + setPosition: function (position) { + this.$el.css(this._applyPlacement(position)); + return this; + }, + + clear: function () { + this.$el.html(''); + this.data = []; + this._index = 0; + this._$header = this._$footer = null; + }, + + activate: function () { + if (!this.shown) { + this.clear(); + this.$el.show(); + if (this.className) { this.$el.addClass(this.className); } + this.completer.fire('textComplete:show'); + this.shown = true; + } + return this; + }, + + deactivate: function () { + if (this.shown) { + this.$el.hide(); + if (this.className) { this.$el.removeClass(this.className); } + this.completer.fire('textComplete:hide'); + this.shown = false; + } + return this; + }, + + isUp: function (e) { + return e.keyCode === 38 || (e.ctrlKey && e.keyCode === 80); // UP, Ctrl-P + }, + + isDown: function (e) { + return e.keyCode === 40 || (e.ctrlKey && e.keyCode === 78); // DOWN, Ctrl-N + }, + + isEnter: function (e) { + var modifiers = e.ctrlKey || e.altKey || e.metaKey || e.shiftKey; + return !modifiers && (e.keyCode === 13 || e.keyCode === 9) // ENTER, TAB + }, + + isPageup: function (e) { + return e.keyCode === 33; // PAGEUP + }, + + isPagedown: function (e) { + return e.keyCode === 34; // PAGEDOWN + }, + + // Private properties + // ------------------ + + _data: null, // Currently shown zipped data. + _index: null, + _$header: null, + _$footer: null, + + // Private methods + // --------------- + + _bindEvents: function () { + this.$el.on('mousedown.' + this.id, '.textcomplete-item', $.proxy(this._onClick, this)) + this.$el.on('mouseover.' + this.id, '.textcomplete-item', $.proxy(this._onMouseover, this)); + this.$inputEl.on('keydown.' + this.id, $.proxy(this._onKeydown, this)); + }, + + _onClick: function (e) { + var $el = $(e.target); + e.preventDefault(); + e.originalEvent.keepTextCompleteDropdown = this.id; + if (!$el.hasClass('textcomplete-item')) { + $el = $el.closest('.textcomplete-item'); + } + var datum = this.data[parseInt($el.data('index'), 10)]; + this.completer.select(datum.value, datum.strategy); + var self = this; + // Deactive at next tick to allow other event handlers to know whether + // the dropdown has been shown or not. + setTimeout(function () { self.deactivate(); }, 0); + }, + + // Activate hovered item. + _onMouseover: function (e) { + var $el = $(e.target); + e.preventDefault(); + if (!$el.hasClass('textcomplete-item')) { + $el = $el.closest('.textcomplete-item'); + } + this._index = parseInt($el.data('index'), 10); + this._activateIndexedItem(); + }, + + _onKeydown: function (e) { + if (!this.shown) { return; } + if (this.isUp(e)) { + e.preventDefault(); + this._up(); + } else if (this.isDown(e)) { + e.preventDefault(); + this._down(); + } else if (this.isEnter(e)) { + e.preventDefault(); + this._enter(); + } else if (this.isPageup(e)) { + e.preventDefault(); + this._pageup(); + } else if (this.isPagedown(e)) { + e.preventDefault(); + this._pagedown(); + } + }, + + _up: function () { + if (this._index === 0) { + this._index = this.data.length - 1; + } else { + this._index -= 1; + } + this._activateIndexedItem(); + this._setScroll(); + }, + + _down: function () { + if (this._index === this.data.length - 1) { + this._index = 0; + } else { + this._index += 1; + } + this._activateIndexedItem(); + this._setScroll(); + }, + + _enter: function () { + var datum = this.data[parseInt(this._getActiveElement().data('index'), 10)]; + this.completer.select(datum.value, datum.strategy); + this._setScroll(); + }, + + _pageup: function () { + var target = 0; + var threshold = this._getActiveElement().position().top - this.$el.innerHeight(); + this.$el.children().each(function (i) { + if ($(this).position().top + $(this).outerHeight() > threshold) { + target = i; + return false; + } + }); + this._index = target; + this._activateIndexedItem(); + this._setScroll(); + }, + + _pagedown: function () { + var target = this.data.length - 1; + var threshold = this._getActiveElement().position().top + this.$el.innerHeight(); + this.$el.children().each(function (i) { + if ($(this).position().top > threshold) { + target = i; + return false + } + }); + this._index = target; + this._activateIndexedItem(); + this._setScroll(); + }, + + _activateIndexedItem: function () { + this.$el.find('.textcomplete-item.active').removeClass('active'); + this._getActiveElement().addClass('active'); + }, + + _getActiveElement: function () { + return this.$el.children('.textcomplete-item:nth(' + this._index + ')'); + }, + + _setScroll: function () { + var $activeEl = this._getActiveElement(); + var itemTop = $activeEl.position().top; + var itemHeight = $activeEl.outerHeight(); + var visibleHeight = this.$el.innerHeight(); + var visibleTop = this.$el.scrollTop(); + if (this._index === 0 || this._index == this.data.length - 1 || itemTop < 0) { + this.$el.scrollTop(itemTop + visibleTop); + } else if (itemTop + itemHeight > visibleHeight) { + this.$el.scrollTop(itemTop + itemHeight + visibleTop - visibleHeight); + } + }, + + _buildContents: function (zippedData) { + var datum, i, index; + var html = ''; + for (i = 0; i < zippedData.length; i++) { + if (this.data.length === this.maxCount) break; + datum = zippedData[i]; + if (include(this.data, datum)) { continue; } + index = this.data.length; + this.data.push(datum); + html += '<li class="textcomplete-item" data-index="' + index + '"><a>'; + html += datum.strategy.template(datum.value); + html += '</a></li>'; + } + return html; + }, + + _renderHeader: function (unzippedData) { + if (this.header) { + if (!this._$header) { + this._$header = $('<li class="textcomplete-header"></li>').prependTo(this.$el); + } + var html = $.isFunction(this.header) ? this.header(unzippedData) : this.header; + this._$header.html(html); + } + }, + + _renderFooter: function (unzippedData) { + if (this.footer) { + if (!this._$footer) { + this._$footer = $('<li class="textcomplete-footer"></li>').appendTo(this.$el); + } + var html = $.isFunction(this.footer) ? this.footer(unzippedData) : this.footer; + this._$footer.html(html); + } + }, + + _renderContents: function (html) { + if (this._$footer) { + this._$footer.before(html); + } else { + this.$el.append(html); + } + }, + + _applyPlacement: function (position) { + // If the 'placement' option set to 'top', move the position above the element. + if (this.placement.indexOf('top') !== -1) { + // Overwrite the position object to set the 'bottom' property instead of the top. + position = { + top: 'auto', + bottom: this.$el.parent().height() - position.top + position.lineHeight, + left: position.left + }; + } else { + position.bottom = 'auto'; + delete position.lineHeight; + } + if (this.placement.indexOf('absleft') !== -1) { + position.left = 0; + } else if (this.placement.indexOf('absright') !== -1) { + position.right = 0; + position.left = 'auto'; + } + return position; + } + }); + + $.fn.textcomplete.Dropdown = Dropdown; +}(jQuery); + ++function ($) { + 'use strict'; + + // Memoize a search function. + var memoize = function (func) { + var memo = {}; + return function (term, callback) { + if (memo[term]) { + callback(memo[term]); + } else { + func.call(this, term, function (data) { + memo[term] = (memo[term] || []).concat(data); + callback.apply(null, arguments); + }); + } + }; + }; + + function Strategy(options) { + $.extend(this, options); + if (this.cache) { this.search = memoize(this.search); } + } + + Strategy.parse = function (optionsArray) { + return $.map(optionsArray, function (options) { + return new Strategy(options); + }); + }; + + $.extend(Strategy.prototype, { + // Public properties + // ----------------- + + // Required + match: null, + replace: null, + search: null, + + // Optional + cache: false, + context: function () { return true; }, + index: 2, + template: function (obj) { return obj; }, + idProperty: null + }); + + $.fn.textcomplete.Strategy = Strategy; + +}(jQuery); + ++function ($) { + 'use strict'; + + var now = Date.now || function () { return new Date().getTime(); }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // `wait` msec. + // + // This utility function was originally implemented at Underscore.js. + var debounce = function (func, wait) { + var timeout, args, context, timestamp, result; + var later = function () { + var last = now() - timestamp; + if (last < wait) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + result = func.apply(context, args); + context = args = null; + } + }; + + return function () { + context = this; + args = arguments; + timestamp = now(); + if (!timeout) { + timeout = setTimeout(later, wait); + } + return result; + }; + }; + + function Adapter () {} + + $.extend(Adapter.prototype, { + // Public properties + // ----------------- + + id: null, // Identity. + completer: null, // Completer object which creates it. + el: null, // Textarea element. + $el: null, // jQuery object of the textarea. + option: null, + + // Public methods + // -------------- + + initialize: function (element, completer, option) { + this.el = element; + this.$el = $(element); + this.id = completer.id + this.constructor.name; + this.completer = completer; + this.option = option; + + if (this.option.debounce) { + this._onKeyup = debounce(this._onKeyup, this.option.debounce); + } + + this._bindEvents(); + }, + + destroy: function () { + this.$el.off('.' + this.id); // Remove all event handlers. + this.$el = this.el = this.completer = null; + }, + + // Update the element with the given value and strategy. + // + // value - The selected object. It is one of the item of the array + // which was callbacked from the search function. + // strategy - The Strategy associated with the selected value. + select: function (/* value, strategy */) { + throw new Error('Not implemented'); + }, + + // Returns the caret's relative coordinates from body's left top corner. + // + // FIXME: Calculate the left top corner of `this.option.appendTo` element. + getCaretPosition: function () { + var position = this._getCaretRelativePosition(); + var offset = this.$el.offset(); + position.top += offset.top; + position.left += offset.left; + return position; + }, + + // Focus on the element. + focus: function () { + this.$el.focus(); + }, + + // Private methods + // --------------- + + _bindEvents: function () { + this.$el.on('keyup.' + this.id, $.proxy(this._onKeyup, this)); + }, + + _onKeyup: function (e) { + if (this._skipSearch(e)) { return; } + this.completer.trigger(this.getTextFromHeadToCaret(), true); + }, + + // Suppress searching if it returns true. + _skipSearch: function (clickEvent) { + switch (clickEvent.keyCode) { + case 40: // DOWN + case 38: // UP + return true; + } + if (clickEvent.ctrlKey) switch (clickEvent.keyCode) { + case 78: // Ctrl-N + case 80: // Ctrl-P + return true; + } + } + }); + + $.fn.textcomplete.Adapter = Adapter; +}(jQuery); + ++function ($) { + 'use strict'; + + // Textarea adapter + // ================ + // + // Managing a textarea. It doesn't know a Dropdown. + function Textarea(element, completer, option) { + this.initialize(element, completer, option); + } + + Textarea.DIV_PROPERTIES = { + left: -9999, + position: 'absolute', + top: 0, + whiteSpace: 'pre-wrap' + } + + Textarea.COPY_PROPERTIES = [ + 'border-width', 'font-family', 'font-size', 'font-style', 'font-variant', + 'font-weight', 'height', 'letter-spacing', 'word-spacing', 'line-height', + 'text-decoration', 'text-align', 'width', 'padding-top', 'padding-right', + 'padding-bottom', 'padding-left', 'margin-top', 'margin-right', + 'margin-bottom', 'margin-left', 'border-style', 'box-sizing', 'tab-size' + ]; + + $.extend(Textarea.prototype, $.fn.textcomplete.Adapter.prototype, { + // Public methods + // -------------- + + // Update the textarea with the given value and strategy. + select: function (value, strategy) { + var pre = this.getTextFromHeadToCaret(); + var post = this.el.value.substring(this.el.selectionEnd); + var newSubstr = strategy.replace(value); + if ($.isArray(newSubstr)) { + post = newSubstr[1] + post; + newSubstr = newSubstr[0]; + } + pre = pre.replace(strategy.match, newSubstr); + this.$el.val(pre + post); + this.el.selectionStart = this.el.selectionEnd = pre.length; + }, + + // Private methods + // --------------- + + // Returns the caret's relative coordinates from textarea's left top corner. + // + // Browser native API does not provide the way to know the position of + // caret in pixels, so that here we use a kind of hack to accomplish + // the aim. First of all it puts a dummy div element and completely copies + // the textarea's style to the element, then it inserts the text and a + // span element into the textarea. + // Consequently, the span element's position is the thing what we want. + _getCaretRelativePosition: function () { + var dummyDiv = $('<div></div>').css(this._copyCss()) + .text(this.getTextFromHeadToCaret()); + var span = $('<span></span>').text('.').appendTo(dummyDiv); + this.$el.before(dummyDiv); + var position = span.position(); + position.top += span.height() - this.$el.scrollTop(); + position.lineHeight = span.height(); + dummyDiv.remove(); + return position; + }, + + _copyCss: function () { + return $.extend({ + // Set 'scroll' if a scrollbar is being shown; otherwise 'auto'. + overflow: this.el.scrollHeight > this.el.offsetHeight ? 'scroll' : 'auto' + }, Textarea.DIV_PROPERTIES, this._getStyles()); + }, + + _getStyles: (function ($) { + var color = $('<div></div>').css(['color']).color; + if (typeof color !== 'undefined') { + return function () { + return this.$el.css(Textarea.COPY_PROPERTIES); + }; + } else { // jQuery < 1.8 + return function () { + var $el = this.$el; + var styles = {}; + $.each(Textarea.COPY_PROPERTIES, function (i, property) { + styles[property] = $el.css(property); + }); + return styles; + }; + } + })($), + + getTextFromHeadToCaret: function () { + return this.el.value.substring(0, this.el.selectionEnd); + } + }); + + $.fn.textcomplete.Textarea = Textarea; +}(jQuery); + ++function ($) { + 'use strict'; + + var sentinelChar = '吶'; + + function IETextarea(element, completer, option) { + this.initialize(element, completer, option); + $('<span>' + sentinelChar + '</span>').css({ + position: 'absolute', + top: -9999, + left: -9999 + }).insertBefore(element); + } + + $.extend(IETextarea.prototype, $.fn.textcomplete.Textarea.prototype, { + // Public methods + // -------------- + + select: function (value, strategy) { + var pre = this.getTextFromHeadToCaret(); + var post = this.el.value.substring(pre.length); + var newSubstr = strategy.replace(value); + if ($.isArray(newSubstr)) { + post = newSubstr[1] + post; + newSubstr = newSubstr[0]; + } + pre = pre.replace(strategy.match, newSubstr); + this.$el.val(pre + post); + this.el.focus(); + var range = this.el.createTextRange(); + range.collapse(true); + range.moveEnd('character', pre.length); + range.moveStart('character', pre.length); + range.select(); + }, + + getTextFromHeadToCaret: function () { + this.el.focus(); + var range = document.selection.createRange(); + range.moveStart('character', -this.el.value.length); + var arr = range.text.split(sentinelChar) + return arr.length === 1 ? arr[0] : arr[1]; + } + }); + + $.fn.textcomplete.IETextarea = IETextarea; +}(jQuery); + +// NOTE: TextComplete plugin has contenteditable support but it does not work +// fine especially on old IEs. +// Any pull requests are REALLY welcome. + ++function ($) { + 'use strict'; + + // ContentEditable adapter + // ======================= + // + // Adapter for contenteditable elements. + function ContentEditable (element, completer, option) { + this.initialize(element, completer, option); + } + + $.extend(ContentEditable.prototype, $.fn.textcomplete.Adapter.prototype, { + // Public methods + // -------------- + + // Update the content with the given value and strategy. + // When an dropdown item is selected, it is executed. + select: function (value, strategy) { + var pre = this.getTextFromHeadToCaret(); + var sel = window.getSelection() + var range = sel.getRangeAt(0); + var selection = range.cloneRange(); + selection.selectNodeContents(range.startContainer); + var content = selection.toString(); + var post = content.substring(range.startOffset); + var newSubstr = strategy.replace(value); + if ($.isArray(newSubstr)) { + post = newSubstr[1] + post; + newSubstr = newSubstr[0]; + } + pre = pre.replace(strategy.match, newSubstr); + range.selectNodeContents(range.startContainer); + range.deleteContents(); + var node = document.createTextNode(pre + post); + range.insertNode(node); + range.setStart(node, pre.length); + range.collapse(true); + sel.removeAllRanges(); + sel.addRange(range); + }, + + // Private methods + // --------------- + + // Returns the caret's relative position from the contenteditable's + // left top corner. + // + // Examples + // + // this._getCaretRelativePosition() + // //=> { top: 18, left: 200, lineHeight: 16 } + // + // Dropdown's position will be decided using the result. + _getCaretRelativePosition: function () { + var range = window.getSelection().getRangeAt(0).cloneRange(); + var node = document.createElement('span'); + range.insertNode(node); + range.selectNodeContents(node); + range.deleteContents(); + var $node = $(node); + var position = $node.offset(); + position.left -= this.$el.offset().left; + position.top += $node.height() - this.$el.offset().top; + position.lineHeight = $node.height(); + var dir = this.$el.attr('dir') || this.$el.css('direction'); + if (dir === 'rtl') { position.left -= this.listView.$el.width(); } + return position; + }, + + // Returns the string between the first character and the caret. + // Completer will be triggered with the result for start autocompleting. + // + // Example + // + // // Suppose the html is '<b>hello</b> wor|ld' and | is the caret. + // this.getTextFromHeadToCaret() + // // => ' wor' // not '<b>hello</b> wor' + getTextFromHeadToCaret: function () { + var range = window.getSelection().getRangeAt(0); + var selection = range.cloneRange(); + selection.selectNodeContents(range.startContainer); + return selection.toString().substring(0, range.startOffset); + } + }); + + $.fn.textcomplete.ContentEditable = ContentEditable; +}(jQuery); diff --git a/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.min.js b/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.min.js new file mode 100644 index 0000000..76aca65 --- /dev/null +++ b/ShoutBox/resources/jquery.textcomplete/jquery.textcomplete.min.js @@ -0,0 +1,4 @@ +/*! jquery-textcomplete - v0.3.3 - 2014-12-03 */if("undefined"==typeof jQuery)throw new Error("jQuery.textcomplete requires jQuery");+function(a){"use strict";var b=function(a){console.warn&&console.warn(a)};a.fn.textcomplete=function(c,d){var e=Array.prototype.slice.call(arguments);return this.each(function(){var f=a(this),g=f.data("textComplete");if(g||(g=new a.fn.textcomplete.Completer(this,d||{}),f.data("textComplete",g)),"string"==typeof c){if(!g)return;e.shift(),g[c].apply(g,e)}else a.each(c,function(c){a.each(["header","footer","placement","maxCount"],function(a){c[a]&&(g.option[a]=c[a],b(a+"as a strategy param is deplicated. Use option."),delete c[a])})}),g.register(a.fn.textcomplete.Strategy.parse(c))})}}(jQuery),+function(a){"use strict";function b(c,d){if(this.$el=a(c),this.id="textcomplete"+e++,this.strategies=[],this.views=[],this.option=a.extend({},b.DEFAULTS,d),!this.$el.is("textarea")&&!c.isContentEditable)throw new Error("textcomplete must be called to a Textarea or a ContentEditable.");if(c===document.activeElement)this.initialize();else{var f=this;this.$el.one("focus."+this.id,function(){f.initialize()})}}var c=function(a){var b,c;return function(){var d=Array.prototype.slice.call(arguments);if(b)return c=d,void 0;b=!0;var e=this;d.unshift(function f(){if(c){var d=c;c=void 0,d.unshift(f),a.apply(e,d)}else b=!1}),a.apply(this,d)}},d=function(a){return"[object String]"===Object.prototype.toString.call(a)},e=0;b.DEFAULTS={appendTo:a("body"),zIndex:"100"},a.extend(b.prototype,{id:null,option:null,strategies:null,adapter:null,dropdown:null,$el:null,initialize:function(){var b=this.$el.get(0);this.dropdown=new a.fn.textcomplete.Dropdown(b,this,this.option);var c,d;this.option.adapter?c=this.option.adapter:(d=this.$el.is("textarea")?"number"==typeof b.selectionEnd?"Textarea":"IETextarea":"ContentEditable",c=a.fn.textcomplete[d]),this.adapter=new c(b,this,this.option)},destroy:function(){this.$el.off("."+this.id),this.adapter&&this.adapter.destroy(),this.dropdown&&this.dropdown.destroy(),this.$el=this.adapter=this.dropdown=null},trigger:function(a,b){this.dropdown||this.initialize(),null!=a||(a=this.adapter.getTextFromHeadToCaret());var c=this._extractSearchQuery(a);if(c.length){var d=c[1];if(b&&this._term===d)return;this._term=d,this._search.apply(this,c)}else this._term=null,this.dropdown.deactivate()},fire:function(a){return this.$el.trigger(a),this},register:function(a){Array.prototype.push.apply(this.strategies,a)},select:function(a,b){this.adapter.select(a,b),this.fire("change").fire("textComplete:select",a,b),this.adapter.focus()},_clearAtNext:!0,_term:null,_extractSearchQuery:function(a){for(var b=0;b<this.strategies.length;b++){var c=this.strategies[b],e=c.context(a);if(e||""===e){d(e)&&(a=e);var f=a.match(c.match);if(f)return[c,f[c.index],f]}}return[]},_search:c(function(a,b,c,d){var e=this;b.search(c,function(c,d){e.dropdown.shown||(e.dropdown.activate(),e.dropdown.setPosition(e.adapter.getCaretPosition())),e._clearAtNext&&(e.dropdown.clear(),e._clearAtNext=!1),e.dropdown.render(e._zip(c,b)),d||(a(),e._clearAtNext=!0)},d)}),_zip:function(b,c){return a.map(b,function(a){return{value:a,strategy:c}})}}),a.fn.textcomplete.Completer=b}(jQuery),+function(a){"use strict";function b(c,e,f){this.$el=b.findOrCreateElement(f),this.completer=e,this.id=e.id+"dropdown",this._data=[],this.$inputEl=a(c),f.listPosition&&(this.setPosition=f.listPosition),f.height&&this.$el.height(f.height);var g=this;a.each(["maxCount","placement","footer","header","className"],function(a,b){null!=f[b]&&(g[b]=f[b])}),this._bindEvents(c),d[this.id]=this}var c=function(a,b){var c,d,e=b.strategy.idProperty;for(c=0;c<a.length;c++)if(d=a[c],d.strategy===b.strategy)if(e){if(d.value[e]===b.value[e])return!0}else if(d.value===b.value)return!0;return!1},d={};a(document).on("click",function(b){var c=b.originalEvent&&b.originalEvent.keepTextCompleteDropdown;a.each(d,function(a,b){a!==c&&b.deactivate()})}),a.extend(b,{findOrCreateElement:function(b){var c=b.appendTo;c instanceof a||(c=a(c));var d=c.children(".dropdown-menu");return d.length||(d=a('<ul class="dropdown-menu"></ul>').css({display:"none",left:0,position:"absolute",zIndex:b.zIndex}).appendTo(c)),d}}),a.extend(b.prototype,{$el:null,$inputEl:null,completer:null,footer:null,header:null,id:null,maxCount:10,placement:"",shown:!1,data:[],className:"",destroy:function(){this.deactivate(),this.$el.off("."+this.id),this.$inputEl.off("."+this.id),this.clear(),this.$el=this.$inputEl=this.completer=null,delete d[this.id]},render:function(b){var c=this._buildContents(b),d=a.map(this.data,function(a){return a.value});this.data.length?(this._renderHeader(d),this._renderFooter(d),c&&(this._renderContents(c),this._activateIndexedItem()),this._setScroll()):this.shown&&this.deactivate()},setPosition:function(a){return this.$el.css(this._applyPlacement(a)),this},clear:function(){this.$el.html(""),this.data=[],this._index=0,this._$header=this._$footer=null},activate:function(){return this.shown||(this.clear(),this.$el.show(),this.className&&this.$el.addClass(this.className),this.completer.fire("textComplete:show"),this.shown=!0),this},deactivate:function(){return this.shown&&(this.$el.hide(),this.className&&this.$el.removeClass(this.className),this.completer.fire("textComplete:hide"),this.shown=!1),this},isUp:function(a){return 38===a.keyCode||a.ctrlKey&&80===a.keyCode},isDown:function(a){return 40===a.keyCode||a.ctrlKey&&78===a.keyCode},isEnter:function(a){var b=a.ctrlKey||a.altKey||a.metaKey||a.shiftKey;return!b&&(13===a.keyCode||9===a.keyCode)},isPageup:function(a){return 33===a.keyCode},isPagedown:function(a){return 34===a.keyCode},_data:null,_index:null,_$header:null,_$footer:null,_bindEvents:function(){this.$el.on("mousedown."+this.id,".textcomplete-item",a.proxy(this._onClick,this)),this.$el.on("mouseover."+this.id,".textcomplete-item",a.proxy(this._onMouseover,this)),this.$inputEl.on("keydown."+this.id,a.proxy(this._onKeydown,this))},_onClick:function(b){var c=a(b.target);b.preventDefault(),b.originalEvent.keepTextCompleteDropdown=this.id,c.hasClass("textcomplete-item")||(c=c.closest(".textcomplete-item"));var d=this.data[parseInt(c.data("index"),10)];this.completer.select(d.value,d.strategy);var e=this;setTimeout(function(){e.deactivate()},0)},_onMouseover:function(b){var c=a(b.target);b.preventDefault(),c.hasClass("textcomplete-item")||(c=c.closest(".textcomplete-item")),this._index=parseInt(c.data("index"),10),this._activateIndexedItem()},_onKeydown:function(a){this.shown&&(this.isUp(a)?(a.preventDefault(),this._up()):this.isDown(a)?(a.preventDefault(),this._down()):this.isEnter(a)?(a.preventDefault(),this._enter()):this.isPageup(a)?(a.preventDefault(),this._pageup()):this.isPagedown(a)&&(a.preventDefault(),this._pagedown()))},_up:function(){0===this._index?this._index=this.data.length-1:this._index-=1,this._activateIndexedItem(),this._setScroll()},_down:function(){this._index===this.data.length-1?this._index=0:this._index+=1,this._activateIndexedItem(),this._setScroll()},_enter:function(){var a=this.data[parseInt(this._getActiveElement().data("index"),10)];this.completer.select(a.value,a.strategy),this._setScroll()},_pageup:function(){var b=0,c=this._getActiveElement().position().top-this.$el.innerHeight();this.$el.children().each(function(d){return a(this).position().top+a(this).outerHeight()>c?(b=d,!1):void 0}),this._index=b,this._activateIndexedItem(),this._setScroll()},_pagedown:function(){var b=this.data.length-1,c=this._getActiveElement().position().top+this.$el.innerHeight();this.$el.children().each(function(d){return a(this).position().top>c?(b=d,!1):void 0}),this._index=b,this._activateIndexedItem(),this._setScroll()},_activateIndexedItem:function(){this.$el.find(".textcomplete-item.active").removeClass("active"),this._getActiveElement().addClass("active")},_getActiveElement:function(){return this.$el.children(".textcomplete-item:nth("+this._index+")")},_setScroll:function(){var a=this._getActiveElement(),b=a.position().top,c=a.outerHeight(),d=this.$el.innerHeight(),e=this.$el.scrollTop();0===this._index||this._index==this.data.length-1||0>b?this.$el.scrollTop(b+e):b+c>d&&this.$el.scrollTop(b+c+e-d)},_buildContents:function(a){var b,d,e,f="";for(d=0;d<a.length&&this.data.length!==this.maxCount;d++)b=a[d],c(this.data,b)||(e=this.data.length,this.data.push(b),f+='<li class="textcomplete-item" data-index="'+e+'"><a>',f+=b.strategy.template(b.value),f+="</a></li>");return f},_renderHeader:function(b){if(this.header){this._$header||(this._$header=a('<li class="textcomplete-header"></li>').prependTo(this.$el));var c=a.isFunction(this.header)?this.header(b):this.header;this._$header.html(c)}},_renderFooter:function(b){if(this.footer){this._$footer||(this._$footer=a('<li class="textcomplete-footer"></li>').appendTo(this.$el));var c=a.isFunction(this.footer)?this.footer(b):this.footer;this._$footer.html(c)}},_renderContents:function(a){this._$footer?this._$footer.before(a):this.$el.append(a)},_applyPlacement:function(a){return-1!==this.placement.indexOf("top")?a={top:"auto",bottom:this.$el.parent().height()-a.top+a.lineHeight,left:a.left}:(a.bottom="auto",delete a.lineHeight),-1!==this.placement.indexOf("absleft")?a.left=0:-1!==this.placement.indexOf("absright")&&(a.right=0,a.left="auto"),a}}),a.fn.textcomplete.Dropdown=b}(jQuery),+function(a){"use strict";function b(b){a.extend(this,b),this.cache&&(this.search=c(this.search))}var c=function(a){var b={};return function(c,d){b[c]?d(b[c]):a.call(this,c,function(a){b[c]=(b[c]||[]).concat(a),d.apply(null,arguments)})}};b.parse=function(c){return a.map(c,function(a){return new b(a)})},a.extend(b.prototype,{match:null,replace:null,search:null,cache:!1,context:function(){return!0},index:2,template:function(a){return a},idProperty:null}),a.fn.textcomplete.Strategy=b}(jQuery),+function(a){"use strict";function b(){}var c=Date.now||function(){return(new Date).getTime()},d=function(a,b){var d,e,f,g,h,i=function(){var j=c()-g;b>j?d=setTimeout(i,b-j):(d=null,h=a.apply(f,e),f=e=null)};return function(){return f=this,e=arguments,g=c(),d||(d=setTimeout(i,b)),h}};a.extend(b.prototype,{id:null,completer:null,el:null,$el:null,option:null,initialize:function(b,c,e){this.el=b,this.$el=a(b),this.id=c.id+this.constructor.name,this.completer=c,this.option=e,this.option.debounce&&(this._onKeyup=d(this._onKeyup,this.option.debounce)),this._bindEvents()},destroy:function(){this.$el.off("."+this.id),this.$el=this.el=this.completer=null},select:function(){throw new Error("Not implemented")},getCaretPosition:function(){var a=this._getCaretRelativePosition(),b=this.$el.offset();return a.top+=b.top,a.left+=b.left,a},focus:function(){this.$el.focus()},_bindEvents:function(){this.$el.on("keyup."+this.id,a.proxy(this._onKeyup,this))},_onKeyup:function(a){this._skipSearch(a)||this.completer.trigger(this.getTextFromHeadToCaret(),!0)},_skipSearch:function(a){switch(a.keyCode){case 40:case 38:return!0}if(a.ctrlKey)switch(a.keyCode){case 78:case 80:return!0}}}),a.fn.textcomplete.Adapter=b}(jQuery),+function(a){"use strict";function b(a,b,c){this.initialize(a,b,c)}b.DIV_PROPERTIES={left:-9999,position:"absolute",top:0,whiteSpace:"pre-wrap"},b.COPY_PROPERTIES=["border-width","font-family","font-size","font-style","font-variant","font-weight","height","letter-spacing","word-spacing","line-height","text-decoration","text-align","width","padding-top","padding-right","padding-bottom","padding-left","margin-top","margin-right","margin-bottom","margin-left","border-style","box-sizing","tab-size"],a.extend(b.prototype,a.fn.textcomplete.Adapter.prototype,{select:function(b,c){var d=this.getTextFromHeadToCaret(),e=this.el.value.substring(this.el.selectionEnd),f=c.replace(b);a.isArray(f)&&(e=f[1]+e,f=f[0]),d=d.replace(c.match,f),this.$el.val(d+e),this.el.selectionStart=this.el.selectionEnd=d.length},_getCaretRelativePosition:function(){var b=a("<div></div>").css(this._copyCss()).text(this.getTextFromHeadToCaret()),c=a("<span></span>").text(".").appendTo(b);this.$el.before(b);var d=c.position();return d.top+=c.height()-this.$el.scrollTop(),d.lineHeight=c.height(),b.remove(),d},_copyCss:function(){return a.extend({overflow:this.el.scrollHeight>this.el.offsetHeight?"scroll":"auto"},b.DIV_PROPERTIES,this._getStyles())},_getStyles:function(a){var c=a("<div></div>").css(["color"]).color;return"undefined"!=typeof c?function(){return this.$el.css(b.COPY_PROPERTIES)}:function(){var c=this.$el,d={};return a.each(b.COPY_PROPERTIES,function(a,b){d[b]=c.css(b)}),d}}(a),getTextFromHeadToCaret:function(){return this.el.value.substring(0,this.el.selectionEnd)}}),a.fn.textcomplete.Textarea=b}(jQuery),+function(a){"use strict";function b(b,d,e){this.initialize(b,d,e),a("<span>"+c+"</span>").css({position:"absolute",top:-9999,left:-9999}).insertBefore(b)}var c="吶";a.extend(b.prototype,a.fn.textcomplete.Textarea.prototype,{select:function(b,c){var d=this.getTextFromHeadToCaret(),e=this.el.value.substring(d.length),f=c.replace(b);a.isArray(f)&&(e=f[1]+e,f=f[0]),d=d.replace(c.match,f),this.$el.val(d+e),this.el.focus();var g=this.el.createTextRange();g.collapse(!0),g.moveEnd("character",d.length),g.moveStart("character",d.length),g.select()},getTextFromHeadToCaret:function(){this.el.focus();var a=document.selection.createRange();a.moveStart("character",-this.el.value.length);var b=a.text.split(c);return 1===b.length?b[0]:b[1]}}),a.fn.textcomplete.IETextarea=b}(jQuery),+function(a){"use strict";function b(a,b,c){this.initialize(a,b,c)}a.extend(b.prototype,a.fn.textcomplete.Adapter.prototype,{select:function(b,c){var d=this.getTextFromHeadToCaret(),e=window.getSelection(),f=e.getRangeAt(0),g=f.cloneRange();g.selectNodeContents(f.startContainer);var h=g.toString(),i=h.substring(f.startOffset),j=c.replace(b);a.isArray(j)&&(i=j[1]+i,j=j[0]),d=d.replace(c.match,j),f.selectNodeContents(f.startContainer),f.deleteContents();var k=document.createTextNode(d+i);f.insertNode(k),f.setStart(k,d.length),f.collapse(!0),e.removeAllRanges(),e.addRange(f)},_getCaretRelativePosition:function(){var b=window.getSelection().getRangeAt(0).cloneRange(),c=document.createElement("span");b.insertNode(c),b.selectNodeContents(c),b.deleteContents();var d=a(c),e=d.offset();e.left-=this.$el.offset().left,e.top+=d.height()-this.$el.offset().top,e.lineHeight=d.height();var f=this.$el.attr("dir")||this.$el.css("direction");return"rtl"===f&&(e.left-=this.listView.$el.width()),e},getTextFromHeadToCaret:function(){var a=window.getSelection().getRangeAt(0),b=a.cloneRange();return b.selectNodeContents(a.startContainer),b.toString().substring(0,a.startOffset)}}),a.fn.textcomplete.ContentEditable=b}(jQuery); +/* +//@ sourceMappingURL=dist/jquery.textcomplete.min.map +*/ \ No newline at end of file -- To view, visit https://gerrit.wikimedia.org/r/189458 To unsubscribe, visit https://gerrit.wikimedia.org/r/settings Gerrit-MessageType: merged Gerrit-Change-Id: I18a7f4c01e7a1cc2f0dbf930967c072cf0e80eac Gerrit-PatchSet: 1 Gerrit-Project: mediawiki/extensions/BlueSpiceExtensions Gerrit-Branch: REL1_23 Gerrit-Owner: Robert Vogel <vo...@hallowelt.biz> Gerrit-Reviewer: Robert Vogel <vo...@hallowelt.biz> Gerrit-Reviewer: Tweichart <weich...@hallowelt.biz> Gerrit-Reviewer: jenkins-bot <> _______________________________________________ MediaWiki-commits mailing list MediaWiki-commits@lists.wikimedia.org https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits