Skip to content

Commit

Permalink
refactor(strategies) Mandatory Elements To Rerender For Strategies (#…
Browse files Browse the repository at this point in the history
…6408)

- Added `combineElementsToRerender` utility function.
- Added `appendElementsToRerenderToApplyResult` utility function.
- Added `StrategyApplicationResult.elementsToRerender`.
- Removed `setElementsToRerenderCommand` and
`appendElementsToRerenderCommand` and the associated supporting code.
- Moved values originally passed to `setElementsToRerenderCommand` to
the new parameter that `strategyApplicationResult` now has.
- Moved values originally passed to `appendElementsToRerenderCommand` to
a call to `appendElementsToRerenderToApplyResult`.
- Added `applyElementsToRerenderFromStrategyResult` utility function.
- Hooked in the `applyElementsToRerenderFromStrategyResult` function
  into various strategy functions to update the `EditorState`.
  • Loading branch information
seanparsons authored Sep 30, 2024
1 parent 3cf3883 commit ef8c8ed
Show file tree
Hide file tree
Showing 48 changed files with 557 additions and 468 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,19 @@ export function applyCanvasStrategy(
return strategy.apply(strategyLifecycle)
}

export function applyElementsToRerenderFromStrategyResult(
editorState: EditorState,
strategyResult: StrategyApplicationResult,
): EditorState {
return {
...editorState,
canvas: {
...editorState.canvas,
elementsToRerender: strategyResult.elementsToRerender,
},
}
}

export function useDelayedEditorState<T>(
selector: StateSelector<EditorStorePatched, T | null>,
selectorName: string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { ElementPath, NodeModules } from '../../../core/shared/project-file
import type { ProjectContentTreeRoot } from '../../assets'
import type { PropertyControlsInfo } from '../../custom-code/code-file'
import type { InsertionSubject } from '../../editor/editor-modes'
import type { AllElementProps } from '../../editor/store/editor-state'
import type { AllElementProps, ElementsToRerender } from '../../editor/store/editor-state'
import type { CanvasCommand } from '../commands/commands'
import type { ActiveFrameAction } from '../commands/set-active-frames-command'
import type { StrategyApplicationStatus } from './interaction-state'
Expand Down Expand Up @@ -53,23 +53,27 @@ export function defaultCustomStrategyState(): CustomStrategyState {

export interface StrategyApplicationResult {
commands: Array<CanvasCommand>
elementsToRerender: ElementsToRerender
customStatePatch: CustomStrategyStatePatch
status: StrategyApplicationStatus
}

export const emptyStrategyApplicationResult: StrategyApplicationResult = {
commands: [],
elementsToRerender: 'rerender-all-elements',
customStatePatch: {},
status: 'success',
}

export function strategyApplicationResult(
commands: Array<CanvasCommand>,
elementsToRerender: ElementsToRerender,
customStatePatch: CustomStrategyStatePatch = {},
status: StrategyApplicationStatus = 'success',
): StrategyApplicationResult {
return {
commands: commands,
elementsToRerender: elementsToRerender,
customStatePatch: customStatePatch,
status: status,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type { CanvasCommand } from '../../commands/commands'
import { foldAndApplyCommandsInner } from '../../commands/commands'
import { duplicateElement } from '../../commands/duplicate-element-command'
import { setCursorCommand } from '../../commands/set-cursor-command'
import { setElementsToRerenderCommand } from '../../commands/set-elements-to-rerender-command'

import { updateFunctionCommand } from '../../commands/update-function-command'
import { updateSelectedViews } from '../../commands/update-selected-views-command'
import { ImmediateParentBounds } from '../../controls/parent-bounds'
Expand Down Expand Up @@ -127,7 +127,6 @@ export function absoluteDuplicateStrategy(
[
...duplicateCommands,
...maybeAddContainLayoutCommand(commonParentPath),
setElementsToRerenderCommand([commonParentPath, ...selectedElements, ...newPaths]),
updateSelectedViews('always', selectedElements),
updateFunctionCommand('always', (editorState, commandLifecycle) =>
runMoveStrategy(
Expand All @@ -140,13 +139,14 @@ export function absoluteDuplicateStrategy(
),
setCursorCommand(CSSCursor.Duplicate),
],
[commonParentPath, ...selectedElements, ...newPaths],
{
duplicatedElementNewUids: duplicatedElementNewUids,
},
)
} else {
// Fallback for when the checks above are not satisfied.
return strategyApplicationResult([setCursorCommand(CSSCursor.Duplicate)])
return strategyApplicationResult([setCursorCommand(CSSCursor.Duplicate)], [])
}
},
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,11 @@ function reparentElement(
expect(strategyResult.customStatePatch).toEqual({})
expect(strategyResult.status).toEqual('success')

// Check if there are set SetElementsToRerenderCommands with the new parent path
expect(
strategyResult.commands.find(
(c) =>
c.type === 'SET_ELEMENTS_TO_RERENDER_COMMAND' &&
c.value !== 'rerender-all-elements' &&
c.value.every((p) => EP.pathsEqual(EP.parentPath(p), newParent)),
),
).not.toBeNull()
strategyResult.elementsToRerender === 'rerender-all-elements'
? []
: strategyResult.elementsToRerender.map(EP.parentPath),
).toEqual([newParent])

const finalEditor = foldAndApplyCommands(
editorState,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,15 +222,11 @@ function reparentElement(
expect(strategyResult.customStatePatch).toEqual({})
expect(strategyResult.status).toEqual('success')

// Check if there are set SetElementsToRerenderCommands with the new parent path
expect(
strategyResult.commands.find(
(c) =>
c.type === 'SET_ELEMENTS_TO_RERENDER_COMMAND' &&
c.value !== 'rerender-all-elements' &&
c.value.every((p) => EP.pathsEqual(EP.parentPath(p), newParent)),
),
).not.toBeNull()
strategyResult.elementsToRerender === 'rerender-all-elements'
? []
: strategyResult.elementsToRerender.map(EP.parentPath),
).toEqual([newParent])

return foldAndApplyCommands(
editorState,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { InsertionPath } from '../../../editor/store/insertion-path'
import { CSSCursor } from '../../canvas-types'
import type { CanvasCommand } from '../../commands/commands'
import { setCursorCommand } from '../../commands/set-cursor-command'
import { setElementsToRerenderCommand } from '../../commands/set-elements-to-rerender-command'

import { setProperty } from '../../commands/set-property-command'
import { updateSelectedViews } from '../../commands/update-selected-views-command'
import { ParentBounds } from '../../controls/parent-bounds'
Expand Down Expand Up @@ -217,7 +217,6 @@ export function applyAbsoluteReparent(
...moveCommands,
...commands.flatMap((c) => c.commands),
updateSelectedViews('always', newPaths),
setElementsToRerenderCommand(elementsToRerender),
...maybeAddContainLayout(
canvasState.startingMetadata,
canvasState.startingAllElementProps,
Expand All @@ -226,6 +225,7 @@ export function applyAbsoluteReparent(
),
setCursorCommand(CSSCursor.Reparent),
],
elementsToRerender,
{
elementsToRerender,
},
Expand All @@ -236,7 +236,7 @@ export function applyAbsoluteReparent(
...defaultCustomStrategyState(),
action: 'reparent',
})?.strategy.apply(strategyLifecycle).commands ?? []
return strategyApplicationResult(moveCommands)
return strategyApplicationResult(moveCommands, 'rerender-all-elements')
}
},
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { pushIntendedBoundsAndUpdateGroups } from '../../commands/push-intended-
import { queueTrueUpElement } from '../../commands/queue-true-up-command'
import { activeFrameTargetRect, setActiveFrames } from '../../commands/set-active-frames-command'
import { setCursorCommand } from '../../commands/set-cursor-command'
import { setElementsToRerenderCommand } from '../../commands/set-elements-to-rerender-command'

import { setSnappingGuidelines } from '../../commands/set-snapping-guidelines-command'
import { updateHighlightedViews } from '../../commands/update-highlighted-views-command'
import { gatherParentAndSiblingTargets } from '../../controls/guideline-helpers'
Expand Down Expand Up @@ -141,7 +141,7 @@ export function absoluteResizeBoundingBoxStrategy(
}),
],
fitness: onlyFitWhenDraggingThisControl(interactionSession, 'RESIZE_HANDLE', 1),
apply: () => {
apply: (lifecycle) => {
if (
interactionSession != null &&
interactionSession.interactionData.type === 'DRAG' &&
Expand Down Expand Up @@ -289,19 +289,24 @@ export function absoluteResizeBoundingBoxStrategy(
]
})

return strategyApplicationResult([
...commandsForSelectedElements,
setSnappingGuidelines('mid-interaction', guidelinesWithSnappingVector),
updateHighlightedViews('mid-interaction', []),
setCursorCommand(pickCursorFromEdgePosition(edgePosition)),
setElementsToRerenderCommand(retargetedTargets),
])
return strategyApplicationResult(
[
...commandsForSelectedElements,
setSnappingGuidelines('mid-interaction', guidelinesWithSnappingVector),
updateHighlightedViews('mid-interaction', []),
setCursorCommand(pickCursorFromEdgePosition(edgePosition)),
],
lifecycle === 'mid-interaction' ? retargetedTargets : 'rerender-all-elements',
)
}
} else {
return strategyApplicationResult([
setCursorCommand(pickCursorFromEdgePosition(edgePosition)),
updateHighlightedViews('mid-interaction', []),
])
return strategyApplicationResult(
[
setCursorCommand(pickCursorFromEdgePosition(edgePosition)),
updateHighlightedViews('mid-interaction', []),
],
[],
)
}
}
// Fallback for when the checks above are not satisfied.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import {
combineElementsToRerender,
type ElementsToRerender,
} from '../../../../components/editor/store/editor-state'
import {
getSimpleAttributeAtPath,
MetadataUtils,
Expand All @@ -9,20 +13,20 @@ import { CSSCursor } from '../../canvas-types'
import type { CanvasCommand } from '../../commands/commands'
import { highlightElementsCommand } from '../../commands/highlight-element-command'
import { setCursorCommand } from '../../commands/set-cursor-command'
import { appendElementsToRerenderCommand } from '../../commands/set-elements-to-rerender-command'
import { wildcardPatch } from '../../commands/wildcard-patch-command'
import { onlyFitWhenThisControlIsActive, type MetaCanvasStrategy } from '../canvas-strategies'
import type {
CanvasStrategy,
InteractionCanvasState,
InteractionLifecycle,
StrategyApplicationResult,
} from '../canvas-strategy-types'
import { getTargetPathsFromInteractionTarget, targetPaths } from '../canvas-strategy-types'
import { DoNothingStrategyID } from './drag-to-move-metastrategy'
import {
retargetStrategyToChildrenOfFragmentLikeElements,
treatElementAsFragmentLike,
} from './fragment-like-helpers'
import { retargetStrategyToChildrenOfFragmentLikeElements } from './fragment-like-helpers'
import type { Optic } from '../../../../core/shared/optics/optics'
import { filtered, fromField } from '../../../../core/shared/optics/optic-creators'
import { modify } from '../../../../core/shared/optics/optic-utilities'

const ANCESTOR_INCOMPATIBLE_STRATEGIES = [DoNothingStrategyID]

Expand Down Expand Up @@ -125,11 +129,7 @@ export function ancestorMetaStrategy(
return nextAncestorResult.map((s) => ({
...s,
fitness: fitness(s),
apply: appendCommandsToApplyResult(
s.apply,
[appendElementsToRerenderCommand([target])],
[],
),
apply: appendElementsToRerenderToApplyResult(s.apply, [target]),
}))
} else {
// Otherwise we should stop at this ancestor and return the strategies for this ancestor
Expand All @@ -150,22 +150,21 @@ export function ancestorMetaStrategy(
id: `${s.id}_ANCESTOR_${level}`,
name: applyLevelSuffix(s.name, level),
fitness: fitness(s),
apply: appendCommandsToApplyResult(
s.apply,
[
appendElementsToRerenderCommand([target]),
highlightElementsCommand([parentPath]),
setCursorCommand(CSSCursor.MovingMagic),
],
[
wildcardPatch('mid-interaction', {
canvas: {
controls: {
dragToMoveIndicatorFlags: { ancestor: { $set: true } },
apply: appendElementsToRerenderToApplyResult(
appendCommandsToApplyResult(
s.apply,
[highlightElementsCommand([parentPath]), setCursorCommand(CSSCursor.MovingMagic)],
[
wildcardPatch('mid-interaction', {
canvas: {
controls: {
dragToMoveIndicatorFlags: { ancestor: { $set: true } },
},
},
},
}),
],
}),
],
),
[target],
),
}
}),
Expand All @@ -175,6 +174,7 @@ export function ancestorMetaStrategy(
}

type ApplyFn = CanvasStrategy['apply']

export function appendCommandsToApplyResult(
applyFn: ApplyFn,
commandsToAppendToExtendResult: Array<CanvasCommand>,
Expand Down Expand Up @@ -204,6 +204,27 @@ export function appendCommandsToApplyResult(
}
}

const strategyResultElementsToRerenderOptic: Optic<StrategyApplicationResult, ElementsToRerender> =
filtered<StrategyApplicationResult>((result) => result.status === 'success').compose(
fromField('elementsToRerender'),
)

export function appendElementsToRerenderToApplyResult(
applyFn: ApplyFn,
additionalElementsToRerender: ElementsToRerender,
): ApplyFn {
return (strategyLifecycle: InteractionLifecycle) => {
const result = applyFn(strategyLifecycle)
return modify(
strategyResultElementsToRerenderOptic,
(toRerender) => {
return combineElementsToRerender(toRerender, additionalElementsToRerender)
},
result,
)
}
}

function applyLevelSuffix(name: string, level: number): string {
// FIXME What should we use for the label here?
const newSuffix = `(Up ${level})`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
import { pushIntendedBoundsAndUpdateGroups } from '../../commands/push-intended-bounds-and-update-groups-command'
import { queueTrueUpElement } from '../../commands/queue-true-up-command'
import { setCursorCommand } from '../../commands/set-cursor-command'
import { setElementsToRerenderCommand } from '../../commands/set-elements-to-rerender-command'

import { updateHighlightedViews } from '../../commands/update-highlighted-views-command'
import { controlsForGridPlaceholders } from '../../controls/grid-controls'
import { ImmediateParentBounds } from '../../controls/parent-bounds'
Expand Down Expand Up @@ -219,24 +219,29 @@ export function basicResizeStrategy(

const elementsToRerender = [...selectedElements, ...gridsToRerender]

return strategyApplicationResult([
adjustCssLengthProperties('always', selectedElement, null, resizeProperties),
updateHighlightedViews('mid-interaction', []),
setCursorCommand(pickCursorFromEdgePosition(edgePosition)),
setElementsToRerenderCommand(elementsToRerender),
pushIntendedBoundsAndUpdateGroups(
[{ target: selectedElement, frame: resizedBounds }],
'starting-metadata',
),
...groupChildren.map((c) =>
queueTrueUpElement([trueUpGroupElementChanged(c.elementPath)]),
),
])
return strategyApplicationResult(
[
adjustCssLengthProperties('always', selectedElement, null, resizeProperties),
updateHighlightedViews('mid-interaction', []),
setCursorCommand(pickCursorFromEdgePosition(edgePosition)),
pushIntendedBoundsAndUpdateGroups(
[{ target: selectedElement, frame: resizedBounds }],
'starting-metadata',
),
...groupChildren.map((c) =>
queueTrueUpElement([trueUpGroupElementChanged(c.elementPath)]),
),
],
elementsToRerender,
)
} else {
return strategyApplicationResult([
updateHighlightedViews('mid-interaction', []),
setCursorCommand(pickCursorFromEdgePosition(edgePosition)),
])
return strategyApplicationResult(
[
updateHighlightedViews('mid-interaction', []),
setCursorCommand(pickCursorFromEdgePosition(edgePosition)),
],
[],
)
}
}
// Fallback for when the checks above are not satisfied.
Expand Down
Loading

0 comments on commit ef8c8ed

Please sign in to comment.