| 29 | } |
| 30 | |
| 31 | export default function withMapControl({ getFormat, getMap } = {}) { |
| 32 | return class MapControl extends Component { |
| 33 | static propTypes = { |
| 34 | onChange: PropTypes.func.isRequired, |
| 35 | field: PropTypes.object.isRequired, |
| 36 | height: PropTypes.string, |
| 37 | value: PropTypes.node, |
| 38 | }; |
| 39 | |
| 40 | static defaultProps = { |
| 41 | value: '', |
| 42 | height: '400px', |
| 43 | }; |
| 44 | |
| 45 | constructor(props) { |
| 46 | super(props); |
| 47 | this.mapContainer = createRef(); |
| 48 | this.resizeObserver = null; |
| 49 | } |
| 50 | |
| 51 | componentDidMount() { |
| 52 | // Manually validate PropTypes - React 19 breaking change |
| 53 | PropTypes.checkPropTypes(MapControl.propTypes, this.props, 'prop', 'MapControl'); |
| 54 | |
| 55 | const { field, onChange, value } = this.props; |
| 56 | const format = getFormat ? getFormat(field) : getDefaultFormat(field); |
| 57 | const features = value ? [format.readFeature(value)] : []; |
| 58 | |
| 59 | const featuresSource = new VectorSource({ features, wrapX: false }); |
| 60 | const featuresLayer = new VectorLayer({ source: featuresSource }); |
| 61 | |
| 62 | const target = this.mapContainer.current; |
| 63 | const map = getMap ? getMap(target, featuresLayer) : getDefaultMap(target, featuresLayer); |
| 64 | if (features.length > 0) { |
| 65 | map.getView().fit(featuresSource.getExtent(), { maxZoom: 16, padding: [80, 80, 80, 80] }); |
| 66 | } |
| 67 | |
| 68 | const draw = new Draw({ source: featuresSource, type: field.get('type', 'Point') }); |
| 69 | map.addInteraction(draw); |
| 70 | |
| 71 | const writeOptions = { decimals: field.get('decimals', 7) }; |
| 72 | draw.on('drawend', ({ feature }) => { |
| 73 | featuresSource.clear(); |
| 74 | onChange(format.writeGeometry(feature.getGeometry(), writeOptions)); |
| 75 | }); |
| 76 | |
| 77 | this.resizeObserver = new ResizeObserver(() => { |
| 78 | map.updateSize(); |
| 79 | }); |
| 80 | |
| 81 | this.resizeObserver.observe(target); |
| 82 | } |
| 83 | |
| 84 | componentWillUnmount() { |
| 85 | if (this.resizeObserver) { |
| 86 | this.resizeObserver.disconnect(); |
| 87 | } |
| 88 | } |