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

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

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