All files / src/app/map/drawing drawing.service.ts

38.27% Statements 31/81
0% Branches 0/14
22.22% Functions 2/9
38.46% Lines 30/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303                                  1x             11x   11x 11x 11x 11x       11x 11x   11x           1x         1x 1x   1x 1x 1x 1x 1x                 1x                                             1x       1x 1x       1x   1x                 1x                     1x                                                                                                             1x                                                                                           1x                                     1x                                     1x                                                                                         1x  
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { loadModules } from 'esri-loader';
 
import { MapComponent } from '../map.component';
import { CircleDrawer } from './circle-drawer';
import { PolygonDrawer } from './polygon-drawer';
import { LineDrawer } from './line-drawer';
import { StripesDrawer } from './stripes-drawer';
import { MarkerDrawer } from './marker-drawer';
import { DrawingShape, DrawingTexture, stripesWidth } from './utils';
import { subtract, arrayToVector, scalarMultiplication, add, normal } from '../../geometry/geometry2d';
import { BsModalService } from 'ngx-bootstrap';
 
@Injectable({
  providedIn: 'root'
})
export class DrawingService {
 
  drawingShape: DrawingShape;
  drawingTexture: DrawingTexture;
 
  private editor: __esri.SketchViewModel;
 
  private actionListeners: IHandle[] = [];
 
  private circleDrawer = new CircleDrawer();
  private polygonDrawer = new PolygonDrawer();
  private lineDrawer = new LineDrawer();
  private stripesDrawer = new StripesDrawer();
  private markerDrawer: MarkerDrawer;
 
  constructor(
    private translate: TranslateService,
    private modalService: BsModalService
  ) {
    this.markerDrawer = new MarkerDrawer(this.translate, modalService);
  }
 
  /**
   * Clear all the service's listeners for DrawAction events.
   */
  clearListeners() {
    if (this.editor) {
      this.editor.complete();
    }
 
    this.actionListeners.forEach((listener) => listener.remove());
    this.actionListeners = [];
 
    this.circleDrawer.clearListeners();
    this.polygonDrawer.clearListeners();
    this.lineDrawer.clearListeners();
    this.stripesDrawer.clearListeners();
    this.markerDrawer.clearListeners();
  }
 
  /**
   * Start drawing the current shape with the current texture on the MapComponent passed
   * as input to the method.
   *
   * @param mapView The MapComponent on which the shape must be drawn.
   */
  async draw(
    map: MapComponent
  ) {
    this.clearListeners();
 
    if (this.drawingShape === DrawingShape.POLYGON) {
      this.polygonDrawer.draw(map, this.drawingTexture);
    } else if (this.drawingShape === DrawingShape.CIRCLE) {
      this.circleDrawer.draw(map, this.drawingTexture);
    } else if (this.drawingShape === DrawingShape.LINE) {
      this.lineDrawer.draw(map);
    } else if (this.drawingShape === DrawingShape.STRIPES) {
      this.stripesDrawer.draw(map);
    } else if (this.drawingShape === DrawingShape.MARKER) {
      this.markerDrawer.draw(map);
    }
  }
 
  /**
   * Start a handler to edit graphics in the drawingsLayer of a MapComponent.
   *
   * @param map The MapComponent whose graphics must be edited.
   */
  async editGraphics(
    map: MapComponent
  ) {
    const [
      SketchViewModel
    ] = await loadModules([
      'esri/widgets/Sketch/SketchViewModel'
    ]);
 
    this.clearListeners();
 
    this.editor = new SketchViewModel({
      view: map.mapView,
      layer: map.drawingsLayer,
      updateOnGraphicClick: false,
      defaultUpdateOperations: {
        toggleToolOnClick: false
      }
    });
 
    this.actionListeners.push(
      map.mapView.on(
        'click',
        (event) => {
          this.handleEditionClick(event, map);
        }
      )
    );
 
    // A listener is added on the 'update' event of the editor to handle special cases
    // such as lines and stripes.
    this.actionListeners.push(
 
      this.editor.on(
        'update',
        async (event) => {
          if (event.state === 'complete') {
            if (event.graphics[0].geometry.type === 'polyline') {
 
              // When a line (polyline) is edited, a white background
              // must be added to it again once modifications are over.
              this.editor.layer.remove(event.graphics[0]);
              await this.lineDrawer.setBackground(map, event.graphics[0].attributes.id, event.graphics[0].geometry);
              this.editor.layer.add(event.graphics[0]);
 
            } else if (event.graphics[0].attributes &&
                       event.graphics[0].attributes.temporaryStripes) {
 
              // When stripes are edited, the graphics (black and white stripes) that compose it
              // are removed from the maps drawingsLayer and it is replaced by a simple temporary rectangle for edition.
              // Once edition on is complete, the stripes must be added back to the graphics layer,
              // and the temporary replacement rectangle is deleted.
              const line = subtract(
                arrayToVector(event.graphics[0].geometry.rings[0][0]),
                arrayToVector(event.graphics[0].geometry.rings[0][1])
              );
              const lineNormal = scalarMultiplication(normal(line), stripesWidth);
 
              const start = add(
                arrayToVector(event.graphics[0].geometry.rings[0][0]),
                lineNormal
              );
              const end = add(
                arrayToVector(event.graphics[0].geometry.rings[0][1]),
                lineNormal
              );
 
              this.editor.layer.remove(event.graphics[0]);
              this.stripesDrawer.createFinalStripes(
                map,
                start,
                end
              );
            }
          }
        }
      )
    );
  }
 
  /**
   * React to a click on a map to edit graphics.
   *
   * @param event The MapViewClickEvent to react to.
   * @param map The MapComponent on which the graphics to edit are.
   */
  private async handleEditionClick(
    event: __esri.MapViewClickEvent,
    map: MapComponent
  ) {
    if (this.editor.state === 'active') {
      return;
    }
 
    map.mapView.hitTest(event).then(
      (response) => {
        const result = response.results[0];
 
        if (result.graphic.layer === this.editor.layer) {
          // Ignore guiding lines backgrounds.
          if (result.graphic.attributes && result.graphic.attributes.background) {
            return;
          }
 
          /* Guiding lines and pedestrian passages need to be handled specifically, as they
             are composed of multiple graphics instead of one. */
          if (result.graphic.geometry.type === 'polyline') {
            const background = this.lineDrawer.getBackground(map, result.graphic);
            this.editor.layer.graphics.remove(background);
            this.editor.update([result.graphic], {tool: 'transform'});
 
          // Markers are edited by setting the text associated to them.
          } else if (result.graphic.geometry.type === 'point') {
            this.markerDrawer.setTextAttribute(result.graphic);
 
          } else if (result.graphic.attributes && result.graphic.attributes.stripes) {
            this.handleStripesEdition(map, result.graphic);
 
          } else {
            this.editor.update([result.graphic], {tool: 'transform'});
          }
        }
      });
  }
 
  /**
   * Handle a click on stripes to edit them.
   *
   * @param map The MapComponent on which the stripes that must be edited are displayed.
   * @param graphic The graphic belonging to the pedestrian passage
   * that must be edited and which was clicked.
   */
  private async handleStripesEdition(
    map: MapComponent,
    graphic: __esri.Graphic
  ) {
    /* When a passage is edited, its graphics are retrieved and removed from the graphics layer,
       and it is temporarily replaced by a simple rectangle. */
    const id = graphic.attributes.id;
    const startEnd = this.stripesDrawer.deleteStripes(map, id);
    const temporaryStripes = await this.stripesDrawer.createTemporaryStripes(map.mapView, startEnd[0], startEnd[1]);
    this.editor.layer.add(temporaryStripes);
    this.editor.update([temporaryStripes], {tool: 'transform'});
  }
 
  /**
   * Start a handler to react to clicks on the input MapComponent to delete graphics.
   *
   * @param map The MapComponent on which the user clicks to delete graphics.
   * @param graphicsLayer The GraphicsLayer in which the graphics to delete are.
   */
  async deleteGraphics(
    map: MapComponent,
  ) {
    this.clearListeners();
 
    this.actionListeners.push(
      map.mapView.on(
        'click',
        (event: __esri.MapViewClickEvent) => this.handleDeletionClick(event, map)
      )
    );
  }
 
  /**
   * React to a click on a MapComponent to delete some graphics.
   *
   * @param event The MapViewClickEvent to react to.
   * @param map The MapComponent on which the graphics to delete are.
   */
  private async handleDeletionClick(
    event: __esri.MapViewClickEvent,
    map: MapComponent
  ) {
    const [
      geometryEngine,
      Circle
    ] = await loadModules([
      'esri/geometry/geometryEngine',
      'esri/geometry/Circle'
    ]);
 
    const matchingGraphics = map.drawingsLayer.graphics.filter(
      // First check if the graphic has a geometry, and then if it intersects with the click.
      (graphic) => graphic.geometry && geometryEngine.intersects(
        graphic.geometry,
        // Create a circle geometry around the position of the click to handle clicks on a line.
        new Circle({center: event.mapPoint, radius: 3}))
    );
 
    const messagesPromises: Promise<string>[] = [];
    messagesPromises.push(this.translate.get('top-bar.confirmMultipleGraphicsDeletion').toPromise());
    messagesPromises.push(this.translate.get('top-bar.confirmSingleGraphicDeletion').toPromise());
 
    Promise.all(messagesPromises).then(
      (messages) => {
        if (
          matchingGraphics.length > 1 && confirm(messages[0]) ||
          matchingGraphics.length === 1 && confirm(messages[1])
        ) {
          matchingGraphics.forEach(
            (graphic) => {
              // Stripes are represented by a set of graphics, they hence need to be handled
              // differently (each graphic which is part of it must be retrieved and deleted separately).
              if (graphic.attributes && graphic.attributes.stripes) {
                this.stripesDrawer.deleteStripes(map, graphic.attributes.id);
              } else {
                map.drawingsLayer.remove(graphic);
              }
            }
          );
        }
      }
    );
  }
}