Open source

This commit is contained in:
Kaan Soral
2023-10-15 13:06:58 +03:00
parent 256ce800e7
commit 553b121f17
2633 changed files with 769945 additions and 454 deletions
BIN
View File
Binary file not shown.
+81
View File
@@ -0,0 +1,81 @@
function drop_to_html(def,mult,color)
{
var html="";
if(def[1]=="open")
{
D.drops[def[2]].forEach(function(d){
html+=drop_to_html(d,mult*def[0],color);
});
return html;
}
html+="<div style='display: inline-block; margin-right: 10px; border: 2px solid "+color+"; padding: 4px 8px 4px 8px'>";
var skin="",prob=parseInt(1/(def[0]*mult));
if(G.items[def[1]]) skin=G.items[def[1]].skin;
else if(def[1]=="shells") skin="shells";
else if(def[1]=="gold") skin="gold";
html+=item_container({skin:skin});
html+="<div style='vertical-align: middle; font-size: 24px'>1 / "+to_pretty_num(prob)+"</div>";
html+="</div>";
return html;
}
function item_analysis()
{
var html="";
["weapon","shield","offhand","helmet"].forEach(function(type){
var items=[];
for(var id in G.items)
{
if(G.items[id].type==type)
items.push(id);
}
html+="<div class='gamebutton'>"+type+"</div>";
items.forEach(function(id){
html+=item_container({skin:G.items[id].skin},{name:id});
})
});
show_modal(html);
}
function visualize()
{
if(!window.D) return pull_D();
var html="<div style='text-align: center'>";
object_sort(G.maps).forEach(function(io){
var mname=io[0],map=G.maps[mname],pc={},mc={},m={},first=false,mx=false;
if(!(D.drops.maps[mname] || map.monsters && map.monsters.length) || G.maps[mname].ignore) return;
html+="<div class='gamebutton gamebutton-large' style='display:block; margin-bottom: 4px'>"+map.name+"</div>";
for(var i=0;i<(D.drops.maps[mname]||[]).length;i++)
{
html+=drop_to_html(D.drops.maps[mname][i],1,"#858B8E"); mx=true;
}
if(mx) html+="<div style='display: inline-block; margin-left: -10px;'></div>";
html+="<div style='margin-bottom: 2px'></div>";
for(var i=0;i<(map.monsters||[]).length;i++)
{
var m_def=map.monsters[i],monster=G.monsters[m_def.type];
pc[m_def.type]=(pc[m_def.type]||0)+1;
mc[m_def.type]=(mc[m_def.type]||0)+m_def.count;
}
for(var i=0;i<(map.monsters||[]).length;i++)
{
var m_def=map.monsters[i],monster=G.monsters[m_def.type],drop=false;
if(m[m_def.type]) continue;
if(!monster) alert("no "+JSON.stringify(m_def));
html+="<div class='gamebutton' style='margin-bottom: 6px; margin-top: 4px; border-color: #6C0001'><div xstyle='border: 2px solid gray; padding: 2px; display: inline-block'>"+sprite(monster.skin)+"</div>"+monster.name+" ["+mc[m_def.type]+"]</div>";
html+="<div></div>";
for(var j=0;j<(D.drops.monsters[m_def.type]||[]).length;j++)
{
html+=drop_to_html(D.drops.monsters[m_def.type][j],1,"#858B8E");
drop=true;
}
if(!drop) html+="<div style='color: orange; font-size: 24px'>No Drop</div>";
else html+="<div style='display: inline-block; margin-left: -10px;'></div>";
html+="<div style='margin-bottom: 6px'></div>";
m[m_def.type]=true;
}
if(!first) html+="<div style='margin-bottom: 15px'></div>"; first=true;
});
html+="</div>"
show_modal(html);
}
BIN
View File
Binary file not shown.
+338
View File
@@ -0,0 +1,338 @@
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
color: black;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
white-space: nowrap;
}
.CodeMirror-guttermarker { color: black; }
.CodeMirror-guttermarker-subtle { color: #999; }
/* CURSOR */
.CodeMirror-cursor {
border-left: 1px solid black;
border-right: none;
width: 0;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.cm-fat-cursor .CodeMirror-cursor {
width: auto;
border: 0 !important;
background: #7e7;
}
.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-animate-fat-cursor {
width: auto;
border: 0;
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
background-color: #7e7;
}
@-moz-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@-webkit-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
/* Can style cursor different in overwrite (non-insert) mode */
.CodeMirror-overwrite .CodeMirror-cursor {}
.cm-tab { display: inline-block; text-decoration: inherit; }
.CodeMirror-ruler {
border-left: 1px solid #ccc;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-strikethrough {text-decoration: line-through;}
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3 {color: #085;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-s-default .cm-error {color: #f00;}
.cm-invalidchar {color: #f00;}
.CodeMirror-composing { border-bottom: 2px solid; }
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
.CodeMirror-activeline-background {background: #e8f2ff;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -30px; margin-right: -30px;
padding-bottom: 30px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
}
.CodeMirror-sizer {
position: relative;
border-right: 30px solid transparent;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actual scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0; bottom: 0;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
min-height: 100%;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
display: inline-block;
vertical-align: top;
margin-bottom: -30px;
/* Hack to make IE7 behave */
*zoom:1;
*display:inline;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
background: none !important;
border: none !important;
}
.CodeMirror-gutter-background {
position: absolute;
top: 0; bottom: 0;
z-index: 4;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
-webkit-font-variant-ligatures: none;
font-variant-ligatures: none;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
overflow: auto;
}
.CodeMirror-widget {}
.CodeMirror-code {
outline: none;
}
/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-cursor { position: absolute; }
.CodeMirror-measure pre { position: static; }
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
div.CodeMirror-dragcursors {
visibility: visible;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
.cm-searching {
background: #ffa;
background: rgba(255, 255, 0, .4);
}
/* IE7 hack to prevent it from returning funny offsetTops on the spans */
.CodeMirror span { *vertical-align: text-bottom; }
/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after { content: ''; }
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext { background: none; }
File diff suppressed because it is too large Load Diff
+825
View File
@@ -0,0 +1,825 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("css", function(config, parserConfig) {
var inline = parserConfig.inline
if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
var indentUnit = config.indentUnit,
tokenHooks = parserConfig.tokenHooks,
documentTypes = parserConfig.documentTypes || {},
mediaTypes = parserConfig.mediaTypes || {},
mediaFeatures = parserConfig.mediaFeatures || {},
mediaValueKeywords = parserConfig.mediaValueKeywords || {},
propertyKeywords = parserConfig.propertyKeywords || {},
nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
fontProperties = parserConfig.fontProperties || {},
counterDescriptors = parserConfig.counterDescriptors || {},
colorKeywords = parserConfig.colorKeywords || {},
valueKeywords = parserConfig.valueKeywords || {},
allowNested = parserConfig.allowNested,
supportsAtComponent = parserConfig.supportsAtComponent === true;
var type, override;
function ret(style, tp) { type = tp; return style; }
// Tokenizers
function tokenBase(stream, state) {
var ch = stream.next();
if (tokenHooks[ch]) {
var result = tokenHooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == "@") {
stream.eatWhile(/[\w\\\-]/);
return ret("def", stream.current());
} else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
return ret(null, "compare");
} else if (ch == "\"" || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "#") {
stream.eatWhile(/[\w\\\-]/);
return ret("atom", "hash");
} else if (ch == "!") {
stream.match(/^\s*\w*/);
return ret("keyword", "important");
} else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (ch === "-") {
if (/[\d.]/.test(stream.peek())) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (stream.match(/^-[\w\\\-]+/)) {
stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false))
return ret("variable-2", "variable-definition");
return ret("variable-2", "variable");
} else if (stream.match(/^\w+-/)) {
return ret("meta", "meta");
}
} else if (/[,+>*\/]/.test(ch)) {
return ret(null, "select-op");
} else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
return ret("qualifier", "qualifier");
} else if (/[:;{}\[\]\(\)]/.test(ch)) {
return ret(null, ch);
} else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) ||
(ch == "d" && stream.match("omain(")) ||
(ch == "r" && stream.match("egexp("))) {
stream.backUp(1);
state.tokenize = tokenParenthesized;
return ret("property", "word");
} else if (/[\w\\\-]/.test(ch)) {
stream.eatWhile(/[\w\\\-]/);
return ret("property", "word");
} else {
return ret(null, null);
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) {
if (quote == ")") stream.backUp(1);
break;
}
escaped = !escaped && ch == "\\";
}
if (ch == quote || !escaped && quote != ")") state.tokenize = null;
return ret("string", "string");
};
}
function tokenParenthesized(stream, state) {
stream.next(); // Must be '('
if (!stream.match(/\s*[\"\')]/, false))
state.tokenize = tokenString(")");
else
state.tokenize = null;
return ret(null, "(");
}
// Context management
function Context(type, indent, prev) {
this.type = type;
this.indent = indent;
this.prev = prev;
}
function pushContext(state, stream, type, indent) {
state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
return type;
}
function popContext(state) {
if (state.context.prev)
state.context = state.context.prev;
return state.context.type;
}
function pass(type, stream, state) {
return states[state.context.type](type, stream, state);
}
function popAndPass(type, stream, state, n) {
for (var i = n || 1; i > 0; i--)
state.context = state.context.prev;
return pass(type, stream, state);
}
// Parser
function wordAsValue(stream) {
var word = stream.current().toLowerCase();
if (valueKeywords.hasOwnProperty(word))
override = "atom";
else if (colorKeywords.hasOwnProperty(word))
override = "keyword";
else
override = "variable";
}
var states = {};
states.top = function(type, stream, state) {
if (type == "{") {
return pushContext(state, stream, "block");
} else if (type == "}" && state.context.prev) {
return popContext(state);
} else if (supportsAtComponent && /@component/.test(type)) {
return pushContext(state, stream, "atComponentBlock");
} else if (/^@(-moz-)?document$/.test(type)) {
return pushContext(state, stream, "documentTypes");
} else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) {
return pushContext(state, stream, "atBlock");
} else if (/^@(font-face|counter-style)/.test(type)) {
state.stateArg = type;
return "restricted_atBlock_before";
} else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {
return "keyframes";
} else if (type && type.charAt(0) == "@") {
return pushContext(state, stream, "at");
} else if (type == "hash") {
override = "builtin";
} else if (type == "word") {
override = "tag";
} else if (type == "variable-definition") {
return "maybeprop";
} else if (type == "interpolation") {
return pushContext(state, stream, "interpolation");
} else if (type == ":") {
return "pseudo";
} else if (allowNested && type == "(") {
return pushContext(state, stream, "parens");
}
return state.context.type;
};
states.block = function(type, stream, state) {
if (type == "word") {
var word = stream.current().toLowerCase();
if (propertyKeywords.hasOwnProperty(word)) {
override = "property";
return "maybeprop";
} else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
override = "string-2";
return "maybeprop";
} else if (allowNested) {
override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
return "block";
} else {
override += " error";
return "maybeprop";
}
} else if (type == "meta") {
return "block";
} else if (!allowNested && (type == "hash" || type == "qualifier")) {
override = "error";
return "block";
} else {
return states.top(type, stream, state);
}
};
states.maybeprop = function(type, stream, state) {
if (type == ":") return pushContext(state, stream, "prop");
return pass(type, stream, state);
};
states.prop = function(type, stream, state) {
if (type == ";") return popContext(state);
if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
if (type == "}" || type == "{") return popAndPass(type, stream, state);
if (type == "(") return pushContext(state, stream, "parens");
if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
override += " error";
} else if (type == "word") {
wordAsValue(stream);
} else if (type == "interpolation") {
return pushContext(state, stream, "interpolation");
}
return "prop";
};
states.propBlock = function(type, _stream, state) {
if (type == "}") return popContext(state);
if (type == "word") { override = "property"; return "maybeprop"; }
return state.context.type;
};
states.parens = function(type, stream, state) {
if (type == "{" || type == "}") return popAndPass(type, stream, state);
if (type == ")") return popContext(state);
if (type == "(") return pushContext(state, stream, "parens");
if (type == "interpolation") return pushContext(state, stream, "interpolation");
if (type == "word") wordAsValue(stream);
return "parens";
};
states.pseudo = function(type, stream, state) {
if (type == "word") {
override = "variable-3";
return state.context.type;
}
return pass(type, stream, state);
};
states.documentTypes = function(type, stream, state) {
if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
override = "tag";
return state.context.type;
} else {
return states.atBlock(type, stream, state);
}
};
states.atBlock = function(type, stream, state) {
if (type == "(") return pushContext(state, stream, "atBlock_parens");
if (type == "}" || type == ";") return popAndPass(type, stream, state);
if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
if (type == "interpolation") return pushContext(state, stream, "interpolation");
if (type == "word") {
var word = stream.current().toLowerCase();
if (word == "only" || word == "not" || word == "and" || word == "or")
override = "keyword";
else if (mediaTypes.hasOwnProperty(word))
override = "attribute";
else if (mediaFeatures.hasOwnProperty(word))
override = "property";
else if (mediaValueKeywords.hasOwnProperty(word))
override = "keyword";
else if (propertyKeywords.hasOwnProperty(word))
override = "property";
else if (nonStandardPropertyKeywords.hasOwnProperty(word))
override = "string-2";
else if (valueKeywords.hasOwnProperty(word))
override = "atom";
else if (colorKeywords.hasOwnProperty(word))
override = "keyword";
else
override = "error";
}
return state.context.type;
};
states.atComponentBlock = function(type, stream, state) {
if (type == "}")
return popAndPass(type, stream, state);
if (type == "{")
return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
if (type == "word")
override = "error";
return state.context.type;
};
states.atBlock_parens = function(type, stream, state) {
if (type == ")") return popContext(state);
if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
return states.atBlock(type, stream, state);
};
states.restricted_atBlock_before = function(type, stream, state) {
if (type == "{")
return pushContext(state, stream, "restricted_atBlock");
if (type == "word" && state.stateArg == "@counter-style") {
override = "variable";
return "restricted_atBlock_before";
}
return pass(type, stream, state);
};
states.restricted_atBlock = function(type, stream, state) {
if (type == "}") {
state.stateArg = null;
return popContext(state);
}
if (type == "word") {
if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
(state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
override = "error";
else
override = "property";
return "maybeprop";
}
return "restricted_atBlock";
};
states.keyframes = function(type, stream, state) {
if (type == "word") { override = "variable"; return "keyframes"; }
if (type == "{") return pushContext(state, stream, "top");
return pass(type, stream, state);
};
states.at = function(type, stream, state) {
if (type == ";") return popContext(state);
if (type == "{" || type == "}") return popAndPass(type, stream, state);
if (type == "word") override = "tag";
else if (type == "hash") override = "builtin";
return "at";
};
states.interpolation = function(type, stream, state) {
if (type == "}") return popContext(state);
if (type == "{" || type == ";") return popAndPass(type, stream, state);
if (type == "word") override = "variable";
else if (type != "variable" && type != "(" && type != ")") override = "error";
return "interpolation";
};
return {
startState: function(base) {
return {tokenize: null,
state: inline ? "block" : "top",
stateArg: null,
context: new Context(inline ? "block" : "top", base || 0, null)};
},
token: function(stream, state) {
if (!state.tokenize && stream.eatSpace()) return null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style && typeof style == "object") {
type = style[1];
style = style[0];
}
override = style;
state.state = states[state.state](type, stream, state);
return override;
},
indent: function(state, textAfter) {
var cx = state.context, ch = textAfter && textAfter.charAt(0);
var indent = cx.indent;
if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
if (cx.prev) {
if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
// Resume indentation from parent context.
cx = cx.prev;
indent = cx.indent;
} else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
// Dedent relative to current context.
indent = Math.max(0, cx.indent - indentUnit);
cx = cx.prev;
}
}
return indent;
},
electricChars: "}",
blockCommentStart: "/*",
blockCommentEnd: "*/",
fold: "brace"
};
});
function keySet(array) {
var keys = {};
for (var i = 0; i < array.length; ++i) {
keys[array[i]] = true;
}
return keys;
}
var documentTypes_ = [
"domain", "regexp", "url", "url-prefix"
], documentTypes = keySet(documentTypes_);
var mediaTypes_ = [
"all", "aural", "braille", "handheld", "print", "projection", "screen",
"tty", "tv", "embossed"
], mediaTypes = keySet(mediaTypes_);
var mediaFeatures_ = [
"width", "min-width", "max-width", "height", "min-height", "max-height",
"device-width", "min-device-width", "max-device-width", "device-height",
"min-device-height", "max-device-height", "aspect-ratio",
"min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
"min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
"max-color", "color-index", "min-color-index", "max-color-index",
"monochrome", "min-monochrome", "max-monochrome", "resolution",
"min-resolution", "max-resolution", "scan", "grid", "orientation",
"device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
"pointer", "any-pointer", "hover", "any-hover"
], mediaFeatures = keySet(mediaFeatures_);
var mediaValueKeywords_ = [
"landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
"interlace", "progressive"
], mediaValueKeywords = keySet(mediaValueKeywords_);
var propertyKeywords_ = [
"align-content", "align-items", "align-self", "alignment-adjust",
"alignment-baseline", "anchor-point", "animation", "animation-delay",
"animation-direction", "animation-duration", "animation-fill-mode",
"animation-iteration-count", "animation-name", "animation-play-state",
"animation-timing-function", "appearance", "azimuth", "backface-visibility",
"background", "background-attachment", "background-blend-mode", "background-clip",
"background-color", "background-image", "background-origin", "background-position",
"background-repeat", "background-size", "baseline-shift", "binding",
"bleed", "bookmark-label", "bookmark-level", "bookmark-state",
"bookmark-target", "border", "border-bottom", "border-bottom-color",
"border-bottom-left-radius", "border-bottom-right-radius",
"border-bottom-style", "border-bottom-width", "border-collapse",
"border-color", "border-image", "border-image-outset",
"border-image-repeat", "border-image-slice", "border-image-source",
"border-image-width", "border-left", "border-left-color",
"border-left-style", "border-left-width", "border-radius", "border-right",
"border-right-color", "border-right-style", "border-right-width",
"border-spacing", "border-style", "border-top", "border-top-color",
"border-top-left-radius", "border-top-right-radius", "border-top-style",
"border-top-width", "border-width", "bottom", "box-decoration-break",
"box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
"caption-side", "clear", "clip", "color", "color-profile", "column-count",
"column-fill", "column-gap", "column-rule", "column-rule-color",
"column-rule-style", "column-rule-width", "column-span", "column-width",
"columns", "content", "counter-increment", "counter-reset", "crop", "cue",
"cue-after", "cue-before", "cursor", "direction", "display",
"dominant-baseline", "drop-initial-after-adjust",
"drop-initial-after-align", "drop-initial-before-adjust",
"drop-initial-before-align", "drop-initial-size", "drop-initial-value",
"elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
"flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
"float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
"font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
"font-stretch", "font-style", "font-synthesis", "font-variant",
"font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
"font-variant-ligatures", "font-variant-numeric", "font-variant-position",
"font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
"grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap",
"grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap",
"grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns",
"grid-template-rows", "hanging-punctuation", "height", "hyphens",
"icon", "image-orientation", "image-rendering", "image-resolution",
"inline-box-align", "justify-content", "left", "letter-spacing",
"line-break", "line-height", "line-stacking", "line-stacking-ruby",
"line-stacking-shift", "line-stacking-strategy", "list-style",
"list-style-image", "list-style-position", "list-style-type", "margin",
"margin-bottom", "margin-left", "margin-right", "margin-top",
"marker-offset", "marks", "marquee-direction", "marquee-loop",
"marquee-play-count", "marquee-speed", "marquee-style", "max-height",
"max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
"nav-left", "nav-right", "nav-up", "object-fit", "object-position",
"opacity", "order", "orphans", "outline",
"outline-color", "outline-offset", "outline-style", "outline-width",
"overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
"padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
"page", "page-break-after", "page-break-before", "page-break-inside",
"page-policy", "pause", "pause-after", "pause-before", "perspective",
"perspective-origin", "pitch", "pitch-range", "play-during", "position",
"presentation-level", "punctuation-trim", "quotes", "region-break-after",
"region-break-before", "region-break-inside", "region-fragment",
"rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
"right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
"ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
"shape-outside", "size", "speak", "speak-as", "speak-header",
"speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
"tab-size", "table-layout", "target", "target-name", "target-new",
"target-position", "text-align", "text-align-last", "text-decoration",
"text-decoration-color", "text-decoration-line", "text-decoration-skip",
"text-decoration-style", "text-emphasis", "text-emphasis-color",
"text-emphasis-position", "text-emphasis-style", "text-height",
"text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
"text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
"text-wrap", "top", "transform", "transform-origin", "transform-style",
"transition", "transition-delay", "transition-duration",
"transition-property", "transition-timing-function", "unicode-bidi",
"vertical-align", "visibility", "voice-balance", "voice-duration",
"voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
"voice-volume", "volume", "white-space", "widows", "width", "word-break",
"word-spacing", "word-wrap", "z-index",
// SVG-specific
"clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
"flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
"color-interpolation", "color-interpolation-filters",
"color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
"marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
"stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
"stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
"baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
"glyph-orientation-vertical", "text-anchor", "writing-mode"
], propertyKeywords = keySet(propertyKeywords_);
var nonStandardPropertyKeywords_ = [
"scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
"scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
"scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
"searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
"searchfield-results-decoration", "zoom"
], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
var fontProperties_ = [
"font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
"font-stretch", "font-weight", "font-style"
], fontProperties = keySet(fontProperties_);
var counterDescriptors_ = [
"additive-symbols", "fallback", "negative", "pad", "prefix", "range",
"speak-as", "suffix", "symbols", "system"
], counterDescriptors = keySet(counterDescriptors_);
var colorKeywords_ = [
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
"bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
"burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
"cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
"darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
"darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
"darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
"deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
"floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
"gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
"hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
"lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
"lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
"lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
"lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
"maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
"mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
"mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
"navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
"orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
"papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
"purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
"salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
"slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
"teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
"whitesmoke", "yellow", "yellowgreen"
], colorKeywords = keySet(colorKeywords_);
var valueKeywords_ = [
"above", "absolute", "activeborder", "additive", "activecaption", "afar",
"after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
"always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
"arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page",
"avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
"bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
"both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
"buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
"capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
"cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
"cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
"col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
"compact", "condensed", "contain", "content",
"content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
"cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
"decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
"destination-in", "destination-out", "destination-over", "devanagari", "difference",
"disc", "discard", "disclosure-closed", "disclosure-open", "document",
"dot-dash", "dot-dot-dash",
"dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
"element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
"ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
"ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
"ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
"ethiopic-halehame-gez", "ethiopic-halehame-om-et",
"ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
"ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
"ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
"extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
"forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove",
"gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
"help", "hidden", "hide", "higher", "highlight", "highlighttext",
"hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
"inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
"infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
"inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
"italic", "japanese-formal", "japanese-informal", "justify", "kannada",
"katakana", "katakana-iroha", "keep-all", "khmer",
"korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
"landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
"line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
"local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
"lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
"lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d",
"media-controls-background", "media-current-time-display",
"media-fullscreen-button", "media-mute-button", "media-play-button",
"media-return-to-realtime-button", "media-rewind-button",
"media-seek-back-button", "media-seek-forward-button", "media-slider",
"media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
"media-volume-slider-container", "media-volume-sliderthumb", "medium",
"menu", "menulist", "menulist-button", "menulist-text",
"menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
"mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize",
"narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
"no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
"ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
"optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
"outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
"painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
"pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
"progress", "push-button", "radial-gradient", "radio", "read-only",
"read-write", "read-write-plaintext-only", "rectangle", "region",
"relative", "repeat", "repeating-linear-gradient",
"repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
"rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
"rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
"s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
"scroll", "scrollbar", "se-resize", "searchfield",
"searchfield-cancel-button", "searchfield-decoration",
"searchfield-results-button", "searchfield-results-decoration",
"semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
"simp-chinese-formal", "simp-chinese-informal", "single",
"skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
"slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
"small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
"source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square",
"square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
"subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table",
"table-caption", "table-cell", "table-column", "table-column-group",
"table-footer-group", "table-header-group", "table-row", "table-row-group",
"tamil",
"telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
"thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
"threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
"tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
"trad-chinese-formal", "trad-chinese-informal",
"translate", "translate3d", "translateX", "translateY", "translateZ",
"transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
"upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
"upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
"var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
"visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
"window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
"xx-large", "xx-small"
], valueKeywords = keySet(valueKeywords_);
var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
.concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
.concat(valueKeywords_);
CodeMirror.registerHelper("hintWords", "css", allWords);
function tokenCComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (maybeEnd && ch == "/") {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return ["comment", "comment"];
}
CodeMirror.defineMIME("text/css", {
documentTypes: documentTypes,
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
fontProperties: fontProperties,
counterDescriptors: counterDescriptors,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
tokenHooks: {
"/": function(stream, state) {
if (!stream.eat("*")) return false;
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
},
name: "css"
});
CodeMirror.defineMIME("text/x-scss", {
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
fontProperties: fontProperties,
allowNested: true,
tokenHooks: {
"/": function(stream, state) {
if (stream.eat("/")) {
stream.skipToEnd();
return ["comment", "comment"];
} else if (stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
} else {
return ["operator", "operator"];
}
},
":": function(stream) {
if (stream.match(/\s*\{/))
return [null, "{"];
return false;
},
"$": function(stream) {
stream.match(/^[\w-]+/);
if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"];
return ["variable-2", "variable"];
},
"#": function(stream) {
if (!stream.eat("{")) return false;
return [null, "interpolation"];
}
},
name: "css",
helperType: "scss"
});
CodeMirror.defineMIME("text/x-less", {
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
fontProperties: fontProperties,
allowNested: true,
tokenHooks: {
"/": function(stream, state) {
if (stream.eat("/")) {
stream.skipToEnd();
return ["comment", "comment"];
} else if (stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
} else {
return ["operator", "operator"];
}
},
"@": function(stream) {
if (stream.eat("{")) return [null, "interpolation"];
if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false;
stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"];
return ["variable-2", "variable"];
},
"&": function() {
return ["atom", "atom"];
}
},
name: "css",
helperType: "less"
});
CodeMirror.defineMIME("text/x-gss", {
documentTypes: documentTypes,
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
fontProperties: fontProperties,
counterDescriptors: counterDescriptors,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
supportsAtComponent: true,
tokenHooks: {
"/": function(stream, state) {
if (!stream.eat("*")) return false;
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
},
name: "css",
helperType: "gss"
});
});
+152
View File
@@ -0,0 +1,152 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var defaultTags = {
script: [
["lang", /(javascript|babel)/i, "javascript"],
["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, "javascript"],
["type", /./, "text/plain"],
[null, null, "javascript"]
],
style: [
["lang", /^css$/i, "css"],
["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"],
["type", /./, "text/plain"],
[null, null, "css"]
]
};
function maybeBackup(stream, pat, style) {
var cur = stream.current(), close = cur.search(pat);
if (close > -1) {
stream.backUp(cur.length - close);
} else if (cur.match(/<\/?$/)) {
stream.backUp(cur.length);
if (!stream.match(pat, false)) stream.match(cur);
}
return style;
}
var attrRegexpCache = {};
function getAttrRegexp(attr) {
var regexp = attrRegexpCache[attr];
if (regexp) return regexp;
return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");
}
function getAttrValue(text, attr) {
var match = text.match(getAttrRegexp(attr))
return match ? match[2] : ""
}
function getTagRegexp(tagName, anchored) {
return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i");
}
function addTags(from, to) {
for (var tag in from) {
var dest = to[tag] || (to[tag] = []);
var source = from[tag];
for (var i = source.length - 1; i >= 0; i--)
dest.unshift(source[i])
}
}
function findMatchingMode(tagInfo, tagText) {
for (var i = 0; i < tagInfo.length; i++) {
var spec = tagInfo[i];
if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];
}
}
CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
var htmlMode = CodeMirror.getMode(config, {
name: "xml",
htmlMode: true,
multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
});
var tags = {};
var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;
addTags(defaultTags, tags);
if (configTags) addTags(configTags, tags);
if (configScript) for (var i = configScript.length - 1; i >= 0; i--)
tags.script.unshift(["type", configScript[i].matches, configScript[i].mode])
function html(stream, state) {
var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName
if (tag && !/[<>\s\/]/.test(stream.current()) &&
(tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&
tags.hasOwnProperty(tagName)) {
state.inTag = tagName + " "
} else if (state.inTag && tag && />$/.test(stream.current())) {
var inTag = /^([\S]+) (.*)/.exec(state.inTag)
state.inTag = null
var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2])
var mode = CodeMirror.getMode(config, modeSpec)
var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);
state.token = function (stream, state) {
if (stream.match(endTagA, false)) {
state.token = html;
state.localState = state.localMode = null;
return null;
}
return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
};
state.localMode = mode;
state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, ""));
} else if (state.inTag) {
state.inTag += stream.current()
if (stream.eol()) state.inTag += " "
}
return style;
};
return {
startState: function () {
var state = CodeMirror.startState(htmlMode);
return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};
},
copyState: function (state) {
var local;
if (state.localState) {
local = CodeMirror.copyState(state.localMode, state.localState);
}
return {token: state.token, inTag: state.inTag,
localMode: state.localMode, localState: local,
htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
},
token: function (stream, state) {
return state.token(stream, state);
},
indent: function (state, textAfter) {
if (!state.localMode || /^\s*<\//.test(textAfter))
return htmlMode.indent(state.htmlState, textAfter);
else if (state.localMode.indent)
return state.localMode.indent(state.localState, textAfter);
else
return CodeMirror.Pass;
},
innerMode: function (state) {
return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
}
};
}, "xml", "javascript", "css");
CodeMirror.defineMIME("text/html", "htmlmixed");
});
+748
View File
@@ -0,0 +1,748 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// TODO actually recognize syntax of TypeScript constructs
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function expressionAllowed(stream, state, backUp) {
return /^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
(state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
}
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var statementIndent = parserConfig.statementIndent;
var jsonldMode = parserConfig.jsonld;
var jsonMode = parserConfig.json || jsonldMode;
var isTS = parserConfig.typescript;
var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
var jsKeywords = {
"if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C,
"var": kw("var"), "const": kw("var"), "let": kw("var"),
"function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
"this": kw("this"), "class": kw("class"), "super": kw("atom"),
"yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
"await": C, "async": kw("async")
};
// Extend the 'normal' keywords with the TypeScript language extensions
if (isTS) {
var type = {type: "variable", style: "variable-3"};
var tsKeywords = {
// object-like things
"interface": kw("class"),
"implements": C,
"namespace": C,
"module": kw("module"),
"enum": kw("module"),
// scope modifiers
"public": kw("modifier"),
"private": kw("modifier"),
"protected": kw("modifier"),
"abstract": kw("modifier"),
// operators
"as": operator,
// types
"string": type, "number": type, "boolean": type, "any": type
};
for (var attr in tsKeywords) {
jsKeywords[attr] = tsKeywords[attr];
}
}
return jsKeywords;
}();
var isOperatorChar = /[+\-*&%=<>!?|~^]/;
var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
function readRegexp(stream) {
var escaped = false, next, inSet = false;
while ((next = stream.next()) != null) {
if (!escaped) {
if (next == "/" && !inSet) return;
if (next == "[") inSet = true;
else if (inSet && next == "]") inSet = false;
}
escaped = !escaped && next == "\\";
}
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
return ret("number", "number");
} else if (ch == "." && stream.match("..")) {
return ret("spread", "meta");
} else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
return ret(ch);
} else if (ch == "=" && stream.eat(">")) {
return ret("=>", "operator");
} else if (ch == "0" && stream.eat(/x/i)) {
stream.eatWhile(/[\da-f]/i);
return ret("number", "number");
} else if (ch == "0" && stream.eat(/o/i)) {
stream.eatWhile(/[0-7]/i);
return ret("number", "number");
} else if (ch == "0" && stream.eat(/b/i)) {
stream.eatWhile(/[01]/i);
return ret("number", "number");
} else if (/\d/.test(ch)) {
stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
return ret("number", "number");
} else if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
} else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
} else if (expressionAllowed(stream, state, 1)) {
readRegexp(stream);
stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
return ret("regexp", "string-2");
} else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator", stream.current());
}
} else if (ch == "`") {
state.tokenize = tokenQuasi;
return tokenQuasi(stream, state);
} else if (ch == "#") {
stream.skipToEnd();
return ret("error", "error");
} else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator", stream.current());
} else if (wordRE.test(ch)) {
stream.eatWhile(wordRE);
var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
ret("variable", "variable", word);
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next;
if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
state.tokenize = tokenBase;
return ret("jsonld-keyword", "meta");
}
while ((next = stream.next()) != null) {
if (next == quote && !escaped) break;
escaped = !escaped && next == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenQuasi(stream, state) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && next == "\\";
}
return ret("quasi", "string-2", stream.current());
}
var brackets = "([{}])";
// This is a crude lookahead trick to try and notice that we're
// parsing the argument patterns for a fat-arrow function before we
// actually hit the arrow token. It only works if the arrow is on
// the same line as the arguments and there's no strange noise
// (comments) in between. Fallback is to only notice when we hit the
// arrow, and not declare the arguments as locals for the arrow
// body.
function findFatArrow(stream, state) {
if (state.fatArrowAt) state.fatArrowAt = null;
var arrow = stream.string.indexOf("=>", stream.start);
if (arrow < 0) return;
var depth = 0, sawSomething = false;
for (var pos = arrow - 1; pos >= 0; --pos) {
var ch = stream.string.charAt(pos);
var bracket = brackets.indexOf(ch);
if (bracket >= 0 && bracket < 3) {
if (!depth) { ++pos; break; }
if (--depth == 0) break;
} else if (bracket >= 3 && bracket < 6) {
++depth;
} else if (wordRE.test(ch)) {
sawSomething = true;
} else if (/["'\/]/.test(ch)) {
return;
} else if (sawSomething && !depth) {
++pos;
break;
}
}
if (sawSomething && !depth) state.fatArrowAt = pos;
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
for (var cx = state.context; cx; cx = cx.prev) {
for (var v = cx.vars; v; v = v.next)
if (v.name == varname) return true;
}
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function register(varname) {
function inList(list) {
for (var v = list; v; v = v.next)
if (v.name == varname) return true;
return false;
}
var state = cx.state;
cx.marked = "def";
if (state.context) {
if (inList(state.localVars)) return;
state.localVars = {name: varname, next: state.localVars};
} else {
if (inList(state.globalVars)) return;
if (parserConfig.globalVars)
state.globalVars = {name: varname, next: state.globalVars};
}
}
// Combinators
var defaultVars = {name: "this", next: {name: "arguments"}};
function pushcontext() {
cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
cx.state.localVars = defaultVars;
}
function popcontext() {
cx.state.localVars = cx.state.context.vars;
cx.state.context = cx.state.context.prev;
}
function pushlex(type, info) {
var result = function() {
var state = cx.state, indent = state.indented;
if (state.lexical.type == "stat") indent = state.lexical.indented;
else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
indent = outer.indented;
state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
function exp(type) {
if (type == wanted) return cont();
else if (wanted == ";") return pass();
else return cont(exp);
};
return exp;
}
function statement(type, value) {
if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "{") return cont(pushlex("}"), block, poplex);
if (type == ";") return cont();
if (type == "if") {
if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
cx.state.cc.pop()();
return cont(pushlex("form"), expression, statement, poplex, maybeelse);
}
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
if (type == "variable") return cont(pushlex("stat"), maybelabel);
if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
block, poplex, poplex);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
statement, poplex, popcontext);
if (type == "class") return cont(pushlex("form"), className, poplex);
if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex)
if (type == "async") return cont(statement)
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function expression(type) {
return expressionInner(type, false);
}
function expressionNoComma(type) {
return expressionInner(type, true);
}
function expressionInner(type, noComma) {
if (cx.state.fatArrowAt == cx.stream.start) {
var body = noComma ? arrowBodyNoComma : arrowBody;
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
}
var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
if (type == "function") return cont(functiondef, maybeop);
if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
if (type == "{") return contCommasep(objprop, "}", null, maybeop);
if (type == "quasi") return pass(quasi, maybeop);
if (type == "new") return cont(maybeTarget(noComma));
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeexpressionNoComma(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expressionNoComma);
}
function maybeoperatorComma(type, value) {
if (type == ",") return cont(expression);
return maybeoperatorNoComma(type, value, false);
}
function maybeoperatorNoComma(type, value, noComma) {
var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
var expr = noComma == false ? expression : expressionNoComma;
if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
if (type == "operator") {
if (/\+\+|--/.test(value)) return cont(me);
if (value == "?") return cont(expression, expect(":"), expr);
return cont(expr);
}
if (type == "quasi") { return pass(quasi, me); }
if (type == ";") return;
if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
if (type == ".") return cont(property, me);
if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
}
function quasi(type, value) {
if (type != "quasi") return pass();
if (value.slice(value.length - 2) != "${") return cont(quasi);
return cont(expression, continueQuasi);
}
function continueQuasi(type) {
if (type == "}") {
cx.marked = "string-2";
cx.state.tokenize = tokenQuasi;
return cont(quasi);
}
}
function arrowBody(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expression);
}
function arrowBodyNoComma(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expressionNoComma);
}
function maybeTarget(noComma) {
return function(type) {
if (type == ".") return cont(noComma ? targetNoComma : target);
else return pass(noComma ? expressionNoComma : expression);
};
}
function target(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
}
function targetNoComma(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperatorComma, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type, value) {
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
if (value == "get" || value == "set") return cont(getterSetter);
return cont(afterprop);
} else if (type == "number" || type == "string") {
cx.marked = jsonldMode ? "property" : (cx.style + " property");
return cont(afterprop);
} else if (type == "jsonld-keyword") {
return cont(afterprop);
} else if (type == "modifier") {
return cont(objprop)
} else if (type == "[") {
return cont(expression, expect("]"), afterprop);
} else if (type == "spread") {
return cont(expression);
}
}
function getterSetter(type) {
if (type != "variable") return pass(afterprop);
cx.marked = "property";
return cont(functiondef);
}
function afterprop(type) {
if (type == ":") return cont(expressionNoComma);
if (type == "(") return pass(functiondef);
}
function commasep(what, end) {
function proceed(type, value) {
if (type == ",") {
var lex = cx.state.lexical;
if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
return cont(what, proceed);
}
if (type == end || value == end) return cont();
return cont(expect(end));
}
return function(type, value) {
if (type == end || value == end) return cont();
return pass(what, proceed);
};
}
function contCommasep(what, end, info) {
for (var i = 3; i < arguments.length; i++)
cx.cc.push(arguments[i]);
return cont(pushlex(end, info), commasep(what, end), poplex);
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function maybetype(type) {
if (isTS && type == ":") return cont(typeexpr);
}
function maybedefault(_, value) {
if (value == "=") return cont(expressionNoComma);
}
function typeexpr(type) {
if (type == "variable") {cx.marked = "variable-3"; return cont(afterType);}
}
function afterType(type, value) {
if (value == "<") return cont(commasep(typeexpr, ">"), afterType)
if (type == "[") return cont(expect("]"), afterType)
}
function vardef() {
return pass(pattern, maybetype, maybeAssign, vardefCont);
}
function pattern(type, value) {
if (type == "modifier") return cont(pattern)
if (type == "variable") { register(value); return cont(); }
if (type == "spread") return cont(pattern);
if (type == "[") return contCommasep(pattern, "]");
if (type == "{") return contCommasep(proppattern, "}");
}
function proppattern(type, value) {
if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
register(value);
return cont(maybeAssign);
}
if (type == "variable") cx.marked = "property";
if (type == "spread") return cont(pattern);
if (type == "}") return pass();
return cont(expect(":"), pattern, maybeAssign);
}
function maybeAssign(_type, value) {
if (value == "=") return cont(expressionNoComma);
}
function vardefCont(type) {
if (type == ",") return cont(vardef);
}
function maybeelse(type, value) {
if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
}
function forspec(type) {
if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
}
function forspec1(type) {
if (type == "var") return cont(vardef, expect(";"), forspec2);
if (type == ";") return cont(forspec2);
if (type == "variable") return cont(formaybeinof);
return pass(expression, expect(";"), forspec2);
}
function formaybeinof(_type, value) {
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
return cont(maybeoperatorComma, forspec2);
}
function forspec2(type, value) {
if (type == ";") return cont(forspec3);
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
return pass(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type != ")") cont(expression);
}
function functiondef(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext);
}
function funarg(type) {
if (type == "spread") return cont(funarg);
return pass(pattern, maybetype, maybedefault);
}
function className(type, value) {
if (type == "variable") {register(value); return cont(classNameAfter);}
}
function classNameAfter(type, value) {
if (value == "extends") return cont(expression, classNameAfter);
if (type == "{") return cont(pushlex("}"), classBody, poplex);
}
function classBody(type, value) {
if (type == "variable" || cx.style == "keyword") {
if (value == "static") {
cx.marked = "keyword";
return cont(classBody);
}
cx.marked = "property";
if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
return cont(functiondef, classBody);
}
if (value == "*") {
cx.marked = "keyword";
return cont(classBody);
}
if (type == ";") return cont(classBody);
if (type == "}") return cont();
}
function classGetterSetter(type) {
if (type != "variable") return pass();
cx.marked = "property";
return cont();
}
function afterExport(_type, value) {
if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
return pass(statement);
}
function afterImport(type) {
if (type == "string") return cont();
return pass(importSpec, maybeFrom);
}
function importSpec(type, value) {
if (type == "{") return contCommasep(importSpec, "}");
if (type == "variable") register(value);
if (value == "*") cx.marked = "keyword";
return cont(maybeAs);
}
function maybeAs(_type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
}
function maybeFrom(_type, value) {
if (value == "from") { cx.marked = "keyword"; return cont(expression); }
}
function arrayLiteral(type) {
if (type == "]") return cont();
return pass(expressionNoComma, maybeArrayComprehension);
}
function maybeArrayComprehension(type) {
if (type == "for") return pass(comprehension, expect("]"));
if (type == ",") return cont(commasep(maybeexpressionNoComma, "]"));
return pass(commasep(expressionNoComma, "]"));
}
function comprehension(type) {
if (type == "for") return cont(forspec, comprehension);
if (type == "if") return cont(expression, comprehension);
}
function isContinuedStatement(state, textAfter) {
return state.lastType == "operator" || state.lastType == "," ||
isOperatorChar.test(textAfter.charAt(0)) ||
/[,.]/.test(textAfter.charAt(0));
}
// Interface
return {
startState: function(basecolumn) {
var state = {
tokenize: tokenBase,
lastType: "sof",
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
context: parserConfig.localVars && {vars: parserConfig.localVars},
indented: basecolumn || 0
};
if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
state.globalVars = parserConfig.globalVars;
return state;
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
findFatArrow(stream, state);
}
if (state.tokenize != tokenComment && stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize == tokenComment) return CodeMirror.Pass;
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
// Kludge to prevent 'maybelse' from blocking lexical scope pops
if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
var c = state.cc[i];
if (c == poplex) lexical = lexical.prev;
else if (c != maybeelse) break;
}
if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "form") return lexical.indented + indentUnit;
else if (type == "stat")
return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
blockCommentStart: jsonMode ? null : "/*",
blockCommentEnd: jsonMode ? null : "*/",
lineComment: jsonMode ? null : "//",
fold: "brace",
closeBrackets: "()[]{}''\"\"``",
helperType: jsonMode ? "json" : "javascript",
jsonldMode: jsonldMode,
jsonMode: jsonMode,
expressionAllowed: expressionAllowed,
skipExpression: function(state) {
var top = state.cc[state.cc.length - 1]
if (top == expression || top == expressionNoComma) state.cc.pop()
}
};
});
CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
});
+53
View File
@@ -0,0 +1,53 @@
/*
Name: material
Author: Michael Kaminsky (http://github.com/mkaminsky11)
Original material color scheme by Mattia Astorino (https://github.com/equinusocio/material-theme)
*/
.cm-s-material {
background-color: #263238;
color: rgba(233, 237, 237, 1);
}
.cm-s-material .CodeMirror-gutters {
background: #263238;
color: rgb(83,127,126);
border: none;
}
.cm-s-material .CodeMirror-guttermarker, .cm-s-material .CodeMirror-guttermarker-subtle, .cm-s-material .CodeMirror-linenumber { color: rgb(83,127,126); }
.cm-s-material .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }
.cm-s-material div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); }
.cm-s-material.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }
.cm-s-material .CodeMirror-line::selection, .cm-s-material .CodeMirror-line > span::selection, .cm-s-material .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }
.cm-s-material .CodeMirror-line::-moz-selection, .cm-s-material .CodeMirror-line > span::-moz-selection, .cm-s-material .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }
.cm-s-material .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); }
.cm-s-material .cm-keyword { color: rgba(199, 146, 234, 1); }
.cm-s-material .cm-operator { color: rgba(233, 237, 237, 1); }
.cm-s-material .cm-variable-2 { color: #80CBC4; }
.cm-s-material .cm-variable-3 { color: #82B1FF; }
.cm-s-material .cm-builtin { color: #DECB6B; }
.cm-s-material .cm-atom { color: #F77669; }
.cm-s-material .cm-number { color: #F77669; }
.cm-s-material .cm-def { color: rgba(233, 237, 237, 1); }
.cm-s-material .cm-string { color: #C3E88D; }
.cm-s-material .cm-string-2 { color: #80CBC4; }
.cm-s-material .cm-comment { color: #546E7A; }
.cm-s-material .cm-variable { color: #82B1FF; }
.cm-s-material .cm-tag { color: #80CBC4; }
.cm-s-material .cm-meta { color: #80CBC4; }
.cm-s-material .cm-attribute { color: #FFCB6B; }
.cm-s-material .cm-property { color: #80CBAE; }
.cm-s-material .cm-qualifier { color: #DECB6B; }
.cm-s-material .cm-variable-3 { color: #DECB6B; }
.cm-s-material .cm-tag { color: rgba(255, 83, 112, 1); }
.cm-s-material .cm-error {
color: rgba(255, 255, 255, 1.0);
background-color: #EC5F67;
}
.cm-s-material .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
+36
View File
@@ -0,0 +1,36 @@
/* Based on Sublime Text's Monokai theme */
.cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; }
.cm-s-monokai div.CodeMirror-selected { background: #49483E; }
.cm-s-monokai .CodeMirror-line::selection, .cm-s-monokai .CodeMirror-line > span::selection, .cm-s-monokai .CodeMirror-line > span > span::selection { background: rgba(73, 72, 62, .99); }
.cm-s-monokai .CodeMirror-line::-moz-selection, .cm-s-monokai .CodeMirror-line > span::-moz-selection, .cm-s-monokai .CodeMirror-line > span > span::-moz-selection { background: rgba(73, 72, 62, .99); }
.cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; }
.cm-s-monokai .CodeMirror-guttermarker { color: white; }
.cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; }
.cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }
.cm-s-monokai span.cm-comment { color: #75715e; }
.cm-s-monokai span.cm-atom { color: #ae81ff; }
.cm-s-monokai span.cm-number { color: #ae81ff; }
.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; }
.cm-s-monokai span.cm-keyword { color: #f92672; }
.cm-s-monokai span.cm-builtin { color: #66d9ef; }
.cm-s-monokai span.cm-string { color: #e6db74; }
.cm-s-monokai span.cm-variable { color: #f8f8f2; }
.cm-s-monokai span.cm-variable-2 { color: #9effff; }
.cm-s-monokai span.cm-variable-3 { color: #66d9ef; }
.cm-s-monokai span.cm-def { color: #fd971f; }
.cm-s-monokai span.cm-bracket { color: #f8f8f2; }
.cm-s-monokai span.cm-tag { color: #f92672; }
.cm-s-monokai span.cm-header { color: #ae81ff; }
.cm-s-monokai span.cm-link { color: #ae81ff; }
.cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; }
.cm-s-monokai .CodeMirror-activeline-background { background: #373831; }
.cm-s-monokai .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
+340
View File
@@ -0,0 +1,340 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var wordOperators = wordRegexp(["and", "or", "not", "is"]);
var commonKeywords = ["as", "assert", "break", "class", "continue",
"def", "del", "elif", "else", "except", "finally",
"for", "from", "global", "if", "import",
"lambda", "pass", "raise", "return",
"try", "while", "with", "yield", "in"];
var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
"classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "filter", "float", "format", "frozenset",
"getattr", "globals", "hasattr", "hash", "help", "hex", "id",
"input", "int", "isinstance", "issubclass", "iter", "len",
"list", "locals", "map", "max", "memoryview", "min", "next",
"object", "oct", "open", "ord", "pow", "property", "range",
"repr", "reversed", "round", "set", "setattr", "slice",
"sorted", "staticmethod", "str", "sum", "super", "tuple",
"type", "vars", "zip", "__import__", "NotImplemented",
"Ellipsis", "__debug__"];
CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
function top(state) {
return state.scopes[state.scopes.length - 1];
}
CodeMirror.defineMode("python", function(conf, parserConf) {
var ERRORCLASS = "error";
var singleDelimiters = parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.]/;
var doubleOperators = parserConf.doubleOperators || /^([!<>]==|<>|<<|>>|\/\/|\*\*)/;
var doubleDelimiters = parserConf.doubleDelimiters || /^(\+=|\-=|\*=|%=|\/=|&=|\|=|\^=)/;
var tripleDelimiters = parserConf.tripleDelimiters || /^(\/\/=|>>=|<<=|\*\*=)/;
var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
if (parserConf.extra_keywords != undefined)
myKeywords = myKeywords.concat(parserConf.extra_keywords);
if (parserConf.extra_builtins != undefined)
myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
var py3 = parserConf.version && parseInt(parserConf.version, 10) == 3
if (py3) {
// since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
var singleOperators = parserConf.singleOperators || /^[\+\-\*\/%&|\^~<>!@]/;
var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
var stringPrefixes = new RegExp("^(([rbuf]|(br))?('{3}|\"{3}|['\"]))", "i");
} else {
var singleOperators = parserConf.singleOperators || /^[\+\-\*\/%&|\^~<>!]/;
var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
myKeywords = myKeywords.concat(["exec", "print"]);
myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
"file", "intern", "long", "raw_input", "reduce", "reload",
"unichr", "unicode", "xrange", "False", "True", "None"]);
var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
}
var keywords = wordRegexp(myKeywords);
var builtins = wordRegexp(myBuiltins);
// tokenizers
function tokenBase(stream, state) {
if (stream.sol()) state.indent = stream.indentation()
// Handle scope changes
if (stream.sol() && top(state).type == "py") {
var scopeOffset = top(state).offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset)
pushPyScope(state);
else if (lineOffset < scopeOffset && dedent(stream, state))
state.errorToken = true;
return null;
} else {
var style = tokenBaseInner(stream, state);
if (scopeOffset > 0 && dedent(stream, state))
style += " " + ERRORCLASS;
return style;
}
}
return tokenBaseInner(stream, state);
}
function tokenBaseInner(stream, state) {
if (stream.eatSpace()) return null;
var ch = stream.peek();
// Handle Comments
if (ch == "#") {
stream.skipToEnd();
return "comment";
}
// Handle Number Literals
if (stream.match(/^[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
if (stream.match(/^\.\d+/)) { floatLiteral = true; }
if (floatLiteral) {
// Float literals may be "imaginary"
stream.eat(/J/i);
return "number";
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true;
// Binary
if (stream.match(/^0b[01]+/i)) intLiteral = true;
// Octal
if (stream.match(/^0o[0-7]+/i)) intLiteral = true;
// Decimal
if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
// Decimal literals may be "imaginary"
stream.eat(/J/i);
// TODO - Can you have imaginary longs?
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
if (intLiteral) {
// Integer literals may be "long"
stream.eat(/L/i);
return "number";
}
}
// Handle Strings
if (stream.match(stringPrefixes)) {
state.tokenize = tokenStringFactory(stream.current());
return state.tokenize(stream, state);
}
// Handle operators and Delimiters
if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters))
return "punctuation";
if (stream.match(doubleOperators) || stream.match(singleOperators))
return "operator";
if (stream.match(singleDelimiters))
return "punctuation";
if (state.lastToken == "." && stream.match(identifiers))
return "property";
if (stream.match(keywords) || stream.match(wordOperators))
return "keyword";
if (stream.match(builtins))
return "builtin";
if (stream.match(/^(self|cls)\b/))
return "variable-2";
if (stream.match(identifiers)) {
if (state.lastToken == "def" || state.lastToken == "class")
return "def";
return "variable";
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function tokenStringFactory(delimiter) {
while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
delimiter = delimiter.substr(1);
var singleline = delimiter.length == 1;
var OUTCLASS = "string";
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol())
return OUTCLASS;
} else if (stream.match(delimiter)) {
state.tokenize = tokenBase;
return OUTCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors)
return ERRORCLASS;
else
state.tokenize = tokenBase;
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function pushPyScope(state) {
while (top(state).type != "py") state.scopes.pop()
state.scopes.push({offset: top(state).offset + conf.indentUnit,
type: "py",
align: null})
}
function pushBracketScope(stream, state, type) {
var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1
state.scopes.push({offset: state.indent + hangingIndent,
type: type,
align: align})
}
function dedent(stream, state) {
var indented = stream.indentation();
while (top(state).offset > indented) {
if (top(state).type != "py") return true;
state.scopes.pop();
}
return top(state).offset != indented;
}
function tokenLexer(stream, state) {
if (stream.sol()) state.beginningOfLine = true;
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle decorators
if (state.beginningOfLine && current == "@")
return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;
if (/\S/.test(current)) state.beginningOfLine = false;
if ((style == "variable" || style == "builtin")
&& state.lastToken == "meta")
style = "meta";
// Handle scope changes.
if (current == "pass" || current == "return")
state.dedent += 1;
if (current == "lambda") state.lambda = true;
if (current == ":" && !state.lambda && top(state).type == "py")
pushPyScope(state);
var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1;
if (delimiter_index != -1)
pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
delimiter_index = "])}".indexOf(current);
if (delimiter_index != -1) {
if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
else return ERRORCLASS;
}
if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
if (state.scopes.length > 1) state.scopes.pop();
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset: basecolumn || 0, type: "py", align: null}],
indent: basecolumn || 0,
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var addErr = state.errorToken;
if (addErr) state.errorToken = false;
var style = tokenLexer(stream, state);
if (style && style != "comment")
state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
if (style == "punctuation") style = null;
if (stream.eol() && state.lambda)
state.lambda = false;
return addErr ? style + " " + ERRORCLASS : style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase)
return state.tokenize.isString ? CodeMirror.Pass : 0;
var scope = top(state), closing = scope.type == textAfter.charAt(0)
if (scope.align != null)
return scope.align - (closing ? 1 : 0)
else
return scope.offset - (closing ? hangingIndent : 0)
},
electricInput: /^\s*[\}\]\)]$/,
closeBrackets: {triples: "'\""},
lineComment: "#",
fold: "indent"
};
return external;
});
CodeMirror.defineMIME("text/x-python", "python");
var words = function(str) { return str.split(" "); };
CodeMirror.defineMIME("text/x-cython", {
name: "python",
extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
"extern gil include nogil property public"+
"readonly struct union DEF IF ELIF ELSE")
});
});
+394
View File
@@ -0,0 +1,394 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var htmlConfig = {
autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
'track': true, 'wbr': true, 'menuitem': true},
implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
'th': true, 'tr': true},
contextGrabbers: {
'dd': {'dd': true, 'dt': true},
'dt': {'dd': true, 'dt': true},
'li': {'li': true},
'option': {'option': true, 'optgroup': true},
'optgroup': {'optgroup': true},
'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
'rp': {'rp': true, 'rt': true},
'rt': {'rp': true, 'rt': true},
'tbody': {'tbody': true, 'tfoot': true},
'td': {'td': true, 'th': true},
'tfoot': {'tbody': true},
'th': {'td': true, 'th': true},
'thead': {'tbody': true, 'tfoot': true},
'tr': {'tr': true}
},
doNotIndent: {"pre": true},
allowUnquoted: true,
allowMissing: true,
caseFold: true
}
var xmlConfig = {
autoSelfClosers: {},
implicitlyClosed: {},
contextGrabbers: {},
doNotIndent: {},
allowUnquoted: false,
allowMissing: false,
caseFold: false
}
CodeMirror.defineMode("xml", function(editorConf, config_) {
var indentUnit = editorConf.indentUnit
var config = {}
var defaults = config_.htmlMode ? htmlConfig : xmlConfig
for (var prop in defaults) config[prop] = defaults[prop]
for (var prop in config_) config[prop] = config_[prop]
// Return variables for tokenizers
var type, setStyle;
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var ch = stream.next();
if (ch == "<") {
if (stream.eat("!")) {
if (stream.eat("[")) {
if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
else return null;
} else if (stream.match("--")) {
return chain(inBlock("comment", "-->"));
} else if (stream.match("DOCTYPE", true, true)) {
stream.eatWhile(/[\w\._\-]/);
return chain(doctype(1));
} else {
return null;
}
} else if (stream.eat("?")) {
stream.eatWhile(/[\w\._\-]/);
state.tokenize = inBlock("meta", "?>");
return "meta";
} else {
type = stream.eat("/") ? "closeTag" : "openTag";
state.tokenize = inTag;
return "tag bracket";
}
} else if (ch == "&") {
var ok;
if (stream.eat("#")) {
if (stream.eat("x")) {
ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
} else {
ok = stream.eatWhile(/[\d]/) && stream.eat(";");
}
} else {
ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
}
return ok ? "atom" : "error";
} else {
stream.eatWhile(/[^&<]/);
return null;
}
}
inText.isInText = true;
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.tokenize = inText;
type = ch == ">" ? "endTag" : "selfcloseTag";
return "tag bracket";
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = inText;
state.state = baseState;
state.tagName = state.tagStart = null;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
state.stringStartCol = stream.column();
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
function inAttribute(quote) {
var closure = function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inTag;
break;
}
}
return "string";
};
closure.isInAttribute = true;
return closure;
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
return style;
};
}
function doctype(depth) {
return function(stream, state) {
var ch;
while ((ch = stream.next()) != null) {
if (ch == "<") {
state.tokenize = doctype(depth + 1);
return state.tokenize(stream, state);
} else if (ch == ">") {
if (depth == 1) {
state.tokenize = inText;
break;
} else {
state.tokenize = doctype(depth - 1);
return state.tokenize(stream, state);
}
}
}
return "meta";
};
}
function Context(state, tagName, startOfLine) {
this.prev = state.context;
this.tagName = tagName;
this.indent = state.indented;
this.startOfLine = startOfLine;
if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
this.noIndent = true;
}
function popContext(state) {
if (state.context) state.context = state.context.prev;
}
function maybePopContext(state, nextTagName) {
var parentTagName;
while (true) {
if (!state.context) {
return;
}
parentTagName = state.context.tagName;
if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
!config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
return;
}
popContext(state);
}
}
function baseState(type, stream, state) {
if (type == "openTag") {
state.tagStart = stream.column();
return tagNameState;
} else if (type == "closeTag") {
return closeTagNameState;
} else {
return baseState;
}
}
function tagNameState(type, stream, state) {
if (type == "word") {
state.tagName = stream.current();
setStyle = "tag";
return attrState;
} else {
setStyle = "error";
return tagNameState;
}
}
function closeTagNameState(type, stream, state) {
if (type == "word") {
var tagName = stream.current();
if (state.context && state.context.tagName != tagName &&
config.implicitlyClosed.hasOwnProperty(state.context.tagName))
popContext(state);
if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
setStyle = "tag";
return closeState;
} else {
setStyle = "tag error";
return closeStateErr;
}
} else {
setStyle = "error";
return closeStateErr;
}
}
function closeState(type, _stream, state) {
if (type != "endTag") {
setStyle = "error";
return closeState;
}
popContext(state);
return baseState;
}
function closeStateErr(type, stream, state) {
setStyle = "error";
return closeState(type, stream, state);
}
function attrState(type, _stream, state) {
if (type == "word") {
setStyle = "attribute";
return attrEqState;
} else if (type == "endTag" || type == "selfcloseTag") {
var tagName = state.tagName, tagStart = state.tagStart;
state.tagName = state.tagStart = null;
if (type == "selfcloseTag" ||
config.autoSelfClosers.hasOwnProperty(tagName)) {
maybePopContext(state, tagName);
} else {
maybePopContext(state, tagName);
state.context = new Context(state, tagName, tagStart == state.indented);
}
return baseState;
}
setStyle = "error";
return attrState;
}
function attrEqState(type, stream, state) {
if (type == "equals") return attrValueState;
if (!config.allowMissing) setStyle = "error";
return attrState(type, stream, state);
}
function attrValueState(type, stream, state) {
if (type == "string") return attrContinuedState;
if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
setStyle = "error";
return attrState(type, stream, state);
}
function attrContinuedState(type, stream, state) {
if (type == "string") return attrContinuedState;
return attrState(type, stream, state);
}
return {
startState: function(baseIndent) {
var state = {tokenize: inText,
state: baseState,
indented: baseIndent || 0,
tagName: null, tagStart: null,
context: null}
if (baseIndent != null) state.baseIndent = baseIndent
return state
},
token: function(stream, state) {
if (!state.tagName && stream.sol())
state.indented = stream.indentation();
if (stream.eatSpace()) return null;
type = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
setStyle = null;
state.state = state.state(type || style, stream, state);
if (setStyle)
style = setStyle == "error" ? style + " error" : setStyle;
}
return style;
},
indent: function(state, textAfter, fullLine) {
var context = state.context;
// Indent multi-line strings (e.g. css).
if (state.tokenize.isInAttribute) {
if (state.tagStart == state.indented)
return state.stringStartCol + 1;
else
return state.indented + indentUnit;
}
if (context && context.noIndent) return CodeMirror.Pass;
if (state.tokenize != inTag && state.tokenize != inText)
return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
// Indent the starts of attribute names.
if (state.tagName) {
if (config.multilineTagIndentPastTag !== false)
return state.tagStart + state.tagName.length + 2;
else
return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
}
if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
if (tagAfter && tagAfter[1]) { // Closing tag spotted
while (context) {
if (context.tagName == tagAfter[2]) {
context = context.prev;
break;
} else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
context = context.prev;
} else {
break;
}
}
} else if (tagAfter) { // Opening tag spotted
while (context) {
var grabbers = config.contextGrabbers[context.tagName];
if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
context = context.prev;
else
break;
}
}
while (context && context.prev && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return state.baseIndent || 0;
},
electricInput: /<\/[\s\w:]+>$/,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
configuration: config.htmlMode ? "html" : "xml",
helperType: config.htmlMode ? "html" : "xml",
skipAttribute: function(state) {
if (state.state == attrValueState)
state.state = attrState
}
};
});
CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
});
+346
View File
@@ -0,0 +1,346 @@
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
color: black;
direction: ltr;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
white-space: nowrap;
}
.CodeMirror-guttermarker { color: black; }
.CodeMirror-guttermarker-subtle { color: #999; }
/* CURSOR */
.CodeMirror-cursor {
border-left: 1px solid black;
border-right: none;
width: 0;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.cm-fat-cursor .CodeMirror-cursor {
width: auto;
border: 0 !important;
background: #7e7;
}
.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-fat-cursor-mark {
background-color: rgba(20, 255, 20, 0.5);
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
}
.cm-animate-fat-cursor {
width: auto;
border: 0;
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
background-color: #7e7;
}
@-moz-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@-webkit-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
/* Can style cursor different in overwrite (non-insert) mode */
.CodeMirror-overwrite .CodeMirror-cursor {}
.cm-tab { display: inline-block; text-decoration: inherit; }
.CodeMirror-rulers {
position: absolute;
left: 0; right: 0; top: -50px; bottom: -20px;
overflow: hidden;
}
.CodeMirror-ruler {
border-left: 1px solid #ccc;
top: 0; bottom: 0;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-strikethrough {text-decoration: line-through;}
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-s-default .cm-error {color: #f00;}
.cm-invalidchar {color: #f00;}
.CodeMirror-composing { border-bottom: 2px solid; }
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}
.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
.CodeMirror-activeline-background {background: #e8f2ff;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -30px; margin-right: -30px;
padding-bottom: 30px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
}
.CodeMirror-sizer {
position: relative;
border-right: 30px solid transparent;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actual scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0; bottom: 0;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
min-height: 100%;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
display: inline-block;
vertical-align: top;
margin-bottom: -30px;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
background: none !important;
border: none !important;
}
.CodeMirror-gutter-background {
position: absolute;
top: 0; bottom: 0;
z-index: 4;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper ::selection { background-color: transparent }
.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
-webkit-font-variant-ligatures: contextual;
font-variant-ligatures: contextual;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
padding: 0.1px; /* Force widget margins to stay inside of the container */
}
.CodeMirror-widget {}
.CodeMirror-rtl pre { direction: rtl; }
.CodeMirror-code {
outline: none;
}
/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-cursor {
position: absolute;
pointer-events: none;
}
.CodeMirror-measure pre { position: static; }
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
div.CodeMirror-dragcursors {
visibility: visible;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
.cm-searching {
background-color: #ffa;
background-color: rgba(255, 255, 0, .4);
}
/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after { content: ''; }
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext { background: none; }
File diff suppressed because it is too large Load Diff
+832
View File
@@ -0,0 +1,832 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("css", function(config, parserConfig) {
var inline = parserConfig.inline
if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
var indentUnit = config.indentUnit,
tokenHooks = parserConfig.tokenHooks,
documentTypes = parserConfig.documentTypes || {},
mediaTypes = parserConfig.mediaTypes || {},
mediaFeatures = parserConfig.mediaFeatures || {},
mediaValueKeywords = parserConfig.mediaValueKeywords || {},
propertyKeywords = parserConfig.propertyKeywords || {},
nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
fontProperties = parserConfig.fontProperties || {},
counterDescriptors = parserConfig.counterDescriptors || {},
colorKeywords = parserConfig.colorKeywords || {},
valueKeywords = parserConfig.valueKeywords || {},
allowNested = parserConfig.allowNested,
lineComment = parserConfig.lineComment,
supportsAtComponent = parserConfig.supportsAtComponent === true;
var type, override;
function ret(style, tp) { type = tp; return style; }
// Tokenizers
function tokenBase(stream, state) {
var ch = stream.next();
if (tokenHooks[ch]) {
var result = tokenHooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == "@") {
stream.eatWhile(/[\w\\\-]/);
return ret("def", stream.current());
} else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
return ret(null, "compare");
} else if (ch == "\"" || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "#") {
stream.eatWhile(/[\w\\\-]/);
return ret("atom", "hash");
} else if (ch == "!") {
stream.match(/^\s*\w*/);
return ret("keyword", "important");
} else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (ch === "-") {
if (/[\d.]/.test(stream.peek())) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (stream.match(/^-[\w\\\-]+/)) {
stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false))
return ret("variable-2", "variable-definition");
return ret("variable-2", "variable");
} else if (stream.match(/^\w+-/)) {
return ret("meta", "meta");
}
} else if (/[,+>*\/]/.test(ch)) {
return ret(null, "select-op");
} else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
return ret("qualifier", "qualifier");
} else if (/[:;{}\[\]\(\)]/.test(ch)) {
return ret(null, ch);
} else if (((ch == "u" || ch == "U") && stream.match(/rl(-prefix)?\(/i)) ||
((ch == "d" || ch == "D") && stream.match("omain(", true, true)) ||
((ch == "r" || ch == "R") && stream.match("egexp(", true, true))) {
stream.backUp(1);
state.tokenize = tokenParenthesized;
return ret("property", "word");
} else if (/[\w\\\-]/.test(ch)) {
stream.eatWhile(/[\w\\\-]/);
return ret("property", "word");
} else {
return ret(null, null);
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) {
if (quote == ")") stream.backUp(1);
break;
}
escaped = !escaped && ch == "\\";
}
if (ch == quote || !escaped && quote != ")") state.tokenize = null;
return ret("string", "string");
};
}
function tokenParenthesized(stream, state) {
stream.next(); // Must be '('
if (!stream.match(/\s*[\"\')]/, false))
state.tokenize = tokenString(")");
else
state.tokenize = null;
return ret(null, "(");
}
// Context management
function Context(type, indent, prev) {
this.type = type;
this.indent = indent;
this.prev = prev;
}
function pushContext(state, stream, type, indent) {
state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
return type;
}
function popContext(state) {
if (state.context.prev)
state.context = state.context.prev;
return state.context.type;
}
function pass(type, stream, state) {
return states[state.context.type](type, stream, state);
}
function popAndPass(type, stream, state, n) {
for (var i = n || 1; i > 0; i--)
state.context = state.context.prev;
return pass(type, stream, state);
}
// Parser
function wordAsValue(stream) {
var word = stream.current().toLowerCase();
if (valueKeywords.hasOwnProperty(word))
override = "atom";
else if (colorKeywords.hasOwnProperty(word))
override = "keyword";
else
override = "variable";
}
var states = {};
states.top = function(type, stream, state) {
if (type == "{") {
return pushContext(state, stream, "block");
} else if (type == "}" && state.context.prev) {
return popContext(state);
} else if (supportsAtComponent && /@component/i.test(type)) {
return pushContext(state, stream, "atComponentBlock");
} else if (/^@(-moz-)?document$/i.test(type)) {
return pushContext(state, stream, "documentTypes");
} else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
return pushContext(state, stream, "atBlock");
} else if (/^@(font-face|counter-style)/i.test(type)) {
state.stateArg = type;
return "restricted_atBlock_before";
} else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
return "keyframes";
} else if (type && type.charAt(0) == "@") {
return pushContext(state, stream, "at");
} else if (type == "hash") {
override = "builtin";
} else if (type == "word") {
override = "tag";
} else if (type == "variable-definition") {
return "maybeprop";
} else if (type == "interpolation") {
return pushContext(state, stream, "interpolation");
} else if (type == ":") {
return "pseudo";
} else if (allowNested && type == "(") {
return pushContext(state, stream, "parens");
}
return state.context.type;
};
states.block = function(type, stream, state) {
if (type == "word") {
var word = stream.current().toLowerCase();
if (propertyKeywords.hasOwnProperty(word)) {
override = "property";
return "maybeprop";
} else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
override = "string-2";
return "maybeprop";
} else if (allowNested) {
override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
return "block";
} else {
override += " error";
return "maybeprop";
}
} else if (type == "meta") {
return "block";
} else if (!allowNested && (type == "hash" || type == "qualifier")) {
override = "error";
return "block";
} else {
return states.top(type, stream, state);
}
};
states.maybeprop = function(type, stream, state) {
if (type == ":") return pushContext(state, stream, "prop");
return pass(type, stream, state);
};
states.prop = function(type, stream, state) {
if (type == ";") return popContext(state);
if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
if (type == "}" || type == "{") return popAndPass(type, stream, state);
if (type == "(") return pushContext(state, stream, "parens");
if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
override += " error";
} else if (type == "word") {
wordAsValue(stream);
} else if (type == "interpolation") {
return pushContext(state, stream, "interpolation");
}
return "prop";
};
states.propBlock = function(type, _stream, state) {
if (type == "}") return popContext(state);
if (type == "word") { override = "property"; return "maybeprop"; }
return state.context.type;
};
states.parens = function(type, stream, state) {
if (type == "{" || type == "}") return popAndPass(type, stream, state);
if (type == ")") return popContext(state);
if (type == "(") return pushContext(state, stream, "parens");
if (type == "interpolation") return pushContext(state, stream, "interpolation");
if (type == "word") wordAsValue(stream);
return "parens";
};
states.pseudo = function(type, stream, state) {
if (type == "meta") return "pseudo";
if (type == "word") {
override = "variable-3";
return state.context.type;
}
return pass(type, stream, state);
};
states.documentTypes = function(type, stream, state) {
if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
override = "tag";
return state.context.type;
} else {
return states.atBlock(type, stream, state);
}
};
states.atBlock = function(type, stream, state) {
if (type == "(") return pushContext(state, stream, "atBlock_parens");
if (type == "}" || type == ";") return popAndPass(type, stream, state);
if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
if (type == "interpolation") return pushContext(state, stream, "interpolation");
if (type == "word") {
var word = stream.current().toLowerCase();
if (word == "only" || word == "not" || word == "and" || word == "or")
override = "keyword";
else if (mediaTypes.hasOwnProperty(word))
override = "attribute";
else if (mediaFeatures.hasOwnProperty(word))
override = "property";
else if (mediaValueKeywords.hasOwnProperty(word))
override = "keyword";
else if (propertyKeywords.hasOwnProperty(word))
override = "property";
else if (nonStandardPropertyKeywords.hasOwnProperty(word))
override = "string-2";
else if (valueKeywords.hasOwnProperty(word))
override = "atom";
else if (colorKeywords.hasOwnProperty(word))
override = "keyword";
else
override = "error";
}
return state.context.type;
};
states.atComponentBlock = function(type, stream, state) {
if (type == "}")
return popAndPass(type, stream, state);
if (type == "{")
return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
if (type == "word")
override = "error";
return state.context.type;
};
states.atBlock_parens = function(type, stream, state) {
if (type == ")") return popContext(state);
if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
return states.atBlock(type, stream, state);
};
states.restricted_atBlock_before = function(type, stream, state) {
if (type == "{")
return pushContext(state, stream, "restricted_atBlock");
if (type == "word" && state.stateArg == "@counter-style") {
override = "variable";
return "restricted_atBlock_before";
}
return pass(type, stream, state);
};
states.restricted_atBlock = function(type, stream, state) {
if (type == "}") {
state.stateArg = null;
return popContext(state);
}
if (type == "word") {
if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
(state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
override = "error";
else
override = "property";
return "maybeprop";
}
return "restricted_atBlock";
};
states.keyframes = function(type, stream, state) {
if (type == "word") { override = "variable"; return "keyframes"; }
if (type == "{") return pushContext(state, stream, "top");
return pass(type, stream, state);
};
states.at = function(type, stream, state) {
if (type == ";") return popContext(state);
if (type == "{" || type == "}") return popAndPass(type, stream, state);
if (type == "word") override = "tag";
else if (type == "hash") override = "builtin";
return "at";
};
states.interpolation = function(type, stream, state) {
if (type == "}") return popContext(state);
if (type == "{" || type == ";") return popAndPass(type, stream, state);
if (type == "word") override = "variable";
else if (type != "variable" && type != "(" && type != ")") override = "error";
return "interpolation";
};
return {
startState: function(base) {
return {tokenize: null,
state: inline ? "block" : "top",
stateArg: null,
context: new Context(inline ? "block" : "top", base || 0, null)};
},
token: function(stream, state) {
if (!state.tokenize && stream.eatSpace()) return null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style && typeof style == "object") {
type = style[1];
style = style[0];
}
override = style;
if (type != "comment")
state.state = states[state.state](type, stream, state);
return override;
},
indent: function(state, textAfter) {
var cx = state.context, ch = textAfter && textAfter.charAt(0);
var indent = cx.indent;
if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
if (cx.prev) {
if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
// Resume indentation from parent context.
cx = cx.prev;
indent = cx.indent;
} else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
// Dedent relative to current context.
indent = Math.max(0, cx.indent - indentUnit);
}
}
return indent;
},
electricChars: "}",
blockCommentStart: "/*",
blockCommentEnd: "*/",
blockCommentContinue: " * ",
lineComment: lineComment,
fold: "brace"
};
});
function keySet(array) {
var keys = {};
for (var i = 0; i < array.length; ++i) {
keys[array[i].toLowerCase()] = true;
}
return keys;
}
var documentTypes_ = [
"domain", "regexp", "url", "url-prefix"
], documentTypes = keySet(documentTypes_);
var mediaTypes_ = [
"all", "aural", "braille", "handheld", "print", "projection", "screen",
"tty", "tv", "embossed"
], mediaTypes = keySet(mediaTypes_);
var mediaFeatures_ = [
"width", "min-width", "max-width", "height", "min-height", "max-height",
"device-width", "min-device-width", "max-device-width", "device-height",
"min-device-height", "max-device-height", "aspect-ratio",
"min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
"min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
"max-color", "color-index", "min-color-index", "max-color-index",
"monochrome", "min-monochrome", "max-monochrome", "resolution",
"min-resolution", "max-resolution", "scan", "grid", "orientation",
"device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
"pointer", "any-pointer", "hover", "any-hover"
], mediaFeatures = keySet(mediaFeatures_);
var mediaValueKeywords_ = [
"landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
"interlace", "progressive"
], mediaValueKeywords = keySet(mediaValueKeywords_);
var propertyKeywords_ = [
"align-content", "align-items", "align-self", "alignment-adjust",
"alignment-baseline", "anchor-point", "animation", "animation-delay",
"animation-direction", "animation-duration", "animation-fill-mode",
"animation-iteration-count", "animation-name", "animation-play-state",
"animation-timing-function", "appearance", "azimuth", "backface-visibility",
"background", "background-attachment", "background-blend-mode", "background-clip",
"background-color", "background-image", "background-origin", "background-position",
"background-repeat", "background-size", "baseline-shift", "binding",
"bleed", "bookmark-label", "bookmark-level", "bookmark-state",
"bookmark-target", "border", "border-bottom", "border-bottom-color",
"border-bottom-left-radius", "border-bottom-right-radius",
"border-bottom-style", "border-bottom-width", "border-collapse",
"border-color", "border-image", "border-image-outset",
"border-image-repeat", "border-image-slice", "border-image-source",
"border-image-width", "border-left", "border-left-color",
"border-left-style", "border-left-width", "border-radius", "border-right",
"border-right-color", "border-right-style", "border-right-width",
"border-spacing", "border-style", "border-top", "border-top-color",
"border-top-left-radius", "border-top-right-radius", "border-top-style",
"border-top-width", "border-width", "bottom", "box-decoration-break",
"box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
"caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count",
"column-fill", "column-gap", "column-rule", "column-rule-color",
"column-rule-style", "column-rule-width", "column-span", "column-width",
"columns", "content", "counter-increment", "counter-reset", "crop", "cue",
"cue-after", "cue-before", "cursor", "direction", "display",
"dominant-baseline", "drop-initial-after-adjust",
"drop-initial-after-align", "drop-initial-before-adjust",
"drop-initial-before-align", "drop-initial-size", "drop-initial-value",
"elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
"flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
"float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
"font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
"font-stretch", "font-style", "font-synthesis", "font-variant",
"font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
"font-variant-ligatures", "font-variant-numeric", "font-variant-position",
"font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
"grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap",
"grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap",
"grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns",
"grid-template-rows", "hanging-punctuation", "height", "hyphens",
"icon", "image-orientation", "image-rendering", "image-resolution",
"inline-box-align", "justify-content", "justify-items", "justify-self", "left", "letter-spacing",
"line-break", "line-height", "line-stacking", "line-stacking-ruby",
"line-stacking-shift", "line-stacking-strategy", "list-style",
"list-style-image", "list-style-position", "list-style-type", "margin",
"margin-bottom", "margin-left", "margin-right", "margin-top",
"marks", "marquee-direction", "marquee-loop",
"marquee-play-count", "marquee-speed", "marquee-style", "max-height",
"max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
"nav-left", "nav-right", "nav-up", "object-fit", "object-position",
"opacity", "order", "orphans", "outline",
"outline-color", "outline-offset", "outline-style", "outline-width",
"overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
"padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
"page", "page-break-after", "page-break-before", "page-break-inside",
"page-policy", "pause", "pause-after", "pause-before", "perspective",
"perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position",
"presentation-level", "punctuation-trim", "quotes", "region-break-after",
"region-break-before", "region-break-inside", "region-fragment",
"rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
"right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
"ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
"shape-outside", "size", "speak", "speak-as", "speak-header",
"speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
"tab-size", "table-layout", "target", "target-name", "target-new",
"target-position", "text-align", "text-align-last", "text-decoration",
"text-decoration-color", "text-decoration-line", "text-decoration-skip",
"text-decoration-style", "text-emphasis", "text-emphasis-color",
"text-emphasis-position", "text-emphasis-style", "text-height",
"text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
"text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
"text-wrap", "top", "transform", "transform-origin", "transform-style",
"transition", "transition-delay", "transition-duration",
"transition-property", "transition-timing-function", "unicode-bidi",
"user-select", "vertical-align", "visibility", "voice-balance", "voice-duration",
"voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
"voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break",
"word-spacing", "word-wrap", "z-index",
// SVG-specific
"clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
"flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
"color-interpolation", "color-interpolation-filters",
"color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
"marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
"stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
"stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
"baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
"glyph-orientation-vertical", "text-anchor", "writing-mode"
], propertyKeywords = keySet(propertyKeywords_);
var nonStandardPropertyKeywords_ = [
"scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
"scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
"scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
"searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
"searchfield-results-decoration", "zoom"
], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
var fontProperties_ = [
"font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
"font-stretch", "font-weight", "font-style"
], fontProperties = keySet(fontProperties_);
var counterDescriptors_ = [
"additive-symbols", "fallback", "negative", "pad", "prefix", "range",
"speak-as", "suffix", "symbols", "system"
], counterDescriptors = keySet(counterDescriptors_);
var colorKeywords_ = [
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
"bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
"burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
"cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
"darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
"darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
"darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
"deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
"floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
"gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
"hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
"lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
"lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
"lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
"lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
"maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
"mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
"mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
"navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
"orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
"papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
"purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
"salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
"slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
"teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
"whitesmoke", "yellow", "yellowgreen"
], colorKeywords = keySet(colorKeywords_);
var valueKeywords_ = [
"above", "absolute", "activeborder", "additive", "activecaption", "afar",
"after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
"always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
"arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page",
"avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
"bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
"both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
"buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
"capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
"cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
"cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
"col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
"compact", "condensed", "contain", "content", "contents",
"content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
"cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
"decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
"destination-in", "destination-out", "destination-over", "devanagari", "difference",
"disc", "discard", "disclosure-closed", "disclosure-open", "document",
"dot-dash", "dot-dot-dash",
"dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
"element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
"ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
"ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
"ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
"ethiopic-halehame-gez", "ethiopic-halehame-om-et",
"ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
"ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
"ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
"extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
"forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove",
"gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
"help", "hidden", "hide", "higher", "highlight", "highlighttext",
"hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
"inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
"infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
"inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
"italic", "japanese-formal", "japanese-informal", "justify", "kannada",
"katakana", "katakana-iroha", "keep-all", "khmer",
"korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
"landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
"line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
"local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
"lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
"lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d",
"media-controls-background", "media-current-time-display",
"media-fullscreen-button", "media-mute-button", "media-play-button",
"media-return-to-realtime-button", "media-rewind-button",
"media-seek-back-button", "media-seek-forward-button", "media-slider",
"media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
"media-volume-slider-container", "media-volume-sliderthumb", "medium",
"menu", "menulist", "menulist-button", "menulist-text",
"menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
"mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize",
"narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
"no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
"ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote",
"optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
"outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
"painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
"pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
"progress", "push-button", "radial-gradient", "radio", "read-only",
"read-write", "read-write-plaintext-only", "rectangle", "region",
"relative", "repeat", "repeating-linear-gradient",
"repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
"rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
"rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
"s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
"scroll", "scrollbar", "scroll-position", "se-resize", "searchfield",
"searchfield-cancel-button", "searchfield-decoration",
"searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end",
"semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
"simp-chinese-formal", "simp-chinese-informal", "single",
"skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
"slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
"small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
"source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square",
"square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
"subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table",
"table-caption", "table-cell", "table-column", "table-column-group",
"table-footer-group", "table-header-group", "table-row", "table-row-group",
"tamil",
"telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
"thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
"threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
"tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
"trad-chinese-formal", "trad-chinese-informal", "transform",
"translate", "translate3d", "translateX", "translateY", "translateZ",
"transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up",
"upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
"upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
"var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
"visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
"window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
"xx-large", "xx-small"
], valueKeywords = keySet(valueKeywords_);
var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
.concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
.concat(valueKeywords_);
CodeMirror.registerHelper("hintWords", "css", allWords);
function tokenCComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (maybeEnd && ch == "/") {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return ["comment", "comment"];
}
CodeMirror.defineMIME("text/css", {
documentTypes: documentTypes,
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
fontProperties: fontProperties,
counterDescriptors: counterDescriptors,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
tokenHooks: {
"/": function(stream, state) {
if (!stream.eat("*")) return false;
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
},
name: "css"
});
CodeMirror.defineMIME("text/x-scss", {
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
fontProperties: fontProperties,
allowNested: true,
lineComment: "//",
tokenHooks: {
"/": function(stream, state) {
if (stream.eat("/")) {
stream.skipToEnd();
return ["comment", "comment"];
} else if (stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
} else {
return ["operator", "operator"];
}
},
":": function(stream) {
if (stream.match(/\s*\{/, false))
return [null, null]
return false;
},
"$": function(stream) {
stream.match(/^[\w-]+/);
if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"];
return ["variable-2", "variable"];
},
"#": function(stream) {
if (!stream.eat("{")) return false;
return [null, "interpolation"];
}
},
name: "css",
helperType: "scss"
});
CodeMirror.defineMIME("text/x-less", {
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
fontProperties: fontProperties,
allowNested: true,
lineComment: "//",
tokenHooks: {
"/": function(stream, state) {
if (stream.eat("/")) {
stream.skipToEnd();
return ["comment", "comment"];
} else if (stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
} else {
return ["operator", "operator"];
}
},
"@": function(stream) {
if (stream.eat("{")) return [null, "interpolation"];
if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"];
return ["variable-2", "variable"];
},
"&": function() {
return ["atom", "atom"];
}
},
name: "css",
helperType: "less"
});
CodeMirror.defineMIME("text/x-gss", {
documentTypes: documentTypes,
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
fontProperties: fontProperties,
counterDescriptors: counterDescriptors,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
supportsAtComponent: true,
tokenHooks: {
"/": function(stream, state) {
if (!stream.eat("*")) return false;
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
},
name: "css",
helperType: "gss"
});
});
+152
View File
@@ -0,0 +1,152 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var defaultTags = {
script: [
["lang", /(javascript|babel)/i, "javascript"],
["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"],
["type", /./, "text/plain"],
[null, null, "javascript"]
],
style: [
["lang", /^css$/i, "css"],
["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"],
["type", /./, "text/plain"],
[null, null, "css"]
]
};
function maybeBackup(stream, pat, style) {
var cur = stream.current(), close = cur.search(pat);
if (close > -1) {
stream.backUp(cur.length - close);
} else if (cur.match(/<\/?$/)) {
stream.backUp(cur.length);
if (!stream.match(pat, false)) stream.match(cur);
}
return style;
}
var attrRegexpCache = {};
function getAttrRegexp(attr) {
var regexp = attrRegexpCache[attr];
if (regexp) return regexp;
return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");
}
function getAttrValue(text, attr) {
var match = text.match(getAttrRegexp(attr))
return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : ""
}
function getTagRegexp(tagName, anchored) {
return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i");
}
function addTags(from, to) {
for (var tag in from) {
var dest = to[tag] || (to[tag] = []);
var source = from[tag];
for (var i = source.length - 1; i >= 0; i--)
dest.unshift(source[i])
}
}
function findMatchingMode(tagInfo, tagText) {
for (var i = 0; i < tagInfo.length; i++) {
var spec = tagInfo[i];
if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];
}
}
CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
var htmlMode = CodeMirror.getMode(config, {
name: "xml",
htmlMode: true,
multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
});
var tags = {};
var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;
addTags(defaultTags, tags);
if (configTags) addTags(configTags, tags);
if (configScript) for (var i = configScript.length - 1; i >= 0; i--)
tags.script.unshift(["type", configScript[i].matches, configScript[i].mode])
function html(stream, state) {
var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName
if (tag && !/[<>\s\/]/.test(stream.current()) &&
(tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&
tags.hasOwnProperty(tagName)) {
state.inTag = tagName + " "
} else if (state.inTag && tag && />$/.test(stream.current())) {
var inTag = /^([\S]+) (.*)/.exec(state.inTag)
state.inTag = null
var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2])
var mode = CodeMirror.getMode(config, modeSpec)
var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);
state.token = function (stream, state) {
if (stream.match(endTagA, false)) {
state.token = html;
state.localState = state.localMode = null;
return null;
}
return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
};
state.localMode = mode;
state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, ""));
} else if (state.inTag) {
state.inTag += stream.current()
if (stream.eol()) state.inTag += " "
}
return style;
};
return {
startState: function () {
var state = CodeMirror.startState(htmlMode);
return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};
},
copyState: function (state) {
var local;
if (state.localState) {
local = CodeMirror.copyState(state.localMode, state.localState);
}
return {token: state.token, inTag: state.inTag,
localMode: state.localMode, localState: local,
htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
},
token: function (stream, state) {
return state.token(stream, state);
},
indent: function (state, textAfter, line) {
if (!state.localMode || /^\s*<\//.test(textAfter))
return htmlMode.indent(state.htmlState, textAfter);
else if (state.localMode.indent)
return state.localMode.indent(state.localState, textAfter, line);
else
return CodeMirror.Pass;
},
innerMode: function (state) {
return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
}
};
}, "xml", "javascript", "css");
CodeMirror.defineMIME("text/html", "htmlmixed");
});
+899
View File
@@ -0,0 +1,899 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var statementIndent = parserConfig.statementIndent;
var jsonldMode = parserConfig.jsonld;
var jsonMode = parserConfig.json || jsonldMode;
var isTS = parserConfig.typescript;
var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
return {
"if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
"debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
"function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
"this": kw("this"), "class": kw("class"), "super": kw("atom"),
"yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
"await": C
};
}();
var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
function readRegexp(stream) {
var escaped = false, next, inSet = false;
while ((next = stream.next()) != null) {
if (!escaped) {
if (next == "/" && !inSet) return;
if (next == "[") inSet = true;
else if (inSet && next == "]") inSet = false;
}
escaped = !escaped && next == "\\";
}
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
return ret("number", "number");
} else if (ch == "." && stream.match("..")) {
return ret("spread", "meta");
} else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
return ret(ch);
} else if (ch == "=" && stream.eat(">")) {
return ret("=>", "operator");
} else if (ch == "0" && stream.match(/^(?:x[\da-f]+|o[0-7]+|b[01]+)n?/i)) {
return ret("number", "number");
} else if (/\d/.test(ch)) {
stream.match(/^\d*(?:n|(?:\.\d*)?(?:[eE][+\-]?\d+)?)?/);
return ret("number", "number");
} else if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
} else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
} else if (expressionAllowed(stream, state, 1)) {
readRegexp(stream);
stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
return ret("regexp", "string-2");
} else {
stream.eat("=");
return ret("operator", "operator", stream.current());
}
} else if (ch == "`") {
state.tokenize = tokenQuasi;
return tokenQuasi(stream, state);
} else if (ch == "#") {
stream.skipToEnd();
return ret("error", "error");
} else if (isOperatorChar.test(ch)) {
if (ch != ">" || !state.lexical || state.lexical.type != ">") {
if (stream.eat("=")) {
if (ch == "!" || ch == "=") stream.eat("=")
} else if (/[<>*+\-]/.test(ch)) {
stream.eat(ch)
if (ch == ">") stream.eat(ch)
}
}
return ret("operator", "operator", stream.current());
} else if (wordRE.test(ch)) {
stream.eatWhile(wordRE);
var word = stream.current()
if (state.lastType != ".") {
if (keywords.propertyIsEnumerable(word)) {
var kw = keywords[word]
return ret(kw.type, kw.style, word)
}
if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false))
return ret("async", "keyword", word)
}
return ret("variable", "variable", word)
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next;
if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
state.tokenize = tokenBase;
return ret("jsonld-keyword", "meta");
}
while ((next = stream.next()) != null) {
if (next == quote && !escaped) break;
escaped = !escaped && next == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenQuasi(stream, state) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && next == "\\";
}
return ret("quasi", "string-2", stream.current());
}
var brackets = "([{}])";
// This is a crude lookahead trick to try and notice that we're
// parsing the argument patterns for a fat-arrow function before we
// actually hit the arrow token. It only works if the arrow is on
// the same line as the arguments and there's no strange noise
// (comments) in between. Fallback is to only notice when we hit the
// arrow, and not declare the arguments as locals for the arrow
// body.
function findFatArrow(stream, state) {
if (state.fatArrowAt) state.fatArrowAt = null;
var arrow = stream.string.indexOf("=>", stream.start);
if (arrow < 0) return;
if (isTS) { // Try to skip TypeScript return type declarations after the arguments
var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
if (m) arrow = m.index
}
var depth = 0, sawSomething = false;
for (var pos = arrow - 1; pos >= 0; --pos) {
var ch = stream.string.charAt(pos);
var bracket = brackets.indexOf(ch);
if (bracket >= 0 && bracket < 3) {
if (!depth) { ++pos; break; }
if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
} else if (bracket >= 3 && bracket < 6) {
++depth;
} else if (wordRE.test(ch)) {
sawSomething = true;
} else if (/["'\/]/.test(ch)) {
return;
} else if (sawSomething && !depth) {
++pos;
break;
}
}
if (sawSomething && !depth) state.fatArrowAt = pos;
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
for (var cx = state.context; cx; cx = cx.prev) {
for (var v = cx.vars; v; v = v.next)
if (v.name == varname) return true;
}
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function inList(name, list) {
for (var v = list; v; v = v.next) if (v.name == name) return true
return false;
}
function register(varname) {
var state = cx.state;
cx.marked = "def";
if (state.context) {
if (state.lexical.info == "var" && state.context && state.context.block) {
// FIXME function decls are also not block scoped
var newContext = registerVarScoped(varname, state.context)
if (newContext != null) {
state.context = newContext
return
}
} else if (!inList(varname, state.localVars)) {
state.localVars = new Var(varname, state.localVars)
return
}
}
// Fall through means this is global
if (parserConfig.globalVars && !inList(varname, state.globalVars))
state.globalVars = new Var(varname, state.globalVars)
}
function registerVarScoped(varname, context) {
if (!context) {
return null
} else if (context.block) {
var inner = registerVarScoped(varname, context.prev)
if (!inner) return null
if (inner == context.prev) return context
return new Context(inner, context.vars, true)
} else if (inList(varname, context.vars)) {
return context
} else {
return new Context(context.prev, new Var(varname, context.vars), false)
}
}
function isModifier(name) {
return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
}
// Combinators
function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
function Var(name, next) { this.name = name; this.next = next }
var defaultVars = new Var("this", new Var("arguments", null))
function pushcontext() {
cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
cx.state.localVars = defaultVars
}
function pushblockcontext() {
cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
cx.state.localVars = null
}
function popcontext() {
cx.state.localVars = cx.state.context.vars
cx.state.context = cx.state.context.prev
}
popcontext.lex = true
function pushlex(type, info) {
var result = function() {
var state = cx.state, indent = state.indented;
if (state.lexical.type == "stat") indent = state.lexical.indented;
else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
indent = outer.indented;
state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
function exp(type) {
if (type == wanted) return cont();
else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
else return cont(exp);
};
return exp;
}
function statement(type, value) {
if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
if (type == "debugger") return cont(expect(";"));
if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
if (type == ";") return cont();
if (type == "if") {
if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
cx.state.cc.pop()();
return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
}
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), className, poplex); }
if (type == "variable") {
if (isTS && value == "declare") {
cx.marked = "keyword"
return cont(statement)
} else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
cx.marked = "keyword"
if (value == "enum") return cont(enumdef);
else if (value == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";"));
else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
} else if (isTS && value == "namespace") {
cx.marked = "keyword"
return cont(pushlex("form"), expression, block, poplex)
} else if (isTS && value == "abstract") {
cx.marked = "keyword"
return cont(statement)
} else {
return cont(pushlex("stat"), maybelabel);
}
}
if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
block, poplex, poplex, popcontext);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
if (type == "async") return cont(statement)
if (value == "@") return cont(expression, statement)
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function maybeCatchBinding(type) {
if (type == "(") return cont(funarg, expect(")"))
}
function expression(type, value) {
return expressionInner(type, value, false);
}
function expressionNoComma(type, value) {
return expressionInner(type, value, true);
}
function parenExpr(type) {
if (type != "(") return pass()
return cont(pushlex(")"), expression, expect(")"), poplex)
}
function expressionInner(type, value, noComma) {
if (cx.state.fatArrowAt == cx.stream.start) {
var body = noComma ? arrowBodyNoComma : arrowBody;
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
}
var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
if (type == "function") return cont(functiondef, maybeop);
if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
if (type == "{") return contCommasep(objprop, "}", null, maybeop);
if (type == "quasi") return pass(quasi, maybeop);
if (type == "new") return cont(maybeTarget(noComma));
if (type == "import") return cont(expression);
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeoperatorComma(type, value) {
if (type == ",") return cont(expression);
return maybeoperatorNoComma(type, value, false);
}
function maybeoperatorNoComma(type, value, noComma) {
var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
var expr = noComma == false ? expression : expressionNoComma;
if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
if (type == "operator") {
if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false))
return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
if (value == "?") return cont(expression, expect(":"), expr);
return cont(expr);
}
if (type == "quasi") { return pass(quasi, me); }
if (type == ";") return;
if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
if (type == ".") return cont(property, me);
if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
if (type == "regexp") {
cx.state.lastType = cx.marked = "operator"
cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
return cont(expr)
}
}
function quasi(type, value) {
if (type != "quasi") return pass();
if (value.slice(value.length - 2) != "${") return cont(quasi);
return cont(expression, continueQuasi);
}
function continueQuasi(type) {
if (type == "}") {
cx.marked = "string-2";
cx.state.tokenize = tokenQuasi;
return cont(quasi);
}
}
function arrowBody(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expression);
}
function arrowBodyNoComma(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expressionNoComma);
}
function maybeTarget(noComma) {
return function(type) {
if (type == ".") return cont(noComma ? targetNoComma : target);
else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
else return pass(noComma ? expressionNoComma : expression);
};
}
function target(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
}
function targetNoComma(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperatorComma, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type, value) {
if (type == "async") {
cx.marked = "property";
return cont(objprop);
} else if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
if (value == "get" || value == "set") return cont(getterSetter);
var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
cx.state.fatArrowAt = cx.stream.pos + m[0].length
return cont(afterprop);
} else if (type == "number" || type == "string") {
cx.marked = jsonldMode ? "property" : (cx.style + " property");
return cont(afterprop);
} else if (type == "jsonld-keyword") {
return cont(afterprop);
} else if (isTS && isModifier(value)) {
cx.marked = "keyword"
return cont(objprop)
} else if (type == "[") {
return cont(expression, maybetype, expect("]"), afterprop);
} else if (type == "spread") {
return cont(expressionNoComma, afterprop);
} else if (value == "*") {
cx.marked = "keyword";
return cont(objprop);
} else if (type == ":") {
return pass(afterprop)
}
}
function getterSetter(type) {
if (type != "variable") return pass(afterprop);
cx.marked = "property";
return cont(functiondef);
}
function afterprop(type) {
if (type == ":") return cont(expressionNoComma);
if (type == "(") return pass(functiondef);
}
function commasep(what, end, sep) {
function proceed(type, value) {
if (sep ? sep.indexOf(type) > -1 : type == ",") {
var lex = cx.state.lexical;
if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
return cont(function(type, value) {
if (type == end || value == end) return pass()
return pass(what)
}, proceed);
}
if (type == end || value == end) return cont();
return cont(expect(end));
}
return function(type, value) {
if (type == end || value == end) return cont();
return pass(what, proceed);
};
}
function contCommasep(what, end, info) {
for (var i = 3; i < arguments.length; i++)
cx.cc.push(arguments[i]);
return cont(pushlex(end, info), commasep(what, end), poplex);
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function maybetype(type, value) {
if (isTS) {
if (type == ":") return cont(typeexpr);
if (value == "?") return cont(maybetype);
}
}
function mayberettype(type) {
if (isTS && type == ":") {
if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
else return cont(typeexpr)
}
}
function isKW(_, value) {
if (value == "is") {
cx.marked = "keyword"
return cont()
}
}
function typeexpr(type, value) {
if (value == "keyof" || value == "typeof") {
cx.marked = "keyword"
return cont(value == "keyof" ? typeexpr : expressionNoComma)
}
if (type == "variable" || value == "void") {
cx.marked = "type"
return cont(afterType)
}
if (type == "string" || type == "number" || type == "atom") return cont(afterType);
if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType)
if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
}
function maybeReturnType(type) {
if (type == "=>") return cont(typeexpr)
}
function typeprop(type, value) {
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property"
return cont(typeprop)
} else if (value == "?") {
return cont(typeprop)
} else if (type == ":") {
return cont(typeexpr)
} else if (type == "[") {
return cont(expression, maybetype, expect("]"), typeprop)
}
}
function typearg(type, value) {
if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
if (type == ":") return cont(typeexpr)
return pass(typeexpr)
}
function afterType(type, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
if (value == "|" || type == "." || value == "&") return cont(typeexpr)
if (type == "[") return cont(expect("]"), afterType)
if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
}
function maybeTypeArgs(_, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
}
function typeparam() {
return pass(typeexpr, maybeTypeDefault)
}
function maybeTypeDefault(_, value) {
if (value == "=") return cont(typeexpr)
}
function vardef(_, value) {
if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
return pass(pattern, maybetype, maybeAssign, vardefCont);
}
function pattern(type, value) {
if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
if (type == "variable") { register(value); return cont(); }
if (type == "spread") return cont(pattern);
if (type == "[") return contCommasep(eltpattern, "]");
if (type == "{") return contCommasep(proppattern, "}");
}
function proppattern(type, value) {
if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
register(value);
return cont(maybeAssign);
}
if (type == "variable") cx.marked = "property";
if (type == "spread") return cont(pattern);
if (type == "}") return pass();
return cont(expect(":"), pattern, maybeAssign);
}
function eltpattern() {
return pass(pattern, maybeAssign)
}
function maybeAssign(_type, value) {
if (value == "=") return cont(expressionNoComma);
}
function vardefCont(type) {
if (type == ",") return cont(vardef);
}
function maybeelse(type, value) {
if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
}
function forspec(type, value) {
if (value == "await") return cont(forspec);
if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
}
function forspec1(type) {
if (type == "var") return cont(vardef, expect(";"), forspec2);
if (type == ";") return cont(forspec2);
if (type == "variable") return cont(formaybeinof);
return pass(expression, expect(";"), forspec2);
}
function formaybeinof(_type, value) {
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
return cont(maybeoperatorComma, forspec2);
}
function forspec2(type, value) {
if (type == ";") return cont(forspec3);
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
return pass(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type != ")") cont(expression);
}
function functiondef(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
}
function funarg(type, value) {
if (value == "@") cont(expression, funarg)
if (type == "spread") return cont(funarg);
if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
return pass(pattern, maybetype, maybeAssign);
}
function classExpression(type, value) {
// Class expressions may have an optional name.
if (type == "variable") return className(type, value);
return classNameAfter(type, value);
}
function className(type, value) {
if (type == "variable") {register(value); return cont(classNameAfter);}
}
function classNameAfter(type, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
if (value == "extends" || value == "implements" || (isTS && type == ",")) {
if (value == "implements") cx.marked = "keyword";
return cont(isTS ? typeexpr : expression, classNameAfter);
}
if (type == "{") return cont(pushlex("}"), classBody, poplex);
}
function classBody(type, value) {
if (type == "async" ||
(type == "variable" &&
(value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
cx.marked = "keyword";
return cont(classBody);
}
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
return cont(isTS ? classfield : functiondef, classBody);
}
if (type == "[")
return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody)
if (value == "*") {
cx.marked = "keyword";
return cont(classBody);
}
if (type == ";") return cont(classBody);
if (type == "}") return cont();
if (value == "@") return cont(expression, classBody)
}
function classfield(type, value) {
if (value == "?") return cont(classfield)
if (type == ":") return cont(typeexpr, maybeAssign)
if (value == "=") return cont(expressionNoComma)
return pass(functiondef)
}
function afterExport(type, value) {
if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
return pass(statement);
}
function exportField(type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
if (type == "variable") return pass(expressionNoComma, exportField);
}
function afterImport(type) {
if (type == "string") return cont();
if (type == "(") return pass(expression);
return pass(importSpec, maybeMoreImports, maybeFrom);
}
function importSpec(type, value) {
if (type == "{") return contCommasep(importSpec, "}");
if (type == "variable") register(value);
if (value == "*") cx.marked = "keyword";
return cont(maybeAs);
}
function maybeMoreImports(type) {
if (type == ",") return cont(importSpec, maybeMoreImports)
}
function maybeAs(_type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
}
function maybeFrom(_type, value) {
if (value == "from") { cx.marked = "keyword"; return cont(expression); }
}
function arrayLiteral(type) {
if (type == "]") return cont();
return pass(commasep(expressionNoComma, "]"));
}
function enumdef() {
return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
}
function enummember() {
return pass(pattern, maybeAssign);
}
function isContinuedStatement(state, textAfter) {
return state.lastType == "operator" || state.lastType == "," ||
isOperatorChar.test(textAfter.charAt(0)) ||
/[,.]/.test(textAfter.charAt(0));
}
function expressionAllowed(stream, state, backUp) {
return state.tokenize == tokenBase &&
/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
(state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
}
// Interface
return {
startState: function(basecolumn) {
var state = {
tokenize: tokenBase,
lastType: "sof",
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
context: parserConfig.localVars && new Context(null, null, false),
indented: basecolumn || 0
};
if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
state.globalVars = parserConfig.globalVars;
return state;
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
findFatArrow(stream, state);
}
if (state.tokenize != tokenComment && stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize == tokenComment) return CodeMirror.Pass;
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
// Kludge to prevent 'maybelse' from blocking lexical scope pops
if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
var c = state.cc[i];
if (c == poplex) lexical = lexical.prev;
else if (c != maybeelse) break;
}
while ((lexical.type == "stat" || lexical.type == "form") &&
(firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
(top == maybeoperatorComma || top == maybeoperatorNoComma) &&
!/^[,\.=+\-*:?[\(]/.test(textAfter))))
lexical = lexical.prev;
if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "form") return lexical.indented + indentUnit;
else if (type == "stat")
return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
blockCommentStart: jsonMode ? null : "/*",
blockCommentEnd: jsonMode ? null : "*/",
blockCommentContinue: jsonMode ? null : " * ",
lineComment: jsonMode ? null : "//",
fold: "brace",
closeBrackets: "()[]{}''\"\"``",
helperType: jsonMode ? "json" : "javascript",
jsonldMode: jsonldMode,
jsonMode: jsonMode,
expressionAllowed: expressionAllowed,
skipExpression: function(state) {
var top = state.cc[state.cc.length - 1]
if (top == expression || top == expressionNoComma) state.cc.pop()
}
};
});
CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
});
+53
View File
@@ -0,0 +1,53 @@
/*
Name: material
Author: Michael Kaminsky (http://github.com/mkaminsky11)
Original material color scheme by Mattia Astorino (https://github.com/equinusocio/material-theme)
*/
.cm-s-material.CodeMirror {
background-color: #263238;
color: rgba(233, 237, 237, 1);
}
.cm-s-material .CodeMirror-gutters {
background: #263238;
color: rgb(83,127,126);
border: none;
}
.cm-s-material .CodeMirror-guttermarker, .cm-s-material .CodeMirror-guttermarker-subtle, .cm-s-material .CodeMirror-linenumber { color: rgb(83,127,126); }
.cm-s-material .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }
.cm-s-material div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); }
.cm-s-material.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }
.cm-s-material .CodeMirror-line::selection, .cm-s-material .CodeMirror-line > span::selection, .cm-s-material .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }
.cm-s-material .CodeMirror-line::-moz-selection, .cm-s-material .CodeMirror-line > span::-moz-selection, .cm-s-material .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }
.cm-s-material .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); }
.cm-s-material .cm-keyword { color: rgba(199, 146, 234, 1); }
.cm-s-material .cm-operator { color: rgba(233, 237, 237, 1); }
.cm-s-material .cm-variable-2 { color: #80CBC4; }
.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #82B1FF; }
.cm-s-material .cm-builtin { color: #DECB6B; }
.cm-s-material .cm-atom { color: #F77669; }
.cm-s-material .cm-number { color: #F77669; }
.cm-s-material .cm-def { color: rgba(233, 237, 237, 1); }
.cm-s-material .cm-string { color: #C3E88D; }
.cm-s-material .cm-string-2 { color: #80CBC4; }
.cm-s-material .cm-comment { color: #546E7A; }
.cm-s-material .cm-variable { color: #82B1FF; }
.cm-s-material .cm-tag { color: #80CBC4; }
.cm-s-material .cm-meta { color: #80CBC4; }
.cm-s-material .cm-attribute { color: #FFCB6B; }
.cm-s-material .cm-property { color: #80CBAE; }
.cm-s-material .cm-qualifier { color: #DECB6B; }
.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #DECB6B; }
.cm-s-material .cm-tag { color: rgba(255, 83, 112, 1); }
.cm-s-material .cm-error {
color: rgba(255, 255, 255, 1.0);
background-color: #EC5F67;
}
.cm-s-material .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
+41
View File
@@ -0,0 +1,41 @@
/* Based on Sublime Text's Monokai theme */
.cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; }
.cm-s-monokai div.CodeMirror-selected { background: #49483E; }
.cm-s-monokai .CodeMirror-line::selection, .cm-s-monokai .CodeMirror-line > span::selection, .cm-s-monokai .CodeMirror-line > span > span::selection { background: rgba(73, 72, 62, .99); }
.cm-s-monokai .CodeMirror-line::-moz-selection, .cm-s-monokai .CodeMirror-line > span::-moz-selection, .cm-s-monokai .CodeMirror-line > span > span::-moz-selection { background: rgba(73, 72, 62, .99); }
.cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; }
.cm-s-monokai .CodeMirror-guttermarker { color: white; }
.cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; }
.cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }
.cm-s-monokai span.cm-comment { color: #75715e; }
.cm-s-monokai span.cm-atom { color: #ae81ff; }
.cm-s-monokai span.cm-number { color: #ae81ff; }
.cm-s-monokai span.cm-comment.cm-attribute { color: #97b757; }
.cm-s-monokai span.cm-comment.cm-def { color: #bc9262; }
.cm-s-monokai span.cm-comment.cm-tag { color: #bc6283; }
.cm-s-monokai span.cm-comment.cm-type { color: #5998a6; }
.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; }
.cm-s-monokai span.cm-keyword { color: #f92672; }
.cm-s-monokai span.cm-builtin { color: #66d9ef; }
.cm-s-monokai span.cm-string { color: #e6db74; }
.cm-s-monokai span.cm-variable { color: #f8f8f2; }
.cm-s-monokai span.cm-variable-2 { color: #9effff; }
.cm-s-monokai span.cm-variable-3, .cm-s-monokai span.cm-type { color: #66d9ef; }
.cm-s-monokai span.cm-def { color: #fd971f; }
.cm-s-monokai span.cm-bracket { color: #f8f8f2; }
.cm-s-monokai span.cm-tag { color: #f92672; }
.cm-s-monokai span.cm-header { color: #ae81ff; }
.cm-s-monokai span.cm-link { color: #ae81ff; }
.cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; }
.cm-s-monokai .CodeMirror-activeline-background { background: #373831; }
.cm-s-monokai .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
+409
View File
@@ -0,0 +1,409 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var wordOperators = wordRegexp(["and", "or", "not", "is"]);
var commonKeywords = ["as", "assert", "break", "class", "continue",
"def", "del", "elif", "else", "except", "finally",
"for", "from", "global", "if", "import",
"lambda", "pass", "raise", "return",
"try", "while", "with", "yield", "in"];
var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
"classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "filter", "float", "format", "frozenset",
"getattr", "globals", "hasattr", "hash", "help", "hex", "id",
"input", "int", "isinstance", "issubclass", "iter", "len",
"list", "locals", "map", "max", "memoryview", "min", "next",
"object", "oct", "open", "ord", "pow", "property", "range",
"repr", "reversed", "round", "set", "setattr", "slice",
"sorted", "staticmethod", "str", "sum", "super", "tuple",
"type", "vars", "zip", "__import__", "NotImplemented",
"Ellipsis", "__debug__"];
CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
function top(state) {
return state.scopes[state.scopes.length - 1];
}
CodeMirror.defineMode("python", function(conf, parserConf) {
var ERRORCLASS = "error";
var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;
// (Backwards-compatiblity with old, cumbersome config system)
var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@])/]
for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)
var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
if (parserConf.extra_keywords != undefined)
myKeywords = myKeywords.concat(parserConf.extra_keywords);
if (parserConf.extra_builtins != undefined)
myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
var py3 = !(parserConf.version && Number(parserConf.version) < 3)
if (py3) {
// since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
var stringPrefixes = new RegExp("^(([rbuf]|(br)|(fr))?('{3}|\"{3}|['\"]))", "i");
} else {
var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
myKeywords = myKeywords.concat(["exec", "print"]);
myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
"file", "intern", "long", "raw_input", "reduce", "reload",
"unichr", "unicode", "xrange", "False", "True", "None"]);
var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
}
var keywords = wordRegexp(myKeywords);
var builtins = wordRegexp(myBuiltins);
// tokenizers
function tokenBase(stream, state) {
var sol = stream.sol() && state.lastToken != "\\"
if (sol) state.indent = stream.indentation()
// Handle scope changes
if (sol && top(state).type == "py") {
var scopeOffset = top(state).offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset)
pushPyScope(state);
else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
state.errorToken = true;
return null;
} else {
var style = tokenBaseInner(stream, state);
if (scopeOffset > 0 && dedent(stream, state))
style += " " + ERRORCLASS;
return style;
}
}
return tokenBaseInner(stream, state);
}
function tokenBaseInner(stream, state) {
if (stream.eatSpace()) return null;
// Handle Comments
if (stream.match(/^#.*/)) return "comment";
// Handle Number Literals
if (stream.match(/^[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
if (stream.match(/^\.\d+/)) { floatLiteral = true; }
if (floatLiteral) {
// Float literals may be "imaginary"
stream.eat(/J/i);
return "number";
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
// Binary
if (stream.match(/^0b[01_]+/i)) intLiteral = true;
// Octal
if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
// Decimal
if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
// Decimal literals may be "imaginary"
stream.eat(/J/i);
// TODO - Can you have imaginary longs?
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
if (intLiteral) {
// Integer literals may be "long"
stream.eat(/L/i);
return "number";
}
}
// Handle Strings
if (stream.match(stringPrefixes)) {
var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;
if (!isFmtString) {
state.tokenize = tokenStringFactory(stream.current());
return state.tokenize(stream, state);
} else {
state.tokenize = formatStringFactory(stream.current(), state.tokenize);
return state.tokenize(stream, state);
}
}
for (var i = 0; i < operators.length; i++)
if (stream.match(operators[i])) return "operator"
if (stream.match(delimiters)) return "punctuation";
if (state.lastToken == "." && stream.match(identifiers))
return "property";
if (stream.match(keywords) || stream.match(wordOperators))
return "keyword";
if (stream.match(builtins))
return "builtin";
if (stream.match(/^(self|cls)\b/))
return "variable-2";
if (stream.match(identifiers)) {
if (state.lastToken == "def" || state.lastToken == "class")
return "def";
return "variable";
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function formatStringFactory(delimiter, tokenOuter) {
while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
delimiter = delimiter.substr(1);
var singleline = delimiter.length == 1;
var OUTCLASS = "string";
function tokenFString(stream, state) {
// inside f-str Expression
if (stream.match(delimiter)) {
// expression ends pre-maturally, but very common in editing
// Could show error to remind users to close brace here
state.tokenize = tokenString
return OUTCLASS;
} else if (stream.match('{')) {
// starting brace, if not eaten below
return "punctuation";
} else if (stream.match('}')) {
// return to regular inside string state
state.tokenize = tokenString
return "punctuation";
} else {
// use tokenBaseInner to parse the expression
return tokenBaseInner(stream, state);
}
}
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\{\}\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol())
return OUTCLASS;
} else if (stream.match(delimiter)) {
state.tokenize = tokenOuter;
return OUTCLASS;
} else if (stream.match('{{')) {
// ignore {{ in f-str
return OUTCLASS;
} else if (stream.match('{', false)) {
// switch to nested mode
state.tokenize = tokenFString
if (stream.current()) {
return OUTCLASS;
} else {
// need to return something, so eat the starting {
stream.next();
return "punctuation";
}
} else if (stream.match('}}')) {
return OUTCLASS;
} else if (stream.match('}')) {
// single } in f-string is an error
return ERRORCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors)
return ERRORCLASS;
else
state.tokenize = tokenOuter;
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function tokenStringFactory(delimiter) {
while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
delimiter = delimiter.substr(1);
var singleline = delimiter.length == 1;
var OUTCLASS = "string";
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol())
return OUTCLASS;
} else if (stream.match(delimiter)) {
state.tokenize = tokenBase;
return OUTCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors)
return ERRORCLASS;
else
state.tokenize = tokenBase;
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function pushPyScope(state) {
while (top(state).type != "py") state.scopes.pop()
state.scopes.push({offset: top(state).offset + conf.indentUnit,
type: "py",
align: null})
}
function pushBracketScope(stream, state, type) {
var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1
state.scopes.push({offset: state.indent + hangingIndent,
type: type,
align: align})
}
function dedent(stream, state) {
var indented = stream.indentation();
while (state.scopes.length > 1 && top(state).offset > indented) {
if (top(state).type != "py") return true;
state.scopes.pop();
}
return top(state).offset != indented;
}
function tokenLexer(stream, state) {
if (stream.sol()) state.beginningOfLine = true;
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle decorators
if (state.beginningOfLine && current == "@")
return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;
if (/\S/.test(current)) state.beginningOfLine = false;
if ((style == "variable" || style == "builtin")
&& state.lastToken == "meta")
style = "meta";
// Handle scope changes.
if (current == "pass" || current == "return")
state.dedent += 1;
if (current == "lambda") state.lambda = true;
if (current == ":" && !state.lambda && top(state).type == "py")
pushPyScope(state);
if (current.length == 1 && !/string|comment/.test(style)) {
var delimiter_index = "[({".indexOf(current);
if (delimiter_index != -1)
pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
delimiter_index = "])}".indexOf(current);
if (delimiter_index != -1) {
if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
else return ERRORCLASS;
}
}
if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
if (state.scopes.length > 1) state.scopes.pop();
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset: basecolumn || 0, type: "py", align: null}],
indent: basecolumn || 0,
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var addErr = state.errorToken;
if (addErr) state.errorToken = false;
var style = tokenLexer(stream, state);
if (style && style != "comment")
state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
if (style == "punctuation") style = null;
if (stream.eol() && state.lambda)
state.lambda = false;
return addErr ? style + " " + ERRORCLASS : style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase)
return state.tokenize.isString ? CodeMirror.Pass : 0;
var scope = top(state), closing = scope.type == textAfter.charAt(0)
if (scope.align != null)
return scope.align - (closing ? 1 : 0)
else
return scope.offset - (closing ? hangingIndent : 0)
},
electricInput: /^\s*[\}\]\)]$/,
closeBrackets: {triples: "'\""},
lineComment: "#",
fold: "indent"
};
return external;
});
CodeMirror.defineMIME("text/x-python", "python");
var words = function(str) { return str.split(" "); };
CodeMirror.defineMIME("text/x-cython", {
name: "python",
extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
"extern gil include nogil property public "+
"readonly struct union DEF IF ELIF ELSE")
});
});
+402
View File
@@ -0,0 +1,402 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var htmlConfig = {
autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
'track': true, 'wbr': true, 'menuitem': true},
implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
'th': true, 'tr': true},
contextGrabbers: {
'dd': {'dd': true, 'dt': true},
'dt': {'dd': true, 'dt': true},
'li': {'li': true},
'option': {'option': true, 'optgroup': true},
'optgroup': {'optgroup': true},
'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
'rp': {'rp': true, 'rt': true},
'rt': {'rp': true, 'rt': true},
'tbody': {'tbody': true, 'tfoot': true},
'td': {'td': true, 'th': true},
'tfoot': {'tbody': true},
'th': {'td': true, 'th': true},
'thead': {'tbody': true, 'tfoot': true},
'tr': {'tr': true}
},
doNotIndent: {"pre": true},
allowUnquoted: true,
allowMissing: true,
caseFold: true
}
var xmlConfig = {
autoSelfClosers: {},
implicitlyClosed: {},
contextGrabbers: {},
doNotIndent: {},
allowUnquoted: false,
allowMissing: false,
allowMissingTagName: false,
caseFold: false
}
CodeMirror.defineMode("xml", function(editorConf, config_) {
var indentUnit = editorConf.indentUnit
var config = {}
var defaults = config_.htmlMode ? htmlConfig : xmlConfig
for (var prop in defaults) config[prop] = defaults[prop]
for (var prop in config_) config[prop] = config_[prop]
// Return variables for tokenizers
var type, setStyle;
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var ch = stream.next();
if (ch == "<") {
if (stream.eat("!")) {
if (stream.eat("[")) {
if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
else return null;
} else if (stream.match("--")) {
return chain(inBlock("comment", "-->"));
} else if (stream.match("DOCTYPE", true, true)) {
stream.eatWhile(/[\w\._\-]/);
return chain(doctype(1));
} else {
return null;
}
} else if (stream.eat("?")) {
stream.eatWhile(/[\w\._\-]/);
state.tokenize = inBlock("meta", "?>");
return "meta";
} else {
type = stream.eat("/") ? "closeTag" : "openTag";
state.tokenize = inTag;
return "tag bracket";
}
} else if (ch == "&") {
var ok;
if (stream.eat("#")) {
if (stream.eat("x")) {
ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
} else {
ok = stream.eatWhile(/[\d]/) && stream.eat(";");
}
} else {
ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
}
return ok ? "atom" : "error";
} else {
stream.eatWhile(/[^&<]/);
return null;
}
}
inText.isInText = true;
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.tokenize = inText;
type = ch == ">" ? "endTag" : "selfcloseTag";
return "tag bracket";
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = inText;
state.state = baseState;
state.tagName = state.tagStart = null;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
state.stringStartCol = stream.column();
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
function inAttribute(quote) {
var closure = function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inTag;
break;
}
}
return "string";
};
closure.isInAttribute = true;
return closure;
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
return style;
}
}
function doctype(depth) {
return function(stream, state) {
var ch;
while ((ch = stream.next()) != null) {
if (ch == "<") {
state.tokenize = doctype(depth + 1);
return state.tokenize(stream, state);
} else if (ch == ">") {
if (depth == 1) {
state.tokenize = inText;
break;
} else {
state.tokenize = doctype(depth - 1);
return state.tokenize(stream, state);
}
}
}
return "meta";
};
}
function Context(state, tagName, startOfLine) {
this.prev = state.context;
this.tagName = tagName;
this.indent = state.indented;
this.startOfLine = startOfLine;
if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
this.noIndent = true;
}
function popContext(state) {
if (state.context) state.context = state.context.prev;
}
function maybePopContext(state, nextTagName) {
var parentTagName;
while (true) {
if (!state.context) {
return;
}
parentTagName = state.context.tagName;
if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
!config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
return;
}
popContext(state);
}
}
function baseState(type, stream, state) {
if (type == "openTag") {
state.tagStart = stream.column();
return tagNameState;
} else if (type == "closeTag") {
return closeTagNameState;
} else {
return baseState;
}
}
function tagNameState(type, stream, state) {
if (type == "word") {
state.tagName = stream.current();
setStyle = "tag";
return attrState;
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return attrState(type, stream, state);
} else {
setStyle = "error";
return tagNameState;
}
}
function closeTagNameState(type, stream, state) {
if (type == "word") {
var tagName = stream.current();
if (state.context && state.context.tagName != tagName &&
config.implicitlyClosed.hasOwnProperty(state.context.tagName))
popContext(state);
if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
setStyle = "tag";
return closeState;
} else {
setStyle = "tag error";
return closeStateErr;
}
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return closeState(type, stream, state);
} else {
setStyle = "error";
return closeStateErr;
}
}
function closeState(type, _stream, state) {
if (type != "endTag") {
setStyle = "error";
return closeState;
}
popContext(state);
return baseState;
}
function closeStateErr(type, stream, state) {
setStyle = "error";
return closeState(type, stream, state);
}
function attrState(type, _stream, state) {
if (type == "word") {
setStyle = "attribute";
return attrEqState;
} else if (type == "endTag" || type == "selfcloseTag") {
var tagName = state.tagName, tagStart = state.tagStart;
state.tagName = state.tagStart = null;
if (type == "selfcloseTag" ||
config.autoSelfClosers.hasOwnProperty(tagName)) {
maybePopContext(state, tagName);
} else {
maybePopContext(state, tagName);
state.context = new Context(state, tagName, tagStart == state.indented);
}
return baseState;
}
setStyle = "error";
return attrState;
}
function attrEqState(type, stream, state) {
if (type == "equals") return attrValueState;
if (!config.allowMissing) setStyle = "error";
return attrState(type, stream, state);
}
function attrValueState(type, stream, state) {
if (type == "string") return attrContinuedState;
if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
setStyle = "error";
return attrState(type, stream, state);
}
function attrContinuedState(type, stream, state) {
if (type == "string") return attrContinuedState;
return attrState(type, stream, state);
}
return {
startState: function(baseIndent) {
var state = {tokenize: inText,
state: baseState,
indented: baseIndent || 0,
tagName: null, tagStart: null,
context: null}
if (baseIndent != null) state.baseIndent = baseIndent
return state
},
token: function(stream, state) {
if (!state.tagName && stream.sol())
state.indented = stream.indentation();
if (stream.eatSpace()) return null;
type = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
setStyle = null;
state.state = state.state(type || style, stream, state);
if (setStyle)
style = setStyle == "error" ? style + " error" : setStyle;
}
return style;
},
indent: function(state, textAfter, fullLine) {
var context = state.context;
// Indent multi-line strings (e.g. css).
if (state.tokenize.isInAttribute) {
if (state.tagStart == state.indented)
return state.stringStartCol + 1;
else
return state.indented + indentUnit;
}
if (context && context.noIndent) return CodeMirror.Pass;
if (state.tokenize != inTag && state.tokenize != inText)
return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
// Indent the starts of attribute names.
if (state.tagName) {
if (config.multilineTagIndentPastTag !== false)
return state.tagStart + state.tagName.length + 2;
else
return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
}
if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
if (tagAfter && tagAfter[1]) { // Closing tag spotted
while (context) {
if (context.tagName == tagAfter[2]) {
context = context.prev;
break;
} else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
context = context.prev;
} else {
break;
}
}
} else if (tagAfter) { // Opening tag spotted
while (context) {
var grabbers = config.contextGrabbers[context.tagName];
if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
context = context.prev;
else
break;
}
}
while (context && context.prev && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return state.baseIndent || 0;
},
electricInput: /<\/[\s\w:]+>$/,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
configuration: config.htmlMode ? "html" : "xml",
helperType: config.htmlMode ? "html" : "xml",
skipAttribute: function(state) {
if (state.state == attrValueState)
state.state = attrState
}
};
});
CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
});
BIN
View File
Binary file not shown.
@@ -0,0 +1,63 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
// declare global: JSHINT
function validator(text, options) {
if (!window.JSHINT) {
if (window.console) {
window.console.error("Error: window.JSHINT not defined, CodeMirror JavaScript linting cannot run.");
}
return [];
}
if (!options.indent) // JSHint error.character actually is a column index, this fixes underlining on lines using tabs for indentation
options.indent = 1; // JSHint default value is 4
JSHINT(text, options, options.globals);
var errors = JSHINT.data().errors, result = [];
if (errors) parseErrors(errors, result);
return result;
}
CodeMirror.registerHelper("lint", "javascript", validator);
function parseErrors(errors, output) {
for ( var i = 0; i < errors.length; i++) {
var error = errors[i];
if (error) {
if (error.line <= 0) {
if (window.console) {
window.console.warn("Cannot display JSHint error (invalid line " + error.line + ")", error);
}
continue;
}
var start = error.character - 1, end = start + 1;
if (error.evidence) {
var index = error.evidence.substring(start).search(/.\b/);
if (index > -1) {
end += index;
}
}
// Convert to format expected by validation service
var hint = {
message: error.reason,
severity: error.code ? (error.code.startsWith('W') ? "warning" : "error") : "error",
from: CodeMirror.Pos(error.line - 1, start),
to: CodeMirror.Pos(error.line - 1, end)
};
output.push(hint);
}
}
}
});
+349
View File
@@ -0,0 +1,349 @@
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
color: black;
direction: ltr;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre.CodeMirror-line,
.CodeMirror pre.CodeMirror-line-like {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
white-space: nowrap;
}
.CodeMirror-guttermarker { color: black; }
.CodeMirror-guttermarker-subtle { color: #999; }
/* CURSOR */
.CodeMirror-cursor {
border-left: 1px solid black;
border-right: none;
width: 0;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.cm-fat-cursor .CodeMirror-cursor {
width: auto;
border: 0 !important;
background: #7e7;
}
.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-fat-cursor-mark {
background-color: rgba(20, 255, 20, 0.5);
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
}
.cm-animate-fat-cursor {
width: auto;
border: 0;
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
background-color: #7e7;
}
@-moz-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@-webkit-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
/* Can style cursor different in overwrite (non-insert) mode */
.CodeMirror-overwrite .CodeMirror-cursor {}
.cm-tab { display: inline-block; text-decoration: inherit; }
.CodeMirror-rulers {
position: absolute;
left: 0; right: 0; top: -50px; bottom: 0;
overflow: hidden;
}
.CodeMirror-ruler {
border-left: 1px solid #ccc;
top: 0; bottom: 0;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-strikethrough {text-decoration: line-through;}
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-s-default .cm-error {color: #f00;}
.cm-invalidchar {color: #f00;}
.CodeMirror-composing { border-bottom: 2px solid; }
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}
.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
.CodeMirror-activeline-background {background: #e8f2ff;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -30px; margin-right: -30px;
padding-bottom: 30px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
}
.CodeMirror-sizer {
position: relative;
border-right: 30px solid transparent;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actual scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0; bottom: 0;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
min-height: 100%;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
display: inline-block;
vertical-align: top;
margin-bottom: -30px;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
background: none !important;
border: none !important;
}
.CodeMirror-gutter-background {
position: absolute;
top: 0; bottom: 0;
z-index: 4;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper ::selection { background-color: transparent }
.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre.CodeMirror-line,
.CodeMirror pre.CodeMirror-line-like {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
-webkit-font-variant-ligatures: contextual;
font-variant-ligatures: contextual;
}
.CodeMirror-wrap pre.CodeMirror-line,
.CodeMirror-wrap pre.CodeMirror-line-like {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
padding: 0.1px; /* Force widget margins to stay inside of the container */
}
.CodeMirror-widget {}
.CodeMirror-rtl pre { direction: rtl; }
.CodeMirror-code {
outline: none;
}
/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-cursor {
position: absolute;
pointer-events: none;
}
.CodeMirror-measure pre { position: static; }
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
div.CodeMirror-dragcursors {
visibility: visible;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
.cm-searching {
background-color: #ffa;
background-color: rgba(255, 255, 0, .4);
}
/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after { content: ''; }
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext { background: none; }
File diff suppressed because it is too large Load Diff
+831
View File
@@ -0,0 +1,831 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("css", function(config, parserConfig) {
var inline = parserConfig.inline
if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
var indentUnit = config.indentUnit,
tokenHooks = parserConfig.tokenHooks,
documentTypes = parserConfig.documentTypes || {},
mediaTypes = parserConfig.mediaTypes || {},
mediaFeatures = parserConfig.mediaFeatures || {},
mediaValueKeywords = parserConfig.mediaValueKeywords || {},
propertyKeywords = parserConfig.propertyKeywords || {},
nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
fontProperties = parserConfig.fontProperties || {},
counterDescriptors = parserConfig.counterDescriptors || {},
colorKeywords = parserConfig.colorKeywords || {},
valueKeywords = parserConfig.valueKeywords || {},
allowNested = parserConfig.allowNested,
lineComment = parserConfig.lineComment,
supportsAtComponent = parserConfig.supportsAtComponent === true;
var type, override;
function ret(style, tp) { type = tp; return style; }
// Tokenizers
function tokenBase(stream, state) {
var ch = stream.next();
if (tokenHooks[ch]) {
var result = tokenHooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == "@") {
stream.eatWhile(/[\w\\\-]/);
return ret("def", stream.current());
} else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
return ret(null, "compare");
} else if (ch == "\"" || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "#") {
stream.eatWhile(/[\w\\\-]/);
return ret("atom", "hash");
} else if (ch == "!") {
stream.match(/^\s*\w*/);
return ret("keyword", "important");
} else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (ch === "-") {
if (/[\d.]/.test(stream.peek())) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (stream.match(/^-[\w\\\-]*/)) {
stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false))
return ret("variable-2", "variable-definition");
return ret("variable-2", "variable");
} else if (stream.match(/^\w+-/)) {
return ret("meta", "meta");
}
} else if (/[,+>*\/]/.test(ch)) {
return ret(null, "select-op");
} else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
return ret("qualifier", "qualifier");
} else if (/[:;{}\[\]\(\)]/.test(ch)) {
return ret(null, ch);
} else if (stream.match(/[\w-.]+(?=\()/)) {
if (/^(url(-prefix)?|domain|regexp)$/.test(stream.current().toLowerCase())) {
state.tokenize = tokenParenthesized;
}
return ret("variable callee", "variable");
} else if (/[\w\\\-]/.test(ch)) {
stream.eatWhile(/[\w\\\-]/);
return ret("property", "word");
} else {
return ret(null, null);
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) {
if (quote == ")") stream.backUp(1);
break;
}
escaped = !escaped && ch == "\\";
}
if (ch == quote || !escaped && quote != ")") state.tokenize = null;
return ret("string", "string");
};
}
function tokenParenthesized(stream, state) {
stream.next(); // Must be '('
if (!stream.match(/\s*[\"\')]/, false))
state.tokenize = tokenString(")");
else
state.tokenize = null;
return ret(null, "(");
}
// Context management
function Context(type, indent, prev) {
this.type = type;
this.indent = indent;
this.prev = prev;
}
function pushContext(state, stream, type, indent) {
state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
return type;
}
function popContext(state) {
if (state.context.prev)
state.context = state.context.prev;
return state.context.type;
}
function pass(type, stream, state) {
return states[state.context.type](type, stream, state);
}
function popAndPass(type, stream, state, n) {
for (var i = n || 1; i > 0; i--)
state.context = state.context.prev;
return pass(type, stream, state);
}
// Parser
function wordAsValue(stream) {
var word = stream.current().toLowerCase();
if (valueKeywords.hasOwnProperty(word))
override = "atom";
else if (colorKeywords.hasOwnProperty(word))
override = "keyword";
else
override = "variable";
}
var states = {};
states.top = function(type, stream, state) {
if (type == "{") {
return pushContext(state, stream, "block");
} else if (type == "}" && state.context.prev) {
return popContext(state);
} else if (supportsAtComponent && /@component/i.test(type)) {
return pushContext(state, stream, "atComponentBlock");
} else if (/^@(-moz-)?document$/i.test(type)) {
return pushContext(state, stream, "documentTypes");
} else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
return pushContext(state, stream, "atBlock");
} else if (/^@(font-face|counter-style)/i.test(type)) {
state.stateArg = type;
return "restricted_atBlock_before";
} else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
return "keyframes";
} else if (type && type.charAt(0) == "@") {
return pushContext(state, stream, "at");
} else if (type == "hash") {
override = "builtin";
} else if (type == "word") {
override = "tag";
} else if (type == "variable-definition") {
return "maybeprop";
} else if (type == "interpolation") {
return pushContext(state, stream, "interpolation");
} else if (type == ":") {
return "pseudo";
} else if (allowNested && type == "(") {
return pushContext(state, stream, "parens");
}
return state.context.type;
};
states.block = function(type, stream, state) {
if (type == "word") {
var word = stream.current().toLowerCase();
if (propertyKeywords.hasOwnProperty(word)) {
override = "property";
return "maybeprop";
} else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
override = "string-2";
return "maybeprop";
} else if (allowNested) {
override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
return "block";
} else {
override += " error";
return "maybeprop";
}
} else if (type == "meta") {
return "block";
} else if (!allowNested && (type == "hash" || type == "qualifier")) {
override = "error";
return "block";
} else {
return states.top(type, stream, state);
}
};
states.maybeprop = function(type, stream, state) {
if (type == ":") return pushContext(state, stream, "prop");
return pass(type, stream, state);
};
states.prop = function(type, stream, state) {
if (type == ";") return popContext(state);
if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
if (type == "}" || type == "{") return popAndPass(type, stream, state);
if (type == "(") return pushContext(state, stream, "parens");
if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
override += " error";
} else if (type == "word") {
wordAsValue(stream);
} else if (type == "interpolation") {
return pushContext(state, stream, "interpolation");
}
return "prop";
};
states.propBlock = function(type, _stream, state) {
if (type == "}") return popContext(state);
if (type == "word") { override = "property"; return "maybeprop"; }
return state.context.type;
};
states.parens = function(type, stream, state) {
if (type == "{" || type == "}") return popAndPass(type, stream, state);
if (type == ")") return popContext(state);
if (type == "(") return pushContext(state, stream, "parens");
if (type == "interpolation") return pushContext(state, stream, "interpolation");
if (type == "word") wordAsValue(stream);
return "parens";
};
states.pseudo = function(type, stream, state) {
if (type == "meta") return "pseudo";
if (type == "word") {
override = "variable-3";
return state.context.type;
}
return pass(type, stream, state);
};
states.documentTypes = function(type, stream, state) {
if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
override = "tag";
return state.context.type;
} else {
return states.atBlock(type, stream, state);
}
};
states.atBlock = function(type, stream, state) {
if (type == "(") return pushContext(state, stream, "atBlock_parens");
if (type == "}" || type == ";") return popAndPass(type, stream, state);
if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
if (type == "interpolation") return pushContext(state, stream, "interpolation");
if (type == "word") {
var word = stream.current().toLowerCase();
if (word == "only" || word == "not" || word == "and" || word == "or")
override = "keyword";
else if (mediaTypes.hasOwnProperty(word))
override = "attribute";
else if (mediaFeatures.hasOwnProperty(word))
override = "property";
else if (mediaValueKeywords.hasOwnProperty(word))
override = "keyword";
else if (propertyKeywords.hasOwnProperty(word))
override = "property";
else if (nonStandardPropertyKeywords.hasOwnProperty(word))
override = "string-2";
else if (valueKeywords.hasOwnProperty(word))
override = "atom";
else if (colorKeywords.hasOwnProperty(word))
override = "keyword";
else
override = "error";
}
return state.context.type;
};
states.atComponentBlock = function(type, stream, state) {
if (type == "}")
return popAndPass(type, stream, state);
if (type == "{")
return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
if (type == "word")
override = "error";
return state.context.type;
};
states.atBlock_parens = function(type, stream, state) {
if (type == ")") return popContext(state);
if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
return states.atBlock(type, stream, state);
};
states.restricted_atBlock_before = function(type, stream, state) {
if (type == "{")
return pushContext(state, stream, "restricted_atBlock");
if (type == "word" && state.stateArg == "@counter-style") {
override = "variable";
return "restricted_atBlock_before";
}
return pass(type, stream, state);
};
states.restricted_atBlock = function(type, stream, state) {
if (type == "}") {
state.stateArg = null;
return popContext(state);
}
if (type == "word") {
if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
(state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
override = "error";
else
override = "property";
return "maybeprop";
}
return "restricted_atBlock";
};
states.keyframes = function(type, stream, state) {
if (type == "word") { override = "variable"; return "keyframes"; }
if (type == "{") return pushContext(state, stream, "top");
return pass(type, stream, state);
};
states.at = function(type, stream, state) {
if (type == ";") return popContext(state);
if (type == "{" || type == "}") return popAndPass(type, stream, state);
if (type == "word") override = "tag";
else if (type == "hash") override = "builtin";
return "at";
};
states.interpolation = function(type, stream, state) {
if (type == "}") return popContext(state);
if (type == "{" || type == ";") return popAndPass(type, stream, state);
if (type == "word") override = "variable";
else if (type != "variable" && type != "(" && type != ")") override = "error";
return "interpolation";
};
return {
startState: function(base) {
return {tokenize: null,
state: inline ? "block" : "top",
stateArg: null,
context: new Context(inline ? "block" : "top", base || 0, null)};
},
token: function(stream, state) {
if (!state.tokenize && stream.eatSpace()) return null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style && typeof style == "object") {
type = style[1];
style = style[0];
}
override = style;
if (type != "comment")
state.state = states[state.state](type, stream, state);
return override;
},
indent: function(state, textAfter) {
var cx = state.context, ch = textAfter && textAfter.charAt(0);
var indent = cx.indent;
if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
if (cx.prev) {
if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
// Resume indentation from parent context.
cx = cx.prev;
indent = cx.indent;
} else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
// Dedent relative to current context.
indent = Math.max(0, cx.indent - indentUnit);
}
}
return indent;
},
electricChars: "}",
blockCommentStart: "/*",
blockCommentEnd: "*/",
blockCommentContinue: " * ",
lineComment: lineComment,
fold: "brace"
};
});
function keySet(array) {
var keys = {};
for (var i = 0; i < array.length; ++i) {
keys[array[i].toLowerCase()] = true;
}
return keys;
}
var documentTypes_ = [
"domain", "regexp", "url", "url-prefix"
], documentTypes = keySet(documentTypes_);
var mediaTypes_ = [
"all", "aural", "braille", "handheld", "print", "projection", "screen",
"tty", "tv", "embossed"
], mediaTypes = keySet(mediaTypes_);
var mediaFeatures_ = [
"width", "min-width", "max-width", "height", "min-height", "max-height",
"device-width", "min-device-width", "max-device-width", "device-height",
"min-device-height", "max-device-height", "aspect-ratio",
"min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
"min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
"max-color", "color-index", "min-color-index", "max-color-index",
"monochrome", "min-monochrome", "max-monochrome", "resolution",
"min-resolution", "max-resolution", "scan", "grid", "orientation",
"device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
"pointer", "any-pointer", "hover", "any-hover"
], mediaFeatures = keySet(mediaFeatures_);
var mediaValueKeywords_ = [
"landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
"interlace", "progressive"
], mediaValueKeywords = keySet(mediaValueKeywords_);
var propertyKeywords_ = [
"align-content", "align-items", "align-self", "alignment-adjust",
"alignment-baseline", "anchor-point", "animation", "animation-delay",
"animation-direction", "animation-duration", "animation-fill-mode",
"animation-iteration-count", "animation-name", "animation-play-state",
"animation-timing-function", "appearance", "azimuth", "backface-visibility",
"background", "background-attachment", "background-blend-mode", "background-clip",
"background-color", "background-image", "background-origin", "background-position",
"background-repeat", "background-size", "baseline-shift", "binding",
"bleed", "bookmark-label", "bookmark-level", "bookmark-state",
"bookmark-target", "border", "border-bottom", "border-bottom-color",
"border-bottom-left-radius", "border-bottom-right-radius",
"border-bottom-style", "border-bottom-width", "border-collapse",
"border-color", "border-image", "border-image-outset",
"border-image-repeat", "border-image-slice", "border-image-source",
"border-image-width", "border-left", "border-left-color",
"border-left-style", "border-left-width", "border-radius", "border-right",
"border-right-color", "border-right-style", "border-right-width",
"border-spacing", "border-style", "border-top", "border-top-color",
"border-top-left-radius", "border-top-right-radius", "border-top-style",
"border-top-width", "border-width", "bottom", "box-decoration-break",
"box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
"caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count",
"column-fill", "column-gap", "column-rule", "column-rule-color",
"column-rule-style", "column-rule-width", "column-span", "column-width",
"columns", "content", "counter-increment", "counter-reset", "crop", "cue",
"cue-after", "cue-before", "cursor", "direction", "display",
"dominant-baseline", "drop-initial-after-adjust",
"drop-initial-after-align", "drop-initial-before-adjust",
"drop-initial-before-align", "drop-initial-size", "drop-initial-value",
"elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
"flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
"float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
"font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
"font-stretch", "font-style", "font-synthesis", "font-variant",
"font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
"font-variant-ligatures", "font-variant-numeric", "font-variant-position",
"font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
"grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap",
"grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap",
"grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns",
"grid-template-rows", "hanging-punctuation", "height", "hyphens",
"icon", "image-orientation", "image-rendering", "image-resolution",
"inline-box-align", "justify-content", "justify-items", "justify-self", "left", "letter-spacing",
"line-break", "line-height", "line-stacking", "line-stacking-ruby",
"line-stacking-shift", "line-stacking-strategy", "list-style",
"list-style-image", "list-style-position", "list-style-type", "margin",
"margin-bottom", "margin-left", "margin-right", "margin-top",
"marks", "marquee-direction", "marquee-loop",
"marquee-play-count", "marquee-speed", "marquee-style", "max-height",
"max-width", "min-height", "min-width", "mix-blend-mode", "move-to", "nav-down", "nav-index",
"nav-left", "nav-right", "nav-up", "object-fit", "object-position",
"opacity", "order", "orphans", "outline",
"outline-color", "outline-offset", "outline-style", "outline-width",
"overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
"padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
"page", "page-break-after", "page-break-before", "page-break-inside",
"page-policy", "pause", "pause-after", "pause-before", "perspective",
"perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position",
"presentation-level", "punctuation-trim", "quotes", "region-break-after",
"region-break-before", "region-break-inside", "region-fragment",
"rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
"right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
"ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
"shape-outside", "size", "speak", "speak-as", "speak-header",
"speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
"tab-size", "table-layout", "target", "target-name", "target-new",
"target-position", "text-align", "text-align-last", "text-decoration",
"text-decoration-color", "text-decoration-line", "text-decoration-skip",
"text-decoration-style", "text-emphasis", "text-emphasis-color",
"text-emphasis-position", "text-emphasis-style", "text-height",
"text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
"text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
"text-wrap", "top", "transform", "transform-origin", "transform-style",
"transition", "transition-delay", "transition-duration",
"transition-property", "transition-timing-function", "unicode-bidi",
"user-select", "vertical-align", "visibility", "voice-balance", "voice-duration",
"voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
"voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break",
"word-spacing", "word-wrap", "z-index",
// SVG-specific
"clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
"flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
"color-interpolation", "color-interpolation-filters",
"color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
"marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
"stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
"stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
"baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
"glyph-orientation-vertical", "text-anchor", "writing-mode"
], propertyKeywords = keySet(propertyKeywords_);
var nonStandardPropertyKeywords_ = [
"scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
"scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
"scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
"searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
"searchfield-results-decoration", "zoom"
], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
var fontProperties_ = [
"font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
"font-stretch", "font-weight", "font-style"
], fontProperties = keySet(fontProperties_);
var counterDescriptors_ = [
"additive-symbols", "fallback", "negative", "pad", "prefix", "range",
"speak-as", "suffix", "symbols", "system"
], counterDescriptors = keySet(counterDescriptors_);
var colorKeywords_ = [
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
"bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
"burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
"cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
"darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
"darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
"darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
"deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
"floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
"gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
"hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
"lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
"lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
"lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
"lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
"maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
"mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
"mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
"navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
"orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
"papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
"purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
"salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
"slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
"teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
"whitesmoke", "yellow", "yellowgreen"
], colorKeywords = keySet(colorKeywords_);
var valueKeywords_ = [
"above", "absolute", "activeborder", "additive", "activecaption", "afar",
"after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
"always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
"arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page",
"avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
"bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
"both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
"buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
"capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
"cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
"cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
"col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
"compact", "condensed", "contain", "content", "contents",
"content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
"cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
"decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
"destination-in", "destination-out", "destination-over", "devanagari", "difference",
"disc", "discard", "disclosure-closed", "disclosure-open", "document",
"dot-dash", "dot-dot-dash",
"dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
"element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
"ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
"ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
"ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
"ethiopic-halehame-gez", "ethiopic-halehame-om-et",
"ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
"ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
"ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
"extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
"forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove",
"gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
"help", "hidden", "hide", "higher", "highlight", "highlighttext",
"hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
"inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
"infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
"inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
"italic", "japanese-formal", "japanese-informal", "justify", "kannada",
"katakana", "katakana-iroha", "keep-all", "khmer",
"korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
"landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
"line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
"local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
"lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
"lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d",
"media-controls-background", "media-current-time-display",
"media-fullscreen-button", "media-mute-button", "media-play-button",
"media-return-to-realtime-button", "media-rewind-button",
"media-seek-back-button", "media-seek-forward-button", "media-slider",
"media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
"media-volume-slider-container", "media-volume-sliderthumb", "medium",
"menu", "menulist", "menulist-button", "menulist-text",
"menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
"mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize",
"narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
"no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
"ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote",
"optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
"outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
"painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
"pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
"progress", "push-button", "radial-gradient", "radio", "read-only",
"read-write", "read-write-plaintext-only", "rectangle", "region",
"relative", "repeat", "repeating-linear-gradient",
"repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
"rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
"rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
"s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
"scroll", "scrollbar", "scroll-position", "se-resize", "searchfield",
"searchfield-cancel-button", "searchfield-decoration",
"searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end",
"semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
"simp-chinese-formal", "simp-chinese-informal", "single",
"skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
"slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
"small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
"source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square",
"square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
"subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table",
"table-caption", "table-cell", "table-column", "table-column-group",
"table-footer-group", "table-header-group", "table-row", "table-row-group",
"tamil",
"telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
"thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
"threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
"tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
"trad-chinese-formal", "trad-chinese-informal", "transform",
"translate", "translate3d", "translateX", "translateY", "translateZ",
"transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up",
"upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
"upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
"var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
"visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
"window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
"xx-large", "xx-small"
], valueKeywords = keySet(valueKeywords_);
var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
.concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
.concat(valueKeywords_);
CodeMirror.registerHelper("hintWords", "css", allWords);
function tokenCComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (maybeEnd && ch == "/") {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return ["comment", "comment"];
}
CodeMirror.defineMIME("text/css", {
documentTypes: documentTypes,
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
fontProperties: fontProperties,
counterDescriptors: counterDescriptors,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
tokenHooks: {
"/": function(stream, state) {
if (!stream.eat("*")) return false;
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
},
name: "css"
});
CodeMirror.defineMIME("text/x-scss", {
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
fontProperties: fontProperties,
allowNested: true,
lineComment: "//",
tokenHooks: {
"/": function(stream, state) {
if (stream.eat("/")) {
stream.skipToEnd();
return ["comment", "comment"];
} else if (stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
} else {
return ["operator", "operator"];
}
},
":": function(stream) {
if (stream.match(/\s*\{/, false))
return [null, null]
return false;
},
"$": function(stream) {
stream.match(/^[\w-]+/);
if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"];
return ["variable-2", "variable"];
},
"#": function(stream) {
if (!stream.eat("{")) return false;
return [null, "interpolation"];
}
},
name: "css",
helperType: "scss"
});
CodeMirror.defineMIME("text/x-less", {
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
fontProperties: fontProperties,
allowNested: true,
lineComment: "//",
tokenHooks: {
"/": function(stream, state) {
if (stream.eat("/")) {
stream.skipToEnd();
return ["comment", "comment"];
} else if (stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
} else {
return ["operator", "operator"];
}
},
"@": function(stream) {
if (stream.eat("{")) return [null, "interpolation"];
if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"];
return ["variable-2", "variable"];
},
"&": function() {
return ["atom", "atom"];
}
},
name: "css",
helperType: "less"
});
CodeMirror.defineMIME("text/x-gss", {
documentTypes: documentTypes,
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
fontProperties: fontProperties,
counterDescriptors: counterDescriptors,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
supportsAtComponent: true,
tokenHooks: {
"/": function(stream, state) {
if (!stream.eat("*")) return false;
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
},
name: "css",
helperType: "gss"
});
});
+152
View File
@@ -0,0 +1,152 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var defaultTags = {
script: [
["lang", /(javascript|babel)/i, "javascript"],
["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"],
["type", /./, "text/plain"],
[null, null, "javascript"]
],
style: [
["lang", /^css$/i, "css"],
["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"],
["type", /./, "text/plain"],
[null, null, "css"]
]
};
function maybeBackup(stream, pat, style) {
var cur = stream.current(), close = cur.search(pat);
if (close > -1) {
stream.backUp(cur.length - close);
} else if (cur.match(/<\/?$/)) {
stream.backUp(cur.length);
if (!stream.match(pat, false)) stream.match(cur);
}
return style;
}
var attrRegexpCache = {};
function getAttrRegexp(attr) {
var regexp = attrRegexpCache[attr];
if (regexp) return regexp;
return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");
}
function getAttrValue(text, attr) {
var match = text.match(getAttrRegexp(attr))
return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : ""
}
function getTagRegexp(tagName, anchored) {
return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i");
}
function addTags(from, to) {
for (var tag in from) {
var dest = to[tag] || (to[tag] = []);
var source = from[tag];
for (var i = source.length - 1; i >= 0; i--)
dest.unshift(source[i])
}
}
function findMatchingMode(tagInfo, tagText) {
for (var i = 0; i < tagInfo.length; i++) {
var spec = tagInfo[i];
if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];
}
}
CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
var htmlMode = CodeMirror.getMode(config, {
name: "xml",
htmlMode: true,
multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
});
var tags = {};
var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;
addTags(defaultTags, tags);
if (configTags) addTags(configTags, tags);
if (configScript) for (var i = configScript.length - 1; i >= 0; i--)
tags.script.unshift(["type", configScript[i].matches, configScript[i].mode])
function html(stream, state) {
var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName
if (tag && !/[<>\s\/]/.test(stream.current()) &&
(tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&
tags.hasOwnProperty(tagName)) {
state.inTag = tagName + " "
} else if (state.inTag && tag && />$/.test(stream.current())) {
var inTag = /^([\S]+) (.*)/.exec(state.inTag)
state.inTag = null
var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2])
var mode = CodeMirror.getMode(config, modeSpec)
var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);
state.token = function (stream, state) {
if (stream.match(endTagA, false)) {
state.token = html;
state.localState = state.localMode = null;
return null;
}
return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
};
state.localMode = mode;
state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "", ""));
} else if (state.inTag) {
state.inTag += stream.current()
if (stream.eol()) state.inTag += " "
}
return style;
};
return {
startState: function () {
var state = CodeMirror.startState(htmlMode);
return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};
},
copyState: function (state) {
var local;
if (state.localState) {
local = CodeMirror.copyState(state.localMode, state.localState);
}
return {token: state.token, inTag: state.inTag,
localMode: state.localMode, localState: local,
htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
},
token: function (stream, state) {
return state.token(stream, state);
},
indent: function (state, textAfter, line) {
if (!state.localMode || /^\s*<\//.test(textAfter))
return htmlMode.indent(state.htmlState, textAfter, line);
else if (state.localMode.indent)
return state.localMode.indent(state.localState, textAfter, line);
else
return CodeMirror.Pass;
},
innerMode: function (state) {
return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
}
};
}, "xml", "javascript", "css");
CodeMirror.defineMIME("text/html", "htmlmixed");
});
+930
View File
@@ -0,0 +1,930 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var statementIndent = parserConfig.statementIndent;
var jsonldMode = parserConfig.jsonld;
var jsonMode = parserConfig.json || jsonldMode;
var isTS = parserConfig.typescript;
var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
return {
"if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
"debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
"function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
"this": kw("this"), "class": kw("class"), "super": kw("atom"),
"yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
"await": C
};
}();
var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
function readRegexp(stream) {
var escaped = false, next, inSet = false;
while ((next = stream.next()) != null) {
if (!escaped) {
if (next == "/" && !inSet) return;
if (next == "[") inSet = true;
else if (inSet && next == "]") inSet = false;
}
escaped = !escaped && next == "\\";
}
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
return ret("number", "number");
} else if (ch == "." && stream.match("..")) {
return ret("spread", "meta");
} else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
return ret(ch);
} else if (ch == "=" && stream.eat(">")) {
return ret("=>", "operator");
} else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
return ret("number", "number");
} else if (/\d/.test(ch)) {
stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
return ret("number", "number");
} else if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
} else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
} else if (expressionAllowed(stream, state, 1)) {
readRegexp(stream);
stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
return ret("regexp", "string-2");
} else {
stream.eat("=");
return ret("operator", "operator", stream.current());
}
} else if (ch == "`") {
state.tokenize = tokenQuasi;
return tokenQuasi(stream, state);
} else if (ch == "#") {
stream.skipToEnd();
return ret("error", "error");
} else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->")) {
stream.skipToEnd()
return ret("comment", "comment")
} else if (isOperatorChar.test(ch)) {
if (ch != ">" || !state.lexical || state.lexical.type != ">") {
if (stream.eat("=")) {
if (ch == "!" || ch == "=") stream.eat("=")
} else if (/[<>*+\-]/.test(ch)) {
stream.eat(ch)
if (ch == ">") stream.eat(ch)
}
}
return ret("operator", "operator", stream.current());
} else if (wordRE.test(ch)) {
stream.eatWhile(wordRE);
var word = stream.current()
if (state.lastType != ".") {
if (keywords.propertyIsEnumerable(word)) {
var kw = keywords[word]
return ret(kw.type, kw.style, word)
}
if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false))
return ret("async", "keyword", word)
}
return ret("variable", "variable", word)
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next;
if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
state.tokenize = tokenBase;
return ret("jsonld-keyword", "meta");
}
while ((next = stream.next()) != null) {
if (next == quote && !escaped) break;
escaped = !escaped && next == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenQuasi(stream, state) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && next == "\\";
}
return ret("quasi", "string-2", stream.current());
}
var brackets = "([{}])";
// This is a crude lookahead trick to try and notice that we're
// parsing the argument patterns for a fat-arrow function before we
// actually hit the arrow token. It only works if the arrow is on
// the same line as the arguments and there's no strange noise
// (comments) in between. Fallback is to only notice when we hit the
// arrow, and not declare the arguments as locals for the arrow
// body.
function findFatArrow(stream, state) {
if (state.fatArrowAt) state.fatArrowAt = null;
var arrow = stream.string.indexOf("=>", stream.start);
if (arrow < 0) return;
if (isTS) { // Try to skip TypeScript return type declarations after the arguments
var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
if (m) arrow = m.index
}
var depth = 0, sawSomething = false;
for (var pos = arrow - 1; pos >= 0; --pos) {
var ch = stream.string.charAt(pos);
var bracket = brackets.indexOf(ch);
if (bracket >= 0 && bracket < 3) {
if (!depth) { ++pos; break; }
if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
} else if (bracket >= 3 && bracket < 6) {
++depth;
} else if (wordRE.test(ch)) {
sawSomething = true;
} else if (/["'\/`]/.test(ch)) {
for (;; --pos) {
if (pos == 0) return
var next = stream.string.charAt(pos - 1)
if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break }
}
} else if (sawSomething && !depth) {
++pos;
break;
}
}
if (sawSomething && !depth) state.fatArrowAt = pos;
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
for (var cx = state.context; cx; cx = cx.prev) {
for (var v = cx.vars; v; v = v.next)
if (v.name == varname) return true;
}
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function inList(name, list) {
for (var v = list; v; v = v.next) if (v.name == name) return true
return false;
}
function register(varname) {
var state = cx.state;
cx.marked = "def";
if (state.context) {
if (state.lexical.info == "var" && state.context && state.context.block) {
// FIXME function decls are also not block scoped
var newContext = registerVarScoped(varname, state.context)
if (newContext != null) {
state.context = newContext
return
}
} else if (!inList(varname, state.localVars)) {
state.localVars = new Var(varname, state.localVars)
return
}
}
// Fall through means this is global
if (parserConfig.globalVars && !inList(varname, state.globalVars))
state.globalVars = new Var(varname, state.globalVars)
}
function registerVarScoped(varname, context) {
if (!context) {
return null
} else if (context.block) {
var inner = registerVarScoped(varname, context.prev)
if (!inner) return null
if (inner == context.prev) return context
return new Context(inner, context.vars, true)
} else if (inList(varname, context.vars)) {
return context
} else {
return new Context(context.prev, new Var(varname, context.vars), false)
}
}
function isModifier(name) {
return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
}
// Combinators
function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
function Var(name, next) { this.name = name; this.next = next }
var defaultVars = new Var("this", new Var("arguments", null))
function pushcontext() {
cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
cx.state.localVars = defaultVars
}
function pushblockcontext() {
cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
cx.state.localVars = null
}
function popcontext() {
cx.state.localVars = cx.state.context.vars
cx.state.context = cx.state.context.prev
}
popcontext.lex = true
function pushlex(type, info) {
var result = function() {
var state = cx.state, indent = state.indented;
if (state.lexical.type == "stat") indent = state.lexical.indented;
else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
indent = outer.indented;
state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
function exp(type) {
if (type == wanted) return cont();
else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
else return cont(exp);
};
return exp;
}
function statement(type, value) {
if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
if (type == "debugger") return cont(expect(";"));
if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
if (type == ";") return cont();
if (type == "if") {
if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
cx.state.cc.pop()();
return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
}
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
if (type == "class" || (isTS && value == "interface")) {
cx.marked = "keyword"
return cont(pushlex("form", type == "class" ? type : value), className, poplex)
}
if (type == "variable") {
if (isTS && value == "declare") {
cx.marked = "keyword"
return cont(statement)
} else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
cx.marked = "keyword"
if (value == "enum") return cont(enumdef);
else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));
else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
} else if (isTS && value == "namespace") {
cx.marked = "keyword"
return cont(pushlex("form"), expression, statement, poplex)
} else if (isTS && value == "abstract") {
cx.marked = "keyword"
return cont(statement)
} else {
return cont(pushlex("stat"), maybelabel);
}
}
if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
block, poplex, poplex, popcontext);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
if (type == "async") return cont(statement)
if (value == "@") return cont(expression, statement)
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function maybeCatchBinding(type) {
if (type == "(") return cont(funarg, expect(")"))
}
function expression(type, value) {
return expressionInner(type, value, false);
}
function expressionNoComma(type, value) {
return expressionInner(type, value, true);
}
function parenExpr(type) {
if (type != "(") return pass()
return cont(pushlex(")"), expression, expect(")"), poplex)
}
function expressionInner(type, value, noComma) {
if (cx.state.fatArrowAt == cx.stream.start) {
var body = noComma ? arrowBodyNoComma : arrowBody;
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
}
var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
if (type == "function") return cont(functiondef, maybeop);
if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
if (type == "{") return contCommasep(objprop, "}", null, maybeop);
if (type == "quasi") return pass(quasi, maybeop);
if (type == "new") return cont(maybeTarget(noComma));
if (type == "import") return cont(expression);
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeoperatorComma(type, value) {
if (type == ",") return cont(expression);
return maybeoperatorNoComma(type, value, false);
}
function maybeoperatorNoComma(type, value, noComma) {
var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
var expr = noComma == false ? expression : expressionNoComma;
if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
if (type == "operator") {
if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false))
return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
if (value == "?") return cont(expression, expect(":"), expr);
return cont(expr);
}
if (type == "quasi") { return pass(quasi, me); }
if (type == ";") return;
if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
if (type == ".") return cont(property, me);
if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
if (type == "regexp") {
cx.state.lastType = cx.marked = "operator"
cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
return cont(expr)
}
}
function quasi(type, value) {
if (type != "quasi") return pass();
if (value.slice(value.length - 2) != "${") return cont(quasi);
return cont(expression, continueQuasi);
}
function continueQuasi(type) {
if (type == "}") {
cx.marked = "string-2";
cx.state.tokenize = tokenQuasi;
return cont(quasi);
}
}
function arrowBody(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expression);
}
function arrowBodyNoComma(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expressionNoComma);
}
function maybeTarget(noComma) {
return function(type) {
if (type == ".") return cont(noComma ? targetNoComma : target);
else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
else return pass(noComma ? expressionNoComma : expression);
};
}
function target(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
}
function targetNoComma(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperatorComma, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type, value) {
if (type == "async") {
cx.marked = "property";
return cont(objprop);
} else if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
if (value == "get" || value == "set") return cont(getterSetter);
var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
cx.state.fatArrowAt = cx.stream.pos + m[0].length
return cont(afterprop);
} else if (type == "number" || type == "string") {
cx.marked = jsonldMode ? "property" : (cx.style + " property");
return cont(afterprop);
} else if (type == "jsonld-keyword") {
return cont(afterprop);
} else if (isTS && isModifier(value)) {
cx.marked = "keyword"
return cont(objprop)
} else if (type == "[") {
return cont(expression, maybetype, expect("]"), afterprop);
} else if (type == "spread") {
return cont(expressionNoComma, afterprop);
} else if (value == "*") {
cx.marked = "keyword";
return cont(objprop);
} else if (type == ":") {
return pass(afterprop)
}
}
function getterSetter(type) {
if (type != "variable") return pass(afterprop);
cx.marked = "property";
return cont(functiondef);
}
function afterprop(type) {
if (type == ":") return cont(expressionNoComma);
if (type == "(") return pass(functiondef);
}
function commasep(what, end, sep) {
function proceed(type, value) {
if (sep ? sep.indexOf(type) > -1 : type == ",") {
var lex = cx.state.lexical;
if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
return cont(function(type, value) {
if (type == end || value == end) return pass()
return pass(what)
}, proceed);
}
if (type == end || value == end) return cont();
if (sep && sep.indexOf(";") > -1) return pass(what)
return cont(expect(end));
}
return function(type, value) {
if (type == end || value == end) return cont();
return pass(what, proceed);
};
}
function contCommasep(what, end, info) {
for (var i = 3; i < arguments.length; i++)
cx.cc.push(arguments[i]);
return cont(pushlex(end, info), commasep(what, end), poplex);
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function maybetype(type, value) {
if (isTS) {
if (type == ":") return cont(typeexpr);
if (value == "?") return cont(maybetype);
}
}
function maybetypeOrIn(type, value) {
if (isTS && (type == ":" || value == "in")) return cont(typeexpr)
}
function mayberettype(type) {
if (isTS && type == ":") {
if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
else return cont(typeexpr)
}
}
function isKW(_, value) {
if (value == "is") {
cx.marked = "keyword"
return cont()
}
}
function typeexpr(type, value) {
if (value == "keyof" || value == "typeof" || value == "infer") {
cx.marked = "keyword"
return cont(value == "typeof" ? expressionNoComma : typeexpr)
}
if (type == "variable" || value == "void") {
cx.marked = "type"
return cont(afterType)
}
if (value == "|" || value == "&") return cont(typeexpr)
if (type == "string" || type == "number" || type == "atom") return cont(afterType);
if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType)
if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
}
function maybeReturnType(type) {
if (type == "=>") return cont(typeexpr)
}
function typeprop(type, value) {
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property"
return cont(typeprop)
} else if (value == "?" || type == "number" || type == "string") {
return cont(typeprop)
} else if (type == ":") {
return cont(typeexpr)
} else if (type == "[") {
return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop)
} else if (type == "(") {
return pass(functiondecl, typeprop)
}
}
function typearg(type, value) {
if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
if (type == ":") return cont(typeexpr)
if (type == "spread") return cont(typearg)
return pass(typeexpr)
}
function afterType(type, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
if (value == "|" || type == "." || value == "&") return cont(typeexpr)
if (type == "[") return cont(typeexpr, expect("]"), afterType)
if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
if (value == "?") return cont(typeexpr, expect(":"), typeexpr)
}
function maybeTypeArgs(_, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
}
function typeparam() {
return pass(typeexpr, maybeTypeDefault)
}
function maybeTypeDefault(_, value) {
if (value == "=") return cont(typeexpr)
}
function vardef(_, value) {
if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
return pass(pattern, maybetype, maybeAssign, vardefCont);
}
function pattern(type, value) {
if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
if (type == "variable") { register(value); return cont(); }
if (type == "spread") return cont(pattern);
if (type == "[") return contCommasep(eltpattern, "]");
if (type == "{") return contCommasep(proppattern, "}");
}
function proppattern(type, value) {
if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
register(value);
return cont(maybeAssign);
}
if (type == "variable") cx.marked = "property";
if (type == "spread") return cont(pattern);
if (type == "}") return pass();
if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
return cont(expect(":"), pattern, maybeAssign);
}
function eltpattern() {
return pass(pattern, maybeAssign)
}
function maybeAssign(_type, value) {
if (value == "=") return cont(expressionNoComma);
}
function vardefCont(type) {
if (type == ",") return cont(vardef);
}
function maybeelse(type, value) {
if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
}
function forspec(type, value) {
if (value == "await") return cont(forspec);
if (type == "(") return cont(pushlex(")"), forspec1, poplex);
}
function forspec1(type) {
if (type == "var") return cont(vardef, forspec2);
if (type == "variable") return cont(forspec2);
return pass(forspec2)
}
function forspec2(type, value) {
if (type == ")") return cont()
if (type == ";") return cont(forspec2)
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) }
return pass(expression, forspec2)
}
function functiondef(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
}
function functiondecl(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);}
if (type == "variable") {register(value); return cont(functiondecl);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl)
}
function typename(type, value) {
if (type == "keyword" || type == "variable") {
cx.marked = "type"
return cont(typename)
} else if (value == "<") {
return cont(pushlex(">"), commasep(typeparam, ">"), poplex)
}
}
function funarg(type, value) {
if (value == "@") cont(expression, funarg)
if (type == "spread") return cont(funarg);
if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
if (isTS && type == "this") return cont(maybetype, maybeAssign)
return pass(pattern, maybetype, maybeAssign);
}
function classExpression(type, value) {
// Class expressions may have an optional name.
if (type == "variable") return className(type, value);
return classNameAfter(type, value);
}
function className(type, value) {
if (type == "variable") {register(value); return cont(classNameAfter);}
}
function classNameAfter(type, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
if (value == "extends" || value == "implements" || (isTS && type == ",")) {
if (value == "implements") cx.marked = "keyword";
return cont(isTS ? typeexpr : expression, classNameAfter);
}
if (type == "{") return cont(pushlex("}"), classBody, poplex);
}
function classBody(type, value) {
if (type == "async" ||
(type == "variable" &&
(value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
cx.marked = "keyword";
return cont(classBody);
}
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
return cont(isTS ? classfield : functiondef, classBody);
}
if (type == "number" || type == "string") return cont(isTS ? classfield : functiondef, classBody);
if (type == "[")
return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody)
if (value == "*") {
cx.marked = "keyword";
return cont(classBody);
}
if (isTS && type == "(") return pass(functiondecl, classBody)
if (type == ";" || type == ",") return cont(classBody);
if (type == "}") return cont();
if (value == "@") return cont(expression, classBody)
}
function classfield(type, value) {
if (value == "?") return cont(classfield)
if (type == ":") return cont(typeexpr, maybeAssign)
if (value == "=") return cont(expressionNoComma)
var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"
return pass(isInterface ? functiondecl : functiondef)
}
function afterExport(type, value) {
if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
return pass(statement);
}
function exportField(type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
if (type == "variable") return pass(expressionNoComma, exportField);
}
function afterImport(type) {
if (type == "string") return cont();
if (type == "(") return pass(expression);
return pass(importSpec, maybeMoreImports, maybeFrom);
}
function importSpec(type, value) {
if (type == "{") return contCommasep(importSpec, "}");
if (type == "variable") register(value);
if (value == "*") cx.marked = "keyword";
return cont(maybeAs);
}
function maybeMoreImports(type) {
if (type == ",") return cont(importSpec, maybeMoreImports)
}
function maybeAs(_type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
}
function maybeFrom(_type, value) {
if (value == "from") { cx.marked = "keyword"; return cont(expression); }
}
function arrayLiteral(type) {
if (type == "]") return cont();
return pass(commasep(expressionNoComma, "]"));
}
function enumdef() {
return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
}
function enummember() {
return pass(pattern, maybeAssign);
}
function isContinuedStatement(state, textAfter) {
return state.lastType == "operator" || state.lastType == "," ||
isOperatorChar.test(textAfter.charAt(0)) ||
/[,.]/.test(textAfter.charAt(0));
}
function expressionAllowed(stream, state, backUp) {
return state.tokenize == tokenBase &&
/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
(state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
}
// Interface
return {
startState: function(basecolumn) {
var state = {
tokenize: tokenBase,
lastType: "sof",
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
context: parserConfig.localVars && new Context(null, null, false),
indented: basecolumn || 0
};
if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
state.globalVars = parserConfig.globalVars;
return state;
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
findFatArrow(stream, state);
}
if (state.tokenize != tokenComment && stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize == tokenComment) return CodeMirror.Pass;
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
// Kludge to prevent 'maybelse' from blocking lexical scope pops
if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
var c = state.cc[i];
if (c == poplex) lexical = lexical.prev;
else if (c != maybeelse) break;
}
while ((lexical.type == "stat" || lexical.type == "form") &&
(firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
(top == maybeoperatorComma || top == maybeoperatorNoComma) &&
!/^[,\.=+\-*:?[\(]/.test(textAfter))))
lexical = lexical.prev;
if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "form") return lexical.indented + indentUnit;
else if (type == "stat")
return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
blockCommentStart: jsonMode ? null : "/*",
blockCommentEnd: jsonMode ? null : "*/",
blockCommentContinue: jsonMode ? null : " * ",
lineComment: jsonMode ? null : "//",
fold: "brace",
closeBrackets: "()[]{}''\"\"``",
helperType: jsonMode ? "json" : "javascript",
jsonldMode: jsonldMode,
jsonMode: jsonMode,
expressionAllowed: expressionAllowed,
skipExpression: function(state) {
var top = state.cc[state.cc.length - 1]
if (top == expression || top == expressionNoComma) state.cc.pop()
}
};
});
CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
});
+135
View File
@@ -0,0 +1,135 @@
/*
Name: material
Author: Mattia Astorino (http://github.com/equinusocio)
Website: https://material-theme.site/
*/
.cm-s-material.CodeMirror {
background-color: #263238;
color: #EEFFFF;
}
.cm-s-material .CodeMirror-gutters {
background: #263238;
color: #546E7A;
border: none;
}
.cm-s-material .CodeMirror-guttermarker,
.cm-s-material .CodeMirror-guttermarker-subtle,
.cm-s-material .CodeMirror-linenumber {
color: #546E7A;
}
.cm-s-material .CodeMirror-cursor {
border-left: 1px solid #FFCC00;
}
.cm-s-material div.CodeMirror-selected {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material.CodeMirror-focused div.CodeMirror-selected {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material .CodeMirror-line::selection,
.cm-s-material .CodeMirror-line>span::selection,
.cm-s-material .CodeMirror-line>span>span::selection {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material .CodeMirror-line::-moz-selection,
.cm-s-material .CodeMirror-line>span::-moz-selection,
.cm-s-material .CodeMirror-line>span>span::-moz-selection {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material .CodeMirror-activeline-background {
background: rgba(0, 0, 0, 0.5);
}
.cm-s-material .cm-keyword {
color: #C792EA;
}
.cm-s-material .cm-operator {
color: #89DDFF;
}
.cm-s-material .cm-variable-2 {
color: #EEFFFF;
}
.cm-s-material .cm-variable-3,
.cm-s-material .cm-type {
color: #f07178;
}
.cm-s-material .cm-builtin {
color: #FFCB6B;
}
.cm-s-material .cm-atom {
color: #F78C6C;
}
.cm-s-material .cm-number {
color: #FF5370;
}
.cm-s-material .cm-def {
color: #82AAFF;
}
.cm-s-material .cm-string {
color: #C3E88D;
}
.cm-s-material .cm-string-2 {
color: #f07178;
}
.cm-s-material .cm-comment {
color: #546E7A;
}
.cm-s-material .cm-variable {
color: #f07178;
}
.cm-s-material .cm-tag {
color: #FF5370;
}
.cm-s-material .cm-meta {
color: #FFCB6B;
}
.cm-s-material .cm-attribute {
color: #C792EA;
}
.cm-s-material .cm-property {
color: #C792EA;
}
.cm-s-material .cm-qualifier {
color: #DECB6B;
}
.cm-s-material .cm-variable-3,
.cm-s-material .cm-type {
color: #DECB6B;
}
.cm-s-material .cm-error {
color: rgba(255, 255, 255, 1.0);
background-color: #FF5370;
}
.cm-s-material .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
+41
View File
@@ -0,0 +1,41 @@
/* Based on Sublime Text's Monokai theme */
.cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; }
.cm-s-monokai div.CodeMirror-selected { background: #49483E; }
.cm-s-monokai .CodeMirror-line::selection, .cm-s-monokai .CodeMirror-line > span::selection, .cm-s-monokai .CodeMirror-line > span > span::selection { background: rgba(73, 72, 62, .99); }
.cm-s-monokai .CodeMirror-line::-moz-selection, .cm-s-monokai .CodeMirror-line > span::-moz-selection, .cm-s-monokai .CodeMirror-line > span > span::-moz-selection { background: rgba(73, 72, 62, .99); }
.cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; }
.cm-s-monokai .CodeMirror-guttermarker { color: white; }
.cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; }
.cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; }
.cm-s-monokai span.cm-comment { color: #75715e; }
.cm-s-monokai span.cm-atom { color: #ae81ff; }
.cm-s-monokai span.cm-number { color: #ae81ff; }
.cm-s-monokai span.cm-comment.cm-attribute { color: #97b757; }
.cm-s-monokai span.cm-comment.cm-def { color: #bc9262; }
.cm-s-monokai span.cm-comment.cm-tag { color: #bc6283; }
.cm-s-monokai span.cm-comment.cm-type { color: #5998a6; }
.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; }
.cm-s-monokai span.cm-keyword { color: #f92672; }
.cm-s-monokai span.cm-builtin { color: #66d9ef; }
.cm-s-monokai span.cm-string { color: #e6db74; }
.cm-s-monokai span.cm-variable { color: #f8f8f2; }
.cm-s-monokai span.cm-variable-2 { color: #9effff; }
.cm-s-monokai span.cm-variable-3, .cm-s-monokai span.cm-type { color: #66d9ef; }
.cm-s-monokai span.cm-def { color: #fd971f; }
.cm-s-monokai span.cm-bracket { color: #f8f8f2; }
.cm-s-monokai span.cm-tag { color: #f92672; }
.cm-s-monokai span.cm-header { color: #ae81ff; }
.cm-s-monokai span.cm-link { color: #ae81ff; }
.cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; }
.cm-s-monokai .CodeMirror-activeline-background { background: #373831; }
.cm-s-monokai .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
+399
View File
@@ -0,0 +1,399 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var wordOperators = wordRegexp(["and", "or", "not", "is"]);
var commonKeywords = ["as", "assert", "break", "class", "continue",
"def", "del", "elif", "else", "except", "finally",
"for", "from", "global", "if", "import",
"lambda", "pass", "raise", "return",
"try", "while", "with", "yield", "in"];
var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
"classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "filter", "float", "format", "frozenset",
"getattr", "globals", "hasattr", "hash", "help", "hex", "id",
"input", "int", "isinstance", "issubclass", "iter", "len",
"list", "locals", "map", "max", "memoryview", "min", "next",
"object", "oct", "open", "ord", "pow", "property", "range",
"repr", "reversed", "round", "set", "setattr", "slice",
"sorted", "staticmethod", "str", "sum", "super", "tuple",
"type", "vars", "zip", "__import__", "NotImplemented",
"Ellipsis", "__debug__"];
CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
function top(state) {
return state.scopes[state.scopes.length - 1];
}
CodeMirror.defineMode("python", function(conf, parserConf) {
var ERRORCLASS = "error";
var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;
// (Backwards-compatiblity with old, cumbersome config system)
var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/]
for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)
var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
if (parserConf.extra_keywords != undefined)
myKeywords = myKeywords.concat(parserConf.extra_keywords);
if (parserConf.extra_builtins != undefined)
myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
var py3 = !(parserConf.version && Number(parserConf.version) < 3)
if (py3) {
// since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
var stringPrefixes = new RegExp("^(([rbuf]|(br)|(fr))?('{3}|\"{3}|['\"]))", "i");
} else {
var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
myKeywords = myKeywords.concat(["exec", "print"]);
myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
"file", "intern", "long", "raw_input", "reduce", "reload",
"unichr", "unicode", "xrange", "False", "True", "None"]);
var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
}
var keywords = wordRegexp(myKeywords);
var builtins = wordRegexp(myBuiltins);
// tokenizers
function tokenBase(stream, state) {
var sol = stream.sol() && state.lastToken != "\\"
if (sol) state.indent = stream.indentation()
// Handle scope changes
if (sol && top(state).type == "py") {
var scopeOffset = top(state).offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset)
pushPyScope(state);
else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
state.errorToken = true;
return null;
} else {
var style = tokenBaseInner(stream, state);
if (scopeOffset > 0 && dedent(stream, state))
style += " " + ERRORCLASS;
return style;
}
}
return tokenBaseInner(stream, state);
}
function tokenBaseInner(stream, state) {
if (stream.eatSpace()) return null;
// Handle Comments
if (stream.match(/^#.*/)) return "comment";
// Handle Number Literals
if (stream.match(/^[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
if (stream.match(/^\.\d+/)) { floatLiteral = true; }
if (floatLiteral) {
// Float literals may be "imaginary"
stream.eat(/J/i);
return "number";
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
// Binary
if (stream.match(/^0b[01_]+/i)) intLiteral = true;
// Octal
if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
// Decimal
if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
// Decimal literals may be "imaginary"
stream.eat(/J/i);
// TODO - Can you have imaginary longs?
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
if (intLiteral) {
// Integer literals may be "long"
stream.eat(/L/i);
return "number";
}
}
// Handle Strings
if (stream.match(stringPrefixes)) {
var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;
if (!isFmtString) {
state.tokenize = tokenStringFactory(stream.current(), state.tokenize);
return state.tokenize(stream, state);
} else {
state.tokenize = formatStringFactory(stream.current(), state.tokenize);
return state.tokenize(stream, state);
}
}
for (var i = 0; i < operators.length; i++)
if (stream.match(operators[i])) return "operator"
if (stream.match(delimiters)) return "punctuation";
if (state.lastToken == "." && stream.match(identifiers))
return "property";
if (stream.match(keywords) || stream.match(wordOperators))
return "keyword";
if (stream.match(builtins))
return "builtin";
if (stream.match(/^(self|cls)\b/))
return "variable-2";
if (stream.match(identifiers)) {
if (state.lastToken == "def" || state.lastToken == "class")
return "def";
return "variable";
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function formatStringFactory(delimiter, tokenOuter) {
while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
delimiter = delimiter.substr(1);
var singleline = delimiter.length == 1;
var OUTCLASS = "string";
function tokenNestedExpr(depth) {
return function(stream, state) {
var inner = tokenBaseInner(stream, state)
if (inner == "punctuation") {
if (stream.current() == "{") {
state.tokenize = tokenNestedExpr(depth + 1)
} else if (stream.current() == "}") {
if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)
else state.tokenize = tokenString
}
}
return inner
}
}
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\{\}\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol())
return OUTCLASS;
} else if (stream.match(delimiter)) {
state.tokenize = tokenOuter;
return OUTCLASS;
} else if (stream.match('{{')) {
// ignore {{ in f-str
return OUTCLASS;
} else if (stream.match('{', false)) {
// switch to nested mode
state.tokenize = tokenNestedExpr(0)
if (stream.current()) return OUTCLASS;
else return state.tokenize(stream, state)
} else if (stream.match('}}')) {
return OUTCLASS;
} else if (stream.match('}')) {
// single } in f-string is an error
return ERRORCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors)
return ERRORCLASS;
else
state.tokenize = tokenOuter;
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function tokenStringFactory(delimiter, tokenOuter) {
while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
delimiter = delimiter.substr(1);
var singleline = delimiter.length == 1;
var OUTCLASS = "string";
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol())
return OUTCLASS;
} else if (stream.match(delimiter)) {
state.tokenize = tokenOuter;
return OUTCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors)
return ERRORCLASS;
else
state.tokenize = tokenOuter;
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function pushPyScope(state) {
while (top(state).type != "py") state.scopes.pop()
state.scopes.push({offset: top(state).offset + conf.indentUnit,
type: "py",
align: null})
}
function pushBracketScope(stream, state, type) {
var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1
state.scopes.push({offset: state.indent + hangingIndent,
type: type,
align: align})
}
function dedent(stream, state) {
var indented = stream.indentation();
while (state.scopes.length > 1 && top(state).offset > indented) {
if (top(state).type != "py") return true;
state.scopes.pop();
}
return top(state).offset != indented;
}
function tokenLexer(stream, state) {
if (stream.sol()) state.beginningOfLine = true;
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle decorators
if (state.beginningOfLine && current == "@")
return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;
if (/\S/.test(current)) state.beginningOfLine = false;
if ((style == "variable" || style == "builtin")
&& state.lastToken == "meta")
style = "meta";
// Handle scope changes.
if (current == "pass" || current == "return")
state.dedent += 1;
if (current == "lambda") state.lambda = true;
if (current == ":" && !state.lambda && top(state).type == "py")
pushPyScope(state);
if (current.length == 1 && !/string|comment/.test(style)) {
var delimiter_index = "[({".indexOf(current);
if (delimiter_index != -1)
pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
delimiter_index = "])}".indexOf(current);
if (delimiter_index != -1) {
if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
else return ERRORCLASS;
}
}
if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
if (state.scopes.length > 1) state.scopes.pop();
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset: basecolumn || 0, type: "py", align: null}],
indent: basecolumn || 0,
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var addErr = state.errorToken;
if (addErr) state.errorToken = false;
var style = tokenLexer(stream, state);
if (style && style != "comment")
state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
if (style == "punctuation") style = null;
if (stream.eol() && state.lambda)
state.lambda = false;
return addErr ? style + " " + ERRORCLASS : style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase)
return state.tokenize.isString ? CodeMirror.Pass : 0;
var scope = top(state), closing = scope.type == textAfter.charAt(0)
if (scope.align != null)
return scope.align - (closing ? 1 : 0)
else
return scope.offset - (closing ? hangingIndent : 0)
},
electricInput: /^\s*[\}\]\)]$/,
closeBrackets: {triples: "'\""},
lineComment: "#",
fold: "indent"
};
return external;
});
CodeMirror.defineMIME("text/x-python", "python");
var words = function(str) { return str.split(" "); };
CodeMirror.defineMIME("text/x-cython", {
name: "python",
extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
"extern gil include nogil property public "+
"readonly struct union DEF IF ELIF ELSE")
});
});
+413
View File
@@ -0,0 +1,413 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var htmlConfig = {
autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
'track': true, 'wbr': true, 'menuitem': true},
implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
'th': true, 'tr': true},
contextGrabbers: {
'dd': {'dd': true, 'dt': true},
'dt': {'dd': true, 'dt': true},
'li': {'li': true},
'option': {'option': true, 'optgroup': true},
'optgroup': {'optgroup': true},
'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
'rp': {'rp': true, 'rt': true},
'rt': {'rp': true, 'rt': true},
'tbody': {'tbody': true, 'tfoot': true},
'td': {'td': true, 'th': true},
'tfoot': {'tbody': true},
'th': {'td': true, 'th': true},
'thead': {'tbody': true, 'tfoot': true},
'tr': {'tr': true}
},
doNotIndent: {"pre": true},
allowUnquoted: true,
allowMissing: true,
caseFold: true
}
var xmlConfig = {
autoSelfClosers: {},
implicitlyClosed: {},
contextGrabbers: {},
doNotIndent: {},
allowUnquoted: false,
allowMissing: false,
allowMissingTagName: false,
caseFold: false
}
CodeMirror.defineMode("xml", function(editorConf, config_) {
var indentUnit = editorConf.indentUnit
var config = {}
var defaults = config_.htmlMode ? htmlConfig : xmlConfig
for (var prop in defaults) config[prop] = defaults[prop]
for (var prop in config_) config[prop] = config_[prop]
// Return variables for tokenizers
var type, setStyle;
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var ch = stream.next();
if (ch == "<") {
if (stream.eat("!")) {
if (stream.eat("[")) {
if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
else return null;
} else if (stream.match("--")) {
return chain(inBlock("comment", "-->"));
} else if (stream.match("DOCTYPE", true, true)) {
stream.eatWhile(/[\w\._\-]/);
return chain(doctype(1));
} else {
return null;
}
} else if (stream.eat("?")) {
stream.eatWhile(/[\w\._\-]/);
state.tokenize = inBlock("meta", "?>");
return "meta";
} else {
type = stream.eat("/") ? "closeTag" : "openTag";
state.tokenize = inTag;
return "tag bracket";
}
} else if (ch == "&") {
var ok;
if (stream.eat("#")) {
if (stream.eat("x")) {
ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
} else {
ok = stream.eatWhile(/[\d]/) && stream.eat(";");
}
} else {
ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
}
return ok ? "atom" : "error";
} else {
stream.eatWhile(/[^&<]/);
return null;
}
}
inText.isInText = true;
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.tokenize = inText;
type = ch == ">" ? "endTag" : "selfcloseTag";
return "tag bracket";
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = inText;
state.state = baseState;
state.tagName = state.tagStart = null;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
state.stringStartCol = stream.column();
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
function inAttribute(quote) {
var closure = function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inTag;
break;
}
}
return "string";
};
closure.isInAttribute = true;
return closure;
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
return style;
}
}
function doctype(depth) {
return function(stream, state) {
var ch;
while ((ch = stream.next()) != null) {
if (ch == "<") {
state.tokenize = doctype(depth + 1);
return state.tokenize(stream, state);
} else if (ch == ">") {
if (depth == 1) {
state.tokenize = inText;
break;
} else {
state.tokenize = doctype(depth - 1);
return state.tokenize(stream, state);
}
}
}
return "meta";
};
}
function Context(state, tagName, startOfLine) {
this.prev = state.context;
this.tagName = tagName;
this.indent = state.indented;
this.startOfLine = startOfLine;
if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
this.noIndent = true;
}
function popContext(state) {
if (state.context) state.context = state.context.prev;
}
function maybePopContext(state, nextTagName) {
var parentTagName;
while (true) {
if (!state.context) {
return;
}
parentTagName = state.context.tagName;
if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
!config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
return;
}
popContext(state);
}
}
function baseState(type, stream, state) {
if (type == "openTag") {
state.tagStart = stream.column();
return tagNameState;
} else if (type == "closeTag") {
return closeTagNameState;
} else {
return baseState;
}
}
function tagNameState(type, stream, state) {
if (type == "word") {
state.tagName = stream.current();
setStyle = "tag";
return attrState;
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return attrState(type, stream, state);
} else {
setStyle = "error";
return tagNameState;
}
}
function closeTagNameState(type, stream, state) {
if (type == "word") {
var tagName = stream.current();
if (state.context && state.context.tagName != tagName &&
config.implicitlyClosed.hasOwnProperty(state.context.tagName))
popContext(state);
if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
setStyle = "tag";
return closeState;
} else {
setStyle = "tag error";
return closeStateErr;
}
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return closeState(type, stream, state);
} else {
setStyle = "error";
return closeStateErr;
}
}
function closeState(type, _stream, state) {
if (type != "endTag") {
setStyle = "error";
return closeState;
}
popContext(state);
return baseState;
}
function closeStateErr(type, stream, state) {
setStyle = "error";
return closeState(type, stream, state);
}
function attrState(type, _stream, state) {
if (type == "word") {
setStyle = "attribute";
return attrEqState;
} else if (type == "endTag" || type == "selfcloseTag") {
var tagName = state.tagName, tagStart = state.tagStart;
state.tagName = state.tagStart = null;
if (type == "selfcloseTag" ||
config.autoSelfClosers.hasOwnProperty(tagName)) {
maybePopContext(state, tagName);
} else {
maybePopContext(state, tagName);
state.context = new Context(state, tagName, tagStart == state.indented);
}
return baseState;
}
setStyle = "error";
return attrState;
}
function attrEqState(type, stream, state) {
if (type == "equals") return attrValueState;
if (!config.allowMissing) setStyle = "error";
return attrState(type, stream, state);
}
function attrValueState(type, stream, state) {
if (type == "string") return attrContinuedState;
if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
setStyle = "error";
return attrState(type, stream, state);
}
function attrContinuedState(type, stream, state) {
if (type == "string") return attrContinuedState;
return attrState(type, stream, state);
}
return {
startState: function(baseIndent) {
var state = {tokenize: inText,
state: baseState,
indented: baseIndent || 0,
tagName: null, tagStart: null,
context: null}
if (baseIndent != null) state.baseIndent = baseIndent
return state
},
token: function(stream, state) {
if (!state.tagName && stream.sol())
state.indented = stream.indentation();
if (stream.eatSpace()) return null;
type = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
setStyle = null;
state.state = state.state(type || style, stream, state);
if (setStyle)
style = setStyle == "error" ? style + " error" : setStyle;
}
return style;
},
indent: function(state, textAfter, fullLine) {
var context = state.context;
// Indent multi-line strings (e.g. css).
if (state.tokenize.isInAttribute) {
if (state.tagStart == state.indented)
return state.stringStartCol + 1;
else
return state.indented + indentUnit;
}
if (context && context.noIndent) return CodeMirror.Pass;
if (state.tokenize != inTag && state.tokenize != inText)
return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
// Indent the starts of attribute names.
if (state.tagName) {
if (config.multilineTagIndentPastTag !== false)
return state.tagStart + state.tagName.length + 2;
else
return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
}
if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
if (tagAfter && tagAfter[1]) { // Closing tag spotted
while (context) {
if (context.tagName == tagAfter[2]) {
context = context.prev;
break;
} else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
context = context.prev;
} else {
break;
}
}
} else if (tagAfter) { // Opening tag spotted
while (context) {
var grabbers = config.contextGrabbers[context.tagName];
if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
context = context.prev;
else
break;
}
}
while (context && context.prev && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return state.baseIndent || 0;
},
electricInput: /<\/[\s\w:]+>$/,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
configuration: config.htmlMode ? "html" : "xml",
helperType: config.htmlMode ? "html" : "xml",
skipAttribute: function(state) {
if (state.state == attrValueState)
state.state = attrState
},
xmlCurrentTag: function(state) {
return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null
},
xmlCurrentContext: function(state) {
var context = []
for (var cx = state.context; cx; cx = cx.prev)
if (cx.tagName) context.push(cx.tagName)
return context.reverse()
}
};
});
CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
});
BIN
View File
Binary file not shown.
+344
View File
@@ -0,0 +1,344 @@
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
color: black;
direction: ltr;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre.CodeMirror-line,
.CodeMirror pre.CodeMirror-line-like {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
white-space: nowrap;
}
.CodeMirror-guttermarker { color: black; }
.CodeMirror-guttermarker-subtle { color: #999; }
/* CURSOR */
.CodeMirror-cursor {
border-left: 1px solid black;
border-right: none;
width: 0;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.cm-fat-cursor .CodeMirror-cursor {
width: auto;
border: 0 !important;
background: #7e7;
}
.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-fat-cursor .CodeMirror-line::selection,
.cm-fat-cursor .CodeMirror-line > span::selection,
.cm-fat-cursor .CodeMirror-line > span > span::selection { background: transparent; }
.cm-fat-cursor .CodeMirror-line::-moz-selection,
.cm-fat-cursor .CodeMirror-line > span::-moz-selection,
.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { background: transparent; }
.cm-fat-cursor { caret-color: transparent; }
@-moz-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@-webkit-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
/* Can style cursor different in overwrite (non-insert) mode */
.CodeMirror-overwrite .CodeMirror-cursor {}
.cm-tab { display: inline-block; text-decoration: inherit; }
.CodeMirror-rulers {
position: absolute;
left: 0; right: 0; top: -50px; bottom: 0;
overflow: hidden;
}
.CodeMirror-ruler {
border-left: 1px solid #ccc;
top: 0; bottom: 0;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-strikethrough {text-decoration: line-through;}
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-s-default .cm-error {color: #f00;}
.cm-invalidchar {color: #f00;}
.CodeMirror-composing { border-bottom: 2px solid; }
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}
.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
.CodeMirror-activeline-background {background: #e8f2ff;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 50px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -50px; margin-right: -50px;
padding-bottom: 50px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
z-index: 0;
}
.CodeMirror-sizer {
position: relative;
border-right: 50px solid transparent;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actual scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
outline: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0; bottom: 0;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
min-height: 100%;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
display: inline-block;
vertical-align: top;
margin-bottom: -50px;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
background: none !important;
border: none !important;
}
.CodeMirror-gutter-background {
position: absolute;
top: 0; bottom: 0;
z-index: 4;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper ::selection { background-color: transparent }
.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre.CodeMirror-line,
.CodeMirror pre.CodeMirror-line-like {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
-webkit-font-variant-ligatures: contextual;
font-variant-ligatures: contextual;
}
.CodeMirror-wrap pre.CodeMirror-line,
.CodeMirror-wrap pre.CodeMirror-line-like {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
padding: 0.1px; /* Force widget margins to stay inside of the container */
}
.CodeMirror-widget {}
.CodeMirror-rtl pre { direction: rtl; }
.CodeMirror-code {
outline: none;
}
/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-cursor {
position: absolute;
pointer-events: none;
}
.CodeMirror-measure pre { position: static; }
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
div.CodeMirror-dragcursors {
visibility: visible;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
.cm-searching {
background-color: #ffa;
background-color: rgba(255, 255, 0, .4);
}
/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after { content: ''; }
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext { background: none; }
File diff suppressed because it is too large Load Diff
+866
View File
@@ -0,0 +1,866 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("css", function(config, parserConfig) {
var inline = parserConfig.inline
if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
var indentUnit = config.indentUnit,
tokenHooks = parserConfig.tokenHooks,
documentTypes = parserConfig.documentTypes || {},
mediaTypes = parserConfig.mediaTypes || {},
mediaFeatures = parserConfig.mediaFeatures || {},
mediaValueKeywords = parserConfig.mediaValueKeywords || {},
propertyKeywords = parserConfig.propertyKeywords || {},
nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
fontProperties = parserConfig.fontProperties || {},
counterDescriptors = parserConfig.counterDescriptors || {},
colorKeywords = parserConfig.colorKeywords || {},
valueKeywords = parserConfig.valueKeywords || {},
allowNested = parserConfig.allowNested,
lineComment = parserConfig.lineComment,
supportsAtComponent = parserConfig.supportsAtComponent === true,
highlightNonStandardPropertyKeywords = config.highlightNonStandardPropertyKeywords !== false;
var type, override;
function ret(style, tp) { type = tp; return style; }
// Tokenizers
function tokenBase(stream, state) {
var ch = stream.next();
if (tokenHooks[ch]) {
var result = tokenHooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == "@") {
stream.eatWhile(/[\w\\\-]/);
return ret("def", stream.current());
} else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
return ret(null, "compare");
} else if (ch == "\"" || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "#") {
stream.eatWhile(/[\w\\\-]/);
return ret("atom", "hash");
} else if (ch == "!") {
stream.match(/^\s*\w*/);
return ret("keyword", "important");
} else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (ch === "-") {
if (/[\d.]/.test(stream.peek())) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (stream.match(/^-[\w\\\-]*/)) {
stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false))
return ret("variable-2", "variable-definition");
return ret("variable-2", "variable");
} else if (stream.match(/^\w+-/)) {
return ret("meta", "meta");
}
} else if (/[,+>*\/]/.test(ch)) {
return ret(null, "select-op");
} else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
return ret("qualifier", "qualifier");
} else if (/[:;{}\[\]\(\)]/.test(ch)) {
return ret(null, ch);
} else if (stream.match(/^[\w-.]+(?=\()/)) {
if (/^(url(-prefix)?|domain|regexp)$/i.test(stream.current())) {
state.tokenize = tokenParenthesized;
}
return ret("variable callee", "variable");
} else if (/[\w\\\-]/.test(ch)) {
stream.eatWhile(/[\w\\\-]/);
return ret("property", "word");
} else {
return ret(null, null);
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) {
if (quote == ")") stream.backUp(1);
break;
}
escaped = !escaped && ch == "\\";
}
if (ch == quote || !escaped && quote != ")") state.tokenize = null;
return ret("string", "string");
};
}
function tokenParenthesized(stream, state) {
stream.next(); // Must be '('
if (!stream.match(/^\s*[\"\')]/, false))
state.tokenize = tokenString(")");
else
state.tokenize = null;
return ret(null, "(");
}
// Context management
function Context(type, indent, prev) {
this.type = type;
this.indent = indent;
this.prev = prev;
}
function pushContext(state, stream, type, indent) {
state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
return type;
}
function popContext(state) {
if (state.context.prev)
state.context = state.context.prev;
return state.context.type;
}
function pass(type, stream, state) {
return states[state.context.type](type, stream, state);
}
function popAndPass(type, stream, state, n) {
for (var i = n || 1; i > 0; i--)
state.context = state.context.prev;
return pass(type, stream, state);
}
// Parser
function wordAsValue(stream) {
var word = stream.current().toLowerCase();
if (valueKeywords.hasOwnProperty(word))
override = "atom";
else if (colorKeywords.hasOwnProperty(word))
override = "keyword";
else
override = "variable";
}
var states = {};
states.top = function(type, stream, state) {
if (type == "{") {
return pushContext(state, stream, "block");
} else if (type == "}" && state.context.prev) {
return popContext(state);
} else if (supportsAtComponent && /@component/i.test(type)) {
return pushContext(state, stream, "atComponentBlock");
} else if (/^@(-moz-)?document$/i.test(type)) {
return pushContext(state, stream, "documentTypes");
} else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
return pushContext(state, stream, "atBlock");
} else if (/^@(font-face|counter-style)/i.test(type)) {
state.stateArg = type;
return "restricted_atBlock_before";
} else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
return "keyframes";
} else if (type && type.charAt(0) == "@") {
return pushContext(state, stream, "at");
} else if (type == "hash") {
override = "builtin";
} else if (type == "word") {
override = "tag";
} else if (type == "variable-definition") {
return "maybeprop";
} else if (type == "interpolation") {
return pushContext(state, stream, "interpolation");
} else if (type == ":") {
return "pseudo";
} else if (allowNested && type == "(") {
return pushContext(state, stream, "parens");
}
return state.context.type;
};
states.block = function(type, stream, state) {
if (type == "word") {
var word = stream.current().toLowerCase();
if (propertyKeywords.hasOwnProperty(word)) {
override = "property";
return "maybeprop";
} else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
override = highlightNonStandardPropertyKeywords ? "string-2" : "property";
return "maybeprop";
} else if (allowNested) {
override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
return "block";
} else {
override += " error";
return "maybeprop";
}
} else if (type == "meta") {
return "block";
} else if (!allowNested && (type == "hash" || type == "qualifier")) {
override = "error";
return "block";
} else {
return states.top(type, stream, state);
}
};
states.maybeprop = function(type, stream, state) {
if (type == ":") return pushContext(state, stream, "prop");
return pass(type, stream, state);
};
states.prop = function(type, stream, state) {
if (type == ";") return popContext(state);
if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
if (type == "}" || type == "{") return popAndPass(type, stream, state);
if (type == "(") return pushContext(state, stream, "parens");
if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
override += " error";
} else if (type == "word") {
wordAsValue(stream);
} else if (type == "interpolation") {
return pushContext(state, stream, "interpolation");
}
return "prop";
};
states.propBlock = function(type, _stream, state) {
if (type == "}") return popContext(state);
if (type == "word") { override = "property"; return "maybeprop"; }
return state.context.type;
};
states.parens = function(type, stream, state) {
if (type == "{" || type == "}") return popAndPass(type, stream, state);
if (type == ")") return popContext(state);
if (type == "(") return pushContext(state, stream, "parens");
if (type == "interpolation") return pushContext(state, stream, "interpolation");
if (type == "word") wordAsValue(stream);
return "parens";
};
states.pseudo = function(type, stream, state) {
if (type == "meta") return "pseudo";
if (type == "word") {
override = "variable-3";
return state.context.type;
}
return pass(type, stream, state);
};
states.documentTypes = function(type, stream, state) {
if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
override = "tag";
return state.context.type;
} else {
return states.atBlock(type, stream, state);
}
};
states.atBlock = function(type, stream, state) {
if (type == "(") return pushContext(state, stream, "atBlock_parens");
if (type == "}" || type == ";") return popAndPass(type, stream, state);
if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
if (type == "interpolation") return pushContext(state, stream, "interpolation");
if (type == "word") {
var word = stream.current().toLowerCase();
if (word == "only" || word == "not" || word == "and" || word == "or")
override = "keyword";
else if (mediaTypes.hasOwnProperty(word))
override = "attribute";
else if (mediaFeatures.hasOwnProperty(word))
override = "property";
else if (mediaValueKeywords.hasOwnProperty(word))
override = "keyword";
else if (propertyKeywords.hasOwnProperty(word))
override = "property";
else if (nonStandardPropertyKeywords.hasOwnProperty(word))
override = highlightNonStandardPropertyKeywords ? "string-2" : "property";
else if (valueKeywords.hasOwnProperty(word))
override = "atom";
else if (colorKeywords.hasOwnProperty(word))
override = "keyword";
else
override = "error";
}
return state.context.type;
};
states.atComponentBlock = function(type, stream, state) {
if (type == "}")
return popAndPass(type, stream, state);
if (type == "{")
return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
if (type == "word")
override = "error";
return state.context.type;
};
states.atBlock_parens = function(type, stream, state) {
if (type == ")") return popContext(state);
if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
return states.atBlock(type, stream, state);
};
states.restricted_atBlock_before = function(type, stream, state) {
if (type == "{")
return pushContext(state, stream, "restricted_atBlock");
if (type == "word" && state.stateArg == "@counter-style") {
override = "variable";
return "restricted_atBlock_before";
}
return pass(type, stream, state);
};
states.restricted_atBlock = function(type, stream, state) {
if (type == "}") {
state.stateArg = null;
return popContext(state);
}
if (type == "word") {
if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
(state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
override = "error";
else
override = "property";
return "maybeprop";
}
return "restricted_atBlock";
};
states.keyframes = function(type, stream, state) {
if (type == "word") { override = "variable"; return "keyframes"; }
if (type == "{") return pushContext(state, stream, "top");
return pass(type, stream, state);
};
states.at = function(type, stream, state) {
if (type == ";") return popContext(state);
if (type == "{" || type == "}") return popAndPass(type, stream, state);
if (type == "word") override = "tag";
else if (type == "hash") override = "builtin";
return "at";
};
states.interpolation = function(type, stream, state) {
if (type == "}") return popContext(state);
if (type == "{" || type == ";") return popAndPass(type, stream, state);
if (type == "word") override = "variable";
else if (type != "variable" && type != "(" && type != ")") override = "error";
return "interpolation";
};
return {
startState: function(base) {
return {tokenize: null,
state: inline ? "block" : "top",
stateArg: null,
context: new Context(inline ? "block" : "top", base || 0, null)};
},
token: function(stream, state) {
if (!state.tokenize && stream.eatSpace()) return null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style && typeof style == "object") {
type = style[1];
style = style[0];
}
override = style;
if (type != "comment")
state.state = states[state.state](type, stream, state);
return override;
},
indent: function(state, textAfter) {
var cx = state.context, ch = textAfter && textAfter.charAt(0);
var indent = cx.indent;
if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
if (cx.prev) {
if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
// Resume indentation from parent context.
cx = cx.prev;
indent = cx.indent;
} else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
// Dedent relative to current context.
indent = Math.max(0, cx.indent - indentUnit);
}
}
return indent;
},
electricChars: "}",
blockCommentStart: "/*",
blockCommentEnd: "*/",
blockCommentContinue: " * ",
lineComment: lineComment,
fold: "brace"
};
});
function keySet(array) {
var keys = {};
for (var i = 0; i < array.length; ++i) {
keys[array[i].toLowerCase()] = true;
}
return keys;
}
var documentTypes_ = [
"domain", "regexp", "url", "url-prefix"
], documentTypes = keySet(documentTypes_);
var mediaTypes_ = [
"all", "aural", "braille", "handheld", "print", "projection", "screen",
"tty", "tv", "embossed"
], mediaTypes = keySet(mediaTypes_);
var mediaFeatures_ = [
"width", "min-width", "max-width", "height", "min-height", "max-height",
"device-width", "min-device-width", "max-device-width", "device-height",
"min-device-height", "max-device-height", "aspect-ratio",
"min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
"min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
"max-color", "color-index", "min-color-index", "max-color-index",
"monochrome", "min-monochrome", "max-monochrome", "resolution",
"min-resolution", "max-resolution", "scan", "grid", "orientation",
"device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
"pointer", "any-pointer", "hover", "any-hover", "prefers-color-scheme",
"dynamic-range", "video-dynamic-range"
], mediaFeatures = keySet(mediaFeatures_);
var mediaValueKeywords_ = [
"landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
"interlace", "progressive",
"dark", "light",
"standard", "high"
], mediaValueKeywords = keySet(mediaValueKeywords_);
var propertyKeywords_ = [
"align-content", "align-items", "align-self", "alignment-adjust",
"alignment-baseline", "all", "anchor-point", "animation", "animation-delay",
"animation-direction", "animation-duration", "animation-fill-mode",
"animation-iteration-count", "animation-name", "animation-play-state",
"animation-timing-function", "appearance", "azimuth", "backdrop-filter",
"backface-visibility", "background", "background-attachment",
"background-blend-mode", "background-clip", "background-color",
"background-image", "background-origin", "background-position",
"background-position-x", "background-position-y", "background-repeat",
"background-size", "baseline-shift", "binding", "bleed", "block-size",
"bookmark-label", "bookmark-level", "bookmark-state", "bookmark-target",
"border", "border-bottom", "border-bottom-color", "border-bottom-left-radius",
"border-bottom-right-radius", "border-bottom-style", "border-bottom-width",
"border-collapse", "border-color", "border-image", "border-image-outset",
"border-image-repeat", "border-image-slice", "border-image-source",
"border-image-width", "border-left", "border-left-color", "border-left-style",
"border-left-width", "border-radius", "border-right", "border-right-color",
"border-right-style", "border-right-width", "border-spacing", "border-style",
"border-top", "border-top-color", "border-top-left-radius",
"border-top-right-radius", "border-top-style", "border-top-width",
"border-width", "bottom", "box-decoration-break", "box-shadow", "box-sizing",
"break-after", "break-before", "break-inside", "caption-side", "caret-color",
"clear", "clip", "color", "color-profile", "column-count", "column-fill",
"column-gap", "column-rule", "column-rule-color", "column-rule-style",
"column-rule-width", "column-span", "column-width", "columns", "contain",
"content", "counter-increment", "counter-reset", "crop", "cue", "cue-after",
"cue-before", "cursor", "direction", "display", "dominant-baseline",
"drop-initial-after-adjust", "drop-initial-after-align",
"drop-initial-before-adjust", "drop-initial-before-align", "drop-initial-size",
"drop-initial-value", "elevation", "empty-cells", "fit", "fit-content", "fit-position",
"flex", "flex-basis", "flex-direction", "flex-flow", "flex-grow",
"flex-shrink", "flex-wrap", "float", "float-offset", "flow-from", "flow-into",
"font", "font-family", "font-feature-settings", "font-kerning",
"font-language-override", "font-optical-sizing", "font-size",
"font-size-adjust", "font-stretch", "font-style", "font-synthesis",
"font-variant", "font-variant-alternates", "font-variant-caps",
"font-variant-east-asian", "font-variant-ligatures", "font-variant-numeric",
"font-variant-position", "font-variation-settings", "font-weight", "gap",
"grid", "grid-area", "grid-auto-columns", "grid-auto-flow", "grid-auto-rows",
"grid-column", "grid-column-end", "grid-column-gap", "grid-column-start",
"grid-gap", "grid-row", "grid-row-end", "grid-row-gap", "grid-row-start",
"grid-template", "grid-template-areas", "grid-template-columns",
"grid-template-rows", "hanging-punctuation", "height", "hyphens", "icon",
"image-orientation", "image-rendering", "image-resolution", "inline-box-align",
"inset", "inset-block", "inset-block-end", "inset-block-start", "inset-inline",
"inset-inline-end", "inset-inline-start", "isolation", "justify-content",
"justify-items", "justify-self", "left", "letter-spacing", "line-break",
"line-height", "line-height-step", "line-stacking", "line-stacking-ruby",
"line-stacking-shift", "line-stacking-strategy", "list-style",
"list-style-image", "list-style-position", "list-style-type", "margin",
"margin-bottom", "margin-left", "margin-right", "margin-top", "marks",
"marquee-direction", "marquee-loop", "marquee-play-count", "marquee-speed",
"marquee-style", "mask-clip", "mask-composite", "mask-image", "mask-mode",
"mask-origin", "mask-position", "mask-repeat", "mask-size","mask-type",
"max-block-size", "max-height", "max-inline-size",
"max-width", "min-block-size", "min-height", "min-inline-size", "min-width",
"mix-blend-mode", "move-to", "nav-down", "nav-index", "nav-left", "nav-right",
"nav-up", "object-fit", "object-position", "offset", "offset-anchor",
"offset-distance", "offset-path", "offset-position", "offset-rotate",
"opacity", "order", "orphans", "outline", "outline-color", "outline-offset",
"outline-style", "outline-width", "overflow", "overflow-style",
"overflow-wrap", "overflow-x", "overflow-y", "padding", "padding-bottom",
"padding-left", "padding-right", "padding-top", "page", "page-break-after",
"page-break-before", "page-break-inside", "page-policy", "pause",
"pause-after", "pause-before", "perspective", "perspective-origin", "pitch",
"pitch-range", "place-content", "place-items", "place-self", "play-during",
"position", "presentation-level", "punctuation-trim", "quotes",
"region-break-after", "region-break-before", "region-break-inside",
"region-fragment", "rendering-intent", "resize", "rest", "rest-after",
"rest-before", "richness", "right", "rotate", "rotation", "rotation-point",
"row-gap", "ruby-align", "ruby-overhang", "ruby-position", "ruby-span",
"scale", "scroll-behavior", "scroll-margin", "scroll-margin-block",
"scroll-margin-block-end", "scroll-margin-block-start", "scroll-margin-bottom",
"scroll-margin-inline", "scroll-margin-inline-end",
"scroll-margin-inline-start", "scroll-margin-left", "scroll-margin-right",
"scroll-margin-top", "scroll-padding", "scroll-padding-block",
"scroll-padding-block-end", "scroll-padding-block-start",
"scroll-padding-bottom", "scroll-padding-inline", "scroll-padding-inline-end",
"scroll-padding-inline-start", "scroll-padding-left", "scroll-padding-right",
"scroll-padding-top", "scroll-snap-align", "scroll-snap-type",
"shape-image-threshold", "shape-inside", "shape-margin", "shape-outside",
"size", "speak", "speak-as", "speak-header", "speak-numeral",
"speak-punctuation", "speech-rate", "stress", "string-set", "tab-size",
"table-layout", "target", "target-name", "target-new", "target-position",
"text-align", "text-align-last", "text-combine-upright", "text-decoration",
"text-decoration-color", "text-decoration-line", "text-decoration-skip",
"text-decoration-skip-ink", "text-decoration-style", "text-emphasis",
"text-emphasis-color", "text-emphasis-position", "text-emphasis-style",
"text-height", "text-indent", "text-justify", "text-orientation",
"text-outline", "text-overflow", "text-rendering", "text-shadow",
"text-size-adjust", "text-space-collapse", "text-transform",
"text-underline-position", "text-wrap", "top", "touch-action", "transform", "transform-origin",
"transform-style", "transition", "transition-delay", "transition-duration",
"transition-property", "transition-timing-function", "translate",
"unicode-bidi", "user-select", "vertical-align", "visibility", "voice-balance",
"voice-duration", "voice-family", "voice-pitch", "voice-range", "voice-rate",
"voice-stress", "voice-volume", "volume", "white-space", "widows", "width",
"will-change", "word-break", "word-spacing", "word-wrap", "writing-mode", "z-index",
// SVG-specific
"clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
"flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
"color-interpolation", "color-interpolation-filters",
"color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
"marker", "marker-end", "marker-mid", "marker-start", "paint-order", "shape-rendering", "stroke",
"stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
"stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
"baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
"glyph-orientation-vertical", "text-anchor", "writing-mode",
], propertyKeywords = keySet(propertyKeywords_);
var nonStandardPropertyKeywords_ = [
"accent-color", "aspect-ratio", "border-block", "border-block-color", "border-block-end",
"border-block-end-color", "border-block-end-style", "border-block-end-width",
"border-block-start", "border-block-start-color", "border-block-start-style",
"border-block-start-width", "border-block-style", "border-block-width",
"border-inline", "border-inline-color", "border-inline-end",
"border-inline-end-color", "border-inline-end-style",
"border-inline-end-width", "border-inline-start", "border-inline-start-color",
"border-inline-start-style", "border-inline-start-width",
"border-inline-style", "border-inline-width", "content-visibility", "margin-block",
"margin-block-end", "margin-block-start", "margin-inline", "margin-inline-end",
"margin-inline-start", "overflow-anchor", "overscroll-behavior", "padding-block", "padding-block-end",
"padding-block-start", "padding-inline", "padding-inline-end",
"padding-inline-start", "scroll-snap-stop", "scrollbar-3d-light-color",
"scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
"scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
"scrollbar-track-color", "searchfield-cancel-button", "searchfield-decoration",
"searchfield-results-button", "searchfield-results-decoration", "shape-inside", "zoom"
], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
var fontProperties_ = [
"font-display", "font-family", "src", "unicode-range", "font-variant",
"font-feature-settings", "font-stretch", "font-weight", "font-style"
], fontProperties = keySet(fontProperties_);
var counterDescriptors_ = [
"additive-symbols", "fallback", "negative", "pad", "prefix", "range",
"speak-as", "suffix", "symbols", "system"
], counterDescriptors = keySet(counterDescriptors_);
var colorKeywords_ = [
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
"bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
"burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
"cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
"darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen",
"darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
"darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet",
"deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick",
"floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
"gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
"hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
"lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
"lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink",
"lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey",
"lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
"maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
"mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
"mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
"navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
"orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
"papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
"purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
"salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
"slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan",
"teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
"whitesmoke", "yellow", "yellowgreen"
], colorKeywords = keySet(colorKeywords_);
var valueKeywords_ = [
"above", "absolute", "activeborder", "additive", "activecaption", "afar",
"after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
"always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
"arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page",
"avoid-region", "axis-pan", "background", "backwards", "baseline", "below", "bidi-override", "binary",
"bengali", "blink", "block", "block-axis", "blur", "bold", "bolder", "border", "border-box",
"both", "bottom", "break", "break-all", "break-word", "brightness", "bullets", "button", "button-bevel",
"buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
"capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
"cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
"cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
"col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
"compact", "condensed", "conic-gradient", "contain", "content", "contents",
"content-box", "context-menu", "continuous", "contrast", "copy", "counter", "counters", "cover", "crop",
"cross", "crosshair", "cubic-bezier", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
"decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
"destination-in", "destination-out", "destination-over", "devanagari", "difference",
"disc", "discard", "disclosure-closed", "disclosure-open", "document",
"dot-dash", "dot-dot-dash",
"dotted", "double", "down", "drop-shadow", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
"element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
"ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
"ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
"ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
"ethiopic-halehame-gez", "ethiopic-halehame-om-et",
"ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
"ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
"ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
"extra-expanded", "fantasy", "fast", "fill", "fill-box", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
"forwards", "from", "geometricPrecision", "georgian", "grayscale", "graytext", "grid", "groove",
"gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
"help", "hidden", "hide", "higher", "highlight", "highlighttext",
"hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "hue-rotate", "icon", "ignore",
"inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
"infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
"inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
"italic", "japanese-formal", "japanese-informal", "justify", "kannada",
"katakana", "katakana-iroha", "keep-all", "khmer",
"korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
"landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
"line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
"local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
"lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
"lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "manipulation", "match", "matrix", "matrix3d",
"media-controls-background", "media-current-time-display",
"media-fullscreen-button", "media-mute-button", "media-play-button",
"media-return-to-realtime-button", "media-rewind-button",
"media-seek-back-button", "media-seek-forward-button", "media-slider",
"media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
"media-volume-slider-container", "media-volume-sliderthumb", "medium",
"menu", "menulist", "menulist-button", "menulist-text",
"menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
"mix", "mongolian", "monospace", "move", "multiple", "multiple_mask_images", "multiply", "myanmar", "n-resize",
"narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
"no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
"ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote",
"optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
"outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
"painted", "page", "paused", "persian", "perspective", "pinch-zoom", "plus-darker", "plus-lighter",
"pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
"progress", "push-button", "radial-gradient", "radio", "read-only",
"read-write", "read-write-plaintext-only", "rectangle", "region",
"relative", "repeat", "repeating-linear-gradient", "repeating-radial-gradient",
"repeating-conic-gradient", "repeat-x", "repeat-y", "reset", "reverse",
"rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
"rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
"s-resize", "sans-serif", "saturate", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
"scroll", "scrollbar", "scroll-position", "se-resize", "searchfield",
"searchfield-cancel-button", "searchfield-decoration",
"searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end",
"semi-condensed", "semi-expanded", "separate", "sepia", "serif", "show", "sidama",
"simp-chinese-formal", "simp-chinese-informal", "single",
"skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
"slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
"small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
"source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square",
"square-button", "start", "static", "status-bar", "stretch", "stroke", "stroke-box", "sub",
"subpixel-antialiased", "svg_masks", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table",
"table-caption", "table-cell", "table-column", "table-column-group",
"table-footer-group", "table-header-group", "table-row", "table-row-group",
"tamil",
"telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
"thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
"threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
"tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
"trad-chinese-formal", "trad-chinese-informal", "transform",
"translate", "translate3d", "translateX", "translateY", "translateZ",
"transparent", "ultra-condensed", "ultra-expanded", "underline", "unidirectional-pan", "unset", "up",
"upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
"upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
"var", "vertical", "vertical-text", "view-box", "visible", "visibleFill", "visiblePainted",
"visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
"window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
"xx-large", "xx-small"
], valueKeywords = keySet(valueKeywords_);
var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
.concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
.concat(valueKeywords_);
CodeMirror.registerHelper("hintWords", "css", allWords);
function tokenCComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (maybeEnd && ch == "/") {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return ["comment", "comment"];
}
CodeMirror.defineMIME("text/css", {
documentTypes: documentTypes,
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
fontProperties: fontProperties,
counterDescriptors: counterDescriptors,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
tokenHooks: {
"/": function(stream, state) {
if (!stream.eat("*")) return false;
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
},
name: "css"
});
CodeMirror.defineMIME("text/x-scss", {
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
fontProperties: fontProperties,
allowNested: true,
lineComment: "//",
tokenHooks: {
"/": function(stream, state) {
if (stream.eat("/")) {
stream.skipToEnd();
return ["comment", "comment"];
} else if (stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
} else {
return ["operator", "operator"];
}
},
":": function(stream) {
if (stream.match(/^\s*\{/, false))
return [null, null]
return false;
},
"$": function(stream) {
stream.match(/^[\w-]+/);
if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"];
return ["variable-2", "variable"];
},
"#": function(stream) {
if (!stream.eat("{")) return false;
return [null, "interpolation"];
}
},
name: "css",
helperType: "scss"
});
CodeMirror.defineMIME("text/x-less", {
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
mediaValueKeywords: mediaValueKeywords,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
fontProperties: fontProperties,
allowNested: true,
lineComment: "//",
tokenHooks: {
"/": function(stream, state) {
if (stream.eat("/")) {
stream.skipToEnd();
return ["comment", "comment"];
} else if (stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
} else {
return ["operator", "operator"];
}
},
"@": function(stream) {
if (stream.eat("{")) return [null, "interpolation"];
if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"];
return ["variable-2", "variable"];
},
"&": function() {
return ["atom", "atom"];
}
},
name: "css",
helperType: "less"
});
CodeMirror.defineMIME("text/x-gss", {
documentTypes: documentTypes,
mediaTypes: mediaTypes,
mediaFeatures: mediaFeatures,
propertyKeywords: propertyKeywords,
nonStandardPropertyKeywords: nonStandardPropertyKeywords,
fontProperties: fontProperties,
counterDescriptors: counterDescriptors,
colorKeywords: colorKeywords,
valueKeywords: valueKeywords,
supportsAtComponent: true,
tokenHooks: {
"/": function(stream, state) {
if (!stream.eat("*")) return false;
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
},
name: "css",
helperType: "gss"
});
});
+960
View File
@@ -0,0 +1,960 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var statementIndent = parserConfig.statementIndent;
var jsonldMode = parserConfig.jsonld;
var jsonMode = parserConfig.json || jsonldMode;
var trackScope = parserConfig.trackScope !== false
var isTS = parserConfig.typescript;
var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
return {
"if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
"debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
"function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
"this": kw("this"), "class": kw("class"), "super": kw("atom"),
"yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
"await": C
};
}();
var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
function readRegexp(stream) {
var escaped = false, next, inSet = false;
while ((next = stream.next()) != null) {
if (!escaped) {
if (next == "/" && !inSet) return;
if (next == "[") inSet = true;
else if (inSet && next == "]") inSet = false;
}
escaped = !escaped && next == "\\";
}
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
return ret("number", "number");
} else if (ch == "." && stream.match("..")) {
return ret("spread", "meta");
} else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
return ret(ch);
} else if (ch == "=" && stream.eat(">")) {
return ret("=>", "operator");
} else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
return ret("number", "number");
} else if (/\d/.test(ch)) {
stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
return ret("number", "number");
} else if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
} else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
} else if (expressionAllowed(stream, state, 1)) {
readRegexp(stream);
stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
return ret("regexp", "string-2");
} else {
stream.eat("=");
return ret("operator", "operator", stream.current());
}
} else if (ch == "`") {
state.tokenize = tokenQuasi;
return tokenQuasi(stream, state);
} else if (ch == "#" && stream.peek() == "!") {
stream.skipToEnd();
return ret("meta", "meta");
} else if (ch == "#" && stream.eatWhile(wordRE)) {
return ret("variable", "property")
} else if (ch == "<" && stream.match("!--") ||
(ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) {
stream.skipToEnd()
return ret("comment", "comment")
} else if (isOperatorChar.test(ch)) {
if (ch != ">" || !state.lexical || state.lexical.type != ">") {
if (stream.eat("=")) {
if (ch == "!" || ch == "=") stream.eat("=")
} else if (/[<>*+\-|&?]/.test(ch)) {
stream.eat(ch)
if (ch == ">") stream.eat(ch)
}
}
if (ch == "?" && stream.eat(".")) return ret(".")
return ret("operator", "operator", stream.current());
} else if (wordRE.test(ch)) {
stream.eatWhile(wordRE);
var word = stream.current()
if (state.lastType != ".") {
if (keywords.propertyIsEnumerable(word)) {
var kw = keywords[word]
return ret(kw.type, kw.style, word)
}
if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false))
return ret("async", "keyword", word)
}
return ret("variable", "variable", word)
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next;
if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
state.tokenize = tokenBase;
return ret("jsonld-keyword", "meta");
}
while ((next = stream.next()) != null) {
if (next == quote && !escaped) break;
escaped = !escaped && next == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenQuasi(stream, state) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && next == "\\";
}
return ret("quasi", "string-2", stream.current());
}
var brackets = "([{}])";
// This is a crude lookahead trick to try and notice that we're
// parsing the argument patterns for a fat-arrow function before we
// actually hit the arrow token. It only works if the arrow is on
// the same line as the arguments and there's no strange noise
// (comments) in between. Fallback is to only notice when we hit the
// arrow, and not declare the arguments as locals for the arrow
// body.
function findFatArrow(stream, state) {
if (state.fatArrowAt) state.fatArrowAt = null;
var arrow = stream.string.indexOf("=>", stream.start);
if (arrow < 0) return;
if (isTS) { // Try to skip TypeScript return type declarations after the arguments
var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
if (m) arrow = m.index
}
var depth = 0, sawSomething = false;
for (var pos = arrow - 1; pos >= 0; --pos) {
var ch = stream.string.charAt(pos);
var bracket = brackets.indexOf(ch);
if (bracket >= 0 && bracket < 3) {
if (!depth) { ++pos; break; }
if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
} else if (bracket >= 3 && bracket < 6) {
++depth;
} else if (wordRE.test(ch)) {
sawSomething = true;
} else if (/["'\/`]/.test(ch)) {
for (;; --pos) {
if (pos == 0) return
var next = stream.string.charAt(pos - 1)
if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break }
}
} else if (sawSomething && !depth) {
++pos;
break;
}
}
if (sawSomething && !depth) state.fatArrowAt = pos;
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true,
"regexp": true, "this": true, "import": true, "jsonld-keyword": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
if (!trackScope) return false
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
for (var cx = state.context; cx; cx = cx.prev) {
for (var v = cx.vars; v; v = v.next)
if (v.name == varname) return true;
}
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function inList(name, list) {
for (var v = list; v; v = v.next) if (v.name == name) return true
return false;
}
function register(varname) {
var state = cx.state;
cx.marked = "def";
if (!trackScope) return
if (state.context) {
if (state.lexical.info == "var" && state.context && state.context.block) {
// FIXME function decls are also not block scoped
var newContext = registerVarScoped(varname, state.context)
if (newContext != null) {
state.context = newContext
return
}
} else if (!inList(varname, state.localVars)) {
state.localVars = new Var(varname, state.localVars)
return
}
}
// Fall through means this is global
if (parserConfig.globalVars && !inList(varname, state.globalVars))
state.globalVars = new Var(varname, state.globalVars)
}
function registerVarScoped(varname, context) {
if (!context) {
return null
} else if (context.block) {
var inner = registerVarScoped(varname, context.prev)
if (!inner) return null
if (inner == context.prev) return context
return new Context(inner, context.vars, true)
} else if (inList(varname, context.vars)) {
return context
} else {
return new Context(context.prev, new Var(varname, context.vars), false)
}
}
function isModifier(name) {
return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
}
// Combinators
function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
function Var(name, next) { this.name = name; this.next = next }
var defaultVars = new Var("this", new Var("arguments", null))
function pushcontext() {
cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
cx.state.localVars = defaultVars
}
function pushblockcontext() {
cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
cx.state.localVars = null
}
pushcontext.lex = pushblockcontext.lex = true
function popcontext() {
cx.state.localVars = cx.state.context.vars
cx.state.context = cx.state.context.prev
}
popcontext.lex = true
function pushlex(type, info) {
var result = function() {
var state = cx.state, indent = state.indented;
if (state.lexical.type == "stat") indent = state.lexical.indented;
else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
indent = outer.indented;
state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
function exp(type) {
if (type == wanted) return cont();
else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
else return cont(exp);
};
return exp;
}
function statement(type, value) {
if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
if (type == "debugger") return cont(expect(";"));
if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
if (type == ";") return cont();
if (type == "if") {
if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
cx.state.cc.pop()();
return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
}
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex);
if (type == "class" || (isTS && value == "interface")) {
cx.marked = "keyword"
return cont(pushlex("form", type == "class" ? type : value), className, poplex)
}
if (type == "variable") {
if (isTS && value == "declare") {
cx.marked = "keyword"
return cont(statement)
} else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
cx.marked = "keyword"
if (value == "enum") return cont(enumdef);
else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));
else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
} else if (isTS && value == "namespace") {
cx.marked = "keyword"
return cont(pushlex("form"), expression, statement, poplex)
} else if (isTS && value == "abstract") {
cx.marked = "keyword"
return cont(statement)
} else {
return cont(pushlex("stat"), maybelabel);
}
}
if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
block, poplex, poplex, popcontext);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
if (type == "async") return cont(statement)
if (value == "@") return cont(expression, statement)
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function maybeCatchBinding(type) {
if (type == "(") return cont(funarg, expect(")"))
}
function expression(type, value) {
return expressionInner(type, value, false);
}
function expressionNoComma(type, value) {
return expressionInner(type, value, true);
}
function parenExpr(type) {
if (type != "(") return pass()
return cont(pushlex(")"), maybeexpression, expect(")"), poplex)
}
function expressionInner(type, value, noComma) {
if (cx.state.fatArrowAt == cx.stream.start) {
var body = noComma ? arrowBodyNoComma : arrowBody;
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
}
var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
if (type == "function") return cont(functiondef, maybeop);
if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
if (type == "{") return contCommasep(objprop, "}", null, maybeop);
if (type == "quasi") return pass(quasi, maybeop);
if (type == "new") return cont(maybeTarget(noComma));
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeoperatorComma(type, value) {
if (type == ",") return cont(maybeexpression);
return maybeoperatorNoComma(type, value, false);
}
function maybeoperatorNoComma(type, value, noComma) {
var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
var expr = noComma == false ? expression : expressionNoComma;
if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
if (type == "operator") {
if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false))
return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
if (value == "?") return cont(expression, expect(":"), expr);
return cont(expr);
}
if (type == "quasi") { return pass(quasi, me); }
if (type == ";") return;
if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
if (type == ".") return cont(property, me);
if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
if (type == "regexp") {
cx.state.lastType = cx.marked = "operator"
cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
return cont(expr)
}
}
function quasi(type, value) {
if (type != "quasi") return pass();
if (value.slice(value.length - 2) != "${") return cont(quasi);
return cont(maybeexpression, continueQuasi);
}
function continueQuasi(type) {
if (type == "}") {
cx.marked = "string-2";
cx.state.tokenize = tokenQuasi;
return cont(quasi);
}
}
function arrowBody(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expression);
}
function arrowBodyNoComma(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expressionNoComma);
}
function maybeTarget(noComma) {
return function(type) {
if (type == ".") return cont(noComma ? targetNoComma : target);
else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
else return pass(noComma ? expressionNoComma : expression);
};
}
function target(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
}
function targetNoComma(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperatorComma, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type, value) {
if (type == "async") {
cx.marked = "property";
return cont(objprop);
} else if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
if (value == "get" || value == "set") return cont(getterSetter);
var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
cx.state.fatArrowAt = cx.stream.pos + m[0].length
return cont(afterprop);
} else if (type == "number" || type == "string") {
cx.marked = jsonldMode ? "property" : (cx.style + " property");
return cont(afterprop);
} else if (type == "jsonld-keyword") {
return cont(afterprop);
} else if (isTS && isModifier(value)) {
cx.marked = "keyword"
return cont(objprop)
} else if (type == "[") {
return cont(expression, maybetype, expect("]"), afterprop);
} else if (type == "spread") {
return cont(expressionNoComma, afterprop);
} else if (value == "*") {
cx.marked = "keyword";
return cont(objprop);
} else if (type == ":") {
return pass(afterprop)
}
}
function getterSetter(type) {
if (type != "variable") return pass(afterprop);
cx.marked = "property";
return cont(functiondef);
}
function afterprop(type) {
if (type == ":") return cont(expressionNoComma);
if (type == "(") return pass(functiondef);
}
function commasep(what, end, sep) {
function proceed(type, value) {
if (sep ? sep.indexOf(type) > -1 : type == ",") {
var lex = cx.state.lexical;
if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
return cont(function(type, value) {
if (type == end || value == end) return pass()
return pass(what)
}, proceed);
}
if (type == end || value == end) return cont();
if (sep && sep.indexOf(";") > -1) return pass(what)
return cont(expect(end));
}
return function(type, value) {
if (type == end || value == end) return cont();
return pass(what, proceed);
};
}
function contCommasep(what, end, info) {
for (var i = 3; i < arguments.length; i++)
cx.cc.push(arguments[i]);
return cont(pushlex(end, info), commasep(what, end), poplex);
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function maybetype(type, value) {
if (isTS) {
if (type == ":") return cont(typeexpr);
if (value == "?") return cont(maybetype);
}
}
function maybetypeOrIn(type, value) {
if (isTS && (type == ":" || value == "in")) return cont(typeexpr)
}
function mayberettype(type) {
if (isTS && type == ":") {
if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
else return cont(typeexpr)
}
}
function isKW(_, value) {
if (value == "is") {
cx.marked = "keyword"
return cont()
}
}
function typeexpr(type, value) {
if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") {
cx.marked = "keyword"
return cont(value == "typeof" ? expressionNoComma : typeexpr)
}
if (type == "variable" || value == "void") {
cx.marked = "type"
return cont(afterType)
}
if (value == "|" || value == "&") return cont(typeexpr)
if (type == "string" || type == "number" || type == "atom") return cont(afterType);
if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
if (type == "{") return cont(pushlex("}"), typeprops, poplex, afterType)
if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType)
if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
if (type == "quasi") { return pass(quasiType, afterType); }
}
function maybeReturnType(type) {
if (type == "=>") return cont(typeexpr)
}
function typeprops(type) {
if (type.match(/[\}\)\]]/)) return cont()
if (type == "," || type == ";") return cont(typeprops)
return pass(typeprop, typeprops)
}
function typeprop(type, value) {
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property"
return cont(typeprop)
} else if (value == "?" || type == "number" || type == "string") {
return cont(typeprop)
} else if (type == ":") {
return cont(typeexpr)
} else if (type == "[") {
return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop)
} else if (type == "(") {
return pass(functiondecl, typeprop)
} else if (!type.match(/[;\}\)\],]/)) {
return cont()
}
}
function quasiType(type, value) {
if (type != "quasi") return pass();
if (value.slice(value.length - 2) != "${") return cont(quasiType);
return cont(typeexpr, continueQuasiType);
}
function continueQuasiType(type) {
if (type == "}") {
cx.marked = "string-2";
cx.state.tokenize = tokenQuasi;
return cont(quasiType);
}
}
function typearg(type, value) {
if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
if (type == ":") return cont(typeexpr)
if (type == "spread") return cont(typearg)
return pass(typeexpr)
}
function afterType(type, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
if (value == "|" || type == "." || value == "&") return cont(typeexpr)
if (type == "[") return cont(typeexpr, expect("]"), afterType)
if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
if (value == "?") return cont(typeexpr, expect(":"), typeexpr)
}
function maybeTypeArgs(_, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
}
function typeparam() {
return pass(typeexpr, maybeTypeDefault)
}
function maybeTypeDefault(_, value) {
if (value == "=") return cont(typeexpr)
}
function vardef(_, value) {
if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
return pass(pattern, maybetype, maybeAssign, vardefCont);
}
function pattern(type, value) {
if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
if (type == "variable") { register(value); return cont(); }
if (type == "spread") return cont(pattern);
if (type == "[") return contCommasep(eltpattern, "]");
if (type == "{") return contCommasep(proppattern, "}");
}
function proppattern(type, value) {
if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
register(value);
return cont(maybeAssign);
}
if (type == "variable") cx.marked = "property";
if (type == "spread") return cont(pattern);
if (type == "}") return pass();
if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
return cont(expect(":"), pattern, maybeAssign);
}
function eltpattern() {
return pass(pattern, maybeAssign)
}
function maybeAssign(_type, value) {
if (value == "=") return cont(expressionNoComma);
}
function vardefCont(type) {
if (type == ",") return cont(vardef);
}
function maybeelse(type, value) {
if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
}
function forspec(type, value) {
if (value == "await") return cont(forspec);
if (type == "(") return cont(pushlex(")"), forspec1, poplex);
}
function forspec1(type) {
if (type == "var") return cont(vardef, forspec2);
if (type == "variable") return cont(forspec2);
return pass(forspec2)
}
function forspec2(type, value) {
if (type == ")") return cont()
if (type == ";") return cont(forspec2)
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) }
return pass(expression, forspec2)
}
function functiondef(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
}
function functiondecl(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);}
if (type == "variable") {register(value); return cont(functiondecl);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl)
}
function typename(type, value) {
if (type == "keyword" || type == "variable") {
cx.marked = "type"
return cont(typename)
} else if (value == "<") {
return cont(pushlex(">"), commasep(typeparam, ">"), poplex)
}
}
function funarg(type, value) {
if (value == "@") cont(expression, funarg)
if (type == "spread") return cont(funarg);
if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
if (isTS && type == "this") return cont(maybetype, maybeAssign)
return pass(pattern, maybetype, maybeAssign);
}
function classExpression(type, value) {
// Class expressions may have an optional name.
if (type == "variable") return className(type, value);
return classNameAfter(type, value);
}
function className(type, value) {
if (type == "variable") {register(value); return cont(classNameAfter);}
}
function classNameAfter(type, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
if (value == "extends" || value == "implements" || (isTS && type == ",")) {
if (value == "implements") cx.marked = "keyword";
return cont(isTS ? typeexpr : expression, classNameAfter);
}
if (type == "{") return cont(pushlex("}"), classBody, poplex);
}
function classBody(type, value) {
if (type == "async" ||
(type == "variable" &&
(value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
cx.marked = "keyword";
return cont(classBody);
}
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
return cont(classfield, classBody);
}
if (type == "number" || type == "string") return cont(classfield, classBody);
if (type == "[")
return cont(expression, maybetype, expect("]"), classfield, classBody)
if (value == "*") {
cx.marked = "keyword";
return cont(classBody);
}
if (isTS && type == "(") return pass(functiondecl, classBody)
if (type == ";" || type == ",") return cont(classBody);
if (type == "}") return cont();
if (value == "@") return cont(expression, classBody)
}
function classfield(type, value) {
if (value == "!") return cont(classfield)
if (value == "?") return cont(classfield)
if (type == ":") return cont(typeexpr, maybeAssign)
if (value == "=") return cont(expressionNoComma)
var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"
return pass(isInterface ? functiondecl : functiondef)
}
function afterExport(type, value) {
if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
return pass(statement);
}
function exportField(type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
if (type == "variable") return pass(expressionNoComma, exportField);
}
function afterImport(type) {
if (type == "string") return cont();
if (type == "(") return pass(expression);
if (type == ".") return pass(maybeoperatorComma);
return pass(importSpec, maybeMoreImports, maybeFrom);
}
function importSpec(type, value) {
if (type == "{") return contCommasep(importSpec, "}");
if (type == "variable") register(value);
if (value == "*") cx.marked = "keyword";
return cont(maybeAs);
}
function maybeMoreImports(type) {
if (type == ",") return cont(importSpec, maybeMoreImports)
}
function maybeAs(_type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
}
function maybeFrom(_type, value) {
if (value == "from") { cx.marked = "keyword"; return cont(expression); }
}
function arrayLiteral(type) {
if (type == "]") return cont();
return pass(commasep(expressionNoComma, "]"));
}
function enumdef() {
return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
}
function enummember() {
return pass(pattern, maybeAssign);
}
function isContinuedStatement(state, textAfter) {
return state.lastType == "operator" || state.lastType == "," ||
isOperatorChar.test(textAfter.charAt(0)) ||
/[,.]/.test(textAfter.charAt(0));
}
function expressionAllowed(stream, state, backUp) {
return state.tokenize == tokenBase &&
/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
(state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
}
// Interface
return {
startState: function(basecolumn) {
var state = {
tokenize: tokenBase,
lastType: "sof",
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
context: parserConfig.localVars && new Context(null, null, false),
indented: basecolumn || 0
};
if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
state.globalVars = parserConfig.globalVars;
return state;
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
findFatArrow(stream, state);
}
if (state.tokenize != tokenComment && stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass;
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
// Kludge to prevent 'maybelse' from blocking lexical scope pops
if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
var c = state.cc[i];
if (c == poplex) lexical = lexical.prev;
else if (c != maybeelse && c != popcontext) break;
}
while ((lexical.type == "stat" || lexical.type == "form") &&
(firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
(top == maybeoperatorComma || top == maybeoperatorNoComma) &&
!/^[,\.=+\-*:?[\(]/.test(textAfter))))
lexical = lexical.prev;
if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "form") return lexical.indented + indentUnit;
else if (type == "stat")
return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
blockCommentStart: jsonMode ? null : "/*",
blockCommentEnd: jsonMode ? null : "*/",
blockCommentContinue: jsonMode ? null : " * ",
lineComment: jsonMode ? null : "//",
fold: "brace",
closeBrackets: "()[]{}''\"\"``",
helperType: jsonMode ? "json" : "javascript",
jsonldMode: jsonldMode,
jsonMode: jsonMode,
expressionAllowed: expressionAllowed,
skipExpression: function(state) {
parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null))
}
};
});
CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", { name: "javascript", json: true });
CodeMirror.defineMIME("application/x-json", { name: "javascript", json: true });
CodeMirror.defineMIME("application/manifest+json", { name: "javascript", json: true })
CodeMirror.defineMIME("application/ld+json", { name: "javascript", jsonld: true });
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
});
+141
View File
@@ -0,0 +1,141 @@
/*
Name: material
Author: Mattia Astorino (http://github.com/equinusocio)
Website: https://material-theme.site/
*/
.cm-s-material.CodeMirror {
background-color: #263238;
color: #EEFFFF;
}
.cm-s-material .CodeMirror-gutters {
background: #263238;
color: #546E7A;
border: none;
}
.cm-s-material .CodeMirror-guttermarker,
.cm-s-material .CodeMirror-guttermarker-subtle,
.cm-s-material .CodeMirror-linenumber {
color: #546E7A;
}
.cm-s-material .CodeMirror-cursor {
border-left: 1px solid #FFCC00;
}
.cm-s-material.cm-fat-cursor .CodeMirror-cursor {
background-color: #5d6d5c80 !important;
}
.cm-s-material .cm-animate-fat-cursor {
background-color: #5d6d5c80 !important;
}
.cm-s-material div.CodeMirror-selected {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material.CodeMirror-focused div.CodeMirror-selected {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material .CodeMirror-line::selection,
.cm-s-material .CodeMirror-line>span::selection,
.cm-s-material .CodeMirror-line>span>span::selection {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material .CodeMirror-line::-moz-selection,
.cm-s-material .CodeMirror-line>span::-moz-selection,
.cm-s-material .CodeMirror-line>span>span::-moz-selection {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material .CodeMirror-activeline-background {
background: rgba(0, 0, 0, 0.5);
}
.cm-s-material .cm-keyword {
color: #C792EA;
}
.cm-s-material .cm-operator {
color: #89DDFF;
}
.cm-s-material .cm-variable-2 {
color: #EEFFFF;
}
.cm-s-material .cm-variable-3,
.cm-s-material .cm-type {
color: #f07178;
}
.cm-s-material .cm-builtin {
color: #FFCB6B;
}
.cm-s-material .cm-atom {
color: #F78C6C;
}
.cm-s-material .cm-number {
color: #FF5370;
}
.cm-s-material .cm-def {
color: #82AAFF;
}
.cm-s-material .cm-string {
color: #C3E88D;
}
.cm-s-material .cm-string-2 {
color: #f07178;
}
.cm-s-material .cm-comment {
color: #546E7A;
}
.cm-s-material .cm-variable {
color: #f07178;
}
.cm-s-material .cm-tag {
color: #FF5370;
}
.cm-s-material .cm-meta {
color: #FFCB6B;
}
.cm-s-material .cm-attribute {
color: #C792EA;
}
.cm-s-material .cm-property {
color: #C792EA;
}
.cm-s-material .cm-qualifier {
color: #DECB6B;
}
.cm-s-material .cm-variable-3,
.cm-s-material .cm-type {
color: #DECB6B;
}
.cm-s-material .cm-error {
color: rgba(255, 255, 255, 1.0);
background-color: #FF5370;
}
.cm-s-material .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
+402
View File
@@ -0,0 +1,402 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var wordOperators = wordRegexp(["and", "or", "not", "is"]);
var commonKeywords = ["as", "assert", "break", "class", "continue",
"def", "del", "elif", "else", "except", "finally",
"for", "from", "global", "if", "import",
"lambda", "pass", "raise", "return",
"try", "while", "with", "yield", "in"];
var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
"classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "filter", "float", "format", "frozenset",
"getattr", "globals", "hasattr", "hash", "help", "hex", "id",
"input", "int", "isinstance", "issubclass", "iter", "len",
"list", "locals", "map", "max", "memoryview", "min", "next",
"object", "oct", "open", "ord", "pow", "property", "range",
"repr", "reversed", "round", "set", "setattr", "slice",
"sorted", "staticmethod", "str", "sum", "super", "tuple",
"type", "vars", "zip", "__import__", "NotImplemented",
"Ellipsis", "__debug__"];
CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
function top(state) {
return state.scopes[state.scopes.length - 1];
}
CodeMirror.defineMode("python", function(conf, parserConf) {
var ERRORCLASS = "error";
var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;
// (Backwards-compatibility with old, cumbersome config system)
var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/]
for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)
var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
if (parserConf.extra_keywords != undefined)
myKeywords = myKeywords.concat(parserConf.extra_keywords);
if (parserConf.extra_builtins != undefined)
myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
var py3 = !(parserConf.version && Number(parserConf.version) < 3)
if (py3) {
// since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
var stringPrefixes = new RegExp("^(([rbuf]|(br)|(rb)|(fr)|(rf))?('{3}|\"{3}|['\"]))", "i");
} else {
var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
myKeywords = myKeywords.concat(["exec", "print"]);
myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
"file", "intern", "long", "raw_input", "reduce", "reload",
"unichr", "unicode", "xrange", "False", "True", "None"]);
var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
}
var keywords = wordRegexp(myKeywords);
var builtins = wordRegexp(myBuiltins);
// tokenizers
function tokenBase(stream, state) {
var sol = stream.sol() && state.lastToken != "\\"
if (sol) state.indent = stream.indentation()
// Handle scope changes
if (sol && top(state).type == "py") {
var scopeOffset = top(state).offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset)
pushPyScope(state);
else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
state.errorToken = true;
return null;
} else {
var style = tokenBaseInner(stream, state);
if (scopeOffset > 0 && dedent(stream, state))
style += " " + ERRORCLASS;
return style;
}
}
return tokenBaseInner(stream, state);
}
function tokenBaseInner(stream, state, inFormat) {
if (stream.eatSpace()) return null;
// Handle Comments
if (!inFormat && stream.match(/^#.*/)) return "comment";
// Handle Number Literals
if (stream.match(/^[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
if (stream.match(/^\.\d+/)) { floatLiteral = true; }
if (floatLiteral) {
// Float literals may be "imaginary"
stream.eat(/J/i);
return "number";
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
// Binary
if (stream.match(/^0b[01_]+/i)) intLiteral = true;
// Octal
if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
// Decimal
if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
// Decimal literals may be "imaginary"
stream.eat(/J/i);
// TODO - Can you have imaginary longs?
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
if (intLiteral) {
// Integer literals may be "long"
stream.eat(/L/i);
return "number";
}
}
// Handle Strings
if (stream.match(stringPrefixes)) {
var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;
if (!isFmtString) {
state.tokenize = tokenStringFactory(stream.current(), state.tokenize);
return state.tokenize(stream, state);
} else {
state.tokenize = formatStringFactory(stream.current(), state.tokenize);
return state.tokenize(stream, state);
}
}
for (var i = 0; i < operators.length; i++)
if (stream.match(operators[i])) return "operator"
if (stream.match(delimiters)) return "punctuation";
if (state.lastToken == "." && stream.match(identifiers))
return "property";
if (stream.match(keywords) || stream.match(wordOperators))
return "keyword";
if (stream.match(builtins))
return "builtin";
if (stream.match(/^(self|cls)\b/))
return "variable-2";
if (stream.match(identifiers)) {
if (state.lastToken == "def" || state.lastToken == "class")
return "def";
return "variable";
}
// Handle non-detected items
stream.next();
return inFormat ? null :ERRORCLASS;
}
function formatStringFactory(delimiter, tokenOuter) {
while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
delimiter = delimiter.substr(1);
var singleline = delimiter.length == 1;
var OUTCLASS = "string";
function tokenNestedExpr(depth) {
return function(stream, state) {
var inner = tokenBaseInner(stream, state, true)
if (inner == "punctuation") {
if (stream.current() == "{") {
state.tokenize = tokenNestedExpr(depth + 1)
} else if (stream.current() == "}") {
if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)
else state.tokenize = tokenString
}
}
return inner
}
}
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\{\}\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol())
return OUTCLASS;
} else if (stream.match(delimiter)) {
state.tokenize = tokenOuter;
return OUTCLASS;
} else if (stream.match('{{')) {
// ignore {{ in f-str
return OUTCLASS;
} else if (stream.match('{', false)) {
// switch to nested mode
state.tokenize = tokenNestedExpr(0)
if (stream.current()) return OUTCLASS;
else return state.tokenize(stream, state)
} else if (stream.match('}}')) {
return OUTCLASS;
} else if (stream.match('}')) {
// single } in f-string is an error
return ERRORCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors)
return ERRORCLASS;
else
state.tokenize = tokenOuter;
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function tokenStringFactory(delimiter, tokenOuter) {
while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
delimiter = delimiter.substr(1);
var singleline = delimiter.length == 1;
var OUTCLASS = "string";
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol())
return OUTCLASS;
} else if (stream.match(delimiter)) {
state.tokenize = tokenOuter;
return OUTCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors)
return ERRORCLASS;
else
state.tokenize = tokenOuter;
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function pushPyScope(state) {
while (top(state).type != "py") state.scopes.pop()
state.scopes.push({offset: top(state).offset + conf.indentUnit,
type: "py",
align: null})
}
function pushBracketScope(stream, state, type) {
var align = stream.match(/^[\s\[\{\(]*(?:#|$)/, false) ? null : stream.column() + 1
state.scopes.push({offset: state.indent + hangingIndent,
type: type,
align: align})
}
function dedent(stream, state) {
var indented = stream.indentation();
while (state.scopes.length > 1 && top(state).offset > indented) {
if (top(state).type != "py") return true;
state.scopes.pop();
}
return top(state).offset != indented;
}
function tokenLexer(stream, state) {
if (stream.sol()) {
state.beginningOfLine = true;
state.dedent = false;
}
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle decorators
if (state.beginningOfLine && current == "@")
return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;
if (/\S/.test(current)) state.beginningOfLine = false;
if ((style == "variable" || style == "builtin")
&& state.lastToken == "meta")
style = "meta";
// Handle scope changes.
if (current == "pass" || current == "return")
state.dedent = true;
if (current == "lambda") state.lambda = true;
if (current == ":" && !state.lambda && top(state).type == "py" && stream.match(/^\s*(?:#|$)/, false))
pushPyScope(state);
if (current.length == 1 && !/string|comment/.test(style)) {
var delimiter_index = "[({".indexOf(current);
if (delimiter_index != -1)
pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
delimiter_index = "])}".indexOf(current);
if (delimiter_index != -1) {
if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
else return ERRORCLASS;
}
}
if (state.dedent && stream.eol() && top(state).type == "py" && state.scopes.length > 1)
state.scopes.pop();
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset: basecolumn || 0, type: "py", align: null}],
indent: basecolumn || 0,
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var addErr = state.errorToken;
if (addErr) state.errorToken = false;
var style = tokenLexer(stream, state);
if (style && style != "comment")
state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
if (style == "punctuation") style = null;
if (stream.eol() && state.lambda)
state.lambda = false;
return addErr ? style + " " + ERRORCLASS : style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase)
return state.tokenize.isString ? CodeMirror.Pass : 0;
var scope = top(state)
var closing = scope.type == textAfter.charAt(0) ||
scope.type == "py" && !state.dedent && /^(else:|elif |except |finally:)/.test(textAfter)
if (scope.align != null)
return scope.align - (closing ? 1 : 0)
else
return scope.offset - (closing ? hangingIndent : 0)
},
electricInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/,
closeBrackets: {triples: "'\""},
lineComment: "#",
fold: "indent"
};
return external;
});
CodeMirror.defineMIME("text/x-python", "python");
var words = function(str) { return str.split(" "); };
CodeMirror.defineMIME("text/x-cython", {
name: "python",
extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
"extern gil include nogil property public "+
"readonly struct union DEF IF ELIF ELSE")
});
});
+417
View File
@@ -0,0 +1,417 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var htmlConfig = {
autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
'track': true, 'wbr': true, 'menuitem': true},
implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
'th': true, 'tr': true},
contextGrabbers: {
'dd': {'dd': true, 'dt': true},
'dt': {'dd': true, 'dt': true},
'li': {'li': true},
'option': {'option': true, 'optgroup': true},
'optgroup': {'optgroup': true},
'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
'rp': {'rp': true, 'rt': true},
'rt': {'rp': true, 'rt': true},
'tbody': {'tbody': true, 'tfoot': true},
'td': {'td': true, 'th': true},
'tfoot': {'tbody': true},
'th': {'td': true, 'th': true},
'thead': {'tbody': true, 'tfoot': true},
'tr': {'tr': true}
},
doNotIndent: {"pre": true},
allowUnquoted: true,
allowMissing: true,
caseFold: true
}
var xmlConfig = {
autoSelfClosers: {},
implicitlyClosed: {},
contextGrabbers: {},
doNotIndent: {},
allowUnquoted: false,
allowMissing: false,
allowMissingTagName: false,
caseFold: false
}
CodeMirror.defineMode("xml", function(editorConf, config_) {
var indentUnit = editorConf.indentUnit
var config = {}
var defaults = config_.htmlMode ? htmlConfig : xmlConfig
for (var prop in defaults) config[prop] = defaults[prop]
for (var prop in config_) config[prop] = config_[prop]
// Return variables for tokenizers
var type, setStyle;
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var ch = stream.next();
if (ch == "<") {
if (stream.eat("!")) {
if (stream.eat("[")) {
if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
else return null;
} else if (stream.match("--")) {
return chain(inBlock("comment", "-->"));
} else if (stream.match("DOCTYPE", true, true)) {
stream.eatWhile(/[\w\._\-]/);
return chain(doctype(1));
} else {
return null;
}
} else if (stream.eat("?")) {
stream.eatWhile(/[\w\._\-]/);
state.tokenize = inBlock("meta", "?>");
return "meta";
} else {
type = stream.eat("/") ? "closeTag" : "openTag";
state.tokenize = inTag;
return "tag bracket";
}
} else if (ch == "&") {
var ok;
if (stream.eat("#")) {
if (stream.eat("x")) {
ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
} else {
ok = stream.eatWhile(/[\d]/) && stream.eat(";");
}
} else {
ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
}
return ok ? "atom" : "error";
} else {
stream.eatWhile(/[^&<]/);
return null;
}
}
inText.isInText = true;
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.tokenize = inText;
type = ch == ">" ? "endTag" : "selfcloseTag";
return "tag bracket";
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = inText;
state.state = baseState;
state.tagName = state.tagStart = null;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
state.stringStartCol = stream.column();
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
function inAttribute(quote) {
var closure = function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inTag;
break;
}
}
return "string";
};
closure.isInAttribute = true;
return closure;
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
return style;
}
}
function doctype(depth) {
return function(stream, state) {
var ch;
while ((ch = stream.next()) != null) {
if (ch == "<") {
state.tokenize = doctype(depth + 1);
return state.tokenize(stream, state);
} else if (ch == ">") {
if (depth == 1) {
state.tokenize = inText;
break;
} else {
state.tokenize = doctype(depth - 1);
return state.tokenize(stream, state);
}
}
}
return "meta";
};
}
function lower(tagName) {
return tagName && tagName.toLowerCase();
}
function Context(state, tagName, startOfLine) {
this.prev = state.context;
this.tagName = tagName || "";
this.indent = state.indented;
this.startOfLine = startOfLine;
if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
this.noIndent = true;
}
function popContext(state) {
if (state.context) state.context = state.context.prev;
}
function maybePopContext(state, nextTagName) {
var parentTagName;
while (true) {
if (!state.context) {
return;
}
parentTagName = state.context.tagName;
if (!config.contextGrabbers.hasOwnProperty(lower(parentTagName)) ||
!config.contextGrabbers[lower(parentTagName)].hasOwnProperty(lower(nextTagName))) {
return;
}
popContext(state);
}
}
function baseState(type, stream, state) {
if (type == "openTag") {
state.tagStart = stream.column();
return tagNameState;
} else if (type == "closeTag") {
return closeTagNameState;
} else {
return baseState;
}
}
function tagNameState(type, stream, state) {
if (type == "word") {
state.tagName = stream.current();
setStyle = "tag";
return attrState;
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return attrState(type, stream, state);
} else {
setStyle = "error";
return tagNameState;
}
}
function closeTagNameState(type, stream, state) {
if (type == "word") {
var tagName = stream.current();
if (state.context && state.context.tagName != tagName &&
config.implicitlyClosed.hasOwnProperty(lower(state.context.tagName)))
popContext(state);
if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
setStyle = "tag";
return closeState;
} else {
setStyle = "tag error";
return closeStateErr;
}
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return closeState(type, stream, state);
} else {
setStyle = "error";
return closeStateErr;
}
}
function closeState(type, _stream, state) {
if (type != "endTag") {
setStyle = "error";
return closeState;
}
popContext(state);
return baseState;
}
function closeStateErr(type, stream, state) {
setStyle = "error";
return closeState(type, stream, state);
}
function attrState(type, _stream, state) {
if (type == "word") {
setStyle = "attribute";
return attrEqState;
} else if (type == "endTag" || type == "selfcloseTag") {
var tagName = state.tagName, tagStart = state.tagStart;
state.tagName = state.tagStart = null;
if (type == "selfcloseTag" ||
config.autoSelfClosers.hasOwnProperty(lower(tagName))) {
maybePopContext(state, tagName);
} else {
maybePopContext(state, tagName);
state.context = new Context(state, tagName, tagStart == state.indented);
}
return baseState;
}
setStyle = "error";
return attrState;
}
function attrEqState(type, stream, state) {
if (type == "equals") return attrValueState;
if (!config.allowMissing) setStyle = "error";
return attrState(type, stream, state);
}
function attrValueState(type, stream, state) {
if (type == "string") return attrContinuedState;
if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
setStyle = "error";
return attrState(type, stream, state);
}
function attrContinuedState(type, stream, state) {
if (type == "string") return attrContinuedState;
return attrState(type, stream, state);
}
return {
startState: function(baseIndent) {
var state = {tokenize: inText,
state: baseState,
indented: baseIndent || 0,
tagName: null, tagStart: null,
context: null}
if (baseIndent != null) state.baseIndent = baseIndent
return state
},
token: function(stream, state) {
if (!state.tagName && stream.sol())
state.indented = stream.indentation();
if (stream.eatSpace()) return null;
type = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
setStyle = null;
state.state = state.state(type || style, stream, state);
if (setStyle)
style = setStyle == "error" ? style + " error" : setStyle;
}
return style;
},
indent: function(state, textAfter, fullLine) {
var context = state.context;
// Indent multi-line strings (e.g. css).
if (state.tokenize.isInAttribute) {
if (state.tagStart == state.indented)
return state.stringStartCol + 1;
else
return state.indented + indentUnit;
}
if (context && context.noIndent) return CodeMirror.Pass;
if (state.tokenize != inTag && state.tokenize != inText)
return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
// Indent the starts of attribute names.
if (state.tagName) {
if (config.multilineTagIndentPastTag !== false)
return state.tagStart + state.tagName.length + 2;
else
return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
}
if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
if (tagAfter && tagAfter[1]) { // Closing tag spotted
while (context) {
if (context.tagName == tagAfter[2]) {
context = context.prev;
break;
} else if (config.implicitlyClosed.hasOwnProperty(lower(context.tagName))) {
context = context.prev;
} else {
break;
}
}
} else if (tagAfter) { // Opening tag spotted
while (context) {
var grabbers = config.contextGrabbers[lower(context.tagName)];
if (grabbers && grabbers.hasOwnProperty(lower(tagAfter[2])))
context = context.prev;
else
break;
}
}
while (context && context.prev && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return state.baseIndent || 0;
},
electricInput: /<\/[\s\w:]+>$/,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
configuration: config.htmlMode ? "html" : "xml",
helperType: config.htmlMode ? "html" : "xml",
skipAttribute: function(state) {
if (state.state == attrValueState)
state.state = attrState
},
xmlCurrentTag: function(state) {
return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null
},
xmlCurrentContext: function(state) {
var context = []
for (var cx = state.context; cx; cx = cx.prev)
context.push(cx.tagName)
return context.reverse()
}
};
});
CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
});
+1
View File
@@ -0,0 +1 @@
cursor.style.top = (pos.top+5) + "px"; //#CUSTOM
+13
View File
@@ -0,0 +1,13 @@
CodeMirror=function(a,b){
this.value=b.value;
this.on=function(){}
this.setValue=function(x){
this.value=x;
};
this.getValue=function(){
return this.value;
}
this.focus=function(){};
this.clearHistory=function(){};
return this;
}
+48
View File
@@ -0,0 +1,48 @@
.cm-s-pixel {
background-color: #000000;
color: rgba(233, 237, 237, 1);
}
.cm-s-pixel .CodeMirror-gutters {
background: black;
color: rgb(83,127,126);
border: none;
}
.lspacer{
background: black;
padding-left: 7px;
}
.cm-s-pixel .CodeMirror-guttermarker, .cm-s-pixel .CodeMirror-guttermarker-subtle, .cm-s-pixel .CodeMirror-linenumber { color: #E0E0D9; background: #303030; }
.cm-s-pixel .CodeMirror-cursor { border-left: 2px solid #f8f8f0; }
.cm-s-pixel div.CodeMirror-selected { background: rgba(255, 255, 255, 0.30); }
.cm-s-pixel.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.25); }
.cm-s-pixel .CodeMirror-line::selection, .cm-s-pixel .CodeMirror-line > span::selection, .cm-s-pixel .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.25); }
.cm-s-pixel .CodeMirror-line::-moz-selection, .cm-s-pixel .CodeMirror-line > span::-moz-selection, .cm-s-pixel .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.25); }
.cm-s-pixel .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); }
.cm-s-pixel .cm-keyword { color: #C792EA; } .cm-s-pixel .cm-keyword {color: #6c6b6d;}
.cm-s-pixel .cm-operator { color: #EDEDED; }
.cm-s-pixel .cm-variable-2 { color: #80CBC4; }
.cm-s-pixel .cm-variable-3 { color: #82B1FF; }
.cm-s-pixel .cm-builtin { color: #DECB6B; }
.cm-s-pixel .cm-atom { color: #F77669; }
.cm-s-pixel .cm-number { color: #F77669; }
.cm-s-pixel .cm-def { color: #EDEDED; }
.cm-s-pixel .cm-string { color: #C3E88D; }
.cm-s-pixel .cm-string-2 { color: #80CBC4; }
.cm-s-pixel .cm-comment { color: #546E7A; }
.cm-s-pixel .cm-variable { color: #82B1FF; } .cm-s-pixel .cm-variable { color: #7d7caf; }
.cm-s-pixel .cm-tag { color: #80CBC4; }
.cm-s-pixel .cm-meta { color: #80CBC4; }
.cm-s-pixel .cm-attribute { color: #FFCB6B; }
.cm-s-pixel .cm-property { color: #80CBAE; } .cm-s-pixel .cm-property { color: #F77669; }
.cm-s-pixel .cm-qualifier { color: #DECB6B; }
.cm-s-pixel .cm-variable-3 { color: #DECB6B; }
.cm-s-pixel .cm-tag { color: #FF5370; }
.cm-s-pixel .cm-error {
color: rgba(255, 255, 255, 1.0);
background-color: #EC5F67;
}
.cm-s-pixel .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
BIN
View File
Binary file not shown.
+80
View File
@@ -0,0 +1,80 @@
function drag_logic()
{
return;
function dragMoveListener (event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
interact('.draggable').draggable({
// inertia: true,
restrict: {
restriction: ".dcontain",
endOnly: true,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
},
//autoScroll: true,
onmove: dragMoveListener,
onend: function (event) {
var textEl = event.target.querySelector('p');
textEl && (textEl.textContent =
'moved a distance of '
+ (Math.sqrt(event.dx * event.dx +
event.dy * event.dy)|0) + 'px');
}
}).actionChecker(function (pointer, event, action) {
if (event.button !== 0) { // without this the right click isn't ideal [26/06/16]
return null;
}
return action;
});
window.dragMoveListener = dragMoveListener;
interact('.itemslot').dropzone({
// only accept elements matching this CSS selector
accept: '.draggable',
// Require a 75% element overlap for a drop to be possible
overlap: 0.75,
ondropactivate: function (event) {
// add active dropzone feedback
event.target.classList.add('drop-active');
},
ondragenter: function (event) {
var draggableElement = event.relatedTarget,
dropzoneElement = event.target;
// feedback the possibility of a drop
dropzoneElement.classList.add('drop-target');
draggableElement.classList.add('can-drop');
draggableElement.textContent = 'Dragged in';
},
ondragleave: function (event) {
// remove the drop feedback style
event.target.classList.remove('drop-target');
event.relatedTarget.classList.remove('can-drop');
event.relatedTarget.textContent = 'Dragged out';
},
ondrop: function (event) {
event.relatedTarget.textContent = 'Dropped';
},
ondropdeactivate: function (event) {
// remove active dropzone feedback
event.target.classList.remove('drop-active');
event.target.classList.remove('drop-target');
}
});
}
+43
View File
@@ -0,0 +1,43 @@
var server_password="adventureland";
var account_email="hello@adventure.land";
var account_password="gg123456";
var server_port=9012;
var url=require('url');
var app=require('http').createServer(http_handler);
app.listen(server_port);
function http_handler(request,response)
{
var body = [];
request.on('error', function(err) {
console.log("http_err: "+err,1);
}).on('data', function(chunk) {
body.push(chunk);
}).on('end', function() {
body = Buffer.concat(body).toString();
try{
var url_parts=url.parse(request.url,true),args=url_parts.query,cookies={},output="";
(body||"").split("&").forEach(function(pv){
var pvp=pv.split("=");
args[pvp[0]]=pvp[1];
});
if(cookies.password!=server_password)
{
response.writeHead(200);
response.end(html_password());
}
response.writeHead(200);
response.end(output);
}catch(e){
console.log("chttp_err: "+e,1);
}
});
}
function html_password()
{
return "What is the password?";
}
@@ -0,0 +1,75 @@
function calculate_move(map, cur_x, cur_y, target_x, target_y) {
var going_down = cur_y < target_y;
var going_right = cur_x < target_x;
var x_lines = map.x_lines || [];
var y_lines = map.y_lines || [];
var min_x = min(cur_x, target_x);
var max_x = max(cur_x, target_x);
var min_y = min(cur_y, target_y);
var max_y = max(cur_y, target_y);
var dx = target_x - cur_x;
var dy = target_y - cur_y;
var dydx = dy / (dx + EPS);
var dxdy = 1 / dydx;
for (var i = 0; i < x_lines.length; i++) {
var line = x_lines[i];
var line_x = line[0];
if (max_x < line_x || min_x > line_x || max_y < line[1] || min_y > line[2]) {
continue;
}
var y_intersect = cur_y + (line_x - cur_x) * dydx;
if (y_intersect < line[1] || y_intersect > line[2]) {
continue;
}
if (going_down) {
target_y = min(target_y, y_intersect);
} else {
target_y = max(target_y, y_intersect);
}
if (going_right) {
target_x = min(target_x, line_x - 3);
} else {
target_x = max(target_x, line_x + 3);
}
}
for (var i = 0; i < y_lines.length; i++) {
var line = y_lines[i];
var line_y = line[0];
if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) {
continue;
}
var x_intersect = cur_x + (line_y - cur_y) * dxdy;
if (x_intersect < line[1] || x_intersect > line[2]) {
continue;
}
if (going_right) {
target_x = min(target_x, x_intersect);
} else {
target_x = max(target_x, x_intersect);
}
if (going_down) {
target_y = min(target_y, line_y - 3);
} else {
target_y = max(target_y, line_y + 7);
}
}
return {
x: target_x,
y: target_y
};
}
@@ -0,0 +1,83 @@
function calculate_move(map, cur_x, cur_y, target_x, target_y) {
var going_down = cur_y < target_y;
var going_right = cur_x < target_x;
var x_lines = map.x_lines || [];
var y_lines = map.y_lines || [];
var min_x = min(cur_x, target_x);
var max_x = max(cur_x, target_x);
var min_y = min(cur_y, target_y);
var max_y = max(cur_y, target_y);
var dx = target_x - cur_x;
var dy = target_y - cur_y;
var dydx = dy / (dx + EPS);
var dxdy = 1 / dydx;
for (var i = 0; i < x_lines.length; i++) {
var line = x_lines[i];
var line_x = line[0];
if (max_x < line_x || min_x > line_x || max_y < line[1] || min_y > line[2]) {
continue;
}
var y_intersect = cur_y + (line_x - cur_x) * dydx;
if (y_intersect < line[1] || y_intersect > line[2]) {
continue;
}
if (going_down) {
target_y = min(target_y, y_intersect);
max_y = target_y;
} else {
target_y = max(target_y, y_intersect);
min_y = target_y;
}
if (going_right) {
target_x = min(target_x, line_x - 3);
max_x = target_x;
} else {
target_x = max(target_x, line_x + 3);
min_x = target_x;
}
}
for (var i = 0; i < y_lines.length; i++) {
var line = y_lines[i];
var line_y = line[0];
if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) {
continue;
}
var x_intersect = cur_x + (line_y - cur_y) * dxdy;
if (x_intersect < line[1] || x_intersect > line[2]) {
continue;
}
if (going_right) {
target_x = min(target_x, x_intersect);
max_x = target_x;
} else {
target_x = max(target_x, x_intersect);
min_x = target_x;
}
if (going_down) {
target_y = min(target_y, line_y - 3);
max_y = target_y;
} else {
target_y = max(target_y, line_y + 7);
min_y = target_y;
}
}
return {
x: target_x,
y: target_y
};
}
@@ -0,0 +1,49 @@
function can_move(map, cur_x, cur_y, target_x, target_y) {
var x_lines = map.x_lines || [];
var y_lines = map.y_lines || [];
var min_x = min(cur_x, target_x);
var max_x = max(cur_x, target_x);
var min_y = min(cur_y, target_y);
var max_y = max(cur_y, target_y);
var dx = target_x - cur_x;
var dy = target_y - cur_y;
var dydx = dy / (dx + EPS);
var dxdy = 1 / dydx;
for (var i = 0; i < x_lines.length; i++) {
var line = x_lines[i];
var line_x = line[0];
if (max_x < line_x || min_x > line_x || max_y < line[1] || min_y > line[2]) {
continue;
}
var y_intersect = cur_y + (line_x - cur_x) * dydx;
if (y_intersect < line[1] || y_intersect > line[2]) {
continue;
}
return false;
}
for (var i = 0; i < y_lines.length; i++) {
var line = y_lines[i];
var line_y = line[0];
if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) {
continue;
}
var x_intersect = cur_x + (line_y - cur_y) * dxdy;
if (x_intersect < line[1] || x_intersect > line[2]) {
continue;
}
return false;
}
return true;
}
@@ -0,0 +1,241 @@
const GRAPH_RESOLUTION = 8;
class Box {
constructor(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
width() {
return this.x2 - this.x1;
}
height() {
return this.y2 - this.y1;
}
contains(x, y) {
return (this.x1 < x && x < this.x2 &&
this.y1 < y && y < this.y2);
}
intersects(box) {
return (this.x1 <= box.x2 &&
box.x1 <= this.x2 &&
this.y1 <= box.y2 &&
box.y1 <= this.y2);
}
static square(cx, cy, side) {
let half_side = side / 2;
return new Box(cx - half_side, cy - half_side, cx + half_side, cy + half_side);
}
}
class NodeTree {
constructor(region, obstacles, root, level) {
if (!level) {
this.level = Math.ceil(Math.log2(region.width() / GRAPH_RESOLUTION));
} else {
this.level = level;
}
if (root) {
this.root = root;
} else {
this.root = this;
}
this.region = region;
this.x = (region.x1 + region.x2) / 2;
this.y = (region.y1 + region.y2) / 2;
this.obstacles = obstacles;
this.crossable = true;
this.is_leaf = false;
if (this.obstacles.length == 0) {
this.is_leaf = true;
} else if (this.level == 0) {
this.is_leaf = true;
this.crossable = false;
}
this.quads = null;
this.neighbors = null;
this.is_inside = false;
if (!this.is_leaf) {
this.subdivide();
}
}
get_quad(x, y) {
if (x < this.x && y < this.y) return this.quads[0];
else if (x >= this.x && y < this.y) return this.quads[1];
else if (x < this.x && y >= this.y) return this.quads[2];
return this.quads[3];
}
subdivide() {
this.quads = [];
let l = this.region.x1;
let r = this.region.x2;
let t = this.region.y1;
let b = this.region.y2;
let x = this.x;
let y = this.y;
let subregions = [
new Box(l, t, x, y),
new Box(x, t, r, y),
new Box(l, y, x, b),
new Box(x, y, r, b),
];
let obstacles = this.obstacles;
for (let i = 0; i < subregions.length; i++) {
let subregion = subregions[i];
let subregion_obstacles = [];
for (let j = 0; j < obstacles.length; j++) {
let obstacle = obstacles[j];
if (subregion.intersects(obstacle)) {
subregion_obstacles.push(obstacle);
}
}
this.quads[i] = new NodeTree(subregion, subregion_obstacles, this.root, this.level - 1);
}
}
get(x, y) {
if (!this.region.contains(x, y)) return null;
if (this.is_leaf) return this;
return this.get_quad(x, y).get(x, y);
}
get_neighbors() {
if (!this.is_leaf) throw new Error('Tried getting neighbors of non-leaf node');
if (this.neighbors) return this.neighbors;
if (!this.crossable) {
this.neighbors = [];
return this.neighbors;
}
let left = this.region.x1;
let right = this.region.x2;
let top = this.region.y1;
let bottom = this.region.y2;
let min_size = this.region.width() * (2 ** -this.level);
let num_neighbors = 2 ** this.level;
let neighbor_set = new Set();
// Top and bottom (and corners).
for (let x = -(num_neighbors + 1); x <= (num_neighbors + 1); x += 2) {
let real_x = this.x + min_size * (x / 2);
let neighbor = this.root.get(real_x, top - min_size / 2);
if (neighbor) neighbor_set.add(neighbor);
neighbor = this.root.get(real_x, bottom + min_size / 2);
if (neighbor) neighbor_set.add(neighbor);
}
// Left and right.
for (let y = -(num_neighbors - 1); y <= (num_neighbors - 1); y += 2) {
let real_y = this.y + min_size * (y / 2);
let neighbor = this.root.get(left - min_size / 2, real_y);
if (neighbor) neighbor_set.add(neighbor);
neighbor = this.root.get(right + min_size / 2, real_y);
if (neighbor) neighbor_set.add(neighbor);
}
this.neighbors = [...neighbor_set];
return this.neighbors;
}
flood_fill() {
if (this.is_inside) return;
this.is_inside = true;
for (let neighbor of this.get_neighbors()) {
neighbor.flood_fill();
}
}
}
function calculate_size(actual_size) {
let cur_size = GRAPH_RESOLUTION;
while (cur_size < actual_size) {
cur_size *= 2;
}
return cur_size;
}
function initialize_graph(map_name) {
let map_data = G.maps[map_name].data;
let min_x = Infinity;
let max_x = -Infinity;
let min_y = Infinity;
let max_y = -Infinity;
let obstacles = [];
for (let line of map_data.x_lines) {
min_x = Math.min(min_x, line[0]);
max_x = Math.max(max_x, line[0]);
obstacles.push(new Box(
line[0] - 3,
line[1] - 3,
line[0] + 3,
line[2] + 7
));
}
for (let line of map_data.y_lines) {
min_y = Math.min(min_y, line[0]);
max_y = Math.max(max_y, line[0]);
obstacles.push(new Box(
line[1] - 3,
line[0] - 3,
line[2] + 3,
line[0] + 7
));
}
let largest_side = Math.max(max_x - min_x, max_y - min_y);
let side = calculate_size(largest_side);
let center_x = (max_x + min_x) / 2;
let center_y = (max_y + min_y) / 2;
let region = Box.square(center_x, center_y, side);
let map_tree = new NodeTree(region, obstacles);
let spawns = G.maps[map_name].spawns;
for (let [x, y] of spawns) {
map_tree.get(x, y).flood_fill();
}
return map_tree;
}
+18
View File
@@ -0,0 +1,18 @@
function on_draw()
{
clear_drawings();
for(var id in parent.entities)
{
var player=parent.entities[id];
if(!parent.is_player(player)) continue;
if(player.target)
{
var target=parent.entities[player.target];
if(target)
{
// game_log(target.name);
draw_line(player.real_x,player.real_y,target.real_x,target.real_y);
}
}
}
}
+400
View File
@@ -0,0 +1,400 @@
// This is draivin's calculate_move - it's well thought, as he introduced going_down and going_right, realising that approach direction matters, this is what probably inpired me to introduce the new simplified system 1.5 years later, where lines are duplicated, so approach direction doesn't need to be introduced in the calculation logic, which complicates things too much [17/07/18]
// [17/07/18 17:25] Sad realization - line duplication can never work, even if lines are increased in length to intersect - there are orphan lines on fences etc.
// [18/07/18 14:22] Latest iteration of movement logic, calculate 4 corners, select the minimal move, simple, easy to calculate
function calculate_move(map,cur_x,cur_y,target_x,target_y) // v4, tries to move back, but, if you are moving at a very very high angle, moving 7px back from an x_line, doesn't really move you 7px back in the y-direction, it's more like 0.1px, trial and error ... :)
{
var o=move_distance(cur_x,cur_y,target_x,target_y);
var f=move_further(cur_x,cur_y,target_x,target_y,7.1288);
var move=calculate_movex(map, cur_x, cur_y, f.x, f.y); // move 4px forward instead, so line logic triggers
var n=move_distance(cur_x,cur_y,move.x,move.y);
console.log((n-o)+" target_x,y: "+target_x+","+target_y+" move.x,y: "+move.x+","+move.y);
if(n-o>=7.1288-EPS) return calculate_move_v2(map, cur_x, cur_y, target_x, target_y); // didn't clash with a line, return normal move
else
{
console.log((o-n+7.1288)+" further");
var fx=move_further(cur_x,cur_y,target_x,target_y,-(o-n+7.1288));
var move=calculate_movex(map, cur_x, cur_y, fx.x, fx.y);
}
return move;
}
function move_further(x0,y0,x1,y1,dt) // Some of the earlier ideas involved trying to move forward and backtracking, imperfect and complex [19/07/18]
{
var distance=Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0));
if(!dt || !distance) return {x:x1,y:y1};
var a=(y1-y0)/distance,b=(x1-x0)/distance;
return {x:x0+b*(distance+dt),y:y0+a*(distance+dt)};
}
function move_exact(x0,y0,x1,y1,dt)
{
var distance=Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0));
if(!dt || !distance) return {x:x1,y:y1};
var a=(y1-y0)/distance,b=(x1-x0)/distance;
return {x:x0+b*(dt),y:y0+a*(dt)};
}
function calculate_movex(map, cur_x, cur_y, target_x, target_y) {
if(target_x==Infinity) target_x=CINF;
if(target_y==Infinity) target_y=CINF;
//console.log(cur_x+" "+cur_y+" "+target_x+" "+target_y);
var going_down = cur_y < target_y;
var going_right = cur_x < target_x;
var x_lines = map.x_lines || [];
var y_lines = map.y_lines || [];
var min_x = min(cur_x, target_x);
var max_x = max(cur_x, target_x);
var min_y = min(cur_y, target_y);
var max_y = max(cur_y, target_y);
var dx = target_x - cur_x;
var dy = target_y - cur_y;
var dydx = dy / (dx + EPS);
//console.log(dydx);
var dxdy = 1 / dydx;
var N_SPC=0; // Tested 2, doesn't work, jail with test_movement.js [16/07/18]
for (var i = 0; i < x_lines.length; i++) {
var line = x_lines[i];
var line_x = line[0];
if (max_x < line_x-N_SPC || min_x > line_x+N_SPC || max_y < line[1]-N_SPC || min_y > line[2]+N_SPC) {
continue;
}
var y_intersect = cur_y + (line_x - cur_x) * dydx;
if (y_intersect < line[1]-N_SPC || y_intersect > line[2]+N_SPC) {
continue;
}
if (going_down) {
target_y = min(target_y, y_intersect);
max_y = target_y;
} else {
target_y = max(target_y, y_intersect);
min_y = target_y;
}
if (going_right) {
target_x = min(target_x, line_x - 3);
max_x = target_x;
} else {
target_x = max(target_x, line_x + 3);
min_x = target_x;
}
}
for (var i = 0; i < y_lines.length; i++) {
var line = y_lines[i];
var line_y = line[0];
if (max_y < line_y-N_SPC || min_y > line_y+N_SPC || max_x < line[1]-N_SPC || min_x > line[2]+N_SPC) {
continue;
}
var x_intersect = cur_x + (line_y - cur_y) * dxdy;
if (x_intersect < line[1]-N_SPC || x_intersect > line[2]+N_SPC) {
continue;
}
if (going_right) {
target_x = min(target_x, x_intersect);
max_x = target_x;
} else {
target_x = max(target_x, x_intersect);
min_x = target_x;
}
if (going_down) {
target_y = min(target_y, line_y - 3);
max_y = target_y;
} else {
target_y = max(target_y, line_y + 7);
min_y = target_y;
}
}
//console.log(target_x+" "+target_y);
return {
x: target_x,
y: target_y
};
}
// This was a bugged version of applying the "Smooth Movement" - if you hit a line, this routine lets you walk as if you slide over the line you hit
function calculate_movev1(map, cur_x, cur_y, target_x, target_y) // improved, v1
{
var move=calculate_movex(map, cur_x, cur_y, target_x, target_y);
if(move.x!=target_x && move.y!=target_y)
{
var move2=calculate_movex(map, move.x,move.y, target_x, move.y);
if(move2.x==move.x)
{
var move2=calculate_movex(map, move2.x,move2.y, move2.x, target_y);
}
return move2;
}
return move;
}
// Pre-perfection versions, introduced binary search in [16/07/18] - and quickly re-wrote the entire system and simplified things
function bsearch_start(arr,value)
{
var start=0,end=arr.length-1,current;
while(start<end-1)
{
current=parseInt((start+end)/2);
if(arr[current][0]<value) start=current;
else end=current-1;
}
// while(start<arr.length && arr[start][0]<value) start++;
return start;
}
function can_move(monster)
{
// An XY-tree would be ideal, but the current improvements should be enough [16/07/18]
var M=G.maps[monster.map].data||{};
var x0=monster.x,y0=monster.y,x1=monster.going_x,y1=monster.going_y,next,mx=min(x0,x1),my=min(y0,y1);
for(var i=bsearch_start(M.x_lines||[],mx);i<(M.x_lines||[]).length;i++)
{
var line=M.x_lines[i];
if(line[0]-0.2<=x1 && line[0]+0.2>=x1 && line[1]-0.2<=y1 && line[2]+0.2>=y1) return false; // 2 instead of 0.2 causes jailing issues
if(mx>line[0]) continue; // can be commented out with: while(start<arr.length && arr[start][0]<value) start++;
if(x0+1<line[0] && x1+1<line[0]) break; // performance improvement, we moved past our range [16/07/18]
next=y0+(y1-y0)*(line[0]-x0)/(x1-x0+EPS);
if(!(line[1]-EPS<=next && next<=line[2]+EPS)) continue; // Fixed EPS [16/07/18]
return false;
}
for(var i=bsearch_start(M.y_lines||[],my);i<(M.y_lines||[]).length;i++)
{
var line=M.y_lines[i];
if(line[0]-0.2<=y1 && line[0]+0.2>=y1 && line[1]-0.2<=x1 && line[2]+0.2>=x1) return false;
if(my>line[0]) continue;
if(y0+1<line[0] && y1+1<line[0]) break;
next=x0+(x1-x0)*(line[0]-y0)/(y1-y0+EPS);
if(!(line[1]-EPS<=next && next<=line[2]+EPS)) continue;
return false;
}
return true;
}
// This is the very first calculate_move - it had issues, at that time, when the first Reddit post blew the game in a small scale, there were a lot of coders interested in helping, draivin thankfully wrote the new one, while I concentrated on other things
function calculate_move_original(M,x0,y0,x1,y1)
{
// #GTODO: Inner corners are problematic, the entire "line" routine could use an overhaul
var next,y0sy1=y0<y1,x0sx1=x0<x1;
for(var i=0;i<(M.x_lines||[]).length;i++)
{
var line=M.x_lines[i];
if(!(x0<=line[0] && line[0]<=x1 || x1<=line[0] && line[0]<=x0)) continue;
next=y0+(y1-y0)*(line[0]-x0)/(x1-x0+EPS);
if(!(line[1]<=next && next<=line[2])) continue;
//console.log(round(x0)+","+round(y0)+" to "+round(x1)+","+round(y1));
if(y0sy1) y1=min(y1,next);
else y1=max(y1,next);
if(x0sx1) x1=min(x1,line[0]-3);
else x1=max(x1,line[0]+3);
//console.log("became "+round(x0)+","+round(y0)+" to "+round(x1)+","+round(y1)+" with ["+line[0]+","+line[1]+","+line[2]+"]");
}
for(var i=0;i<(M.y_lines||[]).length;i++)
{
var line=M.y_lines[i];
if(!(y0<=line[0] && line[0]<=y1 || y1<=line[0] && line[0]<=y0)) continue;
next=x0+(x1-x0)*(line[0]-y0)/(y1-y0+EPS);
if(!(line[1]<=next && next<=line[2])) continue;
if(x0sx1) x1=min(x1,next);
else x1=max(x1,next);
if(y0sy1) y1=min(y1,line[0]-3);
else y1=max(y1,line[0]+7);
}
for(var i=0;i<(M.x_lines||[]).length;i++) // extremely dirty-fix, the worst part is, don't even know why it works :( [03/10/16]
{
var line=M.x_lines[i];
if(!(x0<=line[0] && line[0]<=x1 || x1<=line[0] && line[0]<=x0)) continue;
next=y0+(y1-y0)*(line[0]-x0)/(x1-x0+EPS);
if(!(line[1]<=next && next<=line[2])) continue;
//console.log(round(x0)+","+round(y0)+" to "+round(x1)+","+round(y1));
if(y0sy1) y1=min(y1,next);
else y1=max(y1,next);
if(x0sx1) x1=min(x1,line[0]-3);
else x1=max(x1,line[0]+3);
//console.log("became "+round(x0)+","+round(y0)+" to "+round(x1)+","+round(y1)+" with ["+line[0]+","+line[1]+","+line[2]+"]");
}
return {x:x1,y:y1};
}
// This was an attempt to apply the move 5px forward, if you don't hit a line, move the original distance logic, later on, applied it to calculate_move, it worked well, so this one was left as it is
function calculate_move_new(map,x0,y0,x1,y1)
{
// Incomplete - and no need
var M=map||{};
var distance=Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0)); if(!distance) return {x:x1,y:y1};
var mx=min(x0,x1),my=min(y0,y1);
for(var i=bsearch_start(M.x_lines||[],mx);i<(M.x_lines||[]).length;i++)
{
var line=M.x_lines[i];
if(line[0]-0.2<=x1 && line[0]+0.2>=x1 && line[1]-0.2<=y1 && line[2]+0.2>=y1) return false; // 2 instead of 0.2 causes jailing issues
if(mx>line[0]) continue; // can be commented out with: while(start<arr.length && arr[start][0]<value) start++;
if(x0+1<line[0] && x1+1<line[0]) break; // performance improvement, we moved past our range [16/07/18]
next=y0+(y1-y0)*(line[0]-x0)/(x1-x0+EPS);
if(!(line[1]-EPS<=next && next<=line[2]+EPS)) continue; // Fixed EPS [16/07/18]
return false;
}
for(var i=bsearch_start(M.y_lines||[],my);i<(M.y_lines||[]).length;i++)
{
var line=M.y_lines[i];
if(line[0]-0.2<=y1 && line[0]+0.2>=y1 && line[1]-0.2<=x1 && line[2]+0.2>=x1) return false;
if(my>line[0]) continue;
if(y0+1<line[0] && y1+1<line[0]) break;
next=x0+(x1-x0)*(line[0]-y0)/(y1-y0+EPS);
if(!(line[1]-EPS<=next && next<=line[2]+EPS)) continue;
return false;
}
return true;
}
// Used this can_move, for the longest time, it just worked
function can_move_original(monster) // used at server, .going_x + .going_y is pre-set [14/08/16]
{
// Issue: When a Citizen lands right on top of a line, s/he can't move up or down, basically, equality shouldn't return false, it happens on ["main",-152,152] near the fence [19/07/17]
var M=G.maps[monster.map].data||{};
var x0=monster.x,y0=monster.y,x1=monster.going_x,y1=monster.going_y,next;
// if(simple_distance({x:x0,y:y0},{x:x1,y:y1})<10) return true; // not sure if this is needed [14/08/16]
// ^^ Removed, seems like a huge oversight, especially after the line violations are added [19/07/17]
// can_move({map:"main",x:-10,y:152,going_x:-160,going_y:152}) - you can move onto a line from it's parallel
// can_move({map:"main",x:-152,y:152,going_x:-152,going_y:160}) - yet you can't move vertically away from the line
for(var i=0;i<(M.x_lines||[]).length;i++)
{
var line=M.x_lines[i];
if(!(x0<=line[0] && line[0]<=x1 || x1<=line[0] && line[0]<=x0)) continue;
next=y0+(y1-y0)*(line[0]-x0)/(x1-x0+EPS);
if(!(line[1]<=next && next<=line[2])) continue;
return false;
}
for(var i=0;i<(M.y_lines||[]).length;i++)
{
var line=M.y_lines[i];
if(!(y0<=line[0] && line[0]<=y1 || y1<=line[0] && line[0]<=y0)) continue;
next=x0+(x1-x0)*(line[0]-y0)/(y1-y0+EPS);
if(!(line[1]<=next && next<=line[2])) continue;
return false;
}
return true;
}
function bsearch_start2(arr,value,d)
{
var start=0,end=arr.length-1,current;
while(start<end-1)
{
current=parseInt((start+end)/2);
if(arr[current][0]<value-d) start=current;
else end=current-1;
}
return start;
}
function can_move_170718(monster)
{
// #IMPORTANT: While trying to apply the rectangle logic here, realised that it's best to just add new lines for rectangle's edges, and just duplicating each line was enough, this gave birth to G.geometry, it was a small monumental change [17/07/18]
// This version is similar to calculate_movex, depending on the approach angle, the shape of the rectangle that each single line form changes
var M=G.maps[monster.map].data||{};
var x0=monster.x,y0=monster.y,x1=monster.going_x,y1=monster.going_y,next,mx=min(x0,x1),my=min(y0,y1),going_left=false,going_up=false,x_disp=-3,y_disp=-3;
if(x1<x0) going_left=true,x_disp=3;
if(y1<y0) going_up=true,y_disp=7;
for(var i=bsearch_start2(M.x_lines||[],mx,3);i<(M.x_lines||[]).length;i++)
{
var line=M.x_lines[i];
if(line[0]-3<=x1 && line[0]+3>=x1 && line[1]-7<=y1 && line[2]+3>=y1) return false;
if(mx>line[0]) continue;
if(x0+1<line[0] && x1+1<line[0]) break;
next=y0+(y1-y0)*(line[0]-x0)/(x1-x0+EPS);
if(!(line[1]-EPS<=next && next<=line[2]+EPS)) continue;
return false;
}
for(var i=bsearch_start(M.y_lines||[],my);i<(M.y_lines||[]).length;i++)
{
var line=M.y_lines[i];
if(line[0]-3<=y1 && line[0]+3>=y1 && line[1]-7<=x1 && line[2]+3>=x1) return false;
if(my>line[0]) continue;
if(y0+1<line[0] && y1+1<line[0]) break;
next=x0+(x1-x0)*(line[0]-y0)/(y1-y0+EPS);
if(!(line[1]-EPS<=next && next<=line[2]+EPS)) continue;
return false;
}
return true;
}
function can_movex(map, cur_x, cur_y, target_x, target_y) { // draivin's can_move - didn't use for a long while - don't remember whether it had issues
if(target_x==Infinity) target_x=CINF;
if(target_y==Infinity) target_y=CINF;
//console.log(cur_x+" "+cur_y+" "+target_x+" "+target_y);
var going_down = cur_y < target_y;
var going_right = cur_x < target_x;
var x_lines = map.x_lines || [];
var y_lines = map.y_lines || [];
var min_x = min(cur_x, target_x);
var max_x = max(cur_x, target_x);
var min_y = min(cur_y, target_y);
var max_y = max(cur_y, target_y);
var dx = target_x - cur_x;
var dy = target_y - cur_y;
var dydx = dy / (dx + EPS);
//console.log(dydx);
var dxdy = 1 / dydx;
for (var i = 0; i < x_lines.length; i++) {
var line = x_lines[i];
var line_x = line[0];
if (max_x < line_x || min_x > line_x || max_y < line[1] || min_y > line[2]) {
continue;
}
var y_intersect = cur_y + (line_x - cur_x) * dydx;
if (y_intersect < line[1] || y_intersect > line[2]) {
continue;
}
return false;
}
for (var i = 0; i < y_lines.length; i++) {
var line = y_lines[i];
var line_y = line[0];
if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) {
continue;
}
var x_intersect = cur_x + (line_y - cur_y) * dxdy;
if (x_intersect < line[1] || x_intersect > line[2]) {
continue;
}
return false;
}
return true;
}
+81
View File
@@ -0,0 +1,81 @@
var last_focus=new Date();
setInterval(function(){
if($(":focus").length) last_focus=new Date();
},120);
function touch_startify()
{
return;
$('[onclick]').each(function(){
var $this=$(this);
$this.attr("ontouchstart",$this.attr("onclick"));
$this.removeAttr("onclick");
})
}
function toggle_ui()
{
if(socket && observing && $('.serversuic').is(":visible"))
{
$('.charactersui').hide();
$('.serversui').hide();
}
else if($('.charactersuic').is(":visible"))
{
$('.charactersui').hide(); $('.serversui').css('display','inline-block');
}
else
{
$('.serversui').hide(); $('.charactersui').css('display','inline-block');
}
}
function hide_nav()
{
$('.charactersui').hide(); $('.serversui').hide();
}
var rc_cache="-1";
function render_characters()
{
var html="",key="";
X.characters.forEach(function(char){
key+=char.name+" "+char.level+" "+char.server+" "+char.rip+" "+char.skin+" "+char.cx+"|";
});
if(key==rc_cache) return;
rc_cache=key;
X.characters.forEach(function(char){
if(char.online)
{
html+="<div class='gamebutton mb5 mr5' onclick='if(bc(this)) return; observe_character(\""+char.name+"\");' style='text-align: left; width: 172px'>";
html+="<span style='float:left; margin-right: 5px; margin-top: -5px; margin-left: -4px; margin-bottom: -7px;'>"+sprite(char.skin,{cx:char.cx,rip:char.rip})+"</span>";
html+=char.name.length<=8&&char.name||char.name.substr(0,8)+"..";
html+=" <span style='color: #F3A05D'>["+char.server+"]</span>";
html+="<br />";
html+="Lv."+char.level+" <span class='gray'>"+char.type.toTitleCase()+"</span>";
html+="</div>";
}
});
if(!html) html+="<div class='gamebutton mb5'>ALL OFFLINE</div>";
$(".charactersuic").html(html);
touch_startify();
}
var sl_cache="-1";
function render_servers()
{
var html="",key="";
X.servers.forEach(function(server){
key+=server.name+" "+server.players+"|";
});
if(key==sl_cache) return;
sl_cache=key;
X.servers.forEach(function(server){
html+="<div class='gamebutton mb5 mr5' onclick='if(bc(this)) return; server_addr=\""+server.addr+"\"; server_port=\""+server.port+"\"; init_socket();'>";
html+=server.region+" "+server.name+" <span style='color: #85C76B'>["+server.players+"]</span>";
html+="</div>";
});
if(!html) html+="<div class='gamebutton mb5'>GAME OFFLINE</div>";
$(".serversuic").html(html);
touch_startify();
}
File diff suppressed because it is too large Load Diff
+7009
View File
File diff suppressed because it is too large Load Diff
+6181
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+4
View File
File diff suppressed because one or more lines are too long
+2
View File
File diff suppressed because one or more lines are too long
+2964
View File
File diff suppressed because it is too large Load Diff
+4
View File
File diff suppressed because one or more lines are too long
+2
View File
File diff suppressed because one or more lines are too long
+2
View File
File diff suppressed because one or more lines are too long
+2873
View File
File diff suppressed because it is too large Load Diff
+4
View File
File diff suppressed because one or more lines are too long
+2
View File
File diff suppressed because one or more lines are too long
+5610
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+124
View File
@@ -0,0 +1,124 @@
/* interact.js v1.2.6 | https://raw.github.com/taye/interact.js/master/LICENSE */ (function(F){function ma(){}function t(a){if(!a||"object"!==typeof a)return!1;var b=V(a)||q;return/object|function/.test(typeof b.Element)?a instanceof b.Element:1===a.nodeType&&"string"===typeof a.nodeName}function Ba(a){return a===q||!(!a||!a.Window)&&a instanceof a.Window}function da(a){return z(a)&&void 0!==typeof a.length&&A(a.splice)}function z(a){return!!a&&"object"===typeof a}function A(a){return"function"===typeof a}function K(a){return"number"===typeof a}function H(a){return"boolean"===
typeof a}function N(a){return"string"===typeof a}function ea(a){if(!N(a))return!1;Q.querySelector(a);return!0}function x(a,b){for(var c in b)a[c]=b[c];return a}function ra(a,b){for(var c in b){var d=!1,e;for(e in Ca)if(0===c.indexOf(e)&&Ca[e].test(c)){d=!0;break}d||(a[c]=b[c])}return a}function sa(a,b){a.page=a.page||{};a.page.x=b.page.x;a.page.y=b.page.y;a.client=a.client||{};a.client.x=b.client.x;a.client.y=b.client.y;a.timeStamp=b.timeStamp}function Ta(a,b,c){a.page.x=c.page.x-b.page.x;a.page.y=
c.page.y-b.page.y;a.client.x=c.client.x-b.client.x;a.client.y=c.client.y-b.client.y;a.timeStamp=(new Date).getTime()-b.timeStamp;b=Math.max(a.timeStamp/1E3,.001);a.page.speed=fa(a.page.x,a.page.y)/b;a.page.vx=a.page.x/b;a.page.vy=a.page.y/b;a.client.speed=fa(a.client.x,a.page.y)/b;a.client.vx=a.client.x/b;a.client.vy=a.client.y/b}function Ua(a){return a instanceof q.Event||ga&&q.Touch&&a instanceof q.Touch}function ta(a,b,c){c=c||{};a=a||"page";c.x=b[a+"X"];c.y=b[a+"Y"];return c}function Da(a,b){b=
b||{};Va&&Ua(a)?(ta("screen",a,b),b.x+=q.scrollX,b.y+=q.scrollY):ta("page",a,b);return b}function Wa(a,b){b=b||{};Va&&Ua(a)?ta("screen",a,b):ta("client",a,b);return b}function O(a){return K(a.pointerId)?a.pointerId:a.identifier}function Ea(a){return a instanceof nb?a.correspondingUseElement:a}function V(a){if(Ba(a))return a;a=a.ownerDocument||a;return a.defaultView||a.parentWindow||q}function Fa(a){return(a=a instanceof Xa?a.getBoundingClientRect():a.getClientRects()[0])&&{left:a.left,right:a.right,
top:a.top,bottom:a.bottom,width:a.width||a.right-a.left,height:a.height||a.bottom-a.top}}function ua(a){var b,c=Fa(a);!ob&&c&&(b=(b=V(a))||q,a=b.scrollX||b.document.documentElement.scrollLeft,b=b.scrollY||b.document.documentElement.scrollTop,c.left+=a,c.right+=a,c.top+=b,c.bottom+=b);return c}function Ga(a){var b=[];da(a)?(b[0]=a[0],b[1]=a[1]):"touchend"===a.type?1===a.touches.length?(b[0]=a.touches[0],b[1]=a.changedTouches[0]):0===a.touches.length&&(b[0]=a.changedTouches[0],b[1]=a.changedTouches[1]):
(b[0]=a.touches[0],b[1]=a.touches[1]);return b}function Ya(a){for(var b={pageX:0,pageY:0,clientX:0,clientY:0,screenX:0,screenY:0},c,d=0;d<a.length;d++)for(c in b)b[c]+=a[d][c];for(c in b)b[c]/=a.length;return b}function Ha(a){if(a.length||a.touches&&1<a.touches.length){a=Ga(a);var b=Math.min(a[0].pageX,a[1].pageX),c=Math.min(a[0].pageY,a[1].pageY);return{x:b,y:c,left:b,top:c,width:Math.max(a[0].pageX,a[1].pageX)-b,height:Math.max(a[0].pageY,a[1].pageY)-c}}}function Ia(a,b){b=b||D.deltaSource;var c=
b+"X",d=b+"Y",e=Ga(a);return fa(e[0][c]-e[1][c],e[0][d]-e[1][d])}function Ja(a,b,c){c=c||D.deltaSource;var d=c+"X";c+="Y";a=Ga(a);d=180*Math.atan((a[0][c]-a[1][c])/(a[0][d]-a[1][d]))/Math.PI;K(b)&&(b=(d-b)%360,315<b?d-=360+d/360|0:135<b?d-=180+d/360|0:-315>b?d+=360+d/360|0:-135>b&&(d+=180+d/360|0));return d}function na(a,b){var c=a?a.options.origin:D.origin;"parent"===c?c=L(b):"self"===c?c=a.getRect(b):ea(c)&&(c=Ka(b,c)||{x:0,y:0});A(c)&&(c=c(a&&b));t(c)&&(c=ua(c));c.x="x"in c?c.x:c.left;c.y="y"in
c?c.y:c.top;return c}function Za(a,b,c,d){var e=1-a;return e*e*b+2*e*a*c+a*a*d}function Y(a,b){for(;b;){if(b===a)return!0;b=b.parentNode}return!1}function Ka(a,b){for(var c=L(a);t(c);){if(R(c,b))return c;c=L(c)}return null}function L(a){if((a=a.parentNode)&&a instanceof $a)for(;(a=a.host)&&a&&a instanceof $a;);return a}function va(a,b){return a._context===b.ownerDocument||Y(a._context,b)}function Z(a,b,c){return(a=a.options.ignoreFrom)&&t(c)?N(a)?La(c,a,b):t(a)?Y(a,c):!1:!1}function aa(a,b,c){return(a=
a.options.allowFrom)?t(c)?N(a)?La(c,a,b):t(a)?Y(a,c):!1:!1:!0}function ab(a,b){if(!b)return!1;var c=b.options.drag.axis;return"xy"===a||"xy"===c||c===a}function Ma(a,b){var c=a.options;/^resize/.test(b)&&(b="resize");return c[b].snap&&c[b].snap.enabled}function Na(a,b){var c=a.options;/^resize/.test(b)&&(b="resize");return c[b].restrict&&c[b].restrict.enabled}function ha(a,b,c){for(var d=a.options,e=d[c.name].max,d=d[c.name].maxPerElement,h=0,f=0,g=0,k=0,y=r.length;k<y;k++){var n=r[k],u=n.prepared.name;
if(n.interacting()&&(h++,h>=wa||n.target===a&&(f+=u===c.name|0,f>=e||n.element===b&&(g++,u!==c.name||g>=d))))return!1}return 0<wa}function xa(){this.prevDropElement=this.prevDropTarget=this.dropElement=this.dropTarget=this.element=this.target=null;this.prepared={name:null,axis:null,edges:null};this.matches=[];this.matchElements=[];this.inertiaStatus={active:!1,smoothEnd:!1,ending:!1,startEvent:null,upCoords:{},xe:0,ye:0,sx:0,sy:0,t0:0,vx0:0,vys:0,duration:0,resumeDx:0,resumeDy:0,lambda_v0:0,one_ve_v0:0,
i:null};if(A(Function.prototype.bind))this.boundInertiaFrame=this.inertiaFrame.bind(this),this.boundSmoothEndFrame=this.smoothEndFrame.bind(this);else{var a=this;this.boundInertiaFrame=function(){return a.inertiaFrame()};this.boundSmoothEndFrame=function(){return a.smoothEndFrame()}}this.activeDrops={dropzones:[],elements:[],rects:[]};this.pointers=[];this.pointerIds=[];this.downTargets=[];this.downTimes=[];this.holdTimers=[];this.prevCoords={page:{x:0,y:0},client:{x:0,y:0},timeStamp:0};this.curCoords=
{page:{x:0,y:0},client:{x:0,y:0},timeStamp:0};this.startCoords={page:{x:0,y:0},client:{x:0,y:0},timeStamp:0};this.pointerDelta={page:{x:0,y:0,vx:0,vy:0,speed:0},client:{x:0,y:0,vx:0,vy:0,speed:0},timeStamp:0};this.downEvent=null;this.downPointer={};this.prevEvent=this._curEventTarget=this._eventTarget=null;this.tapTime=0;this.prevTap=null;this.startOffset={left:0,right:0,top:0,bottom:0};this.restrictOffset={left:0,right:0,top:0,bottom:0};this.snapOffsets=[];this.gesture={start:{x:0,y:0},startDistance:0,
prevDistance:0,distance:0,scale:1,startAngle:0,prevAngle:0};this.snapStatus={x:0,y:0,dx:0,dy:0,realX:0,realY:0,snappedX:0,snappedY:0,targets:[],locked:!1,changed:!1};this.restrictStatus={dx:0,dy:0,restrictedX:0,restrictedY:0,snap:null,restricted:!1,changed:!1};this.restrictStatus.snap=this.snapStatus;this.resizing=this.dragging=this.gesturing=this.pointerWasMoved=this.pointerIsDown=!1;this.resizeAxes="xy";this.mouse=!1;r.push(this)}function bb(a,b,c){var d=0,e=r.length,h=/mouse/i.test(a.pointerType||
b)||4===a.pointerType,f;a=O(a);if(/down|start/i.test(b))for(d=0;d<e;d++){f=r[d];var g=c;if(f.inertiaStatus.active&&f.target.options[f.prepared.name].inertia.allowResume&&f.mouse===h)for(;g;){if(g===f.element)return f;g=L(g)}}if(h||!ga&&!oa){for(d=0;d<e;d++)if(r[d].mouse&&!r[d].inertiaStatus.active)return r[d];for(d=0;d<e;d++)if(r[d].mouse&&(!/down/.test(b)||!r[d].inertiaStatus.active))return f;f=new xa;f.mouse=!0;return f}for(d=0;d<e;d++)if(-1!==v(r[d].pointerIds,a))return r[d];if(/up|end|out/i.test(b))return null;
for(d=0;d<e;d++)if(f=r[d],!(f.prepared.name&&!f.target.options.gesture.enabled||f.interacting()||!h&&f.mouse))return f;return new xa}function cb(a){return function(b){var c,d=Ea(b.path?b.path[0]:b.target),e=Ea(b.currentTarget),h;if(ga&&/touch/.test(b.type))for(db=(new Date).getTime(),h=0;h<b.changedTouches.length;h++){var f=b.changedTouches[h];if(c=bb(f,b.type,d))c._updateEventTargets(d,e),c[a](f,b,d,e)}else{if(!oa&&/mouse/.test(b.type)){for(h=0;h<r.length;h++)if(!r[h].mouse&&r[h].pointerIsDown)return;
if(500>(new Date).getTime()-db)return}if(c=bb(b,b.type,d))c._updateEventTargets(d,e),c[a](b,b,d,e)}}}function G(a,b,c,d,e,h){var f,g,k=a.target,y=a.snapStatus,n=a.restrictStatus,u=a.pointers,E=(k&&k.options||D).deltaSource,eb=E+"X",l=E+"Y",ia=k?k.options:D,w=na(k,e),m="start"===d,p="end"===d;f=m?a.startCoords:a.curCoords;e=e||a.element;g=x({},f.page);f=x({},f.client);g.x-=w.x;g.y-=w.y;f.x-=w.x;f.y-=w.y;var I=ia[c].snap&&ia[c].snap.relativePoints;!Ma(k,c)||m&&I&&I.length||(this.snap={range:y.range,
locked:y.locked,x:y.snappedX,y:y.snappedY,realX:y.realX,realY:y.realY,dx:y.dx,dy:y.dy},y.locked&&(g.x+=y.dx,g.y+=y.dy,f.x+=y.dx,f.y+=y.dy));!Na(k,c)||m&&ia[c].restrict.elementRect||!n.restricted||(g.x+=n.dx,g.y+=n.dy,f.x+=n.dx,f.y+=n.dy,this.restrict={dx:n.dx,dy:n.dy});this.pageX=g.x;this.pageY=g.y;this.clientX=f.x;this.clientY=f.y;this.x0=a.startCoords.page.x-w.x;this.y0=a.startCoords.page.y-w.y;this.clientX0=a.startCoords.client.x-w.x;this.clientY0=a.startCoords.client.y-w.y;this.ctrlKey=b.ctrlKey;
this.altKey=b.altKey;this.shiftKey=b.shiftKey;this.metaKey=b.metaKey;this.button=b.button;this.buttons=b.buttons;this.target=e;this.t0=a.downTimes[0];this.type=c+(d||"");this.interaction=a;this.interactable=k;e=a.inertiaStatus;e.active&&(this.detail="inertia");h&&(this.relatedTarget=h);p?"client"===E?(this.dx=f.x-a.startCoords.client.x,this.dy=f.y-a.startCoords.client.y):(this.dx=g.x-a.startCoords.page.x,this.dy=g.y-a.startCoords.page.y):m?this.dy=this.dx=0:"inertiastart"===d?(this.dx=a.prevEvent.dx,
this.dy=a.prevEvent.dy):"client"===E?(this.dx=f.x-a.prevEvent.clientX,this.dy=f.y-a.prevEvent.clientY):(this.dx=g.x-a.prevEvent.pageX,this.dy=g.y-a.prevEvent.pageY);a.prevEvent&&"inertia"===a.prevEvent.detail&&!e.active&&ia[c].inertia&&ia[c].inertia.zeroResumeDelta&&(e.resumeDx+=this.dx,e.resumeDy+=this.dy,this.dx=this.dy=0);"resize"===c&&a.resizeAxes?ia.resize.square?("y"===a.resizeAxes?this.dx=this.dy:this.dy=this.dx,this.axes="xy"):(this.axes=a.resizeAxes,"x"===a.resizeAxes?this.dy=0:"y"===a.resizeAxes&&
(this.dx=0)):"gesture"===c&&(this.touches=[u[0],u[1]],m?(this.distance=Ia(u,E),this.box=Ha(u),this.scale=1,this.ds=0,this.angle=Ja(u,void 0,E),this.da=0):p||b instanceof G?(this.distance=a.prevEvent.distance,this.box=a.prevEvent.box,this.scale=a.prevEvent.scale,this.ds=this.scale-1,this.angle=a.prevEvent.angle,this.da=this.angle-a.gesture.startAngle):(this.distance=Ia(u,E),this.box=Ha(u),this.scale=this.distance/a.gesture.startDistance,this.angle=Ja(u,a.gesture.prevAngle,E),this.ds=this.scale-a.gesture.prevScale,
this.da=this.angle-a.gesture.prevAngle));m?(this.timeStamp=a.downTimes[0],this.velocityY=this.velocityX=this.speed=this.duration=this.dt=0):"inertiastart"===d?(this.timeStamp=a.prevEvent.timeStamp,this.dt=a.prevEvent.dt,this.duration=a.prevEvent.duration,this.speed=a.prevEvent.speed,this.velocityX=a.prevEvent.velocityX,this.velocityY=a.prevEvent.velocityY):(this.timeStamp=(new Date).getTime(),this.dt=this.timeStamp-a.prevEvent.timeStamp,this.duration=this.timeStamp-a.downTimes[0],b instanceof G?(b=
this[eb]-a.prevEvent[eb],l=this[l]-a.prevEvent[l],c=this.dt/1E3,this.speed=fa(b,l)/c,this.velocityX=b/c,this.velocityY=l/c):(this.speed=a.pointerDelta[E].speed,this.velocityX=a.pointerDelta[E].vx,this.velocityY=a.pointerDelta[E].vy));(p||"inertiastart"===d)&&600<a.prevEvent.speed&&150>this.timeStamp-a.prevEvent.timeStamp&&(d=180*Math.atan2(a.prevEvent.velocityY,a.prevEvent.velocityX)/Math.PI,0>d&&(d+=360),p=112.5<=d&&247.5>d,l=202.5<=d&&337.5>d,this.swipe={up:l,down:!l&&22.5<=d&&157.5>d,left:p,right:!p&&
(292.5<=d||67.5>d),angle:d,speed:a.prevEvent.speed,velocity:{x:a.prevEvent.velocityX,y:a.prevEvent.velocityY}})}function fb(){this.originalEvent.preventDefault()}function gb(a){var b="";"drag"===a.name&&(b=za.drag);if("resize"===a.name)if(a.axis)b=za[a.name+a.axis];else if(a.edges){for(var b="resize",c=["top","bottom","left","right"],d=0;4>d;d++)a.edges[c[d]]&&(b+=c[d]);b=za[b]}return b}function hb(a,b,c){a=this.getRect(c);var d=!1,e=null,h=null,f,g=x({},b.curCoords.page),e=this.options;if(!a)return null;
if(S.resize&&e.resize.enabled)if(d=e.resize,f={left:!1,right:!1,top:!1,bottom:!1},z(d.edges)){for(var k in f){var y=f,n=k,u;a:{u=k;var E=d.edges[k],l=g,m=b._eventTarget,p=c,w=a,ya=d.margin||pa;if(E){if(!0===E){var q=K(w.width)?w.width:w.right-w.left,I=K(w.height)?w.height:w.bottom-w.top;0>q&&("left"===u?u="right":"right"===u&&(u="left"));0>I&&("top"===u?u="bottom":"bottom"===u&&(u="top"));if("left"===u){u=l.x<(0<=q?w.left:w.right)+ya;break a}if("top"===u){u=l.y<(0<=I?w.top:w.bottom)+ya;break a}if("right"===
u){u=l.x>(0<=q?w.right:w.left)-ya;break a}if("bottom"===u){u=l.y>(0<=I?w.bottom:w.top)-ya;break a}}u=t(m)?t(E)?E===m:La(m,E,p):!1}else u=!1}y[n]=u}f.left=f.left&&!f.right;f.top=f.top&&!f.bottom;d=f.left||f.right||f.top||f.bottom}else c="y"!==e.resize.axis&&g.x>a.right-pa,a="x"!==e.resize.axis&&g.y>a.bottom-pa,d=c||a,h=(c?"x":"")+(a?"y":"");e=d?"resize":S.drag&&e.drag.enabled?"drag":null;S.gesture&&2<=b.pointerIds.length&&!b.dragging&&!b.resizing&&(e="gesture");return e?{name:e,axis:h,edges:f}:null}
function W(a,b){if(!z(a))return null;var c=a.name,d=b.options;return("resize"===c&&d.resize.enabled||"drag"===c&&d.drag.enabled||"gesture"===c&&d.gesture.enabled)&&S[c]?a:null}function qa(a,b){var c={},d=P[a.type],e=Ea(a.path?a.path[0]:a.target),h=e;b=b?!0:!1;for(var f in a)c[f]=a[f];c.originalEvent=a;for(c.preventDefault=fb;t(h);){for(f=0;f<d.selectors.length;f++){var g=d.contexts[f];if(R(h,d.selectors[f])&&Y(g,e)&&Y(g,h)){g=d.listeners[f];c.currentTarget=h;for(var k=0;k<g.length;k++)if(g[k][1]===
b)g[k][0](c)}}h=L(h)}}function Aa(a){return qa.call(this,a,!0)}function l(a,b){return B.get(a,b)||new C(a,b)}function C(a,b){this._element=a;this._iEvents=this._iEvents||{};var c;if(ea(a)){this.selector=a;var d=b&&b.context;c=d?V(d):q;d&&(c.Node?d instanceof c.Node:t(d)||d===c.document)&&(this._context=d)}else c=V(a),t(a,c)&&(ba?(n.add(this._element,J.down,m.pointerDown),n.add(this._element,J.move,m.pointerHover)):(n.add(this._element,"mousedown",m.pointerDown),n.add(this._element,"mousemove",m.pointerHover),
n.add(this._element,"touchstart",m.pointerDown),n.add(this._element,"touchmove",m.pointerHover)));this._doc=c.document;-1===v(ja,this._doc)&&ib(this._doc);B.push(this);this.set(b)}function M(a,b){var c=!1;return function(){c||(q.console.warn(b),c=!0);return a.apply(this,arguments)}}function jb(a){for(var b=0;b<r.length;b++)r[b].pointerEnd(a,a)}function ib(a){if(-1===v(ja,a)){var b=a.defaultView||a.parentWindow,c;for(c in P)n.add(a,c,qa),n.add(a,c,Aa,!0);ba?(J=ba===b.MSPointerEvent?{up:"MSPointerUp",
down:"MSPointerDown",over:"mouseover",out:"mouseout",move:"MSPointerMove",cancel:"MSPointerCancel"}:{up:"pointerup",down:"pointerdown",over:"pointerover",out:"pointerout",move:"pointermove",cancel:"pointercancel"},n.add(a,J.down,m.selectorDown),n.add(a,J.move,m.pointerMove),n.add(a,J.over,m.pointerOver),n.add(a,J.out,m.pointerOut),n.add(a,J.up,m.pointerUp),n.add(a,J.cancel,m.pointerCancel),n.add(a,J.move,m.autoScrollMove)):(n.add(a,"mousedown",m.selectorDown),n.add(a,"mousemove",m.pointerMove),n.add(a,
"mouseup",m.pointerUp),n.add(a,"mouseover",m.pointerOver),n.add(a,"mouseout",m.pointerOut),n.add(a,"touchstart",m.selectorDown),n.add(a,"touchmove",m.pointerMove),n.add(a,"touchend",m.pointerUp),n.add(a,"touchcancel",m.pointerCancel),n.add(a,"mousemove",m.autoScrollMove),n.add(a,"touchmove",m.autoScrollMove));n.add(b,"blur",jb);try{if(b.frameElement){var d=b.frameElement.ownerDocument,e=d.defaultView;n.add(d,"mouseup",m.pointerEnd);n.add(d,"touchend",m.pointerEnd);n.add(d,"touchcancel",m.pointerEnd);
n.add(d,"pointerup",m.pointerEnd);n.add(d,"MSPointerUp",m.pointerEnd);n.add(e,"blur",jb)}}catch(h){l.windowParentError=h}n.add(a,"dragstart",function(a){for(var b=0;b<r.length;b++){var c=r[b];if(c.element&&(c.element===a.target||Y(c.element,a.target))){c.checkAndPreventDefault(a,c.target,c.element);break}}});n.useAttachEvent&&(n.add(a,"selectstart",function(a){var b=r[0];b.currentAction()&&b.checkAndPreventDefault(a)}),n.add(a,"dblclick",cb("ie8Dblclick")));ja.push(a)}}function v(a,b){for(var c=0,
d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function R(a,b,c){if(ka)return ka(a,b,c);q!==F&&(b=b.replace(/\/deep\//g," "));return a[Oa](b)}function La(a,b,c){for(;t(a);){if(R(a,b))return!0;a=L(a);if(a===c)return R(a,b)}return!1}if(F){var q=function(){var a=F.document.createTextNode("");return a.ownerDocument!==F.document&&"function"===typeof F.wrap&&F.wrap(a)===a?F.wrap(F):F}(),Q=q.document,$a=q.DocumentFragment||ma,Xa=q.SVGElement||ma,pb=q.SVGSVGElement||ma,nb=q.SVGElementInstance||ma,qb=q.HTMLElement||
q.Element,ba=q.PointerEvent||q.MSPointerEvent,J,fa=Math.hypot||function(a,b){return Math.sqrt(a*a+b*b)},la={},ja=[],B=[],r=[],Pa=!1,P={},D={base:{accept:null,actionChecker:null,styleCursor:!0,preventDefault:"auto",origin:{x:0,y:0},deltaSource:"page",allowFrom:null,ignoreFrom:null,_context:Q,dropChecker:null},drag:{enabled:!1,manualStart:!0,max:Infinity,maxPerElement:1,snap:null,restrict:null,inertia:null,autoScroll:null,axis:"xy"},drop:{enabled:!1,accept:null,overlap:"pointer"},resize:{enabled:!1,
manualStart:!1,max:Infinity,maxPerElement:1,snap:null,restrict:null,inertia:null,autoScroll:null,square:!1,preserveAspectRatio:!1,axis:"xy",margin:NaN,edges:null,invert:"none"},gesture:{manualStart:!1,enabled:!1,max:Infinity,maxPerElement:1,restrict:null},perAction:{manualStart:!1,max:Infinity,maxPerElement:1,snap:{enabled:!1,endOnly:!1,range:Infinity,targets:null,offsets:null,relativePoints:null},restrict:{enabled:!1,endOnly:!1},autoScroll:{enabled:!1,container:null,margin:60,speed:300},inertia:{enabled:!1,
resistance:10,minSpeed:100,endSpeed:10,allowResume:!0,zeroResumeDelta:!0,smoothEndDuration:300}},_holdDuration:600},p={interaction:null,i:null,x:0,y:0,scroll:function(){var a=p.interaction.target.options[p.interaction.prepared.name].autoScroll,b=a.container||V(p.interaction.element),c=(new Date).getTime(),d=(c-p.prevTimeX)/1E3,e=(c-p.prevTimeY)/1E3,h;a.velocity?(h=a.velocity.x,a=a.velocity.y):h=a=a.speed;d*=h;e*=a;if(1<=d||1<=e)Ba(b)?b.scrollBy(p.x*d,p.y*e):b&&(b.scrollLeft+=p.x*d,b.scrollTop+=p.y*
e),1<=d&&(p.prevTimeX=c),1<=e&&(p.prevTimeY=c);p.isScrolling&&(X(p.i),p.i=T(p.scroll))},isScrolling:!1,prevTimeX:0,prevTimeY:0,start:function(a){p.isScrolling=!0;X(p.i);p.interaction=a;p.prevTimeX=(new Date).getTime();p.prevTimeY=(new Date).getTime();p.i=T(p.scroll)},stop:function(){p.isScrolling=!1;X(p.i)}},ga="ontouchstart"in q||q.DocumentTouch&&Q instanceof q.DocumentTouch,oa=!!ba,pa=ga||oa?20:10,Qa=1,db=0,wa=Infinity,za=Q.all&&!q.atob?{drag:"move",resizex:"e-resize",resizey:"s-resize",resizexy:"se-resize",
resizetop:"n-resize",resizeleft:"w-resize",resizebottom:"s-resize",resizeright:"e-resize",resizetopleft:"se-resize",resizebottomright:"se-resize",resizetopright:"ne-resize",resizebottomleft:"ne-resize",gesture:""}:{drag:"move",resizex:"ew-resize",resizey:"ns-resize",resizexy:"nwse-resize",resizetop:"ns-resize",resizeleft:"ew-resize",resizebottom:"ns-resize",resizeright:"ew-resize",resizetopleft:"nwse-resize",resizebottomright:"nwse-resize",resizetopright:"nesw-resize",resizebottomleft:"nesw-resize",
gesture:""},S={drag:!0,resize:!0,gesture:!0},kb="onmousewheel"in Q?"mousewheel":"wheel",ca="dragstart dragmove draginertiastart dragend dragenter dragleave dropactivate dropdeactivate dropmove drop resizestart resizemove resizeinertiastart resizeend gesturestart gesturemove gestureinertiastart gestureend down move up cancel tap doubletap hold".split(" "),U={},Va="Opera"==navigator.appName&&ga&&navigator.userAgent.match("Presto"),ob=/iP(hone|od|ad)/.test(navigator.platform)&&/OS 7[^\d]/.test(navigator.appVersion),
Oa="matches"in Element.prototype?"matches":"webkitMatchesSelector"in Element.prototype?"webkitMatchesSelector":"mozMatchesSelector"in Element.prototype?"mozMatchesSelector":"oMatchesSelector"in Element.prototype?"oMatchesSelector":"msMatchesSelector",ka,T=F.requestAnimationFrame,X=F.cancelAnimationFrame,n=function(){function a(b,c,d,h){var l,m=v(k,b),p=y[m],q,I,r=d;if(p&&p.events)if(e&&(q=n[m],I=v(q.supplied,d),r=q.wrapped[I]),"all"===c)for(c in p.events)p.events.hasOwnProperty(c)&&a(b,c,"all");else{if(p.events[c]){var t=
p.events[c].length;if("all"===d){for(l=0;l<t;l++)a(b,c,p.events[c][l],Boolean(h));return}for(l=0;l<t;l++)if(p.events[c][l]===d){b[f](g+c,r,h||!1);p.events[c].splice(l,1);e&&q&&(q.useCount[I]--,0===q.useCount[I]&&(q.supplied.splice(I,1),q.wrapped.splice(I,1),q.useCount.splice(I,1)));break}p.events[c]&&0===p.events[c].length&&(p.events[c]=null,p.typeCount--)}p.typeCount||(y.splice(m,1),k.splice(m,1),n.splice(m,1))}}function b(){this.returnValue=!1}function c(){this.cancelBubble=!0}function d(){this.immediatePropagationStopped=
this.cancelBubble=!0}var e="attachEvent"in q&&!("addEventListener"in q),h=e?"attachEvent":"addEventListener",f=e?"detachEvent":"removeEventListener",g=e?"on":"",k=[],y=[],n=[];return{add:function(a,f,l,p){var m=v(k,a),q=y[m];q||(q={events:{},typeCount:0},m=k.push(a)-1,y.push(q),n.push(e?{supplied:[],wrapped:[],useCount:[]}:null));q.events[f]||(q.events[f]=[],q.typeCount++);if(-1===v(q.events[f],l)){if(e){var m=n[m],r=v(m.supplied,l),t=m.wrapped[r]||function(e){e.immediatePropagationStopped||(e.target=
e.srcElement,e.currentTarget=a,e.preventDefault=e.preventDefault||b,e.stopPropagation=e.stopPropagation||c,e.stopImmediatePropagation=e.stopImmediatePropagation||d,/mouse|click/.test(e.type)&&(e.pageX=e.clientX+V(a).document.documentElement.scrollLeft,e.pageY=e.clientY+V(a).document.documentElement.scrollTop),l(e))};p=a[h](g+f,t,Boolean(p));-1===r?(m.supplied.push(l),m.wrapped.push(t),m.useCount.push(1)):m.useCount[r]++}else p=a[h](f,l,p||!1);q.events[f].push(l);return p}},remove:a,useAttachEvent:e,
_elements:k,_targets:y,_attachedListeners:n}}(),Ca={webkit:/(Movement[XY]|Radius[XY]|RotationAngle|Force)$/};xa.prototype={getPageXY:function(a,b){return Da(a,b,this)},getClientXY:function(a,b){return Wa(a,b,this)},setEventXY:function(a,b){var c=1<b.length?Ya(b):b[0];Da(c,la,this);a.page.x=la.x;a.page.y=la.y;Wa(c,la,this);a.client.x=la.x;a.client.y=la.y;a.timeStamp=(new Date).getTime()},pointerOver:function(a,b,c){function d(a,b){a&&va(a,c)&&!Z(a,c,c)&&aa(a,c,c)&&R(c,b)&&(e.push(a),h.push(c))}if(!this.prepared.name&&
this.mouse){var e=[],h=[],f=this.element;this.addPointer(a);!this.target||!Z(this.target,this.element,c)&&aa(this.target,this.element,c)||(this.element=this.target=null,this.matches=[],this.matchElements=[]);var g=B.get(c),k=g&&!Z(g,c,c)&&aa(g,c,c)&&W(g.getAction(a,b,this,c),g);k&&!ha(g,c,k)&&(k=null);k?(this.target=g,this.element=c,this.matches=[],this.matchElements=[]):(B.forEachSelector(d),this.validateSelector(a,b,e,h)?(this.matches=e,this.matchElements=h,this.pointerHover(a,b,this.matches,this.matchElements),
n.add(c,ba?J.move:"mousemove",m.pointerHover)):this.target&&(Y(f,c)?(this.pointerHover(a,b,this.matches,this.matchElements),n.add(this.element,ba?J.move:"mousemove",m.pointerHover)):(this.element=this.target=null,this.matches=[],this.matchElements=[])))}},pointerHover:function(a,b,c,d,e,h){c=this.target;if(!this.prepared.name&&this.mouse){var f;this.setEventXY(this.curCoords,[a]);e?f=this.validateSelector(a,b,e,h):c&&(f=W(c.getAction(this.pointers[0],b,this,this.element),this.target));c&&c.options.styleCursor&&
(c._doc.documentElement.style.cursor=f?gb(f):"")}else this.prepared.name&&this.checkAndPreventDefault(b,c,this.element)},pointerOut:function(a,b,c){this.prepared.name||(B.get(c)||n.remove(c,ba?J.move:"mousemove",m.pointerHover),this.target&&this.target.options.styleCursor&&!this.interacting()&&(this.target._doc.documentElement.style.cursor=""))},selectorDown:function(a,b,c,d){function e(a,b,d){d=ka?d.querySelectorAll(b):void 0;va(a,g)&&!Z(a,g,c)&&aa(a,g,c)&&R(g,b,d)&&(h.matches.push(a),h.matchElements.push(g))}
var h=this,f=n.useAttachEvent?x({},b):b,g=c,k=this.addPointer(a),l;this.holdTimers[k]=setTimeout(function(){h.pointerHold(n.useAttachEvent?f:a,f,c,d)},D._holdDuration);this.pointerIsDown=!0;if(this.inertiaStatus.active&&this.target.selector)for(;t(g);){if(g===this.element&&W(this.target.getAction(a,b,this,this.element),this.target).name===this.prepared.name){X(this.inertiaStatus.i);this.inertiaStatus.active=!1;this.collectEventTargets(a,b,c,"down");return}g=L(g)}if(!this.interacting()){this.setEventXY(this.curCoords,
[a]);for(this.downEvent=b;t(g)&&!l;)this.matches=[],this.matchElements=[],B.forEachSelector(e),l=this.validateSelector(a,b,this.matches,this.matchElements),g=L(g);if(l)return this.prepared.name=l.name,this.prepared.axis=l.axis,this.prepared.edges=l.edges,this.collectEventTargets(a,b,c,"down"),this.pointerDown(a,b,c,d,l);this.downTimes[k]=(new Date).getTime();this.downTargets[k]=c;ra(this.downPointer,a);sa(this.prevCoords,this.curCoords);this.pointerWasMoved=!1}this.collectEventTargets(a,b,c,"down")},
pointerDown:function(a,b,c,d,e){if(!e&&!this.inertiaStatus.active&&this.pointerWasMoved&&this.prepared.name)this.checkAndPreventDefault(b,this.target,this.element);else{this.pointerIsDown=!0;this.downEvent=b;var h=this.addPointer(a),f;if(1<this.pointerIds.length&&this.target._element===this.element){var g=W(e||this.target.getAction(a,b,this,this.element),this.target);ha(this.target,this.element,g)&&(f=g);this.prepared.name=null}else this.prepared.name||(g=B.get(d))&&!Z(g,d,c)&&aa(g,d,c)&&(f=W(e||
g.getAction(a,b,this,d),g,c))&&ha(g,d,f)&&(this.target=g,this.element=d);var k=(g=this.target)&&g.options;!g||!e&&this.prepared.name?this.inertiaStatus.active&&d===this.element&&W(g.getAction(a,b,this,this.element),g).name===this.prepared.name&&(X(this.inertiaStatus.i),this.inertiaStatus.active=!1,this.checkAndPreventDefault(b,g,this.element)):(f=f||W(e||g.getAction(a,b,this,d),g,this.element),this.setEventXY(this.startCoords,this.pointers),f&&(k.styleCursor&&(g._doc.documentElement.style.cursor=
gb(f)),this.resizeAxes="resize"===f.name?f.axis:null,"gesture"===f&&2>this.pointerIds.length&&(f=null),this.prepared.name=f.name,this.prepared.axis=f.axis,this.prepared.edges=f.edges,this.snapStatus.snappedX=this.snapStatus.snappedY=this.restrictStatus.restrictedX=this.restrictStatus.restrictedY=NaN,this.downTimes[h]=(new Date).getTime(),this.downTargets[h]=c,ra(this.downPointer,a),sa(this.prevCoords,this.startCoords),this.pointerWasMoved=!1,this.checkAndPreventDefault(b,g,this.element)))}},setModifications:function(a,
b){var c=this.target,d=!0,e=Ma(c,this.prepared.name)&&(!c.options[this.prepared.name].snap.endOnly||b),c=Na(c,this.prepared.name)&&(!c.options[this.prepared.name].restrict.endOnly||b);e?this.setSnapping(a):this.snapStatus.locked=!1;c?this.setRestriction(a):this.restrictStatus.restricted=!1;e&&this.snapStatus.locked&&!this.snapStatus.changed?d=c&&this.restrictStatus.restricted&&this.restrictStatus.changed:c&&this.restrictStatus.restricted&&!this.restrictStatus.changed&&(d=!1);return d},setStartOffsets:function(a,
b,c){a=b.getRect(c);var d=na(b,c);c=b.options[this.prepared.name].snap;b=b.options[this.prepared.name].restrict;var e,h;a?(this.startOffset.left=this.startCoords.page.x-a.left,this.startOffset.top=this.startCoords.page.y-a.top,this.startOffset.right=a.right-this.startCoords.page.x,this.startOffset.bottom=a.bottom-this.startCoords.page.y,e="width"in a?a.width:a.right-a.left,h="height"in a?a.height:a.bottom-a.top):this.startOffset.left=this.startOffset.top=this.startOffset.right=this.startOffset.bottom=
0;this.snapOffsets.splice(0);d=c&&"startCoords"===c.offset?{x:this.startCoords.page.x-d.x,y:this.startCoords.page.y-d.y}:c&&c.offset||{x:0,y:0};if(a&&c&&c.relativePoints&&c.relativePoints.length)for(var f=0;f<c.relativePoints.length;f++)this.snapOffsets.push({x:this.startOffset.left-e*c.relativePoints[f].x+d.x,y:this.startOffset.top-h*c.relativePoints[f].y+d.y});else this.snapOffsets.push(d);a&&b.elementRect?(this.restrictOffset.left=this.startOffset.left-e*b.elementRect.left,this.restrictOffset.top=
this.startOffset.top-h*b.elementRect.top,this.restrictOffset.right=this.startOffset.right-e*(1-b.elementRect.right),this.restrictOffset.bottom=this.startOffset.bottom-h*(1-b.elementRect.bottom)):this.restrictOffset.left=this.restrictOffset.top=this.restrictOffset.right=this.restrictOffset.bottom=0},start:function(a,b,c){this.interacting()||!this.pointerIsDown||this.pointerIds.length<("gesture"===a.name?2:1)||(-1===v(r,this)&&r.push(this),this.prepared.name||this.setEventXY(this.startCoords),this.prepared.name=
a.name,this.prepared.axis=a.axis,this.prepared.edges=a.edges,this.target=b,this.element=c,this.setStartOffsets(a.name,b,c),this.setModifications(this.startCoords.page),this.prevEvent=this[this.prepared.name+"Start"](this.downEvent))},pointerMove:function(a,b,c,d,e){if(this.inertiaStatus.active){d=this.inertiaStatus.upCoords.page;var h=this.inertiaStatus.upCoords.client;this.setEventXY(this.curCoords,[{pageX:d.x+this.inertiaStatus.sx,pageY:d.y+this.inertiaStatus.sy,clientX:h.x+this.inertiaStatus.sx,
clientY:h.y+this.inertiaStatus.sy}])}else this.recordPointer(a),this.setEventXY(this.curCoords,this.pointers);d=this.curCoords.page.x===this.prevCoords.page.x&&this.curCoords.page.y===this.prevCoords.page.y&&this.curCoords.client.x===this.prevCoords.client.x&&this.curCoords.client.y===this.prevCoords.client.y;var f,g,h=this.mouse?0:v(this.pointerIds,O(a));this.pointerIsDown&&!this.pointerWasMoved&&(f=this.curCoords.client.x-this.startCoords.client.x,g=this.curCoords.client.y-this.startCoords.client.y,
this.pointerWasMoved=fa(f,g)>Qa);d||this.pointerIsDown&&!this.pointerWasMoved||(this.pointerIsDown&&clearTimeout(this.holdTimers[h]),this.collectEventTargets(a,b,c,"move"));if(this.pointerIsDown)if(d&&this.pointerWasMoved&&!e)this.checkAndPreventDefault(b,this.target,this.element);else if(Ta(this.pointerDelta,this.prevCoords,this.curCoords),this.prepared.name){if(this.pointerWasMoved&&(!this.inertiaStatus.active||a instanceof G&&/inertiastart/.test(a.type))){if(!this.interacting()&&(Ta(this.pointerDelta,
this.prevCoords,this.curCoords),"drag"===this.prepared.name)){f=Math.abs(f);g=Math.abs(g);d=this.target.options.drag.axis;var k=f>g?"x":f<g?"y":"xy";if("xy"!==k&&"xy"!==d&&d!==k){this.prepared.name=null;for(var l=c;t(l);){if((g=B.get(l))&&g!==this.target&&!g.options.drag.manualStart&&"drag"===g.getAction(this.downPointer,this.downEvent,this,l).name&&ab(k,g)){this.prepared.name="drag";this.target=g;this.element=l;break}l=L(l)}if(!this.prepared.name){var n=this;g=function(a,b,d){d=ka?d.querySelectorAll(b):
void 0;if(a!==n.target&&va(a,c)&&!a.options.drag.manualStart&&!Z(a,l,c)&&aa(a,l,c)&&R(l,b,d)&&"drag"===a.getAction(n.downPointer,n.downEvent,n,l).name&&ab(k,a)&&ha(a,l,"drag"))return a};for(l=c;t(l);){if(f=B.forEachSelector(g)){this.prepared.name="drag";this.target=f;this.element=l;break}l=L(l)}}}}if((g=!!this.prepared.name&&!this.interacting())&&(this.target.options[this.prepared.name].manualStart||!ha(this.target,this.element,this.prepared))){this.stop(b);return}if(this.prepared.name&&this.target){g&&
this.start(this.prepared,this.target,this.element);if(this.setModifications(this.curCoords.page,e)||g)this.prevEvent=this[this.prepared.name+"Move"](b);this.checkAndPreventDefault(b,this.target,this.element)}}sa(this.prevCoords,this.curCoords);(this.dragging||this.resizing)&&this.autoScrollMove(a)}},dragStart:function(a){var b=new G(this,a,"drag","start",this.element);this.dragging=!0;this.target.fire(b);this.activeDrops.dropzones=[];this.activeDrops.elements=[];this.activeDrops.rects=[];this.dynamicDrop||
this.setActiveDrops(this.element);a=this.getDropEvents(a,b);a.activate&&this.fireActiveDrops(a.activate);return b},dragMove:function(a){var b=this.target,c=new G(this,a,"drag","move",this.element),d=this.getDrop(c,a,this.element);this.dropTarget=d.dropzone;this.dropElement=d.element;a=this.getDropEvents(a,c);b.fire(c);a.leave&&this.prevDropTarget.fire(a.leave);a.enter&&this.dropTarget.fire(a.enter);a.move&&this.dropTarget.fire(a.move);this.prevDropTarget=this.dropTarget;this.prevDropElement=this.dropElement;
return c},resizeStart:function(a){a=new G(this,a,"resize","start",this.element);if(this.prepared.edges){var b=this.target.getRect(this.element);if(this.target.options.resize.square||this.target.options.resize.preserveAspectRatio){var c=x({},this.prepared.edges);c.top=c.top||c.left&&!c.bottom;c.left=c.left||c.top&&!c.right;c.bottom=c.bottom||c.right&&!c.top;c.right=c.right||c.bottom&&!c.left;this.prepared._linkedEdges=c}else this.prepared._linkedEdges=null;this.target.options.resize.preserveAspectRatio&&
(this.resizeStartAspectRatio=b.width/b.height);this.resizeRects={start:b,current:x({},b),restricted:x({},b),previous:x({},b),delta:{left:0,right:0,width:0,top:0,bottom:0,height:0}};a.rect=this.resizeRects.restricted;a.deltaRect=this.resizeRects.delta}this.target.fire(a);this.resizing=!0;return a},resizeMove:function(a){a=new G(this,a,"resize","move",this.element);var b=this.prepared.edges,c=this.target.options.resize.invert,d="reposition"===c||"negate"===c;if(b){var e=a.dx,h=a.dy,f=this.resizeRects.start,
g=this.resizeRects.current,k=this.resizeRects.restricted,l=this.resizeRects.delta,n=x(this.resizeRects.previous,k),m=b;if(this.target.options.resize.preserveAspectRatio){var p=this.resizeStartAspectRatio,b=this.prepared._linkedEdges;if(m.left&&m.bottom||m.right&&m.top)h=-e/p;else if(m.left||m.right)h=e/p;else if(m.top||m.bottom)e=h*p}else if(this.target.options.resize.square)if(b=this.prepared._linkedEdges,m.left&&m.bottom||m.right&&m.top)h=-e;else if(m.left||m.right)h=e;else if(m.top||m.bottom)e=
h;b.top&&(g.top+=h);b.bottom&&(g.bottom+=h);b.left&&(g.left+=e);b.right&&(g.right+=e);d?(x(k,g),"reposition"===c&&(k.top>k.bottom&&(b=k.top,k.top=k.bottom,k.bottom=b),k.left>k.right&&(b=k.left,k.left=k.right,k.right=b))):(k.top=Math.min(g.top,f.bottom),k.bottom=Math.max(g.bottom,f.top),k.left=Math.min(g.left,f.right),k.right=Math.max(g.right,f.left));k.width=k.right-k.left;k.height=k.bottom-k.top;for(var q in k)l[q]=k[q]-n[q];a.edges=this.prepared.edges;a.rect=k;a.deltaRect=l}this.target.fire(a);
return a},gestureStart:function(a){a=new G(this,a,"gesture","start",this.element);a.ds=0;this.gesture.startDistance=this.gesture.prevDistance=a.distance;this.gesture.startAngle=this.gesture.prevAngle=a.angle;this.gesture.scale=1;this.gesturing=!0;this.target.fire(a);return a},gestureMove:function(a){if(!this.pointerIds.length)return this.prevEvent;a=new G(this,a,"gesture","move",this.element);a.ds=a.scale-this.gesture.scale;this.target.fire(a);this.gesture.prevAngle=a.angle;this.gesture.prevDistance=
a.distance;Infinity===a.scale||null===a.scale||void 0===a.scale||isNaN(a.scale)||(this.gesture.scale=a.scale);return a},pointerHold:function(a,b,c){this.collectEventTargets(a,b,c,"hold")},pointerUp:function(a,b,c,d){var e=this.mouse?0:v(this.pointerIds,O(a));clearTimeout(this.holdTimers[e]);this.collectEventTargets(a,b,c,"up");this.collectEventTargets(a,b,c,"tap");this.pointerEnd(a,b,c,d);this.removePointer(a)},pointerCancel:function(a,b,c,d){var e=this.mouse?0:v(this.pointerIds,O(a));clearTimeout(this.holdTimers[e]);
this.collectEventTargets(a,b,c,"cancel");this.pointerEnd(a,b,c,d);this.removePointer(a)},ie8Dblclick:function(a,b,c){this.prevTap&&b.clientX===this.prevTap.clientX&&b.clientY===this.prevTap.clientY&&c===this.prevTap.target&&(this.downTargets[0]=c,this.downTimes[0]=(new Date).getTime(),this.collectEventTargets(a,b,c,"tap"))},pointerEnd:function(a,b,c,d){var e,h=this.target,f=h&&h.options,g=f&&this.prepared.name&&f[this.prepared.name].inertia;e=this.inertiaStatus;if(this.interacting()){if(e.active&&
!e.ending)return;var k=(new Date).getTime(),l=!1,m=!1,n=!1,p=Ma(h,this.prepared.name)&&f[this.prepared.name].snap.endOnly,q=Na(h,this.prepared.name)&&f[this.prepared.name].restrict.endOnly,r=0,t=0,f=this.dragging?"x"===f.drag.axis?Math.abs(this.pointerDelta.client.vx):"y"===f.drag.axis?Math.abs(this.pointerDelta.client.vy):this.pointerDelta.client.speed:this.pointerDelta.client.speed,m=(l=g&&g.enabled&&"gesture"!==this.prepared.name&&b!==e.startEvent)&&50>k-this.curCoords.timeStamp&&f>g.minSpeed&&
f>g.endSpeed;l&&!m&&(p||q)&&(g={},g.snap=g.restrict=g,p&&(this.setSnapping(this.curCoords.page,g),g.locked&&(r+=g.dx,t+=g.dy)),q&&(this.setRestriction(this.curCoords.page,g),g.restricted&&(r+=g.dx,t+=g.dy)),r||t)&&(n=!0);if(m||n){sa(e.upCoords,this.curCoords);this.pointers[0]=e.startEvent=new G(this,b,this.prepared.name,"inertiastart",this.element);e.t0=k;h.fire(e.startEvent);m?(e.vx0=this.pointerDelta.client.vx,e.vy0=this.pointerDelta.client.vy,e.v0=f,this.calcInertia(e),b=x({},this.curCoords.page),
h=na(h,this.element),b.x=b.x+e.xe-h.x,b.y=b.y+e.ye-h.y,h={useStatusXY:!0,x:b.x,y:b.y,dx:0,dy:0,snap:null},h.snap=h,r=t=0,p&&(b=this.setSnapping(this.curCoords.page,h),b.locked&&(r+=b.dx,t+=b.dy)),q&&(h=this.setRestriction(this.curCoords.page,h),h.restricted&&(r+=h.dx,t+=h.dy)),e.modifiedXe+=r,e.modifiedYe+=t,e.i=T(this.boundInertiaFrame)):(e.smoothEnd=!0,e.xe=r,e.ye=t,e.sx=e.sy=0,e.i=T(this.boundSmoothEndFrame));e.active=!0;return}(p||q)&&this.pointerMove(a,b,c,d,!0)}this.dragging?(e=new G(this,b,
"drag","end",this.element),q=this.getDrop(e,b,this.element),this.dropTarget=q.dropzone,this.dropElement=q.element,q=this.getDropEvents(b,e),q.leave&&this.prevDropTarget.fire(q.leave),q.enter&&this.dropTarget.fire(q.enter),q.drop&&this.dropTarget.fire(q.drop),q.deactivate&&this.fireActiveDrops(q.deactivate),h.fire(e)):this.resizing?(e=new G(this,b,"resize","end",this.element),h.fire(e)):this.gesturing&&(e=new G(this,b,"gesture","end",this.element),h.fire(e));this.stop(b)},collectDrops:function(a){var b=
[],c=[],d;a=a||this.element;for(d=0;d<B.length;d++)if(B[d].options.drop.enabled){var e=B[d],h=e.options.drop.accept;if(!(t(h)&&h!==a||N(h)&&!R(a,h)))for(var h=e.selector?e._context.querySelectorAll(e.selector):[e._element],f=0,g=h.length;f<g;f++){var k=h[f];k!==a&&(b.push(e),c.push(k))}}return{dropzones:b,elements:c}},fireActiveDrops:function(a){var b,c,d,e;for(b=0;b<this.activeDrops.dropzones.length;b++)c=this.activeDrops.dropzones[b],d=this.activeDrops.elements[b],d!==e&&(a.target=d,c.fire(a)),
e=d},setActiveDrops:function(a){a=this.collectDrops(a,!0);this.activeDrops.dropzones=a.dropzones;this.activeDrops.elements=a.elements;this.activeDrops.rects=[];for(a=0;a<this.activeDrops.dropzones.length;a++)this.activeDrops.rects[a]=this.activeDrops.dropzones[a].getRect(this.activeDrops.elements[a])},getDrop:function(a,b,c){var d=[];Pa&&this.setActiveDrops(c);for(var e=0;e<this.activeDrops.dropzones.length;e++){var h=this.activeDrops.elements[e];d.push(this.activeDrops.dropzones[e].dropCheck(a,b,
this.target,c,h,this.activeDrops.rects[e])?h:null)}c=(b=d[0])?0:-1;for(var f,e=[],g=[],h=1;h<d.length;h++)if((a=d[h])&&a!==b)if(!b)b=a,c=h;else if(a.parentNode!==a.ownerDocument)if(b.parentNode===a.ownerDocument)b=a,c=h;else{if(!e.length)for(f=b;f.parentNode&&f.parentNode!==f.ownerDocument;)e.unshift(f),f=f.parentNode;if(b instanceof qb&&a instanceof Xa&&!(a instanceof pb)){if(a===b.parentNode)continue;f=a.ownerSVGElement}else f=a;for(g=[];f.parentNode!==f.ownerDocument;)g.unshift(f),f=f.parentNode;
for(f=0;g[f]&&g[f]===e[f];)f++;f=[g[f-1],g[f],e[f]];for(g=f[0].lastChild;g;){if(g===f[1]){b=a;c=h;e=[];break}else if(g===f[2])break;g=g.previousSibling}}d=c;return{dropzone:this.activeDrops.dropzones[d]||null,element:this.activeDrops.elements[d]||null}},getDropEvents:function(a,b){var c={enter:null,leave:null,activate:null,deactivate:null,move:null,drop:null};this.dropElement!==this.prevDropElement&&(this.prevDropTarget&&(c.leave={target:this.prevDropElement,dropzone:this.prevDropTarget,relatedTarget:b.target,
draggable:b.interactable,dragEvent:b,interaction:this,timeStamp:b.timeStamp,type:"dragleave"},b.dragLeave=this.prevDropElement,b.prevDropzone=this.prevDropTarget),this.dropTarget&&(c.enter={target:this.dropElement,dropzone:this.dropTarget,relatedTarget:b.target,draggable:b.interactable,dragEvent:b,interaction:this,timeStamp:b.timeStamp,type:"dragenter"},b.dragEnter=this.dropElement,b.dropzone=this.dropTarget));"dragend"===b.type&&this.dropTarget&&(c.drop={target:this.dropElement,dropzone:this.dropTarget,
relatedTarget:b.target,draggable:b.interactable,dragEvent:b,interaction:this,timeStamp:b.timeStamp,type:"drop"},b.dropzone=this.dropTarget);"dragstart"===b.type&&(c.activate={target:null,dropzone:null,relatedTarget:b.target,draggable:b.interactable,dragEvent:b,interaction:this,timeStamp:b.timeStamp,type:"dropactivate"});"dragend"===b.type&&(c.deactivate={target:null,dropzone:null,relatedTarget:b.target,draggable:b.interactable,dragEvent:b,interaction:this,timeStamp:b.timeStamp,type:"dropdeactivate"});
"dragmove"===b.type&&this.dropTarget&&(c.move={target:this.dropElement,dropzone:this.dropTarget,relatedTarget:b.target,draggable:b.interactable,dragEvent:b,interaction:this,dragmove:b,timeStamp:b.timeStamp,type:"dropmove"},b.dropzone=this.dropTarget);return c},currentAction:function(){return this.dragging&&"drag"||this.resizing&&"resize"||this.gesturing&&"gesture"||null},interacting:function(){return this.dragging||this.resizing||this.gesturing},clearTargets:function(){this.dropTarget=this.dropElement=
this.prevDropTarget=this.prevDropElement=this.target=this.element=null},stop:function(a){if(this.interacting()){p.stop();this.matches=[];this.matchElements=[];var b=this.target;b.options.styleCursor&&(b._doc.documentElement.style.cursor="");a&&A(a.preventDefault)&&this.checkAndPreventDefault(a,b,this.element);this.dragging&&(this.activeDrops.dropzones=this.activeDrops.elements=this.activeDrops.rects=null)}this.clearTargets();this.pointerIsDown=this.snapStatus.locked=this.dragging=this.resizing=this.gesturing=
!1;this.prepared.name=this.prevEvent=null;for(a=this.inertiaStatus.resumeDx=this.inertiaStatus.resumeDy=0;a<this.pointers.length;a++)-1===v(this.pointerIds,O(this.pointers[a]))&&this.pointers.splice(a,1)},inertiaFrame:function(){var a,b,c=this.inertiaStatus;a=this.target.options[this.prepared.name].inertia.resistance;b=(new Date).getTime()/1E3-c.t0;if(b<c.te){b=1-(Math.exp(-a*b)-c.lambda_v0)/c.one_ve_v0;if(c.modifiedXe===c.xe&&c.modifiedYe===c.ye)c.sx=c.xe*b,c.sy=c.ye*b;else{var d=c.ye,e=c.modifiedYe;
a=Za(b,0,c.xe,c.modifiedXe);b=Za(b,0,d,e);c.sx=a;c.sy=b}this.pointerMove(c.startEvent,c.startEvent);c.i=T(this.boundInertiaFrame)}else c.ending=!0,c.sx=c.modifiedXe,c.sy=c.modifiedYe,this.pointerMove(c.startEvent,c.startEvent),this.pointerEnd(c.startEvent,c.startEvent),c.active=c.ending=!1},smoothEndFrame:function(){var a=this.inertiaStatus,b=(new Date).getTime()-a.t0,c=this.target.options[this.prepared.name].inertia.smoothEndDuration;if(b<c){var d;d=b/c;a.sx=-a.xe*d*(d-2)+0;b/=c;a.sy=-a.ye*b*(b-
2)+0;this.pointerMove(a.startEvent,a.startEvent);a.i=T(this.boundSmoothEndFrame)}else a.ending=!0,a.sx=a.xe,a.sy=a.ye,this.pointerMove(a.startEvent,a.startEvent),this.pointerEnd(a.startEvent,a.startEvent),a.smoothEnd=a.active=a.ending=!1},addPointer:function(a){var b=O(a),c=this.mouse?0:v(this.pointerIds,b);-1===c&&(c=this.pointerIds.length);this.pointerIds[c]=b;this.pointers[c]=a;return c},removePointer:function(a){a=O(a);a=this.mouse?0:v(this.pointerIds,a);-1!==a&&(this.pointers.splice(a,1),this.pointerIds.splice(a,
1),this.downTargets.splice(a,1),this.downTimes.splice(a,1),this.holdTimers.splice(a,1))},recordPointer:function(a){var b=this.mouse?0:v(this.pointerIds,O(a));-1!==b&&(this.pointers[b]=a)},collectEventTargets:function(a,b,c,d){function e(a,b,e){e=ka?e.querySelectorAll(b):void 0;a._iEvents[d]&&t(k)&&va(a,k)&&!Z(a,k,c)&&aa(a,k,c)&&R(k,b,e)&&(f.push(a),g.push(k))}var h=this.mouse?0:v(this.pointerIds,O(a));if("tap"!==d||!this.pointerWasMoved&&this.downTargets[h]&&this.downTargets[h]===c){for(var f=[],
g=[],k=c;k;)l.isSet(k)&&l(k)._iEvents[d]&&(f.push(l(k)),g.push(k)),B.forEachSelector(e),k=L(k);(f.length||"tap"===d)&&this.firePointers(a,b,c,f,g,d)}},firePointers:function(a,b,c,d,e,h){var f=this.mouse?0:v(this.pointerIds,O(a)),g={},k,l;"doubletap"===h?g=a:(ra(g,b),b!==a&&ra(g,a),g.preventDefault=fb,g.stopPropagation=G.prototype.stopPropagation,g.stopImmediatePropagation=G.prototype.stopImmediatePropagation,g.interaction=this,g.timeStamp=(new Date).getTime(),g.originalEvent=b,g.originalPointer=a,
g.type=h,g.pointerId=O(a),g.pointerType=this.mouse?"mouse":oa?N(a.pointerType)?a.pointerType:[,,"touch","pen","mouse"][a.pointerType]:"touch");"tap"===h&&(g.dt=g.timeStamp-this.downTimes[f],k=g.timeStamp-this.tapTime,l=!!(this.prevTap&&"doubletap"!==this.prevTap.type&&this.prevTap.target===g.target&&500>k),g["double"]=l,this.tapTime=g.timeStamp);for(a=0;a<d.length&&!(g.currentTarget=e[a],g.interactable=d[a],d[a].fire(g),g.immediatePropagationStopped||g.propagationStopped&&e[a+1]!==g.currentTarget);a++);
l?(d={},x(d,g),d.dt=k,d.type="doubletap",this.collectEventTargets(d,b,c,"doubletap"),this.prevTap=d):"tap"===h&&(this.prevTap=g)},validateSelector:function(a,b,c,d){for(var e=0,h=c.length;e<h;e++){var f=c[e],g=d[e],k=W(f.getAction(a,b,this,g),f);if(k&&ha(f,g,k))return this.target=f,this.element=g,k}},setSnapping:function(a,b){var c=this.target.options[this.prepared.name].snap,d=[],e,h,f;b=b||this.snapStatus;b.useStatusXY?h={x:b.x,y:b.y}:(e=na(this.target,this.element),h=x({},a),h.x-=e.x,h.y-=e.y);
b.realX=h.x;b.realY=h.y;h.x-=this.inertiaStatus.resumeDx;h.y-=this.inertiaStatus.resumeDy;for(var g=c.targets?c.targets.length:0,k=0;k<this.snapOffsets.length;k++){var l=h.x-this.snapOffsets[k].x,m=h.y-this.snapOffsets[k].y;for(f=0;f<g;f++)(e=A(c.targets[f])?c.targets[f](l,m,this):c.targets[f])&&d.push({x:K(e.x)?e.x+this.snapOffsets[k].x:l,y:K(e.y)?e.y+this.snapOffsets[k].y:m,range:K(e.range)?e.range:c.range})}var c=null,k=!1,n=0,p=0;f=m=l=0;for(g=d.length;f<g;f++){e=d[f];var q=e.range,r=e.x-h.x,
t=e.y-h.y,w=fa(r,t),v=w<=q;Infinity===q&&k&&Infinity!==p&&(v=!1);if(!c||(v?k&&Infinity!==q?w/q<n/p:Infinity===q&&Infinity!==p||w<n:!k&&w<n))Infinity===q&&(v=!0),c=e,n=w,p=q,k=v,l=r,m=t,b.range=q}c?(d=b.snappedX!==c.x||b.snappedY!==c.y,b.snappedX=c.x,b.snappedY=c.y):(d=!0,b.snappedX=NaN,b.snappedY=NaN);b.dx=l;b.dy=m;b.changed=d||k&&!b.locked;b.locked=k;return b},setRestriction:function(a,b){var c=this.target,d=c&&c.options[this.prepared.name].restrict,e=d&&d.restriction;if(!e)return b;b=b||this.restrictStatus;
d=b.useStatusXY?d={x:b.x,y:b.y}:d=x({},a);b.snap&&b.snap.locked&&(d.x+=b.snap.dx||0,d.y+=b.snap.dy||0);d.x-=this.inertiaStatus.resumeDx;d.y-=this.inertiaStatus.resumeDy;b.dx=0;b.dy=0;b.restricted=!1;if(N(e)&&(e="parent"===e?L(this.element):"self"===e?c.getRect(this.element):Ka(this.element,e),!e))return b;A(e)&&(e=e(d.x,d.y,this.element));t(e)&&(e=ua(e));(c=e)?"x"in e&&"y"in e?(e=Math.max(Math.min(c.x+c.width-this.restrictOffset.right,d.x),c.x+this.restrictOffset.left),c=Math.max(Math.min(c.y+c.height-
this.restrictOffset.bottom,d.y),c.y+this.restrictOffset.top)):(e=Math.max(Math.min(c.right-this.restrictOffset.right,d.x),c.left+this.restrictOffset.left),c=Math.max(Math.min(c.bottom-this.restrictOffset.bottom,d.y),c.top+this.restrictOffset.top)):(e=d.x,c=d.y);b.dx=e-d.x;b.dy=c-d.y;b.changed=b.restrictedX!==e||b.restrictedY!==c;b.restricted=!(!b.dx&&!b.dy);b.restrictedX=e;b.restrictedY=c;return b},checkAndPreventDefault:function(a,b,c){if(b=b||this.target){b=b.options;var d=b.preventDefault;"auto"===
d&&c&&!/^(input|select|textarea)$/i.test(a.target.nodeName)?/down|start/i.test(a.type)&&"drag"===this.prepared.name&&"xy"!==b.drag.axis||b[this.prepared.name]&&b[this.prepared.name].manualStart&&!this.interacting()||a.preventDefault():"always"===d&&a.preventDefault()}},calcInertia:function(a){var b=this.target.options[this.prepared.name].inertia,c=b.resistance,d=-Math.log(b.endSpeed/a.v0)/c;a.x0=this.prevEvent.pageX;a.y0=this.prevEvent.pageY;a.t0=a.startEvent.timeStamp/1E3;a.sx=a.sy=0;a.modifiedXe=
a.xe=(a.vx0-d)/c;a.modifiedYe=a.ye=(a.vy0-d)/c;a.te=d;a.lambda_v0=c/a.v0;a.one_ve_v0=1-b.endSpeed/a.v0},autoScrollMove:function(a){var b;if(b=this.interacting()){b=this.prepared.name;var c=this.target.options;/^resize/.test(b)&&(b="resize");b=c[b].autoScroll&&c[b].autoScroll.enabled}if(b)if(this.inertiaStatus.active)p.x=p.y=0;else{var d,e=this.target.options[this.prepared.name].autoScroll,h=e.container||V(this.element);Ba(h)?(d=a.clientX<p.margin,b=a.clientY<p.margin,c=a.clientX>h.innerWidth-p.margin,
a=a.clientY>h.innerHeight-p.margin):(h=Fa(h),d=a.clientX<h.left+p.margin,b=a.clientY<h.top+p.margin,c=a.clientX>h.right-p.margin,a=a.clientY>h.bottom-p.margin);p.x=c?1:d?-1:0;p.y=a?1:b?-1:0;p.isScrolling||(p.margin=e.margin,p.speed=e.speed,p.start(this))}},_updateEventTargets:function(a,b){this._eventTarget=a;this._curEventTarget=b}};G.prototype={preventDefault:ma,stopImmediatePropagation:function(){this.immediatePropagationStopped=this.propagationStopped=!0},stopPropagation:function(){this.propagationStopped=
!0}};for(var m={},lb="dragStart dragMove resizeStart resizeMove gestureStart gestureMove pointerOver pointerOut pointerHover selectorDown pointerDown pointerMove pointerUp pointerCancel pointerEnd addPointer removePointer recordPointer autoScrollMove".split(" "),Ra=0,Sa=lb.length;Ra<Sa;Ra++){var mb=lb[Ra];m[mb]=cb(mb)}B.indexOfElement=function(a,b){b=b||Q;for(var c=0;c<this.length;c++){var d=this[c];if(d.selector===a&&d._context===b||!d.selector&&d._element===a)return c}return-1};B.get=function(a,
b){return this[this.indexOfElement(a,b&&b.context)]};B.forEachSelector=function(a){for(var b=0;b<this.length;b++){var c=this[b];if(c.selector&&(c=a(c,c.selector,c._context,b,this),void 0!==c))return c}};C.prototype={setOnEvents:function(a,b){"drop"===a?(A(b.ondrop)&&(this.ondrop=b.ondrop),A(b.ondropactivate)&&(this.ondropactivate=b.ondropactivate),A(b.ondropdeactivate)&&(this.ondropdeactivate=b.ondropdeactivate),A(b.ondragenter)&&(this.ondragenter=b.ondragenter),A(b.ondragleave)&&(this.ondragleave=
b.ondragleave),A(b.ondropmove)&&(this.ondropmove=b.ondropmove)):(a="on"+a,A(b.onstart)&&(this[a+"start"]=b.onstart),A(b.onmove)&&(this[a+"move"]=b.onmove),A(b.onend)&&(this[a+"end"]=b.onend),A(b.oninertiastart)&&(this[a+"inertiastart"]=b.oninertiastart));return this},draggable:function(a){return z(a)?(this.options.drag.enabled=!1===a.enabled?!1:!0,this.setPerAction("drag",a),this.setOnEvents("drag",a),/^x$|^y$|^xy$/.test(a.axis)?this.options.drag.axis=a.axis:null===a.axis&&delete this.options.drag.axis,
this):H(a)?(this.options.drag.enabled=a,this):this.options.drag},setPerAction:function(a,b){for(var c in b)c in D[a]&&(z(b[c])?(this.options[a][c]=x(this.options[a][c]||{},b[c]),z(D.perAction[c])&&"enabled"in D.perAction[c]&&(this.options[a][c].enabled=!1===b[c].enabled?!1:!0)):H(b[c])&&z(D.perAction[c])?this.options[a][c].enabled=b[c]:void 0!==b[c]&&(this.options[a][c]=b[c]))},dropzone:function(a){return z(a)?(this.options.drop.enabled=!1===a.enabled?!1:!0,this.setOnEvents("drop",a),/^(pointer|center)$/.test(a.overlap)?
this.options.drop.overlap=a.overlap:K(a.overlap)&&(this.options.drop.overlap=Math.max(Math.min(1,a.overlap),0)),"accept"in a&&(this.options.drop.accept=a.accept),"checker"in a&&(this.options.drop.checker=a.checker),this):H(a)?(this.options.drop.enabled=a,this):this.options.drop},dropCheck:function(a,b,c,d,e,h){var f=!1;if(!(h=h||this.getRect(e)))return this.options.drop.checker?this.options.drop.checker(a,b,f,this,e,c,d):!1;var g=this.options.drop.overlap;if("pointer"===g){var k=Da(a),f=na(c,d);k.x+=
f.x;k.y+=f.y;f=k.x>h.left&&k.x<h.right;k=k.y>h.top&&k.y<h.bottom;f=f&&k}k=c.getRect(d);if("center"===g)var f=k.left+k.width/2,l=k.top+k.height/2,f=f>=h.left&&f<=h.right&&l>=h.top&&l<=h.bottom;K(g)&&(f=Math.max(0,Math.min(h.right,k.right)-Math.max(h.left,k.left))*Math.max(0,Math.min(h.bottom,k.bottom)-Math.max(h.top,k.top))/(k.width*k.height)>=g);this.options.drop.checker&&(f=this.options.drop.checker(a,b,f,this,e,c,d));return f},dropChecker:function(a){return A(a)?(this.options.drop.checker=a,this):
null===a?(delete this.options.getRect,this):this.options.drop.checker},accept:function(a){return t(a)||ea(a)?(this.options.drop.accept=a,this):null===a?(delete this.options.drop.accept,this):this.options.drop.accept},resizable:function(a){return z(a)?(this.options.resize.enabled=!1===a.enabled?!1:!0,this.setPerAction("resize",a),this.setOnEvents("resize",a),/^x$|^y$|^xy$/.test(a.axis)?this.options.resize.axis=a.axis:null===a.axis&&(this.options.resize.axis=D.resize.axis),H(a.preserveAspectRatio)?
this.options.resize.preserveAspectRatio=a.preserveAspectRatio:H(a.square)&&(this.options.resize.square=a.square),this):H(a)?(this.options.resize.enabled=a,this):this.options.resize},squareResize:function(a){return H(a)?(this.options.resize.square=a,this):null===a?(delete this.options.resize.square,this):this.options.resize.square},gesturable:function(a){return z(a)?(this.options.gesture.enabled=!1===a.enabled?!1:!0,this.setPerAction("gesture",a),this.setOnEvents("gesture",a),this):H(a)?(this.options.gesture.enabled=
a,this):this.options.gesture},autoScroll:function(a){z(a)?a=x({actions:["drag","resize"]},a):H(a)&&(a={actions:["drag","resize"],enabled:a});return this.setOptions("autoScroll",a)},snap:function(a){a=this.setOptions("snap",a);return a===this?this:a.drag},setOptions:function(a,b){var c=b&&da(b.actions)?b.actions:["drag"],d;if(z(b)||H(b)){for(d=0;d<c.length;d++){var e=/resize/.test(c[d])?"resize":c[d];z(this.options[e])&&(e=this.options[e][a],z(b)?(x(e,b),e.enabled=!1===b.enabled?!1:!0,"snap"===a&&
("grid"===e.mode?e.targets=[l.createSnapGrid(x({offset:e.gridOffset||{x:0,y:0}},e.grid||{}))]:"anchor"===e.mode?e.targets=e.anchors:"path"===e.mode&&(e.targets=e.paths),"elementOrigin"in b&&(e.relativePoints=[b.elementOrigin]))):H(b)&&(e.enabled=b))}return this}c={};e=["drag","resize","gesture"];for(d=0;d<e.length;d++)a in D[e[d]]&&(c[e[d]]=this.options[e[d]][a]);return c},inertia:function(a){a=this.setOptions("inertia",a);return a===this?this:a.drag},getAction:function(a,b,c,d){var e=this.defaultActionChecker(a,
c,d);return this.options.actionChecker?this.options.actionChecker(a,b,e,this,d,c):e},defaultActionChecker:hb,actionChecker:function(a){return A(a)?(this.options.actionChecker=a,this):null===a?(delete this.options.actionChecker,this):this.options.actionChecker},getRect:function(a){a=a||this._element;this.selector&&!t(a)&&(a=this._context.querySelector(this.selector));return ua(a)},rectChecker:function(a){return A(a)?(this.getRect=a,this):null===a?(delete this.options.getRect,this):this.getRect},styleCursor:function(a){return H(a)?
(this.options.styleCursor=a,this):null===a?(delete this.options.styleCursor,this):this.options.styleCursor},preventDefault:function(a){return/^(always|never|auto)$/.test(a)?(this.options.preventDefault=a,this):H(a)?(this.options.preventDefault=a?"always":"never",this):this.options.preventDefault},origin:function(a){return ea(a)||z(a)?(this.options.origin=a,this):this.options.origin},deltaSource:function(a){return"page"===a||"client"===a?(this.options.deltaSource=a,this):this.options.deltaSource},
restrict:function(a){if(!z(a))return this.setOptions("restrict",a);for(var b=["drag","resize","gesture"],c,d=0;d<b.length;d++){var e=b[d];e in a&&(c=x({actions:[e],restriction:a[e]},a),c=this.setOptions("restrict",c))}return c},context:function(){return this._context},_context:Q,ignoreFrom:function(a){return ea(a)||t(a)?(this.options.ignoreFrom=a,this):this.options.ignoreFrom},allowFrom:function(a){return ea(a)||t(a)?(this.options.allowFrom=a,this):this.options.allowFrom},element:function(){return this._element},
fire:function(a){if(!a||!a.type||-1===v(ca,a.type))return this;var b,c,d,e="on"+a.type;if(a.type in this._iEvents)for(b=this._iEvents[a.type],c=0,d=b.length;c<d&&!a.immediatePropagationStopped;c++)b[c](a);if(A(this[e]))this[e](a);if(a.type in U&&(b=U[a.type]))for(c=0,d=b.length;c<d&&!a.immediatePropagationStopped;c++)b[c](a);return this},on:function(a,b,c){var d;N(a)&&-1!==a.search(" ")&&(a=a.trim().split(/ +/));if(da(a)){for(d=0;d<a.length;d++)this.on(a[d],b,c);return this}if(z(a)){for(d in a)this.on(d,
a[d],b);return this}"wheel"===a&&(a=kb);c=c?!0:!1;if(-1!==v(ca,a))a in this._iEvents?this._iEvents[a].push(b):this._iEvents[a]=[b];else if(this.selector){if(!P[a])for(P[a]={selectors:[],contexts:[],listeners:[]},d=0;d<ja.length;d++)n.add(ja[d],a,qa),n.add(ja[d],a,Aa,!0);a=P[a];for(d=a.selectors.length-1;0<=d&&(a.selectors[d]!==this.selector||a.contexts[d]!==this._context);d--);-1===d&&(d=a.selectors.length,a.selectors.push(this.selector),a.contexts.push(this._context),a.listeners.push([]));a.listeners[d].push([b,
c])}else n.add(this._element,a,b,c);return this},off:function(a,b,c){var d;N(a)&&-1!==a.search(" ")&&(a=a.trim().split(/ +/));if(da(a)){for(d=0;d<a.length;d++)this.off(a[d],b,c);return this}if(z(a)){for(var e in a)this.off(e,a[e],b);return this}e=-1;c=c?!0:!1;"wheel"===a&&(a=kb);if(-1!==v(ca,a))(c=this._iEvents[a])&&-1!==(e=v(c,b))&&this._iEvents[a].splice(e,1);else if(this.selector){var h=P[a],f=!1;if(!h)return this;for(e=h.selectors.length-1;0<=e;e--)if(h.selectors[e]===this.selector&&h.contexts[e]===
this._context){var g=h.listeners[e];for(d=g.length-1;0<=d;d--){var k=g[d][1];if(g[d][0]===b&&k===c){g.splice(d,1);g.length||(h.selectors.splice(e,1),h.contexts.splice(e,1),h.listeners.splice(e,1),n.remove(this._context,a,qa),n.remove(this._context,a,Aa,!0),h.selectors.length||(P[a]=null));f=!0;break}}if(f)break}}else n.remove(this._element,a,b,c);return this},set:function(a){z(a)||(a={});this.options=x({},D.base);var b,c=["drag","drop","resize","gesture"],d=["draggable","dropzone","resizable","gesturable"],
e=x(x({},D.perAction),a[h]||{});for(b=0;b<c.length;b++){var h=c[b];this.options[h]=x({},D[h]);this.setPerAction(h,e);this[d[b]](a[h])}c="accept actionChecker allowFrom deltaSource dropChecker ignoreFrom origin preventDefault rectChecker styleCursor".split(" ");b=0;for(Sa=c.length;b<Sa;b++)if(d=c[b],this.options[d]=D.base[d],d in a)this[d](a[d]);return this},unset:function(){n.remove(this._element,"all");if(N(this.selector))for(var a in P)for(var b=P[a];0<b.selectors.length;){b.selectors[0]===this.selector&&
b.contexts[0]===this._context&&(b.selectors.splice(0,1),b.contexts.splice(0,1),b.listeners.splice(0,1),b.selectors.length||(P[a]=null));n.remove(this._context,a,qa);n.remove(this._context,a,Aa,!0);break}else n.remove(this,"all"),this.options.styleCursor&&(this._element.style.cursor="");this.dropzone(!1);B.splice(v(B,this),1);return l}};C.prototype.snap=M(C.prototype.snap,"Interactable#snap is deprecated. See the new documentation for snapping at http://interactjs.io/docs/snapping");C.prototype.restrict=
M(C.prototype.restrict,"Interactable#restrict is deprecated. See the new documentation for resticting at http://interactjs.io/docs/restriction");C.prototype.inertia=M(C.prototype.inertia,"Interactable#inertia is deprecated. See the new documentation for inertia at http://interactjs.io/docs/inertia");C.prototype.autoScroll=M(C.prototype.autoScroll,"Interactable#autoScroll is deprecated. See the new documentation for autoScroll at http://interactjs.io/docs/#autoscroll");C.prototype.squareResize=M(C.prototype.squareResize,
"Interactable#squareResize is deprecated. See http://interactjs.io/docs/#resize-square");C.prototype.accept=M(C.prototype.accept,"Interactable#accept is deprecated. use Interactable#dropzone({ accept: target }) instead");C.prototype.dropChecker=M(C.prototype.dropChecker,"Interactable#dropChecker is deprecated. use Interactable#dropzone({ dropChecker: checkerFunction }) instead");C.prototype.context=M(C.prototype.context,"Interactable#context as a method is deprecated. It will soon be a DOM Node instead");
l.isSet=function(a,b){return-1!==B.indexOfElement(a,b&&b.context)};l.on=function(a,b,c){N(a)&&-1!==a.search(" ")&&(a=a.trim().split(/ +/));if(da(a)){for(var d=0;d<a.length;d++)l.on(a[d],b,c);return l}if(z(a)){for(d in a)l.on(d,a[d],b);return l}-1!==v(ca,a)?U[a]?U[a].push(b):U[a]=[b]:n.add(Q,a,b,c);return l};l.off=function(a,b,c){N(a)&&-1!==a.search(" ")&&(a=a.trim().split(/ +/));if(da(a)){for(var d=0;d<a.length;d++)l.off(a[d],b,c);return l}if(z(a)){for(d in a)l.off(d,a[d],b);return l}if(-1===v(ca,
a))n.remove(Q,a,b,c);else{var e;a in U&&-1!==(e=v(U[a],b))&&U[a].splice(e,1)}return l};l.enableDragging=M(function(a){return null!==a&&void 0!==a?(S.drag=a,l):S.drag},"interact.enableDragging is deprecated and will soon be removed.");l.enableResizing=M(function(a){return null!==a&&void 0!==a?(S.resize=a,l):S.resize},"interact.enableResizing is deprecated and will soon be removed.");l.enableGesturing=M(function(a){return null!==a&&void 0!==a?(S.gesture=a,l):S.gesture},"interact.enableGesturing is deprecated and will soon be removed.");
l.eventTypes=ca;l.debug=function(){var a=r[0]||new xa;return{interactions:r,target:a.target,dragging:a.dragging,resizing:a.resizing,gesturing:a.gesturing,prepared:a.prepared,matches:a.matches,matchElements:a.matchElements,prevCoords:a.prevCoords,startCoords:a.startCoords,pointerIds:a.pointerIds,pointers:a.pointers,addPointer:m.addPointer,removePointer:m.removePointer,recordPointer:m.recordPointer,snap:a.snapStatus,restrict:a.restrictStatus,inertia:a.inertiaStatus,downTime:a.downTimes[0],downEvent:a.downEvent,
downPointer:a.downPointer,prevEvent:a.prevEvent,Interactable:C,interactables:B,pointerIsDown:a.pointerIsDown,defaultOptions:D,defaultActionChecker:hb,actionCursors:za,dragMove:m.dragMove,resizeMove:m.resizeMove,gestureMove:m.gestureMove,pointerUp:m.pointerUp,pointerDown:m.pointerDown,pointerMove:m.pointerMove,pointerHover:m.pointerHover,eventTypes:ca,events:n,globalEvents:U,delegatedEvents:P,prefixedPropREs:Ca}};l.getPointerAverage=Ya;l.getTouchBBox=Ha;l.getTouchDistance=Ia;l.getTouchAngle=Ja;l.getElementRect=
ua;l.getElementClientRect=Fa;l.matchesSelector=R;l.closest=Ka;l.margin=M(function(a){return K(a)?(pa=a,l):pa},"interact.margin is deprecated. Use interact(target).resizable({ margin: number }); instead.");l.supportsTouch=function(){return ga};l.supportsPointerEvent=function(){return oa};l.stop=function(a){for(var b=r.length-1;0<=b;b--)r[b].stop(a);return l};l.dynamicDrop=function(a){return H(a)?(Pa=a,l):Pa};l.pointerMoveTolerance=function(a){return K(a)?(Qa=a,this):Qa};l.maxInteractions=function(a){return K(a)?
(wa=a,this):wa};l.createSnapGrid=function(a){return function(b,c){var d=0,e=0;z(a.offset)&&(d=a.offset.x,e=a.offset.y);return{x:Math.round((b-d)/a.x)*a.x+d,y:Math.round((c-e)/a.y)*a.y+e,range:a.range}}};ib(Q);Oa in Element.prototype&&A(Element.prototype[Oa])||(ka=function(a,b,c){c=c||a.parentNode.querySelectorAll(b);b=0;for(var d=c.length;b<d;b++)if(c[b]===a)return!0;return!1});(function(){for(var a=0,b=["ms","moz","webkit","o"],c=0;c<b.length&&!F.requestAnimationFrame;++c)T=F[b[c]+"RequestAnimationFrame"],
X=F[b[c]+"CancelAnimationFrame"]||F[b[c]+"CancelRequestAnimationFrame"];T||(T=function(b){var c=(new Date).getTime(),h=Math.max(0,16-(c-a)),f=setTimeout(function(){b(c+h)},h);a=c+h;return f});X||(X=function(a){clearTimeout(a)})})();"undefined"!==typeof exports?("undefined"!==typeof module&&module.exports&&(exports=module.exports=l),exports.interact=l):"function"===typeof define&&define.amd?define("interact",function(){return l}):F.interact=l}})("undefined"===typeof window?void 0:window);
//# sourceMappingURL=interact.min.js.map
+395
View File
@@ -0,0 +1,395 @@
(function(doc) {
log = noop; // noOp, remove this line to enable debugging
var coordinateSystemForElementFromPoint;
function main(config) {
config = config || {};
coordinateSystemForElementFromPoint = navigator.userAgent.match(/OS [1-4](?:_\d+)+ like Mac/) ? "page" : "client";
var div = doc.createElement('div');
var dragDiv = 'draggable' in div;
var evts = 'ondragstart' in div && 'ondrop' in div;
var needsPatch = !(dragDiv || evts) || /iPad|iPhone|iPod|Android/.test(navigator.userAgent);
log((needsPatch ? "" : "not ") + "patching html5 drag drop");
if(!needsPatch) {
return;
}
if(!config.enableEnterLeave) {
DragDrop.prototype.synthesizeEnterLeave = noop;
}
doc.addEventListener("touchstart", touchstart);
}
function DragDrop(event, el) {
this.dragData = {};
this.dragDataTypes = [];
this.dragImage = null;
this.dragImageTransform = null;
this.dragImageWebKitTransform = null;
this.customDragImage = null;
this.customDragImageX = null;
this.customDragImageY = null;
this.el = el || event.target;
log("dragstart");
if (this.dispatchDragStart()) {
this.createDragImage();
this.listen();
}
}
DragDrop.prototype = {
listen: function() {
var move = onEvt(doc, "touchmove", this.move, this);
var end = onEvt(doc, "touchend", ontouchend, this);
var cancel = onEvt(doc, "touchcancel", cleanup, this);
function ontouchend(event) {
this.dragend(event, event.target);
cleanup.call(this);
}
function cleanup() {
log("cleanup");
this.dragDataTypes = [];
if (this.dragImage !== null) {
this.dragImage.parentNode.removeChild(this.dragImage);
this.dragImage = null;
this.dragImageTransform = null;
this.dragImageWebKitTransform = null;
}
this.customDragImage = null;
this.customDragImageX = null;
this.customDragImageY = null;
this.el = this.dragData = null;
return [move, end, cancel].forEach(function(handler) {
return handler.off();
});
}
},
move: function(event) {
var pageXs = [], pageYs = [];
[].forEach.call(event.changedTouches, function(touch) {
pageXs.push(touch.pageX);
pageYs.push(touch.pageY);
});
var x = average(pageXs) - (this.customDragImageX || parseInt(this.dragImage.offsetWidth, 10) / 2);
var y = average(pageYs) - (this.customDragImageY || parseInt(this.dragImage.offsetHeight, 10) / 2);
this.translateDragImage(x, y);
this.synthesizeEnterLeave(event);
},
// We use translate instead of top/left because of sub-pixel rendering and for the hope of better performance
// http://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/
translateDragImage: function(x, y) {
var translate = "translate(" + x + "px," + y + "px) ";
if (this.dragImageWebKitTransform !== null) {
this.dragImage.style["-webkit-transform"] = translate + this.dragImageWebKitTransform;
}
if (this.dragImageTransform !== null) {
this.dragImage.style.transform = translate + this.dragImageTransform;
}
},
synthesizeEnterLeave: function(event) {
var target = elementFromTouchEvent(this.el,event)
if (target != this.lastEnter) {
if (this.lastEnter) {
this.dispatchLeave(event);
}
this.lastEnter = target;
if (this.lastEnter) {
this.dispatchEnter(event);
}
}
if (this.lastEnter) {
this.dispatchOver(event);
}
},
dragend: function(event) {
// we'll dispatch drop if there's a target, then dragEnd.
// drop comes first http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#drag-and-drop-processing-model
log("dragend");
if (this.lastEnter) {
this.dispatchLeave(event);
}
var target = elementFromTouchEvent(this.el,event)
if (target) {
log("found drop target " + target.tagName);
this.dispatchDrop(target, event);
} else {
log("no drop target");
}
var dragendEvt = doc.createEvent("Event");
dragendEvt.initEvent("dragend", true, true);
this.el.dispatchEvent(dragendEvt);
},
dispatchDrop: function(target, event) {
var dropEvt = doc.createEvent("Event");
dropEvt.initEvent("drop", true, true);
var touch = event.changedTouches[0];
var x = touch[coordinateSystemForElementFromPoint + 'X'];
var y = touch[coordinateSystemForElementFromPoint + 'Y'];
var targetOffset = getOffset(target);
dropEvt.offsetX = x - targetOffset.x;
dropEvt.offsetY = y - targetOffset.y;
dropEvt.dataTransfer = {
types: this.dragDataTypes,
getData: function(type) {
return this.dragData[type];
}.bind(this),
dropEffect: "move"
};
dropEvt.preventDefault = function() {
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=14638 - if we don't cancel it, we'll snap back
}.bind(this);
once(doc, "drop", function() {
log("drop event not canceled");
},this);
target.dispatchEvent(dropEvt);
},
dispatchEnter: function(event) {
var enterEvt = doc.createEvent("Event");
enterEvt.initEvent("dragenter", true, true);
enterEvt.dataTransfer = {
types: this.dragDataTypes,
getData: function(type) {
return this.dragData[type];
}.bind(this)
};
var touch = event.changedTouches[0];
enterEvt.pageX = touch.pageX;
enterEvt.pageY = touch.pageY;
enterEvt.clientX = touch.clientX;
enterEvt.clientY = touch.clientY;
this.lastEnter.dispatchEvent(enterEvt);
},
dispatchOver: function(event) {
var overEvt = doc.createEvent("Event");
overEvt.initEvent("dragover", true, true);
overEvt.dataTransfer = {
types: this.dragDataTypes,
getData: function(type) {
return this.dragData[type];
}.bind(this)
};
var touch = event.changedTouches[0];
overEvt.pageX = touch.pageX;
overEvt.pageY = touch.pageY;
overEvt.clientX = touch.clientX;
overEvt.clientY = touch.clientY;
this.lastEnter.dispatchEvent(overEvt);
},
dispatchLeave: function(event) {
var leaveEvt = doc.createEvent("Event");
leaveEvt.initEvent("dragleave", true, true);
leaveEvt.dataTransfer = {
types: this.dragDataTypes,
getData: function(type) {
return this.dragData[type];
}.bind(this)
};
var touch = event.changedTouches[0];
leaveEvt.pageX = touch.pageX;
leaveEvt.pageY = touch.pageY;
leaveEvt.clientX = touch.clientX;
leaveEvt.clientY = touch.clientY;
this.lastEnter.dispatchEvent(leaveEvt);
this.lastEnter = null;
},
dispatchDragStart: function() {
var evt = doc.createEvent("Event");
evt.initEvent("dragstart", true, true);
evt.dataTransfer = {
setData: function(type, val) {
this.dragData[type] = val;
if (this.dragDataTypes.indexOf(type) == -1) {
this.dragDataTypes[this.dragDataTypes.length] = type;
}
return val;
}.bind(this),
setDragImage: function(el, x, y){
this.customDragImage = el;
this.customDragImageX = x
this.customDragImageY = y
}.bind(this),
dropEffect: "move"
};
return this.el.dispatchEvent(evt);
},
createDragImage: function() {
if (this.customDragImage) {
this.dragImage = this.customDragImage.cloneNode(true);
duplicateStyle(this.customDragImage, this.dragImage);
} else {
this.dragImage = this.el.cloneNode(true);
duplicateStyle(this.el, this.dragImage);
}
this.dragImage.style.opacity = "0.5";
this.dragImage.style.position = "absolute";
this.dragImage.style.left = "0px";
this.dragImage.style.top = "0px";
this.dragImage.style.zIndex = "999999";
var transform = this.dragImage.style.transform;
if (typeof transform !== "undefined") {
this.dragImageTransform = "";
if (transform != "none") {
this.dragImageTransform = transform.replace(/translate\(\D*\d+[^,]*,\D*\d+[^,]*\)\s*/g, '');
}
}
var webkitTransform = this.dragImage.style["-webkit-transform"];
if (typeof webkitTransform !== "undefined") {
this.dragImageWebKitTransform = "";
if (webkitTransform != "none") {
this.dragImageWebKitTransform = webkitTransform.replace(/translate\(\D*\d+[^,]*,\D*\d+[^,]*\)\s*/g, '');
}
}
this.translateDragImage(-9999, -9999);
doc.body.appendChild(this.dragImage);
}
};
// event listeners
function touchstart(evt) {
var el = evt.target;
do {
if (el.draggable === true) {
// If draggable isn't explicitly set for anchors, then simulate a click event.
// Otherwise plain old vanilla links will stop working.
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Touch_events#Handling_clicks
if (!el.hasAttribute("draggable") && el.tagName.toLowerCase() == "a") {
var clickEvt = document.createEvent("MouseEvents");
clickEvt.initMouseEvent("click", true, true, el.ownerDocument.defaultView, 1,
evt.screenX, evt.screenY, evt.clientX, evt.clientY,
evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null);
el.dispatchEvent(clickEvt);
log("Simulating click to anchor");
}
evt.preventDefault();
new DragDrop(evt,el);
break;
}
} while((el = el.parentNode) && el !== doc.body);
}
// DOM helpers
function elementFromTouchEvent(el,event) {
var touch = event.changedTouches[0];
var target = doc.elementFromPoint(
touch[coordinateSystemForElementFromPoint + "X"],
touch[coordinateSystemForElementFromPoint + "Y"]
);
return target;
}
//calculate the offset position of an element (relative to the window, not the document)
function getOffset(el) {
var rect = el.getBoundingClientRect();
return {
"x": rect.left,
"y": rect.top
};
}
function onEvt(el, event, handler, context) {
if(context) {
handler = handler.bind(context);
}
el.addEventListener(event, handler);
return {
off: function() {
return el.removeEventListener(event, handler);
}
};
}
function once(el, event, handler, context) {
if(context) {
handler = handler.bind(context);
}
function listener(evt) {
handler(evt);
return el.removeEventListener(event,listener);
}
return el.addEventListener(event,listener);
}
// duplicateStyle expects dstNode to be a clone of srcNode
function duplicateStyle(srcNode, dstNode) {
// Is this node an element?
if (srcNode.nodeType == 1) {
// Remove any potential conflict attributes
dstNode.removeAttribute("id");
dstNode.removeAttribute("class");
dstNode.removeAttribute("style");
dstNode.removeAttribute("draggable");
// Clone the style
var cs = window.getComputedStyle(srcNode);
for (var i = 0; i < cs.length; i++) {
var csName = cs[i];
dstNode.style.setProperty(csName, cs.getPropertyValue(csName), cs.getPropertyPriority(csName));
}
// Pointer events as none makes the drag image transparent to document.elementFromPoint()
dstNode.style.pointerEvents = "none";
}
// Do the same for the children
if (srcNode.hasChildNodes()) {
for (var j = 0; j < srcNode.childNodes.length; j++) {
duplicateStyle(srcNode.childNodes[j], dstNode.childNodes[j]);
}
}
}
// general helpers
function log(msg) {
console.log(msg);
}
function average(arr) {
if (arr.length === 0) return 0;
return arr.reduce((function(s, v) {
return v + s;
}), 0) / arr.length;
}
function noop() {}
main(window.iosDragDropShim);
})(document);
+4
View File
File diff suppressed because one or more lines are too long
+4
View File
File diff suppressed because one or more lines are too long
+4
View File
File diff suppressed because one or more lines are too long
+4
View File
File diff suppressed because one or more lines are too long
+151
View File
@@ -0,0 +1,151 @@
var up_pressed=0,down_pressed=0,left_pressed=0,right_pressed=0,z_pressed=0,x_pressed=0,y_pressed=0,cmd_pressed=0,c_pressed=0,f_pressed=0,n_pressed=0,v_pressed=0,l_pressed=0,t_pressed=0,a_pressed=0,b_pressed=0;
// Copy-paste to the "blur" event below
var pressed={};
var last_press=1,total_mousemoves=0,last_cmd=new Date();
var K={
48:"0",
49:"1",
50:"2",
51:"3",
52:"4",
53:"5",
54:"6",
55:"7",
56:"8",
57:"9",
65:"A",
66:"B",
67:"C",
68:"D",
69:"E",
70:"F",
71:"G",
72:"H",
73:"I",
74:"J",
75:"K",
76:"L",
77:"M",
78:"N",
79:"O",
80:"P",
81:"Q",
82:"R",
83:"S",
84:"T",
85:"U",
86:"V",
87:"W",
88:"X",
89:"Y",
90:"Z",
37:"LEFT",
38:"UP",
39:"RIGHT",
40:"DOWN",
9:"TAB",
27:"ESC",
16:"SHIFT",
32:"SPACE",
13:"ENTER",
8:"BACK",
188:",",
189:"-",
220:"\\",
9000:"\\2",
};
function keyboard_logic()
{
if(window.no_html) return;
window.addEventListener(
"keydown", function(event){
// console.log("KEYPRESS "+event.keyCode+" STATE: "+pressed[event.keyCode]);
var state=pressed[event.keyCode];
pressed[event.keyCode]=last_press++;
last_interaction=new Date();
if($('input:focus').length>0 || $('textarea:focus').length>0 || event.target && event.target.hasAttribute("contenteditable"))
{
if(!(event.keyCode==27 && window.character)) return; // not ESC
}
if(event.keyCode==37 || window.map_editor && event.keyCode==65) { left_pressed=last_press++; }
if(event.keyCode==38 || window.map_editor && event.keyCode==87) { up_pressed=last_press++; }
if(event.keyCode==39 || window.map_editor && event.keyCode==68) { right_pressed=last_press++; }
if(event.keyCode==40 || window.map_editor && event.keyCode==83) { down_pressed=last_press++; }
if(event.keyCode==90) { z_pressed=last_press++; }
if(event.keyCode==89) { y_pressed=last_press++; }
if(event.keyCode==88) { x_pressed=last_press++; }
if(event.keyCode==67) { c_pressed=last_press++; }
if(event.keyCode==78) { n_pressed=last_press++; }
if(event.keyCode==86) { v_pressed=last_press++; }
if(event.keyCode==70) { f_pressed=last_press++; }
if(event.keyCode==76) { l_pressed=last_press++; }
if(event.keyCode==84) { t_pressed=last_press++; }
if(event.keyCode==65) { a_pressed=last_press++; }
if(event.keyCode==66) { b_pressed=last_press++; }
if(event.keyCode==91 || event.keyCode==17) cmd_pressed=true,last_cmd=new Date(); // 17 ctrl - 91 cmd [22/06/18]
if(window.character && !state && (!cmd_pressed || ssince(last_cmd)>5))
{
if(event.keyCode==65 && window.socket) socket.emit("interaction",{key:"A"});
if(event.keyCode==66 && window.socket) socket.emit("interaction",{key:"B"});
if(K[event.keyCode]) on_skill(K[event.keyCode],event);
}
if(event.keyCode==27 && window.map_editor && set) destroy_tileset();
if(event.keyCode==27 && window.inside=="selection") $(".onbackbutton").click();
// turns out event.preventDefault helps all kinds of things [OLD]
if(window.stkp) if(!cmd_pressed || window.ssince && ssince(last_cmd)>5) stkp(event); // NEW [21/06/18]
}, false
);
window.addEventListener(
"keyup", function(event){
//console.log("KEYUP "+event.keyCode);
pressed[event.keyCode]=0;
if(event.target && event.target.hasAttribute("contenteditable") && !$(event.target).html()) $(event.target).html(" ");
if($('input:focus').length>0 || $('textarea:focus').length>0 || event.target && event.target.hasAttribute("contenteditable")) return;
if(event.keyCode==37 || window.map_editor && event.keyCode==65) { left_pressed=0; }
if(event.keyCode==38 || window.map_editor && event.keyCode==87) { up_pressed=0; }
if(event.keyCode==39 || window.map_editor && event.keyCode==68) { right_pressed=0; }
if(event.keyCode==40 || window.map_editor && event.keyCode==83) { down_pressed=0; }
if(event.keyCode==90) { z_pressed=0; }
if(event.keyCode==89) { y_pressed=0; }
if(event.keyCode==88) { x_pressed=0; }
if(event.keyCode==67) { c_pressed=0; }
if(event.keyCode==78) { n_pressed=0; }
if(event.keyCode==86) { v_pressed=0; }
if(event.keyCode==70) { f_pressed=0; }
if(event.keyCode==76) { l_pressed=0; }
if(event.keyCode==84) { t_pressed=0; }
if(event.keyCode==65) { a_pressed=0; }
if(event.keyCode==66) { b_pressed=0; }
if(event.keyCode==91 || event.keyCode==17) cmd_pressed=false;
if(window.character && K[event.keyCode]) on_skill_up(K[event.keyCode]);
if(!cmd_pressed && window.stkp) stkp(event);
}, false
);
window.addEventListener(
"mousemove", function(event){
if(mm_afk) last_interaction=new Date();
if(window.options && options.move_with_mouse && character)
{
var x=event.pageX,y=event.pageY;
dx=x-width/2; dy=y-height/2;
if(manual_centering && character) dx=x-character.x,dy=y-character.y;
dx/=scale; dy/=scale;
var mx=character.real_x+dx,my=character.real_y+dy;
var cm=calculate_move(character,mx,my);
if(!character.moving || point_distance(character.real_x,character.real_y,cm.x,cm.y)>4 && mssince(last_move)>120) move(cm.x,cm.y);
}
//total_mousemoves++;
}, false
);
$(window).blur(function(){
// cmd_pressed logic can be removed now [20/07/18]
up_pressed=0,down_pressed=0,left_pressed=0,right_pressed=0,z_pressed=0,x_pressed=0,y_pressed=0,cmd_pressed=0,c_pressed=0,f_pressed=0,n_pressed=0,v_pressed=0,l_pressed=0,t_pressed=0,a_pressed=0,b_pressed=0;
for(var name in K) if(pressed[name]) on_skill_up(K[event.keyCode]);
});
$(window).focus(function(){
if(window.sounds && window.sounds.empty && sounds.empty.cplaying) sounds.empty.stop(),sounds.empty.play();
});
}
BIN
View File
Binary file not shown.
+559
View File
@@ -0,0 +1,559 @@
/*!
* Bowser - a browser detector
* https://github.com/ded/bowser
* MIT License | (c) Dustin Diaz 2015
*/
!function (name, definition) {
if (typeof module != 'undefined' && module.exports) module.exports = definition()
else if (typeof define == 'function' && define.amd) define(name, definition)
else this[name] = definition()
}('bowser', function () {
/**
* See useragents.js for examples of navigator.userAgent
*/
var t = true
function detect(ua) {
function getFirstMatch(regex) {
var match = ua.match(regex);
return (match && match.length > 1 && match[1]) || '';
}
function getSecondMatch(regex) {
var match = ua.match(regex);
return (match && match.length > 1 && match[2]) || '';
}
var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase()
, likeAndroid = /like android/i.test(ua)
, android = !likeAndroid && /android/i.test(ua)
, nexusMobile = /nexus\s*[0-6]\s*/i.test(ua)
, nexusTablet = !nexusMobile && /nexus\s*[0-9]+/i.test(ua)
, chromeos = /CrOS/.test(ua)
, silk = /silk/i.test(ua)
, sailfish = /sailfish/i.test(ua)
, tizen = /tizen/i.test(ua)
, webos = /(web|hpw)os/i.test(ua)
, windowsphone = /windows phone/i.test(ua)
, windows = !windowsphone && /windows/i.test(ua)
, mac = !iosdevice && !silk && /macintosh/i.test(ua)
, linux = !android && !sailfish && !tizen && !webos && /linux/i.test(ua)
, edgeVersion = getFirstMatch(/edge\/(\d+(\.\d+)?)/i)
, versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i)
, tablet = /tablet/i.test(ua)
, mobile = !tablet && /[^-]mobi/i.test(ua)
, xbox = /xbox/i.test(ua)
, result
if (/opera|opr|opios/i.test(ua)) {
result = {
name: 'Opera'
, opera: t
, version: versionIdentifier || getFirstMatch(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i)
}
}
else if (/coast/i.test(ua)) {
result = {
name: 'Opera Coast'
, coast: t
, version: versionIdentifier || getFirstMatch(/(?:coast)[\s\/](\d+(\.\d+)?)/i)
}
}
else if (/yabrowser/i.test(ua)) {
result = {
name: 'Yandex Browser'
, yandexbrowser: t
, version: versionIdentifier || getFirstMatch(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)
}
}
else if (/ucbrowser/i.test(ua)) {
result = {
name: 'UC Browser'
, ucbrowser: t
, version: getFirstMatch(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/mxios/i.test(ua)) {
result = {
name: 'Maxthon'
, maxthon: t
, version: getFirstMatch(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/epiphany/i.test(ua)) {
result = {
name: 'Epiphany'
, epiphany: t
, version: getFirstMatch(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/puffin/i.test(ua)) {
result = {
name: 'Puffin'
, puffin: t
, version: getFirstMatch(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i)
}
}
else if (/sleipnir/i.test(ua)) {
result = {
name: 'Sleipnir'
, sleipnir: t
, version: getFirstMatch(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/k-meleon/i.test(ua)) {
result = {
name: 'K-Meleon'
, kMeleon: t
, version: getFirstMatch(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (windowsphone) {
result = {
name: 'Windows Phone'
, windowsphone: t
}
if (edgeVersion) {
result.msedge = t
result.version = edgeVersion
}
else {
result.msie = t
result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i)
}
}
else if (/msie|trident/i.test(ua)) {
result = {
name: 'Internet Explorer'
, msie: t
, version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i)
}
} else if (chromeos) {
result = {
name: 'Chrome'
, chromeos: t
, chromeBook: t
, chrome: t
, version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)
}
} else if (/chrome.+? edge/i.test(ua)) {
result = {
name: 'Microsoft Edge'
, msedge: t
, version: edgeVersion
}
}
else if (/vivaldi/i.test(ua)) {
result = {
name: 'Vivaldi'
, vivaldi: t
, version: getFirstMatch(/vivaldi\/(\d+(\.\d+)?)/i) || versionIdentifier
}
}
else if (sailfish) {
result = {
name: 'Sailfish'
, sailfish: t
, version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i)
}
}
else if (/seamonkey\//i.test(ua)) {
result = {
name: 'SeaMonkey'
, seamonkey: t
, version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i)
}
}
else if (/firefox|iceweasel|fxios/i.test(ua)) {
result = {
name: 'Firefox'
, firefox: t
, version: getFirstMatch(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i)
}
if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) {
result.firefoxos = t
}
}
else if (silk) {
result = {
name: 'Amazon Silk'
, silk: t
, version : getFirstMatch(/silk\/(\d+(\.\d+)?)/i)
}
}
else if (/phantom/i.test(ua)) {
result = {
name: 'PhantomJS'
, phantom: t
, version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i)
}
}
else if (/slimerjs/i.test(ua)) {
result = {
name: 'SlimerJS'
, slimer: t
, version: getFirstMatch(/slimerjs\/(\d+(\.\d+)?)/i)
}
}
else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) {
result = {
name: 'BlackBerry'
, blackberry: t
, version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i)
}
}
else if (webos) {
result = {
name: 'WebOS'
, webos: t
, version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)
};
/touchpad\//i.test(ua) && (result.touchpad = t)
}
else if (/bada/i.test(ua)) {
result = {
name: 'Bada'
, bada: t
, version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i)
};
}
else if (tizen) {
result = {
name: 'Tizen'
, tizen: t
, version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier
};
}
else if (/qupzilla/i.test(ua)) {
result = {
name: 'QupZilla'
, qupzilla: t
, version: getFirstMatch(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i) || versionIdentifier
}
}
else if (/chromium/i.test(ua)) {
result = {
name: 'Chromium'
, chromium: t
, version: getFirstMatch(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i) || versionIdentifier
}
}
else if (/chrome|crios|crmo/i.test(ua)) {
result = {
name: 'Chrome'
, chrome: t
, version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)
}
}
else if (android) {
result = {
name: 'Android'
, version: versionIdentifier
}
}
else if (/safari|applewebkit/i.test(ua)) {
result = {
name: 'Safari'
, safari: t
}
if (versionIdentifier) {
result.version = versionIdentifier
}
}
else if (iosdevice) {
result = {
name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod'
}
// WTF: version is not part of user agent in web apps
if (versionIdentifier) {
result.version = versionIdentifier
}
}
else if(/googlebot/i.test(ua)) {
result = {
name: 'Googlebot'
, googlebot: t
, version: getFirstMatch(/googlebot\/(\d+(\.\d+))/i) || versionIdentifier
}
}
else {
result = {
name: getFirstMatch(/^(.*)\/(.*) /),
version: getSecondMatch(/^(.*)\/(.*) /)
};
}
// set webkit or gecko flag for browsers based on these engines
if (!result.msedge && /(apple)?webkit/i.test(ua)) {
if (/(apple)?webkit\/537\.36/i.test(ua)) {
result.name = result.name || "Blink"
result.blink = t
} else {
result.name = result.name || "Webkit"
result.webkit = t
}
if (!result.version && versionIdentifier) {
result.version = versionIdentifier
}
} else if (!result.opera && /gecko\//i.test(ua)) {
result.name = result.name || "Gecko"
result.gecko = t
result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i)
}
// set OS flags for platforms that have multiple browsers
if (!result.msedge && (android || result.silk)) {
result.android = t
} else if (iosdevice) {
result[iosdevice] = t
result.ios = t
} else if (mac) {
result.mac = t
} else if (xbox) {
result.xbox = t
} else if (windows) {
result.windows = t
} else if (linux) {
result.linux = t
}
// OS version extraction
var osVersion = '';
if (result.windowsphone) {
osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i);
} else if (iosdevice) {
osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i);
osVersion = osVersion.replace(/[_\s]/g, '.');
} else if (android) {
osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i);
} else if (result.webos) {
osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i);
} else if (result.blackberry) {
osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i);
} else if (result.bada) {
osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i);
} else if (result.tizen) {
osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i);
}
if (osVersion) {
result.osversion = osVersion;
}
// device type extraction
var osMajorVersion = osVersion.split('.')[0];
if (
tablet
|| nexusTablet
|| iosdevice == 'ipad'
|| (android && (osMajorVersion == 3 || (osMajorVersion >= 4 && !mobile)))
|| result.silk
) {
result.tablet = t
} else if (
mobile
|| iosdevice == 'iphone'
|| iosdevice == 'ipod'
|| android
|| nexusMobile
|| result.blackberry
|| result.webos
|| result.bada
) {
result.mobile = t
}
// Graded Browser Support
// http://developer.yahoo.com/yui/articles/gbs
if (result.msedge ||
(result.msie && result.version >= 10) ||
(result.yandexbrowser && result.version >= 15) ||
(result.vivaldi && result.version >= 1.0) ||
(result.chrome && result.version >= 20) ||
(result.firefox && result.version >= 20.0) ||
(result.safari && result.version >= 6) ||
(result.opera && result.version >= 10.0) ||
(result.ios && result.osversion && result.osversion.split(".")[0] >= 6) ||
(result.blackberry && result.version >= 10.1)
|| (result.chromium && result.version >= 20)
) {
result.a = t;
}
else if ((result.msie && result.version < 10) ||
(result.chrome && result.version < 20) ||
(result.firefox && result.version < 20.0) ||
(result.safari && result.version < 6) ||
(result.opera && result.version < 10.0) ||
(result.ios && result.osversion && result.osversion.split(".")[0] < 6)
|| (result.chromium && result.version < 20)
) {
result.c = t
} else result.x = t
return result
}
var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent : '')
bowser.test = function (browserList) {
for (var i = 0; i < browserList.length; ++i) {
var browserItem = browserList[i];
if (typeof browserItem=== 'string') {
if (browserItem in bowser) {
return true;
}
}
}
return false;
}
/**
* Get version precisions count
*
* @example
* getVersionPrecision("1.10.3") // 3
*
* @param {string} version
* @return {number}
*/
function getVersionPrecision(version) {
return version.split(".").length;
}
/**
* Array::map polyfill
*
* @param {Array} arr
* @param {Function} iterator
* @return {Array}
*/
function map(arr, iterator) {
var result = [], i;
if (Array.prototype.map) {
return Array.prototype.map.call(arr, iterator);
}
for (i = 0; i < arr.length; i++) {
result.push(iterator(arr[i]));
}
return result;
}
/**
* Calculate browser version weight
*
* @example
* compareVersions(['1.10.2.1', '1.8.2.1.90']) // 1
* compareVersions(['1.010.2.1', '1.09.2.1.90']); // 1
* compareVersions(['1.10.2.1', '1.10.2.1']); // 0
* compareVersions(['1.10.2.1', '1.0800.2']); // -1
*
* @param {Array<String>} versions versions to compare
* @return {Number} comparison result
*/
function compareVersions(versions) {
// 1) get common precision for both versions, for example for "10.0" and "9" it should be 2
var precision = Math.max(getVersionPrecision(versions[0]), getVersionPrecision(versions[1]));
var chunks = map(versions, function (version) {
var delta = precision - getVersionPrecision(version);
// 2) "9" -> "9.0" (for precision = 2)
version = version + new Array(delta + 1).join(".0");
// 3) "9.0" -> ["000000000"", "000000009"]
return map(version.split("."), function (chunk) {
return new Array(20 - chunk.length).join("0") + chunk;
}).reverse();
});
// iterate in reverse order by reversed chunks array
while (--precision >= 0) {
// 4) compare: "000000009" > "000000010" = false (but "9" > "10" = true)
if (chunks[0][precision] > chunks[1][precision]) {
return 1;
}
else if (chunks[0][precision] === chunks[1][precision]) {
if (precision === 0) {
// all version chunks are same
return 0;
}
}
else {
return -1;
}
}
}
/**
* Check if browser is unsupported
*
* @example
* bowser.isUnsupportedBrowser({
* msie: "10",
* firefox: "23",
* chrome: "29",
* safari: "5.1",
* opera: "16",
* phantom: "534"
* });
*
* @param {Object} minVersions map of minimal version to browser
* @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map
* @param {String} [ua] user agent string
* @return {Boolean}
*/
function isUnsupportedBrowser(minVersions, strictMode, ua) {
var _bowser = bowser;
// make strictMode param optional with ua param usage
if (typeof strictMode === 'string') {
ua = strictMode;
strictMode = void(0);
}
if (strictMode === void(0)) {
strictMode = false;
}
if (ua) {
_bowser = detect(ua);
}
var version = "" + _bowser.version;
for (var browser in minVersions) {
if (minVersions.hasOwnProperty(browser)) {
if (_bowser[browser]) {
// browser version and min supported version.
return compareVersions([version, minVersions[browser]]) < 0;
}
}
}
return strictMode; // not found
}
/**
* Check if browser is supported
*
* @param {Object} minVersions map of minimal version to browser
* @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map
* @param {String} [ua] user agent string
* @return {Boolean}
*/
function check(minVersions, strictMode, ua) {
return !isUnsupportedBrowser(minVersions, strictMode, ua);
}
bowser.isUnsupportedBrowser = isUnsupportedBrowser;
bowser.compareVersions = compareVersions;
bowser.check = check;
/*
* Set our detect method to the main bowser object so we can
* reuse it to test other user agents.
* This is needed to implement future tests.
*/
bowser._detect = detect;
return bowser
});
+225
View File
@@ -0,0 +1,225 @@
/*!
* JavaScript Cookie v2.2.0
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader;
if (typeof define === 'function' && define.amd) {
define(factory);
registeredInModuleLoader = true;
}
if (typeof exports === 'object') {
module.exports = factory();
registeredInModuleLoader = true;
}
if (!registeredInModuleLoader) {
var OldCookies = window.Cookies;
var api = window.Cookies = factory();
api.noConflict = function () {
window.Cookies = OldCookies;
return api;
};
}
}(function () {
function extend () {
var i = 0;
var result = {};
for (; i < arguments.length; i++) {
var attributes = arguments[ i ];
for (var key in attributes) {
result[key] = attributes[key];
}
}
return result;
}
function decode (s) {
return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
}
function init (converter) {
function api() {}
function set (key, value, attributes) {
if (typeof document === 'undefined') {
return;
}
attributes = extend({
path: '/'
}, api.defaults, attributes);
if (typeof attributes.expires === 'number') {
attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
}
// We're using "expires" because "max-age" is not supported by IE
attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
try {
var result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
} catch (e) {}
value = converter.write ?
converter.write(value, key) :
encodeURIComponent(String(value))
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
key = encodeURIComponent(String(key))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[\(\)]/g, escape);
var stringifiedAttributes = '';
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += '; ' + attributeName;
if (attributes[attributeName] === true) {
continue;
}
// Considers RFC 6265 section 5.2:
// ...
// 3. If the remaining unparsed-attributes contains a %x3B (";")
// character:
// Consume the characters of the unparsed-attributes up to,
// not including, the first %x3B (";") character.
// ...
stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
}
return (document.cookie = key + '=' + value + stringifiedAttributes);
}
function get (key, json) {
if (typeof document === 'undefined') {
return;
}
var jar = {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all.
var cookies = document.cookie ? document.cookie.split('; ') : [];
var i = 0;
for (; i < cookies.length; i++) {
var parts = cookies[i].split('=');
var cookie = parts.slice(1).join('=');
if (!json && cookie.charAt(0) === '"') {
cookie = cookie.slice(1, -1);
}
try {
var name = decode(parts[0]);
cookie = (converter.read || converter)(cookie, name) ||
decode(cookie);
if (json) {
try {
cookie = JSON.parse(cookie);
} catch (e) {}
}
jar[name] = cookie;
if (key === name) {
break;
}
} catch (e) {}
}
return key ? jar[key] : jar;
}
api.set = set;
api.get = function (key) {
return get(key, false /* read as raw */);
};
api.getJSON = function (key) {
return get(key, true /* read as json */);
};
api.remove = function (key, attributes) {
set(key, '', extend(attributes, {
expires: -1
}));
};
api.defaults = {};
api.withConverter = init;
return api;
}
return init(function () {});
}));
var convexhull = new function() {
// Source: https://www.nayuki.io/res/convex-hull-algorithm/convex-hull.js [21/06/18]
this.makeHull = function(points) {
var newPoints = points.slice();
newPoints.sort(this.POINT_COMPARATOR);
return this.makeHullPresorted(newPoints);
};
this.makeHullPresorted = function(points) {
if (points.length <= 1)
return points.slice();
var upperHull = [];
for (var i = 0; i < points.length; i++) {
var p = points[i];
while (upperHull.length >= 2) {
var q = upperHull[upperHull.length - 1];
var r = upperHull[upperHull.length - 2];
if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x))
upperHull.pop();
else
break;
}
upperHull.push(p);
}
upperHull.pop();
var lowerHull = [];
for (var i = points.length - 1; i >= 0; i--) {
var p = points[i];
while (lowerHull.length >= 2) {
var q = lowerHull[lowerHull.length - 1];
var r = lowerHull[lowerHull.length - 2];
if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x))
lowerHull.pop();
else
break;
}
lowerHull.push(p);
}
lowerHull.pop();
if (upperHull.length == 1 && lowerHull.length == 1 && upperHull[0].x == lowerHull[0].x && upperHull[0].y == lowerHull[0].y)
return upperHull;
else
return upperHull.concat(lowerHull);
};
this.POINT_COMPARATOR = function(a, b) {
if (a.x < b.x)
return -1;
else if (a.x > b.x)
return +1;
if (a.y < b.y)
return -1;
else if (a.y > b.y)
return +1;
else
return 0;
};
};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
jquery ui draggable is from jqueryui.com, with only draggable selected
+169
View File
@@ -0,0 +1,169 @@
var stripe_state="pay",pamount=25;
function p_log(message,color,support)
{
if(inside!="payments") return;
$("#plog").html("<span style='color: white'>&gt;</span> <span style='color: "+color+"'>"+message+"</span>");
}
function set_pamount(amount)
{
pamount=parseInt(amount);
if(stripe_state=="success")
{
setTimeout(function(){
if(inside!="payments") hide_modal();
stripe_state="pay";
$(".pbutton").removeClass("psuccess");
$(".pbutton").html("Pay $"+pamount);
},20);
return;
}
if(stripe_state=="failed") stripe_state="pay",$(".pbutton").removeClass("pfail");;
if(stripe_state=="declined") stripe_state="pay",$(".pbutton").removeClass("pfail");;
if(stripe_state=="pay") $(".pbutton").html("Pay $"+pamount);
}
function stripe_pay()
{
$("#plog").html("");
if(!window.Stripe) { alert("Stripe hasn't loaded. Please refresh the page and email hello@adventure.land if this is persistent. Thank you."); return; }
if(stripe_state=="process")
{
add_log("Currently processing your payment.");
p_log("Currently processing your payment.");
return;
}
if(stripe_state=="charge")
{
add_log("Currently charging your credit card.");
return;
}
if(in_arr(stripe_state,["failed","declined","success"])) return set_pamount(pamount);
$(".pbutton").html("Processing ...");
stripe_state="process";
Stripe.card.createToken({
name: $('.modal .stripe-name').val(),
number: $('.modal .stripe-number').val(),
cvc: $('.modal .stripe-cvc').val(),
exp_month: $('.modal .stripe-month').val(),
exp_year: $('.modal .stripe-year').val()
},stripe_response);
}
function stripe_response(status,response)
{
if(status==200)
{
$("#plog").html("");
stripe_state="charge";
$(".pbutton").html("Charging ...");
api_call("stripe_payment",{usd:pamount,response:response});
}
else
{
$("#plog").html("");
stripe_state="failed";
$(".pbutton").html("Failed.");
if(response.error && response.error.message) add_log(response.error.message,"gray"),p_log(response.error.message,"gray");
}
// if(is_sdk) show_json(response);
}
function stripe_result(result,cash)
{
if(result=="success")
{
$("#plog").html("");
stripe_state="success";
$(".pbutton").addClass("psuccess");
$(".pbutton").html("Success!");
character.cash=cash;
reset_inventory(1);
}
else if(result=="declined")
{
$("#plog").html("");
stripe_state="declined";
$(".pbutton").addClass("pfail");
$(".pbutton").html("Declined.");
p_log("If you need help, feel free to email hello@adventure.land","#88E5BC");
}
else
{
$("#plog").html("");
stripe_state="failed";
$(".pbutton").addClass("pfail");
$(".pbutton").html("Failed.");
p_log("If you need help, feel free to email hello@adventure.land","#88E5BC");
}
}
function shells_click()
{
if(stripe_enabled) show_payments();
else show_sroffers();
}
function show_payments()
{
show_modal($("#paymentshtml").html(),{wrap:false,opacity:0.4}); return;
var html="";
html+="<div style='position: fixed; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 9999; background: rgba(0,0,0,0.5); text-align: center' class='paymentsui'>";
html+=$("#paymentshtml").html();
html+="<div class='gamebutton clickable' onclick='$(\".paymentsui\").remove()' style='position: fixed; z-index: 10000; top: 0px; right: 0px; color: #CFCFCF'>Back &gt;</div>";
html+="</div>";
$('body').append(html);
}
function show_ppayments()
{
var html="";
html+="<div style='position: fixed; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 9999; background: rgba(0,0,0,0.5)' class='paymentsui'>";
html+="<div style='position: fixed; top: "+round(($(window).height()-520)/2)+"px; left: "+round(($(window).width()-750)/2)+"px;'>";
html+='<iframe src="https://api.paymentwall.com/api/ps/?key=07119679ef07a110740ecfc89da924e6&uid=[USER_ID]&widget=p10_1" width="750" height="520" frameborder="0" ';
html+='style="border: 5px solid gray; background: black"></iframe>';
html+="</div>";
html+="<div class='gamebutton clickable' onclick='$(\".paymentsui\").remove()' style='position: fixed; z-index: 10000; top: 0px; right: 0px; color: #CFCFCF'>Back &gt;</div>";
html+="</div>";
$('body').append(html);
}
function show_poffers()
{
var html="";
html+="<div style='position: fixed; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 9999; background: rgba(0,0,0,0.5)' class='paymentsui'>";
html+="<div style='position: fixed; top: 50px; left: "+round(($(window).width()-800)/2)+"px;'>";
html+='<iframe src="https://api.paymentwall.com/api/?key=07119679ef07a110740ecfc89da924e6&uid=[USER_ID]&widget=w6_1" width="800" height="'+($(window).height()-100)+'" frameborder="0" ';
html+='style="border: 5px solid gray; background: black"></iframe>';
html+="</div>";
html+="<div class='gamebutton clickable' onclick='$(\".paymentsui\").remove()' style='position: fixed; z-index: 10000; top: 0px; right: 0px'>Back &gt;</div>";
html+="</div>";
$('body').append(html);
}
function show_sroffers()
{
var html="";
html+="<div style='position: fixed; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 9999; background: rgba(0,0,0,0.5); overflow-y: scroll' class='paymentsui'>";
html+="<div style='margin-top: 40px; margin-left: "+round(($(window).width()-728)/2)+"px; z-index: 9000'>";
html+='<iframe src="https://wall.superrewards.com/super/offers?h=shmimyttqnb.811777903063&uid='+user_id+'" frameborder="0" width="728" height="2400" scrolling="no"';
html+='style="border: 5px solid gray; background: #FAFAFA"></iframe>';
html+="</div>";
html+="<div class='gamebutton clickable' onclick='$(\".paymentsui\").remove()' style='position: fixed; z-index: 10000; bottom: 0px; right: 0px'>BACK &gt;</div>";
html+="</div>";
$('body').append(html);
}
BIN
View File
Binary file not shown.
+734
View File
@@ -0,0 +1,734 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* @mixin
*/
var CanvasRendererMixin = {
_oldRender: PIXI.CanvasRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
};
module.exports = CanvasRendererMixin;
},{}],2:[function(require,module,exports){
var Const = {
/**
* controls RenderList behaviour. AUTO_ will be assigned by renderlist itself
*/
DISPLAY_FLAG: {
/**
* pass through, recursively go into children
*/
AUTO_CHILDREN: 0,
/**
* container will handle it itself
*/
AUTO_CONTAINER: 1,
/**
* like DisplayObject, no children
*/
AUTO_OBJECT: 2,
/**
* Container will always handle rendering itself, no need to go inside
*/
MANUAL_CONTAINER: 3
}
};
module.exports = Const;
},{}],3:[function(require,module,exports){
/**
* @mixin
*/
var ContainerMixin = {
/**
* @type {PIXI.DisplayList}
*/
displayList: null,
/**
* calculated display children in last
* @type {PIXI.DisplayObject[]}
*/
displayChildren: null,
updateTransform: function () {
if (!this.visible) {
return;
}
this.containerUpdateTransform();
if (this.displayList) {
this.displayList.update(this);
}
},
/**
* Renders the object using the Canvas renderer
*
* @param renderer {PIXI.CanvasRenderer} The renderer
*/
renderCanvas: function (renderer) {
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
// if the object is not visible or the alpha is 0 then no need to render this element
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
//hook for displayList
if (this.displayList) {
this.displayList.renderCanvas(this, renderer);
return;
}
this.containerRenderCanvas(renderer);
},
/**
* Renders the object using the WebGL renderer
*
* @param renderer {PIXI.WebGLRenderer} The renderer
*/
renderWebGL: function (renderer) {
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
// if the object is not visible or the alpha is 0 then no need to render this element
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
//hook for displayList
if (this.displayList) {
this.displayList.renderWebGL(this, renderer);
return;
}
this.containerRenderWebGL(renderer);
},
containerRenderWebGL: PIXI.Container.prototype.renderWebGL,
containerRenderCanvas: PIXI.Container.prototype.renderCanvas
};
module.exports = ContainerMixin;
},{}],4:[function(require,module,exports){
var EventEmitter = PIXI.utils.EventEmitter;
/**
* A shared component for multiple DisplayObject's allows to specify rendering order for them
*
* @class
* @extends EventEmitter
* @memberof PIXI
* @param zIndex {number} z-index for display group
* @param sorting {boolean | Function} if you need to sort elements inside, please provide function that will set displayObject.zOrder accordingly
*/
function DisplayGroup(zIndex, sorting) {
EventEmitter.call(this);
/**
* Children that were rendered in last run
* @type {Array}
*/
this.computedChildren = [];
/**
* Temporary variable for manipulations inside displayList
* @type {null}
*/
this.currentDisplayList = null;
/**
* real order in the current display list
* @type {number}
*/
this.currentIndex = 0;
/**
* Groups with lesser zIndex will be rendered first. Inside one group objects with largest zOrder will be rendered first.
* @type {number}
*/
this.zIndex = zIndex || 0;
/**
* sort elements inside or not
* @type {boolean}
*/
this.enableSort = !!sorting;
if (typeof sorting === 'function') {
this.on('add', sorting);
}
}
DisplayGroup.prototype = Object.create(EventEmitter.prototype);
DisplayGroup.prototype.constructor = DisplayGroup;
module.exports = DisplayGroup;
/**
*
* @param a
* @param b
* @returns {number}
*/
DisplayGroup.compareZOrder = function (a, b) {
if (a.zOrder < b.zOrder) {
return 1;
}
if (a.zOrder > b.zOrder) {
return -1;
}
return a.updateOrder - b.updateOrder;
};
/**
* clears temporary variables
*/
DisplayGroup.prototype.clear = function () {
var list = this.computedChildren;
for (var i = 0; i < list.length; i++) {
var children = list[i].displayChildren;
if (children && children.length > 0) {
for (var j = 0; j < children.length; j++) {
children[j].displayParent = null;
}
children.length = 0;
}
list[i].displayParent = null;
}
list.length = 0;
this.currentDisplayList = null;
this.currentIndex = 0;
};
/**
* used only by displayList before sorting takes place
* @param container {PIXI.DisplayObject}
*/
DisplayGroup.prototype.add = function (displayObject) {
displayObject.displayOrder = this.computedChildren.length;
this.emit('add', displayObject);
this.computedChildren.push(displayObject);
};
/**
* Called after all childrens are computed
*/
DisplayGroup.prototype.update = function () {
this.emit('update');
if (this.enableSort && this.computedChildren.length > 1) {
this.computedChildren.sort(DisplayGroup.compareZOrder);
}
};
},{}],5:[function(require,module,exports){
var EventEmitter = PIXI.utils.EventEmitter,
Const = require('./Const'),
DisplayGroup = require('./DisplayGroup');
/**
* A component for container, sorts all children inside according to their displayGroups
*
* @class
* @extends EventEmitter
* @memberof PIXI
*/
function DisplayList() {
EventEmitter.call(this);
/**
* Children that were rendered in last run
* @type {Array}
*/
this.displayGroups = [];
this.container = null;
/**
* how many elements were rendered by display list last time
* also it is used to generate updateOrder for them
* @type {number}
*/
this.totalElements = 0;
this.defaultDisplayGroup = new DisplayGroup(0, false);
}
DisplayList.prototype = Object.create(EventEmitter.prototype);
DisplayList.prototype.constructor = DisplayList;
module.exports = DisplayList;
/**
* clears all display lists that were used in last rendering session
* please clear it when you stop using this displayList, otherwise you may have problems with GC in some cases
*/
DisplayList.prototype.clear = function () {
var list = this.displayGroups;
for (var i = 0; i < list.length; i++) {
list[i].clear();
}
list.length = 0;
this.totalElements = 0;
this.container = null;
};
/**
* alias for clear()
* please call it if you stop using this displayList
*/
DisplayList.prototype.destroy = function () {
this.clear();
};
DisplayList.compareZIndex = function (a, b) {
if (a.zIndex !== b.zIndex) {
return a.zIndex - b.zIndex;
}
return a.currentIndex - b.currentIndex;
};
/**
*
* @param displayObject {PIXI.DisplayObject} container that we are adding to displaylist
* @param parent {PIXI.Container} it is not direct parent, but some of ancestors
* @private
*/
DisplayList.prototype._addRecursive = function (container, parent) {
if (!container.visible || !container.renderable) {
return;
}
var groups = this.displayGroups;
var group = parent.displayGroup;
container.updateOrder = this.totalElements++;
if (container.displayGroup) {
group = container.displayGroup;
if (!group.currentDisplayList) {
group.currentDisplayList = this;
group.currentIndex = groups.length;
groups.push(group);
}
group.add(container);
container.displayParent = this;
} else {
container.displayParent = parent;
if (!parent.displayChildren) {
parent.displayChildren = [];
}
parent.displayChildren.push(container);
}
if (container.displayFlag !== Const.DISPLAY_FLAG.MANUAL_CONTAINER) {
var children = container.children;
if (children && children.length > 0) {
if (container._mask || container._filters && container._filters.length || container.displayList) {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_CONTAINER;
} else {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_CHILDREN;
for (var i = 0; i < children.length; i++) {
this._addRecursive(children[i], container.displayParent);
}
}
} else {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_OBJECT;
}
}
};
/**
* Called from container that owns this display list
* @param parentContainer
*/
DisplayList.prototype.update = function (parentContainer) {
this.clear();
var tempGroup = parentContainer.displayGroup;
this.displayGroups.push(this.defaultDisplayGroup);
this.defaultDisplayGroup.add(parentContainer);
this.container = parentContainer;
var children = parentContainer.children;
var i;
for (i = 0; i < children.length; i++) {
this._addRecursive(children[i], parentContainer);
}
var groups = this.displayGroups;
groups.sort(DisplayList.compareZIndex);
for (i = 0; i < groups.length; i++) {
groups[i].currentIndex = i;
groups[i].update();
}
this.emit('afterUpdate');
};
/**
* renders container with webgl context
* @param parentContainer
* @param renderer
*/
DisplayList.prototype.renderWebGL = function (parentContainer, renderer) {
var groups = this.displayGroups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var list = group.computedChildren;
for (var j = 0; j < list.length; j++) {
var container = list[j];
if (container.displayFlag) {
container.renderWebGL(renderer);
} else {
container.displayOrder = renderer.incDisplayOrder();
container._renderWebGL(renderer);
var children = container.displayChildren;
if (children && children.length) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
child.displayOrder = renderer.incDisplayOrder();
if (child.displayFlag) {
child.renderWebGL(renderer);
} else {
child._renderWebGL(renderer);
}
}
}
}
}
}
};
/**
* renders container with canvas2d context
* @param parentContainer
* @param renderer
*/
DisplayList.prototype.renderCanvas = function (parentContainer, renderer) {
var groups = this.displayGroups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var list = group.computedChildren;
for (var j = 0; j < list.length; j++) {
var container = list[j];
if (container.displayFlag) {
container.renderCanvas(renderer);
} else {
container.displayOrder = renderer.incDisplayOrder();
container._renderCanvas(renderer);
var children = container.displayChildren;
if (children && children.length) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
child.displayOrder = renderer.incDisplayOrder();
if (child.displayFlag) {
child.renderCanvas(renderer);
} else {
child._renderCanvas(renderer);
}
}
}
}
}
}
};
},{"./Const":2,"./DisplayGroup":4}],6:[function(require,module,exports){
var Const = require('./Const');
/**
* @mixin
*/
var DisplayObjectMixin = {
/**
* please specify it to handle zOrder and zIndex
* @type {PIXI.DisplayGroup}
*/
displayGroup: null,
/**
* calculated inside displayList. Can be set to manual mode
* @type {number}
*/
displayFlag: Const.DISPLAY_FLAG.AUTO_CHILDREN,
/**
* calculated inside displayList. Cleared on displayList.clear()
* Equal to 'this' if displayGroup is specified
* @type {PIXI.Container}
*/
displayParent: null,
/**
* zOrder is distance between screen and object. Objects with largest zOrder will appear first in their DisplayGroup
* @type {number}
*/
zOrder: 0,
/**
* updateOrder is calculated by DisplayList, it is required for sorting inside DisplayGroup
* @type {number}
*/
updateOrder: 0
};
module.exports = DisplayObjectMixin;
},{"./Const":2}],7:[function(require,module,exports){
//TODO: add maxDisplayOrder for displayObjects and use it to speed up the interaction here
var gameofbombs = !!PIXI.Camera2d;
/**
* @mixin
*/
var InteractionManagerMixin = {
/**
* This is private recursive copy of processInteractive
*/
_processInteractive: function (point, displayObject, hitTestOrder, interactive) {
if (!displayObject || !displayObject.visible) {
return false;
}
// Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^
//
// This function will now loop through all objects and then only hit test the objects it HAS to, not all of them. MUCH faster..
// An object will be hit test if the following is true:
//
// 1: It is interactive.
// 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit.
//
// As another little optimisation once an interactive object has been hit we can carry on through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests
// A final optimisation is that an object is not hit test directly if a child has already been hit.
var hit = 0,
interactiveParent = interactive = displayObject.interactive || interactive;
// if the displayobject has a hitArea, then it does not need to hitTest children.
if (displayObject.hitArea) {
interactiveParent = false;
}
// it has a mask! Then lets hit test that before continuing..
if (hitTestOrder < Infinity && displayObject._mask) {
if (!displayObject._mask.containsPoint(point)) {
hitTestOrder = Infinity;
}
}
// it has a filterArea! Same as mask but easier, its a rectangle
if (hitTestOrder < Infinity && displayObject.filterArea) {
if (!displayObject.filterArea.contains(point.x, point.y)) {
hitTestOrder = Infinity;
}
}
// ** FREE TIP **! If an object is not interactive or has no buttons in it (such as a game scene!) set interactiveChildren to false for that displayObject.
// This will allow pixi to completly ignore and bypass checking the displayObjects children.
if (displayObject.interactiveChildren) {
var children = displayObject.children;
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
var hitChild = this._processInteractive(point, child, hitTestOrder, interactiveParent);
// time to get recursive.. if this function will return if something is hit..
if (hitChild) {
hit = hitChild;
hitTestOrder = hitChild;
}
}
}
// no point running this if the item is not interactive or does not have an interactive parent.
if (interactive) {
// if we are hit testing (as in we have no hit any objects yet)
// We also don't need to worry about hit testing if once of the displayObjects children has already been hit!
if (hitTestOrder < displayObject.displayOrder) {
if (gameofbombs) {
//gameofbombs version
if (displayObject.hitArea && displayObject.isRaycastPossible) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
} else {
//pixi v4
if (displayObject.hitArea) {
displayObject.worldTransform.applyInverse(point, this._tempPoint);
if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) {
hit = displayObject.displayOrder;
}
}
else if (displayObject.containsPoint) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
}
}
if (displayObject.interactive) {
this._queueAdd(displayObject, hit);
}
}
return hit;
},
/**
* This function is provides a neat way of crawling through the scene graph and running a specified function on all interactive objects it finds.
* It will also take care of hit testing the interactive objects and passes the hit across in the function.
*
* @param {PIXI.Point} point the point that is tested for collision
* @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject the displayObject that will be hit test (recursively crawls its children)
* @param {boolean} hitTest this indicates if the objects inside should be hit test against the point
* @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function
* @private
* @return {boolean} returns true if the displayObject hit the point
*/
processInteractive: function (point, displayObject, func, hitTest) {
this._startInteractionProcess();
this._processInteractive(point, displayObject, hitTest ? 0 : Infinity, false);
this._finishInteractionProcess(func);
},
_startInteractionProcess: function () {
//move it to constructor
this._eventDisplayOrder = 1;
if (!this._queue) {
//move it to constructor
this._queue = [[], []];
}
this._queue[0].length = 0;
this._queue[1].length = 0;
},
_queueAdd: function (displayObject, order) {
var queue = this._queue;
if (order < this._eventDisplayOrder) {
queue[0].push(displayObject);
} else {
if (order > this._eventDisplayOrder) {
this._eventDisplayOrder = order;
var q = queue[1];
for (var i = 0; i < q.length; i++) {
queue[0].push(q[i]);
}
queue[1].length = 0;
}
queue[1].push(displayObject);
}
},
/**
*
* @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function
*/
_finishInteractionProcess: function (func) {
var queue = this._queue;
var q = queue[0];
var i;
for (i = 0; i < q.length; i++) {
func(q[i], false);
}
q = queue[1];
for (i = 0; i < q.length; i++) {
func(q[i], true);
}
}
};
module.exports = InteractionManagerMixin;
},{}],8:[function(require,module,exports){
/**
* @mixin
*/
var SystemRendererMixin = {
/**
* @private
* @type {number}
*/
_lastDisplayOrder: 0,
/**
* gets new display order for container/displayobject
*/
incDisplayOrder: function() {
return ++this._lastDisplayOrder;
}
};
module.exports = SystemRendererMixin;
},{}],9:[function(require,module,exports){
/**
* @mixin
*/
var WebGLRendererMixin = {
_oldRender: PIXI.WebGLRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
};
module.exports = WebGLRendererMixin;
},{}],10:[function(require,module,exports){
var plugin = {
DisplayGroup: require('./DisplayGroup'),
DisplayList: require('./DisplayList'),
Const: require('./Const'),
DisplayObjectMixin: require('./DisplayObjectMixin'),
ContainerMixin: require('./ContainerMixin'),
SystemRendererMixin: require('./SystemRendererMixin'),
WebGLRendererMixin: require('./WebGLRendererMixin'),
CanvasRendererMixin: require('./CanvasRendererMixin'),
InteractionManagerMixin: require('./InteractionManagerMixin')
};
var pluginMixin = {
DisplayGroup: plugin.DisplayGroup,
DisplayList: plugin.DisplayList
};
Object.assign(pluginMixin, plugin.Const);
Object.assign(PIXI.DisplayObject.prototype, plugin.DisplayObjectMixin);
Object.assign(PIXI.Container.prototype, plugin.ContainerMixin);
Object.assign(PIXI.WebGLRenderer.prototype, plugin.SystemRendererMixin, plugin.WebGLRendererMixin);
Object.assign(PIXI.CanvasRenderer.prototype, plugin.SystemRendererMixin, plugin.CanvasRendererMixin);
Object.assign(PIXI.interaction.InteractionManager.prototype, plugin.InteractionManagerMixin);
Object.assign(PIXI, pluginMixin);
module.exports = plugin;
},{"./CanvasRendererMixin":1,"./Const":2,"./ContainerMixin":3,"./DisplayGroup":4,"./DisplayList":5,"./DisplayObjectMixin":6,"./InteractionManagerMixin":7,"./SystemRendererMixin":8,"./WebGLRendererMixin":9}]},{},[10])
//# sourceMappingURL=pixi-display.js.map
+734
View File
@@ -0,0 +1,734 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* @mixin
*/
var CanvasRendererMixin = {
_oldRender: PIXI.CanvasRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
};
module.exports = CanvasRendererMixin;
},{}],2:[function(require,module,exports){
var Const = {
/**
* controls RenderList behaviour. AUTO_ will be assigned by renderlist itself
*/
DISPLAY_FLAG: {
/**
* pass through, recursively go into children
*/
AUTO_CHILDREN: 0,
/**
* container will handle it itself
*/
AUTO_CONTAINER: 1,
/**
* like DisplayObject, no children
*/
AUTO_OBJECT: 2,
/**
* Container will always handle rendering itself, no need to go inside
*/
MANUAL_CONTAINER: 3
}
};
module.exports = Const;
},{}],3:[function(require,module,exports){
/**
* @mixin
*/
var ContainerMixin = {
/**
* @type {PIXI.DisplayList}
*/
displayList: null,
/**
* calculated display children in last
* @type {PIXI.DisplayObject[]}
*/
displayChildren: null,
updateTransform: function () {
if (!this.visible) {
return;
}
this.containerUpdateTransform();
if (this.displayList) {
this.displayList.update(this);
}
},
/**
* Renders the object using the Canvas renderer
*
* @param renderer {PIXI.CanvasRenderer} The renderer
*/
renderCanvas: function (renderer) {
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
// if the object is not visible or the alpha is 0 then no need to render this element
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
//hook for displayList
if (this.displayList) {
this.displayList.renderCanvas(this, renderer);
return;
}
this.containerRenderCanvas(renderer);
},
/**
* Renders the object using the WebGL renderer
*
* @param renderer {PIXI.WebGLRenderer} The renderer
*/
renderWebGL: function (renderer) {
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
// if the object is not visible or the alpha is 0 then no need to render this element
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
//hook for displayList
if (this.displayList) {
this.displayList.renderWebGL(this, renderer);
return;
}
this.containerRenderWebGL(renderer);
},
containerRenderWebGL: PIXI.Container.prototype.renderWebGL,
containerRenderCanvas: PIXI.Container.prototype.renderCanvas
};
module.exports = ContainerMixin;
},{}],4:[function(require,module,exports){
var EventEmitter = PIXI.utils.EventEmitter;
/**
* A shared component for multiple DisplayObject's allows to specify rendering order for them
*
* @class
* @extends EventEmitter
* @memberof PIXI
* @param zIndex {number} z-index for display group
* @param sorting {boolean | Function} if you need to sort elements inside, please provide function that will set displayObject.zOrder accordingly
*/
function DisplayGroup(zIndex, sorting) {
EventEmitter.call(this);
/**
* Children that were rendered in last run
* @type {Array}
*/
this.computedChildren = [];
/**
* Temporary variable for manipulations inside displayList
* @type {null}
*/
this.currentDisplayList = null;
/**
* real order in the current display list
* @type {number}
*/
this.currentIndex = 0;
/**
* Groups with lesser zIndex will be rendered first. Inside one group objects with largest zOrder will be rendered first.
* @type {number}
*/
this.zIndex = zIndex || 0;
/**
* sort elements inside or not
* @type {boolean}
*/
this.enableSort = !!sorting;
if (typeof sorting === 'function') {
this.on('add', sorting);
}
}
DisplayGroup.prototype = Object.create(EventEmitter.prototype);
DisplayGroup.prototype.constructor = DisplayGroup;
module.exports = DisplayGroup;
/**
*
* @param a
* @param b
* @returns {number}
*/
DisplayGroup.compareZOrder = function (a, b) {
if (a.zOrder < b.zOrder) {
return 1;
}
if (a.zOrder > b.zOrder) {
return -1;
}
return a.updateOrder - b.updateOrder;
};
/**
* clears temporary variables
*/
DisplayGroup.prototype.clear = function () {
var list = this.computedChildren;
for (var i = 0; i < list.length; i++) {
var children = list[i].displayChildren;
if (children && children.length > 0) {
for (var j = 0; j < children.length; j++) {
children[j].displayParent = null;
}
children.length = 0;
}
list[i].displayParent = null;
}
list.length = 0;
this.currentDisplayList = null;
this.currentIndex = 0;
};
/**
* used only by displayList before sorting takes place
* @param container {PIXI.DisplayObject}
*/
DisplayGroup.prototype.add = function (displayObject) {
displayObject.displayOrder = this.computedChildren.length;
this.emit('add', displayObject);
this.computedChildren.push(displayObject);
};
/**
* Called after all childrens are computed
*/
DisplayGroup.prototype.update = function () {
this.emit('update');
if (this.enableSort && this.computedChildren.length > 1) {
this.computedChildren.sort(DisplayGroup.compareZOrder);
}
};
},{}],5:[function(require,module,exports){
var EventEmitter = PIXI.utils.EventEmitter,
Const = require('./Const'),
DisplayGroup = require('./DisplayGroup');
/**
* A component for container, sorts all children inside according to their displayGroups
*
* @class
* @extends EventEmitter
* @memberof PIXI
*/
function DisplayList() {
EventEmitter.call(this);
/**
* Children that were rendered in last run
* @type {Array}
*/
this.displayGroups = [];
this.container = null;
/**
* how many elements were rendered by display list last time
* also it is used to generate updateOrder for them
* @type {number}
*/
this.totalElements = 0;
this.defaultDisplayGroup = new DisplayGroup(0, false);
}
DisplayList.prototype = Object.create(EventEmitter.prototype);
DisplayList.prototype.constructor = DisplayList;
module.exports = DisplayList;
/**
* clears all display lists that were used in last rendering session
* please clear it when you stop using this displayList, otherwise you may have problems with GC in some cases
*/
DisplayList.prototype.clear = function () {
var list = this.displayGroups;
for (var i = 0; i < list.length; i++) {
list[i].clear();
}
list.length = 0;
this.totalElements = 0;
this.container = null;
};
/**
* alias for clear()
* please call it if you stop using this displayList
*/
DisplayList.prototype.destroy = function () {
this.clear();
};
DisplayList.compareZIndex = function (a, b) {
if (a.zIndex !== b.zIndex) {
return a.zIndex - b.zIndex;
}
return a.currentIndex - b.currentIndex;
};
/**
*
* @param displayObject {PIXI.DisplayObject} container that we are adding to displaylist
* @param parent {PIXI.Container} it is not direct parent, but some of ancestors
* @private
*/
DisplayList.prototype._addRecursive = function (container, parent) {
if (!container.visible || !container.renderable) {
return;
}
var groups = this.displayGroups;
var group = parent.displayGroup;
container.updateOrder = this.totalElements++;
if (container.displayGroup) {
group = container.displayGroup;
if (!group.currentDisplayList) {
group.currentDisplayList = this;
group.currentIndex = groups.length;
groups.push(group);
}
group.add(container);
container.displayParent = container;
} else {
container.displayParent = parent;
if (!parent.displayChildren) {
parent.displayChildren = [];
}
parent.displayChildren.push(container);
}
if (container.displayFlag !== Const.DISPLAY_FLAG.MANUAL_CONTAINER) {
var children = container.children;
if (children && children.length > 0) {
if (container._mask || container._filters && container._filters.length || container.displayList) {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_CONTAINER;
} else {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_CHILDREN;
for (var i = 0; i < children.length; i++) {
this._addRecursive(children[i], container.displayParent);
}
}
} else {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_OBJECT;
}
}
};
/**
* Called from container that owns this display list
* @param parentContainer
*/
DisplayList.prototype.update = function (parentContainer) {
this.clear();
var tempGroup = parentContainer.displayGroup;
this.displayGroups.push(this.defaultDisplayGroup);
this.defaultDisplayGroup.add(parentContainer);
this.container = parentContainer;
var children = parentContainer.children;
var i;
for (i = 0; i < children.length; i++) {
this._addRecursive(children[i], parentContainer);
}
var groups = this.displayGroups;
groups.sort(DisplayList.compareZIndex);
for (i = 0; i < groups.length; i++) {
groups[i].currentIndex = i;
groups[i].update();
}
this.emit('afterUpdate');
};
/**
* renders container with webgl context
* @param parentContainer
* @param renderer
*/
DisplayList.prototype.renderWebGL = function (parentContainer, renderer) {
var groups = this.displayGroups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var list = group.computedChildren;
for (var j = 0; j < list.length; j++) {
var container = list[j];
if (container.displayFlag) {
container.renderWebGL(renderer);
} else {
container.displayOrder = renderer.incDisplayOrder();
container._renderWebGL(renderer);
var children = container.displayChildren;
if (children && children.length) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
child.displayOrder = renderer.incDisplayOrder();
if (child.displayFlag) {
child.renderWebGL(renderer);
} else {
child._renderWebGL(renderer);
}
}
}
}
}
}
};
/**
* renders container with canvas2d context
* @param parentContainer
* @param renderer
*/
DisplayList.prototype.renderCanvas = function (parentContainer, renderer) {
var groups = this.displayGroups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var list = group.computedChildren;
for (var j = 0; j < list.length; j++) {
var container = list[j];
if (container.displayFlag) {
container.renderCanvas(renderer);
} else {
container.displayOrder = renderer.incDisplayOrder();
container._renderCanvas(renderer);
var children = container.displayChildren;
if (children && children.length) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
child.displayOrder = renderer.incDisplayOrder();
if (child.displayFlag) {
child.renderCanvas(renderer);
} else {
child._renderCanvas(renderer);
}
}
}
}
}
}
};
},{"./Const":2,"./DisplayGroup":4}],6:[function(require,module,exports){
var Const = require('./Const');
/**
* @mixin
*/
var DisplayObjectMixin = {
/**
* please specify it to handle zOrder and zIndex
* @type {PIXI.DisplayGroup}
*/
displayGroup: null,
/**
* calculated inside displayList. Can be set to manual mode
* @type {number}
*/
displayFlag: Const.DISPLAY_FLAG.AUTO_CHILDREN,
/**
* calculated inside displayList. Cleared on displayList.clear()
* Equal to 'this' if displayGroup is specified
* @type {PIXI.Container}
*/
displayParent: null,
/**
* zOrder is distance between screen and object. Objects with largest zOrder will appear first in their DisplayGroup
* @type {number}
*/
zOrder: 0,
/**
* updateOrder is calculated by DisplayList, it is required for sorting inside DisplayGroup
* @type {number}
*/
updateOrder: 0
};
module.exports = DisplayObjectMixin;
},{"./Const":2}],7:[function(require,module,exports){
//TODO: add maxDisplayOrder for displayObjects and use it to speed up the interaction here
var gameofbombs = !!PIXI.Camera2d;
/**
* @mixin
*/
var InteractionManagerMixin = {
/**
* This is private recursive copy of processInteractive
*/
_processInteractive: function (point, displayObject, hitTestOrder, interactive) {
if (!displayObject || !displayObject.visible) {
return false;
}
// Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^
//
// This function will now loop through all objects and then only hit test the objects it HAS to, not all of them. MUCH faster..
// An object will be hit test if the following is true:
//
// 1: It is interactive.
// 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit.
//
// As another little optimisation once an interactive object has been hit we can carry on through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests
// A final optimisation is that an object is not hit test directly if a child has already been hit.
var hit = 0,
interactiveParent = interactive = displayObject.interactive || interactive;
// if the displayobject has a hitArea, then it does not need to hitTest children.
if (displayObject.hitArea) {
interactiveParent = false;
}
// it has a mask! Then lets hit test that before continuing..
if (hitTestOrder < Infinity && displayObject._mask) {
if (!displayObject._mask.containsPoint(point)) {
hitTestOrder = Infinity;
}
}
// it has a filterArea! Same as mask but easier, its a rectangle
if (hitTestOrder < Infinity && displayObject.filterArea) {
if (!displayObject.filterArea.contains(point.x, point.y)) {
hitTestOrder = Infinity;
}
}
// ** FREE TIP **! If an object is not interactive or has no buttons in it (such as a game scene!) set interactiveChildren to false for that displayObject.
// This will allow pixi to completly ignore and bypass checking the displayObjects children.
if (displayObject.interactiveChildren) {
var children = displayObject.children;
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
var hitChild = this._processInteractive(point, child, hitTestOrder, interactiveParent);
// time to get recursive.. if this function will return if something is hit..
if (hitChild) {
hit = hitChild;
hitTestOrder = hitChild;
}
}
}
// no point running this if the item is not interactive or does not have an interactive parent.
if (interactive) {
// if we are hit testing (as in we have no hit any objects yet)
// We also don't need to worry about hit testing if once of the displayObjects children has already been hit!
if (hitTestOrder < displayObject.displayOrder) {
if (gameofbombs) {
//gameofbombs version
if (displayObject.hitArea && displayObject.isRaycastPossible) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
} else {
//pixi v4
if (displayObject.hitArea) {
displayObject.worldTransform.applyInverse(point, this._tempPoint);
if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) {
hit = displayObject.displayOrder;
}
}
else if (displayObject.containsPoint) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
}
}
if (displayObject.interactive) {
this._queueAdd(displayObject, hit);
}
}
return hit;
},
/**
* This function is provides a neat way of crawling through the scene graph and running a specified function on all interactive objects it finds.
* It will also take care of hit testing the interactive objects and passes the hit across in the function.
*
* @param {PIXI.Point} point the point that is tested for collision
* @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject the displayObject that will be hit test (recursively crawls its children)
* @param {boolean} hitTest this indicates if the objects inside should be hit test against the point
* @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function
* @private
* @return {boolean} returns true if the displayObject hit the point
*/
processInteractive: function (point, displayObject, func, hitTest) {
this._startInteractionProcess();
this._processInteractive(point, displayObject, hitTest ? 0 : Infinity, false);
this._finishInteractionProcess(func);
},
_startInteractionProcess: function () {
//move it to constructor
this._eventDisplayOrder = 1;
if (!this._queue) {
//move it to constructor
this._queue = [[], []];
}
this._queue[0].length = 0;
this._queue[1].length = 0;
},
_queueAdd: function (displayObject, order) {
var queue = this._queue;
if (order < this._eventDisplayOrder) {
queue[0].push(displayObject);
} else {
if (order > this._eventDisplayOrder) {
this._eventDisplayOrder = order;
var q = queue[1];
for (var i = 0; i < q.length; i++) {
queue[0].push(q[i]);
}
queue[1].length = 0;
}
queue[1].push(displayObject);
}
},
/**
*
* @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function
*/
_finishInteractionProcess: function (func) {
var queue = this._queue;
var q = queue[0];
var i;
for (i = 0; i < q.length; i++) {
func(q[i], false);
}
q = queue[1];
for (i = 0; i < q.length; i++) {
func(q[i], true);
}
}
};
module.exports = InteractionManagerMixin;
},{}],8:[function(require,module,exports){
/**
* @mixin
*/
var SystemRendererMixin = {
/**
* @private
* @type {number}
*/
_lastDisplayOrder: 0,
/**
* gets new display order for container/displayobject
*/
incDisplayOrder: function() {
return ++this._lastDisplayOrder;
}
};
module.exports = SystemRendererMixin;
},{}],9:[function(require,module,exports){
/**
* @mixin
*/
var WebGLRendererMixin = {
_oldRender: PIXI.WebGLRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
};
module.exports = WebGLRendererMixin;
},{}],10:[function(require,module,exports){
var plugin = {
DisplayGroup: require('./DisplayGroup'),
DisplayList: require('./DisplayList'),
Const: require('./Const'),
DisplayObjectMixin: require('./DisplayObjectMixin'),
ContainerMixin: require('./ContainerMixin'),
SystemRendererMixin: require('./SystemRendererMixin'),
WebGLRendererMixin: require('./WebGLRendererMixin'),
CanvasRendererMixin: require('./CanvasRendererMixin'),
InteractionManagerMixin: require('./InteractionManagerMixin')
};
var pluginMixin = {
DisplayGroup: plugin.DisplayGroup,
DisplayList: plugin.DisplayList
};
Object.assign(pluginMixin, plugin.Const);
Object.assign(PIXI.DisplayObject.prototype, plugin.DisplayObjectMixin);
Object.assign(PIXI.Container.prototype, plugin.ContainerMixin);
Object.assign(PIXI.WebGLRenderer.prototype, plugin.SystemRendererMixin, plugin.WebGLRendererMixin);
Object.assign(PIXI.CanvasRenderer.prototype, plugin.SystemRendererMixin, plugin.CanvasRendererMixin);
Object.assign(PIXI.interaction.InteractionManager.prototype, plugin.InteractionManagerMixin);
Object.assign(PIXI, pluginMixin);
module.exports = plugin;
},{"./CanvasRendererMixin":1,"./Const":2,"./ContainerMixin":3,"./DisplayGroup":4,"./DisplayList":5,"./DisplayObjectMixin":6,"./InteractionManagerMixin":7,"./SystemRendererMixin":8,"./WebGLRendererMixin":9}]},{},[10])
//# sourceMappingURL=pixi-display.js.map
+734
View File
@@ -0,0 +1,734 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* @mixin
*/
var CanvasRendererMixin = {
_oldRender: PIXI.CanvasRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
};
module.exports = CanvasRendererMixin;
},{}],2:[function(require,module,exports){
var Const = {
/**
* controls RenderList behaviour. AUTO_ will be assigned by renderlist itself
*/
DISPLAY_FLAG: {
/**
* pass through, recursively go into children
*/
AUTO_CHILDREN: 0,
/**
* container will handle it itself
*/
AUTO_CONTAINER: 1,
/**
* like DisplayObject, no children
*/
AUTO_OBJECT: 2,
/**
* Container will always handle rendering itself, no need to go inside
*/
MANUAL_CONTAINER: 3
}
};
module.exports = Const;
},{}],3:[function(require,module,exports){
/**
* @mixin
*/
var ContainerMixin = {
/**
* @type {PIXI.DisplayList}
*/
displayList: null,
/**
* calculated display children in last
* @type {PIXI.DisplayObject[]}
*/
displayChildren: null,
updateTransform: function () {
if (!this.visible) {
return;
}
this.containerUpdateTransform();
if (this.displayList) {
this.displayList.update(this);
}
},
/**
* Renders the object using the Canvas renderer
*
* @param renderer {PIXI.CanvasRenderer} The renderer
*/
renderCanvas: function (renderer) {
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
// if the object is not visible or the alpha is 0 then no need to render this element
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
//hook for displayList
if (this.displayList) {
this.displayList.renderCanvas(this, renderer);
return;
}
this.containerRenderCanvas(renderer);
},
/**
* Renders the object using the WebGL renderer
*
* @param renderer {PIXI.WebGLRenderer} The renderer
*/
renderWebGL: function (renderer) {
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
// if the object is not visible or the alpha is 0 then no need to render this element
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
//hook for displayList
if (this.displayList) {
this.displayList.renderWebGL(this, renderer);
return;
}
this.containerRenderWebGL(renderer);
},
containerRenderWebGL: PIXI.Container.prototype.renderWebGL,
containerRenderCanvas: PIXI.Container.prototype.renderCanvas
};
module.exports = ContainerMixin;
},{}],4:[function(require,module,exports){
var EventEmitter = PIXI.utils.EventEmitter;
/**
* A shared component for multiple DisplayObject's allows to specify rendering order for them
*
* @class
* @extends EventEmitter
* @memberof PIXI
* @param zIndex {number} z-index for display group
* @param sorting {boolean | Function} if you need to sort elements inside, please provide function that will set displayObject.zOrder accordingly
*/
function DisplayGroup(zIndex, sorting) {
EventEmitter.call(this);
/**
* Children that were rendered in last run
* @type {Array}
*/
this.computedChildren = [];
/**
* Temporary variable for manipulations inside displayList
* @type {null}
*/
this.currentDisplayList = null;
/**
* real order in the current display list
* @type {number}
*/
this.currentIndex = 0;
/**
* Groups with lesser zIndex will be rendered first. Inside one group objects with largest zOrder will be rendered first.
* @type {number}
*/
this.zIndex = zIndex || 0;
/**
* sort elements inside or not
* @type {boolean}
*/
this.enableSort = !!sorting;
if (typeof sorting === 'function') {
this.on('add', sorting);
}
}
DisplayGroup.prototype = Object.create(EventEmitter.prototype);
DisplayGroup.prototype.constructor = DisplayGroup;
module.exports = DisplayGroup;
/**
*
* @param a
* @param b
* @returns {number}
*/
DisplayGroup.compareZOrder = function (a, b) {
if (a.zOrder < b.zOrder) {
return 1;
}
if (a.zOrder > b.zOrder) {
return -1;
}
return a.updateOrder - b.updateOrder;
};
/**
* clears temporary variables
*/
DisplayGroup.prototype.clear = function () {
var list = this.computedChildren;
for (var i = 0; i < list.length; i++) {
var children = list[i].displayChildren;
if (children && children.length > 0) {
for (var j = 0; j < children.length; j++) {
children[j].displayParent = null;
}
children.length = 0;
}
list[i].displayParent = null;
}
list.length = 0;
this.currentDisplayList = null;
this.currentIndex = 0;
};
/**
* used only by displayList before sorting takes place
* @param container {PIXI.DisplayObject}
*/
DisplayGroup.prototype.add = function (displayObject) {
displayObject.displayOrder = this.computedChildren.length;
this.emit('add', displayObject);
this.computedChildren.push(displayObject);
};
/**
* Called after all childrens are computed
*/
DisplayGroup.prototype.update = function () {
this.emit('update');
if (this.enableSort && this.computedChildren.length > 1) {
this.computedChildren.sort(DisplayGroup.compareZOrder);
}
};
},{}],5:[function(require,module,exports){
var EventEmitter = PIXI.utils.EventEmitter,
Const = require('./Const'),
DisplayGroup = require('./DisplayGroup');
/**
* A component for container, sorts all children inside according to their displayGroups
*
* @class
* @extends EventEmitter
* @memberof PIXI
*/
function DisplayList() {
EventEmitter.call(this);
/**
* Children that were rendered in last run
* @type {Array}
*/
this.displayGroups = [];
this.container = null;
/**
* how many elements were rendered by display list last time
* also it is used to generate updateOrder for them
* @type {number}
*/
this.totalElements = 0;
this.defaultDisplayGroup = new DisplayGroup(0, false);
}
DisplayList.prototype = Object.create(EventEmitter.prototype);
DisplayList.prototype.constructor = DisplayList;
module.exports = DisplayList;
/**
* clears all display lists that were used in last rendering session
* please clear it when you stop using this displayList, otherwise you may have problems with GC in some cases
*/
DisplayList.prototype.clear = function () {
var list = this.displayGroups;
for (var i = 0; i < list.length; i++) {
list[i].clear();
}
list.length = 0;
this.totalElements = 0;
this.container = null;
};
/**
* alias for clear()
* please call it if you stop using this displayList
*/
DisplayList.prototype.destroy = function () {
this.clear();
};
DisplayList.compareZIndex = function (a, b) {
if (a.zIndex !== b.zIndex) {
return a.zIndex - b.zIndex;
}
return a.currentIndex - b.currentIndex;
};
/**
*
* @param displayObject {PIXI.DisplayObject} container that we are adding to displaylist
* @param parent {PIXI.Container} it is not direct parent, but some of ancestors
* @private
*/
DisplayList.prototype._addRecursive = function (container, parent) {
if (!container.visible || !container.renderable) {
return;
}
var groups = this.displayGroups;
var group = parent.displayGroup;
container.updateOrder = this.totalElements++;
if (container.displayGroup) {
group = container.displayGroup;
if (!group.currentDisplayList) {
group.currentDisplayList = this;
group.currentIndex = groups.length;
groups.push(group);
}
group.add(container);
container.displayParent = container;
} else {
container.displayParent = parent;
if (!parent.displayChildren) {
parent.displayChildren = [];
}
parent.displayChildren.push(container);
}
if (container.displayFlag !== Const.DISPLAY_FLAG.MANUAL_CONTAINER) {
var children = container.children;
if (children && children.length > 0) {
if (container._mask || container._filters && container._filters.length || container.displayList) {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_CONTAINER;
} else {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_CHILDREN;
for (var i = 0; i < children.length; i++) {
this._addRecursive(children[i], container.displayParent);
}
}
} else {
container.displayFlag = Const.DISPLAY_FLAG.AUTO_OBJECT;
}
}
};
/**
* Called from container that owns this display list
* @param parentContainer
*/
DisplayList.prototype.update = function (parentContainer) {
this.clear();
var tempGroup = parentContainer.displayGroup;
this.displayGroups.push(this.defaultDisplayGroup);
this.defaultDisplayGroup.add(parentContainer);
this.container = parentContainer;
var children = parentContainer.children;
var i;
for (i = 0; i < children.length; i++) {
this._addRecursive(children[i], parentContainer);
}
var groups = this.displayGroups;
groups.sort(DisplayList.compareZIndex);
for (i = 0; i < groups.length; i++) {
groups[i].currentIndex = i;
groups[i].update();
}
this.emit('afterUpdate');
};
/**
* renders container with webgl context
* @param parentContainer
* @param renderer
*/
DisplayList.prototype.renderWebGL = function (parentContainer, renderer) {
var groups = this.displayGroups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var list = group.computedChildren;
for (var j = 0; j < list.length; j++) {
var container = list[j];
if (container.displayFlag) {
container.renderWebGL(renderer);
} else {
container.displayOrder = renderer.incDisplayOrder();
container._renderWebGL(renderer);
var children = container.displayChildren;
if (children && children.length) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
child.displayOrder = renderer.incDisplayOrder();
if (child.displayFlag) {
child.renderWebGL(renderer);
} else {
child._renderWebGL(renderer);
}
}
}
}
}
}
};
/**
* renders container with canvas2d context
* @param parentContainer
* @param renderer
*/
DisplayList.prototype.renderCanvas = function (parentContainer, renderer) {
var groups = this.displayGroups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var list = group.computedChildren;
for (var j = 0; j < list.length; j++) {
var container = list[j];
if (container.displayFlag) {
container.renderCanvas(renderer);
} else {
container.displayOrder = renderer.incDisplayOrder();
container._renderCanvas(renderer);
var children = container.displayChildren;
if (children && children.length) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
child.displayOrder = renderer.incDisplayOrder();
if (child.displayFlag) {
child.renderCanvas(renderer);
} else {
child._renderCanvas(renderer);
}
}
}
}
}
}
};
},{"./Const":2,"./DisplayGroup":4}],6:[function(require,module,exports){
var Const = require('./Const');
/**
* @mixin
*/
var DisplayObjectMixin = {
/**
* please specify it to handle zOrder and zIndex
* @type {PIXI.DisplayGroup}
*/
displayGroup: null,
/**
* calculated inside displayList. Can be set to manual mode
* @type {number}
*/
displayFlag: Const.DISPLAY_FLAG.AUTO_CHILDREN,
/**
* calculated inside displayList. Cleared on displayList.clear()
* Equal to 'this' if displayGroup is specified
* @type {PIXI.Container}
*/
displayParent: null,
/**
* zOrder is distance between screen and object. Objects with largest zOrder will appear first in their DisplayGroup
* @type {number}
*/
zOrder: 0,
/**
* updateOrder is calculated by DisplayList, it is required for sorting inside DisplayGroup
* @type {number}
*/
updateOrder: 0
};
module.exports = DisplayObjectMixin;
},{"./Const":2}],7:[function(require,module,exports){
//TODO: add maxDisplayOrder for displayObjects and use it to speed up the interaction here
var gameofbombs = !!PIXI.Camera2d;
/**
* @mixin
*/
var InteractionManagerMixin = {
/**
* This is private recursive copy of processInteractive
*/
_processInteractive: function (point, displayObject, hitTestOrder, interactive) {
if (!displayObject || !displayObject.visible) {
return false;
}
// Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^
//
// This function will now loop through all objects and then only hit test the objects it HAS to, not all of them. MUCH faster..
// An object will be hit test if the following is true:
//
// 1: It is interactive.
// 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit.
//
// As another little optimisation once an interactive object has been hit we can carry on through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests
// A final optimisation is that an object is not hit test directly if a child has already been hit.
var hit = 0,
interactiveParent = interactive = displayObject.interactive || interactive;
// if the displayobject has a hitArea, then it does not need to hitTest children.
if (displayObject.hitArea) {
interactiveParent = false;
}
// it has a mask! Then lets hit test that before continuing..
if (hitTestOrder < Infinity && displayObject._mask) {
if (!displayObject._mask.containsPoint(point)) {
hitTestOrder = Infinity;
}
}
// it has a filterArea! Same as mask but easier, its a rectangle
if (hitTestOrder < Infinity && displayObject.filterArea) {
if (!displayObject.filterArea.contains(point.x, point.y)) {
hitTestOrder = Infinity;
}
}
// ** FREE TIP **! If an object is not interactive or has no buttons in it (such as a game scene!) set interactiveChildren to false for that displayObject.
// This will allow pixi to completly ignore and bypass checking the displayObjects children.
if (displayObject.interactiveChildren) {
var children = displayObject.children;
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
var hitChild = this._processInteractive(point, child, hitTestOrder, interactiveParent);
// time to get recursive.. if this function will return if something is hit..
if (hitChild) {
hit = hitChild;
hitTestOrder = hitChild;
}
}
}
// no point running this if the item is not interactive or does not have an interactive parent.
if (interactive) {
// if we are hit testing (as in we have no hit any objects yet)
// We also don't need to worry about hit testing if once of the displayObjects children has already been hit!
if (hitTestOrder < displayObject.displayOrder) {
if (gameofbombs) {
//gameofbombs version
if (displayObject.hitArea && displayObject.isRaycastPossible) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
} else {
//pixi v4
if (displayObject.hitArea) {
displayObject.worldTransform.applyInverse(point, this._tempPoint);
if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) {
hit = displayObject.displayOrder;
}
}
else if (displayObject.containsPoint) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
}
}
if (displayObject.interactive) {
this._queueAdd(displayObject, hit);
}
}
return hit;
},
/**
* This function is provides a neat way of crawling through the scene graph and running a specified function on all interactive objects it finds.
* It will also take care of hit testing the interactive objects and passes the hit across in the function.
*
* @param {PIXI.Point} point the point that is tested for collision
* @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject the displayObject that will be hit test (recursively crawls its children)
* @param {boolean} hitTest this indicates if the objects inside should be hit test against the point
* @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function
* @private
* @return {boolean} returns true if the displayObject hit the point
*/
processInteractive: function (point, displayObject, func, hitTest) {
this._startInteractionProcess();
this._processInteractive(point, displayObject, hitTest ? 0 : Infinity, false);
this._finishInteractionProcess(func);
},
_startInteractionProcess: function () {
//move it to constructor
this._eventDisplayOrder = 1;
if (!this._queue) {
//move it to constructor
this._queue = [[], []];
}
this._queue[0].length = 0;
this._queue[1].length = 0;
},
_queueAdd: function (displayObject, order) {
var queue = this._queue;
if (order < this._eventDisplayOrder) {
queue[0].push(displayObject);
} else {
if (order > this._eventDisplayOrder) {
this._eventDisplayOrder = order;
var q = queue[1];
for (var i = 0; i < q.length; i++) {
queue[0].push(q[i]);
}
queue[1].length = 0;
}
queue[1].push(displayObject);
}
},
/**
*
* @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function
*/
_finishInteractionProcess: function (func) {
var queue = this._queue;
var q = queue[0];
var i;
for (i = 0; i < q.length; i++) {
func(q[i], false);
}
q = queue[1];
for (i = 0; i < q.length; i++) {
func(q[i], true);
}
}
};
module.exports = InteractionManagerMixin;
},{}],8:[function(require,module,exports){
/**
* @mixin
*/
var SystemRendererMixin = {
/**
* @private
* @type {number}
*/
_lastDisplayOrder: 0,
/**
* gets new display order for container/displayobject
*/
incDisplayOrder: function() {
return ++this._lastDisplayOrder;
}
};
module.exports = SystemRendererMixin;
},{}],9:[function(require,module,exports){
/**
* @mixin
*/
var WebGLRendererMixin = {
_oldRender: PIXI.WebGLRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
};
module.exports = WebGLRendererMixin;
},{}],10:[function(require,module,exports){
var plugin = {
DisplayGroup: require('./DisplayGroup'),
DisplayList: require('./DisplayList'),
Const: require('./Const'),
DisplayObjectMixin: require('./DisplayObjectMixin'),
ContainerMixin: require('./ContainerMixin'),
SystemRendererMixin: require('./SystemRendererMixin'),
WebGLRendererMixin: require('./WebGLRendererMixin'),
CanvasRendererMixin: require('./CanvasRendererMixin'),
InteractionManagerMixin: require('./InteractionManagerMixin')
};
var pluginMixin = {
DisplayGroup: plugin.DisplayGroup,
DisplayList: plugin.DisplayList
};
Object.assign(pluginMixin, plugin.Const);
Object.assign(PIXI.DisplayObject.prototype, plugin.DisplayObjectMixin);
Object.assign(PIXI.Container.prototype, plugin.ContainerMixin);
Object.assign(PIXI.WebGLRenderer.prototype, plugin.SystemRendererMixin, plugin.WebGLRendererMixin);
Object.assign(PIXI.CanvasRenderer.prototype, plugin.SystemRendererMixin, plugin.CanvasRendererMixin);
Object.assign(PIXI.interaction.InteractionManager.prototype, plugin.InteractionManagerMixin);
Object.assign(PIXI, pluginMixin);
module.exports = plugin;
},{"./CanvasRendererMixin":1,"./Const":2,"./ContainerMixin":3,"./DisplayGroup":4,"./DisplayList":5,"./DisplayObjectMixin":6,"./InteractionManagerMixin":7,"./SystemRendererMixin":8,"./WebGLRendererMixin":9}]},{},[10])
//# sourceMappingURL=pixi-display.js.map
+459
View File
@@ -0,0 +1,459 @@
PIXI.DISPLAY_FLAG = {
AUTO_CHILDREN: 0,
AUTO_CONTAINER: 1,
AUTO_OBJECT: 2,
MANUAL_CONTAINER: 3
};
var WebGLRenderer = PIXI.WebGLRenderer;
var CanvasRenderer = PIXI.CanvasRenderer;
Object.assign(PIXI.Container.prototype, {
displayList: null,
displayChildren: null,
displayParent: null,
updateTransform: function () {
if (!this.visible) {
return;
}
this.containerUpdateTransform();
if (this.displayList) {
this.displayList.update(this);
}
},
renderCanvas: function (renderer) {
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
if (this.displayList) {
this.displayList.renderCanvas(this, renderer);
return;
}
this.containerRenderCanvas(renderer);
},
renderWebGL: function (renderer) {
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
if (this.displayList) {
this.displayList.renderWebGL(this, renderer);
return;
}
this.containerRenderWebGL(renderer);
},
containerRenderWebGL: PIXI.Container.prototype.renderWebGL,
containerRenderCanvas: PIXI.Container.prototype.renderCanvas
});
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var pixi_display;
(function (pixi_display) {
var utils = PIXI.utils;
var DisplayGroup = (function (_super) {
__extends(DisplayGroup, _super);
function DisplayGroup(zIndex, sorting) {
_super.call(this);
this.currentIndex = 0;
this.zIndex = 0;
this.enableSort = false;
this.computedChildren = [];
this.currentDisplayList = null;
this.currentIndex = 0;
this.zIndex = zIndex || 0;
this.enableSort = !!sorting;
if (typeof sorting === 'function') {
this.on('add', sorting);
}
}
DisplayGroup.compareZOrder = function (a, b) {
if (a.zOrder < b.zOrder) {
return 1;
}
if (a.zOrder > b.zOrder) {
return -1;
}
return a.updateOrder - b.updateOrder;
};
;
DisplayGroup.prototype.clear = function () {
var list = this.computedChildren;
for (var i = 0; i < list.length; i++) {
var children = list[i].displayChildren;
if (children && children.length > 0) {
for (var j = 0; j < children.length; j++) {
children[j].displayParent = null;
}
children.length = 0;
}
list[i].displayParent = null;
}
list.length = 0;
this.currentDisplayList = null;
this.currentIndex = 0;
};
;
DisplayGroup.prototype.add = function (displayObject) {
displayObject.displayOrder = this.computedChildren.length;
this.emit('add', displayObject);
this.computedChildren.push(displayObject);
};
;
DisplayGroup.prototype.update = function () {
this.emit('update');
if (this.enableSort && this.computedChildren.length > 1) {
this.computedChildren.sort(DisplayGroup.compareZOrder);
}
};
;
DisplayGroup.prototype.renderWebGL = function (parentContainer, renderer) {
var list = this.computedChildren;
for (var j = 0; j < list.length; j++) {
var container = list[j];
if (container.displayFlag) {
container.renderWebGL(renderer);
}
else {
container.displayOrder = renderer.incDisplayOrder();
container._renderWebGL(renderer);
var children = container.displayChildren;
if (children && children.length) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
child.displayOrder = renderer.incDisplayOrder();
if (child.displayFlag) {
child.renderWebGL(renderer);
}
else {
child._renderWebGL(renderer);
}
}
}
}
}
};
;
DisplayGroup.prototype.renderCanvas = function (parentContainer, renderer) {
var list = this.computedChildren;
for (var j = 0; j < list.length; j++) {
var container = list[j];
if (container.displayFlag) {
container.renderCanvas(renderer);
}
else {
container.displayOrder = renderer.incDisplayOrder();
container._renderCanvas(renderer);
var children = container.displayChildren;
if (children && children.length) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
child.displayOrder = renderer.incDisplayOrder();
if (child.displayFlag) {
child.renderCanvas(renderer);
}
else {
child._renderCanvas(renderer);
}
}
}
}
}
};
;
return DisplayGroup;
}(utils.EventEmitter));
pixi_display.DisplayGroup = DisplayGroup;
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
var utils = PIXI.utils;
var DisplayList = (function (_super) {
__extends(DisplayList, _super);
function DisplayList() {
_super.call(this);
this.container = null;
this.totalElements = 0;
this.displayGroups = [];
this.defaultDisplayGroup = new pixi_display.DisplayGroup(0, false);
}
DisplayList.prototype.clear = function () {
var list = this.displayGroups;
for (var i = 0; i < list.length; i++) {
list[i].clear();
}
list.length = 0;
this.totalElements = 0;
this.container = null;
};
;
DisplayList.prototype.destroy = function () {
this.clear();
};
;
DisplayList.compareZIndex = function (a, b) {
if (a.zIndex !== b.zIndex) {
return a.zIndex - b.zIndex;
}
return a.currentIndex - b.currentIndex;
};
;
DisplayList.prototype._addRecursive = function (displayObject, parent) {
var container = displayObject;
if (!container.visible || !container.renderable) {
return;
}
var groups = this.displayGroups;
var group = parent.displayGroup;
container.updateOrder = this.totalElements++;
if (container.displayGroup) {
group = container.displayGroup;
if (!group.currentDisplayList) {
group.currentDisplayList = this;
group.currentIndex = groups.length;
groups.push(group);
}
group.add(container);
container.displayParent = container;
}
else {
container.displayParent = parent;
if (!parent.displayChildren) {
parent.displayChildren = [];
}
parent.displayChildren.push(container);
}
if (container.displayFlag !== PIXI.DISPLAY_FLAG.MANUAL_CONTAINER) {
var children = container.children;
if (children && children.length > 0) {
if (container._mask || container._filters && container._filters.length || container.displayList) {
container.displayFlag = PIXI.DISPLAY_FLAG.AUTO_CONTAINER;
}
else {
container.displayFlag = PIXI.DISPLAY_FLAG.AUTO_CHILDREN;
for (var i = 0; i < children.length; i++) {
this._addRecursive(children[i], container.displayParent);
}
}
}
else {
container.displayFlag = PIXI.DISPLAY_FLAG.AUTO_OBJECT;
}
}
};
;
DisplayList.prototype.update = function (parentContainer) {
this.clear();
var tempGroup = parentContainer.displayGroup;
this.displayGroups.push(this.defaultDisplayGroup);
this.defaultDisplayGroup.add(parentContainer);
this.container = parentContainer;
var children = parentContainer.children;
var i = 0;
for (i = 0; i < children.length; i++) {
this._addRecursive(children[i], parentContainer);
}
var groups = this.displayGroups;
groups.sort(DisplayList.compareZIndex);
for (i = 0; i < groups.length; i++) {
groups[i].currentIndex = i;
groups[i].update();
}
this.emit('afterUpdate');
};
;
DisplayList.prototype.renderWebGL = function (parentContainer, renderer) {
parentContainer.displayFlag = PIXI.DISPLAY_FLAG.AUTO_CHILDREN;
var groups = this.displayGroups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
group.renderWebGL(parentContainer, renderer);
}
};
;
DisplayList.prototype.renderCanvas = function (parentContainer, renderer) {
var groups = this.displayGroups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
group.renderCanvas(parentContainer, renderer);
}
};
;
return DisplayList;
}(utils.EventEmitter));
pixi_display.DisplayList = DisplayList;
})(pixi_display || (pixi_display = {}));
Object.assign(PIXI.DisplayObject.prototype, {
displayGroup: null,
displayFlag: PIXI.DISPLAY_FLAG.AUTO_CHILDREN,
displayParent: null,
zOrder: 0,
updateOrder: 0,
displayOrder: 0
});
var pixi_display;
(function (pixi_display) {
var InteractionManager = PIXI.interaction.InteractionManager;
Object.assign(InteractionManager.prototype, {
_queue: [[], []],
_displayProcessInteractive: function (point, displayObject, hitTestOrder, interactive) {
if (!displayObject || !displayObject.visible) {
return 0;
}
var hit = 0, interactiveParent = interactive = displayObject.interactive || interactive;
if (displayObject.hitArea) {
interactiveParent = false;
}
var mask = displayObject._mask;
if (hitTestOrder < Infinity && mask) {
if (!mask.containsPoint(point)) {
hitTestOrder = Infinity;
}
}
if (hitTestOrder < Infinity && displayObject.filterArea) {
if (!displayObject.filterArea.contains(point.x, point.y)) {
hitTestOrder = Infinity;
}
}
var children = displayObject.children;
if (displayObject.interactiveChildren && children) {
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
var hitChild = this._displayProcessInteractive(point, child, hitTestOrder, interactiveParent);
if (hitChild) {
if (!child.parent) {
continue;
}
hit = hitChild;
hitTestOrder = hitChild;
}
}
}
if (interactive) {
if (hitTestOrder < displayObject.displayOrder) {
if (displayObject.hitArea) {
displayObject.worldTransform.applyInverse(point, this._tempPoint);
if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) {
hit = displayObject.displayOrder;
}
}
else if (displayObject.containsPoint) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
}
if (displayObject.interactive) {
this._queueAdd(displayObject, hit);
}
}
return hit;
},
processInteractive: function (strangeStuff, displayObject, func, hitTest, interactive) {
var interactionEvent = null;
var point = null;
if (strangeStuff.data &&
strangeStuff.data.global) {
interactionEvent = strangeStuff;
point = interactionEvent.data.global;
}
else {
point = strangeStuff;
}
this._startInteractionProcess();
this._displayProcessInteractive(point, displayObject, hitTest ? 0 : Infinity, false);
this._finishInteractionProcess(interactionEvent, func);
},
_startInteractionProcess: function () {
this._eventDisplayOrder = 1;
if (!this._queue) {
this._queue = [[], []];
}
this._queue[0].length = 0;
this._queue[1].length = 0;
},
_queueAdd: function (displayObject, order) {
var queue = this._queue;
if (order < this._eventDisplayOrder) {
queue[0].push(displayObject);
}
else {
if (order > this._eventDisplayOrder) {
this._eventDisplayOrder = order;
var q = queue[1];
for (var i = 0; i < q.length; i++) {
queue[0].push(q[i]);
}
queue[1].length = 0;
}
queue[1].push(displayObject);
}
},
_finishInteractionProcess: function (event, func) {
var queue = this._queue;
var q = queue[0];
var i = 0;
for (; i < q.length; i++) {
if (event) {
func(event, q[i], false);
}
else {
func(q[i], false);
}
}
q = queue[1];
for (i = 0; i < q.length; i++) {
if (event) {
if (!event.target) {
event.target = q[i];
}
func(event, q[i], true);
}
else {
func(q[i], true);
}
}
}
});
})(pixi_display || (pixi_display = {}));
Object.assign(WebGLRenderer.prototype, {
_lastDisplayOrder: 0,
incDisplayOrder: function () {
return ++this._lastDisplayOrder;
},
_oldRender: WebGLRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
});
Object.assign(CanvasRenderer.prototype, {
_lastDisplayOrder: 0,
incDisplayOrder: function () {
return ++this._lastDisplayOrder;
},
_oldRender: CanvasRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
});
Object.assign(PIXI, {
display: pixi_display,
DisplayGroup: pixi_display.DisplayGroup,
DisplayList: pixi_display.DisplayList
});
//# sourceMappingURL=pixi-display.js.map
BIN
View File
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
BIN
View File
Binary file not shown.
+726
View File
@@ -0,0 +1,726 @@
var pixi_display;
(function (pixi_display) {
Object.assign(PIXI.Container.prototype, {
renderWebGL: function (renderer) {
if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) {
return;
}
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
this.containerRenderWebGL(renderer);
},
renderCanvas: function (renderer) {
if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) {
return;
}
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
this.containerRenderCanvas(renderer);
},
containerRenderWebGL: PIXI.Container.prototype.renderWebGL,
containerRenderCanvas: PIXI.Container.prototype.renderCanvas
});
})(pixi_display || (pixi_display = {}));
Object.assign(PIXI.DisplayObject.prototype, {
parentLayer: null,
_activeParentLayer: null,
parentGroup: null,
zOrder: 0,
zIndex: 0,
updateOrder: 0,
displayOrder: 0,
layerableChildren: true
});
if (PIXI.particles && PIXI.particles.ParticleContainer) {
PIXI.particles.ParticleContainer.prototype.layerableChildren = false;
}
else if (PIXI.ParticleContainer) {
PIXI.ParticleContainer.prototype.layerableChildren = false;
}
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var pixi_display;
(function (pixi_display) {
var utils = PIXI.utils;
var Group = (function (_super) {
__extends(Group, _super);
function Group(zIndex, sorting) {
var _this = _super.call(this) || this;
_this._activeLayer = null;
_this._activeStage = null;
_this._activeChildren = [];
_this._lastUpdateId = -1;
_this.useRenderTexture = false;
_this.useDoubleBuffer = false;
_this.sortPriority = 0;
_this.clearColor = new Float32Array([0, 0, 0, 0]);
_this.canDrawWithoutLayer = false;
_this.canDrawInParentStage = true;
_this.zIndex = 0;
_this.enableSort = false;
_this._tempResult = [];
_this._tempZero = [];
_this.useZeroOptimization = false;
_this.zIndex = zIndex;
_this.enableSort = !!sorting;
if (typeof sorting === 'function') {
_this.on('sort', sorting);
}
return _this;
}
Group.prototype.doSort = function (layer, sorted) {
if (this.listeners('sort', true)) {
for (var i = 0; i < sorted.length; i++) {
this.emit('sort', sorted[i]);
}
}
if (this.useZeroOptimization) {
this.doSortWithZeroOptimization(layer, sorted);
}
else {
sorted.sort(Group.compareZIndex);
}
};
Group.compareZIndex = function (a, b) {
if (a.zIndex !== b.zIndex) {
return a.zIndex - b.zIndex;
}
if (a.zOrder > b.zOrder) {
return -1;
}
if (a.zOrder < b.zOrder) {
return 1;
}
return a.updateOrder - b.updateOrder;
};
Group.prototype.doSortWithZeroOptimization = function (layer, sorted) {
throw new Error("not implemented yet");
};
Group.prototype.clear = function () {
this._activeLayer = null;
this._activeStage = null;
this._activeChildren.length = 0;
};
Group.prototype.addDisplayObject = function (stage, displayObject) {
this.check(stage);
displayObject._activeParentLayer = this._activeLayer;
if (this._activeLayer) {
this._activeLayer._activeChildren.push(displayObject);
}
else {
this._activeChildren.push(displayObject);
}
};
Group.prototype.foundLayer = function (stage, layer) {
this.check(stage);
if (this._activeLayer != null) {
Group.conflict();
}
this._activeLayer = layer;
this._activeStage = stage;
};
Group.prototype.foundStage = function (stage) {
if (!this._activeLayer && !this.canDrawInParentStage) {
this.clear();
}
};
Group.prototype.check = function (stage) {
if (this._lastUpdateId < Group._layerUpdateId) {
this._lastUpdateId = Group._layerUpdateId;
this.clear();
this._activeStage = stage;
}
else if (this.canDrawInParentStage) {
var current = this._activeStage;
while (current && current != stage) {
current = current._activeParentStage;
}
this._activeStage = current;
if (current == null) {
this.clear();
return;
}
}
};
Group.conflict = function () {
if (Group._lastLayerConflict + 5000 < Date.now()) {
Group._lastLayerConflict = Date.now();
console.log("PIXI-display plugin found two layers with the same group in one stage - that's not healthy. Please place a breakpoint here and debug it");
}
};
Group._layerUpdateId = 0;
Group._lastLayerConflict = 0;
return Group;
}(utils.EventEmitter));
pixi_display.Group = Group;
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
var InteractionManager = PIXI.interaction.InteractionManager;
Object.assign(InteractionManager.prototype, {
_queue: [[], []],
_displayProcessInteractive: function (point, displayObject, hitTestOrder, interactive, outOfMask) {
if (!displayObject || !displayObject.visible) {
return 0;
}
var hit = 0, interactiveParent = interactive = displayObject.interactive || interactive;
if (displayObject.hitArea) {
interactiveParent = false;
}
if (displayObject._activeParentLayer) {
outOfMask = false;
}
var mask = displayObject._mask;
if (hitTestOrder < Infinity && mask) {
if (!mask.containsPoint(point)) {
outOfMask = true;
}
}
if (hitTestOrder < Infinity && displayObject.filterArea) {
if (!displayObject.filterArea.contains(point.x, point.y)) {
outOfMask = true;
}
}
var children = displayObject.children;
if (displayObject.interactiveChildren && children) {
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
var hitChild = this._displayProcessInteractive(point, child, hitTestOrder, interactiveParent, outOfMask);
if (hitChild) {
if (!child.parent) {
continue;
}
hit = hitChild;
hitTestOrder = hitChild;
}
}
}
if (interactive) {
if (!outOfMask) {
if (hitTestOrder < displayObject.displayOrder) {
if (displayObject.hitArea) {
displayObject.worldTransform.applyInverse(point, this._tempPoint);
if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) {
hit = displayObject.displayOrder;
}
}
else if (displayObject.containsPoint) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
}
if (displayObject.interactive) {
this._queueAdd(displayObject, hit === Infinity ? 0 : hit);
}
}
else {
if (displayObject.interactive) {
this._queueAdd(displayObject, 0);
}
}
}
return hit;
},
processInteractive: function (strangeStuff, displayObject, func, hitTest, interactive) {
var interactionEvent = null;
var point = null;
if (strangeStuff.data &&
strangeStuff.data.global) {
interactionEvent = strangeStuff;
point = interactionEvent.data.global;
}
else {
point = strangeStuff;
}
this._startInteractionProcess();
this._displayProcessInteractive(point, displayObject, hitTest ? 0 : Infinity, false);
this._finishInteractionProcess(interactionEvent, func);
},
_startInteractionProcess: function () {
this._eventDisplayOrder = 1;
if (!this._queue) {
this._queue = [[], []];
}
this._queue[0].length = 0;
this._queue[1].length = 0;
},
_queueAdd: function (displayObject, order) {
var queue = this._queue;
if (order < this._eventDisplayOrder) {
queue[0].push(displayObject);
}
else {
if (order > this._eventDisplayOrder) {
this._eventDisplayOrder = order;
var q = queue[1];
for (var i = 0; i < q.length; i++) {
queue[0].push(q[i]);
}
queue[1].length = 0;
}
queue[1].push(displayObject);
}
},
_finishInteractionProcess: function (event, func) {
var queue = this._queue;
var q = queue[0];
var i = 0;
for (; i < q.length; i++) {
if (event) {
if (func) {
func(event, q[i], false);
}
}
else {
func(q[i], false);
}
}
q = queue[1];
for (i = 0; i < q.length; i++) {
if (event) {
if (!event.target) {
event.target = q[i];
}
if (func) {
func(event, q[i], true);
}
}
else {
func(q[i], true);
}
}
}
});
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
var LayerTextureCache = (function () {
function LayerTextureCache(layer) {
this.layer = layer;
this.renderTexture = null;
this.doubleBuffer = null;
this.currentBufferIndex = 0;
this._tempRenderTarget = null;
}
LayerTextureCache.prototype.initRenderTexture = function (renderer) {
var width = renderer ? renderer.screen.width : 100;
var height = renderer ? renderer.screen.height : 100;
var resolution = renderer ? renderer.resolution : PIXI.settings.RESOLUTION;
this.renderTexture = PIXI.RenderTexture.create(width, height, resolution);
if (this.layer.group.useDoubleBuffer) {
this.doubleBuffer = [
PIXI.RenderTexture.create(width, height, resolution),
PIXI.RenderTexture.create(width, height, resolution)
];
}
};
LayerTextureCache.prototype.getRenderTexture = function () {
if (!this.renderTexture) {
this.initRenderTexture();
}
return this.renderTexture;
};
LayerTextureCache.prototype.pushTexture = function (renderer) {
var screen = renderer.screen;
if (!this.renderTexture) {
this.initRenderTexture(renderer);
}
var rt = this.renderTexture;
var group = this.layer.group;
var db = this.doubleBuffer;
if (rt.width !== screen.width ||
rt.height !== screen.height ||
rt.baseTexture.resolution !== renderer.resolution) {
rt.baseTexture.resolution = renderer.resolution;
rt.resize(screen.width, screen.height);
if (db) {
db[0].baseTexture.resolution = renderer.resolution;
db[0].resize(screen.width, screen.height);
db[1].baseTexture.resolution = renderer.resolution;
db[1].resize(screen.width, screen.height);
}
}
this._tempRenderTarget = renderer._activeRenderTarget;
renderer.currentRenderer.flush();
if (group.useDoubleBuffer) {
var buffer = db[this.currentBufferIndex];
if (!buffer.baseTexture._glTextures[renderer.CONTEXT_UID]) {
renderer.bindRenderTexture(buffer, null);
if (group.clearColor) {
renderer.clear(group.clearColor);
}
}
renderer.unbindTexture(rt);
rt.baseTexture._glTextures = buffer.baseTexture._glTextures;
rt.baseTexture._glRenderTargets = buffer.baseTexture._glRenderTargets;
this.currentBufferIndex = 1 - this.currentBufferIndex;
buffer = db[this.currentBufferIndex];
renderer.bindRenderTexture(buffer, null);
}
else {
renderer.bindRenderTexture(rt, undefined);
}
if (group.clearColor) {
renderer.clear(group.clearColor);
}
};
LayerTextureCache.prototype.popTexture = function (renderer) {
renderer.currentRenderer.flush();
renderer.bindRenderTarget(this._tempRenderTarget);
this._tempRenderTarget = null;
};
LayerTextureCache.prototype.destroy = function () {
if (this.renderTexture) {
this.renderTexture.destroy();
if (this.doubleBuffer) {
this.doubleBuffer[0].destroy(true);
this.doubleBuffer[1].destroy(true);
}
}
};
return LayerTextureCache;
}());
pixi_display.LayerTextureCache = LayerTextureCache;
var Layer = (function (_super) {
__extends(Layer, _super);
function Layer(group) {
if (group === void 0) { group = null; }
var _this = _super.call(this) || this;
_this.isLayer = true;
_this.group = null;
_this._activeChildren = [];
_this._tempChildren = null;
_this._activeStageParent = null;
_this._sortedChildren = [];
_this._tempLayerParent = null;
_this.insertChildrenBeforeActive = true;
_this.insertChildrenAfterActive = true;
if (group != null) {
_this.group = group;
_this.zIndex = group.zIndex;
}
else {
_this.group = new pixi_display.Group(0, false);
}
_this._tempChildren = _this.children;
return _this;
}
Layer.prototype.beginWork = function (stage) {
var active = this._activeChildren;
this._activeStageParent = stage;
this.group.foundLayer(stage, this);
var groupChildren = this.group._activeChildren;
active.length = 0;
for (var i = 0; i < groupChildren.length; i++) {
groupChildren[i]._activeParentLayer = this;
active.push(groupChildren[i]);
}
groupChildren.length = 0;
};
Layer.prototype.endWork = function () {
var children = this.children;
var active = this._activeChildren;
var sorted = this._sortedChildren;
for (var i = 0; i < active.length; i++) {
this.emit("display", active[i]);
}
sorted.length = 0;
if (this.insertChildrenBeforeActive) {
for (var i = 0; i < children.length; i++) {
sorted.push(children[i]);
}
}
for (var i = 0; i < active.length; i++) {
sorted.push(active[i]);
}
if (!this.insertChildrenBeforeActive &&
this.insertChildrenAfterActive) {
for (var i = 0; i < children.length; i++) {
sorted.push(children[i]);
}
}
if (this.group.enableSort) {
this.doSort();
}
};
Object.defineProperty(Layer.prototype, "useRenderTexture", {
get: function () {
return this.group.useRenderTexture;
},
set: function (value) {
this.group.useRenderTexture = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Layer.prototype, "useDoubleBuffer", {
get: function () {
return this.group.useDoubleBuffer;
},
set: function (value) {
this.group.useDoubleBuffer = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Layer.prototype, "clearColor", {
get: function () {
return this.group.clearColor;
},
set: function (value) {
this.group.clearColor = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Layer.prototype, "sortPriority", {
get: function () {
return this.group.sortPriority;
},
set: function (value) {
this.group.sortPriority = value;
},
enumerable: true,
configurable: true
});
Layer.prototype.getRenderTexture = function () {
if (!this.textureCache) {
this.textureCache = new LayerTextureCache(this);
}
return this.textureCache.getRenderTexture();
};
Layer.prototype.updateDisplayLayers = function () {
};
Layer.prototype.doSort = function () {
this.group.doSort(this, this._sortedChildren);
};
Layer.prototype._preRender = function (renderer) {
if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) {
return false;
}
if (!this.visible) {
this.displayOrder = 0;
return false;
}
this.displayOrder = renderer.incDisplayOrder();
if (this.worldAlpha <= 0 || !this.renderable) {
return false;
}
if (this.children !== this._sortedChildren &&
this._tempChildren != this.children) {
this._tempChildren = this.children;
}
this._boundsID++;
this.children = this._sortedChildren;
this._tempLayerParent = renderer._activeLayer;
renderer._activeLayer = this;
return true;
};
Layer.prototype._postRender = function (renderer) {
this.children = this._tempChildren;
renderer._activeLayer = this._tempLayerParent;
this._tempLayerParent = null;
};
Layer.prototype.renderWebGL = function (renderer) {
if (!this._preRender(renderer)) {
return;
}
if (this.group.useRenderTexture) {
if (!this.textureCache) {
this.textureCache = new LayerTextureCache(this);
}
this.textureCache.pushTexture(renderer);
}
this.containerRenderWebGL(renderer);
this._postRender(renderer);
if (this.group.useRenderTexture) {
this.textureCache.popTexture(renderer);
}
};
Layer.prototype.renderCanvas = function (renderer) {
if (this._preRender(renderer)) {
this.containerRenderCanvas(renderer);
this._postRender(renderer);
}
};
Layer.prototype.destroy = function (options) {
if (this.textureCache) {
this.textureCache.destroy();
this.textureCache = null;
}
_super.prototype.destroy.call(this, options);
};
return Layer;
}(PIXI.Container));
pixi_display.Layer = Layer;
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
var Stage = (function (_super) {
__extends(Stage, _super);
function Stage() {
var _this = _super.call(this) || this;
_this.isStage = true;
_this._tempGroups = [];
_this._activeLayers = [];
_this._activeParentStage = null;
return _this;
}
Stage.prototype.clear = function () {
this._activeLayers.length = 0;
this._tempGroups.length = 0;
};
Stage.prototype.destroy = function (options) {
this.clear();
_super.prototype.destroy.call(this, options);
};
Stage.prototype._addRecursive = function (displayObject) {
if (!displayObject.visible) {
return;
}
if (displayObject.isLayer) {
var layer_1 = displayObject;
this._activeLayers.push(layer_1);
layer_1.beginWork(this);
}
if (displayObject != this && displayObject.isStage) {
var stage = displayObject;
stage.updateAsChildStage(this);
return;
}
var group = displayObject.parentGroup;
if (group !== null) {
group.addDisplayObject(this, displayObject);
}
var layer = displayObject.parentLayer;
if (layer !== null) {
group = layer.group;
group.addDisplayObject(this, displayObject);
}
displayObject.updateOrder = ++Stage._updateOrderCounter;
if (displayObject.alpha <= 0 || !displayObject.renderable
|| !displayObject.layerableChildren
|| group && group.sortPriority) {
return;
}
var children = displayObject.children;
if (children && children.length) {
for (var i = 0; i < children.length; i++) {
this._addRecursive(children[i]);
}
}
};
Stage.prototype._addRecursiveChildren = function (displayObject) {
if (displayObject.alpha <= 0 || !displayObject.renderable
|| !displayObject.layerableChildren) {
return;
}
var children = displayObject.children;
if (children && children.length) {
for (var i = 0; i < children.length; i++) {
this._addRecursive(children[i]);
}
}
};
Stage.prototype._updateStageInner = function () {
this.clear();
this._addRecursive(this);
var layers = this._activeLayers;
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
if (layer.group.sortPriority) {
layer.endWork();
var sorted = layer._sortedChildren;
for (var j = 0; j < sorted.length; j++) {
this._addRecursiveChildren(sorted[j]);
}
}
}
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
if (!layer.group.sortPriority) {
layer.endWork();
}
}
};
Stage.prototype.updateAsChildStage = function (stage) {
this._activeParentStage = stage;
Stage._updateOrderCounter = 0;
this._updateStageInner();
};
Stage.prototype.updateStage = function () {
this._activeParentStage = null;
pixi_display.Group._layerUpdateId++;
this._updateStageInner();
};
;
Stage._updateOrderCounter = 0;
return Stage;
}(pixi_display.Layer));
pixi_display.Stage = Stage;
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
Object.assign(PIXI.WebGLRenderer.prototype, {
_lastDisplayOrder: 0,
_activeLayer: null,
incDisplayOrder: function () {
return ++this._lastDisplayOrder;
},
_oldRender: PIXI.WebGLRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._activeLayer = null;
if (displayObject.isStage) {
displayObject.updateStage();
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
});
Object.assign(PIXI.CanvasRenderer.prototype, {
_lastDisplayOrder: 0,
_activeLayer: null,
incDisplayOrder: function () {
return ++this._lastDisplayOrder;
},
_oldRender: PIXI.CanvasRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._activeLayer = null;
if (displayObject.isStage) {
displayObject.updateStage();
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
});
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
PIXI.display = pixi_display;
})(pixi_display || (pixi_display = {}));
//# sourceMappingURL=pixi-layers.js.map
+611
View File
@@ -0,0 +1,611 @@
var pixi_display;
(function (pixi_display) {
Object.assign(PIXI.Container.prototype, {
renderWebGL: function (renderer) {
if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) {
return;
}
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
this.containerRenderWebGL(renderer);
},
renderCanvas: function (renderer) {
if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) {
return;
}
if (!this.visible) {
this.displayOrder = 0;
return;
}
this.displayOrder = renderer.incDisplayOrder();
if (this.worldAlpha <= 0 || !this.renderable) {
return;
}
this.containerRenderCanvas(renderer);
},
containerRenderWebGL: PIXI.Container.prototype.renderWebGL,
containerRenderCanvas: PIXI.Container.prototype.renderCanvas
});
})(pixi_display || (pixi_display = {}));
Object.assign(PIXI.DisplayObject.prototype, {
parentLayer: null,
_activeParentLayer: null,
parentGroup: null,
zOrder: 0,
zIndex: 0,
updateOrder: 0,
displayOrder: 0,
layerableChildren: true
});
if (PIXI.particles && PIXI.particles.ParticleContainer) {
PIXI.particles.ParticleContainer.prototype.layerableChildren = false;
}
else if (PIXI.ParticleContainer) {
PIXI.ParticleContainer.prototype.layerableChildren = false;
}
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var pixi_display;
(function (pixi_display) {
var utils = PIXI.utils;
var Group = (function (_super) {
__extends(Group, _super);
function Group(zIndex, sorting) {
var _this = _super.call(this) || this;
_this._activeLayer = null;
_this._activeStage = null;
_this._activeChildren = [];
_this._lastUpdateId = -1;
_this.useRenderTexture = false;
_this.clearColor = new Float32Array([0, 0, 0, 0]);
_this.canDrawWithoutLayer = false;
_this.canDrawInParentStage = true;
_this.zIndex = 0;
_this.enableSort = false;
_this._tempResult = [];
_this._tempZero = [];
_this.useZeroOptimization = false;
_this.zIndex = zIndex;
_this.enableSort = !!sorting;
if (typeof sorting === 'function') {
_this.on('sort', sorting);
}
return _this;
}
Group.prototype.doSort = function (layer, sorted) {
if (this.listeners('sort', true)) {
for (var i = 0; i < sorted.length; i++) {
this.emit('sort', sorted[i]);
}
}
if (this.useZeroOptimization) {
this.doSortWithZeroOptimization(layer, sorted);
}
else {
sorted.sort(Group.compareZIndex);
}
};
Group.compareZIndex = function (a, b) {
if (a.zIndex !== b.zIndex) {
return a.zIndex - b.zIndex;
}
if (a.zOrder > b.zOrder) {
return -1;
}
if (a.zOrder < b.zOrder) {
return 1;
}
return a.updateOrder - b.updateOrder;
};
Group.prototype.doSortWithZeroOptimization = function (layer, sorted) {
throw new Error("not implemented yet");
};
Group.prototype.clear = function () {
this._activeLayer = null;
this._activeStage = null;
this._activeChildren.length = 0;
};
Group.prototype.addDisplayObject = function (stage, displayObject) {
this.check(stage);
displayObject._activeParentLayer = this._activeLayer;
if (this._activeLayer) {
this._activeLayer._activeChildren.push(displayObject);
}
else {
this._activeChildren.push(displayObject);
}
};
Group.prototype.foundLayer = function (stage, layer) {
this.check(stage);
if (this._activeLayer != null) {
Group.conflict();
}
this._activeLayer = layer;
this._activeStage = stage;
};
Group.prototype.foundStage = function (stage) {
if (!this._activeLayer && !this.canDrawInParentStage) {
this.clear();
}
};
Group.prototype.check = function (stage) {
if (this._lastUpdateId < Group._layerUpdateId) {
this._lastUpdateId = Group._layerUpdateId;
this.clear();
this._activeStage = stage;
}
else if (this.canDrawInParentStage) {
var current = this._activeStage;
while (current && current != stage) {
current = current._activeParentStage;
}
this._activeStage = current;
if (current == null) {
this.clear();
return;
}
}
};
Group.conflict = function () {
if (Group._lastLayerConflict + 5000 < Date.now()) {
Group._lastLayerConflict = Date.now();
console.log("PIXI-display plugin found two layers with the same group in one stage - that's not healthy. Please place a breakpoint here and debug it");
}
};
Group._layerUpdateId = 0;
Group._lastLayerConflict = 0;
return Group;
}(utils.EventEmitter));
pixi_display.Group = Group;
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
var InteractionManager = PIXI.interaction.InteractionManager;
Object.assign(InteractionManager.prototype, {
_queue: [[], []],
_displayProcessInteractive: function (point, displayObject, hitTestOrder, interactive, outOfMask) {
if (!displayObject || !displayObject.visible) {
return 0;
}
var hit = 0, interactiveParent = interactive = displayObject.interactive || interactive;
if (displayObject.hitArea) {
interactiveParent = false;
}
if (displayObject._activeParentLayer) {
outOfMask = false;
}
var mask = displayObject._mask;
if (hitTestOrder < Infinity && mask) {
if (!mask.containsPoint(point)) {
outOfMask = true;
}
}
if (hitTestOrder < Infinity && displayObject.filterArea) {
if (!displayObject.filterArea.contains(point.x, point.y)) {
outOfMask = true;
}
}
var children = displayObject.children;
if (displayObject.interactiveChildren && children) {
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
var hitChild = this._displayProcessInteractive(point, child, hitTestOrder, interactiveParent, outOfMask);
if (hitChild) {
if (!child.parent) {
continue;
}
hit = hitChild;
hitTestOrder = hitChild;
}
}
}
if (interactive) {
if (!outOfMask) {
if (hitTestOrder < displayObject.displayOrder) {
if (displayObject.hitArea) {
displayObject.worldTransform.applyInverse(point, this._tempPoint);
if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) {
hit = displayObject.displayOrder;
}
}
else if (displayObject.containsPoint) {
if (displayObject.containsPoint(point)) {
hit = displayObject.displayOrder;
}
}
}
if (displayObject.interactive) {
this._queueAdd(displayObject, hit === Infinity ? 0 : hit);
}
}
else {
if (displayObject.interactive) {
this._queueAdd(displayObject, 0);
}
}
}
return hit;
},
processInteractive: function (strangeStuff, displayObject, func, hitTest, interactive) {
var interactionEvent = null;
var point = null;
if (strangeStuff.data &&
strangeStuff.data.global) {
interactionEvent = strangeStuff;
point = interactionEvent.data.global;
}
else {
point = strangeStuff;
}
this._startInteractionProcess();
this._displayProcessInteractive(point, displayObject, hitTest ? 0 : Infinity, false);
this._finishInteractionProcess(interactionEvent, func);
},
_startInteractionProcess: function () {
this._eventDisplayOrder = 1;
if (!this._queue) {
this._queue = [[], []];
}
this._queue[0].length = 0;
this._queue[1].length = 0;
},
_queueAdd: function (displayObject, order) {
var queue = this._queue;
if (order < this._eventDisplayOrder) {
queue[0].push(displayObject);
}
else {
if (order > this._eventDisplayOrder) {
this._eventDisplayOrder = order;
var q = queue[1];
for (var i = 0; i < q.length; i++) {
queue[0].push(q[i]);
}
queue[1].length = 0;
}
queue[1].push(displayObject);
}
},
_finishInteractionProcess: function (event, func) {
var queue = this._queue;
var q = queue[0];
var i = 0;
for (; i < q.length; i++) {
if (event) {
if (func) {
func(event, q[i], false);
}
}
else {
func(q[i], false);
}
}
q = queue[1];
for (i = 0; i < q.length; i++) {
if (event) {
if (!event.target) {
event.target = q[i];
}
if (func) {
func(event, q[i], true);
}
}
else {
func(q[i], true);
}
}
}
});
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
var Layer = (function (_super) {
__extends(Layer, _super);
function Layer(group) {
if (group === void 0) { group = null; }
var _this = _super.call(this) || this;
_this.isLayer = true;
_this.group = null;
_this._activeChildren = [];
_this._tempChildren = null;
_this._activeStageParent = null;
_this._sortedChildren = [];
_this._tempLayerParent = null;
_this._thisRenderTexture = null;
_this._tempRenderTarget = null;
_this.insertChildrenBeforeActive = true;
_this.insertChildrenAfterActive = true;
if (group != null) {
_this.group = group;
_this.zIndex = group.zIndex;
}
else {
_this.group = new pixi_display.Group(0, false);
}
_this._tempChildren = _this.children;
return _this;
}
Layer.prototype.beginWork = function (stage) {
var active = this._activeChildren;
this._activeStageParent = stage;
this.group.foundLayer(stage, this);
var groupChildren = this.group._activeChildren;
active.length = 0;
for (var i = 0; i < groupChildren.length; i++) {
groupChildren[i]._activeParentLayer = this;
active.push(groupChildren[i]);
}
groupChildren.length = 0;
};
Layer.prototype.endWork = function () {
var children = this.children;
var active = this._activeChildren;
var sorted = this._sortedChildren;
for (var i = 0; i < active.length; i++) {
this.emit("display", active[i]);
}
sorted.length = 0;
if (this.insertChildrenBeforeActive) {
for (var i = 0; i < children.length; i++) {
sorted.push(children[i]);
}
}
for (var i = 0; i < active.length; i++) {
sorted.push(active[i]);
}
if (!this.insertChildrenBeforeActive &&
this.insertChildrenAfterActive) {
for (var i = 0; i < children.length; i++) {
sorted.push(children[i]);
}
}
if (this.group.enableSort) {
this.doSort();
}
};
Object.defineProperty(Layer.prototype, "useRenderTexture", {
get: function () {
return this.group.useRenderTexture;
},
set: function (value) {
this.group.useRenderTexture = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Layer.prototype, "clearColor", {
get: function () {
return this.group.clearColor;
},
set: function (value) {
this.group.clearColor = value;
},
enumerable: true,
configurable: true
});
Layer.prototype.getRenderTexture = function () {
if (!this._thisRenderTexture) {
this._thisRenderTexture = PIXI.RenderTexture.create(100, 100);
}
return this._thisRenderTexture;
};
Layer.prototype.updateDisplayLayers = function () {
};
Layer.prototype.doSort = function () {
this.group.doSort(this, this._sortedChildren);
};
Layer.prototype._preRender = function (renderer) {
if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) {
return false;
}
if (!this.visible) {
this.displayOrder = 0;
return false;
}
this.displayOrder = renderer.incDisplayOrder();
if (this.worldAlpha <= 0 || !this.renderable) {
return false;
}
if (this.children !== this._sortedChildren &&
this._tempChildren != this.children) {
this._tempChildren = this.children;
}
this._boundsID++;
this.children = this._sortedChildren;
this._tempLayerParent = renderer._activeLayer;
renderer._activeLayer = this;
return true;
};
Layer.prototype._postRender = function (renderer) {
this.children = this._tempChildren;
renderer._activeLayer = this._tempLayerParent;
this._tempLayerParent = null;
};
Layer.prototype._pushTexture = function (renderer) {
var screen = renderer.screen;
if (!this._thisRenderTexture) {
this._thisRenderTexture = PIXI.RenderTexture.create(screen.width, screen.height, null, renderer.resolution);
}
var rt = this._thisRenderTexture;
if (rt.width !== screen.width ||
rt.height !== screen.height ||
rt.baseTexture.resolution !== renderer.resolution) {
rt.baseTexture.resolution = renderer.resolution;
rt.resize(screen.width, screen.height);
}
this._tempRenderTarget = renderer._activeRenderTarget;
renderer.currentRenderer.flush();
renderer.bindRenderTexture(rt, undefined);
if (this.group.clearColor) {
renderer.clear(this.group.clearColor);
}
};
Layer.prototype._popTexture = function (renderer) {
renderer.currentRenderer.flush();
renderer.bindRenderTarget(this._tempRenderTarget);
this._tempRenderTarget = null;
};
Layer.prototype.renderWebGL = function (renderer) {
if (!this._preRender(renderer)) {
return;
}
if (this.group.useRenderTexture) {
this._pushTexture(renderer);
}
this.containerRenderWebGL(renderer);
this._postRender(renderer);
if (this.group.useRenderTexture) {
this._popTexture(renderer);
}
};
Layer.prototype.renderCanvas = function (renderer) {
if (this._preRender(renderer)) {
this.containerRenderCanvas(renderer);
this._postRender(renderer);
}
};
Layer.prototype.destroy = function (options) {
if (this._thisRenderTexture) {
this._thisRenderTexture.destroy(true);
}
_super.prototype.destroy.call(this, options);
};
return Layer;
}(PIXI.Container));
pixi_display.Layer = Layer;
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
Object.assign(PIXI.WebGLRenderer.prototype, {
_lastDisplayOrder: 0,
_activeLayer: null,
incDisplayOrder: function () {
return ++this._lastDisplayOrder;
},
_oldRender: PIXI.WebGLRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._activeLayer = null;
if (displayObject.isStage) {
displayObject.updateStage();
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
});
Object.assign(PIXI.CanvasRenderer.prototype, {
_lastDisplayOrder: 0,
_activeLayer: null,
incDisplayOrder: function () {
return ++this._lastDisplayOrder;
},
_oldRender: PIXI.CanvasRenderer.prototype.render,
render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) {
if (!renderTexture) {
this._lastDisplayOrder = 0;
}
this._activeLayer = null;
if (displayObject.isStage) {
displayObject.updateStage();
}
this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform);
}
});
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
var Stage = (function (_super) {
__extends(Stage, _super);
function Stage() {
var _this = _super.call(this) || this;
_this.isStage = true;
_this._tempGroups = [];
_this._activeLayers = [];
_this._activeParentStage = null;
return _this;
}
Stage.prototype.clear = function () {
this._activeLayers.length = 0;
this._tempGroups.length = 0;
};
Stage.prototype.destroy = function (options) {
this.clear();
_super.prototype.destroy.call(this, options);
};
Stage.prototype._addRecursive = function (displayObject) {
if (!displayObject.visible) {
return;
}
if (displayObject.isLayer) {
var layer_1 = displayObject;
this._activeLayers.push(layer_1);
layer_1.beginWork(this);
}
if (displayObject != this && displayObject.isStage) {
var stage = displayObject;
stage.updateAsChildStage(this);
return;
}
var group = displayObject.parentGroup;
if (group != null) {
displayObject.parentGroup.addDisplayObject(this, displayObject);
}
var layer = displayObject.parentLayer;
if (layer != null) {
layer.group.addDisplayObject(this, displayObject);
}
displayObject.updateOrder = ++Stage._updateOrderCounter;
if (displayObject.alpha <= 0 || !displayObject.renderable || !displayObject.layerableChildren) {
return;
}
var children = displayObject.children;
if (children && children.length) {
for (var i = 0; i < children.length; i++) {
this._addRecursive(children[i]);
}
}
};
Stage.prototype._updateStageInner = function () {
this.clear();
this._addRecursive(this);
var layers = this._activeLayers;
for (var i = 0; i < layers.length; i++) {
layers[i].endWork();
}
};
Stage.prototype.updateAsChildStage = function (stage) {
this._activeParentStage = stage;
Stage._updateOrderCounter = 0;
this._updateStageInner();
};
Stage.prototype.updateStage = function () {
this._activeParentStage = null;
pixi_display.Group._layerUpdateId++;
this._updateStageInner();
};
;
Stage._updateOrderCounter = 0;
return Stage;
}(pixi_display.Layer));
pixi_display.Stage = Stage;
})(pixi_display || (pixi_display = {}));
var pixi_display;
(function (pixi_display) {
PIXI.display = pixi_display;
})(pixi_display || (pixi_display = {}));
//# sourceMappingURL=pixi-layers.js.map
BIN
View File
Binary file not shown.
File diff suppressed because one or more lines are too long
BIN
View File
Binary file not shown.
+32280
View File
File diff suppressed because it is too large Load Diff
+18
View File
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More