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 @@
{}

View File

@ -449,6 +449,12 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz",
"integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg=="
},
"prettier": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.2.0.tgz",
"integrity": "sha512-yYerpkvseM4iKD/BXLYUkQV5aKt4tQPqaGW6EsZjzyu0r7sVZZNPJW4Y8MyKmicp6t42XUPcBVA+H6sB3gqndw==",
"dev": true
},
"randombytes": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",

View File

@ -19,6 +19,7 @@
},
"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",

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,19 +1,20 @@
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',
export default [
{
input: "./src/main.ts",
output: [
{
format: 'es',
dir: 'dist',
sourcemap: true
}
format: "es",
dir: "dist",
sourcemap: true,
},
],
plugins: [
cssimport(),
@ -24,4 +25,5 @@ export default [{
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 => {
mode: "same-origin",
})
.then((r) => r.json())
.then((r) => {
this.setDone(SUCCESS_CLASS);
}).catch(() => {
})
.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...">
${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>` : ""}
</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 = "";
@ -32,7 +31,7 @@ export class AdminLoginsChart extends LitElement {
constructor() {
super();
window.addEventListener('resize', () => {
window.addEventListener("resize", () => {
if (this.chart) {
this.chart.resize();
}
@ -40,56 +39,74 @@ 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')!;
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',
type: "bar",
data: {
datasets: [
{
label: 'Failed Logins',
label: "Failed Logins",
backgroundColor: "rgba(201, 25, 11, .5)",
spanGaps: true,
data: r.logins_failed_per_1h,
},
{
label: 'Successful Logins',
label: "Successful Logins",
backgroundColor: "rgba(189, 229, 184, .5)",
spanGaps: true,
data: r.logins_per_1h,
},
]
],
},
options: {
maintainAspectRatio: false,
spanGaps: true,
scales: {
xAxes: [{
xAxes: [
{
stacked: true,
gridLines: {
color: "rgba(0, 0, 0, 0)",
},
type: 'time',
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);
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
}
}],
yAxes: [{
maxTicksLimit: 8,
},
},
],
yAxes: [
{
stacked: true,
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
},
},
],
},
},
});
});
}
@ -97,5 +114,4 @@ export class AdminLoginsChart extends LitElement {
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,11 +15,13 @@ 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;
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 === "") {
@ -31,18 +32,18 @@ export class AdminSideBar extends LitElement {
}
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,8 +38,13 @@ 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")!;
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);
@ -52,7 +56,9 @@ export class Messages extends LitElement {
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,62 +32,83 @@ 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 => {
this.querySelectorAll<HTMLAnchorElement>("[slot=modal] a").forEach(
(a) => {
// Make click on a close the modal
a.addEventListener("click", e => {
a.addEventListener("click", (e) => {
e.preventDefault();
this.open = false;
});
});
}
);
// Make name field update slug field
this.querySelectorAll<HTMLInputElement>("input[name=name]").forEach((input) => {
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]");
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) => {
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, {
fetch(
form.action === window.location.toString()
? this.href
: form.action,
{
method: form.method,
body: formData,
}).then((response) => {
}
)
.then((response) => {
return response.text();
}).then(data => {
})
.then((data) => {
if (data.indexOf("csrfmiddlewaretoken") !== -1) {
this.setContent(data);
} else {
this.open = false;
this.dispatchEvent(new CustomEvent('hashchange', { bubbles: true }));
this.dispatchEvent(
new CustomEvent("hashchange", {
bubbles: true,
})
);
updateMessages();
}
}).catch((e) => {
})
.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) => {
mode: "same-origin",
})
.then((r) => r.text())
.then((t) => {
this.setContent(t);
this.open = true;
}).catch(e => {
})
.catch((e) => {
console.error(e);
});
}
@ -96,21 +116,32 @@ export class ModalButton extends LitElement {
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,7 +11,9 @@ 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 => {
fetch(url)
.then((r) => r.json())
.then((r) => {
el.textContent = r[key];
el.value = r[key];
});
@ -21,13 +23,13 @@ document.querySelectorAll("[data-pb-fetch-fill]").forEach((el) => {
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,13 +37,17 @@ 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) => {
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")) {
@ -57,7 +63,9 @@ document.querySelectorAll(".pf-c-page__header-brand-toggle>button").forEach((tog
});
// Collapsable Menus in Sidebar
document.querySelectorAll(".pf-m-expandable>.pf-c-nav__link").forEach((menu) => {
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,7 +24,8 @@ export class AdminSiteShell extends LitElement {
loading: boolean = false;
static get styles() {
return [css`
return [
css`
:host {
position: relative;
}
@ -29,7 +36,10 @@ export class AdminSiteShell extends LitElement {
top: 0;
left: 0;
}
`, BullseyeStyle, SpinnerStyle];
`,
BullseyeStyle,
SpinnerStyle,
];
}
constructor() {
@ -41,14 +51,19 @@ 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) => {
fetch(url)
.then((r) => r.text())
.then((t) => {
this.querySelector("[slot=body]")!.innerHTML = t;
}).then(() => {
})
.then(() => {
// Ensure anchors only change the hash
this.querySelectorAll<HTMLAnchorElement>("a:not(.pb-root-link)").forEach(a => {
this.querySelectorAll<HTMLAnchorElement>(
"a:not(.pb-root-link)"
).forEach((a) => {
if (a.href === "") {
return;
}
@ -61,8 +76,8 @@ export class AdminSiteShell extends LitElement {
}
});
// Create refresh buttons
this.querySelectorAll("[role=pb-refresh]").forEach(rt => {
rt.addEventListener("click", e => {
this.querySelectorAll("[role=pb-refresh]").forEach((rt) => {
rt.addEventListener("click", (e) => {
this.loadContent();
});
});
@ -71,19 +86,21 @@ export class AdminSiteShell extends LitElement {
}
render() {
return html`
${this.loading ? html`
<div class="pf-l-bullseye">
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 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>`;
</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,16 +25,20 @@ export class FlowShellCard extends LitElement {
}
firstUpdated() {
fetch(this.flowBodyUrl).then(r => {
fetch(this.flowBodyUrl)
.then((r) => {
if (!r.ok) {
throw Error(r.statusText);
}
return r;
}).then((r) => {
})
.then((r) => {
return r.json();
}).then((r) => {
})
.then((r) => {
this.updateCard(r);
}).catch((e) => {
})
.catch((e) => {
// Catch JSON or Update errors
this.errorMessage(e);
});
@ -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,24 +101,29 @@ 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 => {
})
.then((response) => {
return response.json();
})
.then((data) => {
this.updateCard(data);
}).catch((e) => {
})
.catch((e) => {
this.errorMessage(e);
});
});
@ -141,9 +153,12 @@ 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...">
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>
@ -153,7 +168,7 @@ export class FlowShellCard extends LitElement {
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"]
}
}