Commit 7a5f35b8 authored by Cédric Le Ninivin's avatar Cédric Le Ninivin

Clean unsused Gadgets

parent 58690863
/*jslint nomen: true, indent: 2, maxerr: 3 */
/*global window, rJS */
(function (window, rJS, loopEventListener) {
"use strict";
function loadCribJS (gadget, event) {
var jio_cribjs_gadget,
jio_configurator_gadget;
return RSVP.Queue()
.push(function() {
return RSVP.all([
gadget.getDeclaredGadget("jio_cribjs"),
gadget.getDeclaredGadget("jio_configurator")]);
})
.push(function(gadget_list) {
jio_cribjs_gadget = gadget_list[0];
jio_configurator_gadget = gadget_list[1];
return jio_configurator_gadget.getContent();
})
.push(function (jio_string) {
return jio_cribjs_gadget.load({
path: document.location.href,
jio_config: jio_string,
application_id: "cribjs"
})
})
.push(function (url_list) {
document.location = document.location.href + "crib-editor4/";
})
.push(console.log, console.log);
}
rJS(window)
.declareMethod('render', function (options) {
var gadget = this,
getURL = window.location,
jio_configuration_string = getURL.protocol + "//" + getURL.host + "/cribjs-latest.zip";
return RSVP.Queue()
.push(function () {
return gadget.getDeclaredGadget('jio_configurator');
})
.push(function (jio_configurator_gadget) {
return jio_configurator_gadget.render({value: jio_configuration_string});
})
.push(function () {
return loopEventListener(
gadget.props.element.querySelector("form.loading"),
'submit',
false,
function (event) {loadCribJS(gadget, event)}
);
})
.fail(function(e){console.log(e)})
})
.ready(function (g) {
g.props = {};
return g.getElement()
.push(function (element) {
g.props.element = element;
}).push(function() {
g.render({})
})
;
});
}(window, rJS, loopEventListener));
\ No newline at end of file
html body nav.navbar-default {
background-color: transparent;
}
/*Test*/
html body .navbar-default .navbar-nav>li>a {
color: #337ab7;
}
html body .navbar-default .navbar-brand {
color: #337ab7;
}
iframe {
width: 100%;
height: 100%;
top: 0;
bottom: 0;
position: fixed;
}
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../lib/bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="./cribjs-conqueror.css">
<title>CribJS</title>
<script src="./lib/sha256.js"></script>
<script src="./lib/sha256.amd.js"></script>
<script src="./lib/rsvp.js"></script>
<script src="./lib/jio-latest.js"></script>
<script src="./lib/renderjs.js"></script>
<script src="./cribjs-conqueror.js"></script>
</head>
<body>
<div data-gadget-url="./gadget/crib-sw-gadget.html"
data-gadget-scope="crib_sw_gadget"
data-gadget-sandbox="public"></div>
<div data-gadget-url="https://www.cribjs.com/gadget/cribjs-ide-gadget.html"
data-gadget-scope="crib_ide_gadget"
data-gadget-sandbox="iframe"></div>
</body>
</html>
\ No newline at end of file
/*globals window, document, RSVP, rJS, Handlebars, console*/
/*jslint indent: 2, maxlen: 80*/
(function (window, document, RSVP, rJS, Handlebars, console) {
"use strict";
function callCribSWGadget(gadget, method, param_list) {
var called = false;
return new RSVP.Queue()
.push(function () {
return gadget.getDeclaredGadget("crib_sw_gadget");
})
.push(function (crib_sw_gadget) {
return crib_sw_gadget[method].apply(crib_sw_gadget, param_list);
})
.push(function (result) {
return result;
}, function (error) {
throw error;
});
}
rJS(window)
.ready(function (g) {
g.props = {};
return g.getElement()
.push(function (element) {
g.props.element = element;
});
})
.allowPublicAcquisition("crib_sw_allDocs", function (param_list) {
return callCribSWGadget(this, "allDocs", param_list);
})
.allowPublicAcquisition("crib_sw_remove", function (param_list) {
return callCribSWGadget(this, "remove", param_list);
})
.allowPublicAcquisition("crib_sw_put", function (param_list) {
return callCribSWGadget(this, "put", param_list);
})
.allowPublicAcquisition("crib_sw_get", function (param_list) {
return callCribSWGadget(this, "get", param_list);
})
.declareMethod('render', function (options) {
var promise_list = [],
gadget = this;
gadget.props.options = options;
// Add promise for list Cache content
// promise to use dav storage for jIO
return RSVP.Queue()
.push(function () {
return gadget.getDeclaredGadget('crib_ide_gadget');
})
.push(function (crib_ide_gadget) {
return crib_ide_gadget.render();
});
})
}(window, document, RSVP, rJS, console));
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../lib/bootstrap/bootstrap.min.css">
<title>CribJS</title>
<script src="../lib/sha256.js"></script>
<script src="../lib/sha256.amd.js"></script>
<script src="../lib/rsvp.js"></script>
<script src="../lib/jio-latest.js"></script>
<script src="../lib/renderjs.js"></script>
<script src="./cribjs-ide-gadget.js"></script>
<!--The following CSS shows a lack of developing style -->
<style>
html body nav.navbar-default {
background-color: transparent;
}
html body .navbar-default .navbar-nav>li>a {
color: #337ab7;
}
html body .navbar-default .navbar-brand {
color: #337ab7;
}
</style>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#view=cribjs">CribJS</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#view=url_list">URL List</a></li>
<li><a href="#view=editor">Editor</a></li>
<li><a href="#view=save_load">Save/Load</a></li>
<li><a href="#view=mass_remove">Remove</a></li>
</ul>
</div>
</div>
</nav>
<div class="nav_content cribjs container" style="display:none;">
<h1>CribJS: have a taste of your web</h1>
<p>Developed to bring the free software idea to the web,
CribJS offer to you the possibility to create your version of the web application you are using.
Make your copy of the web from here: learn, modify, improve, share.</p>
<p>As this application is a place to develop web applications, it can edit itself.
See how it is made, modify it, improve it.
Start developping your own way. Feel free to make this place your own crib.</p>
<ul>
<li>1. Browse the <a href="#view=url_list">list of URLs</a> you wish to edit</li>
<li>2. Edit and add files in your <a href="#view=editor">Editor</a></li>
<li>3. <a href="#view=save_load">Save and Load</a> your copy of the web locally and remotly</li>
<li>4. <a href="#view=mass_remove">Remove</a> uncessary URLs</li>
</ul>
<p>Have fun building the web :), here is your <a href="/crib-editor/todo.txt">TODO list</a>.</p>
</div>
<div class="nav_content url_list container" style="display:none;">
<form class="crib-url-list-content">
<h3>URL List</h3>
<button type="submit" name="list-contents" class="btn btn-default">Refresh</button>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Cached</th>
<th>Url</th>
<th>Go</th>
</tr>
</thead>
<tfoot>
</tfoot>
<tbody>
</tbody>
</table>
<div>
<button type="submit" name="list-contents" class="btn btn-default">Refresh</button>
</div>
</form>
</div>
<div class="nav_content editor" style="display:none;">
<div class="container">
<div class="row">
<form class="crib-editor-get form-inline">
<h3>Edit</h3>
<div class="form-group">
<label>URL:
<input name="url" class="url form-control" type="text" size="50" value=""></label>
</div>
<button type="submit" name="get" class="btn btn-default">Get from Cache</button>
</form>
</div>
<div class="row">
<form class="crib-editor-save form-inline">
<div class="form-group">
<label>Mimetype:
<input class="mimetype form-control" name="mimetype" type="text" size="50" value="text/html">
</label>
</div>
<div class="form-group">
<button name="add" type="submit" class="btn btn-primary">Add to Cache</button>
</div>
</form>
</div>
<div class="row">
<table class="table">
<tr>
<td class="success"><span class="crib-editor-save-status"></span></td>
</tr>
</table>
</div>
</div>
<div class="container-fluid">
<div data-gadget-url="./gadget_codemirror.html"
data-gadget-scope="codeeditor"
data-gadget-sandbox="public"></div>
</div>
</div>
<div class="nav_content save_load container" style="display:none;">
<h3>Storage</h3>
<h4>Dav Storage</h4>
<form class="form-horizontal form-use-jio-dav">
<div class="form-group">
<label for="url" class="col-sm-2 control-label">URL</label>
<div class="col-sm-10">
<input type="text" class="form-control url" id="url" value="https://yourdav.node.vifib.com/public/cribjs-storage/">
</div>
</div>
<div class="form-group">
<label for="credential" class="col-sm-2 control-label">Credential</label>
<div class="col-sm-10">
<input type="password" class="form-control credential" id="credential" placeholder="couscous:admin">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Use Dav Storage</button>
</div>
</div>
</form>
<h4>Local Storage</h4>
<form class="form-horizontal form-use-jio-local">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button class="btn btn-default" type="submit">Local is Enough</button>
</div>
</div>
</form>
<form class="crib-save-to-jio form-inline">
<h3>Save</h3>
<div class="form-group">
<label>Save:
<input class="save-path form-control" name="save-path" type="text" size="30" value=""></label>
</div>
<div class="form-group">
<label> to:
<input name="save-id" class="save-id form-control" type="text" size="30" value="cribjs"></label>
</div>
<button name="save-contents" type="submit" class="btn btn-default">Save Cache</button>
</form>
<div><span class="info crib-save-to-jio-status"></span></div>
<form class="crib-load-from-jio form-inline">
<h3>Load</h3>
<div class="form-group">
<label>Load :
<input name="load-id" class="load-id form-control" type="text" size="30" value="cribjs"></label>
</div>
<div class="form-group">
<label> to path:
<input name="load-path" class="load-path form-control" type="text" size="30" value="cribeditor/v1.1">
</label>
</div>
<button name="load-contents" class="load-contents btn btn-default" type="submit">Load Cache</button>
</form>
<div><span class="crib-load-from-jio-status"></span></div>
</div>
<div class="nav_content mass_remove container" style="display:none;">
<form class="crib-mass-remove">
<h3>Mass removal</h3>
<div class="form-group">
<textarea name="mass-remove-list" cols="35" wrap="soft" class="form-control"></textarea>
</div>
<button type="submit" class="mass-remove btn btn-danger" name="mass-remove">Mass remove from Cache</button>
<div><span class="crib-mass-remove-status"></span></div>
</form>
</div>
<div data-gadget-url="./gadget_jio.html"
data-gadget-scope="jio_gadget"
data-gadget-sandbox="public"></div>
</body>
</html>
\ No newline at end of file
This diff is collapsed.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>CribJS Loader</title>
<script src="../lib/rsvp.js"></script>
<script src="../lib/renderjs.js"></script>
<script src="./gadget_cribjs_loader.js"></script>
</head>
<body>
<h1>CribJS Loader</h1>
<div data-gadget-url="./gadget_jio_cribjs.html"
data-gadget-scope="jio_cribjs"
data-gadget-sandbox="public"></div>
<div data-gadget-url="./gadget_jio_configurator.html"
data-gadget-scope="jio_configurator"
data-gadget-sandbox="public"></div>
<form>
<button type="submit">Load</button>
</form>
<ul>
</ul>
</body>
</html>
\ No newline at end of file
/*jslint nomen: true, indent: 2, maxerr: 3 */
/*global window, rJS */
(function (window, rJS) {
"use strict";
function loadCribJS (gadget, event) {
var jio_cribjs_gadget,
jio_configurator_gadget;
return RSVP.Queue()
.push(function() {
return RSVP.all([
gadget.getDeclaredGadget("jio_cribjs"),
gadget.getDeclaredGadget("jio_configurator")]);
})
.push(function(gadget_list) {
jio_cribjs_gadget = gadget_list[0];
jio_configurator_gadget = gadget_list[1];
return jio_configurator_gadget.getContent();
})
.push(function (jio_string) {
return jio_cribjs_gadget.load({
path: document.location.origin,
jio_config: JSON.parse(jio_string),
application_id: "cribjs"
})
})
.push(function (url_list) {
console.log(url_list);
document.location = document.location.origin + "/crib-editor/";
})
}
rJS(window)
.declareMethod('render', function (options) {
var gadget = this,
jio_configuration_string = "";
if (localStorage.hasOwnProperty("crib_js_loader_jio")) {
jio_configuration_string = localStorage.getItem("crib_js_loader_jio");
} else {
jio_configuration_string = '{"type": "dav", "url": "https://cedriclendav.node.vifib.com/public/cribjs-storage/"}';
}
return RSVP.Queue()
.push(function () {
return gadget.getDeclaredGadget('jio_configurator');
})
.push(function (jio_configurator_gadget) {
return jio_configurator_gadget.render({value: jio_configuration_string});
})
.push(function () {
return loopEventListener(
gadget.props.element.querySelector("form.loading"),
'submit',
false,
function (event) {loadCribJS(gadget, event)}
);
})
.fail(function(e){console.log(e)})
})
.ready(function (g) {
g.props = {};
return g.getElement()
.push(function (element) {
g.props.element = element;
});
});
}(window, rJS));
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>CribJS Loader</title>
<script src="../lib/rsvp.js"></script>
<script src="../lib/renderjs.js"></script>
<script src="./gadget_jio_configurator.js"></script>
</head>
<body>
<form>
<textarea name="jio_json_configuration"></textarea>
</form>
</body>
</html>
\ No newline at end of file
/*jslint nomen: true, indent: 2, maxerr: 3 */
/*global window, rJS */
(function (window, rJS) {
"use strict";
rJS(window)
.declareAcquiredMethod("saveContent", "editor_saveContent")
.declareMethod('render', function (options) {
if (options && options.hasOwnProperty("value"))
this.props.element.querySelector("textarea").value = options.value || "";
})
.declareMethod('getContent', function () {
return this.props.element.querySelector("textarea").value;
})
.ready(function (g) {
g.props = {};
return g.getElement()
.push(function (element) {
g.props.element = element;
});
});
}(window, rJS));
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>CribJS Loader</title>
<script src="../lib/rsvp.js"></script>
<script src="../lib/renderjs.js"></script>
<script src="../lib/jszip.js" type="text/javascript"></script>
<script src="./gadget_jio_cribjs.js"></script>
</head>
<body>
<div data-gadget-url="./crib-sw-gadget.html"
data-gadget-scope="crib_sw_gadget"
data-gadget-sandbox="public"></div>
<div data-gadget-url="./gadget_jio.html"
data-gadget-scope="jio_gadget"
data-gadget-sandbox="public"></div>
</body>
</html>
\ No newline at end of file
/*globals window, document, RSVP, rJS,
location, console*/
/*jslint indent: 2, maxlen: 80*/
(function (window, document, RSVP, rJS, location, console, JSZip) {
"use strict";
function getExtension(url) {
var extension = url.split('.').pop();
if (extension.endsWith('/')) {
return ".html";
}
return "." + extension;
}
function getSetting(gadget, key, default_value) {
return default_value;
}
function loadContentFromZIPURL(gadget, zip_url) {
var path_to_load, path_to_load_length, file_list, crib_sw_gadget,
jio_gadget, url_list = [], url_number = 0;
path_to_load = "";
return new RSVP.Queue()
.push(function () {
return gadget.getDeclaredGadget('crib_sw_gadget');
})
.push(function (returned_gadget) {
crib_sw_gadget = returned_gadget;
return fetch(zip_url)
.then(function (response) { // 2) filter on 200 OK
if (response.status === 200 || response.status === 0) {
return Promise.resolve(response.blob());
} else {
return Promise.reject(new Error(response.statusText));
}
});
})
.push(JSZip.loadAsync)
.push(function (zip) {
var promise_list = [];
zip.forEach(function (relativePath, zipEntry) {
var end_url;
url_number += 1;
if ( zipEntry.dir ) {
return
}
if (!relativePath.startsWith("/") && !path_to_load.endsWith("/")) {
end_url = path_to_load + "/" + relativePath
} else if (relativePath.startsWith("/") && path_to_load.endsWith("/")) {
end_url = path_to_load + relativePath.substring(1);
} else {
end_url = path_to_load + relativePath
}
promise_list.push(
new RSVP.Queue().
push(function () {
return zipEntry.async('blob');
})
.push(function (result) {
if ( end_url.endsWith(".js") ) {
// This is a ugly hack as mimetype needs to be correct for JS
result = result.slice(0, result.size, "application/javascript")
} else if ( end_url.endsWith(".html") ) {
// This is a ugly hack as mimetype needs to be correct for JS
result = result.slice(0, result.size, "text/html")
} else if ( end_url.endsWith(".css") ) {
// This is a ugly hack as mimetype needs to be correct for JS
result = result.slice(0, result.size, "text/css")
}
return crib_sw_gadget.put(end_url, {blob: result})
})
)
})
return RSVP.all(promise_list)
})
.push(function() {
gadget.props.element.querySelector(".crib-load-from-zip-status").textContent = "Loaded " + url_number + " files at "+ Date ()
})
.push(console.log, console.log)
}
rJS(window)
.ready(function (g) {
g.props = {};
})
.declareMethod('load', function (options) {
var path_to_load, path_to_load_length, application_id, crib_sw_gadget, jio_config,
jio_gadget, url_list = [], gadget = this;
path_to_load = options.path;
application_id = options.application_id;
jio_config = options.jio_config;
path_to_load_length = path_to_load.length;
return new RSVP.Queue()
.push(function () {
return loadContentFromZIPURL(gadget, jio_config);
})
.push(console.log, console.log)
})
.allowPublicAcquisition("getSetting", function (argument_list) {
return getSetting(this, argument_list[0], argument_list[1]);
})
}(window, document, RSVP, rJS, location, console, JSZip));
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>CribJS Loader</title>
<script src="../lib/rsvp.js"></script>
<script src="../lib/renderjs.js"></script>
<!--script src="gadget_jio_simple_configurator.js"></script-->
</head>
<body>
<h3>Storage</h3>
<div class="row">
<div class="col-md-6">
<form class="select-dav-form">
<button class="btn btn-default btn-lg btn-block" type="submit" data-i18n="DAV Storage">DAV Storage</button>
</form>
</div>
<div class="col-md-6">
<form class="select-local-form">
<button class="btn btn-default btn-lg btn-block" type="submit" data-i18n="Local is Enough">Local is Enough</button>
</form>
</div>
</div>
</body>
</html>
\ No newline at end of file
/*jslint nomen: true, indent: 2, maxerr: 3 */
/*global window, rJS */
(function (window, rJS) {
"use strict";
rJS(window)
.declareAcquiredMethod("saveContent", "editor_saveContent")
.declareMethod('render', function (options) {
if (options && options.hasOwnProperty("value"))
this.props.element.querySelector("textarea").value = options.value || "";
})
.declareMethod('getContent', function () {
return this.props.element.querySelector("textarea").value;
})
.ready(function (g) {
g.props = {};
return g.getElement()
.push(function (element) {
g.props.element = element;
});
});
}(window, rJS));
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>CribJS Loader</title>
<link rel="stylesheet" href="/lib/bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="/landing.css">
<script src="./lib/rsvp.js"></script>
<script src="./lib/renderjs.js"></script>
<script src="./gadget/gadget_global.js"></script>
<script src="landing.js"></script>
</head>
<body>
<div data-gadget-url="./gadget/gadget_landing_cribjs.html"
data-gadget-scope="jio_cribjs"
data-gadget-sandbox="public"></div>
<div class="nav_content container">
<h1>CribJS Loader</h1>
<p>Load your Crib from here</p>
</div>
<div class="nav_content container">
<h3>Edit this Site</h3>
<div class="form-group">
<label>Edit URL:
<input name="edit-url" class="edit-url form-control" type="text" size="60" readonly value="/crib-enable.html"></label>
</div>
</div>
<div class="nav_content container">
<form class="crib-load-from-zip-url form-inline">
<h3>Import from zip URL</h3>
<div class="form-group">
<label>Zip Url:
<input name="load-zip-url" class="load-zip-url form-control" type="text" size="60"></label>
</div>
<div class="form-group">
<label> Path in Zip:
<input name="load-from-zip-path" class="load-from-zip-path form-control" type="text" size="30" value="/">
</label>
</div>
<div class="form-group">
<label> to path:
<input name="load-zip-to-path" class="load-zip-to-path form-control" type="text" size="30" value="/">
</label>
</div>
<div class="form-group">
<label> And redirect to:
<input name="redirect-url" class="redirect-url form-control" type="text" size="30" value="">
</label>
</div>
<button name="load-zip-contents" class="load-zip-contents btn btn-default" type="submit">Import from URL</button>
</form>
</div>
<div class="nav_content container">
<div><span class="info crib-save-to-zip-status"></span></div>
<form class="crib-load-from-zip-file form-inline">
<h3>Import from zip File</h3>
<div class="form-group">
<label>Zip File:
<input name="load-zip-file" class="load-zip-file form-control" type="file" size="30"></label>
</div>
<div class="form-group">
<label> Path in Zip:
<input name="load-zip-path" class="load-from-zip-path form-control" type="text" size="30" value="/">
</label>
</div>
<div class="form-group">
<label> to path:
<input name="load-zip-to-path" class="load-zip-to-path form-control" type="text" size="30" value="/">
</label>
</div>
<div class="form-group">
<label> And redirect to:
<input name="redirect-url" class="redirect-url form-control" type="text" size="30" value="">
</label>
</div>
<button name="load-zip-contents" class="load-zip-contents btn btn-default" type="submit">Import from File</button>
</form>
</div>
<div class="nav_content container">
<p>You can check where it started, and start a crib from the beginning: <a href="jungle.html">The Jungle :)</a>. This one is a simple editor with no import/export functions. First challenge is to use that to add an import/export function :).</p>
<p>A simple editor can be found <a href="base.html">here</a></p>
</div>
</body>
</html>
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This polyfill provides Cache.add(), Cache.addAll(), and CacheStorage.match(),
// which are not implemented in Chrome 40.
// Should not be needed for Chromium > 47 And Firefox > 39
// See https://developer.mozilla.org/en-US/docs/Web/API/Cache
importScripts('./serviceworker-cache-polyfill.js');
// While overkill for this specific sample in which there is only one cache,
// this is one best practice that can be followed in general to keep track of
// multiple caches used by a given service worker, and keep them all versioned.
// It maps a shorthand identifier for a cache to a specific, versioned cache name.
// Note that since global state is discarded in between service worker restarts, these
// variables will be reinitialized each time the service worker handles an event, and you
// should not attempt to change their values inside an event handler. (Treat them as constants.)
// If at any point you want to force pages that use this service worker to start using a fresh
// cache, then increment the CACHE_VERSION value. It will kick off the service worker update
// flow and the old cache(s) will be purged as part of the activate event handler when the
// updated service worker is activated.
var CACHE_VERSION = 1;
var CURRENT_CACHES = {
'cribjs': 'post-message-cache-v' + CACHE_VERSION
};
self.addEventListener('activate', function(event) {
// Delete all caches that aren't named in CURRENT_CACHES.
// While there is only one cache in this example, the same logic will handle the case where
// there are multiple versioned caches.
var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
return CURRENT_CACHES[key];
});
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (expectedCacheNames.indexOf(cacheName) == -1) {
// If this cache name isn't present in the array of "expected" cache names, then delete it.
console.log('Deleting out of date cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', function(event) {
console.log('Handling fetch event for', event.request.url);
if (event.request.method === "GET") {
event.respondWith(
caches.open(CURRENT_CACHES['cribjs']).then(function(cache) {
return cache.match(event.request).then(function(response) {
if (response) {
// If there is an entry in the cache for event.request, then response will be defined
// and we can just return it. Note that in this example, only font resources are cached.
console.log(' Found response in cache:', response);
return response;
} else {
// Otherwise, if there is no entry in the cache for event.request, response will be
// undefined, and we need to fetch() the resource.
console.log(' No response for %s found in cache. About to fetch from network...', event.request.url);
// We call .clone() on the request since we might use it in a call to cache.put() later on.
// Both fetch() and cache.put() "consume" the request, so we need to make a copy.
// (see https://fetch.spec.whatwg.org/#dom-request-clone)
return fetch(event.request.clone()).then(function(response) {
console.log(' Response for %s from network is: %O', event.request.url, response);
// Return the original response object, which will be used to fulfill the resource request.
//cache.put(event.request, response.clone());
return response;
});
}
}).catch(function(error) {
// This catch() will handle exceptions that arise from the match() or fetch() operations.
// Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
// It will return a normal response object that has the appropriate error code set.
console.error(' Error in fetch handler:', error);
throw error;
});
})
);
} else {
event.respondWith(fetch(event.request));
}
});
self.addEventListener('message', function(event) {
console.log('Handling message event:', event);
caches.open(CURRENT_CACHES['cribjs']).then(function(cache) {
switch (event.data.command) {
// This command returns a list of the URLs corresponding to the Request objects
// that serve as keys for the current cache.
case 'keys':
cache.keys().then(function(requests) {
var urls = requests.map(function(request) {
return request.url;
});
// event.ports[0] corresponds to the MessagePort that was transferred as part of the controlled page's
// call to controller.postMessage(). Therefore, event.ports[0].postMessage() will trigger the onmessage
// handler from the controlled page.
// It's up to you how to structure the messages that you send back; this is just one example.
event.ports[0].postMessage({
error: null,
urls: urls.sort()
});
});
break;
// This command adds a new request/response pair to the cache.
case 'add':
// If event.data.url isn't a valid URL, new Request() will throw a TypeError which will be handled
// by the outer .catch().
// Hardcode {mode: 'no-cors} since the default for new Requests constructed from strings is to require
// CORS, and we don't have any way of knowing whether an arbitrary URL that a user entered supports CORS.
var request = new Request(event.data.url, {mode: 'no-cors'}),
response = new Response(event.data.information);
cache.put(request, response).then(function() {
event.ports[0].postMessage({
error: null
});
});
break;
// This command removes a request/response pair from the cache (assuming it exists).
case 'delete':
var request = new Request(event.data.url, {mode: 'no-cors'});
cache.delete(request).then(function(success) {
event.ports[0].postMessage({
error: success ? null : 'Item was not found in the cache.'
});
});
break;
default:
// This will be handled by the outer .catch().
throw 'Unknown command: ' + event.data.command;
}
}).catch(function(error) {
// If the promise rejects, handle it by returning a standardized error message to the controlled page.
console.error('Message handling failed:', error);
event.ports[0].postMessage({
error: error.toString()
});
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment