8000 miniPaint/src/js/tools/text.js at gh-pages · karavan/miniPaint · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
2642 lines (2468 loc) · 88.3 KB

text.js

File metadata and controls

2642 lines (2468 loc) · 88.3 KB
import app from './../app.js';
import config from './../config.js';
import zoomView from './../libs/zoomView.js';
import Base_tools_class from './../core/base-tools.js';
import Base_selection_class from './../core/base-selection.js';
import Base_layers_class from './../core/base-layers.js';
import GUI_tools_class from './../core/gui/gui-tools.js';
import Helper_class from './../libs/helpers.js';
import Dialog_class from './../libs/popup.js';
import WebFont from 'webfontloader';
import alertify from './../../../node_modules/alertifyjs/build/alertify.min.js';
/**
* TODO
* - Add leading, superscript, subscript
* - Implement text direction (right to left, top to bottom, etc.); currently partial implementation
* - Allow search & add google fonts
* - Enable text layer rotation
* - Undo history
*/
// Default text styling
// WARNING - changing this could break backwards compatibility!
// Defaults aren't saved in text layer in order to reduce data size and increase meta comparison performance.
export const metaDefaults = {
size: 40,
family: 'Arial',
kerning: 0,
leading: 0,
bold: false,
italic: false,
underline: false,
strikethrough: false,
fill_color: '#008800',
stroke_size: 0,
stroke_color: '#000000'
};
// Global map of font name to font metrics information.
const fontMetricsMap = new Map();
const layerEditors = new WeakMap();
const fontLoadPromiseMap = new Map();
const fontLoadMap = new Map();
fontLoadMap.set('Arial', true);
fontLoadMap.set('Courier', true);
fontLoadMap.set('Impact', true);
fontLoadMap.set('Helvetica', true);
fontLoadMap.set('Monospace', true);
fontLoadMap.set('Tahoma', true);
fontLoadMap.set('Times New Roman', true);
fontLoadMap.set('Verdana', true);
function load_font_family({ family, variants }, successCallback) {
if (fontLoadMap.get(family) == null) {
fontLoadMap.set(family, false);
const loadPromise = new Promise((resolve, reject) => {
WebFont.load({
google: {
families: [family + (variants ? ':' + variants.join(',') : '')]
},
fontactive: (family) => {
fontLoadMap.set(family, true);
fontLoadPromiseMap.delete(family);
resolve();
},
fontinactive: (family) => {
alertify.error('Font ' + family + ' could not be loaded.');
fontLoadPromiseMap.delete(family);
reject();
}
});
});
fontLoadPromiseMap.set(family, loadPromise);
}
if (successCallback) {
const loadPromise = fontLoadPromiseMap.get(family);
if (loadPromise) {
loadPromise.then(successCallback);
} else if (fontLoadMap.get(family) == true) {
requestAnimationFrame(() => {
successCallback();
});
}
}
}
/**
* The canvas's native font metrics implementation doesn't really give us enough information...
*/
const kerningTestCanvas = document.createElement('canvas');
kerningTestCanvas.width = 10;
kerningTestCanv 9798 as.height = 10;
kerningTestCanvas.style = 'font-kerning: normal; text-rendering: optimizeLegibility;';
const kerningTestCtx = kerningTestCanvas.getContext('2d');
class Font_metrics_class {
constructor(family, size) {
this.family = family || (family = "Arial");
this.size = parseInt(size) || (size = 12);
this.kerningMap = new Map();
// Preparing container
const line = document.createElement('div');
const body = document.body;
line.style.position = 'absolute';
line.style.whiteSpace = 'nowrap';
line.style.font = size + 'px ' + family;
body.appendChild(line);
// Now we can measure width and height of the letter
const text = '——————————'; // 10 symbols to be more accurate with width
line.innerHTML = text;
this.width = line.offsetWidth / text.length;
this.height = line.offsetHeight;
// Now creating 1px sized item that will be aligned to baseline
// to calculate baseline shift
const baseline = document.createElement('span');
baseline.style.display = 'inline-block';
baseline.style.overflow = 'hidden';
baseline.style.width = '1px';
baseline.style.height = '1px';
line.appendChild(baseline);
// Baseline is important for positioning text on canvas
this.baseline = baseline.offsetTop + baseline.offsetHeight;
document.body.removeChild(line);
}
/**
* Attempts to determine the height of a letter via pixel comparison
* @param {string} letter - The letter to check
* @param {string} [baseline] - Baseline position override
*/
calculate_letter_bounds(letter, baseline) {
baseline = baseline || 'alphabetic'
kerningTestCanvas.width = this.width;
kerningTestCanvas.height = this.height;
kerningTestCtx.clearRect(0, 0, this.width, this.height);
kerningTestCtx.font =
' ' + (this.size) + 'px' +
' ' + this.family;
kerningTestCtx.textAlign = 'left';
kerningTestCtx.textBaseline = baseline;
kerningTestCtx.fillStyle = '#000000';
kerningTestCtx.fillText(letter, 0, baseline === 'alphabetic' ? this.baseline : 0);
const pixels = kerningTestCtx.getImageData(0, 0, this.width, this.height).data;
const pixelLength = pixels.length;
let start = 0;
let end = this.height;
for (let i = 0; i < pixelLength; i += 4) {
if (pixels[i + 3] !== 0) {
start = Math.floor(i / 4 / this.width);
break;
}
}
for (let i = pixelLength - 4; i >= 0; i -= 4) {
if (pixels[i + 3] !== 0) {
end = Math.floor(i / 4 / this.width);
break;
}
}
kerningTestCanvas.width = 10;
kerningTestCanvas.height = 10;
return {
top: start,
bottom: end,
height: end - start
}
}
/**
* Calculate the kerning offset between two letters.
* @param {string} letters - a two character string of the two letters to determine font kerning from. Returns the kerning offset that should be used to draw the 2nd letter.
* @param {object} flags - font style, such as bold or italic
*/
get_kerning_offset(letters, flags = {}) {
let offset = this.kerningMap.get(letters);
if (offset == null) {
kerningTestCtx.font =
' ' + (flags.italic ? 'italic' : '') +
' ' + (flags.bold ? 'bold' : '') +
' ' + (this.size) + 'px' +
' ' + this.family;
offset = kerningTestCtx.measureText(letters).width - (kerningTestCtx.measureText(letters[0]).width + kerningTestCtx.measureText(letters[1]).width);
this.kerningMap.set(letters, offset);
}
return offset;
}
}
/**
* This class's job is to store and modify the internal JSON format of a text layer.
*/
class Text_document_class {
constructor() {
this.lines = [];
this.on_change = null;
// If user edits params while no selection, queue meta insertion for next type.
this.queuedMetaChanges = null;
}
/**
* Returns the number of lines in the document.
*/
get_line_count() {
return this.lines.length;
}
/**
* Returns the length of a given line
* @param {number} lineNumber - The number of the line to get the length of
*/
get_line_character_count(lineNumber) {
return this.get_line_text(lineNumber).length;
}
/**
* Returns the text string at a given line (ignores formatting).
* @param {number} lineNumber - The number of the line to get the text from
*/
get_line_text(lineNumber) {
let lineText = '';
for (let i = 0; i < this.lines[lineNumber].length; i++) {
lineText += this.lines[lineNumber][i].text;
}
return lineText;
}
/**
* Returns the position of the end of the the word at the line/character provided
* @param {number} line - The reference line number (0 indexed)
* @param {number} character - The reference character position (0 indexed)
* @param {boolean} noJump - Dont jump to the next word if at the end of current one
*/
get_word_end_position(line, character, noJump) {
let newLine = line;
let newCharacter = character;
let fullText = this.get_line_text(newLine);
if (character === fullText.length && newLine < this.lines.length - 1) {
if (noJump) {
return { line, character };
}
newLine += 1;
character = 0;
fullText = this.get_line_text(newLine);
}
const text = fullText.slice(character);
if (noJump && text[0] === ' ') {
return { line, character };
}
for (let i = 1; i < text.length; i++) {
if (text[i] === ' ') {
newCharacter = character + i;
break;
}
}
if (newCharacter === character) {
newCharacter = fullText.length + 1;
}
return {
line: newLine,
character: newCharacter
}
}
/**
* Returns the position of the start of the the word at the line/character provided
* @param {number} line - The reference line number (0 indexed)
* @param {number} character - The reference character position (0 indexed)
* @param {boolean} noJump - Dont jump to the next word if at the end of current one
*/
get_word_start_position(line, character, noJump) {
let newLine = line;
let newCharacter = character;
let isWrap = false;
if (character === 0 && newLine > 0) {
if (noJump) {
return { line, character };
}
isWrap = true;
newLine -= 1;
}
const fullText = this.get_line_text(newLine);
if (isWrap) {
character = fullText.length;
}
const text = fullText.slice(0, character);
if (noJump && text[text.length - 1] === ' ') {
return { line, character };
}
for (let i = -1; i >= -text.length; i--) {
if (text[i + text.length - 1] === ' ') {
newCharacter = character + i;
break;
}
}
if (newCharacter === character) {
newCharacter = 0;
}
return {
line: newLine,
character: newCharacter
}
}
/**
* Determine if the metadata (formatting) of two text spans is the same, usually used to determine if the spans can be merged together.
*/
is_same_span_meta(meta1, meta2) {
const meta1Keys = Object.keys(meta1).sort();
const meta2Keys = Object.keys(meta2).sort();
if (meta1Keys.length !== meta2Keys.length) {
return false;
}
for (let i = 0; i < meta1Keys.length; i++) {
if (meta1Keys[i] !== meta2Keys[i]) {
return false;
}
const meta1Value = meta1[meta1Keys[i]];
const meta2Value = meta2[meta2Keys[i]];
if (JSON.stringify(meta1Value) !== JSON.stringify(meta2Value)) {
return false;
}
}
return true;
}
/**
* Inserts a span with empty text in the document at the specified line and character position
* @param {number} line - The line number to insert at (0 indexed)
* @param {number} character - The character position to insert at (0 indexed)
* @param {object} meta - Metadata to associate with span
*/
insert_empty_span(line, character, meta) {
let insertedSpan = null;
const lineDef = this.lines[line];
let newLine = [];
let spanStartCharacter = 0;
let wasInserted = false;
for (let span of lineDef) {
if (!wasInserted && character >= spanStartCharacter && character <= spanStartCharacter + span.text.length) {
let textBefore = span.text.slice(0, character - spanStartCharacter);
let textAfter = span.text.slice(character - spanStartCharacter);
if (textBefore.length > 0) {
newLine.push({
text: textBefore,
meta: JSON.parse(JSON.stringify(span.meta))
});
}
const newMeta = JSON.parse(JSON.stringify(span.meta));
for (let metaKey in meta) {
newMeta[metaKey] = meta[metaKey];
}
insertedSpan = {
text: '',
meta: newMeta
};
newLine.push(insertedSpan);
if (textAfter.length > 0) {
newLine.push({
text: textAfter,
meta: JSON.parse(JSON.stringify(span.meta))
});
}
wasInserted = true;
} else {
newLine.push(span);
}
spanStartCharacter += span.text.length;
}
this.lines[line] = newLine;
return insertedSpan;
}
/**
* Inserts a text string in the document at the specified line and character position
* @param {string} text - The text string to insert
* @param {number} line - The line number to insert at (0 indexed)
* @param {number} character - The character position to insert at (0 indexed)
*/
insert_text(text, line, character) {
let insertedSpan;
if (this.queuedMetaChanges) {
insertedSpan = this.insert_empty_span(line, character, this.queuedMetaChanges);
this.queuedMetaChanges = null;
}
const insertLine = this.lines[line];
const textHasNewline = text.includes('\n');
let characterCount = 0;
let modifyingSpan = null;
let previousSpans = [];
let nextSpans = [];
let newLine = line;
let newCharacter = character;
// Insert text into span at specified line/character
for (let i = 0; i < insertLine.length; i++) {
const span = insertLine[i];
const spanLength = span.text.length;
if (!modifyingSpan && (character > characterCount || character === 0) && character <= characterCount + spanLength) {
if (insertLine[i + 1] && insertLine[i + 1].text === '') {
modifyingSpan = insertLine[i + 1];
} else {
modifyingSpan = span;
}
const textIdx = character - characterCount;
modifyingSpan.text = modifyingSpan.text.slice(0, textIdx) + text + modifyingSpan.text.slice(textIdx);
if (!textHasNewline) {
newCharacter = characterCount + textIdx + text.length;
break;
}
} else if (textHasNewline) {
if (modifyingSpan) {
nextSpans.push(span);
} else {
previousSpans.push(span);
}
}
characterCount += spanLength;
}
// Create new lines if newline character was used
if (textHasNewline && modifyingSpan) {
const modifiedSpans = [];
const textLines = modifyingSpan.text.split('\n');
for (let i = 0; i < textLines.length; i++) {
modifiedSpans.push({
meta: JSON.parse(JSON.stringify(modifyingSpan.meta)),
text: textLines[i]
});
}
this.lines[line] = [...previousSpans, modifiedSpans.shift()];
for (let i = 0; i < modifiedSpans.length; i++) {
if (i === modifiedSpans.length - 1) {
if (!modifiedSpans[i].text && nextSpans.length > 0) {
this.lines.splice(line + i + 1, 0, nextSpans);
} else {
this.lines.splice(line + i + 1, 0, [modifiedSpans[i], ...nextSpans]);
}
newLine = line + i + 1;
newCharacter = text.length - 1 - text.lastIndexOf('\n');
} else {
this.lines.splice(line + i + 1, 0, [modifiedSpans[i]]);
}
}
}
// Notify change
if (this.on_change) {
this.on_change(this.lines);
}
// Return end position
return {
line: newLine,
character: newCharacter
};
}
/**
* Deletes text withing the specified range
* @param {number} startLine - The starting line of the text range
* @param {number} startCharacter - The character position at the starting line of the text range
* @param {number} endLine - The ending line of the text range
* @param {number} endCharacter - The character position at the ending line of the text range
*/
delete_range(startLine, startCharacter, endLine, endCharacter) {
// Check bounds
startLine >= 0 || (startLine = 0);
startCharacter >= 0 || (startCharacter = 0);
endLine < this.lines.length || (endLine = this.lines.length - 1);
const endLineCharacterCount = this.get_line_character_count(endLine);
endCharacter <= endLineCharacterCount || (
endCharacter = endLineCharacterCount
);
// Early return if there's nothing to delete
if (startLine === endLine && startCharacter === endCharacter) {
return {
line: startLine,
character: startCharacter
};
}
// Get spans in start line before range
const beforeSpans = [];
const afterSpans = [];
let characterCount = 0;
let startSpan = null;
let startSpanDeleteIndex = 0;
for (let i = 0; i < this.lines[startLine].length; i++) {
const span = this.lines[startLine][i];
const spanLength = span.text.length;
if (!startSpan && (startCharacter > characterCount || startCharacter === 0) && startCharacter <= characterCount + spanLength) {
startSpan = span;
startSpanDeleteIndex = Math.max(0, startCharacter - characterCount);
break;
}
if (!startSpan) {
beforeSpans.push(span);
}
characterCount += spanLength;
}
// Get spans in end line after range
characterCount = 0;
let endSpan = null;
let endSpanDeleteIndex = 0;
for (let i = 0; i < this.lines[endLine].length; i++) {
const span = this.lines[endLine][i];
const spanLength = span.text.length;
if (!endSpan && (endCharacter > characterCount || endCharacter === 0) && endCharacter <= characterCount + spanLength) {
endSpan = span;
endSpanDeleteIndex = Math.max(0, endCharacter - characterCount);
}
else if (endSpan) {
afterSpans.push(span);
}
characterCount += spanLength;
}
// Merge start and end lines
this.lines[startLine] = [...beforeSpans];
if (startSpan === endSpan || this.is_same_span_meta(startSpan.meta, endSpan.meta)) {
const combinedSpans = {
meta: startSpan.meta,
text: startSpan.text.slice(0, startSpanDeleteIndex) + endSpan.text.slice(endSpanDeleteIndex)
};
if (combinedSpans.text || (beforeSpans.length === 0 && afterSpans.length === 0)) {
this.lines[startLine].push(combinedSpans);
}
} else {
const middleSpans = [];
let isAddedStartSpan = false;
let isAddedEndSpan = false;
if (startSpan) {
startSpan.text = startSpan.text.slice(0, startSpanDeleteIndex);
if (startSpan.text) {
middleSpans.push(startSpan);
isAddedStartSpan = true;
}
}
if (endSpan) {
endSpan.text = endSpan.text.slice(endSpanDeleteIndex)
if (endSpan.text || middleSpans.length === 0) {
middleSpans.push(endSpan);
isAddedEndSpan = true;
}
}
if (isAddedStartSpan && !isAddedEndSpan) {
const afterSpan = afterSpans[0];
if (afterSpan && this.is_same_span_meta(startSpan.meta, afterSpan.meta)) {
afterSpans.shift();
startSpan.text += afterSpan.text;
}
}
else if (isAddedEndSpan && !isAddedStartSpan) {
const beforeSpan = beforeSpans[beforeSpans.length - 1];
if (beforeSpan && this.is_same_span_meta(beforeSpan.meta, endSpan.meta)) {
beforeSpans.pop();
beforeSpan.text += endSpan.text;
}
}
else if (middleSpans.length === 0) {
const beforeSpan = beforeSpans[beforeSpans.length - 1];
const afterSpan = afterSpans[0];
if (beforeSpan && afterSpan && this.is_same_span_meta(beforeSpan.meta, afterSpan.meta)) {
afterSpans.shift();
beforeSpan.text += afterSpan.text;
}
}
this.lines[startLine] = this.lines[startLine].concat(middleSpans);
}
this.lines[startLine] = this.lines[startLine].concat(afterSpans);
// Delete lines in-between range
this.lines.splice(startLine + 1, endLine - startLine);
// Notify change
if (this.on_change) {
this.on_change(this.lines);
}
// Return new position
return {
line: startLine,
character: startCharacter
};
}
/**
* Deletes a single character in front or behind the specified character position, handling deleting new lines, etc.
* @param {boolean} forward - True if deleting the next character, otherwise deletes the previous character
* @param {number} startLine - The line number to delete from
* @param {number} startCharacter - The character position to delete from
*/
delete_character(forward, startLine, startCharacter) {
let endLine = startLine;
let endCharacter = startCharacter;
// Delete forwards
if (forward) {
// If there are characters after cursor on this line we remove one
if (startCharacter < this.get_line_character_count(startLine)) {
++endCharacter;
}
// if there are Lines after this one we append it
else if (startLine < this.lines.length - 1) {
++endLine;
endCharacter = 0;
}
}
// Delete backwards
else {
// If there are characters before the cursor on this line we remove one
if (startCharacter > 0) {
--startCharacter;
}
// if there are rows before we append current to previous one
else if (startLine > 0) {
--startLine;
startCharacter = this.get_line_character_count(startLine);
}
}
return this.delete_range(startLine, startCharacter, endLine, endCharacter);
}
/**
* Retrieves a metadata summary object for the specified range of text.
* @param {number} startLine - The starting line of the text range
* @param {number} startCharacter - The character position at the starting line of the text range
* @param {number} endLine - The ending line of the text range
* @param {number} endCharacter - The character position at the ending line of the text range
*/
get_meta_range(startLine, startCharacter, endLine, endCharacter) {
// Check bounds
startLine >= 0 || (startLine = 0);
startCharacter >= 0 || (startCharacter = 0);
endLine < this.lines.length || (endLine = this.lines.length - 1);
const endLineCharacterCount = this.get_line_character_count(endLine);
endCharacter <= endLineCharacterCount || (
endCharacter = endLineCharacterCount
);
const isEmpty = startLine === endLine && startCharacter === endCharacter;
// Loop through all spans in range and collect meta values
const metaCollection = {};
for (const metaKey in metaDefaults) {
metaCollection[metaKey] = [];
}
let isInsideRange = false;
for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) {
const line = this.lines[lineIndex];
let spanStartCharacter = 0;
let startSpan = null;
let endSpan = null;
for (let spanIndex = 0; spanIndex < line.length; spanIndex++) {
const span = line[spanIndex];
if (lineIndex === startLine) {
if (
(!isEmpty && startCharacter >= spanStartCharacter && startCharacter < spanStartCharacter + span.text.length) ||
(isEmpty && startCharacter > spanStartCharacter && startCharacter <= spanStartCharacter + span.text.length) ||
(startCharacter === 0 && spanStartCharacter === 0)
) {
isInsideRange = true;
startSpan = span;
}
}
if (lineIndex === endLine && isInsideRange) {
if (
(!isEmpty && endCharacter <= spanStartCharacter + span.text.length) ||
(isEmpty && endCharacter < spanStartCharacter + span.text.length)
) {
endSpan = span;
isInsideRange = false;
}
}
if (isInsideRange || startSpan === span || (!isEmpty && endSpan === span)) {
for (const metaKey in metaCollection) {
let metaValue = span.meta[metaKey];
if (metaValue == null) {
metaValue = metaDefaults[metaKey];
}
if (!metaCollection[metaKey].includes(metaValue)) {
metaCollection[metaKey].push(metaValue);
}
}
}
spanStartCharacter += span.text.length;
}
}
// Fill in default values for undefined meta keys
for (const metaKey in metaDefaults) {
if (metaCollection[metaKey].length === 0) {
metaCollection[metaKey] = [metaDefaults[metaKey]];
}
}
return metaCollection;
}
/**
* Sets styling metadata for the specified range of text.
* @param {number} startLine - The starting line of the text range
* @param {number} startCharacter - The character position at the starting line of the text range
* @param {number} endLine - The ending line of the text range
* @param {number} endCharacter - The character position at the ending line of the text range
* @param {object} meta - The meta to set
*/
set_meta_range(startLine, startCharacter, endLine, endCharacter, meta) {
// Check bounds
startLine >= 0 || (startLine = 0);
startCharacter >= 0 || (startCharacter = 0);
endLine < this.lines.length || (endLine = this.lines.length - 1);
const endLineCharacterCount = this.get_line_character_count(endLine);
endCharacter <= endLineCharacterCount || (
endCharacter = endLineCharacterCount
);
// Set meta of spans in selection
let isInsideRange = false;
for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) {
const line = this.lines[lineIndex];
let newLine = [];
let spanStartCharacter = 0;
for (let span of line) {
const spanText = span.text;
const spanLength = spanText.length;
if (lineIndex === startLine) {
if (startCharacter <= spanStartCharacter) {
isInsideRange = true;
}
}
if (lineIndex === endLine) {
if (endCharacter < spanStartCharacter + spanLength) {
isInsideRange = false;
}
}
// Selection start splits the span it's inside of
let choppedStartCharacters = 0;
if (startCharacter > spanStartCharacter && startCharacter < spanStartCharacter + spanLength && lineIndex === startLine) {
choppedStartCharacters = startCharacter - spanStartCharacter;
newLine.push({
text: span.text.slice(0, startCharacter - spanStartCharacter),
meta: JSON.parse(JSON.stringify(span.meta))
});
span.text = span.text.slice(startCharacter - spanStartCharacter);
isInsideRange = true;
}
newLine.push(span);
// Selection end splits the span it's inside of
if (endCharacter > spanStartCharacter && endCharacter < spanStartCharacter + spanLength && lineIndex === endLine) {
newLine.push({
text: span.text.slice(endCharacter - spanStartCharacter - choppedStartCharacters),
meta: JSON.parse(JSON.stringify(span.meta))
});
span.text = span.text.slice(0, endCharacter - spanStartCharacter - choppedStartCharacters);
isInsideRange = true;
}
// Add meta to span
if (isInsideRange) {
for (const metaKey in meta) {
span.meta[metaKey] = meta[metaKey];
}
}
spanStartCharacter += spanLength;
}
this.lines[lineIndex] = newLine;
}
this.normalize(startLine, endLine);
// Notify change
if (this.on_change) {
this.on_change(this.lines);
}
}
/**
* Merges sibling spans that have the same metadata, and removes empty spans.
* @param {number} startLine - The starting line of the text range
* @param {number} endLine - The ending line of the text range
*/
normalize(startLine, endLine) {
for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) {
const line = this.lines[lineIndex];
let spanIndex = 0;
for (spanIndex = 0; spanIndex < line.length; spanIndex++) {
const span1 = line[spanIndex];
const span2 = line[spanIndex + 1];
if (span1 && span2 && this.is_same_span_meta(span1.meta, span2.meta)) {
line[spanIndex] = {
text: span1.text + span2.text,
meta: span1.meta
};
line.splice(spanIndex + 1, 1);
spanIndex--;
continue;
}
if (span1.text === '' && line.length > 1) {
line.splice(spanIndex, 1);
spanIndex--;
continue;
}
}
}
}
}
/**
* This class represents a single selection range in a text editor's document.
*/
class Text_selection_class {
constructor(/* Text_editor_class */ editor) {
this.editor = editor;
this.isVisible = false;
this.isCursorVisible = false;
this.isActiveSideEnd = true;
this.isBlinkVisible = true;
this.blinkInterval = 500;
this.start = {
line: 0,
character: 0
};
this.end = {
line: 0,
character: 0
};
this.set_position(0, 0);
}
/**
* Returns if the current text selection contains no characters
* @returns {boolean}
*/
is_empty() {
return this.compare_position(this.start.line, this.start.character, this.end.line, this.end.character) === 0;
}
/**
* Determines the relative position of two line/character sets.
* @param {number} line1
* @param {number} character1
* @param {number} line2
* @param {number} character2
* @returns {number} -1 if line1/character1 is less than line2/character2, 1 if greater, and 0 if equal
*/
compare_position(line1, character1, line2, character2) {
if (line1 < line2) {
return -1;
} else if (line1 > line2) {
return 1;
} else {
if (character1 < character2) {
return -1;
} else if (character1 > character2) {
return 1;
} else {
return 0;
}
}
}
/**
* Sets the head position of the selection to the specified line/character, optionally extends to selection to that position.
* @param {number} line - The line number to set the selection to
* @param {number} character - The character index to set the selection to
* @param {boolean} [keepSelection] - If true, extends the current selection to the specified position. If false or undefined, sets an empty selection at that position.
*/
set_position(line, character, keepSelection) {
if (line == null) {
line = this.end.line;
}
if (character == null) {
character = this.end.character;
}
// Check lower bounds
line >= 0 || (line = 0);
character >= 0 || (character = 0);
// Check upper bounds
const lineCount = this.editor.document.get_line_count();
line < lineCount || (line = lineCount - 1);
const lineCharacterCount = this.editor.document.get_line_character_count(line);
character <= lineCharacterCount || (character = lineCharacterCount);
// Add to selection
if (keepSelection) {
const positionCompare = this.compare_position(
line,
character,
this.start.line,
this.start.character
);
// Determine whether we should make the start side of the range active, selection moving left or up.
if (positionCompare === -1 && (this.is_empty() || line < this.start.line)) {
this.isActiveSideEnd = false;
}
// Assign new value to the side that is active
if (this.isActiveSideEnd) {
this.end.line = line;
this.end.character = character;
} else {
this.start.line = line;
this.start.character = character;
}
// Making sure that end is greater than start and swap if necessary
if (this.compare_position(this.start.line, this.start.character, this.end.line, this.end.character) > 0) {
this.isActiveSideEnd = !this.isActiveSideEnd;
const temp = {
line: this.start.line,
character: this.start.character
}
this.start.line = this.end.line;
this.start.character = this.end.character;
this.end.line = temp.line;
this.end.character = temp.character;
}
}
// Empty cursor move
else {
this.isActiveSideEnd = true;
this.start.line = this.end.line = line;
this.start.character = this.end.character = character;
}
// Reset cursor blink
this.isBlinkVisible = true;
if (this.isVisible) {
this.start_blinking();
}
}
/**
* Retrieves the position of the head of the selection (could be the start or end of the selection based on previous operations)
* @returns {object} - { line, character }
*/
get_position() {
if (this.isActiveSideEnd) {
return {
character: this.end.character,
line: this.end.line
};
} else {
return {
character: this.start.character,
line: this.start.line
};
}
}
/**
* Gets the plain text value in the current selection range.
* @returns {string}
*/
get_text() {
const positionCompare = this.compare_position(this.start.line, this.start.character, this.end.line, this.end.character);
const firstLine = positionCompare === 1 ? this.end.line : this.start.line;
const lastLine = positionCompare === 1 ? this.start.line : this.end.line;
const firstCharacter = positionCompare === 1 ? this.end.character : this.start.character;
const lastCharacter = positionCompare === 1 ? this.start.character : this.end.character;
let textLines = [];
for (let i = firstLine; i <= lastLine; i++) {
if (i === firstLine && i === lastLine) {
textLines.push(this.editor.document.get_line_text(i).slice(firstCharacter, lastCharacter));
} else if (i === firstLine) {
textLines.push(this.editor.document.get_line_text(i).slice(firstCharacter));
} else if (i === lastLine) {
textLines.push(this.editor.document.get_line_text(i).slice(0, lastCharacter));
} else {
textLines.push(this.editor.document.get_line_text(i));
}
}
return textLines.join('\n');
}
/**
* Sets the visibility of the selection in the editor.
* @param {boolean} isVisible
*/
set_visible(isVisible) {
if (this.isVisible != isVisible) {
this.isVisible = isVisible;
}
}
0