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

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;
1.46      damieng    23: import 'dart:math';
1.1       damieng    24: import 'package:daxe/daxe.dart';
                     25: import 'package:daxe/src/xmldom/xmldom.dart' as x;
                     26: import 'package:daxe/src/strings.dart';
1.51      damieng    27: import 'package:daxe/src/nodes/nodes.dart' show DNBlock, DNCData, DNFile, DNText,
1.52    ! damieng    28:   SimpleTypeControl, ParentUpdatingDNText, DNHiddenP, DNString, DNHiddenDiv;
1.1       damieng    29: import 'dart:js' as js;
                     30: 
                     31: import 'lcd_strings.dart';
1.41      damieng    32: part 'about_lc_daxe_dlg.dart';
                     33: part 'lcd_insert_panel.dart';
1.1       damieng    34: part 'nodes/lcd_block.dart';
1.32      damieng    35: part 'nodes/lcd_block_no_newline.dart';
1.51      damieng    36: part 'nodes/lcd_file.dart';
1.1       damieng    37: part 'nodes/lcd_parameter.dart';
                     38: part 'nodes/tex_mathjax.dart';
                     39: part 'nodes/lm.dart';
1.14      damieng    40: part 'nodes/chem.dart';
1.2       damieng    41: part 'nodes/numerical_response.dart';
1.3       damieng    42: part 'nodes/formula_response.dart';
                     43: part 'nodes/string_response.dart';
1.11      damieng    44: part 'nodes/essay_response.dart';
                     45: part 'nodes/textfield.dart';
1.1       damieng    46: part 'nodes/radio_response.dart';
                     47: part 'nodes/radio_foilgroup.dart';
                     48: part 'nodes/radio_foil.dart';
                     49: part 'nodes/option_response.dart';
                     50: part 'nodes/option_foilgroup.dart';
                     51: part 'nodes/option_foil.dart';
1.6       damieng    52: part 'nodes/match_response.dart';
                     53: part 'nodes/match_foilgroup.dart';
                     54: part 'nodes/match_foil.dart';
                     55: part 'nodes/itemgroup.dart';
                     56: part 'nodes/match_item.dart';
1.1       damieng    57: part 'nodes/rank_response.dart';
                     58: part 'nodes/rank_foilgroup.dart';
                     59: part 'nodes/rank_foil.dart';
1.10      damieng    60: part 'nodes/math_response.dart';
                     61: part 'nodes/math_answer.dart';
1.13      damieng    62: part 'nodes/organic_response.dart';
                     63: part 'nodes/jsme_dialog.dart';
                     64: part 'nodes/reaction_response.dart';
1.5       damieng    65: part 'nodes/textline.dart';
1.1       damieng    66: part 'nodes/hintgroup.dart';
                     67: part 'nodes/simple_ui_text.dart';
                     68: part 'nodes/script_block.dart';
1.2       damieng    69: part 'nodes/simple_ui_exception.dart';
1.7       damieng    70: part 'nodes/gnuplot.dart';
1.22      damieng    71: part 'nodes/organic_structure.dart';
1.7       damieng    72: part 'nodes/fake_attribute_element.dart';
                     73: part 'nodes/plot_axis.dart';
                     74: part 'nodes/plot_curve.dart';
1.17      damieng    75: part 'nodes/section.dart';
                     76: part 'nodes/h1.dart';
1.1       damieng    77: 
1.18      damieng    78: List<String> knownSectionRoles = ['activity', 'advice', 'bibliography', 'citation',
                     79:   'conclusion', 'definition', 'demonstration', 'example',
                     80:   'explanation', 'introduction', 'method', 'more_information',
                     81:   'objectives', 'prerequisites', 'remark', 'reminder',
                     82:   'summary', 'syntax', 'warning'];
                     83: 
1.1       damieng    84: 
                     85: void main() {
                     86:   NodeFactory.addCoreDisplayTypes();
                     87:   
1.35      damieng    88:   // LON-CAPA specific display types:
                     89:   
1.45      damieng    90:   setDisplayType('lcdblock',
1.1       damieng    91:         (x.Element ref) => new LCDBlock.fromRef(ref),
                     92:         (x.Node node, DaxeNode parent) => new LCDBlock.fromNode(node, parent)
                     93:     );
                     94:   
1.45      damieng    95:   setDisplayType('texmathjax',
1.1       damieng    96:         (x.Element ref) => new TeXMathJax.fromRef(ref),
                     97:         (x.Node node, DaxeNode parent) => new TeXMathJax.fromNode(node, parent)
                     98:     );
                     99:   
1.45      damieng   100:   setDisplayType('lm',
1.1       damieng   101:         (x.Element ref) => new Lm.fromRef(ref),
                    102:         (x.Node node, DaxeNode parent) => new Lm.fromNode(node, parent)
                    103:     );
                    104:   
1.45      damieng   105:   setDisplayType('chem',
1.14      damieng   106:         (x.Element ref) => new Chem.fromRef(ref),
                    107:         (x.Node node, DaxeNode parent) => new Chem.fromNode(node, parent)
                    108:     );
                    109:   
1.45      damieng   110:   setDisplayType('script',
1.27      damieng   111:         (x.Element ref) => new ScriptBlock.fromRef(ref),
                    112:         (x.Node node, DaxeNode parent) => new ScriptBlock.fromNode(node, parent)
1.1       damieng   113:     );
                    114:   
1.45      damieng   115:   setDisplayType('parameter',
1.1       damieng   116:         (x.Element ref) => new LCDParameter.fromRef(ref),
                    117:         (x.Node node, DaxeNode parent) => new LCDParameter.fromNode(node, parent)
                    118:     );
                    119:   
1.45      damieng   120:   setDisplayType('numericalresponse',
1.2       damieng   121:         (x.Element ref) => new NumericalResponse.fromRef(ref),
                    122:         (x.Node node, DaxeNode parent) => new NumericalResponse.fromNode(node, parent)
                    123:     );
                    124:   
1.45      damieng   125:   setDisplayType('formularesponse',
1.3       damieng   126:         (x.Element ref) => new FormulaResponse.fromRef(ref),
                    127:         (x.Node node, DaxeNode parent) => new FormulaResponse.fromNode(node, parent)
                    128:     );
                    129:   
1.45      damieng   130:   setDisplayType('stringresponse',
1.3       damieng   131:         (x.Element ref) => new StringResponse.fromRef(ref),
                    132:         (x.Node node, DaxeNode parent) => new StringResponse.fromNode(node, parent)
                    133:     );
                    134:   
1.45      damieng   135:   setDisplayType('essayresponse',
1.11      damieng   136:         (x.Element ref) => new EssayResponse.fromRef(ref),
                    137:         (x.Node node, DaxeNode parent) => new EssayResponse.fromNode(node, parent)
                    138:     );
                    139:   
1.45      damieng   140:   setDisplayType('radioresponse',
1.1       damieng   141:         (x.Element ref) => new RadioResponse.fromRef(ref),
                    142:         (x.Node node, DaxeNode parent) => new RadioResponse.fromNode(node, parent)
                    143:     );
                    144:   
1.45      damieng   145:   setDisplayType('optionresponse',
1.1       damieng   146:         (x.Element ref) => new OptionResponse.fromRef(ref),
                    147:         (x.Node node, DaxeNode parent) => new OptionResponse.fromNode(node, parent)
                    148:     );
                    149:   
1.45      damieng   150:   setDisplayType('matchresponse',
1.6       damieng   151:         (x.Element ref) => new MatchResponse.fromRef(ref),
                    152:         (x.Node node, DaxeNode parent) => new MatchResponse.fromNode(node, parent)
                    153:     );
                    154:   
1.45      damieng   155:   setDisplayType('rankresponse',
1.1       damieng   156:         (x.Element ref) => new RankResponse.fromRef(ref),
                    157:         (x.Node node, DaxeNode parent) => new RankResponse.fromNode(node, parent)
                    158:     );
                    159:   
1.45      damieng   160:   setDisplayType('mathresponse',
1.10      damieng   161:         (x.Element ref) => new MathResponse.fromRef(ref),
                    162:         (x.Node node, DaxeNode parent) => new MathResponse.fromNode(node, parent)
                    163:     );
                    164:   
1.45      damieng   165:   setDisplayType('organicresponse',
1.13      damieng   166:         (x.Element ref) => new OrganicResponse.fromRef(ref),
                    167:         (x.Node node, DaxeNode parent) => new OrganicResponse.fromNode(node, parent)
                    168:     );
                    169:   
1.45      damieng   170:   setDisplayType('reactionresponse',
1.13      damieng   171:         (x.Element ref) => new ReactionResponse.fromRef(ref),
                    172:         (x.Node node, DaxeNode parent) => new ReactionResponse.fromNode(node, parent)
                    173:     );
                    174:   
1.45      damieng   175:   setDisplayType('foilgroup',
1.1       damieng   176:         (x.Element ref) {
                    177:           if (ref.getAttribute('type') == 'radiobuttonresponse--foilgroup')
                    178:             return new RadioFoilgroup.fromRef(ref);
                    179:           else if (ref.getAttribute('type') == 'optionresponse--foilgroup')
                    180:             return new OptionFoilgroup.fromRef(ref);
1.6       damieng   181:           else if (ref.getAttribute('type') == 'matchresponse--foilgroup')
                    182:             return new MatchFoilgroup.fromRef(ref);
1.1       damieng   183:           else if (ref.getAttribute('type') == 'rankresponse--foilgroup')
                    184:             return new RankFoilgroup.fromRef(ref);
                    185:           return new LCDBlock.fromRef(ref);
                    186:         },
                    187:         (x.Node node, DaxeNode parent) {
                    188:           if (parent is RadioResponse)
                    189:             return new RadioFoilgroup.fromNode(node, parent);
                    190:           else if (parent is OptionResponse)
                    191:             return new OptionFoilgroup.fromNode(node, parent);
1.6       damieng   192:           else if (parent is MatchResponse)
                    193:             return new MatchFoilgroup.fromNode(node, parent);
1.1       damieng   194:           else if (parent is RankResponse)
                    195:             return new RankFoilgroup.fromNode(node, parent);
                    196:           return new LCDBlock.fromNode(node, parent);
                    197:         }
                    198:     );
                    199:   
1.45      damieng   200:   setDisplayType('foil',
1.1       damieng   201:         (x.Element ref) {
                    202:           if (ref.getAttribute('type') == 'radiobuttonresponse--foil')
                    203:             return new RadioFoil.fromRef(ref);
                    204:           else if (ref.getAttribute('type') == 'optionresponse--foil')
                    205:             return new OptionFoil.fromRef(ref);
1.6       damieng   206:           else if (ref.getAttribute('type') == 'matchresponse--foil')
                    207:             return new MatchFoil.fromRef(ref);
1.1       damieng   208:           else if (ref.getAttribute('type') == 'rankresponse--foil')
                    209:             return new RankFoil.fromRef(ref);
                    210:           return new LCDBlock.fromRef(ref);
                    211:         },
                    212:         (x.Node node, DaxeNode parent) {
                    213:           if (parent is RadioFoilgroup)
                    214:             return new RadioFoil.fromNode(node, parent);
1.19      damieng   215:           else if (parent is OptionFoilgroup ||
                    216:               (parent.parent != null && parent.parent is OptionFoilgroup))
1.1       damieng   217:             return new OptionFoil.fromNode(node, parent);
1.19      damieng   218:           else if (parent is MatchFoilgroup ||
                    219:               (parent.parent != null && parent.parent is MatchFoilgroup))
1.6       damieng   220:             return new MatchFoil.fromNode(node, parent);
1.1       damieng   221:           else if (parent is RankFoilgroup)
                    222:             return new RankFoil.fromNode(node, parent);
                    223:           return new LCDBlock.fromNode(node, parent);
                    224:         }
                    225:     );
                    226:   
1.45      damieng   227:   setDisplayType('itemgroup',
1.6       damieng   228:         (x.Element ref) => new Itemgroup.fromRef(ref),
                    229:         (x.Node node, DaxeNode parent) => new Itemgroup.fromNode(node, parent)
                    230:     );
                    231:   
1.45      damieng   232:   setDisplayType('matchitem',
1.6       damieng   233:         (x.Element ref) => new MatchItem.fromRef(ref),
                    234:         (x.Node node, DaxeNode parent) => new MatchItem.fromNode(node, parent)
                    235:     );
                    236:   
1.45      damieng   237:   setDisplayType('textline',
1.5       damieng   238:         (x.Element ref) => new Textline.fromRef(ref),
                    239:         (x.Node node, DaxeNode parent) => new Textline.fromNode(node, parent)
                    240:     );
                    241:   
1.45      damieng   242:   setDisplayType('textfield',
1.11      damieng   243:         (x.Element ref) => new Textfield.fromRef(ref),
                    244:         (x.Node node, DaxeNode parent) => new Textfield.fromNode(node, parent)
                    245:     );
                    246:   
1.45      damieng   247:   setDisplayType('hintgroup',
1.1       damieng   248:         (x.Element ref) => new Hintgroup.fromRef(ref),
                    249:         (x.Node node, DaxeNode parent) => new Hintgroup.fromNode(node, parent)
                    250:     );
                    251:   
1.45      damieng   252:   setDisplayType('answer',
1.10      damieng   253:         (x.Element ref) {
                    254:           if (ref.getAttribute('type') == 'mathresponse--answer')
                    255:             return new MathAnswer.fromRef(ref);
1.27      damieng   256:           else if (ref.getAttribute('type') == 'caparesponse--answer')
                    257:             return new LCDBlock.fromRef(ref);
                    258:           else
                    259:             return new ScriptBlock.fromRef(ref);
1.10      damieng   260:         },
                    261:         (x.Node node, DaxeNode parent) {
                    262:           if (parent is MathResponse)
                    263:             return new MathAnswer.fromNode(node, parent);
1.27      damieng   264:           else if (parent != null && parent.ref != null &&
                    265:               parent.ref.getAttribute('type') == 'caparesponse--answergroup')
                    266:             return new LCDBlock.fromNode(node, parent);
                    267:           else
                    268:             return new ScriptBlock.fromNode(node, parent);
1.10      damieng   269:         }
                    270:     );
                    271:   
1.45      damieng   272:   setDisplayType('gnuplot',
1.7       damieng   273:         (x.Element ref) => new Gnuplot.fromRef(ref),
                    274:         (x.Node node, DaxeNode parent) => new Gnuplot.fromNode(node, parent)
                    275:     );
                    276:   
1.45      damieng   277:   setDisplayType('organicstructure',
1.22      damieng   278:         (x.Element ref) => new OrganicStructure.fromRef(ref),
                    279:         (x.Node node, DaxeNode parent) => new OrganicStructure.fromNode(node, parent)
                    280:     );
                    281:   
1.45      damieng   282:   setDisplayType('fakeattribute',
1.7       damieng   283:         (x.Element ref) {
                    284:           if (doc.cfg.elementName(ref) != 'title' || ref.getAttribute('type') == 'lonplot--title')
                    285:             return new FakeAttributeElement.fromRef(ref);
                    286:           return new LCDBlock.fromRef(ref);
                    287:         },
                    288:         (x.Node node, DaxeNode parent) {
                    289:           if (parent is Gnuplot || parent is PlotCurve)
                    290:             return new FakeAttributeElement.fromNode(node, parent);
                    291:           return new LCDBlock.fromNode(node, parent);
                    292:         }
                    293:     );
                    294:   
1.45      damieng   295:   setDisplayType('plotaxis',
1.7       damieng   296:         (x.Element ref) => new PlotAxis.fromRef(ref),
                    297:         (x.Node node, DaxeNode parent) => new PlotAxis.fromNode(node, parent)
                    298:     );
                    299:   
1.45      damieng   300:   setDisplayType('plotcurve',
1.7       damieng   301:         (x.Element ref) => new PlotCurve.fromRef(ref),
                    302:         (x.Node node, DaxeNode parent) => new PlotCurve.fromNode(node, parent)
                    303:     );
                    304:   
1.45      damieng   305:   setDisplayType('section',
1.17      damieng   306:         (x.Element ref) => new Section.fromRef(ref),
                    307:         (x.Node node, DaxeNode parent) => new Section.fromNode(node, parent)
                    308:     );
                    309:   
1.45      damieng   310:   setDisplayType('h1',
1.17      damieng   311:         (x.Element ref) => new H1.fromRef(ref),
                    312:         (x.Node node, DaxeNode parent) => new H1.fromNode(node, parent)
                    313:     );
                    314:   
1.45      damieng   315:   setDisplayType('lcdblocknonewline',
1.32      damieng   316:         (x.Element ref) => new LCDBlockNoNewline.fromRef(ref),
                    317:         (x.Node node, DaxeNode parent) => new LCDBlockNoNewline.fromNode(node, parent)
                    318:     );
                    319:   
1.45      damieng   320:   setDisplayType('label',
1.31      damieng   321:         (x.Element ref) {
                    322:           if (ref.getAttribute('type') == 'lonplot--label')
1.37      damieng   323:             return new LCDBlockNoNewline.fromRef(ref); // gnuplot label
1.32      damieng   324:           else if (ref.getAttribute('type') == 'randomlabel--label')
                    325:             return new LCDBlockNoNewline.fromRef(ref); // randomlabel label
                    326:           return new DNString.fromRef(ref); // HTML form label
1.31      damieng   327:         },
                    328:         (x.Node node, DaxeNode parent) {
                    329:           if (parent is Gnuplot || (parent != null && parent.parent is Gnuplot))
1.37      damieng   330:             return new LCDBlockNoNewline.fromNode(node, parent);
1.32      damieng   331:           else if (parent != null && parent.ref != null &&
                    332:               parent.ref.getAttribute('type') == 'randomlabel--labelgroup')
                    333:             return new LCDBlockNoNewline.fromNode(node, parent);
1.31      damieng   334:           return new DNString.fromNode(node, parent);
                    335:         }
                    336:     );
                    337:   
1.52    ! damieng   338:   setDisplayType('lcdfile',
        !           339:         (x.Element ref) => new LCDFile.fromRef(ref),
        !           340:         (x.Node node, DaxeNode parent) => new LCDFile.fromNode(node, parent)
        !           341:     );
        !           342:   
        !           343:   setDisplayType('hiddendiv',
        !           344:         (x.Element ref) => new DNHiddenDiv.fromRef(ref),
        !           345:         (x.Node node, DaxeNode parent) {
        !           346:           // use DNBlock if it is going to be visible
        !           347:           // (otherwise display is like division, with tags)
        !           348:           if (node is x.Element && node.getAttribute('style') != '')
        !           349:             return new DNHiddenDiv.fromNode(node, parent);
        !           350:           else
        !           351:             return new DNBlock.fromNode(node, parent);
        !           352:         }
        !           353:     );
        !           354:   
1.35      damieng   355:   // Initialize Daxe, using daxe.initDaxe as a basis.
                    356:   // The insertion panel is customized.
1.28      damieng   357:   InsertPanel insertP = new LCDInsertPanel();
                    358:   LeftPanel left = new LeftPanel(insert:insertP);
1.35      damieng   359:   // The save action is customized.
1.29      damieng   360:   ActionFunction saveFunction= () {
                    361:     doc.save().then((_) {
                    362:       // h.window.alert(Strings.get('save.success'));
                    363:       // update the preview iframe
1.35      damieng   364:       h.IFrameElement previewIFrame = h.document.getElementById('preview_iframe');
1.47      damieng   365:       if (previewIFrame != null) {
                    366:         h.FormElement form = h.document.getElementById('preview_form');
                    367:         form.submit();
                    368:       }
1.29      damieng   369:     }, onError: (DaxeException ex) {
                    370:       h.window.alert(Strings.get('save.error') + ': ' + ex.message);
                    371:     });
                    372:   };
1.43      damieng   373:   // function to customize the toobar after its default creation
                    374:   ActionFunction customizeToolbar = () {
                    375:     ToolbarMenu sectionMenu = _makeSectionMenu();
1.51      damieng   376:     Toolbar toolbar = page.toolbar;
1.43      damieng   377:     if (sectionMenu != null)
1.51      damieng   378:       toolbar.add(sectionMenu);
                    379:     int fileBoxIndex;
1.43      damieng   380:     ToolbarBox mathBox;
1.51      damieng   381:     if (doc.saveURL != null) {
                    382:       fileBoxIndex = 4;
                    383:       mathBox = toolbar.items[4];
                    384:     } else {
                    385:       fileBoxIndex = 3;
                    386:       mathBox = toolbar.items[3];
                    387:     }
                    388:     List<x.Element> refs = doc.cfg.elementsWithType('lcdfile');
                    389:     if (refs != null && refs.length > 0) {
                    390:       ToolbarBox fileBox = new ToolbarBox();
                    391:       toolbar.addInsertButton(doc.cfg, fileBox, refs, Toolbar.iconPath + 'insert_image.png');
                    392:       toolbar.items.insert(fileBoxIndex, fileBox);
                    393:     }
1.43      damieng   394:     x.Element texRef = doc.cfg.elementReference('m');
                    395:     if (texRef != null) {
                    396:       ToolbarButton texButton = new ToolbarButton(
                    397:           LCDStrings.get('insert_m'), 'images/tex.png',
                    398:           () => doc.insertNewNode(texRef, 'element'), Toolbar.insertButtonUpdate, 
                    399:           data:new ToolbarStyleInfo([texRef], null, null));
                    400:       mathBox.add(texButton);
                    401:     }
                    402:     x.Element lmRef = doc.cfg.elementReference('lm');
                    403:     if (lmRef != null) {
                    404:       ToolbarButton lmButton = new ToolbarButton(
                    405:           LCDStrings.get('insert_lm'), 'packages/daxe/images/toolbar/equation.png',
                    406:           () => doc.insertNewNode(lmRef, 'element'), Toolbar.insertButtonUpdate, 
                    407:           data:new ToolbarStyleInfo([lmRef], null, null));
                    408:       mathBox.add(lmButton);
                    409:     }
                    410:   };
1.35      damieng   411:   // Initialization
1.1       damieng   412:   Future.wait([Strings.load(), LCDStrings.load(), _readTemplates('templates.xml')]).then((List responses) {
1.43      damieng   413:     initDaxe(left:left, saveFunction:saveFunction,
                    414:         customizeToolbar:customizeToolbar).then((v) {
1.35      damieng   415:       // More customizations
                    416:       _addGuttersAndPreview();
1.1       damieng   417:       page.adjustPositionsUnderToolbar();
                    418:       page.updateAfterPathChange();
                    419:       // add things to the menubar
                    420:       if (responses[2] is x.Document) {
                    421:         // at this point the menubar html is already in the document, so we have to fix the HTML
                    422:         h.Element menubarDiv = h.document.getElementsByClassName('menubar')[0];
                    423:         Menu m = _makeTemplatesMenu(responses[2]);
1.34      damieng   424:         if (m != null) {
1.26      damieng   425:           page.mbar.add(m);
1.34      damieng   426:           menubarDiv.append(page.mbar.createMenuDiv(m));
                    427:         }
1.33      damieng   428:         Menu helpMenu = _makeHelpMenu();
                    429:         page.mbar.add(helpMenu);
                    430:         menubarDiv.append(page.mbar.createMenuDiv(helpMenu));
1.1       damieng   431:         page.updateAfterPathChange();
                    432:       } else
                    433:         print("Error reading templates file, could not build the menu.");
1.15      damieng   434:     }).catchError((e) {
1.34      damieng   435:       String msg = 'Initialization error: ' + (e is String ? e : e.toString());
                    436:       print(msg);
                    437:       h.document.body.appendText(msg);
1.1       damieng   438:     });
1.15      damieng   439:   }).catchError((e) {
1.34      damieng   440:     String msg = 'Initialization error: ' + (e is String ? e : e.toString());
                    441:     print(msg);
                    442:     h.document.body.appendText(msg);
1.1       damieng   443:   });
                    444: }
                    445: 
1.35      damieng   446: 
                    447: /**
                    448:  * Adds a movable left gutter between the left panel and the document,
                    449:  * a preview to the right and another gutter beween the document and the preview.
1.39      damieng   450:  * Also hides the left panel initially.
1.35      damieng   451:  */
                    452: void _addGuttersAndPreview() {
                    453:   // NOTE: The preview is in an iframe within Daxe
                    454:   // (so that it works like another LON-CAPA problem preview),
                    455:   // and Daxe itself is in an iframe (so as to get the parameters from the URL).
                    456:   // This makes handling mouse event a little more complicated: the preview iframe
                    457:   // will consume events by default, and events outside the Daxe iframe are not
                    458:   // always sent to the iframe when happening outside.
                    459:   bool moving_left_gutter = false;
                    460:   bool moving_right_gutter = false;
1.39      damieng   461:   // hide left panel
                    462:   h.Element left = h.document.getElementById('left_panel');
                    463:   left.style.width ='0px';
                    464:   left.style.visibility = 'hidden';
                    465:   // add left gutter
1.35      damieng   466:   h.DivElement leftGutter = new h.DivElement();
                    467:   leftGutter.id = 'left_gutter';
                    468:   leftGutter.classes.add('vertical-gutter');
1.39      damieng   469:   leftGutter.style.left ='0px';
1.35      damieng   470:   h.Element doc1 = h.document.getElementById('doc1');
                    471:   h.document.body.insertBefore(leftGutter, doc1);
1.39      damieng   472:   doc1.style.left = '10px';
1.35      damieng   473:   
                    474:   // preview and right gutter
                    475:   h.DivElement previewDiv;
                    476:   h.IFrameElement previewIFrame;
1.40      damieng   477:   if (doc.filePath != null && doc.filePath.startsWith('/daxeopen')) {
1.35      damieng   478:     previewDiv = new h.DivElement();
                    479:     previewDiv.id = 'preview_div';
1.46      damieng   480:     
                    481:     h.FormElement form = new h.FormElement();
1.47      damieng   482:     form.id = 'preview_form';
1.46      damieng   483:     form.action = doc.filePath.substring(9);
                    484:     form.target = 'preview_iframe';
                    485:     form.method = 'post';
                    486:     h.InputElement inhibitmenuInput = new h.InputElement();
                    487:     inhibitmenuInput.name = 'inhibitmenu';
                    488:     inhibitmenuInput.value = 'yes';
                    489:     inhibitmenuInput.hidden = true;
                    490:     form.append(inhibitmenuInput);
                    491:     Random rng = new Random();
                    492:     int rndseed = rng.nextInt(2100000000); // max as in Perl code
                    493:     var rndseedInput = new h.InputElement();
                    494:     rndseedInput.name = 'rndseed';
                    495:     rndseedInput.value = rndseed.toString();
                    496:     rndseedInput.hidden = true;
                    497:     form.append(rndseedInput);
                    498:     var resetButton = new h.ButtonElement();
                    499:     resetButton.name = 'resetdata';
                    500:     resetButton.type = 'submit';
                    501:     resetButton.value = 'reset_submissions';
                    502:     resetButton.appendText(LCDStrings.get('reset_submissions'));
                    503:     form.append(resetButton);
                    504:     form.appendText(' ');
                    505:     var randomizationButton = new h.ButtonElement();
                    506:     randomizationButton.appendText(LCDStrings.get('new_randomization'));
                    507:     randomizationButton.onClick.listen((e) {
                    508:       rndseed = rng.nextInt(2100000000);
                    509:       rndseedInput.value = rndseed.toString();
                    510:       form.submit();
                    511:       e.preventDefault();
                    512:     });
                    513:     form.append(randomizationButton);
                    514:     previewDiv.append(form);
                    515:     
                    516:     previewDiv.append(new h.HRElement());
                    517:     
1.35      damieng   518:     previewIFrame = new h.IFrameElement();
                    519:     previewIFrame.id = 'preview_iframe';
1.46      damieng   520:     previewIFrame.name = 'preview_iframe';
                    521:     previewIFrame.onLoad.listen((e) {
                    522:       // set rndseed in the iframe form
                    523:       // dart does not allow iframe crossing, we have to use dart:js for everything
                    524:       // see https://github.com/dart-lang/sdk/issues/20146
                    525:       // and http://stackoverflow.com/q/28940617/438970
                    526:       var iframe = new js.JsObject.fromBrowserObject(
                    527:         h.document.getElementById('preview_iframe'));
                    528:       var doc = new js.JsObject.fromBrowserObject(iframe['contentDocument']);
                    529:       var forms = doc['forms'];
1.47      damieng   530:       var lonhomework = forms['lonhomework'];
                    531:       if (lonhomework == null)
                    532:         return;
                    533:       var iFrameForm = new js.JsObject.fromBrowserObject(lonhomework);
1.46      damieng   534:       var input = new js.JsObject.fromBrowserObject(
                    535:         doc.callMethod('createElement',['input']));
                    536:       input['name'] = 'rndseed';
                    537:       input['value'] = rndseed.toString();
                    538:       input['type'] = 'hidden';
                    539:       iFrameForm.callMethod('appendChild', [input]);
                    540:     });
1.35      damieng   541:     int previewWidth = (doc1.offsetWidth / 3).round();
                    542:     previewDiv.style.width = "${previewWidth}px";
                    543:     previewDiv.append(previewIFrame);
1.46      damieng   544:     
1.35      damieng   545:     h.DivElement rightGutter = new h.DivElement();
                    546:     rightGutter.id = 'right_gutter';
                    547:     rightGutter.classes.add('vertical-gutter');
                    548:     rightGutter.style.right = "${previewWidth}px";
1.44      damieng   549:     var right_mousedown = (h.Event event) {
1.35      damieng   550:       moving_right_gutter = true;
                    551:       event.preventDefault();
                    552:       previewIFrame.style.pointerEvents = 'none';
1.44      damieng   553:     };
                    554:     rightGutter.onMouseDown.listen(right_mousedown);
                    555:     rightGutter.onTouchStart.listen(right_mousedown);
1.35      damieng   556:     h.document.body.append(rightGutter);
                    557:     doc1.style.right = "${previewWidth + 10}px";
                    558:     h.document.body.append(previewDiv);
1.46      damieng   559:     form.submit(); // fills the iframe
1.35      damieng   560:   }
                    561:   
                    562:   // mousedown on left gutter
1.44      damieng   563:   var left_mousedown = (h.Event event) {
1.35      damieng   564:     moving_left_gutter = true;
                    565:     event.preventDefault();
                    566:     if (previewIFrame != null)
                    567:       previewIFrame.style.pointerEvents = 'none';
1.42      damieng   568:   };
1.44      damieng   569:   leftGutter.onMouseDown.listen(left_mousedown);
                    570:   leftGutter.onTouchStart.listen(left_mousedown);
1.35      damieng   571:   
                    572:   // adjust top positions when the toolbar height changes
                    573:   _adjustPositionsUnderToolbar();
                    574:   h.window.onResize.listen((h.Event event) => _adjustPositionsUnderToolbar());
                    575:   
                    576:   // mousemove for both gutters
1.42      damieng   577:   var mousemove = (h.Event event) {
1.35      damieng   578:     if (!(moving_left_gutter || moving_right_gutter))
                    579:       return;
                    580:     h.Element left = h.document.getElementById('left_panel');
                    581:     h.Element doc1 = h.document.getElementById('doc1');
1.42      damieng   582:     num x;
                    583:     if (event is h.MouseEvent)
                    584:       x = event.client.x;
                    585:     else if (event is h.TouchEvent)
                    586:       x = event.changedTouches[0].client.x;
                    587:     else
                    588:       return;
1.35      damieng   589:     x = x.round();
1.36      damieng   590:     // for IE, temporary change of overflow for doc1,
                    591:     // otherwise IE and Edge never report an empty width when there is a scrollbar
                    592:     // (this slows things down, so it is done only for IE)
                    593:     bool ie = h.window.navigator.appVersion.contains("Trident") || h.window.navigator.appVersion.contains("Edge");
                    594:     if (ie)
                    595:       doc1.style.overflow = 'hidden';
                    596:     num doc1width = doc1.offsetWidth;
                    597:     if (ie)
                    598:       doc1.style.overflow = '';
1.35      damieng   599:     if (moving_left_gutter) {
                    600:       h.Element leftGutter = h.document.getElementById('left_gutter');
                    601:       if (x < 5)
                    602:         x = 5;
1.36      damieng   603:       int maxX = left.offsetWidth + 5 + doc1width;
1.35      damieng   604:       if (x > maxX)
                    605:         x = maxX;
                    606:       if (x == 5)
                    607:         left.style.visibility = 'hidden';
1.36      damieng   608:       else
                    609:         left.style.visibility = '';
                    610:       left.style.width = "${x-5}px";
1.35      damieng   611:       leftGutter.style.left ="${x-5}px";
1.36      damieng   612:       if (x == maxX)
                    613:         doc1.style.visibility = 'hidden';
                    614:       else
                    615:         doc1.style.visibility = '';
1.35      damieng   616:       doc1.style.left ="${x+5}px";
                    617:     } else if (moving_right_gutter) {
                    618:       h.Element previewDiv = h.document.getElementById('preview_div');
                    619:       h.Element rightGutter = h.document.getElementById('right_gutter');
                    620:       int minX = left.offsetWidth + 10 + 5;
                    621:       if (x < minX)
                    622:         x = minX;
1.36      damieng   623:       int maxX = left.offsetWidth + 10 + doc1width + 5 + previewDiv.offsetWidth;
1.35      damieng   624:       if (x > maxX)
                    625:         x = maxX;
                    626:       int previewWidth = maxX - x;
                    627:       if (previewWidth == 0)
                    628:         previewDiv.style.visibility = 'hidden';
1.36      damieng   629:       else
                    630:         previewDiv.style.visibility = '';
                    631:       previewDiv.style.width = "${previewWidth}px";
1.35      damieng   632:       rightGutter.style.right ="${previewWidth}px";
1.36      damieng   633:       if (x == minX)
                    634:         doc1.style.visibility = 'hidden';
                    635:       else
                    636:         doc1.style.visibility = '';
1.35      damieng   637:       doc1.style.right ="${previewWidth + 10}px";
1.48      damieng   638:       _adjustPreviewIFrameHeight();
1.35      damieng   639:     }
                    640:     event.stopPropagation();
                    641:     event.preventDefault();
1.42      damieng   642:   };
                    643:   h.document.onMouseMove.listen(mousemove);
                    644:   h.document.onTouchMove.listen(mousemove);
1.35      damieng   645:   
                    646:   // mouseup
1.42      damieng   647:   var mouseup = (h.Event event) {
1.35      damieng   648:     if (moving_left_gutter || moving_right_gutter) {
1.42      damieng   649:       event.preventDefault();
1.35      damieng   650:       h.IFrameElement previewIFrame = h.document.getElementById('preview_iframe');
                    651:       if (previewIFrame != null) {
                    652:         // restore events on iframe
                    653:         previewIFrame.style.pointerEvents = '';
                    654:       }
                    655:       moving_left_gutter = false;
                    656:       moving_right_gutter = false;
                    657:     }
                    658:   };
                    659:   h.document.onMouseUp.listen(mouseup);
1.42      damieng   660:   h.document.onTouchEnd.listen(mouseup);
1.35      damieng   661:   // if we are in an iframe, we need to use the parent to get
                    662:   // mouseup events outside it with some browsers like Chromium
                    663:   var parent = new js.JsObject.fromBrowserObject(js.context['window'])['parent'];
                    664:   if (parent is h.Window) {
                    665:     // happens with Dartium and Firefox
                    666:     parent.onMouseUp.listen((h.MouseEvent event) => mouseup(event));
                    667:   } else if (parent is js.JsObject) {
                    668:     // happens with Chromium
                    669:     parent.callMethod('addEventListener', ['mouseup', mouseup, false]);
                    670:   }
                    671: }
                    672: 
                    673: /*
                    674:  * This complements WebPage.adjustPositionsUnderToolbar with positions for the gutters and preview.
                    675:  */
                    676: void _adjustPositionsUnderToolbar() {
                    677:   h.Element headers = h.document.getElementById('headers');
                    678:   num y = headers.getBoundingClientRect().bottom;
                    679:   String cssTop = (y.round() + 2).toString() + "px";
                    680:   h.document.getElementById('left_gutter').style.top = cssTop;
                    681:   h.DivElement rightGutter = h.document.getElementById('right_gutter');
                    682:   if (rightGutter != null)
                    683:     rightGutter.style.top = cssTop;
                    684:   h.DivElement previewDiv = h.document.getElementById('preview_div');
                    685:   if (previewDiv != null)
                    686:     previewDiv.style.top = cssTop;
1.48      damieng   687:   _adjustPreviewIFrameHeight();
                    688: }
                    689: 
                    690: /*
                    691:  * Fixes the preview iframe height to take form on top into account
                    692:  * (this cannot be done with pure CSS without flexbox).
                    693:  */
                    694: void _adjustPreviewIFrameHeight() {
                    695:   h.DivElement previewDiv = h.document.getElementById('preview_div');
                    696:   if (previewDiv != null) {
                    697:     h.IFrameElement previewIFrame = h.document.getElementById('preview_iframe');
                    698:     int newHeight = previewDiv.offsetHeight - previewIFrame.offsetTop;
                    699:     previewIFrame.style.height = newHeight.toString() + 'px';
                    700:   }
1.35      damieng   701: }
                    702: 
                    703: 
1.1       damieng   704: ToolbarMenu _makeSectionMenu() {
1.18      damieng   705:   // sort section roles by title
                    706:   knownSectionRoles.sort((String role1, String role2) => LCDStrings.get(role1).compareTo(LCDStrings.get(role2)));
                    707:   
1.1       damieng   708:   Menu menu = new Menu(LCDStrings.get('Section'));
                    709:   List<x.Element> sectionRefs = doc.cfg.elementReferences('section');
                    710:   if (sectionRefs == null || sectionRefs.length == 0)
                    711:     return(null);
                    712:   x.Element h1Ref = doc.cfg.elementReference('h1');
1.18      damieng   713:   for (String role in knownSectionRoles) {
1.1       damieng   714:     MenuItem menuItem = new MenuItem(LCDStrings.get(role), null,
                    715:         data:new ToolbarStyleInfo(sectionRefs, null, null));
                    716:     menuItem.action = () {
                    717:       ToolbarStyleInfo info = menuItem.data;
                    718:       x.Element sectionRef = info.validRef;
1.18      damieng   719:       Section section = new Section.fromRef(sectionRef);
1.1       damieng   720:       section.state = 1;
                    721:       section.setAttribute('class', 'role-' + role);
1.17      damieng   722:       H1 h1 = NodeFactory.create(h1Ref);
1.1       damieng   723:       h1.state = 1;
1.18      damieng   724:       h1.appendChild(new DNText(LCDStrings.get(role)));
1.9       damieng   725:       section.appendChild(h1);
                    726:       x.Element hiddenp = doc.cfg.findSubElement(sectionRef, doc.hiddenParaRefs);
1.18      damieng   727:       DNHiddenP p = new DNHiddenP.fromRef(hiddenp);
1.9       damieng   728:       section.appendChild(p);
1.17      damieng   729:       section.setupSimpleUI();
1.1       damieng   730:       if (doc.insert2(section, page.getSelectionStart())) {
1.18      damieng   731:         page.cursor.moveTo(new Position(p, 0));
1.1       damieng   732:         page.updateAfterPathChange();
                    733:       }
                    734:     };
                    735:     menu.add(menuItem);
                    736:   }
                    737:   ToolbarMenu tbmenu = new ToolbarMenu(menu, Toolbar.insertMenuUpdate, page.toolbar);
                    738:   return(tbmenu);
                    739: }
                    740: 
1.35      damieng   741: 
1.1       damieng   742: Future<x.Document> _readTemplates(String templatesPath) {
                    743:   x.DOMParser dp = new x.DOMParser();
                    744:   return(dp.parseFromURL(templatesPath));
                    745: }
                    746: 
                    747: Menu _makeTemplatesMenu(x.Document templatesDoc) {
1.26      damieng   748:   List<x.Element> problemRefs = doc.cfg.elementReferences('problem');
                    749:   if (problemRefs == null || problemRefs.length == 0)
                    750:     return(null);
1.1       damieng   751:   Menu menu = new Menu(LCDStrings.get('Templates'));
                    752:   x.Element templates = templatesDoc.documentElement;
                    753:   for (x.Node child in templates.childNodes) {
                    754:     if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'menu') {
                    755:       menu.add(_makeMenu(child));
                    756:     }
                    757:   }
                    758:   return(menu);
                    759: }
                    760: 
                    761: Menu _makeMenu(x.Element el) {
                    762:   String locale = LCDStrings.systemLocale;
                    763:   String defaultLocale = LCDStrings.defaultLocale;
                    764:   String title;
                    765:   for (x.Node child in el.childNodes) {
                    766:     if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'title') {
                    767:       if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    768:         if ((child as x.Element).getAttribute('lang') == locale) {
                    769:           title = child.firstChild.nodeValue;
                    770:           break;
                    771:         } else if ((child as x.Element).getAttribute('lang') == defaultLocale) {
                    772:           title = child.firstChild.nodeValue;
                    773:         }
                    774:       }
                    775:     }
                    776:   }
                    777:   if (title == null)
                    778:     title = '?';
                    779:   Menu menu = new Menu(title);
                    780:   for (x.Node child in el.childNodes) {
                    781:     if (child.nodeType == x.Node.ELEMENT_NODE) {
                    782:       if (child.nodeName == 'menu') {
                    783:         menu.add(_makeMenu(child));
                    784:       } else if (child.nodeName == 'item') {
                    785:         menu.add(_makeItem(child));
                    786:       }
                    787:     }
                    788:   }
                    789:   return(menu);
                    790: }
                    791: 
                    792: MenuItem _makeItem(x.Element item) {
                    793:   String locale = LCDStrings.systemLocale;
                    794:   String defaultLocale = LCDStrings.defaultLocale;
                    795:   String path, type, title, help;
                    796:   for (x.Node child in item.childNodes) {
                    797:     if (child.nodeType == x.Node.ELEMENT_NODE) {
                    798:       if (child.nodeName == 'title') {
                    799:         if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    800:           if ((child as x.Element).getAttribute('lang') == locale) {
                    801:             title = child.firstChild.nodeValue;
                    802:           } else if (title == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
                    803:             title = child.firstChild.nodeValue;
                    804:           }
                    805:         }
                    806:       } else if (child.nodeName == 'path' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    807:         path = child.firstChild.nodeValue;
                    808:       } else if (child.nodeName == 'type' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    809:         type = child.firstChild.nodeValue;
                    810:       } else if (child.nodeName == 'help') {
                    811:         if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    812:           if ((child as x.Element).getAttribute('lang') == locale) {
                    813:             help = child.firstChild.nodeValue;
                    814:           } else if (help == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
                    815:             help = child.firstChild.nodeValue;
                    816:           }
                    817:         }
                    818:       }
                    819:     }
                    820:   }
                    821:   if (type == null) {
                    822:     print("Warning: missing type for template $title\n");
                    823:     type = 'problem';
                    824:   }
                    825:   x.Element refElement = doc.cfg.elementReference(type);
                    826:   MenuItem menuItem = new MenuItem(title, () => _insertTemplate(path), data: refElement);
                    827:   if (help != null)
                    828:     menuItem.toolTipText = help;
                    829:   return menuItem;
                    830: }
                    831: 
                    832: void _insertTemplate(String filePath) {
                    833:   try {
                    834:     x.DOMParser dp = new x.DOMParser();
                    835:     dp.parseFromURL(filePath).then((x.Document templateDoc) {
                    836:       x.Element root = templateDoc.documentElement;
                    837:       if (root == null)
                    838:         return;
                    839:       doc.removeWhitespace(root);
                    840:       DaxeNode dnRoot = NodeFactory.createFromNode(root, null);
1.49      damieng   841:       List<x.Element> rootAttributes = doc.cfg.elementAttributes(dnRoot.ref);
                    842:       if (dnRoot is LCDBlock && rootAttributes != null && rootAttributes.length > 0)
1.27      damieng   843:         dnRoot.state = 0; // make attributes editable for the template root
1.1       damieng   844:       UndoableEdit edit;
                    845:       Position pos = page.getSelectionStart();
                    846:       if (dnRoot.nodeName == 'loncapa' && doc.getRootElement() != null)
                    847:         edit = doc.insertChildrenEdit(dnRoot, pos, checkValidity:true);
1.12      damieng   848:       else {
                    849:         DaxeNode parent = pos.dn;
                    850:         if (parent is DNText)
                    851:           parent = parent.parent;
                    852:         if (parent is DNHiddenP && !doc.cfg.isSubElement(parent.ref, dnRoot.ref)) {
                    853:           // The node must be inserted outside of the paragraph.
                    854:           // If there is something in the paragraph to the right of the cursor, it must be
                    855:           // moved into a new paragraph after the inserted node.
                    856:           // (as in DaxeDocument.insert2)
                    857:           DNHiddenP p = parent;
                    858:           edit = new UndoableEdit.compound(Strings.get('undo.insert_element'));
                    859:           Position pend = new Position(p, p.offsetLength);
                    860:           pend.moveInsideTextNodeIfPossible();
                    861:           if (pos < pend) {
                    862:             DaxeNode clone = doc.cloneBetween(pos, pend);
                    863:             edit.addSubEdit(doc.removeBetweenEdit(pos, pend));
                    864:             DNHiddenP newp = NodeFactory.create(p.ref);
                    865:             edit.addSubEdit(new UndoableEdit.insertNode(
                    866:                 new Position(p.parent, p.parent.offsetOf(p) + 1), newp));
                    867:             edit.addSubEdit(doc.insertChildrenEdit(clone, new Position(newp, 0)));
                    868:           }
                    869:           edit.addSubEdit(new UndoableEdit.insertNode(
                    870:               new Position(p.parent, p.parent.offsetOf(p)+1), dnRoot));
                    871:         } else
                    872:           edit = new UndoableEdit.insertNode(pos, dnRoot);
                    873:       }
1.1       damieng   874:       doc.doNewEdit(edit);
                    875:       page.updateAfterPathChange();
1.8       damieng   876:       if (dnRoot.nodeName != 'loncapa')
                    877:         page.scrollToNode(dnRoot);
1.1       damieng   878:     });
                    879:   } on x.DOMException catch(ex) {
                    880:     h.window.alert(ex.toString());
                    881:   }
                    882: }
1.33      damieng   883: 
                    884: Menu _makeHelpMenu() {
                    885:   Menu menu = new Menu(LCDStrings.get('help'));
1.38      damieng   886:   menu.add(new MenuItem(LCDStrings.get('getting_started'),
                    887:       () => h.window.open('tutorial/getting_started.xhtml', '_blank')));
                    888:   menu.add(new MenuItem(LCDStrings.get('author_manual'),
                    889:       () => h.window.open('/adm/help/author.manual.pdf', '_blank')));
1.41      damieng   890:   menu.add(new MenuItem(LCDStrings.get('about_lcdaxe'),
                    891:       () => (new AboutLCDaxeDlg()).show()));
1.33      damieng   892:   return(menu);
                    893: }

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