Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add toolbar events #89

Closed
wants to merge 10 commits into from
12 changes: 11 additions & 1 deletion .babelrc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
'@babel/preset-react'
],
plugins: [
// Preact
['@babel/plugin-transform-react-jsx', { pragma: 'h' }],
Expand Down
11 changes: 11 additions & 0 deletions jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"resolveJsonModule": true,
"baseUrl": ".",
"paths": {
"@common": ["./src/common"],
"@common/*": ["./src/common/*"],
}
},
"exclude": ["node_modules", "build"]
}
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "prismic-toolbar",
"version": "4.0.4",
"version": "4.0.6",
"description": "Prismic Toolbar",
"license": "Apache-2.0",
"main": "build/prismic-toolbar.js",
Expand Down
20 changes: 20 additions & 0 deletions src/common/events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export const toolbarEvents = {
prismic: 'prismic',
previewUpdate: 'prismicPreviewUpdate',
previewEnd: 'prismicPreviewEnd'
};

/**
* Dispatches an event with given data
*
* @param {string} event - Event name
* @param {?any} data - Data to attach to the event
*
* @return {boolean} - `true` if event `event.preventDefault()`
* was not called (event was not cancelled)
*/
export const dispatchToolbarEvent = (event, data = null) =>
window.dispatchEvent(new CustomEvent(event, {
detail: data,
cancelable: true
}));
4 changes: 4 additions & 0 deletions src/common/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
export { getCookie, setCookie, deleteCookie, demolishCookie } from './cookie';
export { Hooks } from './hooks';
export { Sorter } from './sorter';
export {
toolbarEvents,
dispatchToolbarEvent,
} from './events';
export {
warn,
err,
Expand Down
41 changes: 33 additions & 8 deletions src/iframe/preview.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchy, query, getCookie, demolishCookie, throttle, memoize, once } from '@common';
import { fetchy, query, getCookie, demolishCookie, throttle, memoize } from '@common';

const SESSION_ID = getCookie('io.prismic.previewSession');

Expand All @@ -11,7 +11,14 @@ const PreviewRef = {
getCurrent: throttle(async () => {
const s = await State.get();
const ref = encodeURIComponent(s.preview.ref);
return fetchy({ url: `/previews/${SESSION_ID}/ping?ref=${ref}` });
const current = await fetchy({ url: `/previews/${SESSION_ID}/ping?ref=${ref}` });

if (typeof s.preview === 'object') {
s.preview.ref = current.ref;
State.set(s);
}

return current;
}, 2000)
};

Expand Down Expand Up @@ -65,12 +72,30 @@ const Share = {
const State = {
liveStateNeeded: Boolean(getCookie('is-logged-in')) || Boolean(getCookie('io.prismic.previewSession')),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check if this is still necessary (if the toolbar is not loaded when no cookie is found, we can get rid of this @arnaudlewis)


get: once(async () => {
if (!State.liveStateNeeded) return State.normalize();
return fetchy({
url: '/toolbar/state',
}).then(State.normalize);
}),
state: null,

get: async () => {
if (!State.state) {
await State.insert();
}
return State.state;
},

set: (newState = {}) => {
State.state = newState;
},

setNormalized: (newState = {}) => {
State.set(State.normalize(newState));
},

insert: async () => {
if (!State.liveStateNeeded) {
State.setNormalized();
} else {
State.setNormalized(await fetchy({ url: '/toolbar/state' }));
}
},

normalize: (_state = {}) => (
Object.assign({}, {
Expand Down
9 changes: 5 additions & 4 deletions src/toolbar/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import './checkBrowser';
import { ToolbarService } from '@toolbar-service';
import { script } from '@common';
import { toolbarEvents, dispatchToolbarEvent, script } from '@common';
import { reloadOrigin, getAbsoluteURL } from './utils';
import { Preview } from './preview';
import { Prediction } from './prediction';
Expand Down Expand Up @@ -40,7 +40,7 @@ window.prismic = window.PrismicToolbar = {
let repos = new Set();

// Prismic variable is available
window.dispatchEvent(new CustomEvent('prismic'));
dispatchToolbarEvent(toolbarEvents.prismic);

// Auto-querystring setup
const scriptURL = new URL(getAbsoluteURL(document.currentScript.getAttribute('src')));
Expand All @@ -56,10 +56,11 @@ if (legacyEndpoint) {

if (!repos.size) warn`Your are not connected to a repository.`;

repos.forEach(setup);

// Setup the Prismic Toolbar for one repository TODO support multi-repo
let setupDomain = null;

repos.forEach(setup);

async function setup (rawInput) {
// Validate repository
const domain = parseEndpoint(rawInput);
Expand Down
16 changes: 12 additions & 4 deletions src/toolbar/preview/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getLocation } from '@common';
import { toolbarEvents, dispatchToolbarEvent, getLocation } from '@common';
import { reloadOrigin } from '../utils';
import screenshot from './screenshot';

Expand Down Expand Up @@ -44,7 +44,12 @@ export class Preview {
async updatePreview() {
const { reload, ref } = await this.client.updatePreview();
this.start(ref);
if (reload) { reloadOrigin(); }
if (reload) {
// Dispatch the update event and hard reload if not cancelled by handlers
if (dispatchToolbarEvent(toolbarEvents.previewUpdate, { ref })) {
reloadOrigin();
}
}
}

// Start preview
Expand All @@ -67,8 +72,11 @@ export class Preview {
await this.client.closePreviewSession();
if (!this.cookie.getRefForDomain()) return;
this.cookie.deletePreviewForDomain();
// reload to get rid of preview data and display the live version
reloadOrigin();

// Dispatch the end event and hard reload if not cancelled by handlers
if (dispatchToolbarEvent(toolbarEvents.previewEnd)) {
reloadOrigin();
}
}

async share() {
Expand Down