|
| 1 | +import { defineComponent, h, ref } from 'vue' |
| 2 | +import type { Component, ComponentOptions, VNode } from 'vue' |
| 3 | + |
| 4 | +export const CodeGroup: ComponentOptions = defineComponent({ |
| 5 | + name: 'CodeGroup', |
| 6 | + |
| 7 | + setup(_, { slots }) { |
| 8 | + // index of current active item |
| 9 | + const activeIndex = ref(-1) |
| 10 | + |
| 11 | + return () => { |
| 12 | + // NOTICE: here we put the `slots.default()` inside the render function to make |
| 13 | + // the slots reactive, otherwise the slot content won't be changed once the |
| 14 | + // `setup()` function of current component is called |
| 15 | + |
| 16 | + // get children code-group-item |
| 17 | + const items = (slots.default?.() || []) |
| 18 | + .filter((vnode) => (vnode.type as Component).name === 'CodeGroupItem') |
| 19 | + .map((vnode) => { |
| 20 | + if (vnode.props === null) vnode.props = {} |
| 21 | + |
| 22 | + return vnode as VNode & { props: Exclude<VNode['props'], null> } |
| 23 | + }) |
| 24 | + |
| 25 | + // do not render anything if there is no code-group-item |
| 26 | + if (items.length === 0) return null |
| 27 | + |
| 28 | + if (activeIndex.value < 0 || activeIndex.value > items.length - 1) { |
| 29 | + // if `activeIndex` is invalid |
| 30 | + |
| 31 | + // find the index of the code-group-item with `active` props |
| 32 | + activeIndex.value = items.findIndex( |
| 33 | + (vnode) => vnode.props.active === '' || vnode.props.active === true |
| 34 | + ) |
| 35 | + |
| 36 | + // if there is no `active` props on code-group-item, set the first item active |
| 37 | + if (activeIndex.value === -1) activeIndex.value = 0 |
| 38 | + } else { |
| 39 | + // set the active item |
| 40 | + items.forEach((vnode, i) => { |
| 41 | + vnode.props.active = i === activeIndex.value |
| 42 | + }) |
| 43 | + } |
| 44 | + |
| 45 | + return h('div', { class: 'code-group' }, [ |
| 46 | + h( |
| 47 | + 'div', |
| 48 | + { class: 'code-group__nav' }, |
| 49 | + h( |
| 50 | + 'ul', |
| 51 | + { class: 'code-group__ul' }, |
| 52 | + items.map((vnode, i) => { |
| 53 | + const isActive = i === activeIndex.value |
| 54 | + |
| 55 | + return h( |
| 56 | + 'li', |
| 57 | + { class: 'code-group__li' }, |
| 58 | + h( |
| 59 | + 'button', |
| 60 | + { |
| 61 | + class: { |
| 62 | + 'code-group__nav-tab': true, |
| 63 | + 'code-group__nav-tab-active': isActive, |
| 64 | + }, |
| 65 | + ariaPressed: isActive, |
| 66 | + ariaExpanded: isActive, |
| 67 | + onClick: () => (activeIndex.value = i), |
| 68 | + }, |
| 69 | + vnode.props.title |
| 70 | + ) |
| 71 | + ) |
| 72 | + }) |
| 73 | + ) |
| 74 | + ), |
| 75 | + items, |
| 76 | + ]) |
| 77 | + } |
| 78 | + }, |
| 79 | +}) |
0 commit comments