Jump to content

User:Polygnotus/Scripts/DetectPromo-v2.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Polygnotus (talk | contribs) at 07:13, 18 September 2024. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//Forked from [[User:Novem Linguae/Scripts/DetectPromo.js]]

// <nowiki>

/*
- Let reviewer know when certain promotional and POV keywords are detected.
- Displays an orange bar at the top of the article, listing the detected keywords.
- Highlights detected promotional words with a yellow background and red border within the article text.
*/

class DetectPromo {
    /** @type {string[]} */
    wordsToSearch = [
        '% growth', '100%', '6-figure', '7-figure', '8-figure', '9-figure',
        'B2B', 'B2C', 'a record', 'acclaimed', 'accomplished',
        'are a necessity', 'around the world', 'award winning', 'award-winning',
        'beloved', 'best available', 'bestselling', 'boasts', 'comprehensive',
        'countless hours', 'create a revolution', 'critical acclaim',
        'disrupt', 'drastically', 'dynamic', 'elevate', 'eminent', 'engaging',
        'entrepreneur', 'evangelist', 'excelled', 'exceptional', 'exemplified',
        'exemplify', 'expert', 'expertise', 'extensive', 'famous', 'fascinating',
        'fast growing', 'fast-growing', 'fastest growing', 'fastest-growing',
        'finest', 'fully integrated', 'fully-integrated', 'globally',
        'globally recognized', 'growing popularity', 'highlights',
        'highly accomplished', 'highly praised', 'highly specialized',
        'historic', 'honored with', 'hypnotic', 'illustrious', 'impressive',
        'indelible', 'inexhaustible', 'influential', 'innovation', 'innovative',
        'insights', 'inspired by', 'integrate', 'invaluable', 'leader in',
        'leading', 'legendary', 'leverag', 'massive', 'mastermind', 'more than',
        'most highly', 'most important', 'most impressive', 'most notable',
        'mystical', 'natural charm', 'noteworthy', 'numerous', 'organically',
        'outstanding', 'perfect', 'philanthropist', 'picturesque', 'pioneer',
        'pioneering', 'popular destination', 'popularity', 'premiere',
        'prestigious', 'prominence', 'prominent', 'promising', 'promulgator',
        'ranked', 'reinvent', 'remarkable', 'renowed', 'renowned', 'resonating',
        'respected', 'revolutionary', 'rising star', 'save millions', 'savvy',
        'seamless', 'sensual', 'several offers', 'showcased', 'signature',
        'significant', 'soulful', 'spanning', 'state of art', 'state of the art',
        'state-of-art', 'state-of-the-art', 'striking', 'super famous',
        'tailored', 'tranquility', 'transcend', 'transform', 'underpin',
        'ventured into', 'very first', 'visionary', 'wide selection',
        'widely used', 'world class', 'world-class', 'worldwide', 'zero to hero'
    ];

    /**
     * @param {Object} mw
     * @param {jQuery} $
     */
    constructor(mw, $) {
        this.mw = mw;
        this.$ = $;
    }

    async execute() {
        if (!this.shouldRunOnThisPage()) {
            return;
        }

        const title = this.mw.config.get('wgPageName');
        const wikicode = await this.getWikicode(title);
        if (!wikicode) return;

        const cleanedWikicode = this.cleanWikicode(wikicode);
        const searchResults = this.getSearchResults(cleanedWikicode);
        
        if (searchResults.length > 0) {
            this.displayResults(searchResults);
            this.highlightPromoWords(searchResults);
        }
    }

    /**
     * @param {string[]} searchResults
     */
    displayResults(searchResults) {
        const MAX_DISPLAYED_RESULTS = 20;
        const displayedResults = searchResults.slice(0, MAX_DISPLAYED_RESULTS);
        if (searchResults.length > MAX_DISPLAYED_RESULTS) {
            displayedResults.push('...... and more.');
        }

        const resultsString = displayedResults.join(', ');
        const html = `
            <div id="DetectPromo" style="background-color: orange; padding: 10px; margin-bottom: 10px;">
                <span style="font-weight: bold;">Promotional words detected:</span> ${resultsString}
            </div>
        `;
        this.$('#contentSub').after(html);
    }

    /**
     * Highlight promotional words with yellow background and red border within the article text
     * @param {string[]} searchResults
     */
    highlightPromoWords(searchResults) {
        const content = this.$('#mw-content-text');
        const highlightStyle = 'background-color: yellow; border: 1px solid red; padding: 2px; margin: -2px;';
        
        searchResults.forEach(word => {
            const regex = new RegExp(`\\b${this.escapeRegEx(word)}\\b`, 'gi');
            content.find('*').contents().filter(function() {
                return this.nodeType === Node.TEXT_NODE;
            }).each((_, textNode) => {
                const text = textNode.textContent;
                if (regex.test(text)) {
                    const newHtml = text.replace(regex, `<span style="${highlightStyle}">$&</span>`);
                    const newElement = document.createElement('span');
                    newElement.innerHTML = newHtml;
                    textNode.parentNode.replaceChild(newElement, textNode);
                }
            });
        });
    }

    /**
     * @param {string} wikicode
     * @return {string[]} searchResults
     */
    getSearchResults(wikicode) {
        return this.wordsToSearch.filter(word => {
            const regEx = new RegExp(`(?<!\\w)${this.escapeRegEx(word)}(?!\\w)`, 'i');
            return regEx.test(wikicode);
        });
    }

    /**
     * @param {string} wikicode
     * @return {string} cleanedWikicode
     */
    cleanWikicode(wikicode) {
        return wikicode
            .replace(/\[\[|\]\]/g, '') // Remove [[ ]]
            .replace(/<ref[^<]*<\/ref>|<ref[^>]*\/>/gm, ''); // Remove <ref></ref> and <ref />
    }

    /**
     * @return {boolean}
     */
    shouldRunOnThisPage() {
        const action = this.mw.config.get('wgAction');
        const isDiff = this.mw.config.get('wgDiffNewId');
        const isDeletedPage = !this.mw.config.get('wgCurRevisionId');
        const namespace = this.mw.config.get('wgNamespaceNumber');
        const title = this.mw.config.get('wgPageName');

        return (
            action === 'view' &&
            !isDiff &&
            !isDeletedPage &&
            ([0, 118].includes(namespace) || title === 'User:Novem_Linguae/sandbox')
        );
    }

    /**
     * @param {string} title
     * @return {Promise<string|null>} wikicode
     */
    async getWikicode(title) {
        try {
            const api = new this.mw.Api();
            const response = await api.get({
                action: 'parse',
                page: title,
                prop: 'wikitext',
                formatversion: '2',
                format: 'json'
            });
            return response.parse.wikitext;
        } catch (error) {
            console.error('Error fetching wikicode:', error);
            return null;
        }
    }

    /**
     * @param {string} string
     * @return {string} escapedString
     */
    escapeRegEx(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
}

$(() => {
    mw.loader.using(['mediawiki.api']).then(() => {
        new DetectPromo(mw, $).execute();
    });
});

// </nowiki>