static: format code

This commit is contained in:
Jens Langhammer 2020-11-21 20:48:49 +01:00
parent e42ad3f659
commit 1cb227305c
21 changed files with 1221 additions and 1077 deletions

View File

@ -0,0 +1,3 @@
# Ignore artifacts:
dist
coverage

View File

@ -0,0 +1 @@
{}

File diff suppressed because it is too large Load Diff

View File

@ -1,28 +1,29 @@
{
"license": "MIT",
"scripts": {
"build": "rollup -c ./rollup.config.js",
"watch": "rollup -c -w"
},
"dependencies": {
"@fortawesome/fontawesome-free": "^5.15.1",
"@patternfly/patternfly": "^4.65.6",
"@types/chart.js": "^2.9.28",
"@types/codemirror": "0.0.98",
"chart.js": "^2.9.4",
"codemirror": "^5.58.3",
"lit-element": "^2.4.0",
"lit-html": "^1.3.0",
"rollup": "^2.33.3",
"rollup-plugin-cssimport": "^1.0.2",
"tslib": "^2.0.3"
},
"devDependencies": {
"@rollup/plugin-typescript": "^6.1.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-minify-html-literals": "^1.2.5",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-sourcemaps": "^0.6.3",
"rollup-plugin-terser": "^7.0.2"
}
"license": "MIT",
"scripts": {
"build": "rollup -c ./rollup.config.js",
"watch": "rollup -c -w"
},
"dependencies": {
"@fortawesome/fontawesome-free": "^5.15.1",
"@patternfly/patternfly": "^4.65.6",
"@types/chart.js": "^2.9.28",
"@types/codemirror": "0.0.98",
"chart.js": "^2.9.4",
"codemirror": "^5.58.3",
"lit-element": "^2.4.0",
"lit-html": "^1.3.0",
"rollup": "^2.33.3",
"rollup-plugin-cssimport": "^1.0.2",
"tslib": "^2.0.3"
},
"devDependencies": {
"@rollup/plugin-typescript": "^6.1.0",
"prettier": "2.2.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-minify-html-literals": "^1.2.5",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-sourcemaps": "^0.6.3",
"rollup-plugin-terser": "^7.0.2"
}
}

View File

@ -1,7 +1,7 @@
@font-face {
font-family: 'DIN 1451 Std';
src: url('fonts/DINEngschriftStd.woff2') format('woff2'),
url('fonts/DINEngschriftStd.woff') format('woff');
font-family: "DIN 1451 Std";
src: url("fonts/DINEngschriftStd.woff2") format("woff2"),
url("fonts/DINEngschriftStd.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
@ -13,7 +13,7 @@
display: flex;
flex-direction: row;
align-items: center;
margin-right: .5em;
margin-right: 0.5em;
color: var(--pf-global--Color--light-200);
}
@ -23,11 +23,11 @@
.pb-brand > img {
max-height: 68px;
margin-right: .5em;
margin-right: 0.5em;
}
.pf-c-background-image::before {
background-image: url('./flow_background.jpg');
background-image: url("./flow_background.jpg");
background-position: center;
}
@ -91,7 +91,8 @@ select[multiple] {
flex: 1 1;
}
.selector-available, .selector-chosen {
.selector-available,
.selector-chosen {
width: auto;
flex: 1 1;
display: flex;
@ -114,7 +115,8 @@ select[multiple] {
list-style: none;
}
.selector-add, .selector-remove {
.selector-add,
.selector-remove {
width: 20px;
height: 20px;
background-size: 20px auto;
@ -128,7 +130,8 @@ select[multiple] {
background-position: 0 -80px;
}
a.selector-chooseall, a.selector-clearall {
a.selector-chooseall,
a.selector-clearall {
align-self: center;
}
@ -145,7 +148,8 @@ a.selector-chooseall, a.selector-clearall {
margin-bottom: 0;
}
.stacked .selector-available, .stacked .selector-chosen {
.stacked .selector-available,
.stacked .selector-chosen {
width: auto;
}
@ -161,7 +165,8 @@ a.selector-chooseall, a.selector-clearall {
padding: 3px;
}
.stacked .selector-add, .stacked .selector-remove {
.stacked .selector-add,
.stacked .selector-remove {
background-size: 20px auto;
}
@ -181,7 +186,8 @@ a.selector-chooseall, a.selector-clearall {
background-position: 0 -20px;
}
.help-tooltip, .selector .help-icon {
.help-tooltip,
.selector .help-icon {
display: none;
}
@ -212,7 +218,8 @@ form .form-row p.datetime {
overflow: auto;
}
.selector-add, .selector-remove {
.selector-add,
.selector-remove {
width: 16px;
height: 16px;
display: block;
@ -222,11 +229,13 @@ form .form-row p.datetime {
opacity: 0.3;
}
.active.selector-add, .active.selector-remove {
.active.selector-add,
.active.selector-remove {
opacity: 1;
}
.active.selector-add:hover, .active.selector-remove:hover {
.active.selector-add:hover,
.active.selector-remove:hover {
cursor: pointer;
}
@ -234,7 +243,8 @@ form .form-row p.datetime {
background: url(../admin/img/selector-icons.svg) 0 -96px no-repeat;
}
.active.selector-add:focus, .active.selector-add:hover {
.active.selector-add:focus,
.active.selector-add:hover {
background-position: 0 -112px;
}

View File

@ -1,27 +1,29 @@
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import minifyHTML from 'rollup-plugin-minify-html-literals';
import { terser } from 'rollup-plugin-terser';
import sourcemaps from 'rollup-plugin-sourcemaps';
import typescript from '@rollup/plugin-typescript';
import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import minifyHTML from "rollup-plugin-minify-html-literals";
import { terser } from "rollup-plugin-terser";
import sourcemaps from "rollup-plugin-sourcemaps";
import typescript from "@rollup/plugin-typescript";
import cssimport from "rollup-plugin-cssimport";
export default [{
input: './src/main.ts',
output: [
export default [
{
format: 'es',
dir: 'dist',
sourcemap: true
}
],
plugins: [
cssimport(),
typescript(),
resolve({browser: true}),
commonjs(),
sourcemaps(),
minifyHTML(),
terser(),
],
}];
input: "./src/main.ts",
output: [
{
format: "es",
dir: "dist",
sourcemap: true,
},
],
plugins: [
cssimport(),
typescript(),
resolve({ browser: true }),
commonjs(),
sourcemaps(),
minifyHTML(),
terser(),
],
},
];

View File

@ -9,10 +9,11 @@ const PROGRESS_CLASSES = ["pf-m-progress", "pf-m-in-progress"];
@customElement("pb-action-button")
export class ActionButton extends LitElement {
constructor() {
super();
this.querySelector("button")?.addEventListener('click', e => this.callAction());
this.querySelector("button")?.addEventListener("click", (e) =>
this.callAction()
);
}
@property()
@ -41,33 +42,39 @@ export class ActionButton extends LitElement {
return;
}
this.setLoading();
const csrftoken = getCookie('passbook_csrf');
const request = new Request(
this.url,
{ headers: { 'X-CSRFToken': csrftoken! } }
);
const csrftoken = getCookie("passbook_csrf");
const request = new Request(this.url, {
headers: { "X-CSRFToken": csrftoken! },
});
fetch(request, {
method: "POST",
mode: 'same-origin',
}).then(r => r.json()).then(r => {
this.setDone(SUCCESS_CLASS);
}).catch(() => {
this.setDone(ERROR_CLASS);
});
mode: "same-origin",
})
.then((r) => r.json())
.then((r) => {
this.setDone(SUCCESS_CLASS);
})
.catch(() => {
this.setDone(ERROR_CLASS);
});
}
render() {
return html`<button class="pf-c-button pf-m-primary">
${this.isRunning ? html`
<span class="pf-c-button__progress">
<span class="pf-c-spinner pf-m-md" role="progressbar" aria-valuetext="Loading...">
<span class="pf-c-spinner__clipper"></span>
<span class="pf-c-spinner__lead-ball"></span>
<span class="pf-c-spinner__tail-ball"></span>
</span>
</span>` : ""}
${this.isRunning
? html` <span class="pf-c-button__progress">
<span
class="pf-c-spinner pf-m-md"
role="progressbar"
aria-valuetext="Loading..."
>
<span class="pf-c-spinner__clipper"></span>
<span class="pf-c-spinner__lead-ball"></span>
<span class="pf-c-spinner__tail-ball"></span>
</span>
</span>`
: ""}
<slot></slot>
</button>`;
}
}

View File

@ -8,7 +8,6 @@ interface TickValue {
@customElement("pb-admin-logins-chart")
export class AdminLoginsChart extends LitElement {
@property()
url: string = "";
@ -16,23 +15,23 @@ export class AdminLoginsChart extends LitElement {
static get styles() {
return css`
:host {
position: relative;
height: 100%;
width: 100%;
display: block;
min-height: 25rem;
}
canvas {
width: 100px;
height: 100px;
}
:host {
position: relative;
height: 100%;
width: 100%;
display: block;
min-height: 25rem;
}
canvas {
width: 100px;
height: 100px;
}
`;
}
constructor() {
super();
window.addEventListener('resize', () => {
window.addEventListener("resize", () => {
if (this.chart) {
this.chart.resize();
}
@ -40,62 +39,79 @@ export class AdminLoginsChart extends LitElement {
}
firstUpdated() {
fetch(this.url).then(r => r.json()).catch(e => console.error(e)).then(r => {
let ctx = (<HTMLCanvasElement>this.shadowRoot?.querySelector("canvas")).getContext('2d')!;
this.chart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [
{
label: 'Failed Logins',
backgroundColor: "rgba(201, 25, 11, .5)",
spanGaps: true,
data: r.logins_failed_per_1h,
},
{
label: 'Successful Logins',
backgroundColor: "rgba(189, 229, 184, .5)",
spanGaps: true,
data: r.logins_per_1h,
},
]
},
options: {
maintainAspectRatio: false,
spanGaps: true,
scales: {
xAxes: [{
stacked: true,
gridLines: {
color: "rgba(0, 0, 0, 0)",
fetch(this.url)
.then((r) => r.json())
.catch((e) => console.error(e))
.then((r) => {
let ctx = (<HTMLCanvasElement>(
this.shadowRoot?.querySelector("canvas")
)).getContext("2d")!;
this.chart = new Chart(ctx, {
type: "bar",
data: {
datasets: [
{
label: "Failed Logins",
backgroundColor: "rgba(201, 25, 11, .5)",
spanGaps: true,
data: r.logins_failed_per_1h,
},
type: 'time',
offset: true,
ticks: {
callback: function (value, index: number, values) {
const valueStamp = <TickValue>(<unknown>values[index]);
const delta = (Date.now() - valueStamp.value);
const ago = Math.round(delta / 1000 / 3600);
return `${ago} Hours ago`;
{
label: "Successful Logins",
backgroundColor: "rgba(189, 229, 184, .5)",
spanGaps: true,
data: r.logins_per_1h,
},
],
},
options: {
maintainAspectRatio: false,
spanGaps: true,
scales: {
xAxes: [
{
stacked: true,
gridLines: {
color: "rgba(0, 0, 0, 0)",
},
type: "time",
offset: true,
ticks: {
callback: function (
value,
index: number,
values
) {
const valueStamp = <TickValue>(
(<unknown>values[index])
);
const delta =
Date.now() - valueStamp.value;
const ago = Math.round(
delta / 1000 / 3600
);
return `${ago} Hours ago`;
},
autoSkip: true,
maxTicksLimit: 8,
},
},
autoSkip: true,
maxTicksLimit: 8
}
}],
yAxes: [{
stacked: true,
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
],
yAxes: [
{
stacked: true,
gridLines: {
color: "rgba(0, 0, 0, 0)",
},
},
],
},
},
});
});
});
}
render() {
return html`<canvas></canvas>`;
}
}

View File

@ -7,7 +7,6 @@ interface RegexAnchor {
@customElement("pb-admin-sidebar")
export class AdminSideBar extends LitElement {
@property()
activePath: string;
@ -16,33 +15,35 @@ export class AdminSideBar extends LitElement {
constructor() {
super();
this.activePath = window.location.hash.slice(1, Infinity);
window.addEventListener("hashchange", e => {
window.addEventListener("hashchange", (e) => {
this.activePath = window.location.hash.slice(1, Infinity);
});
this.querySelectorAll<HTMLAnchorElement>(".pf-c-nav__link").forEach(a => {
let rawValue = a.attributes.getNamedItem("pb-url-prefix")?.value;
if (!rawValue) {
const parsedURL = new URL(a.href);
if (parsedURL.hash === "") {
console.log(`Ignoring ${a}`);
return;
this.querySelectorAll<HTMLAnchorElement>(".pf-c-nav__link").forEach(
(a) => {
let rawValue = a.attributes.getNamedItem("pb-url-prefix")
?.value;
if (!rawValue) {
const parsedURL = new URL(a.href);
if (parsedURL.hash === "") {
console.log(`Ignoring ${a}`);
return;
}
rawValue = `^${parsedURL.hash.slice(1, Infinity)}$`;
}
rawValue = `^${parsedURL.hash.slice(1, Infinity)}$`;
const regexp = RegExp(rawValue);
this.paths.push({ anchor: a, match: regexp });
}
const regexp = RegExp(rawValue);
this.paths.push({anchor: a, match: regexp});
});
);
}
render() {
this.paths.forEach(path => {
this.paths.forEach((path) => {
if (path.match.exec(this.activePath)) {
path.anchor.classList.add("pf-m-current");
} else {
path.anchor.classList.remove("pf-m-current");
}
})
});
return html`<slot></slot>`;
}
}

View File

@ -9,7 +9,6 @@ import "codemirror/mode/python/python.js";
@customElement("pb-codemirror")
export class CodeMirrorTextarea extends LitElement {
@property()
readOnly: boolean = false;
@ -29,7 +28,7 @@ export class CodeMirrorTextarea extends LitElement {
}
this.editor = CodeMirror.fromTextArea(textarea, {
mode: this.mode,
theme: 'monokai',
theme: "monokai",
lineNumbers: false,
readOnly: this.readOnly,
autoRefresh: true,
@ -38,5 +37,4 @@ export class CodeMirrorTextarea extends LitElement {
this.editor?.save();
});
}
}

View File

@ -2,12 +2,11 @@ import { customElement, html, LitElement } from "lit-element";
@customElement("pb-dropdown")
export class DropdownButton extends LitElement {
constructor() {
super()
const menu = <HTMLElement>this.querySelector('.pf-c-dropdown__menu')!;
this.querySelectorAll("button").forEach(btn => {
btn.addEventListener("click", e => {
super();
const menu = <HTMLElement>this.querySelector(".pf-c-dropdown__menu")!;
this.querySelectorAll("button").forEach((btn) => {
btn.addEventListener("click", (e) => {
menu.hidden = !menu.hidden;
});
});
@ -16,5 +15,4 @@ export class DropdownButton extends LitElement {
render() {
return html`<slot></slot>`;
}
}

View File

@ -1,12 +1,11 @@
import { LitElement, html, customElement, property } from 'lit-element';
import { LitElement, html, customElement, property } from "lit-element";
interface ComparisonHash {
[key: string]: (a: any, b: any) => boolean
[key: string]: (a: any, b: any) => boolean;
}
@customElement("fetch-fill-slot")
export class FetchFillSlot extends LitElement {
@property()
url: string = "";
@ -18,14 +17,30 @@ export class FetchFillSlot extends LitElement {
comparison(slotName: string) {
let comparisonOperatorsHash = <ComparisonHash>{
'<': function (a: any, b: any) { return a < b; },
'>': function (a: any, b: any) { return a > b; },
'>=': function (a: any, b: any) { return a >= b; },
'<=': function (a: any, b: any) { return a <= b; },
'==': function (a: any, b: any) { return a == b; },
'!=': function (a: any, b: any) { return a != b; },
'===': function (a: any, b: any) { return a === b; },
'!==': function (a: any, b: any) { return a !== b; },
"<": function (a: any, b: any) {
return a < b;
},
">": function (a: any, b: any) {
return a > b;
},
">=": function (a: any, b: any) {
return a >= b;
},
"<=": function (a: any, b: any) {
return a <= b;
},
"==": function (a: any, b: any) {
return a == b;
},
"!=": function (a: any, b: any) {
return a != b;
},
"===": function (a: any, b: any) {
return a === b;
},
"!==": function (a: any, b: any) {
return a !== b;
},
};
const tokens = slotName.split(" ");
if (tokens.length < 3) {
@ -45,13 +60,16 @@ export class FetchFillSlot extends LitElement {
}
const comp = tokens[1];
if (!(comp in comparisonOperatorsHash)) {
throw new Error("Invalid comparison")
throw new Error("Invalid comparison");
}
return comparisonOperatorsHash[comp](a, b);
}
firstUpdated() {
fetch(this.url).then(r => r.json()).then(r => r[this.key]).then(r => this.value = r);
fetch(this.url)
.then((r) => r.json())
.then((r) => r[this.key])
.then((r) => (this.value = r));
}
render() {
@ -59,13 +77,13 @@ export class FetchFillSlot extends LitElement {
return html`<slot></slot>`;
}
let selectedSlot = "";
this.querySelectorAll("[slot]").forEach(slot => {
this.querySelectorAll("[slot]").forEach((slot) => {
const comp = slot.getAttribute("slot")!;
if (this.comparison(comp)) {
selectedSlot = comp;
}
});
this.querySelectorAll("[data-value]").forEach(dv => {
this.querySelectorAll("[data-value]").forEach((dv) => {
dv.textContent = this.value;
});
return html`<slot name=${selectedSlot}></slot>`;

View File

@ -1,10 +1,10 @@
import { LitElement, html, customElement, property } from 'lit-element';
import { LitElement, html, customElement, property } from "lit-element";
const LEVEL_ICON_MAP: { [key: string]: string } = {
"error": "fas fa-exclamation-circle",
"warning": "fas fa-exclamation-triangle",
"success": "fas fa-check-circle",
"info": "fas fa-info",
error: "fas fa-exclamation-circle",
warning: "fas fa-exclamation-triangle",
success: "fas fa-check-circle",
info: "fas fa-info",
};
let ID = function (prefix: string) {
@ -23,7 +23,6 @@ interface Message {
@customElement("pb-messages")
export class Messages extends LitElement {
@property()
url: string = "";
@ -39,20 +38,27 @@ export class Messages extends LitElement {
}
fetchMessages() {
return fetch(this.url).then(r => r.json()).then(r => this.messages = r).then((r) => {
const container = <HTMLElement>this.querySelector(".pf-c-alert-group")!;
r.forEach((message: Message) => {
const messageElement = this.renderMessage(message);
container.appendChild(messageElement);
return fetch(this.url)
.then((r) => r.json())
.then((r) => (this.messages = r))
.then((r) => {
const container = <HTMLElement>(
this.querySelector(".pf-c-alert-group")!
);
r.forEach((message: Message) => {
const messageElement = this.renderMessage(message);
container.appendChild(messageElement);
});
});
});
}
renderMessage(message: Message): ChildNode {
const id = ID("pb-message");
const el = document.createElement("template");
el.innerHTML = `<li id=${id} class="pf-c-alert-group__item">
<div class="pf-c-alert pf-m-${message.level_tag} ${message.level_tag === 'error' ? 'pf-m-danger': ''}">
<div class="pf-c-alert pf-m-${message.level_tag} ${
message.level_tag === "error" ? "pf-m-danger" : ""
}">
<div class="pf-c-alert__icon">
<i class="${LEVEL_ICON_MAP[message.level_tag]}"></i>
</div>

View File

@ -10,7 +10,6 @@ import { convertToSlug } from "../utils";
@customElement("pb-modal-button")
export class ModalButton extends LitElement {
@property()
href: string = "";
@ -18,12 +17,12 @@ export class ModalButton extends LitElement {
open: boolean = false;
static get styles() {
return [ModalBoxStyle, BullseyeStyle, BackdropStyle]
return [ModalBoxStyle, BullseyeStyle, BackdropStyle];
}
constructor() {
super();
window.addEventListener("keyup", e => {
window.addEventListener("keyup", (e) => {
if (e.code === "Escape") {
this.open = false;
}
@ -33,84 +32,116 @@ export class ModalButton extends LitElement {
setContent(content: string) {
this.querySelector("[slot=modal]")!.innerHTML = content;
// Ensure links close the modal
this.querySelectorAll<HTMLAnchorElement>("[slot=modal] a").forEach(a => {
// Make click on a close the modal
a.addEventListener("click", e => {
e.preventDefault();
this.open = false;
});
});
// Make name field update slug field
this.querySelectorAll<HTMLInputElement>("input[name=name]").forEach((input) => {
input.addEventListener("input", (e) => {
const form = input.closest("form");
if (form === null) {
return;
}
const slugField = form.querySelector<HTMLInputElement>("input[name=slug]");
if (!slugField) {
return;
}
slugField.value = convertToSlug(input.value);
});
});
// Ensure forms sends in AJAX
this.querySelectorAll<HTMLFormElement>("[slot=modal] form").forEach(form => {
form.addEventListener('submit', (e) => {
e.preventDefault();
let formData = new FormData(form);
fetch((form.action === window.location.toString()) ? this.href : form.action, {
method: form.method,
body: formData,
}).then((response) => {
return response.text();
}).then(data => {
if (data.indexOf("csrfmiddlewaretoken") !== -1) {
this.setContent(data);
} else {
this.open = false;
this.dispatchEvent(new CustomEvent('hashchange', { bubbles: true }));
updateMessages();
}
}).catch((e) => {
console.error(e);
this.querySelectorAll<HTMLAnchorElement>("[slot=modal] a").forEach(
(a) => {
// Make click on a close the modal
a.addEventListener("click", (e) => {
e.preventDefault();
this.open = false;
});
});
});
}
);
// Make name field update slug field
this.querySelectorAll<HTMLInputElement>("input[name=name]").forEach(
(input) => {
input.addEventListener("input", (e) => {
const form = input.closest("form");
if (form === null) {
return;
}
const slugField = form.querySelector<HTMLInputElement>(
"input[name=slug]"
);
if (!slugField) {
return;
}
slugField.value = convertToSlug(input.value);
});
}
);
// Ensure forms sends in AJAX
this.querySelectorAll<HTMLFormElement>("[slot=modal] form").forEach(
(form) => {
form.addEventListener("submit", (e) => {
e.preventDefault();
let formData = new FormData(form);
fetch(
form.action === window.location.toString()
? this.href
: form.action,
{
method: form.method,
body: formData,
}
)
.then((response) => {
return response.text();
})
.then((data) => {
if (data.indexOf("csrfmiddlewaretoken") !== -1) {
this.setContent(data);
} else {
this.open = false;
this.dispatchEvent(
new CustomEvent("hashchange", {
bubbles: true,
})
);
updateMessages();
}
})
.catch((e) => {
console.error(e);
});
});
}
);
}
onClick(e: MouseEvent) {
const request = new Request(
this.href,
);
const request = new Request(this.href);
fetch(request, {
mode: 'same-origin',
}).then(r => r.text()).then((t) => {
this.setContent(t);
this.open = true;
}).catch(e => {
console.error(e);
});
mode: "same-origin",
})
.then((r) => r.text())
.then((t) => {
this.setContent(t);
this.open = true;
})
.catch((e) => {
console.error(e);
});
}
renderModal() {
return html`<div class="pf-c-backdrop">
<div class="pf-l-bullseye">
<div class="pf-c-modal-box pf-m-md" role="dialog" aria-modal="true" aria-labelledby="modal-md-title" aria-describedby="modal-md-description">
<button @click=${() => this.open = false} class="pf-c-button pf-m-plain" type="button" aria-label="Close dialog">
<div
class="pf-c-modal-box pf-m-md"
role="dialog"
aria-modal="true"
aria-labelledby="modal-md-title"
aria-describedby="modal-md-description"
>
<button
@click=${() => (this.open = false)}
class="pf-c-button pf-m-plain"
type="button"
aria-label="Close dialog"
>
<i class="fas fa-times" aria-hidden="true"></i>
</button>
<slot name="modal">
</slot>
<slot name="modal"> </slot>
</div>
</div>
</div>`;
}
render() {
return html`
<slot name="trigger" @click=${(e: any) => this.onClick(e)}></slot>
return html` <slot
name="trigger"
@click=${(e: any) => this.onClick(e)}
></slot>
${this.open ? this.renderModal() : ""}`;
}
}

View File

@ -1,27 +1,34 @@
import { LitElement, html, customElement } from 'lit-element';
import { LitElement, html, customElement } from "lit-element";
@customElement("pb-tabs")
export class Tabs extends LitElement {
_currentPage? = "";
_firstPage? = "";
get currentPage() {
return this._currentPage
return this._currentPage;
}
set currentPage(value) {
try {
// Show active tab page
this.querySelector(`.pf-c-tab-content[tab-name='${value}']`)?.removeAttribute("hidden");
this.querySelector(
`.pf-c-tab-content[tab-name='${value}']`
)?.removeAttribute("hidden");
// Update active status on buttons
this.querySelector(`.pf-c-tabs__item[tab-name='${value}']`)?.classList.add("pf-m-current");
this.querySelector(
`.pf-c-tabs__item[tab-name='${value}']`
)?.classList.add("pf-m-current");
// Hide other tab pages
this.querySelectorAll(`.pf-c-tab-content:not([tab-name='${value}'])`).forEach((el) => {
this.querySelectorAll(
`.pf-c-tab-content:not([tab-name='${value}'])`
).forEach((el) => {
el.setAttribute("hidden", "");
});
// Update active status on other buttons
this.querySelectorAll(`.pf-c-tabs__item:not([tab-name='${value}'])`).forEach((el) => {
this.querySelectorAll(
`.pf-c-tabs__item:not([tab-name='${value}'])`
).forEach((el) => {
el.classList.remove("pf-m-current");
});
// Update window hash
@ -37,7 +44,9 @@ export class Tabs extends LitElement {
}
firstUpdated() {
this._firstPage = this.querySelector(".pf-c-tab-content")?.getAttribute("tab-name")!;
this._firstPage = this.querySelector(".pf-c-tab-content")?.getAttribute(
"tab-name"
)!;
if (window.location.hash) {
this.currentPage = window.location.hash;
} else {
@ -47,8 +56,7 @@ export class Tabs extends LitElement {
button.addEventListener("click", (e) => {
let tabPage = button.parentElement?.getAttribute("tab-name")!;
this.currentPage = tabPage;
})
});
});
}
}

View File

@ -11,23 +11,25 @@ document.querySelectorAll("input[type=search]").forEach((si) => {
document.querySelectorAll("[data-pb-fetch-fill]").forEach((el) => {
const url = el.dataset.pbFetchFill;
const key = el.dataset.pbFetchKey;
fetch(url).then(r => r.json()).then(r => {
el.textContent = r[key];
el.value = r[key];
});
fetch(url)
.then((r) => r.json())
.then((r) => {
el.textContent = r[key];
el.value = r[key];
});
});
// Modal
document.querySelectorAll("[data-target='modal']").forEach((m) => {
m.addEventListener("click", (e) => {
const parentContainer = e.target.closest('[data-target="modal"]');
const modalId = parentContainer.attributes['data-modal'].value;
const modalId = parentContainer.attributes["data-modal"].value;
document.querySelector(`#${modalId}`).removeAttribute("hidden");
});
});
document.querySelectorAll(".pf-c-modal-box [data-modal-close]").forEach((b) => {
b.addEventListener("click", (e) => {
const parentContainer = e.target.closest('.pf-c-backdrop');
const parentContainer = e.target.closest(".pf-c-backdrop");
parentContainer.setAttribute("hidden", true);
});
});
@ -35,31 +37,37 @@ document.querySelectorAll(".pf-c-modal-box [data-modal-close]").forEach((b) => {
// Make Checkbox label click trigger checkbox toggle
document.querySelectorAll(".pf-c-check__label").forEach((checkLabel) => {
checkLabel.addEventListener("click", (e) => {
const checkbox = e.target.parentElement.querySelector("input[type=checkbox]");
const checkbox = e.target.parentElement.querySelector(
"input[type=checkbox]"
);
checkbox.checked = !checkbox.checked;
});
});
// Hamburger Menu
document.querySelectorAll(".pf-c-page__header-brand-toggle>button").forEach((toggle) => {
toggle.addEventListener("click", (e) => {
const sidebar = document.querySelector(".pf-c-page__sidebar");
if (sidebar.classList.contains("pf-m-expanded")) {
// Sidebar already expanded
sidebar.classList.remove("pf-m-expanded");
sidebar.style.zIndex = 0;
} else {
// Sidebar not expanded yet
sidebar.classList.add("pf-m-expanded");
sidebar.style.zIndex = 200;
}
document
.querySelectorAll(".pf-c-page__header-brand-toggle>button")
.forEach((toggle) => {
toggle.addEventListener("click", (e) => {
const sidebar = document.querySelector(".pf-c-page__sidebar");
if (sidebar.classList.contains("pf-m-expanded")) {
// Sidebar already expanded
sidebar.classList.remove("pf-m-expanded");
sidebar.style.zIndex = 0;
} else {
// Sidebar not expanded yet
sidebar.classList.add("pf-m-expanded");
sidebar.style.zIndex = 200;
}
});
});
});
// Collapsable Menus in Sidebar
document.querySelectorAll(".pf-m-expandable>.pf-c-nav__link").forEach((menu) => {
menu.addEventListener("click", (e) => {
e.preventDefault();
menu.parentElement.classList.toggle("pf-m-expanded");
document
.querySelectorAll(".pf-m-expandable>.pf-c-nav__link")
.forEach((menu) => {
menu.addEventListener("click", (e) => {
e.preventDefault();
menu.parentElement.classList.toggle("pf-m-expanded");
});
});
});

View File

@ -1,13 +1,13 @@
import "./legacy.js";
import './elements/ActionButton';
import './elements/AdminSidebar';
import './elements/CodeMirror';
import './elements/Dropdown';
import './elements/FetchFillSlot';
import './elements/Messages';
import './elements/ModalButton';
import './elements/Tabs';
import './pages/AdminSiteShell';
import './pages/FlowShellCard';
import "./elements/ActionButton";
import "./elements/AdminSidebar";
import "./elements/CodeMirror";
import "./elements/Dropdown";
import "./elements/FetchFillSlot";
import "./elements/Messages";
import "./elements/ModalButton";
import "./elements/Tabs";
import "./pages/AdminSiteShell";
import "./pages/FlowShellCard";
import "./elements/AdminLoginsChart";

View File

@ -1,4 +1,11 @@
import { css, customElement, html, LitElement, property, TemplateResult } from "lit-element";
import {
css,
customElement,
html,
LitElement,
property,
TemplateResult,
} from "lit-element";
// @ts-ignore
import BullseyeStyle from "@patternfly/patternfly/layouts/Bullseye/bullseye.css";
// @ts-ignore
@ -6,7 +13,6 @@ import SpinnerStyle from "@patternfly/patternfly/components/Spinner/spinner.css"
@customElement("pb-admin-shell")
export class AdminSiteShell extends LitElement {
@property()
set defaultUrl(value: string) {
if (window.location.hash === "" && value !== undefined) {
@ -18,18 +24,22 @@ export class AdminSiteShell extends LitElement {
loading: boolean = false;
static get styles() {
return [css`
:host {
position: relative;
}
:host .pf-l-bullseye {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
`, BullseyeStyle, SpinnerStyle];
return [
css`
:host {
position: relative;
}
:host .pf-l-bullseye {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
`,
BullseyeStyle,
SpinnerStyle,
];
}
constructor() {
@ -41,49 +51,56 @@ export class AdminSiteShell extends LitElement {
loadContent() {
let url = window.location.hash.slice(1, Infinity);
if (url === "") {
return
return;
}
this.loading = true;
fetch(url).then(r => r.text()).then((t) => {
this.querySelector("[slot=body]")!.innerHTML = t;
}).then(() => {
// Ensure anchors only change the hash
this.querySelectorAll<HTMLAnchorElement>("a:not(.pb-root-link)").forEach(a => {
if (a.href === "") {
return;
}
try {
const url = new URL(a.href);
const qs = url.search || "";
a.href = `#${url.pathname}${qs}`;
} catch (e) {
a.href = `#${a.href}`;
}
});
// Create refresh buttons
this.querySelectorAll("[role=pb-refresh]").forEach(rt => {
rt.addEventListener("click", e => {
this.loadContent();
fetch(url)
.then((r) => r.text())
.then((t) => {
this.querySelector("[slot=body]")!.innerHTML = t;
})
.then(() => {
// Ensure anchors only change the hash
this.querySelectorAll<HTMLAnchorElement>(
"a:not(.pb-root-link)"
).forEach((a) => {
if (a.href === "") {
return;
}
try {
const url = new URL(a.href);
const qs = url.search || "";
a.href = `#${url.pathname}${qs}`;
} catch (e) {
a.href = `#${a.href}`;
}
});
// Create refresh buttons
this.querySelectorAll("[role=pb-refresh]").forEach((rt) => {
rt.addEventListener("click", (e) => {
this.loadContent();
});
});
this.loading = false;
});
this.loading = false;
});
}
render() {
return html`
${this.loading ? html`
<div class="pf-l-bullseye">
<div class="pf-l-bullseye__item">
<span class="pf-c-spinner pf-m-xl" role="progressbar" aria-valuetext="Loading...">
<span class="pf-c-spinner__clipper"></span>
<span class="pf-c-spinner__lead-ball"></span>
<span class="pf-c-spinner__tail-ball"></span>
</span>
</div>
</div>`: ""}
<slot name="body">
</slot>`;
return html` ${this.loading
? html` <div class="pf-l-bullseye">
<div class="pf-l-bullseye__item">
<span
class="pf-c-spinner pf-m-xl"
role="progressbar"
aria-valuetext="Loading..."
>
<span class="pf-c-spinner__clipper"></span>
<span class="pf-c-spinner__lead-ball"></span>
<span class="pf-c-spinner__tail-ball"></span>
</span>
</div>
</div>`
: ""}
<slot name="body"> </slot>`;
}
}

View File

@ -1,9 +1,9 @@
import { LitElement, html, customElement, property } from 'lit-element';
import { LitElement, html, customElement, property } from "lit-element";
import { updateMessages } from "../elements/Messages";
enum ResponseType {
redirect = "redirect",
template = "template"
template = "template",
}
interface Response {
@ -14,7 +14,6 @@ interface Response {
@customElement("pb-flow-shell-card")
export class FlowShellCard extends LitElement {
@property()
flowBodyUrl: string = "";
@ -26,19 +25,23 @@ export class FlowShellCard extends LitElement {
}
firstUpdated() {
fetch(this.flowBodyUrl).then(r => {
if (!r.ok) {
throw Error(r.statusText);
}
return r;
}).then((r) => {
return r.json();
}).then((r) => {
this.updateCard(r);
}).catch((e) => {
// Catch JSON or Update errors
this.errorMessage(e);
});
fetch(this.flowBodyUrl)
.then((r) => {
if (!r.ok) {
throw Error(r.statusText);
}
return r;
})
.then((r) => {
return r.json();
})
.then((r) => {
this.updateCard(r);
})
.catch((e) => {
// Catch JSON or Update errors
this.errorMessage(e);
});
}
async updateCard(data: Response) {
@ -54,13 +57,15 @@ export class FlowShellCard extends LitElement {
this.loadFormCode();
this.setFormSubmitHandlers();
default:
console.log(`passbook/flows: unexpected data type ${data.type}`);
console.log(
`passbook/flows: unexpected data type ${data.type}`
);
break;
}
};
}
loadFormCode() {
this.querySelectorAll("script").forEach(script => {
this.querySelectorAll("script").forEach((script) => {
let newScript = document.createElement("script");
newScript.src = script.src;
document.head.appendChild(newScript);
@ -78,7 +83,9 @@ export class FlowShellCard extends LitElement {
for (let index = 0; index < form.elements.length; index++) {
const element = <HTMLInputElement>form.elements[index];
if (element.value === form.action) {
console.log("passbook/flows: Found Form action URL in form elements, not changing form action.");
console.log(
"passbook/flows: Found Form action URL in form elements, not changing form action."
);
return false;
}
}
@ -94,26 +101,31 @@ export class FlowShellCard extends LitElement {
}
setFormSubmitHandlers() {
this.querySelectorAll("form").forEach(form => {
console.log(`passbook/flows: Checking for autosubmit attribute ${form}`);
this.querySelectorAll("form").forEach((form) => {
console.log(
`passbook/flows: Checking for autosubmit attribute ${form}`
);
this.checkAutosubmit(form);
console.log(`passbook/flows: Setting action for form ${form}`);
this.updateFormAction(form);
console.log(`passbook/flows: Adding handler for form ${form}`);
form.addEventListener('submit', (e) => {
form.addEventListener("submit", (e) => {
e.preventDefault();
let formData = new FormData(form);
this.flowBody = undefined;
fetch(this.flowBodyUrl, {
method: 'post',
method: "post",
body: formData,
}).then((response) => {
return response.json()
}).then(data => {
this.updateCard(data);
}).catch((e) => {
this.errorMessage(e);
});
})
.then((response) => {
return response.json();
})
.then((data) => {
this.updateCard(data);
})
.catch((e) => {
this.errorMessage(e);
});
});
form.classList.add("pb-flow-wrapped");
});
@ -141,19 +153,22 @@ export class FlowShellCard extends LitElement {
}
loading() {
return html`
<div class="pf-c-login__main-body pb-loading">
<span class="pf-c-spinner" role="progressbar" aria-valuetext="Loading...">
<span class="pf-c-spinner__clipper"></span>
<span class="pf-c-spinner__lead-ball"></span>
<span class="pf-c-spinner__tail-ball"></span>
</span>
</div>`;
return html` <div class="pf-c-login__main-body pb-loading">
<span
class="pf-c-spinner"
role="progressbar"
aria-valuetext="Loading..."
>
<span class="pf-c-spinner__clipper"></span>
<span class="pf-c-spinner__lead-ball"></span>
<span class="pf-c-spinner__tail-ball"></span>
</span>
</div>`;
}
render() {
if (this.flowBody) {
return html(<TemplateStringsArray><unknown>[this.flowBody]);
return html(<TemplateStringsArray>(<unknown>[this.flowBody]));
}
return this.loading();
}

View File

@ -1,12 +1,14 @@
export function getCookie(name: string) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
if (document.cookie && document.cookie !== "") {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
if (cookie.substring(0, name.length + 1) === name + "=") {
cookieValue = decodeURIComponent(
cookie.substring(name.length + 1)
);
break;
}
}
@ -17,6 +19,6 @@ export function getCookie(name: string) {
export function convertToSlug(text: string): string {
return text
.toLowerCase()
.replace(/ /g, '-')
.replace(/[^\w-]+/g, '');
.replace(/ /g, "-")
.replace(/[^\w-]+/g, "");
}

View File

@ -9,10 +9,6 @@
"target": "es2017",
"module": "es2015",
"moduleResolution": "node",
"lib": [
"es2017",
"dom",
"dom.iterable"
],
"lib": ["es2017", "dom", "dom.iterable"]
}
}