Merge pull request #28 from OptimistikSAS/storageDialog

#storageDialog dialog separate moved dialog
master
JFH 2020-12-30 10:01:45 +01:00 committed by GitHub
commit ed6c4f0986
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 313 additions and 133 deletions

View File

@ -7,3 +7,4 @@ import './seSelectDialog.js';
import './seConfirmDialog.js'; import './seConfirmDialog.js';
import './sePromptDialog.js'; import './sePromptDialog.js';
import './seAlertDialog.js'; import './seAlertDialog.js';
import './storageDialog.js';

View File

@ -0,0 +1,166 @@
/* eslint-disable node/no-unpublished-import */
import 'elix/define/Dialog.js';
const template = document.createElement('template');
template.innerHTML = `
<style>
#dialog_content {
margin: 10px 10px 5px 10px;
background: #DDD;
overflow: auto;
text-align: left;
border: 1px solid #B0B0B0;
}
#dialog_content p, #dialog_content select, #dialog_content label {
margin: 10px;
line-height: 1.3em;
}
#dialog_container {
font-family: Verdana;
text-align: center;
left: 50%;
top: 50%;
max-width: 400px;
z-index: 50001;
background: #CCC;
border: 1px outset #777;
font-family:Verdana,Helvetica,sans-serif;
font-size:0.8em;
}
#dialog_container, #dialog_content {
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
#dialog_buttons input[type=text] {
width: 90%;
display: block;
margin: 0 0 5px 11px;
}
#dialog_buttons input[type=button] {
margin: 0 1em;
}
</style>
<elix-dialog id="dialog_box" aria-label="SVG-Edit storage preferences" closed>
<div class="overlay"></div>
<div id="dialog_container">
<div id="dialog_content">
<p>
By default and where supported, SVG-Edit can store your editor preferences and SVG content locally on your machine so you do not need to add these back each time you load SVG-Edit. If, for privacy reasons, you do not wish to store this information on your machine, you can change away from the default option below.
</p>
<select id="se-storage-pref">
<option value="prefsAndContent" id="js-storage" disabled>Store preferences and SVG content locally</option>
<option value="prefsOnly">Only store preferences locally</option>
<option value="noPrefsOrContent">Do not store my preferences or SVG content locally</option>
</select>
<label title="If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again.">
Remember this choice?<input type="checkbox" id="se-remember" value="" checked>
</label>
</div>
<div id="dialog_buttons">
<button id="storage_ok">
<img class="svg_icon" src="./images/ok.svg" alt="icon" width="16" height="16" />
Ok
</button>
<button id="storage_cancel">
<img class="svg_icon" src="./images/cancel.svg" alt="icon" width="16" height="16" />
Cancel
</button>
</div>
</div>
</elix-dialog>
`;
/**
* @class SeStorageDialog
*/
export class SeStorageDialog extends HTMLElement {
/**
* @function constructor
*/
constructor () {
super();
// create the shadowDom and insert the template
this._shadowRoot = this.attachShadow({mode: 'open'});
this._shadowRoot.appendChild(template.content.cloneNode(true));
this.$dialog = this._shadowRoot.querySelector('#dialog_box');
this.$storage = this._shadowRoot.querySelector('#js-storage');
this.$okBtn = this._shadowRoot.querySelector('#storage_ok');
this.$cancelBtn = this._shadowRoot.querySelector('#storage_cancel');
this.$storageInput = this._shadowRoot.querySelector('#se-storage-pref');
this.$rememberInput = this._shadowRoot.querySelector('#se-remember');
}
/**
* @function observedAttributes
* @returns {any} observed
*/
static get observedAttributes () {
return ['dialog', 'storage'];
}
/**
* @function attributeChangedCallback
* @param {string} name
* @param {string} oldValue
* @param {string} newValue
* @returns {void}
*/
attributeChangedCallback (name, oldValue, newValue) {
switch (name) {
case 'dialog':
if (newValue === 'open') {
this.$dialog.open();
} else {
this.$dialog.close();
}
break;
case 'storage':
if (newValue === 'true') {
this.$storageInput.options[0].disabled = false;
} else {
this.$storageInput.options[0].disabled = true;
}
break;
default:
// super.attributeChangedCallback(name, oldValue, newValue);
break;
}
}
/**
* @function get
* @returns {any}
*/
get dialog () {
return this.getAttribute('dialog');
}
/**
* @function set
* @returns {void}
*/
set dialog (value) {
this.setAttribute('dialog', value);
}
/**
* @function connectedCallback
* @returns {void}
*/
connectedCallback () {
const onSubmitHandler = (e, action) => {
const triggerEvent = new CustomEvent('change', {detail: {
trigger: action,
select: this.$storageInput.value,
checkbox: this.$rememberInput.checked
}});
this.dispatchEvent(triggerEvent);
};
this.$okBtn.addEventListener('click', (evt) => onSubmitHandler(evt, 'ok'));
this.$cancelBtn.addEventListener('click', (evt) => onSubmitHandler(evt, 'cancel'));
}
}
// Register
customElements.define('se-storage-dialog', SeStorageDialog);

View File

@ -44,7 +44,6 @@ export default {
// to change, set the "emptyStorageOnDecline" config setting to true // to change, set the "emptyStorageOnDecline" config setting to true
// in svgedit-config-iife.js/svgedit-config-es.js. // in svgedit-config-iife.js/svgedit-config-es.js.
const { const {
emptyStorageOnDecline,
// When the code in svg-editor.js prevents local storage on load per // When the code in svg-editor.js prevents local storage on load per
// user request, we also prevent storing on unload here so as to // user request, we also prevent storing on unload here so as to
// avoid third-party sites making XSRF requests or providing links // avoid third-party sites making XSRF requests or providing links
@ -57,30 +56,7 @@ export default {
noStorageOnLoad, noStorageOnLoad,
forceStorage forceStorage
} = svgEditor.curConfig; } = svgEditor.curConfig;
const {storage, updateCanvas} = svgEditor; const {storage} = svgEditor;
/**
* Replace `storagePrompt` parameter within URL.
* @param {string} val
* @returns {void}
* @todo Replace the string manipulation with `searchParams.set`
*/
function replaceStoragePrompt (val) {
val = val ? 'storagePrompt=' + val : '';
const loc = top.location; // Allow this to work with the embedded editor as well
if (loc.href.includes('storagePrompt=')) {
/*
loc.href = loc.href.replace(/(?<sep>[&?])storagePrompt=[^&]*(?<amp>&?)/, function (n0, sep, amp) {
return (val ? sep : '') + val + (!val && amp ? sep : (amp || ''));
});
*/
loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) {
return (val ? n1 : '') + val + (!val && amp ? n1 : (amp || ''));
});
} else {
loc.href += (loc.href.includes('?') ? '&' : '?') + val;
}
}
/** /**
* Sets SVG content as a string with "svgedit-" and the current * Sets SVG content as a string with "svgedit-" and the current
@ -99,40 +75,6 @@ export default {
} }
} }
/**
* Set the cookie to expire.
* @param {string} cookie
* @returns {void}
*/
function expireCookie (cookie) {
document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
}
/**
* Expire the storage cookie.
* @returns {void}
*/
function removeStoragePrefCookie () {
expireCookie('svgeditstore');
}
/**
* Empties storage for each of the current preferences.
* @returns {void}
*/
function emptyStorage () {
setSVGContentStorage('');
Object.keys(svgEditor.curPrefs).forEach((name) => {
name = 'svg-edit-' + name;
if (storage) {
storage.removeItem(name);
}
expireCookie(name);
});
}
// emptyStorage();
/** /**
* Listen for unloading: If and only if opted in by the user, set the content * Listen for unloading: If and only if opted in by the user, set the content
* document and preferences into storage: * document and preferences into storage:
@ -214,83 +156,13 @@ export default {
) )
// ...then show the storage prompt. // ...then show the storage prompt.
)) { )) {
/* const options = storage ? true : false;
const options = [];
if (storage) {
options.unshift(
{value: 'prefsAndContent', text: storagePrefsAndContent},
{value: 'prefsOnly', text: storagePrefsOnly},
{value: 'noPrefsOrContent', text: storageNoPrefsOrContent}
);
} else {
options.unshift(
{value: 'prefsOnly', text: storagePrefs},
{value: 'noPrefsOrContent', text: storageNoPrefs}
);
}
*/
const options = storage ? ['prefsAndContent', 'prefsOnly', 'noPrefsOrContent'] : ['prefsOnly', 'noPrefsOrContent'];
// Open select-with-checkbox dialog // Open select-with-checkbox dialog
// From svg-editor.js // From svg-editor.js
svgEditor.storagePromptState = 'waiting'; svgEditor.storagePromptState = 'waiting';
/* JFH !!!!! const $storageDialog = document.getElementById('se-storage-dialog');
const {response: pref, checked} = await $.select( $storageDialog.setAttribute('dialog', 'open');
message, $storageDialog.setAttribute('storage', options);
options,
null,
null,
{
label: rememberLabel,
checked: true,
tooltip: rememberTooltip
}
);
*/
const pref = await seSelect(message, options);
if (pref && pref !== 'noPrefsOrContent') {
// Regardless of whether the user opted
// to remember the choice (and move to a URL which won't
// ask them again), we have to assume the user
// doesn't even want to remember their not wanting
// storage, so we don't set the cookie or continue on with
// setting storage on beforeunload
document.cookie = 'svgeditstore=' + encodeURIComponent(pref) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT'; // 'prefsAndContent' | 'prefsOnly'
// If the URL was configured to always insist on a prompt, if
// the user does indicate a wish to store their info, we
// don't want ask them again upon page refresh so move
// them instead to a URL which does not always prompt
if (storagePrompt === 'true' /* && checked */) {
replaceStoragePrompt();
return;
}
} else { // The user does not wish storage (or cancelled, which we treat equivalently)
removeStoragePrefCookie();
if (pref && // If the user explicitly expresses wish for no storage
emptyStorageOnDecline
) {
emptyStorage();
}
if (pref /* && checked */) {
// Open a URL which won't set storage and won't prompt user about storage
replaceStoragePrompt('false');
return;
}
}
// It should be enough to (conditionally) add to storage on
// beforeunload, but if we wished to update immediately,
// we might wish to try setting:
// svgEditor.setConfig({noStorageOnLoad: true});
// and then call:
// svgEditor.loadContentAndPrefs();
// We don't check for noStorageOnLoad here because
// the prompt gives the user the option to store data
setupBeforeUnloadListener();
svgEditor.storagePromptState = 'closed';
updateCanvas(true);
} else if (!noStorageOnLoad || forceStorage) { } else if (!noStorageOnLoad || forceStorage) {
setupBeforeUnloadListener(); setupBeforeUnloadListener();
} }

View File

@ -222,6 +222,14 @@ editor.init = () => {
const dialogBox = document.createElement('se-cmenu_canvas-dialog'); const dialogBox = document.createElement('se-cmenu_canvas-dialog');
dialogBox.setAttribute('id', 'se-cmenu_canvas'); dialogBox.setAttribute('id', 'se-cmenu_canvas');
document.body.append(dialogBox); document.body.append(dialogBox);
// alertDialog added to DOM
const alertBox = document.createElement('se-alert-dialog');
alertBox.setAttribute('id', 'se-alert-dialog');
document.body.append(alertBox);
// storageDialog added to DOM
const storageBox = document.createElement('se-storage-dialog');
storageBox.setAttribute('id', 'se-storage-dialog');
document.body.append(storageBox);
// promptDialog added to DOM // promptDialog added to DOM
const promptBox = document.createElement('se-prompt-dialog'); const promptBox = document.createElement('se-prompt-dialog');
promptBox.setAttribute('id', 'se-prompt-dialog'); promptBox.setAttribute('id', 'se-prompt-dialog');
@ -1982,6 +1990,105 @@ editor.init = () => {
} }
}; };
/**
* Replace `storagePrompt` parameter within URL.
* @param {string} val
* @returns {void}
* @todo Replace the string manipulation with `searchParams.set`
*/
function replaceStoragePrompt (val) {
val = val ? 'storagePrompt=' + val : '';
const loc = top.location; // Allow this to work with the embedded editor as well
if (loc.href.includes('storagePrompt=')) {
/*
loc.href = loc.href.replace(/(?<sep>[&?])storagePrompt=[^&]*(?<amp>&?)/, function (n0, sep, amp) {
return (val ? sep : '') + val + (!val && amp ? sep : (amp || ''));
});
*/
loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) {
return (val ? n1 : '') + val + (!val && amp ? n1 : (amp || ''));
});
} else {
loc.href += (loc.href.includes('?') ? '&' : '?') + val;
}
}
/**
* Sets SVG content as a string with "svgedit-" and the current
* canvas name as namespace.
* @param {string} val
* @returns {void}
*/
function setSVGContentStorage (val) {
if (editor.storage) {
const name = 'svgedit-' + editor.curConfig.canvasName;
if (!val) {
editor.storage.removeItem(name);
} else {
editor.storage.setItem(name, val);
}
}
}
/**
* Listen for unloading: If and only if opted in by the user, set the content
* document and preferences into storage:
* 1. Prevent save warnings (since we're automatically saving unsaved
* content into storage)
* 2. Use localStorage to set SVG contents (potentially too large to allow in cookies)
* 3. Use localStorage (where available) or cookies to set preferences.
* @returns {void}
*/
function setupBeforeUnloadListener () {
window.addEventListener('beforeunload', function (e) {
// Don't save anything unless the user opted in to storage
if (!document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/)) {
return;
}
if (document.cookie.match(/(?:^|;\s*)svgeditstore=prefsAndContent/)) {
setSVGContentStorage(svgCanvas.getSvgString());
}
editor.setConfig({no_save_warning: true}); // No need for explicit saving at all once storage is on
// svgEditor.showSaveWarning = false;
const {curPrefs} = editor;
Object.entries(curPrefs).forEach(([key, val]) => {
const store = (val !== undefined);
key = 'svg-edit-' + key;
if (!store) {
return;
}
if (editor.storage) {
editor.storage.setItem(key, val);
} else if (window.widget) {
window.widget.setPreferenceForKey(val, key);
} else {
val = encodeURIComponent(val);
document.cookie = encodeURIComponent(key) + '=' + val + '; expires=Fri, 31 Dec 9999 23:59:59 GMT';
}
});
});
}
/**
* Set the cookie to expire.
* @param {string} cookie
* @returns {void}
*/
function expireCookie (cookie) {
document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
}
/**
* Expire the storage cookie.
* @returns {void}
*/
function removeStoragePrefCookie () {
expireCookie('svgeditstore');
}
const winWh = {width: $(window).width(), height: $(window).height()}; const winWh = {width: $(window).width(), height: $(window).height()};
$(window).resize(function (evt) { $(window).resize(function (evt) {
@ -2153,6 +2260,40 @@ editor.init = () => {
break; break;
} }
}); });
$id('se-storage-dialog').addEventListener('change', function (e) {
document.getElementById('se-storage-dialog').setAttribute('dialog', 'close');
if (e?.detail?.trigger === 'ok') {
if (e?.detail?.select !== 'noPrefsOrContent') {
const storagePrompt = new URL(top.location).searchParams.get('storagePrompt');
document.cookie = 'svgeditstore=' + encodeURIComponent(e.detail.select) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT';
if (storagePrompt === 'true' && e?.detail?.checkbox ) {
replaceStoragePrompt();
return;
}
} else {
removeStoragePrefCookie();
if (editor.curConfig.emptyStorageOnDecline && e?.detail?.checkbox) {
setSVGContentStorage('');
Object.keys(editor.curPrefs).forEach((name) => {
name = 'svg-edit-' + name;
if (editor.storage) {
editor.storage.removeItem(name);
}
expireCookie(name);
});
}
if (e?.detail?.select && e?.detail?.checkbox) {
replaceStoragePrompt('false');
return;
}
}
} else if (e?.detail?.trigger === 'cancel') {
removeStoragePrefCookie();
}
setupBeforeUnloadListener();
editor.storagePromptState = 'closed';
updateCanvas(true);
});
const toolButtons = [ const toolButtons = [
// Shortcuts not associated with buttons // Shortcuts not associated with buttons