Browse Source

Start work on removing constants from _converse object

JC Brand 2 years ago
parent
commit
48e7987f38

+ 1 - 1
Makefile

@@ -86,7 +86,7 @@ po:
 .PHONY: release
 release:
 	find ./src -name "*~" -exec rm {} \;
-	$(SED) -i '/^_converse.VERSION_NAME =/s/=.*/= "v$(VERSION)";/' src/headless/core.js
+	$(SED) -i '/^export const VERSION_NAME =/s/=.*/= "v$(VERSION)";/' src/headless/shared/constants.js
 	$(SED) -i '/Version:/s/:.*/: $(VERSION)/' COPYRIGHT
 	$(SED) -i '/Project-Id-Version:/s/:.*/: Converse.js $(VERSION)\n"/' src/i18n/converse.pot
 	$(SED) -i '/"version":/s/:.*/: "$(VERSION)",/' manifest.json

+ 2 - 1
src/headless/plugins/chat/model.js

@@ -5,6 +5,7 @@ import isObject from "lodash-es/isObject";
 import log from '@converse/headless/log';
 import pick from "lodash-es/pick";
 import { Model } from '@converse/skeletor/src/model.js';
+import { TimeoutError } from '../../shared/errors.js';
 import { _converse, api, converse } from "../../core.js";
 import { debouncedPruneHistory, handleCorrection } from '@converse/headless/shared/chat/utils.js';
 import { getMediaURLsMetadata } from '@converse/headless/shared/parsers.js';
@@ -368,7 +369,7 @@ const ChatBox = ModelWithContact.extend({
     },
 
     async createMessageFromError (error) {
-        if (error instanceof _converse.TimeoutError) {
+        if (error instanceof TimeoutError) {
             const msg = await this.createMessage({
                 'type': 'error',
                 'message': error.message,

+ 3 - 2
src/headless/plugins/mam/api.js

@@ -1,6 +1,7 @@
-import { RSM } from '@converse/headless/shared/rsm';
 import log from '@converse/headless/log';
 import sizzle from "sizzle";
+import { RSM } from '@converse/headless/shared/rsm';
+import { TimeoutError } from '../../shared/errors.js';
 import { _converse, api, converse } from "@converse/headless/core";
 
 const { Strophe, $iq, dayjs } = converse.env;
@@ -270,7 +271,7 @@ export default {
                 const { __ } = _converse;
                 const err_msg = __("Timeout while trying to fetch archived messages.");
                 log.error(err_msg);
-                error = new _converse.TimeoutError(err_msg);
+                error = new TimeoutError(err_msg);
                 return { messages, error };
 
             } else if (u.isErrorStanza(iq_result)) {

+ 5 - 4
src/headless/plugins/muc/muc.js

@@ -7,6 +7,7 @@ import sizzle from 'sizzle';
 import { Model } from '@converse/skeletor/src/model.js';
 import { ROOMSTATUS } from './constants.js';
 import { Strophe, $build, $iq, $msg, $pres } from 'strophe.js/src/strophe';
+import { TimeoutError } from '../../shared/errors.js';
 import { _converse, api, converse } from '../../core.js';
 import { computeAffiliationsDelta, setAffiliations, getAffiliationList }  from './affiliations/utils.js';
 import { getOpenPromise } from '@converse/openpromise';
@@ -709,8 +710,8 @@ const ChatRoomMixin = {
      * @private
      * @method _converse.ChatRoom#sendTimedMessage
      * @param { _converse.Message|Element } message
-     * @returns { Promise<Element>|Promise<_converse.TimeoutError> } Returns a promise
-     *  which resolves with the reflected message stanza or with an error stanza or {@link _converse.TimeoutError}.
+     * @returns { Promise<Element>|Promise<TimeoutError> } Returns a promise
+     *  which resolves with the reflected message stanza or with an error stanza or {@link TimeoutError}.
      */
     sendTimedMessage (el) {
         if (typeof el.tree === 'function') {
@@ -726,7 +727,7 @@ const ChatRoomMixin = {
         const timeout = api.settings.get('stanza_timeout');
         const timeoutHandler = _converse.connection.addTimedHandler(timeout, () => {
             _converse.connection.deleteHandler(handler);
-            const err = new _converse.TimeoutError('Timeout Error: No response from server');
+            const err = new TimeoutError('Timeout Error: No response from server');
             promise.resolve(err);
             return false;
         });
@@ -776,7 +777,7 @@ const ChatRoomMixin = {
 
         if (u.isErrorStanza(result)) {
             log.error(result);
-        } else if (result instanceof _converse.TimeoutError) {
+        } else if (result instanceof TimeoutError) {
             log.error(result);
             message.save({
                 editable,

+ 52 - 34
src/headless/shared/_converse.js

@@ -1,15 +1,37 @@
 import i18n from './i18n.js';
 import log from '../log.js';
 import pluggable from 'pluggable.js/src/pluggable.js';
-import { VERSION_NAME } from './constants';
 import { Events } from '@converse/skeletor/src/events.js';
 import { Router } from '@converse/skeletor/src/router.js';
-import { TimeoutError } from './errors.js';
 import { createStore, getDefaultStore } from '../utils/storage.js';
 import { getInitSettings } from './settings/utils.js';
 import { getOpenPromise } from '@converse/openpromise';
 import { shouldClearCache } from '../utils/core.js';
 
+import {
+    ACTIVE,
+    ANONYMOUS,
+    CHATROOMS_TYPE,
+    CLOSED,
+    COMPOSING,
+    CONTROLBOX_TYPE,
+    DEFAULT_IMAGE,
+    DEFAULT_IMAGE_TYPE,
+    EXTERNAL,
+    FAILURE,
+    GONE,
+    HEADLINES_TYPE,
+    INACTIVE,
+    LOGIN,
+    LOGOUT,
+    OPENED,
+    PAUSED,
+    PREBIND,
+    PRIVATE_CHAT_TYPE,
+    SUCCESS,
+    VERSION_NAME
+} from './constants';
+
 
 /**
  * A private, closured object containing the private api (via {@link _converse.api})
@@ -28,46 +50,42 @@ const _converse = {
         'initialized': getOpenPromise()
     },
 
-    ANONYMOUS: 'anonymous',
-    CLOSED: 'closed',
-    EXTERNAL: 'external',
-    LOGIN: 'login',
-    LOGOUT: 'logout',
-    OPENED: 'opened',
-    PREBIND: 'prebind',
-
-    SUCCESS: 'success',
-    FAILURE: 'failure',
-
-    // Generated from css/images/user.svg
-    DEFAULT_IMAGE_TYPE: 'image/svg+xml',
-    DEFAULT_IMAGE: "PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iIzU1NSIvPgogPGNpcmNsZSBjeD0iNjQiIGN5PSI0MSIgcj0iMjQiIGZpbGw9IiNmZmYiLz4KIDxwYXRoIGQ9Im0yOC41IDExMiB2LTEyIGMwLTEyIDEwLTI0IDI0LTI0IGgyMyBjMTQgMCAyNCAxMiAyNCAyNCB2MTIiIGZpbGw9IiNmZmYiLz4KPC9zdmc+Cg==",
-
+    // TODO: remove constants in next major release
+    ANONYMOUS,
+    CLOSED,
+    EXTERNAL,
+    LOGIN,
+    LOGOUT,
+    OPENED,
+    PREBIND,
+
+    SUCCESS,
+    FAILURE,
+
+    DEFAULT_IMAGE_TYPE,
+    DEFAULT_IMAGE,
+
+    INACTIVE,
+    ACTIVE,
+    COMPOSING,
+    PAUSED,
+    GONE,
+
+    PRIVATE_CHAT_TYPE,
+    CHATROOMS_TYPE,
+    HEADLINES_TYPE,
+    CONTROLBOX_TYPE,
+
+    // Set as module attr so that we can override in tests.
+    // TODO: replace with config settings
     TIMEOUTS: {
-        // Set as module attr so that we can override in tests.
         PAUSED: 10000,
         INACTIVE: 90000
     },
 
-    // XEP-0085 Chat states
-    // https://xmpp.org/extensions/xep-0085.html
-    INACTIVE: 'inactive',
-    ACTIVE: 'active',
-    COMPOSING: 'composing',
-    PAUSED: 'paused',
-    GONE: 'gone',
-
-    // Chat types
-    PRIVATE_CHAT_TYPE: 'chatbox',
-    CHATROOMS_TYPE: 'chatroom',
-    HEADLINES_TYPE: 'headline',
-    CONTROLBOX_TYPE: 'controlbox',
-
     default_connection_options: {'explicitResourceBinding': true},
     router: new Router(),
 
-    TimeoutError: TimeoutError,
-
     isTestEnv: () => {
         return getInitSettings()['bosh_service_url'] === 'montague.lit/http-bind';
     },

+ 18 - 15
src/headless/shared/api/public.js

@@ -6,10 +6,11 @@ import i18n from '../i18n';
 import log from '../../log.js';
 import sizzle from 'sizzle';
 import u, { setUnloadEvent } from '../../utils/core.js';
-import { CHAT_STATES, KEYCODES, VERSION_NAME } from '../constants.js';
+import { ANONYMOUS, CHAT_STATES, KEYCODES, VERSION_NAME } from '../constants.js';
 import { Collection } from "@converse/skeletor/src/collection";
 import { Model } from '@converse/skeletor/src/model.js';
 import { Strophe, $build, $iq, $msg, $pres } from 'strophe.js/src/strophe';
+import { TimeoutError } from '../errors.js';
 import { html } from 'lit';
 import { initAppSettings } from '../settings/utils.js';
 import { sprintf } from 'sprintf-js';
@@ -71,7 +72,7 @@ export const converse = Object.assign(window.converse || {}, {
         _converse.strict_plugin_dependencies = settings.strict_plugin_dependencies; // Needed by pluggable.js
         log.setLogLevel(api.settings.get("loglevel"));
 
-        if (api.settings.get("authentication") === _converse.ANONYMOUS) {
+        if (api.settings.get("authentication") === ANONYMOUS) {
             if (api.settings.get("auto_login") && !api.settings.get('jid')) {
                 throw new Error("Config Error: you need to provide the server's " +
                       "domain via the 'jid' option when using anonymous " +
@@ -170,22 +171,22 @@ export const converse = Object.assign(window.converse || {}, {
     /**
      * Utility methods and globals from bundled 3rd party libraries.
      * @typedef ConverseEnv
-     * @property {function} converse.env.$build    - Creates a Strophe.Builder, for creating stanza objects.
-     * @property {function} converse.env.$iq       - Creates a Strophe.Builder with an <iq/> element as the root.
-     * @property {function} converse.env.$msg      - Creates a Strophe.Builder with an <message/> element as the root.
-     * @property {function} converse.env.$pres     - Creates a Strophe.Builder with an <presence/> element as the root.
-     * @property {function} converse.env.Promise   - The Promise implementation used by Converse.
-     * @property {function} converse.env.Strophe   - The [Strophe](http://strophe.im/strophejs) XMPP library used by Converse.
-     * @property {function} converse.env.f         - And instance of Lodash with its methods wrapped to produce immutable auto-curried iteratee-first data-last methods.
-     * @property {function} converse.env.sizzle    - [Sizzle](https://sizzlejs.com) CSS selector engine.
-     * @property {function} converse.env.sprintf
-     * @property {object} converse.env._           - The instance of [lodash-es](http://lodash.com) used by Converse.
-     * @property {object} converse.env.dayjs       - [DayJS](https://github.com/iamkun/dayjs) date manipulation library.
-     * @property {object} converse.env.utils       - Module containing common utility methods used by Converse.
+     * @property { Error } converse.env.TimeoutError
+     * @property { function } converse.env.$build    - Creates a Strophe.Builder, for creating stanza objects.
+     * @property { function } converse.env.$iq       - Creates a Strophe.Builder with an <iq/> element as the root.
+     * @property { function } converse.env.$msg      - Creates a Strophe.Builder with an <message/> element as the root.
+     * @property { function } converse.env.$pres     - Creates a Strophe.Builder with an <presence/> element as the root.
+     * @property { function } converse.env.Promise   - The Promise implementation used by Converse.
+     * @property { function } converse.env.Strophe   - The [Strophe](http://strophe.im/strophejs) XMPP library used by Converse.
+     * @property { function } converse.env.f         - And instance of Lodash with its methods wrapped to produce immutable auto-curried iteratee-first data-last methods.
+     * @property { function } converse.env.sizzle    - [Sizzle](https://sizzlejs.com) CSS selector engine.
+     * @property { function } converse.env.sprintf
+     * @property { object } converse.env._           - The instance of [lodash-es](http://lodash.com) used by Converse.
+     * @property { object } converse.env.dayjs       - [DayJS](https://github.com/iamkun/dayjs) date manipulation library.
+     * @property { object } converse.env.utils       - Module containing common utility methods used by Converse.
      * @memberOf converse
      */
     'env': {
-        VERSION_NAME,
         $build,
         $iq,
         $msg,
@@ -195,7 +196,9 @@ export const converse = Object.assign(window.converse || {}, {
         Model,
         Promise,
         Strophe,
+        TimeoutError,
         URI,
+        VERSION_NAME,
         dayjs,
         html,
         log,

+ 3 - 2
src/headless/shared/api/user.js

@@ -4,6 +4,7 @@ import u, { replacePromise } from '../../utils/core.js';
 import { attemptNonPreboundSession, initConnection, setUserJID } from '../../utils/init.js';
 import { getOpenPromise } from '@converse/openpromise';
 import { user_settings_api } from '../settings/api.js';
+import { LOGOUT, PREBIND } from '../constants.js';
 
 export default {
     /**
@@ -60,7 +61,7 @@ export default {
             if (bosh_plugin?.enabled()) {
                 if (await _converse.restoreBOSHSession()) {
                     return;
-                } else if (api.settings.get("authentication") === _converse.PREBIND && (!automatic || api.settings.get("auto_login"))) {
+                } else if (api.settings.get("authentication") === PREBIND && (!automatic || api.settings.get("auto_login"))) {
                     return _converse.startNewPreboundBOSHSession();
                 }
             }
@@ -100,7 +101,7 @@ export default {
                 promise.resolve();
             }
 
-            _converse.connection.setDisconnectionCause(_converse.LOGOUT, undefined, true);
+            _converse.connection.setDisconnectionCause(LOGOUT, undefined, true);
             if (_converse.connection !== undefined) {
                 api.listen.once('disconnected', () => complete());
                 _converse.connection.disconnect();

+ 6 - 6
src/headless/shared/connection/index.js

@@ -1,7 +1,7 @@
 import debounce from 'lodash-es/debounce';
 import log from "../../log.js";
 import sizzle from 'sizzle';
-import { BOSH_WAIT } from '../../shared/constants.js';
+import { ANONYMOUS, BOSH_WAIT, LOGOUT } from '../../shared/constants.js';
 import { CONNECTION_STATUS } from '../constants';
 import { Strophe } from 'strophe.js/src/core.js';
 import { _converse, api } from "../../core.js";
@@ -128,7 +128,7 @@ export class Connection extends Strophe.Connection {
             this._proto = new Strophe.Bosh(this);
             this.service = api.settings.get('bosh_service_url');
         } else if (api.connection.isType('bosh') && api.settings.get("websocket_url")) {
-            if (api.settings.get("authentication") === _converse.ANONYMOUS) {
+            if (api.settings.get("authentication") === ANONYMOUS) {
                 // When reconnecting anonymously, we need to connect with only
                 // the domain, not the full JID that we had in our previous
                 // (now failed) session.
@@ -150,7 +150,7 @@ export class Connection extends Strophe.Connection {
         const conn_status = _converse.connfeedback.get('connection_status');
         if (conn_status === Strophe.Status.CONNFAIL) {
             this.switchTransport();
-        } else if (conn_status === Strophe.Status.AUTHFAIL && api.settings.get("authentication") === _converse.ANONYMOUS) {
+        } else if (conn_status === Strophe.Status.AUTHFAIL && api.settings.get("authentication") === ANONYMOUS) {
             // When reconnecting anonymously, we need to connect with only
             // the domain, not the full JID that we had in our previous
             // (now failed) session.
@@ -164,7 +164,7 @@ export class Connection extends Strophe.Connection {
          */
         api.trigger('will-reconnect');
 
-        if (api.settings.get("authentication") === _converse.ANONYMOUS) {
+        if (api.settings.get("authentication") === ANONYMOUS) {
             await clearSession();
         }
         return api.user.login();
@@ -265,7 +265,7 @@ export class Connection extends Strophe.Connection {
         if (api.settings.get("auto_reconnect")) {
             const reason = this.disconnection_reason;
             if (this.disconnection_cause === Strophe.Status.AUTHFAIL) {
-                if (api.settings.get("credentials_url") || api.settings.get("authentication") === _converse.ANONYMOUS) {
+                if (api.settings.get("credentials_url") || api.settings.get("authentication") === ANONYMOUS) {
                     // If `credentials_url` is set, we reconnect, because we might
                     // be receiving expirable tokens from the credentials_url.
                     //
@@ -287,7 +287,7 @@ export class Connection extends Strophe.Connection {
                 );
                 return this.finishDisconnection();
             } else if (
-                this.disconnection_cause === _converse.LOGOUT ||
+                this.disconnection_cause === LOGOUT ||
                 reason === Strophe.ErrorCondition.NO_AUTH_MECH ||
                 reason === "host-unknown" ||
                 reason === "remote-connection-failed"

+ 29 - 0
src/headless/shared/constants.js

@@ -13,6 +13,35 @@ export const STATUS_WEIGHTS = {
     online: 1,
 };
 
+export const ANONYMOUS = 'anonymous';
+export const CLOSED = 'closed';
+export const EXTERNAL = 'external';
+export const LOGIN = 'login';
+export const LOGOUT = 'logout';
+export const OPENED = 'opened';
+export const PREBIND = 'prebind';
+export const SUCCESS = 'success';
+export const FAILURE = 'failure';
+
+// Generated from css/images/user.svg
+export const DEFAULT_IMAGE_TYPE = 'image/svg+xml';
+export const DEFAULT_IMAGE =
+    'PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iIzU1NSIvPgogPGNpcmNsZSBjeD0iNjQiIGN5PSI0MSIgcj0iMjQiIGZpbGw9IiNmZmYiLz4KIDxwYXRoIGQ9Im0yOC41IDExMiB2LTEyIGMwLTEyIDEwLTI0IDI0LTI0IGgyMyBjMTQgMCAyNCAxMiAyNCAyNCB2MTIiIGZpbGw9IiNmZmYiLz4KPC9zdmc+Cg==';
+
+// XEP-0085 Chat states
+// https =//xmpp.org/extensions/xep-0085.html
+export const INACTIVE = 'inactive';
+export const ACTIVE = 'active';
+export const COMPOSING = 'composing';
+export const PAUSED = 'paused';
+export const GONE = 'gone';
+
+// Chat types
+export const PRIVATE_CHAT_TYPE = 'chatbox';
+export const CHATROOMS_TYPE = 'chatroom';
+export const HEADLINES_TYPE = 'headline';
+export const CONTROLBOX_TYPE = 'controlbox';
+
 export const CONNECTION_STATUS = {};
 CONNECTION_STATUS[Strophe.Status.ATTACHED] = 'ATTACHED';
 CONNECTION_STATUS[Strophe.Status.AUTHENTICATING] = 'AUTHENTICATING';

+ 1 - 1
src/headless/shared/errors.js

@@ -1,5 +1,5 @@
 /**
  * Custom error for indicating timeouts
- * @namespace _converse
+ * @namespace converse.env
  */
 export class TimeoutError extends Error {}

+ 7 - 7
src/headless/utils/init.js

@@ -4,7 +4,7 @@ import debounce from 'lodash-es/debounce';
 import localDriver from 'localforage-webextensionstorage-driver/local';
 import log from '../log.js';
 import syncDriver from 'localforage-webextensionstorage-driver/sync';
-import { CORE_PLUGINS } from '../shared/constants.js';
+import { ANONYMOUS, CORE_PLUGINS, EXTERNAL, LOGIN, PREBIND } from '../shared/constants.js';
 import { Connection, MockConnection } from '../shared/connection/index.js';
 import { Model } from '@converse/skeletor/src/model.js';
 import { Strophe } from 'strophe.js/src/strophe';
@@ -43,7 +43,7 @@ export function initConnection () {
     const api = _converse.api;
 
     if (! api.settings.get('bosh_service_url')) {
-        if (api.settings.get("authentication") === _converse.PREBIND) {
+        if (api.settings.get("authentication") === PREBIND) {
             throw new Error("authentication is set to 'prebind' but we don't have a BOSH connection");
         }
     }
@@ -182,7 +182,7 @@ function initPersistentStorage (_converse, store_name) {
 
 function saveJIDtoSession (_converse, jid) {
     jid = _converse.session.get('jid') || jid;
-    if (_converse.api.settings.get("authentication") !== _converse.ANONYMOUS && !Strophe.getResourceFromJid(jid)) {
+    if (_converse.api.settings.get("authentication") !== ANONYMOUS && !Strophe.getResourceFromJid(jid)) {
         jid = jid.toLowerCase() + Connection.generateResource();
     }
     _converse.jid = jid;
@@ -387,7 +387,7 @@ async function getLoginCredentialsFromSCRAMKeys () {
 export async function attemptNonPreboundSession (credentials, automatic) {
     const { api } = _converse;
 
-    if (api.settings.get("authentication") === _converse.LOGIN) {
+    if (api.settings.get("authentication") === LOGIN) {
         // XXX: If EITHER ``keepalive`` or ``auto_login`` is ``true`` and
         // ``authentication`` is set to ``login``, then Converse will try to log the user in,
         // since we don't have a way to distinguish between wether we're
@@ -417,7 +417,7 @@ export async function attemptNonPreboundSession (credentials, automatic) {
         if (!_converse.isTestEnv()) log.warn("attemptNonPreboundSession: Couldn't find credentials to log in with");
 
     } else if (
-        [_converse.ANONYMOUS, _converse.EXTERNAL].includes(api.settings.get("authentication")) &&
+        [ANONYMOUS, EXTERNAL].includes(api.settings.get("authentication")) &&
         (!automatic || api.settings.get("auto_login"))
     ) {
         connect();
@@ -446,7 +446,7 @@ export async function savedLoginInfo (jid) {
 
 async function connect (credentials) {
     const { api } = _converse;
-    if ([_converse.ANONYMOUS, _converse.EXTERNAL].includes(api.settings.get("authentication"))) {
+    if ([ANONYMOUS, EXTERNAL].includes(api.settings.get("authentication"))) {
         if (!_converse.jid) {
             throw new Error("Config Error: when using anonymous login " +
                 "you need to provide the server's domain via the 'jid' option. " +
@@ -457,7 +457,7 @@ async function connect (credentials) {
             _converse.connection.reset();
         }
         _converse.connection.connect(_converse.jid.toLowerCase());
-    } else if (api.settings.get("authentication") === _converse.LOGIN) {
+    } else if (api.settings.get("authentication") === LOGIN) {
         const password = credentials?.password ?? (_converse.connection?.pass || api.settings.get("password"));
         if (!password) {
             if (api.settings.get("auto_login")) {

+ 2 - 1
src/plugins/controlbox/controlbox.js

@@ -1,6 +1,7 @@
 import tplControlbox from './templates/controlbox.js';
 import { CustomElement } from 'shared/components/element.js';
 import { _converse, api, converse } from '@converse/headless/core.js';
+import { LOGOUT } from '@converse/headless/shared/constants.js';
 
 const u = converse.env.utils;
 
@@ -49,7 +50,7 @@ class ControlBox extends CustomElement {
         ev?.preventDefault?.();
         if (
             ev?.name === 'closeAllChatBoxes' &&
-            (_converse.disconnection_cause !== _converse.LOGOUT ||
+            (_converse.disconnection_cause !== LOGOUT ||
                 api.settings.get('show_controlbox_by_default'))
         ) {
             return;

+ 2 - 1
src/plugins/controlbox/loginform.js

@@ -1,5 +1,6 @@
 import bootstrap from 'bootstrap.native';
 import tplLoginPanel from './templates/loginform.js';
+import { ANONYMOUS } from '@converse/headless/shared/constants';
 import { CustomElement } from 'shared/components/element.js';
 import { _converse, api, converse } from '@converse/headless/core.js';
 import { initConnection } from '@converse/headless/utils/init.js';
@@ -36,7 +37,7 @@ class LoginForm extends CustomElement {
     async onLoginFormSubmitted (ev) {
         ev?.preventDefault();
 
-        if (api.settings.get('authentication') === _converse.ANONYMOUS) {
+        if (api.settings.get('authentication') === ANONYMOUS) {
             return this.connect(_converse.jid);
         }
 

+ 70 - 52
src/plugins/controlbox/templates/loginform.js

@@ -1,32 +1,41 @@
 import 'shared/components/brand-heading.js';
 import tplSpinner from 'templates/spinner.js';
-import { CONNECTION_STATUS } from '@converse/headless/shared/constants';
+import { ANONYMOUS, EXTERNAL, LOGIN, PREBIND, CONNECTION_STATUS } from '@converse/headless/shared/constants';
 import { REPORTABLE_STATUSES, PRETTY_CONNECTION_STATUS, CONNECTION_STATUS_CSS_CLASS } from '../constants.js';
 import { __ } from 'i18n';
-import { _converse, api } from "@converse/headless/core";
-import { html } from "lit";
-
+import { _converse, api } from '@converse/headless/core';
+import { html } from 'lit';
 
 const trust_checkbox = (checked) => {
     const i18n_hint_trusted = __(
-        'To improve performance, we cache your data in this browser. '+
-        'Uncheck this box if this is a public computer or if you want your data to be deleted when you log out. '+
-        'It\'s important that you explicitly log out, otherwise not all cached data might be deleted. '+
-        'Please note, when using an untrusted device, OMEMO encryption is NOT available.')
+        'To improve performance, we cache your data in this browser. ' +
+            'Uncheck this box if this is a public computer or if you want your data to be deleted when you log out. ' +
+            "It's important that you explicitly log out, otherwise not all cached data might be deleted. " +
+            'Please note, when using an untrusted device, OMEMO encryption is NOT available.'
+    );
     const i18n_trusted = __('This is a trusted device');
     return html`
         <div class="form-group form-check login-trusted">
-            <input id="converse-login-trusted" type="checkbox" class="form-check-input" name="trusted" ?checked=${checked}>
+            <input
+                id="converse-login-trusted"
+                type="checkbox"
+                class="form-check-input"
+                name="trusted"
+                ?checked=${checked}
+            />
             <label for="converse-login-trusted" class="form-check-label login-trusted__desc">${i18n_trusted}</label>
 
-            <converse-icon class="fa fa-info-circle" data-toggle="popover"
+            <converse-icon
+                class="fa fa-info-circle"
+                data-toggle="popover"
                 data-title="Trusted device?"
                 data-content="${i18n_hint_trusted}"
                 size="1.2em"
-                title="${i18n_hint_trusted}"></converse-icon>
+                title="${i18n_hint_trusted}"
+            ></converse-icon>
         </div>
     `;
-}
+};
 
 const connection_url_input = () => {
     const i18n_connection_url = __('Connection URL');
@@ -36,53 +45,60 @@ const connection_url_input = () => {
         <div class="form-group fade-in">
             <label for="converse-conn-url">${i18n_connection_url}</label>
             <p class="form-help instructions">${i18n_form_help}</p>
-            <input id="converse-conn-url"
-                   class="form-control"
-                   type="url"
-                   name="connection-url"
-                   placeholder="${i18n_placeholder}"/>
+            <input
+                id="converse-conn-url"
+                class="form-control"
+                type="url"
+                name="connection-url"
+                placeholder="${i18n_placeholder}"
+            />
         </div>
     `;
-}
+};
 
 const password_input = () => {
     const i18n_password = __('Password');
     return html`
         <div class="form-group">
             <label for="converse-login-password">${i18n_password}</label>
-            <input id="converse-login-password"
+            <input
+                id="converse-login-password"
                 class="form-control"
                 required="required"
                 value="${api.settings.get('password') ?? ''}"
                 type="password"
                 name="password"
-                placeholder="${i18n_password}"/>
+                placeholder="${i18n_password}"
+            />
         </div>
     `;
-}
+};
 
 const tplRegisterLink = () => {
-    const i18n_create_account = __("Create an account");
+    const i18n_create_account = __('Create an account');
     const i18n_hint_no_account = __("Don't have a chat account?");
     return html`
         <fieldset class="switch-form">
             <p>${i18n_hint_no_account}</p>
-            <p><a class="register-account toggle-register-login" href="#converse/register">${i18n_create_account}</a></p>
+            <p>
+                <a class="register-account toggle-register-login" href="#converse/register">${i18n_create_account}</a>
+            </p>
         </fieldset>
     `;
-}
+};
 
 const tplShowRegisterLink = () => {
-    return api.settings.get('allow_registration') &&
-        !api.settings.get("auto_login") &&
-        _converse.pluggable.plugins['converse-register'].enabled(_converse);
-}
-
+    return (
+        api.settings.get('allow_registration') &&
+        !api.settings.get('auto_login') &&
+        _converse.pluggable.plugins['converse-register'].enabled(_converse)
+    );
+};
 
 const auth_fields = (el) => {
     const authentication = api.settings.get('authentication');
     const i18n_login = __('Log in');
-    const i18n_xmpp_address = __("XMPP Address");
+    const i18n_xmpp_address = __('XMPP Address');
     const locked_domain = api.settings.get('locked_domain');
     const default_domain = api.settings.get('default_domain');
     const placeholder_username = ((locked_domain || default_domain) && __('Username')) || __('user@domain');
@@ -91,7 +107,8 @@ const auth_fields = (el) => {
     return html`
         <div class="form-group">
             <label for="converse-login-jid">${i18n_xmpp_address}:</label>
-            <input id="converse-login-jid"
+            <input
+                id="converse-login-jid"
                 ?autofocus=${api.settings.get('auto_focus') ? true : false}
                 @changed=${el.validate}
                 value="${api.settings.get('jid') ?? ''}"
@@ -99,31 +116,31 @@ const auth_fields = (el) => {
                 class="form-control"
                 type="text"
                 name="jid"
-                placeholder="${placeholder_username}"/>
+                placeholder="${placeholder_username}"
+            />
         </div>
-        ${ (authentication !== _converse.EXTERNAL) ? password_input() : '' }
-        ${ api.settings.get('show_connection_url_input') ? connection_url_input() : '' }
-        ${ show_trust_checkbox ? trust_checkbox(show_trust_checkbox === 'off' ? false : true) : '' }
+        ${authentication !== EXTERNAL ? password_input() : ''}
+        ${api.settings.get('show_connection_url_input') ? connection_url_input() : ''}
+        ${show_trust_checkbox ? trust_checkbox(show_trust_checkbox === 'off' ? false : true) : ''}
         <fieldset class="form-group buttons">
-            <input class="btn btn-primary" type="submit" value="${i18n_login}"/>
+            <input class="btn btn-primary" type="submit" value="${i18n_login}" />
         </fieldset>
-        ${ tplShowRegisterLink() ? tplRegisterLink(el) : '' }
+        ${tplShowRegisterLink() ? tplRegisterLink() : ''}
     `;
-}
-
+};
 
 const form_fields = (el) => {
     const authentication = api.settings.get('authentication');
-    const { ANONYMOUS, EXTERNAL, LOGIN, PREBIND } = _converse;
     const i18n_disconnected = __('Disconnected');
     const i18n_anon_login = __('Click here to log in anonymously');
     return html`
-        ${ (authentication == LOGIN || authentication == EXTERNAL) ? auth_fields(el) : '' }
-        ${ authentication == ANONYMOUS ? html`<input class="btn btn-primary login-anon" type="submit" value="${i18n_anon_login}">` : '' }
-        ${ authentication == PREBIND ? html`<p>${i18n_disconnected}</p>` : '' }
+        ${authentication == LOGIN || authentication == EXTERNAL ? auth_fields(el) : ''}
+        ${authentication == ANONYMOUS
+            ? html`<input class="btn btn-primary login-anon" type="submit" value="${i18n_anon_login}" />`
+            : ''}
+        ${authentication == PREBIND ? html`<p>${i18n_disconnected}</p>` : ''}
     `;
-}
-
+};
 
 export default (el) => {
     const connection_status = _converse.connfeedback.get('connection_status');
@@ -133,13 +150,14 @@ export default (el) => {
         feedback_class = CONNECTION_STATUS_CSS_CLASS[connection_status];
     }
     const conn_feedback_message = _converse.connfeedback.get('message');
-    return html`
-        <converse-brand-heading></converse-brand-heading>
+    return html` <converse-brand-heading></converse-brand-heading>
         <form id="converse-login" class="converse-form" method="post" @submit=${el.onLoginFormSubmitted}>
-            <div class="conn-feedback fade-in ${ !pretty_status ? 'hidden' : feedback_class}">
-                <p class="feedback-subject">${ pretty_status }</p>
-                <p class="feedback-message ${ !conn_feedback_message ? 'hidden' : '' }">${conn_feedback_message}</p>
+            <div class="conn-feedback fade-in ${!pretty_status ? 'hidden' : feedback_class}">
+                <p class="feedback-subject">${pretty_status}</p>
+                <p class="feedback-message ${!conn_feedback_message ? 'hidden' : ''}">${conn_feedback_message}</p>
             </div>
-            ${ (CONNECTION_STATUS[connection_status] === 'CONNECTING') ? tplSpinner({'classes': 'hor_centered'}) : form_fields(el) }
+            ${CONNECTION_STATUS[connection_status] === 'CONNECTING'
+                ? tplSpinner({ 'classes': 'hor_centered' })
+                : form_fields(el)}
         </form>`;
-}
+};