zmk/docs/src/keymap-upgrade/index.ts
Joel Spadin 37fcf190e6 feat(keymap-upgrader): Highlight changes
Updated the keymap upgrader to highlight which lines it changed as well
as indicate when nothing needed to be upgraded.

Also adjusted the line highlight colors to be more readable in both
light and dark color schemes.
2024-01-25 18:03:37 -06:00

59 lines
1.5 KiB
TypeScript

import { createParser } from "./parser";
import { applyEdits, Range } from "./textedit";
import { upgradeBehaviors } from "./behaviors";
import { upgradeHeaders } from "./headers";
import { upgradeKeycodes } from "./keycodes";
import { upgradeProperties } from "./properties";
export { initParser } from "./parser";
const upgradeFunctions = [
upgradeBehaviors,
upgradeHeaders,
upgradeKeycodes,
upgradeProperties,
];
export function upgradeKeymap(text: string) {
const parser = createParser();
const tree = parser.parse(text);
const edits = upgradeFunctions.map((f) => f(tree)).flat();
return applyEdits(text, edits);
}
export function rangesToLineNumbers(
text: string,
changedRanges: Range[]
): string {
const lineBreaks = getLineBreakPositions(text);
const changedLines = changedRanges.map((range) => {
const startLine = positionToLineNumber(range.startIndex, lineBreaks);
const endLine = positionToLineNumber(range.endIndex, lineBreaks);
return startLine === endLine ? `${startLine}` : `${startLine}-${endLine}`;
});
return `{${changedLines.join(",")}}`;
}
function getLineBreakPositions(text: string) {
const positions: number[] = [];
let index = 0;
while ((index = text.indexOf("\n", index)) >= 0) {
positions.push(index);
index++;
}
return positions;
}
function positionToLineNumber(position: number, lineBreaks: number[]) {
const line = lineBreaks.findIndex((lineBreak) => position <= lineBreak);
return line < 0 ? 0 : line + 1;
}