MediaWiki:Gadget-FotoPicker.js

Z Dane WikiZagłębie

Uwaga: aby zobaczyć zmiany po opublikowaniu, może zajść potrzeba wyczyszczenia pamięci podręcznej przeglądarki.

  • Firefox / Safari: Przytrzymaj Shift podczas klikania Odśwież bieżącą stronę, lub naciśnij klawisze Ctrl+F5, lub Ctrl+R (⌘-R na komputerze Mac)
  • Google Chrome: Naciśnij Ctrl-Shift-R (⌘-Shift-R na komputerze Mac)
  • Edge: Przytrzymaj Ctrl, jednocześnie klikając Odśwież, lub naciśnij klawisze Ctrl+F5.
  • Opera: Naciśnij klawisze Ctrl+F5.
/**
 * Wybór pliku z Foto WikiZagłębie dla Dane (dane.wikizaglebie.org), wersja 1.0.0 (11.2026).
 * Przy edycji wartości właściwości plikowych (typ „ciąg znaków”: plik herbu, flagi, okładki, zdjęcia, logo,
 * mapy, podpisu) podpowiada pliki z foto.wikizaglebie.org z miniaturami, pozwala przeglądać zdjęcia
 * (też z kategorii foto elementu – P17) i ostrzega, gdy pliku nie ma na Foto.
 * Tylko interfejs – nie zmienia danych ani Wikibase. Składnia ES2016 (walidacja ResourceLoadera MW 1.43).
 * Wdrożenie: MediaWiki:Gadget-FotoPicker.js i .css na Dane.
 */
( function () {
	'use strict';

	const VERSION = '1.0.1';
	const FOTO_API = 'https://foto.wikizaglebie.org/api.php';
	const FOTO_WIKI = 'https://foto.wikizaglebie.org/wiki/';
	const FILE_PROPERTIES = [ 'P15', 'P75', 'P76', 'P90', 'P251', 'P252', 'P264', 'P266' ];
	const CATEGORY_PROPERTY = 'P17';
	const THUMB = 160;
	const DEBOUNCE_MS = 300;

	// Nazwa pliku z wpisu: bez „Plik:”/„File:”, bez adresu, spacje zamiast podkreślników
	function fileName( value ) {
		let name = String( value || '' ).trim();
		const url = /\/(?:wiki\/|index\.php\?title=)(?:Plik|File|Grafika|Image):([^?#&]+)/i.exec( name );
		if ( url ) {
			try { name = decodeURIComponent( url[ 1 ] ); } catch ( e ) { name = url[ 1 ]; }
		}
		name = name.replace( /^(?:Plik|File|Grafika|Image)\s*:/i, '' ).replace( /_/g, ' ' ).replace( /\s+/g, ' ' ).trim();
		return name ? name.charAt( 0 ).toUpperCase() + name.slice( 1 ) : '';
	}

	function propertyOf( input ) {
		const snak = input.closest( '.wikibase-snakview' );
		if ( !snak ) { return null; }
		const link = snak.querySelector( '.wikibase-snakview-property a[href*="Property:P"]' );
		if ( link ) {
			const m = /Property:(P\d+)/.exec( link.getAttribute( 'href' ) );
			if ( m ) { return m[ 1 ]; }
		}
		const field = snak.querySelector( '.wikibase-snakview-property input' );
		if ( field && window.jQuery ) {
			const selector = window.jQuery( field ).data( 'entityselector' );
			const entity = selector && selector.selectedEntity && selector.selectedEntity();
			if ( entity && entity.id ) { return entity.id; }
		}
		const group = input.closest( '.wikibase-statementgroupview' );
		return group && /^P\d+$/.test( group.id ) ? group.id : null;
	}

	function api( params ) {
		const query = Object.assign( { format: 'json', formatversion: 2, origin: '*' }, params );
		const url = FOTO_API + '?' + Object.keys( query ).map( ( k ) =>
			encodeURIComponent( k ) + '=' + encodeURIComponent( query[ k ] ) ).join( '&' );
		return fetch( url, { credentials: 'omit' } ).then( ( r ) => {
			if ( !r.ok ) { throw new Error( 'Foto API: HTTP ' + r.status ); }
			return r.json();
		} );
	}

	function filesFrom( data ) {
		const pages = data && data.query && data.query.pages || [];
		return pages.filter( ( p ) => p.imageinfo && p.imageinfo[ 0 ] && !p.missing )
			.sort( ( a, b ) => ( a.index || 0 ) - ( b.index || 0 ) )
			.map( ( p ) => ( {
				name: p.title.replace( /^[^:]+:/, '' ),
				thumb: p.imageinfo[ 0 ].thumburl || p.imageinfo[ 0 ].url,
				width: p.imageinfo[ 0 ].width,
				height: p.imageinfo[ 0 ].height
			} ) );
	}

	const IMAGE_PROPS = { prop: 'imageinfo', iiprop: 'url|size', iiurlwidth: THUMB };

	// Najpierw początek nazwy, potem wyszukiwanie pełnotekstowe – bez powtórzeń
	function search( text, limit ) {
		const term = fileName( text );
		if ( term.length < 2 ) { return Promise.resolve( [] ); }
		const prefix = api( Object.assign( { action: 'query', generator: 'prefixsearch', gpssearch: term,
			gpsnamespace: 6, gpslimit: limit }, IMAGE_PROPS ) ).then( filesFrom ).catch( () => [] );
		const full = api( Object.assign( { action: 'query', generator: 'search', gsrsearch: term,
			gsrnamespace: 6, gsrlimit: limit }, IMAGE_PROPS ) ).then( filesFrom ).catch( () => [] );
		return Promise.all( [ prefix, full ] ).then( ( lists ) => {
			const seen = new Set();
			return lists[ 0 ].concat( lists[ 1 ] ).filter( ( f ) => !seen.has( f.name ) && seen.add( f.name ) ).slice( 0, limit );
		} );
	}

	function categoryFiles( category ) {
		return api( Object.assign( { action: 'query', generator: 'categorymembers',
			gcmtitle: 'Kategoria:' + category, gcmtype: 'file', gcmlimit: 60 }, IMAGE_PROPS ) ).then( filesFrom );
	}

	function exists( name ) {
		return api( { action: 'query', titles: 'Plik:' + name, prop: 'imageinfo', iiprop: 'size' } )
			.then( ( data ) => {
				const page = data.query && data.query.pages && data.query.pages[ 0 ];
				return !!( page && !page.missing && page.imageinfo );
			} );
	}

	// Kategoria zdjęć obiektu na Foto (P17 bieżącego elementu)
	function entityCategory() {
		let entity = mw.config.get( 'wbEntity' );
		try { entity = typeof entity === 'string' ? JSON.parse( entity ) : entity; } catch ( e ) { return null; }
		const claims = entity && entity.claims && entity.claims[ CATEGORY_PROPERTY ];
		const snak = claims && claims[ 0 ] && claims[ 0 ].mainsnak;
		const value = snak && snak.datavalue && snak.datavalue.value;
		return typeof value === 'string' && value.trim() ? value.replace( /^Kategoria:/, '' ).trim() : null;
	}

	function el( tag, cls, text ) {
		const node = document.createElement( tag );
		if ( cls ) { node.className = cls; }
		if ( text !== undefined ) { node.textContent = text; }
		return node;
	}

	// Wstawienie nazwy tak, by widget wartości Wikibase ją przyjął
	function setValue( input, name ) {
		input.value = name;
		[ 'input', 'keyup', 'change' ].forEach( ( type ) => input.dispatchEvent( new Event( type, { bubbles: true } ) ) );
		if ( window.jQuery ) { window.jQuery( input ).trigger( 'eachchange' ); }
		input.focus();
	}

	function fileTile( file, onPick ) {
		const tile = el( 'button', 'fp-tile' );
		tile.type = 'button';
		tile.title = file.name;
		const img = el( 'img' );
		img.src = file.thumb; img.alt = ''; img.loading = 'lazy';
		tile.append( img, el( 'span', 'fp-tile-name', file.name ),
			el( 'span', 'fp-tile-size', file.width && file.height ? file.width + '×' + file.height : '' ) );
		tile.addEventListener( 'mousedown', ( e ) => e.preventDefault() );
		tile.addEventListener( 'click', () => onPick( file ) );
		return tile;
	}

	// Okno przeglądania: wyszukiwarka i siatka miniatur (na start – zdjęcia obiektu z P17)
	function browse( input ) {
		const dialog = el( 'dialog', 'fp-dialog' );
		const head = el( 'div', 'fp-dialog-head' );
		head.append( el( 'strong', '', 'Wybierz plik z Foto WikiZagłębie' ) );
		const close = el( 'button', 'fp-close', '×' );
		close.type = 'button'; close.setAttribute( 'aria-label', 'Zamknij' );
		head.append( close );
		const form = el( 'form', 'fp-dialog-search' );
		const query = el( 'input' );
		query.type = 'search'; query.placeholder = 'Szukaj zdjęć na Foto…';
		query.value = fileName( input.value );
		const go = el( 'button', 'fp-btn', 'Szukaj' ); go.type = 'submit';
		form.append( query, go );
		const status = el( 'div', 'fp-status' );
		const grid = el( 'div', 'fp-grid' );
		dialog.append( head, form, status, grid );
		document.body.append( dialog );
		const done = () => { if ( dialog.open ) { dialog.close(); } dialog.remove(); };
		close.addEventListener( 'click', done );
		dialog.addEventListener( 'close', () => dialog.remove() );
		dialog.addEventListener( 'click', ( e ) => { if ( e.target === dialog ) { done(); } } );
		const pick = ( file ) => { done(); setValue( input, file.name ); check( input ); };
		let serial = 0;
		function show( promise, label ) {
			const ticket = ++serial;
			status.textContent = 'Wczytywanie…';
			grid.replaceChildren();
			promise.then( ( files ) => {
				if ( ticket !== serial ) { return; }
				status.textContent = files.length ? label + ' (' + files.length + ')' : 'Nic nie znaleziono.';
				files.forEach( ( f ) => grid.append( fileTile( f, pick ) ) );
			} ).catch( ( e ) => {
				if ( ticket === serial ) { status.textContent = 'Błąd: ' + e.message; }
			} );
		}
		form.addEventListener( 'submit', ( e ) => {
			e.preventDefault();
			show( search( query.value, 60 ), 'Wyniki dla „' + fileName( query.value ) + '”' );
		} );
		const category = entityCategory();
		if ( query.value.length >= 2 ) {
			show( search( query.value, 60 ), 'Wyniki dla „' + query.value + '”' );
		} else if ( category ) {
			show( categoryFiles( category ), 'Zdjęcia z kategorii „' + category + '”' );
		} else {
			status.textContent = 'Wpisz nazwę i kliknij „Szukaj”.';
		}
		dialog.showModal();
		query.focus();
	}

	// Ostrzeżenie, gdy wpisanego pliku nie ma na Foto
	function check( input ) {
		const box = helper( input );
		const name = fileName( input.value );
		const note = box.querySelector( '.fp-note' );
		if ( !name ) { note.textContent = ''; note.className = 'fp-note'; return; }
		exists( name ).then( ( ok ) => {
			if ( fileName( input.value ) !== name ) { return; }
			note.className = 'fp-note ' + ( ok ? 'fp-ok' : 'fp-warn' );
			note.textContent = '';
			if ( ok ) {
				const link = el( 'a', '', '✓ plik jest na Foto' );
				link.href = FOTO_WIKI + 'Plik:' + encodeURIComponent( name.replace( / /g, '_' ) );
				link.target = '_blank'; link.rel = 'noopener';
				note.append( link );
			} else {
				note.textContent = '⚠ Nie ma pliku „' + name + '” na foto.wikizaglebie.org – infoboks go nie pokaże.';
			}
			if ( ok && name !== input.value ) { setValue( input, name ); }
		} ).catch( () => { note.textContent = ''; } );
	}

	// Pasek pod polem: przycisk „Przeglądaj”, lista podpowiedzi, ostrzeżenie
	function helper( input ) {
		const existing = input.parentNode.querySelector( ':scope > .fp-helper' );
		if ( existing ) { return existing; }
		const box = el( 'div', 'fp-helper' );
		const bar = el( 'div', 'fp-bar' );
		const browseBtn = el( 'button', 'fp-btn', '🖼 Przeglądaj zdjęcia z Foto' );
		browseBtn.type = 'button';
		browseBtn.addEventListener( 'mousedown', ( e ) => e.preventDefault() );
		browseBtn.addEventListener( 'click', () => browse( input ) );
		bar.append( browseBtn, el( 'span', 'fp-note' ) );
		const list = el( 'div', 'fp-suggest' );
		list.hidden = true;
		box.append( bar, list );
		input.after( box );
		return box;
	}

	// Eksport pomocniczy tylko do testów Node.js
	if ( typeof module !== 'undefined' && module.exports ) {
		module.exports = { fileName, filesFrom, VERSION };
	}
	if ( typeof document === 'undefined' || typeof mw === 'undefined' ) { return; }

	const timers = new WeakMap();
	let suggestSerial = 0;

	function suggest( input ) {
		const box = helper( input );
		const list = box.querySelector( '.fp-suggest' );
		const value = input.value;
		const ticket = ++suggestSerial;
		if ( fileName( value ).length < 2 ) { list.hidden = true; list.replaceChildren(); return; }
		search( value, 12 ).then( ( files ) => {
			if ( ticket !== suggestSerial || input.value !== value ) { return; }
			list.replaceChildren();
			files.forEach( ( f ) => list.append( fileTile( f, ( file ) => {
				list.hidden = true;
				setValue( input, file.name );
				check( input );
			} ) ) );
			list.hidden = !files.length;
		} );
	}

	function isFileInput( target ) {
		return target && target.matches && target.matches( '.wikibase-snakview-value textarea, .wikibase-snakview-value input[type=text], .wikibase-snakview-value .valueview-input' ) &&
			FILE_PROPERTIES.indexOf( propertyOf( target ) ) !== -1;
	}

	document.addEventListener( 'focusin', ( e ) => {
		if ( isFileInput( e.target ) ) {
			helper( e.target );
			if ( e.target.value ) { check( e.target ); }
		}
	} );
	document.addEventListener( 'input', ( e ) => {
		if ( !isFileInput( e.target ) || !e.isTrusted ) { return; }
		const input = e.target;
		clearTimeout( timers.get( input ) );
		timers.set( input, setTimeout( () => { suggest( input ); check( input ); }, DEBOUNCE_MS ) );
	} );
	document.addEventListener( 'keydown', ( e ) => {
		if ( e.key === 'Escape' && isFileInput( e.target ) ) {
			const list = e.target.parentNode.querySelector( '.fp-suggest' );
			if ( list && !list.hidden ) { list.hidden = true; e.stopPropagation(); }
		}
	}, true );

	mw.log( 'FotoPicker ' + VERSION + ' — załadowano.' );
}() );