function prepareStyles(styles, commands = []) {
let lastStyle, lastStyleCommands, lastDrawCommands;
const setCurrentStyle = (style) => {
if (!style) return false;
if (lastStyle !== style) {
lastStyle = style;
const commands = getStyleCommands(style);
lastStyleCommands = commands[0];
lastDrawCommands = commands[1];
}
return lastDrawCommands && lastDrawCommands.length > 0;
}
return Object.assign((layer) => {
const layerStyles = styles[layer.name] || styles['default'];
if (!layerStyles) return ;
return (feature, layer) => {
if (layerStyles.filter && !layerStyles.filter(feature, layer)) return ;
return (geometryType, feature, layer) => {
if (geometryType === 'Point') {
const pointStyle = layerStyles.points;
if (!setCurrentStyle(pointStyle)) return ;
const radius = pointStyle.radius || 1;
commands.push(...lastStyleCommands);
return {
onPoint(x, y, feature, layer) {
commands.push(['beginPath'], ['arc', x, y, radius, 0, 2 * Math.PI], ['closePath']);
commands.push(...lastDrawCommands);
}
}
}
if (geometryType === 'LineString') {
const lineStyle = layerStyles.lines;
if (!setCurrentStyle(lineStyle)) return ;
commands.push(...lastStyleCommands);
return {
beginLine(feature, layer) {
commands.push(['beginPath']);
this.start = true;
},
onLinePoint(x, y, feature, layer) {
commands.push([this.start ? 'moveTo' : 'lineTo', x, y]);
this.start = false;
},
endLine(feature, layer) {
commands.push(...lastDrawCommands); }
}
}
if (geometryType === 'Polygon') {
const polygonStyle = layerStyles.polygons;
if (!setCurrentStyle(polygonStyle)) return ;
commands.push(...lastStyleCommands);
return {
beginPolygon(feature, layer) { commands.push(['beginPath']); },
beginPolygonRing(feature, layer) { this.start = true; },
onPolygonPoint(x, y, feature, layer) {
commands.push([this.start ? 'moveTo' : 'lineTo', x, y]);
this.start = false;
},
endPolygon(feature, layer) {
commands.push(['closePath']);
commands.push(...lastDrawCommands);
}
}
}
}
}
}, { commands });
function getStyleCommands(style) {
const styleCommands = [];
const drawCommands = [];
let styleArgs = {};
let lineDash = [];
for (let [key, value] of Object.entries(style)) {
if (key === 'lineDash') { lineDash = value; }
if (key === 'id' || key === 'radius') continue;
else { styleArgs[key] = value; }
}
let fill = !!styleArgs.fillStyle;
let stroke = false;
if (styleArgs.strokeStyle && styleArgs.lineWidth !== 0) {
styleArgs.lineWidth = styleArgs.lineWidth || 1; // Set 1 if lineWidth is not defined
styleCommands.push(['setLineDash', lineDash]);
stroke = true;
}
if (fill || stroke) { styleCommands.push(['setStyle', styleArgs]); }
if (fill) drawCommands.push(['fill']);
if (stroke) drawCommands.push(['stroke']);
return [styleCommands, drawCommands];
}
}