Skip to content

Instantly share code, notes, and snippets.

@satyr
Created January 12, 2009 18:57
Show Gist options
  • Save satyr/46107 to your computer and use it in GitHub Desktop.
Save satyr/46107 to your computer and use it in GitHub Desktop.
const Name = 'gimage',
Google = 'http://www.google.com/',
GImage = 'http://image.google.com/',
PPath = 'extensions.ubiquity.google.',
PLang = PPath +'lang',
PSafe = PPath +'safe',
PSize = PPath +'size',
{prefs} = Application,
ID = '#_'+ (Math.random() * 1e9 | 0),
Base = <div class={Name}><style><![CDATA[
@img {border:none}
@ul {list-style:none; text-align:center; margin:2px 0; padding:0}
@li {display:inline-block; vertical-align:top;
margin:0 1px 2px; padding:0; line-height:88%}
@button {padding:0; margin:0; border-width:1px}
@button[disabled]{background-color:transparent; color:inherit}
@li button {position:absolute; opacity:0.6}
@li button[disabled]{display:none}
@kbd {text-decoration:underline}
@button, @kbd {font:bold 92% "Consolas", monospace}
@.count {position:absolute; right:4px}
@.pagination {text-align:center}
@.logo {clear:both; display:block}
@.loading + .logo {opacity:0.4}
@.error + .logo {opacity:0.7}
]]></style><div id={ID.slice(1)}/><a class="logo" href={GImage}
><img src={GImage +'intl/en_ALL/images/images_hp.gif'}
height="55" width="138"/></a></div
>.toXMLString().replace(/@/g, '.'+ Name +' '),
Langs = {
all: '',
Arabic: 'ar',
Bulgarian: 'bg',
Catalan: 'ca',
'Chinese (Simplified)': 'zh_CN',
'Chinese (Traditional)': 'zh_TW',
Croatian: 'hr',
Czech: 'cs',
Danish: 'da',
Dutch: 'nl',
English: 'en',
Estonian: 'et',
Filipino: 'tl',
Finnish: 'fi',
French: 'fr',
German: 'de',
Greek: 'el',
Hebrew: 'iw',
Hindi: 'hi',
Hungarian: 'hu',
Icelandic: 'is',
Indonesian: 'id',
Italian: 'it',
Japanese: 'ja',
Korean: 'ko',
Latvian: 'lv',
Lithuanian: 'lt',
Norwegian: 'no',
Polish: 'pl',
Portuguese: 'pt',
Romanian: 'ro',
Russian: 'ru',
Serbian: 'sr',
Slovak: 'sk',
Slovenian: 'sl',
Spanish: 'es',
Swedish: 'sv',
Thai: 'th',
Turkish: 'tr',
Ukrainian: 'uk',
Urdu: 'ur',
Vietnamese: 'vi',
},
DefRSZ = 'large';
var entry;
CmdUtils.CreateCommand({
name: Name,
icon: Google +'favicon.ico',
takes: {'?': noun_arb_text},
modifiers: {
at: noun('size', 'icon small medium large xlarge xxlarge huge'),
as: noun('type', 'news face clipart lineart photo'),
of: noun('tone', 'mono gray color'),
in: noun('lang', Langs),
'#': noun('safe', 'active moderate off'),
},
description: ''+<><a href={GImage}>Google Image</a> + keyboard navigation</>,
help:
[[<a href={Google +'language_tools'}>Language</a>,
PLang, Langs, ''],
[<a href={Google +'safesearch_help.html'}>Safe Search</a>,
PSafe, {active: 'active', moderate: 'moderate', off: 'off'}, 'moderate'],
[<>Result Size</>, PSize, {4: 'small', 8: 'large'}, DefRSZ],
].reduce(function(form, [name, pref, dict, defv]){
var select = <select onchange={
'Application.prefs.setValue("'+ pref +'", this.value)'}/>;
defv = prefs.getValue(pref, defv);
for(var [key, val] in Iterator(dict)){
var opt = <option value={val}>{key}</option>;
if(val === defv) opt.@selected = 'selected';
select.* += opt;
}
form.ul.* += <li>{name}{select}</li>;
return form;
}, <form>Options<ul style="list-style:none"/></form>) +'',
execute: function(dob, mod){
Utils.openUrlInBrowser(GImage +'images'+
Utils.paramsToString(params(dob, mod)));
},
preview: function(pbl, dob, mod, index){
var prms = params(dob, mod), me = this,
$p = jQuery(pbl), $c = $p.find(ID);
if(!$c[0]) $c = $p.html(Base).find(ID), entry = '';
if(!prms.q || entry === (entry = index + uneval(prms))) return;
$c.addClass('loading');
prms.start = index << ((prms.rsz = prefs.getValue(PSize, DefRSZ))
=== 'small' ? 2 : 3);
CmdUtils.previewAjax(pbl, {
url: 'http://www.google.com/uds/GimageSearch',
data: prms,
dataType: 'json',
success: function({responseStatus: stat, responseData: data}){
if(stat !== 200) return oops(
$c, stat === 400 ? 'Out of page range.' : 'Error: '+ stat);
var {results, cursor} = data;
if(!results.length) return oops($c, 'No results.');
($c.removeClass().html(render(results, cursor))
.find('.b_open').each(function(i){
tie(this, function(){
this.disabled = true;
Utils.openUrlInBrowser(results[i].unescapedUrl);
})}).end()
.find('.b_page').each(function(){
this.disabled || tie(this, function(){
me.preview(pbl, dob, mod, this.value - 1);
})}).end());
},
error: function(x) oops($c, x.status, x.statusText),
});
},
previewDelay: 333,
author: 'satyr'.link('http://d.hatena.ne.jp/murky-satyr'), license: 'MIT',
});
function noun(name, dict){
if(typeof dict === 'string')
dict = dict.match(/\S+/g).reduce(function(d, w) d[w] = d, {});
return {_name: name, suggest: suggest,
list: [{text: k, data: dict[k], summary: k} for(k in dict)]}
}
function suggest(txt, htm, cb, sx){
if(sx || !txt) return [];
try { var re = RegExp(txt, 'i') } catch(_){ re = /(?:)/ }
var sg = this.list.filter(function(x) re.test(x.text));
return sg.length ? sg : this.list;
}
function params({text}, mod)({
q: jQuery.trim(text), ie: 'utf-8', v: '1.0',
imgsz: mod.at.text || '',
imgtype: mod.as.text || '',
imgc: mod.of.text || '',
hl: mod.in.data || prefs.getValue(PLang, ''),
safe: mod['#'].text || prefs.getValue(PSafe, ''),
});
function tie(it, fn){
it.addEventListener('focus', function(e){
this.blur(), e.preventDefault(), e.stopPropagation();
fn.call(it, it);
}, true);
}
function oops($c){
$c.removeClass('loading').addClass('error')
.text(Array.slice(arguments, 1).join(' '));
}
function render(res, cur){
with(cur) var a2h, i2p, gmg = [
'<div class="count"><a href="', cur.moreResultsUrl, '" accesskey="0">',
(cur.estimatedResultCount +'').match(/.+?(?=(?:...)*$)/g).join(','),
'</a></div><div class="pagination">',
paginates(cur.currentPageIndex + 1, cur.pages.length), '</div><ul>'];
for(var i in res) with(res[i]) gmg.push(
'<li style="width:', tbWidth, 'px"><label for="', i, '"><button id="', i,
'" class="b_open" accesskey="', a2h = 'ABCDEFGH'[i], '">', a2h,
'</button><img src="', tbUrl, '" alt="', contentNoFormatting,
'"></label><span class="size">', width, 'x', height,
'</span> <a class="url" href="', originalContextUrl,
'" accesskey="', i2p = 'IJKLMNOP'[i], '">', visibleUrl,
'</a> <kbd>', i2p, '</kbd></li>');
return gmg.join('') +'</ul>';
}
function paginates(cpi, len)(
btn('&lt;,', ',', cpi <= 1, cpi - 1) +
[btn(++i, i, cpi === i, i) for(i in Array(len)+0)].join('') +
btn('.&gt;', '.', cpi >= len, cpi + 1));
function btn(txt, key, dis, val)(
'<button class="b_page" accesskey="'+ key +'" value="'+ val +
(dis ? '" disabled="disabled">' : '">') + txt +'</button>');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment