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

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

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