All files / src/services jsonDocumentSymbols.ts

73.33% Statements 132/180
59.84% Branches 73/122
100% Functions 17/17
77.36% Lines 123/159

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          1x 1x 1x   1x             1x   329x     14x   8x 8x       8x     8x 8x                                               8x     8x 8x   8x   8x 76x 3x 15x 15x     73x 23x 219x 219x 218x 53x 53x 53x 53x 53x   165x               8x 76x 76x     8x 2x   8x     10x   6x 6x       6x     6x 6x                                                 6x 6x     6x 6x   6x 53x 3x 12x 12x 12x 12x 12x 12x 12x 12x 12x           50x 20x 210x 210x 210x 35x 35x 35x 35x 35x 35x   175x               6x 53x 53x     6x 2x   6x       1x 100x   19x   1x   70x   4x   6x           1x 88x 88x 86x   88x 84x   4x     1x 1x 1x 1x 1x 1x 1x 3x 3x 2x 2x 2x 2x 2x 2x   2x 2x 2x                   1x       1x 2x 2x     7x 7x       2x 1x   1x   2x   2x     1x     137x  
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
 
import * as Parser from '../parser/jsonParser';
import * as Strings from '../utils/strings';
import { colorFromHex } from '../utils/colors';
 
import {
	TextDocument, Thenable, ColorInformation, ColorPresentation, Color, ASTNode, PropertyASTNode, DocumentSymbolsContext, Range, TextEdit,
	SymbolInformation, SymbolKind, DocumentSymbol, Location
} from "../jsonLanguageTypes";
 
import { IJSONSchemaService } from "./jsonSchemaService";
 
export class JSONDocumentSymbols {
 
	constructor(private schemaService: IJSONSchemaService) {
	}
 
	public findDocumentSymbols(document: TextDocument, doc: Parser.JSONDocument, context: DocumentSymbolsContext = { resultLimit: Number.MAX_VALUE }): SymbolInformation[] {
 
		const root = doc.root;
		Iif (!root) {
			return [];
		}
 
		let limit = context.resultLimit || Number.MAX_VALUE;
 
		// special handling for key bindings
		const resourceString = document.uri;
		Iif ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
			if (root.type === 'array') {
				const result: SymbolInformation[] = [];
				for (const item of root.items) {
					if (item.type === 'object') {
						for (const property of item.properties) {
							if (property.keyNode.value === 'key' && property.valueNode) {
								const location = Location.create(document.uri, getRange(document, item));
								result.push({ name: Parser.getNodeValue(property.valueNode), kind: SymbolKind.Function, location: location });
								limit--;
								if (limit <= 0) {
									if (context && context.onResultLimitExceeded) {
										context.onResultLimitExceeded(resourceString);
									}
									return result;
								}
							}
						}
					}
				}
				return result;
			}
		}
 
		const toVisit: { node: ASTNode, containerName: string }[] = [
			{ node: root, containerName: '' }
		];
		let nextToVisit = 0;
		let limitExceeded = false;
 
		const result: SymbolInformation[] = [];
 
		const collectOutlineEntries = (node: ASTNode, containerName: string): void => {
			if (node.type === 'array') {
				node.items.forEach(node => {
					Eif (node) {
						toVisit.push({ node, containerName });
					}
				});
			} else if (node.type === 'object') {
				node.properties.forEach((property: PropertyASTNode) => {
					const valueNode = property.valueNode;
					if (valueNode) {
						if (limit > 0) {
							limit--;
							const location = Location.create(document.uri, getRange(document, property));
							const childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
							result.push({ name: this.getKeyLabel(property), kind: this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
							toVisit.push({ node: valueNode, containerName: childContainerName });
						} else {
							limitExceeded = true;
						}
					}
				});
			}
		};
 
		// breath first traversal
		while (nextToVisit < toVisit.length) {
			const next = toVisit[nextToVisit++];
			collectOutlineEntries(next.node, next.containerName);
		}
 
		if (limitExceeded && context && context.onResultLimitExceeded) {
			context.onResultLimitExceeded(resourceString);
		}
		return result;
	}
 
	public findDocumentSymbols2(document: TextDocument, doc: Parser.JSONDocument, context: DocumentSymbolsContext = { resultLimit: Number.MAX_VALUE }): DocumentSymbol[] {
 
		const root = doc.root;
		Iif (!root) {
			return [];
		}
 
		let limit = context.resultLimit || Number.MAX_VALUE;
 
		// special handling for key bindings
		const resourceString = document.uri;
		Iif ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
			if (root.type === 'array') {
				const result: DocumentSymbol[] = [];
				for (const item of root.items) {
					if (item.type === 'object') {
						for (const property of item.properties) {
							if (property.keyNode.value === 'key' && property.valueNode) {
								const range = getRange(document, item);
								const selectionRange = getRange(document, property.keyNode);
								result.push({ name: Parser.getNodeValue(property.valueNode), kind: SymbolKind.Function, range, selectionRange });
								limit--;
								if (limit <= 0) {
									if (context && context.onResultLimitExceeded) {
										context.onResultLimitExceeded(resourceString);
									}
									return result;
								}
							}
						}
					}
				}
				return result;
			}
		}
 
		const result: DocumentSymbol[] = [];
		const toVisit: { node: ASTNode, result: DocumentSymbol[] }[] = [
			{ node: root, result }
		];
		let nextToVisit = 0;
		let limitExceeded = false;
 
		const collectOutlineEntries = (node: ASTNode, result: DocumentSymbol[]) => {
			if (node.type === 'array') {
				node.items.forEach((node, index) => {
					Eif (node) {
						Eif (limit > 0) {
							limit--;
							const range = getRange(document, node);
							const selectionRange = range;
							const name = String(index);
							const symbol = { name, kind: this.getSymbolKind(node.type), range, selectionRange, children: [] };
							result.push(symbol);
							toVisit.push({ result: symbol.children, node });
						} else {
							limitExceeded = true;
						}
					}
				});
			} else if (node.type === 'object') {
				node.properties.forEach((property: PropertyASTNode) => {
					const valueNode = property.valueNode;
					Eif (valueNode) {
						if (limit > 0) {
							limit--;
							const range = getRange(document, property);
							const selectionRange = getRange(document, property.keyNode);
							const symbol = { name: this.getKeyLabel(property), kind: this.getSymbolKind(valueNode.type), range, selectionRange, children: [] };
							result.push(symbol);
							toVisit.push({ result: symbol.children, node: valueNode });
						} else {
							limitExceeded = true;
						}
					}
				});
			}
		};
 
		// breath first traversal
		while (nextToVisit < toVisit.length) {
			const next = toVisit[nextToVisit++];
			collectOutlineEntries(next.node, next.result);
		}
 
		if (limitExceeded && context && context.onResultLimitExceeded) {
			context.onResultLimitExceeded(resourceString);
		}
		return result;
	}
 
 
	private getSymbolKind(nodeType: string): SymbolKind {
		switch (nodeType) {
			case 'object':
				return SymbolKind.Module;
			case 'string':
				return SymbolKind.String;
			case 'number':
				return SymbolKind.Number;
			case 'array':
				return SymbolKind.Array;
			case 'boolean':
				return SymbolKind.Boolean;
			default: // 'null'
				return SymbolKind.Variable;
		}
	}
 
	private getKeyLabel(property: PropertyASTNode) {
		let name = property.keyNode.value;
		if (name) {
			name = name.replace(/[\n]/g, '↵');
		}
		if (name && name.trim()) {
			return name;
		}
		return `"${name}"`;
	}
 
	public findDocumentColors(document: TextDocument, doc: Parser.JSONDocument, context?: DocumentSymbolsContext): Thenable<ColorInformation[]> {
		return this.schemaService.getSchemaForResource(document.uri, doc).then(schema => {
			const result: ColorInformation[] = [];
			Eif (schema) {
				let limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
				const matchingSchemas = doc.getMatchingSchemas(schema.schema);
				const visitedNode: { [nodeId: string]: boolean } = {};
				for (const s of matchingSchemas) {
					if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
						const nodeId = String(s.node.offset);
						Eif (!visitedNode[nodeId]) {
							const color = colorFromHex(Parser.getNodeValue(s.node));
							Eif (color) {
								const range = getRange(document, s.node);
								result.push({ color, range });
							}
							visitedNode[nodeId] = true;
							limit--;
							Iif (limit <= 0) {
								if (context && context.onResultLimitExceeded) {
									context.onResultLimitExceeded(document.uri);
								}
								return result;
							}
						}
					}
				}
			}
			return result;
		});
	}
 
	public getColorPresentations(document: TextDocument, doc: Parser.JSONDocument, color: Color, range: Range): ColorPresentation[] {
		const result: ColorPresentation[] = [];
		const red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
 
		function toTwoDigitHex(n: number): string {
			const r = n.toString(16);
			return r.length !== 2 ? '0' + r : r;
		}
 
		let label;
		if (color.alpha === 1) {
			label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}`;
		} else {
			label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}${toTwoDigitHex(Math.round(color.alpha * 255))}`;
		}
		result.push({ label: label, textEdit: TextEdit.replace(range, JSON.stringify(label)) });
 
		return result;
	}
 
}
 
function getRange(document: TextDocument, node: ASTNode) {
	return Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
}