import { Fill, Text, Icon, Stroke, Style } from 'ol/style'; import startIcon from '../../icons/flag-start-b-svgrepo-com-green.svg'; import finishIcon from '../../icons/flag-finish-b-o-svgrepo-com-red.svg'; import wptIcon from '../../icons/location-pin-svgrepo-com-red.svg'; import { Feature } from 'ol'; import memoize from 'memoizee'; interface StyleParameters { type: string; isSelected: boolean; } const textStroke = new Stroke({ color: '#fff', width: 3, }); const textFill = new Fill({ color: '#000', }); 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, }), }, }, }; 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; }); 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 } ); export const style = (feature: Feature, resolution: number) => { const type = feature.get('type'); const isSelected = feature.get('isSelected') === true; console.log({ caller: 'style', type, isSelected }); if (styleRequiresFeature(type)) { return getStyle(type, isSelected, feature); } return getStyle(type, isSelected, null); }; export default style;