@neovici/cosmoz-autocomplete 6.0.0 → 6.2.0

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.
@@ -0,0 +1,16 @@
1
+ import '@neovici/cosmoz-input';
2
+ import { Props as Base, RProps } from './use-autocomplete';
3
+ export interface Props<I> extends Base<I> {
4
+ invalid?: boolean;
5
+ errorMessage?: string;
6
+ label?: string;
7
+ placeholder?: string;
8
+ noLabelFloat?: boolean;
9
+ alwaysFloatLabel?: boolean;
10
+ showSingle?: boolean;
11
+ itemHeight?: number;
12
+ itemLimit?: number;
13
+ }
14
+ type AProps<I> = Omit<Props<I>, keyof RProps<I>> & RProps<I>;
15
+ declare const autocomplete: <I>(props: AProps<I>) => import("lit-html").TemplateResult<1>, Autocomplete: <I>(props: Props<I>) => import("lit-html").TemplateResult<1>, observedAttributes: string[];
16
+ export { autocomplete, Autocomplete, observedAttributes };
@@ -0,0 +1,79 @@
1
+ import { html, nothing } from 'lit-html'; // eslint-disable-line object-curly-newline
2
+ import { live } from 'lit-html/directives/live.js';
3
+ import { until } from 'lit-html/directives/until.js';
4
+ import { when } from 'lit-html/directives/when.js';
5
+ import { useCallback } from 'haunted';
6
+ import { useHost } from '@neovici/cosmoz-utils/hooks/use-host';
7
+ import '@neovici/cosmoz-input';
8
+ import { useAutocomplete } from './use-autocomplete';
9
+ import { listbox } from '../listbox';
10
+ import style from './styles.css';
11
+ import { selection } from './selection';
12
+ const blank = () => nothing;
13
+ const inputParts = ['input', 'label', 'line', 'error']
14
+ .map((part) => `${part}: input-${part}`)
15
+ .join();
16
+ const autocomplete = (props) => {
17
+ const { invalid, errorMessage, label, placeholder, disabled, noLabelFloat, alwaysFloatLabel, textual, text, onText, onFocus, onClick, onDeselect, value, limit, showSingle, items$, values$, } = props, host = useHost(), isOne = limit == 1, // eslint-disable-line eqeqeq
18
+ isSingle = isOne && value?.[0] != null,
19
+ // TODO: Refactor with ref or a state callback
20
+ anchor = useCallback(() => host.shadowRoot.querySelector('#input'), [host, value]), suggestions = until(items$.then((items) => when((!isSingle || showSingle) && items.length, () => listbox({
21
+ ...props,
22
+ anchor,
23
+ items,
24
+ multi: !isOne,
25
+ }))));
26
+ return html ` <style>
27
+ ${style}
28
+ </style>
29
+ <cosmoz-input
30
+ id="input"
31
+ part="input"
32
+ .label=${label}
33
+ .placeholder=${isSingle ? undefined : placeholder}
34
+ ?no-label-float=${noLabelFloat}
35
+ ?always-float-label=${isSingle || alwaysFloatLabel}
36
+ ?readonly=${isSingle}
37
+ ?disabled=${disabled}
38
+ ?invalid=${until(values$.then(() => invalid, () => true), invalid)}
39
+ .errorMessage=${until(values$.then(() => errorMessage, (e) => e.message), errorMessage)}
40
+ .value=${live(text)}
41
+ @value-changed=${onText}
42
+ @focusin=${onFocus}
43
+ @focusout=${onFocus}
44
+ @click=${onClick}
45
+ autocomplete="off"
46
+ exportparts=${inputParts}
47
+ >
48
+ <slot name="prefix" slot="prefix"></slot>
49
+ <slot name="suffix" slot="suffix"></slot>
50
+ ${selection({
51
+ value,
52
+ isOne,
53
+ onDeselect,
54
+ textual,
55
+ disabled,
56
+ })}
57
+ ${until(values$.then(blank, blank), html `<div slot="suffix" class="spinner"></div>`)}
58
+ </cosmoz-input>
59
+
60
+ ${suggestions}`;
61
+ }, Autocomplete = (props) => autocomplete({
62
+ ...props,
63
+ ...useAutocomplete(props),
64
+ }), observedAttributes = [
65
+ 'disabled',
66
+ 'invalid',
67
+ 'no-label-float',
68
+ 'always-float-label',
69
+ 'text-property',
70
+ 'limit',
71
+ 'show-single',
72
+ 'keep-query',
73
+ 'keep-opened',
74
+ 'hide-empty',
75
+ 'default-index',
76
+ 'item-height',
77
+ 'item-limit',
78
+ ];
79
+ export { autocomplete, Autocomplete, observedAttributes };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { component, useCallback } from 'haunted';
2
+ import { Autocomplete, observedAttributes as atts, } from './autocomplete';
3
+ const Standalone = (host) => {
4
+ const { onChange, onText, ...props } = host;
5
+ return Autocomplete({
6
+ ...props,
7
+ onChange: useCallback((value, ...args) => {
8
+ host.value = value;
9
+ onChange?.(value, ...args);
10
+ }, [onChange]),
11
+ onText: useCallback((text) => {
12
+ host.text = text;
13
+ onText?.(text);
14
+ }, [onText]),
15
+ });
16
+ };
17
+ const observedAttributes = atts;
18
+ customElements.define('cosmoz-autocomplete-ui', component(Autocomplete, { observedAttributes }));
19
+ customElements.define('cosmoz-autocomplete', component(Standalone, { observedAttributes }));
@@ -0,0 +1,11 @@
1
+ import type { RProps } from './use-autocomplete';
2
+ type Deselect<I> = RProps<I>['onDeselect'];
3
+ interface Props<I> {
4
+ value: I[];
5
+ isOne: boolean;
6
+ onDeselect: Deselect<I>;
7
+ textual: (i: I) => string;
8
+ disabled?: boolean;
9
+ }
10
+ export declare const selection: <I>({ value, isOne, onDeselect, textual, disabled, }: Props<I>) => import("lit-html").TemplateResult<1> | undefined;
11
+ export {};
@@ -0,0 +1,58 @@
1
+ import { html } from 'lit-html'; // eslint-disable-line object-curly-newline
2
+ import { when } from 'lit-html/directives/when.js';
3
+ const clear = html `
4
+ <svg
5
+ width="9"
6
+ height="8"
7
+ viewBox="0 0 9 8"
8
+ fill="none"
9
+ xmlns="http://www.w3.org/2000/svg"
10
+ >
11
+ <line
12
+ x1="7.53033"
13
+ y1="0.994808"
14
+ x2="1.16637"
15
+ y2="7.35877"
16
+ stroke-width="1.5"
17
+ />
18
+ <line
19
+ x1="7.46967"
20
+ y1="7.35882"
21
+ x2="1.10571"
22
+ y2="0.99486"
23
+ stroke-width="1.5"
24
+ />
25
+ </svg>
26
+ `;
27
+ const chip = ({ text, onClear, disabled, isOne, }) => html `
28
+ <div class="chip" part="chip" slot="suffix" title=${text} ?data-one=${isOne}>
29
+ <span class="chip-text" part="chip-text">${text}</span>
30
+ ${when(!disabled, () => html ` <span class="chip-clear" part="chip-clear" @click=${onClear}>
31
+ ${clear}
32
+ </span>`)}
33
+ </div>
34
+ `;
35
+ const badge = ({ value, onDeselect, }) => {
36
+ const len = value?.length;
37
+ return when(len > 0, () => html `<div class="badge" slot="suffix" part="badge">
38
+ ${len}
39
+ <span
40
+ class="badge-clear"
41
+ part="chip-clear"
42
+ @click=${() => onDeselect(value)}
43
+ >${clear}</span
44
+ >
45
+ </div>`);
46
+ };
47
+ export const selection = ({ value, isOne, onDeselect, textual, disabled, }) => {
48
+ if (isOne || value.length === 1) {
49
+ const val = value[0];
50
+ return when(val, () => chip({
51
+ text: textual(val),
52
+ onClear: () => onDeselect(val),
53
+ disabled,
54
+ isOne,
55
+ }));
56
+ }
57
+ return badge({ value, onDeselect });
58
+ };
@@ -0,0 +1,2 @@
1
+ declare const _default: string;
2
+ export default _default;
@@ -0,0 +1,107 @@
1
+ import { tagged as css } from '@neovici/cosmoz-utils';
2
+ export default css `
3
+ :host {
4
+ display: block;
5
+ position: relative;
6
+ }
7
+ .chip {
8
+ border-radius: var(--cosmoz-autocomplete-chip-border-radius, 500px);
9
+ background: var(--cosmoz-autocomplete-chip-bg-color, #cbcfdb);
10
+ margin: 1px 4px 1px 0;
11
+ white-space: nowrap;
12
+ overflow: hidden;
13
+ display: flex;
14
+ flex-direction: row;
15
+ align-items: center;
16
+ flex: 0.00001 1 min-content;
17
+ max-width: 285px;
18
+ max-width: 28ch;
19
+ }
20
+ .chip[data-one] {
21
+ position: absolute;
22
+ left: 0;
23
+ top: 1px;
24
+ bottom: 1px;
25
+ right: 0;
26
+ margin: 0;
27
+ z-index: 2;
28
+ pointer-events: auto;
29
+ max-width: initial;
30
+ }
31
+ .chip-text {
32
+ color: var(--cosmoz-autocomplete-chip-color, #424242);
33
+ margin: var(--cosmoz-autocomplete-chip-text-margin, 0 10px);
34
+ font-size: var(--cosmoz-autocomplete-chip-text-font-size, 12px);
35
+ line-height: var(--cosmoz-autocomplete-chip-text-line-height, 22px);
36
+ overflow: hidden;
37
+ text-overflow: ellipsis;
38
+ flex: 1;
39
+ }
40
+ .chip-clear {
41
+ margin: 2px 4px 2px -6px;
42
+ background-color: var(--cosmoz-autocomplete-chip-clear-bg-color, #81899b);
43
+ border-radius: 500px;
44
+ cursor: pointer;
45
+ width: 16px;
46
+ height: 16px;
47
+ stroke: var(
48
+ --cosmoz-autocomplete-chip-clear-stroke,
49
+ var(--cosmoz-autocomplete-chip-bg-color, #cbcfdb)
50
+ );
51
+ display: block;
52
+ }
53
+
54
+ .chip-clear svg,
55
+ .badge-clear svg {
56
+ display: block;
57
+ transform: translate(3.5px, 3.5px);
58
+ }
59
+
60
+ .badge {
61
+ background: var(--cosmoz-autocomplete-chip-bg-color, #cbcfdb);
62
+ color: var(--cosmoz-autocomplete-chip-color, #424242);
63
+ font-weight: 500;
64
+ font-size: 12px;
65
+ line-height: 22px;
66
+ padding: 0 4px 0 6px;
67
+ gap: 4px;
68
+ border-radius: 90px;
69
+ text-align: center;
70
+ box-sizing: border-box;
71
+ /* fallback for unsupported min-content FF, Safari */
72
+ flex: 0.01 2 30px;
73
+ flex: 0 2 min-content;
74
+ display: flex;
75
+ align-items: center;
76
+ }
77
+ .badge-clear {
78
+ background-color: var(--cosmoz-autocomplete-chip-clear-bg-color, #81899b);
79
+ border-radius: 500px;
80
+ cursor: pointer;
81
+ width: 16px;
82
+ height: 16px;
83
+ stroke: var(--cosmoz-autocomplete-chip-bg-color, #cbcfdb);
84
+ display: block;
85
+ }
86
+
87
+ slot {
88
+ display: contents !important;
89
+ }
90
+
91
+ @keyframes rotating {
92
+ 100% {
93
+ transform: rotate(360deg);
94
+ }
95
+ }
96
+ .spinner {
97
+ border-radius: 50%;
98
+ width: 22px;
99
+ height: 22px;
100
+ border: 2px solid rgba(0, 0, 0, 0.1);
101
+ border-top: 2px solid #5f5a92;
102
+ animation: rotating 1.2s infinite cubic-bezier(0.785, 0.135, 0.15, 0.86);
103
+ box-sizing: border-box;
104
+ margin-top: -3px;
105
+ flex: none;
106
+ }
107
+ `;
@@ -0,0 +1,41 @@
1
+ type Source<I> = (opts: {
2
+ query: string;
3
+ active?: boolean;
4
+ }) => PromiseLike<I[]>;
5
+ interface Base<I> {
6
+ value: I | I[];
7
+ limit?: number;
8
+ keepQuery?: boolean;
9
+ keepOpened?: boolean;
10
+ onText: (text: string) => void;
11
+ onChange: (value: I[], done?: () => void) => void;
12
+ onSelect: (value: I, meta: Meta<I>) => void;
13
+ }
14
+ interface Meta<I> extends Omit<Base<I>, 'value'> {
15
+ setClosed: (closed: boolean) => void;
16
+ value: I[];
17
+ }
18
+ export interface Props<I> extends Base<I> {
19
+ text: string;
20
+ source: I[] | Source<I>;
21
+ textProperty?: string;
22
+ valueProperty?: string;
23
+ external?: boolean;
24
+ hideEmpty?: boolean;
25
+ disabled?: boolean;
26
+ onFocus?: (focused?: boolean) => void;
27
+ }
28
+ export declare const useAutocomplete: <I>({ value: _value, text, onChange: _onChange, onText: _onText, onSelect, limit, source, textProperty, valueProperty, external, hideEmpty, keepQuery, keepOpened, ...thru }: Props<I>) => {
29
+ query: string;
30
+ textual: <O>(o: O) => string;
31
+ value: I[];
32
+ values$: Promise<I[]>;
33
+ items$: Promise<I[]>;
34
+ onClick: () => void;
35
+ onFocus: (e: FocusEvent) => void;
36
+ onText: (e: InputEvent) => void;
37
+ onSelect: (newVal: I) => void;
38
+ onDeselect: (val: I | I[]) => void;
39
+ };
40
+ export type RProps<I> = ReturnType<typeof useAutocomplete<I>>;
41
+ export {};
@@ -0,0 +1,74 @@
1
+ import { useCallback, useMemo } from 'haunted';
2
+ import { without, array } from '@neovici/cosmoz-utils/array';
3
+ import { prop, strProp } from '@neovici/cosmoz-utils/object';
4
+ import { useHost } from '@neovici/cosmoz-utils/hooks/use-host';
5
+ import { useMeta } from '@neovici/cosmoz-utils/hooks/use-meta';
6
+ import { useFocus } from '@neovici/cosmoz-dropdown/use-focus';
7
+ import { useKeys } from './use-keys';
8
+ import { search, notify, useNotify, EMPTY$ } from './util';
9
+ export const useAutocomplete = ({ value: _value, text, onChange: _onChange, onText: _onText, onSelect, limit, source, textProperty, valueProperty, external, hideEmpty, keepQuery, keepOpened, ...thru }) => {
10
+ const textual = useMemo(() => strProp(textProperty), [textProperty]), { active, onFocus, setClosed } = useFocus(thru), empty = !text, query = useMemo(() => text?.trim().toLowerCase(), [text]), host = useHost(), onText = useNotify(host, _onText, 'text'), onChange = useCallback((val) => {
11
+ _onChange?.(val, () => setClosed(true));
12
+ notify(host, 'value', val);
13
+ }, [_onChange]), source$ = useMemo(() => Promise.resolve(typeof source === 'function' ? source({ query, active }) : source), [source, active, query]), value = useMemo(() => array(_value), [_value]), values$ = useMemo(() => source$.then((source) => [
14
+ ...value,
15
+ ...without(value, prop(valueProperty))(source),
16
+ ]), [source$, value, valueProperty]);
17
+ useKeys({
18
+ active,
19
+ empty,
20
+ limit,
21
+ value,
22
+ hideEmpty,
23
+ onChange,
24
+ onText,
25
+ });
26
+ const meta = useMeta({
27
+ onText,
28
+ onChange,
29
+ value,
30
+ limit,
31
+ keepQuery,
32
+ keepOpened,
33
+ setClosed,
34
+ onSelect,
35
+ });
36
+ return {
37
+ query,
38
+ textual,
39
+ value,
40
+ values$,
41
+ items$: useMemo(() => {
42
+ if (!active || (hideEmpty && empty)) {
43
+ return EMPTY$;
44
+ }
45
+ return query && !external
46
+ ? values$.then((values) => search(values, query, textual))
47
+ : values$;
48
+ }, [values$, active, query, textual, external, hideEmpty, empty]),
49
+ onClick: useCallback(() => setClosed(false), []),
50
+ onFocus,
51
+ onText: useCallback((e) => {
52
+ onText(e.target.value);
53
+ setClosed(false);
54
+ }, [onText, text, setClosed]),
55
+ onSelect: useCallback((newVal) => {
56
+ const { onSelect } = meta;
57
+ if (onSelect) {
58
+ return onSelect(newVal, meta);
59
+ }
60
+ const { onChange, onText, limit, value: val, keepQuery, keepOpened, setClosed, } = meta;
61
+ if (!keepQuery) {
62
+ onText('');
63
+ }
64
+ if (!keepOpened) {
65
+ setClosed(true);
66
+ }
67
+ const value = array(val);
68
+ onChange((value.includes(newVal)
69
+ ? without(newVal)(value)
70
+ : [...value, newVal]).slice(-limit));
71
+ }, [meta]),
72
+ onDeselect: useCallback((val) => meta.onChange(without(val)(meta.value)), [meta]),
73
+ };
74
+ };
@@ -0,0 +1,10 @@
1
+ export interface Props<I> {
2
+ active?: boolean;
3
+ empty?: boolean;
4
+ hideEmpty?: boolean;
5
+ value: I | I[];
6
+ limit?: number;
7
+ onChange: (v: I[]) => void;
8
+ onText: (s: string) => void;
9
+ }
10
+ export declare const useKeys: <I>({ active, empty, ...info }: Props<I>) => void;
@@ -0,0 +1,29 @@
1
+ import { useEffect } from 'haunted';
2
+ import { array } from '@neovici/cosmoz-utils/array';
3
+ import { useMeta } from '@neovici/cosmoz-utils/hooks/use-meta';
4
+ export const useKeys = ({ active, empty, ...info }) => {
5
+ const enabled = active && empty, meta = useMeta(info);
6
+ useEffect(() => {
7
+ if (!enabled) {
8
+ return;
9
+ }
10
+ const handler = (e) => {
11
+ if (e.defaultPrevented) {
12
+ return;
13
+ }
14
+ const { key } = e, values = array(meta.value), isOne = meta.limit == 1; //eslint-disable-line eqeqeq
15
+ if (values.length > 0 &&
16
+ (key === 'Backspace' || (isOne && key.length === 1))) {
17
+ return meta.onChange(values.slice(0, -1));
18
+ }
19
+ else if (meta.hideEmpty &&
20
+ values.length < 1 &&
21
+ ['Up', 'ArrowUp', 'Down', 'ArrowDown'].includes(key)) {
22
+ meta.onText(' ');
23
+ e.preventDefault();
24
+ }
25
+ };
26
+ document.addEventListener('keydown', handler, true);
27
+ return () => document.removeEventListener('keydown', handler, true);
28
+ }, [enabled, meta]);
29
+ };
@@ -0,0 +1,4 @@
1
+ export declare const search: <I>(source: I[], query: string, textual: (i: I) => string) => I[];
2
+ export declare const notify: <T>(host: EventTarget, name: string, detail: T) => boolean;
3
+ export declare const useNotify: <V>(host: EventTarget, fn: ((v: V) => void) | undefined, name: string) => (val: V) => void;
4
+ export declare const EMPTY: never[], EMPTY$: Promise<never[]>;
@@ -0,0 +1,25 @@
1
+ import { useCallback } from 'haunted';
2
+ export const search = (source, query, textual) => {
3
+ const matches = [];
4
+ for (const item of source) {
5
+ const index = textual(item).toLowerCase().indexOf(query);
6
+ if (index < 0) {
7
+ continue;
8
+ }
9
+ matches.push({
10
+ item,
11
+ index,
12
+ });
13
+ }
14
+ return matches
15
+ .sort((a, b) => {
16
+ return a.index - b.index;
17
+ })
18
+ .map(({ item }) => item);
19
+ };
20
+ export const notify = (host, name, detail) => host.dispatchEvent(new CustomEvent(name, { detail }));
21
+ export const useNotify = (host, fn, name) => useCallback((val) => {
22
+ fn?.(val);
23
+ notify(host, name, val);
24
+ }, [fn]);
25
+ export const EMPTY = [], EMPTY$ = Promise.resolve(EMPTY);
@@ -0,0 +1 @@
1
+ import './autocomplete/';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import './autocomplete/';
@@ -0,0 +1,20 @@
1
+ import { Props } from './use-listbox';
2
+ export declare const listbox: <I>({ multi, ...thru }: Props<I> & {
3
+ multi?: boolean | undefined;
4
+ }) => import("lit-html/directive").DirectiveResult<{
5
+ new (_partInfo: import("lit-html/directive").PartInfo): {
6
+ _op?: import("lit-html").ChildPart | undefined;
7
+ _outlet?: HTMLElement | undefined;
8
+ _content?: unknown;
9
+ render(content: unknown, outlet?: HTMLElement | undefined): import("lit-html").TemplateResult<1>;
10
+ update(part: import("lit-html").Part, [content, outlet]: [unknown, (HTMLElement | undefined)?]): import("lit-html").TemplateResult<1>;
11
+ updateOutlet(outlet: HTMLElement, content: unknown): void;
12
+ clearOutlet(): void;
13
+ disconnected(): void;
14
+ reconnected(): void;
15
+ isConnected: boolean;
16
+ _$initialize(part: import("lit-html").Part, parent: import("lit-html").Disconnectable, attributeIndex: number | undefined): void;
17
+ setValue(value: unknown): void;
18
+ readonly _$isConnected: boolean;
19
+ };
20
+ }>;
@@ -0,0 +1,41 @@
1
+ import { html, component, useEffect, useRef, useMemo } from 'haunted';
2
+ import { ref } from 'lit-html/directives/ref.js';
3
+ import { virtualize, virtualizerRef, } from '@lit-labs/virtualizer/virtualize.js';
4
+ import { portal } from '@neovici/cosmoz-utils/directives/portal';
5
+ import { spreadProps } from '@neovici/cosmoz-utils/directives/spread-props';
6
+ import { props } from '@neovici/cosmoz-utils/object';
7
+ import { useListbox, properties } from './use-listbox';
8
+ import { styles } from './style.css';
9
+ const Listbox = (props) => {
10
+ const listRef = useRef(undefined);
11
+ const { position, items, renderItem, height, itemHeight } = useListbox(props);
12
+ useEffect(() => {
13
+ if (!position.scroll)
14
+ return;
15
+ const vl = listRef.current?.[virtualizerRef];
16
+ if (!vl?.['_layout'])
17
+ return;
18
+ vl.element(position.index)?.scrollIntoView({ block: 'nearest' });
19
+ }, [position]);
20
+ const layout = useMemo(() => ({
21
+ _itemSize: { height: itemHeight - 0.00001 },
22
+ }), [itemHeight]);
23
+ return html ` <style>
24
+ ${styles({ ...position, height, itemHeight })}
25
+ </style>
26
+ <div class="items" ${ref((el) => (listRef.current = el))}>
27
+ <div virtualizer-sizer></div>
28
+ ${virtualize({
29
+ items,
30
+ renderItem,
31
+ scroller: true,
32
+ layout,
33
+ })}
34
+ </div>`;
35
+ };
36
+ customElements.define('cosmoz-listbox', component(Listbox));
37
+ export const listbox = ({ multi, ...thru }) => portal(html `<cosmoz-listbox
38
+ part="listbox"
39
+ ?multi=${multi}
40
+ ...=${spreadProps(props(properties)(thru))}
41
+ ></cosmoz-listbox>`);
@@ -0,0 +1,25 @@
1
+ import { TemplateResult } from 'lit-html';
2
+ export interface Opts<I> {
3
+ highlight: (i: number) => void;
4
+ select: (item: I) => void;
5
+ isSelected: (item: I) => void;
6
+ query: string;
7
+ textual: (i: I) => string;
8
+ }
9
+ export type Render<I> = (content: unknown, item: I, i: number) => unknown;
10
+ export type ItemRenderer<I> = (item: I, i: number, opts: Opts<I>) => TemplateResult;
11
+ export declare const itemRenderer: <I>(render?: Render<I>) => (item: I, i: number, { highlight, select, textual, query, isSelected, }: {
12
+ highlight: (i: number) => void;
13
+ select: (item: I) => void;
14
+ isSelected: (item: I) => void;
15
+ query: string;
16
+ textual: (i: I) => string;
17
+ }) => TemplateResult;
18
+ declare const _default: (item: unknown, i: number, { highlight, select, textual, query, isSelected, }: {
19
+ highlight: (i: number) => void;
20
+ select: (item: unknown) => void;
21
+ isSelected: (item: unknown) => void;
22
+ query: string;
23
+ textual: (i: unknown) => string;
24
+ }) => TemplateResult;
25
+ export default _default;
@@ -0,0 +1,21 @@
1
+ import { html } from 'lit-html';
2
+ import { identity } from '@neovici/cosmoz-utils/function';
3
+ import { mark } from './util';
4
+ export const itemRenderer = (render = identity) => (item, i, { highlight, select, textual = identity, query, isSelected, }) => {
5
+ const text = textual(item), content = mark(text, query), rendered = render(content, item, i);
6
+ return html ` <div
7
+ class="item"
8
+ role="option"
9
+ part="option"
10
+ ?aria-selected=${isSelected(item)}
11
+ data-index=${i}
12
+ @mouseenter=${() => highlight(i)}
13
+ @click=${() => select(item)}
14
+ @mousedown=${(e) => e.preventDefault()}
15
+ title=${text}
16
+ >
17
+ ${rendered}
18
+ </div>
19
+ <div class="sizer" virtualizer-sizer>${rendered}</div>`;
20
+ };
21
+ export default itemRenderer();
@@ -0,0 +1,7 @@
1
+ declare const style: string;
2
+ export default style;
3
+ export declare const styles: ({ index, height, itemHeight, }: {
4
+ index?: number | undefined;
5
+ height: number;
6
+ itemHeight: number;
7
+ }) => string;
@@ -0,0 +1,104 @@
1
+ import { tagged as css } from '@neovici/cosmoz-utils';
2
+ const svg =
3
+ /* eslint-disable quotes */
4
+ "data:image/svg+xml,%3Csvg width='11' height='8' viewBox='0 0 11 8' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath " +
5
+ "d='M9.5 1L5.20039 7.04766L1.66348 3.46152' stroke='white' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E";
6
+ /* eslint-enable quotes */
7
+ const style = css `
8
+ :host {
9
+ position: fixed;
10
+ z-index: 1000;
11
+ font-family: var(--paper-font-subhead_-_font-family, initial);
12
+ background: #fff;
13
+ min-width: 72px;
14
+ box-shadow: 0 3px 4px 0 rgba(0, 0, 0, 0.14), 0 1px 8px 0 rgba(0, 0, 0, 0.12),
15
+ 0 3px 3px -2px rgba(0, 0, 0, 0.4);
16
+ }
17
+ .items {
18
+ position: relative;
19
+ overflow-y: auto;
20
+ contain: layout paint !important;
21
+ height: 100%;
22
+ }
23
+ .item {
24
+ font-size: 14px;
25
+ padding: 0 20px;
26
+ box-sizing: border-box;
27
+ width: 100%;
28
+ cursor: pointer;
29
+ text-overflow: ellipsis;
30
+ white-space: nowrap;
31
+ transition: background 0.2s;
32
+ color: var(--cosmoz-listbox-color, #101010);
33
+ }
34
+
35
+ .sizer {
36
+ position: relative;
37
+ visibility: hidden;
38
+ opacity: 0;
39
+ pointer-events: none;
40
+ z-index: -1;
41
+ height: 0;
42
+ width: auto;
43
+ padding: 0 20px;
44
+ overflow: hidden;
45
+ max-width: inherit;
46
+ font-size: 14px;
47
+ }
48
+
49
+ :host(:not([multi])) .item[aria-selected] {
50
+ background: var(--cosmoz-listbox-single-selection-color, #dadada);
51
+ }
52
+
53
+ :host([multi]) .item {
54
+ padding-left: 0;
55
+ }
56
+ :host([multi]) .item::before {
57
+ content: '';
58
+ font-size: 0;
59
+ padding: 7.5px;
60
+ margin: 0 8px;
61
+ background: #fff;
62
+ border: 1px solid #d6d6d5;
63
+ border-radius: 4px;
64
+ vertical-align: top;
65
+ }
66
+ :host([multi]) .item[aria-selected]::before {
67
+ border-color: #5881f6;
68
+ /* prettier-ignore */
69
+ background: url("${svg}") #5881f6 no-repeat 50%;
70
+ }
71
+ :host([multi]) .sizer {
72
+ padding-left: 33px;
73
+ }
74
+ .swatch {
75
+ width: 18px;
76
+ height: 18px;
77
+ display: inline-block;
78
+ box-sizing: border-box;
79
+ vertical-align: middle;
80
+ border-radius: 50%;
81
+ border: 2px solid #eee;
82
+ }
83
+ `;
84
+ export default style;
85
+ export const styles = ({ index, height, itemHeight, }) => css `
86
+ ${style}
87
+
88
+ :host {
89
+ min-height: ${itemHeight}px;
90
+ height: ${height}px;
91
+ }
92
+
93
+ .item {
94
+ line-height: ${itemHeight}px;
95
+ height: ${itemHeight}px;
96
+ }
97
+
98
+ .item[data-index='${index || '0'}'] {
99
+ background: var(
100
+ --cosmoz-listbox-active-color,
101
+ var(--cosmoz-selection-color, rgba(58, 145, 226, 0.1))
102
+ );
103
+ }
104
+ `;
@@ -0,0 +1,14 @@
1
+ export interface UseItems<T> {
2
+ items: T[];
3
+ onSelect: (item: T, index?: number) => void;
4
+ defaultIndex?: number;
5
+ }
6
+ export interface Position {
7
+ index: number;
8
+ scroll?: boolean;
9
+ }
10
+ export declare const useItems: <T>({ items, onSelect, defaultIndex, }: UseItems<T>) => {
11
+ position: Position;
12
+ highlight: (index: number) => void;
13
+ select: (item: T) => void;
14
+ };
@@ -0,0 +1,26 @@
1
+ import { useCallback, useEffect, useState } from 'haunted';
2
+ import { useKeyboard } from './use-keyboard';
3
+ export const useItems = ({ items, onSelect, defaultIndex = 0, }) => {
4
+ const [position, setPosition] = useState({
5
+ index: defaultIndex,
6
+ }), { index } = position, { length } = items;
7
+ useEffect(() => {
8
+ setPosition({ index: defaultIndex, scroll: true });
9
+ }, [items, defaultIndex]);
10
+ useKeyboard({
11
+ onUp: useCallback(() => setPosition((p) => ({
12
+ index: p.index > 0 ? p.index - 1 : length - 1,
13
+ scroll: true,
14
+ })), [length]),
15
+ onDown: useCallback(() => setPosition((p) => ({
16
+ index: p.index < length - 1 ? p.index + 1 : 0,
17
+ scroll: true,
18
+ })), [length]),
19
+ onEnter: useCallback(() => index > -1 && index < length && onSelect?.(items[index], index), [index, items, onSelect]),
20
+ });
21
+ return {
22
+ position,
23
+ highlight: useCallback((index) => setPosition({ index }), []),
24
+ select: useCallback((item) => onSelect?.(item), [onSelect]),
25
+ };
26
+ };
@@ -0,0 +1,8 @@
1
+ type Handler = () => void;
2
+ export interface Handlers {
3
+ onUp: Handler;
4
+ onDown: Handler;
5
+ onEnter: Handler;
6
+ }
7
+ export declare const useKeyboard: (handlers: Handlers) => void;
8
+ export {};
@@ -0,0 +1,32 @@
1
+ import { useEffect } from 'haunted';
2
+ import { useMeta } from '@neovici/cosmoz-utils/hooks/use-meta';
3
+ export const useKeyboard = (handlers) => {
4
+ const listeners = useMeta(handlers);
5
+ useEffect(() => {
6
+ const handler = (e) => {
7
+ if ((e.ctrlKey && e.altKey) || e.defaultPrevented) {
8
+ return;
9
+ }
10
+ switch (e.key) {
11
+ case 'Up':
12
+ case 'ArrowUp':
13
+ e.preventDefault();
14
+ listeners.onUp();
15
+ break;
16
+ case 'Down':
17
+ case 'ArrowDown':
18
+ e.preventDefault();
19
+ listeners.onDown();
20
+ break;
21
+ case 'Enter':
22
+ e.preventDefault();
23
+ listeners.onEnter();
24
+ break;
25
+ default:
26
+ break;
27
+ }
28
+ };
29
+ document.addEventListener('keydown', handler, true);
30
+ return () => document.removeEventListener('keydown', handler, true);
31
+ }, [listeners]);
32
+ };
@@ -0,0 +1,28 @@
1
+ import { Placement } from '@neovici/cosmoz-dropdown/use-position';
2
+ import { useRenderItem, ItemRenderer } from './use-render-item';
3
+ export declare const properties: string[];
4
+ export interface Props<I> {
5
+ value: I | I[];
6
+ valueProperty?: string;
7
+ items: I[];
8
+ onSelect: (i: I) => void;
9
+ defaultIndex?: number;
10
+ query: string;
11
+ textual: (i: I) => string;
12
+ itemRenderer?: ItemRenderer<I>;
13
+ itemHeight?: number;
14
+ itemLimit?: number;
15
+ anchor?: () => HTMLElement | null;
16
+ confinement?: HTMLElement;
17
+ placement?: Placement;
18
+ }
19
+ export declare const useListbox: <I>({ value, valueProperty, items: _items, onSelect, defaultIndex, query, textual, itemRenderer, itemHeight, itemLimit, ...thru }: Props<I>) => {
20
+ position: import("./use-items").Position;
21
+ items: I[];
22
+ height: number;
23
+ highlight: (index: number) => void;
24
+ select: (item: I) => void;
25
+ itemHeight: number;
26
+ renderItem: (item: I, i: number) => import("lit-html").TemplateResult;
27
+ };
28
+ export { useRenderItem };
@@ -0,0 +1,54 @@
1
+ import { useMemo } from 'haunted';
2
+ import { useHost } from '@neovici/cosmoz-utils/hooks/use-host';
3
+ import { usePosition } from '@neovici/cosmoz-dropdown/use-position';
4
+ import { byValue } from './util';
5
+ import { useItems } from './use-items';
6
+ import { useRenderItem } from './use-render-item';
7
+ export const properties = [
8
+ 'query',
9
+ 'items',
10
+ 'onSelect',
11
+ 'textual',
12
+ 'anchor',
13
+ 'confinement',
14
+ 'placement',
15
+ 'itemHeight',
16
+ 'itemLimit',
17
+ 'itemRenderer',
18
+ 'defaultIndex',
19
+ 'value',
20
+ 'valueProperty',
21
+ ];
22
+ export const useListbox = ({ value, valueProperty, items: _items, onSelect, defaultIndex, query, textual, itemRenderer, itemHeight = 40, itemLimit = 5, ...thru }) => {
23
+ const isSelected = useMemo(() => byValue(value, valueProperty), [value, valueProperty]),
24
+ // TODO: investigate if we can drop this
25
+ items = useMemo(() => _items.slice(), [_items, isSelected]), { position, highlight, select } = useItems({
26
+ items,
27
+ onSelect,
28
+ defaultIndex: isNaN(defaultIndex)
29
+ ? undefined
30
+ : Number(defaultIndex),
31
+ });
32
+ usePosition({
33
+ host: useHost(),
34
+ ...thru,
35
+ limit: true,
36
+ });
37
+ return {
38
+ position,
39
+ items,
40
+ height: Math.min(itemLimit, items.length) * itemHeight,
41
+ highlight,
42
+ select,
43
+ itemHeight,
44
+ renderItem: useRenderItem({
45
+ itemRenderer,
46
+ highlight,
47
+ select,
48
+ textual,
49
+ query,
50
+ isSelected,
51
+ }),
52
+ };
53
+ };
54
+ export { useRenderItem };
@@ -0,0 +1,5 @@
1
+ import { ItemRenderer, Opts } from './item-renderer';
2
+ export declare const useRenderItem: <I>({ itemRenderer, ...meta }: Opts<I> & {
3
+ itemRenderer?: ItemRenderer<I> | undefined;
4
+ }) => (item: I, i: number) => import("lit-html").TemplateResult;
5
+ export type { ItemRenderer };
@@ -0,0 +1,7 @@
1
+ import { useCallback } from 'haunted';
2
+ import { useMeta } from '@neovici/cosmoz-utils/hooks/use-meta';
3
+ import { itemRenderer as mkItemRenderer, } from './item-renderer';
4
+ export const useRenderItem = ({ itemRenderer = mkItemRenderer(), ...meta }) => {
5
+ const info = useMeta(meta);
6
+ return useCallback((item, i) => itemRenderer(item, i, info), [info, itemRenderer]);
7
+ };
@@ -0,0 +1,2 @@
1
+ export declare const byValue: <K extends PropertyKey | undefined, T>(value: T | T[], valueProperty: K) => ((item: T) => boolean) | ((item: T) => T | undefined);
2
+ export declare const mark: (text: string, query: string) => string | (string | import("lit-html").TemplateResult<1>)[];
@@ -0,0 +1,24 @@
1
+ import { html } from 'lit-html';
2
+ import { array } from '@neovici/cosmoz-utils/array';
3
+ export const byValue = (value, valueProperty) => {
4
+ if (!valueProperty) {
5
+ return (item) => array(value).includes(item);
6
+ }
7
+ return (item) => array(value).find((value) => value[valueProperty] ===
8
+ item[valueProperty]);
9
+ };
10
+ export const mark = (text, query) => {
11
+ if (!query || !text) {
12
+ return text;
13
+ }
14
+ const i = text.toLowerCase().indexOf(query.toLowerCase());
15
+ if (i < 0) {
16
+ return text;
17
+ }
18
+ const end = i + query.length;
19
+ return [
20
+ text.slice(0, i),
21
+ html `<mark>${text.slice(i, end)}</mark>`,
22
+ text.slice(end),
23
+ ];
24
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neovici/cosmoz-autocomplete",
3
- "version": "6.0.0",
3
+ "version": "6.2.0",
4
4
  "description": "A autocomplete input web component",
5
5
  "keywords": [
6
6
  "lit-html",
@@ -67,7 +67,7 @@
67
67
  "./item-renderer": "./dist/listbox/item-renderer.js"
68
68
  },
69
69
  "dependencies": {
70
- "@lit-labs/virtualizer": "^1.0.0",
70
+ "@lit-labs/virtualizer": "^2.0.0",
71
71
  "@neovici/cosmoz-dropdown": "^3.0.0",
72
72
  "@neovici/cosmoz-input": "^3.0.0",
73
73
  "@neovici/cosmoz-utils": "^5.0.0",
@@ -85,8 +85,8 @@
85
85
  "@web/dev-server-storybook": "^0.6.0",
86
86
  "eslint-import-resolver-exports": "^1.0.0-beta.5",
87
87
  "husky": "^8.0.0",
88
- "semantic-release": "^20.0.0",
88
+ "semantic-release": "^21.0.0",
89
89
  "sinon": "^15.0.0",
90
- "typescript": "^4.6.0"
90
+ "typescript": "^5.0.0"
91
91
  }
92
92
  }