Reapply "Merge pull request !2870 from rhodecode-enterprise-ce Polymer-lit-migration-1"

This reverts commit 2aebe6862d.
This commit is contained in:
Andrii V 2025-12-01 18:06:16 +01:00
parent 2aebe6862d
commit 7971df8a49
18 changed files with 3386 additions and 2323 deletions

View file

@ -4,10 +4,9 @@
"env",
{
"targets": {
"browsers": [
"last 2 versions"
]
}
"esmodules": true
},
"exclude": ["transform-es2015-classes"]
}
]
],

View file

@ -13,10 +13,10 @@ module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-terser');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-webpack');
grunt.registerTask('default', ['less:production', 'less:components', 'copy', 'webpack', 'concat:dist', 'uglify:dist']);
grunt.registerTask('default', ['less:production', 'less:components', 'copy', 'webpack', 'concat:dist', 'terser:dist']);
};

View file

@ -667,13 +667,14 @@ search.location = %(here)s/data/index
channelstream.enabled = true
; server address for channelstream server on the backend
channelstream.server = channelstream:9800
channelstream.server = channelstream:8000
; location of the channelstream server from outside world
; use ws:// for http or wss:// for https. This address needs to be handled
; by external HTTP server such as Nginx or Apache
; see Nginx/Apache configuration examples in our docs
channelstream.ws_url = ws://rhodecode.yourserver.com/_channelstream
; For development, comment this out to use auto-generated proxy URL
;channelstream.ws_url = ws://rhodecode.yourserver.com/_channelstream
channelstream.secret = ENV_GENERATED
channelstream.history.location = /var/opt/rhodecode_data/channelstream_history

View file

@ -629,7 +629,7 @@ search.location = %(here)s/data/index
channelstream.enabled = true
; server address for channelstream server on the backend
channelstream.server = channelstream:9800
channelstream.server = channelstream:8000
; location of the channelstream server from outside world
; use ws:// for http or wss:// for https. This address needs to be handled

View file

@ -52,10 +52,12 @@ Supported Databases
Supported Browsers
------------------
* Chrome
* Safari
* Firefox
* Internet Explorer 10 & 11
* Chrome 67+
* Firefox 63+
* Safari 11.1+
* Edge 79+
Note: Internet Explorer is no longer supported
System Requirements
-------------------

View file

@ -102,10 +102,23 @@
"nonull": true
}
},
"uglify": {
"terser": {
"dist": {
"src": "<%= dirs.js.dest %>/scripts.js",
"dest": "<%= dirs.js.dest %>/scripts.min.js"
"options": {
"compress": {
"ecma": 6
},
"mangle": {
"keep_classnames": true,
"keep_fnames": false
},
"output": {
"ecma": 6
}
},
"files": {
"<%= dirs.js.dest %>/scripts.min.js": "<%= dirs.js.dest %>/scripts.js"
}
}
},
"less": {
@ -156,7 +169,6 @@
"tasks": [
"less:development",
"less:components",
"concat:polymercss",
"webpack",
"concat:dist"
]
@ -169,7 +181,6 @@
],
"tasks": [
"less:components",
"concat:polymercss",
"webpack",
"concat:dist"
]

3880
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -21,6 +21,8 @@
"@webcomponents/webcomponentsjs": "^2.0.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.2",
"babel-plugin-syntax-class-properties": "^6.13.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.0",
"clipboard": "^2.0.1",
@ -35,7 +37,7 @@
"grunt-contrib-copy": "^1.0.0",
"grunt-contrib-jshint": "^0.12.0",
"grunt-contrib-less": "^1.1.0",
"grunt-contrib-uglify": "^4.0.1",
"grunt-terser": "^1.0.0",
"grunt-contrib-watch": "^0.6.1",
"grunt-webpack": "^3.1.3",
"html-loader": "^0.4.4",
@ -57,5 +59,9 @@
"webpack": "4.23.1",
"webpack-cli": "3.1.2",
"webpack-uglify-js-plugin": "^1.1.9"
},
"dependencies": {
"lit": "^2.8.0",
"regenerator-runtime": "^0.13.9"
}
}

View file

@ -1,577 +1,446 @@
import {Polymer, html} from '@polymer/polymer/polymer-legacy';
import '@polymer/iron-ajax/iron-ajax.js';
import {LitElement} from 'lit';
const elemTemplate = html`
<iron-ajax
id="ajaxConnect"
url=""
handle-as="json"
method="post"
content-type="application/json"
loading="{{loadingConnect}}"
last-response="{{connectLastResponse}}"
on-response="_handleConnect"
on-error="_handleConnectError"
debounce-duration="100"></iron-ajax>
<iron-ajax
id="ajaxDisconnect"
url=""
handle-as="json"
method="post"
content-type="application/json"
loading="{{loadingDisconnect}}"
last-response="{{_disconnectLastResponse}}"
on-response="_handleDisconnect"
debounce-duration="100"></iron-ajax>
<iron-ajax
id="ajaxSubscribe"
url=""
handle-as="json"
method="post"
content-type="application/json"
loading="{{loadingSubscribe}}"
last-response="{{subscribeLastResponse}}"
on-response="_handleSubscribe"
debounce-duration="100"></iron-ajax>
<iron-ajax
id="ajaxUnsubscribe"
url=""
handle-as="json"
method="post"
content-type="application/json"
loading="{{loadingUnsubscribe}}"
last-response="{{unsubscribeLastResponse}}"
on-response="_handleUnsubscribe"
debounce-duration="100"></iron-ajax>
<iron-ajax
id="ajaxMessage"
url=""
handle-as="json"
method="post"
content-type="application/json"
loading="{{loadingMessage}}"
last-response="{{messageLastResponse}}"
on-response="_handleMessage"
on-error="_handleMessageError"
debounce-duration="100"></iron-ajax>
<iron-ajax
id="ajaxListen"
url=""
handle-as="text"
loading="{{loadingListen}}"
last-response="{{listenLastResponse}}"
on-request="_handleListenOpen"
on-error="_handleListenError"
on-response="_handleListenMessageEvent"
debounce-duration="100"></iron-ajax>
`
Polymer({
is: 'channelstream-connection',
_template: elemTemplate,
/**
* Fired when `channels` array changes.
*
* @event channelstream-channels-changed
/**
* Simplified Lit version of channelstream-connection
* Replaces iron-ajax with native fetch()
*/
export class ChannelstreamConnection extends LitElement {
static properties = {
channels: {type: Array},
username: {type: String},
connectionId: {type: String},
websocket: {type: Object},
websocketUrl: {type: String},
connectUrl: {type: String},
disconnectUrl: {type: String},
subscribeUrl: {type: String},
unsubscribeUrl: {type: String},
messageUrl: {type: String},
longPollUrl: {type: String},
shouldReconnect: {type: Boolean},
heartbeats: {type: Boolean},
increaseBounceIv: {type: Number},
_currentBounceIv: {type: Number},
useWebsocket: {type: Boolean},
connected: {type: Boolean},
channelsState: {type: Object},
userState: {type: Object}
};
/**
* Fired when `connect()` method succeeds.
*
* @event channelstream-connected
*/
constructor() {
super();
this.channels = [];
this.username = 'Anonymous';
this.connectionId = '';
this.websocket = null;
this.websocketUrl = '';
this.connectUrl = '';
this.disconnectUrl = '';
this.subscribeUrl = '';
this.unsubscribeUrl = '';
this.messageUrl = '';
this.longPollUrl = '';
this.shouldReconnect = true;
this.heartbeats = true;
this.increaseBounceIv = 2000;
this._currentBounceIv = 0;
this.useWebsocket = true;
this.connected = false;
this.channelsState = {};
this.userState = {};
/**
* Fired when `connect` fails.
*
* @event channelstream-connect-error
*/
// Mutators - simplified to just arrays
this.mutators = {
connect: [],
message: [],
subscribe: [],
unsubscribe: [],
disconnect: []
};
/**
* Fired when `disconnect()` succeeds.
*
* @event channelstream-disconnected
*/
/**
* Fired when `message()` succeeds.
*
* @event channelstream-message-sent
*/
/**
* Fired when `message()` fails.
*
* @event channelstream-message-error
*/
/**
* Fired when `subscribe()` succeeds.
*
* @event channelstream-subscribed
*/
/**
* Fired when `subscribe()` fails.
*
* @event channelstream-subscribe-error
*/
/**
* Fired when `unsubscribe()` succeeds.
*
* @event channelstream-unsubscribed
*/
/**
* Fired when `unsubscribe()` fails.
*
* @event channelstream-unsubscribe-error
*/
/**
* Fired when listening connection receives a message.
*
* @event channelstream-listen-message
*/
/**
* Fired when listening connection is opened.
*
* @event channelstream-listen-opened
*/
/**
* Fired when listening connection is closed.
*
* @event channelstream-listen-closed
*/
/**
* Fired when listening connection suffers an error.
*
* @event channelstream-listen-error
*/
properties: {
isReady: Boolean,
/** List of channels user should be subscribed to. */
channels: {
type: Array,
value: function () {
return []
},
notify: true
},
/** Username of connecting user. */
username: {
type: String,
value: 'Anonymous',
reflectToAttribute: true
},
/** Connection identifier. */
connectionId: {
type: String,
reflectToAttribute: true
},
/** Websocket instance. */
websocket: {
type: Object,
value: null
},
/** Websocket connection url. */
websocketUrl: {
type: String,
value: ''
},
/** URL used in `connect()`. */
connectUrl: {
type: String,
value: ''
},
/** URL used in `disconnect()`. */
disconnectUrl: {
type: String,
value: ''
},
/** URL used in `subscribe()`. */
subscribeUrl: {
type: String,
value: ''
},
/** URL used in `unsubscribe()`. */
unsubscribeUrl: {
type: String,
value: ''
},
/** URL used in `message()`. */
messageUrl: {
type: String,
value: ''
},
/** Long-polling connection url. */
longPollUrl: {
type: String,
value: ''
},
/** Long-polling connection url. */
shouldReconnect: {
type: Boolean,
value: true
},
/** Should send heartbeats. */
heartbeats: {
type: Boolean,
value: true
},
/** How much should every retry interval increase (in milliseconds) */
increaseBounceIv: {
type: Number,
value: 2000
},
_currentBounceIv: {
type: Number,
reflectToAttribute: true,
value: 0
},
/** Should use websockets or long-polling by default */
useWebsocket: {
type: Boolean,
reflectToAttribute: true,
value: true
},
connected: {
type: Boolean,
reflectToAttribute: true,
value: false
this._heartbeatInterval = null;
}
},
observers: [
'_handleChannelsChange(channels.splices)'
],
// No render needed - this component has no template
render() {
return null;
}
listeners: {
'channelstream-connected': 'startListening',
'channelstream-connect-error': 'retryConnection',
},
updated(changedProperties) {
if (changedProperties.has('channels')) {
this.dispatchEvent(new CustomEvent('channelstream-channels-changed', {
detail: {value: this.channels}
}));
}
}
connectedCallback() {
super.connectedCallback();
// Set up self-event listeners (replaces Polymer's 'listeners' property)
this.addEventListener('channelstream-connected', this.startListening.bind(this));
this.addEventListener('channelstream-connect-error', this.retryConnection.bind(this));
}
/**
* Mutators hold functions that you can set locally to change the data
* that the client is sending to all endpoints
* you can call it like `elem.mutators('connect', yourFunc())`
* mutators will be executed in order they were pushed onto arrays
*
* Helper method for fetch requests
*/
mutators: {
connect: function () {
return []
}(),
message: function () {
return []
}(),
subscribe: function () {
return []
}(),
unsubscribe: function () {
return []
}(),
disconnect: function () {
return []
}()
},
ready: function () {
this.isReady = true;
async _fetchJSON(url, options = {}) {
const {body, headers, ...fetchOptions} = options;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers
},
body: body ? JSON.stringify(body) : undefined,
...fetchOptions
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
}
/**
* Connects user and fetches connection id from the server.
*
* Connects user and fetches connection id from the server
*/
connect: function () {
var request = this.$['ajaxConnect'];
request.url = this.connectUrl;
request.body = {
async connect() {
const body = {
username: this.username,
channels: this.channels
};
for (var i = 0; i < this.mutators.connect.length; i++) {
this.mutators.connect[i](request);
// Apply mutators
for (let mutator of this.mutators.connect) {
mutator({body});
}
request.generateRequest()
},
try {
const response = await this._fetchJSON(this.connectUrl, {body});
this._handleConnect({detail: {response}});
} catch (error) {
this._handleConnectError({detail: {error}});
}
}
/**
* Overwrite with custom function that will
* Subscribes user to channels
*/
addMutator: function (type, func) {
this.mutators[type].push(func);
},
/**
* Subscribes user to channels.
*
*/
subscribe: function (channels) {
var request = this.$['ajaxSubscribe'];
request.url = this.subscribeUrl;
request.body = {
async subscribe(channels) {
const body = {
channels: channels,
conn_id: this.connectionId
};
for (var i = 0; i < this.mutators.subscribe.length; i++) {
this.mutators.subscribe[i](request);
}
if (request.body.channels.length) {
request.generateRequest();
}
},
/**
* Unsubscribes user from channels.
*
*/
unsubscribe: function (unsubscribe) {
var request = this.$['ajaxUnsubscribe'];
request.url = this.unsubscribeUrl;
request.body = {
channels: unsubscribe,
// Apply mutators
for (let mutator of this.mutators.subscribe) {
mutator({body});
}
if (body.channels.length) {
try {
const response = await this._fetchJSON(this.subscribeUrl, {body});
this._handleSubscribe({detail: {response}});
} catch (error) {
this.dispatchEvent(new CustomEvent('channelstream-subscribe-error', {detail: error}));
}
}
}
/**
* Unsubscribes user from channels
*/
async unsubscribe(channels) {
const body = {
channels: channels,
conn_id: this.connectionId
};
for (var i = 0; i < this.mutators.unsubscribe.length; i++) {
this.mutators.unsubscribe[i](request);
// Apply mutators
for (let mutator of this.mutators.unsubscribe) {
mutator({body});
}
try {
const response = await this._fetchJSON(this.unsubscribeUrl, {body});
this._handleUnsubscribe({detail: {response}});
} catch (error) {
this.dispatchEvent(new CustomEvent('channelstream-unsubscribe-error', {detail: error}));
}
}
request.generateRequest()
},
/**
* calculates list of channels we should add user to based on difference
* between channels property and passed channel list
* Calculates list of channels to add user to
*/
calculateSubscribe: function (channels) {
var currentlySubscribed = this.channels;
var toSubscribe = [];
for (var i = 0; i < channels.length; i++) {
calculateSubscribe(channels) {
const currentlySubscribed = this.channels;
const toSubscribe = [];
for (let i = 0; i < channels.length; i++) {
if (currentlySubscribed.indexOf(channels[i]) === -1) {
toSubscribe.push(channels[i]);
}
}
return toSubscribe
},
return toSubscribe;
}
/**
* calculates list of channels we should remove user from based difference
* between channels property and passed channel list
* Calculates list of channels to remove user from
*/
calculateUnsubscribe: function (channels) {
var currentlySubscribed = this.channels;
var toUnsubscribe = [];
for (var i = 0; i < channels.length; i++) {
calculateUnsubscribe(channels) {
const currentlySubscribed = this.channels;
const toUnsubscribe = [];
for (let i = 0; i < channels.length; i++) {
if (currentlySubscribed.indexOf(channels[i]) !== -1) {
toUnsubscribe.push(channels[i]);
}
}
return toUnsubscribe
},
/**
* Marks the connection as expired.
*
*/
disconnect: function () {
var request = this.$['ajaxDisconnect'];
request.url = this.disconnectUrl;
request.params = {
conn_id: this.connectionId
};
for (var i = 0; i < this.mutators.disconnect.length; i++) {
this.mutators.disconnect[i](request);
return toUnsubscribe;
}
// mark connection as expired
request.generateRequest();
// disconnect existing connection
this.closeConnection();
},
/**
* Sends a message to the server.
*
* Marks the connection as expired
*/
message: function (message) {
var request = this.$['ajaxMessage'];
request.url = this.messageUrl;
request.body = message;
for (var i = 0; i < this.mutators.message.length; i++) {
this.mutators.message[i](request)
async disconnect() {
const params = new URLSearchParams({conn_id: this.connectionId});
// Apply mutators
for (let mutator of this.mutators.disconnect) {
mutator({params});
}
request.generateRequest();
},
try {
const response = await fetch(`${this.disconnectUrl}?${params}`);
const data = await response.json();
this._handleDisconnect({detail: {response: data}});
} catch (error) {
console.error('Disconnect error:', error);
}
// Disconnect existing connection
this.closeConnection();
}
/**
* Opens "long lived" (websocket/longpoll) connection to the channelstream server.
*
* Sends a message to the server
*/
startListening: function (event) {
this.fire('start-listening', {});
async message(messageData) {
const body = messageData;
// Apply mutators
for (let mutator of this.mutators.message) {
mutator({body});
}
try {
const response = await this._fetchJSON(this.messageUrl, {body});
this._handleMessage({detail: {response}});
} catch (error) {
this._handleMessageError({detail: {error}});
}
}
/**
* Opens long lived connection (websocket/longpoll)
*/
startListening(event) {
this.dispatchEvent(new CustomEvent('start-listening', {detail: {}}));
if (this.useWebsocket) {
this.useWebsocket = window.WebSocket ? true : false;
}
if (this.useWebsocket) {
this.openWebsocket();
}
else {
} else {
this.openLongPoll();
}
},
}
/**
* Opens websocket connection.
*
* Opens websocket connection
*/
openWebsocket: function () {
var url = this.websocketUrl + '?conn_id=' + this.connectionId;
openWebsocket() {
const url = this.websocketUrl + '?conn_id=' + this.connectionId;
this.websocket = new WebSocket(url);
this.websocket.onopen = this._handleListenOpen.bind(this);
this.websocket.onclose = this._handleListenCloseEvent.bind(this);
this.websocket.onerror = this._handleListenErrorEvent.bind(this);
this.websocket.onmessage = this._handleListenMessageEvent.bind(this);
},
}
/**
* Opens long-poll connection.
*
* Opens long-poll connection
*/
openLongPoll: function () {
var request = this.$['ajaxListen'];
request.url = this.longPollUrl + '?conn_id=' + this.connectionId;
request.generateRequest()
},
async openLongPoll() {
const url = this.longPollUrl + '?conn_id=' + this.connectionId;
try {
this._handleListenOpen();
const response = await fetch(url);
const text = await response.text();
this._handleListenMessageEvent({data: text});
} catch (error) {
this._handleListenError({detail: {error}});
}
}
/**
* Retries `connect()` call while incrementing interval between tries up to 1 minute.
*
* Retries connect() call with increasing interval
*/
retryConnection: function () {
retryConnection() {
if (!this.shouldReconnect) {
return;
}
if (this._currentBounceIv < 60000) {
this._currentBounceIv = this._currentBounceIv + this.increaseBounceIv;
}
else {
} else {
this._currentBounceIv = 60000;
}
setTimeout(this.connect.bind(this), this._currentBounceIv);
},
}
/**
* Closes listening connection.
*
* Closes listening connection
*/
closeConnection: function () {
var request = this.$['ajaxListen'];
closeConnection() {
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
this.websocket.onclose = null;
this.websocket.onerror = null;
this.websocket.close();
}
if (request.loading) {
request.lastRequest.abort();
if (this._heartbeatInterval) {
clearInterval(this._heartbeatInterval);
this._heartbeatInterval = null;
}
this.connected = false;
},
_handleChannelsChange: function (event) {
// do not fire the event if set() didn't mutate anything
// is this a reliable way to do it?
if (!this.isReady || event === undefined) {
return
}
this.fire('channelstream-channels-changed', event)
},
_handleListenOpen: function (event) {
this.connected = true;
this.fire('channelstream-listen-opened', event);
this.createHeartBeats();
},
createHeartBeats: function () {
if (typeof self._heartbeat === 'undefined' && this.websocket !== null
&& this.heartbeats) {
self._heartbeat = setInterval(this._sendHeartBeat.bind(this), 10000);
/**
* Add mutator function
*/
addMutator(type, func) {
this.mutators[type].push(func);
}
},
_sendHeartBeat: function () {
if (this.websocket.readyState === WebSocket.OPEN && this.heartbeats) {
/**
* Create heartbeat interval
*/
createHeartBeats() {
if (!this._heartbeatInterval && this.websocket !== null && this.heartbeats) {
this._heartbeatInterval = setInterval(this._sendHeartBeat.bind(this), 10000);
}
}
/**
* Send heartbeat
*/
_sendHeartBeat() {
if (this.websocket && this.websocket.readyState === WebSocket.OPEN && this.heartbeats) {
this.websocket.send(JSON.stringify({type: 'heartbeat'}));
}
},
}
_handleListenError: function (event) {
// Event handlers
_handleListenOpen(event) {
this.connected = true;
this.dispatchEvent(new CustomEvent('channelstream-listen-opened', {detail: event}));
this.createHeartBeats();
}
_handleListenError(event) {
this.connected = false;
this.retryConnection();
},
_handleConnectError: function (event) {
this.connected = false;
this.fire('channelstream-connect-error', event.detail);
},
}
_handleListenMessageEvent: function (event) {
var data = null;
// comes from iron-ajax
if (event.detail) {
data = JSON.parse(event.detail.response)
// comes from websocket
_handleConnectError(event) {
this.connected = false;
this.dispatchEvent(new CustomEvent('channelstream-connect-error', {detail: event.detail}));
}
_handleListenMessageEvent(event) {
let data = null;
// From long-poll (fetch)
if (event.detail && event.detail.response) {
data = JSON.parse(event.detail.response);
setTimeout(this.openLongPoll.bind(this), 0);
} else {
data = JSON.parse(event.data)
}
this.fire('channelstream-listen-message', data);
// From websocket
else if (event.data) {
data = JSON.parse(event.data);
}
},
if (data) {
this.dispatchEvent(new CustomEvent('channelstream-listen-message', {detail: data}));
}
}
_handleListenCloseEvent: function (event) {
_handleListenCloseEvent(event) {
this.connected = false;
this.fire('channelstream-listen-closed', event.detail);
this.dispatchEvent(new CustomEvent('channelstream-listen-closed', {detail: event}));
this.retryConnection();
},
_handleListenErrorEvent: function (event) {
this.connected = false;
this.fire('channelstream-listen-error', {})
},
_handleConnect: function (event) {
this.currentBounceIv = 0;
this.connectionId = event.detail.response.conn_id;
this.fire('channelstream-connected', event.detail.response);
},
_handleDisconnect: function (event) {
this.connected = false;
this.fire('channelstream-disconnected', {});
},
_handleMessage: function (event) {
this.fire('channelstream-message-sent', event.detail.response);
},
_handleMessageError: function (event) {
this.fire('channelstream-message-error', event.detail);
},
_handleSubscribe: function (event) {
this.fire('channelstream-subscribed', event.detail.response);
},
_handleSubscribeError: function (event) {
this.fire('channelstream-subscribe-error', event.detail);
},
_handleUnsubscribe: function (event) {
this.fire('channelstream-unsubscribed', event.detail.response);
},
_handleUnsubscribeError: function (event) {
this.fire('channelstream-unsubscribe-error', event.detail);
}
});
_handleListenErrorEvent(event) {
this.connected = false;
this.dispatchEvent(new CustomEvent('channelstream-listen-error', {detail: {}}));
}
_handleConnect(event) {
this._currentBounceIv = 0;
this.connectionId = event.detail.response.conn_id;
this.dispatchEvent(new CustomEvent('channelstream-connected', {detail: event.detail.response}));
}
_handleDisconnect(event) {
this.connected = false;
this.dispatchEvent(new CustomEvent('channelstream-disconnected', {detail: {}}));
}
_handleMessage(event) {
this.dispatchEvent(new CustomEvent('channelstream-message-sent', {detail: event.detail.response}));
}
_handleMessageError(event) {
this.dispatchEvent(new CustomEvent('channelstream-message-error', {detail: event.detail}));
}
_handleSubscribe(event) {
this.dispatchEvent(new CustomEvent('channelstream-subscribed', {detail: event.detail.response}));
}
_handleUnsubscribe(event) {
this.dispatchEvent(new CustomEvent('channelstream-unsubscribed', {detail: event.detail.response}));
}
// Polymer compatibility methods - keep these for rhodecode-app
push(path, value) {
if (path === 'channels') {
this.channels = [...this.channels, value];
}
}
set(path, value) {
if (typeof path === 'string') {
this[path] = value;
this.requestUpdate(path);
} else if (Array.isArray(path)) {
// Handle nested paths like ['channelsState', key] or ['userState', key]
if (path.length === 2 && path[0] === 'channelsState') {
this.channelsState = {...this.channelsState, [path[1]]: value};
} else if (path.length === 2 && path[0] === 'userState') {
this.userState = {...this.userState, [path[1]]: value};
}
}
}
}
customElements.define('channelstream-connection', ChannelstreamConnection);

View file

@ -1,3 +1,4 @@
import 'regenerator-runtime/runtime.js';
import '@polymer/iron-ajax/iron-ajax.js';
import './shared-styles.js';
import './channelstream-connection/channelstream-connection.js';

View file

@ -1,51 +1,54 @@
import {PolymerElement, html} from '@polymer/polymer/polymer-element.js';
import '../channelstream-connection/channelstream-connection.js';
import '../rhodecode-toast/rhodecode-toast.js';
import '../rhodecode-favicon/rhodecode-favicon.js';
import { html, LitElement, css } from "lit";
var ccLog = Logger.get('RhodeCodeApp');
import "../channelstream-connection/channelstream-connection.js";
import "../rhodecode-toast/rhodecode-toast.js";
import "../rhodecode-favicon/rhodecode-favicon.js";
var ccLog = Logger.get("RhodeCodeApp");
ccLog.setLevel(Logger.OFF);
export class RhodecodeApp extends PolymerElement {
export class RhodecodeApp extends LitElement {
static get is() {
return 'rhodecode-app';
return "rhodecode-app";
}
static get template(){
render() {
return html`
<channelstream-connection
id="channelstream-connection"
on-channelstream-listen-message="receivedMessage"
on-channelstream-connected="handleConnected"
on-channelstream-subscribed="handleSubscribed">
@channelstream-listen-message="${this.receivedMessage}"
@channelstream-connected="${this.handleConnected}"
@channelstream-subscribed="${this.handleSubscribed}"
>
</channelstream-connection>
<rhodecode-favicon></rhodecode-favicon>
`
`;
}
connectedCallback() {
super.connectedCallback();
ccLog.debug('rhodeCodeApp created');
$.Topic('/notifications').subscribe(this.handleNotifications.bind(this));
$.Topic('/comment').subscribe(this.handleComment.bind(this));
$.Topic('/favicon/update').subscribe(this.faviconUpdate.bind(this));
$.Topic('/connection_controller/subscribe').subscribe(
this.subscribeToChannelTopic.bind(this)
ccLog.debug("rhodeCodeApp created");
$.Topic("/notifications").subscribe(this.handleNotifications.bind(this));
$.Topic("/comment").subscribe(this.handleComment.bind(this));
$.Topic("/favicon/update").subscribe(this.faviconUpdate.bind(this));
$.Topic("/connection_controller/subscribe").subscribe(
this.subscribeToChannelTopic.bind(this),
);
// this event can be used to coordinate plugins to do their
// initialization before channelstream is kicked off
$.Topic('/__MAIN_APP__').publish({});
$.Topic("/__MAIN_APP__").publish({});
for (var i = 0; i < alertMessagePayloads.length; i++) {
$.Topic('/notifications').publish(alertMessagePayloads[i]);
$.Topic("/notifications").publish(alertMessagePayloads[i]);
}
this.initPlugins();
// after rest of application loads and topics get fired, launch connection
$(document).ready(function () {
$(document).ready(
function () {
this.kickoffChannelstreamPlugin();
}.bind(this));
}.bind(this),
);
}
initPlugins() {
@ -54,7 +57,7 @@ export class RhodecodeApp extends PolymerElement {
if (pluginDef.component) {
var pluginElem = document.createElement(pluginDef.component);
this.shadowRoot.appendChild(pluginElem);
if (typeof pluginElem.init !== 'undefined') {
if (typeof pluginElem.init !== "undefined") {
pluginElem.init();
}
}
@ -63,39 +66,37 @@ export class RhodecodeApp extends PolymerElement {
/** proxy to channelstream connection */
getChannelStreamConnection() {
return this.$['channelstream-connection'];
return this.renderRoot.querySelector("#channelstream-connection");
}
handleNotifications(data) {
var elem = document.getElementById('notifications');
var elem = document.getElementById("notifications");
if (elem) {
elem.handleNotification(data);
}
}
handleComment(data) {
if (data.message.comment_data.length !== 0) {
if (window.refreshAllComments !== undefined) {
refreshAllComments()
refreshAllComments();
}
var json_data = data.message.comment_data;
if (window.commentsController !== undefined) {
window.commentsController.attachComment(json_data)
window.commentsController.attachComment(json_data);
}
}
}
faviconUpdate(data) {
this.shadowRoot.querySelector('rhodecode-favicon').counter = data.count;
this.shadowRoot.querySelector("rhodecode-favicon").counter = data.count;
}
/** opens connection to ws server */
kickoffChannelstreamPlugin(data) {
ccLog.debug('kickoffChannelstreamPlugin');
var channels = ['broadcast'];
ccLog.debug("kickoffChannelstreamPlugin");
var channels = ["broadcast"];
var addChannels = this.checkViewChannels();
for (var i = 0; i < addChannels.length; i++) {
channels.push(addChannels[i]);
@ -104,14 +105,17 @@ export class RhodecodeApp extends PolymerElement {
var channelstreamConnection = this.getChannelStreamConnection();
channelstreamConnection.connectUrl = CHANNELSTREAM_URLS.connect;
channelstreamConnection.subscribeUrl = CHANNELSTREAM_URLS.subscribe;
channelstreamConnection.websocketUrl = CHANNELSTREAM_URLS.ws + '/ws';
channelstreamConnection.longPollUrl = CHANNELSTREAM_URLS.longpoll + '/listen';
channelstreamConnection.websocketUrl = CHANNELSTREAM_URLS.ws + "/ws";
channelstreamConnection.longPollUrl =
CHANNELSTREAM_URLS.longpoll + "/listen";
channelstreamConnection.username =
window.templateContext.rhodecode_user.username;
// some channels might already be registered by topic
for (var i = 0; i < channels.length; i++) {
channelstreamConnection.push('channels', channels[i]);
channelstreamConnection.push("channels", channels[i]);
}
// append any additional channels registered in other plugins
$.Topic('/connection_controller/subscribe').processPrepared();
$.Topic("/connection_controller/subscribe").processPrepared();
channelstreamConnection.connect();
}
@ -123,13 +127,19 @@ export class RhodecodeApp extends PolymerElement {
var channels = [];
// subscribe to PR repo channel for PR's'
if (templateContext.pull_request_data.pull_request_id) {
var channelName = '/repo$' + templateContext.repo_name + '$/pr/' +
var channelName =
"/repo$" +
templateContext.repo_name +
"$/pr/" +
String(templateContext.pull_request_data.pull_request_id);
channels.push(channelName);
}
if (templateContext.commit_data.commit_id) {
var channelName = '/repo$' + templateContext.repo_name + '$/commit/' +
var channelName =
"/repo$" +
templateContext.repo_name +
"$/commit/" +
String(templateContext.commit_data.commit_id);
channels.push(channelName);
}
@ -141,7 +151,7 @@ export class RhodecodeApp extends PolymerElement {
subscribeToChannelTopic(channels) {
var channelstreamConnection = this.getChannelStreamConnection();
var toSubscribe = channelstreamConnection.calculateSubscribe(channels);
ccLog.debug('subscribeToChannelTopic', toSubscribe);
ccLog.debug("subscribeToChannelTopic", toSubscribe);
if (toSubscribe.length > 0) {
// if we are connected then subscribe
if (channelstreamConnection.connected) {
@ -150,7 +160,7 @@ export class RhodecodeApp extends PolymerElement {
// not connected? just push channels onto the stack
else {
for (var i = 0; i < toSubscribe.length; i++) {
channelstreamConnection.push('channels', toSubscribe[i]);
channelstreamConnection.push("channels", toSubscribe[i]);
}
}
}
@ -161,23 +171,21 @@ export class RhodecodeApp extends PolymerElement {
for (var i = 0; i < event.detail.length; i++) {
var message = event.detail[i];
if (message.message.topic) {
ccLog.debug('publishing', message.message.topic);
ccLog.debug("publishing", message.message.topic);
$.Topic(message.message.topic).publish(message);
}
else if (message.type === 'presence') {
$.Topic('/connection_controller/presence').publish(message);
}
else {
ccLog.warn('unhandled message', message);
} else if (message.type === "presence") {
$.Topic("/connection_controller/presence").publish(message);
} else {
ccLog.warn("unhandled message", message);
}
}
}
handleConnected(event) {
var channelstreamConnection = this.getChannelStreamConnection();
channelstreamConnection.set('channelsState', event.detail.channels_info);
channelstreamConnection.set('userState', event.detail.state);
channelstreamConnection.set('channels', event.detail.channels);
channelstreamConnection.set("channelsState", event.detail.channels_info);
channelstreamConnection.set("userState", event.detail.state);
channelstreamConnection.set("channels", event.detail.channels);
this.propagageChannelsState();
}
@ -187,9 +195,9 @@ export class RhodecodeApp extends PolymerElement {
var channelKeys = Object.keys(event.detail.channels_info);
for (var i = 0; i < channelKeys.length; i++) {
var key = channelKeys[i];
channelstreamConnection.set(['channelsState', key], channelInfo[key]);
channelstreamConnection.set(["channelsState", key], channelInfo[key]);
}
channelstreamConnection.set('channels', event.detail.channels);
channelstreamConnection.set("channels", event.detail.channels);
this.propagageChannelsState();
}
@ -200,12 +208,12 @@ export class RhodecodeApp extends PolymerElement {
var channels = channelstreamConnection.channels;
for (var i = 0; i < channels.length; i++) {
var key = channels[i];
$.Topic('/connection_controller/channel_update').publish(
{channel: key, state: channel_data[key]}
);
$.Topic("/connection_controller/channel_update").publish({
channel: key,
state: channel_data[key],
});
}
}
}
customElements.define(RhodecodeApp.is, RhodecodeApp);

View file

@ -1,19 +1,15 @@
import {PolymerElement, html} from '@polymer/polymer/polymer-element.js';
import {LitElement} from 'lit';
export class RhodecodeFavicon extends PolymerElement {
export class RhodecodeFavicon extends LitElement {
static properties = {
favicon: {type: Object},
counter: {type: Number}
};
static get is() {
return 'rhodecode-favicon';
}
static get properties() {
return {
favicon: Object,
counter: {
type: Number,
observer: '_handleCounter'
}
}
constructor() {
super();
this.favicon = null;
this.counter = 0;
}
connectedCallback() {
@ -24,10 +20,11 @@ export class RhodecodeFavicon extends PolymerElement {
});
}
_handleCounter(newVal, oldVal) {
updated(changedProperties) {
if (changedProperties.has('counter') && this.favicon) {
this.favicon.badge(this.counter);
}
}
}
customElements.define(RhodecodeFavicon.is, RhodecodeFavicon);
customElements.define('rhodecode-favicon', RhodecodeFavicon);

View file

@ -1,25 +1,9 @@
import {PolymerElement, html} from '@polymer/polymer/polymer-element.js';
import '@polymer/paper-toggle-button/paper-toggle-button.js';
import {mixinBehaviors} from '@polymer/polymer/lib/legacy/class.js';
import {IronA11yKeysBehavior} from '@polymer/iron-a11y-keys-behavior/iron-a11y-keys-behavior.js';
import {LitElement, html, css} from 'lit';
import {classMap} from 'lit/directives/class-map.js';
import '../rhodecode-unsafe-html/rhodecode-unsafe-html.js';
export class RhodecodeToast extends mixinBehaviors([IronA11yKeysBehavior], PolymerElement) {
static get is() {
return 'rhodecode-toast';
}
static get template(){
return html`
<style include="shared-styles">
/* inset border for buttons - does not work in ie */
/* rounded borders */
/* rounded borders - bottom only */
/* rounded borders - top only */
/* text shadow */
/* centers text in a circle - input diameter of circle and color */
/* pill version of the circle */
export class RhodecodeToast extends LitElement {
static styles = css`
.absolute-center {
margin: auto;
position: absolute;
@ -78,7 +62,34 @@ export class RhodecodeToast extends mixinBehaviors([IronA11yKeysBehavior], Polym
}
.alert {
clear: both;
padding: 15px;
margin: 10px 0;
border: 1px solid;
border-radius: 2px;
color: #7E7F7F;
border-color: #84a5d2;
background-color: #e6edf6;
}
.alert-success {
border-color: #0ac878;
background-color: #daf7eb;
}
.alert-error {
border-color: #e85e4d;
background-color: #fbdfdb;
}
.alert-warning {
border-color: #ffc854;
background-color: #fff4dd;
}
.alert-info {
border-color: #84a5d2;
background-color: #e6edf6;
}
.toast-close {
@ -101,131 +112,130 @@ export class RhodecodeToast extends mixinBehaviors([IronA11yKeysBehavior], Polym
right: 0;
z-index: 100;
}
</style>
`;
<template is="dom-if" if="[[hasToasts]]">
<div class$="container toast-message-holder [[conditionalClass(isFixed)]]">
<template is="dom-repeat" items="[[toasts]]">
<div class$="alert alert-[[item.level]]">
<div on-click="dismissNotification" class="toast-close" index-pos="[[index]]">
<span>[[_gettext('Close')]]</span>
</div>
<rhodecode-unsafe-html text="[[item.message]]"></rhodecode-unsafe-html>
</div>
</template>
</div>
</template>
`
static properties = {
toasts: {type: Array},
isFixed: {type: Boolean}
};
constructor() {
super();
this.toasts = [];
this.isFixed = false;
this._headerNode = null;
this._debouncedCalcBound = this._debouncedCalc.bind(this);
this._handleKeyupBound = this._handleKeyup.bind(this);
this._debounceTimeout = null;
}
static get properties() {
return {
toasts: {
type: Array,
value() {
return []
}
},
isFixed: {
type: Boolean,
value: false
},
hasToasts: {
type: Boolean,
computed: '_computeHasToasts(toasts.*)'
},
keyEventTarget: {
type: Object,
value() {
return document.body;
}
}
}
}
get keyBindings() {
return {
'esc:keyup': '_hideOnEsc'
}
}
static get observers() {
return [
'_changedToasts(toasts.splices)'
]
}
_hideOnEsc(event) {
return this.dismissNotifications();
}
_computeHasToasts() {
return this.toasts.length > 0;
}
_debouncedCalc() {
// calculate once in a while
this.debounce('debouncedCalc', this.toastInWindow, 25);
}
conditionalClass() {
return this.isFixed ? 'fixed' : '';
}
toastInWindow() {
if (!this._headerNode) {
return true
}
var headerHeight = this._headerNode.offsetHeight;
var scrollPosition = window.scrollY;
if (this.isFixed) {
this.isFixed = 1 <= scrollPosition;
}
else {
this.isFixed = headerHeight <= scrollPosition;
}
get hasToasts() {
return this.toasts && this.toasts.length > 0;
}
connectedCallback() {
super.connectedCallback();
this._headerNode = document.querySelector('.header', document);
this.listen(window, 'scroll', '_debouncedCalc');
this.listen(window, 'resize', '_debouncedCalc');
this._headerNode = document.querySelector('.header');
window.addEventListener('scroll', this._debouncedCalcBound);
window.addEventListener('resize', this._debouncedCalcBound);
window.addEventListener('keyup', this._handleKeyupBound);
this._debouncedCalc();
}
_changedToasts(newValue, oldValue) {
$.Topic('/favicon/update').publish({count: this.toasts.length});
disconnectedCallback() {
super.disconnectedCallback();
window.removeEventListener('scroll', this._debouncedCalcBound);
window.removeEventListener('resize', this._debouncedCalcBound);
window.removeEventListener('keyup', this._handleKeyupBound);
if (this._debounceTimeout) {
clearTimeout(this._debounceTimeout);
}
}
dismissNotification(e) {
$.Topic('/favicon/update').publish({count: this.toasts.length - 1});
var idx = e.target.parentNode.indexPos
this.splice('toasts', idx, 1);
updated(changedProperties) {
if (changedProperties.has('toasts')) {
$.Topic('/favicon/update').publish({count: this.toasts.length});
}
}
render() {
if (!this.hasToasts) {
return html``;
}
return html`
<div class=${classMap({
'container': true,
'toast-message-holder': true,
'fixed': this.isFixed
})}>
${this.toasts.map((item, index) => html`
<div class="alert alert-${item.level}">
<div class="toast-close" @click=${() => this.dismissNotification(index)}>
<span>${this._gettext('Close')}</span>
</div>
<rhodecode-unsafe-html .text=${item.message}></rhodecode-unsafe-html>
</div>
`)}
</div>
`;
}
_handleKeyup(event) {
if (event.key === 'Escape') {
this.dismissNotifications();
}
}
_debouncedCalc() {
if (this._debounceTimeout) {
clearTimeout(this._debounceTimeout);
}
this._debounceTimeout = setTimeout(() => {
this.toastInWindow();
}, 25);
}
toastInWindow() {
if (!this._headerNode) {
return true;
}
const headerHeight = this._headerNode.offsetHeight;
const scrollPosition = window.scrollY;
if (this.isFixed) {
this.isFixed = 1 <= scrollPosition;
} else {
this.isFixed = headerHeight <= scrollPosition;
}
}
dismissNotification(index) {
$.Topic('/favicon/update').publish({count: this.toasts.length - 1});
this.toasts = [
...this.toasts.slice(0, index),
...this.toasts.slice(index + 1)
];
}
dismissNotifications() {
$.Topic('/favicon/update').publish({count: 0});
this.splice('toasts', 0);
this.toasts = [];
}
handleNotification(data) {
if (!templateContext.rhodecode_user.notification_status && !data.message.force) {
// do not act if notifications are disabled
return
return;
}
this.push('toasts', {
this.toasts = [...this.toasts, {
level: data.message.level,
message: data.message.message
});
}];
}
_gettext(x){
return _gettext(x)
_gettext(x) {
return _gettext(x);
}
}
customElements.define(RhodecodeToast.is, RhodecodeToast);
customElements.define('rhodecode-toast', RhodecodeToast);

View file

@ -1,30 +1,24 @@
import {PolymerElement, html} from '@polymer/polymer/polymer-element.js';
import {LitElement, html} from 'lit';
export class RhodecodeUnsafeHtml extends PolymerElement {
export class RhodecodeUnsafeHtml extends LitElement {
static properties = {
text: {type: String}
};
static get is() {
return 'rhodecode-unsafe-html';
constructor() {
super();
this.text = '';
}
static get template() {
return html`
<style include="shared-styles"></style>
<slot></slot>
`;
render() {
return html`<slot></slot>`;
}
static get properties() {
return {
text: {
type: String,
observer: '_handleText'
}
}
}
_handleText(newVal, oldVal) {
updated(changedProperties) {
if (changedProperties.has('text')) {
this.innerHTML = this.text;
}
}
}
customElements.define(RhodecodeUnsafeHtml.is, RhodecodeUnsafeHtml);
customElements.define('rhodecode-unsafe-html', RhodecodeUnsafeHtml);

View file

@ -58,7 +58,6 @@ c.template_context['attachment_store'] = {
</%def>
${self.robots()}
<link rel="icon" href="${h.asset('images/favicon.ico', ver=c.rhodecode_version_hash)}" sizes="16x16 32x32" type="image/png" />
<script src="${h.asset('js/vendors/webcomponentsjs/custom-elements-es5-adapter.js', ver=c.rhodecode_version_hash)}"></script>
<script src="${h.asset('js/vendors/webcomponentsjs/webcomponents-bundle.js', ver=c.rhodecode_version_hash)}"></script>
## CSS definitions

File diff suppressed because one or more lines are too long

View file

@ -588,7 +588,7 @@ search.location = %(here)s/.rc-test-data/data/index
channelstream.enabled = false
; server address for channelstream server on the backend
channelstream.server = channelstream:9800
channelstream.server = channelstream:8000
; location of the channelstream server from outside world
; use ws:// for http or wss:// for https. This address needs to be handled

View file

@ -15,11 +15,19 @@ let babelRCOptions = {
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions"]
}
"esmodules": true
},
"exclude": [
"transform-es2015-classes",
"transform-regenerator",
"transform-async-to-generator"
]
}]
],
"plugins": ["transform-object-rest-spread"]
"plugins": [
["transform-class-properties", { "loose": true }],
"transform-object-rest-spread"
]
};
module.exports = {
@ -67,9 +75,10 @@ module.exports = {
{
// If you see a file that ends in .js, just send it to the babel-loader.
test: /\.js$/,
// Exclude node_modules, but process our Lit components
// Babel is configured to NOT transpile ES6 classes (see babelRCOptions exclude)
exclude: /node_modules/,
use: {loader: 'babel-loader', options: babelRCOptions}
// Optionally exclude node_modules from transpilation except for polymer-webpack-loader:
// exclude: /node_modules\/(?!polymer-webpack-loader\/).*/
},
// this is required because of bug:
// https://github.com/webpack-contrib/polymer-webpack-loader/issues/49