MediaWiki:Gadget-autosave.js: различия между версиями

Нет описания правки
Нет описания правки
Строка 1: Строка 1:
// =================================================
// ===    «Автосохранение вики-черновиков»      ===
// =================================================
// Версия 2.0, улучшенная и исправленная
// Идёт в связке с [[MediaWiki:Gadget-autosave.css]]
// Лицензия: MIT (opensource.org/license/mit) ==> 2026, absurdopedia.wiki
// Поддерживает движки от MediaWiki 1.35+
// Автосохранение срабатывает через 3 сек. после того, как вы перестали печатать
// При выходе со страницы сохранение происходит мгновенно
// Ручное сохранение — только Ctrl+S (Cmd+S на Mac)
// Индикатор показывает «Редактирование…» пока вы печатаете, и иное по делу
// Работает без интернета, если страница редактирования уже загружена
// Не нагружает сервер: всё хранится в localStorage браузера
// При сбое ломается только сам скрипт, страница продолжает работать
// Сохраняется текст и для несозданных (новых) статей — ключ привязан к имени страницы
// Черновики разделов хранятся отдельно: правка раздела 1 не предлагается в разделе 2
// Очистка кэша браузера НЕ удаляет черновики
// История браузера (Ctrl+Shift+Del с галочкой «Данные сайтов») удалит черновики
// Режим инкогнито: черновики живут до закрытия окна
// Черновики старше 7 дней удаляются при следующей попытке загрузки
// Браузер может удалить данные при переполнении хранилища сайта (квота ~5 МБ)
// Ключ хранилища включает имя вики, имя страницы, номер и заголовок раздела
( function () {
( function () {
     'use strict';
     'use strict';
Строка 75: Строка 99:
     // ---- Уведомления ----
     // ---- Уведомления ----
     function toast( message, color ) {
     function toast( message, color ) {
         var $t = $( '<div>' ).css( {
         var $t = $( '<div>' ).addClass( 'autosave-toast' ).text( message );
            position: 'fixed',
        if ( color ) $t.css( 'border-left-color', color );
            bottom: '20px',
            left: '50%',
            transform: 'translateX(-50%)',
            background: color || '#36c',
            color: '#fff',
            padding: '10px 18px',
            borderRadius: '6px',
            boxShadow: '0 4px 16px rgba(0,0,0,0.25)',
            fontSize: '0.95em',
            zIndex: 10000,
            maxWidth: '90vw',
            textAlign: 'center'
        } ).text( message );
         $( document.body ).append( $t );
         $( document.body ).append( $t );
         setTimeout( function () {
         setTimeout( function () {
             $t.css( 'transition', 'opacity 0.3s' ).css( 'opacity', '0' );
             $t.addClass( 'autosave-toast--hide' );
             setTimeout( function () { $t.remove(); }, 300 );
             setTimeout( function () { $t.remove(); }, 300 );
         }, 2500 );
         }, 2500 );
Строка 102: Строка 113:
     function buildIndicator() {
     function buildIndicator() {
         if ( $indicator ) return;
         if ( $indicator ) return;
         $indicator = $( '<div>' ).attr( 'id', 'autosave-indicator' ).css( {
         $indicator = $( '<div>' ).attr( 'id', 'autosave-indicator' ).addClass( 'autosave-panel' );
            display: 'flex',
 
            alignItems: 'center',
        var $text = $( '<span>' ).attr( 'id', 'autosave-text' )
            gap: '8px',
             .addClass( 'autosave-panel-text' ).text( 'Черновик не сохранён' );
            fontSize: '0.9em',
            margin: '8px 0',
            padding: '8px 12px',
             background: '#f8f9fa',
            border: '1px solid #eaecf0',
            borderRadius: '6px',
            color: '#72777d',
            fontFamily: 'sans-serif',
            flexWrap: 'wrap'
        } );


        var $text = $( '<span>' ).attr( 'id', 'autosave-text' ).text( 'Черновик не сохранён' );
         var $restore = $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'autosave-restore' )
         var $restore = $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'autosave-restore' ).css( {
            .addClass( 'autosave-btn autosave-btn--primary' )
            marginLeft: 'auto',
             .css( { display: 'none', marginLeft: 'auto' } )
             padding: '4px 12px',
             .text( 'Восстановить' )
            background: '#36c',
            .on( 'click', openDraftDialog );
            color: '#fff',
            border: 'none',
            borderRadius: '4px',
             cursor: 'pointer',
            fontSize: '0.9em',
            display: 'none'
        } ).text( 'Восстановить' ).on( 'click', openDraftDialog );


         $indicator.append( $text, $restore );
         $indicator.append( $text, $restore );
Строка 137: Строка 131:
         if ( !$indicator ) return;
         if ( !$indicator ) return;
         var map = {
         var map = {
             saved:  { t: 'Черновик сохранён',       c: '#00af89' },
             saved:  { t: 'Черновик сохранён',   cls: 'autosave-panel--saved' },
             editing: { t: 'Редактирование…',         c: '#36c' },
             editing: { t: 'Редактирование…',     cls: 'autosave-panel--editing' },
             error:  { t: 'Ошибка сохранения',       c: '#d33' },
             error:  { t: 'Ошибка сохранения',   cls: 'autosave-panel--error' },
             idle:    { t: 'Черновик не сохранён',   c: '#72777d' },
             idle:    { t: 'Черновик не сохранён', cls: 'autosave-panel--idle' },
             found:  { t: 'Найден черновик',         c: '#ac6600' }
             found:  { t: 'Найден черновик',     cls: 'autosave-panel--found' }
         };
         };
         var m = map[ status ] || map.idle;
         var m = map[ status ] || map.idle;
         $indicator.find( '#autosave-text' ).text( m.t ).css( 'color', m.c );
         $indicator
            .removeClass( 'autosave-panel--saved autosave-panel--editing autosave-panel--error autosave-panel--idle autosave-panel--found' )
            .addClass( m.cls );
        $indicator.find( '#autosave-text' ).text( m.t );
     }
     }


     function toggleRestoreBtn( show ) {
     function toggleRestoreBtn( show ) {
         if ( $indicator ) $indicator.find( '#autosave-restore' ).css( 'display', show ? 'inline-block' : 'none' );
         if ( !$indicator ) return;
        var $b = $indicator.find( '#autosave-restore' );
        if ( show ) {
            $b.css( { display: 'inline-block', marginLeft: 'auto' } );
        } else {
            $b.css( 'display', 'none' );
        }
     }
     }


Строка 198: Строка 201:
     function openDraftDialog() {
     function openDraftDialog() {
         if ( !draftData ) return;
         if ( !draftData ) return;
         var $ov = $( '<div>' ).css( {
        if ( $( '.autosave-overlay' ).length ) return;  // защита от повторного открытия
            position: 'fixed', inset: '0', background: 'rgba(0,0,0,0.45)',
 
            zIndex: 10001, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '12px'
         var $ov = $( '<div>' ).addClass( 'autosave-overlay' );
        } );
         var $box = $( '<div>' ).addClass( 'autosave-dialog' );
         var $box = $( '<div>' ).css( {
 
            background: '#fff', borderRadius: '8px', boxShadow: '0 8px 30px rgba(0,0,0,0.25)',
            padding: '16px', width: '100%', maxWidth: '380px', maxHeight: '80vh', overflow: 'auto',
            fontFamily: 'sans-serif', fontSize: '0.95em', color: '#202122', boxSizing: 'border-box'
        } );
         var preview = draftData.content.length > 200 ? draftData.content.slice( 0, 200 ) + '…' : draftData.content;
         var preview = draftData.content.length > 200 ? draftData.content.slice( 0, 200 ) + '…' : draftData.content;
        var closed = false;
        function close() {
            if ( closed ) return;
            closed = true;
            $ov.remove();
        }
        var $actions = $( '<div>' ).addClass( 'autosave-dialog-actions' );
        $actions.append(
            $( '<button>' ).attr( 'type', 'button' ).addClass( 'autosave-btn autosave-btn--ghost' )
                .text( 'Отмена' ).on( 'click', close ),
            $( '<button>' ).attr( 'type', 'button' ).addClass( 'autosave-btn autosave-btn--secondary' )
                .text( 'Удалить' ).on( 'click', function () {
                    storage.remove( storageKey );
                    draftData = null;
                    updateIndicator( 'idle' );
                    toggleRestoreBtn( false );
                    close();
                } ),
            $( '<button>' ).attr( 'type', 'button' ).addClass( 'autosave-btn autosave-btn--primary' )
                .text( 'Восстановить' ).on( 'click', function () {
                    applyDraft( draftData );
                    close();
                } )
        );
         $box.append(
         $box.append(
             $( '<div>' ).css( { fontWeight: 'bold', fontSize: '1.05em', marginBottom: '8px' } ).text( 'Сохранённый черновик' ),
             $( '<div>' ).addClass( 'autosave-dialog-title' ).text( 'Сохранённый черновик' ),
             $( '<div>' ).css( { color: '#54595d', fontSize: '0.85em', marginBottom: '8px' } )
             $( '<div>' ).addClass( 'autosave-dialog-meta' )
                 .text( new Date( draftData.timestamp ).toLocaleString() + ' · ' + draftData.content.length + ' симв.' ),
                 .text( new Date( draftData.timestamp ).toLocaleString() + ' · ' + draftData.content.length + ' симв.' ),
             $( '<pre>' ).css( {
             $( '<pre>' ).addClass( 'autosave-dialog-preview' ).text( preview ),
                background: '#f8f9fa', border: '1px solid #eaecf0', borderRadius: '4px',
             $actions
                padding: '8px', whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                maxHeight: '140px', overflow: 'auto', fontSize: '0.85em', margin: '0 0 12px'
            } ).text( preview ),
             ( function () {
                var $a = $( '<div>' ).css( { display: 'flex', gap: '8px', justifyContent: 'flex-end', flexWrap: 'wrap' } );
                function close() { $ov.remove(); }
                $a.append(
                    $( '<button>' ).attr( 'type', 'button' ).css( {
                        padding: '6px 12px', background: 'transparent', color: '#36c',
                        border: '1px solid #c8ccd1', borderRadius: '4px', cursor: 'pointer'
                    } ).text( 'Отмена' ).on( 'click', close ),
                    $( '<button>' ).attr( 'type', 'button' ).css( {
                        padding: '6px 12px', background: '#eaecf0', color: '#202122',
                        border: 'none', borderRadius: '4px', cursor: 'pointer'
                    } ).text( 'Удалить' ).on( 'click', function () {
                        storage.remove( storageKey ); draftData = null;
                        updateIndicator( 'idle' ); toggleRestoreBtn( false ); close();
                    } ),
                    $( '<button>' ).attr( 'type', 'button' ).css( {
                        padding: '6px 12px', background: '#36c', color: '#fff',
                        border: 'none', borderRadius: '4px', cursor: 'pointer'
                    } ).text( 'Восстановить' ).on( 'click', function () { applyDraft( draftData ); close(); } )
                );
                return $a;
            } )()
         );
         );
         $ov.append( $box ).on( 'click', function ( e ) { if ( e.target === $ov[ 0 ] ) $ov.remove(); } );
 
         $ov.append( $box ).on( 'click', function ( e ) {
            if ( e.target === $ov[ 0 ] ) close();
        } );
 
        // Закрытие по Esc
        $( document ).one( 'keydown.autosaveDialog', function ( e ) {
            if ( e.key === 'Escape' ) close();
        } );
 
         $( document.body ).append( $ov );
         $( document.body ).append( $ov );
     }
     }
Строка 250: Строка 261:
         var current = $textbox.val() || '';
         var current = $textbox.val() || '';
         if ( draftData.content === current ) {
         if ( draftData.content === current ) {
             lastSavedContent = current; updateIndicator( 'saved' ); return;
             lastSavedContent = current;
            updateIndicator( 'saved' );
            return;
         }
         }
         if ( current.trim() === '' ) {
         if ( current.trim() === '' ) {
             applyDraft( draftData ); return;
             applyDraft( draftData );
            return;
        }
        if ( draftData.content.trim() === '' ) {
            storage.remove( storageKey );
            draftData = null;
            updateIndicator( 'idle' );
            return;
         }
         }
         updateIndicator( 'found' );
         updateIndicator( 'found' );