MediaWiki:Gadget-autosave.js: различия между версиями
Перейти к навигации
Перейти к поиску
Ланселот (обсуждение | вклад) Новая страница: «( function () { 'use strict'; // ---- Проверки окружения ---- var wgAction = mw.config.get( 'wgAction' ); var wgNamespace = mw.config.get( 'wgNamespaceNumber' ); var wgPageName = mw.config.get( 'wgPageName' ); var wgDBname = mw.config.get( 'wgDBname' ) || 'wiki'; // Разрешаем: обычное редактирование, submit, редактирование новой/красной ссылки. //...» |
Ланселот (обсуждение | вклад) Нет описания правки |
||
| Строка 2: | Строка 2: | ||
'use strict'; | 'use strict'; | ||
// ---- | // ---- Окружение ---- | ||
var wgAction = mw.config.get( 'wgAction' ); | var wgAction = mw.config.get( 'wgAction' ); | ||
var wgNamespace = mw.config.get( 'wgNamespaceNumber' ); | var wgNamespace = mw.config.get( 'wgNamespaceNumber' ); | ||
| Строка 8: | Строка 8: | ||
var wgDBname = mw.config.get( 'wgDBname' ) || 'wiki'; | var wgDBname = mw.config.get( 'wgDBname' ) || 'wiki'; | ||
var allowedActions = [ 'edit', 'submit', 'editredlink', 'formedit' ]; | var allowedActions = [ 'edit', 'submit', 'editredlink', 'formedit' ]; | ||
if ( allowedActions.indexOf( wgAction ) === -1 ) | if ( allowedActions.indexOf( wgAction ) === -1 ) return; | ||
if ( wgNamespace === -1 ) return; | |||
if ( mw.config.get( 'wgVisualEditorActive' ) ) return; | |||
if ( wgNamespace === -1 ) | |||
if ( mw.config.get( 'wgVisualEditorActive' ) ) | |||
// ---- Конфиг ---- | |||
// ---- | |||
var config = { | var config = { | ||
saveDelay: 3000, | saveDelay: 3000, | ||
maxDraftAgeDays: 7, | maxDraftAgeDays: 7, | ||
idleDelay: 2500, | |||
highlightMs: 2000 | |||
}; | }; | ||
var storageKey = 'wiki_draft_' + wgDBname + '_' + wgPageName; | var storageKey = 'wiki_draft_' + wgDBname + '_' + wgPageName; | ||
var $textbox = null; | |||
var saveTimeout = null; | var saveTimeout = null; | ||
var | var idleTimeout = null; | ||
var lastSavedContent = | var lastSavedContent = ''; | ||
var draftData = null; | |||
// ---- localStorage ---- | |||
var storage = ( function () { | |||
var ok = false; | |||
try { | |||
localStorage.setItem( '__t__', '1' ); | |||
localStorage.removeItem( '__t__' ); | |||
ok = true; | |||
} catch ( e ) {} | |||
return { | |||
ok: ok, | |||
get: function ( k ) { try { return ok ? localStorage.getItem( k ) : null; } catch ( e ) { return null; } }, | |||
set: function ( k, v ) { try { return ok ? ( localStorage.setItem( k, v ), true ) : false; } catch ( e ) { return false; } }, | |||
remove: function ( k ) { try { if ( ok ) localStorage.removeItem( k ); } catch ( e ) {} } | |||
}; | |||
} )(); | |||
// ---- | // ---- Уведомления (свой, без mw.notify) ---- | ||
function toast( message, color ) { | |||
var $t = $( '<div>' ).css( { | |||
position: 'fixed', | |||
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 ); | |||
setTimeout( function () { | |||
$t.css( 'transition', 'opacity 0.3s' ).css( 'opacity', '0' ); | |||
setTimeout( function () { $t.remove(); }, 300 ); | |||
}, 2500 ); | |||
} | |||
} | |||
} | |||
// ---- | // ---- Панель ---- | ||
var $indicator = null; | var $indicator = null; | ||
function | function buildIndicator() { | ||
if ( $( ' | if ( $indicator ) return; | ||
$indicator = $( '<div>' ).attr( 'id', 'autosave-indicator' ).css( { | |||
display: 'flex', | |||
} | alignItems: 'center', | ||
gap: '8px', | |||
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 $dot = $( '<span>' ).attr( 'id', 'autosave-dot' ).css( { | ||
display: 'inline-block', | |||
width: '8px', | |||
height: '8px', | |||
borderRadius: '50%', | |||
background: '#72777d', | |||
flex: '0 0 auto' | |||
} ); | |||
var $text = $( '<span>' ).attr( 'id', 'autosave-text' ).text( 'Черновик не сохранён' ); | |||
var $restore = $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'autosave-restore' ).css( { | |||
marginLeft: 'auto', | |||
padding: '4px 12px', | |||
background: '#36c', | |||
color: '#fff', | |||
} ); | border: 'none', | ||
borderRadius: '4px', | |||
cursor: 'pointer', | |||
fontSize: '0.9em', | |||
display: 'none' | |||
} ).text( 'Восстановить' ).on( 'click', openDraftDialog ); | |||
$indicator.append( $dot, $text, $restore ); | |||
$indicator.append( $dot, $text, $ | |||
$textbox.after( $indicator ); | $textbox.after( $indicator ); | ||
} | } | ||
function updateIndicator( status ) { | function updateIndicator( status ) { | ||
if ( !$indicator | if ( !$indicator ) return; | ||
if ( | if ( idleTimeout ) { clearTimeout( idleTimeout ); idleTimeout = null; } | ||
var map = { | |||
saved: { t: 'Черновик сохранён', c: '#00af89' }, | |||
editing: { t: 'Редактирование…', c: '#36c' }, | |||
error: { t: 'Ошибка сохранения', c: '#d33' }, | |||
var | idle: { t: 'Черновик не сохранён', c: '#72777d' }, | ||
saved: { | found: { t: 'Найден черновик', c: '#ac6600' } | ||
editing: { | |||
error: { | |||
idle: { | |||
found: { | |||
}; | }; | ||
var m = map[ status ] || map.idle; | |||
var | $indicator.find( '#autosave-dot' ).css( 'background', m.c ); | ||
$indicator.find( '#autosave-dot' ).css( 'background', | $indicator.find( '#autosave-text' ).text( m.t ).css( 'color', m.c ); | ||
$indicator.find( '#autosave-text' ).text( | |||
if ( status === 'saved' ) { | if ( status === 'saved' ) { | ||
idleTimeout = setTimeout( function () { updateIndicator( 'idle' ); }, config.idleDelay ); | |||
} | } | ||
} | } | ||
function | function toggleRestoreBtn( show ) { | ||
if ( | if ( $indicator ) $indicator.find( '#autosave-restore' ).css( 'display', show ? 'inline-block' : 'none' ); | ||
} | } | ||
// ---- Сохранение ---- | // ---- Сохранение ---- | ||
function saveDraft( silent ) { | function saveDraft( silent ) { | ||
if ( !storage. | if ( !storage.ok || !$textbox ) return false; | ||
var content = $textbox.val(); | |||
if ( content === lastSavedContent ) return false; | |||
var data = { | |||
content: content, | |||
var | timestamp: Date.now(), | ||
if ( | page: wgPageName, | ||
revId: mw.config.get( 'wgCurRevisionId' ) || 0 | |||
}; | |||
if ( storage.set( storageKey, JSON.stringify( data ) ) ) { | |||
lastSavedContent = content; | |||
lastSavedContent = | |||
updateIndicator( 'saved' ); | updateIndicator( 'saved' ); | ||
return true; | return true; | ||
} | } | ||
updateIndicator( 'error' ); | |||
if ( !silent ) toast( 'Не удалось сохранить черновик', '#d33' ); | |||
return false; | |||
} | } | ||
// ---- | // ---- Чтение черновика ---- | ||
function loadDraft() { | function loadDraft() { | ||
var raw = storage.get( storageKey ); | var raw = storage.get( storageKey ); | ||
if ( !raw ) return null; | if ( !raw ) return null; | ||
var data; | var data; | ||
try { | try { data = JSON.parse( raw ); } catch ( e ) { storage.remove( storageKey ); return null; } | ||
if ( !data || data.page !== wgPageName || typeof data.content !== 'string' ) return null; | |||
var ageDays = ( Date.now() - data.timestamp ) / 86400000; | |||
if ( ageDays > config.maxDraftAgeDays ) { storage.remove( storageKey ); return null; } | |||
if ( !data || data.page !== wgPageName || typeof data.content !== 'string' ) | |||
var ageDays = ( Date.now() - data.timestamp ) / | |||
if ( ageDays > config.maxDraftAgeDays ) { | |||
return data; | return data; | ||
} | } | ||
function applyDraft( | function applyDraft( d ) { | ||
$textbox.val( | $textbox.val( d.content ); | ||
lastSavedContent = | lastSavedContent = d.content; | ||
$textbox.addClass( 'autosave-restored' ); | $textbox.addClass( 'autosave-restored' ); | ||
setTimeout( function () { | setTimeout( function () { $textbox.removeClass( 'autosave-restored' ); }, config.highlightMs ); | ||
toast( 'Черновик восстановлен', '#00af89' ); | |||
updateIndicator( 'saved' ); | updateIndicator( 'saved' ); | ||
} | } | ||
// ---- | // ---- Диалог выбора ---- | ||
function openDraftDialog() { | function openDraftDialog() { | ||
if ( !draftData ) return; | if ( !draftData ) return; | ||
var $ov = $( '<div>' ).css( { | |||
var $ | position: 'fixed', inset: '0', background: 'rgba(0,0,0,0.45)', | ||
position: 'fixed', | zIndex: 10001, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '12px' | ||
zIndex: | |||
} ); | } ); | ||
var $box = $( '<div>' ).css( { | var $box = $( '<div>' ).css( { | ||
background: '#fff', | 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' | |||
padding: ' | |||
fontFamily: 'sans-serif', | |||
} ); | } ); | ||
var preview = draftData.content.length > 200 ? draftData.content.slice( 0, 200 ) + '…' : draftData.content; | |||
$box.append( | |||
$( '<div>' ).css( { fontWeight: 'bold', fontSize: '1.05em', marginBottom: '8px' } ).text( 'Сохранённый черновик' ), | |||
$( '<div>' ).css( { color: '#54595d', fontSize: '0.85em', marginBottom: '8px' } ) | |||
.text( new Date( draftData.timestamp ).toLocaleString() + ' · ' + draftData.content.length + ' симв.' ), | |||
$( '<pre>' ).css( { | |||
background: '#f8f9fa', border: '1px solid #eaecf0', borderRadius: '4px', | |||
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(); } ); | |||
$( document.body ).append( $ov ); | |||
$ | |||
$( document.body ).append( $ | |||
} | } | ||
| Строка 370: | Строка 230: | ||
function initDraft() { | function initDraft() { | ||
draftData = loadDraft(); | draftData = loadDraft(); | ||
if ( !draftData ) { | if ( !draftData ) { updateIndicator( 'idle' ); return; } | ||
var current = $textbox.val() || ''; | |||
return; | if ( draftData.content === current ) { | ||
lastSavedContent = current; updateIndicator( 'saved' ); return; | |||
} | } | ||
if ( current.trim() === '' ) { | |||
applyDraft( draftData ); return; | |||
} | } | ||
updateIndicator( 'found' ); | updateIndicator( 'found' ); | ||
toggleRestoreBtn( true ); | |||
toast( 'Найден черновик — нажмите «Восстановить»', '#ac6600' ); | |||
} | } | ||
// ---- | // ---- Обработчики ---- | ||
function | function bindEvents() { | ||
$textbox.on( 'input', function () { | |||
if ( saveTimeout ) clearTimeout( saveTimeout ); | |||
updateIndicator( 'editing' ); | |||
saveTimeout = setTimeout( function () { saveDraft( true ); }, config.saveDelay ); | |||
} ); | } ); | ||
// | // Ctrl+S | ||
$( document ).on( 'keydown', function ( e ) { | |||
if ( ( e.ctrlKey || e.metaKey ) && ( e.key === 's' || e.key === 'S' ) ) { | |||
$( | e.preventDefault(); | ||
if ( saveDraft( false ) ) toast( 'Черновик сохранён', '#00af89' ); | |||
} | } | ||
} ); | } ); | ||
// Уход со страницы | |||
$( window ).on( 'beforeunload', function () { | |||
if ( !$textbox ) return; | |||
if ( $textbox.val() !== lastSavedContent ) saveDraft( true ); | |||
} ); | |||
$( document ).on( 'visibilitychange', function () { | |||
if ( document.visibilityState === 'hidden' && $textbox && $textbox.val() !== lastSavedContent ) { | |||
saveDraft( true ); | saveDraft( true ); | ||
} | } | ||
} ); | |||
// Удаление черновика при отправке формы | |||
var submitted = false; | |||
$( document ).on( 'submit', 'form', function () { | |||
submitted = true; | |||
} ); | |||
$( window ).on( 'pagehide', function () { | |||
if ( | if ( submitted ) storage.remove( storageKey ); | ||
} | } ); | ||
} | } | ||
// ---- | // ---- Ждём появления textarea (мобильный скин!) ---- | ||
function waitForTextbox( cb ) { | |||
var tries = 0; | |||
var timer = setInterval( function () { | |||
var $tb = $( '#wpTextbox1' ); | |||
if ( | if ( $tb.length ) { | ||
clearInterval( timer ); | |||
cb( $tb ); | |||
} else if ( ++tries > 100 ) { // ~10 секунд | |||
clearInterval( timer ); | |||
} | } | ||
} | }, 100 ); | ||
} | } | ||
// ---- Старт ---- | // ---- Старт ---- | ||
if ( document.readyState === 'loading' ) { | |||
document.addEventListener( 'DOMContentLoaded', boot ); | |||
} else { | |||
boot(); | |||
} | |||
function boot() { | |||
waitForTextbox( function ( $tb ) { | |||
$textbox = $tb; | |||
lastSavedContent = $textbox.val() || ''; | |||
buildIndicator(); | |||
initDraft(); | |||
bindEvents(); | |||
} ); | |||
} | |||
} )(); | } )(); | ||
Версия от 22:46, 15 ноября 2026
( function () {
'use strict';
// ---- Окружение ----
var wgAction = mw.config.get( 'wgAction' );
var wgNamespace = mw.config.get( 'wgNamespaceNumber' );
var wgPageName = mw.config.get( 'wgPageName' );
var wgDBname = mw.config.get( 'wgDBname' ) || 'wiki';
var allowedActions = [ 'edit', 'submit', 'editredlink', 'formedit' ];
if ( allowedActions.indexOf( wgAction ) === -1 ) return;
if ( wgNamespace === -1 ) return;
if ( mw.config.get( 'wgVisualEditorActive' ) ) return;
// ---- Конфиг ----
var config = {
saveDelay: 3000,
maxDraftAgeDays: 7,
idleDelay: 2500,
highlightMs: 2000
};
var storageKey = 'wiki_draft_' + wgDBname + '_' + wgPageName;
var $textbox = null;
var saveTimeout = null;
var idleTimeout = null;
var lastSavedContent = '';
var draftData = null;
// ---- localStorage ----
var storage = ( function () {
var ok = false;
try {
localStorage.setItem( '__t__', '1' );
localStorage.removeItem( '__t__' );
ok = true;
} catch ( e ) {}
return {
ok: ok,
get: function ( k ) { try { return ok ? localStorage.getItem( k ) : null; } catch ( e ) { return null; } },
set: function ( k, v ) { try { return ok ? ( localStorage.setItem( k, v ), true ) : false; } catch ( e ) { return false; } },
remove: function ( k ) { try { if ( ok ) localStorage.removeItem( k ); } catch ( e ) {} }
};
} )();
// ---- Уведомления (свой, без mw.notify) ----
function toast( message, color ) {
var $t = $( '<div>' ).css( {
position: 'fixed',
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 );
setTimeout( function () {
$t.css( 'transition', 'opacity 0.3s' ).css( 'opacity', '0' );
setTimeout( function () { $t.remove(); }, 300 );
}, 2500 );
}
// ---- Панель ----
var $indicator = null;
function buildIndicator() {
if ( $indicator ) return;
$indicator = $( '<div>' ).attr( 'id', 'autosave-indicator' ).css( {
display: 'flex',
alignItems: 'center',
gap: '8px',
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 $dot = $( '<span>' ).attr( 'id', 'autosave-dot' ).css( {
display: 'inline-block',
width: '8px',
height: '8px',
borderRadius: '50%',
background: '#72777d',
flex: '0 0 auto'
} );
var $text = $( '<span>' ).attr( 'id', 'autosave-text' ).text( 'Черновик не сохранён' );
var $restore = $( '<button>' ).attr( 'type', 'button' ).attr( 'id', 'autosave-restore' ).css( {
marginLeft: 'auto',
padding: '4px 12px',
background: '#36c',
color: '#fff',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '0.9em',
display: 'none'
} ).text( 'Восстановить' ).on( 'click', openDraftDialog );
$indicator.append( $dot, $text, $restore );
$textbox.after( $indicator );
}
function updateIndicator( status ) {
if ( !$indicator ) return;
if ( idleTimeout ) { clearTimeout( idleTimeout ); idleTimeout = null; }
var map = {
saved: { t: 'Черновик сохранён', c: '#00af89' },
editing: { t: 'Редактирование…', c: '#36c' },
error: { t: 'Ошибка сохранения', c: '#d33' },
idle: { t: 'Черновик не сохранён', c: '#72777d' },
found: { t: 'Найден черновик', c: '#ac6600' }
};
var m = map[ status ] || map.idle;
$indicator.find( '#autosave-dot' ).css( 'background', m.c );
$indicator.find( '#autosave-text' ).text( m.t ).css( 'color', m.c );
if ( status === 'saved' ) {
idleTimeout = setTimeout( function () { updateIndicator( 'idle' ); }, config.idleDelay );
}
}
function toggleRestoreBtn( show ) {
if ( $indicator ) $indicator.find( '#autosave-restore' ).css( 'display', show ? 'inline-block' : 'none' );
}
// ---- Сохранение ----
function saveDraft( silent ) {
if ( !storage.ok || !$textbox ) return false;
var content = $textbox.val();
if ( content === lastSavedContent ) return false;
var data = {
content: content,
timestamp: Date.now(),
page: wgPageName,
revId: mw.config.get( 'wgCurRevisionId' ) || 0
};
if ( storage.set( storageKey, JSON.stringify( data ) ) ) {
lastSavedContent = content;
updateIndicator( 'saved' );
return true;
}
updateIndicator( 'error' );
if ( !silent ) toast( 'Не удалось сохранить черновик', '#d33' );
return false;
}
// ---- Чтение черновика ----
function loadDraft() {
var raw = storage.get( storageKey );
if ( !raw ) return null;
var data;
try { data = JSON.parse( raw ); } catch ( e ) { storage.remove( storageKey ); return null; }
if ( !data || data.page !== wgPageName || typeof data.content !== 'string' ) return null;
var ageDays = ( Date.now() - data.timestamp ) / 86400000;
if ( ageDays > config.maxDraftAgeDays ) { storage.remove( storageKey ); return null; }
return data;
}
function applyDraft( d ) {
$textbox.val( d.content );
lastSavedContent = d.content;
$textbox.addClass( 'autosave-restored' );
setTimeout( function () { $textbox.removeClass( 'autosave-restored' ); }, config.highlightMs );
toast( 'Черновик восстановлен', '#00af89' );
updateIndicator( 'saved' );
}
// ---- Диалог выбора ----
function openDraftDialog() {
if ( !draftData ) return;
var $ov = $( '<div>' ).css( {
position: 'fixed', inset: '0', background: 'rgba(0,0,0,0.45)',
zIndex: 10001, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '12px'
} );
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;
$box.append(
$( '<div>' ).css( { fontWeight: 'bold', fontSize: '1.05em', marginBottom: '8px' } ).text( 'Сохранённый черновик' ),
$( '<div>' ).css( { color: '#54595d', fontSize: '0.85em', marginBottom: '8px' } )
.text( new Date( draftData.timestamp ).toLocaleString() + ' · ' + draftData.content.length + ' симв.' ),
$( '<pre>' ).css( {
background: '#f8f9fa', border: '1px solid #eaecf0', borderRadius: '4px',
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(); } );
$( document.body ).append( $ov );
}
// ---- Инициализация черновика ----
function initDraft() {
draftData = loadDraft();
if ( !draftData ) { updateIndicator( 'idle' ); return; }
var current = $textbox.val() || '';
if ( draftData.content === current ) {
lastSavedContent = current; updateIndicator( 'saved' ); return;
}
if ( current.trim() === '' ) {
applyDraft( draftData ); return;
}
updateIndicator( 'found' );
toggleRestoreBtn( true );
toast( 'Найден черновик — нажмите «Восстановить»', '#ac6600' );
}
// ---- Обработчики ----
function bindEvents() {
$textbox.on( 'input', function () {
if ( saveTimeout ) clearTimeout( saveTimeout );
updateIndicator( 'editing' );
saveTimeout = setTimeout( function () { saveDraft( true ); }, config.saveDelay );
} );
// Ctrl+S
$( document ).on( 'keydown', function ( e ) {
if ( ( e.ctrlKey || e.metaKey ) && ( e.key === 's' || e.key === 'S' ) ) {
e.preventDefault();
if ( saveDraft( false ) ) toast( 'Черновик сохранён', '#00af89' );
}
} );
// Уход со страницы
$( window ).on( 'beforeunload', function () {
if ( !$textbox ) return;
if ( $textbox.val() !== lastSavedContent ) saveDraft( true );
} );
$( document ).on( 'visibilitychange', function () {
if ( document.visibilityState === 'hidden' && $textbox && $textbox.val() !== lastSavedContent ) {
saveDraft( true );
}
} );
// Удаление черновика при отправке формы
var submitted = false;
$( document ).on( 'submit', 'form', function () {
submitted = true;
} );
$( window ).on( 'pagehide', function () {
if ( submitted ) storage.remove( storageKey );
} );
}
// ---- Ждём появления textarea (мобильный скин!) ----
function waitForTextbox( cb ) {
var tries = 0;
var timer = setInterval( function () {
var $tb = $( '#wpTextbox1' );
if ( $tb.length ) {
clearInterval( timer );
cb( $tb );
} else if ( ++tries > 100 ) { // ~10 секунд
clearInterval( timer );
}
}, 100 );
}
// ---- Старт ----
if ( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', boot );
} else {
boot();
}
function boot() {
waitForTextbox( function ( $tb ) {
$textbox = $tb;
lastSavedContent = $textbox.val() || '';
buildIndicator();
initDraft();
bindEvents();
} );
}
} )();