Skip to content

Commit

Permalink
style should be an object in react not a string
Browse files Browse the repository at this point in the history
  • Loading branch information
ac-willeke committed Jun 7, 2024
1 parent 31a54cf commit 2cb6542
Showing 1 changed file with 42 additions and 5 deletions.
47 changes: 42 additions & 5 deletions src/pages/viewer/components/LegendSymbol.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,34 @@ import { createElement } from 'react';

// Based on: https://github.com/watergis/maplibre-gl-legend/blob/main/packages/maplibre-gl-legend/src/lib/index.ts#L124

const formatStringToCamelCase = str => {
const splitted = str.split("-");
if (splitted.length === 1) return splitted[0];
return (
splitted[0] +
splitted
.slice(1)
.map(word => word[0].toUpperCase() + word.slice(1))
.join("")
);
};

const getStyleObjectFromString = str => {
const style = {};
str.split(";").forEach(el => {
const [property, value] = el.split(":");
if (!property) return;

const formattedProperty = formatStringToCamelCase(property.trim());
style[formattedProperty] = value.trim();
});

return style;
};

// Transforms xml attributes in React compatible attributes (dash to camelCase, className)
function transformAttributes(attributes) {
console.log(attributes)
const copy = {}
Object.keys(attributes).forEach(k => {
copy[k.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase())] = attributes[k];
Expand All @@ -15,6 +41,10 @@ function transformAttributes(attributes) {
delete copy.class;
}

if (copy.style) {
copy.style = getStyleObjectFromString(copy.style);
}

return copy;
}

Expand All @@ -23,17 +53,24 @@ function toComponent(json) {
}

function LegendSymbol(layer, map) {
let symbol = toComponent(Symbol({
sprite: layer.sprite,
zoom: map.getZoom(),
layer: layer,
}), [layer]);
let symbol = null;
try {
symbol = toComponent(Symbol({
sprite: layer.sprite,
zoom: map.getZoom(),
layer: layer,
}), [layer]);
} catch (e) {
console.error('Error while creating legend symbol', e, layer, map);
}

// fallback for raster images
if (!symbol) {
return <i className='fas fa-image'></i>
}

console.log(layer.id, symbol)

return symbol;
}

Expand Down

0 comments on commit 2cb6542

Please sign in to comment.