Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

MediaWiki:Gadget-paragraphfinder.js: Difference between revisions

MediaWiki interface page
Add delay for VE to load
Don't wait for ready
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
mw.loader.using(['oojs-ui-core', 'oojs-ui-widgets', 'ext.visualEditor.desktopArticleTarget.init', 'ext.cite.visualEditor'], function () {
mw.loader.using(['oojs-ui-core', 'oojs-ui-widgets', 'ext.visualEditor.desktopArticleTarget.init', 'ext.cite.visualEditor'], function () {
     // Wait for VisualEditor to be ready
     // Wait for VisualEditor to be ready
     if (!mw.config.get('wgVisualEditorConfig')) return;
     // if (!mw.config.get('wgVisualEditorConfig')) return;


     const apiBase = 'https://wingsoffire.wiki/find_paragraph';
     const apiBase = 'https://wingsoffire.wiki/find_paragraph';
Line 152: Line 152:
     function interceptCiteBookTemplate() {
     function interceptCiteBookTemplate() {


         // Delay to ensure ve.init.target is ready
         var originalStaticOptions = ve.ui.MWCitationDialog.static.getTemplateOptionsStatic;
        setTimeout(function () {
            var veTarget = ve.init && ve.init.target;
            if (!veTarget) return;


            var originalGetTemplates = ve.ui.MWCitationDialog.prototype.getTemplateOptions;
        ve.ui.MWCitationDialog.static.getTemplateOptionsStatic = function () {
            var templates = originalStaticOptions.apply(this, arguments);


             ve.ui.MWCitationDialog.prototype.getTemplateOptions = function () {
             var citeBook = templates.find(function (t) {
                 var templates = originalGetTemplates.call(this);
                 return t.template && t.template.getName() === 'Cite book';
            });


                var citeBook = templates.find(function (t) {
            if (citeBook && !citeBook._paragraphFinderPatched) {
                    return t.template && t.template.getName() === 'Cite book';
                citeBook._paragraphFinderPatched = true;
                });


                 if (citeBook && !citeBook._paragraphFinderPatched) {
                 var originalAction = citeBook.action;
                    citeBook._paragraphFinderPatched = true;


                     var originalAction = citeBook.action;
                citeBook.action = function () {
                     showParagraphFinderDialog(function (data) {
                        // Call original Cite book action to open dialog
                        originalAction.call(citeBook);


                    citeBook.action = function () {
                        // Fill in fields once dialog is ready
                         showParagraphFinderDialog(function (data) {
                         setTimeout(function () {
                             originalAction.call(citeBook);
                             var dialog = ve.ui.windowFactory.getOpenedWindows()[0].dialog;


                             setTimeout(function () {
                             if (dialog && dialog.bookWidget) {
                                 var dialog = ve.ui.windowFactory.getOpenedWindows()[0].dialog;
                                 dialog.bookWidget.setValue(data.book);
                                dialog.chapterWidget.setValue(data.chapter);
                                dialog.paragraphWidget.setValue(data.paragraph.toString());
                                dialog.quoteWidget.setValue(data.quote);
                            }
                        }, 500);
                    });
                };
            }


                                if (dialog && dialog.bookWidget) {
            return templates;
                                    dialog.bookWidget.setValue(data.book);
        };
                                    dialog.chapterWidget.setValue(data.chapter);
    }
                                    dialog.paragraphWidget.setValue(data.paragraph.toString());
                                    dialog.quoteWidget.setValue(data.quote);
                                }
                            }, 500);
                        });
                    };
                }


                return templates;
    interceptCiteBookTemplate();
            };
        }, 200); // Give VE time to fully load
    }


     // Hook into VE once it loads
     // Hook into VE once it loads
     mw.hook('ve.activationComplete').add(interceptCiteBookTemplate);
     // mw.hook('ve.activationComplete').add(interceptCiteBookTemplate);
});
});

Latest revision as of 07:17, 22 July 2025

mw.loader.using(['oojs-ui-core', 'oojs-ui-widgets', 'ext.visualEditor.desktopArticleTarget.init', 'ext.cite.visualEditor'], function () {
    // Wait for VisualEditor to be ready
    // if (!mw.config.get('wgVisualEditorConfig')) return;

    const apiBase = 'https://wingsoffire.wiki/find_paragraph';

    function showParagraphFinderDialog(onComplete) {
        const windowManager = new OO.ui.WindowManager();
        $(document.body).append(windowManager.$element);

        const dialog = new OO.ui.ProcessDialog({
            size: 'medium',
            title: 'Find Paragraph Automatically'
        });

        dialog.getBodyHeight = function () {
            return 250;
        };

        dialog.initialize = function () {
            OO.ui.ProcessDialog.prototype.initialize.apply(this, arguments);

            const dialogInstance = this;

            // UI Elements
            this.bookSelect = new OO.ui.DropdownInputWidget({
                label: 'Select book',
                options: [{ data: '', label: 'Loading…' }],
                required: true
            });

            this.chapterSelect = new OO.ui.DropdownInputWidget({
                label: 'Select chapter',
                options: [{ data: '', label: 'Choose a book first' }],
                required: true
            });

            this.quoteInput = new OO.ui.MultilineTextInputWidget({
                placeholder: 'Paste the full paragraph you want to cite',
                autosize: true,
                rows: 4
            });

            this.errorLabel = new OO.ui.LabelWidget({
                label: '',
                classes: ['error'],
                invisibleLabel: true
            });

            this.panel = new OO.ui.PanelLayout({
                padded: true,
                expanded: false
            });

            this.panel.$element.append(
                new OO.ui.LabelWidget({ label: 'Book:' }).$element,
                this.bookSelect.$element,
                new OO.ui.LabelWidget({ label: 'Chapter:' }).$element,
                this.chapterSelect.$element,
                new OO.ui.LabelWidget({ label: 'Quote:' }).$element,
                this.quoteInput.$element,
                this.errorLabel.$element
            );

            this.$body.append(this.panel.$element);

            // Load book list
            fetch(apiBase + '/books')
                .then((r) => r.json())
                .then((data) => {
                    const opts = data.available_books.map((book) => ({
                        data: book,
                        label: book.replace(/_/g, ' ')
                    }));
                    this.bookSelect.setOptions(opts);
                });

            // Load chapter list when book changes
            this.bookSelect.on('change', (book) => {
                this.chapterSelect.setOptions([{ data: '', label: 'Loading…' }]);
                fetch(`${apiBase}/books/${encodeURIComponent(book)}/chapters`)
                    .then((r) => r.json())
                    .then((data) => {
                        const opts = data.available_chapters.map((ch) => ({
                            data: ch,
                            label: ch
                        }));
                        this.chapterSelect.setOptions(opts);
                    });
            });
        };

        dialog.getActionProcess = function (action) {
            if (action === 'find') {
                const book = this.bookSelect.getValue();
                const chapter = this.chapterSelect.getValue();
                const quote = this.quoteInput.getValue();

                if (!book || !chapter || !quote.trim()) {
                    this.errorLabel.setLabel('Please fill in all fields.');
                    return new OO.ui.Process(() => { });
                }

                this.errorLabel.setLabel('');

                return new OO.ui.Process(() => {
                    return fetch(apiBase, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            book_name: book,
                            chapter: chapter,
                            paragraph: quote
                        })
                    })
                        .then(function (response) {
                            if (!response.ok) {
                                return response.json().then(function (err) {
                                    throw new Error(err.reason || 'No match found');
                                });
                            }
                            return response.json();
                        })
                        .then(function (result) {
                            onComplete({
                                book: book,
                                chapter: chapter,
                                paragraph: result.index,
                                quote: result.match
                            });
                            windowManager.closeWindow(dialog);
                        })
                        .catch(function (err) {
                            dialog.errorLabel.setLabel(err.message);
                        });
                });
            }
            return new OO.ui.Process(() => windowManager.closeWindow(dialog));
        };

        dialog.getActions = function () {
            return [
                { action: 'find', label: 'Find Paragraph', flags: ['primary', 'progressive'] },
                { action: 'cancel', label: 'Cancel', flags: ['safe', 'close'] }
            ];
        };

        windowManager.addWindows([dialog]);
        windowManager.openWindow(dialog);
    }

    function interceptCiteBookTemplate() {

        var originalStaticOptions = ve.ui.MWCitationDialog.static.getTemplateOptionsStatic;

        ve.ui.MWCitationDialog.static.getTemplateOptionsStatic = function () {
            var templates = originalStaticOptions.apply(this, arguments);

            var citeBook = templates.find(function (t) {
                return t.template && t.template.getName() === 'Cite book';
            });

            if (citeBook && !citeBook._paragraphFinderPatched) {
                citeBook._paragraphFinderPatched = true;

                var originalAction = citeBook.action;

                citeBook.action = function () {
                    showParagraphFinderDialog(function (data) {
                        // Call original Cite book action to open dialog
                        originalAction.call(citeBook);

                        // Fill in fields once dialog is ready
                        setTimeout(function () {
                            var dialog = ve.ui.windowFactory.getOpenedWindows()[0].dialog;

                            if (dialog && dialog.bookWidget) {
                                dialog.bookWidget.setValue(data.book);
                                dialog.chapterWidget.setValue(data.chapter);
                                dialog.paragraphWidget.setValue(data.paragraph.toString());
                                dialog.quoteWidget.setValue(data.quote);
                            }
                        }, 500);
                    });
                };
            }

            return templates;
        };
    }

    interceptCiteBookTemplate();

    // Hook into VE once it loads
    // mw.hook('ve.activationComplete').add(interceptCiteBookTemplate);
});
Cookies help us deliver our services. By using our services, you agree to our use of cookies.