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: setup knwoledge graph selector - WF-138 #739

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from
Open
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
62 changes: 62 additions & 0 deletions src/ui/src/builder/BuilderGraphSelect.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import BuilderGraphSelect from "./BuilderGraphSelect.vue";
import { flushPromises, shallowMount } from "@vue/test-utils";
import { buildMockCore } from "@/tests/mocks";
import injectionKeys from "@/injectionKeys";
import BuilderSelect from "./BuilderSelect.vue";
import WdsTextInput from "@/wds/WdsTextInput.vue";

describe("BuilderGraphSelect", () => {
const graphs = [
{ id: "1", name: "one" },
{ id: "2", name: "two" },
];
let core: ReturnType<typeof buildMockCore>["core"];

beforeEach(() => {
core = buildMockCore().core;
});

it("should fetch and display graphs", async () => {
const sendListResourcesRequest = vi
.spyOn(core, "sendListResourcesRequest")
.mockResolvedValue(graphs);

const wrapper = shallowMount(BuilderGraphSelect, {
props: { modelValue: "1" },
global: {
stubs: {
BuilderSelect: true,
},
provide: {
[injectionKeys.core as symbol]: core,
},
},
});
await flushPromises();
expect(sendListResourcesRequest).toHaveBeenCalledOnce();
expect(wrapper.findComponent(BuilderSelect).exists()).toBe(true);
});

it("should fallback to input", async () => {
const sendListResourcesRequest = vi
.spyOn(core, "sendListResourcesRequest")
.mockRejectedValue(new Error());

const wrapper = shallowMount(BuilderGraphSelect, {
props: { modelValue: "1" },
global: {
stubs: {
BuilderSelect: true,
},
provide: {
[injectionKeys.core as symbol]: core,
},
},
});
await flushPromises();
expect(sendListResourcesRequest).toHaveBeenCalledOnce();
expect(wrapper.findComponent(BuilderSelect).exists()).toBe(false);
expect(wrapper.findComponent(WdsTextInput).exists()).toBe(true);
});
});
86 changes: 86 additions & 0 deletions src/ui/src/builder/BuilderGraphSelect.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<script setup lang="ts">
import injectionKeys from "@/injectionKeys";
import {
computed,
defineAsyncComponent,
inject,
onMounted,
PropType,
} from "vue";
import { useListResources } from "@/composables/useListResources";
import type { Option } from "./BuilderSelect.vue";
import BuilderAsyncLoader from "./BuilderAsyncLoader.vue";
import type { WriterGraph } from "@/writerTypes";
import WdsTextInput from "@/wds/WdsTextInput.vue";

const BuilderSelect = defineAsyncComponent({
loader: () => import("./BuilderSelect.vue"),
loadingComponent: BuilderAsyncLoader,
});

const wf = inject(injectionKeys.core);

defineProps({
enableMultiSelection: { type: Boolean, required: false },
});

const currentValue = defineModel({
type: [String, Array] as PropType<string | string[]>,
required: true,
});

const {
load: loadGraphs,
data: graphs,
isLoading,
} = useListResources<WriterGraph>(wf, "graphs");

onMounted(loadGraphs);

const options = computed(() =>
graphs.value
.map<Option>((graph) => ({
label: graph.name,
detail: graph.description,
value: graph.id,
}))
.sort((a, b) => a.label.localeCompare(b.label)),
);

const currentValueStr = computed<string>({
get() {
if (currentValue.value === undefined) return "";

return typeof currentValue.value === "string"
? currentValue.value
: currentValue.value.join(",");
},
set(value: string) {
currentValue.value = value.split(",");
},
});
</script>

<template>
<div class="BuilderGraphSelect--text">
<BuilderSelect
v-if="graphs.length > 0 || isLoading"
v-model="currentValue"
:options="options"
hide-icons
enable-search
:loading="isLoading"
:enable-multi-selection="enableMultiSelection"
/>
<WdsTextInput v-else v-model="currentValueStr" />
</div>
</template>

<style scoped>
.BuilderGraphSelect--text {
width: 100%;
display: flex;
gap: 12px;
align-items: center;
}
</style>
54 changes: 54 additions & 0 deletions src/ui/src/builder/BuilderSelect.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { flushPromises, mount, shallowMount } from "@vue/test-utils";
import { describe, expect, it } from "vitest";

import BuilderSelect from "./BuilderSelect.vue";
import { Option } from "./BuilderSelect.vue";
import WdsDropdownMenu from "@/wds/WdsDropdownMenu.vue";

describe("BuilderSelect", () => {
const options: Option[] = [
{ label: "Label A", value: "a" },
{ label: "Label B", value: "b" },
{ label: "Label C", value: "c" },
];

it("should display unknow value selected", () => {
const wrapper = shallowMount(BuilderSelect, {
props: {
modelValue: "x",
enableMultiSelection: false,
hideIcons: true,
options,
},
});

expect(wrapper.get(".material-symbols-outlined").text()).toBe(
"help_center",
);
});

it("should support single mode", async () => {
const wrapper = mount(BuilderSelect, {
props: {
modelValue: "a",
enableMultiSelection: false,
options,
},
global: {
stubs: {
WdsDropdownMenu: true,
},
},
});
await flushPromises();

await wrapper.get(".BuilderSelect__trigger").trigger("click");
await flushPromises();

const dropdownMenu = wrapper.getComponent(WdsDropdownMenu);
dropdownMenu.vm.$emit("select", "b");
await flushPromises();

expect(wrapper.emitted("update:modelValue").at(0)).toStrictEqual(["b"]);
});
});
111 changes: 96 additions & 15 deletions src/ui/src/builder/BuilderSelect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,28 @@
role="button"
@click="isOpen = !isOpen"
>
<i v-if="!hideIcons" class="material-symbols-outlined">{{
currentIcon
}}</i>
<i
v-if="
(hasUnknowOptionSelected || !hideIcons) &&
!enableMultiSelection
"
class="material-symbols-outlined"
>{{ currentIcon }}</i
>
<div
v-if="enableMultiSelection"
class="BuilderSelect__trigger__multiSelectLabel"
>
<WdsTag
v-for="option of selectedOptions"
:key="option.value"
:text="option.label"
closable
@close="handleRemoveValue(option.value)"
/>
</div>
<div
v-else
class="BuilderSelect__trigger__label"
data-writer-tooltip-strategy="overflow"
:data-writer-tooltip="currentLabel"
Expand All @@ -19,10 +37,13 @@
<i class="material-symbols-outlined">{{ expandIcon }}</i>
</div>
</button>
<WdsMenu
<WdsDropdownMenu
v-if="isOpen"
ref="dropdown"
:enable-search="enableSearch"
:enable-multi-selection="enableMultiSelection"
:hide-icons="hideIcons"
:loading="loading"
:options="options"
:selected="currentValue"
:style="floatingStyles"
Expand All @@ -49,46 +70,92 @@ import {
import { useFloating, autoPlacement } from "@floating-ui/vue";
import type { WdsDropdownMenuOption } from "@/wds/WdsDropdownMenu.vue";
import { useFocusWithin } from "@/composables/useFocusWithin";
import WdsTag from "@/wds/WdsTag.vue";

const WdsMenu = defineAsyncComponent(() => import("@/wds/WdsDropdownMenu.vue"));
const WdsDropdownMenu = defineAsyncComponent(
() => import("@/wds/WdsDropdownMenu.vue"),
);

const props = defineProps({
options: {
type: Array as PropType<WdsDropdownMenuOption[]>,
type: Array as PropType<
WdsDropdownMenuOption[] | Readonly<WdsDropdownMenuOption[]>
>,
default: () => [],
},
defaultIcon: { type: String, required: false, default: undefined },
hideIcons: { type: Boolean, required: false },
enableSearch: { type: Boolean, required: false },
enableMultiSelection: { type: Boolean, required: false },
loading: { type: Boolean, required: false },
});

const currentValue = defineModel({ type: String, required: false });
const currentValue = defineModel({
type: [String, Array] as PropType<string | string[]>,
required: true,
default: undefined,
});
const isOpen = ref(false);
const trigger = useTemplateRef("trigger");
const dropdown = useTemplateRef("dropdown");

const middleware = computed(() =>
// avoid placement on the top when search mode is enabled
props.enableSearch
? []
: [autoPlacement({ allowedPlacements: ["bottom", "top"] })],
);

const { floatingStyles, update: updateFloatingStyle } = useFloating(
trigger,
dropdown,
{
placement: "bottom",
middleware: [autoPlacement({ allowedPlacements: ["bottom", "top"] })],
middleware,
},
);

const expandIcon = computed(() =>
isOpen.value ? "keyboard_arrow_up" : "expand_more",
);

const selectedOption = computed(() =>
props.options.find((o) => o.value === currentValue.value),
const currentValueArray = computed(() => {
if (!currentValue.value) return [];
const array = Array.isArray(currentValue.value)
? currentValue.value
: [currentValue.value];
return array.filter(Boolean);
});

const selectedOptions = computed<WdsDropdownMenuOption[]>(() =>
currentValueArray.value.map(
(v) =>
props.options.find((o) => o.value === v) ?? { value: v, label: v },
),
);

const currentLabel = computed(() => selectedOption.value?.label ?? "");
const hasUnknowOptionSelected = computed(() => {
return (
currentValue.value &&
!props.options.some((o) => o.value === currentValue.value)
);
});

const currentLabel = computed(() => {
if (hasUnknowOptionSelected.value) return String(currentValue.value);

return selectedOptions.value
.map((o) => o.label)
.sort()
.join(" / ");
});

const currentIcon = computed(() => {
if (hasUnknowOptionSelected.value) return "help_center";
if (props.hideIcons) return "";
return selectedOption.value?.icon ?? props.defaultIcon ?? "help_center";
return (
selectedOptions.value.at(0)?.icon ?? props.defaultIcon ?? "help_center"
);
});

// close the dropdown when clicking outside
Expand All @@ -104,10 +171,15 @@ watch(
{ immediate: true },
);

function onSelect(value: string) {
isOpen.value = false;
function onSelect(value: string | string[]) {
if (!props.enableMultiSelection) isOpen.value = false;
currentValue.value = value;
}

function handleRemoveValue(value: string) {
if (!Array.isArray(currentValue.value)) return;
currentValue.value = currentValue.value.filter((v) => v !== value);
}
</script>

<style scoped>
Expand All @@ -123,7 +195,7 @@ function onSelect(value: string) {
align-items: center;
gap: 8px;

height: 40px;
min-height: 40px;
width: 100%;
padding: 8.5px 12px 8.5px 12px;

Expand Down Expand Up @@ -159,4 +231,13 @@ function onSelect(value: string) {
font-weight: 300;
cursor: pointer;
}

.BuilderSelect__trigger__multiSelectLabel {
flex-grow: 1;

display: flex;
flex-wrap: wrap;
justify-content: flex-start;
gap: 8px;
}
</style>
Loading
Loading