@bwui/vue 0.1.9 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/modal.ts ADDED
@@ -0,0 +1,160 @@
1
+ import { defineComponent, h, onBeforeUnmount, watch, type PropType } from 'vue'
2
+ import { cn } from './cn'
3
+
4
+ type ModalSize = 'sm' | 'md' | 'lg' | 'full'
5
+ type HeaderRecipe = 'plain' | 'muted' | 'bordered'
6
+ type FooterRecipe = 'plain' | 'muted' | 'actions'
7
+
8
+ const FOCUSABLE =
9
+ 'a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])'
10
+
11
+ export const Modal = defineComponent({
12
+ name: 'BwModal',
13
+ props: {
14
+ open: { type: Boolean, default: false },
15
+ title: { type: String, required: true },
16
+ closeLabel: { type: String, required: true },
17
+ size: { type: String as PropType<ModalSize>, default: 'md' },
18
+ backdropDismiss: { type: Boolean, default: true },
19
+ headerRecipe: { type: String as PropType<HeaderRecipe>, default: 'plain' },
20
+ footerRecipe: { type: String as PropType<FooterRecipe>, default: 'plain' },
21
+ },
22
+ emits: ['update:open', 'openChange'],
23
+ setup(props, { slots, attrs, emit }) {
24
+ let previouslyFocused: HTMLElement | null = null
25
+ let prevOverflow = ''
26
+ let panelEl: HTMLElement | null = null
27
+
28
+ const close = () => {
29
+ emit('update:open', false)
30
+ emit('openChange', false)
31
+ }
32
+
33
+ const onKey = (e: KeyboardEvent) => {
34
+ if (!props.open) return
35
+ if (e.key === 'Escape') {
36
+ e.preventDefault()
37
+ close()
38
+ return
39
+ }
40
+ if (e.key !== 'Tab' || !panelEl) return
41
+ const nodes = Array.from(panelEl.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
42
+ (el) => el.tabIndex !== -1,
43
+ )
44
+ if (nodes.length === 0) {
45
+ e.preventDefault()
46
+ panelEl.focus()
47
+ return
48
+ }
49
+ const first = nodes[0]
50
+ const last = nodes[nodes.length - 1]
51
+ if (e.shiftKey && document.activeElement === first) {
52
+ e.preventDefault()
53
+ last.focus()
54
+ } else if (!e.shiftKey && document.activeElement === last) {
55
+ e.preventDefault()
56
+ first.focus()
57
+ }
58
+ }
59
+
60
+ watch(
61
+ () => props.open,
62
+ (open) => {
63
+ if (open) {
64
+ previouslyFocused =
65
+ document.activeElement instanceof HTMLElement ? document.activeElement : null
66
+ prevOverflow = document.body.style.overflow
67
+ document.body.style.overflow = 'hidden'
68
+ document.addEventListener('keydown', onKey)
69
+ requestAnimationFrame(() => {
70
+ const autofocus = panelEl?.querySelector<HTMLElement>('[data-bw-autofocus]')
71
+ const nodes = panelEl
72
+ ? Array.from(panelEl.querySelectorAll<HTMLElement>(FOCUSABLE))
73
+ : []
74
+ ;(autofocus || nodes[0] || panelEl)?.focus()
75
+ })
76
+ } else {
77
+ document.removeEventListener('keydown', onKey)
78
+ document.body.style.overflow = prevOverflow
79
+ previouslyFocused?.focus?.()
80
+ previouslyFocused = null
81
+ }
82
+ },
83
+ )
84
+
85
+ onBeforeUnmount(() => {
86
+ document.removeEventListener('keydown', onKey)
87
+ document.body.style.overflow = prevOverflow
88
+ })
89
+
90
+ return () => {
91
+ const headerExtra =
92
+ props.headerRecipe !== 'plain' ? ` bw-modal--header-${props.headerRecipe}` : ''
93
+ const footerExtra =
94
+ props.footerRecipe !== 'plain' ? ` bw-modal--footer-${props.footerRecipe}` : ''
95
+ const headerMod =
96
+ props.headerRecipe !== 'plain' ? ` bw-modal__header--${props.headerRecipe}` : ''
97
+ const footerMod =
98
+ props.footerRecipe !== 'plain' ? ` bw-modal__footer--${props.footerRecipe}` : ''
99
+ const titleId = 'bw-modal-title'
100
+ return h(
101
+ 'div',
102
+ {
103
+ ...attrs,
104
+ class: cn(
105
+ 'bw-modal',
106
+ `bw-modal--size-${props.size}`,
107
+ props.open && 'bw-modal--open',
108
+ headerExtra.trim(),
109
+ footerExtra.trim(),
110
+ String(attrs.class || ''),
111
+ ),
112
+ role: 'presentation',
113
+ ...(props.open ? { 'data-bw-open': '' } : {}),
114
+ },
115
+ [
116
+ h('div', {
117
+ class: 'bw-modal__scrim',
118
+ 'aria-hidden': 'true',
119
+ onClick: () => {
120
+ if (props.backdropDismiss) close()
121
+ },
122
+ }),
123
+ h(
124
+ 'div',
125
+ {
126
+ class: 'bw-modal__panel',
127
+ role: 'dialog',
128
+ 'aria-modal': 'true',
129
+ 'aria-labelledby': titleId,
130
+ tabindex: -1,
131
+ ref: (el) => {
132
+ panelEl = (el as HTMLElement | null) ?? null
133
+ },
134
+ },
135
+ [
136
+ h('header', { class: `bw-modal__header${headerMod}` }, [
137
+ h('h2', { class: 'bw-modal__title', id: titleId }, props.title),
138
+ h(
139
+ 'button',
140
+ {
141
+ type: 'button',
142
+ class:
143
+ 'bw-modal__close bw-btn bw-btn--ghost bw-btn--size-sm bw-btn--icon-only',
144
+ 'aria-label': props.closeLabel,
145
+ onClick: close,
146
+ },
147
+ [h('span', { 'aria-hidden': 'true' }, '×')],
148
+ ),
149
+ ]),
150
+ h('div', { class: 'bw-modal__body' }, slots.default?.()),
151
+ slots.footer
152
+ ? h('footer', { class: `bw-modal__footer${footerMod}` }, slots.footer())
153
+ : null,
154
+ ],
155
+ ),
156
+ ],
157
+ )
158
+ }
159
+ },
160
+ })
package/src/popover.ts ADDED
@@ -0,0 +1,241 @@
1
+ import {
2
+ defineComponent,
3
+ h,
4
+ nextTick,
5
+ onBeforeUnmount,
6
+ onMounted,
7
+ ref,
8
+ watch,
9
+ type PropType,
10
+ } from 'vue'
11
+ import { cn } from './cn'
12
+
13
+ // Popover (docs/components/popover.md, R39 / H15). Emits the same bw-popover*
14
+ // classes, role and anatomy as the HTML, Django and React deliveries (POP-071):
15
+ // a div root with a placement modifier, a button trigger, and a role="dialog"
16
+ // panel that is the trigger's next sibling and stays mounted while closed
17
+ // (POP-038). It is not modal: no scrim, no focus trap, no inert page, no
18
+ // scroll lock, no aria-modal, and Tab never closes it. No user-visible English
19
+ // originates here (POP-076): the close label is a required prop when closable.
20
+
21
+ export type PopoverPlacement = 'top' | 'bottom' | 'start' | 'end'
22
+ export type PopoverCloseReason = 'escape' | 'outside' | 'close-button' | 'trigger' | 'programmatic'
23
+ type PopoverTriggerVariant = 'primary' | 'secondary' | 'ghost' | 'danger'
24
+ type PopoverTriggerSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
25
+
26
+ const FOCUSABLE =
27
+ 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]'
28
+
29
+ let popoverSeq = 0
30
+
31
+ function closeIcon() {
32
+ return h(
33
+ 'svg',
34
+ {
35
+ class: 'bw-icon',
36
+ viewBox: '0 0 24 24',
37
+ fill: 'none',
38
+ stroke: 'currentColor',
39
+ 'stroke-width': '2',
40
+ 'stroke-linecap': 'round',
41
+ 'stroke-linejoin': 'round',
42
+ 'aria-hidden': 'true',
43
+ },
44
+ [h('path', { d: 'M18 6 6 18' }), h('path', { d: 'm6 6 12 12' })],
45
+ )
46
+ }
47
+
48
+ /**
49
+ * Popover (docs/components/popover.md). Slots: `trigger`, the default (body)
50
+ * and `footer`. `v-model:open` carries the state (or leave it unbound for an
51
+ * uncontrolled popover). Escape with focus on the trigger or in the panel, and
52
+ * a press outside, close it; every close returns focus to the trigger only if
53
+ * it was inside the panel or on the trigger (POP-035). The panel needs a name:
54
+ * pass `title` or `aria-label` (POP-051).
55
+ */
56
+ export const Popover = defineComponent({
57
+ name: 'BwPopover',
58
+ inheritAttrs: false,
59
+ props: {
60
+ id: String,
61
+ placement: { type: String as PropType<PopoverPlacement>, default: 'bottom' },
62
+ title: String,
63
+ ariaLabel: String,
64
+ closable: { type: Boolean, default: false },
65
+ // POP-053 / POP-076: required when closable; no English default.
66
+ closeLabel: {
67
+ type: String,
68
+ default: undefined,
69
+ validator(value: unknown, props: { closable?: boolean }) {
70
+ if (!props.closable) return true
71
+ return typeof value === 'string' && value.trim().length > 0
72
+ },
73
+ },
74
+ triggerVariant: { type: String as PropType<PopoverTriggerVariant>, default: 'secondary' },
75
+ triggerSize: { type: String as PropType<PopoverTriggerSize>, default: 'md' },
76
+ triggerLabel: String,
77
+ open: { type: Boolean, default: undefined },
78
+ defaultOpen: { type: Boolean, default: false },
79
+ },
80
+ emits: ['update:open', 'open-change'],
81
+ setup(props, { attrs, emit, slots }) {
82
+ if (props.closable && !(typeof props.closeLabel === 'string' && props.closeLabel.trim())) {
83
+ throw new Error('BwPopover: closeLabel is required when closable is true (POP-053).')
84
+ }
85
+ popoverSeq += 1
86
+ const panelId = props.id ?? `bw-popover-v${popoverSeq}`
87
+ const titleId = `${panelId}-title`
88
+ const internal = ref(props.defaultOpen)
89
+ const isOpen = () => (props.open !== undefined ? props.open : internal.value)
90
+
91
+ const root = ref<HTMLElement | null>(null)
92
+ const trigger = ref<HTMLElement | null>(null)
93
+ const panel = ref<HTMLElement | null>(null)
94
+
95
+ function change(next: boolean, reason: PopoverCloseReason) {
96
+ if (props.open === undefined) internal.value = next
97
+ emit('update:open', next)
98
+ emit('open-change', next, reason)
99
+ }
100
+
101
+ // Every keyboard and trigger close routes through here (POP-035).
102
+ function close(reason: PopoverCloseReason) {
103
+ const active = document.activeElement
104
+ const restore = active === trigger.value || Boolean(panel.value?.contains(active))
105
+ if (restore && trigger.value?.isConnected) trigger.value.focus()
106
+ change(false, reason)
107
+ }
108
+
109
+ // POP-031: focus moves into the panel on open, not on first mount.
110
+ watch(
111
+ () => isOpen(),
112
+ async (open, wasOpen) => {
113
+ if (!open || wasOpen) return
114
+ await nextTick()
115
+ const el = panel.value
116
+ if (!el) return
117
+ const marked = el.querySelector<HTMLElement>('[data-bw-autofocus]')
118
+ const all = Array.from(el.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
119
+ (node) => !node.closest('[hidden]'),
120
+ )
121
+ const others = all.filter((node) => !node.classList.contains('bw-popover__close'))
122
+ const target = marked ?? others[0] ?? all[0] ?? el
123
+ target.focus()
124
+ },
125
+ )
126
+
127
+ // POP-033: a pointerdown outside the root closes it.
128
+ function onPointerDown(event: PointerEvent) {
129
+ if (!isOpen()) return
130
+ const el = root.value
131
+ if (!el || el.contains(event.target as Node)) return
132
+ // The press moves focus after this handler. Close without touching focus
133
+ // now; if focus was inside and the press left it nowhere, return it to
134
+ // the trigger once the press has settled.
135
+ const hadFocus = Boolean(panel.value?.contains(document.activeElement))
136
+ change(false, 'outside')
137
+ if (hadFocus) {
138
+ setTimeout(() => {
139
+ const now = document.activeElement
140
+ if ((!now || now === document.body) && trigger.value?.isConnected) trigger.value.focus()
141
+ }, 0)
142
+ }
143
+ }
144
+ onMounted(() => document.addEventListener('pointerdown', onPointerDown))
145
+ onBeforeUnmount(() => document.removeEventListener('pointerdown', onPointerDown))
146
+
147
+ // POP-032: Escape acts only with focus on the trigger or inside the panel,
148
+ // and stops propagation so an enclosing overlay does not also close.
149
+ function onKeydown(event: KeyboardEvent) {
150
+ if (event.key !== 'Escape' || !isOpen()) return
151
+ const active = document.activeElement
152
+ if (active !== trigger.value && !panel.value?.contains(active)) return
153
+ event.preventDefault()
154
+ event.stopPropagation()
155
+ close('escape')
156
+ }
157
+
158
+ function onPanelClick(event: MouseEvent) {
159
+ const control = (event.target as Element).closest('[data-bw-popover-close]')
160
+ if (control && panel.value?.contains(control)) close('close-button')
161
+ }
162
+
163
+ return () => {
164
+ const open = isOpen()
165
+ const named = props.title ? { 'aria-labelledby': titleId } : { 'aria-label': props.ariaLabel }
166
+ const variant = props.triggerVariant
167
+ return h(
168
+ 'div',
169
+ {
170
+ ...attrs,
171
+ ref: root,
172
+ class: cn(
173
+ 'bw-popover',
174
+ `bw-popover--${props.placement}`,
175
+ String(attrs.class || ''),
176
+ ),
177
+ ...(open ? { 'data-bw-open': '' } : {}),
178
+ onKeydown,
179
+ },
180
+ [
181
+ h(
182
+ 'button',
183
+ {
184
+ ref: trigger,
185
+ type: 'button',
186
+ class: cn(
187
+ 'bw-popover__trigger',
188
+ 'bw-btn',
189
+ `bw-btn--${variant}`,
190
+ `bw-btn--size-${props.triggerSize}`,
191
+ props.triggerLabel && 'bw-btn--icon-only',
192
+ ),
193
+ 'aria-haspopup': 'dialog',
194
+ 'aria-expanded': open ? 'true' : 'false',
195
+ 'aria-controls': panelId,
196
+ 'aria-label': props.triggerLabel,
197
+ onClick: () => (open ? close('trigger') : change(true, 'trigger')),
198
+ },
199
+ slots.trigger?.(),
200
+ ),
201
+ h(
202
+ 'div',
203
+ {
204
+ ref: panel,
205
+ id: panelId,
206
+ role: 'dialog',
207
+ ...named,
208
+ tabindex: -1,
209
+ hidden: !open,
210
+ class: 'bw-popover__panel',
211
+ onClick: onPanelClick,
212
+ },
213
+ [
214
+ props.title || props.closable
215
+ ? h('div', { class: 'bw-popover__header' }, [
216
+ props.title
217
+ ? h('h2', { class: 'bw-popover__title', id: titleId }, props.title)
218
+ : null,
219
+ props.closable
220
+ ? h(
221
+ 'button',
222
+ {
223
+ type: 'button',
224
+ class: 'bw-popover__close',
225
+ 'aria-label': props.closeLabel,
226
+ 'data-bw-popover-close': '',
227
+ },
228
+ [closeIcon()],
229
+ )
230
+ : null,
231
+ ])
232
+ : null,
233
+ h('div', { class: 'bw-popover__body' }, slots.default?.()),
234
+ slots.footer ? h('div', { class: 'bw-popover__footer' }, slots.footer()) : null,
235
+ ],
236
+ ),
237
+ ],
238
+ )
239
+ }
240
+ },
241
+ })