Skip to content

Commit 9958619

Browse files
committed
fixes #630 and updates codemirror
1 parent 63be548 commit 9958619

File tree

8 files changed

+336
-17
lines changed

8 files changed

+336
-17
lines changed

client/modules/IDE/actions/uploader.js

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import axios from 'axios';
22
import { createFile } from './files';
3+
import { TEXT_FILE_REGEX } from '../../../../server/utils/fileUtils';
34

4-
const textFileRegex = /(text\/|application\/json)/;
55
const s3BucketHttps = process.env.S3_BUCKET_URL_BASE ||
66
`https://s3-${process.env.AWS_REGION}.amazonaws.com/${process.env.S3_BUCKET}/`;
77
const ROOT_URL = process.env.API_URL;
@@ -33,10 +33,8 @@ function localIntercept(file, options = {}) {
3333

3434
export function dropzoneAcceptCallback(userId, file, done) {
3535
return () => {
36-
// for text files and small files
37-
// check mime type
38-
// if text, local interceptor
39-
if (file.type.match(textFileRegex) && file.size < MAX_LOCAL_FILE_SIZE) {
36+
// if a user would want to edit this file as text, local interceptor
37+
if (file.name.match(TEXT_FILE_REGEX) && file.size < MAX_LOCAL_FILE_SIZE) {
4038
localIntercept(file).then((result) => {
4139
file.content = result; // eslint-disable-line
4240
done('Uploading plaintext file locally.');
@@ -79,7 +77,7 @@ export function dropzoneAcceptCallback(userId, file, done) {
7977

8078
export function dropzoneSendingCallback(file, xhr, formData) {
8179
return () => {
82-
if (!file.type.match(textFileRegex) || file.size >= MAX_LOCAL_FILE_SIZE) {
80+
if (!file.name.match(TEXT_FILE_REGEX) || file.size >= MAX_LOCAL_FILE_SIZE) {
8381
Object.keys(file.postData).forEach((key) => {
8482
formData.append(key, file.postData[key]);
8583
});
@@ -92,7 +90,7 @@ export function dropzoneSendingCallback(file, xhr, formData) {
9290

9391
export function dropzoneCompleteCallback(file) {
9492
return (dispatch, getState) => { // eslint-disable-line
95-
if ((!file.type.match(textFileRegex) || file.size >= MAX_LOCAL_FILE_SIZE) && file.status !== 'error') {
93+
if ((!file.name.match(TEXT_FILE_REGEX) || file.size >= MAX_LOCAL_FILE_SIZE) && file.status !== 'error') {
9694
let inputHidden = '<input type="hidden" name="attachments[]" value="';
9795
const json = {
9896
url: `${s3BucketHttps}${file.postData.key}`,

client/modules/IDE/components/Editor.jsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import classNames from 'classnames';
2828
import { debounce } from 'lodash';
2929
import '../../../utils/htmlmixed';
3030
import '../../../utils/p5-javascript';
31+
import '../../../utils/webGL-clike';
3132
import Timer from '../components/Timer';
3233
import EditorAccessibility from '../components/EditorAccessibility';
3334
import {
@@ -212,6 +213,8 @@ class Editor extends React.Component {
212213
mode = 'htmlmixed';
213214
} else if (fileName.match(/.+\.json$/i)) {
214215
mode = 'application/json';
216+
} else if (fileName.match(/.+\.(frag|vert)$/i)) {
217+
mode = 'clike';
215218
} else {
216219
mode = 'text/plain';
217220
}

client/modules/IDE/components/PreviewFrame.jsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
MEDIA_FILE_REGEX,
1515
MEDIA_FILE_QUOTED_REGEX,
1616
STRING_REGEX,
17-
TEXT_FILE_REGEX,
17+
PLAINTEXT_FILE_REGEX,
1818
EXTERNAL_LINK_REGEX,
1919
NOT_EXTERNAL_LINK_REGEX
2020
} from '../../../../server/utils/fileUtils';
@@ -228,7 +228,7 @@ class PreviewFrame extends React.Component {
228228
if (resolvedFile) {
229229
if (resolvedFile.url) {
230230
newContent = newContent.replace(filePath, resolvedFile.url);
231-
} else if (resolvedFile.name.match(TEXT_FILE_REGEX)) {
231+
} else if (resolvedFile.name.match(PLAINTEXT_FILE_REGEX)) {
232232
// could also pull file from API instead of using bloburl
233233
const blobURL = getBlobUrl(resolvedFile);
234234
this.props.setBlobUrl(resolvedFile, blobURL);

client/utils/webGL-clike.js

Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
1+
// CodeMirror, copyright (c) by Marijn Haverbeke and others
2+
// Distributed under an MIT license: http://codemirror.net/LICENSE
3+
4+
// Taken from https://github.com/tangrams/GLSL-live-editor/blob/master/src/codemirror/mode/webGL-clike.js
5+
/* eslint-disable */
6+
7+
(function(mod) {
8+
if (typeof exports == "object" && typeof module == "object") // CommonJS
9+
mod(require("codemirror"));
10+
else if (typeof define == "function" && define.amd) // AMD
11+
define(["codemirror"], mod);
12+
else // Plain browser env
13+
mod(CodeMirror);
14+
})(function(CodeMirror) {
15+
"use strict";
16+
17+
CodeMirror.defineMode("clike", function(config, parserConfig) {
18+
var indentUnit = config.indentUnit,
19+
statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
20+
dontAlignCalls = parserConfig.dontAlignCalls,
21+
keywords = parserConfig.keywords || {},
22+
builtin = parserConfig.builtin || {},
23+
blockKeywords = parserConfig.blockKeywords || {},
24+
atoms = parserConfig.atoms || {},
25+
hooks = parserConfig.hooks || {},
26+
multiLineStrings = parserConfig.multiLineStrings,
27+
indentStatements = parserConfig.indentStatements !== false;
28+
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
29+
30+
var curPunc;
31+
32+
function tokenBase(stream, state) {
33+
var ch = stream.next();
34+
if (hooks[ch]) {
35+
var result = hooks[ch](stream, state);
36+
if (result !== false) return result;
37+
}
38+
if (ch == '"' || ch == "'") {
39+
state.tokenize = tokenString(ch);
40+
return state.tokenize(stream, state);
41+
}
42+
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
43+
curPunc = ch;
44+
return null;
45+
}
46+
if (/\d/.test(ch)) {
47+
stream.eatWhile(/[\w\.]/);
48+
return "number";
49+
}
50+
if (ch == "/") {
51+
if (stream.eat("*")) {
52+
state.tokenize = tokenComment;
53+
return tokenComment(stream, state);
54+
}
55+
if (stream.eat("/")) {
56+
stream.skipToEnd();
57+
return "comment";
58+
}
59+
}
60+
if (isOperatorChar.test(ch)) {
61+
stream.eatWhile(isOperatorChar);
62+
return "operator";
63+
}
64+
stream.eatWhile(/[\w\$_\xa1-\uffff]/);
65+
var cur = stream.current();
66+
if (keywords.propertyIsEnumerable(cur)) {
67+
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
68+
return "keyword";
69+
}
70+
if (builtin.propertyIsEnumerable(cur)) {
71+
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
72+
return "builtin";
73+
}
74+
if (atoms.propertyIsEnumerable(cur)) return "atom";
75+
return "variable";
76+
}
77+
78+
function tokenString(quote) {
79+
return function(stream, state) {
80+
var escaped = false, next, end = false;
81+
while ((next = stream.next()) != null) {
82+
if (next == quote && !escaped) {end = true; break;}
83+
escaped = !escaped && next == "\\";
84+
}
85+
if (end || !(escaped || multiLineStrings))
86+
state.tokenize = null;
87+
return "string";
88+
};
89+
}
90+
91+
function tokenComment(stream, state) {
92+
var maybeEnd = false, ch;
93+
while (ch = stream.next()) {
94+
if (ch == "/" && maybeEnd) {
95+
state.tokenize = null;
96+
break;
97+
}
98+
maybeEnd = (ch == "*");
99+
}
100+
return "comment";
101+
}
102+
103+
function Context(indented, column, type, align, prev) {
104+
this.indented = indented;
105+
this.column = column;
106+
this.type = type;
107+
this.align = align;
108+
this.prev = prev;
109+
}
110+
function pushContext(state, col, type) {
111+
var indent = state.indented;
112+
if (state.context && state.context.type == "statement")
113+
indent = state.context.indented;
114+
return state.context = new Context(indent, col, type, null, state.context);
115+
}
116+
function popContext(state) {
117+
var t = state.context.type;
118+
if (t == ")" || t == "]" || t == "}")
119+
state.indented = state.context.indented;
120+
return state.context = state.context.prev;
121+
}
122+
123+
// Interface
124+
125+
return {
126+
startState: function(basecolumn) {
127+
return {
128+
tokenize: null,
129+
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
130+
indented: 0,
131+
startOfLine: true
132+
};
133+
},
134+
135+
token: function(stream, state) {
136+
var ctx = state.context;
137+
if (stream.sol()) {
138+
if (ctx.align == null) ctx.align = false;
139+
state.indented = stream.indentation();
140+
state.startOfLine = true;
141+
}
142+
if (stream.eatSpace()) return null;
143+
curPunc = null;
144+
var style = (state.tokenize || tokenBase)(stream, state);
145+
if (style == "comment" || style == "meta") return style;
146+
if (ctx.align == null) ctx.align = true;
147+
148+
if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
149+
else if (curPunc == "{") pushContext(state, stream.column(), "}");
150+
else if (curPunc == "[") pushContext(state, stream.column(), "]");
151+
else if (curPunc == "(") pushContext(state, stream.column(), ")");
152+
else if (curPunc == "}") {
153+
while (ctx.type == "statement") ctx = popContext(state);
154+
if (ctx.type == "}") ctx = popContext(state);
155+
while (ctx.type == "statement") ctx = popContext(state);
156+
}
157+
else if (curPunc == ctx.type) popContext(state);
158+
else if (indentStatements &&
159+
(((ctx.type == "}" || ctx.type == "top") && curPunc != ';') ||
160+
(ctx.type == "statement" && curPunc == "newstatement")))
161+
pushContext(state, stream.column(), "statement");
162+
state.startOfLine = false;
163+
return style;
164+
},
165+
166+
indent: function(state, textAfter) {
167+
if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
168+
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
169+
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
170+
var closing = firstChar == ctx.type;
171+
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
172+
else if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
173+
else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
174+
else return ctx.indented + (closing ? 0 : indentUnit);
175+
},
176+
177+
electricChars: "{}",
178+
blockCommentStart: "/*",
179+
blockCommentEnd: "*/",
180+
lineComment: "//",
181+
fold: "brace"
182+
};
183+
});
184+
185+
function words(str) {
186+
var obj = {}, words = str.split(" ");
187+
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
188+
return obj;
189+
}
190+
var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
191+
"double static else struct entry switch extern typedef float union for unsigned " +
192+
"goto while enum void const signed volatile";
193+
194+
function cppHook(stream, state) {
195+
if (!state.startOfLine) return false;
196+
for (;;) {
197+
if (stream.skipTo("\\")) {
198+
stream.next();
199+
if (stream.eol()) {
200+
state.tokenize = cppHook;
201+
break;
202+
}
203+
} else {
204+
stream.skipToEnd();
205+
state.tokenize = null;
206+
break;
207+
}
208+
}
209+
return "meta";
210+
}
211+
212+
function cpp11StringHook(stream, state) {
213+
stream.backUp(1);
214+
// Raw strings.
215+
if (stream.match(/(R|u8R|uR|UR|LR)/)) {
216+
var match = stream.match(/"([^\s\\()]{0,16})\(/);
217+
if (!match) {
218+
return false;
219+
}
220+
state.cpp11RawStringDelim = match[1];
221+
state.tokenize = tokenRawString;
222+
return tokenRawString(stream, state);
223+
}
224+
// Unicode strings/chars.
225+
if (stream.match(/(u8|u|U|L)/)) {
226+
if (stream.match(/["']/, /* eat */ false)) {
227+
return "string";
228+
}
229+
return false;
230+
}
231+
// Ignore this hook.
232+
stream.next();
233+
return false;
234+
}
235+
236+
// C#-style strings where "" escapes a quote.
237+
function tokenAtString(stream, state) {
238+
var next;
239+
while ((next = stream.next()) != null) {
240+
if (next == '"' && !stream.eat('"')) {
241+
state.tokenize = null;
242+
break;
243+
}
244+
}
245+
return "string";
246+
}
247+
248+
// C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
249+
// <delim> can be a string up to 16 characters long.
250+
function tokenRawString(stream, state) {
251+
// Escape characters that have special regex meanings.
252+
var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
253+
var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
254+
if (match)
255+
state.tokenize = null;
256+
else
257+
stream.skipToEnd();
258+
return "string";
259+
}
260+
261+
function def(mimes, mode) {
262+
if (typeof mimes == "string") mimes = [mimes];
263+
var words = [];
264+
function add(obj) {
265+
if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
266+
words.push(prop);
267+
}
268+
add(mode.keywords);
269+
add(mode.builtin);
270+
add(mode.atoms);
271+
if (words.length) {
272+
mode.helperType = mimes[0];
273+
CodeMirror.registerHelper("hintWords", mimes[0], words);
274+
}
275+
276+
for (var i = 0; i < mimes.length; ++i)
277+
CodeMirror.defineMIME(mimes[i], mode);
278+
}
279+
280+
def(["x-shader/x-vertex", "x-shader/x-fragment"], {
281+
name: "clike",
282+
keywords: words("float int bool void " +
283+
"vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
284+
"mat2 mat3 mat4 " +
285+
"sampler2D sampler3D samplerCube " +
286+
"const attribute uniform varying " +
287+
"break continue discard return " +
288+
"for while do if else struct " +
289+
"in out inout"),
290+
blockKeywords: words("for while do if else struct"),
291+
builtin: words("radians degrees sin cos tan asin acos atan " +
292+
"pow exp log exp2 sqrt inversesqrt " +
293+
"abs sign floor ceil fract mod min max clamp mix step smoothstep " +
294+
"length distance dot cross normalize faceforward " +
295+
"reflect refract matrixCompMult " +
296+
"lessThan lessThanEqual greaterThan greaterThanEqual " +
297+
"equal notEqual any all not " +
298+
"texture2D texture2DLod texture2DProjLod " +
299+
"textureCube textureCubeLod "),
300+
atoms: words("true false " +
301+
"gl_FragColor " +
302+
"gl_PointCoord " +
303+
"gl_Position gl_PointSize " +
304+
"gl_FragCoord gl_FrontFacing " +
305+
"gl_FragData " +
306+
"gl_DepthRangeParameters " +
307+
"gl_MaxVertexAttribs gl_MaxVaryingVectors gl_MaxVertexUniformVectors" +
308+
"gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
309+
"gl_MaxFragmentUniformVectors " +
310+
"gl_MaxDrawBuffers"),
311+
hooks: {"#": cppHook},
312+
modeProps: {fold: ["brace", "include"]}
313+
});
314+
315+
});

0 commit comments

Comments
 (0)