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

Tailwind Padding #6537

Closed
wants to merge 13 commits into from
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import * as EP from '../../../../core/shared/element-path'
import { assertNever } from '../../../../core/shared/utils'
import { TailwindConfigPath } from '../../../../core/tailwind/tailwind-config'
import { createModifiedProject } from '../../../../sample-projects/sample-project-utils.test-utils'
import type { Modifiers } from '../../../../utils/modifiers'
import { cmdModifier, shiftModifier } from '../../../../utils/modifiers'
import { expectSingleUndo2Saves, wait } from '../../../../utils/utils.test-utils'
import { cmdModifier } from '../../../../utils/modifiers'
import {
expectSingleUndo2Saves,
selectComponentsForTest,
setFeatureForBrowserTestsUseInDescribeBlockOnly,
wait,
} from '../../../../utils/utils.test-utils'
import { StoryboardFilePath } from '../../../editor/store/editor-state'
import { cssNumber } from '../../../inspector/common/css-utils'
import type { EdgePiece } from '../../canvas-types'
import { isHorizontalEdgePiece } from '../../canvas-types'
Expand Down Expand Up @@ -39,6 +48,7 @@ import {
getPrintedUiJsCode,
makeTestProjectCodeWithSnippet,
renderTestEditorWithCode,
renderTestEditorWithModel,
} from '../../ui-jsx.test-utils'
import { PaddingTearThreshold, SetPaddingStrategyName } from './set-padding-strategy'

Expand Down Expand Up @@ -745,6 +755,88 @@ describe('Padding resize strategy', () => {
})
})
})

describe('Tailwind', () => {
setFeatureForBrowserTestsUseInDescribeBlockOnly('Tailwind', true)

const TailwindProject = (classes: string) =>
createModifiedProject({
[StoryboardFilePath]: `
import React from 'react'
import { Scene, Storyboard } from 'utopia-api'
export var storyboard = (
<Storyboard data-uid='sb'>
<Scene
id='scene'
commentId='scene'
data-uid='scene'
style={{
width: 700,
height: 759,
position: 'absolute',
left: 212,
top: 128,
}}
>
<div
data-uid='mydiv'
data-testid='mydiv'
className='top-10 left-10 absolute flex flex-row ${classes}'
>
<div className='bg-red-500 w-10 h-10' data-uid='child-1' />
<div className='bg-red-500 w-10 h-10' data-uid='child-2' />
</div>
</Scene>
</Storyboard>
)

`,
[TailwindConfigPath]: `
const TailwindConfig = { }
export default TailwindConfig
`,
'app.css': `
@tailwind base;
@tailwind components;
@tailwind utilities;`,
})

it('can set tailwind padding', async () => {
const editor = await renderTestEditorWithModel(
TailwindProject('p-12'),
'await-first-dom-report',
)
await selectComponentsForTest(editor, [EP.fromString('sb/scene/mydiv')])
await testPaddingResizeForEdge(editor, 50, 'top', 'precise')
await editor.getDispatchFollowUpActionsFinished()
const div = editor.renderedDOM.getByTestId('mydiv')
expect(div.className).toEqual('top-10 left-10 absolute flex flex-row p-[6rem_3rem_3rem_3rem]')
})

it('can remove tailwind padding', async () => {
const editor = await renderTestEditorWithModel(
TailwindProject('p-4'),
'await-first-dom-report',
)
await selectComponentsForTest(editor, [EP.fromString('sb/scene/mydiv')])
await testPaddingResizeForEdge(editor, -150, 'top', 'precise')
await editor.getDispatchFollowUpActionsFinished()
const div = editor.renderedDOM.getByTestId('mydiv')
expect(div.className).toEqual('top-10 left-10 absolute flex flex-row pb-4 pl-4 pr-4')
})

it('can set tailwind padding longhand', async () => {
const editor = await renderTestEditorWithModel(
TailwindProject('pt-12'),
'await-first-dom-report',
)
await selectComponentsForTest(editor, [EP.fromString('sb/scene/mydiv')])
await testPaddingResizeForEdge(editor, 50, 'top', 'precise')
await editor.getDispatchFollowUpActionsFinished()
const div = editor.renderedDOM.getByTestId('mydiv')
expect(div.className).toEqual('top-10 left-10 absolute flex flex-row pt-24')
})
})
})

async function testAdjustIndividualPaddingValue(edge: EdgePiece, precision: AdjustPrecision) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { optionalMap } from '../../../../core/shared/optional-utils'
import type { ElementPath } from '../../../../core/shared/project-file-types'
import { assertNever } from '../../../../core/shared/utils'
import { stylePropPathMappingFn } from '../../../inspector/common/property-path-hooks'
import type { EdgePiece } from '../../canvas-types'
import type { EdgePiece, StyleInfo } from '../../canvas-types'
import { CSSCursor, isHorizontalEdgePiece, oppositeEdgePiece } from '../../canvas-types'
import { deleteProperties } from '../../commands/delete-properties-command'
import { setCursorCommand } from '../../commands/set-cursor-command'
Expand All @@ -32,7 +32,7 @@ import {
paddingPropForEdge,
paddingToPaddingString,
printCssNumberWithDefaultUnit,
simplePaddingFromMetadata,
simplePaddingFromStyleInfo,
} from '../../padding-utils'
import type { CanvasStrategyFactory } from '../canvas-strategies'
import { onlyFitWhenDraggingThisControl } from '../canvas-strategies'
Expand Down Expand Up @@ -118,6 +118,7 @@ export const setPaddingStrategy: CanvasStrategyFactory = (canvasState, interacti
canvasState.startingMetadata,
canvasState.startingElementPathTree,
selectedElements[0],
canvasState.styleInfoReader(selectedElements[0]),
)
) {
return null
Expand Down Expand Up @@ -184,7 +185,11 @@ export const setPaddingStrategy: CanvasStrategyFactory = (canvasState, interacti

const edgePiece = interactionSession.activeControl.edgePiece
const drag = interactionSession.interactionData.drag ?? canvasVector({ x: 0, y: 0 })
const padding = simplePaddingFromMetadata(canvasState.startingMetadata, selectedElement)
const padding = simplePaddingFromStyleInfo(
canvasState.startingMetadata,
selectedElement,
canvasState.styleInfoReader(selectedElement),
)
const paddingPropInteractedWith = paddingPropForEdge(edgePiece)
const currentPadding = padding[paddingPropInteractedWith]?.renderedValuePx ?? 0
const rawDelta = deltaFromEdge(drag, edgePiece)
Expand Down Expand Up @@ -351,6 +356,7 @@ function supportsPaddingControls(
metadata: ElementInstanceMetadataMap,
pathTrees: ElementPathTrees,
path: ElementPath,
styleInfo: StyleInfo | null,
): boolean {
const element = MetadataUtils.findElementByElementPath(metadata, path)
if (element == null) {
Expand All @@ -365,7 +371,7 @@ function supportsPaddingControls(
return false
}

const padding = simplePaddingFromMetadata(metadata, path)
const padding = simplePaddingFromStyleInfo(metadata, path, styleInfo)
const { top, right, bottom, left } = element.specialSizeMeasurements.padding
const elementHasNonzeroPaddingFromMeasurements = [top, right, bottom, left].some(
(s) => s != null && s > 0,
Expand Down Expand Up @@ -430,9 +436,10 @@ function paddingValueIndicatorProps(

const edgePiece = interactionSession.activeControl.edgePiece

const padding = simplePaddingFromMetadata(
const padding = simplePaddingFromStyleInfo(
canvasState.startingMetadata,
filteredSelectedElements[0],
canvasState.styleInfoReader(selectedElement),
)
const currentPadding =
padding[paddingPropForEdge(edgePiece)] ?? unitlessCSSNumberWithRenderedValue(0)
Expand Down Expand Up @@ -558,7 +565,11 @@ function calculateAdjustDelta(

const edgePiece = interactionSession.activeControl.edgePiece
const drag = interactionSession.interactionData.drag ?? canvasVector({ x: 0, y: 0 })
const padding = simplePaddingFromMetadata(canvasState.startingMetadata, selectedElement)
const padding = simplePaddingFromStyleInfo(
canvasState.startingMetadata,
selectedElement,
canvasState.styleInfoReader(selectedElement),
)
const paddingPropInteractedWith = paddingPropForEdge(edgePiece)
const currentPadding = padding[paddingPropForEdge(edgePiece)]?.renderedValuePx ?? 0
const rawDelta = deltaFromEdge(drag, edgePiece)
Expand Down
9 changes: 8 additions & 1 deletion editor/src/components/canvas/canvas-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import type {
import { InteractionSession } from './canvas-strategies/interaction-state'
import type { CanvasStrategyId } from './canvas-strategies/canvas-strategy-types'
import type { MouseButtonsPressed } from '../../utils/mouse'
import type { CSSNumber, FlexDirection } from '../inspector/common/css-utils'
import type { CSSNumber, CSSPadding, FlexDirection } from '../inspector/common/css-utils'

export const CanvasContainerID = 'canvas-container'

Expand Down Expand Up @@ -550,8 +550,15 @@ export const withPropertyTag = <T>(value: T): WithPropertyTag<T> => ({
export type FlexGapInfo = WithPropertyTag<CSSNumber>

export type FlexDirectionInfo = WithPropertyTag<FlexDirection>
export type PaddingInfo = WithPropertyTag<CSSPadding>
export type PaddingSideInfo = WithPropertyTag<CSSNumber>

export interface StyleInfo {
gap: FlexGapInfo | null
flexDirection: FlexDirectionInfo | null
padding: PaddingInfo | null
paddingTop: PaddingSideInfo | null
paddingRight: PaddingSideInfo | null
paddingBottom: PaddingSideInfo | null
paddingLeft: PaddingSideInfo | null
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {
paddingAdjustMode,
paddingFromSpecialSizeMeasurements,
PaddingIndictorOffset,
simplePaddingFromMetadata,
simplePaddingFromStyleInfo,
} from '../../padding-utils'
import { useBoundingBox } from '../bounding-box-hooks'
import { CanvasOffsetWrapper } from '../canvas-offset-wrapper'
Expand All @@ -43,6 +43,7 @@ import type { CSSNumberWithRenderedValue } from './controls-common'
import { CanvasLabel, fallbackEmptyValue, PillHandle, useHoverWithDelay } from './controls-common'
import { MetadataUtils } from '../../../../core/model/element-metadata-utils'
import { mapDropNulls } from '../../../../core/shared/array-utils'
import { getActivePlugin } from '../../plugins/style-plugins'

export const paddingControlTestId = (edge: EdgePiece): string => `padding-control-${edge}`
export const paddingControlHandleTestId = (edge: EdgePiece): string =>
Expand Down Expand Up @@ -358,12 +359,24 @@ export const PaddingResizeControl = controlForStrategyMemoized((props: PaddingCo
}
}, [hoveredViews, selectedElements])

const currentPadding = React.useMemo(() => {
return combinePaddings(
paddingFromSpecialSizeMeasurements(elementMetadata, selectedElements[0]),
simplePaddingFromMetadata(elementMetadata, selectedElements[0]),
)
}, [elementMetadata, selectedElements])
const currentPadding = useEditorState(
Substores.fullStore,
(store) => {
return combinePaddings(
paddingFromSpecialSizeMeasurements(store.editor.jsxMetadata, selectedElements[0]),
simplePaddingFromStyleInfo(
elementMetadata,
selectedElements[0],
getActivePlugin(store.editor).styleInfoFactory({
metadata: store.editor.jsxMetadata,
projectContents: store.editor.projectContents,
elementPathTree: store.editor.elementPathTree,
})(selectedElements[0]),
),
)
},
'PaddingResizeControl currentPadding',
)

const shownByParent = selectedElementHovered || anyControlHovered

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import React from 'react'
import { useColorTheme } from '../../../../uuiui'
import { Substores, useEditorState, useRefEditorState } from '../../../editor/store/store-hook'
import type { EdgePiece } from '../../canvas-types'
import { paddingPropForEdge, simplePaddingFromMetadata } from '../../padding-utils'
import { paddingPropForEdge, simplePaddingFromStyleInfo } from '../../padding-utils'
import { useBoundingBox } from '../bounding-box-hooks'
import { CanvasOffsetWrapper } from '../canvas-offset-wrapper'
import { getActivePlugin } from '../../plugins/style-plugins'

export interface SubduedPaddingControlProps {
side: EdgePiece
Expand All @@ -25,9 +26,21 @@ export const SubduedPaddingControl = React.memo<SubduedPaddingControlProps>((pro
const isVerticalPadding = !isHorizontalPadding
const paddingKey = paddingPropForEdge(side)

const styleInfoRef = useRefEditorState((store) =>
getActivePlugin(store.editor).styleInfoFactory({
metadata: store.editor.jsxMetadata,
projectContents: store.editor.projectContents,
elementPathTree: store.editor.elementPathTree,
})(targets[0]),
)

// TODO Multiselect
const sideRef = useBoundingBox(targets, (ref, boundingBox) => {
const padding = simplePaddingFromMetadata(elementMetadata.current, targets[0])
const padding = simplePaddingFromStyleInfo(
elementMetadata.current,
targets[0],
styleInfoRef.current,
)
const paddingValue = padding[paddingKey]?.renderedValuePx ?? 0

const { x, y, width, height } = boundingBox
Expand Down
46 changes: 12 additions & 34 deletions editor/src/components/canvas/padding-utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { styleStringInArray } from '../../utils/common-constants'
import { getLayoutProperty } from '../../core/layout/getLayoutProperty'
import { MetadataUtils } from '../../core/model/element-metadata-utils'
import { defaultEither, isLeft, right } from '../../core/shared/either'
import type { ElementInstanceMetadataMap } from '../../core/shared/element-template'
import type {
ElementInstanceMetadata,
ElementInstanceMetadataMap,
} from '../../core/shared/element-template'
import { isJSXElement } from '../../core/shared/element-template'
import type { CanvasVector, Size } from '../../core/shared/math-utils'
import { numberIsZero, roundTo, zeroRectIfNullOrInfinity } from '../../core/shared/math-utils'
Expand All @@ -11,7 +14,7 @@ import type { ElementPath } from '../../core/shared/project-file-types'
import { assertNever } from '../../core/shared/utils'
import type { CSSNumber, CSSNumberUnit, CSSPadding } from '../inspector/common/css-utils'
import { printCSSNumber } from '../inspector/common/css-utils'
import type { EdgePiece } from './canvas-types'
import type { EdgePiece, StyleInfo } from './canvas-types'
import type {
AdjustPrecision,
CSSNumberWithRenderedValue,
Expand Down Expand Up @@ -58,52 +61,27 @@ export function paddingFromSpecialSizeMeasurements(
return paddingMappedMeasurements
}

export function simplePaddingFromMetadata(
export function simplePaddingFromStyleInfo(
metadata: ElementInstanceMetadataMap,
elementPath: ElementPath,
styleInfo: StyleInfo | null,
): CSSPaddingMappedValues<CSSNumberWithRenderedValue | undefined> {
const element = MetadataUtils.findElementByElementPath(metadata, elementPath)

const defaults: CSSPaddingMappedValues<CSSNumber | undefined> = {
paddingTop: undefined,
paddingRight: undefined,
paddingBottom: undefined,
paddingLeft: undefined,
}

if (element == null || isLeft(element.element) || !isJSXElement(element.element.value)) {
return {
paddingTop: undefined,
paddingRight: undefined,
paddingBottom: undefined,
paddingLeft: undefined,
}
}

const paddingNumbers = paddingFromSpecialSizeMeasurements(metadata, elementPath)

const padding: CSSPadding | undefined = defaultEither(
undefined,
getLayoutProperty('padding', right(element.element.value.props), styleStringInArray),
)
const padding: CSSPadding | undefined = styleInfo?.padding?.value

const paddingLonghands: CSSPaddingMappedValues<CSSNumber | undefined> = {
paddingTop: defaultEither(
undefined,
getLayoutProperty('paddingTop', right(element.element.value.props), styleStringInArray),
),
paddingBottom: defaultEither(
undefined,
getLayoutProperty('paddingBottom', right(element.element.value.props), styleStringInArray),
),
paddingLeft: defaultEither(
undefined,
getLayoutProperty('paddingLeft', right(element.element.value.props), styleStringInArray),
),
paddingRight: defaultEither(
undefined,
getLayoutProperty('paddingRight', right(element.element.value.props), styleStringInArray),
),
paddingTop: styleInfo?.paddingTop?.value,
paddingBottom: styleInfo?.paddingBottom?.value,
paddingLeft: styleInfo?.paddingLeft?.value,
paddingRight: styleInfo?.paddingRight?.value,
}

const make = (prop: CSSPaddingKey): CSSNumberWithRenderedValue | undefined => {
Expand Down
Loading
Loading