Skip to content

Commit

Permalink
updating editor
Browse files Browse the repository at this point in the history
  • Loading branch information
FelipeSimoes committed Nov 13, 2024
1 parent 40c0df4 commit dd60057
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 134 deletions.
2 changes: 2 additions & 0 deletions blocks/theming/theming.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
runTasks,
} from '../../scripts/libs.js';
import { externalConfig } from '../../scripts/libs/external-config.js';
import { publish } from '../../scripts/pubsub.js';

const k = Object.keys;

Expand Down Expand Up @@ -203,6 +204,7 @@ ${k(f)

setTimeout(() => {
document.body.style.display = 'block';
publish('raqn:page:load', {}, { usePostMessage: true, targetOrigin: '*' });
});
}
}
4 changes: 4 additions & 0 deletions scripts/component-list/component-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const componentList = {
module: {
path: '/blocks/theming/theming',
priority: 1,
editor: true,
},
},
breadcrumbs: {
Expand Down Expand Up @@ -171,6 +172,7 @@ export const componentList = {
module: {
path: '/blocks/card/card',
priority: 2,
editor: true,
},
},
accordion: {
Expand All @@ -192,6 +194,7 @@ export const componentList = {
module: {
path: '/blocks/button/button',
priority: 0,
editor: true,
},
},
'popup-trigger': {
Expand Down Expand Up @@ -253,6 +256,7 @@ export const componentList = {
path: '/blocks/grid/grid',
priority: 0,
dependencies: ['grid-item'],
editor: true,
},
},
'grid-item': {
Expand Down
216 changes: 92 additions & 124 deletions scripts/editor.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { deepMerge, flat, getBaseUrl, loadModule } from './libs.js';
import { deepMerge, getBaseUrl, loadModule, runTasks } from './libs.js';
import { publish } from './pubsub.js';
import { generateVirtualDom } from './render/dom.js';
import { raqnComponents, raqnComponentsList } from './render/dom-reducers.js';

window.raqnEditor = window.raqnEditor || {};
let watcher = false;
Expand All @@ -17,105 +17,75 @@ export const MessagesEvents = {
themeUpdate: 'raqn:editor:theme:update',
};

export function refresh(id) {
Object.keys(window.raqnEditor).forEach((webComponentName) => {
const instancesOrdered = Array.from(document.querySelectorAll(webComponentName));
window.raqnComponents[webComponentName].instances = instancesOrdered;
window.raqnEditor[webComponentName].instances = instancesOrdered.map((item) =>
// eslint-disable-next-line no-use-before-define
getComponentValues(window.raqnEditor[webComponentName].dialog, item),
export default {
async init() {
// no mods no party
if (!this.mods().length) return;
// inicial run tasks
await runTasks.call(
this,
null,
this.loadEditorModules,
this.publishInit,
);
});
const bodyRect = window.document.body.getBoundingClientRect();
publish(
MessagesEvents.render,
{ components: window.raqnEditor, bodyRect, uuid: id },
{ usePostMessage: true, targetOrigin: '*' },
);
}

export function updateComponent(component) {
const { webComponentName, uuid } = component;
const instance = window.raqnComponents[webComponentName].instances.find((element) => element.uuid === uuid);
if (!instance) return;
instance.attributesValues = deepMerge({}, instance.attributesValues, component.attributesValues);
instance.runConfigsByViewport();
refresh(uuid);
}

export function getComponentValues(dialog, element) {
const html = element.innerHTML;
window.document.body.style.height = 'auto';

const domRect = element.getBoundingClientRect();
let { variables = {}, attributes = {} } = dialog;
variables = Object.keys(variables).reduce((data, variable) => {
const value = getComputedStyle(element).getPropertyValue(variable);
data[variable] = { ...variables[variable], value };
return data;
}, {});
attributes = Object.keys(attributes).reduce((data, attribute) => {
if (attribute === 'data') {
const flatData = flat(element.dataset);
Object.keys(flatData).forEach((key) => {
const value = flatData[key];
if (attributes[attribute] && attributes[attribute][key]) {
if (data[attribute]) {
const extend = { ...attributes[attribute][key], value };
data[attribute][key] = extend;
} else {
data[attribute] = { [key]: { ...attributes[attribute][key], value } };
}
}
// update on resize
if (!watcher) {
window.addEventListener('resize', () => {
this.refresh();
this.sendUpdatedRender();
});
return data;
watcher = true;
}

const value = element.getAttribute(attribute);
data[attribute] = { ...attributes[attribute], value };
return data;
}, {});
const cleanData = Object.fromEntries(Object.entries(element));
const { attributesValues, webComponentName, componentName, uuid } = cleanData;
const children = generateVirtualDom(element.children, false);
const editor = { ...dialog, attributes };
return { attributesValues, webComponentName, componentName, uuid, domRect, dialog, editor, html, children };
}

export default function initEditor(listeners = true) {
Promise.all(
Object.keys(window.raqnComponents).map(
(componentName) =>
new Promise((resolve) => {
setTimeout(async () => {
try {
const fn = window.raqnComponents[componentName];
const name = fn.name.toLowerCase();
const component = loadModule(`/blocks/${name}/${name}.editor`, { loadCSS: false });
const mod = await component.js;
if (mod && mod.default) {
const dialog = await mod.default();

const masterConfig = window.raqnComponentsMasterConfig;
const variations = masterConfig[componentName];
dialog.selection = variations;
window.raqnEditor[componentName] = { dialog, instances: [], name: componentName };
const { webComponentName } = window.raqnInstances[componentName][0];
const instancesOrdered = Array.from(document.querySelectorAll(webComponentName));
window.raqnEditor[componentName].instances = instancesOrdered.map((item) =>
getComponentValues(dialog, item),
);
}
resolve();
} catch (error) {
resolve();
}
});
}),
),
).finally(() => {
},
// alias to get all components
mods: () => Object.keys(raqnComponents),
// get values from component and sizes
getComponentValues (dialog, element) {
const domRect = element.getBoundingClientRect();
return {
attributesValues: element.attributesValues,
uuid: element.uuid,
domRect,
dialog,
};
},
// refresh all components
refresh() {
this.mods().forEach((k) => {
this.refreshComponents(k);
});
},
// send updated to editor interface
sendUpdatedRender(uuid) {
const bodyRect = window.document.body.getBoundingClientRect();
publish(
MessagesEvents.render,
{ components: window.raqnEditor, bodyRect, uuid },
{ usePostMessage: true, targetOrigin: '*' },
);
},
// refresh one type of web components
refreshWebComponent(k) {
const instancesOrdered = Array.from(document.querySelectorAll(k));
window.raqnComponents[k].instances = instancesOrdered;
window.raqnEditor[k].instances = instancesOrdered.map((item) =>
this.getComponentValues(window.raqnEditor[k].dialog, item),
);
},
// refresh one instance of web component
updateIntance(component) {
const { webComponentName, uuid } = component;
const instance = window.raqnComponents[webComponentName].instances.find((element) => element.uuid === uuid);
if (!instance) return;
instance.attributesValues = deepMerge({}, instance.attributesValues, component.attributesValues);
instance.runConfigsByViewport();
this.refresh();
this.sendUpdatedRender(uuid);
},
// publish update to editor
publishInit() {
const bodyRect = window.document.body.getBoundingClientRect();

publish(
MessagesEvents.loaded,
{
Expand All @@ -126,32 +96,30 @@ export default function initEditor(listeners = true) {
},
{ usePostMessage: true, targetOrigin: '*' },
);

if (!watcher) {
window.addEventListener('resize', () => {
refresh();
});
watcher = true;
}
});
if (listeners) {
// init editor if message from parent
window.addEventListener('message', async (e) => {
if (e && e.data) {
const { message, params } = e.data;
switch (message) {
case MessagesEvents.select:
updateComponent(params);
break;

case MessagesEvents.updateComponent:
updateComponent(params);
break;

default:
break;
},
/* load all editor modules */
async loadEditorModules() {
// check if all components are loaded and then init the editor
await Promise.allSettled(this.mods().map((k) => new Promise((resolve) => {
raqnComponents[k].then(async (contructor) => {
const name = contructor.name.replace('raqn-', '').toLowerCase();
if (raqnComponentsList[name] && raqnComponentsList[name].module && raqnComponentsList[name].module.editor) {
const component = loadModule(`/blocks/${name}/${name}.editor`, { loadCSS: false });
const mod = await component.js;
if (mod && mod.default) {
const dialog = await mod.default();
const masterConfig = window.raqnComponentsMasterConfig;
const variations = masterConfig[name];
dialog.selection = variations;
window.raqnEditor[name] = { dialog, instances: [], name };
const instancesOrdered = Array.from(document.querySelectorAll(k));
window.raqnEditor[name].instances = instancesOrdered.map((item) =>
this.getComponentValues(dialog, item),
);
}
}
}
});
}
}
resolve();
});
})));
},
}.init();
7 changes: 5 additions & 2 deletions scripts/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { generateVirtualDom, renderVirtualDom } from './render/dom.js';
import { pageManipulation, templateManipulation } from './render/dom-manipulations.js';
import { getMeta, metaTags, runTasks, isTemplatePage, previewModule } from './libs.js';
import { subscribe } from './pubsub.js';

await previewModule(import.meta);

export default {
init() {
runTasks.call(
return runTasks.call(
this, // all the tasks bellow will be bound to this object when called.
null,
this.generatePageVirtualDom,
Expand Down Expand Up @@ -89,4 +90,6 @@ export default {
async templateVirtualDomManipulation({ templateVirtualDom }) {
await templateManipulation(templateVirtualDom);
},
}.init();
}.init().then(() => {
subscribe('raqn:page:editor:load', () => import('./editor.js'));
});
11 changes: 9 additions & 2 deletions scripts/libs.js
Original file line number Diff line number Diff line change
Expand Up @@ -465,8 +465,13 @@ export function loadModule(urlWithoutExtension, { loadCSS = true, loadJS = true
export async function loadAndDefine(componentConfig) {
const { tag, module: { path, loadJS, loadCSS } = {} } = componentConfig;
if (window.raqnComponents[tag]) {
return { tag, module: window.raqnComponents[tag] };
// fix
return { tag, module: await window.raqnComponents[tag] };
}
let resolveModule;
window.raqnComponents[tag] = new Promise((resolve) => {
resolveModule = resolve;
});

const { js } = loadModule(path, { loadJS, loadCSS });

Expand All @@ -475,7 +480,7 @@ export async function loadAndDefine(componentConfig) {
if (module?.default?.prototype instanceof HTMLElement) {
if (!window.customElements.get(tag)) {
window.customElements.define(tag, module.default);
window.raqnComponents[tag] = module.default;
resolveModule(module.default);
}
}
return { tag, module };
Expand Down Expand Up @@ -697,6 +702,8 @@ export const previewModule = async (path, name) => {
return name ? module[name] : module;
};

/* Yield to the main thread */

export function yieldToMain() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
Expand Down
14 changes: 9 additions & 5 deletions scripts/render/dom-reducers.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import { deepMerge, getMeta, loadAndDefine, previewModule } from '../libs.js';
import { recursive, tplPlaceholderCheck, queryTemplatePlaceholders, setPropsAndAttributes } from './dom-utils.js';
import { componentList, injectedComponents } from '../component-list/component-list.js';

window.raqnLoadedComponents ??= {};
window.raqnComponentsList ??= {};
window.raqnOnComponentsLoaded ??= [];
window.raqnComponents ??= {};
const { raqnLoadedComponents } = window;
// export those variables to be used in other modules
export const { raqnComponentsList } = window;
export const { raqnComponents } = window;
export const { raqnOnComponentsLoaded } = window;

export const forPreviewManipulation = async (manipulation) => (await previewModule(import.meta, manipulation)) || {};
export const { noContentPlaceholder, duplicatedPlaceholder } = await forPreviewManipulation();
Expand Down Expand Up @@ -51,8 +54,8 @@ const addToLoadComponents = (blockSelector, config) => {
const toLoad = [blockSelector, ...(dependencies || [])];

toLoad.forEach((load) => {
if (!raqnLoadedComponents[load]) {
raqnLoadedComponents[load] = componentList[load];
if (!raqnComponentsList[load]) {
raqnComponentsList[load] = componentList[load];
}
});
};
Expand Down Expand Up @@ -107,7 +110,7 @@ export const toWebComponent = (virtualDom) => {

// load modules in order of priority
export const loadModules = (nodes, extra = {}) => {
const modules = { ...raqnLoadedComponents, ...extra };
const modules = { ...raqnComponentsList, ...extra };
window.raqnOnComponentsLoaded = Object.keys(modules)
.filter((component) => modules[component]?.module?.path)
.sort((a, b) => modules[a].module.priority - modules[b].module.priority)
Expand All @@ -121,6 +124,7 @@ export const loadModules = (nodes, extra = {}) => {
setTimeout(async () => {
try {
const { module } = await loadAndDefine(modules[component]);

resolve(module);
} catch (error) {
reject(error);
Expand Down
Loading

0 comments on commit dd60057

Please sign in to comment.