@thebigcrunch/sdk
Version:
The big crunch SDK library
90 lines (77 loc) • 3.01 kB
JavaScript
// This file is separate to the renderers file because drawing layers is more complicated than
// the other renders
import {
getOptions,
setElementToSpaceRatio,
createElementForSpace,
setFullHeightWidth,
setElementToParentSize
} from "./common";
import { renderSpaceIntoElement } from "./renderers";
import { crunch } from "../crunch";
import { types } from "../constants";
const createTurtleDivFromLayer = function createTurtleDivFromLayer(layer) {
const element = document.createElement("div");
const properties = layer.properties;
element.style.width = properties.width;
element.style.height = properties.height;
element.style.top = properties.top;
element.style.left = properties.left;
element.style.position = "absolute";
return element;
};
export const crunchLayer = function crunchLayer(location, layerDiv) {
// Fetch the space from the server
return crunch(location, (value, layerSpace) => {
// Empty the div, if we're rendering for a second time
layerDiv.innerHTML = "";
if (value === null && layerSpace.type !== types.visualisation) {
return;
}
// Get the element to draw into canvas or div
const renderElement = createElementForSpace(layerSpace, layerDiv);
setFullHeightWidth(renderElement);
layerDiv.appendChild(renderElement);
// Draw the layer
renderSpaceIntoElement(layerSpace, renderElement, { fit: "stretch" }); // Turtles stretch
});
};
/**
* Renders a layered space to the canvas.
* @param space
* @param element a document element to put the layers in
* @param opts {fit: 'stretch or cellaspect }
* @param depth the recursive count
*/
export default function renderLayersToElement(space, element, opts, depth = 5) {
if (depth === 0) return;
const options = getOptions(opts);
const turtleContainer = document.createElement("div");
setElementToParentSize(turtleContainer, element);
element.appendChild(turtleContainer);
if (options.fit === "cellaspect") {
setElementToSpaceRatio(space, turtleContainer, options);
}
// This makes sure the turtle layers overlay.
turtleContainer.style.position = "relative";
turtleContainer.style.overflow = "hidden";
const baseElement = createElementForSpace(space);
setElementToParentSize(baseElement, turtleContainer);
// Append element before renderering so it's got a size.
turtleContainer.appendChild(baseElement);
renderSpaceIntoElement(space, baseElement, options);
const layerConnections = [];
space.layers.forEach(layer => {
// Create a div for this layer
const layerDiv = createTurtleDivFromLayer(layer);
turtleContainer.appendChild(layerDiv);
layerConnections.push(crunchLayer(layer.location, layerDiv, depth));
});
return {
close: () => {
layerConnections.forEach(conn => {
conn.close();
});
}
};
}