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

Reparent into grid #6258

Merged
merged 5 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { stripNulls, zip } from '../../../../core/shared/array-utils'
import type { Either } from '../../../../core/shared/either'
import { isLeft, left, right } from '../../../../core/shared/either'
import * as EP from '../../../../core/shared/element-path'
import * as PP from '../../../../core/shared/property-path'
import type { ElementPathTrees } from '../../../../core/shared/element-path-tree'
import type { ElementInstanceMetadataMap } from '../../../../core/shared/element-template'
import {
Expand Down Expand Up @@ -54,7 +53,6 @@ import type { CanvasCommand } from '../../commands/commands'
import { foldAndApplyCommandsInner } from '../../commands/commands'
import { deleteElement } from '../../commands/delete-element-command'
import { queueTrueUpElement } from '../../commands/queue-true-up-command'
import { propertyToDelete, updateBulkProperties } from '../../commands/set-property-command'
import { showToastCommand } from '../../commands/show-toast-command'
import { updateFunctionCommand } from '../../commands/update-function-command'
import { updateSelectedViews } from '../../commands/update-selected-views-command'
Expand Down Expand Up @@ -289,13 +287,6 @@ export function staticReparentAndUpdatePosition(
target.parentPath.intendedParentPath,
)

const isGrid = MetadataUtils.isGridLayoutedContainer(
MetadataUtils.findElementByElementPath(
editorStateContext.startingMetadata,
target.parentPath.intendedParentPath,
),
)

const commands = elementsToInsert.flatMap((elementToInsert) => {
return [
updateFunctionCommand('always', (editor, commandLifecycle) => {
Expand Down Expand Up @@ -327,17 +318,7 @@ export function staticReparentAndUpdatePosition(
)

function getAbsolutePositioningCommands(targetPath: ElementPath): Array<CanvasCommand> {
if (isGrid) {
return [
updateBulkProperties('always', targetPath, [
propertyToDelete(PP.create('style', 'position')),
propertyToDelete(PP.create('style', 'top')),
propertyToDelete(PP.create('style', 'left')),
propertyToDelete(PP.create('style', 'bottom')),
propertyToDelete(PP.create('style', 'right')),
]),
]
} else if (strategy === 'REPARENT_AS_ABSOLUTE') {
if (strategy === 'REPARENT_AS_ABSOLUTE') {
return positionElementToCoordinatesCommands(
{ oldPath: elementToInsert.elementPath, newPath: targetPath },
pasteContext.originalAllElementProps,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,7 @@ import {
import type { InteractionSession, UpdatedPathMap } from '../interaction-state'
import { absoluteMoveStrategy } from './absolute-move-strategy'
import { honoursPropsPosition, shouldKeepMovingDraggedGroupChildren } from './absolute-utils'
import {
replaceFragmentLikePathsWithTheirChildrenRecursive,
treatElementAsFragmentLike,
} from './fragment-like-helpers'
import { replaceFragmentLikePathsWithTheirChildrenRecursive } from './fragment-like-helpers'
import { ifAllowedToReparent, isAllowedToReparent } from './reparent-helpers/reparent-helpers'
import type { ForcePins } from './reparent-helpers/reparent-property-changes'
import { getAbsoluteReparentPropertyChanges } from './reparent-helpers/reparent-property-changes'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
targetPaths,
} from '../canvas-strategy-types'
import type { InteractionSession } from '../interaction-state'
import type { ParentDisplayType } from './reparent-metastrategy'
import { getApplicableReparentFactories } from './reparent-metastrategy'
import type { ReparentStrategy } from './reparent-helpers/reparent-strategy-helpers'
import { styleStringInArray } from '../../../../utils/common-constants'
Expand Down Expand Up @@ -116,9 +117,11 @@ export const dragToInsertMetaStrategy: MetaCanvasStrategy = (

function getDragToInsertStrategyName(
strategyType: ReparentStrategy,
parentDisplayType: 'flex' | 'flow',
parentDisplayType: ParentDisplayType,
): string {
switch (strategyType) {
case 'REPARENT_INTO_GRID':
return 'Drag to Insert (Grid)'
case 'REPARENT_AS_ABSOLUTE':
return 'Drag to Insert (Abs)'
case 'REPARENT_AS_STATIC':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { isImg } from '../../../../core/model/project-file-utils'
import { mapDropNulls, stripNulls } from '../../../../core/shared/array-utils'
import { foldEither } from '../../../../core/shared/either'
import * as EP from '../../../../core/shared/element-path'
import { elementPath } from '../../../../core/shared/element-path'
import type {
ElementInstanceMetadataMap,
JSXAttributes,
Expand Down Expand Up @@ -56,6 +55,7 @@ import {
} from '../canvas-strategy-types'
import type { InteractionSession } from '../interaction-state'
import { boundingArea } from '../interaction-state'
import type { ParentDisplayType } from './reparent-metastrategy'
import { getApplicableReparentFactories } from './reparent-metastrategy'
import type { ReparentStrategy } from './reparent-helpers/reparent-strategy-helpers'
import { styleStringInArray } from '../../../../utils/common-constants'
Expand All @@ -68,6 +68,7 @@ import { wildcardPatch } from '../../commands/wildcard-patch-command'
import type { InsertionPath } from '../../../editor/store/insertion-path'
import { childInsertionPath } from '../../../editor/store/insertion-path'
import { gridDrawToInsertStrategy } from './grid-draw-to-insert-strategy'
import { assertNever } from '../../../../core/shared/utils'

/**
*
Expand Down Expand Up @@ -141,17 +142,23 @@ export const drawToInsertMetaStrategy: MetaCanvasStrategy = (

export function getDrawToInsertStrategyName(
strategyType: ReparentStrategy,
parentDisplayType: 'flex' | 'flow',
parentDisplayType: ParentDisplayType,
): string {
switch (strategyType) {
case 'REPARENT_AS_ABSOLUTE':
return 'Draw to Insert (Abs)'
case 'REPARENT_AS_STATIC':
if (parentDisplayType === 'flex') {
return 'Draw to Insert (Flex)'
} else if (parentDisplayType === 'grid') {
return 'Draw to Insert (Grid)'
} else {
return 'Draw to Insert (Flow)'
}
case 'REPARENT_INTO_GRID':
return 'Draw to Insert (Grid)'
default:
assertNever(strategyType)
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
import { MetadataUtils } from '../../../../core/model/element-metadata-utils'
import { mapDropNulls } from '../../../../core/shared/array-utils'
import * as EP from '../../../../core/shared/element-path'
import * as PP from '../../../../core/shared/property-path'
import type { ElementPath } from '../../../../core/shared/project-file-types'
import { CSSCursor } from '../../canvas-types'
import { setCursorCommand } from '../../commands/set-cursor-command'
import {
propertyToDelete,
propertyToSet,
updateBulkProperties,
} from '../../commands/set-property-command'
import { updateSelectedViews } from '../../commands/update-selected-views-command'
import { ParentBounds } from '../../controls/parent-bounds'
import { ParentOutlines } from '../../controls/parent-outlines'
import { ZeroSizedElementControls } from '../../controls/zero-sized-element-controls'
import type { CanvasStrategyFactory } from '../canvas-strategies'
import type {
CanvasStrategy,
CustomStrategyState,
InteractionCanvasState,
} from '../canvas-strategy-types'
import {
controlWithProps,
emptyStrategyApplicationResult,
getTargetPathsFromInteractionTarget,
strategyApplicationResult,
} from '../canvas-strategy-types'
import type { InteractionSession, UpdatedPathMap } from '../interaction-state'
import { honoursPropsPosition, shouldKeepMovingDraggedGroupChildren } from './absolute-utils'
import { replaceFragmentLikePathsWithTheirChildrenRecursive } from './fragment-like-helpers'
import { ifAllowedToReparent, isAllowedToReparent } from './reparent-helpers/reparent-helpers'
import type { ReparentTarget } from './reparent-helpers/reparent-strategy-helpers'
import { getReparentOutcome, pathToReparent } from './reparent-utils'
import { flattenSelection } from './shared-move-strategies-helpers'
import { isInfinityRectangle } from '../../../../core/shared/math-utils'
import { showGridControls } from '../../commands/show-grid-controls-command'
import { GridControls } from '../../controls/grid-controls'
import type { ElementInstanceMetadataMap } from '../../../../core/shared/element-template'
import type { ElementPathTrees } from '../../../../core/shared/element-path-tree'
import type { AllElementProps } from '../../../editor/store/editor-state'
import type { BuiltInDependencies } from '../../../../core/es-modules/package-manager/built-in-dependencies-list'
import type { NodeModules, ProjectContentTreeRoot } from 'utopia-shared/src/types'
import type { InsertionPath } from '../../../editor/store/insertion-path'

export function gridReparentStrategy(
reparentTarget: ReparentTarget,
fitness: number,
customStrategyState: CustomStrategyState,
): CanvasStrategyFactory {
return (
canvasState: InteractionCanvasState,
interactionSession: InteractionSession | null,
): CanvasStrategy | null => {
const selectedElements = getTargetPathsFromInteractionTarget(canvasState.interactionTarget)
if (
selectedElements.length === 0 ||
interactionSession == null ||
interactionSession.interactionData.type !== 'DRAG'
) {
return null
}

const gridFrame = MetadataUtils.findElementByElementPath(
canvasState.startingMetadata,
reparentTarget.newParent.intendedParentPath,
)?.globalFrame
if (gridFrame == null || isInfinityRectangle(gridFrame)) {
return null
}

const dragInteractionData = interactionSession.interactionData
const filteredSelectedElements = flattenSelection(selectedElements)
const isApplicable = replaceFragmentLikePathsWithTheirChildrenRecursive(
canvasState.startingMetadata,
canvasState.startingAllElementProps,
canvasState.startingElementPathTree,
filteredSelectedElements,
).every((element) => {
return honoursPropsPosition(canvasState, element)
})
if (!isApplicable) {
return null
}
return {
id: `GRID_REPARENT`,
name: `Reparent (Grid)`,
descriptiveLabel: 'Reparent (Grid)',
icon: {
category: 'modalities',
type: 'reparent-large',
},
controlsToRender: [
controlWithProps({
control: ParentOutlines,
props: { targetParent: reparentTarget.newParent.intendedParentPath },
key: 'parent-outlines-control',
show: 'visible-only-while-active',
}),
controlWithProps({
control: ParentBounds,
props: { targetParent: reparentTarget.newParent.intendedParentPath },
key: 'parent-bounds-control',
show: 'visible-only-while-active',
}),
controlWithProps({
control: ZeroSizedElementControls,
props: { showAllPossibleElements: true },
key: 'zero-size-control',
show: 'visible-only-while-active',
}),
{
control: GridControls,
props: { targets: [reparentTarget.newParent.intendedParentPath] },
key: `draw-into-grid-strategy-controls`,
show: 'always-visible',
priority: 'bottom',
},
],
fitness: shouldKeepMovingDraggedGroupChildren(
canvasState.startingMetadata,
selectedElements,
reparentTarget.newParent,
)
? 1
: fitness,
apply: () => {
const { projectContents, nodeModules } = canvasState
const newParent = reparentTarget.newParent
return ifAllowedToReparent(
canvasState,
canvasState.startingMetadata,
filteredSelectedElements,
newParent.intendedParentPath,
() => {
if (dragInteractionData.drag == null) {
return emptyStrategyApplicationResult
}

const allowedToReparent = filteredSelectedElements.every((selectedElement) => {
return isAllowedToReparent(
canvasState.projectContents,
canvasState.startingMetadata,
selectedElement,
newParent.intendedParentPath,
)
})

if (!(reparentTarget.shouldReparent && allowedToReparent)) {
return emptyStrategyApplicationResult
}
const outcomes = mapDropNulls(
(selectedElement) =>
gridReparentCommands(
canvasState.startingMetadata,
canvasState.startingElementPathTree,
canvasState.startingAllElementProps,
canvasState.builtInDependencies,
projectContents,
nodeModules,
selectedElement,
newParent,
),
selectedElements,
)

let newPaths: Array<ElementPath> = []
let updatedTargetPaths: UpdatedPathMap = {}

outcomes.forEach((c) => {
newPaths.push(c.newPath)
updatedTargetPaths[EP.toString(c.oldPath)] = c.newPath
})

const gridContainerCommands = updateBulkProperties(
'mid-interaction',
reparentTarget.newParent.intendedParentPath,
[
propertyToSet(PP.create('style', 'width'), gridFrame.width),
propertyToSet(PP.create('style', 'height'), gridFrame.height),
],
)

const elementsToRerender = EP.uniqueElementPaths([
...customStrategyState.elementsToRerender,
...newPaths,
...newPaths.map(EP.parentPath),
...filteredSelectedElements.map(EP.parentPath),
])

return strategyApplicationResult(
[
...outcomes.flatMap((c) => c.commands),
gridContainerCommands,
updateSelectedViews('always', newPaths),
setCursorCommand(CSSCursor.Reparent),
showGridControls('mid-interaction', reparentTarget.newParent.intendedParentPath),
],
{
elementsToRerender,
},
)
},
)
},
}
}
}

function gridReparentCommands(
jsxMetadata: ElementInstanceMetadataMap,
tree: ElementPathTrees,
allElementProps: AllElementProps,
builtinDependencies: BuiltInDependencies,
projectContents: ProjectContentTreeRoot,
nodeModules: NodeModules,
target: ElementPath,
newParent: InsertionPath,
) {
const reparentResult = getReparentOutcome(
jsxMetadata,
tree,
allElementProps,
builtinDependencies,
projectContents,
nodeModules,
pathToReparent(target),
newParent,
'always',
null,
)

if (reparentResult == null) {
return null
}

const { commands: reparentCommands, newPath } = reparentResult

const gridCellCommands = updateBulkProperties('always', newPath, [
propertyToDelete(PP.create('style', 'position')),
propertyToDelete(PP.create('style', 'top')),
propertyToDelete(PP.create('style', 'left')),
propertyToDelete(PP.create('style', 'bottom')),
propertyToDelete(PP.create('style', 'right')),
])

return {
commands: [...reparentCommands, gridCellCommands],
newPath: newPath,
oldPath: target,
}
}
Loading
Loading