Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using Monaco decorations to presist node UIDs across edits #879

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"buffer": "^6.0.3",
"classnames": "^2.3.2",
"cmdk": "^0.1.20",
"diff-match-patch": "^1.0.5",
"file-system-access": "^1.0.4",
"filer": "^1.4.1",
"idb-keyval": "^6.2.0",
Expand All @@ -51,6 +52,7 @@
},
"devDependencies": {
"@babel/core": "^7.19.6",
"@types/diff-match-patch": "^1.0.36",
"@types/file-saver": "^2.0.5",
"@types/js-beautify": "^1.14.3",
"@types/lodash": "^4.14.191",
Expand Down
21 changes: 18 additions & 3 deletions src/_redux/main/nodeTree/event/slice.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import undoable from "redux-undo";

import { TNodeUid } from "@_api/types";
import { TNodePositionInfo, TNodeUid } from "@_api/types";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";

import {
Expand All @@ -15,6 +15,7 @@ import { TNodeEventReducerState } from "./types";
const nodeEventReducerInitialState: TNodeEventReducerState = {
currentFileContent: "",
selectedNodeUids: [],
nodeUidPositions: new Map(),
currentFileUid: "",
};
const nodeEventSlice = createSlice({
Expand All @@ -29,6 +30,13 @@ const nodeEventSlice = createSlice({
const selectedNodeUids = action.payload;
state.selectedNodeUids = [...selectedNodeUids];
},
setNodeUidPositions(
state,
action: PayloadAction<Map<TNodeUid, TNodePositionInfo>>,
) {
const nodeUidPositions = action.payload;
state.nodeUidPositions = nodeUidPositions;
},
setNeedToSelectNodeUids(state, action: PayloadAction<TNodeUid[]>) {
const needToSelectNodeUids = action.payload;
state.selectedNodeUids = needToSelectNodeUids;
Expand All @@ -42,6 +50,7 @@ const nodeEventSlice = createSlice({
export const {
setCurrentFileContent,
setSelectedNodeUids,
setNodeUidPositions,
setNeedToSelectNodeUids,
setCurrentFileUid,
} = nodeEventSlice.actions;
Expand All @@ -54,7 +63,10 @@ export const NodeEventReducer = undoable(nodeEventSlice.reducer, {

groupBy: (action, currentState, previousHistory) => {
if (previousHistory.index) {
if (action.type === "nodeEvent/setCurrentFileContent") {
if (
action.type === "nodeEvent/setCurrentFileContent" ||
action.type === "nodeEvent/setNodeUidPositions"
) {
return `node-action-${previousHistory.index}`;
} else if (action.type === "nodeEvent/setNeedToSelectNodeUids") {
return `node-action-${previousHistory.index - 1}`;
Expand All @@ -63,7 +75,10 @@ export const NodeEventReducer = undoable(nodeEventSlice.reducer, {
return null;
},
filter: (action, currentState) => {
const ignoreActionTypes = ["nodeEvent/setCurrentFileUid"];
const ignoreActionTypes = [
"nodeEvent/setCurrentFileUid",
"nodeEvent/setNodeUidPositions",
];
if (ignoreActionTypes.includes(action.type)) return false;
if (currentState.currentFileUid.split(".")[1] !== "html") return false;
return true;
Expand Down
3 changes: 2 additions & 1 deletion src/_redux/main/nodeTree/event/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { TNodeUid } from "@_api/types";
import { TNodePositionInfo, TNodeUid } from "@_api/types";

export type TNodeEventReducerState = {
currentFileContent: string;
selectedNodeUids: TNodeUid[];
nodeUidPositions: Map<TNodeUid, TNodePositionInfo>;
currentFileUid: string;
};

Expand Down
8 changes: 7 additions & 1 deletion src/_redux/useAppState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ export const useAppState = () => {
},
nodeEvent: {
past: nodeEventPast,
present: { currentFileContent, selectedNodeUids, currentFileUid },
present: {
currentFileContent,
selectedNodeUids,
nodeUidPositions,
currentFileUid,
},
future: nodeEventFuture,
},
designView: { iframeSrc, iframeLoading, linkToOpen, syncConfigs },
Expand Down Expand Up @@ -137,6 +142,7 @@ export const useAppState = () => {

currentFileContent,
selectedNodeUids,
nodeUidPositions,

nodeEventPast,
nodeEventPastLength,
Expand Down
84 changes: 65 additions & 19 deletions src/actions/useFormatCode.action.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
import useRnbw from "@_services/useRnbw";
import { Range, editor } from "monaco-editor";

// helperModel added to update the code in the codeViewInstanceModel
// once when the action is executed, this improves the History Management
const helperModel = editor.createModel("", "html");
import { diff_match_patch, Diff } from "diff-match-patch";

import { sortUidsByMaxEndIndex } from "@src/sidebarView/nodeTreeView/helpers";
import { useAppState } from "@_redux/useAppState";
import { PrettyCode } from "@_services/useElementsHelper";
import { PrettyCode, useElementHelper } from "@_services/useElementsHelper";
import { useContext } from "react";
import { MainContext } from "@src/_redux/main";

export default function useFormatCode() {
const { validNodeTree } = useAppState();
const { monacoEditorRef } = useContext(MainContext);
const { setEditorModelValue, getEditorModelWithCurrentCode } =
useElementHelper();

const rnbw = useRnbw();

async function formatCode() {
const codeViewInstanceModel = rnbw.files.getEditorRef().current?.getModel();
const codeViewInstanceModel = monacoEditorRef.current?.getModel();
if (!codeViewInstanceModel) return;

helperModel.setValue(codeViewInstanceModel.getValue());

const helperModel = getEditorModelWithCurrentCode();
const selectedElements = rnbw.elements.getSelectedElements();
const sortedUids = sortUidsByMaxEndIndex(selectedElements, validNodeTree);
const dmp = new diff_match_patch();

const edits = await Promise.all(
await Promise.all(
sortedUids.map(async (uid) => {
const node = rnbw.elements.getElement(uid);
if (!node) return null;
Expand All @@ -31,20 +34,63 @@ export default function useFormatCode() {
node.data.sourceCodeLocation;
const range = new Range(startLine, startCol, endLine, endCol);
const code = codeViewInstanceModel.getValueInRange(range);
const text = await PrettyCode({ code, startCol });
const formattedCode = await PrettyCode({ code, startCol });

return { range, text };
// Compute the diff
const diffs = dmp.diff_main(code, formattedCode);
dmp.diff_cleanupSemantic(diffs);

// Generate Monaco edits from the diffs
let currentPosition = range.getStartPosition();

diffs.forEach((diff) => {
const [operation, text] = diff;
if (operation === 0) {
// No change
currentPosition = helperModel.modifyPosition(
currentPosition,
text.length,
);
} else if (operation === -1) {
// Delete text
const endPosition = helperModel.modifyPosition(
currentPosition,
text.length,
);
helperModel.applyEdits([
{
range: new Range(
currentPosition.lineNumber,
currentPosition.column,
endPosition.lineNumber,
endPosition.column,
),
text: "",
},
]);
} else if (operation === 1) {
// Insert text
helperModel.applyEdits([
{
range: new Range(
currentPosition.lineNumber,
currentPosition.column,
currentPosition.lineNumber,
currentPosition.column,
),
text,
},
]);
currentPosition = helperModel.modifyPosition(
currentPosition,
text.length,
);
}
});
}),
);

edits.forEach((edit) => {
if (edit) {
helperModel.applyEdits([edit]);
}
});

const code = helperModel.getValue();
codeViewInstanceModel.setValue(code);
setEditorModelValue(helperModel, codeViewInstanceModel);
}

const config = {
Expand Down
26 changes: 15 additions & 11 deletions src/actions/useTurnInto.actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,26 @@ import { Range, editor } from "monaco-editor";

import { PrettyCode, useElementHelper } from "@_services/useElementsHelper";
import { toast } from "react-toastify";

// helperModel added to update the code in the codeViewInstanceModel
// once when the action is executed, this improves the History Management
const helperModel = editor.createModel("", "html");
import { useContext } from "react";
import { MainContext } from "@src/_redux/main";

export default function useTurnInto() {
const rnbw = useRnbw();
const { isPastingAllowed, sortUidsDsc, findNodeToSelectAfterAction } =
useElementHelper();
const { monacoEditorRef } = useContext(MainContext);
const {
isPastingAllowed,
sortUidsDsc,
findNodeToSelectAfterAction,
setEditorModelValue,
getEditorModelWithCurrentCode,
} = useElementHelper();

const selectedElements = rnbw.elements.getSelectedElements();

async function turnInto(tagName: string) {
const sortedUids = sortUidsDsc(selectedElements);

const codeViewInstanceModel = rnbw.files.getEditorRef().current?.getModel();
const codeViewInstanceModel = monacoEditorRef.current?.getModel();
if (!codeViewInstanceModel) return;
helperModel.setValue(codeViewInstanceModel.getValue());

// Checking if a parent component can have a tag as a child
const { isAllowed } = isPastingAllowed({
Expand All @@ -33,6 +35,8 @@ export default function useTurnInto() {
return;
}

const helperModel = getEditorModelWithCurrentCode();

for (const uid of sortedUids) {
const node = rnbw.elements.getElement(uid);
if (!node) return;
Expand Down Expand Up @@ -66,8 +70,8 @@ export default function useTurnInto() {
};
helperModel.applyEdits([edit]);
}
const code = helperModel.getValue();
codeViewInstanceModel.setValue(code);

setEditorModelValue(helperModel, codeViewInstanceModel);

await findNodeToSelectAfterAction({
nodeUids: sortedUids,
Expand Down
19 changes: 19 additions & 0 deletions src/api/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
TNodeUid,
} from "./types";
import { THtmlNodeData } from "./node";
import { editor } from "monaco-editor";

export const getSubNodeUidsByBfs = (
uid: TNodeUid,
Expand Down Expand Up @@ -235,3 +236,21 @@ export const getNodeDepthExternal = (

return nodeDepth;
};
export const isUidDecoration = (decoration: editor.IModelDecoration) => {
return decoration.options.className?.startsWith("uid-");
};
export const getUidDecorations = (
model: editor.ITextModel | null | undefined,
) => {
return model?.getAllDecorations().filter(isUidDecoration) || [];
};
export const getDecorationUid = (decoration: editor.IModelDecoration) => {
const className = decoration.options.className as string;
return className.replace(/\D/g, "");
};
export const setDecorationUid = (
decoration: editor.IModelDecoration | editor.IModelDeltaDecoration,
uid: TNodeUid,
) => {
decoration.options.className = `uid-${uid}`;
};
2 changes: 2 additions & 0 deletions src/api/node/type/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Document } from "parse5/dist/tree-adapters/default";
import {
TNode,
TNodeData,
TNodePositionInfo,
TNodeSourceCodeLocation,
TNodeTreeData,
TNodeUid,
Expand Down Expand Up @@ -46,4 +47,5 @@ export type THtmlParserResponse = {
nodeTree: TNodeTreeData;
htmlDom: Document;
selectedNodeUids: TNodeUid[];
nodeUidPositions?: Map<TNodeUid, TNodePositionInfo> | null;
};
5 changes: 5 additions & 0 deletions src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ export type TNodeSourceCodeLocation = {
endTag?: Omit<TNodeSourceCodeLocation, "startTag" | "endTag">;
};

export type TNodePositionInfo = {
decorationId?: string | null;
location: TNodeSourceCodeLocation;
};

export type TNodeActionType =
| "add"
| "remove"
Expand Down
Loading