-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch-element.js
149 lines (126 loc) · 4.56 KB
/
fetch-element.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
export function
wait4DomUpdated( cb )
{
return new Promise( resolve =>
{
const assureDom = window.requestIdleCallback || window.requestAnimationFrame
, done = () => resolve( cb && cb() );
assureDom ? assureDom( done ) : setTimeout( done, 100 );
} )
}
export function
toKebbabCase( s )
{ return ( s || '' ).toLowerCase().replaceAll( /\s/g, '-' )}
export class
FetchElement extends HTMLElement
{
static get observedAttributes(){ return [ 'src', 'method', 'headers', 'state', 'status', 'error', 'skiprender' ]; }
static get mime2mod(){ return { 'application/json':async ()=>(await import('./render/json.js')).default
, 'text/html': ()=>FetchElement.prototype.renderHtml
, 'text/xml': ()=>FetchElement.prototype.renderHtml
, 'application/xml': ()=>FetchElement.prototype.renderHtml
, 'image/svg+xml': ()=>FetchElement.prototype.renderHtml
}}
get headers(){ return {} }
abort(){}
fetch(...args){ return this._fetch(...args); }
constructor()
{
super();
let promise = Promise.resolve();
const controller = new AbortController();
const { signal } = controller;
this.abort = () => controller.abort();
this._fetch = async( url, options ) =>
{
this.state = 'loading';
this.status = '';
const opt = {
method: this.getAttribute( 'method' ) || 'GET'
, headers: this.headers
, ...options
, signal
};
return promise = new Promise( async( resolve, reject ) =>
{
try
{ const response = await fetch( url, opt );
const ret = await this.onResponse( response )
const res = await this.onResult( ret );
this.error ? reject( this.error ) : resolve( res );
}catch( ex )
{ reject( this.onError( ex ) ); }
} )
};
Object.defineProperty( this, 'promise', { get(){ return promise; } } );
FetchElement.observedAttributes
.filter( prop => prop !== 'headers' )
.forEach( prop => Object.defineProperty( this, prop,
{
get: () => this.getAttribute( prop )
, set: val => this.setAttribute( prop, val )
} ) );
}
connectedCallback()
{
this.src && this.fetch( this.src );
this.initialized = !0;
}
attributeChangedCallback( name, oldValue, newValue )
{
switch( name )
{ case 'headers':
this[ name ] = eval( newValue );
break;
case 'src':
this.initialized && this.fetch( newValue );
break;
default:
if( this[ name ] !== newValue )
this[ name ] = newValue;
}
}
async onResponse( response )
{
const s = 1 * ( this.status = response.status );
if( s < 200 || s >= 300 )
this.error = 'network error';
this.contentType = response.headers.get( 'content-type' );
this.responseHeaders = response.headers;
if( this.contentType.includes( 'json' ) )
return response.json();
return response.text();
}
setContent( html ){ this.innerHTML = html; }
async onResult( result )
{
try
{ if( this.hasAttribute('skiprender') )
return;
let mod = await this.constructor.mime2mod[ this.contentType.split(';')[0] ]();
if( typeof mod === 'string' )
mod = (await import(mod)).default;
this.state = 'rendering';
return ( mod || this.render ).call( this, result, this.contentType, this.status, this.responseHeaders );
}finally
{
this.state = 'loaded';
}
}
render( data, contentType, httpCode, responseHeaders ){}
async renderHtml( data, contentType, httpCode, responseHeaders )
{
this.setContent( data );
await wait4DomUpdated();
this.render( ...arguments );
await wait4DomUpdated();
}
onError( error )
{
this.state = 'error';
return error;
}
getKeys( obj ){ return Object.keys( obj ); }
}
export default FetchElement;
window.customElements.define( 'fetch-element', FetchElement );