@cat-of-summer/st-script 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +130 -0
- package/dist/app/form.esm.min.js +1 -0
- package/dist/app/form.min.js +2 -0
- package/dist/app.esm.min.js +1 -0
- package/dist/app.min.js +2 -0
- package/dist/cookie.esm.min.js +1 -0
- package/dist/cookie.min.js +2 -0
- package/dist/core.esm.min.js +1 -0
- package/dist/core.min.js +2 -0
- package/dist/index.esm.min.js +1 -0
- package/dist/index.min.js +2 -0
- package/dist/loader.esm.min.js +1 -0
- package/dist/loader.min.js +2 -0
- package/dist/modal.esm.min.js +1 -0
- package/dist/modal.min.js +2 -0
- package/dist/route.esm.min.js +1 -0
- package/dist/route.min.js +2 -0
- package/dist/select.esm.min.js +1 -0
- package/dist/select.min.js +2 -0
- package/dist/st_button_widget.esm.min.js +1 -0
- package/dist/st_button_widget.min.js +2 -0
- package/dist/st_links_widget.esm.min.js +1 -0
- package/dist/st_links_widget.min.js +2 -0
- package/dist/st_mask.esm.min.js +1 -0
- package/dist/st_mask.min.js +2 -0
- package/dist/st_observer.esm.min.js +1 -0
- package/dist/st_observer.min.js +2 -0
- package/dist/st_typograf.esm.min.js +1 -0
- package/dist/st_typograf.min.js +2 -0
- package/dist/st_validator.esm.min.js +1 -0
- package/dist/st_validator.min.js +2 -0
- package/dist/toggle.esm.min.js +1 -0
- package/dist/toggle.min.js +2 -0
- package/dist/uploader.esm.min.js +1 -0
- package/dist/uploader.min.js +2 -0
- package/package.json +35 -0
- package/src/_traits/hasInstanceSymbol.js +29 -0
- package/src/app/form/index.js +357 -0
- package/src/app/index.js +1040 -0
- package/src/cookie/index.js +141 -0
- package/src/core/index.js +159 -0
- package/src/index.js +16 -0
- package/src/loader/index.js +169 -0
- package/src/modal/index.js +297 -0
- package/src/route/index.js +208 -0
- package/src/select/index.js +210 -0
- package/src/st_button_widget/README.txt +62 -0
- package/src/st_button_widget/index.js +322 -0
- package/src/st_links_widget/README.txt +54 -0
- package/src/st_links_widget/index.js +294 -0
- package/src/st_mask/index.js +183 -0
- package/src/st_observer/index.js +426 -0
- package/src/st_typograf/index.js +200 -0
- package/src/st_validator/index.js +57 -0
- package/src/toggle/index.js +181 -0
- package/src/uploader/index.js +297 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
export default class Cookie {
|
|
2
|
+
static set(name, value, params = {}) {
|
|
3
|
+
params = {
|
|
4
|
+
path: '/',
|
|
5
|
+
expires: 3600,
|
|
6
|
+
|
|
7
|
+
...params
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
if (!(params.expires instanceof Date)) {
|
|
11
|
+
let expires = params.expires;
|
|
12
|
+
|
|
13
|
+
params.expires = new Date((typeof expires === "number")
|
|
14
|
+
? Date.now() + expires * 1000
|
|
15
|
+
: Date.parse(expires) || Date.parse(expires.replace(/-/g, '/'))
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + "; expires=" + params.expires.toUTCString() + "; path=" + params.path + (params.domain ? "; domain=" + params.domain : '') + (params.secure ? "; secure" : '') + (params.sameSite ? "; samesite=" + params.sameSite : '');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
static get(name) {
|
|
23
|
+
name = encodeURIComponent(name);
|
|
24
|
+
let cookies_array = document.cookie.split(';');
|
|
25
|
+
|
|
26
|
+
for (let i = 0; i < cookies_array.length; i++) {
|
|
27
|
+
let cookie = cookies_array[i].trim();
|
|
28
|
+
|
|
29
|
+
if (cookie.startsWith(name + '=')) {
|
|
30
|
+
let value = decodeURIComponent(cookie.substring(name.length + 1));
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
return JSON.parse(value);
|
|
34
|
+
} catch {
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
static delete(name, params = {}) {
|
|
44
|
+
Cookie.set(name, '', {
|
|
45
|
+
expires: 0,
|
|
46
|
+
...params
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
static callback(name, callback, params = {}) {
|
|
51
|
+
params = {
|
|
52
|
+
interval: 0,
|
|
53
|
+
delay: 0,
|
|
54
|
+
value: true,
|
|
55
|
+
|
|
56
|
+
...params
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
let interval = setInterval(() => {
|
|
60
|
+
if (Cookie.get(name) === null) {
|
|
61
|
+
Cookie.set(name, params.value, params);
|
|
62
|
+
|
|
63
|
+
setTimeout(() => {
|
|
64
|
+
callback(name);
|
|
65
|
+
}, params.delay * 1000);
|
|
66
|
+
}
|
|
67
|
+
if (!params.interval) clearInterval(interval);
|
|
68
|
+
}, params.interval * 1000);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static consent(params) {
|
|
72
|
+
params = {
|
|
73
|
+
content: `<div><span>Этот сайт использует файлы cookies и сервисы сбора технических данных посетителей (данные об IP-адресе, местоположении и т.д.) для обеспечения работоспособности и улучшения качества обслуживания.</span><div><button action='accept'>Принять</button><button action='decline'>Отклонить</button></div></div>`,
|
|
74
|
+
container: 'body',
|
|
75
|
+
location: 'bottom',
|
|
76
|
+
zIndex: 1000,
|
|
77
|
+
name: 'cookie_consent',
|
|
78
|
+
interval: 5,
|
|
79
|
+
|
|
80
|
+
...params
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
let container = document.createElement('container');
|
|
84
|
+
|
|
85
|
+
if (params.container == 'body')
|
|
86
|
+
Object.assign(container.style, {
|
|
87
|
+
position: 'absolute',
|
|
88
|
+
overflow: 'hidden',
|
|
89
|
+
width: 'max-content',
|
|
90
|
+
height: 'max-content',
|
|
91
|
+
maxWidth: '100vw',
|
|
92
|
+
maxHeight: '100vh',
|
|
93
|
+
zIndex: params.zIndex,
|
|
94
|
+
transition: 'inherit',
|
|
95
|
+
pointerEvents: 'all',
|
|
96
|
+
display: 'none',
|
|
97
|
+
|
|
98
|
+
...(() => {
|
|
99
|
+
let location = (params.location || '').toLowerCase().split(/\s+/);
|
|
100
|
+
|
|
101
|
+
let style = {
|
|
102
|
+
top: location.includes('top') ? 0 : location.includes('bottom') ? undefined : '50%',
|
|
103
|
+
bottom: location.includes('bottom') ? 0 : undefined,
|
|
104
|
+
left: location.includes('left') ? 0 : location.includes('right') ? undefined : '50%',
|
|
105
|
+
right: location.includes('right') ? 0 : undefined,
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
let tx = style.left === '50%' ? 'translateX(-50%)' : '';
|
|
109
|
+
let ty = style.top === '50%' ? 'translateY(-50%)' : '';
|
|
110
|
+
|
|
111
|
+
if (tx || ty) style.transform = `${tx} ${ty}`.trim();
|
|
112
|
+
|
|
113
|
+
return style;
|
|
114
|
+
})()
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
document.querySelector(params.container).append(container);
|
|
118
|
+
|
|
119
|
+
if (!(params.content instanceof Element)) {
|
|
120
|
+
let content = params.content;
|
|
121
|
+
|
|
122
|
+
params.content = content.trim().startsWith('<')
|
|
123
|
+
? (new DOMParser()).parseFromString(content, 'text/html').body.firstElementChild
|
|
124
|
+
: document.querySelector(content) ?? (() => { throw new Error("Селектор не найден") })();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
container.append(params.content);
|
|
128
|
+
|
|
129
|
+
Cookie.callback(params.name, e => {
|
|
130
|
+
['accept', 'decline'].forEach(action => {
|
|
131
|
+
container.querySelectorAll(`[action=${action}]`).forEach(t => {
|
|
132
|
+
t.addEventListener('click', e => {
|
|
133
|
+
Cookie.set(params.name, action == 'accept', params);
|
|
134
|
+
container.style.display = 'none';
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
container.style.display = '';
|
|
139
|
+
}, {...params, value: null});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
export default class Core {
|
|
2
|
+
|
|
3
|
+
static merge(...objects) {
|
|
4
|
+
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
5
|
+
&& (Object.getPrototypeOf(v) ?? Object.prototype) === Object.prototype;
|
|
6
|
+
|
|
7
|
+
const merge = (a, b) => {
|
|
8
|
+
if (typeof a === 'function' && typeof b === 'function')
|
|
9
|
+
return (...args) => merge(a(...args), b(...args));
|
|
10
|
+
if (!((Array.isArray(a) && Array.isArray(b)) || (plain(a) && plain(b))))
|
|
11
|
+
return b;
|
|
12
|
+
|
|
13
|
+
const result = Array.isArray(a) ? a.slice() : { ...a };
|
|
14
|
+
for (const [k, v] of Object.entries(b))
|
|
15
|
+
result[k] = k in result ? merge(result[k], v) : v;
|
|
16
|
+
return result;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
return objects.reduce(merge, {});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
static generate_unique_prefix(params) {
|
|
23
|
+
params = {
|
|
24
|
+
characters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
|
|
25
|
+
length: 16,
|
|
26
|
+
|
|
27
|
+
...params,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
return [...Array(params.length)].map(_ =>
|
|
31
|
+
params.characters[Math.random() * params.characters.length | 0]
|
|
32
|
+
).join('');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
static fetch(params) {
|
|
36
|
+
if (params instanceof HTMLFormElement)
|
|
37
|
+
params = {
|
|
38
|
+
url: params.getAttribute('action') || '',
|
|
39
|
+
method: params.getAttribute('method') || '',
|
|
40
|
+
data: new FormData(params),
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
params = { url: '', method: '', data: null, headers: {}, timeout: 0, response_type: '', ...params };
|
|
44
|
+
|
|
45
|
+
const events = {
|
|
46
|
+
beforeSend: [params.before_send],
|
|
47
|
+
onSend: [params.on_send],
|
|
48
|
+
onSuccess: [params.on_success],
|
|
49
|
+
onComplete: [params.on_complete],
|
|
50
|
+
onFailed: [params.on_failed],
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
let request, resolve, reject, done = false;
|
|
54
|
+
const promise = new Promise((res, rej) => (resolve = res, reject = rej));
|
|
55
|
+
const fire = (event, payload) => {
|
|
56
|
+
for (const cb of events[event])
|
|
57
|
+
if (cb) try { cb(payload) } catch (e) { console.error(`st_ajax: ${event} error`, e) }
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const api = {
|
|
61
|
+
then: (a, b) => promise.then(a, b),
|
|
62
|
+
catch: b => promise.catch(b),
|
|
63
|
+
finally: f => promise.finally(f),
|
|
64
|
+
abort: () => request?.abort(),
|
|
65
|
+
};
|
|
66
|
+
for (const event of Object.keys(events))
|
|
67
|
+
api[event] = cb => (events[event].push(cb), api);
|
|
68
|
+
|
|
69
|
+
const handle_error = (err) => {
|
|
70
|
+
if (done) return;
|
|
71
|
+
done = true;
|
|
72
|
+
const payload = err instanceof XMLHttpRequest
|
|
73
|
+
? { status: err.status, status_text: err.statusText, response: err.responseText, request: err }
|
|
74
|
+
: { status: undefined, status_text: '', response: err };
|
|
75
|
+
fire('onFailed', payload);
|
|
76
|
+
reject(payload);
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
queueMicrotask(() => {
|
|
80
|
+
try {
|
|
81
|
+
let url = params.url, method = params.method, body;
|
|
82
|
+
|
|
83
|
+
fire('beforeSend', params);
|
|
84
|
+
|
|
85
|
+
if (params.data instanceof FormData)
|
|
86
|
+
body = params.data;
|
|
87
|
+
else if (params.data instanceof HTMLFormElement) {
|
|
88
|
+
url = url || params.data.getAttribute('action');
|
|
89
|
+
method = method || params.data.getAttribute('method');
|
|
90
|
+
body = new FormData(params.data);
|
|
91
|
+
} else
|
|
92
|
+
body = params.data;
|
|
93
|
+
|
|
94
|
+
url = url || window.location.href;
|
|
95
|
+
method = method ? method.toUpperCase() : 'GET';
|
|
96
|
+
|
|
97
|
+
if (body && typeof body == 'object') {
|
|
98
|
+
if (method == 'GET') {
|
|
99
|
+
const query = body instanceof FormData
|
|
100
|
+
? new URLSearchParams(body).toString()
|
|
101
|
+
: Object.entries(body).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
|
|
102
|
+
if (query) url += (/\?.+=/.test(url) ? '&' : '?') + query;
|
|
103
|
+
body = null;
|
|
104
|
+
} else if (!(body instanceof FormData)) {
|
|
105
|
+
body = JSON.stringify(params.data);
|
|
106
|
+
if (!Object.keys(params.headers).some(h => h.toLowerCase() == 'content-type'))
|
|
107
|
+
params.headers['Content-Type'] = 'application/json';
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
request = new XMLHttpRequest();
|
|
112
|
+
if (params.response_type) try { request.responseType = params.response_type } catch (e) {}
|
|
113
|
+
if (params.timeout > 0 && Number.isFinite(params.timeout)) request.timeout = params.timeout;
|
|
114
|
+
|
|
115
|
+
request.onerror = request.ontimeout = () => handle_error(request);
|
|
116
|
+
request.onreadystatechange = () => {
|
|
117
|
+
if (request.readyState !== 4) return;
|
|
118
|
+
|
|
119
|
+
let data;
|
|
120
|
+
if (request.status >= 200 && request.status < 300) {
|
|
121
|
+
if (request.responseType)
|
|
122
|
+
data = request.response;
|
|
123
|
+
else {
|
|
124
|
+
const type = request.getResponseHeader('Content-Type') || params.response_type || '';
|
|
125
|
+
if (type.includes('/json'))
|
|
126
|
+
try { data = JSON.parse(request.responseText) } catch (e) { data = request.responseText }
|
|
127
|
+
else if (type.includes('/xml'))
|
|
128
|
+
data = new DOMParser().parseFromString(request.responseText, 'application/xml');
|
|
129
|
+
else if (type.includes('/html'))
|
|
130
|
+
data = new DOMParser().parseFromString(request.responseText, 'text/html');
|
|
131
|
+
else
|
|
132
|
+
data = request.responseText;
|
|
133
|
+
}
|
|
134
|
+
fire('onSuccess', { data, request });
|
|
135
|
+
done = true;
|
|
136
|
+
resolve({ data, request });
|
|
137
|
+
} else
|
|
138
|
+
handle_error(request);
|
|
139
|
+
|
|
140
|
+
fire('onComplete', { data, request });
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
request.open(method, url, true);
|
|
144
|
+
for (const name in params.headers)
|
|
145
|
+
if (Object.prototype.hasOwnProperty.call(params.headers, name))
|
|
146
|
+
try { request.setRequestHeader(name, params.headers[name]) } catch (e) {}
|
|
147
|
+
|
|
148
|
+
request.send(body);
|
|
149
|
+
fire('onSend', { detail: params });
|
|
150
|
+
} catch (error) {
|
|
151
|
+
handle_error(error);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
return api;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Aggregate entry — re-exports every standalone module.
|
|
2
|
+
export { default as Loader } from './loader/index.js';
|
|
3
|
+
export { default as App } from './app/index.js';
|
|
4
|
+
export { default as st_button_widget } from './st_button_widget/index.js';
|
|
5
|
+
export { default as Cookie } from './cookie/index.js';
|
|
6
|
+
export { default as st_links_widget } from './st_links_widget/index.js';
|
|
7
|
+
export { default as st_mask } from './st_mask/index.js';
|
|
8
|
+
export { default as Modal } from './modal/index.js';
|
|
9
|
+
export { default as st_observer } from './st_observer/index.js';
|
|
10
|
+
export { default as Select } from './select/index.js';
|
|
11
|
+
export { default as Route } from './route/index.js';
|
|
12
|
+
export { default as Core } from './core/index.js';
|
|
13
|
+
export { default as Toggle } from './toggle/index.js';
|
|
14
|
+
export { default as st_typograf } from './st_typograf/index.js';
|
|
15
|
+
export { default as Uploader } from './uploader/index.js';
|
|
16
|
+
export { default as st_validator } from './st_validator/index.js';
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { element, find, own } from '../_traits/hasInstanceSymbol.js';
|
|
2
|
+
import Core from '../core/index.js';
|
|
3
|
+
|
|
4
|
+
export default class Loader {
|
|
5
|
+
#config = {};
|
|
6
|
+
#request = null;
|
|
7
|
+
|
|
8
|
+
static find = find;
|
|
9
|
+
|
|
10
|
+
// composable-хуки: при per-type оверрайде root → branch вызываются оба
|
|
11
|
+
static HOOKS = ['before_load', 'on_load', 'before_paste', 'on_paste',
|
|
12
|
+
'on_failed', 'on_complete', 'before_init', 'on_init'];
|
|
13
|
+
|
|
14
|
+
// строка ИЛИ tagged template → первый Element (шаблон-хелпер)
|
|
15
|
+
static html(s, ...v) {
|
|
16
|
+
let str = Array.isArray(s) ? s.reduce((a, p, i) => a + v[i - 1] + p) : s;
|
|
17
|
+
return new DOMParser().parseFromString(str, 'text/html').body.firstElementChild;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
get params() {
|
|
21
|
+
let o = {};
|
|
22
|
+
for (let [k, v] of Object.entries(this.#config))
|
|
23
|
+
if (typeof v != 'function' && k != 'formats') o[k] = v;
|
|
24
|
+
return o;
|
|
25
|
+
}
|
|
26
|
+
get loading() { return !!this.#request; }
|
|
27
|
+
|
|
28
|
+
html = Loader.html;
|
|
29
|
+
|
|
30
|
+
clone(params = {}) {
|
|
31
|
+
return new Loader({
|
|
32
|
+
...this.#config, ...params,
|
|
33
|
+
formats: { ...this.#config.formats, ...params.formats },
|
|
34
|
+
parent: this,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
constructor(params) {
|
|
39
|
+
this.#config = {
|
|
40
|
+
target: null, // селектор/Element контейнера
|
|
41
|
+
source: null, // HTML: CSS-селектор; JSON: dot-path до данных
|
|
42
|
+
mode: 'append', // append | replace | prepend
|
|
43
|
+
multiple: true, // true → массив элементов; false → один элемент
|
|
44
|
+
allow_interrupt: false,
|
|
45
|
+
formats: {}, // per-type оверрайды: { json:{…}, html:{…}, text:{…} }
|
|
46
|
+
|
|
47
|
+
render(item) { return item; }, // деф.: identity (готовый HTML-элемент)
|
|
48
|
+
|
|
49
|
+
before_load: () => {},
|
|
50
|
+
on_load: () => {},
|
|
51
|
+
before_paste: () => {},
|
|
52
|
+
on_paste: () => {},
|
|
53
|
+
on_failed: () => {},
|
|
54
|
+
on_complete: () => {},
|
|
55
|
+
before_init: () => {},
|
|
56
|
+
on_init: () => {},
|
|
57
|
+
|
|
58
|
+
...params,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
this.#config.before_init.call(this, this.#config);
|
|
62
|
+
|
|
63
|
+
this.target = element(this.#config.target);
|
|
64
|
+
if (this.target) own(this.target, this);
|
|
65
|
+
|
|
66
|
+
this.#config.on_init.call(this, this.#config);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// тип ответа из распарсенных Core данных
|
|
70
|
+
#type(response) {
|
|
71
|
+
if (response instanceof Document) return 'html';
|
|
72
|
+
if (typeof response == 'string') return 'text';
|
|
73
|
+
return 'json';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// эффективный конфиг для типа: root + formats[type] (хуки складываются, прочее перекрывается)
|
|
77
|
+
#resolve(type) {
|
|
78
|
+
let root = this.#config, branch = root.formats?.[type] ?? {}, out = {};
|
|
79
|
+
|
|
80
|
+
for (let k of new Set([...Object.keys(root), ...Object.keys(branch)])) {
|
|
81
|
+
if (k == 'formats') continue;
|
|
82
|
+
let a = root[k], b = branch[k], v;
|
|
83
|
+
|
|
84
|
+
if (k in branch && k in root && Loader.HOOKS.includes(k)
|
|
85
|
+
&& typeof a == 'function' && typeof b == 'function')
|
|
86
|
+
// on_load прокидывает data по цепочке (return заменяет); прочие хуки — сайд-эффекты
|
|
87
|
+
v = k == 'on_load'
|
|
88
|
+
? (response, data, request) => {
|
|
89
|
+
let d = a.call(this, response, data, request) ?? data;
|
|
90
|
+
return b.call(this, response, d, request) ?? d;
|
|
91
|
+
}
|
|
92
|
+
: (...args) => { a.apply(this, args); b.apply(this, args); };
|
|
93
|
+
else
|
|
94
|
+
v = k in branch ? b : a;
|
|
95
|
+
|
|
96
|
+
out[k] = typeof v == 'function' ? v.bind(this) : v;
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// response → this.data по source/multiple/type
|
|
102
|
+
#extract(response, cfg, type) {
|
|
103
|
+
if (type == 'html') {
|
|
104
|
+
let root = response.body ?? response.documentElement ?? response;
|
|
105
|
+
if (cfg.source)
|
|
106
|
+
return cfg.multiple ? [...root.querySelectorAll(cfg.source)] : root.querySelector(cfg.source);
|
|
107
|
+
return cfg.multiple ? [...root.children] : root.firstElementChild;
|
|
108
|
+
}
|
|
109
|
+
if (type == 'json')
|
|
110
|
+
return cfg.source ? cfg.source.split('.').reduce((o, k) => o?.[k], response) : response;
|
|
111
|
+
return response; // text
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
load(params = {}) {
|
|
115
|
+
let { mode, ...fetch } = typeof params == 'string' ? { url: params } : params;
|
|
116
|
+
|
|
117
|
+
if (this.#request) {
|
|
118
|
+
if (!this.#config.allow_interrupt) return this;
|
|
119
|
+
this.#request.abort();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
this.target?.setAttribute('state', 'loading');
|
|
123
|
+
this.#config.before_load.call(this, fetch);
|
|
124
|
+
|
|
125
|
+
let req = Core.fetch(fetch)
|
|
126
|
+
.onSuccess(({ data: response, request }) => {
|
|
127
|
+
let type = this.#type(response);
|
|
128
|
+
let cfg = this.#resolve(type);
|
|
129
|
+
|
|
130
|
+
let data = this.#extract(response, cfg, type);
|
|
131
|
+
data = cfg.on_load(response, data, request) ?? data;
|
|
132
|
+
|
|
133
|
+
let nodes = [];
|
|
134
|
+
let n = cfg.multiple ? (data?.length ?? 0) : 1;
|
|
135
|
+
for (let i = 0; i < n; i++) {
|
|
136
|
+
let item = cfg.multiple ? data?.[i] : data;
|
|
137
|
+
let node = cfg.render(item, i);
|
|
138
|
+
if (node instanceof Node) nodes.push(node);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
cfg.before_paste(nodes);
|
|
142
|
+
|
|
143
|
+
let frag = document.createDocumentFragment();
|
|
144
|
+
nodes.forEach(node => frag.append(node));
|
|
145
|
+
|
|
146
|
+
let m = mode ?? cfg.mode;
|
|
147
|
+
if (this.target)
|
|
148
|
+
m == 'replace' ? this.target.replaceChildren(frag)
|
|
149
|
+
: m == 'prepend' ? this.target.prepend(frag)
|
|
150
|
+
: this.target.append(frag);
|
|
151
|
+
|
|
152
|
+
cfg.on_paste(nodes, response);
|
|
153
|
+
})
|
|
154
|
+
.onFailed(payload => this.#config.on_failed.call(this, payload))
|
|
155
|
+
.onComplete(payload => this.#config.on_complete.call(this, payload));
|
|
156
|
+
|
|
157
|
+
// сброс состояния на любом завершении; guard от устаревшего finally при abort+новый запрос
|
|
158
|
+
req.finally(() => {
|
|
159
|
+
if (this.#request !== req) return;
|
|
160
|
+
this.#request = null;
|
|
161
|
+
this.target?.setAttribute('state', 'loaded');
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
this.#request = req;
|
|
165
|
+
return this;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
abort() { this.#request?.abort(); return this; }
|
|
169
|
+
}
|