group each plugin in its own folder

This commit is contained in:
jfh
2020-09-06 08:32:10 +02:00
parent caa4fe38cc
commit cfb3620d3a
322 changed files with 519 additions and 956 deletions

View File

@@ -0,0 +1,538 @@
/**
* @file ext-imagelib.js
*
* @license MIT
*
* @copyright 2010 Alexis Deveria
*
*/
export default {
name: 'imagelib',
async init ({$, decode64, dropXMLInternalSubset}) {
const svgEditor = this;
// eslint-disable-next-line node/no-unsupported-features/es-syntax
const {default: imagelibStrings} = await import(`./locale/${svgEditor.curPrefs.lang}.js`);
const {uiStrings, canvas: svgCanvas} = svgEditor;
const allowedImageLibOrigins = imagelibStrings.imgLibs.map(({url}) => {
try {
return new URL(url).origin;
} catch (err) {
return location.origin;
}
});
/**
*
* @returns {void}
*/
function closeBrowser () {
$('#imgbrowse_holder').hide();
document.activeElement.blur(); // make sure focus is the body to correct issue #417
}
/**
* @param {string} url
* @returns {void}
*/
function importImage (url) {
const newImage = svgCanvas.addSVGElementFromJson({
element: 'image',
attr: {
x: 0,
y: 0,
width: 0,
height: 0,
id: svgCanvas.getNextId(),
style: 'pointer-events:inherit'
}
});
svgCanvas.clearSelection();
svgCanvas.addToSelection([newImage]);
svgCanvas.setImageURL(url);
}
const pending = {};
let mode = 's';
let multiArr = [];
let transferStopped = false;
let preview, submit;
/**
* Contains the SVG to insert.
* @typedef {PlainObject} ImageLibMessage
* @property {"imagelib"} namespace Required to distinguish from any other messages of app.
* @property {string} href Set to same value as previous `ImageLibMetaMessage` `id`.
* @property {string} data The response (as an SVG string or URL)
*/
/**
* Used for setting meta-data before images are retrieved.
* @typedef {PlainObject} ImageLibMetaMessage
* @property {"imagelib"} namespace Required to distinguish from any other messages of app.
* @property {string} name If the subsequent response is an SVG string or if `preview_url`
* is present, will be used as the title for the preview image. When an
* SVG string is present, will default to the first `<title>`'s contents or
* "(SVG #<Length of response>)" if none is present. Otherwise, if `preview_url`
* is present, will default to the empty string. Though `name` may be falsy,
* it is always expected to be present for meta messages.
* @property {string} id Identifier (the expected `href` for a subsequent response message);
* used for ensuring the subsequent response can be tied to this `ImageLibMetaMessage` object.
* @property {string} [preview_url] When import mode is multiple, used to set an image
* source along with the name/title. If the subsequent response is an SVG string
* and there is no `preview_url`, the default will just be to show the
* name/title. If the response is not an SVG string, the default will be to
* show that response (i.e., the URL).
* @property {string} entry Set automatically with div holding retrieving
* message (until ready to delete)
* @todo Should use a separate Map instead of `entry`
*/
/**
* @param {PlainObject} cfg
* @param {string} cfg.origin
* @param {ImageLibMetaMessage|ImageLibMessage|string} cfg.data String is deprecated when parsed to JSON `ImageLibMessage`
* @returns {void}
*/
async function onMessage ({origin, data: response}) { // eslint-disable-line no-shadow
if (!response || !['string', 'object'].includes(typeof response)) {
// Do nothing
return;
}
let id;
let type;
try {
// Todo: This block can be removed (and the above check changed to
// insist on an object) if embedAPI moves away from a string to
// an object (if IE9 support not needed)
response = typeof response === 'object' ? response : JSON.parse(response);
if (response.namespace !== 'imagelib') {
return;
}
if (!allowedImageLibOrigins.includes('*') && !allowedImageLibOrigins.includes(origin)) {
// Todo: Surface this error to user?
console.log(`Origin ${origin} not whitelisted for posting to ${window.origin}`); // eslint-disable-line no-console
return;
}
const hasName = 'name' in response;
const hasHref = 'href' in response;
if (!hasName && transferStopped) {
transferStopped = false;
return;
}
if (hasHref) {
id = response.href;
response = response.data;
}
// Hide possible transfer dialog box
$('#dialog_box').hide();
type = hasName
? 'meta'
: response.charAt(0);
} catch (e) {
// This block is for backward compatibility (for IAN and Openclipart);
// should otherwise return
if (typeof response === 'string') {
const char1 = response.charAt(0);
if (char1 !== '{' && transferStopped) {
transferStopped = false;
return;
}
if (char1 === '|') {
const secondpos = response.indexOf('|', 1);
id = response.substr(1, secondpos - 1);
response = response.substr(secondpos + 1);
type = response.charAt(0);
}
}
}
let entry, curMeta, svgStr, imgStr;
switch (type) {
case 'meta': {
// Metadata
transferStopped = false;
curMeta = response;
// Should be safe to add dynamic property as passed metadata
pending[curMeta.id] = curMeta; // lgtm [js/remote-property-injection]
const name = (curMeta.name || 'file');
const message = uiStrings.notification.retrieving.replace('%s', name);
if (mode !== 'm') {
await $.process_cancel(message);
transferStopped = true;
// Should a message be sent back to the frame?
$('#dialog_box').hide();
} else {
entry = $('<div>').text(message).data('id', curMeta.id);
preview.append(entry);
curMeta.entry = entry;
}
return;
}
case '<':
svgStr = true;
break;
case 'd': {
if (response.startsWith('data:image/svg+xml')) {
const pre = 'data:image/svg+xml;base64,';
const src = response.substring(pre.length);
response = decode64(src);
svgStr = true;
break;
} else if (response.startsWith('data:image/')) {
imgStr = true;
break;
}
}
// Else fall through
default:
// TODO: See if there's a way to base64 encode the binary data stream
// const str = 'data:;base64,' + svgedit.utilities.encode64(response, true);
// Assume it's raw image data
// importImage(str);
// Don't give warning as postMessage may have been used by something else
if (mode !== 'm') {
closeBrowser();
} else {
pending[id].entry.remove();
}
// await $.alert('Unexpected data was returned: ' + response, function() {
// if (mode !== 'm') {
// closeBrowser();
// } else {
// pending[id].entry.remove();
// }
// });
return;
}
switch (mode) {
case 's':
// Import one
if (svgStr) {
svgCanvas.importSvgString(response);
} else if (imgStr) {
importImage(response);
}
closeBrowser();
break;
case 'm': {
// Import multiple
multiArr.push([(svgStr ? 'svg' : 'img'), response]);
curMeta = pending[id];
let title;
if (svgStr) {
if (curMeta && curMeta.name) {
title = curMeta.name;
} else {
// Try to find a title
// `dropXMLInternalSubset` is to help prevent the billion laughs attack
const xml = new DOMParser().parseFromString(dropXMLInternalSubset(response), 'text/xml').documentElement; // lgtm [js/xml-bomb]
title = $(xml).children('title').first().text() || '(SVG #' + response.length + ')';
}
if (curMeta) {
preview.children().each(function () {
if ($(this).data('id') === id) {
if (curMeta.preview_url) {
$(this).html(
$('<span>').append(
$('<img>').attr('src', curMeta.preview_url),
title
)
);
} else {
$(this).text(title);
}
submit.removeAttr('disabled');
}
});
} else {
preview.append(
$('<div>').text(title)
);
submit.removeAttr('disabled');
}
} else {
if (curMeta && curMeta.preview_url) {
title = curMeta.name || '';
entry = $('<span>').append(
$('<img>').attr('src', curMeta.preview_url),
title
);
} else {
entry = $('<img>').attr('src', response);
}
if (curMeta) {
preview.children().each(function () {
if ($(this).data('id') === id) {
$(this).html(entry);
submit.removeAttr('disabled');
}
});
} else {
preview.append($('<div>').append(entry));
submit.removeAttr('disabled');
}
}
break;
} case 'o': {
// Open
if (!svgStr) { break; }
closeBrowser();
const ok = await svgEditor.openPrep();
if (!ok) { return; }
svgCanvas.clear();
svgCanvas.setSvgString(response);
// updateCanvas();
break;
}
}
}
// Receive `postMessage` data
window.addEventListener('message', onMessage, true);
/**
* @param {boolean} show
* @returns {void}
*/
function toggleMulti (show) {
$('#lib_framewrap, #imglib_opts').css({right: (show ? 200 : 10)});
if (!preview) {
preview = $('<div id=imglib_preview>').css({
position: 'absolute',
top: 45,
right: 10,
width: 180,
bottom: 45,
background: '#fff',
overflow: 'auto'
}).insertAfter('#lib_framewrap');
submit = $('<button disabled>Import selected</button>')
.appendTo('#imgbrowse')
.on('click touchend', function () {
$.each(multiArr, function (i) {
const type = this[0];
const data = this[1];
if (type === 'svg') {
svgCanvas.importSvgString(data);
} else {
importImage(data);
}
svgCanvas.moveSelectedElements(i * 20, i * 20, false);
});
preview.empty();
multiArr = [];
$('#imgbrowse_holder').hide();
}).css({
position: 'absolute',
bottom: 10,
right: -10
});
}
preview.toggle(show);
submit.toggle(show);
}
/**
*
* @returns {void}
*/
function showBrowser () {
let browser = $('#imgbrowse');
if (!browser.length) {
$('<div id=imgbrowse_holder><div id=imgbrowse class=toolbar_button>' +
'</div></div>').insertAfter('#svg_docprops');
browser = $('#imgbrowse');
const allLibs = imagelibStrings.select_lib;
const libOpts = $('<ul id=imglib_opts>').appendTo(browser);
const frame = $('<iframe src="javascript:0"/>').prependTo(browser).hide().wrap('<div id=lib_framewrap>');
const header = $('<h1>').prependTo(browser).text(allLibs).css({
position: 'absolute',
top: 0,
left: 0,
width: '100%'
});
const cancel = $('<button>' + uiStrings.common.cancel + '</button>')
.appendTo(browser)
.on('click touchend', function () {
$('#imgbrowse_holder').hide();
}).css({
position: 'absolute',
top: 5,
right: -10
});
const leftBlock = $('<span>').css({position: 'absolute', top: 5, left: 10}).appendTo(browser);
const back = $('<button hidden>' + imagelibStrings.show_list + '</button>')
.appendTo(leftBlock)
.on('click touchend', function () {
frame.attr('src', 'about:blank').hide();
libOpts.show();
header.text(allLibs);
back.hide();
}).css({
'margin-right': 5
}).hide();
/* const type = */ $('<select><option value=s>' +
imagelibStrings.import_single + '</option><option value=m>' +
imagelibStrings.import_multi + '</option><option value=o>' +
imagelibStrings.open + '</option></select>').appendTo(leftBlock).change(function () {
mode = $(this).val();
switch (mode) {
case 's':
case 'o':
toggleMulti(false);
break;
case 'm':
// Import multiple
toggleMulti(true);
break;
}
}).css({
'margin-top': 10
});
cancel.prepend($.getSvgIcon('cancel', true));
back.prepend($.getSvgIcon('tool_imagelib', true));
imagelibStrings.imgLibs.forEach(function ({name, url, description}) {
$('<li>')
.appendTo(libOpts)
.text(name)
.on('click touchend', function () {
frame.attr(
'src',
url
).show();
header.text(name);
libOpts.hide();
back.show();
}).append(`<span>${description}</span>`);
});
} else {
$('#imgbrowse_holder').show();
}
}
const buttons = [{
id: 'tool_imagelib',
type: 'app_menu', // _flyout
icon: 'imagelib.png',
position: 4,
events: {
mouseup: showBrowser
}
}];
return {
svgicons: 'ext-imagelib.xml',
buttons: imagelibStrings.buttons.map((button, i) => {
return Object.assign(buttons[i], button);
}),
callback () {
$('<style>').text(
'#imgbrowse_holder {' +
'position: absolute;' +
'top: 0;' +
'left: 0;' +
'width: 100%;' +
'height: 100%;' +
'background-color: rgba(0, 0, 0, .5);' +
'z-index: 5;' +
'}' +
'#imgbrowse {' +
'position: absolute;' +
'top: 25px;' +
'left: 25px;' +
'right: 25px;' +
'bottom: 25px;' +
'min-width: 300px;' +
'min-height: 200px;' +
'background: #B0B0B0;' +
'border: 1px outset #777;' +
'}' +
'#imgbrowse h1 {' +
'font-size: 20px;' +
'margin: .4em;' +
'text-align: center;' +
'}' +
'#lib_framewrap,' +
'#imgbrowse > ul {' +
'position: absolute;' +
'top: 45px;' +
'left: 10px;' +
'right: 10px;' +
'bottom: 10px;' +
'background: white;' +
'margin: 0;' +
'padding: 0;' +
'}' +
'#imgbrowse > ul {' +
'overflow: auto;' +
'}' +
'#imgbrowse > div {' +
'border: 1px solid #666;' +
'}' +
'#imglib_preview > div {' +
'padding: 5px;' +
'font-size: 12px;' +
'}' +
'#imglib_preview img {' +
'display: block;' +
'margin: 0 auto;' +
'max-height: 100px;' +
'}' +
'#imgbrowse li {' +
'list-style: none;' +
'padding: .5em;' +
'background: #E8E8E8;' +
'border-bottom: 1px solid #B0B0B0;' +
'line-height: 1.2em;' +
'font-style: sans-serif;' +
'}' +
'#imgbrowse li > span {' +
'color: #666;' +
'font-size: 15px;' +
'display: block;' +
'}' +
'#imgbrowse li:hover {' +
'background: #FFC;' +
'cursor: pointer;' +
'}' +
'#imgbrowse iframe {' +
'width: 100%;' +
'height: 100%;' +
'border: 0;' +
'}'
).appendTo('head');
}
};
}
};

View File

@@ -0,0 +1,49 @@
/* globals jQuery */
const $ = jQuery;
$('a').click(function () {
const {href} = this;
const target = window.parent;
const post = (message) => {
// Todo: Make origin customizable as set by opening window
// Todo: If dropping IE9, avoid stringifying
target.postMessage(JSON.stringify({
namespace: 'imagelib',
...message
}), '*');
};
// Convert Non-SVG images to data URL first
// (this could also have been done server-side by the library)
// Send metadata (also indicates file is about to be sent)
post({
name: $(this).text(),
id: href
});
if (!href.includes('.svg')) {
const img = new Image();
img.addEventListener('load', function () {
const canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
// load the raster image into the canvas
canvas.getContext('2d').drawImage(this, 0, 0);
// retrieve the data: URL
let data;
try {
data = canvas.toDataURL();
} catch (err) {
// This fails in Firefox with `file:///` URLs :(
// Todo: This could use a generic alert library instead
alert('Data URL conversion failed: ' + err); // eslint-disable-line no-alert
data = '';
}
post({href, data});
});
img.src = href;
} else {
// Do ajax request for image's href value
$.get(href, function (data) {
post({href, data});
}, 'html'); // 'html' is necessary to keep returned data as a string
}
return false;
});

View File

@@ -0,0 +1,33 @@
export default {
select_lib: 'Select an image library',
show_list: 'Show library list',
import_single: 'Import single',
import_multi: 'Import multiple',
open: 'Open as new document',
buttons: [
{
title: 'Bilder-Bibliothek'
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
/*
// See message in "en" locale for further details
,
{
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,38 @@
export default {
select_lib: 'Select an image library',
show_list: 'Show library list',
import_single: 'Import single',
import_multi: 'Import multiple',
open: 'Open as new document',
buttons: [
{
title: 'Image library'
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
// The site is no longer using our API, and they have added an
// `X-Frame-Options` header which prevents our usage cross-origin:
// Getting messages like this in console:
// Refused to display 'https://openclipart.org/detail/307176/sign-bike' in a frame
// because it set 'X-Frame-Options' to 'sameorigin'.
// url: 'https://openclipart.org/svgedit',
// However, they do have a custom API which we are using here:
/*
{
name: 'Openclipart',
url: '{path}imagelib/openclipart.html',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,33 @@
export default {
select_lib: "Choisir une bibliothèque d'images",
show_list: 'show_list',
import_single: 'import_single',
import_multi: 'import_multi',
open: 'open',
buttons: [
{
title: "Bibliothèque d'images"
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
/*
// See message in "en" locale for further details
,
{
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,33 @@
export default {
select_lib: 'Select an image library',
show_list: 'Show library list',
import_single: 'Import single',
import_multi: 'Import multiple',
open: 'Open as new document',
buttons: [
{
title: 'Biblioteka obrazów'
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
/*
// See message in "en" locale for further details
,
{
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,33 @@
export default {
select_lib: 'Select an image library',
show_list: 'Show library list',
import_single: 'Import single',
import_multi: 'Import multiple',
open: 'Open as new document',
buttons: [
{
title: 'Biblioteca de Imagens'
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
/*
// See message in "en" locale for further details
,
{
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,33 @@
export default {
select_lib: 'Select an image library',
show_list: 'Show library list',
import_single: 'Import single',
import_multi: 'Import multiple',
open: 'Open as new document',
buttons: [
{
title: 'Bibliotecă de Imagini'
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
/*
// See message in "en" locale for further details
,
{
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,33 @@
export default {
select_lib: 'Select an image library',
show_list: 'Show library list',
import_single: 'Import single',
import_multi: 'Import multiple',
open: 'Open as new document',
buttons: [
{
title: 'Knižnica obrázkov'
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
/*
// See message in "en" locale for further details
,
{
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,33 @@
export default {
select_lib: 'Select an image library',
show_list: 'Show library list',
import_single: 'Import single',
import_multi: 'Import multiple',
open: 'Open as new document',
buttons: [
{
title: 'Knjižnica slik'
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
/*
// See message in "en" locale for further details
,
{
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,33 @@
export default {
select_lib: 'Select an image library',
show_list: 'Show library list',
import_single: 'Import single',
import_multi: 'Import multiple',
open: 'Open as new document',
buttons: [
{
title: '图像库'
}
],
imgLibs: [
{
name: 'Demo library (local)',
url: '{path}imagelib/index.html',
description: 'Demonstration library for SVG-edit on this server'
},
{
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
}
/*
// See message in "en" locale for further details
,
{
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
]
};

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>-</title>
<link rel="icon" type="image/png" href="../../images/logo.png" />
<!-- Lacking browser support -->
<script nomodule="" src="../../redirect-on-no-module-support.js"></script>
<script type="module" src="../../redirect-on-lacking-support.js"></script>
<!-- Browser polyfills -->
<script src="../../external/dom-polyfill/dom-polyfill.js"></script>
<!-- ES6+ polyfills (Babel) -->
<script src="../../external/core-js-bundle/minified.js"></script>
<script src="../../external/regenerator-runtime/runtime.js"></script>
<script type="module" src="openclipart.js"></script>
</head>
<body>
</body>
</html>

View File

@@ -0,0 +1,346 @@
import {jml, body, nbsp} from '../../../external/jamilih/jml-es.js';
import $ from '../../../external/query-result/esm/index.js';
import {manipulation} from '../../../external/qr-manipulation/dist/index-es.js';
manipulation($, jml);
const baseAPIURL = 'https://openclipart.org/search/json/';
const jsVoid = 'javascript: void(0);'; // eslint-disable-line no-script-url
/**
* Shows results after query submission.
* @param {string} url
* @returns {Promise<void>}
*/
async function processResults (url) {
/**
* @param {string} query
* @returns {external:JamilihArray}
*/
function queryLink (query) {
return ['a', {
href: jsVoid,
dataset: {value: query},
$on: {click (e) {
e.preventDefault();
const {value} = this.dataset;
$('#query')[0].$set(value);
$('#openclipart')[0].$submit();
}}
}, [query]];
}
const r = await fetch(url);
const json = await r.json();
// console.log('json', json);
if (!json || json.msg !== 'success') {
// Todo: This could use a generic alert library instead
alert('There was a problem downloading the results'); // eslint-disable-line no-alert
return;
}
const {payload, info: {
results: numResults,
pages,
current_page: currentPage
}} = json;
// $('#page')[0].value = currentPage;
// $('#page')[0].max = pages;
// Unused properties:
// - `svg_filesize` always 0?
// - `dimensions: {
// png_thumb: {width, height},
// png_full_lossy: {width, height}
// }` object of relevance?
// - No need for `tags` with `tags_array`
// - `svg`'s: `png_thumb`, `png_full_lossy`, `png_2400px`
const semiColonSep = '; ' + nbsp;
$('#results').jml('div', [
['span', [
'Number of results: ',
numResults
]],
semiColonSep,
['span', [
'page ',
currentPage,
' out of ',
pages
]],
...payload.map(({
title, description, id,
uploader, created,
svg: {url: svgURL},
detail_link: detailLink,
tags_array: tagsArray,
downloaded_by: downloadedBy,
total_favorites: totalFavorites
}) => {
const imgHW = '100px';
const colonSep = ': ' + nbsp;
return ['div', [
['button', {style: 'margin-right: 8px; border: 2px solid black;', dataset: {id, value: svgURL}, $on: {
async click (e) {
e.preventDefault();
const {value: svgurl} = this.dataset;
// console.log('this', id, svgurl);
const post = (message) => {
// Todo: Make origin customizable as set by opening window
// Todo: If dropping IE9, avoid stringifying
window.parent.postMessage(JSON.stringify({
namespace: 'imagelib',
...message
}), '*');
};
// Send metadata (also indicates file is about to be sent)
post({
name: title,
id: svgurl
});
const result = await fetch(svgurl);
const svg = await result.text();
// console.log('url and svg', svgurl, svg);
post({
href: svgurl,
data: svg
});
}
}}, [
// If we wanted interactive versions despite security risk:
// ['object', {data: svgURL, type: 'image/svg+xml'}]
['img', {src: svgURL, style: `width: ${imgHW}; height: ${imgHW};`}]
]],
['b', [title]],
' ',
['i', [description]],
' ',
['span', [
'(ID: ',
['a', {
href: jsVoid,
dataset: {value: id},
$on: {
click (e) {
e.preventDefault();
const {value} = this.dataset;
$('#byids')[0].$set(value);
$('#openclipart')[0].$submit();
}
}
}, [id]],
')'
]],
' ',
['i', [
['a', {
href: detailLink,
target: '_blank'
}, ['Details']]
]],
['br'],
['span', [
['u', ['Uploaded by']], colonSep,
queryLink(uploader),
semiColonSep
]],
['span', [
['u', ['Download count']], colonSep,
downloadedBy,
semiColonSep
]],
['span', [
['u', ['Times used as favorite']], colonSep,
totalFavorites,
semiColonSep
]],
['span', [
['u', ['Created date']], colonSep,
created
]],
['br'],
['u', ['Tags']], colonSep,
...tagsArray.map((tag) => {
return ['span', [
' ',
queryLink(tag)
]];
})
]];
}),
['br'], ['br'],
(currentPage === 1 || pages <= 2
? ''
: ['span', [
['a', {
href: jsVoid,
$on: {
click (e) {
e.preventDefault();
$('#page')[0].value = 1;
$('#openclipart')[0].$submit();
}
}
}, ['First']],
' '
]]
),
(currentPage === 1
? ''
: ['span', [
['a', {
href: jsVoid,
$on: {
click (e) {
e.preventDefault();
$('#page')[0].value = currentPage - 1;
$('#openclipart')[0].$submit();
}
}
}, ['Prev']],
' '
]]
),
(currentPage === pages
? ''
: ['span', [
['a', {
href: jsVoid,
$on: {
click (e) {
e.preventDefault();
$('#page')[0].value = currentPage + 1;
$('#openclipart')[0].$submit();
}
}
}, ['Next']],
' '
]]
),
(currentPage === pages || pages <= 2
? ''
: ['span', [
['a', {
href: jsVoid,
$on: {
click (e) {
e.preventDefault();
$('#page')[0].value = pages;
$('#openclipart')[0].$submit();
}
}
}, ['Last']],
' '
]]
)
]);
}
jml('div', [
['style', [
`.control {
padding-top: 10px;
}`
]],
['form', {
id: 'openclipart',
$custom: {
async $submit () {
const url = new URL(baseAPIURL);
[
'query', 'sort', 'amount', 'page', 'byids'
].forEach((prop) => {
const {value} = $('#' + prop)[0];
if (value) {
url.searchParams.set(prop, value);
}
});
await processResults(url);
}
},
$on: {
submit (e) {
e.preventDefault();
this.$submit();
}
}
}, [
// Todo: i18nize
['fieldset', [
['legend', ['Search terms']],
['div', {class: 'control'}, [
['label', [
'Query (Title, description, uploader, or tag): ',
['input', {id: 'query', name: 'query', placeholder: 'cat', $custom: {
$set (value) {
$('#byids')[0].value = '';
this.value = value;
}
}, $on: {
change () {
$('#byids')[0].value = '';
}
}}]
]]
]],
['br'],
' OR ',
['br'],
['div', {class: 'control'}, [
['label', [
'IDs (single or comma-separated): ',
['input', {id: 'byids', name: 'ids', placeholder: '271380, 265741', $custom: {
$set (value) {
$('#query')[0].value = '';
this.value = value;
}
}, $on: {
change () {
$('#query')[0].value = '';
}
}}]
]]
]]
]],
['fieldset', [
['legend', ['Configuring results']],
['div', {class: 'control'}, [
['label', [
'Sort by: ',
['select', {id: 'sort'}, [
// Todo: i18nize first values
['Date', 'date'],
['Downloads', 'downloads'],
['Favorited', 'favorites']
].map(([text, value = text]) => {
return ['option', {value}, [text]];
})]
]]
]],
['div', {class: 'control'}, [
['label', [
'Results per page: ',
['input', {
id: 'amount', name: 'amount', value: 10,
type: 'number', min: 1, max: 200, step: 1, pattern: '\\d+'}]
]]
]],
['div', {class: 'control'}, [
['label', [
'Page number: ',
['input', {
// max: 1, // We'll change this based on available results
id: 'page', name: 'page', value: 1, style: 'width: 40px;',
type: 'number', min: 1, step: 1, pattern: '\\d+'
}]
]]
]]
]],
['div', {class: 'control'}, [
['input', {type: 'submit'}]
]]
]],
['div', {id: 'results'}]
], body);

View File

@@ -0,0 +1,12 @@
<svg width="137" height="137" xmlns="http://www.w3.org/2000/svg">
<title>Cool smiley</title>
<path fill="url(#svg_4)" stroke="#000000" stroke-width="3" d="m32.18682,97.71674q36.3159,24.94076 72.54585,0m-64.67542,-49.25576c0,-3.8554 3.12526,-6.98079 6.98068,-6.98079c3.85449,0 6.97872,3.12539 6.97872,6.98079c0,3.85346 -3.12423,6.97867 -6.97872,6.97867c-3.85542,0 -6.98068,-3.12521 -6.98068,-6.97867m42.93047,0c0,-3.8554 3.12529,-6.98079 6.97963,-6.98079c3.8544,0 6.97971,3.12539 6.97971,6.98079c0,3.85346 -3.12531,6.97867 -6.97971,6.97867c-3.85434,0 -6.97963,-3.12521 -6.97963,-6.97867m-81.48596,20.036l0,0c0,-37.00197 29.99679,-66.99892 67.00095,-66.99892c37.00303,0 66.99998,29.99695 66.99998,66.99892c0,37.00409 -29.99695,67.00101 -66.99998,67.00101c-37.00416,0 -67.00095,-29.99692 -67.00095,-67.00101zm0,0l0,0c0,-37.00197 29.99679,-66.99892 67.00095,-66.99892c37.00303,0 66.99998,29.99695 66.99998,66.99892c0,37.00409 -29.99695,67.00101 -66.99998,67.00101c-37.00416,0 -67.00095,-29.99692 -67.00095,-67.00101z" id="svg_1"/>
<path id="svg_5" d="m23.84005,41.03445l17.57052,0l5.42937,-19.67914l5.42941,19.67914l17.5706,0l-14.21488,12.16242l5.42982,19.67939l-14.21495,-12.16281l-14.21489,12.16281l5.42991,-19.67939l-14.21491,-12.16242l0,0z" stroke-width="3" fill="#000000"/>
<path id="svg_6" d="m65.84005,41.03445l17.57052,0l5.42937,-19.67914l5.42941,19.67914l17.5706,0l-14.21487,12.16242l5.42982,19.67939l-14.21496,-12.1628l-14.2149,12.1628l5.42992,-19.67939l-14.21491,-12.16242l0,0z" stroke-width="3" fill="#000000"/>
<defs>
<linearGradient y2="0.25391" x2="0.46484" y1="0.94922" x1="0.44531" id="svg_4">
<stop stop-color="#ff0000" offset="0"/>
<stop stop-color="#ffff00" offset="1"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB