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

Grids: presetve repeat from inspector changes #6388

Merged
merged 4 commits into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -29,7 +29,13 @@ import {
} from '../../../../core/shared/math-utils'
import * as PP from '../../../../core/shared/property-path'
import { absolute } from '../../../../utils/utils'
import { cssNumber, isCSSKeyword } from '../../../inspector/common/css-utils'
import type { GridDimension } from '../../../inspector/common/css-utils'
import {
cssNumber,
gridCSSRepeat,
isCSSKeyword,
isGridCSSRepeat,
} from '../../../inspector/common/css-utils'
import type { CanvasCommand } from '../../commands/commands'
import { deleteProperties } from '../../commands/delete-properties-command'
import { reorderElement } from '../../commands/reorder-element-command'
Expand All @@ -45,6 +51,8 @@ import {
gridCellCoordinates,
} from './grid-cell-bounds'
import { memoize } from '../../../../core/shared/memoize'
import { mapDropNulls } from '../../../../core/shared/array-utils'
import { assertNever } from '../../../../core/shared/utils'

export function runGridRearrangeMove(
targetElement: ElementPath,
Expand Down Expand Up @@ -647,3 +655,125 @@ function gridTemplateToNumbers(gridTemplate: GridTemplate | null): Array<number>

return result
}

type DimensionIndexes = {
originalIndex: number // the index of this element in the original values
repeatedIndex: number // the index of this element, if it's generated via a repeat, inside the repeated values array definition
}

export type ExpandedGridDimension = GridDimension & {
indexes: DimensionIndexes
}

function expandedGridDimension(
dim: GridDimension,
originalIndex: number,
repeatedIndex: number = 0,
): ExpandedGridDimension {
return {
...dim,
indexes: {
originalIndex: originalIndex,
repeatedIndex: repeatedIndex,
},
}
}

export function expandGridDimensions(template: GridDimension[]): ExpandedGridDimension[] {
// Expanded representation of the original values, where repeated elements are serialized.
// Each element also contains the indexes information to be used later on to build the resized
// template string.
return template.reduce((acc, cur, index) => {
if (isGridCSSRepeat(cur)) {
const repeatGroup = cur.value.map((dim, repeatedIndex) =>
expandedGridDimension(dim, index, repeatedIndex),
)
let expanded: ExpandedGridDimension[] = []
for (let i = 0; i < cur.times; i++) {
expanded.push(...repeatGroup)
}
return [...acc, ...expanded]
} else {
return [...acc, expandedGridDimension(cur, index)]
}
}, [] as ExpandedGridDimension[])
}

function alterGridDimensions(params: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function does not generally alters the grid dimensions, but it alters the repeats, I would express this in the name

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it does alter them, you can replace or remove any dimension, not just repeats.

originalValues: GridDimension[]
target: ExpandedGridDimension
action: AlterGridTemplateDimensionAction
}): GridDimension[] {
return mapDropNulls((dim, index) => {
if (index !== params.target.indexes.originalIndex) {
return dim
} else if (isGridCSSRepeat(dim)) {
const repeatedIndex = params.target.indexes.repeatedIndex ?? 0
const before = dim.value.slice(0, repeatedIndex)
const after = dim.value.slice(repeatedIndex + 1)
switch (params.action.type) {
case 'REMOVE':
if (before.length + after.length === 0) {
return null
}
return gridCSSRepeat(dim.times, [...before, ...after])
case 'REPLACE':
return gridCSSRepeat(dim.times, [...before, params.action.newValue, ...after])
default:
assertNever(params.action)
}
} else {
switch (params.action.type) {
case 'REPLACE':
return params.action.newValue
case 'REMOVE':
return null
default:
assertNever(params.action)
}
}
}, params.originalValues)
}

export type ReplaceGridDimensionAction = {
type: 'REPLACE'
newValue: GridDimension
}

export type RemoveGridDimensionAction = {
type: 'REMOVE'
}

export type AlterGridTemplateDimensionAction =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really like the Action terminology, we use that for our dispatchable actions, someone would easily think these actions are EditorActions too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah good point

| ReplaceGridDimensionAction
| RemoveGridDimensionAction

export function replaceGridTemplateDimensionAtIndex(
template: GridDimension[],
expanded: ExpandedGridDimension[],
index: number,
newValue: GridDimension,
): GridDimension[] {
return alterGridDimensions({
originalValues: template,
target: expanded[index],
action: {
type: 'REPLACE',
newValue: newValue,
},
})
}

export function removeGridTemplateDimensionAtIndex(
template: GridDimension[],
expanded: ExpandedGridDimension[],
index: number,
): GridDimension[] {
return alterGridDimensions({
originalValues: template,
target: expanded[index],
action: {
type: 'REMOVE',
},
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ import type { GridDimension } from '../../../../components/inspector/common/css-
import {
cssNumber,
gridCSSNumber,
gridCSSRepeat,
isGridCSSNumber,
isGridCSSRepeat,
printArrayGridDimensions,
} from '../../../../components/inspector/common/css-utils'
import { toFirst } from '../../../../core/shared/optics/optic-utilities'
Expand All @@ -36,6 +34,7 @@ import type { Either } from '../../../../core/shared/either'
import { foldEither, isLeft, isRight } from '../../../../core/shared/either'
import { roundToNearestWhole } from '../../../../core/shared/math-utils'
import type { GridAutoOrTemplateBase } from '../../../../core/shared/element-template'
import { expandGridDimensions, replaceGridTemplateDimensionAtIndex } from './grid-helpers'

export const resizeGridStrategy: CanvasStrategyFactory = (
canvasState: InteractionCanvasState,
Expand Down Expand Up @@ -116,24 +115,7 @@ export const resizeGridStrategy: CanvasStrategyFactory = (
return emptyStrategyApplicationResult
}

// Expanded representation of the original values, where repeated elements are serialized.
// Each element also contains the indexes information to be used later on to build the resized
// template string.
const expandedOriginalValues = originalValues.dimensions.reduce((acc, cur, index) => {
if (isGridCSSRepeat(cur)) {
const repeatGroup = cur.value.map((dim, repeatedIndex) =>
expandedGridDimension(dim, index, repeatedIndex),
)
let expanded: ExpandedGridDimension[] = []
for (let i = 0; i < cur.times; i++) {
expanded.push(...repeatGroup)
}
return [...acc, ...expanded]
} else {
return [...acc, expandedGridDimension(cur, index)]
}
}, [] as ExpandedGridDimension[])

const expandedOriginalValues = expandGridDimensions(originalValues.dimensions)
const mergedValues: GridAutoOrTemplateBase = {
type: calculatedValues.type,
dimensions: calculatedValues.dimensions.map((dim, index) => {
Expand Down Expand Up @@ -181,11 +163,12 @@ export const resizeGridStrategy: CanvasStrategyFactory = (
areaName,
)

const newDimensions = buildResizedDimensions({
newValue: newValue,
originalValues: originalValues.dimensions,
target: expandedOriginalValues[control.columnOrRow],
})
const newDimensions = replaceGridTemplateDimensionAtIndex(
originalValues.dimensions,
expandedOriginalValues,
control.columnOrRow,
newValue,
)

const propertyValueAsString = printArrayGridDimensions(newDimensions)

Expand All @@ -207,51 +190,6 @@ export const resizeGridStrategy: CanvasStrategyFactory = (
}
}

type DimensionIndexes = {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all this stuff now lives in grid-hepers.ts

originalIndex: number // the index of this element in the original values
repeatedIndex: number // the index of this element, if it's generated via a repeat, inside the repeated values array definition
}

function expandedGridDimension(
dim: GridDimension,
originalIndex: number,
repeatedIndex: number = 0,
): ExpandedGridDimension {
return {
...dim,
indexes: {
originalIndex: originalIndex,
repeatedIndex: repeatedIndex,
},
}
}

type ExpandedGridDimension = GridDimension & {
indexes: DimensionIndexes
}

function buildResizedDimensions(params: {
newValue: GridDimension
originalValues: GridDimension[]
target: ExpandedGridDimension
}) {
return params.originalValues.map((dim, index) => {
if (index !== params.target.indexes.originalIndex) {
return dim
} else if (isGridCSSRepeat(dim)) {
const repeatedIndex = params.target.indexes.repeatedIndex ?? 0
const repeatGroup = [
...dim.value.slice(0, repeatedIndex),
params.newValue,
...dim.value.slice(repeatedIndex + 1),
]
return gridCSSRepeat(dim.times, repeatGroup)
} else {
return params.newValue
}
})
}

function getNewDragValue(
dragAmount: number,
isFractional: boolean,
Expand Down
12 changes: 8 additions & 4 deletions editor/src/components/inspector/common/css-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -823,14 +823,18 @@ export function printCSSNumber(

export function printGridDimension(dimension: GridDimension): string {
switch (dimension.type) {
case 'KEYWORD':
return dimension.value.value
case 'NUMBER':
case 'KEYWORD': {
const areaName = dimension.areaName != null ? `[${dimension.areaName}] ` : ''
return `${areaName}${dimension.value.value}`
}
case 'NUMBER': {
const printed = printCSSNumber(dimension.value, null)
const areaName = dimension.areaName != null ? `[${dimension.areaName}] ` : ''
return `${areaName}${printed}`
case 'REPEAT':
}
case 'REPEAT': {
return `repeat(${dimension.times}, ${printArrayGridDimensions(dimension.value)})`
}
default:
assertNever(dimension)
}
Expand Down
75 changes: 74 additions & 1 deletion editor/src/components/inspector/flex-section.spec.browser2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,24 @@ describe('flex section', () => {
)
await selectComponentsForTest(renderResult, [EP.fromString('sb/grid')])
const control = await screen.findByTestId('grid-dimension-column-0')
await typeIntoField(control, '100')
await typeIntoField(control, '100px')
const grid = await renderResult.renderedDOM.findByTestId('grid')
expect(grid.style.gridTemplateColumns).toEqual('100px auto auto')
})
it('updates a repeated value', async () => {
const renderResult = await renderTestEditorWithCode(
gridProjectWithRepeat,
'await-first-dom-report',
)
await selectComponentsForTest(renderResult, [EP.fromString('sb/grid')])
await typeIntoField(await screen.findByTestId('grid-dimension-column-2'), '42')

const grid = await renderResult.renderedDOM.findByTestId('grid')
expect(grid.style.gridTemplateColumns).toEqual('[area1] 1fr repeat(2, 10px 42px) 2fr')

await typeIntoField(await screen.findByTestId('grid-dimension-column-1'), '.5fr')
expect(grid.style.gridTemplateColumns).toEqual('[area1] 1fr repeat(2, 0.5fr 42px) 2fr')
})
})
})

Expand Down Expand Up @@ -190,3 +204,62 @@ export var storyboard = (
</Storyboard>
)
`

const gridProjectWithRepeat = `
import * as React from 'react'
import { Storyboard } from 'utopia-api'

export var storyboard = (
<Storyboard data-uid='sb'>
<div
data-uid='grid'
data-testid='grid'
style={{
display: 'grid',
gridTemplateRows: '80px 1fr 1fr',
gridTemplateColumns: '[area1] 1fr repeat(2, 10px 30px) 2fr',
gridGap: 10,
height: 322,
width: 364,
backgroundColor: '#FFFFFF',
padding: 20,
}}
>
<div
data-uid='foo'
data-testid='foo'
style={{
backgroundColor: '#aaaaaa33',
gridColumn: 3,
gridRow: 2,
}}
/>
<div
data-uid='bar'
data-testid='bar'
style={{
width: 41,
height: 23,
border: '1px solid #000',
gridColumn: 'area1',
gridRow: 1,
backgroundColor: '#09f',
}}
/>
<div
data-uid='baz'
data-testid='baz'
style={{
height: 53,
width: 'max-content',
gridColumn: 2,
gridRow: 2,
backgroundColor: '#0f9',
}}
>
a test
</div>
</div>
</Storyboard>
)
`
Loading
Loading