Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Add `corex` to your `mix.exs` dependencies:
```elixir
def deps do
[
{:corex, "~> 0.1.0-alpha.25"}
{:corex, "~> 0.1.0-alpha.26"}
]
end
```
Expand Down
86 changes: 69 additions & 17 deletions assets/components/combobox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class Combobox extends Component<Props, Api> {
this.options = options;
}

private getCollection() {
getCollection() {
const items = this.options || this.allOptions || [];

if (this.hasGroups) {
Expand All @@ -45,7 +45,7 @@ export class Combobox extends Component<Props, Api> {

// eslint-disable-next-line @typescript-eslint/no-explicit-any
initMachine(props: Props): VanillaMachine<any> {
const getCollection = this.getCollection.bind(this);
const getCollection = () => this.getCollection();

return new VanillaMachine(machine, {
...props,
Expand All @@ -61,14 +61,17 @@ export class Combobox extends Component<Props, Api> {
}
},
onInputValueChange: (details: InputValueChangeDetails) => {
const filtered = this.allOptions.filter((item: ComboboxItem) =>
item.label.toLowerCase().includes(details.inputValue.toLowerCase())
);
this.options = filtered.length > 0 ? filtered : this.allOptions;

if (props.onInputValueChange) {
props.onInputValueChange(details);
}
if (this.el.hasAttribute("data-filter")) {
const filtered = this.allOptions.filter((item: ComboboxItem) =>
item.label.toLowerCase().includes(details.inputValue.toLowerCase())
);
this.options = filtered.length > 0 ? filtered : this.allOptions;
} else {
this.options = this.allOptions;
}
},
});
}
Expand All @@ -94,38 +97,88 @@ export class Combobox extends Component<Props, Api> {
.querySelectorAll('[data-scope="combobox"][data-part="item-group"]:not([data-template])')
.forEach((el) => el.remove());

if (this.hasGroups) {
contentEl
.querySelectorAll('[data-scope="combobox"][data-part="empty"]:not([data-template])')
.forEach((el) => el.remove());

const items = this.options?.length ? this.options : this.allOptions;

if (items.length === 0) {
const emptyTemplate = templatesContainer.querySelector<HTMLElement>(
'[data-scope="combobox"][data-part="empty"][data-template]'
);
if (emptyTemplate) {
const emptyEl = emptyTemplate.cloneNode(true) as HTMLElement;
emptyEl.removeAttribute("data-template");
contentEl.appendChild(emptyEl);
}
} else if (this.hasGroups) {
const groups = this.api.collection.group?.() ?? [];
this.renderGroupedItems(contentEl, templatesContainer, groups);
} else {
const items = this.options?.length ? this.options : this.allOptions;
this.renderFlatItems(contentEl, templatesContainer, items);
}
}

buildOrderedBlocks(
items: ComboboxItem[]
): (
| { type: "default"; items: ComboboxItem[] }
| { type: "group"; groupId: string; items: ComboboxItem[] }
)[] {
const blocks: (
| { type: "default"; items: ComboboxItem[] }
| { type: "group"; groupId: string; items: ComboboxItem[] }
)[] = [];
let current:
| { type: "default"; items: ComboboxItem[] }
| { type: "group"; groupId: string; items: ComboboxItem[] }
| null = null;

for (const item of items) {
const groupKey = item.group ?? "";
if (groupKey === "") {
if (current?.type !== "default") {
current = { type: "default", items: [] };
blocks.push(current);
}
current.items.push(item);
} else {
if (current?.type !== "group" || current.groupId !== groupKey) {
current = { type: "group", groupId: groupKey, items: [] };
blocks.push(current);
}
current.items.push(item);
}
}
return blocks;
}

renderGroupedItems(
contentEl: HTMLElement,
templatesContainer: HTMLElement,
groups: [string | null, ComboboxItem[]][]
_groups: [string | null, ComboboxItem[]][]
): void {
for (const [groupId, groupItems] of groups) {
if (groupId == null) continue;
const items = this.options?.length ? this.options : this.allOptions;
const blocks = this.buildOrderedBlocks(items);

for (const block of blocks) {
const templateId = block.type === "default" ? "default" : block.groupId;
const groupTemplate = templatesContainer.querySelector<HTMLElement>(
`[data-scope="combobox"][data-part="item-group"][data-id="${groupId}"][data-template]`
`[data-scope="combobox"][data-part="item-group"][data-id="${templateId}"][data-template]`
);
if (!groupTemplate) continue;

const groupEl = groupTemplate.cloneNode(true) as HTMLElement;
groupEl.removeAttribute("data-template");

this.spreadProps(groupEl, this.api.getItemGroupProps({ id: groupId }));
this.spreadProps(groupEl, this.api.getItemGroupProps({ id: templateId }));

const labelEl = groupEl.querySelector<HTMLElement>(
'[data-scope="combobox"][data-part="item-group-label"]'
);
if (labelEl) {
this.spreadProps(labelEl, this.api.getItemGroupLabelProps({ htmlFor: groupId }));
this.spreadProps(labelEl, this.api.getItemGroupLabelProps({ htmlFor: templateId }));
}

const groupContentEl = groupEl.querySelector<HTMLElement>(
Expand All @@ -135,7 +188,7 @@ export class Combobox extends Component<Props, Api> {

groupContentEl.innerHTML = "";

for (const item of groupItems) {
for (const item of block.items) {
const itemEl = this.cloneItem(templatesContainer, item);
if (itemEl) groupContentEl.appendChild(itemEl);
}
Expand Down Expand Up @@ -171,7 +224,6 @@ export class Combobox extends Component<Props, Api> {
const textEl = el.querySelector<HTMLElement>('[data-scope="combobox"][data-part="item-text"]');
if (textEl) {
this.spreadProps(textEl, this.api.getItemTextProps({ item }));
// Only set textContent if there are no child elements (custom HTML slots preserve their structure)
if (textEl.children.length === 0) {
textEl.textContent = item.label || "";
}
Expand Down
108 changes: 7 additions & 101 deletions assets/hooks/combobox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const ComboboxHook: Hook<object & ComboboxHookState, HTMLElement> = {
invalid: getBoolean(el, "invalid"),
allowCustomValue: false,
selectionBehavior: "replace",
name: "",
name: getString(el, "name"),
form: getString(el, "form"),
readOnly: getBoolean(el, "readOnly"),
required: getBoolean(el, "required"),
Expand Down Expand Up @@ -122,65 +122,12 @@ const ComboboxHook: Hook<object & ComboboxHookState, HTMLElement> = {
}
},
onValueChange: (details: ValueChangeDetails) => {
const valueInput = el.querySelector<HTMLInputElement>(
'[data-scope="combobox"][data-part="value-input"]'
const hiddenInput = el.querySelector<HTMLInputElement>(
'[data-scope="combobox"][data-part="input"]'
);
if (valueInput) {
const toId = (val: string) => {
const item = allItems.find(
(i: { id?: string; label?: string }) => String(i.id ?? "") === val || i.label === val
);
return item ? String(item.id ?? "") : val;
};
const idValue =
details.value.length === 0
? ""
: details.value.length === 1
? toId(String(details.value[0]))
: details.value.map((v) => toId(String(v))).join(",");
valueInput.value = idValue;

const formId = valueInput.getAttribute("form");
let form: HTMLFormElement | null = null;

if (formId) {
form = document.getElementById(formId) as HTMLFormElement;
} else {
form = valueInput.closest("form");
}

const changeEvent = new Event("change", {
bubbles: true,
cancelable: true,
});
valueInput.dispatchEvent(changeEvent);

const inputEvent = new Event("input", {
bubbles: true,
cancelable: true,
});
valueInput.dispatchEvent(inputEvent);

if (form && form.hasAttribute("phx-change")) {
requestAnimationFrame(() => {
const formElement = form.querySelector("input, select, textarea") as HTMLElement;
if (formElement) {
const formChangeEvent = new Event("change", {
bubbles: true,
cancelable: true,
});
formElement.dispatchEvent(formChangeEvent);
} else {
const formChangeEvent = new Event("change", {
bubbles: true,
cancelable: true,
});
form.dispatchEvent(formChangeEvent);
}
});
}
if (hiddenInput) {
hiddenInput.dispatchEvent(new Event("change", { bubbles: true }));
}

const eventName = getString(el, "onValueChange");
if (eventName && !this.liveSocket.main.isDead && this.liveSocket.main.isConnected()) {
pushEvent(eventName, {
Expand Down Expand Up @@ -211,39 +158,6 @@ const ComboboxHook: Hook<object & ComboboxHookState, HTMLElement> = {
combobox.setAllOptions(allItems);
combobox.init();

const visibleInput = el.querySelector<HTMLInputElement>(
'[data-scope="combobox"][data-part="input"]'
);
if (visibleInput) {
visibleInput.removeAttribute("name");
visibleInput.removeAttribute("form");
}

const initialValue = getBoolean(el, "controlled")
? getStringList(el, "value")
: getStringList(el, "defaultValue");

if (initialValue && initialValue.length > 0) {
const selectedItems = allItems.filter((item: { id?: string }) =>
initialValue.includes(item.id ?? "")
);
if (selectedItems.length > 0) {
const inputValue = selectedItems
.map((item: { label?: string }) => item.label ?? "")
.join(", ");
if (combobox.api && typeof combobox.api.setInputValue === "function") {
combobox.api.setInputValue(inputValue);
} else {
const inputEl = el.querySelector<HTMLInputElement>(
'[data-scope="combobox"][data-part="input"]'
);
if (inputEl) {
inputEl.value = inputValue;
}
}
}
}

this.combobox = combobox;
this.handlers = [];
},
Expand All @@ -255,10 +169,12 @@ const ComboboxHook: Hook<object & ComboboxHookState, HTMLElement> = {
if (this.combobox) {
this.combobox.hasGroups = hasGroups;
this.combobox.setAllOptions(newCollection);
this.combobox.render();
this.combobox.updateProps({
...(getBoolean(this.el, "controlled")
? { value: getStringList(this.el, "value") }
: { defaultValue: getStringList(this.el, "defaultValue") }),
collection: this.combobox.getCollection(),
name: getString(this.el, "name"),
form: getString(this.el, "form"),
disabled: getBoolean(this.el, "disabled"),
Expand All @@ -268,15 +184,6 @@ const ComboboxHook: Hook<object & ComboboxHookState, HTMLElement> = {
required: getBoolean(this.el, "required"),
readOnly: getBoolean(this.el, "readOnly"),
});

const inputEl = this.el.querySelector<HTMLInputElement>(
'[data-scope="combobox"][data-part="input"]'
);
if (inputEl) {
inputEl.removeAttribute("name");
inputEl.removeAttribute("form");
inputEl.name = "";
}
}
},

Expand All @@ -286,7 +193,6 @@ const ComboboxHook: Hook<object & ComboboxHookState, HTMLElement> = {
this.removeHandleEvent(handler);
}
}

this.combobox?.destroy();
},
};
Expand Down
22 changes: 22 additions & 0 deletions design/components/combobox.css
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@
@apply ui-label;
}

.combobox [data-scope="combobox"][data-part="empty"] {
@apply ui-label;

list-style: none;
padding-inline: var(--spacing-ui-padding);
padding-block: var(--spacing-mini-padding-sm);
}

.combobox [data-scope="combobox"][data-part="control"] {
display: flex;
width: 100%;
Expand Down Expand Up @@ -66,6 +74,13 @@
.combobox [data-scope="combobox"][data-part="item-group"] {
display: flex;
flex-direction: column;
min-height: fit-content;
}

.combobox [data-scope="combobox"][data-part="item-group-content"] {
min-height: fit-content;
display: flex;
flex-direction: column;
}

.combobox [data-scope="combobox"][data-part="item-group-label"] {
Expand All @@ -81,6 +96,13 @@

.combobox [data-scope="combobox"][data-part="item"] {
@apply ui-item;

align-items: flex-start;
min-height: fit-content;
}

.combobox [data-scope="combobox"][data-part="item"] [data-part="item-text"] {
min-height: fit-content;
}

.combobox [data-scope="combobox"][data-part="error"] {
Expand Down
Loading
Loading