dyomedea/src/components/gpx/styles.ts

123 lines
2.7 KiB
TypeScript
Raw Normal View History

2022-11-29 18:49:05 +00:00
import { Fill, Text, Icon, Stroke, Style } from 'ol/style';
2022-11-28 07:38:21 +00:00
import startIcon from '../../icons/flag-start-b-svgrepo-com-green.svg';
import finishIcon from '../../icons/flag-finish-b-o-svgrepo-com-red.svg';
2022-11-28 18:33:02 +00:00
import wptIcon from '../../icons/location-pin-svgrepo-com-red.svg';
2022-11-28 07:38:21 +00:00
import { Feature } from 'ol';
2022-11-29 18:49:05 +00:00
import memoize from 'memoizee';
2022-11-28 07:38:21 +00:00
2022-11-29 18:49:05 +00:00
interface StyleParameters {
type: string;
isSelected: boolean;
}
2022-11-28 07:38:21 +00:00
2022-11-28 11:14:09 +00:00
const textStroke = new Stroke({
color: '#fff',
width: 3,
});
const textFill = new Fill({
color: '#000',
});
2022-11-29 18:49:05 +00:00
const styles = {
default: {
trkseg: {
stroke: new Stroke({
color: 'blue',
width: 3,
}),
},
'trkseg-start': {
image: new Icon({
src: startIcon,
scale: 0.2,
opacity: 0.6,
anchor: [0.5, 1],
}),
},
'trkseg-finish': {
image: new Icon({
src: finishIcon,
scale: 0.2,
opacity: 0.6,
anchor: [0.5, 1],
}),
},
wpt: {
image: new Icon({
src: wptIcon,
scale: 0.1,
opacity: 0.9,
anchor: [0.5, 1],
}),
text: (feature: Feature) =>
new Text({
font: '16px Calibri,sans-serif',
text: feature.get('name'),
fill: textFill,
stroke: textStroke,
offsetY: -40,
}),
},
},
selected: {
trkseg: {
stroke: new Stroke({
color: 'red',
width: 3,
}),
},
},
};
2022-11-28 11:14:09 +00:00
2022-11-29 18:49:05 +00:00
const styleRequiresFeature = memoize((type: keyof typeof styles.default) => {
const defaults = styles.default[type];
const selected = styles.selected[type];
const all = { ...defaults, ...selected };
for (const key of Object.keys(all)) {
if (all[key] instanceof Function) {
return true;
}
}
return false;
});
2022-11-28 07:38:21 +00:00
2022-11-29 18:49:05 +00:00
const getStyle = memoize(
(
type: keyof typeof styles.default,
isSelected: boolean = false,
params: any
) => {
const defaults = styles.default[type];
const selected = styles.selected[type];
const all = isSelected ? { ...defaults, ...selected } : { ...defaults };
console.log({
caller: 'style / getStyle',
type,
isSelected,
params,
defaults,
selected,
all,
});
for (const key of Object.keys(all)) {
if (all[key] instanceof Function) {
all[key] = all[key](params);
}
}
return new Style(all);
},
{ length: 3, max: 1024 }
);
2022-11-28 10:52:50 +00:00
2022-11-28 07:38:21 +00:00
export const style = (feature: Feature, resolution: number) => {
const type = feature.get('type');
2022-11-29 18:49:05 +00:00
const isSelected = feature.get('isSelected') === true;
console.log({ caller: 'style', type, isSelected });
if (styleRequiresFeature(type)) {
return getStyle(type, isSelected, feature);
2022-11-28 10:52:50 +00:00
}
2022-11-29 18:49:05 +00:00
return getStyle(type, isSelected, null);
2022-11-28 07:38:21 +00:00
};
export default style;