JSFiddle - React, Tailwind, and code Playground
by rich_harris
HTML
<script src="https://rawgit.com/rstacruz/ractive-promise-alt/master/index.js"></script>
<main></main>
<script id='template' type='text/ractive'>
<div class='search'>
<label>
Search for a topic
<input value='{{topic}}'/>
</label>
{{#with searchResult}}
{{#with result.query}}
<h2>search results</h2>
<p>click link to preview below</p>
<ul>
{{#each pages}}
<li><a on-click='preview(title, pageid)' href='http://en.wikipedia.org/wiki/{{encodeURIComponent(title)}}'>{{title}}</a></li>
{{/each}}
</ul>
{{elseif pending}}
<p>loading preview for {{title}}...</p>
{{elseif error}}
<p>something went wrong! {{error}}</p>
{{/with}}
{{/with}}
</div>
<div class='preview'>
{{#with preview}}
{{#with result}}
<h2>previewing extract of {{title}}</h2>
{{{extract || '<p>no extract available</p>'}}}
{{elseif pending}}
<p>searching for {{topic}}...</p>
{{elseif error}}
<p>something went wrong! {{error}}</p>
{{/with}}
{{/with}}
</div>
</script>
<script id='searchResult' type='text/ractive'>
</script>
CSS
body {
font-family: 'Helvetica Neue', arial, sans-serif;
font-weight: 200;
color: #353535;
}
h1, h2, h3, h4, h5, h6 {
font-weight: 200;
}
.error {
color: #d00;
font-family: monospace;
}
input {
font-family: inherit;
font-size: inherit;
display: block;
margin: 1em 0;
}
JavaScript
var ractive = new Ractive({
el: 'main',
template: '#template',
data: {
topic: 'promises'
},
adapt: [ 'promise-alt' ],
preview: function ( title, pageid ) {
this.event.original.preventDefault();
var url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&pageids=' + pageid;
this.set({
title: title,
preview: jsonp( url ).then( function ( response ) {
return response.query.pages[ pageid ];
})
});
}
});
function jsonp ( url ) {
return new Promise( function ( fulfil, reject ) {
var id = 'JSONP_' + ~~( Math.random() * 100000 );
var script = document.createElement( 'script' );
window[ id ] = function ( data ) {
console.log( data );
try {
fulfil( data );
} catch ( err ) {
reject( err );
}
script.parentNode.removeChild( script );
delete window[ id ];
};
url += '&callback=' + id;
script.src = url;
script.onerror = reject;
document.querySelector( 'body' ).appendChild( script );
});
}
ractive.observe( 'topic', function ( topic ) {
var url = 'http://en.wikipedia.org/w/api.php?action=query&titles=' + encodeURIComponent( topic ) + '&prop=info&continue=&format=json';
this.set( 'searchResult', jsonp( url ) );
});