shahnevis-core
Version:
**Shahnevis Core** is a lightweight and flexible library for building custom code editors. It provides essential features like syntax highlighting, a minimap, multi-cursor support, line numbering, and plugin management. This library is framework-agnostic,
226 lines (199 loc) • 10.7 kB
JavaScript
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
/*
This file is part of Shahnevis Core.
Copyright (C) 2024 shahrooz saneidarani (github.com/shahroozD)
Shahnevis Core is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Shahnevis Core is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { expandViewToFull } from "./folding";
/**
* Detects changes made in the editor and returns detailed change information.
* This includes detecting insertion, deletion, or modification of code, handling folded blocks.
*
* @param {Event} event - The event object from the editor change.
* @param {string} newCode - The code after the change.
* @param {string} oldCode - The code before the change.
* @param {Object} foldedBlocks - Information about folded blocks in the editor.
* @returns {Object} changeInfo - Information about the detected change.
**/
export function detectChange(e, editor, foldedBlocksMap) {
var key = e.key || "";
var viewBefore = editor.value;
var startPos = editor.selectionStart;
var endPos = editor.selectionEnd;
// figure out exactly what was removed or inserted
var insertText = "";
var removedText = viewBefore.slice(startPos, endPos);
if (key.length === 1 || key === "Enter") {
insertText = key === "Enter" ? "\n" : key;
} else if (key === "Backspace" || key === "Delete") {
if (startPos === endPos) {
if (key === "Backspace" && startPos > 0) {
startPos -= 1;
removedText = viewBefore.charAt(startPos);
} else if (key === "Delete" && endPos < viewBefore.length) {
removedText = viewBefore.charAt(endPos);
endPos += 1;
} else {
return null;
}
}
}
// Count how many view‐lines the edit touched
var removedViewLines = (removedText.match(/\n/g) || []).length;
var insertedViewLines = (insertText.match(/\n/g) || []).length;
// Build the “after” view so we can expand it
var viewAfter = viewBefore.slice(0, startPos) + insertText + viewBefore.slice(endPos);
// Expand both to full text & grab the mapping
var beforeExp = expandViewToFull(viewBefore, foldedBlocksMap);
var afterExp = expandViewToFull(viewAfter, foldedBlocksMap);
var fullBefore = beforeExp.fullText;
var fullAfter = afterExp.fullText;
var viewToFull = beforeExp.viewToFull;
// Compute the view→full start line
var viewStartLine = viewBefore.slice(0, startPos).split("\n").length - 1;
var fullStartLine = viewToFull[viewStartLine];
// Now do the one true logical line‐count diff
var fullBeforeLines = fullBefore.length;
var fullAfterLines = fullAfter.length;
var logicalCountChange = fullAfterLines - fullBeforeLines;
return {
changeType: removedText.length && !insertText ? "deletion" : "insertion",
startLine: fullStartLine,
endLine: fullStartLine + removedViewLines,
startPos: startPos,
data: insertText || null,
lineCountChange: insertedViewLines - removedViewLines,
logicalCountChange: logicalCountChange
};
}
/**
* Build a changeInfo object for an insertion (paste), taking folded blocks into account.
*
* @param {ClipboardEvent} e
* @param {HTMLTextAreaElement} editor
* @param {Object} foldedBlocksMap
* @returns {{
* changeType: "insertion",
* startLine: number,
* endLine: number,
* startPos: number,
* data: string,
* lineCountChange: number,
* logicalCountChange: number
* }}
*/
export function makePasteChangeInfo(e, editor, foldedBlocksMap) {
// 1) Raw paste data and selection in the *view* (collapsed) text
var pasteText = e.clipboardData.getData("text/plain");
var viewText = editor.value;
var selectionStart = editor.selectionStart,
selectionEnd = editor.selectionEnd;
// 2) Rebuild full→view mapping so we can convert view-lines → full-lines
var _expandViewToFull = expandViewToFull(viewText, foldedBlocksMap),
viewToFull = _expandViewToFull.viewToFull;
// 3) Compute where the selection begins/ends in view lines & cols
var beforeStart = viewText.slice(0, selectionStart);
var beforeEnd = viewText.slice(0, selectionEnd);
var viewStartLine = beforeStart.split("\n").length - 1;
var viewStartCol = selectionStart - (beforeStart.lastIndexOf("\n") + 1);
var viewEndLine = beforeEnd.split("\n").length - 1;
var viewEndCol = selectionEnd - (beforeEnd.lastIndexOf("\n") + 1);
// 4) Translate those view lines into full‑text lines
var fullStartLine = viewToFull[viewStartLine];
var fullEndLine = viewToFull[viewEndLine];
// 5) Count lines removed & inserted in the *view*
var removedViewLines = viewEndLine - viewStartLine;
var insertedViewLines = pasteText.split("\n").length - 1;
var lineCountChange = insertedViewLines - removedViewLines;
// 6) Count lines removed & inserted in the *full* text
var removedFullLines = fullEndLine - fullStartLine;
var insertedFullLines = insertedViewLines; // same as view for paste
var logicalCountChange = insertedFullLines - removedFullLines;
return {
changeType: "insertion",
startLine: fullStartLine,
endLine: fullEndLine,
startPos: selectionStart,
data: pasteText,
lineCountChange: lineCountChange,
logicalCountChange: logicalCountChange
};
}
/**
* Returns the full code by inserting folded blocks back into the visible code.
*
* @param {string} currentVisibleCode - The code as seen in the editor (with folded blocks hidden).
* @returns {string} - The full code with all folded blocks inserted.
*/
export function generateFullCode(currentVisibleCode, standalone_foldedBlocks) {
var codeLines = currentVisibleCode.split('\n'); // Split visible code into lines
var fullCode = []; // Array to store the final full code
// Loop through each line in the visible code
for (var i = 0; i < codeLines.length; i++) {
fullCode.push(codeLines[i]); // Add the current visible line to fullCode
// Check if this line is a folded line (i.e., it's the start of a folded block)
if (standalone_foldedBlocks[i]) {
// Insert the folded block (stored lines) into the correct place
var foldedLines = standalone_foldedBlocks[i];
console.log(foldedLines);
fullCode.push.apply(fullCode, _toConsumableArray(foldedLines)); // Unfold and insert the folded lines
}
}
return fullCode.join('\n'); // Combine all lines back into a single string and return
}
export function cleanForFolded(fullCode, standalone_foldedBlocks) {
// Split the full code into lines
var lines = fullCode.split("\n");
// Create an array to store the resulting lines after removing the folded ones
var visibleLines = [];
// Iterate through each line, skipping the ones that are part of folded blocks
lines.forEach(function (line, lineIndex) {
// Check if the current lineIndex is part of any folded block
var isFoldedLine = false;
for (var _i = 0, _Object$entries = Object.entries(standalone_foldedBlocks); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
foldStartIndex = _Object$entries$_i[0],
foldedBlockLines = _Object$entries$_i[1];
var startIndex = parseInt(foldStartIndex, 10);
var endIndex = startIndex + foldedBlockLines.length;
// If the current line index falls within the folded block range, mark it as folded
if (lineIndex > startIndex && lineIndex <= endIndex) {
isFoldedLine = true;
break; // No need to check further once it's determined as folded
}
}
// If it's not part of any folded block, add it to the visibleLines array
if (!isFoldedLine) {
visibleLines.push(line);
}
});
// Join the visible lines back into a string and return the updated code
return visibleLines.join("\n");
}
export function handleCodeChange(event, editor, minimapContent, lineNumbers, foldingManager) {
// Only intercept real inserrt events
if (!event.altKey && !event.ctrlKey) {
var foldedBlocks = foldingManager.getFoldedBlocksById();
var changeInfo = detectChange(event, editor, foldedBlocks);
// Update Folding State (handle fold/unfold based on code changes)
foldingManager.updateFoldingState(changeInfo, editor, foldedBlocks, minimapContent, lineNumbers, foldingManager);
}
}