사용자:Hsl0/common.js: 두 판 사이의 차이
< 사용자:Hsl0
imported>Hsl0 편집 요약 없음 |
imported>Hsl0 잔글편집 요약 없음 |
||
34번째 줄: | 34번째 줄: | ||
} : $.getScript; | } : $.getScript; | ||
mw.loader.using([ | |||
'mediawiki.api.options', | |||
'mediawiki.notification', | |||
'oojs-ui-core' | |||
]).then(function() { | ]).then(function() { | ||
var title = mw.config.get('wgPageName').split('/')[0]; | var title = mw.config.get('wgPageName').split('/')[0]; | ||
325번째 줄: | 322번째 줄: | ||
case 'save': | case 'save': | ||
/* | /* | ||
default: 새 키를 생성할 때만 저장 | |||
reset: 미사용 파라미터 제거 | |||
*/ | */ | ||
if(!('default' in data && key in base) && location.search) base[key] = JSON.stringify('reset' in data? geturlSearch() : Object.assign(JSON.parse(storage.getItem(key)), geturlSearch())); | |||
break; | break; | ||
335번째 줄: | 331번째 줄: | ||
case 'load': | case 'load': | ||
/* | /* | ||
reset: 파라미터 강제 교체 | |||
reset: 파라미터 강제 | |||
*/ | */ | ||
if(!location.search || 'reset' in data) Object.assign(this.params, JSON.parse(storage.getItem(key))); | if(!location.search || 'reset' in data) Object.assign(this.params, JSON.parse(storage.getItem(key))); | ||
break; | break; | ||
348번째 줄: | 338번째 줄: | ||
// 기본 | // 기본 | ||
case '호출': | case '호출': | ||
case ' | case 'get': | ||
/* | /* | ||
reset: 파라미터 초기화 | |||
*/ | */ | ||
if('reset' in data) this.params = {}; | |||
this.params[data.arg] = storage.getItem(key); | this.params[data.arg] = storage.getItem(key); | ||
break; | break; | ||
360번째 줄: | 348번째 줄: | ||
case '수정': | case '수정': | ||
case 'set': | case 'set': | ||
base[key] = data.arg; | /* | ||
default: 새 키를 생성할 때만 저장 | |||
*/ | |||
if(!('default' in data && key in base)) base[key] = data.arg; | |||
break; | break; | ||
372번째 줄: | 363번째 줄: | ||
case 'json': | case 'json': | ||
/* | /* | ||
reset: 파라미터 초기화 | |||
delete: 데이터 초기화 | |||
reset: 파라미터 | |||
*/ | */ | ||
if('reset' in data) this.params = {}; | if('reset' in data) this.params = {}; | ||
params = this.params; | params = this.params; |
2020년 4월 19일 (일) 01:06 판
/* [[틀:JSON수정]] 차단 시작 */
$('.uncy-jsonedit').remove();
delete window.uncy_jsonEdit;
/* [[틀:JSON수정]] 차단 끝 */
/**
* punycode.js - 퓨니코드 처리 라이브러리
* DB2에서 미디어위키 옵션 저장소 키의 문자열 제한 우회를 위해 사용중
* 제작자: bestiejs - https://github.com/bestiejs/punycode.js
* 출처: CDNJS - https://cdnjs.cloudflare.com/ajax/libs/punycode/1.4.1/punycode.min.js
**/
!function(e){function o(e){throw new RangeError(T[e])}function n(e,o){for(var n=e.length,r=[];n--;)r[n]=o(e[n]);return r}function r(e,o){var r=e.split("@"),t="";r.length>1&&(t=r[0]+"@",e=r[1]),e=e.replace(S,".");var u=e.split("."),i=n(u,o).join(".");return t+i}function t(e){for(var o,n,r=[],t=0,u=e.length;u>t;)o=e.charCodeAt(t++),o>=55296&&56319>=o&&u>t?(n=e.charCodeAt(t++),56320==(64512&n)?r.push(((1023&o)<<10)+(1023&n)+65536):(r.push(o),t--)):r.push(o);return r}function u(e){return n(e,function(e){var o="";return e>65535&&(e-=65536,o+=P(e>>>10&1023|55296),e=56320|1023&e),o+=P(e)}).join("")}function i(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:b}function f(e,o){return e+22+75*(26>e)-((0!=o)<<5)}function c(e,o,n){var r=0;for(e=n?M(e/j):e>>1,e+=M(e/o);e>L*C>>1;r+=b)e=M(e/L);return M(r+(L+1)*e/(e+m))}function l(e){var n,r,t,f,l,s,d,a,p,h,v=[],g=e.length,w=0,m=I,j=A;for(r=e.lastIndexOf(E),0>r&&(r=0),t=0;r>t;++t)e.charCodeAt(t)>=128&&o("not-basic"),v.push(e.charCodeAt(t));for(f=r>0?r+1:0;g>f;){for(l=w,s=1,d=b;f>=g&&o("invalid-input"),a=i(e.charCodeAt(f++)),(a>=b||a>M((x-w)/s))&&o("overflow"),w+=a*s,p=j>=d?y:d>=j+C?C:d-j,!(p>a);d+=b)h=b-p,s>M(x/h)&&o("overflow"),s*=h;n=v.length+1,j=c(w-l,n,0==l),M(w/n)>x-m&&o("overflow"),m+=M(w/n),w%=n,v.splice(w++,0,m)}return u(v)}function s(e){var n,r,u,i,l,s,d,a,p,h,v,g,w,m,j,F=[];for(e=t(e),g=e.length,n=I,r=0,l=A,s=0;g>s;++s)v=e[s],128>v&&F.push(P(v));for(u=i=F.length,i&&F.push(E);g>u;){for(d=x,s=0;g>s;++s)v=e[s],v>=n&&d>v&&(d=v);for(w=u+1,d-n>M((x-r)/w)&&o("overflow"),r+=(d-n)*w,n=d,s=0;g>s;++s)if(v=e[s],n>v&&++r>x&&o("overflow"),v==n){for(a=r,p=b;h=l>=p?y:p>=l+C?C:p-l,!(h>a);p+=b)j=a-h,m=b-h,F.push(P(f(h+j%m,0))),a=M(j/m);F.push(P(f(a,0))),l=c(r,w,u==i),r=0,++u}++r,++n}return F.join("")}function d(e){return r(e,function(e){return F.test(e)?l(e.slice(4).toLowerCase()):e})}function a(e){return r(e,function(e){return O.test(e)?"xn--"+s(e):e})}var p="object"==typeof exports&&exports&&!exports.nodeType&&exports,h="object"==typeof module&&module&&!module.nodeType&&module,v="object"==typeof global&&global;v.global!==v&&v.window!==v&&v.self!==v||(e=v);var g,w,x=2147483647,b=36,y=1,C=26,m=38,j=700,A=72,I=128,E="-",F=/^xn--/,O=/[^\x20-\x7E]/,S=/[\x2E\u3002\uFF0E\uFF61]/g,T={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},L=b-y,M=Math.floor,P=String.fromCharCode;if(g={version:"1.4.1",ucs2:{decode:t,encode:u},decode:l,encode:s,toASCII:a,toUnicode:d},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return g});else if(p&&h)if(module.exports==p)h.exports=g;else for(w in g)g.hasOwnProperty(w)&&(p[w]=g[w]);else e.punycode=g}(this);
//# sourceMappingURL=./punycode.min.js.map
/* punycode.js 끝 */
var fetchScript = fetch? function fetchScript(url, integrity) {
return fetch(url, {
header: {
Accept: [
'application/javascript',
'application/ecmascript',
'text/javascript',
'application/x-javascript',
'*/*'
]
},
integrity: integrity
}).then(function(res) {
return res.text().then(function(text) {
new Function(text)();
return new $.Deferred().resolve(text, res.statusText, res).promise();
});
});
} : $.getScript;
mw.loader.using([
'mediawiki.api.options',
'mediawiki.notification',
'oojs-ui-core'
]).then(function() {
var title = mw.config.get('wgPageName').split('/')[0];
var noti;
/* option key 인코딩
퓨니코드 + url인코딩
% = _
_ = __
*/
function encode(key) {
return encodeURIComponent(punycode.toASCII(key))
.replace(/\./g, '%2E')
.replace(/!/g, '%21')
.replace(/~/g, '%7E')
.replace(/\*/g, '%2A')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/_/g, '__')
.replace(/%/g, '_');
}
function decode(key) {
return punycode.toUnicode(decodeURIComponent(key.replace(/_(?=[a-zA-Z0-9]{2})/g, '%').replace(/__/g, '_')));
}
// hybridStorage 서브셋 생성
window.setStoragePrefix = function(storage, prefix, except) {
var spp = new Proxy(storage, {
get: function(target, prop, receiver) {
function keys() {
return Object.keys(target).filter(function(key) {
return key.startsWith(prefix);
});
}
return Reflect.get(Object.assign({
length: (prop === 'length') && keys().length,
getItem: function getItem(key) {
return target.getItem(prefix + key);
},
key: function key(index) {
return keys()[index].slice(prefix.length);
},
removeItem: function removeItem(key) {
return target.removeItem(prefix + key).then(function() {
return spp;
});
},
setItem: function setItem(key, value) {
return target.setItem(prefix + key, value).then(function() {
return spp;
});
}
}, except), prop, receiver) || target.getItem(prefix + prop);
},
set: function(target, prop, value) {
return target.setItem(prefix + prop, value);
},
deleteProperty: function(target, prop) {
return target.removeItem(prefix + prop);
},
has: function(target, prop) {
Reflect.has(target, prefix + prop);
},
ownKeys: function(target) {
return Reflect.ownKeys(target).filter(function(key) {
return key.startsWith(prefix);
}).map(function(key) {
return key.slice(prefix.length);
});
}
});
return spp;
};
/*
anon = localStorage[*]
user = mw.user.options[userjs-*]
*/
window.hybridStorage = (function() {
var action;
var api = new mw.Api();
var storage, action;
var saveOption = (function() {
var options = {};
var deferred = new $.Deferred();
var timeout = null;
return function saveOption(key, value) {
if(timeout) clearTimeout(timeout);
options[key] = value;
timeout = setTimeout(function() {
deferred.resolve(api.saveOptions(options));
options = {};
timeout = null;
deferred = new $.Deferred();
}, 100);
return deferred.promise();
};
})();
if(mw.user.isAnon()) {
storage = new Proxy(localStorage, {
get: function(target, prop, receiver) {
var value = Reflect.get({
length: target.length,
getItem: target.getItem,
key: target.key,
removeItem: function removeItem(key) {
return Promise.resolve(target.removeItem(key));
},
setItem: function setItem(key, value) {
return Promise.resolve(target.setItem(key, value));
},
refresh: function refresh() {
return Promise.resolve(storage);
},
needRefresh: false
}, prop, receiver) || target.getItem(prop);
return (value === null)? undefined : value;
},
set: function(target, prop, value, receiver) {
return Promise.resolve(target.setItem(prop, value));
},
deleteProperty: function(target, prop) {
return Promise.resolve(target.removeItem(prop));
}
});
} else {
action = {
removeItem: function removeItem(key) {
if(key) return saveOption("userjs-" + key, null).then(action.refresh);
else throw new TypeError("Failed to execute 'removeItem' on 'Storage': 1 argument required, but only 0 present.");
},
setItem: function setItem(key, value) {
if(key) return saveOption("userjs-" + key, value).then(action.refresh);
else throw new TypeError("Failed to execute 'removeItem' on 'Storage': 1 argument required, but only 0 present.");
},
refresh: (function() {
var deferred = new $.Deferred();
var timeout = null;
return function refresh() {
if(timeout) clearTimeout(timeout);
timeout = setTimeout(function() {
setTimeout(function() {
deferred.resolve(api.get({
action: 'query',
meta: 'userinfo',
uiprop: 'options'
}, {
cache: false
}).then(function(response) {
mw.user.options.values = response.query.userinfo.options;
return storage;
}));
timeout = null;
deferred = new $.Deferred();
}, 300);
}, 100);
return deferred.promise();
};
})()
};
storage = new Proxy(mw.user.options, {
get: function(target, prop, receiver) {
function keys() {
return Object.keys(target.values).filter(function(key) {
return key.startsWith('userjs-');
});
}
return Reflect.get({
length: prop === 'length' && keys().length,
getItem: function getItem(key) {
if(key) return target.get("userjs-" + encode(key));
else throw new TypeError("Failed to execute 'getItem' on 'Storage': 1 argument required, but only 0 present.");
},
key: function key(index) {
return decode(keys()[index].slice(7));
},
removeItem: function removeItem(key) {
key = encode(key);
Reflect.deleteProperty(target.values, key);
return action.removeItem(key);
},
setItem: function setItem(key, value) {
key = encode(key);
target.set(key, value);
return action.setItem(key, value);
},
refresh: action.refresh,
needRefresh: true
}, prop, receiver) || Reflect.get(target.values, "userjs-" + encode(prop), receiver);
},
set: function(target, prop, value, receiver) {
prop = encode(prop);
Reflect.set(target.values, prop, value, receiver);
return action.setItem(encode(prop, value));
},
deleteProperty: function(target, prop) {
prop = encode(prop);
Reflect.deleteProperty(target.values, prop);
return action.removeItem(prop);
},
has: function(target, prop) {
return Reflect.has(target.values, "userjs-" + encode(prop));
},
ownKeys: function(target) {
return Reflect.ownKeys(target.values).filter(function(key) {
return key.startsWith("userjs-");
}).map(function(key) {
return decode(key.slice(7));
});
}
});
}
return storage;
})();
// local + global 슈퍼셋 (hybridStorage[gamedb-*])
var rootGameDB = setStoragePrefix(hybridStorage, 'gamedb-', {
refresh: function() {
return hybridStorage.refresh().then(function() {
return rootGameDB;
});
},
needRefresh: hybridStorage.needRefresh
});
// 게임별로 할당되는 영역 (rootGameDB[{게임}/*])
window.localGameDB = setStoragePrefix(rootGameDB, mw.config.get('wgPageName').split('/')[0] + '/', {
refresh: function() {
return rootGameDB.refresh().then(function() {
return localGameDB;
});
},
needRefresh: rootGameDB.needRefresh
});
// 모든 게임이 공유하는 영역 (rootGameDB[#*])
window.globalGameDB = setStoragePrefix(rootGameDB, '#', {
refresh: function() {
return rootGameDB.refresh().then(function() {
return globalGameDB;
});
},
needRefresh: rootGameDB.needRefresh
});
function DataChange(href) {
this.params = geturlSearch(new URL(href, location));
this.local = {};
this.global = {};
this.root = {};
this.refresh = false;
}
DataChange.prototype.control = function control(element) {
var base, key, storage, params;
var data = element.dataset;
/* 저장할 키
local: 키 지정
global: 전역 키 지정
local global: 키 지정
(없음): 기본 키
*/
if('local' in data) {
storage = localGameDB;
base = this.local;
key = data.local;
} else if('global' in data) {
storage = globalGameDB;
base = this.global;
key = data.global;
} else {
storage = rootGameDB;
base = this.root;
key = title;
}
switch(data.action) {
// 호환
case '저장':
case 'save':
/*
default: 새 키를 생성할 때만 저장
reset: 미사용 파라미터 제거
*/
if(!('default' in data && key in base) && location.search) base[key] = JSON.stringify('reset' in data? geturlSearch() : Object.assign(JSON.parse(storage.getItem(key)), geturlSearch()));
break;
case '로드':
case 'load':
/*
reset: 파라미터 강제 교체
*/
if(!location.search || 'reset' in data) Object.assign(this.params, JSON.parse(storage.getItem(key)));
break;
// 기본
case '호출':
case 'get':
/*
reset: 파라미터 초기화
*/
if('reset' in data) this.params = {};
this.params[data.arg] = storage.getItem(key);
break;
case '수정':
case 'set':
/*
default: 새 키를 생성할 때만 저장
*/
if(!('default' in data && key in base)) base[key] = data.arg;
break;
case '삭제':
case 'del':
delete base[key];
break;
// JSON
case 'JSON':
case 'json':
/*
reset: 파라미터 초기화
delete: 데이터 초기화
*/
if('reset' in data) this.params = {};
params = this.params;
this.data[key] = JSON.stringify(new CGI2Parser({
get: function(args) {
if(typeof args === 'object') Object.pairs(args).forEach(function(pair) {
params[pair[0]] = this[pair[1]];
});
else Array.from(arguments).forEach(function(key) {
params[key] = this[key];
});
},
set: function(args) {
Object.pairs(args).forEach(function(pair) {
this[pair[0]] = pair[1];
});
},
del: function() {
Array.from(arguments).forEach(function(key) {
delete this[key];
});
},
def: function(args) {
Object.pairs(args).forEach(function(pair) {
if(!(pair[0] in params)) params[pair[0]] = this[pair[1]];
});
},
sav: function(args) {
if(typeof args === 'object') Object.pairs(args).forEach(function(pair) {
this[pair[0]] = params[pair[1]];
});
else Array.from(arguments).forEach(function(key) {
this[key] = params[key];
});
}
}).parse(JSON.parse(base.getItem(key)), data.arg));
Object.assign(this.params, params);
break;
}
};
// TODO: .gameDB-control, .gameDB-container, .gameDB-link click 이벤트 리스너 구현
/**
* DB 저장
* @function
* @param {DataChange} change
*/
function save(change) {
var key;
var promises = [];
if(title in change.root) {
promises.push(rootGameDB.setItem(key, change.root[title]));
}
for(key in change.local) {
promises.push(localGameDB.setItem(key, change.local[key]));
}
for(key in change.global) {
promises.push(globalGameDB.setItem(key, change.global[key]));
}
if(promises.length && !mw.user.isAnon()) noti = mw.notification.notify('데이터를 저장하는 중입니다...', {
autoHide: false,
tag: 'gameDB',
type: 'pending'
});
return Promise.all(promises);
}
function handleError(code, object) {
mw.notification.notify(
code === 'http'?
$('<span />')
.append($('<p />', {class: 'gameDB-noti-errmsg'}).text(object.xhr.responseText))
.append($('<code />', {class: 'gameDB-noti-errcode'}).text('HTTP ' + object.xhr.status)) :
$('<span />')
.append($('<p />', {class: 'gameDB-noti-errmsg'}).text(object.error.info))
.append($('<code />', {class: 'gameDB-noti-errcode'}).text(code)),
{
title: '데이터 저장에 실패하였습니다.',
type: 'error',
tag: 'gameDB'
}
);
}
// 즉시
(function() {
var instant = new DataChange();
$('.gameDB-control').each(function() {
instant.control(this);
});
save(instant).then(function() {
instant.params = searchParamToString(instant.params);
if(instant.params.length > 1) Promise.all(promises).then(function() {
location.search = instant.params;
});
else noti.close();
}, handleError);
})();
// 링크
(function() {
function process(link, controllers, change) {
var href = new URL(link.href, location);
controllers.each(function() {
change.control(this);
});
href.search = searchParamToString(Object.assign(geturlSearch(href), change.params));
link.href = href.href;
}
$('.gameDB-container').not(':has(a, .gameDB-container)').each(function() {
$(this).html($('<a />').text(this.innerText));
});
$('.gameDB-container a').each(function() {
var change = new DataChange(this.href);
var controllers = $($(this).parents('.gameDB-container').get().reverse());
process(this, controllers.not('[data-live]'), change);
$(this).data('change', change);
$(this).addClass('gameDB-link');
});
$('.gameDB-link').on('click', 'gameDB', function(event) {
var link = this;
var parents = $($(this).parents('.gameDB-container[data-live]').get().reverse());
var change = $(this).data('change');
var promise;
if(!('done' in this.dataset)) event.preventDefault();
if(parents.length) {
mw.notification.notify('데이터를 가져오는 중입니다...', {
tag: 'gameDB',
type: 'pending'
});
promise = hybridStorage.refresh().then(function() {
process(link, parents, change);
return save(change);
});
} else promise = save(change);
promise.then(function() {
link.dataset.done = '';
if(link.href) $(link).off('click', 'gameDB').click();
else mw.notification.notify('데이터가 저장되었습니다.', {
tag: 'gameDB'
});
}, handleError);
});
})();
});