Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provides a short access to document elements by ID via delegated #126

Merged
merged 1 commit into from
Jan 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/jsMain/kotlin/dom-js.kt
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,41 @@ private val Node.ownerDocumentExt: Document
this is Document -> this
else -> ownerDocument ?: throw IllegalStateException("Node has no ownerDocument")
}


/**
* Provides a short access to document elements by ID via delegated
* property syntax. Received element is not cached and received
* directly from the [Document] by calling [Document.getElementById]
* function on every property access. Throws an exception if element
* is not found or has different type
*
* To access an element with `theId` ID use the following property declaration
* ```
* val theId by document.gettingElementById
* ```
*
* To access an element of specific type, just add it to the property declaration
* ```
* val theId: HTMLImageElement by document.gettingElementById
* ```
*/
inline val Document.gettingElementById get() = DocumentGettingElementById(this)

/**
* Implementation details of [Document.gettingElementById]
* @see Document.gettingElementById
*/
inline class DocumentGettingElementById(val document: Document) {
/**
* Implementation details of [Document.gettingElementById]. Delegated property
* @see Document.gettingElementById
*/
inline operator fun <reified T : Element> getValue(x: Any?, kProperty: KProperty<*>): T {
val id = kProperty.name
val element = document.getElementById(id) ?: throw NullPointerException("Element $id is not found")
return element as? T ?: throw ClassCastException(
"Element $id has type ${element::class.simpleName} which does not implement ${T::class.simpleName}"
)
}
}