/*

*/

// ==UserScript==
// @name        loFaP_0707
// @namespace   Violentmonkey Scripts
// @match       *://*/*
// @grant       none
// @version     0.7.1
// @author      -
// @description 2025/7/7 00:00:00
// ==/UserScript==

(() => {
    'use strict';

const uniqueLauncher = () => {
    const triggerExist = document.querySelector('div#triggerField');
    triggerExist === null ? preprocessPrecast() :
    console.log('already entity');
}

const appendRefer = ( urlFile ) => {
    const fileExtension = urlFile.match(/\.[^/.]+$/);
    const referElem = createByExtens(urlFile, fileExtension[0]);
    const fileName = urlFile.match(/[^\/=\b]+(?=\.[^\/.]*$)/)[0];
    referElem.id = fileName.replace(/\./g,'_')
    + fileExtension[0].replace(/\./g,'_');
    return referElem;
}

const createByExtens = ( urlFile, fileExtens ) => {
    switch (fileExtens) {
        case '.css':
            const linkRefer = document.createElement('link');
            linkRefer.href = urlFile;
            linkRefer.setAttribute('rel', 'stylesheet');
            return linkRefer;
        case '.js':
        case '.md':
            const scriptRefer = document.createElement('script');
            scriptRefer.src = urlFile;
            return scriptRefer;
        default:
            console.log(fileExtens);
            break;
    }
}

const rO_imagesLoaded = {
    exist: typeof imagesLoaded,
    schedule: "function",
    referS: [
        "https://unpkg.com/imagesloaded@5/imagesloaded.pkgd.min.js",
    ],
    method: ( elem ) => {
        ilProgress ( elem );
    },
};

const createWindow = ( elem, param ) => {
    const oWin = new Object();
    oWin.callback = (panel) => {
        panel.content.appendChild( elem );
    };
    oWin.opacity = .9;
    oWin.theme = "primary";
    
    switch ( param ) {
        case undefined:
            oWin.contentSize = "400 250";
            oWin.position = "right-top -10 125";
            break;
        case "dashBoard":
            oWin.contentSize = "450 250";
            oWin.headerTitle = param;
            oWin.id = param;
            oWin.position = "right-bottom -10 -10";
            break;
    }

    jsPanel.create( oWin );
}

const rO_jspanel = {
    exist: typeof jsPanel,
    schedule: "object",
    referS: [
        "https://jspanel.de/jspanel/dist/jspanel.min.css",
        "https://jspanel.de/jspanel/dist/jspanel.min.js",
    ],
    method: ( elem, param ) => {
        createWindow ( elem, param );
    },
};

const rO_retrieveMsn = {
    exist: typeof retrieveMsn,
    schedule: "function",
    referS: [
        "https://66e.github.io/j/msn_JS.md",
    ],
    method: ( elem ) => {
        const arrMsn = retrieveMsn ();
        generateUnit ( arrMsn );
    },
};

const rO = new Object();
rO.fancybox = new Object();
rO.fancybox.exist = typeof Fancybox;
rO.fancybox.schedule = "function";
rO.fancybox.referS = [
    "https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.36/fancybox/fancybox.min.css",
    "https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.36/fancybox/fancybox.umd.min.js",
];
rO.fancybox.method = () => console.log(typeof Fancybox);

const secuReFerShell = ({ referObj, targetElem, param }) => {
    if ( referObj.exist === referObj.schedule ) {
        referObj.method( targetElem, param );
    } else {
        const urlS = referObj.referS;
        const exeCuTable = /(_JS\.md|\.js)$/i;
        urlS.forEach(( url ) => {
            const tag = appendRefer ( url );
            if ( exeCuTable.test(url) ) {
                tag.addEventListener("load", () => {
                    referObj.method( targetElem, param );
                });
            }
            document.body.appendChild(tag);
        });
    }
}

const generateUnit = ( arrIn ) => {
    const trgtContainer = document.querySelector("div#containErNT");
    const unit = processElem ( arrIn );
    secuReFerShell ({
        referObj: rO_imagesLoaded, 
        targetElem: unit,
    });
    if (trgtContainer) {
        trgtContainer.appendChild( unit );
    } else {
        geNEWin(unit);
    }
}

const geNEWin = ( elem ) => {
    const div = document.createElement("div");
    div.id = "containErNT";
    div.appendChild( elem );
    secuReFerShell ({
        referObj : rO_jspanel,
        targetElem : div,
    });
    secuReFerShell ({
        referObj: rO_imagesLoaded, 
        targetElem: elem,
    });
    secuReFerShell ({
        referObj : rO.fancybox,
    });
}

const genGFormT = ( txt ) => {
    const urlSArr = extractUrls ( txt );
    generateUnit ( urlSArr );
}

const resolveTxt = ( txtIn ) => {
    const paras = arrSpliter( txtIn, ">        " );
    const objS = [];
    const div = document.createElement("div");
    paras.forEach(( elem ) => {
        const lines = arrSpliter( elem, "\n" );
        const innerObj = [];
        const innerDiv = document.createElement("div");
        lines.forEach(( el ) => {
            const identify = parseURL( el );
            const iter = filterString( el );
            innerObj.push( identify );
            innerDiv.appendChild( iter );
        });
        objS.push( innerObj );
        div.appendChild( innerDiv );
    });
    return [ div, objS ];
}

const fetchCors = async (url, targetElm) => {
    const respons = await fetch(url);
    const docData = await respons.text();
    targetElm.value = docData;
    const hybirdUnit = resolveTxt ( docData );
    geNEWin( hybirdUnit[0] );
}

const extractUrls = ( input ) => {
    // Search the input text for URLs (the regular expression pattern is taken from the excellent
    // "Regular Expressions Cookbook" by Jan Goyvaerts and Steven Levithan)
    const match = input.match(/\b((https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/ig);

    // Output the found URLs
    return match ? match : "No URLs found";
}

const arrSpliter = ( txtIn, SpliTeR ) => {
    const arrOut = txtIn.trim().split(SpliTeR);
    return arrOut;
}

const filterString = (strIn) => {
    const currentStr = parseURL(strIn);
    switch (currentStr) {
        case "a":
            const aTag = document.createElement("a");
            aTag.textContent = strIn;
            return aTag;
            break;
        case "img":
            const liImg = createIlLi( strIn );
            return liImg;
        case "p":
            const pTag = document.createElement("p");
            pTag.textContent = strIn;
            return pTag;
            break;
        case "pRompt6Exe":
            const div = document.createElement("div");
            div.textContent = strIn;
            return div;
            break;
        default:
        console.log("default");
    }
}

const parseURL = ($string, param) => {
    const __urlR = "((https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]";
    const __imgR = "\.(?:img|jpe?g|gif|png)";
    const urlRegex = new RegExp(__urlR, "i");
    const imgRegex = new RegExp(__imgR, "i");
    const imgWURegex = new RegExp(__urlR + __imgR, "i");
    const pRompt6Exe = /^\#6\/p\/\w+$/i;
    const strIsUrl = urlRegex.test($string);
    if ( strIsUrl ) {
        switch ( true ) {
            case imgRegex.test($string):
                if ( param ) {
                    const trimmed = $string.match(imgWURegex)[0];
                    return trimmed;
                }
                return "img";
                break;
            
            default:
                return "a";
        }
    } else if (pRompt6Exe.test($string)) {
        return "pRompt6Exe";
    } else {
        return "p";
    }
}

const visualizeComponentS = () => {
    const input = document.createElement("input");
        input.addEventListener("dblclick", () => {
            input.value = '';
        });
        input.addEventListener("paste", (e) => {
            setTimeout(() => {
                fetchCors( e.target.value, textarea );
            }, 1);
        });
        input.id = "input";
        input.size = 40;
        const docUrl = "https://66e.github.io/9/2025-06-08-y.md";
        input.value = docUrl;
        const btnRtrv = document.createElement("button");
        btnRtrv.addEventListener("click", () => {
            fetchCors( input.value, textarea );
        });
        btnRtrv.id = "btnRtrv";
        btnRtrv.textContent = "retrieve";
        const checkbox = document.createElement("input");
        checkbox.textContent = "checkbox";
        checkbox.id = "checkbox";
        checkbox.type = "checkbox";
        const textarea = document.createElement("textarea");
        textarea.addEventListener("dblclick", () => {
            textarea.value = "";
        });
        textarea.addEventListener("paste", () => {
            setTimeout(() => {
                genGFormT ( textarea.value );
            }, 1);
        });
        textarea.cols = "50";
        textarea.rows = "10";
        textarea.id = "textarea";
        textarea.style.overflow = "auto";
        const btnRslv = document.createElement("button");
        btnRslv.textContent = "resolve";
        btnRslv.id = "btnRslv";
        btnRslv.addEventListener("click", () => {
            genGFormT ( textarea.value );
        });
        const btnMsn = document.createElement("button");
        btnMsn.addEventListener("click", () => {
            secuReFerShell ({
                referObj : rO_retrieveMsn,
            });
        });
        btnMsn.textContent = "Msn";
        btnMsn.id = "btnMsn";
        
        const div = document.createElement("div");
        div.id = "dashboard";
        div.appendChild(input);
        div.appendChild(btnRtrv);
        div.appendChild(checkbox);
        div.appendChild(textarea);
        div.appendChild(btnRslv);
        div.appendChild(btnMsn);
        return div;
}

const createIlLi = ( url ) => {
    const urlTrimmed = parseURL ( url, "trim" );
    const li = document.createElement("li");
    li.style.backgroundColor = "#000";
    li.style.backgroundImage = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/loading.gif')";
    li.style.backgroundPosition = "center center";
    li.style.backgroundRepeat = "no-repeat";
    li.style.borderRadius = "4px";
    li.style.display = "block";
    li.style.float = "left";
    li.style.height = "70px";
    li.style.margin = "2px 2px 2px 2px";

    const img = new Image();
    img.src = urlTrimmed;
    img.style.borderRadius = "4px";
    img.style.opacity = 0;
    img.style.maxHeight = "70px";
    img.style.minWidth = "25px";
    img.style.transition = "opacity 0.4s";
    img.addEventListener("click", (e) => {
        const trgtContainer = document.querySelector("div#containErNT");
        const arrImgS = trgtContainer.querySelectorAll("div > div > div > div > li > img");
        const arrForFB = new Array();
        arrImgS.forEach((elemImg) => {
            arrForFB.push({ src: elemImg.src });
        });
        const clickTarget = e.currentTarget;
        const galIdx = [].indexOf.call( arrImgS, clickTarget );
        new Fancybox(
            arrForFB,
            {
                startIndex: galIdx,
            }
        );
    });

    li.appendChild(img);
    return li;
}

const ilProgress = ( elem ) => {
    const imgLoad = imagesLoaded( elem );
imgLoad.on( 'always', ( instance ) => {
  console.log( imgLoad.images.length + ' in total' );
});
imgLoad.on( 'done', ( instance ) => {
  console.log('DONE  - all success');
});
imgLoad.on( 'fail', ( instance ) => {
  console.log('FAIL - loaded, one mORe broken');
});
imgLoad.on( 'progress', ( instance, image ) => {
    if ( image.isLoaded ) {
        image.img.style.opacity = 1;
    } else {
        image.img.parentNode.style.backgroundColor = "#DCDCDC";
        image.img.parentNode.style.backgroundImage = "url('https://fastly.jsdelivr.net/gh/microsoft/fluentui-system-icons/assets/Image%20Prohibited/SVG/ic_fluent_image_prohibited_24_filled.svg')";
    }
    const result = image.isLoaded ? 'loaded' : 'broken';
    console.log('[' + result + '] ' + image.img.src);
});

}

const processElem = ( urlS ) => {
    const objS = new Array();
    const div = document.createElement("div");

urlS.forEach(( url ) => {
    objS.push({ src: url });
    const liImg = createIlLi ( url );
    div.appendChild(liImg);
});

div.className = "cntInner";
return div;
}

const preprocessPrecast = () => {
    const trigger = createTrigger();
    const bar = createBar();
    trigger.addEventListener('mouseover', () => {
        bar.style.display = 'block';
    });
    trigger.appendChild(bar);
    const button = document.createElement('button');
    button.textContent = 'x';
    button.style.width = '16px';
    button.style.height = '16px';
    button.addEventListener('mouseup', () => {
        trigger.remove();
    });
    bar.appendChild(button);

    document.body.appendChild(trigger);
}

const createTrigger = () => {
    const triggerField = document.createElement('div');
    triggerField.style.position = 'fixed';
    triggerField.style.zIndex = 801;
    triggerField.id = 'triggerField';
    triggerField.style.bottom = '0px';
    triggerField.style.right = '0px';
    triggerField.style.width = '16px';
    triggerField.style.height = '16px';
    triggerField.style.backgroundColor = '#ccc';
    triggerField.addEventListener('contextmenu', () => {
		console.log('contextmenu');
    });
    return triggerField;
}

const createBar = () => {
    const div = document.createElement('div');
    div.style.position = 'fixed';
    div.style.bottom = '16px';
    div.style.right = '0px';
    div.style.width = '16px';
    div.style.backgroundColor = '#ccc';
    div.style.display = 'none';
    div.addEventListener('mouseleave', () => {
        div.style.display = 'none';
    });
    return div;
}

const createCheckbox = () => {
    const check = document.createElement('input');
    check.type = 'checkbox';
    check.style.margin = '0';
    return check;
}

if (document.body) {
    uniqueLauncher();
} else {
    document.addEventListener("DOMContentLoaded", () => {
        uniqueLauncher();
    });
}

const domainReStrict = ( dest ) => {
    const ghPage = /\bhttps?:\/\/\S+\.github\.io/i;
    const msnCn = /\bhttps?:\/\/www\.msn\.cn\/zh-cn\/\w+\/\w+\/[%-\w]+\/[-\w]+/i;
    switch ( true ) {
        case ghPage.test(dest):
            return "ghPage";
            break;
        case msnCn.test(dest):
            return "msnCn";
            break;
        default:
            console.log("default");
    }
}

const msnBehaviour = ( mutateObserv ) => {
    const observer = new MutationObserver((mutationsList, observer) => {
    const cpArticleElement = document.querySelector( mutateObserv );
    if ( cpArticleElement ) {
        secuReFerShell ({
            referObj : rO_retrieveMsn,
        });
        observer.disconnect();
    }
});

// 配置观察器:监视子节点的变化和所有后代的变化
const config = { childList: true, subtree: true };

// 开始观察整个文档或特定的父元素
// 如果你知道cp-article会出现在哪个父元素下,观察该父元素会更高效
observer.observe(document.body, config);
}

const reStrict = domainReStrict ( document.URL );
switch ( reStrict ) {
    case "ghPage":
        const unit = visualizeComponentS ();
        secuReFerShell ({
            referObj : rO_jspanel,
            targetElem : unit,
            param : "dashBoard",
        });
        break;
    case "msnCn":
        msnBehaviour ( "cp-article" );
        break;
    default:
        console.log("default");
}

    // Your code here...
})();

/*

*/