MediaWiki:Gadget-FastLinkWZ.js

From WikiZagłębie

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * FastLink dla WikiZagłębia, wersja WZ-1.0.0 (na bazie fastlink.js 1.1.0).
 * Wyszukiwanie: WikiZagłębie (bieżąca instalacja MediaWiki) i Wikipedia PL.
 * Bez Wikidanych, bez fact.js, bez zależności od innych skryptów użytkownika.
 * Edycja wyłącznie po jednoznacznym zlokalizowaniu zaznaczenia i potwierdzeniu.
 * Źródło wariantu: archiwum fact-fastlink-wspolny-pasek (19.10.2026).
 * Wdrożenie: MediaWiki:Gadget-FastLinkWZ.js.
 * WZ-1.2.0: tryb serii – po zapisie bez przeładowania strony (link wstawiany na stronie, nowa wersja zapamiętana).
 * WZ-1.1.0: zaznaczenie w czerwonym linku (np. w tabeli) zamienia ten link na wybrany wynik (11.2026).
 * Składnia ES2016 (bez async/await) – ResourceLoader MW 1.43 waliduje skrypty gadżetów jako ES2016 (10.11.2026).
 */

( function () {
    'use strict';

    const VERSION = 'WZ-1.2.0';
    const SELECTOR = '.mw-parser-output';
    const BUTTON_ID = 'wz-fastlink-button';
    const DIALOG_ID = 'wz-fastlink-dialog';
    const STYLE_ID = 'wz-fastlink-style';
    const MAX_SELECTION = 160;
    const TOOL_PAGE = 'MediaWiki:Gadget-FastLinkWZ.js';
    const SUMMARY = 'Adding a link (using [[' + TOOL_PAGE + '|FastLink]])';
    const SEARCH_DEBOUNCE_MS = 400;
    let localApi, wikipediaApi, button, lastSnapshot, searchSerial = 0;
    let directPlInterwikiPrefix = null;
    let toolbarInstance = null;
    // Tryb serii: wersja strony po ostatnim zapisie FastLinka (bez przeładowania)
    let currentRevision = null;
    let seriesCount = 0;
    const SERIES_KEY = 'wz-fastlink-series';

    function seriesEnabled() {
        try { return window.localStorage.getItem( SERIES_KEY ) === '1'; } catch ( e ) { return false; }
    }

    function setSeries( on ) {
        try { window.localStorage.setItem( SERIES_KEY, on ? '1' : '0' ); } catch ( e ) { /* bez zapamiętania */ }
    }

    function viewedRevision() {
        return currentRevision || Number( mw.config.get( 'wgRevisionId' ) );
    }

    function permitted() {
        const action = mw.config.get( 'wgAction' );
        const ns = Number( mw.config.get( 'wgNamespaceNumber' ) );
        const page = String( mw.config.get( 'wgPageName' ) || '' ).replace( /_/g, ' ' );
        const username = String( mw.config.get( 'wgUserName' ) || '' ).replace( /_/g, ' ' );
        // Artykuły i własna przestrzeń użytkownika do testów.
        const ownUserPage = ns === 2 && page.includes( ':' ) &&
            page.slice( page.indexOf( ':' ) + 1 ).split( '/' )[ 0 ].toLowerCase() === username.toLowerCase();
        return action === 'view' && !!username &&
            ( ns === 0 || ownUserPage ) && Number( mw.config.get( 'wgRevisionId' ) ) > 0;
    }

    function normalize( value ) {
        return String( value || '' ).replace( /\s+/g, ' ' ).trim();
    }

    function textParts( selected ) {
        const match = /^(\s*)([\s\S]*?)([\s.,;:!?…]+)?$/.exec( selected );
        if ( !match ) { throw new Error( 'Unable to read the selection.' ); }
        const before = match[ 1 ];
        const after = match[ 3 ] || '';
        const word = match[ 2 ];
        if ( !word.trim() || /[\r\n\[\]{}|<>]/.test( word ) ) {
            throw new Error( 'Select a name or phrase without wiki markup or line breaks.' );
        }
        return { before, word, after };
    }

    function snapshotSelection() {
        const selection = window.getSelection();
        if ( !selection || selection.isCollapsed || selection.rangeCount !== 1 ) { return null; }
        const range = selection.getRangeAt( 0 );
        const selected = selection.toString();
        if ( !selected || selected.length > MAX_SELECTION ) { return null; }
        const parent = range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE ?
            range.commonAncestorContainer : range.commonAncestorContainer.parentElement;
        const redlink = parent && parent.closest( SELECTOR + ' a.new' );
        if ( redlink ) { return snapshotRedlink( redlink ); }
        if ( !parent || !parent.closest( SELECTOR ) || parent.closest(
            'a, .reference, .reflist, .navbox, .infobox, .toc, .mw-editsection, .wz-fastlink-ui'
        ) ) { return null; }
        if ( range.startContainer.nodeType !== Node.TEXT_NODE ||
            range.endContainer.nodeType !== Node.TEXT_NODE ) { return null; }
        const plain = range.startContainer === range.endContainer;
        const first = range.startContainer;
        const last = range.endContainer;
        const selectedValue = plain ? first.data.slice( range.startOffset, range.endOffset ) : selected;
        if ( !normalize( selectedValue ) ) { return null; }
        const contextBefore = plain ? first.data.slice( Math.max( 0, range.startOffset - 45 ), range.startOffset ) : '';
        const contextAfter = plain ? last.data.slice( range.endOffset, range.endOffset + 45 ) : '';
        try { textParts( selectedValue ); } catch ( e ) { return null; }
        const rect = range.getBoundingClientRect();
        return {
            selected: selectedValue,
            range: plain ? range.cloneRange() : null,
            plain,
            contextBefore,
            contextAfter,
            x: rect.right,
            y: rect.bottom,
            viewedRevision: viewedRevision()
        };
    }

    // Czerwony link: cel z adresu, kolejność wśród czerwonych linków do tego samego celu na stronie
    function redlinkTarget( anchor ) {
        try {
            const title = new URL( anchor.getAttribute( 'href' ), window.location.href ).searchParams.get( 'title' );
            return title ? title.replace( /_/g, ' ' ) : null;
        } catch ( e ) { return null; }
    }

    function snapshotRedlink( anchor ) {
        if ( anchor.closest( '.reference, .reflist, .references, .navbox, .infobox, .toc, .mw-editsection, .wz-fastlink-ui' ) ) {
            return null;
        }
        const target = redlinkTarget( anchor );
        const label = normalize( anchor.textContent );
        if ( !target || !label || label.length > MAX_SELECTION || /[\[\]{}|<>]/.test( label ) ) { return null; }
        const same = Array.from( document.querySelectorAll( SELECTOR + ' a.new' ) )
            .filter( ( a ) => redlinkTarget( a ) === target );
        const rect = anchor.getBoundingClientRect();
        return {
            selected: label,
            plain: true,
            contextBefore: '',
            contextAfter: '',
            redlink: { target, label, index: same.indexOf( anchor ), total: same.length },
            anchor,
            x: rect.right,
            y: rect.bottom,
            viewedRevision: viewedRevision()
        };
    }

    function escapeRegExp( text ) {
        return text.replace( /[.*+?^${}()|[\]\\]/g, '\\$&' );
    }

    // Wystąpienia [[Cel]] / [[Cel|opis]] w wikikodzie (pierwsza litera bez rozróżniania wielkości, spacja = _)
    function redlinkOccurrences( source, target ) {
        const first = target.charAt( 0 );
        const rest = escapeRegExp( target.slice( 1 ) ).replace( / /g, '[ _]+' );
        const head = first.toUpperCase() === first.toLowerCase() ? escapeRegExp( first ) :
            '[' + escapeRegExp( first.toUpperCase() ) + escapeRegExp( first.toLowerCase() ) + ']';
        const pattern = new RegExp( '\\[\\[[ _]*' + head + rest + '[ _]*(?:\\|([^\\[\\]]*))?\\]\\]', 'g' );
        const hidden = [];
        const hiding = /<!--[\s\S]*?-->|<ref\b[^>]*?(?:\/>|>[\s\S]*?<\/ref\s*>)|<nowiki>[\s\S]*?<\/nowiki>/gi;
        let h;
        while ( ( h = hiding.exec( source ) ) !== null ) { hidden.push( [ h.index, h.index + h[ 0 ].length ] ); }
        const found = [];
        let m;
        while ( ( m = pattern.exec( source ) ) !== null ) {
            found.push( {
                start: m.index, end: m.index + m[ 0 ].length,
                label: m[ 1 ] !== undefined ? m[ 1 ] : m[ 0 ].slice( 2, -2 ).trim(),
                hidden: hidden.some( ( r ) => m.index >= r[ 0 ] && m.index < r[ 1 ] )
            } );
        }
        return found;
    }

    function planRedlinkEdit( source, snapshot, option, target ) {
        const red = snapshot.redlink;
        const found = redlinkOccurrences( source, red.target );
        if ( red.index < 0 || found.length !== red.total || found.some( ( f ) => f.hidden ) ) {
            throw new Error( 'Cannot unambiguously identify this red link in the wikitext' +
                '(the link is in a template, reference or comment). Use the source editor.' );
        }
        const hit = found[ red.index ];
        const replacement = makeLink( option, hit.label, target );
        return {
            start: hit.start, end: hit.end, old: source.slice( hit.start, hit.end ), replacement,
            original: source.slice( Math.max( 0, hit.start - 75 ), Math.min( source.length, hit.end + 75 ) ),
            previewBefore: source.slice( Math.max( 0, hit.start - 75 ), hit.start ),
            previewAfter: source.slice( hit.end, Math.min( source.length, hit.end + 75 ) ),
            text: source.slice( 0, hit.start ) + replacement + source.slice( hit.end )
        };
    }

    function countMatches( source, needle ) {
        const found = [];
        if ( !needle ) { return found; }
        let pos = 0;
        while ( ( pos = source.indexOf( needle, pos ) ) !== -1 ) {
            found.push( pos );
            if ( found.length > 100 ) { break; }
            pos++;
        }
        return found;
    }

    // Strażnik struktury wikikodu. Składniowo nie jest pełnym parserem;
    // przypadki niejednoznaczne odrzuca zamiast modyfikować stronę.
    function isPlainPosition( source, position ) {
        let templates = 0, links = 0;
        const blocked = [];
        const tags = new Set( [ 'ref', 'references', 'nowiki', 'pre', 'math', 'source',
            'syntaxhighlight', 'gallery', 'code', 'timeline', 'score', 'templatedata',
            'poem', 'graph', 'mapframe', 'maplink' ] );
        for ( let i = 0; i < position; ) {
            if ( source.startsWith( '<!--', i ) ) {
                const end = source.indexOf( '-->', i + 4 );
                if ( end < 0 || end + 3 > position ) { return false; }
                i = end + 3;
                continue;
            }
            if ( source.charAt( i ) === '<' ) {
                const end = source.indexOf( '>', i + 1 );
                if ( end < 0 || end >= position ) { return false; }
                const tag = /^<\s*(\/?)\s*([a-zA-Z][\w-]*)\b/.exec( source.slice( i, end + 1 ) );
                if ( tag && tags.has( tag[ 2 ].toLowerCase() ) ) {
                    const name = tag[ 2 ].toLowerCase();
                    if ( tag[ 1 ] ) {
                        if ( blocked.pop() !== name ) { return false; }
                    } else if ( !/\/\s*>$/.test( source.slice( i, end + 1 ) ) ) {
                        blocked.push( name );
                    }
                }
                i = end + 1;
                continue;
            }
            if ( blocked.length ) { i++; continue; }
            if ( source.startsWith( '{{', i ) ) { templates++; i += 2; continue; }
            if ( source.startsWith( '}}', i ) ) { templates = Math.max( 0, templates - 1 ); i += 2; continue; }
            if ( source.startsWith( '[[', i ) ) { links++; i += 2; continue; }
            if ( source.startsWith( ']]', i ) ) { links = Math.max( 0, links - 1 ); i += 2; continue; }
            i++;
        }
        return !templates && !links && !blocked.length;
    }

    function safeSpan( source, start, end ) {
        return isPlainPosition( source, start ) && isPlainPosition( source, end );
    }

    function makeLink( option, visible, target ) {
        if ( !target || /[\[\]{}|\r\n#<>]/.test( target ) || target.length > 250 ||
            /[\[\]{}|<>]/.test( visible ) ) {
            throw new Error( 'Invalid link title or display text.' );
        }
        if ( option.kind === 'local' ) {
            return target === visible ? '[[' + target + ']]' : '[[' + target + '|' + visible + ']]';
        }
        if ( option.kind === 'plwiki' ) {
            // Używamy interwiki wyłącznie po odczytaniu mapy lokalnego serwera.
            if ( directPlInterwikiPrefix ) {
                const prefixTitle = ':' + directPlInterwikiPrefix + ':' + target;
                return '[[' + prefixTitle + '|' + visible + ']]';
            }
            // Zawsze poprawny fallback w standardowej składni MediaWiki.
            const linkUrl = 'https://pl.wikipedia.org/wiki/' +
                encodeURIComponent( target.replace( / /g, '_' ) );
            return '[' + linkUrl + ' ' + visible + ']';
        }
        throw new Error( 'Unsupported search source.' );
    }

    function planEdit( source, snapshot, option, target ) {
        if ( snapshot.redlink ) { return planRedlinkEdit( source, snapshot, option, target ); }
        if ( !snapshot.plain ) {
            throw new Error( 'The selection spans multiple HTML elements (e.g. links or references).' +
                'Select plain text within a single paragraph fragment.' );
        }
        const parts = textParts( snapshot.selected );
        const full = snapshot.selected;
        const needlePositions = countMatches( source, full ).filter( ( pos ) =>
            safeSpan( source, pos, pos + full.length ) );
        const before = snapshot.contextBefore;
        const after = snapshot.contextAfter;
        const contextual = needlePositions.filter( ( pos ) =>
            ( !before || source.slice( Math.max( 0, pos - before.length ), pos ) === before ) &&
            ( !after || source.slice( pos + full.length, pos + full.length + after.length ) === after ) );
        // Bez kontekstu zaakceptuj tylko unikalny fragment, który można zweryfikować.
        const matches = contextual.length ? contextual :
            ( needlePositions.length === 1 && !before && !after ? needlePositions : [] );
        if ( matches.length !== 1 ) {
            throw new Error( 'Cannot unambiguously match the selection to the wikitext.' +
                'Try selecting a shorter fragment of plain text or use the source editor.' );
        }
        const start = matches[ 0 ];
        const end = start + full.length;
        const insert = makeLink( option, parts.word, target );
        const replacement = parts.before + insert + parts.after;
        return {
            start, end, old: full, replacement,
            original: source.slice( Math.max( 0, start - 75 ), Math.min( source.length, end + 75 ) ),
            previewBefore: source.slice( Math.max( 0, start - 75 ), start ),
            previewAfter: source.slice( end, Math.min( source.length, end + 75 ) ),
            text: source.slice( 0, start ) + replacement + source.slice( end )
        };
    }

    function dom( tag, className, value ) {
        const element = document.createElement( tag );
        if ( className ) { element.className = className; }
        if ( value !== undefined ) { element.textContent = value; }
        return element;
    }


    // Samodzielny pasek zaznaczenia. Nie dzieli stanu z fact.js.
    function selectionToolbar() {
        if ( toolbarInstance ) {
            return toolbarInstance;
        }
        const style = document.createElement( 'style' );
        style.id = 'wz-fastlink-toolbar-styles';
        style.textContent = `
            #wz-fastlink-toolbar {
                position: fixed;
                z-index: 10040;
                display: none;
                flex-direction: column;
                gap: 6px;
                width: min(232px, calc(100vw - 16px));
                pointer-events: none;
            }
            #wz-fastlink-toolbar > button {
                position: static !important;
                display: none;
                box-sizing: border-box !important;
                width: 100% !important;
                height: 44px !important;
                min-height: 44px;
                max-width: none !important;
                padding: 8px 11px !important;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                gap: 7px;
                margin: 0 !important;
                font: 600 13px/1.35 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
                white-space: nowrap;
                pointer-events: auto;
            }
        `;
        document.head.appendChild( style );
        const host = document.createElement( 'div' );
        host.id = 'wz-fastlink-toolbar';
        host.setAttribute( 'role', 'group' );
        host.setAttribute( 'aria-label', 'Selected text tools' );
        document.body.appendChild( host );
        const api = {
            add( element ) {
                host.appendChild( element );
                element.style.display = 'none';

                api.layout();
            },
            show( element ) {
                element.style.display = 'inline-flex';
                api.layout();
            },
            hide( element ) {
                element.style.display = 'none';
                api.layout();
            },
            hideAll() {
                for ( const child of host.children ) {
                    child.style.display = 'none';
                }
                host.style.display = 'none';
            },
            contains( node ) { return host.contains( node ); },
            layout() {
                const visible = Array.from( host.children ).some( ( child ) =>
                    child.style.display !== 'none'
                );
                if ( !visible ) {
                    host.style.display = 'none';
                    return;
                }
                const selection = window.getSelection();
                if ( !selection || selection.isCollapsed || !selection.rangeCount ) {
                    api.hideAll();
                    return;
                }
                const range = selection.getRangeAt( 0 );
                const rects = range.getClientRects();
                const rect = rects.length ? rects[ rects.length - 1 ] : range.getBoundingClientRect();
                host.style.visibility = 'hidden';
                host.style.display = 'flex';
                const width = host.offsetWidth;
                const height = host.offsetHeight;
                const edgeRight = document.documentElement.clientWidth || window.innerWidth;
                const edgeBottom = window.innerHeight;
                const left = Math.max( 8, Math.min( rect.right + 8, edgeRight - width - 8 ) );
                const below = rect.bottom + 8;
                const above = rect.top - height - 8;
                const top = below + height <= edgeBottom - 8 ? below :
                    above >= 8 ? above : Math.max( 8, Math.min( below, edgeBottom - height - 8 ) );
                host.style.left = left + 'px';
                host.style.top = top + 'px';
                host.style.visibility = 'visible';
            }
        };
        toolbarInstance = api;
        window.addEventListener( 'scroll', api.hideAll, { passive: true } );
        window.addEventListener( 'resize', api.hideAll );
        return api;
    }

    function addStyles() {
        if ( document.getElementById( STYLE_ID ) ) { return; }
        const style = dom( 'style' );
        style.id = STYLE_ID;
        style.textContent = `
            #${BUTTON_ID} { position:fixed;z-index:10040;display:none;border:1px solid #235ca3;
              border-radius:9px;background:#2769ae;color:#fff;padding:9px 13px;font:600 13px/1.4 sans-serif;
              box-shadow:0 6px 22px #0004;cursor:pointer }
            #${BUTTON_ID}:hover { background:#174d88 }
            #${BUTTON_ID}:focus-visible {outline:3px solid #ffcc33;outline-offset:2px}
            #${DIALOG_ID} { box-sizing:border-box;width:min(860px,calc(100vw - 20px));max-height:min(850px,calc(100vh - 24px));
              margin:auto;padding:0;border:1px solid var(--border-color-base,#a2a9b1);border-radius:14px;
              background:var(--background-color-base,#fff);color:var(--color-base,#202122);
              box-shadow:0 24px 86px #0005;font:14px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
              overflow:auto }
            #${DIALOG_ID}::backdrop {background:#0b192b99;backdrop-filter:blur(2px)}
            #${DIALOG_ID} *,#${DIALOG_ID} *::before,#${DIALOG_ID} *::after {box-sizing:border-box}
            #${DIALOG_ID} h2,#${DIALOG_ID} h3 {font-family:inherit; color:inherit;border:0;padding:0}
            #${DIALOG_ID} h2 {font-size:20px;font-weight:700;margin:0}
            #${DIALOG_ID} h3 {font-size:15px;font-weight:700;margin:17px 0 6px}
            #${DIALOG_ID} .fl-header {display:flex;align-items:center;gap:12px;padding:20px 22px 12px;border-bottom:1px solid var(--border-color-subtle,#c8ccd1)}
            #${DIALOG_ID} .fl-icon {height:40px;width:40px;border-radius:12px;display:grid;place-items:center;background:#e4f0fc;color:#18558c;font-weight:800;font-size:20px}
            #${DIALOG_ID} .fl-muted {color:var(--color-subtle,#54595d);font-size:12px}
            #${DIALOG_ID} .fl-body {padding:16px 22px 20px}
            #${DIALOG_ID} .fl-search {display:flex;gap:9px;flex-wrap:wrap;margin-top:12px}
            #${DIALOG_ID} input[type=text] {flex:1 1 240px;min-width:80px;padding:9px 11px;border:1px solid var(--border-color-base,#a2a9b1);border-radius:7px;
              background:var(--background-color-base,#fff);color:inherit;font:inherit}
            #${DIALOG_ID} button {font:inherit;cursor:pointer}
            #${DIALOG_ID} button:disabled {opacity:.58;cursor:default}
            #${DIALOG_ID} .fl-btn {border:1px solid var(--border-color-base,#a2a9b1);border-radius:7px;padding:8px 13px;color:inherit;
              background:var(--background-color-base,#fff);font-weight:600}
            #${DIALOG_ID} .fl-primary {background:#36c;border-color:#36c;color:white}
            #${DIALOG_ID} .fl-primary:hover:not(:disabled) {background:#3056a9}
            #${DIALOG_ID} .fl-secondary {background:var(--background-color-neutral-subtle,#f8f9fa)}
            #${DIALOG_ID} .fl-close {font-size:22px;line-height:1;border:0;background:transparent;color:inherit;margin-left:auto;padding:5px 9px;border-radius:5px}
            #${DIALOG_ID} .fl-close:hover {background:var(--background-color-interactive-subtle,#eaecf0)}
            #${DIALOG_ID} .fl-results {display:grid;grid-template-columns:1fr 1fr;gap:16px}
            #${DIALOG_ID} [hidden] {display:none!important}
            #${DIALOG_ID} .fl-item {display:flex;gap:8px;align-items:start;border:1px solid var(--border-color-subtle,#c8ccd1);border-radius:8px;
              margin:7px 0;padding:11px;background:var(--background-color-base,#fff)}
            #${DIALOG_ID} .fl-item.fl-chosen {border-color:#36c;box-shadow:0 0 0 1px #36c}
            #${DIALOG_ID} .fl-item-main {min-width:0;flex:1}
            #${DIALOG_ID} .fl-item-title {display:block;font-weight:700;overflow-wrap:anywhere}
            #${DIALOG_ID} .fl-item-note {font-size:12px;color:var(--color-subtle,#54595d);overflow-wrap:anywhere;margin:4px 0}
            #${DIALOG_ID} .fl-tag {display:inline-block;background:var(--background-color-neutral-subtle,#eaecf0);color:var(--color-base,#202122);
              border-radius:5px;padding:1px 6px;margin:3px 4px 3px 0;font-size:11px}
            #${DIALOG_ID} .fl-editor {margin-top:15px;padding:12px;border:1px solid var(--border-color-subtle,#c8ccd1);border-radius:9px;
              background:var(--background-color-neutral-subtle,#f8f9fa)}
            #${DIALOG_ID} .fl-code {background:var(--background-color-neutral-subtle,#f8f9fa);white-space:pre-wrap;overflow-wrap:anywhere;
              border:1px solid var(--border-color-subtle,#c8ccd1);border-radius:7px;padding:11px;font:13px/1.55 ui-monospace,Menlo,Consolas,monospace}
            #${DIALOG_ID} .fl-code mark {background:#ccf1dc;color:#164d32;padding:2px;border-radius:3px}
            #${DIALOG_ID} .fl-alert {border-left:3px solid #dc6d16;background:var(--background-color-warning-subtle,#fff8e7);padding:9px 12px;margin:10px 0}
            #${DIALOG_ID} .fl-dock {position:sticky;bottom:0;z-index:2;background:var(--background-color-base,#fff);
              box-shadow:0 -8px 18px #0000001f}
            #${DIALOG_ID} .fl-dock > .fl-editor {margin:12px 22px 0;padding:9px 12px}
            #${DIALOG_ID} .fl-dock .fl-code {margin-bottom:0;max-height:5.5em;overflow:auto}
            #${DIALOG_ID} .fl-series {margin-right:auto;align-self:center;font-size:13px;cursor:pointer;user-select:none}
            .wz-fastlink-added {background:#ccf1dc;border-radius:3px;box-shadow:0 0 0 2px #ccf1dc}
            #${DIALOG_ID} .fl-footer {display:flex;justify-content:flex-end;gap:10px;padding:14px 22px;border-top:1px solid var(--border-color-subtle,#c8ccd1)}
            @media(max-width:700px) {#${DIALOG_ID} .fl-results {grid-template-columns:1fr}#${DIALOG_ID} .fl-body {padding:12px}#${DIALOG_ID} .fl-header {padding:12px}}
        `;
        document.head.appendChild( style );
    }

    function hideButton() { if ( button ) { selectionToolbar().hide( button ); } }

    function selectionChanged() {
        if ( document.getElementById( DIALOG_ID ) ) { return; }
        const snapshot = snapshotSelection();
        if ( !snapshot ) { hideButton(); lastSnapshot = null; return; }
        lastSnapshot = snapshot;
        selectionToolbar().show( button );
    }

    function findPlWikipediaPrefix() {
        // Sprawdzamy tylko rzeczywiście zadeklarowane w WikiZagłębiu interwiki.
        // Jeżeli brakuje bezpośredniego prefiksu do pl.wikipedia.org, link zewnętrzny.
        return Promise.resolve().then( () => localApi.get( {
            action: 'query', meta: 'siteinfo', siprop: 'interwikimap', formatversion: 2
        } ) ).then( ( response ) => {
            const map = response.query && response.query.interwikimap || [];
            const matching = map.find( ( entry ) => {
                if ( !entry || !/^[a-z][a-z0-9_-]*$/i.test( entry.prefix || '' ) ||
                    !entry.url || !entry.url.includes( '$1' ) ) { return false; }
                try {
                    const url = new URL( entry.url.replace( '$1', 'TEST' ) );
                    return url.protocol === 'https:' && url.hostname === 'pl.wikipedia.org' &&
                        ( url.pathname.includes( '/wiki/' ) || url.pathname.includes( '/w/index.php' ) );
                } catch ( e ) { return false; }
            } );
            directPlInterwikiPrefix = matching ? matching.prefix : null;
        } ).catch( () => {
            directPlInterwikiPrefix = null;
        } );
    }

    function searchAll( term ) {
        const specs = [
            { kind: 'local', api: localApi, label: 'WikiZagłębie', mode: 'title', limit: 12 },
            { kind: 'local', api: localApi, label: 'WikiZagłębie', mode: 'text', limit: 8 },
            { kind: 'plwiki', api: wikipediaApi, label: 'Wikipedia PL', mode: 'title', limit: 12 },
            { kind: 'plwiki', api: wikipediaApi, label: 'Wikipedia PL', mode: 'text', limit: 8 }
        ];
        const requests = specs.map( ( spec ) => spec.api.get( {
            action: 'query', list: 'search', srsearch: term, srnamespace: 0,
            srwhat: spec.mode, srlimit: spec.limit, srprop: 'redirecttitle',
            formatversion: 2
        } ).then( ( data ) => {
            return ( data.query && data.query.search || [] ).map( ( hit ) => ( {
                kind: spec.kind, title: hit.title, redirected: hit.redirecttitle || '',
                mode: spec.mode
            } ) );
        } ) );
        return Promise.allSettled( requests ).then( ( settled ) => {
        if ( settled.every( ( entry ) => entry.status === 'rejected' ) ) {
            throw new Error( 'Unable to connect to any API search service.' );
        }
        const errors = [];
        const sources = { local: new Map(), plwiki: new Map() };
        settled.forEach( ( entry, index ) => {
            const spec = specs[ index ];
            if ( entry.status !== 'fulfilled' ) {
                if ( !errors.includes( spec.label ) ) { errors.push( spec.label ); }
                return;
            }
            for ( const item of entry.value ) {
                if ( !item.title || item.title.length > 250 ) { continue; }
                const key = item.title.replace( /_/g, ' ' ).toLocaleLowerCase( 'pl-PL' );
                if ( !sources[ spec.kind ].has( key ) ) {
                    sources[ spec.kind ].set( key, item );
                }
            }
        } );
        return {
            local: Array.from( sources.local.values() ),
            plwiki: Array.from( sources.plwiki.values() ), errors
        };
        } );
    }

    function readPage() {
        const title = mw.config.get( 'wgPageName' ).replace( /_/g, ' ' );
        return Promise.resolve( localApi.get( {
            action: 'query', prop: 'revisions', titles: title, rvslots: 'main',
            rvprop: 'ids|timestamp|content', formatversion: 2, curtimestamp: 1
        } ) ).then( ( data ) => {
        const page = data.query && data.query.pages && data.query.pages[ 0 ];
        const rev = page && page.revisions && page.revisions[ 0 ];
        const content = rev && rev.slots && rev.slots.main && rev.slots.main.content;
        if ( typeof content !== 'string' || !rev.revid ) {
            throw new Error( 'Unable to retrieve the source of the current page revision.' );
        }
        if ( rev.revid !== lastSnapshot.viewedRevision ) {
            throw new Error( 'The article has changed since this page was displayed. Refresh and try again.' );
        }
        return { title, source: content, rev: rev.revid, timestamp: rev.timestamp,
            currentTime: data.curtimestamp };
        } );
    }

    function wikiUrl( title, kind ) {
        if ( kind === 'plwiki' ) {
            return 'https://pl.wikipedia.org/wiki/' + encodeURIComponent( title.replace( / /g, '_' ) );
        }
        return mw.util.getUrl( title );
    }

    // Tryb serii: zapisany link pokazany od razu na stronie, bez przeładowania
    function applyToPage( snapshot, option, target ) {
        const href = wikiUrl( target, option.kind );
        let link;
        if ( snapshot.redlink && snapshot.anchor && snapshot.anchor.isConnected ) {
            link = snapshot.anchor;
            link.classList.remove( 'new' );
        } else if ( snapshot.range ) {
            const parts = textParts( snapshot.selected );
            link = document.createElement( 'a' );
            link.textContent = parts.word;
            const fragment = document.createDocumentFragment();
            if ( parts.before ) { fragment.append( document.createTextNode( parts.before ) ); }
            fragment.append( link );
            if ( parts.after ) { fragment.append( document.createTextNode( parts.after ) ); }
            snapshot.range.deleteContents();
            snapshot.range.insertNode( fragment );
        } else {
            return false;
        }
        link.href = href;
        link.title = target;
        if ( option.kind === 'plwiki' ) { link.classList.add( 'extiw' ); }
        link.classList.add( 'wz-fastlink-added' );
        return true;
    }

    function showDialog( snapshot ) {
        addStyles();
        selectionToolbar().hideAll();
        let chosen = null;
        let debounceTimer = null;
        const dlg = dom( 'dialog', 'wz-fastlink-ui' );
        dlg.id = DIALOG_ID;
        dlg.setAttribute( 'aria-label', 'FastLink — find a link' );
        const header = dom( 'div', 'fl-header' );
        header.append( dom( 'div', 'fl-icon', '🔗' ) );
        const headline = dom( 'div' );
        headline.append( dom( 'h2', '', 'FastLink — WikiZagłębie / Wikipedia PL' ) );
        headline.append( dom( 'div', 'fl-muted', 'Zaznaczenie: „' + normalize( snapshot.selected ) + '”' ) );
        header.append( headline );
        const close = dom( 'button', 'fl-close', '×' );
        close.type = 'button'; close.title = 'Zamknij'; close.setAttribute( 'aria-label', 'Zamknij' );
        header.append( close );
        const body = dom( 'div', 'fl-body' );
        const instructions = dom( 'div', 'fl-muted',
            'Check local articles first. Wikipedia results link to Wikipedia, not to nonexistent WikiZagłębie pages.' );
        const form = dom( 'form', 'fl-search' );
        const query = dom( 'input' ); query.type = 'text'; query.maxLength = 160;
        query.setAttribute( 'aria-label', 'Name to search' );
        query.value = textParts( snapshot.selected ).word;
        const submit = dom( 'button', 'fl-btn fl-primary', 'Szukaj' );
        submit.type = 'submit';
        form.append( query, submit );
        const status = dom( 'p', 'fl-muted', '' ); status.setAttribute( 'role', 'status' );
        const lists = dom( 'div', 'fl-results' );
        const selectedBox = dom( 'div', 'fl-editor' ); selectedBox.hidden = true;
        const selectedCaption = dom( 'div', '', '' );
        const sample = dom( 'pre', 'fl-code' ); sample.style.marginTop = '8px';
        selectedBox.append( selectedCaption, sample );
        const footer = dom( 'div', 'fl-footer' );
        const cancel = dom( 'button', 'fl-btn fl-secondary', 'Anuluj' );
        cancel.type = 'button';
        const proceed = dom( 'button', 'fl-btn fl-primary', 'Go to preview' );
        proceed.type = 'button'; proceed.disabled = true;
        const seriesLabel = dom( 'label', 'fl-series' );
        const series = dom( 'input' ); series.type = 'checkbox'; series.checked = seriesEnabled();
        series.addEventListener( 'change', () => setSeries( series.checked ) );
        seriesLabel.append( series, document.createTextNode( 'Batch mode (without reloading the page)' ) );
        seriesLabel.title = 'After saving, the link appears immediately on the page, and you can select the next fragment.';
        footer.append( seriesLabel, cancel, proceed );
        // Wybrany link i przyciski przyklejone do dołu okna – widoczne przy przewijaniu długich wyników
        const dock = dom( 'div', 'fl-dock' );
        dock.append( selectedBox, footer );
        body.append( instructions, form, status, lists );
        dlg.append( header, body, dock );
        document.body.appendChild( dlg );

        const destroy = () => {
            searchSerial++;
            if ( debounceTimer ) { clearTimeout( debounceTimer ); }
            if ( dlg.open ) { dlg.close(); }
            dlg.remove();
        };
        close.addEventListener( 'click', destroy );
        cancel.addEventListener( 'click', destroy );
        dlg.addEventListener( 'close', () => {
            searchSerial++;
            if ( debounceTimer ) { clearTimeout( debounceTimer ); }
            dlg.remove();
        } );
        dlg.addEventListener( 'click', ( e ) => { if ( e.target === dlg ) { destroy(); } } );

        function refreshSelected() {
            if ( !chosen ) { selectedBox.hidden = true; proceed.disabled = true; return; }
            selectedBox.hidden = false;
            selectedCaption.textContent = chosen.kind === 'local' ?
                'Internal WikiZagłębie link:' : 'Link to Polish Wikipedia:';
            try {
                sample.textContent = makeLink( chosen, textParts( snapshot.selected ).word, chosen.title );
                proceed.disabled = false;
            } catch ( e ) { sample.textContent = e.message; proceed.disabled = true; }
        }

        function createResult( item, dest ) {
            const tile = dom( 'div', 'fl-item' );
            const main = dom( 'div', 'fl-item-main' );
            const top = dom( 'a', 'fl-item-title', item.title );
            top.href = wikiUrl( item.title, item.kind );
            top.target = '_blank'; top.rel = 'noopener noreferrer';
            main.append( top );
            main.append( dom( 'div', 'fl-item-note', item.redirected ?
                'Przekierowanie: ' + item.redirected :
                ( item.mode === 'title' ? 'Title match' : 'Content match' ) ) );
            main.append( dom( 'span', 'fl-tag', item.kind === 'local' ? 'WikiZagłębie' : 'Wikipedia PL' ) );
            const pick = dom( 'button', 'fl-btn fl-secondary', 'Wybierz' ); pick.type = 'button';
            pick.addEventListener( 'click', () => {
                chosen = item;
                dlg.querySelectorAll( '.fl-chosen' ).forEach( ( n ) => n.classList.remove( 'fl-chosen' ) );
                tile.classList.add( 'fl-chosen' );
                refreshSelected();
            } );
            tile.append( main, pick ); dest.append( tile );
        }

        function doSearch() {
            const value = normalize( query.value );
            const ticket = ++searchSerial;
            chosen = null;
            refreshSelected();
            lists.replaceChildren();
            if ( !value ) { status.textContent = 'Enter a name to search for.'; submit.disabled = false; return; }
            status.textContent = 'Searching WikiZagłębie and Polish Wikipedia…';
            submit.disabled = true;
            return Promise.resolve().then( () => searchAll( value ) ).then( ( data ) => {
                if ( ticket !== searchSerial || !dlg.isConnected ) { return; }
                const left = dom( 'section' );
                const right = dom( 'section' );
                left.append( dom( 'h3', '', 'WikiZagłębie (' + data.local.length + ')' ) );
                right.append( dom( 'h3', '', 'Wikipedia PL (' + data.plwiki.length + ')' ) );
                data.local.forEach( ( item ) => createResult( item, left ) );
                data.plwiki.forEach( ( item ) => createResult( item, right ) );
                if ( !data.local.length ) { left.append( dom( 'div', 'fl-muted', 'Not found.' ) ); }
                if ( !data.plwiki.length ) { right.append( dom( 'div', 'fl-muted', 'Not found.' ) ); }
                lists.append( left, right );
                status.textContent = 'Results for “' + value + '”. Select the correct article.' +
                    ( data.errors.length ? 'Some results unavailable:' + data.errors.join( ', ' ) + '.' : '' );
            } ).catch( ( error ) => {
                if ( ticket === searchSerial ) { status.textContent = 'Search error:' + error.message; }
            } ).then( () => { if ( ticket === searchSerial ) { submit.disabled = false; } } );
        }
        form.addEventListener( 'submit', ( e ) => {
            e.preventDefault();
            if ( debounceTimer ) { clearTimeout( debounceTimer ); }
            void doSearch();
        } );
        query.addEventListener( 'input', () => {
            // Unieważnia stare żądanie natychmiast, a nie po 400 ms.
            searchSerial++;
            if ( debounceTimer ) { clearTimeout( debounceTimer ); }
            chosen = null;
            submit.disabled = false;
            refreshSelected();
            debounceTimer = setTimeout( () => { void doSearch(); }, SEARCH_DEBOUNCE_MS );
        } );

        proceed.addEventListener( 'click', () => {
            if ( !chosen ) { return; }
            const target = chosen;
            proceed.disabled = true;
            status.textContent = 'Retrieving wikitext and checking the selection position…';
            let page, planned;
            Promise.resolve().then( () => readPage() ).then( ( loaded ) => {
                page = loaded;
                planned = planEdit( page.source, snapshot, target, target.title );
                return confirmPlan( dlg, planned );
            } ).then( ( accepted ) => {
                if ( !accepted ) { status.textContent = 'Cancelled — no changes saved.'; return; }
                status.textContent = 'Zapisywanie zmiany…';
                return Promise.resolve( localApi.postWithEditToken( {
                    action: 'edit', title: page.title, text: planned.text,
                    summary: SUMMARY, nocreate: true,
                    baserevid: page.rev, basetimestamp: page.timestamp,
                    starttimestamp: page.currentTime, assert: 'user', format: 'json'
                } ) ).then( ( result ) => {
                    if ( !result || !result.edit || result.edit.result !== 'Success' ) {
                        throw new Error( 'The API did not confirm that the change was saved.' );
                    }
                    if ( !series.checked ) {
                        mw.notify( 'FastLink: link zapisany.', { type: 'success' } );
                        destroy();
                        window.location.reload();
                        return;
                    }
                    if ( result.edit.newrevid ) { currentRevision = Number( result.edit.newrevid ); }
                    seriesCount++;
                    let shown = false;
                    try { shown = applyToPage( snapshot, target, target.title ); } catch ( e ) { shown = false; }
                    mw.notify( 'FastLink: link zapisany (seria: ' + seriesCount + ').' +
                        ( shown ? '' : ' Odśwież stronę, aby go zobaczyć.' ), { type: 'success' } );
                    destroy();
                    window.getSelection().removeAllRanges();
                    lastSnapshot = null;
                } );
            } ).catch( ( e ) => {
                status.textContent = 'Change not saved:' + ( e && e.message || 'Unknown API error.' );
                const alert = dom( 'div', 'fl-alert', status.textContent );
                const old = body.querySelector( '.fl-alert' );
                if ( old ) { old.remove(); }
                body.insertBefore( alert, lists );
            } ).then( () => { if ( dlg.isConnected ) { proceed.disabled = !chosen; } } );
        } );
        dlg.showModal();
        void doSearch();
    }

    function confirmPlan( parent, plan ) {
        return new Promise( ( resolve ) => {
            const area = dom( 'div', 'fl-editor' );
            area.append( dom( 'h3', '', 'Podgląd zmiany — nic nie zostanie zapisane bez potwierdzenia' ) );
            area.append( dom( 'div', 'fl-muted', 'Before the change:' ) );
            area.append( dom( 'pre', 'fl-code', plan.original ) );
            area.append( dom( 'div', 'fl-muted', 'After the change:' ) );
            const after = dom( 'pre', 'fl-code' );
            after.append( document.createTextNode( plan.previewBefore ) );
            const mark = dom( 'mark', '', plan.replacement );
            after.append( mark, document.createTextNode( plan.previewAfter ) );
            area.append( after );
            // Przyciski podglądu przyklejone do dołu okna, jak w widoku wyników
            const buttons = dom( 'div', 'fl-dock' );
            const buttonRow = dom( 'div', 'fl-footer' );
            const no = dom( 'button', 'fl-btn fl-secondary', 'Back to results' );
            const yes = dom( 'button', 'fl-btn fl-primary', 'Save change' );
            no.type = yes.type = 'button';
            buttonRow.append( no, yes ); buttons.append( buttonRow );
            const results = parent.querySelector( '.fl-results' );
            if ( results ) { results.hidden = true; }
            const selection = parent.querySelector( '.fl-dock' );
            if ( selection ) { selection.hidden = true; }
            const footer = parent.querySelector( '.fl-footer' );
            if ( footer ) { footer.hidden = true; }
            parent.querySelector( '.fl-body' ).append( area );
            parent.append( buttons );
            const onClosed = () => cleanup( false );
            parent.addEventListener( 'close', onClosed, { once: true } );
            const cleanup = ( confirmed ) => {
                parent.removeEventListener( 'close', onClosed );
                area.remove();
                buttons.remove();
                if ( results ) { results.hidden = false; }
                if ( selection ) { selection.hidden = false; }
                if ( footer ) { footer.hidden = false; }
                resolve( confirmed );
            };
            no.addEventListener( 'click', () => cleanup( false ) );
            yes.addEventListener( 'click', () => cleanup( true ) );
        } );
    }

    function boot() {
        localApi = new mw.Api();
        wikipediaApi = new mw.ForeignApi( 'https://pl.wikipedia.org/w/api.php', { anonymous: true } );
        void findPlWikipediaPrefix();
        addStyles();
        button = dom( 'button', '', '🔗 Znajdź link' );
        button.id = BUTTON_ID;
        button.type = 'button';
        button.setAttribute( 'aria-label', 'FastLink — find a link for selected text' );
        button.addEventListener( 'mousedown', ( e ) => e.preventDefault() );
        button.addEventListener( 'click', () => {
            if ( lastSnapshot ) { showDialog( lastSnapshot ); }
        } );
        const toolbar = selectionToolbar();
        toolbar.add( button );
        document.addEventListener( 'mouseup', ( e ) => {
            if ( toolbar.contains( e.target ) ||
                ( e.target.closest && e.target.closest( '.wz-fastlink-ui' ) ) ) { return; }
            selectionChanged();
        } );
        document.addEventListener( 'keyup', ( e ) => {
            if ( /^(Shift|ArrowLeft|ArrowRight|ArrowUp|ArrowDown|Home|End)$/.test( e.key ) ) {
                selectionChanged();
            }
        } );
        mw.log( 'FastLink WikiZagłębie ' + VERSION + '— loaded.' );
    }

    // Eksport pomocniczy tylko do testów Node.js.
    if ( typeof module !== 'undefined' && module.exports ) {
        module.exports = { textParts, isPlainPosition, makeLink, planEdit, redlinkOccurrences, searchAll, findPlWikipediaPrefix, setLocalApi: (api) => { localApi = api; }, setWikipediaApi: (api) => { wikipediaApi = api; }, setInterwikiPrefix: (p) => { directPlInterwikiPrefix = p; } };
    }

    // Testy czystej logiki mogą uruchamiać moduł poza MediaWiki.
    if ( typeof mw === 'undefined' ) { return; }
    if ( !permitted() ) { return; }
    mw.loader.using( [ 'mediawiki.api', 'mediawiki.ForeignApi', 'mediawiki.util' ] ).then( boot ).catch( ( error ) => {
        mw.log.error( 'Unable to load FastLink WikiZagłębie', error );
    } );

}() );