[MERGE] website, *: improve CSS edition usability + add JS edition

* web, web_editor

See sub-commits for details.

Currently, when an user wants to edit the css of its website, he has
access to lots of files and, in debug mode, to even more files. While
the feature is nice for people who know what they are doing, a lambda
person can easily break its website by changing the wrong files. Also,
nothing warns the user that the files that are edited will never receive
updates anymore (unless if they are reset). The goal is to prevent
those behavior while still allowing the add custom css. Another goal
is to be able to *add* custom javascript.

Custom files created for the user:
SCSS: user_custom_rules.scss, user_custom_bootstrap_overridden.scss
JS: user_custom_javascript.js

task-1919350

closes odoo/odoo#29999
This commit is contained in:
Robot Odoo
2019-02-06 02:13:10 +01:00
committed by GitHub
13 changed files with 1016 additions and 210 deletions
@@ -0,0 +1,48 @@
define("ace/mode/doc_comment_highlight_rules",["require","exports","module"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
},
DocCommentHighlightRules.getTagRule(),
{
defaultToken : "comment.doc",
caseInsensitive: true
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getTagRule = function(start) {
return {
token : "comment.doc.tag.storage.type",
regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b"
};
};
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
+588
View File
@@ -0,0 +1,588 @@
define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
// TODO: Unicode escape sequences
var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*";
var JavaScriptHighlightRules = function(options) {
// see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects
var keywordMapper = this.createKeywordMapper({
"variable.language":
"Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors
"Namespace|QName|XML|XMLList|" + // E4X
"ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" +
"Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" +
"Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors
"SyntaxError|TypeError|URIError|" +
"decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions
"isNaN|parseFloat|parseInt|" +
"JSON|Math|" + // Other
"this|arguments|prototype|window|document" , // Pseudo
"keyword":
"const|yield|import|get|set|async|await|" +
"break|case|catch|continue|default|delete|do|else|finally|for|function|" +
"if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" +
// invalid or reserved
"__parent__|__count__|escape|unescape|with|__proto__|" +
"class|enum|extends|super|export|implements|private|public|interface|package|protected|static",
"storage.type":
"const|let|var|function",
"constant.language":
"null|Infinity|NaN|undefined",
"support.function":
"alert",
"constant.language.boolean": "true|false"
}, "identifier");
// keywords which can be followed by regular expressions
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void";
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
"u[0-9a-fA-F]{4}|" + // unicode
"u{[0-9a-fA-F]{1,6}}|" + // es6 unicode
"[0-2][0-7]{0,2}|" + // oct
"3[0-7][0-7]?|" + // oct
"[4-7][0-7]?|" + //oct
".)";
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"no_regex" : [
DocCommentHighlightRules.getStartRule("doc-start"),
comments("no_regex"),
{
token : "string",
regex : "'(?=.)",
next : "qstring"
}, {
token : "string",
regex : '"(?=.)',
next : "qqstring"
}, {
token : "constant.numeric", // hexadecimal, octal and binary
regex : /0(?:[xX][0-9a-fA-F]+|[oO][0-7]+|[bB][01]+)\b/
}, {
token : "constant.numeric", // decimal integers and floats
regex : /(?:\d\d*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+\b)?/
}, {
// Sound.prototype.play =
token : [
"storage.type", "punctuation.operator", "support.function",
"punctuation.operator", "entity.name.function", "text","keyword.operator"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)",
next: "function_arguments"
}, {
// Sound.play = function() { }
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
// play = function() { }
token : [
"entity.name.function", "text", "keyword.operator", "text", "storage.type",
"text", "paren.lparen"
],
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
// Sound.play = function play() { }
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",
next: "function_arguments"
}, {
// function myFunc(arg) { }
token : [
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
next: "function_arguments"
}, {
// foobar: function() { }
token : [
"entity.name.function", "text", "punctuation.operator",
"text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
// : function() { } (this is for issues with 'foo': function() { })
token : [
"text", "text", "storage.type", "text", "paren.lparen"
],
regex : "(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
// from "module-path" (this is the only case where 'from' should be a keyword)
token : "keyword",
regex : "from(?=\\s*('|\"))"
}, {
token : "keyword",
regex : "(?:" + kwBeforeRe + ")\\b",
next : "start"
}, {
token : ["support.constant"],
regex : /that\b/
}, {
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/
}, {
token : keywordMapper,
regex : identifierRe
}, {
token : "punctuation.operator",
regex : /[.](?![.])/,
next : "property"
}, {
token : "storage.type",
regex : /=>/,
next : "start"
}, {
token : "keyword.operator",
regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/,
next : "start"
}, {
token : "punctuation.operator",
regex : /[?:,;.]/,
next : "start"
}, {
token : "paren.lparen",
regex : /[\[({]/,
next : "start"
}, {
token : "paren.rparen",
regex : /[\])}]/
}, {
token: "comment",
regex: /^#!.*$/
}
],
property: [{
token : "text",
regex : "\\s+"
}, {
// Sound.play = function play() { }
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()",
next: "function_arguments"
}, {
token : "punctuation.operator",
regex : /[.](?![.])/
}, {
token : "support.function",
regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
}, {
token : "support.function.dom",
regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
}, {
token : "support.constant",
regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
}, {
token : "identifier",
regex : identifierRe
}, {
regex: "",
token: "empty",
next: "no_regex"
}
],
// regular expressions are only allowed after certain tokens. This
// makes sure we don't mix up regexps with the divison operator
"start": [
DocCommentHighlightRules.getStartRule("doc-start"),
comments("start"),
{
token: "string.regexp",
regex: "\\/",
next: "regex"
}, {
token : "text",
regex : "\\s+|^$",
next : "start"
}, {
// immediately return to the start mode without matching
// anything
token: "empty",
regex: "",
next: "no_regex"
}
],
"regex": [
{
// escapes
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
// flag
token: "string.regexp",
regex: "/[sxngimy]*",
next: "no_regex"
}, {
// invalid operators
token : "invalid",
regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/
}, {
// operators
token : "constant.language.escape",
regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/
}, {
token : "constant.language.delimiter",
regex: /\|/
}, {
token: "constant.language.escape",
regex: /\[\^?/,
next: "regex_character_class"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp"
}
],
"regex_character_class": [
{
token: "regexp.charclass.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "constant.language.escape",
regex: "]",
next: "regex"
}, {
token: "constant.language.escape",
regex: "-"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp.charachterclass"
}
],
"function_arguments": [
{
token: "variable.parameter",
regex: identifierRe
}, {
token: "punctuation.operator",
regex: "[, ]+"
}, {
token: "punctuation.operator",
regex: "$"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
consumeLineEnd : true
}, {
token : "string",
regex : '"|$',
next : "no_regex"
}, {
defaultToken: "string"
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
consumeLineEnd : true
}, {
token : "string",
regex : "'|$",
next : "no_regex"
}, {
defaultToken: "string"
}
]
};
if (!options || !options.noES6) {
this.$rules.no_regex.unshift({
regex: "[{}]", onMatch: function(val, state, stack) {
this.next = val == "{" ? this.nextState : "";
if (val == "{" && stack.length) {
stack.unshift("start", state);
}
else if (val == "}" && stack.length) {
stack.shift();
this.next = stack.shift();
if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1)
return "paren.quasi.end";
}
return val == "{" ? "paren.lparen" : "paren.rparen";
},
nextState: "start"
}, {
token : "string.quasi.start",
regex : /`/,
push : [{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "paren.quasi.start",
regex : /\${/,
push : "start"
}, {
token : "string.quasi.end",
regex : /`/,
next : "pop"
}, {
defaultToken: "string.quasi"
}]
});
if (!options || options.jsx != false)
JSX.call(this);
}
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("no_regex") ]);
this.normalizeRules();
};
oop.inherits(JavaScriptHighlightRules, TextHighlightRules, DocCommentHighlightRules);
function JSX() {
var tagRegex = identifierRe.replace("\\d", "\\d\\-");
var jsxTag = {
onMatch : function(val, state, stack) {
var offset = val.charAt(1) == "/" ? 2 : 1;
if (offset == 1) {
if (state != this.nextState)
stack.unshift(this.next, this.nextState, 0);
else
stack.unshift(this.next);
stack[2]++;
} else if (offset == 2) {
if (state == this.nextState) {
stack[1]--;
if (!stack[1] || stack[1] < 0) {
stack.shift();
stack.shift();
}
}
}
return [{
type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml",
value: val.slice(0, offset)
}, {
type: "meta.tag.tag-name.xml",
value: val.substr(offset)
}];
},
regex : "</?" + tagRegex + "",
next: "jsxAttributes",
nextState: "jsx"
};
this.$rules.start.unshift(jsxTag);
var jsxJsRule = {
regex: "{",
token: "paren.quasi.start",
push: "start"
};
this.$rules.jsx = [
jsxJsRule,
jsxTag,
{include : "reference"},
{defaultToken: "string"}
];
this.$rules.jsxAttributes = [{
token : "meta.tag.punctuation.tag-close.xml",
regex : "/?>",
onMatch : function(value, currentState, stack) {
if (currentState == stack[0])
stack.shift();
if (value.length == 2) {
if (stack[0] == this.nextState)
stack[1]--;
if (!stack[1] || stack[1] < 0) {
stack.splice(0, 2);
}
}
this.next = stack[0] || "start";
return [{type: this.token, value: value}];
},
nextState: "jsx"
},
jsxJsRule,
comments("jsxAttributes"),
{
token : "entity.other.attribute-name.xml",
regex : tagRegex
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "="
}, {
token : "text.tag-whitespace.xml",
regex : "\\s+"
}, {
token : "string.attribute-value.xml",
regex : "'",
stateName : "jsx_attr_q",
push : [
{token : "string.attribute-value.xml", regex: "'", next: "pop"},
{include : "reference"},
{defaultToken : "string.attribute-value.xml"}
]
}, {
token : "string.attribute-value.xml",
regex : '"',
stateName : "jsx_attr_qq",
push : [
{token : "string.attribute-value.xml", regex: '"', next: "pop"},
{include : "reference"},
{defaultToken : "string.attribute-value.xml"}
]
},
jsxTag
];
this.$rules.reference = [{
token : "constant.language.escape.reference.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}];
}
function comments(next) {
return [
{
token : "comment", // multi line comment
regex : /\/\*/,
next: [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "\\*\\/", next : next || "pop"},
{defaultToken : "comment", caseInsensitive: true}
]
}, {
token : "comment",
regex : "\\/\\/",
next: [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "$|^", next : next || "pop"},
{defaultToken : "comment", caseInsensitive: true}
]
}
];
}
exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
});
define("ace/mode/js",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/js","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = JavaScriptHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.$quotes = {'"': '"', "'": "'", "`": "`"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "no_regex") {
var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || endState == "no_regex") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker");
worker.attachToDocument(session.getDocument());
worker.on("annotate", function(results) {
session.setAnnotations(results.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/javascript";
}).call(Mode.prototype);
exports.Mode = Mode;
});
+2
View File
@@ -457,8 +457,10 @@
<script type="text/javascript" src="/web/static/lib/nvd3/nv.d3.js"></script>
<script type="text/javascript" src="/web/static/src/js/libs/nvd3.js"></script>
<script type="text/javascript" src="/web/static/lib/ace/ace.js"></script>
<script type="text/javascript" src="/web/static/lib/ace/javascript_highlight_rules.js"></script>
<script type="text/javascript" src="/web/static/lib/ace/mode-python.js"></script>
<script type="text/javascript" src="/web/static/lib/ace/mode-xml.js"></script>
<script type="text/javascript" src="/web/static/lib/ace/mode-js.js"></script>
<script type="text/javascript">
odoo.define('web.WebClientWithoutServices', function (require) {
+147 -121
View File
@@ -304,130 +304,149 @@ class Web_Editor(http.Controller):
## @param key - the xml_id or id of the view the resources are related to
## @param get_views - True if the views must be fetched (default to True)
## @param get_scss - True if the style must be fetched (default to True)
## @param get_js - True if the javascript must be fetched (default to True)
## @param bundles - True if the bundles views must be fetched (default to False)
## @param bundles_restriction - Names of the bundle in which to look for scss files (if empty, search in all of them)
## @param only_user_custom_files - True if only user custom files are needed (default to True)
## @returns a dictionary with views info in the views key and style info in the scss key
@http.route("/web_editor/get_assets_editor_resources", type="json", auth="user", website=True)
def get_assets_editor_resources(self, key, get_views=True, get_scss=True, bundles=False, bundles_restriction=[]):
def get_assets_editor_resources(self, key, get_views=True, get_scss=True, get_js=True, bundles=False, bundles_restriction=[], only_user_custom_files=True):
# Related views must be fetched if the user wants the views and/or the style
views = request.env["ir.ui.view"].get_related_views(key, bundles=bundles)
views = views.read(self._get_view_fields_to_read())
js_files_data_by_bundle = []
scss_files_data_by_bundle = []
# Load scss only if asked by the user
if get_js:
js_files_data_by_bundle = self.load_resources('js', views, bundles_restriction, only_user_custom_files)
if get_scss:
# Compile regex outside of the loop
# This will used to exclude library scss files from the result
excluded_url_matcher = re.compile("^(.+/lib/.+)|(.+import_bootstrap.+\.scss)$")
# Load already customized scss files attachments
custom_url = self._make_custom_scss_file_url("%%.%%", "%%")
custom_attachments = self.get_custom_attachment(custom_url, op='=like')
# First check the t-call-assets used in the related views
url_infos = dict()
for v in views:
for asset_call_node in etree.fromstring(v["arch"]).xpath("//t[@t-call-assets]"):
if asset_call_node.get("t-css") == "false":
continue
asset_name = asset_call_node.get("t-call-assets")
# Loop through bundle files to search for scss file info
scss_files_data = []
for file_info in request.env["ir.qweb"]._get_asset_content(asset_name, {})[0]:
if file_info["atype"] != "text/scss":
continue
url = file_info["url"]
# Exclude library files (see regex above)
if excluded_url_matcher.match(url):
continue
# Check if the file is customized and get bundle/path info
scss_file_data = self._match_scss_file_url(url)
if not scss_file_data:
continue
# Save info (arch will be fetched later)
url_infos[url] = scss_file_data
scss_files_data.append(url)
# scss data is returned sorted by bundle, with the bundles names and xmlids
if len(scss_files_data):
scss_files_data_by_bundle.append([dict(xmlid=asset_name, name=request.env.ref(asset_name).name), scss_files_data])
# Filter bundles/files:
# - A file which appears in multiple bundles only appears in the first one (the first in the DOM)
# - Only keep bundles with files which appears in the asked bundles and only keep those files
for i in range(0, len(scss_files_data_by_bundle)):
bundle_1 = scss_files_data_by_bundle[i]
for j in range(0, len(scss_files_data_by_bundle)):
bundle_2 = scss_files_data_by_bundle[j]
# In unwanted bundles, keep only the files which are in wanted bundles too (_assets_helpers)
if bundle_1[0]["xmlid"] not in bundles_restriction and bundle_2[0]["xmlid"] in bundles_restriction:
bundle_1[1] = [item_1 for item_1 in bundle_1[1] if item_1 in bundle_2[1]]
for i in range(0, len(scss_files_data_by_bundle)):
bundle_1 = scss_files_data_by_bundle[i]
for j in range(i+1, len(scss_files_data_by_bundle)):
bundle_2 = scss_files_data_by_bundle[j]
# In every bundle, keep only the files which were not found in previous bundles
bundle_2[1] = [item_2 for item_2 in bundle_2[1] if item_2 not in bundle_1[1]]
# Only keep bundles which still have files and that were requested
scss_files_data_by_bundle = [
data for data in scss_files_data_by_bundle
if (len(data[1]) > 0 and (not bundles_restriction or data[0]["xmlid"] in bundles_restriction))
]
# Fetch the arch of each kept file, in each bundle
for bundle_data in scss_files_data_by_bundle:
for i in range(0, len(bundle_data[1])):
url = bundle_data[1][i]
url_info = url_infos[url]
content = None
if url_info["customized"]:
# If the file is already customized, the content is found in the corresponding attachment
content = base64.b64decode(custom_attachments.filtered(lambda a: a.url == url).datas)
else:
# If the file is not yet customized, the content is found by reading the local scss file
module = url_info["module"]
module_path = get_module_path(module)
module_resource_path = get_resource_path(module, url_info["resource_path"])
if module_path and module_resource_path:
module_path = os.path.join(os.path.normpath(module_path), '') # join ensures the path ends with '/'
module_resource_path = os.path.normpath(module_resource_path)
if module_resource_path.startswith(module_path):
with open(module_resource_path, "rb") as f:
content = f.read()
bundle_data[1][i] = dict(
url = "/%s/%s" % (url_info["module"], url_info["resource_path"]),
arch = content,
customized = url_info["customized"],
)
scss_files_data_by_bundle = self.load_resources('scss', views, bundles_restriction, only_user_custom_files)
return dict(
views = get_views and views or [],
scss = get_scss and scss_files_data_by_bundle or [],
views=get_views and views or [],
scss=get_scss and scss_files_data_by_bundle or [],
js=get_js and js_files_data_by_bundle or [],
)
def save_scss_view_hook(self):
def load_resources(self, file_type, views, bundles_restriction, only_user_custom_files):
files_data_by_bundle = []
resources_type_info = {'t_call_assets_attribute': 't-js', 'mimetype': 'text/javascript'}
if file_type == 'scss':
resources_type_info = {'t_call_assets_attribute': 't-css', 'mimetype': 'text/scss'}
# Compile regex outside of the loop
# This will used to exclude library scss files from the result
excluded_url_matcher = re.compile("^(.+/lib/.+)|(.+import_bootstrap.+\.scss)$")
# Load already customized files attachments
custom_url = self._make_custom_scss_or_js_file_url("%%.%%", "%%")
custom_attachments = self.get_custom_attachment(custom_url, op='=like')
# First check the t-call-assets used in the related views
url_infos = dict()
for v in views:
for asset_call_node in etree.fromstring(v["arch"]).xpath("//t[@t-call-assets]"):
if asset_call_node.get(resources_type_info['t_call_assets_attribute']) == "false":
continue
asset_name = asset_call_node.get("t-call-assets")
# Loop through bundle files to search for file info
files_data = []
for file_info in request.env["ir.qweb"]._get_asset_content(asset_name, {})[0]:
if file_info["atype"] != resources_type_info['mimetype']:
continue
url = file_info["url"]
# Exclude library files (see regex above)
if excluded_url_matcher.match(url):
continue
# Check if the file is customized and get bundle/path info
file_data = self._match_scss_or_js_file_url(url)
if not file_data:
continue
# Save info according to the filter (arch will be fetched later)
url_infos[url] = file_data
if '/user_custom_' in url \
or file_data['customized'] \
or file_type == 'scss' and not only_user_custom_files:
files_data.append(url)
# File data is returned sorted by bundle, with the bundles names and xmlids
if len(files_data):
files_data_by_bundle.append([dict(xmlid=asset_name, name=request.env.ref(asset_name).name), files_data])
# Filter bundles/files:
# - A file which appears in multiple bundles only appears in the first one (the first in the DOM)
# - Only keep bundles with files which appears in the asked bundles and only keep those files
for i in range(0, len(files_data_by_bundle)):
bundle_1 = files_data_by_bundle[i]
for j in range(0, len(files_data_by_bundle)):
bundle_2 = files_data_by_bundle[j]
# In unwanted bundles, keep only the files which are in wanted bundles too (_assets_helpers)
if bundle_1[0]["xmlid"] not in bundles_restriction and bundle_2[0]["xmlid"] in bundles_restriction:
bundle_1[1] = [item_1 for item_1 in bundle_1[1] if item_1 in bundle_2[1]]
for i in range(0, len(files_data_by_bundle)):
bundle_1 = files_data_by_bundle[i]
for j in range(i + 1, len(files_data_by_bundle)):
bundle_2 = files_data_by_bundle[j]
# In every bundle, keep only the files which were not found in previous bundles
bundle_2[1] = [item_2 for item_2 in bundle_2[1] if item_2 not in bundle_1[1]]
# Only keep bundles which still have files and that were requested
files_data_by_bundle = [
data for data in files_data_by_bundle
if (len(data[1]) > 0 and (not bundles_restriction or data[0]["xmlid"] in bundles_restriction))
]
# Fetch the arch of each kept file, in each bundle
for bundle_data in files_data_by_bundle:
for i in range(0, len(bundle_data[1])):
url = bundle_data[1][i]
url_info = url_infos[url]
content = None
if url_info["customized"]:
# If the file is already customized, the content is found in the corresponding attachment
content = base64.b64decode(custom_attachments.filtered(lambda a: a.url == url).datas)
else:
# If the file is not yet customized, the content is found by reading the local scss file
module = url_info["module"]
module_path = get_module_path(module)
module_resource_path = get_resource_path(module, url_info["resource_path"])
if module_path and module_resource_path:
module_path = os.path.join(os.path.normpath(module_path), '') # join ensures the path ends with '/'
module_resource_path = os.path.normpath(module_resource_path)
if module_resource_path.startswith(module_path):
with open(module_resource_path, "rb") as f:
content = f.read()
bundle_data[1][i] = dict(
url="/%s/%s" % (url_info["module"], url_info["resource_path"]),
arch=content,
customized=url_info["customized"],
)
return files_data_by_bundle
def save_scss_or_js_view_hook(self):
return {}
def save_scss_attachment_hook(self):
def save_scss_or_js_attachment_hook(self):
return {}
## The save_scss route is in charge of saving a given modification of a scss file.
## @param url - the original url of the scss file which has to be modified
## @param bundle_xmlid - the xmlid of the bundle in which the scss file addition can be found
## @param content - the new content of the scss file
@http.route("/web_editor/save_scss", type="json", auth="user", website=True)
def save_scss(self, url, bundle_xmlid, content):
## The save_scss_or_js route is in charge of saving a given modification of a scss/js file.
## @param url - the original url of the scss/js file which has to be modified
## @param bundle_xmlid - the xmlid of the bundle in which the scss/js file addition can be found
## @param content - the new content of the scss/js file
## @param file_type - scss or js
@http.route("/web_editor/save_scss_or_js", type="json", auth="user", website=True)
def save_scss_or_js(self, url, bundle_xmlid, content, file_type):
IrAttachment = request.env["ir.attachment"]
custom_url = self._make_custom_scss_file_url(url, bundle_xmlid)
custom_url = self._make_custom_scss_or_js_file_url(url, bundle_xmlid)
# Check if the file to save had already been modified
custom_attachment = self.get_custom_attachment(custom_url)
@@ -436,20 +455,24 @@ class Web_Editor(http.Controller):
# If it was already modified, simply override the corresponding attachment content
custom_attachment.write({"datas": datas})
else:
# If not, create a new attachment to copy the original scss file content, with its modifications
# If not, create a new attachment to copy the original scss/js file content, with its modifications
new_attach = {
'name': custom_url,
'type': "binary",
'mimetype': "text/scss",
'mimetype': (file_type == 'js' and 'text/javascript' or 'text/scss'),
'datas': datas,
'datas_fname': url.split("/")[-1],
'url': custom_url,
}
new_attach.update(self.save_scss_attachment_hook())
new_attach.update(self.save_scss_or_js_attachment_hook())
IrAttachment.create(new_attach)
# Create a view to extend the template which adds the original file to link the new modified version instead
IrUiView = request.env["ir.ui.view"]
file_type_info = {
'tag': 'link' if file_type == 'scss' else 'script',
'attribute': 'href' if file_type == 'scss' else 'src',
}
def views_linking_url(view):
"""
@@ -457,19 +480,22 @@ class Web_Editor(http.Controller):
(note: searching for the URL string is not enough as it could appear in a comment or an xpath expression.)
"""
return bool(etree.XML(view.arch).xpath("//link[@href='{}']".format(url)))
tree = etree.XML(view.arch)
return bool(tree.xpath("//%%(tag)s[@%%(attribute)s='%(url)s']" % {
'url': url,
} % file_type_info))
view_to_xpath = IrUiView.get_related_views(bundle_xmlid, bundles=True).filtered(views_linking_url)
new_view = {
'name': custom_url,
'key': 'web_editor.scss_%s' % str(uuid.uuid4())[:6],
'key': 'web_editor.%s_%s' % (file_type, str(uuid.uuid4())[:6]),
'mode': "extension",
'inherit_id': view_to_xpath.id,
'arch': """
<data inherit_id="%(inherit_xml_id)s" name="%(name)s">
<xpath expr="//link[@href='%(url_to_replace)s']" position="attributes">
<attribute name="href">%(new_url)s</attribute>
<xpath expr="//%%(tag)s[@%%(attribute)s='%(url_to_replace)s']" position="attributes">
<attribute name="%%(attribute)s">%(new_url)s</attribute>
</xpath>
</data>
""" % {
@@ -477,21 +503,21 @@ class Web_Editor(http.Controller):
'name': custom_url,
'url_to_replace': url,
'new_url': custom_url,
}
} % file_type_info
}
new_view.update(self.save_scss_view_hook())
new_view.update(self.save_scss_or_js_view_hook())
IrUiView.create(new_view)
request.env["ir.qweb"].clear_caches()
## The reset_scss route is in charge of reverting all the changes that were done to a scss file.
## The reset_scss_or_js route is in charge of reverting all the changes that were done to a scss/js file.
## @param url - the original URL of the scss file to reset
## @param bundle_xmlid - the xmlid of the bundle in which the scss file addition can be found
@http.route("/web_editor/reset_scss", type="json", auth="user", website=True)
def reset_scss(self, url, bundle_xmlid):
custom_url = self._make_custom_scss_file_url(url, bundle_xmlid)
@http.route("/web_editor/reset_scss_or_js", type="json", auth="user", website=True)
def reset_scss_or_js(self, url, bundle_xmlid):
custom_url = self._make_custom_scss_or_js_file_url(url, bundle_xmlid)
# Simply delete the attachement which contains the modified scss file and the xpath view which links it
# Simply delete the attachement which contains the modified scss/js file and the xpath view which links it
self.get_custom_attachment(custom_url).unlink()
self.get_custom_view(custom_url).unlink()
@@ -505,13 +531,13 @@ class Web_Editor(http.Controller):
IrUiView = request.env["ir.ui.view"]
return IrUiView.search([("name", op, custom_url)])
def _make_custom_scss_file_url(self, url, bundle):
def _make_custom_scss_or_js_file_url(self, url, bundle):
parts = url.rsplit(".", 1)
return "%s.custom.%s.%s" % (parts[0], bundle, parts[1])
_match_scss_file_url_regex = re.compile("^/(\w+)/(.+?)(\.custom\.(.+))?\.(\w+)$")
def _match_scss_file_url(self, url):
m = self._match_scss_file_url_regex.match(url)
_match_file_url_regex = re.compile("^/(\w+)/(.+?)(\.custom\.(.+))?\.(\w+)$")
def _match_scss_or_js_file_url(self, url):
m = self._match_file_url_regex.match(url)
if not m:
return False
return {
+132 -69
View File
@@ -119,20 +119,22 @@ var ViewEditor = Widget.extend({
jsLibs: [
'/web/static/lib/ace/ace.js',
[
'/web/static/lib/ace/javascript_highlight_rules.js',
'/web/static/lib/ace/mode-xml.js',
'/web/static/lib/ace/mode-scss.js',
'/web/static/lib/ace/mode-js.js',
'/web/static/lib/ace/theme-monokai.js'
]
],
events: {
'click .o_ace_type_switcher_choice': '_onTypeChoice',
'change .o_res_list': '_onResChange',
'click .js_include_bundles': '_onIncludeBundlesChange',
'click .js_include_all_scss': '_onIncludeAllSCSSChange',
'click .o_ace_filter': '_onFilterChange',
'click button[data-action=save]': '_onSaveClick',
'click button[data-action=reset]': '_onResetClick',
'click button[data-action=format]': '_onFormatClick',
'click button[data-action=close]': '_onCloseClick',
'click #ace-view-id > .alert-warning .close': '_onCloseWarningClick'
},
/**
@@ -150,8 +152,9 @@ var ViewEditor = Widget.extend({
* @param {string} [options.position=right]
* @param {boolean} [options.doNotLoadViews=false]
* @param {boolean} [options.doNotLoadSCSS=false]
* @param {boolean} [options.doNotLoadJS=false]
* @param {boolean} [options.includeBundles=false]
* @param {boolean} [options.includeAllSCSS=false]
* @param {string} [options.filesFilter=custom]
* @param {string[]} [options.defaultBundlesRestriction]
*/
init: function (parent, viewKey, options) {
@@ -164,18 +167,20 @@ var ViewEditor = Widget.extend({
position: 'right',
doNotLoadViews: false,
doNotLoadSCSS: false,
doNotLoadJS: false,
includeBundles: false,
includeAllSCSS: false,
filesFilter: 'custom',
defaultBundlesRestriction: [],
});
this.resources = {xml: {}, scss: {}};
this.editingSessions = {xml: {}, scss: {}};
this.resources = {xml: {}, scss: {}, js: {}};
this.editingSessions = {xml: {}, scss: {}, js: {}};
this.currentType = 'xml';
// Alias
this.views = this.resources.xml;
this.scss = this.resources.scss;
this.js = this.resources.js;
},
/**
* Loads everything the ace library needs to work.
@@ -204,11 +209,13 @@ var ViewEditor = Widget.extend({
this.$lists = {
xml: this.$('#ace-view-list'),
scss: this.$('#ace-scss-list')
scss: this.$('#ace-scss-list'),
js: this.$('#ace-js-list'),
};
this.$includeBundlesArea = this.$('.oe_include_bundles');
this.$includeAllSCSSArea = this.$('.o_include_all_scss');
this.$viewID = this.$('#ace-view-id > span');
this.$warningMessage = this.$('#ace-view-id > .alert-warning');
this.$formatButton = this.$('button[data-action=format]');
this.$resetButton = this.$('button[data-action=reset]');
@@ -228,12 +235,24 @@ var ViewEditor = Widget.extend({
var initType;
if (this.options.initialResID) {
initResID = this.options.initialResID;
initType = (_.isString(initResID) && initResID[0] === '/') ? 'scss' : 'xml';
if (_.isString(initResID) && initResID[0] === '/') {
if (_.str.endsWith(initResID, '.scss')) {
initType = 'scss';
} else {
initType = 'js';
}
} else {
initType = 'xml';
}
} else {
if (!this.options.doNotLoadSCSS) {
initResID = this.sortedSCSS[0][1][0].url; // first bundle, scss files, first one
initType = 'scss';
}
if (!this.options.doNotLoadJS) {
initResID = this.sortedJS[0][1][0].url; // first bundle, js files, first one
initType = 'js';
}
if (!this.options.doNotLoadViews) {
if (typeof this.viewKey === "number") {
initResID = this.viewKey;
@@ -321,7 +340,7 @@ var ViewEditor = Widget.extend({
* Initializes a text editor for the specified resource.
*
* @private
* @param {integer|string} resID - the ID/URL of the view/scss file
* @param {integer|string} resID - the ID/URL of the view/scss/js file
* @param {string} [type] (default to the currently selected one)
* @returns {ace.EditSession}
*/
@@ -341,13 +360,13 @@ var ViewEditor = Widget.extend({
return editingSession;
},
/**
* Forces the view/scss file identified by its ID/URL to be displayed in the
* Forces the view/scss/js file identified by its ID/URL to be displayed in the
* editor. The method will update the resource select DOM element as well if
* necessary.
*
* @private
* @param {integer|string} resID
* @param {string} [type] - the type of resource (either 'xml' or 'scss')
* @param {string} [type] - the type of resource (either 'xml', 'scss' or 'js')
*/
_displayResource: function (resID, type) {
if (type) {
@@ -360,14 +379,29 @@ var ViewEditor = Widget.extend({
}
this.aceEditor.setSession(editingSession);
var isCustomized = false;
if (this.currentType === 'xml') {
this.$viewID.text(_.str.sprintf(_t("Template ID: %s"), this.views[resID].key));
} else {
} else if (this.currentType === 'scss') {
isCustomized = this.scss[resID].customized;
this.$viewID.text(_.str.sprintf(_t("SCSS file: %s"), resID));
} else {
isCustomized = this.js[resID].customized;
this.$viewID.text(_.str.sprintf(_t("JS file: %s"), resID));
}
this.$lists[this.currentType].select2('val', resID);
this.$resetButton.toggleClass('d-none', this.currentType === 'xml' || !this.scss[resID].customized);
this.$resetButton.toggleClass('d-none', this.currentType === 'xml' || !isCustomized);
// TODO the warning message is always shown for XML templates but:
// 1) We have to implement a way to be able to reset XML templates
// otherwise the warning message is not accurate
// 2) We should be able to detect if the XML template is customized to
// not show the warning in that case
this.$warningMessage.toggleClass('d-none',
this.currentType !== 'xml' && (resID.indexOf('/user_custom_') >= 0 || isCustomized));
this.aceEditor.resize(true);
},
/**
* Formats the current resource being vizualized.
@@ -403,10 +437,11 @@ var ViewEditor = Widget.extend({
*/
_loadResources: function () {
// Reset resources
this.resources = {xml: {}, scss: {}};
this.editingSessions = {xml: {}, scss: {}};
this.resources = {xml: {}, scss: {}, js: {}};
this.editingSessions = {xml: {}, scss: {}, js: {}};
this.views = this.resources.xml;
this.scss = this.resources.scss;
this.js = this.resources.js;
// Load resources
return this._rpc({
@@ -415,12 +450,15 @@ var ViewEditor = Widget.extend({
key: this.viewKey,
get_views: !this.options.doNotLoadViews,
get_scss: !this.options.doNotLoadSCSS,
get_js: !this.options.doNotLoadJS,
bundles: this.options.includeBundles,
bundles_restriction: this.options.includeAllSCSS ? [] : this.options.defaultBundlesRestriction,
bundles_restriction: this.options.filesFilter === 'all' ? [] : this.options.defaultBundlesRestriction,
only_user_custom_files: this.options.filesFilter === 'custom',
},
}).then((function (resources) {
_processViews.call(this, resources.views || []);
_processSCSS.call(this, resources.scss || []);
_processJSorSCSS.call(this, resources.scss || [], 'scss');
_processJSorSCSS.call(this, resources.js || [], 'js');
}).bind(this));
function _processViews(views) {
@@ -461,20 +499,24 @@ var ViewEditor = Widget.extend({
});
}
function _processSCSS(scss) {
// The received scss data is already sorted by bundle and DOM order
this.sortedSCSS = scss;
function _processJSorSCSS(data, type) {
// The received scss or js data is already sorted by bundle and DOM order
if (type === 'scss') {
this.sortedSCSS = data;
} else {
this.sortedJS = data;
}
// Store the URL ungrouped by bundle and use the URL as key (resource ID)
var self = this;
_.each(scss, function (bundleInfos) {
var resources = type === 'scss' ? this.scss : this.js;
_.each(data, function (bundleInfos) {
_.each(bundleInfos[1], function (info) { info.bundle_xmlid = bundleInfos[0].xmlid; });
_.extend(self.scss, _.indexBy(bundleInfos[1], 'url'));
_.extend(resources, _.indexBy(bundleInfos[1], 'url'));
});
}
},
/**
* Forces the view/scss file identified by its ID/URL to be reset to the way
* Forces the view/scss/js file identified by its ID/URL to be reset to the way
* it was before the user started editing it.
*
* @todo views reset is not supported yet
@@ -491,37 +533,42 @@ var ViewEditor = Widget.extend({
if (this.currentType === 'xml') {
return $.Defered().reject(_t("Reseting views is not supported yet"));
} else {
var resource = type === 'scss' ? this.scss[resID] : this.js[resID];
return this._rpc({
route: '/web_editor/reset_scss',
route: '/web_editor/reset_scss_or_js',
params: {
url: resID,
bundle_xmlid: this.scss[resID].bundle_xmlid,
bundle_xmlid: resource.bundle_xmlid,
},
});
}
},
/**
* Saves an unique SCSS file.
* Saves an unique SCSS or JS file.
*
* @private
* @param {Object} session - contains the 'id' (url) and the 'text' of the
* SCSS file to save.
* SCSS or JS file to save.
* @return {Deferred} status indicates if the save is finished or if an
* error occured.
*/
_saveSCSS: function (session) {
_saveSCSSorJS: function (session) {
var def = $.Deferred();
var self = this;
this._rpc({
route: '/web_editor/save_scss',
var sessionIdEndsWithJS = _.string.endsWith(session.id, '.js');
var bundleXmlID = sessionIdEndsWithJS ? this.js[session.id].bundle_xmlid : this.scss[session.id].bundle_xmlid;
var fileType = sessionIdEndsWithJS ? 'js' : 'scss';
self._rpc({
route: '/web_editor/save_scss_or_js',
params: {
url: session.id,
bundle_xmlid: this.scss[session.id].bundle_xmlid,
bundle_xmlid: bundleXmlID,
content: session.text,
file_type: fileType,
},
}).then(function () {
self._toggleDirtyInfo(session.id, 'scss', false);
self._toggleDirtyInfo(session.id, fileType, false);
def.resolve();
}, function (source, error) {
def.reject(session, error);
@@ -572,7 +619,7 @@ var ViewEditor = Widget.extend({
_toSave = _.sortBy(_toSave, 'id').reverse();
_.each(_toSave, function (session) {
defs.push(mutex.exec(function () {
return (type === 'xml' ? self._saveView(session) : self._saveSCSS(session));
return (type === 'xml' ? self._saveView(session) : self._saveSCSSorJS(session));
}));
});
}).bind(this));
@@ -665,11 +712,11 @@ var ViewEditor = Widget.extend({
}
},
/**
* Switches to the SCSS or XML edition. Calling this method will adapt all
* Switches to the SCSS, XML or JS edition. Calling this method will adapt all
* DOM elements to keep the editor consistent.
*
* @private
* @param {string} type - either 'xml' or 'scss'
* @param {string} type - either 'xml', 'scss' or 'js'
*/
_switchType: function (type) {
this.currentType = type;
@@ -677,9 +724,10 @@ var ViewEditor = Widget.extend({
_.each(this.$lists, function ($list, _type) { $list.toggleClass('d-none', type !== _type); });
this.$lists[type].change();
this.$includeBundlesArea.toggleClass('d-none', this.currentType === 'scss' || !session.debug);
this.$includeAllSCSSArea.toggleClass('d-none', this.currentType === 'xml' || !session.debug || this.options.defaultBundlesRestriction.length === 0);
this.$formatButton.toggleClass('d-none', this.currentType === 'scss');
this.$includeBundlesArea.toggleClass('d-none', this.currentType !== 'xml' || !session.debug);
this.$includeAllSCSSArea.toggleClass('d-none', this.currentType !== 'scss' || !session.debug);
this.$includeAllSCSSArea.find('[data-value="restricted"]').toggleClass('d-none', this.options.defaultBundlesRestriction.length === 0);
this.$formatButton.toggleClass('d-none', this.currentType !== 'xml');
},
/**
* Updates the select option DOM element associated with a particular resID
@@ -724,21 +772,10 @@ var ViewEditor = Widget.extend({
});
this.$lists.scss.empty();
_.each(this.sortedSCSS, function (bundleInfos) {
var $optgroup = $('<optgroup/>', {
label: bundleInfos[0].name,
}).appendTo(self.$lists.scss);
_.each(bundleInfos[1], function (scssInfo) {
var name = scssInfo.url.substring(_.lastIndexOf(scssInfo.url, '/') + 1, scssInfo.url.length - 5);
$optgroup.append($('<option/>', {
value: scssInfo.url,
text: name,
selected: currentId === scssInfo.url,
'data-debug': scssInfo.url,
'data-customized': scssInfo.customized
}));
});
});
_populateList(this.sortedSCSS, this.$lists.scss, 5);
this.$lists.js.empty();
_populateList(this.sortedJS, this.$lists.js, 3);
this.$lists.xml.select2('destroy');
this.$lists.xml.select2({
@@ -752,6 +789,30 @@ var ViewEditor = Widget.extend({
formatSelection: _formatDisplay.bind(this, true),
});
this.$lists.scss.data('select2').dropdown.addClass('o_ace_select2_dropdown');
this.$lists.js.select2('destroy');
this.$lists.js.select2({
formatResult: _formatDisplay.bind(this, false),
formatSelection: _formatDisplay.bind(this, true),
});
this.$lists.js.data('select2').dropdown.addClass('o_ace_select2_dropdown');
function _populateList(sortedData, $list, lettersToRemove) {
_.each(sortedData, function (bundleInfos) {
var $optgroup = $('<optgroup/>', {
label: bundleInfos[0].name,
}).appendTo($list);
_.each(bundleInfos[1], function (dataInfo) {
var name = dataInfo.url.substring(_.lastIndexOf(dataInfo.url, '/') + 1, dataInfo.url.length - lettersToRemove);
$optgroup.append($('<option/>', {
value: dataInfo.url,
text: name,
selected: currentId === dataInfo.url,
'data-debug': dataInfo.url,
'data-customized': dataInfo.customized
}));
});
});
}
function _formatDisplay(isSelected, data) {
var $elem = $(data.element);
@@ -803,25 +864,20 @@ var ViewEditor = Widget.extend({
this._formatResource();
},
/**
* Called when the checkbox which indicates if all SCSS should be included
* is toggled -> reloads the resources accordingly.
* Called when a filter dropdown item is cliked. Reload the resources
* according to the new filter and make it visually active.
*
* @private
* @param {Event} ev
*/
_onIncludeAllSCSSChange: function (ev) {
this.options.includeAllSCSS = $(ev.target).prop('checked');
this._loadResources().then(this._updateViewSelectDOM.bind(this));
},
/**
* Called when the checkbox which indicates if assets bundles should be
* included is toggled -> reloads the resources accordingly.
*
* @private
* @param {Event} ev
*/
_onIncludeBundlesChange: function (ev) {
this.options.includeBundles = $(ev.target).prop('checked');
_onFilterChange: function (ev) {
var $item = $(ev.target);
$item.addClass('active').siblings().removeClass('active');
if ($item.data('type') === 'xml') {
this.options.includeBundles = $(ev.target).data('value') === 'all';
} else {
this.options.filesFilter = $item.data('value');
}
this._loadResources().then(this._updateViewSelectDOM.bind(this));
},
/**
@@ -867,6 +923,13 @@ var ViewEditor = Widget.extend({
ev.preventDefault();
this._switchType($(ev.target).data('type'));
},
/**
* Allows to hide the warning message without removing it from the DOM
* -> by default Bootstrap removes alert from the DOM
*/
_onCloseWarningClick: function () {
this.$warningMessage.addClass('d-none');
},
});
return ViewEditor;
+27 -14
View File
@@ -9,26 +9,33 @@
<div class="dropdown-menu" role="menu">
<a role="menuitem" href="#" class="dropdown-item o_ace_type_switcher_choice" data-type="xml">XML (HTML)</a>
<a role="menuitem" href="#" class="dropdown-item o_ace_type_switcher_choice" data-type="scss">SCSS (CSS)</a>
<a role="menuitem" href="#" class="dropdown-item o_ace_type_switcher_choice" data-type="js">JS</a>
</div>
</div>
<select id="ace-view-list" class="o_res_list"/>
<select id="ace-scss-list" class="o_res_list d-none"/>
<select id="ace-js-list" class="o_res_list d-none"/>
<label class="o_include_option oe_include_bundles">
<div class="custom-control custom-checkbox">
<input type="checkbox" id="o_ace_view_editor_include_bundle"
class="custom-control-input js_include_bundles"
t-att-checked="widget.options.includeBundles ? 'checked' : undefined"/>
<label for="o_ace_view_editor_include_bundle"
class="custom-control-label">Include Asset Bundles</label>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="o_dropdown_filter_views" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Filter
</button>
<div class="dropdown-menu" aria-labelledby="o_dropdown_filter_views">
<a class="dropdown-item o_ace_filter active" data-type="xml" data-value="default" href="#">Only Views</a>
<a class="dropdown-item o_ace_filter" data-type="xml" data-value="all" href="#">Views and Assets bundles</a>
</div>
</div>
</label>
<label class="o_include_option o_include_all_scss d-none">
<div class="custom-control custom-checkbox">
<input type="checkbox" id="o_ace_view_editor_include_all_scss"
class="custom-control-input js_include_all_scss"
t-att-checked="widget.options.includeAllSCSS ? 'checked' : undefined"/>
<label for="o_ace_view_editor_include_all_scss"
class="custom-control-label">Include All SCSS Files</label>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="o_dropdown_filter_assets" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Filter
</button>
<div class="dropdown-menu" aria-labelledby="o_dropdown_filter_assets">
<a class="dropdown-item o_ace_filter active" data-type="scss" data-value="custom" href="#">Only Custom SCSS Files</a>
<a class="dropdown-item o_ace_filter" data-type="scss" data-value="restricted" href="#">Only Page SCSS Files</a>
<a class="dropdown-item o_ace_filter" data-type="scss" data-value="all" href="#">All SCSS Files</a>
</div>
</div>
</label>
<div class="o_button_section">
@@ -37,11 +44,17 @@
</div>
</div>
<div id="ace-view-id">
<span/>
<div class="float-right">
<div class="float-right mb-2">
<button data-action="reset" type="button" class="btn btn-sm btn-danger"><i class="fa fa-undo"/> Reset</button>
<button data-action="format" type="button" class="btn btn-sm btn-link">Format</button>
</div>
<span/>
<div class="alert alert-warning alert-dismissible mt-2 mb-0" role="alert">
If you edit and save this file, you will never receive updates anymore unless you reset your customizations.
<button type="button" class="close" aria-label="Close">
<span>&amp;times;</span>
</button>
</div>
</div>
<div id="ace-view-editor"/>
</div>
+4 -4
View File
@@ -11,16 +11,16 @@ class Web_Editor(Web_Editor):
res.append('website_id')
return res
def save_scss_view_hook(self):
res = super(Web_Editor, self).save_scss_view_hook()
def save_scss_or_js_view_hook(self):
res = super(Web_Editor, self).save_scss_or_js_view_hook()
website = request.env['website'].get_current_website()
if website:
res['website_id'] = website.id
return res
def save_scss_attachment_hook(self):
res = super(Web_Editor, self).save_scss_attachment_hook()
def save_scss_or_js_attachment_hook(self):
res = super(Web_Editor, self).save_scss_or_js_attachment_hook()
website = request.env['website'].get_current_website()
if website:
@@ -0,0 +1,24 @@
//
// This file is meant to regroup your javascript code. You can either copy/past
// any code that should be executed on each page loading or write your own
// taking advantage of the Odoo framework to create new behaviors or modify
// existing ones. For example, doing this will greet any visitor with a 'Hello,
// world !' message in a popup:
//
/*
odoo.define('website.user_custom_code', function (require) {
'use strict';
var Dialog = require('web.Dialog');
var sAnimations = require('website.content.snippets.animation');
sAnimations.registry.HelloWorldPopup = sAnimations.Class.extend({
selector: '#wrapwrap',
start: function () {
Dialog.alert(this, "Hello, world!");
return this._super.apply(this, arguments);
},
})
});
*/
@@ -467,8 +467,10 @@ var ThemeCustomizeDialog = Dialog.extend({
key: 'website.layout',
get_views: false,
get_scss: true,
get_js: false,
bundles: false,
bundles_restriction: [],
only_user_custom_files: false,
},
}).then(function (data) {
var files = data.scss[0][1];
@@ -501,11 +503,12 @@ var ThemeCustomizeDialog = Dialog.extend({
});
return self._rpc({
route: '/web_editor/save_scss',
route: '/web_editor/save_scss_or_js',
params: {
url: file.url,
bundle_xmlid: 'web.assets_common',
content: updatedFileContent,
file_type: 'scss',
},
});
}).then(function () {
@@ -0,0 +1,22 @@
//
// /!\
// This file is meant to regroup your bootstrap customizations. In that file,
// you must define variables *ONLY*. If you want to introduce new CSS rules
// for your website, check the 'user_custom_rules.scss' file you can also edit.
// /!\
//
// You can change the value of a variable you can find in the bootstrap 4
// documentation (or in the file /web/static/lib/bootstrap/scss/_variables.scss)
// and Odoo will automatically adapt its design to your new bootstrap. For
// example, doing this will make some shadows and gradients appear, especially
// for your buttons design:
//
// $enable-shadows: true;
// $enable-gradients: true;
//
// Notice that Odoo already overrides bootstrap variables according to your
// choices in the "Customize Theme" dialog, you should first take a look at
// it and do customizations this way. Indeed, if you overridde the same
// variables, Odoo will either have to ignore them or not be able to make
// the "Customize Theme" dialog work for these variables anymore.
//
@@ -0,0 +1,8 @@
//
// This file is meant to regroup your design customizations. For example, doing
// this will separate your footer with a dotted border using your primary color.
//
// footer {
// border-top: 5px dotted theme-color('primary');
// }
//
@@ -50,7 +50,7 @@
<a class="dropdown-toggle o-no-caret waves" data-toggle="dropdown" data-display="static" href="#">Customize</a>
<div class="dropdown-menu" role="menu">
<a role="menuitem" href="#" data-action="customize_theme" class="dropdown-item" id="theme_customize">Customize Theme</a>
<a role="menuitem" href="#" data-action="ace" class="dropdown-item" id="html_editor">HTML/CSS Editor</a>
<a role="menuitem" href="#" data-action="ace" class="dropdown-item" id="html_editor">HTML/CSS/JS Editor</a>
<a role="menuitem" href="/web#action=website.action_website_add_features" class="dropdown-item" id="install_apps" context="{'search_default_web_features' : 1}">Add Features</a>
<div role="separator" class="dropdown-divider"/>
</div>
@@ -33,6 +33,9 @@
<template id="_assets_frontend_helpers" inherit_id="portal._assets_frontend_helpers">
<xpath expr="//link" position="before">
<!-- Custom empty file for user custom bootstrap override -->
<link rel="stylesheet" type="text/scss" href="/website/static/src/scss/user_custom_bootstrap_overridden.scss"/>
<link rel="stylesheet" type="text/scss" href="/website/static/src/scss/bootstrap_overridden.scss"/>
</xpath>
</template>
@@ -42,6 +45,9 @@
<link rel="stylesheet" type="text/scss" href="/website/static/src/scss/website.scss"/>
<link rel="stylesheet" type="text/scss" href="/website/static/src/scss/website.ui.scss"/>
<link rel="stylesheet" type="text/scss" href="/website/static/src/scss/website.zoomodoo.scss"/>
<!-- Custom empty file for user custom rules -->
<link rel="stylesheet" type="text/scss" href="/website/static/src/scss/user_custom_rules.scss"/>
</xpath>
<xpath expr="//script[@src='/web/static/src/js/chrome/public_root_widget.js']" position="replace">
<script type="text/javascript" src="/website/static/src/js/content/website_root.js"/>
@@ -59,6 +65,9 @@
<script type="text/javascript" src="/website/static/src/js/menu/navbar.js"/>
<script type="text/javascript" src="/website/static/src/js/html_editor.test.js"/>
<!-- Custom empty file for user javascript -->
<script type="text/javascript" src="/website/static/src/js/user_custom_javascript.js"/>
</xpath>
</template>