UNPKG

2.2 kBPlain TextView Raw
1// Copyright (c) Jupyter Development Team.
2// Distributed under the terms of the Modified BSD License.
3
4import { Text } from '@jupyterlab/coreutils';
5
6/**
7 * Inner works of class combining functions
8 */
9function _classes(
10 classes: (string | false | undefined | null | { [className: string]: any })[]
11): string[] {
12 return classes
13 .map(c =>
14 c && typeof c === 'object'
15 ? Object.keys(c).map(key => !!c[key] && key)
16 : typeof c === 'string'
17 ? c.split(/\s+/)
18 : []
19 )
20 .reduce((flattened, c) => flattened.concat(c), [] as string[])
21 .filter(c => !!c) as string[];
22}
23
24/**
25 * Combines classNames.
26 *
27 * @param classes - A list of classNames
28 *
29 * @returns A single string with the combined className
30 */
31export function classes(
32 ...classes: (
33 | string
34 | false
35 | undefined
36 | null
37 | { [className: string]: any }
38 )[]
39): string {
40 return _classes(classes).join(' ');
41}
42
43/**
44 * Combines classNames. Removes all duplicates
45 *
46 * @param classes - A list of classNames
47 *
48 * @returns A single string with the combined className
49 */
50export function classesDedupe(
51 ...classes: (
52 | string
53 | false
54 | undefined
55 | null
56 | { [className: string]: any }
57 )[]
58): string {
59 return [...new Set(_classes(classes))].join(' ');
60}
61
62/**
63 * Translates the attributes of a DOM element into attributes that can
64 * be understood by React. Currently not comprehensive, we will add special
65 * cases as they become relevant.
66 *
67 * @param elem - A DOM element
68 *
69 * @param ignore - An optional list of attribute names to ignore
70 *
71 * @returns An object with key:value pairs that are the React-friendly
72 * translation of elem's attributes
73 */
74export function getReactAttrs(
75 elem: Element,
76 { ignore = [] }: { ignore?: string[] } = {}
77): { [key: string]: string | null } {
78 return elem
79 .getAttributeNames()
80 .reduce<{ [key: string]: string | null }>((d, name) => {
81 if (name === 'style' || ignore.includes(name)) {
82 void 0;
83 } else if (name.startsWith('data')) {
84 d[name] = elem.getAttribute(name);
85 } else {
86 d[Text.camelCase(name)] = elem.getAttribute(name);
87 }
88 return d;
89 }, {});
90}
91
\No newline at end of file