Simplify Current JS implementation
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { current } from "helpers"
|
||||
|
||||
export default class extends Controller {
|
||||
static classes = [ "myComment" ]
|
||||
@@ -9,6 +8,6 @@ export default class extends Controller {
|
||||
}
|
||||
|
||||
get #myComments() {
|
||||
return this.element.querySelectorAll(`.comment[data-creator-id='${current.user.id}']`)
|
||||
return this.element.querySelectorAll(`.comment[data-creator-id='${Current.user.id}']`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
// On-demand JavaScript objects from "current" HTML <meta> elements. Example:
|
||||
//
|
||||
// <meta name="current-identity-id" content="123">
|
||||
// <meta name="current-identity-time-zone-name" content="Central Time (US & Canada)">
|
||||
//
|
||||
// >> current.identity
|
||||
// => { id: "123", timeZoneName: "Central Time (US & Canada)" }
|
||||
//
|
||||
// >> current.foo
|
||||
// => {}
|
||||
export const current = new Proxy({}, {
|
||||
get(_target, propertyName) {
|
||||
const result = {}
|
||||
const prefix = `current-${propertyName}-`
|
||||
for (const { name, content } of document.head.querySelectorAll(`meta[name^=${prefix}]`)) {
|
||||
const key = camelize(name.slice(prefix.length))
|
||||
result[key] = content
|
||||
}
|
||||
return result
|
||||
}
|
||||
})
|
||||
|
||||
function camelize(string) {
|
||||
return string.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase())
|
||||
}
|
||||
@@ -1,2 +1 @@
|
||||
export * from "helpers/current_helpers"
|
||||
export * from "helpers/timing_helpers"
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
class Current {
|
||||
get user() {
|
||||
const currentUserId = this.#extractContentFromMetaTag("current-user-id")
|
||||
|
||||
if (currentUserId) {
|
||||
return { id: parseInt(currentUserId) }
|
||||
}
|
||||
}
|
||||
|
||||
#extractContentFromMetaTag(name) {
|
||||
return document.head.querySelector(`meta[name="${name}"]`)?.getAttribute("content")
|
||||
}
|
||||
}
|
||||
|
||||
window.Current = new Current()
|
||||
@@ -1 +1,2 @@
|
||||
import "initializers/current"
|
||||
import "initializers/local_time"
|
||||
|
||||
Reference in New Issue
Block a user