Annotation of modules/damieng/graphical_editor/loncapa_daxe/web/loncapa_daxe.dart, revision 1.3
1.1 damieng 1: /*
2: This file is part of LON-CAPA.
3:
4: LON-CAPA is free software: you can redistribute it and/or modify
5: it under the terms of the GNU General Public License as published by
6: the Free Software Foundation, either version 3 of the License, or
7: (at your option) any later version.
8:
9: LON-CAPA is distributed in the hope that it will be useful,
10: but WITHOUT ANY WARRANTY; without even the implied warranty of
11: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12: GNU General Public License for more details.
13:
14: You should have received a copy of the GNU General Public License
15: along with LON-CAPA. If not, see <http://www.gnu.org/licenses/>.
16: */
17:
18: library loncapa_daxe;
19:
20: import 'dart:async';
21: import 'dart:collection';
22: import 'dart:html' as h;
23: import 'package:daxe/daxe.dart';
24: import 'package:daxe/src/xmldom/xmldom.dart' as x;
25: import 'package:daxe/src/strings.dart';
26: import 'package:daxe/src/nodes/nodes.dart' show DNCData, DNText, SimpleTypeControl, ParentUpdatingDNText;
27: import 'dart:js' as js;
28:
29: import 'lcd_strings.dart';
30: part 'nodes/lcd_block.dart';
31: part 'nodes/lcd_parameter.dart';
32: part 'nodes/tex_mathjax.dart';
33: part 'nodes/lm.dart';
1.2 damieng 34: part 'nodes/numerical_response.dart';
1.3 ! damieng 35: part 'nodes/formula_response.dart';
! 36: part 'nodes/string_response.dart';
1.1 damieng 37: part 'nodes/radio_response.dart';
38: part 'nodes/radio_foilgroup.dart';
39: part 'nodes/radio_foil.dart';
40: part 'nodes/option_response.dart';
41: part 'nodes/option_foilgroup.dart';
42: part 'nodes/option_foil.dart';
43: part 'nodes/rank_response.dart';
44: part 'nodes/rank_foilgroup.dart';
45: part 'nodes/rank_foil.dart';
46: part 'nodes/hintgroup.dart';
47: part 'nodes/simple_ui_text.dart';
48: part 'nodes/script_block.dart';
1.2 damieng 49: part 'nodes/simple_ui_exception.dart';
1.1 damieng 50: part 'lcd_button.dart';
51:
52:
53: void main() {
54: NodeFactory.addCoreDisplayTypes();
55:
56: addDisplayType('lcdblock',
57: (x.Element ref) => new LCDBlock.fromRef(ref),
58: (x.Node node, DaxeNode parent) => new LCDBlock.fromNode(node, parent)
59: );
60:
61: addDisplayType('texmathjax',
62: (x.Element ref) => new TeXMathJax.fromRef(ref),
63: (x.Node node, DaxeNode parent) => new TeXMathJax.fromNode(node, parent)
64: );
65:
66: addDisplayType('lm',
67: (x.Element ref) => new Lm.fromRef(ref),
68: (x.Node node, DaxeNode parent) => new Lm.fromNode(node, parent)
69: );
70:
71: addDisplayType('script',
72: (x.Element ref) => new ScriptBlock.fromRef(ref),
73: (x.Node node, DaxeNode parent) => new ScriptBlock.fromNode(node, parent)
74: );
75:
76: addDisplayType('parameter',
77: (x.Element ref) => new LCDParameter.fromRef(ref),
78: (x.Node node, DaxeNode parent) => new LCDParameter.fromNode(node, parent)
79: );
80:
1.2 damieng 81: addDisplayType('numericalresponse',
82: (x.Element ref) => new NumericalResponse.fromRef(ref),
83: (x.Node node, DaxeNode parent) => new NumericalResponse.fromNode(node, parent)
84: );
85:
1.3 ! damieng 86: addDisplayType('formularesponse',
! 87: (x.Element ref) => new FormulaResponse.fromRef(ref),
! 88: (x.Node node, DaxeNode parent) => new FormulaResponse.fromNode(node, parent)
! 89: );
! 90:
! 91: addDisplayType('stringresponse',
! 92: (x.Element ref) => new StringResponse.fromRef(ref),
! 93: (x.Node node, DaxeNode parent) => new StringResponse.fromNode(node, parent)
! 94: );
! 95:
1.1 damieng 96: addDisplayType('radioresponse',
97: (x.Element ref) => new RadioResponse.fromRef(ref),
98: (x.Node node, DaxeNode parent) => new RadioResponse.fromNode(node, parent)
99: );
100:
101: addDisplayType('optionresponse',
102: (x.Element ref) => new OptionResponse.fromRef(ref),
103: (x.Node node, DaxeNode parent) => new OptionResponse.fromNode(node, parent)
104: );
105:
106: addDisplayType('rankresponse',
107: (x.Element ref) => new RankResponse.fromRef(ref),
108: (x.Node node, DaxeNode parent) => new RankResponse.fromNode(node, parent)
109: );
110:
111: addDisplayType('foilgroup',
112: (x.Element ref) {
113: if (ref.getAttribute('type') == 'radiobuttonresponse--foilgroup')
114: return new RadioFoilgroup.fromRef(ref);
115: else if (ref.getAttribute('type') == 'optionresponse--foilgroup')
116: return new OptionFoilgroup.fromRef(ref);
117: else if (ref.getAttribute('type') == 'rankresponse--foilgroup')
118: return new RankFoilgroup.fromRef(ref);
119: return new LCDBlock.fromRef(ref);
120: },
121: (x.Node node, DaxeNode parent) {
122: if (parent is RadioResponse)
123: return new RadioFoilgroup.fromNode(node, parent);
124: else if (parent is OptionResponse)
125: return new OptionFoilgroup.fromNode(node, parent);
126: else if (parent is RankResponse)
127: return new RankFoilgroup.fromNode(node, parent);
128: return new LCDBlock.fromNode(node, parent);
129: }
130: );
131:
132: addDisplayType('foil',
133: (x.Element ref) {
134: if (ref.getAttribute('type') == 'radiobuttonresponse--foil')
135: return new RadioFoil.fromRef(ref);
136: else if (ref.getAttribute('type') == 'optionresponse--foil')
137: return new OptionFoil.fromRef(ref);
138: else if (ref.getAttribute('type') == 'rankresponse--foil')
139: return new RankFoil.fromRef(ref);
140: return new LCDBlock.fromRef(ref);
141: },
142: (x.Node node, DaxeNode parent) {
143: if (parent is RadioFoilgroup)
144: return new RadioFoil.fromNode(node, parent);
145: else if (parent is OptionFoilgroup)
146: return new OptionFoil.fromNode(node, parent);
147: else if (parent is RankFoilgroup)
148: return new RankFoil.fromNode(node, parent);
149: return new LCDBlock.fromNode(node, parent);
150: }
151: );
152:
153: addDisplayType('hintgroup',
154: (x.Element ref) => new Hintgroup.fromRef(ref),
155: (x.Node node, DaxeNode parent) => new Hintgroup.fromNode(node, parent)
156: );
157:
158: Future.wait([Strings.load(), LCDStrings.load(), _readTemplates('templates.xml')]).then((List responses) {
159: _init_daxe().then((v) {
160: // add things to the toolbar
161: ToolbarMenu sectionMenu = _makeSectionMenu();
162: if (sectionMenu != null)
163: page.toolbar.add(sectionMenu);
164: x.Element texRef = doc.cfg.elementReference('m');
165: if (texRef != null) {
166: ToolbarBox insertBox = new ToolbarBox();
167: ToolbarButton texButton = new ToolbarButton(
168: LCDStrings.get('tex_equation'), 'images/tex.png',
169: () => doc.insertNewNode(texRef, 'element'), Toolbar.insertButtonUpdate,
170: data:new ToolbarStyleInfo([texRef], null, null));
171: insertBox.add(texButton);
172: page.toolbar.add(insertBox);
173: }
174: h.Element tbh = h.querySelector('.toolbar');
175: tbh.replaceWith(page.toolbar.html());
176: page.adjustPositionsUnderToolbar();
177: page.updateAfterPathChange();
178: // add things to the menubar
179: if (responses[2] is x.Document) {
180: // at this point the menubar html is already in the document, so we have to fix the HTML
181: h.Element menubarDiv = h.document.getElementsByClassName('menubar')[0];
182: if (doc.filePath.indexOf('&url=') != -1) { // otherwise we are not on LON-CAPA
183: MenuItem item = new MenuItem(Strings.get('menu.save'), () => save(), shortcut: 'S');
184: Menu fileMenu = page.mbar.menus[0];
185: fileMenu.add(item);
186: menubarDiv.firstChild.replaceWith(page.mbar.createMenuDiv(fileMenu));
187: }
188: Menu m = _makeTemplatesMenu(responses[2]);
189: page.mbar.add(m);
190: menubarDiv.append(page.mbar.createMenuDiv(m));
191: page.updateAfterPathChange();
192: } else
193: print("Error reading templates file, could not build the menu.");
194: });
195: });
196: }
197:
198: Future _init_daxe() {
199: Completer completer = new Completer();
200: doc = new DaxeDocument();
201: page = new WebPage();
202:
203: // check parameters for a config and file to open
204: String file = null;
205: String config = null;
206: String saveURL = null;
207: h.Location location = h.window.location;
208: String search = location.search;
209: if (search.startsWith('?'))
210: search = search.substring(1);
211: List<String> parameters = search.split('&');
212: for (String param in parameters) {
213: List<String> lparam = param.split('=');
214: if (lparam.length != 2)
215: continue;
216: if (lparam[0] == 'config')
217: config = lparam[1];
218: else if (lparam[0] == 'file')
219: file = Uri.decodeComponent(lparam[1]);
220: else if (lparam[0] == 'save')
221: saveURL = lparam[1];
222: }
223: if (saveURL != null)
224: doc.saveURL = saveURL;
225: if (config != null && file != null)
226: page.openDocument(file, config).then((v) => completer.complete());
227: else if (config != null)
228: page.newDocument(config).then((v) => completer.complete());
229: else {
230: h.window.alert(Strings.get('daxe.missing_config'));
231: completer.completeError(Strings.get('daxe.missing_config'));
232: }
233: return(completer.future);
234: }
235:
236: void save() {
237: saveOnLONCAPA().then((_) {
238: h.window.alert(Strings.get('save.success'));
239: }, onError: (DaxeException ex) {
240: h.window.alert(Strings.get('save.error') + ': ' + ex.message);
241: });
242: }
243:
244: /**
245: * Send the document with a POST request to LON-CAPA.
246: */
247: Future saveOnLONCAPA() {
248: int ind = doc.filePath.indexOf('&url=');
249: if (ind == -1)
250: return(new Future.error(new DaxeException('bad URL')));
251: String path = doc.filePath.substring(ind+5);
252: path = Uri.decodeQueryComponent(path);
253: ind = path.lastIndexOf('/');
254: String filename;
255: if (ind == -1)
256: filename = path;
257: else {
258: filename = path.substring(ind+1);
259: path = path.substring(0, ind+1);
260: }
261: Completer completer = new Completer();
262: String bound = 'AaB03x';
263: h.HttpRequest request = new h.HttpRequest();
264: request.onLoad.listen((h.ProgressEvent event) {
265: completer.complete(); // TODO: check for something, status is sometimes wrongly OK
266: });
267: request.onError.listen((h.ProgressEvent event) {
268: completer.completeError(new DaxeException(request.status.toString()));
269: });
270: request.open('POST', '/upload_file');
271: request.setRequestHeader('Content-Type', "multipart/form-data; boundary=$bound");
272:
273: StringBuffer sb = new StringBuffer();
274: sb.write("--$bound\r\n");
275: sb.write('Content-Disposition: form-data; name="uploads_path"\r\n');
276: sb.write('Content-type: text/plain; charset=UTF-8\r\n');
277: sb.write('Content-transfer-encoding: 8bit\r\n\r\n');
278: sb.write(path);
279: sb.write("\r\n--$bound\r\n");
280: sb.write('Content-Disposition: form-data; name="uploads"; filename="$filename"\r\n');
281: sb.write('Content-Type: application/octet-stream\r\n\r\n');
282: doc.dndoc.xmlEncoding = 'UTF-8'; // the document is forced to use UTF-8
283: sb.write(doc.toString());
284: sb.write('\r\n--$bound--\r\n\r\n');
285: request.send(sb.toString());
286: return(completer.future);
287: }
288:
289: ToolbarMenu _makeSectionMenu() {
290: Menu menu = new Menu(LCDStrings.get('Section'));
291: List<x.Element> sectionRefs = doc.cfg.elementReferences('section');
292: if (sectionRefs == null || sectionRefs.length == 0)
293: return(null);
294: x.Element h1Ref = doc.cfg.elementReference('h1');
295: for (String role in ['introduction', 'conclusion', 'prerequisites', 'objectives',
296: 'reminder', 'definition', 'demonstration', 'example', 'advise',
297: 'remark', 'warning', 'more_information', 'method',
298: 'activity', 'bibliography', 'citation']) {
299: MenuItem menuItem = new MenuItem(LCDStrings.get(role), null,
300: data:new ToolbarStyleInfo(sectionRefs, null, null));
301: menuItem.action = () {
302: ToolbarStyleInfo info = menuItem.data;
303: x.Element sectionRef = info.validRef;
304: LCDBlock section = NodeFactory.create(sectionRef);
305: section.state = 1;
306: section.setAttribute('class', 'role-' + role);
307: LCDBlock h1 = NodeFactory.create(h1Ref);
308: h1.state = 1;
309: if (doc.insert2(section, page.getSelectionStart())) {
310: doc.insertNode(h1, new Position(section, 0));
311: page.cursor.moveTo(new Position(h1, 0));
312: page.updateAfterPathChange();
313: }
314: };
315: menu.add(menuItem);
316: }
317: ToolbarMenu tbmenu = new ToolbarMenu(menu, Toolbar.insertMenuUpdate, page.toolbar);
318: return(tbmenu);
319: }
320:
321: Future<x.Document> _readTemplates(String templatesPath) {
322: x.DOMParser dp = new x.DOMParser();
323: return(dp.parseFromURL(templatesPath));
324: }
325:
326: Menu _makeTemplatesMenu(x.Document templatesDoc) {
327: Menu menu = new Menu(LCDStrings.get('Templates'));
328: x.Element templates = templatesDoc.documentElement;
329: for (x.Node child in templates.childNodes) {
330: if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'menu') {
331: menu.add(_makeMenu(child));
332: }
333: }
334: return(menu);
335: }
336:
337: Menu _makeMenu(x.Element el) {
338: String locale = LCDStrings.systemLocale;
339: String defaultLocale = LCDStrings.defaultLocale;
340: String title;
341: for (x.Node child in el.childNodes) {
342: if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'title') {
343: if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
344: if ((child as x.Element).getAttribute('lang') == locale) {
345: title = child.firstChild.nodeValue;
346: break;
347: } else if ((child as x.Element).getAttribute('lang') == defaultLocale) {
348: title = child.firstChild.nodeValue;
349: }
350: }
351: }
352: }
353: if (title == null)
354: title = '?';
355: Menu menu = new Menu(title);
356: for (x.Node child in el.childNodes) {
357: if (child.nodeType == x.Node.ELEMENT_NODE) {
358: if (child.nodeName == 'menu') {
359: menu.add(_makeMenu(child));
360: } else if (child.nodeName == 'item') {
361: menu.add(_makeItem(child));
362: }
363: }
364: }
365: return(menu);
366: }
367:
368: MenuItem _makeItem(x.Element item) {
369: String locale = LCDStrings.systemLocale;
370: String defaultLocale = LCDStrings.defaultLocale;
371: String path, type, title, help;
372: for (x.Node child in item.childNodes) {
373: if (child.nodeType == x.Node.ELEMENT_NODE) {
374: if (child.nodeName == 'title') {
375: if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
376: if ((child as x.Element).getAttribute('lang') == locale) {
377: title = child.firstChild.nodeValue;
378: } else if (title == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
379: title = child.firstChild.nodeValue;
380: }
381: }
382: } else if (child.nodeName == 'path' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
383: path = child.firstChild.nodeValue;
384: } else if (child.nodeName == 'type' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
385: type = child.firstChild.nodeValue;
386: } else if (child.nodeName == 'help') {
387: if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
388: if ((child as x.Element).getAttribute('lang') == locale) {
389: help = child.firstChild.nodeValue;
390: } else if (help == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
391: help = child.firstChild.nodeValue;
392: }
393: }
394: }
395: }
396: }
397: if (type == null) {
398: print("Warning: missing type for template $title\n");
399: type = 'problem';
400: }
401: x.Element refElement = doc.cfg.elementReference(type);
402: MenuItem menuItem = new MenuItem(title, () => _insertTemplate(path), data: refElement);
403: if (help != null)
404: menuItem.toolTipText = help;
405: return menuItem;
406: }
407:
408: void _insertTemplate(String filePath) {
409: try {
410: x.DOMParser dp = new x.DOMParser();
411: dp.parseFromURL(filePath).then((x.Document templateDoc) {
412: x.Element root = templateDoc.documentElement;
413: if (root == null)
414: return;
415: doc.removeWhitespace(root);
416: DaxeNode dnRoot = NodeFactory.createFromNode(root, null);
417: UndoableEdit edit;
418: Position pos = page.getSelectionStart();
419: if (dnRoot.nodeName == 'loncapa' && doc.getRootElement() != null)
420: edit = doc.insertChildrenEdit(dnRoot, pos, checkValidity:true);
421: else
422: edit = new UndoableEdit.insertNode(pos, dnRoot);
423: doc.doNewEdit(edit);
424: page.updateAfterPathChange();
425: });
426: } on x.DOMException catch(ex) {
427: h.window.alert(ex.toString());
428: }
429: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>