View Javadoc
1   /*
2    * Copyright (c) 2020 bahlef.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the Eclipse Public License v2.0
5    * which accompanies this distribution, and is available at
6    * http://www.eclipse.org/legal/epl-v20.html
7    * Contributors:
8    * bahlef - initial API and implementation and/or initial documentation
9    */
10  package de.funfried.netbeans.plugins.external.formatter.javascript.base;
11  
12  import java.util.Collections;
13  import java.util.List;
14  import java.util.SortedSet;
15  
16  import javax.swing.text.BadLocationException;
17  import javax.swing.text.StyledDocument;
18  
19  import org.apache.commons.lang3.tuple.Pair;
20  
21  import de.funfried.netbeans.plugins.external.formatter.FormatJob;
22  import de.funfried.netbeans.plugins.external.formatter.FormatterService;
23  import de.funfried.netbeans.plugins.external.formatter.MimeType;
24  import de.funfried.netbeans.plugins.external.formatter.exceptions.FormattingFailedException;
25  
26  /**
27   * Abstract base implementation of {@link FormatterService} for javascript formatters.
28   *
29   * @author bahlef
30   */
31  public abstract class AbstractJavascriptFormatterService implements FormatterService {
32  	/**
33  	 * Returns the {@link FormatJob}.
34  	 *
35  	 * @param document the {@link StyledDocument} which should be formatted
36  	 * @param changedElement an optional range as a {@link Pair} object defining the offsets which should be formatted
37  	 */
38  	protected abstract FormatJob getFormatJob(StyledDocument document, Pair<Integer, Integer> changedElement);
39  
40  	/**
41  	 * {@inheritDoc}
42  	 */
43  	@Override
44  	public boolean format(StyledDocument document, SortedSet<Pair<Integer, Integer>> changedElements) throws BadLocationException, FormattingFailedException {
45  		if (!canHandle(document)) {
46  			throw new FormattingFailedException("The file type '" + MimeType.getMimeTypeAsString(document) + "' is not supported");
47  		}
48  
49  		getFormatJob(document, changedElements != null ? changedElements.first() : null).format();
50  
51  		return true;
52  	}
53  
54  	/**
55  	 * {@inheritDoc}
56  	 */
57  	@Override
58  	public List<MimeType> getSupportedMimeTypes() {
59  		return Collections.singletonList(MimeType.JAVASCRIPT);
60  	}
61  }