-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathClasses.kt
51 lines (44 loc) · 1.64 KB
/
Classes.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlinx.dom
import org.w3c.dom.*
/** Returns true if the element has the given CSS class style in its 'class' attribute */
@SinceKotlin("1.4")
public fun Element.hasClass(cssClass: String): Boolean = className.matches("""(^|.*\s+)$cssClass($|\s+.*)""".toRegex())
/**
* Adds CSS class to element. Has no effect if all specified classes are already in class attribute of the element
*
* @return true if at least one class has been added
*/
@SinceKotlin("1.4")
public fun Element.addClass(vararg cssClasses: String): Boolean {
val missingClasses = cssClasses.filterNot { hasClass(it) }
if (missingClasses.isNotEmpty()) {
val presentClasses = className.trim()
className = buildString {
append(presentClasses)
if (!presentClasses.isEmpty()) {
append(" ")
}
missingClasses.joinTo(this, " ")
}
return true
}
return false
}
/**
* Removes all [cssClasses] from element. Has no effect if all specified classes are missing in class attribute of the element
*
* @return true if at least one class has been removed
*/
@SinceKotlin("1.4")
public fun Element.removeClass(vararg cssClasses: String): Boolean {
if (cssClasses.any { hasClass(it) }) {
val toBeRemoved = cssClasses.toSet()
className = className.trim().split("\\s+".toRegex()).filter { it !in toBeRemoved }.joinToString(" ")
return true
}
return false
}