Skip to content
Snippets Groups Projects
Commit 01d9e498 authored by Steinwender, Tamara's avatar Steinwender, Tamara
Browse files

Merge branch 'master' of gitlab.tugraz.at:dbp/web-components/toolkit

parents 1d9f1a5b 3c4691d4
No related branches found
No related tags found
No related merge requests found
Pipeline #13413 passed
Showing
with 1351 additions and 0 deletions
dist
node_modules
.idea
npm-debug.log
package-lock.json
This diff is collapsed.
# Location Select Web Component
[GitLab Repository](https://gitlab.tugraz.at/dbp/web-components/toolkit)
## Usage
```html
<dbp-location-select></dbp-location-select>
```
## Attributes
- `lang` (optional, default: `de`): set to `de` or `en` for German or English
- example `<dbp-location-select lang="de"></dbp-location-select>`
- `entry-point-url` (optional, default is the TU Graz entry point url): entry point url to access the api
- example `<dbp-location-select entry-point-url="http://127.0.0.1:8000"></dbp-location-select>`
- `value` (optional): api path of location to preload the selector with
- example `<dbp-location-select value="Besprechungsraum"></dbp-location-select>`
- the `value` will also be set automatically when a location is chosen in the selector
- `data-object` (read-only): when a location is selected the location object will be set as json string
- example `<dbp-location-select data-object="{"@id":"id", "@type":"http://schema.org/Place", "identifier":"id", "name":"Besprechungsraum", "maximumPhysicalAttendeeCapacity":"50"}"></dbp-location-select>`
- `show-capacity` (optional): also shows the capacity of the locations
- example `<dbp-location-select show-capacity></dbp-location-select>`
- `show-reload-button` (optional): if set a reload button will be viewed next to the select box
- the button triggers a `change` event on the web component
- the button is disabled if no location is selected
- example `<dbp-location-select show-reload-button></dbp-location-select>`
- `reload-button-title` (optional): sets a title text on the reload button
- example `<dbp-location-select show-reload-button reload-button-text="Reload result list"></dbp-location-select>`
## Local development
```bash
# get the source
git clone git@gitlab.tugraz.at:dbp/web-components/toolkit.git
cd toolkit/packages/location-select
git submodule update --init
# install dependencies (make sure you have npm version 4+ installed, so symlinks to the git submodules are created automatically)
yarn install
# constantly build dist/bundle.js and run a local web-server on port 8002
yarn run watch-local
# run tests
yarn test
```
Jump to <http://localhost:8002> and you should get a Single Sign On login page.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="module" src="dbp-location-select-demo.js"></script>
</head>
<body>
<dbp-location-select-demo lang="de"></dbp-location-select-demo>
</body>
</html>
module.exports = {
input: [
'src/*.js',
],
output: './',
options: {
debug: false,
removeUnusedKeys: true,
lngs: ['en','de'],
resource: {
loadPath: 'src/i18n/{{lng}}/{{ns}}.json',
savePath: 'src/i18n/{{lng}}/{{ns}}.json'
},
},
}
// Trick to use the auto-downloaded puppeteer chrome binary
process.env.CHROME_BIN = require('puppeteer').executablePath();
const pkg = require('./package.json');
module.exports = function(config) {
config.set({
basePath: 'dist',
frameworks: ['mocha', 'chai'],
files: [
{pattern: './*.js', included: true, watched: true, served: true, type: 'module'},
{pattern: './**/*', included: false, watched: true, served: true},
],
autoWatch: true,
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
singleRun: false,
logLevel: config.LOG_ERROR
});
}
{
"name": "dbp-location-select",
"version": "1.0.0",
"main": "src/index.js",
"license": "LGPL-2.1-or-later",
"private": true,
"devDependencies": {
"@rollup/plugin-commonjs": "^14.0.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^8.1.0",
"@rollup/plugin-replace": "^2.3.3",
"@rollup/plugin-url": "^5.0.1",
"chai": "^4.2.0",
"i18next-scanner": "^2.10.2",
"karma": "^5.1.0",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^3.0.0",
"karma-mocha": "^2.0.1",
"mocha": "^8.0.1",
"puppeteer": "^2.1.1",
"rollup": "^2.19.0",
"rollup-plugin-consts": "^1.0.1",
"rollup-plugin-copy": "^3.1.0",
"rollup-plugin-delete": "^2.0.0",
"rollup-plugin-serve": "^1.0.1",
"rollup-plugin-terser": "^6.1.0"
},
"dependencies": {
"@open-wc/scoped-elements": "^1.1.1",
"jquery": "^3.4.1",
"keycloak-js": "^10.0.2",
"lit-element": "^2.3.1",
"select2": "^4.0.10",
"dbp-auth": "^1.0.0",
"dbp-common": "^1.0.0"
},
"scripts": {
"clean": "rm dist/*",
"build": "npm run build-local",
"build-local": "rollup -c",
"build-dev": "rollup -c --environment BUILD:development",
"build-prod": "rollup -c --environment BUILD:production",
"build-demo": "rollup -c --environment BUILD:demo",
"build-test": "rollup -c --environment BUILD:test",
"i18next": "i18next-scanner",
"watch": "npm run watch-local",
"watch-local": "rollup -c --watch",
"watch-dev": "rollup -c --watch --environment BUILD:development",
"test": "npm run build-test && karma start --singleRun"
}
}
import glob from 'glob';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import copy from 'rollup-plugin-copy';
import {terser} from "rollup-plugin-terser";
import json from '@rollup/plugin-json';
import serve from 'rollup-plugin-serve';
import url from "@rollup/plugin-url"
import consts from 'rollup-plugin-consts';
import del from 'rollup-plugin-delete';
import {getPackagePath} from '../../rollup.utils.js';
const build = (typeof process.env.BUILD !== 'undefined') ? process.env.BUILD : 'local';
console.log("build: " + build);
export default (async () => {
return {
input: (build != 'test') ? ['src/dbp-location-select.js', 'src/dbp-location-select-demo.js'] : glob.sync('test/**/*.js'),
output: {
dir: 'dist',
entryFileNames: '[name].js',
chunkFileNames: 'shared/[name].[hash].[format].js',
format: 'esm',
sourcemap: true
},
onwarn: function (warning, warn) {
// keycloak bundled code uses eval
if (warning.code === 'EVAL') {
return;
}
warn(warning);
},
plugins: [
del({
targets: 'dist/*'
}),
consts({
environment: build,
}),
resolve(),
commonjs(),
url({
limit: 0,
include: [
await getPackagePath('select2', '**/*.css'),
],
emitFiles: true,
fileName: 'shared/[name].[hash][extname]'
}),
json(),
(build !== 'local' && build !== 'test') ? terser() : false,
copy({
targets: [
{src: 'assets/index.html', dest: 'dist'},
{src: await getPackagePath('dbp-common', 'assets/icons/*.svg'), dest: 'dist/local/dbp-common/icons'},
],
}),
(process.env.ROLLUP_WATCH === 'true') ? serve({contentBase: 'dist', host: '127.0.0.1', port: 8002}) : false
]
};
})();
\ No newline at end of file
import {i18n} from './i18n.js';
import {css, html, LitElement} from 'lit-element';
import {ScopedElementsMixin} from '@open-wc/scoped-elements';
import {LocationSelect} from './location-select.js';
import {AuthKeycloak, LoginButton} from 'dbp-auth';
import * as commonUtils from 'dbp-common/utils';
import * as commonStyles from 'dbp-common/styles';
class LocationSelectDemo extends ScopedElementsMixin(LitElement) {
constructor() {
super();
this.lang = 'de';
this.noAuth = false;
}
static get scopedElements() {
return {
'dbp-auth-keycloak': AuthKeycloak,
'dbp-login-button': LoginButton,
'dbp-location-select': LocationSelect,
};
}
static get properties() {
return {
lang: { type: String },
noAuth: { type: Boolean, attribute: 'no-auth' },
};
}
connectedCallback() {
super.connectedCallback();
i18n.changeLanguage(this.lang);
this.updateComplete.then(()=>{
});
}
static get styles() {
// language=css
return [
commonStyles.getThemeCSS(),
commonStyles.getGeneralCSS(),
css`
h1.title {margin-bottom: 1em;}
div.container {margin-bottom: 1.5em;}
`
];
}
getAuthComponentHtml() {
return this.noAuth ? html`` : html`
<div class="container">
<dbp-auth-keycloak lang="${this.lang}" url="https://auth-dev.tugraz.at/auth" realm="tugraz" client-id="auth-dev-mw-frontend-local" load-person try-login></dbp-auth-keycloak>
<dbp-login-button lang="${this.lang}" show-image></dbp-login-button>
</div>
`;
}
render() {
return html`
<section class="section">
<div class="container">
<h1 class="title">Location-Select-Demo</h1>
</div>
${this.getAuthComponentHtml()}
<div class="container">
<form>
<div class="field">
<label class="label">Location 1</label>
<div class="control">
<dbp-location-select lang="${this.lang}" entry-point-url="${commonUtils.getAPiUrl()}"></dbp-location-select>
</div>
</div>
<div class="field">
<label class="label">Location 2</label>
<div class="control">
<dbp-location-select lang="${this.lang}" entry-point-url="${commonUtils.getAPiUrl()}" show-reload-button reload-button-title="Click me"></dbp-location-select>
</div>
</div>
</form>
</div>
</section>
`;
}
}
commonUtils.defineCustomElement('dbp-location-select-demo', LocationSelectDemo);
import * as commonUtils from 'dbp-common/utils';
import {LocationSelect} from './location-select.js';
commonUtils.defineCustomElement('dbp-location-select', LocationSelect);
import './dbp-location-select-demo.js';
import {createInstance} from 'dbp-common/i18next.js';
import de from './i18n/de/translation.json';
import en from './i18n/en/translation.json';
export const i18n = createInstance({en: en, de: de}, 'de', 'en');
\ No newline at end of file
/**
* Content from https://github.com/select2/select2/blob/master/src/js/select2/i18n/de.js
*/
export default function () {
// German
return {
errorLoading: function () {
return 'Die Ergebnisse konnten nicht geladen werden.';
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
return 'Bitte ' + overChars + ' Zeichen weniger eingeben';
},
inputTooShort: function (args) {
var remainingChars = args.minimum - args.input.length;
return 'Bitte ' + remainingChars + ' Zeichen mehr eingeben, es kann nach mehreren Teilen von Namen gesucht werden';
},
loadingMore: function () {
return 'Lade mehr Ergebnisse…';
},
maximumSelected: function (args) {
var message = 'Sie können nur ' + args.maximum + ' Eintr';
if (args.maximum === 1) {
message += 'ag';
} else {
message += 'äge';
}
message += ' auswählen';
return message;
},
noResults: function () {
return 'Keine Übereinstimmungen gefunden';
},
searching: function () {
return 'Suche…';
},
removeAllItems: function () {
return 'Entferne alle Gegenstände';
}
};
};
{
"location-select": {
"placeholder": "Bitte wählen Sie einen Ort aus",
"error-summary": "Ein Fehler ist aufgetreten",
"login-required": "Anmeldung erforderlich"
}
}
/**
* Content from https://github.com/select2/select2/blob/master/src/js/select2/i18n/en.js
*/
export default function () {
// English
return {
errorLoading: function () {
return 'The results could not be loaded.';
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
var message = 'Please delete ' + overChars + ' character';
if (overChars != 1) {
message += 's';
}
return message;
},
inputTooShort: function (args) {
var remainingChars = args.minimum - args.input.length;
var message = 'Please enter ' + remainingChars + ' or more characters, you can also search for multiple parts of names';
return message;
},
loadingMore: function () {
return 'Loading more results…';
},
maximumSelected: function (args) {
var message = 'You can only select ' + args.maximum + ' item';
if (args.maximum != 1) {
message += 's';
}
return message;
},
noResults: function () {
return 'No results found';
},
searching: function () {
return 'Searching…';
},
removeAllItems: function () {
return 'Remove all items';
}
};
};
{
"location-select": {
"placeholder": "Please select a location",
"error-summary": "An error occurred",
"login-required": "Login required"
}
}
import {LocationSelect} from './location-select.js';
export {LocationSelect};
\ No newline at end of file
import $ from 'jquery';
import {findObjectInApiResults} from './utils.js';
import select2 from 'select2';
import select2LangDe from './i18n/de/select2'
import select2LangEn from './i18n/en/select2'
import JSONLD from 'dbp-common/jsonld';
import {css, html, LitElement} from 'lit-element';
import {ScopedElementsMixin} from '@open-wc/scoped-elements';
import {i18n} from './i18n.js';
import {Icon} from 'dbp-common';
import * as commonUtils from 'dbp-common/utils';
import * as commonStyles from 'dbp-common/styles';
import select2CSSPath from 'select2/dist/css/select2.min.css';
import * as errorUtils from "dbp-common/error";
const locationContext = {
"@id": "@id",
"name": "http://schema.org/name",
"maximumPhysicalAttendeeCapacity": "http://schema.org/maximumPhysicalAttendeeCapacity"
};
select2(window, $);
export class LocationSelect extends ScopedElementsMixin(LitElement) {
constructor() {
super();
this.lang = 'de';
this.entryPointUrl = commonUtils.getAPiUrl();
this.jsonld = null;
this.$select = null;
this.active = false;
// For some reason using the same ID on the whole page twice breaks select2 (regardless if they are in different custom elements)
this.selectId = 'location-select-' + commonUtils.makeId(24);
this.value = '';
this.object = null;
this.ignoreValueUpdate = false;
this.isSearching = false;
this.lastResult = {};
this.showReloadButton = false;
this.reloadButtonTitle = '';
this.showCapacity = false;
}
static get scopedElements() {
return {
'dbp-icon': Icon,
};
}
$(selector) {
return $(this.shadowRoot.querySelector(selector));
}
static get properties() {
return {
lang: { type: String },
active: { type: Boolean, attribute: false },
entryPointUrl: { type: String, attribute: 'entry-point-url' },
value: { type: String },
object: { type: Object, attribute: false },
showReloadButton: { type: Boolean, attribute: 'show-reload-button' },
reloadButtonTitle: { type: String, attribute: 'reload-button-title' },
showBirthDate: { type: Boolean, attribute: 'show-capacity' },
};
}
clear() {
this.object = null;
$(this).attr("data-object", "");
$(this).data("object", null);
this.$select.val(null).trigger('change').trigger('select2:unselect');
}
connectedCallback() {
super.connectedCallback();
const that = this;
this.updateComplete.then(()=>{
that.$select = that.$('#' + that.selectId);
// close the selector on blur of the web component
$(that).blur(() => {
// the 500ms delay is a workaround to actually get an item selected when clicking on it,
// because the blur gets also fired when clicking in the selector
setTimeout(() => {
if (this.select2IsInitialized()) {
that.$select.select2('close');
}
}, 500);
});
// try an init when user-interface is loaded
that.initJSONLD();
});
}
initJSONLD(ignorePreset = false) {
const that = this;
JSONLD.initialize(this.entryPointUrl, function (jsonld) {
that.jsonld = jsonld;
that.active = true;
// 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()
commonUtils.pollFunc(() => { return that.initSelect2(ignorePreset); }, 10000, 100);
}, {}, this.lang);
}
/**
* Initializes the Select2 selector
*/
initSelect2(ignorePreset = false) {
const that = this;
const $this = $(this);
if (this.jsonld === null) {
return false;
}
// find the correct api url for a location
const apiUrl = this.jsonld.getApiUrlForIdentifier("http://schema.org/Place");
// const apiUrl = this.jsonld.getApiUrlForEntityName("CheckInPlace");
if (this.$select === null) {
return false;
}
// we need to destroy Select2 and remove the event listeners before we can initialize it again
if (this.$select && this.$select.hasClass('select2-hidden-accessible')) {
this.$select.select2('destroy');
this.$select.off('select2:select');
this.$select.off('select2:closing');
}
this.$select.select2({
width: '100%',
language: this.lang === "de" ? select2LangDe() : select2LangEn(),
minimumInputLength: 2,
placeholder: i18n.t('location-select.placeholder'),
dropdownParent: this.$('#location-select-dropdown'),
ajax: {
delay: 500,
url: apiUrl,
contentType: "application/ld+json",
beforeSend: function (jqXHR) {
jqXHR.setRequestHeader('Authorization', 'Bearer ' + window.DBPAuthToken);
that.isSearching = true;
},
data: function (params) {
return {
search: params.term.trim(),
};
},
processResults: function (data) {
that.lastResult = data;
let transformed = that.jsonld.transformMembers(data, locationContext); //TODO
const results = [];
transformed.forEach((place) => {
results.push({id: place["@id"], text: that.generateOptionText(place)});
});
return {
results: results
};
},
error: errorUtils.handleXhrError,
complete: (jqXHR, textStatus) => {
that.isSearching = false;
}
}
}).on("select2:select", function (e) {
// set custom element attributes
const identifier = e.params.data.id;
that.object = findObjectInApiResults(identifier, that.lastResult);
$this.attr("data-object", JSON.stringify(that.object));
$this.data("object", that.object);
if ($this.attr("value") !== identifier) {
that.ignoreValueUpdate = true;
$this.attr("value", identifier);
// fire a change event
that.dispatchEvent(new CustomEvent('change', {
detail: {
value: identifier,
},
bubbles: true
}));
}
}).on("select2:closing", (e) => {
if (that.isSearching) {
e.preventDefault();
}
});
// TODO: doesn't work here
// this.$('.select2-selection__arrow').click(() => {
// console.log("click");
// });
// preset a place
if (!ignorePreset && this.value !== '') {
const apiUrl = this.entryPointUrl + this.value;
fetch(apiUrl, {
headers: {
'Content-Type': 'application/ld+json',
'Authorization': 'Bearer ' + window.DBPAuthToken,
},
})
.then(result => {
if (!result.ok) throw result;
return result.json();
})
.then((place) => {
that.object = place;
const transformed = that.jsonld.compactMember(that.jsonld.expandMember(place), locationContext);
const identifier = transformed["@id"];
const option = new Option(that.generateOptionText(transformed), identifier, true, true);
$this.attr("data-object", JSON.stringify(place));
$this.data("object", place); //TODO the object is changed here
that.$select.append(option).trigger('change');
// fire a change event
that.dispatchEvent(new CustomEvent('change', {
detail: {
value: identifier,
},
bubbles: true
}));
}).catch((e) => {
console.log(e);
that.clear();
});
}
return true;
}
generateOptionText(place) {
let text = place["name"];
// add maximum capacity to location if present
if (this.showCapacity && (place["maximumPhysicalAttendeeCapacity"] !== undefined) && (place["maximumPhysicalAttendeeCapacity"] !== null)) {
let capacity = place["maximumPhysicalAttendeeCapacity"];
text += ` (${capacity})`;
}
return text;
}
update(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
switch (propName) {
case "lang":
i18n.changeLanguage(this.lang);
if (this.select2IsInitialized()) {
// no other way to set an other language at runtime did work
this.initSelect2(true);
}
break;
case "value":
if (!this.ignoreValueUpdate && this.select2IsInitialized()) {
this.initSelect2();
}
this.ignoreValueUpdate = false;
break;
case "entryPointUrl":
// we don't need to preset the selector if the entry point url changes
this.initJSONLD(true);
break;
}
});
super.update(changedProperties);
}
select2IsInitialized() {
return this.$select !== null && this.$select.hasClass("select2-hidden-accessible");
}
reloadClick() {
if (this.object === null) {
return;
}
// fire a change event
this.dispatchEvent(new CustomEvent('change', {
detail: {
value: this.value,
},
bubbles: true
}));
}
static get styles() {
return [
commonStyles.getThemeCSS(),
commonStyles.getGeneralCSS(),
commonStyles.getButtonCSS(),
commonStyles.getFormAddonsCSS(),
commonStyles.getSelect2CSS(),
css`
.select2-control.control {
width: 100%;
}
.field .button.control {
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #aaa;
-moz-border-radius-topright: var(--dbp-border-radius);
-moz-border-radius-bottomright: var(--dbp-border-radius);
line-height: 100%;
}
.field .button.control dbp-icon {
top: 0;
}
`
];
}
render() {
const select2CSS = commonUtils.getAssetURL(select2CSSPath);
return html`
<link rel="stylesheet" href="${select2CSS}">
<style>
#${this.selectId} {
width: 100%;
}
</style>
<div class="select">
<div class="field has-addons">
<div class="select2-control control">
<!-- https://select2.org-->
<select id="${this.selectId}" name="location" class="select" ?disabled=${!this.active}>${!this.active ? html`<option value="" disabled selected>${ i18n.t('location-select.login-required')}</option>` : ''}</select>
</div>
<a class="control button"
id="reload-button"
?disabled=${this.object === null}
@click="${this.reloadClick}"
style="display: ${this.showReloadButton ? "flex" : "none"}"
title="${this.reloadButtonTitle}">
<dbp-icon name="reload"></dbp-icon>
</a>
</div>
<div id="location-select-dropdown"></div>
</div>
`;
}
}
\ No newline at end of file
/**
* Finds an object in a JSON result by identifier
*
* @param identifier
* @param results
* @param identifierAttribute
*/
export const findObjectInApiResults = (identifier, results, identifierAttribute = "@id") => {
const members = results["hydra:member"];
if (members === undefined) {
return;
}
for (const object of members){
if (object[identifierAttribute] === identifier) {
return object;
}
}
};
import '../src/dbp-location-select.js';
import '../src/demo.js';
describe('dbp-location-select basics', () => {
let node;
beforeEach(async () => {
node = document.createElement('dbp-location-select');
document.body.appendChild(node);
await node.updateComplete;
});
afterEach(() => {
node.remove();
});
it('should render', () => {
expect(node).to.have.property('shadowRoot');
});
});
describe('dbp-location-select-demo basics', () => {
let node;
beforeEach(async () => {
node = document.createElement('dbp-location-select-demo');
document.body.appendChild(node);
await node.updateComplete;
});
afterEach(() => {
node.remove();
});
it('should render', () => {
expect(node).to.have.property('shadowRoot');
});
});
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment