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

[Navigation Menu]feat: 1/3 #167

Merged
merged 19 commits into from
Jul 15, 2023
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
69 changes: 28 additions & 41 deletions packages/radix-vue/src/Collapsible/CollapsibleContent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,34 @@ export interface CollapsibleContentProps {
</script>

<script setup lang="ts">
import { inject, nextTick, onMounted, ref, watch } from "vue";
import { computed, inject, nextTick, ref, watch } from "vue";
import {
COLLAPSIBLE_INJECTION_KEY,
type CollapsibleProvideValue,
} from "./CollapsibleRoot.vue";
import { PrimitiveDiv, usePrimitiveElement } from "@/Primitive";
import { Presence } from "@/Presence";

const injectedValue = inject<CollapsibleProvideValue>(
COLLAPSIBLE_INJECTION_KEY
);

const presentRef = ref<InstanceType<typeof Presence>>();
const { primitiveElement, currentElement } = usePrimitiveElement();

const width = ref(0);
const height = ref(0);
const currentStyle = ref<Record<string, string>>();

// when opening we want it to immediately open to retrieve dimensions
// when closing we delay `present` to retrieve dimensions before closing
const isMountAnimationPrevented = ref(injectedValue?.open.value);
const isPresent = ref(false);
const hasAnimations = ref(false);
const isOpen = computed(() => injectedValue?.open.value);
const isMountAnimationPrevented = ref(isOpen.value);
const currentStyle = ref<Record<string, string>>();

watch(
() => [injectedValue?.open.value, currentElement.value],
() => [isOpen.value, presentRef.value?.present],
async () => {
if (injectedValue?.open.value) {
isPresent.value = true;
} else if (!hasAnimations.value) {
isPresent.value = false;
}

await nextTick();

const node = currentElement.value;
if (!node) return;
currentStyle.value = currentStyle.value || {
Expand All @@ -65,20 +59,12 @@ watch(
}
);

onMounted(() => {
const currentElementStyle = getComputedStyle(currentElement.value!);
if (currentElementStyle?.animationName !== "none") {
hasAnimations.value = true;
currentElement.value?.addEventListener("animationend", () => {
if (!injectedValue?.open.value) {
isPresent.value = false;
}
});
}
requestAnimationFrame(() => {
isMountAnimationPrevented.value = false;
});

requestAnimationFrame(() => {
isMountAnimationPrevented.value = false;
});
defineOptions({
inheritAttrs: false,
});

const props = withDefaults(defineProps<CollapsibleContentProps>(), {
Expand All @@ -87,20 +73,21 @@ const props = withDefaults(defineProps<CollapsibleContentProps>(), {
</script>

<template>
<PrimitiveDiv
ref="primitiveElement"
:asChild="props.asChild"
:data-state="injectedValue?.open.value ? 'open' : 'closed'"
:data-disabled="injectedValue?.disabled?.value ? '' : undefined"
:id="injectedValue?.contentId"
:hidden="!isPresent"
:style="{
[`--radix-collapsible-content-height`]: `${height}px`,
[`--radix-collapsible-content-width`]: `${width}px`,
}"
>
<template v-if="isPresent">
<Presence ref="presentRef" :present="injectedValue!.open.value">
<PrimitiveDiv
ref="primitiveElement"
v-bind="$attrs"
:asChild="props.asChild"
:data-state="injectedValue?.open.value ? 'open' : 'closed'"
:data-disabled="injectedValue?.disabled?.value ? 'true' : undefined"
:id="injectedValue?.contentId"
:hidden="!injectedValue?.open"
:style="{
[`--radix-collapsible-content-height`]: `${height}px`,
[`--radix-collapsible-content-width`]: `${width}px`,
}"
>
<slot />
</template>
</PrimitiveDiv>
</PrimitiveDiv>
</Presence>
</template>
4 changes: 2 additions & 2 deletions packages/radix-vue/src/Collapsible/CollapsibleRoot.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ export interface CollapsibleRootProps {

export interface CollapsibleProvideValue {
contentId: string;
disabled?: Readonly<Ref<boolean>>;
open: Readonly<Ref<boolean>>;
disabled?: Ref<boolean>;
open: Ref<boolean>;
onOpenToggle(): void;
}

Expand Down
72 changes: 72 additions & 0 deletions packages/radix-vue/src/NavigationMenu/NavigationMenuContent.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<script setup lang="ts">
import { NAVIGATION_MENU_INJECTION_KEY } from "./NavigationMenuRoot.vue";
import { NAVIGATION_MENU_ITEM_INJECTION_KEY } from "./NavigationMenuItem.vue";
import {
computed,
inject,
onMounted,
ref,
watch,
type VNode,
getCurrentInstance,
} from "vue";
import { getOpenState } from "./utils";
import NavigationMenuContentImpl from "./NavigationMenuContentImpl.vue";
import { Presence } from "@/Presence";

defineOptions({
inheritAttrs: false,
});

const context = inject(NAVIGATION_MENU_INJECTION_KEY);
const itemContext = inject(NAVIGATION_MENU_ITEM_INJECTION_KEY);

const open = computed(() => itemContext?.value === context?.modelValue.value);

const commonProps = computed(() => ({
value: itemContext!.value,
triggerRef: itemContext!.triggerRef,
focusProxyRef: itemContext!.focusProxyRef,
wasEscapeCloseRef: itemContext!.wasEscapeCloseRef,
onContentFocusOutside: itemContext!.onContentFocusOutside,
// onRootContentClose: itemContext!.onRootContentClose,
}));

const elementRef = ref<VNode>();

watch(elementRef, () => {
itemContext!.contentRef.value = elementRef.value;
});

const instance = getCurrentInstance();
onMounted(() => {
// @ts-ignore
const vnode = instance?.vnode.children?.default()?.[0];
if (context?.viewport && vnode) {
vnode.props = { ...vnode.props, ...commonProps.value };
vnode.parentProps = instance.vnode.props;
itemContext!.contentRef.value = vnode;
context.onViewportContentChange(itemContext!.value, vnode);
}
});

const handleEscape = () => {
itemContext!.wasEscapeCloseRef.value = true;
};
</script>

<template>
<Presence v-if="!context?.viewport" :present="open">
<NavigationMenuContentImpl
ref="elementRef"
:data-state="getOpenState(open)"
:style="{
pointerEvents: !open && context?.isRootMenu ? 'none' : undefined,
}"
v-bind="($attrs, commonProps)"
@escape="handleEscape"
>
<slot></slot>
</NavigationMenuContentImpl>
</Presence>
</template>
135 changes: 135 additions & 0 deletions packages/radix-vue/src/NavigationMenu/NavigationMenuContentImpl.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<script lang="ts">
type MotionAttribute = "to-start" | "to-end" | "from-start" | "from-end";

interface NavigationMenuContentImplProps {
value: string;
triggerRef: Ref<HTMLElement | undefined>;
focusProxyRef: Ref<HTMLElement | undefined>;
wasEscapeCloseRef: Ref<boolean>;
onContentFocusOutside(): void;
// onRootContentClose(): void;
}
</script>

<script setup lang="ts">
import { NAVIGATION_MENU_INJECTION_KEY } from "./NavigationMenuRoot.vue";
import { computed, inject, ref, type Ref } from "vue";
import {
focusFirst,
getTabbableCandidates,
makeContentId,
makeTriggerId,
} from "./utils";
import { useArrowNavigation, useCollection, onFocusOutside } from "@/shared";

const props = defineProps<NavigationMenuContentImplProps>();
const emits = defineEmits<{
(e: "escape", event: KeyboardEvent): void;
}>();

const { getItems } = useCollection();

const elementRef = ref<HTMLElement>();
const context = inject(NAVIGATION_MENU_INJECTION_KEY);
const triggerId = makeTriggerId(context!.baseId, props.value);
const contentId = makeContentId(context!.baseId, props.value);

const prevMotionAttributeRef = ref<MotionAttribute | null>(null);
const motionAttribute = computed(() => {
const items = getItems();
const values = items.map((item) => item.id.split("trigger-")[1]);
if (context?.dir === "rtl") values.reverse();
const index = values.indexOf(context!.modelValue.value);
const prevIndex = values.indexOf(context!.previousValue.value);
const isSelected = props.value === context?.modelValue.value;
const wasSelected = prevIndex === values.indexOf(props.value);

// We only want to update selected and the last selected content
// this avoids animations being interrupted outside of that range
if (!isSelected && !wasSelected) return prevMotionAttributeRef.value;

const attribute = (() => {
// Don't provide a direction on the initial open
if (index !== prevIndex) {
// If we're moving to this item from another
if (isSelected && prevIndex !== -1)
return index > prevIndex ? "from-end" : "from-start";
// If we're leaving this item for another
if (wasSelected && index !== -1)
return index > prevIndex ? "to-start" : "to-end";
}
// Otherwise we're entering from closed or leaving the list
// entirely and should not animate in any direction
return null;
})();

// eslint-disable-next-line vue/no-side-effects-in-computed-properties
prevMotionAttributeRef.value = attribute;
return attribute;
});

onFocusOutside(elementRef, (ev) => {
props.onContentFocusOutside();
const target = ev.target as HTMLElement;
// Only dismiss content when focus moves outside of the menu
if (context!.rootNavigationMenu?.value?.contains(target)) ev.preventDefault();
});

const handleKeydown = (ev: KeyboardEvent) => {
const isMetaKey = ev.altKey || ev.ctrlKey || ev.metaKey;
const isTabKey = ev.key === "Tab" && !isMetaKey;
const candidates = getTabbableCandidates(ev.currentTarget as HTMLElement);

if (isTabKey) {
const focusedElement = document.activeElement;
const index = candidates.findIndex(
(candidate) => candidate === focusedElement
);
const isMovingBackwards = ev.shiftKey;
const nextCandidates = isMovingBackwards
? candidates.slice(0, index).reverse()
: candidates.slice(index + 1, candidates.length);

if (focusFirst(nextCandidates)) {
// prevent browser tab keydown because we've handled focus
ev.preventDefault();
} else {
// If we can't focus that means we're at the edges
// so focus the proxy and let browser handle
// tab/shift+tab keypress on the proxy instead
props.focusProxyRef.value?.focus();
return;
}
}

const newSelectedElement = useArrowNavigation(
ev,
document.activeElement as HTMLElement,
undefined,
{ itemsArray: candidates, loop: false }
);
newSelectedElement?.focus();
ev.preventDefault();
};

const handleEscape = (ev: KeyboardEvent) => {
emits("escape", ev);
};

defineExpose({
...props,
});
</script>

<template>
<div
ref="elementRef"
:id="contentId"
:aria-labelledby="triggerId"
:data-motion="motionAttribute"
@keydown="handleKeydown"
@keydown.escape.prevent="handleEscape"
>
<slot></slot>
</div>
</template>
Loading
Loading