This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
authentik/web/src/elements/CodeMirror.ts

83 lines
2.3 KiB
TypeScript
Raw Normal View History

import { CSSResult, customElement, html, LitElement, property, TemplateResult } from "lit-element";
import PFForm from "@patternfly/patternfly/components/Form/form.css";
2020-11-21 17:32:34 +00:00
import CodeMirror from "codemirror";
import "codemirror/addon/display/autorefresh";
import "codemirror/mode/xml/xml.js";
import "codemirror/mode/yaml/yaml.js";
2021-02-03 20:58:30 +00:00
import "codemirror/mode/javascript/javascript.js";
2020-11-21 17:32:34 +00:00
import "codemirror/mode/python/python.js";
import CodeMirrorStyle from "codemirror/lib/codemirror.css";
import CodeMirrorTheme from "codemirror/theme/monokai.css";
import { ifDefined } from "lit-html/directives/if-defined";
import YAML from "yaml";
2020-11-21 17:32:34 +00:00
2020-12-05 21:08:42 +00:00
@customElement("ak-codemirror")
2020-11-21 17:32:34 +00:00
export class CodeMirrorTextarea extends LitElement {
2020-12-02 14:44:40 +00:00
@property({type: Boolean})
2020-12-01 08:15:41 +00:00
readOnly = false;
2020-11-21 17:32:34 +00:00
@property()
2020-12-01 08:15:41 +00:00
mode = "yaml";
2020-11-21 17:32:34 +00:00
@property()
name?: string;
editor?: CodeMirror.EditorFromTextArea;
private _value?: string;
@property()
set value(v: string) {
if (v === null) return;
this._value = v.toString();
}
get value(): string {
switch (this.mode.toLowerCase()) {
case "yaml":
return YAML.parse(this.getInnerValue());
case "javascript":
return JSON.parse(this.getInnerValue());
default:
return this.getInnerValue();
}
}
private getInnerValue(): string {
if (!this.shadowRoot) {
return "";
}
const ta = this.shadowRoot?.querySelector("textarea");
if (!ta) {
return "";
}
return ta.value;
}
2020-11-21 17:32:34 +00:00
static get styles(): CSSResult[] {
return [PFForm, CodeMirrorStyle, CodeMirrorTheme];
2020-11-21 17:32:34 +00:00
}
firstUpdated(): void {
const textarea = this.shadowRoot?.querySelector("textarea");
2020-11-21 17:32:34 +00:00
if (!textarea) {
return;
}
this.editor = CodeMirror.fromTextArea(textarea, {
mode: this.mode,
2020-11-21 19:48:49 +00:00
theme: "monokai",
2020-11-21 17:32:34 +00:00
lineNumbers: false,
readOnly: this.readOnly,
autoRefresh: true,
});
this.editor.on("blur", () => {
2020-11-21 17:32:34 +00:00
this.editor?.save();
});
}
render(): TemplateResult {
return html`<textarea class="pf-c-form-control" name=${ifDefined(this.name)}>${this._value || ""}</textarea>`;
}
2020-11-21 17:32:34 +00:00
}