V2.0.0-beta (#308)
* test vue-echarts and dataset>source instead of series>data Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix disposed state of chart & delete update interval of settings page Signed-off-by: Stefan Dej <meteyou@gmail.com> * init TS migation & dashboard Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: dashbaord console Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: add "disabled" status to the filament runout sensor on the dashboard Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix klipper restart process Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix status panel during a print Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert g-code files to typescript Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert history files to typescript Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert machine limits to typescript Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert update manager to typescript Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert endstops & logfiles to typescript Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix temp display in tools panel Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert machine > config files to TS Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert select printer dialog to TS Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert select printer menu to TS Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert farm page to TS Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix debug output of farm printer getters Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix import webcam streams in farm view Signed-off-by: Stefan Dej <meteyou@gmail.com> * better handling when changing printers Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert heightmap to TS Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert heightmap to TS Signed-off-by: Stefan Dej <meteyou@gmail.com> * Console QOL (#300) * CHORE Signed-off-by: Eike Ahmels <eike.ahmels@tu-dortmund.de> * NEW: console ts refactor, linux autocomplete, gui helplist, multiline Signed-off-by: Eike Ahmels <eike.ahmels@tu-dortmund.de> * FIX: console autocomplete flood fix Signed-off-by: Eike Ahmels <eike.ahmels@tu-dortmund.de> * fix merged console Signed-off-by: Stefan Dej <meteyou@gmail.com> * fixed return of ConsoleTable.vue isCommand Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: add toast after creating file in ConfigFilesPanel.vue Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: file upload message Signed-off-by: Stefan Dej <meteyou@gmail.com> * add toolbar to files panels Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: disable scrollbars in TempChart.vue Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: sidebar z-index and farm printer toolbar Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: sidebar & topbar z-index and farm printer toolbar Signed-off-by: Stefan Dej <meteyou@gmail.com> * update toolbars in gcode-files and history Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: new settings dialog (#302) * create settings dialog and integrate general, console, control, marcos, presets, webcams Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: renamed webcam gui state variable Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: temperature_fan chamber in farm printers dashboard Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: only display RPM in tools panel, when its available Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: reading empty remote printers list Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: loading additionalSensors in temp panel Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix: bed_mesh loading rework heightmap settings save heightmap settings in moonraker db Signed-off-by: Stefan Dej <meteyou@gmail.com> * add remote printers to settings Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix types Signed-off-by: Stefan Dej <meteyou@gmail.com> * add beforeDestroy to echarts Signed-off-by: Stefan Dej <meteyou@gmail.com> * add heightmap visualMap scaling and format tooltip Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: logo & primary color customizing Signed-off-by: Stefan Dej <meteyou@gmail.com> * remove keep-alive in app.vue Signed-off-by: Stefan Dej <meteyou@gmail.com> * round tempchart data Signed-off-by: Stefan Dej <meteyou@gmail.com> * normalize toolbar buttons Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix series attributes & update echarts-gl Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix hostname in sidebar Signed-off-by: Stefan Dej <meteyou@gmail.com> * rework websocket loadings Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix rework websocket loadings Signed-off-by: Stefan Dej <meteyou@gmail.com> * Fixes for console QOL PR (#301) * FIX: command help dialog added Signed-off-by: Eike Ahmels <eike.ahmels@tu-dortmund.de> * FIX: console fixes Signed-off-by: Eike Ahmels <eike.ahmels@tu-dortmund.de> * rework events store Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: check customFilters if string or array Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: edit preset dont work (existing name check) Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: save webcam with index 0 Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: tool combobox input dont work Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: tooltip position & z-index Signed-off-by: Stefan Dej <meteyou@gmail.com> * rework console Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix output name of filament sensor Signed-off-by: Stefan Dej <meteyou@gmail.com> * store performance updates and StatusPanel.vue optimizing Signed-off-by: Stefan Dej <meteyou@gmail.com> * console bugfixes Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix icon-rotate in temperatures panel Signed-off-by: Stefan Dej <meteyou@gmail.com> * add auto-grow to console input fields Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix dialog action button colors Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix refreshMetadata of gcocde files Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: add multi fileupload to drag&drop upload Signed-off-by: Stefan Dej <meteyou@gmail.com> * convert SystemPanel to TS Signed-off-by: Stefan Dej <meteyou@gmail.com> * add init and getters for system panels Signed-off-by: Stefan Dej <meteyou@gmail.com> * add init and getters for system panels Signed-off-by: Stefan Dej <meteyou@gmail.com> * finish SystemPanel.vue Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: raspberry throttled flags in topbar Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: fix type in TheThrottledStates.vue Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: add new editor (#307) * init test Signed-off-by: Stefan Dej <meteyou@gmail.com> * theme test Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: switch to codemirror editor Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: fix type in TheThrottledStates.vue Signed-off-by: Stefan Dej <meteyou@gmail.com> * reformat flags output and deactivate debug output Signed-off-by: Stefan Dej <meteyou@gmail.com> * add types to throttle states Signed-off-by: Stefan Dej <meteyou@gmail.com> * display "dirty" in the board firmware version string Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix mini console array cut Signed-off-by: Stefan Dej <meteyou@gmail.com> * delete old comment Signed-off-by: Stefan Dej <meteyou@gmail.com> * fix config files on small devices Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: display macro description in settings tab Signed-off-by: Stefan Dej <meteyou@gmail.com> * change settings icons Signed-off-by: Stefan Dej <meteyou@gmail.com> * rename dashboard panel & change slider text in settings Signed-off-by: Stefan Dej <meteyou@gmail.com> * responsive optimations for settings Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix throttled state flags filter Signed-off-by: Stefan Dej <meteyou@gmail.com> * Code highlighting for codemirror (#309) * init test Signed-off-by: Stefan Dej <meteyou@gmail.com> * theme test Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: switch to codemirror editor Signed-off-by: Stefan Dej <meteyou@gmail.com> * NEW: klipper_config editor theme Signed-off-by: Eike Ahmels <eike.ahmels@tu-dortmund.de> * NEW: code highlighting for codemirror Signed-off-by: Eike Ahmels <eike.ahmels@tu-dortmund.de> Co-authored-by: Stefan Dej <meteyou@gmail.com> * feature: hide/show jobs with special print status Signed-off-by: Stefan Dej <meteyou@gmail.com> * redesign console help modal Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: default state of sidebar was wrong on mobile devices Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: mobile view interface settings Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: optimize mobile view interface settings Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: block empty console commands Signed-off-by: Stefan Dej <meteyou@gmail.com> * push version number Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: add current / max flow in status panel Signed-off-by: Stefan Dej <meteyou@gmail.com> * feature: add big gcode thumbnail to status panel Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: fix favicon and setting tab names Signed-off-by: Stefan Dej <meteyou@gmail.com> * cleanup old editor Signed-off-by: Stefan Dej <meteyou@gmail.com> * bugfix: add redirect for updates from 1.6.0 to 2.0.0 Signed-off-by: Stefan Dej <meteyou@gmail.com> Co-authored-by: Eike Ahmels <hui_buh-@gmx.net>
This commit is contained in:
1 parent
84e86bb8b2
commit
baa25c4bcd
227 files changed
+25004
-28604
No files matched your search
@@ -0,0 +1,69 @@
|
||||
import {StringStream} from "@codemirror/stream-parser";
|
||||
|
||||
export const gcode = {
|
||||
token: function(stream: StringStream, state: StreamParserGcodeState, zeroPos = 0): string | null {
|
||||
const ch = stream.peek();
|
||||
|
||||
if (stream.pos === zeroPos && state.klipperMacro) state.klipperMacro = false
|
||||
|
||||
/* Klipper macro attributes */
|
||||
if (stream.pos > zeroPos && state.klipperMacro) {
|
||||
if (stream.match(/^\s*[A-Z_]+/))
|
||||
return 'propertyName'
|
||||
else if (stream.match(/^\s*[A-Za-z0-9_]+/))
|
||||
return 'number'
|
||||
else if (stream.match(/^{.*}/))
|
||||
return 'variable'
|
||||
}
|
||||
|
||||
/* comments */
|
||||
if ([';', '#'].includes(ch ?? '')) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
|
||||
/* Mxxx Gxxx commands */
|
||||
if (stream.pos == zeroPos && stream.match(/[GMgm][\d]+/)) {
|
||||
return 'namespace'
|
||||
}
|
||||
|
||||
/* G0/1 movements */
|
||||
if (stream.pos > zeroPos && stream.match(/[XYZIJxyzij]-?([\d]*\.[\d]+|[\d]+)?/)) {
|
||||
return 'className'
|
||||
}
|
||||
|
||||
/* G0/1 speeds */
|
||||
if (stream.pos > zeroPos && stream.match(/[Ff]-?([\d]*\.[\d]+|[\d]+)/)) {
|
||||
return 'string'
|
||||
}
|
||||
|
||||
/* G0/1 extrusions */
|
||||
if (stream.pos > zeroPos && stream.match(/[TtSsEe]-?([\d]*\.[\d]+|[\d]+)/)) {
|
||||
return 'atom'
|
||||
}
|
||||
|
||||
if (stream.pos > zeroPos && stream.match(/^{.*}/))
|
||||
return 'propertyName'
|
||||
|
||||
/* Klipper macro names */
|
||||
if (stream.pos == zeroPos && stream.match(/^[A-Z_]+/)) {
|
||||
state.klipperMacro = true
|
||||
return 'name'
|
||||
}
|
||||
|
||||
stream.next();
|
||||
return null;
|
||||
},
|
||||
startState: function(): StreamParserGcodeState {
|
||||
return {
|
||||
klipperMacro: false,
|
||||
};
|
||||
},
|
||||
languageData: {
|
||||
commentTokens: {line: ";"}
|
||||
}
|
||||
};
|
||||
|
||||
interface StreamParserGcodeState {
|
||||
klipperMacro: boolean
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
import {StringStream} from "@codemirror/stream-parser";
|
||||
let keywords = ["and", "as", "block", "endblock", "by", "cycle", "debug", "else", "elif",
|
||||
"extends", "filter", "endfilter", "firstof", "for",
|
||||
"endfor", "if", "endif", "ifchanged", "endifchanged",
|
||||
"ifequal", "endifequal", "ifnotequal",
|
||||
"endifnotequal", "in", "include", "load", "not", "now", "or",
|
||||
"parsed", "regroup", "reversed", "spaceless",
|
||||
"endspaceless", "ssi", "templatetag", "openblock",
|
||||
"closeblock", "openvariable", "closevariable",
|
||||
"openbrace", "closebrace", "opencomment",
|
||||
"closecomment", "widthratio", "url", "with", "endwith",
|
||||
"get_current_language", "trans", "endtrans", "noop", "blocktrans",
|
||||
"endblocktrans", "get_available_languages",
|
||||
"get_current_language_bidi", "plural"];
|
||||
const operator = /^[+\-*&%=<>!?|~^]/;
|
||||
const sign = /^[:[({]/;
|
||||
let atom = ["true", "false"];
|
||||
const number = /^(\d[+\-*!/])?\d+(\.\d+)?/;
|
||||
|
||||
keywords = new RegExp("((" + keywords.join(")|(") + "))\\b");
|
||||
atom = new RegExp("((" + atom.join(")|(") + "))\\b");
|
||||
|
||||
export const jinja2 = {
|
||||
token: function(stream: StringStream, state: StreamParserJinja2State): string {
|
||||
let ch: string | void = stream.peek();
|
||||
|
||||
//Comment
|
||||
if (state.incomment) {
|
||||
if(!stream.skipTo("#}")) {
|
||||
stream.skipToEnd();
|
||||
} else {
|
||||
stream.eatWhile(/[#}]/);
|
||||
state.incomment = false;
|
||||
}
|
||||
return "comment";
|
||||
//Tag
|
||||
} else if (state.intag) {
|
||||
//After operator
|
||||
if(state.operator) {
|
||||
state.operator = false;
|
||||
if(stream.match(atom)) {
|
||||
return "atom";
|
||||
}
|
||||
if(stream.match(number)) {
|
||||
return "number";
|
||||
}
|
||||
}
|
||||
//After sign
|
||||
if(state.sign) {
|
||||
state.sign = false;
|
||||
if(stream.match(atom)) {
|
||||
return "atom";
|
||||
}
|
||||
if(stream.match(number)) {
|
||||
return "number";
|
||||
}
|
||||
}
|
||||
|
||||
if(state.instring) {
|
||||
if(ch == state.instring) {
|
||||
state.instring = false;
|
||||
}
|
||||
stream.next();
|
||||
return "string";
|
||||
} else if(ch == "'" || ch == '"') {
|
||||
state.instring = ch;
|
||||
stream.next();
|
||||
return "string";
|
||||
} else if(stream.match(state.intag + "}") || stream.eat("-") && stream.match(state.intag + "}")) {
|
||||
state.intag = false;
|
||||
return "tag";
|
||||
} else if(stream.match(operator)) {
|
||||
state.operator = true;
|
||||
return "operator";
|
||||
} else if(stream.match(sign)) {
|
||||
state.sign = true;
|
||||
} else {
|
||||
if(stream.eat(" ") || stream.sol()) {
|
||||
if(stream.match(keywords)) {
|
||||
return "keyword";
|
||||
}
|
||||
if(stream.match(atom)) {
|
||||
return "atom";
|
||||
}
|
||||
if(stream.match(number)) {
|
||||
return "number";
|
||||
}
|
||||
if(stream.sol()) {
|
||||
stream.next();
|
||||
}
|
||||
} else {
|
||||
stream.next();
|
||||
}
|
||||
|
||||
}
|
||||
return "variable";
|
||||
} else if (stream.eat("{")) {
|
||||
if (stream.eat("#")) {
|
||||
state.incomment = true;
|
||||
if(!stream.skipTo("#}")) {
|
||||
stream.skipToEnd();
|
||||
} else {
|
||||
stream.eatWhile(/[#}]/);
|
||||
state.incomment = false;
|
||||
}
|
||||
return "comment";
|
||||
//Open tag
|
||||
// eslint-disable-next-line no-cond-assign
|
||||
} else if (ch = stream.eat(/[{%]/)) {
|
||||
//Cache close tag
|
||||
state.intag = ch;
|
||||
if(ch == "{") {
|
||||
state.intag = "}";
|
||||
}
|
||||
stream.eat("-");
|
||||
return "tag";
|
||||
}
|
||||
}
|
||||
stream.next();
|
||||
},
|
||||
startState: function(): StreamParserJinja2State {
|
||||
return {
|
||||
incomment: false,
|
||||
intag: false,
|
||||
operator: false,
|
||||
sign: false,
|
||||
instring: false
|
||||
};
|
||||
},
|
||||
languageData: {
|
||||
blockCommentStart: "{#",
|
||||
blockCommentEnd: "#}"
|
||||
}
|
||||
}
|
||||
|
||||
export interface StreamParserJinja2State {
|
||||
incomment: boolean,
|
||||
intag: string | boolean,
|
||||
operator: boolean,
|
||||
sign: boolean,
|
||||
instring: boolean | string,
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,146 @@
|
||||
import {StringStream} from "@codemirror/stream-parser";
|
||||
import {gcode} from "@/plugins/StreamParserGcode";
|
||||
|
||||
export const klipper_config = {
|
||||
token: function (stream: StringStream, state: StreamParserKlipperConfigState): string | null {
|
||||
const ch = stream.peek();
|
||||
|
||||
|
||||
/* comments */
|
||||
if (stream.match(/^\s+#/) || (
|
||||
ch === "#" && (stream.pos === 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))
|
||||
)) {
|
||||
stream.skipToEnd();
|
||||
state.pair = false;
|
||||
return "comment";
|
||||
}
|
||||
|
||||
if (state.gcode &&
|
||||
!state.klipperMacroJinja &&
|
||||
(ch === '[')
|
||||
) {
|
||||
state.gcode = false;
|
||||
state.gcodeZeroPos = null;
|
||||
}
|
||||
|
||||
if (state.gcode) {
|
||||
stream.eatSpace();
|
||||
if (state.gcodeZeroPos === null) {
|
||||
state.gcodeZeroPos = stream.pos;
|
||||
}
|
||||
if (state.klipperMacroJinja) {
|
||||
if (stream.match(/^%?}/)) {
|
||||
state.klipperMacroJinja = false;
|
||||
return null;
|
||||
}
|
||||
if (stream.eat(/.(?!%})/)) {
|
||||
return "string";
|
||||
}
|
||||
if (stream.eat(/.(?!})/)) {
|
||||
return "string";
|
||||
}
|
||||
stream.match(/^.*$/);
|
||||
return "string";
|
||||
}
|
||||
|
||||
if (stream.match(/^{%?/)) {
|
||||
state.klipperMacroJinja = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
return gcode.token(stream, state, state.gcodeZeroPos);
|
||||
}
|
||||
|
||||
if (stream.match(/^gcode:\s*/)) {
|
||||
stream.skipToEnd();
|
||||
state.gcode = true;
|
||||
return "atom";
|
||||
}
|
||||
|
||||
if (state.pair) {
|
||||
if (stream.match(/^[\^!]*[a-z_]+[0-9]*?:/i)) {
|
||||
stream.backUp(1);
|
||||
return "macroName";
|
||||
} else if (
|
||||
stream.match(/^[\^!]*(?:(?:P[A-Z]?|A[A-Z]?|EXP|GPIOCHIP|GPIO)+[0-9.]+|z_virtual_endstop)(_[0-9]+)?/i) ||
|
||||
stream.match(/^\/gpio[0-9]+/i)) {
|
||||
if (stream.eol()) {
|
||||
state.pair = false;
|
||||
}
|
||||
return "macroName";
|
||||
} else if (stream.match(/^\s*\[?(-?[0-9,.:]+)]?/)) {
|
||||
if (stream.eol()) {
|
||||
state.pair = false;
|
||||
}
|
||||
return "number";
|
||||
} else if (stream.match(/^([a-zA-Z0-9~"'.,:_/\-\s]+)/)) {
|
||||
if (stream.eol()) {
|
||||
state.pair = false;
|
||||
}
|
||||
return "string";
|
||||
} else if (stream.match(/^\s*#.*$/)) {
|
||||
stream.skipToEnd();
|
||||
state.pair = false;
|
||||
return "comment";
|
||||
}
|
||||
stream.next();
|
||||
return null;
|
||||
}
|
||||
|
||||
if (stream.match(/^[a-zA-Z0-9_]+\s?[:=]\s?/)) {
|
||||
state.pair = true;
|
||||
return "atom";
|
||||
}
|
||||
|
||||
/*if (stream.match(/^\[include.*]$/)) {
|
||||
console.log(stream, state);
|
||||
return "macroName";
|
||||
}*/
|
||||
|
||||
if (state.block) {
|
||||
if (stream.match(/^[a-z0-9-_]+/i)) {
|
||||
return "namespace"
|
||||
}
|
||||
if (stream.match(/^\s[a-z0-9-_./*\s]+/i)) {
|
||||
return "className";
|
||||
}
|
||||
stream.skipToEnd();
|
||||
state.block = false;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (stream.next() === '[') {
|
||||
state.block = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (stream.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/))
|
||||
return "string";
|
||||
|
||||
stream.next();
|
||||
return "string";
|
||||
},
|
||||
startState: function (): StreamParserKlipperConfigState {
|
||||
return {
|
||||
block: false,
|
||||
pair: false,
|
||||
gcode: false,
|
||||
klipperMacro: false,
|
||||
gcodeZeroPos: null,
|
||||
klipperMacroJinja: false,
|
||||
};
|
||||
},
|
||||
languageData: {
|
||||
commentTokens: {line: "#"}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
interface StreamParserKlipperConfigState {
|
||||
block: boolean,
|
||||
pair: boolean,
|
||||
gcode: boolean,
|
||||
gcodeZeroPos: number | null,
|
||||
klipperMacro: boolean,
|
||||
klipperMacroJinja: boolean
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import {StringStream} from "@codemirror/stream-parser";
|
||||
|
||||
const cons = ['true', 'false', 'on', 'off', 'yes', 'no'];
|
||||
const keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i');
|
||||
|
||||
export const yaml = {
|
||||
token: function(stream: StringStream, state: StreamParserYamlState): string | null {
|
||||
const ch = stream.peek();
|
||||
const esc = state.escaped;
|
||||
|
||||
state.escaped = false;
|
||||
/* comments */
|
||||
if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
|
||||
if (stream.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/))
|
||||
return "string";
|
||||
|
||||
if (state.literal && stream.indentation() > state.keyCol) {
|
||||
stream.skipToEnd(); return "string";
|
||||
} else if (state.literal) { state.literal = false; }
|
||||
if (stream.sol()) {
|
||||
state.keyCol = 0;
|
||||
state.pair = false;
|
||||
state.pairStart = false;
|
||||
/* document start */
|
||||
if(stream.match('---')) { return "def"; }
|
||||
/* document end */
|
||||
if (stream.match('...')) { return "def"; }
|
||||
/* array list item */
|
||||
if (stream.match(/^\s*-\s+/)) { return 'meta'; }
|
||||
}
|
||||
|
||||
if (stream.match(/^\[[a-zA-Z]\s/)) {
|
||||
window.console.log("keys", stream)
|
||||
return 'number'
|
||||
}
|
||||
|
||||
/* inline pairs/lists */
|
||||
if (stream.match(/^(\{|\}|\[|\])/)) {
|
||||
if (ch == '{')
|
||||
state.inlinePairs++;
|
||||
else if (ch == '}')
|
||||
state.inlinePairs--;
|
||||
else if (ch == '[')
|
||||
state.inlineList++;
|
||||
else
|
||||
state.inlineList--;
|
||||
return 'meta';
|
||||
}
|
||||
|
||||
/* list separator */
|
||||
if (state.inlineList > 0 && !esc && ch == ',') {
|
||||
stream.next();
|
||||
return 'meta';
|
||||
}
|
||||
/* pairs separator */
|
||||
if (state.inlinePairs > 0 && !esc && ch == ',') {
|
||||
state.keyCol = 0;
|
||||
state.pair = false;
|
||||
state.pairStart = false;
|
||||
stream.next();
|
||||
return 'meta';
|
||||
}
|
||||
|
||||
/* start of value of a pair */
|
||||
if (state.pairStart) {
|
||||
/* block literals */
|
||||
if (stream.match(/^\s*(\||>)\s*/)) { state.literal = true; return 'meta'; }
|
||||
/* references */
|
||||
if (stream.match(/^\s*(&|\*)[a-z0-9._-]+\b/i)) { return 'variable'; }
|
||||
/* numbers */
|
||||
if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9.,]+\s?$/)) { return 'number'; }
|
||||
if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9.,]+\s?(?=(,|}))/)) { return 'number'; }
|
||||
/* keywords */
|
||||
if (stream.match(keywordRegex)) { return 'keyword'; }
|
||||
}
|
||||
|
||||
/* pairs (associative arrays) -> key */
|
||||
if (!state.pair && stream.match(/^\s*(?:[,[\]{}&*!|>'"%@`][^\s'":]|[^,[\]{}#&*!|>'"%@`])[^#]*?(?=\s*:($|\s))/)) {
|
||||
state.pair = true;
|
||||
state.keyCol = stream.indentation();
|
||||
return "atom";
|
||||
}
|
||||
if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; }
|
||||
|
||||
/* nothing found, continue */
|
||||
state.pairStart = false;
|
||||
state.escaped = (ch == '\\');
|
||||
stream.next();
|
||||
return null;
|
||||
},
|
||||
startState: function(): StreamParserYamlState {
|
||||
return {
|
||||
pair: false,
|
||||
pairStart: false,
|
||||
keyCol: 0,
|
||||
inlinePairs: 0,
|
||||
inlineList: 0,
|
||||
literal: false,
|
||||
escaped: false
|
||||
};
|
||||
},
|
||||
languageData: {
|
||||
commentTokens: {line: "#"}
|
||||
}
|
||||
};
|
||||
|
||||
interface StreamParserYamlState {
|
||||
pair: boolean
|
||||
pairStart: boolean
|
||||
keyCol: number
|
||||
inlinePairs: number
|
||||
inlineList: number
|
||||
literal: boolean
|
||||
escaped: boolean
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import {EditorView} from "@codemirror/view"
|
||||
import {Extension} from "@codemirror/state"
|
||||
import {HighlightStyle, tags as t} from "@codemirror/highlight"
|
||||
|
||||
const ui = {
|
||||
background: '#1e1e1e',
|
||||
foreground: '#d4d4d4',
|
||||
}
|
||||
|
||||
export const mainsailEditor = EditorView.theme({
|
||||
"&": {
|
||||
color: '#d4d4d4',
|
||||
backgroundColor: ui.background
|
||||
},
|
||||
|
||||
".cm-activeLine.cm-line": {
|
||||
caretColor: "#d4d4d4 !important"
|
||||
},
|
||||
|
||||
".cm-gutters": {
|
||||
backgroundColor: ui.background,
|
||||
color: '#858585',
|
||||
border: "none"
|
||||
},
|
||||
|
||||
".cm-activeLine": {
|
||||
background: 'rgba(43,47,61,0.5)'
|
||||
},
|
||||
|
||||
".cm-activeLineGutter": {
|
||||
color: '#c6c6c6',
|
||||
backgroundColor: 'rgba(33, 36, 49, 0.5)'
|
||||
},
|
||||
|
||||
".cm-selectionMatch": {
|
||||
backgroundColor: '#add6ff26',
|
||||
},
|
||||
|
||||
}, {dark: true})
|
||||
|
||||
export const mainsailHighlightStyle = HighlightStyle.define([
|
||||
{tag: t.number,
|
||||
color: '#b5cea8'},
|
||||
{tag: [t.meta],
|
||||
color: '#d4d4d4'},
|
||||
{tag: [t.comment],
|
||||
color: '#6a9955'},
|
||||
{tag: t.atom,
|
||||
color: '#9cdcfe' },
|
||||
{tag: t.string,
|
||||
color: '#4ec9b0' },
|
||||
{tag: t.namespace,
|
||||
color: '#569cd6', fontWeight: 'bold' },
|
||||
{tag: t.className,
|
||||
color: '#c586c0' },
|
||||
{tag: t.name,
|
||||
color: '#e40', fontWeight: 'bold' },
|
||||
{tag: t.propertyName,
|
||||
color: '#e56735' },
|
||||
])
|
||||
|
||||
/// Extension to enable the Mox theme (both the editor theme and
|
||||
/// the highlight style).
|
||||
export const mainsailTheme: Extension = [mainsailEditor, mainsailHighlightStyle]
|
||||
@@ -1,50 +0,0 @@
|
||||
export function findDirectory (folder, dirArray) {
|
||||
if (folder !== undefined && dirArray.length) {
|
||||
if (folder.childrens) folder = folder.childrens;
|
||||
|
||||
let parent = folder.find(element => (element.isDirectory && element.filename === dirArray[0]));
|
||||
if (parent) {
|
||||
dirArray.shift();
|
||||
if (dirArray.length) {
|
||||
return findDirectory(parent, dirArray);
|
||||
} else return parent.childrens;
|
||||
} else return folder;
|
||||
}
|
||||
}
|
||||
|
||||
export function caseInsensitiveNameSort(a, b) {
|
||||
let nameA = a.name.toUpperCase();
|
||||
let nameB = b.name.toUpperCase();
|
||||
|
||||
if (nameA < nameB) return -1;
|
||||
if (nameA > nameB) return 1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function colorConsoleMessage(item) {
|
||||
if (item.message.startsWith('!! ')) return "red--text"
|
||||
if ('type' in item && item.type === 'command') return "blue--text"
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
export function formatConsoleMessage(message) {
|
||||
message = message.replaceAll('!! ', '')
|
||||
message = message.replaceAll('// ', '')
|
||||
message = message.replace('\n// ', '<br>')
|
||||
message = message.replace(/(?:\r\n|\r|\n)/g, '<br>')
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
export function convertName(name) {
|
||||
let output = ""
|
||||
name = name.replaceAll("_", " ")
|
||||
name.split(" ").forEach(split => {
|
||||
output += " "+split.charAt(0).toUpperCase() + split.slice(1)
|
||||
})
|
||||
output = output.slice(1)
|
||||
|
||||
return output;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { ServerStateEvent } from "@/store/server/types"
|
||||
import {FileStateFile} from "@/store/files/types";
|
||||
|
||||
export const findDirectory = (folder: FileStateFile[], dirArray: string[]): FileStateFile[] | null => {
|
||||
if (folder !== undefined && folder !== null && dirArray.length) {
|
||||
|
||||
const parent = folder?.find((element: FileStateFile) => (element.isDirectory && element.filename === dirArray[0]));
|
||||
if (parent) {
|
||||
dirArray.shift();
|
||||
|
||||
if (parent.childrens && dirArray.length) return findDirectory(parent.childrens, dirArray)
|
||||
else if(parent.childrens) return parent.childrens
|
||||
}
|
||||
|
||||
return folder
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export const caseInsensitiveSort = (values: any[], orderType: string): any[] => {
|
||||
return values.sort((a, b) => {
|
||||
const stringA = a[orderType].toLowerCase()
|
||||
const stringB = b[orderType].toLowerCase()
|
||||
|
||||
if (stringA < stringB) return -1
|
||||
if (stringA > stringB) return 1
|
||||
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
export const camelize = (str: string): string => {
|
||||
return str.replaceAll('_', ' ').replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => {
|
||||
return index === 0 ? word.toLowerCase() : word.toUpperCase();
|
||||
}).replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
export function formatConsoleMessage(message: string): string {
|
||||
message = message.replaceAll('!! ', '')
|
||||
message = message.replaceAll('// ', '')
|
||||
message = message.replace('\n// ', '<br>')
|
||||
message = message.replace(/\r\n|\r|\n/g, '<br>')
|
||||
//message = message.replaceAll('<br />', '<br>')
|
||||
//return message.split('<br>');
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
export const convertName = (name: string): string => {
|
||||
let output = ""
|
||||
name = name.replaceAll("_", " ")
|
||||
name.split(" ").forEach(split => {
|
||||
output += " "+split.charAt(0).toUpperCase() + split.slice(1)
|
||||
})
|
||||
output = output.slice(1)
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
export const formatFilesize = (fileSizeInBytes: number): string => {
|
||||
let i = -1
|
||||
const byteUnits = [' kB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB']
|
||||
do {
|
||||
fileSizeInBytes = fileSizeInBytes / 1024
|
||||
i++
|
||||
} while (fileSizeInBytes > 1024)
|
||||
|
||||
return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i]
|
||||
}
|
||||
|
||||
export const formatDate = (date: number): string => {
|
||||
const tmp2 = new Date(date)
|
||||
|
||||
return tmp2.toLocaleString().replace(',', '')
|
||||
}
|
||||
|
||||
export const formatFrequency = (frequency: number): string => {
|
||||
let i = -1
|
||||
const units = [' kHz', ' MHz', ' GHz']
|
||||
do {
|
||||
frequency = frequency / 1000
|
||||
i++
|
||||
} while (frequency > 1000)
|
||||
|
||||
return Math.max(frequency, 0.1).toFixed() + units[i]
|
||||
}
|
||||
|
||||
export const sortFiles = (items: FileStateFile[] | null, sortBy: string[], sortDesc: boolean[]): FileStateFile[] => {
|
||||
const sortBySingle = sortBy.length ? sortBy[0] : 'filename';
|
||||
const sortDescSingle = sortDesc[0];
|
||||
|
||||
if (items !== null) {
|
||||
// Sort by index
|
||||
items.sort(function(a: any, b: any) {
|
||||
if (a[sortBySingle] === b[sortBySingle]) return 0
|
||||
if (a[sortBySingle] === null || a[sortBySingle] === undefined) return -1
|
||||
if (b[sortBySingle] === null || b[sortBySingle] === undefined) return 1
|
||||
|
||||
if (a[sortBySingle].constructor === String && b[sortBySingle].constructor === String) {
|
||||
return a[sortBySingle].localeCompare(b[sortBySingle], undefined, { sensivity: 'base' })
|
||||
}
|
||||
|
||||
if (a[sortBySingle] instanceof Array && b[sortBySingle] instanceof Array) {
|
||||
const reducedA = a[sortBySingle].length ? a.filament.reduce((a: any, b: any) => a + b) : 0
|
||||
const reducedB = b[sortBySingle].length ? b.filament.reduce((a: any, b: any) => a + b) : 0
|
||||
return reducedA - reducedB
|
||||
}
|
||||
|
||||
return a[sortBySingle] - b[sortBySingle]
|
||||
})
|
||||
|
||||
// Deal with descending order
|
||||
if (sortDescSingle) items.reverse()
|
||||
|
||||
// Then make sure directories come first
|
||||
items.sort((a: any, b: any) => (a.isDirectory === b.isDirectory) ? 0 : (a.isDirectory ? -1 : 1))
|
||||
}
|
||||
|
||||
return items ?? []
|
||||
}
|
||||
|
||||
|
||||
export function strLongestEqual(a: string, b: string): string {
|
||||
const l = Math.min(a?.length ?? Number.MAX_VALUE, b?.length ?? Number.MAX_VALUE);
|
||||
let i = 0;
|
||||
while (i < l && (a.charCodeAt(i) ^ b.charCodeAt(i)) === 0) {
|
||||
i += 1;
|
||||
}
|
||||
return a.substr(0, i);
|
||||
}
|
||||
|
||||
export function reverseString(str: string): string {
|
||||
return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
|
||||
}
|
||||
|
||||
export function formatTime(date: Date): string {
|
||||
let hours: string | number = date.getHours()
|
||||
if (hours < 10) hours = "0"+hours.toString()
|
||||
let minutes: string | number = date.getMinutes()
|
||||
if (minutes < 10) minutes = "0"+minutes.toString()
|
||||
let seconds: string | number = date.getSeconds()
|
||||
if (seconds < 10) seconds = "0"+seconds.toString()
|
||||
|
||||
|
||||
return hours+":"+minutes+":"+seconds
|
||||
}
|
||||
@@ -4,7 +4,7 @@ Vue.use(VueI18n)
|
||||
|
||||
function loadLocaleMessages() {
|
||||
const locales = require.context('../locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
|
||||
const messages = {}
|
||||
const messages: any = {}
|
||||
|
||||
locales.keys().forEach(key => {
|
||||
const matched = key.match(/([A-Za-z0-9-_]+)\./i)
|
||||
@@ -1,147 +0,0 @@
|
||||
import { loadWASM } from 'onigasm' // peer dependency of 'monaco-textmate'
|
||||
import { Registry } from 'monaco-textmate' // peer dependency
|
||||
import { wireTmGrammars } from 'monaco-editor-textmate';
|
||||
import * as monaco from 'monaco-editor';
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
import * as monacoNamespace from 'monaco-editor';
|
||||
|
||||
export const LANGUAGE_MAP = {
|
||||
cfg: 'klipper-config',
|
||||
conf: 'klipper-config',
|
||||
sh: 'shell',
|
||||
log: 'plaintext',
|
||||
js: 'javascript'
|
||||
};
|
||||
|
||||
let onigasmLoaded = false;
|
||||
|
||||
class MultiRegistry {
|
||||
registries = new Map();
|
||||
|
||||
async loadGrammar(id) {
|
||||
if (!this.registries.has(id)) {
|
||||
this.registries.set(id,
|
||||
new Registry({
|
||||
getGrammarDefinition: async () => {
|
||||
return Promise.resolve({
|
||||
format: 'json',
|
||||
content: await (await fetch(`/grammars/${id.split('.').pop()}.tmLanguage.json`)).text()
|
||||
})
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
return await this.registries.get(id).loadGrammar(id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {monacoNamespace} monaco
|
||||
*/
|
||||
export async function liftOff(monaco) {
|
||||
if (!onigasmLoaded) {
|
||||
await loadWASM(`/libs/onigasm.wasm`) // See https://www.npmjs.com/package/onigasm#light-it-up
|
||||
onigasmLoaded = true;
|
||||
}
|
||||
const registry = new MultiRegistry();
|
||||
|
||||
const grammars = new Map();
|
||||
grammars.set('klipper-config', 'source.klipper-config');
|
||||
grammars.set('gcode', 'source.gcode');
|
||||
|
||||
monaco.languages.register({ id: 'klipper-config' });
|
||||
monaco.languages.register({ id: 'gcode' });
|
||||
|
||||
monaco.languages.registerCompletionItemProvider('klipper-config', {
|
||||
provideCompletionItems: () => ({suggestions: []})
|
||||
});
|
||||
monaco.languages.registerCompletionItemProvider('gcode', {
|
||||
provideCompletionItems: () => ({suggestions: []})
|
||||
});
|
||||
|
||||
// monaco's built-in themes aren't powereful enough to handle TM tokens
|
||||
// https://github.com/Nishkalkashyap/monaco-vscode-textmate-theme-converter#monaco-vscode-textmate-theme-converter
|
||||
const theme = await (await fetch('/editor.theme.json')).json();
|
||||
monaco.editor.defineTheme('dark-converted', theme);
|
||||
monaco.editor.setTheme('dark-converted');
|
||||
|
||||
/*var editor = monaco.editor.create(document.getElementById('container'), {
|
||||
value: [
|
||||
'html, body {',
|
||||
' margin: 0;',
|
||||
'}'
|
||||
].join('\n'),
|
||||
language: 'css', // this won't work out of the box, see below for more info,
|
||||
theme: 'vs-code-theme-converted' // very important, see comment above
|
||||
})*/
|
||||
|
||||
await wireTmGrammars(monaco, registry, grammars)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {monaco} monaco
|
||||
*/
|
||||
export function inject(monaco) {
|
||||
// Register a new language
|
||||
monaco.languages.register({id: 'gcode', extensions: ['gcode']});
|
||||
|
||||
// Register a tokens provider for the language
|
||||
monaco.languages.setMonarchTokensProvider('gcode', {
|
||||
tokenizer: {
|
||||
root: [
|
||||
[/;.*/, "comment"],
|
||||
[/[GMgm][\d]+/, 'gm-commands'],
|
||||
[/[XYZIJxyzij]-?([\d]*\.[\d]+|[\d]+)/, 'movement'],
|
||||
[/[FEfe]-?([\d]*\.[\d]+|[\d]+)/, 'speeds'],
|
||||
[/^[A-Z_]+/, 'klipper-macros'],
|
||||
[/([A-Z_]+)=/, 'klipper-macros-parameter-name'],
|
||||
],
|
||||
}
|
||||
});
|
||||
|
||||
monaco.editor.defineTheme('gcode-dark', {
|
||||
base: 'vs-dark',
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: 'gm-commands', foreground: '#005ca2', fontStyle: 'bold' },
|
||||
{ token: 'movement', foreground: '#ff5c5c' },
|
||||
{ token: 'speeds', foreground: '#ffa941' },
|
||||
{ token: 'klipper-macros', foreground: '#85fcff' },
|
||||
{ token: 'klipper-macros-parameter-name', foreground: '#00fbff' },
|
||||
]
|
||||
});
|
||||
|
||||
// Register a completion item provider for the new language
|
||||
monaco.languages.registerCompletionItemProvider('gcode', {
|
||||
provideCompletionItems: () => {
|
||||
/*var suggestions = [{
|
||||
label: 'simpleText',
|
||||
kind: monaco.languages.CompletionItemKind.Text,
|
||||
insertText: 'simpleText'
|
||||
}, {
|
||||
label: 'testing',
|
||||
kind: monaco.languages.CompletionItemKind.Keyword,
|
||||
insertText: 'testing(${1:condition})',
|
||||
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
|
||||
}, {
|
||||
label: 'ifelse',
|
||||
kind: monaco.languages.CompletionItemKind.Snippet,
|
||||
insertText: [
|
||||
'if (${1:condition}) {',
|
||||
'\t$0',
|
||||
'} else {',
|
||||
'\t',
|
||||
'}'
|
||||
].join('\n'),
|
||||
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
|
||||
documentation: 'If-Else Statement'
|
||||
}];*/
|
||||
return {suggestions: []};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
liftOff(monaco);
|
||||
@@ -1,6 +1,6 @@
|
||||
import VueRouter from 'vue-router'
|
||||
import Vue from "vue";
|
||||
import routes from "../routes";
|
||||
import Vue from "vue"
|
||||
import routes from "@/routes"
|
||||
|
||||
Vue.use(VueRouter);
|
||||
const router = new VueRouter({mode: 'history', routes});
|
||||
@@ -1,35 +0,0 @@
|
||||
import '@mdi/font/css/materialdesignicons.css'
|
||||
import Vue from 'vue';
|
||||
import Vuetify, { VSnackbar, VBtn, VIcon } from 'vuetify/lib';
|
||||
|
||||
//vue-toast-notification
|
||||
import VueToast from 'vue-toast-notification';
|
||||
import 'vue-toast-notification/dist/theme-sugar.css';
|
||||
|
||||
Vue.use(VueToast, {
|
||||
duration: 3000,
|
||||
})
|
||||
|
||||
Vue.use(Vuetify,{
|
||||
options: {
|
||||
customProperties: true
|
||||
},
|
||||
components: {
|
||||
VSnackbar,
|
||||
VBtn,
|
||||
VIcon,
|
||||
}
|
||||
})
|
||||
|
||||
export default new Vuetify({
|
||||
theme: {
|
||||
themes: {
|
||||
dark: {
|
||||
|
||||
}
|
||||
}
|
||||
},
|
||||
icons: {
|
||||
iconfont: 'mdi',
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import '@mdi/font/css/materialdesignicons.css'
|
||||
import Vue from 'vue'
|
||||
import Vuetify from 'vuetify/lib'
|
||||
|
||||
|
||||
Vue.use(Vuetify)
|
||||
|
||||
export default new Vuetify({
|
||||
theme: { dark: true },
|
||||
icons: {
|
||||
iconfont: 'mdi',
|
||||
},
|
||||
breakpoint: {
|
||||
mobileBreakpoint: 768
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,170 @@
|
||||
import {Store} from "vuex"
|
||||
import _Vue from "vue";
|
||||
import {RootState} from "@/store/types";
|
||||
|
||||
export class WebSocketClient {
|
||||
url = ''
|
||||
instance: WebSocket | null = null
|
||||
maxReconnects = 5
|
||||
reconnectInterval = 1000
|
||||
reconnects = 0
|
||||
keepAliveTimeout = 1000
|
||||
timerId: number | null = null
|
||||
store: Store<RootState> | null = null
|
||||
waits: Wait[] = []
|
||||
|
||||
constructor (options: WebSocketPluginOptions) {
|
||||
this.url = options.url
|
||||
this.maxReconnects = options.maxReconnects || 5
|
||||
this.reconnectInterval = options.reconnectInterval || 1000
|
||||
this.store = options.store
|
||||
}
|
||||
|
||||
setUrl(url: string): void {
|
||||
this.url = url
|
||||
}
|
||||
|
||||
passToStore (eventName: string, event: any): void {
|
||||
if (!eventName.startsWith('socket/')) { return }
|
||||
|
||||
this.store?.dispatch(eventName, event)
|
||||
}
|
||||
|
||||
connect(): void {
|
||||
this.store?.dispatch("socket/setData", { isConnecting: true })
|
||||
this.instance = new WebSocket(this.url)
|
||||
|
||||
this.instance.onopen = () => {
|
||||
this.reconnects = 0
|
||||
this.store?.dispatch('socket/onOpen', event)
|
||||
}
|
||||
|
||||
this.instance.onclose = (e) => {
|
||||
if (!e.wasClean && this.reconnects < this.maxReconnects) {
|
||||
this.reconnects++
|
||||
setTimeout(() => {
|
||||
this.connect()
|
||||
}, this.reconnectInterval)
|
||||
} else this.store?.dispatch('socket/onClose', e)
|
||||
}
|
||||
|
||||
this.instance.onerror = () => {
|
||||
if (this.instance) this.instance.close()
|
||||
}
|
||||
|
||||
this.instance.onmessage = (msg) => {
|
||||
const data = JSON.parse(msg.data)
|
||||
if (this.store) {
|
||||
const wait = this.getWaitById(data.id)
|
||||
if (wait && wait.action !== ""){
|
||||
if (data.error && data.error.message) {
|
||||
window.console.error("Response Error: "+wait.action+" > "+data.error.message)
|
||||
if (wait.params) window.console.log(wait.params)
|
||||
|
||||
/*this.store?.dispatch(wait.action,
|
||||
Object.assign(wait.actionPreload || {}, {
|
||||
error: data.error,
|
||||
requestParams: wait.params
|
||||
})
|
||||
)*/
|
||||
} else if (wait.action) {
|
||||
let result = data.result
|
||||
if (result === "ok") result = { result: result }
|
||||
if (typeof(result) === "string") result = { result: result }
|
||||
|
||||
const preload = {}
|
||||
if (wait.actionPayload) Object.assign(preload, wait.actionPayload)
|
||||
Object.assign(preload, { requestParams: wait.params })
|
||||
Object.assign(preload, result)
|
||||
this.store?.dispatch(wait.action, preload)
|
||||
}
|
||||
} else this.store?.dispatch('socket/onMessage', data)
|
||||
|
||||
if (wait) this.removeWaitById(wait.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close():void {
|
||||
if (this.instance) this.instance.close()
|
||||
}
|
||||
|
||||
getWaitById(id: number): Wait | null {
|
||||
return this.waits.find((wait: Wait) => wait.id === id) ?? null
|
||||
}
|
||||
|
||||
removeWaitById(id: number): void {
|
||||
const index = this.waits.findIndex((wait: Wait) => wait.id === id)
|
||||
if (index) {
|
||||
const wait = this.waits[index]
|
||||
if (wait.loading && this.store) {
|
||||
this.store.dispatch("socket/removeLoading", { name: wait.loading })
|
||||
}
|
||||
this.waits.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
emit(method: string, params: Params, options: emitOptions = {}):void {
|
||||
if (this.instance?.readyState === WebSocket.OPEN) {
|
||||
const id = Math.floor(Math.random() * 10000) + 1
|
||||
this.waits.push({
|
||||
id: id,
|
||||
params: params,
|
||||
action: options.action ?? null,
|
||||
actionPayload: options.actionPayload ?? {},
|
||||
loading: options.loading ?? null,
|
||||
})
|
||||
|
||||
if (options.loading && this.store) {
|
||||
this.store.dispatch("socket/addLoading", { name: options.loading })
|
||||
}
|
||||
|
||||
const msg = JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
method: method,
|
||||
params: params,
|
||||
id: id
|
||||
})
|
||||
|
||||
this.instance.send(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function WebSocketPlugin<WebSocketPlugin>(Vue: typeof _Vue, options: WebSocketPluginOptions): void {
|
||||
const socket = new WebSocketClient(options)
|
||||
Vue.prototype.$socket = socket
|
||||
Vue.$socket = socket
|
||||
}
|
||||
|
||||
export interface WebSocketPluginOptions {
|
||||
url: string
|
||||
maxReconnects?: number
|
||||
reconnectInterval?: number
|
||||
store: Store<RootState>
|
||||
}
|
||||
|
||||
export interface WebSocketClient {
|
||||
connect(): void
|
||||
close(): void
|
||||
emit(method: string, params: Params, emitOptions: emitOptions):void
|
||||
}
|
||||
|
||||
export interface Wait {
|
||||
id: number
|
||||
params: any
|
||||
action?: string | null
|
||||
actionPayload?: any
|
||||
loading?: string | null
|
||||
}
|
||||
|
||||
interface Params {
|
||||
data?: any
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
interface emitOptions {
|
||||
action?: string | null
|
||||
actionPayload?: Params
|
||||
loading?: string | null
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
export default class WebSocketClient {
|
||||
|
||||
constructor (url, options) {
|
||||
this.instance = null
|
||||
this.url = url
|
||||
this.reconnects = 0
|
||||
this.maxReconnects = options.maxReconnects || 5
|
||||
this.reconnectInterval = options.reconnectInterval || 1000
|
||||
this.store = options.store
|
||||
this.wsData = []
|
||||
this.timerId = 0
|
||||
this.keepAliveTimeout = 1000
|
||||
|
||||
this.onOpen = null
|
||||
this.onMessage = null
|
||||
this.onClose = null
|
||||
this.onError = null
|
||||
this.blacklistMessages = [
|
||||
"Metadata not available for",
|
||||
"Klippy Request Timed Out",
|
||||
"Klippy Host not connected",
|
||||
]
|
||||
this.blacklistFunctions = [
|
||||
"getPowerDevices",
|
||||
]
|
||||
}
|
||||
|
||||
setUrl(url) {
|
||||
this.url = url
|
||||
}
|
||||
|
||||
createMessage (method, params, id) {
|
||||
let msg = {
|
||||
jsonrpc: '2.0', method: method, params: params, id: id
|
||||
};
|
||||
return JSON.stringify(msg)
|
||||
}
|
||||
|
||||
passToStore (eventName, event) {
|
||||
if (!eventName.startsWith('socket/')) { return }
|
||||
let method = 'dispatch'
|
||||
let target = eventName
|
||||
let msg = event
|
||||
if (event && event.data) {
|
||||
msg = JSON.parse(event.data)
|
||||
}
|
||||
this.store[method](target, msg);
|
||||
}
|
||||
|
||||
connect () {
|
||||
this.store.dispatch("socket/setData", { isConnecting: true })
|
||||
this.instance = new WebSocket(this.url)
|
||||
|
||||
this.instance.onopen = () => {
|
||||
this.reconnects = 0
|
||||
if (this.store) this.passToStore('socket/onOpen', event)
|
||||
}
|
||||
|
||||
this.instance.onclose = (e) => {
|
||||
if (this.instance) this.instance.close()
|
||||
this.passToStore('socket/onClose', e)
|
||||
|
||||
if (!e.wasClean && this.reconnects < this.maxReconnects) {
|
||||
this.reconnects++
|
||||
setTimeout(() => {
|
||||
this.connect()
|
||||
}, this.reconnectInterval)
|
||||
} else {
|
||||
this.store.dispatch("socket/setData", {
|
||||
isConnecting: false,
|
||||
connectingFailed: true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
this.instance.onerror = () => {
|
||||
if (this.instance) this.instance.close()
|
||||
}
|
||||
|
||||
this.instance.onmessage = (msg) => {
|
||||
let data = JSON.parse(msg.data)
|
||||
if (this.store) {
|
||||
const wsDataIndex = this.wsData.findIndex(item => item.id === data.id)
|
||||
if (wsDataIndex !== -1 && this.wsData[wsDataIndex].action !== ""){
|
||||
let tmpWsData = this.wsData[wsDataIndex]
|
||||
|
||||
if (data.error && data.error.message) {
|
||||
if (
|
||||
!this.blacklistMessages.find(element => data.error.message.startsWith(element)) &&
|
||||
!this.blacklistFunctions.find(element => tmpWsData.action.startsWith(element))
|
||||
) {
|
||||
window.console.error("Response Error: "+tmpWsData.action+" > "+data.error.message);
|
||||
|
||||
this.store.dispatch(tmpWsData.action,
|
||||
Object.assign(tmpWsData.actionPreload || {}, {
|
||||
error: data.error,
|
||||
requestParams: tmpWsData.params
|
||||
})
|
||||
)
|
||||
}
|
||||
} else {
|
||||
let result = data.result
|
||||
if (result === "ok") result = { result: result }
|
||||
if (typeof(result) === "string") result = { result: result }
|
||||
|
||||
let preload = {}
|
||||
if (tmpWsData.actionPreload) Object.assign(preload, tmpWsData.actionPreload)
|
||||
Object.assign(preload, { requestParams: tmpWsData.params })
|
||||
Object.assign(preload, result)
|
||||
this.store.dispatch(tmpWsData.action, preload)
|
||||
}
|
||||
} else this.passToStore('socket/onMessage', data)
|
||||
|
||||
if (wsDataIndex !== -1) this.wsData.splice(wsDataIndex, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.instance) this.instance.close()
|
||||
}
|
||||
|
||||
sendObj (method, params, action = '', actionPreload = null) {
|
||||
if (this.instance.readyState === WebSocket.OPEN) {
|
||||
let id = Math.floor(Math.random() * 10000) + 1
|
||||
this.wsData.push({
|
||||
id: id,
|
||||
action: action,
|
||||
params: params,
|
||||
actionPreload: actionPreload,
|
||||
})
|
||||
this.instance.send(this.createMessage(method, params, id))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user