Annotation of modules/damieng/graphical_editor/loncapa_daxe/web/loncapa_daxe.dart, revision 1.12

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';
1.9       damieng    26: import 'package:daxe/src/nodes/nodes.dart' show DNCData, DNText, SimpleTypeControl, ParentUpdatingDNText, DNHiddenP;
1.1       damieng    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.11      damieng    37: part 'nodes/essay_response.dart';
                     38: part 'nodes/textfield.dart';
1.1       damieng    39: part 'nodes/radio_response.dart';
                     40: part 'nodes/radio_foilgroup.dart';
                     41: part 'nodes/radio_foil.dart';
                     42: part 'nodes/option_response.dart';
                     43: part 'nodes/option_foilgroup.dart';
                     44: part 'nodes/option_foil.dart';
1.6       damieng    45: part 'nodes/match_response.dart';
                     46: part 'nodes/match_foilgroup.dart';
                     47: part 'nodes/match_foil.dart';
                     48: part 'nodes/itemgroup.dart';
                     49: part 'nodes/match_item.dart';
1.1       damieng    50: part 'nodes/rank_response.dart';
                     51: part 'nodes/rank_foilgroup.dart';
                     52: part 'nodes/rank_foil.dart';
1.10      damieng    53: part 'nodes/math_response.dart';
                     54: part 'nodes/math_answer.dart';
1.5       damieng    55: part 'nodes/textline.dart';
1.1       damieng    56: part 'nodes/hintgroup.dart';
                     57: part 'nodes/simple_ui_text.dart';
                     58: part 'nodes/script_block.dart';
1.2       damieng    59: part 'nodes/simple_ui_exception.dart';
1.7       damieng    60: part 'nodes/gnuplot.dart';
                     61: part 'nodes/fake_attribute_element.dart';
                     62: part 'nodes/plot_axis.dart';
                     63: part 'nodes/plot_curve.dart';
1.1       damieng    64: part 'lcd_button.dart';
                     65: 
                     66: 
                     67: void main() {
                     68:   NodeFactory.addCoreDisplayTypes();
                     69:   
                     70:   addDisplayType('lcdblock',
                     71:         (x.Element ref) => new LCDBlock.fromRef(ref),
                     72:         (x.Node node, DaxeNode parent) => new LCDBlock.fromNode(node, parent)
                     73:     );
                     74:   
                     75:   addDisplayType('texmathjax',
                     76:         (x.Element ref) => new TeXMathJax.fromRef(ref),
                     77:         (x.Node node, DaxeNode parent) => new TeXMathJax.fromNode(node, parent)
                     78:     );
                     79:   
                     80:   addDisplayType('lm',
                     81:         (x.Element ref) => new Lm.fromRef(ref),
                     82:         (x.Node node, DaxeNode parent) => new Lm.fromNode(node, parent)
                     83:     );
                     84:   
                     85:   addDisplayType('script',
                     86:         (x.Element ref) => new ScriptBlock.fromRef(ref),
                     87:         (x.Node node, DaxeNode parent) => new ScriptBlock.fromNode(node, parent)
                     88:     );
                     89:   
                     90:   addDisplayType('parameter',
                     91:         (x.Element ref) => new LCDParameter.fromRef(ref),
                     92:         (x.Node node, DaxeNode parent) => new LCDParameter.fromNode(node, parent)
                     93:     );
                     94:   
1.2       damieng    95:   addDisplayType('numericalresponse',
                     96:         (x.Element ref) => new NumericalResponse.fromRef(ref),
                     97:         (x.Node node, DaxeNode parent) => new NumericalResponse.fromNode(node, parent)
                     98:     );
                     99:   
1.3       damieng   100:   addDisplayType('formularesponse',
                    101:         (x.Element ref) => new FormulaResponse.fromRef(ref),
                    102:         (x.Node node, DaxeNode parent) => new FormulaResponse.fromNode(node, parent)
                    103:     );
                    104:   
                    105:   addDisplayType('stringresponse',
                    106:         (x.Element ref) => new StringResponse.fromRef(ref),
                    107:         (x.Node node, DaxeNode parent) => new StringResponse.fromNode(node, parent)
                    108:     );
                    109:   
1.11      damieng   110:   addDisplayType('essayresponse',
                    111:         (x.Element ref) => new EssayResponse.fromRef(ref),
                    112:         (x.Node node, DaxeNode parent) => new EssayResponse.fromNode(node, parent)
                    113:     );
                    114:   
1.1       damieng   115:   addDisplayType('radioresponse',
                    116:         (x.Element ref) => new RadioResponse.fromRef(ref),
                    117:         (x.Node node, DaxeNode parent) => new RadioResponse.fromNode(node, parent)
                    118:     );
                    119:   
                    120:   addDisplayType('optionresponse',
                    121:         (x.Element ref) => new OptionResponse.fromRef(ref),
                    122:         (x.Node node, DaxeNode parent) => new OptionResponse.fromNode(node, parent)
                    123:     );
                    124:   
1.6       damieng   125:   addDisplayType('matchresponse',
                    126:         (x.Element ref) => new MatchResponse.fromRef(ref),
                    127:         (x.Node node, DaxeNode parent) => new MatchResponse.fromNode(node, parent)
                    128:     );
                    129:   
1.1       damieng   130:   addDisplayType('rankresponse',
                    131:         (x.Element ref) => new RankResponse.fromRef(ref),
                    132:         (x.Node node, DaxeNode parent) => new RankResponse.fromNode(node, parent)
                    133:     );
                    134:   
1.10      damieng   135:   addDisplayType('mathresponse',
                    136:         (x.Element ref) => new MathResponse.fromRef(ref),
                    137:         (x.Node node, DaxeNode parent) => new MathResponse.fromNode(node, parent)
                    138:     );
                    139:   
1.1       damieng   140:   addDisplayType('foilgroup',
                    141:         (x.Element ref) {
                    142:           if (ref.getAttribute('type') == 'radiobuttonresponse--foilgroup')
                    143:             return new RadioFoilgroup.fromRef(ref);
                    144:           else if (ref.getAttribute('type') == 'optionresponse--foilgroup')
                    145:             return new OptionFoilgroup.fromRef(ref);
1.6       damieng   146:           else if (ref.getAttribute('type') == 'matchresponse--foilgroup')
                    147:             return new MatchFoilgroup.fromRef(ref);
1.1       damieng   148:           else if (ref.getAttribute('type') == 'rankresponse--foilgroup')
                    149:             return new RankFoilgroup.fromRef(ref);
                    150:           return new LCDBlock.fromRef(ref);
                    151:         },
                    152:         (x.Node node, DaxeNode parent) {
                    153:           if (parent is RadioResponse)
                    154:             return new RadioFoilgroup.fromNode(node, parent);
                    155:           else if (parent is OptionResponse)
                    156:             return new OptionFoilgroup.fromNode(node, parent);
1.6       damieng   157:           else if (parent is MatchResponse)
                    158:             return new MatchFoilgroup.fromNode(node, parent);
1.1       damieng   159:           else if (parent is RankResponse)
                    160:             return new RankFoilgroup.fromNode(node, parent);
                    161:           return new LCDBlock.fromNode(node, parent);
                    162:         }
                    163:     );
                    164:   
                    165:   addDisplayType('foil',
                    166:         (x.Element ref) {
                    167:           if (ref.getAttribute('type') == 'radiobuttonresponse--foil')
                    168:             return new RadioFoil.fromRef(ref);
                    169:           else if (ref.getAttribute('type') == 'optionresponse--foil')
                    170:             return new OptionFoil.fromRef(ref);
1.6       damieng   171:           else if (ref.getAttribute('type') == 'matchresponse--foil')
                    172:             return new MatchFoil.fromRef(ref);
1.1       damieng   173:           else if (ref.getAttribute('type') == 'rankresponse--foil')
                    174:             return new RankFoil.fromRef(ref);
                    175:           return new LCDBlock.fromRef(ref);
                    176:         },
                    177:         (x.Node node, DaxeNode parent) {
                    178:           if (parent is RadioFoilgroup)
                    179:             return new RadioFoil.fromNode(node, parent);
                    180:           else if (parent is OptionFoilgroup)
                    181:             return new OptionFoil.fromNode(node, parent);
1.6       damieng   182:           else if (parent is MatchFoilgroup)
                    183:             return new MatchFoil.fromNode(node, parent);
1.1       damieng   184:           else if (parent is RankFoilgroup)
                    185:             return new RankFoil.fromNode(node, parent);
                    186:           return new LCDBlock.fromNode(node, parent);
                    187:         }
                    188:     );
                    189:   
1.6       damieng   190:   addDisplayType('itemgroup',
                    191:         (x.Element ref) => new Itemgroup.fromRef(ref),
                    192:         (x.Node node, DaxeNode parent) => new Itemgroup.fromNode(node, parent)
                    193:     );
                    194:   
                    195:   addDisplayType('matchitem',
                    196:         (x.Element ref) => new MatchItem.fromRef(ref),
                    197:         (x.Node node, DaxeNode parent) => new MatchItem.fromNode(node, parent)
                    198:     );
                    199:   
1.5       damieng   200:   addDisplayType('textline',
                    201:         (x.Element ref) => new Textline.fromRef(ref),
                    202:         (x.Node node, DaxeNode parent) => new Textline.fromNode(node, parent)
                    203:     );
                    204:   
1.11      damieng   205:   addDisplayType('textfield',
                    206:         (x.Element ref) => new Textfield.fromRef(ref),
                    207:         (x.Node node, DaxeNode parent) => new Textfield.fromNode(node, parent)
                    208:     );
                    209:   
1.1       damieng   210:   addDisplayType('hintgroup',
                    211:         (x.Element ref) => new Hintgroup.fromRef(ref),
                    212:         (x.Node node, DaxeNode parent) => new Hintgroup.fromNode(node, parent)
                    213:     );
                    214:   
1.10      damieng   215:   addDisplayType('answer',
                    216:         (x.Element ref) {
                    217:           if (ref.getAttribute('type') == 'mathresponse--answer')
                    218:             return new MathAnswer.fromRef(ref);
                    219:           return new LCDBlock.fromRef(ref);
                    220:         },
                    221:         (x.Node node, DaxeNode parent) {
                    222:           if (parent is MathResponse)
                    223:             return new MathAnswer.fromNode(node, parent);
                    224:           return new LCDBlock.fromNode(node, parent);
                    225:         }
                    226:     );
                    227:   
1.7       damieng   228:   addDisplayType('gnuplot',
                    229:         (x.Element ref) => new Gnuplot.fromRef(ref),
                    230:         (x.Node node, DaxeNode parent) => new Gnuplot.fromNode(node, parent)
                    231:     );
                    232:   
                    233:   addDisplayType('fakeattribute',
                    234:         (x.Element ref) {
                    235:           if (doc.cfg.elementName(ref) != 'title' || ref.getAttribute('type') == 'lonplot--title')
                    236:             return new FakeAttributeElement.fromRef(ref);
                    237:           return new LCDBlock.fromRef(ref);
                    238:         },
                    239:         (x.Node node, DaxeNode parent) {
                    240:           if (parent is Gnuplot || parent is PlotCurve)
                    241:             return new FakeAttributeElement.fromNode(node, parent);
                    242:           return new LCDBlock.fromNode(node, parent);
                    243:         }
                    244:     );
                    245:   
                    246:   addDisplayType('plotaxis',
                    247:         (x.Element ref) => new PlotAxis.fromRef(ref),
                    248:         (x.Node node, DaxeNode parent) => new PlotAxis.fromNode(node, parent)
                    249:     );
                    250:   
                    251:   addDisplayType('plotcurve',
                    252:         (x.Element ref) => new PlotCurve.fromRef(ref),
                    253:         (x.Node node, DaxeNode parent) => new PlotCurve.fromNode(node, parent)
                    254:     );
                    255:   
1.1       damieng   256:   Future.wait([Strings.load(), LCDStrings.load(), _readTemplates('templates.xml')]).then((List responses) {
                    257:     _init_daxe().then((v) {
                    258:       // add things to the toolbar
                    259:       ToolbarMenu sectionMenu = _makeSectionMenu();
                    260:       if (sectionMenu != null)
                    261:         page.toolbar.add(sectionMenu);
                    262:       x.Element texRef = doc.cfg.elementReference('m');
                    263:       if (texRef != null) {
                    264:         ToolbarBox insertBox = new ToolbarBox();
                    265:         ToolbarButton texButton = new ToolbarButton(
                    266:             LCDStrings.get('tex_equation'), 'images/tex.png',
                    267:             () => doc.insertNewNode(texRef, 'element'), Toolbar.insertButtonUpdate, 
                    268:             data:new ToolbarStyleInfo([texRef], null, null));
                    269:         insertBox.add(texButton);
                    270:         page.toolbar.add(insertBox);
                    271:       }
                    272:       h.Element tbh = h.querySelector('.toolbar');
                    273:       tbh.replaceWith(page.toolbar.html());
                    274:       page.adjustPositionsUnderToolbar();
                    275:       page.updateAfterPathChange();
                    276:       // add things to the menubar
                    277:       if (responses[2] is x.Document) {
                    278:         // at this point the menubar html is already in the document, so we have to fix the HTML
                    279:         h.Element menubarDiv = h.document.getElementsByClassName('menubar')[0];
1.4       damieng   280:         if (doc.filePath != null && doc.filePath.indexOf('&url=') != -1) { // otherwise we are not on LON-CAPA
1.1       damieng   281:           MenuItem item = new MenuItem(Strings.get('menu.save'), () => save(), shortcut: 'S');
                    282:           Menu fileMenu = page.mbar.menus[0];
                    283:           fileMenu.add(item);
                    284:           menubarDiv.firstChild.replaceWith(page.mbar.createMenuDiv(fileMenu));
                    285:         }
                    286:         Menu m = _makeTemplatesMenu(responses[2]);
                    287:         page.mbar.add(m);
                    288:         menubarDiv.append(page.mbar.createMenuDiv(m));
                    289:         page.updateAfterPathChange();
                    290:       } else
                    291:         print("Error reading templates file, could not build the menu.");
                    292:     });
                    293:   });
                    294: }
                    295: 
                    296: Future _init_daxe() {
                    297:   Completer completer = new Completer();
                    298:   doc = new DaxeDocument();
                    299:   page = new WebPage();
                    300:   
                    301:   // check parameters for a config and file to open
                    302:   String file = null;
                    303:   String config = null;
                    304:   String saveURL = null;
                    305:   h.Location location = h.window.location;
                    306:   String search = location.search;
                    307:   if (search.startsWith('?'))
                    308:     search = search.substring(1);
                    309:   List<String> parameters = search.split('&');
                    310:   for (String param in parameters) {
                    311:     List<String> lparam = param.split('=');
                    312:     if (lparam.length != 2)
                    313:       continue;
                    314:     if (lparam[0] == 'config')
                    315:       config = lparam[1];
                    316:     else if (lparam[0] == 'file')
                    317:       file = Uri.decodeComponent(lparam[1]);
                    318:     else if (lparam[0] == 'save')
                    319:       saveURL = lparam[1];
                    320:   }
                    321:   if (saveURL != null)
                    322:     doc.saveURL = saveURL;
                    323:   if (config != null && file != null)
                    324:     page.openDocument(file, config).then((v) => completer.complete());
                    325:   else if (config != null)
                    326:     page.newDocument(config).then((v) => completer.complete());
                    327:   else {
                    328:     h.window.alert(Strings.get('daxe.missing_config'));
                    329:     completer.completeError(Strings.get('daxe.missing_config'));
                    330:   }
                    331:   return(completer.future);
                    332: }
                    333: 
                    334: void save() {
                    335:   saveOnLONCAPA().then((_) {
                    336:     h.window.alert(Strings.get('save.success'));
                    337:   }, onError: (DaxeException ex) {
                    338:     h.window.alert(Strings.get('save.error') + ': ' + ex.message);
                    339:   });
                    340: }
                    341: 
                    342: /**
                    343:  * Send the document with a POST request to LON-CAPA.
                    344:  */
                    345: Future saveOnLONCAPA() {
                    346:   int ind = doc.filePath.indexOf('&url=');
                    347:   if (ind == -1)
                    348:     return(new Future.error(new DaxeException('bad URL')));
                    349:   String path = doc.filePath.substring(ind+5);
                    350:   path = Uri.decodeQueryComponent(path);
                    351:   ind = path.lastIndexOf('/');
                    352:   String filename;
                    353:   if (ind == -1)
                    354:     filename = path;
                    355:   else {
                    356:     filename = path.substring(ind+1);
                    357:     path = path.substring(0, ind+1);
                    358:   }
                    359:   Completer completer = new Completer();
                    360:   String bound = 'AaB03x';
                    361:   h.HttpRequest request = new h.HttpRequest();
                    362:   request.onLoad.listen((h.ProgressEvent event) {
                    363:     completer.complete(); // TODO: check for something, status is sometimes wrongly OK
                    364:   });
                    365:   request.onError.listen((h.ProgressEvent event) {
                    366:     completer.completeError(new DaxeException(request.status.toString()));
                    367:   });
                    368:   request.open('POST', '/upload_file');
                    369:   request.setRequestHeader('Content-Type', "multipart/form-data; boundary=$bound");
                    370:   
                    371:   StringBuffer sb = new StringBuffer();
                    372:   sb.write("--$bound\r\n");
                    373:   sb.write('Content-Disposition: form-data; name="uploads_path"\r\n');
                    374:   sb.write('Content-type: text/plain; charset=UTF-8\r\n');
                    375:   sb.write('Content-transfer-encoding: 8bit\r\n\r\n');
                    376:   sb.write(path);
                    377:   sb.write("\r\n--$bound\r\n");
                    378:   sb.write('Content-Disposition: form-data; name="uploads"; filename="$filename"\r\n');
                    379:   sb.write('Content-Type: application/octet-stream\r\n\r\n');
                    380:   doc.dndoc.xmlEncoding = 'UTF-8'; // the document is forced to use UTF-8
                    381:   sb.write(doc.toString());
                    382:   sb.write('\r\n--$bound--\r\n\r\n');
                    383:   request.send(sb.toString());
                    384:   return(completer.future);
                    385: }
                    386: 
                    387: ToolbarMenu _makeSectionMenu() {
                    388:   Menu menu = new Menu(LCDStrings.get('Section'));
                    389:   List<x.Element> sectionRefs = doc.cfg.elementReferences('section');
                    390:   if (sectionRefs == null || sectionRefs.length == 0)
                    391:     return(null);
                    392:   x.Element h1Ref = doc.cfg.elementReference('h1');
                    393:   for (String role in ['introduction', 'conclusion', 'prerequisites', 'objectives',
                    394:                        'reminder', 'definition', 'demonstration', 'example', 'advise',
                    395:                        'remark', 'warning', 'more_information', 'method',
                    396:                        'activity', 'bibliography', 'citation']) {
                    397:     MenuItem menuItem = new MenuItem(LCDStrings.get(role), null,
                    398:         data:new ToolbarStyleInfo(sectionRefs, null, null));
                    399:     menuItem.action = () {
                    400:       ToolbarStyleInfo info = menuItem.data;
                    401:       x.Element sectionRef = info.validRef;
                    402:       LCDBlock section = NodeFactory.create(sectionRef);
                    403:       section.state = 1;
                    404:       section.setAttribute('class', 'role-' + role);
                    405:       LCDBlock h1 = NodeFactory.create(h1Ref);
                    406:       h1.state = 1;
1.9       damieng   407:       section.appendChild(h1);
                    408:       x.Element hiddenp = doc.cfg.findSubElement(sectionRef, doc.hiddenParaRefs);
                    409:       DNHiddenP p = NodeFactory.create(hiddenp);
                    410:       section.appendChild(p);
1.1       damieng   411:       if (doc.insert2(section, page.getSelectionStart())) {
                    412:         page.cursor.moveTo(new Position(h1, 0));
                    413:         page.updateAfterPathChange();
                    414:       }
                    415:     };
                    416:     menu.add(menuItem);
                    417:   }
                    418:   ToolbarMenu tbmenu = new ToolbarMenu(menu, Toolbar.insertMenuUpdate, page.toolbar);
                    419:   return(tbmenu);
                    420: }
                    421: 
                    422: Future<x.Document> _readTemplates(String templatesPath) {
                    423:   x.DOMParser dp = new x.DOMParser();
                    424:   return(dp.parseFromURL(templatesPath));
                    425: }
                    426: 
                    427: Menu _makeTemplatesMenu(x.Document templatesDoc) {
                    428:   Menu menu = new Menu(LCDStrings.get('Templates'));
                    429:   x.Element templates = templatesDoc.documentElement;
                    430:   for (x.Node child in templates.childNodes) {
                    431:     if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'menu') {
                    432:       menu.add(_makeMenu(child));
                    433:     }
                    434:   }
                    435:   return(menu);
                    436: }
                    437: 
                    438: Menu _makeMenu(x.Element el) {
                    439:   String locale = LCDStrings.systemLocale;
                    440:   String defaultLocale = LCDStrings.defaultLocale;
                    441:   String title;
                    442:   for (x.Node child in el.childNodes) {
                    443:     if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'title') {
                    444:       if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    445:         if ((child as x.Element).getAttribute('lang') == locale) {
                    446:           title = child.firstChild.nodeValue;
                    447:           break;
                    448:         } else if ((child as x.Element).getAttribute('lang') == defaultLocale) {
                    449:           title = child.firstChild.nodeValue;
                    450:         }
                    451:       }
                    452:     }
                    453:   }
                    454:   if (title == null)
                    455:     title = '?';
                    456:   Menu menu = new Menu(title);
                    457:   for (x.Node child in el.childNodes) {
                    458:     if (child.nodeType == x.Node.ELEMENT_NODE) {
                    459:       if (child.nodeName == 'menu') {
                    460:         menu.add(_makeMenu(child));
                    461:       } else if (child.nodeName == 'item') {
                    462:         menu.add(_makeItem(child));
                    463:       }
                    464:     }
                    465:   }
                    466:   return(menu);
                    467: }
                    468: 
                    469: MenuItem _makeItem(x.Element item) {
                    470:   String locale = LCDStrings.systemLocale;
                    471:   String defaultLocale = LCDStrings.defaultLocale;
                    472:   String path, type, title, help;
                    473:   for (x.Node child in item.childNodes) {
                    474:     if (child.nodeType == x.Node.ELEMENT_NODE) {
                    475:       if (child.nodeName == 'title') {
                    476:         if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    477:           if ((child as x.Element).getAttribute('lang') == locale) {
                    478:             title = child.firstChild.nodeValue;
                    479:           } else if (title == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
                    480:             title = child.firstChild.nodeValue;
                    481:           }
                    482:         }
                    483:       } else if (child.nodeName == 'path' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    484:         path = child.firstChild.nodeValue;
                    485:       } else if (child.nodeName == 'type' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    486:         type = child.firstChild.nodeValue;
                    487:       } else if (child.nodeName == 'help') {
                    488:         if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    489:           if ((child as x.Element).getAttribute('lang') == locale) {
                    490:             help = child.firstChild.nodeValue;
                    491:           } else if (help == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
                    492:             help = child.firstChild.nodeValue;
                    493:           }
                    494:         }
                    495:       }
                    496:     }
                    497:   }
                    498:   if (type == null) {
                    499:     print("Warning: missing type for template $title\n");
                    500:     type = 'problem';
                    501:   }
                    502:   x.Element refElement = doc.cfg.elementReference(type);
                    503:   MenuItem menuItem = new MenuItem(title, () => _insertTemplate(path), data: refElement);
                    504:   if (help != null)
                    505:     menuItem.toolTipText = help;
                    506:   return menuItem;
                    507: }
                    508: 
                    509: void _insertTemplate(String filePath) {
                    510:   try {
                    511:     x.DOMParser dp = new x.DOMParser();
                    512:     dp.parseFromURL(filePath).then((x.Document templateDoc) {
                    513:       x.Element root = templateDoc.documentElement;
                    514:       if (root == null)
                    515:         return;
                    516:       doc.removeWhitespace(root);
                    517:       DaxeNode dnRoot = NodeFactory.createFromNode(root, null);
                    518:       UndoableEdit edit;
                    519:       Position pos = page.getSelectionStart();
                    520:       if (dnRoot.nodeName == 'loncapa' && doc.getRootElement() != null)
                    521:         edit = doc.insertChildrenEdit(dnRoot, pos, checkValidity:true);
1.12    ! damieng   522:       else {
        !           523:         DaxeNode parent = pos.dn;
        !           524:         if (parent is DNText)
        !           525:           parent = parent.parent;
        !           526:         if (parent is DNHiddenP && !doc.cfg.isSubElement(parent.ref, dnRoot.ref)) {
        !           527:           // The node must be inserted outside of the paragraph.
        !           528:           // If there is something in the paragraph to the right of the cursor, it must be
        !           529:           // moved into a new paragraph after the inserted node.
        !           530:           // (as in DaxeDocument.insert2)
        !           531:           DNHiddenP p = parent;
        !           532:           edit = new UndoableEdit.compound(Strings.get('undo.insert_element'));
        !           533:           Position pend = new Position(p, p.offsetLength);
        !           534:           pend.moveInsideTextNodeIfPossible();
        !           535:           if (pos < pend) {
        !           536:             DaxeNode clone = doc.cloneBetween(pos, pend);
        !           537:             edit.addSubEdit(doc.removeBetweenEdit(pos, pend));
        !           538:             DNHiddenP newp = NodeFactory.create(p.ref);
        !           539:             edit.addSubEdit(new UndoableEdit.insertNode(
        !           540:                 new Position(p.parent, p.parent.offsetOf(p) + 1), newp));
        !           541:             edit.addSubEdit(doc.insertChildrenEdit(clone, new Position(newp, 0)));
        !           542:           }
        !           543:           edit.addSubEdit(new UndoableEdit.insertNode(
        !           544:               new Position(p.parent, p.parent.offsetOf(p)+1), dnRoot));
        !           545:         } else
        !           546:           edit = new UndoableEdit.insertNode(pos, dnRoot);
        !           547:       }
1.1       damieng   548:       doc.doNewEdit(edit);
                    549:       page.updateAfterPathChange();
1.8       damieng   550:       if (dnRoot.nodeName != 'loncapa')
                    551:         page.scrollToNode(dnRoot);
1.1       damieng   552:     });
                    553:   } on x.DOMException catch(ex) {
                    554:     h.window.alert(ex.toString());
                    555:   }
                    556: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>