1
0
Fork 0
mirror of https://github.com/Findus23/RPGnotes.git synced 2024-09-19 15:43:45 +02:00

typescript

This commit is contained in:
Lukas Winkler 2022-07-31 00:46:21 +02:00
parent 93e221eed1
commit 5ff82cc392
Signed by: lukas
GPG key ID: 54DE4D798D244853
16 changed files with 1265 additions and 74 deletions

View file

@ -31,13 +31,3 @@
</form>
{% endblock %}
{#{% block extra_js %}#}
{# {{ super() }}#}
{# {% if "Safari/" not in request.META.get('HTTP_USER_AGENT', '') %}#}
{# <script src="{{ static("libs/easymde.min.js") }}"></script>#}
{# <script src="{{ static("libs/fontawesome-solid.min.js") }}"></script>#}
{# <script src="{{ static("libs/fontawesome.min.js") }}"></script>#}
{# <script src="{{ static("js/markdown.js") }}"></script>#}
{# {% endif %}#}
{#{% endblock %}#}

974
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"scripts": {
"dev": "vite",
"build": "vite build",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
@ -18,13 +18,16 @@
"@trevoreyre/autocomplete-js": "^2.2.0",
"bootstrap": "^5.2.0-beta1",
"codemirror": "^6.0.1",
"dts-gen": "^0.6.0",
"luminous-lightbox": "^2.3.5",
"typescript": "^4.7.4",
"vite": "^3.0.2",
"y-codemirror.next": "^0.3.2",
"y-webrtc": "^10.2.3",
"yjs": "^13.5.41"
},
"devDependencies": {
"@types/bootstrap": "^5.2.1",
"rollup-plugin-visualizer": "^5.7.1",
"sass": "^1.54.0"
}

View file

@ -1,6 +1,12 @@
import Autocomplete from "@trevoreyre/autocomplete-js"
const form = document.getElementById("autocomplete-form")
interface AutocompleteResult {
url: string
name: string
distance: number
}
const form = document.getElementById("autocomplete-form")! as HTMLFormElement
form.addEventListener("submit", function (e) {
e.preventDefault()
@ -17,13 +23,13 @@ new Autocomplete('#autocomplete', {
fetch(url)
.then(response => response.json())
.then(data => {
.then((data: AutocompleteResult[]) => {
resolve(data)
})
})
},
getResultValue: result => result.name,
onSubmit: result => {
getResultValue: (result: AutocompleteResult) => result.name,
onSubmit: (result: AutocompleteResult) => {
if (!result) {
form.submit()
return

View file

@ -1,34 +1,15 @@
import {InjectCSS, register, ReplaceElements} from '@fortawesome/fontawesome-svg-core/plugins'
import {
faArrowsAlt,
faBold,
faColumns,
faEye,
faHeading,
faImage,
faItalic,
faLink,
faListOl,
faListUl,
faQuestionCircle,
faQuoteLeft
} from '@fortawesome/free-solid-svg-icons'
import {EditorView, minimalSetup} from "codemirror"
import {markdownLanguage} from "@codemirror/lang-markdown"
import {foldGutter} from "@codemirror/language";
interface DraftSaveResponse {
message: string
}
const api = register([InjectCSS, ReplaceElements])
api.library.add(
faBold, faItalic, faHeading, faQuoteLeft, faListUl, faListOl, faLink, faImage,
faEye, faColumns, faArrowsAlt, faQuestionCircle,
)
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
const csrftoken = (document.querySelector('[name=csrfmiddlewaretoken]')! as HTMLInputElement).value;
const ids = ["id_description_md"];
ids.forEach(function (id) {
const element = document.getElementById(id);
const element = document.getElementById(id) as HTMLTextAreaElement;
if (!element) {
return
}
@ -44,10 +25,10 @@ ids.forEach(function (id) {
// color: "red",
// colorLight: "lightred"
// })
const labelEl = element.labels[0]
const div = document.createElement("div")
element.style.display = "none"
element.parentElement.insertBefore(div, element)
element.parentElement!.insertBefore(div, element)
const view = new EditorView({
extensions: [
minimalSetup,
@ -60,7 +41,7 @@ ids.forEach(function (id) {
parent: div,
doc: element.value,
})
element.form.addEventListener("submit", () => {
element.form!.addEventListener("submit", () => {
element.value = view.state.doc.toString()
})
// const easyMDE = new EasyMDE({
@ -88,23 +69,23 @@ ids.forEach(function (id) {
// status: ["lines", "words", "cursor", "saveStatus"],
// });
// window.editor = easyMDE
// setInterval(function () {
// const content = easyMDE.value();
// fetch("/api/draft/save", {
// method: "POST",
// body: JSON.stringify({
// "draft_md": content
// }),
// headers: {'X-CSRFToken': csrftoken},
// })
// .then(response => response.json())
// .then(data => {
// easyMDE.updateStatusBar("saveStatus", data.message)
// setTimeout(e => easyMDE.updateStatusBar("saveStatus", ""), 5000)
// }).catch(e => {
// easyMDE.updateStatusBar("saveStatus", "error saving draft")
// })
//
// }, 1000 * 30)
const originalLabel = labelEl.innerText
setInterval(function () {
const content = view.state.doc.toString();
fetch("/api/draft/save", {
method: "POST",
body: JSON.stringify({
"draft_md": content
}),
headers: {'X-CSRFToken': csrftoken},
})
.then(response => response.json())
.then((data: DraftSaveResponse) => {
labelEl.innerText += ": " + data.message
setTimeout(() => labelEl.innerText = originalLabel, 5000)
}).catch(e => {
labelEl.innerText += ": " + "error saving draft"
})
}, 1000 * 30)
});
api.dom.i2svg()

View file

View file

@ -16,7 +16,6 @@ import {
faQuoteLeft
} from '@fortawesome/free-solid-svg-icons'
console.log("in markdown.js")
const api = register([InjectCSS, ReplaceElements])
api.library.add(

View file

@ -1,6 +1,8 @@
// @ts-ignore
import {default as Popover} from "bootstrap/js/src/popover";
// import type {Popover as PopoverType} from "bootstrap";
const popoverTriggerList = document.querySelectorAll('.content a')
const popoverTriggerList: NodeListOf<HTMLAnchorElement> = document.querySelectorAll('.content a')
const popoverList = [...popoverTriggerList].map(popoverTriggerEl => {
console.log(popoverTriggerEl.host)
console.log(popoverTriggerEl.href.startsWith("htt"))
@ -13,7 +15,7 @@ const popoverList = [...popoverTriggerList].map(popoverTriggerEl => {
trigger: 'hover focus',
placement: "bottom",
sanitize: false,
sanitizeFn: a => a
sanitizeFn: (a: string) => a
});
popoverTriggerEl.addEventListener('inserted.bs.popover', (e) => {
console.log("shown")

View file

@ -8,3 +8,4 @@ if (sentryMetaEl) {
})
}
export const test = 1

View file

@ -2,7 +2,9 @@ import 'vite/modulepreload-polyfill'
// import "./scss/main.scss"
import "./js/sentry"
// @ts-ignore
import {default as Dropdown} from 'bootstrap/js/src/dropdown'
// @ts-ignore
import {default as Collapse} from 'bootstrap/js/src/collapse'
import "./js/autocomplete"

View file

@ -0,0 +1,114 @@
// Type definitions for @trevoreyre/autocomplete 2.0
// Project: https://github.com/trevoreyre/autocomplete/, https://autocomplete.trevoreyre.com/
// Definitions by: versedi <https://github.com/versedi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// from https://github.com/versedi/DefinitelyTyped/tree/trevoreyre/autocomplete-js/types/trevoreyre__autocomplete-js
declare module "@trevoreyre/autocomplete-js" {
// export as namespace Autocomplete;
/**
* Creates a props object with overridden toString function. toString returns an attributes
* string in the format: `key1="value1" key2="value2"` for easy use in an HTML string.
*/
export class Props {
/**
* @param index string
* @param selectedIndex string
* @param baseClass string
*/
constructor(index: string, selectedIndex: string, baseClass: string);
public toString(): string;
}
// --------------------------------------------------------------------------------------
// Options Interfaces
// --------------------------------------------------------------------------------------
export interface AutocompleteOptions {
/**
* Controls whether first result should be highlighted after input
this.foo = val* Defaults to false, optional
*/
autoSelect?: boolean;
/**
* The search function to be executed on user input. Can be a synchronous function or a Promise.
* @param input
*/
search(input: string): object | Promise<object>;
/**
* Sets the value of the calling component's input element
*/
setValue?(): () => void;
/**
* Sets attributes on the calling component's input element
*/
setAttribute?(): () => void;
/**
* Fired when the results list is updated. Receives results (Array), and selectedIndex (Number) as arguments.
*/
onUpdate?(): () => void;
/**
* Fired when user submits result. Receives result as argument.
* @param result
*/
onSubmit(result: object): void;
// getResultValue?(): (result:object) => string;
getResultValue?: (result) => any
/**
*
* @param result
* @param props
*/
renderResult?(result: object, props: Props): string;
/**
* Fired when the results list is shown
*/
onShow?(): () => void;
/**
* Fired when the results list is hidden
*/
onHide?(): () => void;
/**
* Fired if search is a Promise and hasn't resolved yet
*/
onLoading?(): () => void;
/**
* Fired after asynchronous search function resolves
*/
onLoaded?(): () => void;
}
export interface EventHandlers {
handleInput: () => void;
handleKeyDown: () => void;
handleBlur: () => void;
handleResultMouseDown: () => void;
handleResultClick: () => void;
}
// --------------------------------------------------------------------------------------
// Autocomplete
// --------------------------------------------------------------------------------------
export default class Autocomplete<TElement = HTMLElement> {
public options: AutocompleteOptions;
constructor(inputSelector: string, options?: AutocompleteOptions);
}
}

28
static/types/luminous-lightbox.d.ts vendored Normal file
View file

@ -0,0 +1,28 @@
declare module "luminous-lightbox" {
/** Declaration file generated by dts-gen */
export class Luminous {
constructor(trigger: any, ...args: any[]);
close(e: any): void;
destroy(): void;
open(e: any): void;
}
export class LuminousGallery {
constructor(triggers: NodeListOf<Element>, ...args: any[]);
destroy(): any;
nextTrigger(trigger: any): any;
onChange(_ref: any): void;
previousTrigger(trigger: any): any;
}
}

View file

@ -10,7 +10,7 @@
{% if debug %}
<link rel="stylesheet" href="{{ url("css") }}">
{% else %}
{% for dep in get_dependencies("main.js") %}
{% for dep in get_dependencies("main.ts") %}
<link rel="modulepreload" href="{{ dep }}"></link>
{% endfor %}
<link rel="stylesheet" href="{{ static("css/main.css") }}">
@ -46,9 +46,9 @@
</footer>
{% if debug %}
<script type="module" src="http://localhost:5173/@vite/client"></script>
<script type="module" src="http://localhost:5173/static/main.js"></script>
<script type="module" src="http://localhost:5173/static/main.ts"></script>
{% else %}
<script type="module" src="{{ js_asset_url("main.js") }}"></script>
<script type="module" src="{{ js_asset_url("main.ts") }}"></script>
{% endif %}
{% if sentry_event_id %}

103
tsconfig.json Normal file
View file

@ -0,0 +1,103 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
"useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
"isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

View file

@ -13,7 +13,7 @@ export default defineConfig({
rollupOptions: {
// overwrite default .html entry
input: {
"main": 'static/main.js',
"main": 'static/main.ts',
// "tenantbase": 'static/tenantbase.js',
// "editor": 'static/editor.js'
},