Skip to content
Snippets Groups Projects
Commit ab105550 authored by Reiter, Christoph's avatar Reiter, Christoph :snake:
Browse files

Re-format all code

parent 44c83e8d
No related branches found
No related tags found
1 merge request!124Add prettier
Pipeline #86099 passed
Showing
with 689 additions and 601 deletions
module.exports = { module.exports = {
input: [ input: ['src/*.js'],
'src/*.js',
],
output: './', output: './',
options: { options: {
debug: false, debug: false,
...@@ -10,7 +8,7 @@ module.exports = { ...@@ -10,7 +8,7 @@ module.exports = {
lngs: ['en', 'de'], lngs: ['en', 'de'],
resource: { resource: {
loadPath: 'src/i18n/{{lng}}/{{ns}}.json', loadPath: 'src/i18n/{{lng}}/{{ns}}.json',
savePath: 'src/i18n/{{lng}}/{{ns}}.json' savePath: 'src/i18n/{{lng}}/{{ns}}.json',
}, },
}, },
} };
...@@ -2,43 +2,51 @@ import glob from 'glob'; ...@@ -2,43 +2,51 @@ import glob from 'glob';
import resolve from '@rollup/plugin-node-resolve'; import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs'; import commonjs from '@rollup/plugin-commonjs';
import copy from 'rollup-plugin-copy'; import copy from 'rollup-plugin-copy';
import {terser} from "rollup-plugin-terser"; import {terser} from 'rollup-plugin-terser';
import json from '@rollup/plugin-json'; import json from '@rollup/plugin-json';
import serve from 'rollup-plugin-serve'; import serve from 'rollup-plugin-serve';
import del from 'rollup-plugin-delete'; import del from 'rollup-plugin-delete';
import {getPackagePath, getDistPath} from '../../rollup.utils.js'; import {getPackagePath, getDistPath} from '../../rollup.utils.js';
const pkg = require('./package.json'); const pkg = require('./package.json');
const build = (typeof process.env.BUILD !== 'undefined') ? process.env.BUILD : 'local'; const build = typeof process.env.BUILD !== 'undefined' ? process.env.BUILD : 'local';
console.log("build: " + build); console.log('build: ' + build);
export default (async () => { export default (async () => {
return { return {
input: (build != 'test') ? ['src/dbp-auth.js', 'src/dbp-auth-demo.js'] : glob.sync('test/**/*.js'), input:
build != 'test'
? ['src/dbp-auth.js', 'src/dbp-auth-demo.js']
: glob.sync('test/**/*.js'),
output: { output: {
dir: 'dist', dir: 'dist',
entryFileNames: '[name].js', entryFileNames: '[name].js',
chunkFileNames: 'shared/[name].[hash].[format].js', chunkFileNames: 'shared/[name].[hash].[format].js',
format: 'esm', format: 'esm',
sourcemap: true sourcemap: true,
}, },
plugins: [ plugins: [
del({ del({
targets: 'dist/*' targets: 'dist/*',
}), }),
resolve(), resolve(),
commonjs(), commonjs(),
json(), json(),
(build !== 'local' && build !== 'test') ? terser() : false, build !== 'local' && build !== 'test' ? terser() : false,
copy({ copy({
targets: [ targets: [
{src: 'assets/index.html', dest: 'dist'}, {src: 'assets/index.html', dest: 'dist'},
{src: 'assets/silent-check-sso.html', dest: 'dist'}, {src: 'assets/silent-check-sso.html', dest: 'dist'},
{src: 'assets/favicon.ico', dest: 'dist'}, {src: 'assets/favicon.ico', dest: 'dist'},
{src: await getPackagePath('@dbp-toolkit/common', 'assets/icons/*.svg'), dest: 'dist/' + await getDistPath('@dbp-toolkit/common', 'icons')}, {
src: await getPackagePath('@dbp-toolkit/common', 'assets/icons/*.svg'),
dest: 'dist/' + (await getDistPath('@dbp-toolkit/common', 'icons')),
},
], ],
}), }),
(process.env.ROLLUP_WATCH === 'true') ? serve({contentBase: 'dist', host: '127.0.0.1', port: 8002}) : false process.env.ROLLUP_WATCH === 'true'
] ? serve({contentBase: 'dist', host: '127.0.0.1', port: 8002})
: false,
],
}; };
})(); })();
...@@ -2,8 +2,7 @@ import {createInstance} from './i18n.js'; ...@@ -2,8 +2,7 @@ import {createInstance} from './i18n.js';
import JSONLD from '@dbp-toolkit/common/jsonld'; import JSONLD from '@dbp-toolkit/common/jsonld';
import {KeycloakWrapper} from './keycloak.js'; import {KeycloakWrapper} from './keycloak.js';
import {LoginStatus} from './util.js'; import {LoginStatus} from './util.js';
import {AdapterLitElement} from "@dbp-toolkit/provider/src/adapter-lit-element"; import {AdapterLitElement} from '@dbp-toolkit/provider/src/adapter-lit-element';
/** /**
* Keycloak auth web component * Keycloak auth web component
...@@ -20,13 +19,13 @@ export class AuthKeycloak extends AdapterLitElement { ...@@ -20,13 +19,13 @@ export class AuthKeycloak extends AdapterLitElement {
constructor() { constructor() {
super(); super();
this.forceLogin = false; this.forceLogin = false;
this.token = ""; this.token = '';
this.subject = ""; this.subject = '';
this.name = ""; this.name = '';
this.tryLogin = false; this.tryLogin = false;
this.entryPointUrl = ''; this.entryPointUrl = '';
this._user = null; this._user = null;
this._userId = ""; this._userId = '';
this._authenticated = false; this._authenticated = false;
this._loginStatus = LoginStatus.UNKNOWN; this._loginStatus = LoginStatus.UNKNOWN;
this.requestedLoginStatus = LoginStatus.UNKNOWN; this.requestedLoginStatus = LoginStatus.UNKNOWN;
...@@ -56,7 +55,7 @@ export class AuthKeycloak extends AdapterLitElement { ...@@ -56,7 +55,7 @@ export class AuthKeycloak extends AdapterLitElement {
JSONLD.getInstance(this.entryPointUrl, this.lang); JSONLD.getInstance(this.entryPointUrl, this.lang);
break; break;
case 'requestedLoginStatus': case 'requestedLoginStatus':
console.log("requested-login-status changed", this.requestedLoginStatus); console.log('requested-login-status changed', this.requestedLoginStatus);
switch (this.requestedLoginStatus) { switch (this.requestedLoginStatus) {
case LoginStatus.LOGGED_IN: case LoginStatus.LOGGED_IN:
this._kcwrapper.login({lang: this.lang, scope: this.scope || ''}); this._kcwrapper.login({lang: this.lang, scope: this.scope || ''});
...@@ -87,16 +86,16 @@ export class AuthKeycloak extends AdapterLitElement { ...@@ -87,16 +86,16 @@ export class AuthKeycloak extends AdapterLitElement {
jsonld = await JSONLD.getInstance(this.entryPointUrl, this.lang); jsonld = await JSONLD.getInstance(this.entryPointUrl, this.lang);
let baseUrl = ''; let baseUrl = '';
try { try {
baseUrl = jsonld.getApiUrlForEntityName("FrontendUser"); baseUrl = jsonld.getApiUrlForEntityName('FrontendUser');
} catch (error) { } catch (error) {
// backwards compat // backwards compat
baseUrl = jsonld.getApiUrlForEntityName("Person"); baseUrl = jsonld.getApiUrlForEntityName('Person');
} }
const apiUrl = baseUrl + '/' + encodeURIComponent(userId); const apiUrl = baseUrl + '/' + encodeURIComponent(userId);
let response = await fetch(apiUrl, { let response = await fetch(apiUrl, {
headers: { headers: {
'Authorization': 'Bearer ' + this.token, Authorization: 'Bearer ' + this.token,
}, },
}); });
if (!response.ok) { if (!response.ok) {
...@@ -114,13 +113,13 @@ export class AuthKeycloak extends AdapterLitElement { ...@@ -114,13 +113,13 @@ export class AuthKeycloak extends AdapterLitElement {
this._authenticated = kc.authenticated; this._authenticated = kc.authenticated;
if (kc.authenticated) { if (kc.authenticated) {
let tokenChanged = (this.token !== kc.token); let tokenChanged = this.token !== kc.token;
this.name = kc.idTokenParsed.name; this.name = kc.idTokenParsed.name;
this.token = kc.token; this.token = kc.token;
this.subject = kc.subject; this.subject = kc.subject;
const userId = kc.idTokenParsed.preferred_username; const userId = kc.idTokenParsed.preferred_username;
let userChanged = (userId !== this._userId); let userChanged = userId !== this._userId;
if (userChanged) { if (userChanged) {
this._userId = userId; this._userId = userId;
let user; let user;
...@@ -144,10 +143,10 @@ export class AuthKeycloak extends AdapterLitElement { ...@@ -144,10 +143,10 @@ export class AuthKeycloak extends AdapterLitElement {
if (this._loginStatus === LoginStatus.LOGGED_IN) { if (this._loginStatus === LoginStatus.LOGGED_IN) {
this._setLoginStatus(LoginStatus.LOGGING_OUT); this._setLoginStatus(LoginStatus.LOGGING_OUT);
} }
this.name = ""; this.name = '';
this.token = ""; this.token = '';
this.subject = ""; this.subject = '';
this._userId = ""; this._userId = '';
this._user = null; this._user = null;
this._setLoginStatus(LoginStatus.LOGGED_OUT); this._setLoginStatus(LoginStatus.LOGGED_OUT);
...@@ -157,13 +156,13 @@ export class AuthKeycloak extends AdapterLitElement { ...@@ -157,13 +156,13 @@ export class AuthKeycloak extends AdapterLitElement {
sendSetPropertyEvents() { sendSetPropertyEvents() {
const auth = { const auth = {
'login-status': this._loginStatus, 'login-status': this._loginStatus,
'subject': this.subject, subject: this.subject,
'token': this.token, token: this.token,
'user-full-name': this.name, 'user-full-name': this.name,
'user-id': this._userId, 'user-id': this._userId,
// Deprecated // Deprecated
'person-id': this._userId, 'person-id': this._userId,
'person': this._user, person: this._user,
}; };
// inject a window.DBPAuth variable for cypress // inject a window.DBPAuth variable for cypress
...@@ -175,8 +174,7 @@ export class AuthKeycloak extends AdapterLitElement { ...@@ -175,8 +174,7 @@ export class AuthKeycloak extends AdapterLitElement {
} }
_setLoginStatus(status, force) { _setLoginStatus(status, force) {
if (this._loginStatus === status && !force) if (this._loginStatus === status && !force) return;
return;
this._loginStatus = status; this._loginStatus = status;
this.sendSetPropertyEvents(); this.sendSetPropertyEvents();
...@@ -208,13 +206,16 @@ export class AuthKeycloak extends AdapterLitElement { ...@@ -208,13 +206,16 @@ export class AuthKeycloak extends AdapterLitElement {
connectedCallback() { connectedCallback() {
super.connectedCallback(); super.connectedCallback();
if (!this.keycloakUrl) if (!this.keycloakUrl) throw Error('url not set');
throw Error("url not set"); if (!this.realm) throw Error('realm not set');
if (!this.realm) if (!this.clientId) throw Error('client-id not set');
throw Error("realm not set"); this._kcwrapper = new KeycloakWrapper(
if (!this.clientId) this.keycloakUrl,
throw Error("client-id not set"); this.realm,
this._kcwrapper = new KeycloakWrapper(this.keycloakUrl, this.realm, this.clientId, this.silentCheckSsoRedirectUri, this.idpHint); this.clientId,
this.silentCheckSsoRedirectUri,
this.idpHint
);
this._kcwrapper.addEventListener('changed', this._onKCChanged); this._kcwrapper.addEventListener('changed', this._onKCChanged);
const handleLogin = async () => { const handleLogin = async () => {
......
...@@ -5,7 +5,7 @@ import {AuthKeycloak} from './auth-keycloak.js'; ...@@ -5,7 +5,7 @@ import {AuthKeycloak} from './auth-keycloak.js';
import {LoginButton} from './login-button.js'; import {LoginButton} from './login-button.js';
import * as commonUtils from '@dbp-toolkit/common/utils'; import * as commonUtils from '@dbp-toolkit/common/utils';
//import {name as pkgName} from './../package.json'; //import {name as pkgName} from './../package.json';
import DBPLitElement from "@dbp-toolkit/common/dbp-lit-element"; import DBPLitElement from '@dbp-toolkit/common/dbp-lit-element';
export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) { export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) {
constructor() { constructor() {
...@@ -36,7 +36,7 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) { ...@@ -36,7 +36,7 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) {
update(changedProperties) { update(changedProperties) {
changedProperties.forEach((oldValue, propName) => { changedProperties.forEach((oldValue, propName) => {
if (propName === "lang") { if (propName === 'lang') {
this._i18n.changeLanguage(this.lang); this._i18n.changeLanguage(this.lang);
} }
}); });
...@@ -47,21 +47,20 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) { ...@@ -47,21 +47,20 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) {
async _onUserInfoClick() { async _onUserInfoClick() {
const div = this._('#person-info'); const div = this._('#person-info');
if (!this.auth.token) { if (!this.auth.token) {
console.error("not logged in"); console.error('not logged in');
div.innerHTML = "You are not logged in!"; div.innerHTML = 'You are not logged in!';
return; return;
} }
let userInfoURL = 'https://auth-dev.tugraz.at/auth/realms/tugraz-vpu/protocol/openid-connect/userinfo'; let userInfoURL =
'https://auth-dev.tugraz.at/auth/realms/tugraz-vpu/protocol/openid-connect/userinfo';
// NOTE: the URL and realm need to match the keycloak config above // NOTE: the URL and realm need to match the keycloak config above
const response = await fetch( const response = await fetch(userInfoURL, {
userInfoURL, {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.auth.token Authorization: 'Bearer ' + this.auth.token,
} },
} });
);
const person = await response.json(); const person = await response.json();
console.log(person); console.log(person);
div.innerHTML = JSON.stringify(person); div.innerHTML = JSON.stringify(person);
...@@ -70,8 +69,8 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) { ...@@ -70,8 +69,8 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) {
async _onShowToken() { async _onShowToken() {
const div = this._('#token-info'); const div = this._('#token-info');
if (!this.auth.token) { if (!this.auth.token) {
console.error("not logged in"); console.error('not logged in');
div.innerHTML = "You are not logged in!"; div.innerHTML = 'You are not logged in!';
return; return;
} }
...@@ -80,11 +79,21 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) { ...@@ -80,11 +79,21 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) {
} }
getAuthComponentHtml() { getAuthComponentHtml() {
return this.noAuth ? html`<dbp-login-button subscribe="auth" lang="${this.lang}"></dbp-login-button>` : html` return this.noAuth
? html`
<dbp-login-button subscribe="auth" lang="${this.lang}"></dbp-login-button>
`
: html`
<div class="container"> <div class="container">
<dbp-auth-keycloak subscribe="requested-login-status" lang="${this.lang}" entry-point-url="${this.entryPointUrl}" silent-check-sso-redirect-uri="/silent-check-sso.html" <dbp-auth-keycloak
url="https://auth-dev.tugraz.at/auth" realm="tugraz-vpu" subscribe="requested-login-status"
client-id="auth-dev-mw-frontend-local" try-login></dbp-auth-keycloak> lang="${this.lang}"
entry-point-url="${this.entryPointUrl}"
silent-check-sso-redirect-uri="/silent-check-sso.html"
url="https://auth-dev.tugraz.at/auth"
realm="tugraz-vpu"
client-id="auth-dev-mw-frontend-local"
try-login></dbp-auth-keycloak>
<dbp-login-button subscribe="auth" lang="${this.lang}"></dbp-login-button> <dbp-login-button subscribe="auth" lang="${this.lang}"></dbp-login-button>
</div> </div>
`; `;
...@@ -100,9 +109,14 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) { ...@@ -100,9 +109,14 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) {
} }
.content h1 { .content h1 {
font-size: 2em; font-size: 2em;
margin-bottom: .5em; margin-bottom: 0.5em;
} }
.content h1, .content h2, .content h3, .content h4, .content h5, .content h6 { .content h1,
.content h2,
.content h3,
.content h4,
.content h5,
.content h6 {
color: var(--dbp-text); color: var(--dbp-text);
font-weight: 600; font-weight: 600;
line-height: 1.125; line-height: 1.125;
...@@ -118,8 +132,8 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) { ...@@ -118,8 +132,8 @@ export class DbpAuthDemo extends ScopedElementsMixin(DBPLitElement) {
</div> </div>
${this.getAuthComponentHtml()} ${this.getAuthComponentHtml()}
<div class="container"> <div class="container">
<input type="button" value="Fetch userinfo" @click="${this._onUserInfoClick}"> <input type="button" value="Fetch userinfo" @click="${this._onUserInfoClick}" />
<input type="button" value="Show token" @click="${this._onShowToken}"> <input type="button" value="Show token" @click="${this._onShowToken}" />
<h4>Person info:</h4> <h4>Person info:</h4>
<div id="person-info"></div> <div id="person-info"></div>
<h4>Token info:</h4> <h4>Token info:</h4>
......
import {EventTarget} from "event-target-shim"; // Because EventTarget() doesn't exist on Safari import {EventTarget} from 'event-target-shim'; // Because EventTarget() doesn't exist on Safari
/** /**
* Imports the keycloak JS API as if it was a module. * Imports the keycloak JS API as if it was a module.
...@@ -10,14 +9,12 @@ async function importKeycloak(baseUrl) { ...@@ -10,14 +9,12 @@ async function importKeycloak(baseUrl) {
const keycloakSrc = baseUrl + '/js/keycloak.min.js'; const keycloakSrc = baseUrl + '/js/keycloak.min.js';
// Importing will write it to window so we take it from there // Importing will write it to window so we take it from there
await import(keycloakSrc); await import(keycloakSrc);
if (importKeycloak._keycloakMod !== undefined) if (importKeycloak._keycloakMod !== undefined) return importKeycloak._keycloakMod;
return importKeycloak._keycloakMod;
importKeycloak._keycloakMod = window.Keycloak; importKeycloak._keycloakMod = window.Keycloak;
delete window.Keycloak; delete window.Keycloak;
return importKeycloak._keycloakMod; return importKeycloak._keycloakMod;
} }
const promiseTimeout = function (ms, promise) { const promiseTimeout = function (ms, promise) {
let timeout = new Promise((resolve, reject) => { let timeout = new Promise((resolve, reject) => {
let id = setTimeout(() => { let id = setTimeout(() => {
...@@ -26,13 +23,9 @@ const promiseTimeout = function(ms, promise) { ...@@ -26,13 +23,9 @@ const promiseTimeout = function(ms, promise) {
}, ms); }, ms);
}); });
return Promise.race([ return Promise.race([promise, timeout]);
promise,
timeout
]);
}; };
/** /**
* Returns a URL for a relative path or URL * Returns a URL for a relative path or URL
* *
...@@ -46,7 +39,6 @@ const ensureURL = function(urlOrPath) { ...@@ -46,7 +39,6 @@ const ensureURL = function(urlOrPath) {
} }
}; };
/** /**
* Wraps the keycloak API to support async/await, adds auto token refreshing and consolidates all * Wraps the keycloak API to support async/await, adds auto token refreshing and consolidates all
* events into one native "changed" event * events into one native "changed" event
...@@ -54,7 +46,6 @@ const ensureURL = function(urlOrPath) { ...@@ -54,7 +46,6 @@ const ensureURL = function(urlOrPath) {
* The "changed" event has the real keycloak instance as "detail" * The "changed" event has the real keycloak instance as "detail"
*/ */
export class KeycloakWrapper extends EventTarget { export class KeycloakWrapper extends EventTarget {
constructor(baseURL, realm, clientId, silentCheckSsoUri, idpHint) { constructor(baseURL, realm, clientId, silentCheckSsoUri, idpHint) {
super(); super();
...@@ -77,36 +68,35 @@ export class KeycloakWrapper extends EventTarget { ...@@ -77,36 +68,35 @@ export class KeycloakWrapper extends EventTarget {
this.DEBUG = false; this.DEBUG = false;
this._onVisibilityChanged = this._onVisibilityChanged.bind(this); this._onVisibilityChanged = this._onVisibilityChanged.bind(this);
document.addEventListener("visibilitychange", this._onVisibilityChanged); document.addEventListener('visibilitychange', this._onVisibilityChanged);
} }
/** /**
* This needs to be called or the instance will leak; * This needs to be called or the instance will leak;
*/ */
close() { close() {
document.removeEventListener("visibilitychange", this._onVisibilityChanged); document.removeEventListener('visibilitychange', this._onVisibilityChanged);
} }
_onVisibilityChanged() { _onVisibilityChanged() {
let isVisible = (document.visibilityState === 'visible'); let isVisible = document.visibilityState === 'visible';
if (isVisible && this._keycloak.authenticated) { if (isVisible && this._keycloak.authenticated) {
this._checkTokeHasExpired(); this._checkTokeHasExpired();
} }
} }
_onChanged() { _onChanged() {
const event = new CustomEvent("changed", { const event = new CustomEvent('changed', {
detail: this._keycloak, detail: this._keycloak,
bubbles: true, bubbles: true,
composed: true composed: true,
}); });
this.dispatchEvent(event); this.dispatchEvent(event);
} }
_onReady(authenticated) { _onReady(authenticated) {
// Avoid emitting changed when nothing has changed on init() // Avoid emitting changed when nothing has changed on init()
if (authenticated) if (authenticated) this._onChanged();
this._onChanged();
} }
async _onTokenExpired() { async _onTokenExpired() {
...@@ -121,7 +111,7 @@ export class KeycloakWrapper extends EventTarget { ...@@ -121,7 +111,7 @@ export class KeycloakWrapper extends EventTarget {
return; return;
} }
console.assert(refreshed, "token should have been refreshed"); console.assert(refreshed, 'token should have been refreshed');
} }
async _checkTokeHasExpired() { async _checkTokeHasExpired() {
...@@ -137,8 +127,7 @@ export class KeycloakWrapper extends EventTarget { ...@@ -137,8 +127,7 @@ export class KeycloakWrapper extends EventTarget {
console.log('Failed to refresh the token', error); console.log('Failed to refresh the token', error);
} }
if (this.DEBUG && refreshed) if (this.DEBUG && refreshed) console.log('token has been refreshed');
console.log("token has been refreshed");
} }
async _onAuthSuccess() { async _onAuthSuccess() {
...@@ -148,7 +137,10 @@ export class KeycloakWrapper extends EventTarget { ...@@ -148,7 +137,10 @@ export class KeycloakWrapper extends EventTarget {
clearInterval(this._checkId); clearInterval(this._checkId);
this._checkId = null; this._checkId = null;
} }
this._checkId = setInterval(this._checkTokeHasExpired.bind(this), this.CHECK_INTERVAL * 1000); this._checkId = setInterval(
this._checkTokeHasExpired.bind(this),
this.CHECK_INTERVAL * 1000
);
this._onChanged(); this._onChanged();
} }
...@@ -163,8 +155,7 @@ export class KeycloakWrapper extends EventTarget { ...@@ -163,8 +155,7 @@ export class KeycloakWrapper extends EventTarget {
} }
async _ensureInstance() { async _ensureInstance() {
if (this._keycloak !== null) if (this._keycloak !== null) return;
return;
const Keycloak = await importKeycloak(this._baseURL); const Keycloak = await importKeycloak(this._baseURL);
...@@ -195,8 +186,7 @@ export class KeycloakWrapper extends EventTarget { ...@@ -195,8 +186,7 @@ export class KeycloakWrapper extends EventTarget {
async _ensureInit() { async _ensureInit() {
await this._ensureInstance(); await this._ensureInstance();
if (this._initDone) if (this._initDone) return;
return;
this._initDone = true; this._initDone = true;
const options = { const options = {
...@@ -209,7 +199,6 @@ export class KeycloakWrapper extends EventTarget { ...@@ -209,7 +199,6 @@ export class KeycloakWrapper extends EventTarget {
} }
if (this._silentCheckSsoUri) { if (this._silentCheckSsoUri) {
options['onLoad'] = 'check-sso'; options['onLoad'] = 'check-sso';
options['silentCheckSsoRedirectUri'] = ensureURL(this._silentCheckSsoUri); options['silentCheckSsoRedirectUri'] = ensureURL(this._silentCheckSsoUri);
...@@ -222,7 +211,6 @@ export class KeycloakWrapper extends EventTarget { ...@@ -222,7 +211,6 @@ export class KeycloakWrapper extends EventTarget {
} else { } else {
await this._keycloakInit(options); await this._keycloakInit(options);
} }
} }
/** /**
...@@ -230,7 +218,7 @@ export class KeycloakWrapper extends EventTarget { ...@@ -230,7 +218,7 @@ export class KeycloakWrapper extends EventTarget {
*/ */
isLoggingIn() { isLoggingIn() {
const href = window.location.href; const href = window.location.href;
return (href.search('[&#]state=') >= 0 && href.search('[&#]session_state=') >= 0); return href.search('[&#]state=') >= 0 && href.search('[&#]session_state=') >= 0;
} }
/** /**
......
...@@ -52,7 +52,6 @@ let loginSVG = ` ...@@ -52,7 +52,6 @@ let loginSVG = `
`; `;
export class LoginButton extends ScopedElementsMixin(AdapterLitElement) { export class LoginButton extends ScopedElementsMixin(AdapterLitElement) {
constructor() { constructor() {
super(); super();
this._i18n = createInstance(); this._i18n = createInstance();
...@@ -93,7 +92,7 @@ export class LoginButton extends ScopedElementsMixin(AdapterLitElement) { ...@@ -93,7 +92,7 @@ export class LoginButton extends ScopedElementsMixin(AdapterLitElement) {
update(changedProperties) { update(changedProperties) {
changedProperties.forEach((oldValue, propName) => { changedProperties.forEach((oldValue, propName) => {
if (propName === "lang") { if (propName === 'lang') {
this._i18n.changeLanguage(this.lang); this._i18n.changeLanguage(this.lang);
} }
}); });
...@@ -124,12 +123,14 @@ export class LoginButton extends ScopedElementsMixin(AdapterLitElement) { ...@@ -124,12 +123,14 @@ export class LoginButton extends ScopedElementsMixin(AdapterLitElement) {
transition: background-color 0.15s, color 0.15s; transition: background-color 0.15s, color 0.15s;
} }
.login-box svg, .icon { .login-box svg,
.icon {
width: 1.1em; width: 1.1em;
height: 1.1em; height: 1.1em;
} }
.login-box svg, .spinner { .login-box svg,
.spinner {
display: flex; display: flex;
} }
...@@ -147,7 +148,7 @@ export class LoginButton extends ScopedElementsMixin(AdapterLitElement) { ...@@ -147,7 +148,7 @@ export class LoginButton extends ScopedElementsMixin(AdapterLitElement) {
.login-box .label { .login-box .label {
padding-left: 0.2em; padding-left: 0.2em;
} }
` `,
]; ];
} }
...@@ -158,7 +159,9 @@ export class LoginButton extends ScopedElementsMixin(AdapterLitElement) { ...@@ -158,7 +159,9 @@ export class LoginButton extends ScopedElementsMixin(AdapterLitElement) {
return html` return html`
<a href="#"> <a href="#">
<div class="login-box login-button"> <div class="login-box login-button">
<div class="icon"><dbp-mini-spinner class="spinner"></dbp-mini-spinner></div> <div class="icon">
<dbp-mini-spinner class="spinner"></dbp-mini-spinner>
</div>
<div class="label">&#8203;</div> <div class="label">&#8203;</div>
</div> </div>
</a> </a>
......
module.exports = { module.exports = {
input: [ input: ['src/*.js'],
'src/*.js',
],
output: './', output: './',
options: { options: {
debug: false, debug: false,
...@@ -10,7 +8,7 @@ module.exports = { ...@@ -10,7 +8,7 @@ module.exports = {
lngs: ['en', 'de'], lngs: ['en', 'de'],
resource: { resource: {
loadPath: 'src/i18n/{{lng}}/{{ns}}.json', loadPath: 'src/i18n/{{lng}}/{{ns}}.json',
savePath: 'src/i18n/{{lng}}/{{ns}}.json' savePath: 'src/i18n/{{lng}}/{{ns}}.json',
}, },
}, },
} };
...@@ -2,49 +2,55 @@ import glob from 'glob'; ...@@ -2,49 +2,55 @@ import glob from 'glob';
import resolve from '@rollup/plugin-node-resolve'; import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs'; import commonjs from '@rollup/plugin-commonjs';
import copy from 'rollup-plugin-copy'; import copy from 'rollup-plugin-copy';
import {terser} from "rollup-plugin-terser"; import {terser} from 'rollup-plugin-terser';
import json from '@rollup/plugin-json'; import json from '@rollup/plugin-json';
import serve from 'rollup-plugin-serve'; import serve from 'rollup-plugin-serve';
import url from "@rollup/plugin-url" import url from '@rollup/plugin-url';
import del from 'rollup-plugin-delete'; import del from 'rollup-plugin-delete';
import {getPackagePath, getDistPath} from '../../rollup.utils.js'; import {getPackagePath, getDistPath} from '../../rollup.utils.js';
const build = (typeof process.env.BUILD !== 'undefined') ? process.env.BUILD : 'local'; const build = typeof process.env.BUILD !== 'undefined' ? process.env.BUILD : 'local';
console.log("build: " + build); console.log('build: ' + build);
export default (async () => { export default (async () => {
return { return {
input: (build != 'test') ? ['src/dbp-check-in-place-select.js', 'src/dbp-check-in-place-select-demo.js'] : glob.sync('test/**/*.js'), input:
build != 'test'
? ['src/dbp-check-in-place-select.js', 'src/dbp-check-in-place-select-demo.js']
: glob.sync('test/**/*.js'),
output: { output: {
dir: 'dist', dir: 'dist',
entryFileNames: '[name].js', entryFileNames: '[name].js',
chunkFileNames: 'shared/[name].[hash].[format].js', chunkFileNames: 'shared/[name].[hash].[format].js',
format: 'esm', format: 'esm',
sourcemap: true sourcemap: true,
}, },
plugins: [ plugins: [
del({ del({
targets: 'dist/*' targets: 'dist/*',
}), }),
resolve(), resolve(),
commonjs(), commonjs(),
url({ url({
limit: 0, limit: 0,
include: [ include: [await getPackagePath('select2', '**/*.css')],
await getPackagePath('select2', '**/*.css'),
],
emitFiles: true, emitFiles: true,
fileName: 'shared/[name].[hash][extname]' fileName: 'shared/[name].[hash][extname]',
}), }),
json(), json(),
(build !== 'local' && build !== 'test') ? terser() : false, build !== 'local' && build !== 'test' ? terser() : false,
copy({ copy({
targets: [ targets: [
{src: 'assets/index.html', dest: 'dist'}, {src: 'assets/index.html', dest: 'dist'},
{src: await getPackagePath('@dbp-toolkit/common', 'assets/icons/*.svg'), dest: 'dist/' + await getDistPath('@dbp-toolkit/common', 'icons')}, {
src: await getPackagePath('@dbp-toolkit/common', 'assets/icons/*.svg'),
dest: 'dist/' + (await getDistPath('@dbp-toolkit/common', 'icons')),
},
], ],
}), }),
(process.env.ROLLUP_WATCH === 'true') ? serve({contentBase: 'dist', host: '127.0.0.1', port: 8002}) : false process.env.ROLLUP_WATCH === 'true'
] ? serve({contentBase: 'dist', host: '127.0.0.1', port: 8002})
: false,
],
}; };
})(); })();
...@@ -9,19 +9,16 @@ import {Icon} from '@dbp-toolkit/common'; ...@@ -9,19 +9,16 @@ import {Icon} from '@dbp-toolkit/common';
import * as commonUtils from '@dbp-toolkit/common/utils'; import * as commonUtils from '@dbp-toolkit/common/utils';
import * as commonStyles from '@dbp-toolkit/common/styles'; import * as commonStyles from '@dbp-toolkit/common/styles';
import select2CSSPath from 'select2/dist/css/select2.min.css'; import select2CSSPath from 'select2/dist/css/select2.min.css';
import * as errorUtils from "@dbp-toolkit/common/error"; import * as errorUtils from '@dbp-toolkit/common/error';
import {AdapterLitElement} from "@dbp-toolkit/provider/src/adapter-lit-element"; import {AdapterLitElement} from '@dbp-toolkit/provider/src/adapter-lit-element';
const checkInPlaceContext = { const checkInPlaceContext = {
"@id": "@id", '@id': '@id',
"name": "http://schema.org/name", name: 'http://schema.org/name',
"maximumPhysicalAttendeeCapacity": "http://schema.org/maximumPhysicalAttendeeCapacity" maximumPhysicalAttendeeCapacity: 'http://schema.org/maximumPhysicalAttendeeCapacity',
}; };
export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
constructor() { constructor() {
super(); super();
Object.assign(CheckInPlaceSelect.prototype, errorUtils.errorMixin); Object.assign(CheckInPlaceSelect.prototype, errorUtils.errorMixin);
...@@ -53,10 +50,9 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -53,10 +50,9 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
} }
$(selector) { $(selector) {
if (typeof selector === "string") if (typeof selector === 'string')
return this._jquery(this.shadowRoot.querySelector(selector)); return this._jquery(this.shadowRoot.querySelector(selector));
else else return this._jquery(selector);
return this._jquery(selector);
} }
static get properties() { static get properties() {
...@@ -76,9 +72,9 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -76,9 +72,9 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
clear() { clear() {
this.object = null; this.object = null;
this.$(this).attr("data-object", ""); this.$(this).attr('data-object', '');
this.$(this).attr("value", ""); this.$(this).attr('value', '');
this.$(this).data("object", null); this.$(this).data('object', null);
this.$select.val(null).trigger('change').trigger('select2:unselect'); this.$select.val(null).trigger('change').trigger('select2:unselect');
} }
...@@ -106,10 +102,9 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -106,10 +102,9 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
} }
_onDocumentClicked(event) { _onDocumentClicked(event) {
if (event.composedPath().includes(this)) if (event.composedPath().includes(this)) return;
return;
const $select = this.$('#' + this.selectId); const $select = this.$('#' + this.selectId);
console.assert($select.length, "select2 missing"); console.assert($select.length, 'select2 missing');
if (this.select2IsInitialized($select)) { if (this.select2IsInitialized($select)) {
$select.select2('close'); $select.select2('close');
} }
...@@ -118,14 +113,24 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -118,14 +113,24 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
initJSONLD(ignorePreset = false) { initJSONLD(ignorePreset = false) {
const that = this; const that = this;
JSONLD.getInstance(this.entryPointUrl).then(function (jsonld) { JSONLD.getInstance(this.entryPointUrl).then(
function (jsonld) {
that.jsonld = jsonld; that.jsonld = jsonld;
that.active = true; that.active = true;
// we need to poll because maybe the user interface isn't loaded yet // we need to poll because maybe the user interface isn't loaded yet
// Note: we need to call initSelect2() in a different function so we can access "this" inside initSelect2() // Note: we need to call initSelect2() in a different function so we can access "this" inside initSelect2()
commonUtils.pollFunc(() => { return that.initSelect2(ignorePreset); }, 10000, 100); commonUtils.pollFunc(
}, {}, this.lang); () => {
return that.initSelect2(ignorePreset);
},
10000,
100
);
},
{},
this.lang
);
} }
/** /**
...@@ -142,7 +147,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -142,7 +147,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
} }
// find the correct api url for a checkInPlace // find the correct api url for a checkInPlace
const apiUrl = this.jsonld.getApiUrlForIdentifier("http://schema.org/Place"); const apiUrl = this.jsonld.getApiUrlForIdentifier('http://schema.org/Place');
// const apiUrl = this.jsonld.getApiUrlForEntityName("CheckInPlace"); // const apiUrl = this.jsonld.getApiUrlForEntityName("CheckInPlace");
if (this.$select === null) { if (this.$select === null) {
...@@ -156,16 +161,17 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -156,16 +161,17 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
this.$select.off('select2:closing'); this.$select.off('select2:closing');
} }
this.$select.select2({ this.$select
.select2({
width: '100%', width: '100%',
language: this.lang === "de" ? select2LangDe() : select2LangEn(), language: this.lang === 'de' ? select2LangDe() : select2LangEn(),
minimumInputLength: 2, minimumInputLength: 2,
placeholder: this._i18n.t('check-in-place-select.placeholder'), placeholder: this._i18n.t('check-in-place-select.placeholder'),
dropdownParent: this.$('#check-in-place-select-dropdown'), dropdownParent: this.$('#check-in-place-select-dropdown'),
ajax: { ajax: {
delay: 500, delay: 500,
url: apiUrl, url: apiUrl,
contentType: "application/ld+json", contentType: 'application/ld+json',
beforeSend: function (jqXHR) { beforeSend: function (jqXHR) {
jqXHR.setRequestHeader('Authorization', 'Bearer ' + that.auth.token); jqXHR.setRequestHeader('Authorization', 'Bearer ' + that.auth.token);
that.isSearching = true; that.isSearching = true;
...@@ -182,28 +188,36 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -182,28 +188,36 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
let transformed = that.jsonld.transformMembers(data, checkInPlaceContext); let transformed = that.jsonld.transformMembers(data, checkInPlaceContext);
const results = []; const results = [];
transformed.forEach((place) => { transformed.forEach((place) => {
results.push({id: place["@id"], maximumPhysicalAttendeeCapacity: place["maximumPhysicalAttendeeCapacity"], text: that.generateOptionText(place)}); results.push({
id: place['@id'],
maximumPhysicalAttendeeCapacity:
place['maximumPhysicalAttendeeCapacity'],
text: that.generateOptionText(place),
});
}); });
return { return {
results: results results: results,
}; };
}, },
error: (jqXHR, textStatus, errorThrown) => { this.handleXhrError(jqXHR, textStatus, errorThrown); }, error: (jqXHR, textStatus, errorThrown) => {
this.handleXhrError(jqXHR, textStatus, errorThrown);
},
complete: (jqXHR, textStatus) => { complete: (jqXHR, textStatus) => {
that.isSearching = false; that.isSearching = false;
} },
} },
}).on("select2:open", function (e) { })
.on('select2:open', function (e) {
const selectId = e.target.id; const selectId = e.target.id;
that.$(".select2-search__field[aria-controls='select2-" + selectId + "-results']").each(function ( that.$(
key, ".select2-search__field[aria-controls='select2-" + selectId + "-results']"
value, ).each(function (key, value) {
) {
value.focus(); value.focus();
}); });
}).on("select2:select", function (e) { })
.on('select2:select', function (e) {
that.$('#check-in-place-select-dropdown').removeClass('select2-bug'); that.$('#check-in-place-select-dropdown').removeClass('select2-bug');
// set custom element attributes // set custom element attributes
const identifier = e.params.data.id; const identifier = e.params.data.id;
...@@ -212,26 +226,29 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -212,26 +226,29 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
const room = that.object.identifier; const room = that.object.identifier;
$this.attr("data-object", JSON.stringify(that.object)); $this.attr('data-object', JSON.stringify(that.object));
$this.data("object", that.object); $this.data('object', that.object);
const roomName = that.object.name; const roomName = that.object.name;
if ($this.attr("value") !== identifier) { if ($this.attr('value') !== identifier) {
that.ignoreValueUpdate = true; that.ignoreValueUpdate = true;
$this.attr("value", identifier); $this.attr('value', identifier);
// fire a change event // fire a change event
that.dispatchEvent(new CustomEvent('change', { that.dispatchEvent(
new CustomEvent('change', {
detail: { detail: {
value: identifier, value: identifier,
capacity: maxCapacity, capacity: maxCapacity,
room: room, room: room,
name: roomName, name: roomName,
}, },
bubbles: true bubbles: true,
})); })
);
} }
}).on("select2:closing", (e) => { })
.on('select2:closing', (e) => {
if (that.isSearching) { if (that.isSearching) {
e.preventDefault(); e.preventDefault();
} }
...@@ -249,37 +266,48 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -249,37 +266,48 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
fetch(apiUrl, { fetch(apiUrl, {
headers: { headers: {
'Content-Type': 'application/ld+json', 'Content-Type': 'application/ld+json',
'Authorization': 'Bearer ' + this.auth.token, Authorization: 'Bearer ' + this.auth.token,
}, },
}) })
.then(result => { .then((result) => {
if (!result.ok) throw result; if (!result.ok) throw result;
return result.json(); return result.json();
}) })
.then((place) => { .then((place) => {
that.object = place; that.object = place;
const transformed = that.jsonld.compactMember(that.jsonld.expandMember(place), checkInPlaceContext); const transformed = that.jsonld.compactMember(
const identifier = transformed["@id"]; that.jsonld.expandMember(place),
const maxCapacity = transformed["maximumPhysicalAttendeeCapacity"]; checkInPlaceContext
const roomName = transformed["name"]; );
const identifier = transformed['@id'];
const maxCapacity = transformed['maximumPhysicalAttendeeCapacity'];
const roomName = transformed['name'];
const room = place.identifier; const room = place.identifier;
const option = new Option(that.generateOptionText(transformed), identifier, true, true); const option = new Option(
$this.attr("data-object", JSON.stringify(place)); that.generateOptionText(transformed),
$this.data("object", place); identifier,
true,
true
);
$this.attr('data-object', JSON.stringify(place));
$this.data('object', place);
that.$select.append(option).trigger('change'); that.$select.append(option).trigger('change');
// fire a change event // fire a change event
that.dispatchEvent(new CustomEvent('change', { that.dispatchEvent(
new CustomEvent('change', {
detail: { detail: {
value: identifier, value: identifier,
capacity: maxCapacity, capacity: maxCapacity,
room: room, room: room,
name: roomName, name: roomName,
}, },
bubbles: true bubbles: true,
})); })
}).catch((e) => { );
})
.catch((e) => {
console.log(e); console.log(e);
that.clear(); that.clear();
}); });
...@@ -289,11 +317,15 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -289,11 +317,15 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
} }
generateOptionText(place) { generateOptionText(place) {
let text = place["name"]; let text = place['name'];
// add maximum capacity to checkInPlace if present // add maximum capacity to checkInPlace if present
if (this.showCapacity && (place["maximumPhysicalAttendeeCapacity"] !== undefined) && (place["maximumPhysicalAttendeeCapacity"] !== null)) { if (
let capacity = place["maximumPhysicalAttendeeCapacity"]; this.showCapacity &&
place['maximumPhysicalAttendeeCapacity'] !== undefined &&
place['maximumPhysicalAttendeeCapacity'] !== null
) {
let capacity = place['maximumPhysicalAttendeeCapacity'];
text += ` (${capacity})`; text += ` (${capacity})`;
} }
...@@ -303,7 +335,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -303,7 +335,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
update(changedProperties) { update(changedProperties) {
changedProperties.forEach((oldValue, propName) => { changedProperties.forEach((oldValue, propName) => {
switch (propName) { switch (propName) {
case "lang": case 'lang':
this._i18n.changeLanguage(this.lang); this._i18n.changeLanguage(this.lang);
if (this.select2IsInitialized()) { if (this.select2IsInitialized()) {
...@@ -311,14 +343,14 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -311,14 +343,14 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
this.initSelect2(true); this.initSelect2(true);
} }
break; break;
case "value": case 'value':
if (!this.ignoreValueUpdate && this.select2IsInitialized()) { if (!this.ignoreValueUpdate && this.select2IsInitialized()) {
this.initSelect2(); this.initSelect2();
} }
this.ignoreValueUpdate = false; this.ignoreValueUpdate = false;
break; break;
case "entryPointUrl": case 'entryPointUrl':
// we don't need to preset the selector if the entry point url changes // we don't need to preset the selector if the entry point url changes
this.initJSONLD(true); this.initJSONLD(true);
break; break;
...@@ -329,7 +361,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -329,7 +361,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
} }
select2IsInitialized() { select2IsInitialized() {
return this.$select !== null && this.$select.hasClass("select2-hidden-accessible"); return this.$select !== null && this.$select.hasClass('select2-hidden-accessible');
} }
reloadClick() { reloadClick() {
...@@ -338,12 +370,14 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -338,12 +370,14 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
} }
// fire a change event // fire a change event
this.dispatchEvent(new CustomEvent('change', { this.dispatchEvent(
new CustomEvent('change', {
detail: { detail: {
value: this.value, value: this.value,
}, },
bubbles: true bubbles: true,
})); })
);
} }
static get styles() { static get styles() {
...@@ -377,7 +411,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -377,7 +411,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
border-radius: 0; border-radius: 0;
} }
input[type="search"] { input[type='search'] {
-webkit-appearance: none; -webkit-appearance: none;
} }
...@@ -385,7 +419,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -385,7 +419,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
.select2-bug .loading-results { .select2-bug .loading-results {
display: none !important; display: none !important;
} }
` `,
]; ];
} }
...@@ -393,7 +427,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -393,7 +427,7 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
const select2CSS = commonUtils.getAssetURL(select2CSSPath); const select2CSS = commonUtils.getAssetURL(select2CSSPath);
const i18n = this._i18n; const i18n = this._i18n;
return html` return html`
<link rel="stylesheet" href="${select2CSS}"> <link rel="stylesheet" href="${select2CSS}" />
<style> <style>
#${this.selectId} { #${this.selectId} {
width: 100%; width: 100%;
...@@ -404,13 +438,26 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) { ...@@ -404,13 +438,26 @@ export class CheckInPlaceSelect extends ScopedElementsMixin(AdapterLitElement) {
<div class="field has-addons"> <div class="field has-addons">
<div class="select2-control control"> <div class="select2-control control">
<!-- https://select2.org--> <!-- https://select2.org-->
<select id="${this.selectId}" name="check-in-place" class="select" ?disabled=${!this.active}>${!this.active ? html`<option value="" disabled selected>${ i18n.t('check-in-place-select.login-required')}</option>` : ''}</select> <select
id="${this.selectId}"
name="check-in-place"
class="select"
?disabled=${!this.active}>
${!this.active
? html`
<option value="" disabled selected>
${i18n.t('check-in-place-select.login-required')}
</option>
`
: ''}
</select>
</div> </div>
<a class="control button" <a
class="control button"
id="reload-button" id="reload-button"
?disabled=${this.object === null} ?disabled=${this.object === null}
@click="${this.reloadClick}" @click="${this.reloadClick}"
style="display: ${this.showReloadButton ? "flex" : "none"}" style="display: ${this.showReloadButton ? 'flex' : 'none'}"
title="${this.reloadButtonTitle}"> title="${this.reloadButtonTitle}">
<dbp-icon name="reload"></dbp-icon> <dbp-icon name="reload"></dbp-icon>
</a> </a>
......
...@@ -4,10 +4,9 @@ import {CheckInPlaceSelect} from './check-in-place-select.js'; ...@@ -4,10 +4,9 @@ import {CheckInPlaceSelect} from './check-in-place-select.js';
import {AuthKeycloak, LoginButton} from '@dbp-toolkit/auth'; import {AuthKeycloak, LoginButton} from '@dbp-toolkit/auth';
import * as commonUtils from '@dbp-toolkit/common/utils'; import * as commonUtils from '@dbp-toolkit/common/utils';
import * as commonStyles from '@dbp-toolkit/common/styles'; import * as commonStyles from '@dbp-toolkit/common/styles';
import DBPLitElement from "@dbp-toolkit/common/dbp-lit-element"; import DBPLitElement from '@dbp-toolkit/common/dbp-lit-element';
import {createInstance} from './i18n.js'; import {createInstance} from './i18n.js';
export class CheckInPlaceSelectDemo extends ScopedElementsMixin(DBPLitElement) { export class CheckInPlaceSelectDemo extends ScopedElementsMixin(DBPLitElement) {
constructor() { constructor() {
super(); super();
...@@ -44,18 +43,32 @@ export class CheckInPlaceSelectDemo extends ScopedElementsMixin(DBPLitElement) { ...@@ -44,18 +43,32 @@ export class CheckInPlaceSelectDemo extends ScopedElementsMixin(DBPLitElement) {
commonStyles.getThemeCSS(), commonStyles.getThemeCSS(),
commonStyles.getGeneralCSS(), commonStyles.getGeneralCSS(),
css` css`
h1.title {margin-bottom: 1em;} h1.title {
div.container {margin-bottom: 1.5em;} margin-bottom: 1em;
` }
div.container {
margin-bottom: 1.5em;
}
`,
]; ];
} }
getAuthComponentHtml() { getAuthComponentHtml() {
return this.noAuth ? html`<dbp-login-button subscribe="auth" lang="${this.lang}"></dbp-login-button>` : html` return this.noAuth
? html`
<dbp-login-button subscribe="auth" lang="${this.lang}"></dbp-login-button>
`
: html`
<div class="container"> <div class="container">
<dbp-auth-keycloak subscribe="requested-login-status" lang="${this.lang}" entry-point-url="${this.entryPointUrl}" silent-check-sso-redirect-uri="/dist/silent-check-sso.html" <dbp-auth-keycloak
url="https://auth-dev.tugraz.at/auth" realm="tugraz-vpu" subscribe="requested-login-status"
client-id="auth-dev-mw-frontend-local" try-login></dbp-auth-keycloak> lang="${this.lang}"
entry-point-url="${this.entryPointUrl}"
silent-check-sso-redirect-uri="/dist/silent-check-sso.html"
url="https://auth-dev.tugraz.at/auth"
realm="tugraz-vpu"
client-id="auth-dev-mw-frontend-local"
try-login></dbp-auth-keycloak>
<dbp-login-button subscribe="auth" lang="${this.lang}"></dbp-login-button> <dbp-login-button subscribe="auth" lang="${this.lang}"></dbp-login-button>
</div> </div>
`; `;
...@@ -73,13 +86,21 @@ export class CheckInPlaceSelectDemo extends ScopedElementsMixin(DBPLitElement) { ...@@ -73,13 +86,21 @@ export class CheckInPlaceSelectDemo extends ScopedElementsMixin(DBPLitElement) {
<div class="field"> <div class="field">
<label class="label">Check-In-Place 1</label> <label class="label">Check-In-Place 1</label>
<div class="control"> <div class="control">
<dbp-check-in-place-select lang="${this.lang}" entry-point-url="${this.entryPointUrl}" subscribe="auth"></dbp-check-in-place-select> <dbp-check-in-place-select
lang="${this.lang}"
entry-point-url="${this.entryPointUrl}"
subscribe="auth"></dbp-check-in-place-select>
</div> </div>
</div> </div>
<div class="field"> <div class="field">
<label class="label">Check-In-Place 2</label> <label class="label">Check-In-Place 2</label>
<div class="control"> <div class="control">
<dbp-check-in-place-select lang="${this.lang}" entry-point-url="${this.entryPointUrl}" subscribe="auth" show-reload-button reload-button-title="Click me"></dbp-check-in-place-select> <dbp-check-in-place-select
lang="${this.lang}"
entry-point-url="${this.entryPointUrl}"
subscribe="auth"
show-reload-button
reload-button-title="Click me"></dbp-check-in-place-select>
</div> </div>
</div> </div>
</form> </form>
......
...@@ -15,7 +15,11 @@ export default function () { ...@@ -15,7 +15,11 @@ export default function () {
inputTooShort: function (args) { inputTooShort: function (args) {
var remainingChars = args.minimum - args.input.length; var remainingChars = args.minimum - args.input.length;
return 'Bitte ' + remainingChars + ' Zeichen mehr eingeben, es kann nach mehreren Teilen von Namen gesucht werden'; return (
'Bitte ' +
remainingChars +
' Zeichen mehr eingeben, es kann nach mehreren Teilen von Namen gesucht werden'
);
}, },
loadingMore: function () { loadingMore: function () {
return 'Lade mehr Ergebnisse…'; return 'Lade mehr Ergebnisse…';
...@@ -41,6 +45,6 @@ export default function () { ...@@ -41,6 +45,6 @@ export default function () {
}, },
removeAllItems: function () { removeAllItems: function () {
return 'Entferne alle Gegenstände'; return 'Entferne alle Gegenstände';
} },
}; };
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment