پرش به محتوا

مدیاویکی:Gadget-AncreTitres.js: تفاوت میان نسخه‌ها

از دانشنامه علوم انسانی
imported>Jeeputer
سازگاری با ساختار HTML جدید عنوان بخش‌ها
imported>Jeeputer
این نسخه را از ویکی‌پدیای فرانسوی به‌روز کردم و قابلیت کپی کردن پیوند پایدار را به آن افزودم (به‌دلیل تغییر ساختار عنوان بخش‌ها، در مقاله‌ها ظاهر نمی‌شد). در نسخهٔ قبلی، پیوند پایدار به‌صورت نشانی وب کپی می‌شد، اما در این نسخه به‌شکل پیوند پایدار داخلی کپی می‌شود و مبنایش هم دریافت شناسه از API است.
خط ۱: خط ۱:
/*jslint browser:true */
/**
/*global $, */
* AncreTitres
/*global alert, jQuery, mediaWiki, window */
*
* Cette fonction fournit un lien vers une section de page en cliquant
* sur le lien [URL] ou [[lien]] à droite du titre de section.
*
* Auteurs : Pabix, Phe, Bayo, Chphe, Arkanosis, Mah3110, Ash_Crow, Dalba, Jeeputer
* {{Projet:JavaScript/Script|AncreTitres}}
*/
/* global $, mw */
/* eslint-env browser */
// <nowiki>
// <nowiki>
(function (mw, $) {
mw.loader.using( [ 'mediawiki.util', 'user' ], function () {
    'use strict';
'use strict';
    function toClipboard(what, text) {
        // https://stackoverflow.com/a/30810322/2705757
        var textArea = document.createElement("textarea");
        // Prevent scrolling to bottom of page in MS Edge/FF
        textArea.style.position = "fixed";
        textArea.style.top = 0;
        textArea.style.left = 0;
        // Ensure it has a small width and height. Setting to 1px / 1em
        // doesn't work as this gives a negative w/h on some browsers.
        textArea.style.width = '2em';
        textArea.style.height = '2em';
        // We don't need padding, reducing the size if it does flash render.
        textArea.style.padding = 0;
        // Clean up any borders.
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';
        // Avoid flash of white box if rendered for any reason.
        textArea.style.background = 'transparent';
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
            document.execCommand('copy');
        } catch (err) {
            mw.notify('امکان انتقال به بریده‌دان نبود');
            return;
        }
        finally {
            document.body.removeChild(textArea);
        }
        mw.notify(what + ' به بریده‌دان منتقل شد');
    }
    $(function () {
        var _option = {
            nom_permalink: 'پایاپیوند',
            nom_ancre: 'نشانی وب',
            nom_lien_interne: 'ویکی‌پیوند',
            description_pl: 'فرستادن پیوند پایدار به بریده‌دان',
            description: 'انتقال نشانی وب ساده به بریده‌دان',
            descinterne: 'انتقال ویکی‌پیوند به بریده‌دان',
        };
        if (typeof window.AncreTitres !== 'undefined') {
            $.extend(_option, window.AncreTitres);
        }


        var sep = $('<span> | </span>');
$( function ( $ ) {
        var permalink = $('#t-permalink a').length && $('#t-permalink a')[0].href;
var lang = mw.config.get( 'wgUserLanguage' ),
        var urlPrefix = 'https:' + mw.config.get('wgServer') + mw.config.get('wgScript') + '?title=' + mw.config.get('wgPageName');
messages = {
en: {
'ancretitres-anchor-name': '[URL]',
'ancretitres-internal-link-name': '[[Link]]',
'ancretitres-permanent-link-name': '[[Permalink]]',
'ancretitres-description': 'Get an URL to this section',
'ancretitres-int-description': 'Get an internal link to this section',
'ancretitres-int-description': 'Get a permanent link to this section',
'ancretitres-notif-title': 'Text copied to clipboard',
'ancretitres-notif-error': 'Could not copy to clipboard'
},
fa: {
'ancretitres-anchor-name': '[نشانی وب]',
'ancretitres-internal-link-name': '[[ویکی‌پیوند]]',
'ancretitres-permanent-link-name': '[[پایاپیوند]]',
'ancretitres-description': 'دریافت نشانی وب برای این بخش',
'ancretitres-int-description': 'دریافت پیوند داخلی به این بخش',
'ancretitres-permanent-description': 'دریافت پیوند پایدار به این بخش',
'ancretitres-notif-title': 'متن به بریده‌دان منتقل شد',
'ancretitres-notif-error': 'ناتوان از رونویسی در بریده‌دان'
}
},
options = {
afficheE: true,
afficheI: true,
afficheP: true
};


        $('.mw-heading > h2').each(function (_, headline) {
mw.messages.set( messages.en );
            var linksSection = $('<span> <span class="mw-editsection-bracket">[</span><span class="mw-editsection-bracket">]</span></span>');
if ( lang !== 'en' && lang in messages ) {
            var lastBracket = linksSection.find('.mw-editsection-bracket').last();
mw.messages.set( messages[ lang ] );
            linksSection.css({
}
                '-moz-user-select': 'none',
                '-ms-user-select': 'none',
                '-webkit-user-select': 'none',
                'user-select': 'none',
                'font-size': 'small',
                'font-weight': 'normal',
                'line-height': '1em'
            });


            if (headline.id) {
function copyTextToClipboard( text ) {
                var anchor = '#' + headline.id.replace(/\|/g, encodeURIComponent);
function notifySuccess() {
            } else {
mw.notify( text, { title: mw.msg( 'ancretitres-notif-title' ), tag: 'ancretitres', type: 'info', autoHide: true } );
                var anchor = '';
}
            }


            $('<a href="#" title="' + _option.description + '">' + _option.nom_ancre + '</a>').click(function () {
function notifyError() {
                toClipboard('نشانی وب معمولی', urlPrefix + anchor);
mw.notify( mw.msg( 'ancretitres-notif-error' ), { tag: 'ancretitres', type: 'error', autoHide: true } );
                return false;
}
            }).insertBefore(lastBracket);


            if (permalink) {
if ( navigator.clipboard ) {
                sep.clone().insertBefore(lastBracket);
// Clipboard API
                $('<a href="#" title="' + _option.description_pl + '">' + _option.nom_permalink + '</a>').click(function () {
navigator.clipboard.writeText( text ).then( notifySuccess, notifyError );
                    toClipboard('پایاپیوند', permalink + anchor);
} else {
                    return false;
notifyError();
                }).insertBefore(lastBracket);
}
            }
}


            sep.clone().insertBefore(lastBracket);
if ( typeof window.AncreTitres !== 'undefined' ) {
            $('<a href="#" title="' + _option.descinterne + '">' + _option.nom_lien_interne + '</a>').click(function () {
Object.assign( options, window.AncreTitres );
                toClipboard('ویکی‌پیوند', '[[' + mw.config.get('wgPageName') + anchor + ']]');
}
                return false;
            }).insertBefore(lastBracket);


            if (headline.nextElementSibling && headline.nextElementSibling.className === 'mw-editsection') {
if ( !options.afficheI && !options.afficheE && !options.afficheP ) {
                linksSection.appendTo(headline.nextElementSibling);
return;
            } else {
}
                linksSection.appendTo(headline);
 
            }
// https://phabricator.wikimedia.org/T13555
        });
// https://www.mediawiki.org/wiki/Heading_HTML_changes
    });
 
}(mediaWiki, jQuery));
// old markup (hN > .mw-headline)
// </nowiki>
$( '.mw-headline' ).each( function ( _, mwHeadline ) {
if ( mwHeadline.id ) {
processHeading( mwHeadline.parentElement, mwHeadline.id );
}
} );
 
// new markup (.mw-heading > hN)
$( '.mw-heading' ).each( function ( _, mwHeading ) {
var heading = mwHeading.querySelector( 'h1, h2, h3, h4, h5, h6' );
if ( heading && heading.id ) {
processHeading( mwHeading, heading.id );
}
} );
 
function processHeading( headingContainer, sectionId ) {
var $span = $( '<span>' )
.addClass( 'noprint ancretitres' )
.css( {
'font-size': 'xx-small',
'font-weight': 'normal',
'user-select': 'none' // jQuery se charge d'ajouter un vendor prefix si nécessaire
} );
 
var sectionUrl = 'https://' + mw.config.get( 'wgServerName' ) + mw.util.getUrl() + '#' + sectionId;
 
if ( options.afficheE ) {
var $linkE = $( '<a>' )
.attr( 'href', sectionUrl )
.attr( 'title', mw.msg( 'ancretitres-description' ) )
.text( mw.msg( 'ancretitres-anchor-name' ) )
.click( function ( e ) {
e.preventDefault();
copyTextToClipboard( sectionUrl );
} );
$span.append( ' ', $linkE );
}
 
if ( options.afficheI ) {
var $linkI = $( '<a>' )
.attr( 'href', sectionUrl )
.attr( 'title', mw.msg( 'ancretitres-int-description' ) )
.text( mw.msg( 'ancretitres-internal-link-name' ) )
.click( function ( e ) {
e.preventDefault();
var escapedAnchor = sectionId
// escaping caractères spéciaux HTML
// (partiel, '"& ne sont pas escapés pour ne pas dégrader inutilement la lisibilité du lien)
.replaceAll( '<', '&lt;' )
.replaceAll( '>', '&gt;' )
// escaping caractères spéciaux MediaWiki
.replaceAll( '[', '&#91;' )
.replaceAll( ']', '&#93;' )
.replaceAll( '{', '&#123;' )
.replaceAll( '|', '&#124;' )
.replaceAll( '}', '&#125;' );
var outputText = '[[' + ( mw.config.get( 'wgPageName' ) + '#' + escapedAnchor ).replaceAll( '_', ' ' ) + ']]';
copyTextToClipboard( outputText );
} );
$span.append( ' ', $linkI );
}
if ( options.afficheP ) {
var $linkP = $( '<a>' )
.attr( 'href', sectionUrl )
.attr( 'title', mw.msg( 'ancretitres-permanent-description' ) )
.text( mw.msg( 'ancretitres-permanent-link-name' ) )
.click( function ( e ) {
e.preventDefault();
var api = new mw.Api(),
apiParams = {
action: 'query',
prop: 'revisions',
titles:  mw.config.get( 'wgPageName' ),
rvprop: 'ids',
rvslots: 'main',
formatversion: '2',
format: 'json'
},
escapedAnchor = sectionId
// escaping caractères spéciaux HTML
// (partiel, '"& ne sont pas escapés pour ne pas dégrader inutilement la lisibilité du lien)
.replaceAll( '<', '&lt;' )
.replaceAll( '>', '&gt;' )
// escaping caractères spéciaux MediaWiki
.replaceAll( '[', '&#91;' )
.replaceAll( ']', '&#93;' )
.replaceAll( '{', '&#123;' )
.replaceAll( '|', '&#124;' )
.replaceAll( '}', '&#125;' ),
revid;
api.get( apiParams ).done( function ( data ) {
revid = data.query.pages[0].revisions[0].revid
var outputText = '[[ویژه:پیوند دائمی/' + revid + '#' + ( escapedAnchor ).replaceAll( '_', ' ' ) + ']]';
copyTextToClipboard( outputText );
});
} );
$span.append( ' ', $linkP );
}
 
headingContainer.append( $span[ 0 ] );
}
 
} );
 
} );

نسخهٔ ۲۹ ژوئیهٔ ۲۰۲۴، ساعت ۰۷:۰۶

/**
 * AncreTitres
 *
 * Cette fonction fournit un lien vers une section de page en cliquant
 * sur le lien [URL] ou [[lien]] à droite du titre de section.
 *
 * Auteurs : Pabix, Phe, Bayo, Chphe, Arkanosis, Mah3110, Ash_Crow, Dalba, Jeeputer
 * {{Projet:JavaScript/Script|AncreTitres}}
 */
/* global $, mw */
/* eslint-env browser */
// <nowiki>
mw.loader.using( [ 'mediawiki.util', 'user' ], function () {
	'use strict';

	$( function ( $ ) {
		var lang = mw.config.get( 'wgUserLanguage' ),
			messages = {
				en: {
					'ancretitres-anchor-name': '[URL]',
					'ancretitres-internal-link-name': '[[Link]]',
					'ancretitres-permanent-link-name': '[[Permalink]]',
					'ancretitres-description': 'Get an URL to this section',
					'ancretitres-int-description': 'Get an internal link to this section',
					'ancretitres-int-description': 'Get a permanent link to this section',
					'ancretitres-notif-title': 'Text copied to clipboard',
					'ancretitres-notif-error': 'Could not copy to clipboard'
				},
				fa: {
					'ancretitres-anchor-name': '[نشانی وب]',
					'ancretitres-internal-link-name': '[[ویکی‌پیوند]]',
					'ancretitres-permanent-link-name': '[[پایاپیوند]]',
					'ancretitres-description': 'دریافت نشانی وب برای این بخش',
					'ancretitres-int-description': 'دریافت پیوند داخلی به این بخش',
					'ancretitres-permanent-description': 'دریافت پیوند پایدار به این بخش',
					'ancretitres-notif-title': 'متن به بریده‌دان منتقل شد',
					'ancretitres-notif-error': 'ناتوان از رونویسی در بریده‌دان'
				}
			},
			options = {
				afficheE: true,
				afficheI: true,
				afficheP: true
			};

		mw.messages.set( messages.en );
		if ( lang !== 'en' && lang in messages ) {
			mw.messages.set( messages[ lang ] );
		}

		function copyTextToClipboard( text ) {
			function notifySuccess() {
				mw.notify( text, { title: mw.msg( 'ancretitres-notif-title' ), tag: 'ancretitres', type: 'info', autoHide: true } );
			}

			function notifyError() {
				mw.notify( mw.msg( 'ancretitres-notif-error' ), { tag: 'ancretitres', type: 'error', autoHide: true } );
			}

			if ( navigator.clipboard ) {
				// Clipboard API
				navigator.clipboard.writeText( text ).then( notifySuccess, notifyError );
			} else {
				notifyError();
			}
		}

		if ( typeof window.AncreTitres !== 'undefined' ) {
			Object.assign( options, window.AncreTitres );
		}

		if ( !options.afficheI && !options.afficheE && !options.afficheP ) {
			return;
		}

		// https://phabricator.wikimedia.org/T13555
		// https://www.mediawiki.org/wiki/Heading_HTML_changes

		// old markup (hN > .mw-headline)
		$( '.mw-headline' ).each( function ( _, mwHeadline ) {
			if ( mwHeadline.id ) {
				processHeading( mwHeadline.parentElement, mwHeadline.id );
			}
		} );

		// new markup (.mw-heading > hN)
		$( '.mw-heading' ).each( function ( _, mwHeading ) {
			var heading = mwHeading.querySelector( 'h1, h2, h3, h4, h5, h6' );
			if ( heading && heading.id ) {
				processHeading( mwHeading, heading.id );
			}
		} );

		function processHeading( headingContainer, sectionId ) {
			var $span = $( '<span>' )
				.addClass( 'noprint ancretitres' )
				.css( {
					'font-size': 'xx-small',
					'font-weight': 'normal',
					'user-select': 'none' // jQuery se charge d'ajouter un vendor prefix si nécessaire
				} );

			var sectionUrl = 'https://' + mw.config.get( 'wgServerName' ) + mw.util.getUrl() + '#' + sectionId;

			if ( options.afficheE ) {
				var $linkE = $( '<a>' )
					.attr( 'href', sectionUrl )
					.attr( 'title', mw.msg( 'ancretitres-description' ) )
					.text( mw.msg( 'ancretitres-anchor-name' ) )
					.click( function ( e ) {
						e.preventDefault();
						copyTextToClipboard( sectionUrl );
					} );
				$span.append( ' ', $linkE );
			}

			if ( options.afficheI ) {
				var $linkI = $( '<a>' )
					.attr( 'href', sectionUrl )
					.attr( 'title', mw.msg( 'ancretitres-int-description' ) )
					.text( mw.msg( 'ancretitres-internal-link-name' ) )
					.click( function ( e ) {
						e.preventDefault();
						var escapedAnchor = sectionId
							// escaping caractères spéciaux HTML
							// (partiel, '"& ne sont pas escapés pour ne pas dégrader inutilement la lisibilité du lien)
							.replaceAll( '<', '&lt;' )
							.replaceAll( '>', '&gt;' )
							// escaping caractères spéciaux MediaWiki
							.replaceAll( '[', '&#91;' )
							.replaceAll( ']', '&#93;' )
							.replaceAll( '{', '&#123;' )
							.replaceAll( '|', '&#124;' )
							.replaceAll( '}', '&#125;' );
						var outputText = '[[' + ( mw.config.get( 'wgPageName' ) + '#' + escapedAnchor ).replaceAll( '_', ' ' ) + ']]';
						copyTextToClipboard( outputText );
					} );
				$span.append( ' ', $linkI );
			}
			
			if ( options.afficheP ) {
				var $linkP = $( '<a>' )
					.attr( 'href', sectionUrl )
					.attr( 'title', mw.msg( 'ancretitres-permanent-description' ) )
					.text( mw.msg( 'ancretitres-permanent-link-name' ) )
					.click( function ( e ) {
						e.preventDefault();
						var api = new mw.Api(),
						apiParams = {
							action: 'query',
							prop: 'revisions',
							titles:  mw.config.get( 'wgPageName' ),
							rvprop: 'ids',
							rvslots: 'main',
							formatversion: '2',
							format: 'json'
						},
						escapedAnchor = sectionId
							// escaping caractères spéciaux HTML
							// (partiel, '"& ne sont pas escapés pour ne pas dégrader inutilement la lisibilité du lien)
							.replaceAll( '<', '&lt;' )
							.replaceAll( '>', '&gt;' )
							// escaping caractères spéciaux MediaWiki
							.replaceAll( '[', '&#91;' )
							.replaceAll( ']', '&#93;' )
							.replaceAll( '{', '&#123;' )
							.replaceAll( '|', '&#124;' )
							.replaceAll( '}', '&#125;' ),
						revid;
						api.get( apiParams ).done( function ( data ) {
							revid = data.query.pages[0].revisions[0].revid
							var outputText = '[[ویژه:پیوند دائمی/' + revid + '#' + ( escapedAnchor ).replaceAll( '_', ' ' ) + ']]';
							copyTextToClipboard( outputText );
						});
					} );
				$span.append( ' ', $linkP );
			}

			headingContainer.append( $span[ 0 ] );
		}

	} );

} );