/** * Where the app's state comes from and goes to: the query string it loads * and the permalink it writes, gists it creates and updates, downloads. * Mixed onto ShExBaseApp; see ShExBaseApp.js. * * This is doc/ShExBaseApp-links.js's source (tsconfig.app.json compiles src/app/ into * doc/); edit here and run `npm run build`. */ mixin(ShExBaseApp, { /** * Load URL search parameters */ async loadSearchParameters() { // don't overwrite if we arrived here from going back and forth in history if (this.Caches.inputSchema.selection.val() !== "" || this.Caches.inputData.selection.val() !== "") return Promise.resolve(); const iface = this.parseQueryString(location.search); this.toggleControlsArrow("down"); $(".manifest li").text("no manifest schemas loaded"); if ("examples" in iface) { // deprecated ?examples= interface iface.manifestURL = iface.examples; delete iface.examples; } if (!("manifest" in iface) && !("manifestURL" in iface)) { iface.manifestURL = ["../examples/manifest.json"]; } // a gist-hosted manifest can be edited in place: reveal Menu → "/Update" const gistManifest = "manifestURL" in iface && iface.manifestURL[0].match(/^https:\/\/gist\.githubusercontent\.com\/([^\/]+)\/([0-9a-f]+)\/raw\/(?:([0-9a-f]+)\/)?/); if (gistManifest) { this.loadedGist = { owner: gistManifest[1], id: gistManifest[2], sha: gistManifest[3] }; $("#updateGist").show(); } // Load all known query parameters. Save load results into array like: /* [ [ "data", { "skipped": "skipped" } ], [ "manifest", { "fromUrl": { "url": "http://...", "data": "..." } } ], ] */ // Plugins first, and one at a time: what one adds -- panes, and the // parameters and manifest keys that fill them -- has to be in // QueryParams before the walk below reads QueryParams. ?plugin= and // ?pluginURL= are the same thing said two ways; a permalink writes the // second, and a person writes whichever they remember. await this.loadPlugins([].concat(iface.pluginURL || [], iface.plugin || [])); const loadedAsArray = await Promise.all(this.QueryParams.map(async (input) => { const label = input.queryStringParm; const parm = label; if (input.earlyLoad) return [label, { skipped: "skipped" }]; if (parm + "URL" in iface) { const url = iface[parm + "URL"][0]; if (url.length > 0) { // manifest= loads no manifest // !!! set anyways in asyncGet? input.cache.url = url; // all fooURL query parms are caches. try { const got = await input.cache.asyncGet(url); return [label, { fromUrl: got }]; } catch (e) { if ("fail" in input) { input.fail(e); } else { input.location.val(e.message); } this.resultsWidget.append($("
").text(e).addClass("error")); return [label, { loadFailure: e instanceof Error ? e : Error(e) }]; } ; } } else if (parm in iface) { const prepend = input.location.prop("tagName") === "TEXTAREA" ? input.location.val() : ""; const value = prepend + (input.normalize ? input.normalize((parm === "data" ? iface[parm].slice(0, 1) : iface[parm]).join("")) : (parm === "data" ? iface[parm].slice(0, 1) : iface[parm]).join("")); const origValue = input.location.val(); try { if ("cache" in input) { await input.cache.set(value, location.href); } else { input.location.val(prepend + value); if (input.location.val() === null) throw Error(`Unable to set value to ${prepend + value}`); } return [label, { literal: value }]; } catch (e) { input.location.val(origValue); if ("fail" in input) { input.fail(e); } this.resultsWidget.append($("").text("error setting " + label + ":\n" + e + "\n" + value).addClass("error")); return [label, { failure: e }]; } } else if ("deflt" in input) { input.location.val(input.deflt); return [label, { deflt: "deflt" }]; // flag that it was a default } return [label, { skipped: "skipped" }]; })); // convert loaded array into Object: /* { "data": { "skipped": "skipped" }, "manifest": { "fromUrl": { "url": "http://...", "data": "..." } }, } */ const loaded = loadedAsArray.reduce((acc, fromArray) => { acc[fromArray[0]] = fromArray[1]; return acc; }, {}); // A data source may hold several documents: `data=` repeats, once per // pane in the order they are shown. With `dataURL=` the first document // came from there and the `data=` values are the ones after it. if (iface.data && this.neighborhoods && iface.data.length > ("dataURL" in iface ? 0 : 1)) this.neighborhoods.setDocuments(("dataURL" in iface ? [this.Caches.inputData.selection.val()] : []) .concat(iface.data)); // Parse the shape-map using the prefixes and base. What it reports is // rendered where the map is; this is called for what it fills in -- and // awaited, so that a link finishes loading with the map it named ready // to validate rather than still being built. (It reports its errors // rather than throwing them, so a bad map is a message, not a failed // load.) if ($("#queryMap").val().trim().length > 0) await this.Caches.shapeMap.copyQueryMapToEditMap(); else this.Caches.shapeMap.makeFreshEditMap(); this.customizeInterface(); $("body").keydown((e) => { const code = e.keyCode || e.charCode; // standards anyone? return !this.keyDownHandlers.find(h => h(e, code)); // if we find a handler, stop propagation }); // A link that carries a schema does not validate on arrival. It used to // say it did -- and threw a ReferenceError instead, for the two years // since these became methods of a class (`callValidator()`, with no // `this`), so nothing has ever run here. Opening a link is not asking // for the walk behind it: a permalink may name an endpoint or a Wikibase, // where validating costs a hundred requests to somebody else's service. // Press validate. return loaded; }, parseQueryString(query) { if (query[0] === '?') query = query.substr(1); // optional leading '?' const map = {}; query.replace(/([^&,=]+)=?([^&,]*)(?:[&,]+|$)/g, (match, key, value) => { key = decodeURIComponent(key); value = decodeURIComponent(value); (map[key] = map[key] || []).push(value); }); return map; }, /** * update location with a current values of some inputs */ async getPermalink() { let parms = []; // The map as it stands, whether or not the source can still answer it: // a link is about what is on screen, and a query map this source cannot // resolve -- a `SPARQL '''…'''` after a slurp handed the reader the // local store -- is still what the link should carry. Failing to build // one leaves the menu with no link and says nothing about why. try { await this.Caches.shapeMap.copyEditMapToQueryMap(); } catch (e) { // the query map keeps what it says, which is what goes in the link } parms = parms.concat(this.QueryParams.reduce((acc, input) => { let parm = input.queryStringParm; let val = input.location.val(); // more than one plugin may be loaded, and the link has to bring // them all back if (input.cache && Array.isArray(input.cache.urls)) return acc.concat(input.cache.urls.map(u => parm + "URL=" + encodeURIComponent(u))); if (input.cache && input.cache.url && // Specifically avoid loading from DefaultBase?schema=blah // because that will load the HTML page. !input.cache.url.startsWith(DefaultBase)) { parm += "URL"; val = input.cache.url; } // a parameter left out comes back as its default, so a link only // says what differs from it if ("deflt" in input && val === input.deflt) return acc; return val.length > 0 ? acc.concat(parm + "=" + encodeURIComponent(val)) : acc; }, [])); // The data source may hold several documents (a measurement in one, its // patient in another): `data=` repeats, once per pane in the order they // are shown. With `dataURL=` the first came from there, so the rest follow. const neighborhoods = this.neighborhoods; if (neighborhoods && neighborhoods.documents().length > 1) { const docs = neighborhoods.documents().map((d, at) => neighborhoods.docAt(at).text); const fromUrl = parms.some(p => p.startsWith("dataURL=")); parms = parms.filter(p => !p.startsWith("data=")); (fromUrl ? docs.slice(1) : docs).forEach(text => parms.push("data=" + encodeURIComponent(text))); } const s = parms.join("&"); return location.origin + location.pathname + "?" + s; }, /** Menu → "shorten": swap the (often very long) permalink for a TinyURL * short link. TinyURL's keyless api-create.php is CORS-enabled and hands * back the short URL as plain text, so no server of our own is needed; we * show it beside Permalink and copy it to the clipboard. TinyURL answers * 200 with an error string rather than an HTTP error when it refuses a URL * (an over-long one, say), so we vet the body, not just the status, and on * any failure keep the long link -- for a link too big to shorten, "Create * Gist" is the path that scales. */ async shortenPermalink(evt) { if (evt) evt.preventDefault(); const $btn = $("#shortenPermalink"), $out = $("#shortPermalink"), $row = $("#shortPermalinkRow"); const label = $btn.text() || "shorten"; // the menu builds the permalink as it opens; build one now in case the // click somehow beat that const long = $("#permalinkAnchor").attr("href") || await this.getPermalink(); $btn.prop("disabled", true).text("shortening…"); $row.hide(); $out.removeAttr("href").text(""); try { const resp = await fetch("https://tinyurl.com/api-create.php?url=" + encodeURIComponent(long)); const body = (await resp.text()).trim(); // TinyURL answers 200 with an error string (not an HTTP error) when it // refuses a URL -- an over-long one, say -- so vet the body, not the status if (!resp.ok || !/^https?:\/\//.test(body)) throw new Error(body || ("HTTP " + resp.status)); // show it beside Permalink, log it (a place to copy it from), and put it // on the clipboard $out.attr("href", body).text(body); $row.show(); console.log("TinyURL short link: " + body); let copied = false; try { await navigator.clipboard.writeText(body); copied = true; } catch (e) { /* clipboard needs a secure context + permission; link still shows */ } $btn.text(copied ? "copied ✓" : "shortened"); } catch (e) { $btn.text("shorten failed").attr("title", "TinyURL: " + e.message); console.warn("TinyURL shorten failed:", e); } window.setTimeout(() => $btn.prop("disabled", false).text(label) .attr("title", "Shorten this link with TinyURL"), 2500); return null; }, /** Menu → "Create Gist": publish the inputs this app registered with a * manifest descriptor in its QueryParams (shex.html: schema, data, * queryMap; shexmap adds staticVars, outputSchema, outputShapeMap) as a * github gist (modeled on *