@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
46 lines (45 loc) • 1.86 kB
JavaScript
import { distributeCells, getDefaultSizes, getGridSize, isCellComponent, isCellComponentAvailable, isLayoutType } from '../../state/layout.js';
export default class LayoutSerializer {
context;
constructor(context) {
this.context = context;
}
get layout() {
return this.context.stateManager.state.layout;
}
brainSerialize(layout) {
return JSON.stringify({
type: layout.type,
cells: layout.cells,
sizes: layout.sizes
});
}
brainDeserialize(str) {
const parsedLayout = JSON.parse(str);
if (!isLayoutType(parsedLayout.type)) {
console.warn(`${parsedLayout.type} is not a valid layout. The shared layout will be ignored.`);
return;
}
this.applyLayout(parsedLayout.type, parsedLayout.cells, parsedLayout.sizes);
}
/**
* Applies a layout to the state, ignoring the values that are not valid anymore.
* A shared state can have been created by another version of the application,
* in which other components or other layouts were available.
*/
applyLayout(type, cells, sizes) {
const layout = this.layout;
const streetviewConfig = this.context.configManager.Config.streetview;
layout.type = type;
layout.cells = distributeCells(type, (cells ?? []).map((cell) => isCellComponent(cell) && isCellComponentAvailable(cell, streetviewConfig) ? cell : null));
layout.sizes = this.getValidSizes(type, sizes);
}
getValidSizes(type, sizes) {
const defaultSizes = getDefaultSizes(type);
const { columns, rows } = getGridSize(type);
if (sizes?.columns?.length !== columns || sizes?.rows?.length !== rows) {
return defaultSizes;
}
return { columns: sizes.columns, rows: sizes.rows };
}
}