Skip to content

Commit

Permalink
autocomplete url
Browse files Browse the repository at this point in the history
  • Loading branch information
FredericHeem committed Dec 27, 2023
1 parent f82b83b commit 7d89382
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { Context } from "@grucloud/bau-ui/context";
import autocomplete from "@grucloud/bau-ui/autocomplete";
import button from "@grucloud/bau-ui/button";

export default (context: Context) => {
const { bau, css } = context;
const { form, article, footer, div, span } = bau.tags;

const Autocomplete = autocomplete(context);
const Button = button(context, {
variant: "outline",
color: "primary",
});

const options = [
{ code: "AD", label: "Andorra", phone: "376" },
{ code: "AF", label: "Afghanistan", phone: "93" },
];

const Option = (option: any) =>
div(
{
class: css`
display: flex;
justify-content: space-between;
gap: 0.5rem;
`,
},
span(option.label),
span(option.code)
);

const autocompleteName = "country";

return () => {
const onsubmit = (event: any) => {
event.preventDefault();
const payload = Object.fromEntries(new FormData(event.currentTarget));
alert(JSON.stringify(payload));
};

const search = new URLSearchParams(window.location.search);
const defaultCode = search.get("country");

const getOptionValue = ({ code }: any) => code;

const onSelect = (option: any) => {
const search = new URLSearchParams(window.location.search);
search.delete(autocompleteName);
search.append(autocompleteName, getOptionValue(option));
window.history.replaceState(
"",
"",
`?${search.toString()}${window.location.hash}`
);
};

return form(
{ onsubmit },
article(
Autocomplete({
name: autocompleteName,
options,
Option,
defaultOption: options.find(({ code }) => code == defaultCode),
getOptionValue: ({ code }: any) => code,
getOptionLabel: ({ label }: any) => label,
label: "Country",
placeholder: "Search countries",
onSelect,
})
),
footer(Button({ type: "submit" }, "Submit"))
);
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import codeDefaultOption from "./autocomplete-default-option.ts?raw";
import autocompleteLoading from "./autocomplete-loading.ts";
// @ts-ignore
import codeExampleLoading from "./autocomplete-loading.ts?raw";

import autocompleteUrl from "./autocomplete-url.ts";
// @ts-ignore
import codeUrl from "./autocomplete-url.ts?raw";

export const autocompleteSpec = {
title: "Auto Complete",
package: "autocomplete",
Expand Down Expand Up @@ -41,6 +46,12 @@ export const autocompleteSpec = {
code: codeDefaultOption,
createComponent: autocompleteDefaultOption,
},
{
title: "URL State",
description: "A autocomplete with the state in the URL",
code: codeUrl,
createComponent: autocompleteUrl,
},
],
gridItem: autocompleteGridItem,
};
Expand Down

0 comments on commit 7d89382

Please sign in to comment.