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

Unify prefix for custom elements #196

Merged
merged 2 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 6 additions & 12 deletions assets/js/Chat/ChatService.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { client } from '../Common/HttpClient.js'
import {client} from '../Common/HttpClient.js'

class ChatService
{
class ChatService {
/**
* @param {HttpClient} httpClient
*/
constructor(httpClient)
{
constructor(httpClient) {
this.httpClient = httpClient;
}

Expand All @@ -15,22 +13,18 @@ class ChatService
* @param {String} message
* @returns {Promise}
*/
writeMessage(chatId, message)
{
writeMessage(chatId, message) {
return this.httpClient.post(
'/api/chat/chats/' + chatId + '/write-message',
{
message: message
}
{message}
);
}

/**
* @param {String} chatId
* @returns {Promise}
*/
messages(chatId)
{
messages(chatId) {
return this.httpClient.get(
'/api/chat/chats/' + chatId + '/messages'
);
Expand Down
48 changes: 16 additions & 32 deletions assets/js/Chat/Widget.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { service } from './ChatService.js'
import {service} from './ChatService.js'

class WidgetElement extends HTMLElement
{
connectedCallback()
{
customElements.define('chat-widget', class extends HTMLElement {
connectedCallback() {
this._onDisconnect = [];

this.classList.add('loading-indicator');
Expand Down Expand Up @@ -33,16 +31,14 @@ class WidgetElement extends HTMLElement
this._registerEventHandler();
}

disconnectedCallback()
{
disconnectedCallback() {
this._onDisconnect.forEach(f => f());
}

/**
* @param {String} chatId
*/
_initialize(chatId)
{
_initialize(chatId) {
if (this._chatId === '') {
this._chatId = chatId;

Expand All @@ -53,8 +49,7 @@ class WidgetElement extends HTMLElement
/**
* @param {String} chatId
*/
_loadMessages(chatId)
{
_loadMessages(chatId) {
service.messages(chatId).then((messages) => {
messages.messages.forEach((message) => {
this._appendMessage(message);
Expand All @@ -76,8 +71,7 @@ class WidgetElement extends HTMLElement
/**
* @param {Object} message
*/
_appendMessage(message)
{
_appendMessage(message) {
if (!this._isDuplicate(message)) {
this._messageHolder.append(
this._createMessageNode(message)
Expand All @@ -91,13 +85,11 @@ class WidgetElement extends HTMLElement
* @param {Object} message
* @returns {Boolean}
*/
_isDuplicate(message)
{
_isDuplicate(message) {
return this._messageHolder.querySelector(['[data-id="' + message.messageId + '"]']) !== null;
}

_flushMessageBuffer()
{
_flushMessageBuffer() {
this._messageBuffer.forEach((message) => {
this._appendMessage(message);
});
Expand All @@ -109,8 +101,7 @@ class WidgetElement extends HTMLElement
* @param {Object} message
* @returns {Node}
*/
_createMessageNode(message)
{
_createMessageNode(message) {
let writtenAt = new Date(message.writtenAt);
let hours = ('0' + writtenAt.getHours()).slice(-2);
let minutes = ('0' + writtenAt.getMinutes()).slice(-2);
Expand All @@ -131,13 +122,11 @@ class WidgetElement extends HTMLElement
return li;
}

_clearInput()
{
_clearInput() {
this._input.value = '';
}

_onKeyPress(event)
{
_onKeyPress(event) {
if (event.which === 13 && !event.shiftKey) {
event.preventDefault();
let message = this._input.value;
Expand All @@ -153,8 +142,7 @@ class WidgetElement extends HTMLElement
}
}

_onMessageWritten(event)
{
_onMessageWritten(event) {
let message = event.detail;

if (!this._isAlreadyInitialized) {
Expand All @@ -164,15 +152,13 @@ class WidgetElement extends HTMLElement
}
}

_onChatAssigned(event)
{
_onChatAssigned(event) {
window.dispatchEvent(new CustomEvent('sse:addsubscription', {detail: {name: 'chat-' + event.detail.chatId}}));

this._initialize(event.detail.chatId);
}

_registerEventHandler()
{
_registerEventHandler() {
this._input.addEventListener('keypress', this._onKeyPress.bind(this));

((n, f) => {
Expand All @@ -185,6 +171,4 @@ class WidgetElement extends HTMLElement
this._onDisconnect.push(() => window.removeEventListener(n, f));
})('ConnectFour.ChatAssigned', this._onChatAssigned.bind(this));
}
}

customElements.define('chat-widget', WidgetElement);
});
22 changes: 7 additions & 15 deletions assets/js/Common/EventSource.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
class EventSourceElement extends HTMLElement
{
connectedCallback()
{
customElements.define('event-source', class extends HTMLElement {
connectedCallback() {
this._eventSource = null;
this._lastEventId = null;
this._subscriptions = this.getAttribute('subscriptions').split(',');
Expand All @@ -19,13 +17,11 @@ class EventSourceElement extends HTMLElement
})('app:load', this._connect.bind(this));
}

disconnectedCallback()
{
disconnectedCallback() {
this._onDisconnect.forEach(f => f());
}

_connect()
{
_connect() {
if (this._eventSource) this._eventSource.close();

let url = '/sse/sub?id=' + this._subscriptions.join(',');
Expand All @@ -35,8 +31,7 @@ class EventSourceElement extends HTMLElement
this._eventSource.onmessage = this._onMessage.bind(this);
}

_onMessage(message)
{
_onMessage(message) {
this._lastEventId = message.lastEventId;

let payload = JSON.parse(message.data);
Expand All @@ -48,13 +43,10 @@ class EventSourceElement extends HTMLElement
if (this._verbose) console.log(eventName, payload);
}

_onAddSubscription(event)
{
_onAddSubscription(event) {
if (this._subscriptions.indexOf(event.detail.name) !== -1) return;

this._subscriptions.push(event.detail.name);
this._connect();
}
}

customElements.define('event-source', EventSourceElement);
});
85 changes: 23 additions & 62 deletions assets/js/Common/HttpClient.js
Original file line number Diff line number Diff line change
@@ -1,89 +1,50 @@
class HttpClient
{
constructor()
{
class HttpClient {
constructor() {
this.onError = (response) => {

};
}

/**
* @param {String} url
* @returns {Promise}
*/
get(url)
{
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open('GET', url);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.addEventListener('load', () => {
let response = JSON.parse(request.responseText);

if (request.status >= 200 && request.status < 300) {
resolve(response);
} else {
this.onError(response);
reject(response);
}
});
request.send();
async get(url) {
const response = await fetch(url, {
headers: {'X-Requested-With': 'XMLHttpRequest'}
});
const json = await response.json();

if (response.status >= 200 && response.status < 300) return json;

this.onError(json);
throw json;
}

/**
* @param {String} url
* @param {Object} [postParameters]
* @param {Object} data
* @returns {Promise}
*/
post(url, postParameters)
{
postParameters = postParameters || {};
async post(url, data) {
const response = await fetch(url, {
method: 'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
body: new URLSearchParams(data)
});
const json = await response.json();

return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open('POST', url);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.addEventListener('load', () => {
let response = JSON.parse(request.responseText);
if (response.status >= 200 && response.status < 300) return json;

if (request.status >= 200 && request.status < 300) {
resolve(response);
} else {
this.onError(response);
reject(response);
}
});
request.send(
this._preparePostParameters(postParameters)
);
});
this.onError(json);
throw json;
}

/**
* @param {String} url
*/
redirectTo(url)
{
redirectTo(url) {
window.app.navigate(url);
}

/**
* @param {Object} postParameters
* @returns {String}
*/
_preparePostParameters(postParameters)
{
let preparedPostParameters = [];

for (let name in postParameters) {
let value = postParameters[name];
preparedPostParameters.push(name + '=' + encodeURIComponent(value));
}

return preparedPostParameters.join('&');
}
}

export const client = new HttpClient();
16 changes: 5 additions & 11 deletions assets/js/Common/NotificationList.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
class NotificationListElement extends HTMLElement
{
connectedCallback()
{
customElements.define('notification-list', class extends HTMLElement {
connectedCallback() {
this._ul = document.createElement('ul');
this._ul.classList.add('notification');

Expand All @@ -11,8 +9,7 @@ class NotificationListElement extends HTMLElement
/**
* @param {String} message
*/
appendMessage(message)
{
appendMessage(message) {
let messageNode = this._createMessageNode(message);

this._ul.insertBefore(messageNode, this._ul.childNodes[0]);
Expand All @@ -30,8 +27,7 @@ class NotificationListElement extends HTMLElement
* @param {String} message
* @returns {Node}
*/
_createMessageNode(message)
{
_createMessageNode(message) {
let smiley = document.createTextNode('¯\\_(ツ)_/¯');
let br = document.createElement('br');
let text = document.createTextNode(message);
Expand All @@ -45,6 +41,4 @@ class NotificationListElement extends HTMLElement

return li;
}
}

customElements.define('notification-list', NotificationListElement);
});
Loading
Loading