Best JavaScript code snippet using playwright-internal
linesLayout.js
Source:linesLayout.js
1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5'use strict';6import { WhitespaceComputer } from './whitespaceComputer.js';7/**8 * Layouting of objects that take vertical space (by having a height) and push down other objects.9 *10 * These objects are basically either text (lines) or spaces between those lines (whitespaces).11 * This provides commodity operations for working with lines that contain whitespace that pushes lines lower (vertically).12 * This is written with no knowledge of an editor in mind.13 */14var LinesLayout = /** @class */ (function () {15 function LinesLayout(lineCount, lineHeight) {16 this._lineCount = lineCount;17 this._lineHeight = lineHeight;18 this._whitespaces = new WhitespaceComputer();19 }20 /**21 * Change the height of a line in pixels.22 */23 LinesLayout.prototype.setLineHeight = function (lineHeight) {24 this._lineHeight = lineHeight;25 };26 /**27 * Set the number of lines.28 *29 * @param lineCount New number of lines.30 */31 LinesLayout.prototype.onFlushed = function (lineCount) {32 this._lineCount = lineCount;33 };34 /**35 * Insert a new whitespace of a certain height after a line number.36 * The whitespace has a "sticky" characteristic.37 * Irrespective of edits above or below `afterLineNumber`, the whitespace will follow the initial line.38 *39 * @param afterLineNumber The conceptual position of this whitespace. The whitespace will follow this line as best as possible even when deleting/inserting lines above/below.40 * @param heightInPx The height of the whitespace, in pixels.41 * @return An id that can be used later to mutate or delete the whitespace42 */43 LinesLayout.prototype.insertWhitespace = function (afterLineNumber, ordinal, heightInPx) {44 return this._whitespaces.insertWhitespace(afterLineNumber, ordinal, heightInPx);45 };46 /**47 * Change properties associated with a certain whitespace.48 */49 LinesLayout.prototype.changeWhitespace = function (id, newAfterLineNumber, newHeight) {50 return this._whitespaces.changeWhitespace(id, newAfterLineNumber, newHeight);51 };52 /**53 * Remove an existing whitespace.54 *55 * @param id The whitespace to remove56 * @return Returns true if the whitespace is found and it is removed.57 */58 LinesLayout.prototype.removeWhitespace = function (id) {59 return this._whitespaces.removeWhitespace(id);60 };61 /**62 * Notify the layouter that lines have been deleted (a continuous zone of lines).63 *64 * @param fromLineNumber The line number at which the deletion started, inclusive65 * @param toLineNumber The line number at which the deletion ended, inclusive66 */67 LinesLayout.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) {68 this._lineCount -= (toLineNumber - fromLineNumber + 1);69 this._whitespaces.onLinesDeleted(fromLineNumber, toLineNumber);70 };71 /**72 * Notify the layouter that lines have been inserted (a continuous zone of lines).73 *74 * @param fromLineNumber The line number at which the insertion started, inclusive75 * @param toLineNumber The line number at which the insertion ended, inclusive.76 */77 LinesLayout.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) {78 this._lineCount += (toLineNumber - fromLineNumber + 1);79 this._whitespaces.onLinesInserted(fromLineNumber, toLineNumber);80 };81 /**82 * Get the sum of heights for all objects.83 *84 * @return The sum of heights for all objects.85 */86 LinesLayout.prototype.getLinesTotalHeight = function () {87 var linesHeight = this._lineHeight * this._lineCount;88 var whitespacesHeight = this._whitespaces.getTotalHeight();89 return linesHeight + whitespacesHeight;90 };91 /**92 * Get the vertical offset (the sum of heights for all objects above) a certain line number.93 *94 * @param lineNumber The line number95 * @return The sum of heights for all objects above `lineNumber`.96 */97 LinesLayout.prototype.getVerticalOffsetForLineNumber = function (lineNumber) {98 lineNumber = lineNumber | 0;99 var previousLinesHeight;100 if (lineNumber > 1) {101 previousLinesHeight = this._lineHeight * (lineNumber - 1);102 }103 else {104 previousLinesHeight = 0;105 }106 var previousWhitespacesHeight = this._whitespaces.getAccumulatedHeightBeforeLineNumber(lineNumber);107 return previousLinesHeight + previousWhitespacesHeight;108 };109 /**110 * Returns the accumulated height of whitespaces before the given line number.111 *112 * @param lineNumber The line number113 */114 LinesLayout.prototype.getWhitespaceAccumulatedHeightBeforeLineNumber = function (lineNumber) {115 return this._whitespaces.getAccumulatedHeightBeforeLineNumber(lineNumber);116 };117 /**118 * Returns if there is any whitespace in the document.119 */120 LinesLayout.prototype.hasWhitespace = function () {121 return this._whitespaces.getCount() > 0;122 };123 /**124 * Check if `verticalOffset` is below all lines.125 */126 LinesLayout.prototype.isAfterLines = function (verticalOffset) {127 var totalHeight = this.getLinesTotalHeight();128 return verticalOffset > totalHeight;129 };130 /**131 * Find the first line number that is at or after vertical offset `verticalOffset`.132 * i.e. if getVerticalOffsetForLine(line) is x and getVerticalOffsetForLine(line + 1) is y, then133 * getLineNumberAtOrAfterVerticalOffset(i) = line, x <= i < y.134 *135 * @param verticalOffset The vertical offset to search at.136 * @return The line number at or after vertical offset `verticalOffset`.137 */138 LinesLayout.prototype.getLineNumberAtOrAfterVerticalOffset = function (verticalOffset) {139 verticalOffset = verticalOffset | 0;140 if (verticalOffset < 0) {141 return 1;142 }143 var linesCount = this._lineCount | 0;144 var lineHeight = this._lineHeight;145 var minLineNumber = 1;146 var maxLineNumber = linesCount;147 while (minLineNumber < maxLineNumber) {148 var midLineNumber = ((minLineNumber + maxLineNumber) / 2) | 0;149 var midLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(midLineNumber) | 0;150 if (verticalOffset >= midLineNumberVerticalOffset + lineHeight) {151 // vertical offset is after mid line number152 minLineNumber = midLineNumber + 1;153 }154 else if (verticalOffset >= midLineNumberVerticalOffset) {155 // Hit156 return midLineNumber;157 }158 else {159 // vertical offset is before mid line number, but mid line number could still be what we're searching for160 maxLineNumber = midLineNumber;161 }162 }163 if (minLineNumber > linesCount) {164 return linesCount;165 }166 return minLineNumber;167 };168 /**169 * Get all the lines and their relative vertical offsets that are positioned between `verticalOffset1` and `verticalOffset2`.170 *171 * @param verticalOffset1 The beginning of the viewport.172 * @param verticalOffset2 The end of the viewport.173 * @return A structure describing the lines positioned between `verticalOffset1` and `verticalOffset2`.174 */175 LinesLayout.prototype.getLinesViewportData = function (verticalOffset1, verticalOffset2) {176 verticalOffset1 = verticalOffset1 | 0;177 verticalOffset2 = verticalOffset2 | 0;178 var lineHeight = this._lineHeight;179 // Find first line number180 // We don't live in a perfect world, so the line number might start before or after verticalOffset1181 var startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;182 var startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;183 var endLineNumber = this._lineCount | 0;184 // Also keep track of what whitespace we've got185 var whitespaceIndex = this._whitespaces.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0;186 var whitespaceCount = this._whitespaces.getCount() | 0;187 var currentWhitespaceHeight;188 var currentWhitespaceAfterLineNumber;189 if (whitespaceIndex === -1) {190 whitespaceIndex = whitespaceCount;191 currentWhitespaceAfterLineNumber = endLineNumber + 1;192 currentWhitespaceHeight = 0;193 }194 else {195 currentWhitespaceAfterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;196 currentWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(whitespaceIndex) | 0;197 }198 var currentVerticalOffset = startLineNumberVerticalOffset;199 var currentLineRelativeOffset = currentVerticalOffset;200 // IE (all versions) cannot handle units above about 1,533,908 px, so every 500k pixels bring numbers down201 var STEP_SIZE = 500000;202 var bigNumbersDelta = 0;203 if (startLineNumberVerticalOffset >= STEP_SIZE) {204 // Compute a delta that guarantees that lines are positioned at `lineHeight` increments205 bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE) * STEP_SIZE;206 bigNumbersDelta = Math.floor(bigNumbersDelta / lineHeight) * lineHeight;207 currentLineRelativeOffset -= bigNumbersDelta;208 }209 var linesOffsets = [];210 var verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;211 var centeredLineNumber = -1;212 // Figure out how far the lines go213 for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {214 if (centeredLineNumber === -1) {215 var currentLineTop = currentVerticalOffset;216 var currentLineBottom = currentVerticalOffset + lineHeight;217 if ((currentLineTop <= verticalCenter && verticalCenter < currentLineBottom) || currentLineTop > verticalCenter) {218 centeredLineNumber = lineNumber;219 }220 }221 // Count current line height in the vertical offsets222 currentVerticalOffset += lineHeight;223 linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;224 // Next line starts immediately after this one225 currentLineRelativeOffset += lineHeight;226 while (currentWhitespaceAfterLineNumber === lineNumber) {227 // Push down next line with the height of the current whitespace228 currentLineRelativeOffset += currentWhitespaceHeight;229 // Count current whitespace in the vertical offsets230 currentVerticalOffset += currentWhitespaceHeight;231 whitespaceIndex++;232 if (whitespaceIndex >= whitespaceCount) {233 currentWhitespaceAfterLineNumber = endLineNumber + 1;234 }235 else {236 currentWhitespaceAfterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;237 currentWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(whitespaceIndex) | 0;238 }239 }240 if (currentVerticalOffset >= verticalOffset2) {241 // We have covered the entire viewport area, time to stop242 endLineNumber = lineNumber;243 break;244 }245 }246 if (centeredLineNumber === -1) {247 centeredLineNumber = endLineNumber;248 }249 var endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0;250 var completelyVisibleStartLineNumber = startLineNumber;251 var completelyVisibleEndLineNumber = endLineNumber;252 if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {253 if (startLineNumberVerticalOffset < verticalOffset1) {254 completelyVisibleStartLineNumber++;255 }256 }257 if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {258 if (endLineNumberVerticalOffset + lineHeight > verticalOffset2) {259 completelyVisibleEndLineNumber--;260 }261 }262 return {263 bigNumbersDelta: bigNumbersDelta,264 startLineNumber: startLineNumber,265 endLineNumber: endLineNumber,266 relativeVerticalOffset: linesOffsets,267 centeredLineNumber: centeredLineNumber,268 completelyVisibleStartLineNumber: completelyVisibleStartLineNumber,269 completelyVisibleEndLineNumber: completelyVisibleEndLineNumber270 };271 };272 LinesLayout.prototype.getVerticalOffsetForWhitespaceIndex = function (whitespaceIndex) {273 whitespaceIndex = whitespaceIndex | 0;274 var afterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);275 var previousLinesHeight;276 if (afterLineNumber >= 1) {277 previousLinesHeight = this._lineHeight * afterLineNumber;278 }279 else {280 previousLinesHeight = 0;281 }282 var previousWhitespacesHeight;283 if (whitespaceIndex > 0) {284 previousWhitespacesHeight = this._whitespaces.getAccumulatedHeight(whitespaceIndex - 1);285 }286 else {287 previousWhitespacesHeight = 0;288 }289 return previousLinesHeight + previousWhitespacesHeight;290 };291 LinesLayout.prototype.getWhitespaceIndexAtOrAfterVerticallOffset = function (verticalOffset) {292 verticalOffset = verticalOffset | 0;293 var midWhitespaceIndex, minWhitespaceIndex = 0, maxWhitespaceIndex = this._whitespaces.getCount() - 1, midWhitespaceVerticalOffset, midWhitespaceHeight;294 if (maxWhitespaceIndex < 0) {295 return -1;296 }297 // Special case: nothing to be found298 var maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex);299 var maxWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(maxWhitespaceIndex);300 if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) {301 return -1;302 }303 while (minWhitespaceIndex < maxWhitespaceIndex) {304 midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2);305 midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex);306 midWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(midWhitespaceIndex);307 if (verticalOffset >= midWhitespaceVerticalOffset + midWhitespaceHeight) {308 // vertical offset is after whitespace309 minWhitespaceIndex = midWhitespaceIndex + 1;310 }311 else if (verticalOffset >= midWhitespaceVerticalOffset) {312 // Hit313 return midWhitespaceIndex;314 }315 else {316 // vertical offset is before whitespace, but midWhitespaceIndex might still be what we're searching for317 maxWhitespaceIndex = midWhitespaceIndex;318 }319 }320 return minWhitespaceIndex;321 };322 /**323 * Get exactly the whitespace that is layouted at `verticalOffset`.324 *325 * @param verticalOffset The vertical offset.326 * @return Precisely the whitespace that is layouted at `verticaloffset` or null.327 */328 LinesLayout.prototype.getWhitespaceAtVerticalOffset = function (verticalOffset) {329 verticalOffset = verticalOffset | 0;330 var candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset);331 if (candidateIndex < 0) {332 return null;333 }334 if (candidateIndex >= this._whitespaces.getCount()) {335 return null;336 }337 var candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex);338 if (candidateTop > verticalOffset) {339 return null;340 }341 var candidateHeight = this._whitespaces.getHeightForWhitespaceIndex(candidateIndex);342 var candidateId = this._whitespaces.getIdForWhitespaceIndex(candidateIndex);343 var candidateAfterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(candidateIndex);344 return {345 id: candidateId,346 afterLineNumber: candidateAfterLineNumber,347 verticalOffset: candidateTop,348 height: candidateHeight349 };350 };351 /**352 * Get a list of whitespaces that are positioned between `verticalOffset1` and `verticalOffset2`.353 *354 * @param verticalOffset1 The beginning of the viewport.355 * @param verticalOffset2 The end of the viewport.356 * @return An array with all the whitespaces in the viewport. If no whitespace is in viewport, the array is empty.357 */358 LinesLayout.prototype.getWhitespaceViewportData = function (verticalOffset1, verticalOffset2) {359 verticalOffset1 = verticalOffset1 | 0;360 verticalOffset2 = verticalOffset2 | 0;361 var startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);362 var endIndex = this._whitespaces.getCount() - 1;363 if (startIndex < 0) {364 return [];365 }366 var result = [];367 for (var i = startIndex; i <= endIndex; i++) {368 var top_1 = this.getVerticalOffsetForWhitespaceIndex(i);369 var height = this._whitespaces.getHeightForWhitespaceIndex(i);370 if (top_1 >= verticalOffset2) {371 break;372 }373 result.push({374 id: this._whitespaces.getIdForWhitespaceIndex(i),375 afterLineNumber: this._whitespaces.getAfterLineNumberForWhitespaceIndex(i),376 verticalOffset: top_1,377 height: height378 });379 }380 return result;381 };382 /**383 * Get all whitespaces.384 */385 LinesLayout.prototype.getWhitespaces = function () {386 return this._whitespaces.getWhitespaces(this._lineHeight);387 };388 return LinesLayout;389}());...
whitespaceComputer.js
Source:whitespaceComputer.js
1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5'use strict';6/**7 * Represent whitespaces in between lines and provide fast CRUD management methods.8 * The whitespaces are sorted ascending by `afterLineNumber`.9 */10var WhitespaceComputer = /** @class */ (function () {11 function WhitespaceComputer() {12 this._heights = [];13 this._ids = [];14 this._afterLineNumbers = [];15 this._ordinals = [];16 this._prefixSum = [];17 this._prefixSumValidIndex = -1;18 this._whitespaceId2Index = {};19 this._lastWhitespaceId = 0;20 }21 /**22 * Find the insertion index for a new value inside a sorted array of values.23 * If the value is already present in the sorted array, the insertion index will be after the already existing value.24 */25 WhitespaceComputer.findInsertionIndex = function (sortedArray, value, ordinals, valueOrdinal) {26 var low = 0;27 var high = sortedArray.length;28 while (low < high) {29 var mid = ((low + high) >>> 1);30 if (value === sortedArray[mid]) {31 if (valueOrdinal < ordinals[mid]) {32 high = mid;33 }34 else {35 low = mid + 1;36 }37 }38 else if (value < sortedArray[mid]) {39 high = mid;40 }41 else {42 low = mid + 1;43 }44 }45 return low;46 };47 /**48 * Insert a new whitespace of a certain height after a line number.49 * The whitespace has a "sticky" characteristic.50 * Irrespective of edits above or below `afterLineNumber`, the whitespace will follow the initial line.51 *52 * @param afterLineNumber The conceptual position of this whitespace. The whitespace will follow this line as best as possible even when deleting/inserting lines above/below.53 * @param heightInPx The height of the whitespace, in pixels.54 * @return An id that can be used later to mutate or delete the whitespace55 */56 WhitespaceComputer.prototype.insertWhitespace = function (afterLineNumber, ordinal, heightInPx) {57 afterLineNumber = afterLineNumber | 0;58 ordinal = ordinal | 0;59 heightInPx = heightInPx | 0;60 var id = (++this._lastWhitespaceId);61 var insertionIndex = WhitespaceComputer.findInsertionIndex(this._afterLineNumbers, afterLineNumber, this._ordinals, ordinal);62 this._insertWhitespaceAtIndex(id, insertionIndex, afterLineNumber, ordinal, heightInPx);63 return id;64 };65 WhitespaceComputer.prototype._insertWhitespaceAtIndex = function (id, insertIndex, afterLineNumber, ordinal, heightInPx) {66 id = id | 0;67 insertIndex = insertIndex | 0;68 afterLineNumber = afterLineNumber | 0;69 ordinal = ordinal | 0;70 heightInPx = heightInPx | 0;71 this._heights.splice(insertIndex, 0, heightInPx);72 this._ids.splice(insertIndex, 0, id);73 this._afterLineNumbers.splice(insertIndex, 0, afterLineNumber);74 this._ordinals.splice(insertIndex, 0, ordinal);75 this._prefixSum.splice(insertIndex, 0, 0);76 var keys = Object.keys(this._whitespaceId2Index);77 for (var i = 0, len = keys.length; i < len; i++) {78 var sid = keys[i];79 var oldIndex = this._whitespaceId2Index[sid];80 if (oldIndex >= insertIndex) {81 this._whitespaceId2Index[sid] = oldIndex + 1;82 }83 }84 this._whitespaceId2Index[id.toString()] = insertIndex;85 this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1);86 };87 /**88 * Change properties associated with a certain whitespace.89 */90 WhitespaceComputer.prototype.changeWhitespace = function (id, newAfterLineNumber, newHeight) {91 id = id | 0;92 newAfterLineNumber = newAfterLineNumber | 0;93 newHeight = newHeight | 0;94 var hasChanges = false;95 hasChanges = this.changeWhitespaceHeight(id, newHeight) || hasChanges;96 hasChanges = this.changeWhitespaceAfterLineNumber(id, newAfterLineNumber) || hasChanges;97 return hasChanges;98 };99 /**100 * Change the height of an existing whitespace101 *102 * @param id The whitespace to change103 * @param newHeightInPx The new height of the whitespace, in pixels104 * @return Returns true if the whitespace is found and if the new height is different than the old height105 */106 WhitespaceComputer.prototype.changeWhitespaceHeight = function (id, newHeightInPx) {107 id = id | 0;108 newHeightInPx = newHeightInPx | 0;109 var sid = id.toString();110 if (this._whitespaceId2Index.hasOwnProperty(sid)) {111 var index = this._whitespaceId2Index[sid];112 if (this._heights[index] !== newHeightInPx) {113 this._heights[index] = newHeightInPx;114 this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1);115 return true;116 }117 }118 return false;119 };120 /**121 * Change the line number after which an existing whitespace flows.122 *123 * @param id The whitespace to change124 * @param newAfterLineNumber The new line number the whitespace will follow125 * @return Returns true if the whitespace is found and if the new line number is different than the old line number126 */127 WhitespaceComputer.prototype.changeWhitespaceAfterLineNumber = function (id, newAfterLineNumber) {128 id = id | 0;129 newAfterLineNumber = newAfterLineNumber | 0;130 var sid = id.toString();131 if (this._whitespaceId2Index.hasOwnProperty(sid)) {132 var index = this._whitespaceId2Index[sid];133 if (this._afterLineNumbers[index] !== newAfterLineNumber) {134 // `afterLineNumber` changed for this whitespace135 // Record old ordinal136 var ordinal = this._ordinals[index];137 // Record old height138 var heightInPx = this._heights[index];139 // Since changing `afterLineNumber` can trigger a reordering, we're gonna remove this whitespace140 this.removeWhitespace(id);141 // And add it again142 var insertionIndex = WhitespaceComputer.findInsertionIndex(this._afterLineNumbers, newAfterLineNumber, this._ordinals, ordinal);143 this._insertWhitespaceAtIndex(id, insertionIndex, newAfterLineNumber, ordinal, heightInPx);144 return true;145 }146 }147 return false;148 };149 /**150 * Remove an existing whitespace.151 *152 * @param id The whitespace to remove153 * @return Returns true if the whitespace is found and it is removed.154 */155 WhitespaceComputer.prototype.removeWhitespace = function (id) {156 id = id | 0;157 var sid = id.toString();158 if (this._whitespaceId2Index.hasOwnProperty(sid)) {159 var index = this._whitespaceId2Index[sid];160 delete this._whitespaceId2Index[sid];161 this._removeWhitespaceAtIndex(index);162 return true;163 }164 return false;165 };166 WhitespaceComputer.prototype._removeWhitespaceAtIndex = function (removeIndex) {167 removeIndex = removeIndex | 0;168 this._heights.splice(removeIndex, 1);169 this._ids.splice(removeIndex, 1);170 this._afterLineNumbers.splice(removeIndex, 1);171 this._ordinals.splice(removeIndex, 1);172 this._prefixSum.splice(removeIndex, 1);173 this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1);174 var keys = Object.keys(this._whitespaceId2Index);175 for (var i = 0, len = keys.length; i < len; i++) {176 var sid = keys[i];177 var oldIndex = this._whitespaceId2Index[sid];178 if (oldIndex >= removeIndex) {179 this._whitespaceId2Index[sid] = oldIndex - 1;180 }181 }182 };183 /**184 * Notify the computer that lines have been deleted (a continuous zone of lines).185 * This gives it a chance to update `afterLineNumber` for whitespaces, giving the "sticky" characteristic.186 *187 * @param fromLineNumber The line number at which the deletion started, inclusive188 * @param toLineNumber The line number at which the deletion ended, inclusive189 */190 WhitespaceComputer.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) {191 fromLineNumber = fromLineNumber | 0;192 toLineNumber = toLineNumber | 0;193 for (var i = 0, len = this._afterLineNumbers.length; i < len; i++) {194 var afterLineNumber = this._afterLineNumbers[i];195 if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {196 // The line this whitespace was after has been deleted197 // => move whitespace to before first deleted line198 this._afterLineNumbers[i] = fromLineNumber - 1;199 }200 else if (afterLineNumber > toLineNumber) {201 // The line this whitespace was after has been moved up202 // => move whitespace up203 this._afterLineNumbers[i] -= (toLineNumber - fromLineNumber + 1);204 }205 }206 };207 /**208 * Notify the computer that lines have been inserted (a continuous zone of lines).209 * This gives it a chance to update `afterLineNumber` for whitespaces, giving the "sticky" characteristic.210 *211 * @param fromLineNumber The line number at which the insertion started, inclusive212 * @param toLineNumber The line number at which the insertion ended, inclusive.213 */214 WhitespaceComputer.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) {215 fromLineNumber = fromLineNumber | 0;216 toLineNumber = toLineNumber | 0;217 for (var i = 0, len = this._afterLineNumbers.length; i < len; i++) {218 var afterLineNumber = this._afterLineNumbers[i];219 if (fromLineNumber <= afterLineNumber) {220 this._afterLineNumbers[i] += (toLineNumber - fromLineNumber + 1);221 }222 }223 };224 /**225 * Get the sum of all the whitespaces.226 */227 WhitespaceComputer.prototype.getTotalHeight = function () {228 if (this._heights.length === 0) {229 return 0;230 }231 return this.getAccumulatedHeight(this._heights.length - 1);232 };233 /**234 * Return the sum of the heights of the whitespaces at [0..index].235 * This includes the whitespace at `index`.236 *237 * @param index The index of the whitespace.238 * @return The sum of the heights of all whitespaces before the one at `index`, including the one at `index`.239 */240 WhitespaceComputer.prototype.getAccumulatedHeight = function (index) {241 index = index | 0;242 var startIndex = Math.max(0, this._prefixSumValidIndex + 1);243 if (startIndex === 0) {244 this._prefixSum[0] = this._heights[0];245 startIndex++;246 }247 for (var i = startIndex; i <= index; i++) {248 this._prefixSum[i] = this._prefixSum[i - 1] + this._heights[i];249 }250 this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index);251 return this._prefixSum[index];252 };253 /**254 * Find all whitespaces with `afterLineNumber` < `lineNumber` and return the sum of their heights.255 *256 * @param lineNumber The line number whitespaces should be before.257 * @return The sum of the heights of the whitespaces before `lineNumber`.258 */259 WhitespaceComputer.prototype.getAccumulatedHeightBeforeLineNumber = function (lineNumber) {260 lineNumber = lineNumber | 0;261 var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);262 if (lastWhitespaceBeforeLineNumber === -1) {263 return 0;264 }265 return this.getAccumulatedHeight(lastWhitespaceBeforeLineNumber);266 };267 WhitespaceComputer.prototype._findLastWhitespaceBeforeLineNumber = function (lineNumber) {268 lineNumber = lineNumber | 0;269 // Find the whitespace before line number270 var afterLineNumbers = this._afterLineNumbers;271 var low = 0;272 var high = afterLineNumbers.length - 1;273 while (low <= high) {274 var delta = (high - low) | 0;275 var halfDelta = (delta / 2) | 0;276 var mid = (low + halfDelta) | 0;277 if (afterLineNumbers[mid] < lineNumber) {278 if (mid + 1 >= afterLineNumbers.length || afterLineNumbers[mid + 1] >= lineNumber) {279 return mid;280 }281 else {282 low = (mid + 1) | 0;283 }284 }285 else {286 high = (mid - 1) | 0;287 }288 }289 return -1;290 };291 WhitespaceComputer.prototype._findFirstWhitespaceAfterLineNumber = function (lineNumber) {292 lineNumber = lineNumber | 0;293 var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);294 var firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;295 if (firstWhitespaceAfterLineNumber < this._heights.length) {296 return firstWhitespaceAfterLineNumber;297 }298 return -1;299 };300 /**301 * Find the index of the first whitespace which has `afterLineNumber` >= `lineNumber`.302 * @return The index of the first whitespace with `afterLineNumber` >= `lineNumber` or -1 if no whitespace is found.303 */304 WhitespaceComputer.prototype.getFirstWhitespaceIndexAfterLineNumber = function (lineNumber) {305 lineNumber = lineNumber | 0;306 return this._findFirstWhitespaceAfterLineNumber(lineNumber);307 };308 /**309 * The number of whitespaces.310 */311 WhitespaceComputer.prototype.getCount = function () {312 return this._heights.length;313 };314 /**315 * Get the `afterLineNumber` for whitespace at index `index`.316 *317 * @param index The index of the whitespace.318 * @return `afterLineNumber` of whitespace at `index`.319 */320 WhitespaceComputer.prototype.getAfterLineNumberForWhitespaceIndex = function (index) {321 index = index | 0;322 return this._afterLineNumbers[index];323 };324 /**325 * Get the `id` for whitespace at index `index`.326 *327 * @param index The index of the whitespace.328 * @return `id` of whitespace at `index`.329 */330 WhitespaceComputer.prototype.getIdForWhitespaceIndex = function (index) {331 index = index | 0;332 return this._ids[index];333 };334 /**335 * Get the `height` for whitespace at index `index`.336 *337 * @param index The index of the whitespace.338 * @return `height` of whitespace at `index`.339 */340 WhitespaceComputer.prototype.getHeightForWhitespaceIndex = function (index) {341 index = index | 0;342 return this._heights[index];343 };344 /**345 * Get all whitespaces.346 */347 WhitespaceComputer.prototype.getWhitespaces = function (deviceLineHeight) {348 deviceLineHeight = deviceLineHeight | 0;349 var result = [];350 for (var i = 0; i < this._heights.length; i++) {351 result.push({352 id: this._ids[i],353 afterLineNumber: this._afterLineNumbers[i],354 heightInLines: this._heights[i] / deviceLineHeight355 });356 }357 return result;358 };359 return WhitespaceComputer;360}());...
whitespace-control.js
Source:whitespace-control.js
1import Visitor from './visitor';2function WhitespaceControl(options = {}) {3 this.options = options;4}5WhitespaceControl.prototype = new Visitor();6WhitespaceControl.prototype.Program = function(program) {7 const doStandalone = !this.options.ignoreStandalone;8 let isRoot = !this.isRootSeen;9 this.isRootSeen = true;10 let body = program.body;11 for (let i = 0, l = body.length; i < l; i++) {12 let current = body[i],13 strip = this.accept(current);14 if (!strip) {15 continue;16 }17 let _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),18 _isNextWhitespace = isNextWhitespace(body, i, isRoot),19 openStandalone = strip.openStandalone && _isPrevWhitespace,20 closeStandalone = strip.closeStandalone && _isNextWhitespace,21 inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;22 if (strip.close) {23 omitRight(body, i, true);24 }25 if (strip.open) {26 omitLeft(body, i, true);27 }28 if (doStandalone && inlineStandalone) {29 omitRight(body, i);30 if (omitLeft(body, i)) {31 // If we are on a standalone node, save the indent info for partials32 if (current.type === 'PartialStatement') {33 // Pull out the whitespace from the final line34 current.indent = (/([ \t]+$)/).exec(body[i - 1].original)[1];35 }36 }37 }38 if (doStandalone && openStandalone) {39 omitRight((current.program || current.inverse).body);40 // Strip out the previous content node if it's whitespace only41 omitLeft(body, i);42 }43 if (doStandalone && closeStandalone) {44 // Always strip the next node45 omitRight(body, i);46 omitLeft((current.inverse || current.program).body);47 }48 }49 return program;50};51WhitespaceControl.prototype.BlockStatement =52WhitespaceControl.prototype.DecoratorBlock =53WhitespaceControl.prototype.PartialBlockStatement = function(block) {54 this.accept(block.program);55 this.accept(block.inverse);56 // Find the inverse program that is involed with whitespace stripping.57 let program = block.program || block.inverse,58 inverse = block.program && block.inverse,59 firstInverse = inverse,60 lastInverse = inverse;61 if (inverse && inverse.chained) {62 firstInverse = inverse.body[0].program;63 // Walk the inverse chain to find the last inverse that is actually in the chain.64 while (lastInverse.chained) {65 lastInverse = lastInverse.body[lastInverse.body.length - 1].program;66 }67 }68 let strip = {69 open: block.openStrip.open,70 close: block.closeStrip.close,71 // Determine the standalone candiacy. Basically flag our content as being possibly standalone72 // so our parent can determine if we actually are standalone73 openStandalone: isNextWhitespace(program.body),74 closeStandalone: isPrevWhitespace((firstInverse || program).body)75 };76 if (block.openStrip.close) {77 omitRight(program.body, null, true);78 }79 if (inverse) {80 let inverseStrip = block.inverseStrip;81 if (inverseStrip.open) {82 omitLeft(program.body, null, true);83 }84 if (inverseStrip.close) {85 omitRight(firstInverse.body, null, true);86 }87 if (block.closeStrip.open) {88 omitLeft(lastInverse.body, null, true);89 }90 // Find standalone else statments91 if (!this.options.ignoreStandalone92 && isPrevWhitespace(program.body)93 && isNextWhitespace(firstInverse.body)) {94 omitLeft(program.body);95 omitRight(firstInverse.body);96 }97 } else if (block.closeStrip.open) {98 omitLeft(program.body, null, true);99 }100 return strip;101};102WhitespaceControl.prototype.Decorator =103WhitespaceControl.prototype.MustacheStatement = function(mustache) {104 return mustache.strip;105};106WhitespaceControl.prototype.PartialStatement =107 WhitespaceControl.prototype.CommentStatement = function(node) {108 /* istanbul ignore next */109 let strip = node.strip || {};110 return {111 inlineStandalone: true,112 open: strip.open,113 close: strip.close114 };115};116function isPrevWhitespace(body, i, isRoot) {117 if (i === undefined) {118 i = body.length;119 }120 // Nodes that end with newlines are considered whitespace (but are special121 // cased for strip operations)122 let prev = body[i - 1],123 sibling = body[i - 2];124 if (!prev) {125 return isRoot;126 }127 if (prev.type === 'ContentStatement') {128 return (sibling || !isRoot ? (/\r?\n\s*?$/) : (/(^|\r?\n)\s*?$/)).test(prev.original);129 }130}131function isNextWhitespace(body, i, isRoot) {132 if (i === undefined) {133 i = -1;134 }135 let next = body[i + 1],136 sibling = body[i + 2];137 if (!next) {138 return isRoot;139 }140 if (next.type === 'ContentStatement') {141 return (sibling || !isRoot ? (/^\s*?\r?\n/) : (/^\s*?(\r?\n|$)/)).test(next.original);142 }143}144// Marks the node to the right of the position as omitted.145// I.e. {{foo}}' ' will mark the ' ' node as omitted.146//147// If i is undefined, then the first child will be marked as such.148//149// If mulitple is truthy then all whitespace will be stripped out until non-whitespace150// content is met.151function omitRight(body, i, multiple) {152 let current = body[i == null ? 0 : i + 1];153 if (!current || current.type !== 'ContentStatement' || (!multiple && current.rightStripped)) {154 return;155 }156 let original = current.value;157 current.value = current.value.replace(multiple ? (/^\s+/) : (/^[ \t]*\r?\n?/), '');158 current.rightStripped = current.value !== original;159}160// Marks the node to the left of the position as omitted.161// I.e. ' '{{foo}} will mark the ' ' node as omitted.162//163// If i is undefined then the last child will be marked as such.164//165// If mulitple is truthy then all whitespace will be stripped out until non-whitespace166// content is met.167function omitLeft(body, i, multiple) {168 let current = body[i == null ? body.length - 1 : i - 1];169 if (!current || current.type !== 'ContentStatement' || (!multiple && current.leftStripped)) {170 return;171 }172 // We omit the last node if it's whitespace only and not preceeded by a non-content node.173 let original = current.value;174 current.value = current.value.replace(multiple ? (/\s+$/) : (/[ \t]+$/), '');175 current.leftStripped = current.value !== original;176 return current.leftStripped;177}...
JDK-8019987.js
Source:JDK-8019987.js
1/*2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.4 *5 * This code is free software; you can redistribute it and/or modify it6 * under the terms of the GNU General Public License version 2 only, as7 * published by the Free Software Foundation.8 *9 * This code is distributed in the hope that it will be useful, but WITHOUT10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12 * version 2 for more details (a copy is included in the LICENSE file that13 * accompanied this code).14 *15 * You should have received a copy of the GNU General Public License version16 * 2 along with this work; if not, write to the Free Software Foundation,17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18 *19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20 * or visit www.oracle.com if you need additional information or have any21 * questions.22 */23/**24 * JDK-8019987: String trimRight and trimLeft could be defined.25 *26 * @test27 * @run28 */29var TESTSTRING = "abcde";30var SPACES = " ";31var TESTSTRING_LEFT_SPACES = SPACES + TESTSTRING;32var TESTSTRING_RIGHT_SPACES = TESTSTRING + SPACES;33var TESTSTRING_BOTH_SPACES = SPACES + TESTSTRING + SPACES;34var TESTSTRING_MIDDLE_SPACES = TESTSTRING + SPACES + TESTSTRING;35var WHITESPACE =36 " \t" + // space and tab37 "\n\r" + // newline and return38 "\u2028" + // line separator39 "\u2029" + // paragraph separator40 "\u000b" + // tabulation line41 "\u000c" + // ff (ctrl-l)42 "\u00a0" + // Latin-1 space43 "\u1680" + // Ogham space mark44 "\u180e" + // separator, Mongolian vowel45 "\u2000" + // en quad46 "\u2001" + // em quad47 "\u2002" + // en space48 "\u2003" + // em space49 "\u2004" + // three-per-em space50 "\u2005" + // four-per-em space51 "\u2006" + // six-per-em space52 "\u2007" + // figure space53 "\u2008" + // punctuation space54 "\u2009" + // thin space55 "\u200a" + // hair space56 "\u202f" + // narrow no-break space57 "\u205f" + // medium mathematical space58 "\u3000" + // ideographic space59 "\ufeff"; // byte order mark60var TESTSTRING_LEFT_WHITESPACE = WHITESPACE + TESTSTRING;61var TESTSTRING_RIGHT_WHITESPACE = TESTSTRING + WHITESPACE;62var TESTSTRING_BOTH_WHITESPACE = WHITESPACE + TESTSTRING + WHITESPACE;63var TESTSTRING_MIDDLE_WHITESPACE = TESTSTRING + WHITESPACE + TESTSTRING;64function escape(string) {65 var sb = new java.lang.StringBuilder();66 sb.append("\"");67 for (var i = 0; i < string.length; i++) {68 var ch = string.charAt(i);69 switch (ch) {70 case '\\':71 sb.append("\\\\");72 break;73 case '"':74 sb.append("\\\"");75 break;76 case '\'':77 sb.append("\\\'");78 break;79 case '\b':80 sb.append("\\b");81 break;82 case '\f':83 sb.append("\\f");84 break;85 case '\n':86 sb.append("\\n");87 break;88 case '\r':89 sb.append("\\r");90 break;91 case '\t':92 sb.append("\\t");93 break;94 default:95 var code = string.charCodeAt(i);96 if (code < 0x20 || code >= 0xFF) {97 sb.append("\\u");98 var hex = java.lang.Integer.toHexString(code);99 for (var i = hex.length; i < 4; i++) {100 sb.append('0');101 }102 sb.append(hex);103 } else {104 sb.append(ch);105 }106 break;107 }108 }109 sb.append("\"");110 return sb.toString();111}112var count = 0;113function test(expected, trimmed) {114 count++;115 if (trimmed != expected) {116 print(count + ": Expected: " + escape(expected) + ", found: " + escape(trimmed));117 }118}119test("", SPACES.trim());120test("", SPACES.trimLeft());121test("", SPACES.trimRight());122test(TESTSTRING, TESTSTRING_LEFT_SPACES.trim());123test(TESTSTRING, TESTSTRING_LEFT_SPACES.trimLeft());124test(TESTSTRING_LEFT_SPACES, TESTSTRING_LEFT_SPACES.trimRight());125test(TESTSTRING, TESTSTRING_RIGHT_SPACES.trim());126test(TESTSTRING_RIGHT_SPACES, TESTSTRING_RIGHT_SPACES.trimLeft());127test(TESTSTRING, TESTSTRING_RIGHT_SPACES.trimRight());128test(TESTSTRING, TESTSTRING_BOTH_SPACES.trim());129test(TESTSTRING_RIGHT_SPACES, TESTSTRING_BOTH_SPACES.trimLeft());130test(TESTSTRING_LEFT_SPACES, TESTSTRING_BOTH_SPACES.trimRight());131test(TESTSTRING_MIDDLE_SPACES, TESTSTRING_MIDDLE_SPACES.trim());132test(TESTSTRING_MIDDLE_SPACES, TESTSTRING_MIDDLE_SPACES.trimLeft());133test(TESTSTRING_MIDDLE_SPACES, TESTSTRING_MIDDLE_SPACES.trimRight());134test("", WHITESPACE.trim());135test("", WHITESPACE.trimLeft());136test("", WHITESPACE.trimRight());137test(TESTSTRING, TESTSTRING_LEFT_WHITESPACE.trim());138test(TESTSTRING, TESTSTRING_LEFT_WHITESPACE.trimLeft());139test(TESTSTRING_LEFT_WHITESPACE, TESTSTRING_LEFT_WHITESPACE.trimRight());140test(TESTSTRING, TESTSTRING_RIGHT_WHITESPACE.trim());141test(TESTSTRING_RIGHT_WHITESPACE, TESTSTRING_RIGHT_WHITESPACE.trimLeft());142test(TESTSTRING, TESTSTRING_RIGHT_WHITESPACE.trimRight());143test(TESTSTRING, TESTSTRING_BOTH_WHITESPACE.trim());144test(TESTSTRING_RIGHT_WHITESPACE, TESTSTRING_BOTH_WHITESPACE.trimLeft());145test(TESTSTRING_LEFT_WHITESPACE, TESTSTRING_BOTH_WHITESPACE.trimRight());146test(TESTSTRING_MIDDLE_WHITESPACE, TESTSTRING_MIDDLE_WHITESPACE.trim());147test(TESTSTRING_MIDDLE_WHITESPACE, TESTSTRING_MIDDLE_WHITESPACE.trimLeft());...
whitespace.js
Source:whitespace.js
1/* The contents of this file are subject to the Netscape Public2 * License Version 1.1 (the "License"); you may not use this file3 * except in compliance with the License. You may obtain a copy of4 * the License at http://www.mozilla.org/NPL/5 *6 * Software distributed under the License is distributed on an "AS7 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or8 * implied. See the License for the specific language governing9 * rights and limitations under the License.10 *11 * The Original Code is Mozilla Communicator client code, released March12 * 31, 1998.13 *14 * The Initial Developer of the Original Code is Netscape Communications15 * Corporation. Portions created by Netscape are16 * Copyright (C) 1998 Netscape Communications Corporation. All17 * Rights Reserved.18 *19 * Contributor(s): 20 * 21 */22/**23 Filename: whitespace.js24 Description: 'Tests regular expressions containing \f\n\r\t\v\s\S\ '25 Author: Nick Lerissa26 Date: March 10, 199827*/28 var SECTION = 'As described in Netscape doc "Whats new in JavaScript 1.2"';29 var VERSION = 'no version';30 startTest();31 var TITLE = 'RegExp: \\f\\n\\r\\t\\v\\s\\S ';32 writeHeaderToLog('Executing script: whitespace.js');33 writeHeaderToLog( SECTION + " "+ TITLE);34 var count = 0;35 var testcases = new Array();36 var non_whitespace = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()-+={[}]|\\:;'<,>./?1234567890" + '"';37 var whitespace = "\f\n\r\t\v ";38 // be sure all whitespace is matched by \s39 testcases[count++] = new TestCase ( SECTION,40 "'" + whitespace + "'.match(new RegExp('\\s+'))",41 String([whitespace]), String(whitespace.match(new RegExp('\\s+'))));42 // be sure all non-whitespace is matched by \S43 testcases[count++] = new TestCase ( SECTION,44 "'" + non_whitespace + "'.match(new RegExp('\\S+'))",45 String([non_whitespace]), String(non_whitespace.match(new RegExp('\\S+'))));46 // be sure all non-whitespace is not matched by \s47 testcases[count++] = new TestCase ( SECTION,48 "'" + non_whitespace + "'.match(new RegExp('\\s'))",49 null, non_whitespace.match(new RegExp('\\s')));50 // be sure all whitespace is not matched by \S51 testcases[count++] = new TestCase ( SECTION,52 "'" + whitespace + "'.match(new RegExp('\\S'))",53 null, whitespace.match(new RegExp('\\S')));54 var s = non_whitespace + whitespace;55 // be sure all digits are matched by \s56 testcases[count++] = new TestCase ( SECTION,57 "'" + s + "'.match(new RegExp('\\s+'))",58 String([whitespace]), String(s.match(new RegExp('\\s+'))));59 s = whitespace + non_whitespace;60 // be sure all non-whitespace are matched by \S61 testcases[count++] = new TestCase ( SECTION,62 "'" + s + "'.match(new RegExp('\\S+'))",63 String([non_whitespace]), String(s.match(new RegExp('\\S+'))));64 // '1233345find me345'.match(new RegExp('[a-z\\s][a-z\\s]+'))65 testcases[count++] = new TestCase ( SECTION, "'1233345find me345'.match(new RegExp('[a-z\\s][a-z\\s]+'))",66 String(["find me"]), String('1233345find me345'.match(new RegExp('[a-z\\s][a-z\\s]+'))));67 var i;68 // be sure all whitespace characters match individually69 for (i = 0; i < whitespace.length; ++i)70 {71 s = 'ab' + whitespace[i] + 'cd';72 testcases[count++] = new TestCase ( SECTION,73 "'" + s + "'.match(new RegExp('\\\\s'))",74 String([whitespace[i]]), String(s.match(new RegExp('\\s'))));75 testcases[count++] = new TestCase ( SECTION,76 "'" + s + "'.match(/\s/)",77 String([whitespace[i]]), String(s.match(/\s/)));78 }79 // be sure all non_whitespace characters match individually80 for (i = 0; i < non_whitespace.length; ++i)81 {82 s = ' ' + non_whitespace[i] + ' ';83 testcases[count++] = new TestCase ( SECTION,84 "'" + s + "'.match(new RegExp('\\\\S'))",85 String([non_whitespace[i]]), String(s.match(new RegExp('\\S'))));86 testcases[count++] = new TestCase ( SECTION,87 "'" + s + "'.match(/\S/)",88 String([non_whitespace[i]]), String(s.match(/\S/)));89 }90 function test()91 {92 for ( tc=0; tc < testcases.length; tc++ ) {93 testcases[tc].passed = writeTestCaseResult(94 testcases[tc].expect,95 testcases[tc].actual,96 testcases[tc].description +" = "+97 testcases[tc].actual );98 testcases[tc].reason += ( testcases[tc].passed ) ? "" : "wrong value ";99 }100 stopTest();101 return ( testcases );102 }...
trim-methods.js
Source:trim-methods.js
1import assert from 'assert';2import lodashStable from 'lodash';3import { _, whitespace } from './utils.js';4describe('trim methods', function() {5 lodashStable.each(['trim', 'trimStart', 'trimEnd'], function(methodName, index) {6 var func = _[methodName],7 parts = [];8 if (index != 2) {9 parts.push('leading');10 }11 if (index != 1) {12 parts.push('trailing');13 }14 parts = parts.join(' and ');15 it('`_.' + methodName + '` should remove ' + parts + ' whitespace', function() {16 var string = whitespace + 'a b c' + whitespace,17 expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : '');18 assert.strictEqual(func(string), expected);19 });20 it('`_.' + methodName + '` should coerce `string` to a string', function() {21 var object = { 'toString': lodashStable.constant(whitespace + 'a b c' + whitespace) },22 expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : '');23 assert.strictEqual(func(object), expected);24 });25 it('`_.' + methodName + '` should remove ' + parts + ' `chars`', function() {26 var string = '-_-a-b-c-_-',27 expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : '');28 assert.strictEqual(func(string, '_-'), expected);29 });30 it('`_.' + methodName + '` should coerce `chars` to a string', function() {31 var object = { 'toString': lodashStable.constant('_-') },32 string = '-_-a-b-c-_-',33 expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : '');34 assert.strictEqual(func(string, object), expected);35 });36 it('`_.' + methodName + '` should return an empty string for empty values and `chars`', function() {37 lodashStable.each([null, '_-'], function(chars) {38 assert.strictEqual(func(null, chars), '');39 assert.strictEqual(func(undefined, chars), '');40 assert.strictEqual(func('', chars), '');41 });42 });43 it('`_.' + methodName + '` should work with `undefined` or empty string values for `chars`', function() {44 var string = whitespace + 'a b c' + whitespace,45 expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : '');46 assert.strictEqual(func(string, undefined), expected);47 assert.strictEqual(func(string, ''), string);48 });49 it('`_.' + methodName + '` should work as an iteratee for methods like `_.map`', function() {50 var string = Object(whitespace + 'a b c' + whitespace),51 trimmed = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''),52 actual = lodashStable.map([string, string, string], func);53 assert.deepStrictEqual(actual, [trimmed, trimmed, trimmed]);54 });55 it('`_.' + methodName + '` should return an unwrapped value when implicitly chaining', function() {56 var string = whitespace + 'a b c' + whitespace,57 expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : '');58 assert.strictEqual(_(string)[methodName](), expected);59 });60 it('`_.' + methodName + '` should return a wrapped value when explicitly chaining', function() {61 var string = whitespace + 'a b c' + whitespace;62 assert.ok(_(string).chain()[methodName]() instanceof _);63 });64 });...
index.js
Source:index.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.needsWhitespace = needsWhitespace;6exports.needsWhitespaceBefore = needsWhitespaceBefore;7exports.needsWhitespaceAfter = needsWhitespaceAfter;8exports.needsParens = needsParens;9var whitespace = require("./whitespace");10var parens = require("./parentheses");11var t = require("@babel/types");12const {13 isCallExpression,14 isExpressionStatement,15 isMemberExpression,16 isNewExpression17} = t;18function expandAliases(obj) {19 const newObj = {};20 function add(type, func) {21 const fn = newObj[type];22 newObj[type] = fn ? function (node, parent, stack) {23 const result = fn(node, parent, stack);24 return result == null ? func(node, parent, stack) : result;25 } : func;26 }27 for (const type of Object.keys(obj)) {28 const aliases = t.FLIPPED_ALIAS_KEYS[type];29 if (aliases) {30 for (const alias of aliases) {31 add(alias, obj[type]);32 }33 } else {34 add(type, obj[type]);35 }36 }37 return newObj;38}39const expandedParens = expandAliases(parens);40const expandedWhitespaceNodes = expandAliases(whitespace.nodes);41const expandedWhitespaceList = expandAliases(whitespace.list);42function find(obj, node, parent, printStack) {43 const fn = obj[node.type];44 return fn ? fn(node, parent, printStack) : null;45}46function isOrHasCallExpression(node) {47 if (isCallExpression(node)) {48 return true;49 }50 return isMemberExpression(node) && isOrHasCallExpression(node.object);51}52function needsWhitespace(node, parent, type) {53 if (!node) return 0;54 if (isExpressionStatement(node)) {55 node = node.expression;56 }57 let linesInfo = find(expandedWhitespaceNodes, node, parent);58 if (!linesInfo) {59 const items = find(expandedWhitespaceList, node, parent);60 if (items) {61 for (let i = 0; i < items.length; i++) {62 linesInfo = needsWhitespace(items[i], node, type);63 if (linesInfo) break;64 }65 }66 }67 if (typeof linesInfo === "object" && linesInfo !== null) {68 return linesInfo[type] || 0;69 }70 return 0;71}72function needsWhitespaceBefore(node, parent) {73 return needsWhitespace(node, parent, "before");74}75function needsWhitespaceAfter(node, parent) {76 return needsWhitespace(node, parent, "after");77}78function needsParens(node, parent, printStack) {79 if (!parent) return false;80 if (isNewExpression(parent) && parent.callee === node) {81 if (isOrHasCallExpression(node)) return true;82 }83 return find(expandedParens, node, parent, printStack);...
ve.ui.WhitespacePreservingTextInputWidget.js
Source:ve.ui.WhitespacePreservingTextInputWidget.js
1/*!2 * VisualEditor UserInterface WhitespacePreservingTextInputWidget class.3 *4 * @copyright 2011-2015 VisualEditor Team and others; see http://ve.mit-license.org5 */6/**7 * Text input widget which hides but preserves leading and trailing whitespace8 *9 * @class10 * @extends OO.ui.TextInputWidget11 *12 * @constructor13 * @param {Object} [config] Configuration options14 * @cfg {string} [valueAndWhitespace] Initial value and whitespace15 * @cfg {number} [limit] Maximum number of characters to preserve at each end16 */17ve.ui.WhitespacePreservingTextInputWidget = function VeUiWhitespacePreservingTextInputWidget( config ) {18 // Configuration19 config = config || {};20 // Parent constructor21 ve.ui.WhitespacePreservingTextInputWidget.super.call( this, config );22 this.limit = config.limit;23 this.whitespace = [ '', '' ];24 this.setValueAndWhitespace( config.valueAndWhitespace || '' );25 this.$element.addClass( 've-ui-WhitespacePreservingTextInputWidget' );26};27/* Inheritance */28OO.inheritClass( ve.ui.WhitespacePreservingTextInputWidget, OO.ui.TextInputWidget );29/* Methods */30/**31 * Set the value of the widget and extract whitespace.32 *33 * @param {string} value Value34 */35ve.ui.WhitespacePreservingTextInputWidget.prototype.setValueAndWhitespace = function ( value ) {36 var leftValue, rightValue;37 leftValue = this.limit ? value.slice( 0, this.limit ) : value;38 this.whitespace[ 0 ] = leftValue.match( /^\s*/ )[ 0 ];39 value = value.slice( this.whitespace[ 0 ].length );40 rightValue = this.limit ? value.slice( -this.limit ) : value;41 this.whitespace[ 1 ] = rightValue.match( /\s*$/ )[ 0 ];42 value = value.slice( 0, value.length - this.whitespace[ 1 ].length );43 this.setValue( value );44};45/**46 * Set the value of the widget and extract whitespace.47 *48 * @param {string[]} whitespace Outer whitespace49 */50ve.ui.WhitespacePreservingTextInputWidget.prototype.setWhitespace = function ( whitespace ) {51 this.whitespace = whitespace;52};53/**54 * @inheritdoc55 */56ve.ui.WhitespacePreservingTextInputWidget.prototype.getValue = function () {57 if ( !this.whitespace ) {58 // In case getValue() is called from a parent constructor59 return this.value;60 }61 return this.whitespace[ 0 ] + this.getInnerValue() + this.whitespace[ 1 ];62};63/**64 * Get the inner/displayed value of text widget, excluding hidden outer whitespace65 *66 * @return {string} Inner/displayed value67 */68ve.ui.WhitespacePreservingTextInputWidget.prototype.getInnerValue = function () {69 return $.trim( this.value );...
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9const {chromium} = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: `example.png` });15 await browser.close();16})();17const {chromium} = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: `example.png` });23 await browser.close();24})();25const {chromium} = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: `example.png` });31 await browser.close();32})();33const {chromium} = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: `example.png` });39 await browser.close();40})();41const {chromium} = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.screenshot({
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('my test', async ({ page }) => {3 await page.click('text=Get started');4 await page.click('text=Docs');5 await page.click('text=API');6 await page.click('text=Page');
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('My test', async ({ page }) => {3 await page.whitespace();4});5const { test, expect } = require('@playwright/test');6test('My test', async ({ page }) => {7 await page.whitespace();8});9const { test, expect } = require('@playwright/test');10test('My test', async ({ page }) => {11 await page.whitespace();12});13const { test, expect } = require('@playwright/test');14test('My test', async ({ page }) => {15 await page.whitespace();16});17const { test, expect } = require('@playwright/test');18test('My test', async ({ page }) => {19 await page.whitespace();20});21const { test, expect } = require('@playwright/test');22test('My test', async ({ page }) => {23 await page.whitespace();24});25const { test, expect } = require('@playwright/test');26test('My test', async ({ page }) => {27 await page.whitespace();28});29const { test, expect } = require('@playwright/test');30test('My test', async ({ page }) => {31 await page.whitespace();32});33const { test, expect } = require('@playwright/test');34test('My test', async ({ page }) => {35 await page.whitespace();36});37const { test, expect } = require('@playwright/test');38test('My test', async ({ page }) => {39 await page.whitespace();40});41const { test, expect } = require
Using AI Code Generation
1import { whitespace } from 'playwright-internal'2await page.click('button', { offset: { x: whitespace(1), y: whitespace(1) } })3import { whitespace } from 'playwright'4await page.click('button', { offset: { x: whitespace(1), y: whitespace(1) } })5import { whitespace } from 'playwright-test'6await page.click('button', { offset: { x: whitespace(1), y: whitespace(1) } })7import { whitespace } from 'playwright-test-internal'8await page.click('button', { offset: { x: whitespace(1), y: whitespace(1) } })
Using AI Code Generation
1const {whitespace} = require('playwright');2const text = 'This is a text';3const textWithWhitespace = whitespace(text);4const {whitespace} = require('playwright');5const text = 'This is a text';6const textWithWhitespace = whitespace(text);7const {whitespace} = require('playwright');8const text = 'This is a text';9const textWithWhitespace = whitespace(text);10const {whitespace} = require('playwright');11const text = 'This is a text';12const textWithWhitespace = whitespace(text);13const {whitespace} = require('playwright');14const text = 'This is a text';15const textWithWhitespace = whitespace(text);16const {whitespace} = require('playwright');17const text = 'This is a text';18const textWithWhitespace = whitespace(text);19const {whitespace} = require('playwright');20const text = 'This is a text';21const textWithWhitespace = whitespace(text);22const {whitespace} = require('playwright');23const text = 'This is a text';24const textWithWhitespace = whitespace(text);25const {whitespace} = require('playwright');26const text = 'This is a text';27const textWithWhitespace = whitespace(text);28const {whitespace} = require('playwright');29const text = 'This is a text';30const textWithWhitespace = whitespace(text);31const {whitespace} = require('playwright');32const text = 'This is a text';33const textWithWhitespace = whitespace(text);34const {whitespace} = require('playwright');35const text = 'This is a text';36const textWithWhitespace = whitespace(text);37const {whitespace} = require('playwright');
Using AI Code Generation
1const { _client } = await page;2const { whitespace } = _client;3const { whitespace } = await page._client;4const { _client } = await page;5const { whitespace } = _client;6const { whitespace } = await page._client;7const { _client } = await page;8const { whitespace } = _client;9const { whitespace } = await page._client;10const { _client } = await page;11const { whitespace } = _client;12const { whitespace } = await page._client;13const { _client } = await page;14const { whitespace } = _client;15const { whitespace } = await page._client;16const { _client } = await page;17const { whitespace } = _client;18const { whitespace } = await page._client;19const { _client } = await page;20const { whitespace } = _client;21const { whitespace } = await page._client;22const { _client } = await page;23const { whitespace } = _client;24const { whitespace } = await page._client;25const { _client } = await page;26const { whitespace } = _client;27const { whitespace } = await page._client;28const { _client } = await page;29const { whitespace } = _client;30const { whitespace } = await page._client;31const { _client } = await page;32const { whitespace } = _client;33const { whitespace } = await page._client;34const { _client } = await page;35const { whitespace } = _client;36const { whitespace } = await page._client;37const { _client } = await page;38const { whitespace } = _client;39const { whitespace } = await page._client;
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!