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

Fixed deleting element around array/map expressions #786

Merged
merged 18 commits into from
Dec 7, 2024
Merged
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
4 changes: 3 additions & 1 deletion apps/studio/electron/main/run/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type GeneratorOptions } from '@babel/generator';
import * as t from '@babel/types';
import type { TemplateNode, TemplateTag } from '@onlook/models/element';
import type { DynamicType, TemplateNode, TemplateTag } from '@onlook/models/element';
import * as fs from 'fs';
import { customAlphabet } from 'nanoid/non-secure';
import * as nodePath from 'path';
Expand Down Expand Up @@ -62,6 +62,7 @@ export function getTemplateNode(
path: any,
filename: string,
componentStack: string[],
dynamicType?: DynamicType,
): TemplateNode {
const startTag: TemplateTag = getTemplateTag(path.node.openingElement);
const endTag: TemplateTag | null = path.node.closingElement
Expand All @@ -73,6 +74,7 @@ export function getTemplateNode(
startTag,
endTag,
component,
dynamicType,
};
return domNode;
}
Expand Down
45 changes: 43 additions & 2 deletions apps/studio/electron/main/run/setup.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import traverse, { NodePath } from '@babel/traverse';
import * as t from '@babel/types';
import { EditorAttributes } from '@onlook/models/constants';
import type { TemplateNode } from '@onlook/models/element';
import type { DynamicType, TemplateNode } from '@onlook/models/element';
import { generateCode } from '../code/diff/helpers';
import { formatContent, readFile } from '../code/files';
import { parseJsxFile } from '../code/helpers';
Expand Down Expand Up @@ -67,6 +67,8 @@ export function createMappingFromContent(content: string, filename: string) {
function createMapping(ast: t.File, filename: string): Record<string, TemplateNode> | null {
const mapping: Record<string, TemplateNode> = {};
const componentStack: string[] = [];
const dynamicTypeStack: DynamicType[] = [];
const isFirstLayer: boolean[] = [];

traverse(ast, {
FunctionDeclaration: {
Expand All @@ -93,6 +95,28 @@ function createMapping(ast: t.File, filename: string): Record<string, TemplateNo
componentStack.pop();
},
},
CallExpression: {
enter(path) {
if (
t.isMemberExpression(path.node.callee) &&
t.isIdentifier(path.node.callee.property) &&
path.node.callee.property.name === 'map'
) {
dynamicTypeStack.push('array');
isFirstLayer.push(true);
}
},
exit(path) {
if (
t.isMemberExpression(path.node.callee) &&
t.isIdentifier(path.node.callee.property) &&
path.node.callee.property.name === 'map'
) {
dynamicTypeStack.pop();
isFirstLayer.pop();
}
},
},
JSXElement(path: any) {
if (isReactFragment(path.node.openingElement)) {
return;
Expand All @@ -105,9 +129,26 @@ function createMapping(ast: t.File, filename: string): Record<string, TemplateNo

if (idAttr) {
const elementId = idAttr.value.value;
const templateNode = getTemplateNode(path, filename, componentStack);

const isInFirstLayer = isFirstLayer[isFirstLayer.length - 1];
const currentDynamicType =
dynamicTypeStack.length > 0 && isInFirstLayer
? dynamicTypeStack[dynamicTypeStack.length - 1]
: undefined;
const templateNode = getTemplateNode(
path,
filename,
componentStack,
currentDynamicType,
);

mapping[elementId] = templateNode;
}

// After processing the first JSX element in a map, mark that we're no longer in first layer
if (isFirstLayer[isFirstLayer.length - 1]) {
isFirstLayer[isFirstLayer.length - 1] = false;
}
},
});
return mapping;
Expand Down
9 changes: 8 additions & 1 deletion apps/studio/electron/preload/webview/api.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { contextBridge } from 'electron';
import { processDom } from './dom';
import { getDomElementByDomId, getElementAtLoc, updateElementInstance } from './elements';
import { getActionElementByDomId, getActionLocation } from './elements/dom/helpers';
import {
getActionElementByDomId,
getActionLocation,
setDynamicElementType,
getDynamicElementType,
} from './elements/dom/helpers';
import { getInsertLocation } from './elements/dom/insert';
import { getRemoveActionFromDomId } from './elements/dom/remove';
import { getElementIndex } from './elements/move';
Expand All @@ -22,6 +27,8 @@ export function setApi() {
// Elements
getElementAtLoc,
getDomElementByDomId,
setDynamicElementType,
getDynamicElementType,

// Actions
getActionLocation,
Expand Down
22 changes: 22 additions & 0 deletions apps/studio/electron/preload/webview/elements/dom/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { getOrAssignDomId } from '../../ids';
import { getImmediateTextContent } from '../helpers';
import { elementFromDomId } from '/common/helpers';
import { getInstanceId, getOid } from '/common/helpers/ids';
import { EditorAttributes } from '@onlook/models/constants';
import type { DynamicType } from '@onlook/models/element';

export function getActionElementByDomId(domId: string): ActionElement | null {
const el = elementFromDomId(domId);
Expand Down Expand Up @@ -77,3 +79,23 @@ export function getActionLocation(domId: string): ActionLocation | null {
originalIndex: index,
};
}

export function getDynamicElementType(domId: string): DynamicType | null {
const el = document.querySelector(
`[${EditorAttributes.DATA_ONLOOK_DOM_ID}="${domId}"]`,
) as HTMLElement | null;

if (!el) {
console.warn('No element found', { domId });
return null;
}

return el.getAttribute(EditorAttributes.DATA_ONLOOK_DYNAMIC_TYPE) as DynamicType;
}

export function setDynamicElementType(domId: string, dynamicType: string) {
const el = document.querySelector(`[${EditorAttributes.DATA_ONLOOK_DOM_ID}="${domId}"]`);
if (el) {
el.setAttribute(EditorAttributes.DATA_ONLOOK_DYNAMIC_TYPE, dynamicType);
}
}
10 changes: 10 additions & 0 deletions apps/studio/src/lib/editor/engine/ast/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ export class AstManager {
return;
}

if (templateNode.dynamicType) {
node.dynamicType = templateNode.dynamicType;
const webview = this.editorEngine.webviews.getWebview(webviewId);
if (webview) {
webview.executeJavaScript(
`window.api?.setDynamicElementType('${node.domId}', '${templateNode.dynamicType}')`,
);
}
}

this.findNodeInstance(webviewId, node, node, templateNode);
}

Expand Down
16 changes: 16 additions & 0 deletions apps/studio/src/lib/editor/engine/element/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { DomElement } from '@onlook/models/element';
import { debounce } from 'lodash';
import { makeAutoObservable } from 'mobx';
import type { EditorEngine } from '..';
import { toast } from '@onlook/ui/use-toast';

export class ElementManager {
private hoveredElement: DomElement | undefined;
Expand Down Expand Up @@ -155,6 +156,20 @@ export class ElementManager {
return;
}

const dynamicElementType = await webview.executeJavaScript(
`window.api?.getDynamicElementType('${selectedEl.domId}')`,
);

if (dynamicElementType) {
toast({
title: 'Invalid Action',
description: `This element is part of a react expression (${dynamicElementType}) and cannot be deleted`,
variant: 'destructive',
});

return;
}

const removeAction = (await webview.executeJavaScript(
`window.api?.getRemoveActionFromDomId('${selectedEl.domId}', '${webviewId}')`,
)) as RemoveElementAction | null;
Expand All @@ -166,6 +181,7 @@ export class ElementManager {
if (!codeBlock) {
console.error('Code block not found');
}

this.editorEngine.action.run(removeAction);
}
}
1 change: 1 addition & 0 deletions packages/models/src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export enum EditorAttributes {
DATA_ONLOOK_DRAG_START_POSITION = 'data-onlook-drag-start-position',
DATA_ONLOOK_NEW_INDEX = 'data-onlook-new-index',
DATA_ONLOOK_EDITING_TEXT = 'data-onlook-editing-text',
DATA_ONLOOK_DYNAMIC_TYPE = 'data-onlook-dynamic-type',
}

export enum WebviewChannels {
Expand Down
4 changes: 4 additions & 0 deletions packages/models/src/element/layers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { z } from 'zod';

export const DynamicTypeEnum = z.enum(['array', 'conditional', 'unknown']);
export type DynamicType = z.infer<typeof DynamicTypeEnum>;

const LayerNodeSchema = z.object({
domId: z.string(),
webviewId: z.string(),
Expand All @@ -8,6 +11,7 @@ const LayerNodeSchema = z.object({
textContent: z.string(),
tagName: z.string(),
isVisible: z.boolean(),
dynamicType: DynamicTypeEnum.optional(),
component: z.string().nullable(),
children: z.array(z.string()).nullable(),
parent: z.string().nullable(),
Expand Down
2 changes: 2 additions & 0 deletions packages/models/src/element/templateNode.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { z } from 'zod';
import { DynamicTypeEnum } from './layers';

export const TemplateTagPositionSchema = z.object({
line: z.number(),
Expand All @@ -15,6 +16,7 @@ export const TemplateNodeSchema = z.object({
startTag: TemplateTagSchema,
endTag: TemplateTagSchema.nullable(),
component: z.string().nullable(),
dynamicType: DynamicTypeEnum.nullable().optional(),
});

export type TemplateNode = z.infer<typeof TemplateNodeSchema>;
Expand Down