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

feat: Improved UX for adding multiple advanced style panel properties #4846

Merged
merged 19 commits into from
Feb 9, 2025
Merged
Show file tree
Hide file tree
Changes from 12 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
@@ -1,11 +1,12 @@
import { lexer } from "css-tree";
import { colord } from "colord";
import {
forwardRef,
memo,
useEffect,
useMemo,
useRef,
useState,
type ComponentProps,
type ReactNode,
} from "react";
import { useStore } from "@nanostores/react";
Expand All @@ -28,6 +29,7 @@ import {
SectionTitle,
SectionTitleButton,
SectionTitleLabel,
Separator,
Text,
theme,
Tooltip,
Expand Down Expand Up @@ -73,6 +75,7 @@ import {
import { useClientSupports } from "~/shared/client-supports";
import { $selectedInstancePath } from "~/shared/awareness";
import { $settings } from "~/builder/shared/client-settings";
import { composeEventHandlers } from "~/shared/event-utils";

// Only here to keep the same section module interface
export const properties = [];
Expand All @@ -91,6 +94,7 @@ const AdvancedStyleSection = (props: {
label={label}
isOpen={isOpen}
onOpenChange={setIsOpen}
fullWidth
trigger={
<SectionTitle
dots={getDots(styles)}
Expand Down Expand Up @@ -147,16 +151,23 @@ const getNewPropertyDescription = (item: null | SearchItem) => {
const insertStyles = (text: string) => {
const parsedStyles = parseCss(`selector{${text}}`);
if (parsedStyles.length === 0) {
return false;
return [];
}
const batch = createBatchUpdate();
for (const { property, value } of parsedStyles) {
batch.setProperty(property)(value);
}
batch.publish({ listed: true });
return true;
return parsedStyles;
};

const sortedProperties = Object.keys(propertiesData)
.sort(Intl.Collator().compare)
.map((property) => ({
value: property,
label: hyphenateProperty(property),
}));

/**
*
* Advanced search control supports following interactions
Expand All @@ -167,37 +178,21 @@ const insertStyles = (text: string) => {
* paste css declarations
*
*/
const AdvancedSearch = ({
usedProperties,
onSelect,
onClose,
}: {
usedProperties: string[];
onSelect: (value: StyleProperty) => void;
onClose: () => void;
}) => {
const availableProperties = useMemo(() => {
const properties = Object.keys(propertiesData).sort(
Intl.Collator().compare
) as StyleProperty[];
const availableProperties: SearchItem[] = [];
for (const property of properties) {
if (usedProperties.includes(property) === false) {
availableProperties.push({
value: property,
label: hyphenateProperty(property),
});
}
}
return availableProperties;
}, [usedProperties]);
const AddProperty = forwardRef<
HTMLInputElement,
{
onSelect: (value: StyleProperty) => void;
onClose: () => void;
onSubmit: (value: string) => void;
}
>(({ onSelect, onClose, onSubmit }, forwardedRef) => {
const [item, setItem] = useState<SearchItem>({
value: "",
label: "",
});

const combobox = useCombobox<SearchItem>({
getItems: () => availableProperties,
getItems: () => sortedProperties,
itemToString: (item) => item?.label ?? "",
value: item,
defaultHighlightedIndex: 0,
Expand All @@ -210,23 +205,30 @@ const AdvancedSearch = ({
const descriptionItem = combobox.items[combobox.highlightedIndex];
const description = getNewPropertyDescription(descriptionItem);
const descriptions = combobox.items.map(getNewPropertyDescription);
const inputProps = combobox.getInputProps();

const handleKeys = (event: KeyboardEvent) => {
if (event.key === "Enter") {
onSubmit(item.value);
return;
}
if (event.key === "Escape") {
onClose();
}
};
const handleKeyDown = composeEventHandlers(handleKeys, inputProps.onKeyDown, {
// Pass prevented events to the combobox (e.g., the Escape key doesn't work otherwise, as it's blocked by Radix)
checkForDefaultPrevented: false,
});
return (
<ComboboxRoot open={combobox.isOpen}>
<form
{...combobox.getComboboxProps()}
onSubmit={(event) => {
event.preventDefault();
const isInserted = insertStyles(item.value);
if (isInserted) {
onClose();
}
}}
>
<div {...combobox.getComboboxProps()}>
<input type="submit" hidden />
<ComboboxAnchor>
<InputField
{...combobox.getInputProps()}
{...inputProps}
inputRef={forwardedRef}
onKeyDown={handleKeyDown}
autoFocus={true}
placeholder="Add styles"
suffix={<NestedInputButton {...combobox.getToggleButtonProps()} />}
Expand All @@ -251,12 +253,18 @@ const AdvancedSearch = ({
)}
</ComboboxListbox>
</ComboboxContent>
</form>
</div>
</ComboboxRoot>
);
};
});

const AdvancedPropertyLabel = ({ property }: { property: StyleProperty }) => {
const AdvancedPropertyLabel = ({
property,
onReset,
}: {
property: StyleProperty;
onReset?: () => void;
}) => {
const styleDecl = useComputedStyleDecl(property);
const label = hyphenateProperty(property);
const description = propertyDescriptions[property];
Expand All @@ -272,6 +280,7 @@ const AdvancedPropertyLabel = ({ property }: { property: StyleProperty }) => {
if (event.altKey) {
event.preventDefault();
deleteProperty(property);
onReset?.();
return;
}
setIsOpen(true);
Expand All @@ -285,6 +294,7 @@ const AdvancedPropertyLabel = ({ property }: { property: StyleProperty }) => {
onReset={() => {
deleteProperty(property);
setIsOpen(false);
onReset?.();
}}
/>
}
Expand All @@ -305,9 +315,13 @@ const AdvancedPropertyLabel = ({ property }: { property: StyleProperty }) => {
const AdvancedPropertyValue = ({
autoFocus,
property,
onChangeComplete,
}: {
autoFocus?: boolean;
property: StyleProperty;
onChangeComplete: ComponentProps<
typeof CssValueInputContainer
>["onChangeComplete"];
}) => {
const styleDecl = useComputedStyleDecl(property);
const inputRef = useRef<HTMLInputElement>(null);
Expand All @@ -323,6 +337,7 @@ const AdvancedPropertyValue = ({
variant="chromeless"
text="mono"
fieldSizing="content"
onChangeComplete={onChangeComplete}
prefix={
isColor && (
<ColorPopover
Expand Down Expand Up @@ -445,9 +460,15 @@ const AdvancedProperty = memo(
({
property,
autoFocus,
onChangeComplete,
onReset,
}: {
property: StyleProperty;
autoFocus: boolean;
autoFocus?: boolean;
onReset?: () => void;
onChangeComplete?: ComponentProps<
typeof CssValueInputContainer
>["onChangeComplete"];
}) => {
const visibilityChangeEventSupported = useClientSupports(
() => "oncontentvisibilityautostatechange" in document.body
Expand Down Expand Up @@ -501,9 +522,13 @@ const AdvancedProperty = memo(
>
{isVisible && (
<>
<AdvancedPropertyLabel property={property} />
<AdvancedPropertyLabel property={property} onReset={onReset} />
<Text>:</Text>
<AdvancedPropertyValue autoFocus={autoFocus} property={property} />
<AdvancedPropertyValue
autoFocus={autoFocus}
property={property}
onChangeComplete={onChangeComplete}
/>
</>
)}
</Flex>
Expand All @@ -514,36 +539,90 @@ const AdvancedProperty = memo(
export const Section = () => {
const [isAdding, setIsAdding] = useState(false);
const advancedProperties = useStore($advancedProperties);
const newlyAddedProperty = useRef<undefined | StyleProperty>(undefined);
const [recentProperties, setRecentProperties] = useState<StyleProperty[]>([]);
const addPropertyInputRef = useRef<HTMLInputElement>(null);

const addRecentProperties = (properties: StyleProperty[]) => {
setRecentProperties(
Array.from(new Set([...recentProperties, ...properties]))
);
};

return (
<AdvancedStyleSection
label="Advanced"
properties={advancedProperties}
onAdd={() => setIsAdding(true)}
onAdd={() => {
setIsAdding(true);
// User can click twice on the add button, so we need to focus the input on the second click after autoFocus isn't working.
addPropertyInputRef.current?.focus();
}}
>
{isAdding && (
<AdvancedSearch
usedProperties={advancedProperties}
onSelect={(property) => {
newlyAddedProperty.current = property;
setIsAdding(false);
setProperty(property)(
{ type: "guaranteedInvalid" },
{ listed: true }
);
}}
onClose={() => setIsAdding(false)}
/>
)}
<Box>
{advancedProperties.map((property) => (
<Box css={{ paddingInline: theme.panel.paddingInline }}>
{recentProperties.map((property, index, properties) => (
<AdvancedProperty
key={property}
property={property}
autoFocus={newlyAddedProperty.current === property}
autoFocus={index === properties.length - 1}
onChangeComplete={(event) => {
if (event.type === "enter") {
setIsAdding(true);
}
}}
onReset={() => {
setRecentProperties((properties) => {
return properties.filter(
(recentProperty) => recentProperty !== property
);
});
}}
/>
))}
{isAdding ? (
<Box css={{ paddingTop: theme.spacing[3] }}>
<AddProperty
onSelect={(property) => {
setIsAdding(false);
const isNew = advancedProperties.includes(property) === false;
if (isNew) {
setProperty(property)(
{ type: "guaranteedInvalid" },
{ listed: true }
);
}
addRecentProperties([property]);
}}
onSubmit={(value) => {
setIsAdding(false);
const styles = insertStyles(value);
const insertedProperties = styles.map(
({ property }) => property
);
addRecentProperties(insertedProperties);
}}
onClose={() => {
setIsAdding(false);
}}
ref={addPropertyInputRef}
/>
</Box>
) : (
// This empty div allows showing the add property input on tab in the last value
<div
tabIndex={0}
onFocus={() => {
setIsAdding(true);
}}
/>
kof marked this conversation as resolved.
Show resolved Hide resolved
)}
</Box>
{recentProperties.length > 0 && <Separator />}
<Box css={{ paddingInline: theme.panel.paddingInline }}>
{advancedProperties
.filter((property) => recentProperties.includes(property) === false)
.map((property) => (
<AdvancedProperty key={property} property={property} />
))}
</Box>
</AdvancedStyleSection>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ type CssValueInputContainerProps = {
ComponentProps<typeof CssValueInput>,
| "onChange"
| "onHighlight"
| "onChangeComplete"
| "onReset"
| "onAbort"
| "intermediateValue"
>;
| "onChangeComplete"
> & {
onChangeComplete?: ComponentProps<typeof CssValueInput>["onChangeComplete"];
};

export const CssValueInputContainer = ({
property,
setValue,
deleteProperty,
onChangeComplete,
...props
}: CssValueInputContainerProps) => {
const [intermediateValue, setIntermediateValue] = useState<
Expand Down Expand Up @@ -50,9 +53,10 @@ export const CssValueInputContainer = ({
deleteProperty(property, { isEphemeral: true });
}
}}
onChangeComplete={({ value }) => {
setValue(value);
onChangeComplete={(event) => {
setValue(event.value);
setIntermediateValue(undefined);
onChangeComplete?.(event);
}}
onAbort={() => {
deleteProperty(property, { isEphemeral: true });
Expand Down